images_model.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. const pull = require("../server/node_modules/pull-stream");
  2. const { getConfig } = require("../configs/config-manager.js");
  3. const categories = require("../backend/opinion_categories");
  4. const logLimit = getConfig().ssbLogStream?.limit || 1000;
  5. const safeArr = (v) => (Array.isArray(v) ? v : []);
  6. const normalizeTags = (raw) => {
  7. if (raw === undefined || raw === null) return undefined;
  8. if (Array.isArray(raw)) return raw.map((t) => String(t || "").trim()).filter(Boolean);
  9. return String(raw).split(",").map((t) => t.trim()).filter(Boolean);
  10. };
  11. const parseBlobId = (blobMarkdown) => {
  12. const s = String(blobMarkdown || "");
  13. const match = s.match(/\(([^)]+)\)/);
  14. return match ? match[1] : s || null;
  15. };
  16. const voteSum = (opinions = {}) =>
  17. Object.values(opinions || {}).reduce((s, n) => s + (Number(n) || 0), 0);
  18. module.exports = ({ cooler }) => {
  19. let ssb;
  20. const openSsb = async () => {
  21. if (!ssb) ssb = await cooler.open();
  22. return ssb;
  23. };
  24. const getAllMessages = async (ssbClient) =>
  25. new Promise((resolve, reject) => {
  26. pull(
  27. ssbClient.createLogStream({ limit: logLimit }),
  28. pull.collect((err, msgs) => (err ? reject(err) : resolve(msgs)))
  29. );
  30. });
  31. const getMsg = async (ssbClient, key) =>
  32. new Promise((resolve, reject) => {
  33. ssbClient.get(key, (err, msg) => (err ? reject(err) : resolve(msg)));
  34. });
  35. const buildIndex = (messages) => {
  36. const tomb = new Set();
  37. const nodes = new Map();
  38. const parent = new Map();
  39. const child = new Map();
  40. for (const m of messages) {
  41. const k = m.key;
  42. const v = m.value || {};
  43. const c = v.content;
  44. if (!c) continue;
  45. if (c.type === "tombstone" && c.target) {
  46. tomb.add(c.target);
  47. continue;
  48. }
  49. if (c.type !== "image") continue;
  50. const ts = v.timestamp || m.timestamp || 0;
  51. nodes.set(k, { key: k, ts, c });
  52. if (c.replaces) {
  53. parent.set(k, c.replaces);
  54. child.set(c.replaces, k);
  55. }
  56. }
  57. const rootOf = (id) => {
  58. let cur = id;
  59. while (parent.has(cur)) cur = parent.get(cur);
  60. return cur;
  61. };
  62. const tipOf = (id) => {
  63. let cur = id;
  64. while (child.has(cur)) cur = child.get(cur);
  65. return cur;
  66. };
  67. const roots = new Set();
  68. for (const id of nodes.keys()) roots.add(rootOf(id));
  69. const tipByRoot = new Map();
  70. for (const r of roots) tipByRoot.set(r, tipOf(r));
  71. const forward = new Map();
  72. for (const [newId, oldId] of parent.entries()) forward.set(oldId, newId);
  73. return { tomb, nodes, parent, child, rootOf, tipOf, tipByRoot, forward };
  74. };
  75. const buildImage = (node, rootId, viewerId) => {
  76. const c = node.c || {};
  77. const voters = safeArr(c.opinions_inhabitants);
  78. return {
  79. key: node.key,
  80. rootId,
  81. url: c.url,
  82. createdAt: c.createdAt || new Date(node.ts).toISOString(),
  83. updatedAt: c.updatedAt || null,
  84. tags: safeArr(c.tags),
  85. author: c.author,
  86. title: c.title || "",
  87. description: c.description || "",
  88. mapUrl: c.mapUrl || "",
  89. meme: !!c.meme,
  90. opinions: c.opinions || {},
  91. opinions_inhabitants: voters,
  92. hasVoted: viewerId ? voters.includes(viewerId) : false
  93. };
  94. };
  95. return {
  96. type: "image",
  97. async resolveCurrentId(id) {
  98. const ssbClient = await openSsb();
  99. const messages = await getAllMessages(ssbClient);
  100. const idx = buildIndex(messages);
  101. let tip = id;
  102. while (idx.forward.has(tip)) tip = idx.forward.get(tip);
  103. if (idx.tomb.has(tip)) throw new Error("Image not found");
  104. return tip;
  105. },
  106. async resolveRootId(id) {
  107. const ssbClient = await openSsb();
  108. const messages = await getAllMessages(ssbClient);
  109. const idx = buildIndex(messages);
  110. let tip = id;
  111. while (idx.forward.has(tip)) tip = idx.forward.get(tip);
  112. if (idx.tomb.has(tip)) throw new Error("Image not found");
  113. let root = tip;
  114. while (idx.parent.has(root)) root = idx.parent.get(root);
  115. return root;
  116. },
  117. async createImage(blobMarkdown, tagsRaw, title, description, memeBool, mapUrl) {
  118. const ssbClient = await openSsb();
  119. const blobId = parseBlobId(blobMarkdown);
  120. const tags = normalizeTags(tagsRaw) || [];
  121. const now = new Date().toISOString();
  122. const content = {
  123. type: "image",
  124. url: blobId,
  125. createdAt: now,
  126. updatedAt: now,
  127. author: ssbClient.id,
  128. tags,
  129. title: title || "",
  130. description: description || "",
  131. mapUrl: mapUrl || "",
  132. meme: !!memeBool,
  133. opinions: {},
  134. opinions_inhabitants: []
  135. };
  136. return new Promise((resolve, reject) => {
  137. ssbClient.publish(content, (err, res) => (err ? reject(err) : resolve(res)));
  138. });
  139. },
  140. async updateImageById(id, blobMarkdown, tagsRaw, title, description, memeBool, mapUrl) {
  141. const ssbClient = await openSsb();
  142. const userId = ssbClient.id;
  143. const tipId = await this.resolveCurrentId(id);
  144. const oldMsg = await getMsg(ssbClient, tipId);
  145. if (!oldMsg || oldMsg.content?.type !== "image") throw new Error("Image not found");
  146. if (Object.keys(oldMsg.content.opinions || {}).length > 0) throw new Error("Cannot edit image after it has received opinions.");
  147. if (oldMsg.content.author !== userId) throw new Error("Not the author");
  148. const tags = tagsRaw !== undefined ? normalizeTags(tagsRaw) || [] : safeArr(oldMsg.content.tags);
  149. const blobId = blobMarkdown ? parseBlobId(blobMarkdown) : null;
  150. const now = new Date().toISOString();
  151. const updated = {
  152. ...oldMsg.content,
  153. replaces: tipId,
  154. url: blobId || oldMsg.content.url,
  155. tags,
  156. title: title !== undefined ? title || "" : oldMsg.content.title || "",
  157. description: description !== undefined ? description || "" : oldMsg.content.description || "",
  158. mapUrl: mapUrl !== undefined ? mapUrl || "" : oldMsg.content.mapUrl || "",
  159. meme: typeof memeBool === "boolean" ? memeBool : !!oldMsg.content.meme,
  160. createdAt: oldMsg.content.createdAt,
  161. updatedAt: now
  162. };
  163. const tombstone = { type: "tombstone", target: tipId, deletedAt: now, author: userId };
  164. await new Promise((res, rej) => ssbClient.publish(tombstone, (e) => (e ? rej(e) : res())));
  165. return new Promise((resolve, reject) => {
  166. ssbClient.publish(updated, (err, result) => (err ? reject(err) : resolve(result)));
  167. });
  168. },
  169. async deleteImageById(id) {
  170. const ssbClient = await openSsb();
  171. const userId = ssbClient.id;
  172. const tipId = await this.resolveCurrentId(id);
  173. const msg = await getMsg(ssbClient, tipId);
  174. if (!msg || msg.content?.type !== "image") throw new Error("Image not found");
  175. if (msg.content.author !== userId) throw new Error("Not the author");
  176. const tombstone = { type: "tombstone", target: tipId, deletedAt: new Date().toISOString(), author: userId };
  177. return new Promise((resolve, reject) => {
  178. ssbClient.publish(tombstone, (err2, res) => (err2 ? reject(err2) : resolve(res)));
  179. });
  180. },
  181. async listAll(filterOrOpts = "all", maybeOpts = {}) {
  182. const ssbClient = await openSsb();
  183. const opts = typeof filterOrOpts === "object" ? filterOrOpts : maybeOpts || {};
  184. const filter = (typeof filterOrOpts === "string" ? filterOrOpts : opts.filter || "all") || "all";
  185. const q = String(opts.q || "").trim().toLowerCase();
  186. const sort = String(opts.sort || "recent").trim();
  187. const viewerId = opts.viewerId || ssbClient.id;
  188. const messages = await getAllMessages(ssbClient);
  189. const idx = buildIndex(messages);
  190. const items = [];
  191. for (const [rootId, tipId] of idx.tipByRoot.entries()) {
  192. if (idx.tomb.has(tipId)) continue;
  193. const node = idx.nodes.get(tipId);
  194. if (!node) continue;
  195. items.push(buildImage(node, rootId, viewerId));
  196. }
  197. let list = items;
  198. const now = Date.now();
  199. if (filter === "mine") list = list.filter((im) => String(im.author) === String(viewerId));
  200. else if (filter === "recent") list = list.filter((im) => new Date(im.createdAt).getTime() >= now - 86400000);
  201. else if (filter === "meme") list = list.filter((im) => im.meme === true);
  202. else if (filter === "top") {
  203. list = list
  204. .slice()
  205. .sort((a, b) => voteSum(b.opinions) - voteSum(a.opinions) || new Date(b.createdAt) - new Date(a.createdAt));
  206. }
  207. if (q) {
  208. list = list.filter((im) => {
  209. const t = String(im.title || "").toLowerCase();
  210. const d = String(im.description || "").toLowerCase();
  211. const tags = safeArr(im.tags).join(" ").toLowerCase();
  212. const a = String(im.author || "").toLowerCase();
  213. return t.includes(q) || d.includes(q) || tags.includes(q) || a.includes(q);
  214. });
  215. }
  216. if (sort === "top") {
  217. list = list
  218. .slice()
  219. .sort((a, b) => voteSum(b.opinions) - voteSum(a.opinions) || new Date(b.createdAt) - new Date(a.createdAt));
  220. } else if (sort === "oldest") {
  221. list = list.slice().sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
  222. } else {
  223. list = list.slice().sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  224. }
  225. return list;
  226. },
  227. async getImageById(id, viewerId = null) {
  228. const ssbClient = await openSsb();
  229. const viewer = viewerId || ssbClient.id;
  230. const messages = await getAllMessages(ssbClient);
  231. const idx = buildIndex(messages);
  232. let tip = id;
  233. while (idx.forward.has(tip)) tip = idx.forward.get(tip);
  234. if (idx.tomb.has(tip)) throw new Error("Image not found");
  235. let root = tip;
  236. while (idx.parent.has(root)) root = idx.parent.get(root);
  237. const node = idx.nodes.get(tip);
  238. if (node) return buildImage(node, root, viewer);
  239. const msg = await getMsg(ssbClient, tip);
  240. if (!msg || msg.content?.type !== "image") throw new Error("Image not found");
  241. return buildImage({ key: tip, ts: msg.timestamp || 0, c: msg.content }, root, viewer);
  242. },
  243. async createOpinion(id, category) {
  244. if (!categories.includes(category)) throw new Error("Invalid voting category");
  245. const ssbClient = await openSsb();
  246. const userId = ssbClient.id;
  247. const tipId = await this.resolveCurrentId(id);
  248. const msg = await getMsg(ssbClient, tipId);
  249. if (!msg || msg.content?.type !== "image") throw new Error("Image not found");
  250. const voters = safeArr(msg.content.opinions_inhabitants);
  251. if (voters.includes(userId)) throw new Error("Already voted");
  252. const now = new Date().toISOString();
  253. const updated = {
  254. ...msg.content,
  255. replaces: tipId,
  256. opinions: {
  257. ...msg.content.opinions,
  258. [category]: (msg.content.opinions?.[category] || 0) + 1
  259. },
  260. opinions_inhabitants: voters.concat(userId),
  261. updatedAt: now
  262. };
  263. const tombstone = { type: "tombstone", target: tipId, deletedAt: now, author: userId };
  264. await new Promise((res, rej) => ssbClient.publish(tombstone, (e) => (e ? rej(e) : res())));
  265. return new Promise((resolve, reject) => {
  266. ssbClient.publish(updated, (err2, result) => (err2 ? reject(err2) : resolve(result)));
  267. });
  268. }
  269. };
  270. };