Ignore:
Timestamp:
06/24/2026 01:24:23 PM (3 months ago)
Author:
Robin Genis <roboburr@…>
Branches:
main
Children:
a885afc
Parents:
cc24fa1
Message:

feat(activitypub): nested threading + delete your own replies

Inbox now stores replies-to-comments nested (findThreadTarget resolves the post
via the parent comment); getInteractions builds a thread tree shown on the post
(fedi-node partial). deliverReply also cc's the post author's inbox so their
Klonkt threads it. Owners can delete their outbound replies (Delete+Tombstone)
inline + via /fediverse manage list. Schema: ap_interactions.parent_uri.

Co-Authored-By: Claude <noreply@…>

File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/services/ActivityPubService.js

    rcc24fa1 r7d932ce  
    198198function iStmts() {
    199199  if (!_insI) {
    200     _insI = db.prepare('INSERT OR IGNORE INTO ap_interactions (kind, post_id, object_uri, actor_uri, actor_name, actor_handle, actor_url, actor_icon, content, published, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)');
     200    _insI = db.prepare('INSERT OR IGNORE INTO ap_interactions (kind, post_id, object_uri, actor_uri, actor_name, actor_handle, actor_url, actor_icon, content, published, parent_uri, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)');
    201201    _delLA = db.prepare('DELETE FROM ap_interactions WHERE kind = ? AND post_id = ? AND actor_uri = ?');
    202202    _delReply = db.prepare("DELETE FROM ap_interactions WHERE kind = 'reply' AND object_uri = ?");
    203     _listI = db.prepare('SELECT id, kind, object_uri, actor_uri, actor_name, actor_handle, actor_url, actor_icon, content, published, created_at FROM ap_interactions WHERE post_id = ? ORDER BY created_at ASC');
     203    _listI = db.prepare('SELECT id, kind, object_uri, parent_uri, actor_uri, actor_name, actor_handle, actor_url, actor_icon, content, published, created_at FROM ap_interactions WHERE post_id = ? ORDER BY created_at ASC');
    204204    _getI = db.prepare('SELECT * FROM ap_interactions WHERE id = ?');
    205205    _insO = db.prepare('INSERT INTO ap_outbox (id, site_slug, post_id, post_slug, in_reply_to, to_actor, to_handle, content, created_at) VALUES (?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)');
     
    235235}
    236236
    237 // Stored, view-ready summary of a post's inbound fediverse activity + our replies.
    238 export function getInteractions(postId) {
     237// Given an inReplyTo note URL, find which local post the thread belongs to + the
     238// note being replied to (parent), so a reply-to-a-comment can be nested.
     239function findThreadTarget(inReplyTo, base) {
     240  if (!inReplyTo) return null;
     241  const seg = postIdFromNoteUrl(inReplyTo, base); // our /ap/notes/<id> segment (if ours)
     242  if (seg && localPostExists(seg)) return { post_id: seg, parent_uri: inReplyTo };
     243  if (seg) {
     244    try { const o = db.prepare('SELECT post_id FROM ap_outbox WHERE id = ?').get(seg); if (o && o.post_id) return { post_id: o.post_id, parent_uri: inReplyTo }; } catch { /* ignore */ }
     245  }
     246  try { const row = db.prepare("SELECT post_id FROM ap_interactions WHERE object_uri = ? AND kind = 'reply' LIMIT 1").get(inReplyTo); if (row && row.post_id) return { post_id: row.post_id, parent_uri: inReplyTo }; } catch { /* ignore */ }
     247  return null;
     248}
     249
     250// View-ready threaded view of a post's fediverse activity (inbound replies +
     251// our outbound replies, nested), plus like/boost counts.
     252export function getInteractions(postId, base) {
    239253  const s = iStmts();
    240254  const rows = s.list.all(postId);
    241   const outReplies = s.listO.all(postId).map((o) => ({
    242     id: o.id, content: o.content, in_reply_to: o.in_reply_to, to_handle: o.to_handle,
    243     created_at: o.created_at, mine: true,
    244   }));
     255  const baseClean = (base || process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
     256  const postNoteId = baseClean ? `${baseClean}/ap/notes/${postId}` : null;
     257
     258  const nodes = [];
     259  for (const r of rows) {
     260    if (r.kind !== 'reply') continue;
     261    nodes.push({
     262      noteId: r.object_uri, parent: r.parent_uri || null, mine: false,
     263      actor_name: r.actor_name, actor_handle: r.actor_handle, actor_url: r.actor_url,
     264      actor_icon: r.actor_icon, content: r.content, created_at: r.published || r.created_at,
     265      children: [],
     266    });
     267  }
     268  for (const o of s.listO.all(postId)) {
     269    nodes.push({
     270      noteId: baseClean ? `${baseClean}/ap/notes/${o.id}` : o.id, parent: o.in_reply_to || null,
     271      mine: true, outboxId: o.id, content: o.content, created_at: o.created_at, children: [],
     272    });
     273  }
     274
     275  const byId = new Map(nodes.map((n) => [n.noteId, n]));
     276  const isTop = (n) => !n.parent || n.parent === postNoteId || !byId.has(n.parent);
     277  const tops = [];
     278  for (const n of nodes) {
     279    if (isTop(n)) { tops.push(n); continue; }
     280    let anc = n, guard = 0;
     281    while (!isTop(anc) && guard++ < 12) anc = byId.get(anc.parent);
     282    anc.children.push(n);
     283  }
     284  const byTime = (a, b) => new Date(a.created_at) - new Date(b.created_at);
     285  tops.sort(byTime).forEach((t) => t.children.sort(byTime));
     286
    245287  return {
    246     replies: rows.filter((r) => r.kind === 'reply'),
    247     outReplies,
     288    thread: tops,
    248289    likeCount: rows.filter((r) => r.kind === 'like').length,
    249290    announceCount: rows.filter((r) => r.kind === 'announce').length,
    250     total: rows.length + outReplies.length,
     291    total: nodes.length,
    251292  };
    252293}
     
    346387  const resolveActor = async (uri) => ((verified && verified.id === uri) ? verified : await fetchActor(uri).catch(() => null));
    347388
    348   // Inbound reply: a Create whose object replies to one of our notes.
     389  // Inbound reply: a Create whose object replies to one of our notes (post OR comment).
    349390  if (type === 'Create' && act.object && (act.object.type === 'Note' || act.object.type === 'Article')) {
    350391    const o = act.object;
    351     const pid = postIdFromNoteUrl(o.inReplyTo, base);
    352     if (pid && actorUri && localPostExists(pid)) {
     392    const tgt = findThreadTarget(o.inReplyTo, base);
     393    if (tgt && actorUri) {
    353394      const ai = actorInfo(await resolveActor(actorUri), actorUri);
    354395      const html = HtmlSanitizerService.sanitize(o.content || '');
    355       iStmts().ins.run('reply', pid, o.id || '', actorUri, ai.name, ai.handle, ai.url, ai.icon, html, o.published || null);
    356       console.log('[AP] reply', actorUri, '→', pid);
     396      iStmts().ins.run('reply', tgt.post_id, o.id || '', actorUri, ai.name, ai.handle, ai.url, ai.icon, html, o.published || null, tgt.parent_uri);
     397      console.log('[AP] reply', actorUri, '→', tgt.post_id);
    357398    }
    358399    return 202;
     
    363404    if (pid && actorUri && localPostExists(pid)) {
    364405      const ai = actorInfo(await resolveActor(actorUri), actorUri);
    365       iStmts().ins.run(type.toLowerCase(), pid, '', actorUri, ai.name, ai.handle, ai.url, ai.icon, null, null);
     406      iStmts().ins.run(type.toLowerCase(), pid, '', actorUri, ai.name, ai.handle, ai.url, ai.icon, null, null, null);
    366407      console.log('[AP]', type === 'Like' ? 'like' : 'boost', actorUri, '→', pid);
    367408    }
     
    475516    if (a) inboxes.add((a.endpoints && a.endpoints.sharedInbox) || a.inbox);
    476517  }
     518  if (parent.threadInbox) inboxes.add(parent.threadInbox); // post author's server (nesting)
    477519  for (const f of fStmts().list.all(site.slug)) inboxes.add(f.shared_inbox || f.inbox);
    478520  let delivered = 0;
     
    495537  const actor = await fetchActor(actorUri).catch(() => null);
    496538  const ai = actorInfo(actor, actorUri);
     539  // If this note is itself a reply (a comment), also reach the original post's
     540  // author so THEIR server threads our reply under the comment.
     541  let threadInbox = null;
     542  if (note.inReplyTo) {
     543    const parentUrl = typeof note.inReplyTo === 'string' ? note.inReplyTo : (note.inReplyTo && note.inReplyTo.id);
     544    const parentNote = parentUrl ? await fetchActor(parentUrl).catch(() => null) : null;
     545    const pAtt = parentNote && (typeof parentNote.attributedTo === 'string' ? parentNote.attributedTo : (parentNote.attributedTo && parentNote.attributedTo.id));
     546    if (pAtt && pAtt !== actorUri) {
     547      const pa = await fetchActor(pAtt).catch(() => null);
     548      threadInbox = pa && ((pa.endpoints && pa.endpoints.sharedInbox) || pa.inbox);
     549    }
     550  }
    497551  const rawHtml = String(note.content || '').replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
    498552  const images = (Array.isArray(note.attachment) ? note.attachment : [])
     
    509563    content: HtmlSanitizerService.sanitize(rawHtml),       // full, sanitized
    510564    images,
     565    threadInbox,                                            // post author's inbox (if a comment)
    511566    preview: HtmlSanitizerService.toPlainText(note.content || '').slice(0, 240),
    512567  };
     568}
     569
     570// List a site's own outbound fediverse replies (for the manage/delete view).
     571export function listOutbox(siteSlug) {
     572  return db.prepare('SELECT id, content, to_handle, in_reply_to, created_at FROM ap_outbox WHERE site_slug = ? ORDER BY created_at DESC').all(siteSlug);
     573}
     574
     575// Delete one of our outbound replies: send Delete(Tombstone) to recipients + remove it.
     576export async function deliverOutboxDelete(site, outboxId) {
     577  const row = iStmts().getO.get(outboxId);
     578  if (!row || row.site_slug !== site.slug) return false;
     579  const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
     580  if (base) {
     581    const me = actorId(base, site.slug);
     582    const nid = noteId(base, row.id);
     583    const del = { '@context': 'https://www.w3.org/ns/activitystreams', id: `${nid}#delete-${Date.now()}`, type: 'Delete', actor: me, to: [PUBLIC], object: { id: nid, type: 'Tombstone' } };
     584    const keys = getOrCreateKeys(site.slug);
     585    const inboxes = new Set();
     586    if (row.to_actor) { const a = await fetchActor(row.to_actor).catch(() => null); if (a) inboxes.add((a.endpoints && a.endpoints.sharedInbox) || a.inbox); }
     587    for (const f of fStmts().list.all(site.slug)) inboxes.add(f.shared_inbox || f.inbox);
     588    for (const inbox of [...inboxes].filter(Boolean)) { try { await deliver(inbox, del, `${me}#main-key`, keys.private_pem); } catch { /* best-effort */ } }
     589  }
     590  db.prepare('DELETE FROM ap_outbox WHERE id = ?').run(outboxId);
     591  return true;
    513592}
    514593
     
    518597  followerCount, deliver, fetchActor, verifyRequest, handleInbox, deliverCreate, deliverDelete,
    519598  getInteractions, getInteractionById, buildReplyNote, getOutboxNote, deliverReply, resolveRemoteNote,
     599  listOutbox, deliverOutboxDelete,
    520600};
Note: See TracChangeset for help on using the changeset viewer.