activity_model.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. const pull = require('../server/node_modules/pull-stream');
  2. const ssbRef = require('../server/node_modules/ssb-ref');
  3. const { getConfig } = require('../configs/config-manager.js');
  4. const logLimit = getConfig().ssbLogStream?.limit || 1000;
  5. const safeFeedId = (v) => {
  6. if (typeof v === 'string' && ssbRef.isFeed(v)) return v;
  7. if (v && typeof v === 'object' && typeof v.link === 'string' && ssbRef.isFeed(v.link)) return v.link;
  8. return null;
  9. };
  10. const isContentSane = (c) => {
  11. if (!c || typeof c !== 'object') return false;
  12. if (c.type === 'contact') return !!safeFeedId(c.contact);
  13. if (c.type === 'about') {
  14. if (c.about === undefined) return true;
  15. if (typeof c.about === 'string' && ssbRef.isFeed(c.about)) return true;
  16. return false;
  17. }
  18. if (c.type === 'pub') {
  19. const addr = c.address;
  20. if (!addr || typeof addr !== 'object') return false;
  21. return typeof addr.key === 'string' && ssbRef.isFeed(addr.key);
  22. }
  23. return true;
  24. };
  25. const N = s => String(s || '').toUpperCase().replace(/\s+/g, '_');
  26. const ORDER_MARKET = ['FOR_SALE','OPEN','RESERVED','CLOSED','SOLD'];
  27. const ORDER_PROJECT = ['CANCELLED','PAUSED','ACTIVE','COMPLETED'];
  28. const SCORE_MARKET = s => { const i = ORDER_MARKET.indexOf(N(s)); return i < 0 ? -1 : i };
  29. const SCORE_PROJECT = s => { const i = ORDER_PROJECT.indexOf(N(s)); return i < 0 ? -1 : i };
  30. function inferType(c = {}) {
  31. if (c.type === 'wallet' && c.coin === 'ECO' && typeof c.address === 'string') return 'bankWallet';
  32. if (c.type === 'bankClaim') return 'bankClaim';
  33. if (c.type === 'karmaScore') return 'karmaScore';
  34. if (c.type === 'courts_case') return 'courtsCase';
  35. if (c.type === 'courts_evidence') return 'courtsEvidence';
  36. if (c.type === 'courts_answer') return 'courtsAnswer';
  37. if (c.type === 'courts_verdict') return 'courtsVerdict';
  38. if (c.type === 'courts_settlement') return 'courtsSettlement';
  39. if (c.type === 'courts_nomination') return 'courtsNomination';
  40. if (c.type === 'courts_nom_vote') return 'courtsNominationVote';
  41. if (c.type === 'courts_public_pref') return 'courtsPublicPref';
  42. if (c.type === 'courts_mediators') return 'courtsMediators';
  43. if (c.type === 'map') return 'map';
  44. if (c.type === 'mapMarker') return 'mapMarker';
  45. if (c.type === 'chat') return 'chat';
  46. if (c.type === 'chatMessage') return 'chatMessage';
  47. if (c.type === 'vote' && c.vote && typeof c.vote.link === 'string') {
  48. const br = Array.isArray(c.branch) ? c.branch : [];
  49. if (br.includes(c.vote.link) && Number(c.vote.value) === 1) return 'spread';
  50. }
  51. return c.type || '';
  52. }
  53. const HIDDEN_ENVELOPE_TYPES = new Set([
  54. 'tribe-keys-distrib',
  55. 'tribe-invite-msg',
  56. 'tribe-invite-tombstone'
  57. ]);
  58. module.exports = ({ cooler, tribeCrypto, tribesModel }) => {
  59. let ssb;
  60. const openSsb = async () => { if (!ssb) ssb = await cooler.open(); return ssb };
  61. let _feedCache = null;
  62. let _feedCacheInflight = null;
  63. const FEED_CACHE_MS = 15 * 1000;
  64. const buildAccessibleTribeIds = async () => {
  65. const set = new Set();
  66. if (!tribesModel) return set;
  67. try {
  68. const list = await tribesModel.listAll();
  69. for (const t of list) {
  70. if (!t || !t.id) continue;
  71. set.add(t.id);
  72. try {
  73. const chain = await tribesModel.getChainIds(t.id);
  74. for (const cid of chain) set.add(cid);
  75. } catch (_) {}
  76. }
  77. } catch (_) {}
  78. return set;
  79. };
  80. const hasBlob = async (ssbClient, url) => new Promise(resolve => ssbClient.blobs.has(url, (err, has) => resolve(!err && has)));
  81. const getMsg = async (ssbClient, key) => new Promise(resolve => ssbClient.get(key, (err, msg) => resolve(err ? null : msg)));
  82. const normNL = (s) => String(s || '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
  83. const stripHtml = (s) => normNL(s)
  84. .replace(/<br\s*\/?>/gi, '\n')
  85. .replace(/<\/p\s*>/gi, '\n\n')
  86. .replace(/<[^>]*>/g, '')
  87. .replace(/[ \t]+\n/g, '\n')
  88. .replace(/\n{3,}/g, '\n\n')
  89. .trim();
  90. const excerpt = (s, max = 900) => {
  91. const t = stripHtml(s);
  92. if (!t) return '';
  93. return t.length > max ? t.slice(0, max - 1) + '…' : t;
  94. };
  95. return {
  96. invalidateCache() {
  97. _feedCache = null;
  98. _feedCacheInflight = null;
  99. },
  100. async listFeed(filter = 'all') {
  101. const cacheKey = filter || 'all';
  102. const now = Date.now();
  103. if (!_feedCache) _feedCache = new Map();
  104. const entry = _feedCache.get(cacheKey);
  105. if (entry && now - entry.ts < FEED_CACHE_MS) return entry.value;
  106. if (!_feedCacheInflight) _feedCacheInflight = new Map();
  107. if (_feedCacheInflight.has(cacheKey)) return _feedCacheInflight.get(cacheKey);
  108. const promise = (async () => {
  109. const ssbClient = await openSsb();
  110. const userId = ssbClient.id;
  111. const results = await new Promise((resolve, reject) => {
  112. pull(
  113. ssbClient.createLogStream({ reverse: true, limit: logLimit }),
  114. pull.collect((err, msgs) => err ? reject(err) : resolve(msgs))
  115. );
  116. });
  117. const tombstoned = new Set();
  118. const parentOf = new Map();
  119. const idToAction = new Map();
  120. const rawById = new Map();
  121. const fpIdx = tribeCrypto ? tribeCrypto.buildFingerprintIndex() : null;
  122. const accessibleTribeIds = await buildAccessibleTribeIds();
  123. for (const msg of results) {
  124. const k = msg.key;
  125. const v = msg.value;
  126. let c = v?.content;
  127. if (!c) continue;
  128. if (typeof c === 'string' && c.endsWith('.box')) continue;
  129. if (c.type && HIDDEN_ENVELOPE_TYPES.has(c.type)) continue;
  130. if (tribeCrypto && tribeCrypto.isTribeMsg(c)) {
  131. const r = fpIdx ? tribeCrypto.unwrapMsg(c, fpIdx) : null;
  132. if (!r || !r.body) continue;
  133. const inner = r.body;
  134. if (inner.k !== 'tribe' || inner.op !== 'create') continue;
  135. c = { ...inner, type: 'tribe', _decrypted: true, _rootId: r.rootId };
  136. } else if (c.tribeId && !accessibleTribeIds.has(c.tribeId)) {
  137. continue;
  138. }
  139. if (!c.type) continue;
  140. if (c.type === 'tombstone' && c.target) { tombstoned.add(c.target); continue }
  141. if (!isContentSane(c)) continue;
  142. const ts = v?.timestamp || Number(c?.timestamp || 0) || (c?.updatedAt ? Date.parse(c.updatedAt) : 0) || 0;
  143. const normalized = c.type === 'contact' ? { ...c, contact: safeFeedId(c.contact) } : c;
  144. idToAction.set(k, { id: k, author: v?.author, ts, type: inferType(c), content: normalized });
  145. rawById.set(k, msg);
  146. if (c.replaces) parentOf.set(k, c.replaces);
  147. }
  148. const replacedIds = new Set(parentOf.values());
  149. const spreadVoteState = new Map();
  150. for (const a of idToAction.values()) {
  151. const c = a.content || {};
  152. if (c.type !== 'vote' || !c.vote || typeof c.vote.link !== 'string') continue;
  153. const link = c.vote.link;
  154. const br = Array.isArray(c.branch) ? c.branch : [];
  155. if (!br.includes(link)) continue;
  156. if (tombstoned.has(a.id)) continue;
  157. if (replacedIds.has(a.id)) continue;
  158. if (tombstoned.has(link)) continue;
  159. const author = a.author;
  160. if (!author) continue;
  161. const value = Number(c.vote.value);
  162. const key = `${link}:${author}`;
  163. const prev = spreadVoteState.get(key);
  164. const curTs = a.ts || 0;
  165. if (!prev || curTs > prev.ts || (curTs === prev.ts && String(a.id || '').localeCompare(String(prev.id || '')) > 0)) {
  166. spreadVoteState.set(key, { ts: curTs, id: a.id, value, link });
  167. }
  168. }
  169. const spreadCountByTarget = new Map();
  170. for (const v of spreadVoteState.values()) {
  171. if (Number(v.value) !== 1) continue;
  172. spreadCountByTarget.set(v.link, (spreadCountByTarget.get(v.link) || 0) + 1);
  173. }
  174. const fetchedTargetCache = new Map();
  175. for (const a of idToAction.values()) {
  176. if (a.type !== 'spread') continue;
  177. const c = a.content || {};
  178. const link = c.vote?.link || '';
  179. const totalSpreads = link ? (spreadCountByTarget.get(link) || 0) : 0;
  180. let targetMsg = link ? rawById.get(link) : null;
  181. if (!targetMsg && link) {
  182. if (fetchedTargetCache.has(link)) targetMsg = fetchedTargetCache.get(link);
  183. else {
  184. const got = await getMsg(ssbClient, link);
  185. if (got) {
  186. const wrapped = { key: link, value: got };
  187. fetchedTargetCache.set(link, wrapped);
  188. targetMsg = wrapped;
  189. } else {
  190. fetchedTargetCache.set(link, null);
  191. targetMsg = null;
  192. }
  193. }
  194. }
  195. const targetContent = targetMsg?.value?.content || null;
  196. const title =
  197. (typeof targetContent?.title === 'string' && targetContent.title.trim())
  198. ? targetContent.title.trim()
  199. : (typeof targetContent?.name === 'string' && targetContent.name.trim())
  200. ? targetContent.name.trim()
  201. : '';
  202. const rawText =
  203. (typeof targetContent?.text === 'string' && targetContent.text.trim())
  204. ? targetContent.text
  205. : (typeof targetContent?.description === 'string' && targetContent.description.trim())
  206. ? targetContent.description
  207. : '';
  208. const text = rawText ? excerpt(rawText, 700) : '';
  209. const cw =
  210. (typeof targetContent?.contentWarning === 'string' && targetContent.contentWarning.trim())
  211. ? targetContent.contentWarning
  212. : '';
  213. a.content = {
  214. ...c,
  215. spreadTargetId: link,
  216. spreadTotalSpreads: totalSpreads,
  217. spreadOriginalAuthor: targetMsg?.value?.author || '',
  218. spreadTitle: title,
  219. spreadContentWarning: cw,
  220. spreadText: text
  221. };
  222. }
  223. const rootOf = (id) => { let cur = id; while (parentOf.has(cur)) cur = parentOf.get(cur); return cur };
  224. const groups = new Map();
  225. for (const [id, action] of idToAction.entries()) {
  226. const root = rootOf(id);
  227. if (!groups.has(root)) groups.set(root, []);
  228. groups.get(root).push(action);
  229. }
  230. const idToTipId = new Map();
  231. for (const [root, arr] of groups.entries()) {
  232. if (!arr.length) continue;
  233. const type = arr[0].type;
  234. if (type !== 'project') {
  235. const tip = arr.reduce((best, a) => (a.ts > best.ts ? a : best), arr[0]);
  236. for (const a of arr) idToTipId.set(a.id, tip.id);
  237. if (type === 'task' && tip && tip.content && tip.content.isPublic !== 'PRIVATE') {
  238. const uniq = (xs) => Array.from(new Set((Array.isArray(xs) ? xs : []).filter(x => typeof x === 'string' && x.trim().length)));
  239. const sorted = arr
  240. .filter(a => a.type === 'task' && a.content && typeof a.content === 'object')
  241. .sort((a, b) => (a.ts || 0) - (b.ts || 0));
  242. let prev = null;
  243. for (const ev of sorted) {
  244. const cur = uniq(ev.content.assignees);
  245. if (prev) {
  246. const prevSet = new Set(prev);
  247. const curSet = new Set(cur);
  248. const added = cur.filter(x => !prevSet.has(x));
  249. const removed = prev.filter(x => !curSet.has(x));
  250. if (added.length || removed.length) {
  251. const overlayId = `${ev.id}:assignees:${added.join(',')}:${removed.join(',')}`;
  252. idToAction.set(overlayId, {
  253. id: overlayId,
  254. author: ev.author,
  255. ts: ev.ts,
  256. type: 'taskAssignment',
  257. content: {
  258. taskId: tip.id,
  259. title: tip.content.title || ev.content.title || '',
  260. added,
  261. removed,
  262. isPublic: tip.content.isPublic
  263. }
  264. });
  265. idToTipId.set(overlayId, overlayId);
  266. }
  267. }
  268. prev = cur;
  269. }
  270. }
  271. continue;
  272. }
  273. let tip = arr[0];
  274. let bestScore = SCORE_PROJECT(tip.content.status);
  275. for (const a of arr) {
  276. const s = SCORE_PROJECT(a.content.status);
  277. if (s > bestScore || (s === bestScore && a.ts > tip.ts)) { tip = a; bestScore = s }
  278. }
  279. for (const a of arr) idToTipId.set(a.id, tip.id);
  280. const baseTitle = (tip.content && tip.content.title) || '';
  281. const overlays = arr
  282. .filter(a => a.type === 'project' && (a.content.followersOp || a.content.backerPledge))
  283. .sort((a, b) => (a.ts || 0) - (b.ts || 0));
  284. for (const ev of overlays) {
  285. if (tombstoned.has(ev.id)) continue;
  286. let kind = null;
  287. let amount = null;
  288. if (ev.content.followersOp === 'follow') kind = 'follow';
  289. else if (ev.content.followersOp === 'unfollow') kind = 'unfollow';
  290. if (ev.content.backerPledge && typeof ev.content.backerPledge.amount !== 'undefined') {
  291. const amt = Math.max(0, parseFloat(ev.content.backerPledge.amount || 0) || 0);
  292. if (amt > 0) { kind = kind || 'pledge'; amount = amt }
  293. }
  294. if (!kind) continue;
  295. const augmented = {
  296. ...ev,
  297. type: 'project',
  298. content: {
  299. ...ev.content,
  300. title: baseTitle,
  301. projectId: tip.id,
  302. activity: { kind, amount },
  303. activityActor: ev.author
  304. }
  305. };
  306. idToAction.set(ev.id, augmented);
  307. idToTipId.set(ev.id, ev.id);
  308. }
  309. }
  310. const latest = [];
  311. for (const a of idToAction.values()) {
  312. if (tombstoned.has(a.id)) continue;
  313. if (a.type === 'tribe' && parentOf.has(a.id)) continue;
  314. const c = a.content || {};
  315. if (c.root && tombstoned.has(c.root)) continue;
  316. if (a.type === 'vote' && tombstoned.has(c.vote?.link)) continue;
  317. if (a.type === 'spread' && (c.spreadTargetId || c.vote?.link) && tombstoned.has(c.spreadTargetId || c.vote?.link)) continue;
  318. if (c.key && tombstoned.has(c.key)) continue;
  319. if (c.branch && tombstoned.has(c.branch)) continue;
  320. if (c.target && tombstoned.has(c.target)) continue;
  321. if (a.type === 'document') {
  322. const url = c.url;
  323. const ok = await hasBlob(ssbClient, url);
  324. if (!ok) continue;
  325. }
  326. if (a.type === 'forum' && c.root) {
  327. const rootId = typeof c.root === 'string' ? c.root : (c.root?.key || c.root?.id || '');
  328. const rootAction = idToAction.get(rootId);
  329. a.content.rootTitle = rootAction?.content?.title || a.content.rootTitle || '';
  330. a.content.rootKey = rootId || a.content.rootKey || '';
  331. }
  332. const actionRoot = rootOf(a.id);
  333. latest.push({ ...a, tipId: idToTipId.get(a.id) || a.id, rootId: actionRoot !== a.id ? actionRoot : null });
  334. }
  335. let deduped = latest.filter(a => !a.tipId || a.tipId === a.id || (a.type === 'tribe' && !parentOf.has(a.id)));
  336. const mediaTypes = new Set(['image','video','audio','document','bookmark','map']);
  337. const perAuthorUnique = new Set(['karmaScore']);
  338. const byKey = new Map();
  339. const norm = s => String(s || '').trim().toLowerCase();
  340. for (const a of deduped) {
  341. const c = a.content || {};
  342. const effTs =
  343. (c.updatedAt && Date.parse(c.updatedAt)) ||
  344. (c.createdAt && Date.parse(c.createdAt)) ||
  345. (a.ts || 0);
  346. if (mediaTypes.has(a.type)) {
  347. const u = c.url || c.title || `${a.type}:${a.id}`;
  348. const key = `${a.type}:${u}`;
  349. const prev = byKey.get(key);
  350. if (!prev || effTs > prev.__effTs) byKey.set(key, { ...a, __effTs: effTs });
  351. } else if (perAuthorUnique.has(a.type)) {
  352. const key = `${a.type}:${a.author}`;
  353. const prev = byKey.get(key);
  354. if (!prev || effTs > prev.__effTs) byKey.set(key, { ...a, __effTs: effTs });
  355. } else if (a.type === 'about') {
  356. const target = c.about || a.author;
  357. const key = `about:${target}`;
  358. const prev = byKey.get(key);
  359. const prevContent = prev && (prev.content || {});
  360. const prevHasImage = !!(prevContent && prevContent.image);
  361. const newHasImage = !!c.image;
  362. if (!prev) {
  363. byKey.set(key, { ...a, __effTs: effTs, __hasImage: newHasImage });
  364. } else if (!prevHasImage && newHasImage) {
  365. byKey.set(key, { ...a, __effTs: effTs, __hasImage: newHasImage });
  366. } else if (prevHasImage === newHasImage && effTs > prev.__effTs) {
  367. byKey.set(key, { ...a, __effTs: effTs, __hasImage: newHasImage });
  368. }
  369. } else if (a.type === 'tribe') {
  370. const t = norm(c.title);
  371. if (t) {
  372. const key = `tribe:${t}::${a.author}`;
  373. const prev = byKey.get(key);
  374. if (!prev || effTs > prev.__effTs) byKey.set(key, { ...a, __effTs: effTs });
  375. } else {
  376. const key = `id:${a.id}`;
  377. byKey.set(key, { ...a, __effTs: effTs });
  378. }
  379. } else {
  380. const key = `id:${a.id}`;
  381. byKey.set(key, { ...a, __effTs: effTs });
  382. }
  383. }
  384. deduped = Array.from(byKey.values()).map(x => { delete x.__effTs; delete x.__hasImage; return x });
  385. const tribeInternalTypes = new Set(['tribe-content', 'tribeParliamentCandidature', 'tribeParliamentTerm', 'tribeParliamentProposal', 'tribeParliamentRule', 'tribeParliamentLaw', 'tribeParliamentRevocation']);
  386. const hiddenTypes = new Set(['padEntry', 'chatMessage', 'calendarDate', 'calendarNote', 'calendarReminderSent', 'taskReminderSent', 'feed-action', 'pubBalance', 'pubAvailability', 'log']);
  387. const isAllowedTribeActivity = (a) => {
  388. if (tribeInternalTypes.has(a.type)) return false;
  389. const c = a.content || {};
  390. if (c.tribeId) return false;
  391. if (a.type === 'tribe') {
  392. const isInitial = !c.replaces;
  393. if (!isInitial) return false;
  394. if (c.isAnonymous === true && !c._decrypted) return false;
  395. }
  396. return true;
  397. };
  398. const isVisible = (a) => {
  399. if (hiddenTypes.has(a.type)) return false;
  400. if (a.type === 'pad' && (a.content || {}).status !== 'OPEN') return false;
  401. if (a.type === 'chat' && (a.content || {}).status !== 'OPEN') return false;
  402. if (a.type === 'calendar' && (a.content || {}).status !== 'OPEN') return false;
  403. if (a.type === 'event' && String((a.content || {}).isPublic || '').toLowerCase() === 'private' && (a.content || {}).organizer !== userId && !(Array.isArray((a.content || {}).attendees) && (a.content || {}).attendees.includes(userId))) return false;
  404. if (a.type === 'task' && String((a.content || {}).isPublic || '').toUpperCase() === 'PRIVATE' && a.author !== userId && !(Array.isArray((a.content || {}).assignees) && (a.content || {}).assignees.includes(userId))) return false;
  405. return true;
  406. };
  407. let out;
  408. if (filter === 'mine') out = deduped.filter(a => a.author === userId && isAllowedTribeActivity(a) && isVisible(a));
  409. else if (filter === 'recent') { const cutoff = Date.now() - 24 * 60 * 60 * 1000; out = deduped.filter(a => (a.ts || 0) >= cutoff && isAllowedTribeActivity(a) && isVisible(a)) }
  410. else if (filter === 'all') out = deduped.filter(a => isAllowedTribeActivity(a) && isVisible(a));
  411. else if (filter === 'banking') out = deduped.filter(a => a.type === 'bankWallet' || a.type === 'bankClaim' || a.type === 'ubiClaim' || a.type === 'ubiclaimresult');
  412. else if (filter === 'karma') out = deduped.filter(a => a.type === 'karmaScore');
  413. else if (filter === 'tribe') out = deduped.filter(a => a.type === 'tribe' || String(a.type || '').startsWith('tribe'));
  414. else if (filter === 'spread') out = deduped.filter(a => a.type === 'spread');
  415. else if (filter === 'parliament')
  416. out = deduped.filter(a =>
  417. ['parliamentCandidature','parliamentTerm','parliamentProposal','parliamentRevocation','parliamentLaw'].includes(a.type)
  418. );
  419. else if (filter === 'courts')
  420. out = deduped.filter(a => {
  421. const t = String(a.type || '').toLowerCase();
  422. return t === 'courtscase' || t === 'courtsnomination' || t === 'courtsnominationvote';
  423. });
  424. else if (filter === 'task')
  425. out = deduped.filter(a => a.type === 'task' || a.type === 'taskAssignment');
  426. else if (filter === 'gameScore') out = deduped.filter(a => a.type === 'gameScore');
  427. else if (filter === 'pad') out = deduped.filter(a => a.type === 'pad' && (a.content || {}).status === 'OPEN');
  428. else if (filter === 'chat') out = deduped.filter(a => a.type === 'chat' && (a.content || {}).status === 'OPEN');
  429. else if (filter === 'calendar') out = deduped.filter(a => a.type === 'calendar' && (a.content || {}).status === 'OPEN');
  430. else out = deduped.filter(a => a.type === filter);
  431. out.sort((a, b) => (b.ts || 0) - (a.ts || 0));
  432. return out;
  433. })();
  434. _feedCacheInflight.set(cacheKey, promise);
  435. try {
  436. const value = await promise;
  437. _feedCache.set(cacheKey, { value, ts: Date.now() });
  438. return value;
  439. } finally {
  440. _feedCacheInflight.delete(cacheKey);
  441. }
  442. }
  443. };
  444. };