123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644 |
- "use strict";
- const path = require("path");
- const envPaths = require("env-paths");
- const fs = require("fs");
- const homedir = require('os').homedir();
- const supportingPath = path.join(homedir, ".ssb/flume/contacts2.json");
- const offsetPath = path.join(homedir, ".ssb/flume/log.offset");
- const debug = require("debug")("oasis");
- const highlightJs = require("highlight.js");
- const MarkdownIt = require("markdown-it");
- const prettyMs = require("pretty-ms");
- const updater = require("../updater.js");
- global.updaterequired = "";
- global.ck = updater.getRemoteVersion(async function(checkversion){
- if (checkversion === "required"){
- ck = "required";
- }
- });
- const {
- a,
- article,
- br,
- body,
- button,
- details,
- div,
- em,
- footer,
- form,
- h1,
- h2,
- head,
- header,
- hr,
- html,
- img,
- input,
- label,
- li,
- link,
- main,
- meta,
- nav,
- option,
- p,
- pre,
- progress,
- section,
- select,
- span,
- summary,
- textarea,
- title,
- ul,
- } = require("hyperaxe");
- const { about, blob, vote } = require("../models")({});
- const lodash = require("lodash");
- const markdown = require("./markdown");
- const i18nBase = require("./i18n");
- let selectedLanguage = "en";
- let i18n = i18nBase[selectedLanguage];
- exports.setLanguage = (language) => {
- selectedLanguage = language;
- i18n = Object.assign({}, i18nBase.en, i18nBase[language]);
- };
- const markdownUrl = "https://commonmark.org/help/";
- const snhUrl = "https://solarnethub.com/";
- const doctypeString = "<!DOCTYPE html>";
- const THREAD_PREVIEW_LENGTH = 3;
- const toAttributes = (obj) =>
- Object.entries(obj)
- .map(([key, val]) => `${key}=${val}`)
- .join(", ");
- // non-breaking space
- const nbsp = "\xa0";
- const template = (titlePrefix, ...elements) => {
- const navLink = ({ href, emoji, text }) =>
- li(
- a(
- { href, class: titlePrefix === text ? "current" : "" },
- span({ class: "emoji" }, emoji),
- nbsp,
- text
- )
- );
- const customCSS = (filename) => {
- const customStyleFile = path.join(
- envPaths("oasis", { suffix: "" }).config,
- filename
- );
- try {
- if (fs.existsSync(customStyleFile)) {
- return link({ rel: "stylesheet", href: filename });
- }
- } catch (error) {
- return "";
- }
- };
- const nodes = html(
- { lang: "en" },
- head(
- title(titlePrefix, " | SNH-Oasis"),
- link({ rel: "stylesheet", href: "/theme.css" }),
- link({ rel: "stylesheet", href: "/assets/style.css" }),
- link({ rel: "stylesheet", href: "/assets/highlight.css" }),
- customCSS("/custom-style.css"),
- link({ rel: "icon", type: "image/svg+xml", href: "/assets/favicon.svg" }),
- meta({ charset: "utf-8" }),
- meta({
- name: "description",
- content: i18n.oasisDescription,
- }),
- meta({
- name: "viewport",
- content: toAttributes({ width: "device-width", "initial-scale": 1 }),
- })
- ),
- body(
- nav(
- ul(
- //navLink({ href: "/imageSearch", emoji: "✧", text: i18n.imageSearch }),
- navLink({ href: "/public/popular/day", emoji: "⌘", text: i18n.popular }),
- navLink({ href: "/mentions", emoji: "✺", text: i18n.mentions }),
- navLink({ href: "/public/latest", emoji: "☄", text: i18n.latest }),
- navLink({ href: "/public/latest/summaries", emoji: "※", text: i18n.summaries }),
- navLink({ href: "/public/latest/topics", emoji: "ϟ", text: i18n.topics }),
- navLink({ href: "/public/latest/extended", emoji: "∞", text: i18n.extended }),
- navLink({ href: "/public/latest/threads", emoji: "♺", text: i18n.threads }),
- )
- ),
- main({ id: "content" }, elements),
- nav(
- ul(
- navLink({ href: "/publish", emoji: "❂",text: i18n.publish }),
- navLink({ href: "/search", emoji: "✦", text: i18n.search }),
- navLink({ href: "/inbox", emoji: "☂", text: i18n.private }),
- navLink({ href: "/profile", emoji: "⚉", text: i18n.profile }),
- navLink({ href: "/invites", emoji: "❄", text: i18n.invites }),
- navLink({ href: "/peers", emoji: "⧖", text: i18n.peers }),
- navLink({ href: "/settings", emoji: "⚙", text: i18n.settings })
- )
- )
- )
- );
- const result = doctypeString + nodes.outerHTML;
- return result;
- };
- const thread = (messages) => {
- // this first loop is preprocessing to enable auto-expansion of forks when a
- // message in the fork is linked to
- let lookingForTarget = true;
- let shallowest = Infinity;
- for (let i = messages.length - 1; i >= 0; i--) {
- const msg = messages[i];
- const depth = lodash.get(msg, "value.meta.thread.depth", 0);
- if (lookingForTarget) {
- const isThreadTarget = Boolean(
- lodash.get(msg, "value.meta.thread.target", false)
- );
- if (isThreadTarget) {
- lookingForTarget = false;
- }
- } else {
- if (depth < shallowest) {
- lodash.set(msg, "value.meta.thread.ancestorOfTarget", true);
- shallowest = depth;
- }
- }
- }
- const msgList = [];
- for (let i = 0; i < messages.length; i++) {
- const j = i + 1;
- const currentMsg = messages[i];
- const nextMsg = messages[j];
- const depth = (msg) => {
- // will be undefined when checking depth(nextMsg) when currentMsg is the
- // last message in the thread
- if (msg === undefined) return 0;
- return lodash.get(msg, "value.meta.thread.depth", 0);
- };
- msgList.push(post({ msg: currentMsg }).outerHTML);
- if (depth(currentMsg) < depth(nextMsg)) {
- const isAncestor = Boolean(
- lodash.get(currentMsg, "value.meta.thread.ancestorOfTarget", false)
- );
- const isBlocked = Boolean(nextMsg.value.meta.blocking);
- msgList.push(`<div class="indent"><details ${isAncestor ? "open" : ""}>`);
- const nextAuthor = lodash.get(nextMsg, "value.meta.author.name");
- const nextSnippet = postSnippet(
- lodash.has(nextMsg, "value.content.contentWarning")
- ? lodash.get(nextMsg, "value.content.contentWarning")
- : lodash.get(nextMsg, "value.content.text")
- );
- msgList.push(
- summary(
- isBlocked
- ? i18n.relationshipBlockingPost
- : `${nextAuthor}: ${nextSnippet}`
- ).outerHTML
- );
- } else if (depth(currentMsg) > depth(nextMsg)) {
- // getting more shallow
- const diffDepth = depth(currentMsg) - depth(nextMsg);
- const shallowList = [];
- for (let d = 0; d < diffDepth; d++) {
- // on the way up it might go several depths at once
- shallowList.push("</details></div>");
- }
- msgList.push(shallowList);
- }
- }
- const htmlStrings = lodash.flatten(msgList);
- return div(
- {},
- { class: "thread-container", innerHTML: htmlStrings.join("") }
- );
- };
- const postSnippet = (text) => {
- const max = 40;
- text = text.trim().split("\n", 3).join("\n");
- // this is taken directly from patchwork. i'm not entirely sure what this
- // regex is doing
- text = text.replace(/_|`|\*|#|^\[@.*?]|\[|]|\(\S*?\)/g, "").trim();
- text = text.replace(/:$/, "");
- text = text.trim().split("\n", 1)[0].trim();
- if (text.length > max) {
- text = text.substring(0, max - 1) + "…";
- }
- return text;
- };
- /**
- * Render a section containing a link that takes users to the context for a
- * thread preview.
- *
- * @param {Array} thread with SSB message objects
- * @param {Boolean} isComment true if this is shown in the context of a comment
- * instead of a post
- */
- const continueThreadComponent = (thread, isComment) => {
- const encoded = {
- next: encodeURIComponent(thread[THREAD_PREVIEW_LENGTH + 1].key),
- parent: encodeURIComponent(thread[0].key),
- };
- const left = thread.length - (THREAD_PREVIEW_LENGTH + 1);
- let continueLink;
- if (isComment == false) {
- continueLink = `/thread/${encoded.parent}#${encoded.next}`;
- return a(
- { href: continueLink },
- `continue reading ${left} more comment${left === 1 ? "" : "s"}`
- );
- } else {
- continueLink = `/thread/${encoded.parent}`;
- return a({ href: continueLink }, "read the rest of the thread");
- }
- };
- /**
- * Render an aside with a preview of comments on a message
- *
- * For posts, up to three comments are shown, for comments, up to 3 messages
- * directly following this one in the thread are displayed. If there are more
- * messages in the thread, a link is rendered that links to the rest of the
- * context.
- *
- * @param {Object} post for which to display the aside
- */
- const postAside = ({ key, value }) => {
- const thread = value.meta.thread;
- if (thread == null) return null;
- const isComment = value.meta.postType === "comment";
- let postsToShow;
- if (isComment) {
- const commentPosition = thread.findIndex((msg) => msg.key === key);
- postsToShow = thread.slice(
- commentPosition + 1,
- Math.min(commentPosition + (THREAD_PREVIEW_LENGTH + 1), thread.length)
- );
- } else {
- postsToShow = thread.slice(
- 1,
- Math.min(thread.length, THREAD_PREVIEW_LENGTH + 1)
- );
- }
- const fragments = postsToShow.map((p) => post({ msg: p }));
- if (thread.length > THREAD_PREVIEW_LENGTH + 1) {
- fragments.push(section(continueThreadComponent(thread, isComment)));
- }
- return div({ class: "indent" }, fragments);
- };
- const post = ({ msg, aside = false }) => {
- const encoded = {
- key: encodeURIComponent(msg.key),
- author: encodeURIComponent(msg.value.author),
- parent: encodeURIComponent(msg.value.content.root),
- };
- const url = {
- author: `/author/${encoded.author}`,
- likeForm: `/like/${encoded.key}`,
- link: `/thread/${encoded.key}#${encoded.key}`,
- parent: `/thread/${encoded.parent}#${encoded.parent}`,
- avatar: msg.value.meta.author.avatar.url,
- json: `/json/${encoded.key}`,
- subtopic: `/subtopic/${encoded.key}`,
- comment: `/comment/${encoded.key}`,
- };
- const isPrivate = Boolean(msg.value.meta.private);
- const isBlocked = Boolean(msg.value.meta.blocking);
- const isRoot = msg.value.content.root == null;
- const isFork = msg.value.meta.postType === "subtopic";
- const hasContentWarning =
- typeof msg.value.content.contentWarning === "string";
- const isThreadTarget = Boolean(
- lodash.get(msg, "value.meta.thread.target", false)
- );
- const { name } = msg.value.meta.author;
- const ts_received = msg.value.meta.timestamp.received;
- const timeAgo = ts_received.since.replace("~", "");
- const timeAbsolute = ts_received.iso8601.split(".")[0].replace("T", " ");
- const markdownContent = markdown(
- msg.value.content.text,
- msg.value.content.mentions
- );
- const likeButton = msg.value.meta.voted
- ? { value: 0, class: "liked" }
- : { value: 1, class: null };
- const likeCount = msg.value.meta.votes.length;
- const maxLikedNameLength = 16;
- const maxLikedNames = 16;
- const likedByNames = msg.value.meta.votes
- .slice(0, maxLikedNames)
- .map((person) => person.name)
- .map((name) => name.slice(0, maxLikedNameLength))
- .join(", ");
- const additionalLikesMessage =
- likeCount > maxLikedNames ? `+${likeCount - maxLikedNames} more` : ``;
- const likedByMessage =
- likeCount > 0 ? `${likedByNames} ${additionalLikesMessage}` : null;
- const messageClasses = ["post"];
- const recps = [];
- const addRecps = (recpsInfo) => {
- recpsInfo.forEach(function (recp) {
- recps.push(
- a(
- { href: `/author/${encodeURIComponent(recp.feedId)}` },
- img({ class: "avatar", src: recp.avatarUrl, alt: "" })
- )
- );
- });
- };
- if (isPrivate) {
- messageClasses.push("private");
- addRecps(msg.value.meta.recpsInfo);
- }
- if (isThreadTarget) {
- messageClasses.push("thread-target");
- }
- // TODO: Refactor to stop using strings and use constants/symbols.
- const postOptions = {
- post: null,
- comment: i18n.commentDescription({ parentUrl: url.parent }),
- subtopic: i18n.subtopicDescription({ parentUrl: url.parent }),
- mystery: i18n.mysteryDescription,
- };
- const emptyContent = "<p>undefined</p>\n";
- const articleElement =
- markdownContent === emptyContent
- ? article(
- { class: "content" },
- pre({
- innerHTML: highlightJs.highlight(
- JSON.stringify(msg, null, 2),
- {language: "json", ignoreIllegals: true}
- ).value,
- })
- )
- : article({ class: "content", innerHTML: markdownContent });
- if (isBlocked) {
- messageClasses.push("blocked");
- return section(
- {
- id: msg.key,
- class: messageClasses.join(" "),
- },
- i18n.relationshipBlockingPost
- );
- }
- const articleContent = hasContentWarning
- ? details(summary(msg.value.content.contentWarning), articleElement)
- : articleElement;
- const fragment = section(
- {
- id: msg.key,
- class: messageClasses.join(" "),
- },
- header(
- div(
- span(
- { class: "author" },
- a(
- { href: url.author },
- img({ class: "avatar", src: url.avatar, alt: "" }),
- name
- )
- ),
- span({ class: "author-action" }, postOptions[msg.value.meta.postType]),
- span(
- {
- class: "time",
- title: timeAbsolute,
- },
- isPrivate ? "🔒" : null,
- isPrivate ? recps : null,
- a({ href: url.link }, nbsp, timeAgo)
- )
- )
- ),
- articleContent,
- // HACK: centered-footer
- //
- // Here we create an empty div with an anchor tag that can be linked to.
- // In our CSS we ensure that this gets centered on the screen when we
- // link to this anchor tag.
- //
- // This is used for redirecting users after they like a post, when we
- // want the like button that they just clicked to remain close-ish to
- // where it was before they clicked the button.
- div({ id: `centered-footer-${encoded.key}`, class: "centered-footer" }),
- footer(
- div(
- form(
- { action: url.likeForm, method: "post" },
- button(
- {
- name: "voteValue",
- type: "submit",
- value: likeButton.value,
- class: likeButton.class,
- title: likedByMessage,
- },
- `☉ ${likeCount}`
- )
- ),
- a({ href: url.comment }, i18n.comment),
- isPrivate || isRoot || isFork
- ? null
- : a({ href: url.subtopic }, nbsp, i18n.subtopic),
- a({ href: url.json }, nbsp, i18n.json)
- ),
- br()
- )
- );
- const threadSeparator = [div({ class: "text-browser" }, hr(), br())];
- if (aside) {
- return [fragment, postAside(msg), isRoot ? threadSeparator : null];
- } else {
- return fragment;
- }
- };
- exports.editProfileView = ({ name, description }) =>
- template(
- i18n.editProfile,
- section(
- h1(i18n.editProfile),
- p(i18n.editProfileDescription),
- form(
- {
- action: "/profile/edit",
- method: "POST",
- enctype: "multipart/form-data",
- },
- label(
- i18n.profileImage,
- input({ type: "file", name: "image", accept: "image/*" })
- ),
- label(i18n.profileName, input({ name: "name", value: name })),
- label(
- i18n.profileDescription,
- textarea(
- {
- autofocus: true,
- name: "description",
- },
- description
- )
- ),
- button(
- {
- type: "submit",
- },
- i18n.submit
- )
- )
- )
- );
- /**
- * @param {{avatarUrl: string, description: string, feedId: string, messages: any[], name: string, relationship: object, firstPost: object, lastPost: object}} input
- */
- exports.authorView = ({
- avatarUrl,
- description,
- feedId,
- messages,
- firstPost,
- lastPost,
- name,
- relationship,
- }) => {
- const mention = `[@${name}](${feedId})`;
- const markdownMention = highlightJs.highlight(mention, {language: "markdown", ignoreIllegals: true}).value;
- const contactForms = [];
- const addForm = ({ action }) =>
- contactForms.push(
- form(
- {
- action: `/${action}/${encodeURIComponent(feedId)}`,
- method: "post",
- },
- button(
- {
- type: "submit",
- },
- i18n[action]
- )
- )
- );
- if (relationship.me === false) {
- if (relationship.following) {
- addForm({ action: "unfollow" });
- } else if (relationship.blocking) {
- addForm({ action: "unblock" });
- } else {
- addForm({ action: "follow" });
- addForm({ action: "block" });
- }
- }
- const relationshipText = (() => {
- if (relationship.me === true) {
- return i18n.relationshipYou;
- } else if (
- relationship.following === true &&
- relationship.blocking === false
- ) {
- return i18n.relationshipFollowing;
- } else if (
- relationship.following === false &&
- relationship.blocking === true
- ) {
- return i18n.relationshipBlocking;
- } else if (
- relationship.following === false &&
- relationship.blocking === false
- ) {
- return i18n.relationshipNone;
- } else if (
- relationship.following === true &&
- relationship.blocking === true
- ) {
- return i18n.relationshipConflict;
- } else {
- throw new Error(`Unknown relationship ${JSON.stringify(relationship)}`);
- }
- })();
- const prefix = section(
- { class: "message" },
- div(
- { class: "profile" },
- img({ class: "avatar", src: avatarUrl }),
- h1(name)
- ),
- pre({
- class: "md-mention",
- innerHTML: markdownMention,
- }),
- description !== "" ? article({ innerHTML: markdown(description) }) : null,
- footer(
- div(
- a({ href: `/likes/${encodeURIComponent(feedId)}` }, i18n.viewLikes),
- span(nbsp, relationshipText),
- ...contactForms,
- relationship.me
- ? a({ href: `/profile/edit` }, nbsp, i18n.editProfile)
- : null
- ),
- br()
- )
- );
- const linkUrl = relationship.me
- ? "/profile/"
- : `/author/${encodeURIComponent(feedId)}/`;
- let items = messages.map((msg) => post({ msg }));
- if (items.length === 0) {
- if (lastPost === undefined) {
- items.push(section(div(span(i18n.feedEmpty))));
- } else {
- items.push(
- section(
- div(
- span(i18n.feedRangeEmpty),
- a({ href: `${linkUrl}` }, i18n.seeFullFeed)
- )
- )
- );
- }
- } else {
- const highestSeqNum = messages[0].value.sequence;
- const lowestSeqNum = messages[messages.length - 1].value.sequence;
- let newerPostsLink;
- if (lastPost !== undefined && highestSeqNum < lastPost.value.sequence)
- newerPostsLink = a(
- { href: `${linkUrl}?gt=${highestSeqNum}` },
- i18n.newerPosts
- );
- else newerPostsLink = span(i18n.newerPosts, { title: i18n.noNewerPosts });
- let olderPostsLink;
- if (lowestSeqNum > firstPost.value.sequence)
- olderPostsLink = a(
- { href: `${linkUrl}?lt=${lowestSeqNum}` },
- i18n.olderPosts
- );
- else
- olderPostsLink = span(i18n.olderPosts, { title: i18n.beginningOfFeed });
- const pagination = section(
- { class: "message" },
- footer(div(newerPostsLink, olderPostsLink), br())
- );
- items.unshift(pagination);
- items.push(pagination);
- }
- return template(i18n.profile, prefix, items);
- };
- exports.previewCommentView = async ({
- previewData,
- messages,
- myFeedId,
- parentMessage,
- contentWarning,
- }) => {
- const publishAction = `/comment/${encodeURIComponent(messages[0].key)}`;
- const preview = generatePreview({
- previewData,
- contentWarning,
- action: publishAction,
- });
- return exports.commentView(
- { messages, myFeedId, parentMessage },
- preview,
- previewData.text,
- contentWarning
- );
- };
- exports.commentView = async (
- { messages, myFeedId, parentMessage },
- preview,
- text,
- contentWarning
- ) => {
- let markdownMention;
- const messageElements = await Promise.all(
- messages.reverse().map((message) => {
- debug("%O", message);
- const authorName = message.value.meta.author.name;
- const authorFeedId = message.value.author;
- if (authorFeedId !== myFeedId) {
- if (message.key === parentMessage.key) {
- const x = `[@${authorName}](${authorFeedId})\n\n`;
- markdownMention = x;
- }
- }
- return post({ msg: message });
- })
- );
- const action = `/comment/preview/${encodeURIComponent(messages[0].key)}`;
- const method = "post";
- const isPrivate = parentMessage.value.meta.private;
- const authorName = parentMessage.value.meta.author.name;
- const publicOrPrivate = isPrivate ? i18n.commentPrivate : i18n.commentPublic;
- const maybeSubtopicText = isPrivate ? [null] : i18n.commentWarning;
- return template(
- i18n.commentTitle({ authorName }),
- div({ class: "thread-container" }, messageElements),
- preview !== undefined ? preview : "",
- p(
- ...i18n.commentLabel({ publicOrPrivate, markdownUrl }),
- ...maybeSubtopicText
- ),
- form(
- { action, method, enctype: "multipart/form-data" },
- label(
- i18n.contentWarningLabel,
- input({
- name: "contentWarning",
- type: "text",
- class: "contentWarning",
- value: contentWarning ? contentWarning : "",
- placeholder: i18n.contentWarningPlaceholder,
- })
- ),
- textarea(
- {
- autofocus: true,
- required: true,
- name: "text",
- },
- text ? text : isPrivate ? null : markdownMention
- ),
- button({ type: "submit" }, i18n.preview),
- label({ class: "file-button", for: "blob" }, i18n.attachFiles),
- input({ type: "file", id: "blob", name: "blob" })
- )
- );
- };
- exports.mentionsView = ({ messages }) => {
- return messageListView({
- messages,
- viewTitle: i18n.mentions,
- viewDescription: i18n.mentionsDescription,
- });
- };
- exports.privateView = ({ messages }) => {
- return messageListView({
- messages,
- viewTitle: i18n.private,
- viewDescription: i18n.privateDescription,
- });
- };
- exports.publishCustomView = async () => {
- const action = "/publish/custom";
- const method = "post";
- return template(
- i18n.publishCustom,
- section(
- h1(i18n.publishCustom),
- p(i18n.publishCustomDescription),
- form(
- { action, method },
- textarea(
- {
- autofocus: true,
- required: true,
- name: "text",
- },
- "{\n",
- ' "type": "test",\n',
- ' "hello": "world"\n',
- "}"
- ),
- button(
- {
- type: "submit",
- },
- i18n.submit
- )
- )
- ),
- p(i18n.publishBasicInfo({ href: "/publish" }))
- );
- };
- exports.threadView = ({ messages }) => {
- const rootMessage = messages[0];
- const rootAuthorName = rootMessage.value.meta.author.name;
- const rootSnippet = postSnippet(
- lodash.get(rootMessage, "value.content.text", i18n.mysteryDescription)
- );
- return template([`@${rootAuthorName}: `, rootSnippet], thread(messages));
- };
- exports.publishView = (preview, text, contentWarning) => {
- return template(
- i18n.publish,
- section(
- h1(i18n.publish),
- form(
- {
- action: "/publish/preview",
- method: "post",
- enctype: "multipart/form-data",
- },
- label(
- i18n.publishLabel({ markdownUrl, linkTarget: "_blank" }),
- label(
- i18n.contentWarningLabel,
- input({
- name: "contentWarning",
- type: "text",
- class: "contentWarning",
- value: contentWarning ? contentWarning : "",
- placeholder: i18n.contentWarningPlaceholder,
- })
- ),
- textarea({ required: true, name: "text", placeholder: i18n.publishWarningPlaceholder }, text ? text : "")
- ),
- button({ type: "submit" }, i18n.preview),
- label({ class: "file-button", for: "blob" }, i18n.attachFiles),
- input({ type: "file", id: "blob", name: "blob" })
- )
- ),
- preview ? preview : "",
- p(i18n.publishCustomInfo({ href: "/publish/custom" }))
- );
- };
- const generatePreview = ({ previewData, contentWarning, action }) => {
- const { authorMeta, text, mentions } = previewData;
- // craft message that looks like it came from the db
- // cb: this kinda fragile imo? this is for getting a proper post styling ya?
- const msg = {
- key: "%non-existent.preview",
- value: {
- author: authorMeta.id,
- // sequence: -1,
- content: {
- type: "post",
- text: text,
- },
- timestamp: Date.now(),
- meta: {
- isPrivate: true,
- votes: [],
- author: {
- name: authorMeta.name,
- avatar: {
- url: `/image/64/${encodeURIComponent(authorMeta.image)}`,
- },
- },
- },
- },
- };
- if (contentWarning) msg.value.content.contentWarning = contentWarning;
- const ts = new Date(msg.value.timestamp);
- lodash.set(msg, "value.meta.timestamp.received.iso8601", ts.toISOString());
- const ago = Date.now() - Number(ts);
- const prettyAgo = prettyMs(ago, { compact: true });
- lodash.set(msg, "value.meta.timestamp.received.since", prettyAgo);
- return div(
- Object.keys(mentions).length === 0
- ? ""
- : section(
- { class: "mention-suggestions" },
- h2(i18n.mentionsMatching),
- Object.keys(mentions).map((name) => {
- let matches = mentions[name];
- return div(
- matches.map((m) => {
- let relationship = { emoji: "", desc: "" };
- if (m.rel.followsMe && m.rel.following) {
- relationship.emoji = "☍";
- relationship.desc = i18n.relationshipMutuals;
- } else if (m.rel.following) {
- relationship.emoji = "☌";
- relationship.desc = i18n.relationshipFollowing;
- } else if (m.rel.followsMe) {
- relationship.emoji = "⚼";
- relationship.desc = i18n.relationshipTheyFollow;
- } else {
- relationship.emoji = "❓";
- relationship.desc = i18n.relationshipNotFollowing;
- }
- return div(
- { class: "mentions-container" },
- a(
- {
- class: "mentions-image",
- href: `/author/${encodeURIComponent(m.feed)}`,
- },
- img({ src: `/image/64/${encodeURIComponent(m.img)}` })
- ),
- a(
- {
- class: "mentions-name",
- href: `/author/${encodeURIComponent(m.feed)}`,
- },
- m.name
- ),
- div(
- { class: "emo-rel" },
- span(
- { class: "emoji", title: relationship.desc },
- relationship.emoji
- ),
- span(
- { class: "mentions-listing" },
- `[@${m.name}](${m.feed})`
- )
- )
- );
- })
- );
- })
- ),
- section(
- { class: "post-preview" },
- post({ msg }),
- // doesn't need blobs, preview adds them to the text
- form(
- { action, method: "post" },
- input({
- name: "contentWarning",
- type: "hidden",
- value: contentWarning,
- }),
- input({
- name: "text",
- type: "hidden",
- value: text,
- }),
- button({ type: "submit" }, i18n.publish)
- )
- )
- );
- };
- exports.previewView = ({ previewData, contentWarning }) => {
- const publishAction = "/publish";
- const preview = generatePreview({
- previewData,
- contentWarning,
- action: publishAction,
- });
- return exports.publishView(preview, previewData.text, contentWarning);
- };
- exports.peersView = async ({ peers }) => {
- const startButton = form(
- { action: "/settings/conn/start", method: "post" },
- button({ type: "submit" }, i18n.startNetworking)
- );
- const restartButton = form(
- { action: "/settings/conn/restart", method: "post" },
- button({ type: "submit" }, i18n.restartNetworking)
- );
- const stopButton = form(
- { action: "/settings/conn/stop", method: "post" },
- button({ type: "submit" }, i18n.stopNetworking)
- );
- const syncButton = form(
- { action: "/settings/conn/sync", method: "post" },
- button({ type: "submit" }, i18n.sync)
- );
- const connButtons = div({ class: "form-button-group" }, [
- startButton,
- restartButton,
- stopButton,
- syncButton,
- ]);
- const peerList = (peers || [])
- .filter(([, data]) => data.state === "connected")
- .map(([, data]) => {
- return li(
- a(
- { href: `/author/${encodeURIComponent(data.key)}` },
- data.name || data.host || data.key
- )
- );
- });
- try{
- var supporting = JSON.parse(fs.readFileSync(supportingPath, {encoding:'utf8', flag:'r'})).value;
- }catch{
- var supporting = undefined;
- }
- if (supporting == undefined) {
- var supportingValue = "false";
- }else{
- var keys = Object.keys(supporting);
- if (keys[0] === undefined){
- var supportingValue = "false";
- }else{
- var supportingValue = "true";
- }
- }
- if (supportingValue === "true") {
- var arr = [];
- var keys = Object.keys(supporting);
- var data = Object.entries(supporting[keys[0]]);
- Object.entries(data).forEach(([key, value]) => {
- if (value[1]===1){
- var supported = (value[0])
- if (!arr.includes(supported)) {
- arr.push(
- li(
- a(
- { href: `/author/${encodeURIComponent(supported)}` },
- supported
- )
- )
- );
- }
- }
- });
- }else{
- var arr = [];
- }
- var supports = arr;
- if (supportingValue === "true") {
- var arr = [];
- var keys = Object.keys(supporting);
- var data = Object.entries(supporting[keys[0]]);
- Object.entries(data).forEach(([key, value]) => {
- if (value[1]===-1){
- var blocked = (value[0])
- if (!arr.includes(blocked)) {
- arr.push(
- li(
- a(
- { href: `/author/${encodeURIComponent(blocked)}` },
- blocked
- )
- )
- );
- }
- }
- });
- }else{
- var arr = [];
- }
- var blocks = arr;
- if (supportingValue === "true") {
- var arr = [];
- var keys = Object.keys(supporting);
- var data = Object.entries(supporting[keys[0]]);
- Object.entries(data).forEach(([key, value]) => {
- if (value[1]===-2){
- var recommended = (value[0])
- if (!arr.includes(recommended)) {
- arr.push(
- li(
- a(
- { href: `/author/${encodeURIComponent(recommended)}` },
- recommended
- )
- )
- );
- }
- }
- });
- }else{
- var arr = [];
- }
- var recommends = arr;
- return template(
- i18n.peers,
- section(
- { class: "message" },
- h1(i18n.peerConnections),
- connButtons,
- h1(i18n.online, " (", peerList.length, ")"),
- peerList.length > 0 ? ul(peerList) : i18n.noConnections,
- p(i18n.connectionActionIntro),
- h1(i18n.supported, " (", supports.length, ")"),
- supports.length > 0 ? ul(supports): i18n.noSupportedConnections,
- p(i18n.connectionActionIntro),
- h1(i18n.recommended, " (", recommends.length, ")"),
- recommends.length > 0 ? ul(recommends): i18n.noRecommendedConnections,
- p(i18n.connectionActionIntro),
- h1(i18n.blocked, " (", blocks.length, ")"),
- blocks.length > 0 ? ul(blocks): i18n.noBlockedConnections,
- p(i18n.connectionActionIntro),
- )
- );
- };
- exports.invitesView = ({ invites }) => {
- const pubsList = (pub)
- var pubs = fs.readFileSync(offsetPath, "utf8");
- var arr = pubs.split(/[{,}]/);
- const arr2 = [];
- const arr3 = [];
- var host = [];
- var id = [];
- for(var i in arr){
- arr.push(arr[i]);
- }
- for(var i=0; i<arr.length; i++){
- if (arr[i] === '"address":') {
- host = arr[i+1].split(':').pop().split(';')[0].split('"')[1];
- id = arr[i+3].split(':').pop().split(';')[0].split('"')[1];
- }
- if (!arr2.includes(host + ":" + id)){
- arr2.push(host + ":" + id)
- }
- var f = arr2.filter(function (el) {
- return el != "" & el != ":";
- });
- }
- for(const v of f){
- var h = v.split(":")[0];
- var i = v.split(":")[1];
- arr3.push(
- li(
- "PUB: " + h, br,
- a(
- { href: `/author/${encodeURIComponent(i)}` },
- i
- ), br, br
- )
- );
- }
- var pub = arr3;
- return template(
- i18n.invites,
- section(
- { class: "message" },
- h1(i18n.invites),
- p(i18n.invitesDescription),
- form(
- { action: "/settings/invite/accept", method: "post" },
- input({ name: "invite", type: "text", autofocus: true, required: true }),
- button({ type: "submit" }, i18n.acceptInvite),
- h1(i18n.acceptedInvites, " (", pub.length, ")"),
- pub.length > 0 ? ul(pub): i18n.noInvites,
- ),
- )
- );
- };
- exports.settingsView = ({ theme, themeNames, version }) => {
- const themeElements = themeNames.map((cur) => {
- const isCurrentTheme = cur === theme;
- if (isCurrentTheme) {
- return option({ value: cur, selected: true }, cur);
- } else {
- return option({ value: cur }, cur);
- }
- });
- const base16 = [
- // '00', removed because this is the background
- "01",
- "02",
- "03",
- "04",
- "05",
- "06",
- "07",
- "08",
- "09",
- "0A",
- "0B",
- "0C",
- "0D",
- "0E",
- "0F",
- ];
- const base16Elements = base16.map((base) =>
- div({
- class: `theme-preview theme-preview-${base}`,
- })
- );
- const languageOption = (longName, shortName) =>
- shortName === selectedLanguage
- ? option({ value: shortName, selected: true }, longName)
- : option({ value: shortName }, longName);
- const rebuildButton = form(
- { action: "/settings/rebuild", method: "post" },
- button({ type: "submit" }, i18n.rebuildName)
- );
- if (ck === "required"){
- updaterequired = form(
- { action: "/update", method: "post" },
- button({ type: "submit"}, i18n.updateit)
- );
- };
- return template(
- i18n.settings,
- section(
- { class: "message" },
- h1(i18n.settings),
- p(a({ href:snhUrl, target: "_blank" }, i18n.settingsIntro({ version }))),
- p(updaterequired),
- h2(i18n.theme),
- p(i18n.themeIntro),
- form(
- { action: "/theme.css", method: "post" },
- select({ name: "theme" }, ...themeElements),
- button({ type: "submit" }, i18n.setTheme)
- ),
- h2(i18n.language),
- p(i18n.languageDescription),
- form(
- { action: "/language", method: "post" },
- select({ name: "language" }, [
- // Languages are sorted alphabetically by their 'long name'.
- /* spell-checker:disable */
- languageOption("English", "en"),
- languageOption("Español", "es"),
- /* spell-checker:enable */
- ]),
- button({ type: "submit" }, i18n.setLanguage)
- ),
- h2(i18n.indexes),
- p(i18n.indexesDescription),
- rebuildButton,
- )
- );
- };
- /** @param {{ viewTitle: string, viewDescription: string }} input */
- const viewInfoBox = ({ viewTitle = null, viewDescription = null }) => {
- if (!viewTitle && !viewDescription) {
- return null;
- }
- return section(
- { class: "viewInfo" },
- viewTitle ? h1(viewTitle) : null,
- viewDescription ? em(viewDescription) : null
- );
- };
- exports.likesView = async ({ messages, feed, name }) => {
- const authorLink = a(
- { href: `/author/${encodeURIComponent(feed)}` },
- "@" + name
- );
- return template(
- ["@", name, i18n.likedBy],
- viewInfoBox({
- viewTitle: span(authorLink, i18n.likedBy),
- viewDescription: span(i18n.spreadedDescription)
- }),
- messages.map((msg) => post({ msg }))
- );
- };
- const messageListView = ({
- messages,
- viewTitle = null,
- viewDescription = null,
- viewElements = null,
- // If `aside = true`, it will show a few comments in the thread.
- aside = null,
- }) => {
- return template(
- viewTitle,
- section(h1(viewTitle), p(viewDescription), viewElements),
- messages.map((msg) => post({ msg, aside }))
- );
- };
- exports.popularView = ({ messages, prefix }) => {
- return messageListView({
- messages,
- viewElements: prefix,
- viewTitle: i18n.popular,
- viewDescription: i18n.popularDescription,
- });
- };
- exports.extendedView = ({ messages }) => {
- return messageListView({
- messages,
- viewTitle: i18n.extended,
- viewDescription: i18n.extendedDescription,
- });
- };
- exports.latestView = ({ messages }) => {
- return messageListView({
- messages,
- viewTitle: i18n.latest,
- viewDescription: i18n.latestDescription,
- });
- };
- exports.topicsView = ({ messages, prefix }) => {
- return messageListView({
- messages,
- viewTitle: i18n.topics,
- viewDescription: i18n.topicsDescription,
- viewElements: prefix,
- });
- };
- exports.summaryView = ({ messages }) => {
- return messageListView({
- messages,
- viewTitle: i18n.summaries,
- viewDescription: i18n.summariesDescription,
- aside: true,
- });
- };
- exports.spreadedView = ({ messages }) => {
- return spreadedListView({
- messages,
- viewTitle: i18n.spreaded,
- viewDescription: i18n.spreadedDescription,
- });
- };
- exports.threadsView = ({ messages }) => {
- return messageListView({
- messages,
- viewTitle: i18n.threads,
- viewDescription: i18n.threadsDescription,
- aside: true,
- });
- };
- exports.previewSubtopicView = async ({
- previewData,
- messages,
- myFeedId,
- contentWarning,
- }) => {
- const publishAction = `/subtopic/${encodeURIComponent(messages[0].key)}`;
- const preview = generatePreview({
- previewData,
- contentWarning,
- action: publishAction,
- });
- return exports.subtopicView(
- { messages, myFeedId },
- preview,
- previewData.text,
- contentWarning
- );
- };
- exports.subtopicView = async (
- { messages, myFeedId },
- preview,
- text,
- contentWarning
- ) => {
- const subtopicForm = `/subtopic/preview/${encodeURIComponent(
- messages[messages.length - 1].key
- )}`;
- let markdownMention;
- const messageElements = await Promise.all(
- messages.reverse().map((message) => {
- debug("%O", message);
- const authorName = message.value.meta.author.name;
- const authorFeedId = message.value.author;
- if (authorFeedId !== myFeedId) {
- if (message.key === messages[0].key) {
- const x = `[@${authorName}](${authorFeedId})\n\n`;
- markdownMention = x;
- }
- }
- return post({ msg: message });
- })
- );
- const authorName = messages[messages.length - 1].value.meta.author.name;
- return template(
- i18n.subtopicTitle({ authorName }),
- div({ class: "thread-container" }, messageElements),
- preview !== undefined ? preview : "",
- p(i18n.subtopicLabel({ markdownUrl })),
- form(
- { action: subtopicForm, method: "post", enctype: "multipart/form-data" },
- textarea(
- {
- autofocus: true,
- required: true,
- name: "text",
- },
- text ? text : markdownMention
- ),
- label(
- i18n.contentWarningLabel,
- input({
- name: "contentWarning",
- type: "text",
- class: "contentWarning",
- value: contentWarning ? contentWarning : "",
- placeholder: i18n.contentWarningPlaceholder,
- })
- ),
- button({ type: "submit" }, i18n.preview),
- label({ class: "file-button", for: "blob" }, i18n.attachFiles),
- input({ type: "file", id: "blob", name: "blob" })
- )
- );
- };
- exports.searchView = ({ messages, query }) => {
- const searchInput = input({
- name: "query",
- required: false,
- type: "search",
- value: query,
- });
- // - Minimum length of 3 because otherwise SSB-Search hangs forever. :)
- // https://github.com/ssbc/ssb-search/issues/8
- // - Using `setAttribute()` because HyperScript (the HyperAxe dependency has
- // a bug where the `minlength` property is being ignored. No idea why.
- // https://github.com/hyperhype/hyperscript/issues/91
- searchInput.setAttribute("minlength", 3);
- return template(
- i18n.search,
- section(
- h1(i18n.search),
- form(
- { action: "/search", method: "get" },
- label(i18n.searchLabel, searchInput),
- button(
- {
- type: "submit",
- },
- i18n.submit
- )
- )
- ),
- messages.map((msg) => post({ msg }))
- );
- };
- const imageResult = ({ id, infos }) => {
- const encodedBlobId = encodeURIComponent(id);
- // only rendering the first message result so far
- // todo: render links to the others as well
- const info = infos[0];
- const encodedMsgId = encodeURIComponent(info.msg);
- return div(
- {
- class: "image-result",
- },
- [
- a(
- {
- href: `/blob/${encodedBlobId}`,
- },
- img({ src: `/image/256/${encodedBlobId}` })
- ),
- a(
- {
- href: `/thread/${encodedMsgId}#${encodedMsgId}`,
- class: "result-text",
- },
- info.name
- ),
- ]
- );
- };
- exports.imageSearchView = ({ blobs, query }) => {
- const searchInput = input({
- name: "query",
- required: false,
- type: "search",
- value: query,
- });
- // - Minimum length of 3 because otherwise SSB-Search hangs forever. :)
- // https://github.com/ssbc/ssb-search/issues/8
- // - Using `setAttribute()` because HyperScript (the HyperAxe dependency has
- // a bug where the `minlength` property is being ignored. No idea why.
- // https://github.com/hyperhype/hyperscript/issues/91
- searchInput.setAttribute("minlength", 3);
- return template(
- i18n.imageSearch,
- section(
- h1(i18n.imageSearch),
- form(
- { action: "/imageSearch", method: "get" },
- label(i18n.imageSearchLabel, searchInput),
- button(
- {
- type: "submit",
- },
- i18n.submit
- )
- )
- ),
- div(
- {
- class: "image-search-grid",
- },
- Object.keys(blobs)
- // todo: add pagination
- .slice(0, 30)
- .map((blobId) => imageResult({ id: blobId, infos: blobs[blobId] }))
- )
- );
- };
- exports.hashtagView = ({ messages, hashtag }) => {
- return template(
- `#${hashtag}`,
- section(h1(`#${hashtag}`), p(i18n.hashtagDescription)),
- messages.map((msg) => post({ msg }))
- );
- };
- /** @param {{percent: number}} input */
- exports.indexingView = ({ percent }) => {
- // TODO: i18n
- const message = `Oasis has only processed ${percent}% of the messages and needs to catch up. This page will refresh every 10 seconds. Thanks for your patience! ❤`;
- const nodes = html(
- { lang: "en" },
- head(
- title("Oasis"),
- link({ rel: "icon", type: "image/svg+xml", href: "/assets/favicon.svg" }),
- meta({ charset: "utf-8" }),
- meta({
- name: "description",
- content: i18n.oasisDescription,
- }),
- meta({
- name: "viewport",
- content: toAttributes({ width: "device-width", "initial-scale": 1 }),
- }),
- meta({ "http-equiv": "refresh", content: 10 })
- ),
- body(
- main(
- { id: "content" },
- p(message),
- progress({ value: percent, max: 100 })
- )
- )
- );
- const result = doctypeString + nodes.outerHTML;
- return result;
- };
|