videos_model.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 !== "video") 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 buildVideo = (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. opinions: c.opinions || {},
  90. opinions_inhabitants: voters,
  91. hasVoted: viewerId ? voters.includes(viewerId) : false
  92. };
  93. };
  94. return {
  95. type: "video",
  96. async resolveCurrentId(id) {
  97. const ssbClient = await openSsb();
  98. const messages = await getAllMessages(ssbClient);
  99. const idx = buildIndex(messages);
  100. let tip = id;
  101. while (idx.forward.has(tip)) tip = idx.forward.get(tip);
  102. if (idx.tomb.has(tip)) throw new Error("Video not found");
  103. return tip;
  104. },
  105. async resolveRootId(id) {
  106. const ssbClient = await openSsb();
  107. const messages = await getAllMessages(ssbClient);
  108. const idx = buildIndex(messages);
  109. let tip = id;
  110. while (idx.forward.has(tip)) tip = idx.forward.get(tip);
  111. if (idx.tomb.has(tip)) throw new Error("Video not found");
  112. let root = tip;
  113. while (idx.parent.has(root)) root = idx.parent.get(root);
  114. return root;
  115. },
  116. async createVideo(blobMarkdown, tagsRaw, title, description, mapUrl) {
  117. const ssbClient = await openSsb();
  118. const blobId = parseBlobId(blobMarkdown);
  119. const tags = normalizeTags(tagsRaw) || [];
  120. const now = new Date().toISOString();
  121. const content = {
  122. type: "video",
  123. url: blobId,
  124. createdAt: now,
  125. updatedAt: now,
  126. author: ssbClient.id,
  127. tags,
  128. title: title || "",
  129. description: description || "",
  130. mapUrl: mapUrl || "",
  131. opinions: {},
  132. opinions_inhabitants: []
  133. };
  134. return new Promise((resolve, reject) => {
  135. ssbClient.publish(content, (err, res) => (err ? reject(err) : resolve(res)));
  136. });
  137. },
  138. async updateVideoById(id, blobMarkdown, tagsRaw, title, description, mapUrl) {
  139. const ssbClient = await openSsb();
  140. const userId = ssbClient.id;
  141. const tipId = await this.resolveCurrentId(id);
  142. const oldMsg = await getMsg(ssbClient, tipId);
  143. if (!oldMsg || oldMsg.content?.type !== "video") throw new Error("Video not found");
  144. if (Object.keys(oldMsg.content.opinions || {}).length > 0) throw new Error("Cannot edit video after it has received opinions.");
  145. if (oldMsg.content.author !== userId) throw new Error("Not the author");
  146. const tags = tagsRaw !== undefined ? normalizeTags(tagsRaw) || [] : safeArr(oldMsg.content.tags);
  147. const blobId = blobMarkdown ? parseBlobId(blobMarkdown) : null;
  148. const now = new Date().toISOString();
  149. const updated = {
  150. ...oldMsg.content,
  151. replaces: tipId,
  152. url: blobId || oldMsg.content.url,
  153. tags,
  154. title: title !== undefined ? title || "" : oldMsg.content.title || "",
  155. description: description !== undefined ? description || "" : oldMsg.content.description || "",
  156. mapUrl: mapUrl !== undefined ? mapUrl || "" : oldMsg.content.mapUrl || "",
  157. createdAt: oldMsg.content.createdAt,
  158. updatedAt: now
  159. };
  160. const tombstone = { type: "tombstone", target: tipId, deletedAt: now, author: userId };
  161. await new Promise((res, rej) => ssbClient.publish(tombstone, (e) => (e ? rej(e) : res())));
  162. return new Promise((resolve, reject) => {
  163. ssbClient.publish(updated, (err, result) => (err ? reject(err) : resolve(result)));
  164. });
  165. },
  166. async deleteVideoById(id) {
  167. const ssbClient = await openSsb();
  168. const userId = ssbClient.id;
  169. const tipId = await this.resolveCurrentId(id);
  170. const msg = await getMsg(ssbClient, tipId);
  171. if (!msg || msg.content?.type !== "video") throw new Error("Video not found");
  172. if (msg.content.author !== userId) throw new Error("Not the author");
  173. const tombstone = { type: "tombstone", target: tipId, deletedAt: new Date().toISOString(), author: userId };
  174. return new Promise((resolve, reject) => {
  175. ssbClient.publish(tombstone, (err2, res) => (err2 ? reject(err2) : resolve(res)));
  176. });
  177. },
  178. async listAll(filterOrOpts = "all", maybeOpts = {}) {
  179. const ssbClient = await openSsb();
  180. const opts = typeof filterOrOpts === "object" ? filterOrOpts : maybeOpts || {};
  181. const filter = (typeof filterOrOpts === "string" ? filterOrOpts : opts.filter || "all") || "all";
  182. const q = String(opts.q || "").trim().toLowerCase();
  183. const sort = String(opts.sort || "recent").trim();
  184. const viewerId = opts.viewerId || ssbClient.id;
  185. const messages = await getAllMessages(ssbClient);
  186. const idx = buildIndex(messages);
  187. const items = [];
  188. for (const [rootId, tipId] of idx.tipByRoot.entries()) {
  189. if (idx.tomb.has(tipId)) continue;
  190. const node = idx.nodes.get(tipId);
  191. if (!node) continue;
  192. items.push(buildVideo(node, rootId, viewerId));
  193. }
  194. let list = items;
  195. const now = Date.now();
  196. if (filter === "mine") list = list.filter((v) => String(v.author) === String(viewerId));
  197. else if (filter === "recent") list = list.filter((v) => new Date(v.createdAt).getTime() >= now - 86400000);
  198. else if (filter === "top") {
  199. list = list
  200. .slice()
  201. .sort((a, b) => voteSum(b.opinions) - voteSum(a.opinions) || new Date(b.createdAt) - new Date(a.createdAt));
  202. }
  203. if (q) {
  204. list = list.filter((v) => {
  205. const t = String(v.title || "").toLowerCase();
  206. const d = String(v.description || "").toLowerCase();
  207. const tags = safeArr(v.tags).join(" ").toLowerCase();
  208. const a = String(v.author || "").toLowerCase();
  209. return t.includes(q) || d.includes(q) || tags.includes(q) || a.includes(q);
  210. });
  211. }
  212. if (sort === "top") {
  213. list = list
  214. .slice()
  215. .sort((a, b) => voteSum(b.opinions) - voteSum(a.opinions) || new Date(b.createdAt) - new Date(a.createdAt));
  216. } else if (sort === "oldest") {
  217. list = list.slice().sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
  218. } else {
  219. list = list.slice().sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  220. }
  221. return list;
  222. },
  223. async getVideoById(id, viewerId = null) {
  224. const ssbClient = await openSsb();
  225. const viewer = viewerId || ssbClient.id;
  226. const messages = await getAllMessages(ssbClient);
  227. const idx = buildIndex(messages);
  228. let tip = id;
  229. while (idx.forward.has(tip)) tip = idx.forward.get(tip);
  230. if (idx.tomb.has(tip)) throw new Error("Video not found");
  231. let root = tip;
  232. while (idx.parent.has(root)) root = idx.parent.get(root);
  233. const node = idx.nodes.get(tip);
  234. if (node) return buildVideo(node, root, viewer);
  235. const msg = await getMsg(ssbClient, tip);
  236. if (!msg || msg.content?.type !== "video") throw new Error("Video not found");
  237. return buildVideo({ key: tip, ts: msg.timestamp || 0, c: msg.content }, root, viewer);
  238. },
  239. async createOpinion(id, category) {
  240. if (!categories.includes(category)) throw new Error("Invalid voting category");
  241. const ssbClient = await openSsb();
  242. const userId = ssbClient.id;
  243. const tipId = await this.resolveCurrentId(id);
  244. const msg = await getMsg(ssbClient, tipId);
  245. if (!msg || msg.content?.type !== "video") throw new Error("Video not found");
  246. const voters = safeArr(msg.content.opinions_inhabitants);
  247. if (voters.includes(userId)) throw new Error("Already voted");
  248. const now = new Date().toISOString();
  249. const updated = {
  250. ...msg.content,
  251. replaces: tipId,
  252. opinions: {
  253. ...msg.content.opinions,
  254. [category]: (msg.content.opinions?.[category] || 0) + 1
  255. },
  256. opinions_inhabitants: voters.concat(userId),
  257. updatedAt: now
  258. };
  259. const tombstone = { type: "tombstone", target: tipId, deletedAt: now, author: userId };
  260. await new Promise((res, rej) => ssbClient.publish(tombstone, (e) => (e ? rej(e) : res())));
  261. return new Promise((resolve, reject) => {
  262. ssbClient.publish(updated, (err2, result) => (err2 ? reject(err2) : resolve(result)));
  263. });
  264. }
  265. };
  266. };