import { readFile, readdir } from "node:fs/promises"; import path from "node:path"; import type { Post } from "yt-dlp-transcript-common/lib/posts"; import { readAllPosts } from "yt-dlp-transcript-common/lib/posts-server"; import { CASE_FILES, LEAD_DISPOSITIONS, isLeadDisposition, type CaseLead, type LeadDisposition, } from "yt-dlp-transcript-common/lib/research/caseTypes"; import { privateNameHash } from "yt-dlp-transcript-common/lib/research/privateNames-server"; import { assertNoPrivateNames, withholdPrivateNames } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; import { CHANNELS_DIR } from "../paths.mjs"; import { CaseError, feedPrivateNameHash, labelOf, privateHashes, readJsonFile, scopeChannels, stageDir, stageFile, withFileLock, writeWhole, } from "./case-stage-files"; import { editorCall, refusalText, startJob } from "./case-editor"; // --------------------------------------------------------------------------- // STAGE 8, LEADS (release 38 lane C): over a posts or forum channel in the // case's scope, the accounts and URLs its posts link most, counted by post, // with context snippets on demand. Each lead gets a role note and one of // `archive | watch | never-archive`: // // never-archive the lead's NAME (the handle, the user, the page's last // segment) is fed to the case's private names as its hash // (privateNameHash) and the lead itself is kept only as that // hash -- `key: "hash:"`, no URL -- so no file holds // it. A later scan withholds every lead whose name hashes to a // private name, and every snippet is redacted the same way. // archive the channel is created through the editor's create-channel // op, ON NO SITE (X never on a site, by rule; a site is the // operator's to add), its first fetch started with it; the // older walk is a second button once it has posts. // watch kept, nothing started. // // leads.json is CaseLead[], one writer (case-stage-files.ts). // --------------------------------------------------------------------------- export const HASH_KEY_PREFIX = "hash:"; export const MAX_LEADS = 200; const SNIPPET_CHARS = 280; export type LeadCandidate = { key: string; url: string; platform: string; name: string }; const X_HOSTS = new Set(["twitter.com", "www.twitter.com", "mobile.twitter.com", "x.com", "www.x.com", "mobile.x.com"]); const X_NOT_HANDLES = new Set(["i", "intent", "share", "search", "hashtag", "home", "explore", "settings", "login", "signup", "messages", "notifications", "tos", "privacy"]); const YT_HOSTS = new Set(["youtube.com", "www.youtube.com", "m.youtube.com"]); /** What a linked URL is a lead to: an account where the platform has one, else the page (host + path). */ export function leadOf(raw: string): LeadCandidate | null { let u: URL; try { u = new URL(raw); } catch { return null; } if (u.protocol !== "http:" && u.protocol !== "https:") return null; const host = u.hostname.toLowerCase(); const segs = u.pathname.split("/").filter(Boolean); if (X_HOSTS.has(host)) { const h = segs[0]; if (!h || X_NOT_HANDLES.has(h.toLowerCase()) || !/^[A-Za-z0-9_]{1,15}$/.test(h)) return null; return { key: `x:@${h.toLowerCase()}`, url: `https://x.com/${h}`, platform: "x", name: h }; } if (YT_HOSTS.has(host)) { const m = /^(@[^/]+)$/.exec(segs[0] ?? "") ?? (["c", "user", "channel"].includes(segs[0] ?? "") && segs[1] ? [segs[1], segs[1]] : null); if (!m) return null; const name = m[1]; const at = segs[0].startsWith("@") ? segs[0] : `${segs[0]}/${segs[1]}`; return { key: `youtube:${at.toLowerCase()}`, url: `https://www.youtube.com/${at}`, platform: "youtube", name: name.replace(/^@/, "") }; } if (host === "bsky.app" && segs[0] === "profile" && segs[1]) { return { key: `bluesky:${segs[1].toLowerCase()}`, url: `https://bsky.app/profile/${segs[1]}`, platform: "bluesky", name: segs[1].split(".")[0] }; } const sub = (suffix: string) => (host.endsWith(suffix) ? host.slice(0, -suffix.length) : ""); for (const [suffix, platform] of [[".tumblr.com", "tumblr"], [".newgrounds.com", "newgrounds"], [".deviantart.com", "deviantart"]] as const) { const s = sub(suffix); if (s && s !== "www" && !s.includes(".")) return { key: `${platform}:${s}`, url: `https://${s}${suffix}/`, platform, name: s }; } if ((host === "reddit.com" || host.endsWith(".reddit.com")) && (segs[0] === "u" || segs[0] === "user") && segs[1]) { return { key: `reddit:u/${segs[1].toLowerCase()}`, url: `https://www.reddit.com/user/${segs[1]}`, platform: "reddit", name: segs[1] }; } if ((host === "instagram.com" || host === "www.instagram.com") && segs[0] && !["p", "reel", "explore"].includes(segs[0])) { return { key: `instagram:${segs[0].toLowerCase()}`, url: `https://www.instagram.com/${segs[0]}/`, platform: "instagram", name: segs[0] }; } if ((host === "tiktok.com" || host === "www.tiktok.com") && segs[0]?.startsWith("@")) { return { key: `tiktok:${segs[0].toLowerCase()}`, url: `https://www.tiktok.com/${segs[0]}`, platform: "tiktok", name: segs[0].slice(1) }; } const bare = host.replace(/^www\./, ""); const p = segs.join("/"); return { key: `${bare}${p ? `/${p}` : ""}`.toLowerCase(), url: `${u.protocol}//${host}${u.pathname.replace(/\/+$/, "") || "/"}`, platform: "web", name: segs.length ? segs[segs.length - 1] : bare.split(".")[0] }; } const nameHash = (c: Pick) => privateNameHash(c.name.replace(/^@/, "")); // ── the channels a scan can read ── export type PostsChannel = { slug: string; name: string; platform: string; inScope: boolean }; const SOCIAL_PLATFORMS = new Set(["xenforo", "twitter", "bluesky", "webpage", "instagram", "x-search"]); async function configOf(slug: string): Promise | null> { if (!/^[A-Za-z0-9_.@-]+$/.test(slug)) return null; try { return JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(CHANNELS_DIR, slug, "config.json"), "utf8")); } catch { return null; } } /** Every posts/forum channel the editor holds, the case's scope first. */ export async function postsChannels(caseId: string): Promise { const scope = new Set(await scopeChannels(caseId)); const names = await readdir(/* turbopackIgnore: true */ CHANNELS_DIR).catch(() => [] as string[]); const out: PostsChannel[] = []; for (const slug of names.sort()) { if (slug.startsWith(".")) continue; const c = await configOf(slug); const platform = typeof c?.platform === "string" ? c.platform : ""; if (c?.sourceKind !== "social" && !SOCIAL_PLATFORMS.has(platform)) continue; out.push({ slug, name: typeof c?.name === "string" ? c.name : slug, platform: platform || "social", inScope: scope.has(slug) }); } return out.sort((a, b) => Number(b.inScope) - Number(a.inScope) || a.slug.localeCompare(b.slug)); } // ── the scan ── export type LeadRow = CaseLead & { withheld?: boolean; posts?: string[] }; export type LeadsView = { channel: string | null; channels: PostsChannel[]; leads: LeadRow[]; /** Leads whose names hash to the case's private names: counted, never listed. */ withheld: number; posts: number; dispositions: readonly LeadDisposition[]; }; type Tally = LeadCandidate & { count: number; posts: string[] }; /** The leads a channel's posts link, by how many posts link each (the channel's own forum host left out). */ export function tallyLeads(posts: Post[], ownHosts: Set): Tally[] { const by = new Map(); for (const p of posts) { const seen = new Set(); for (const link of p.links ?? []) { const c = leadOf(link); if (!c || seen.has(c.key)) continue; try { if (ownHosts.has(new URL(link).hostname.toLowerCase())) continue; } catch { continue; } seen.add(c.key); const t = by.get(c.key) ?? { ...c, count: 0, posts: [] }; t.count++; if (t.posts.length < 50) t.posts.push(p.id); by.set(c.key, t); } } return [...by.values()].sort((a, b) => b.count - a.count || a.key.localeCompare(b.key)); } function hostsOf(posts: Post[], config: Record | null): Set { const out = new Set(); for (const p of posts.slice(0, 50)) if (p.forum?.host) out.add(p.forum.host.toLowerCase()); const url = typeof config?.url === "string" ? config.url : ""; try { if (url && config?.platform === "xenforo") out.add(new URL(url).hostname.toLowerCase()); } catch { // no URL } for (const h of [...out]) out.add(h.startsWith("www.") ? h.slice(4) : `www.${h}`); return out; } async function leadsFile(caseId: string) { return stageFile(await stageDir(caseId), CASE_FILES.leads); } export async function readLeads(caseId: string): Promise { const v = await readJsonFile(await leadsFile(caseId), [], labelOf(caseId, CASE_FILES.leads)); if (!Array.isArray(v)) throw new CaseError(`${labelOf(caseId, CASE_FILES.leads)} is not a list of leads`, 409); return v.filter((l): l is CaseLead => !!l && typeof l === "object" && typeof (l as CaseLead).key === "string"); } async function postsOf(slug: string): Promise { if (!/^[A-Za-z0-9_.@-]+$/.test(slug)) throw new CaseError(`not a channel: ${slug}`, 400); return readAllPosts(path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug)); } /** Scan `channel` (default: the scope's first posts channel) and merge the counts into the case's leads. */ export async function leadsView(caseId: string, channel?: string | null): Promise { const channels = await postsChannels(caseId); const slug = channel || channels.find((c) => c.inScope)?.slug || null; const hashes = new Set(await privateHashes(caseId)); const saved = await readLeads(caseId); if (!slug) return { channel: null, channels, leads: saved, withheld: 0, posts: 0, dispositions: LEAD_DISPOSITIONS }; if (!channels.some((c) => c.slug === slug)) throw new CaseError(`${slug} is not a posts or forum channel`, 404); const posts = await postsOf(slug); const tally = tallyLeads(posts, hostsOf(posts, await configOf(slug))); let withheld = 0; const savedBy = new Map(saved.map((l) => [l.key, l])); const rows: LeadRow[] = []; for (const t of tally) { const h = nameHash(t); if (hashes.has(h) || savedBy.has(`${HASH_KEY_PREFIX}${h}`)) { withheld++; continue; } const prev = savedBy.get(t.key); rows.push({ ...(prev ?? {}), key: t.key, url: t.url, platform: t.platform, count: t.count, posts: t.posts }); if (rows.length >= MAX_LEADS) break; } // Decided leads the scan no longer finds stay listed (a person decided them), after the rest. const listed = new Set(rows.map((r) => r.key)); for (const l of saved) if (!listed.has(l.key) && l.disposition && !l.key.startsWith(HASH_KEY_PREFIX)) rows.push({ ...l }); const never = saved.filter((l) => l.key.startsWith(HASH_KEY_PREFIX)).map((l) => ({ ...l, url: "", withheld: true })); return { channel: slug, channels, leads: [...rows, ...never], withheld, posts: posts.length, dispositions: LEAD_DISPOSITIONS }; } // ── context, on demand ── export type LeadContext = { key: string; snippets: { post: string; date: string; author: string; text: string; url: string; position?: number }[] }; /** The posts that link `key`, each a snippet around the link, private names withheld. */ export async function leadContext(caseId: string, channel: string, key: string, limit = 8): Promise { if (key.startsWith(HASH_KEY_PREFIX)) throw new CaseError("a never-archive lead has no context to show", 400); const hashes = await privateHashes(caseId); const posts = (await postsOf(channel)).sort((a, b) => a.createdAt.localeCompare(b.createdAt)); const out: LeadContext["snippets"] = []; for (const p of posts) { const link = (p.links ?? []).find((l) => leadOf(l)?.key === key); if (!link) continue; const text = p.text ?? ""; const c = leadOf(link)!; let at = text.indexOf(link); if (at < 0) at = text.toLowerCase().indexOf(c.name.toLowerCase()); const from = Math.max(0, (at < 0 ? 0 : at) - SNIPPET_CHARS / 2); let snip = text.slice(from, from + SNIPPET_CHARS).replace(/\s+/g, " ").trim(); if (from > 0) snip = `… ${snip}`; if (from + SNIPPET_CHARS < text.length) snip = `${snip} …`; out.push({ post: p.id, date: p.uploadDate, author: withholdPrivateNames(p.author ?? "", hashes).text, text: withholdPrivateNames(snip, hashes).text, url: p.url, ...(p.forum?.position ? { position: p.forum.position } : {}), }); if (out.length >= limit) break; } return { key, snippets: out }; } // ── a decision ── /** `url` and `count`: the scan's, for a lead decided before it is saved (its key must be what the URL makes). */ export type LeadDecision = { key: string; disposition?: string | null; role?: string; name?: string; url?: string; count?: number }; function channelFieldsFor(lead: Pick, name: string): { fields: Record; start: Record } { if (lead.platform === "x") return { fields: { name, handling: "transcribe", url: lead.url }, start: { fetchPostsNow: true } }; if (lead.platform === "bluesky") return { fields: { name, handling: "transcribe", url: lead.url }, start: { fetchPostsNow: true } }; if (lead.platform === "youtube") return { fields: { name, handling: "youtube", url: `${lead.url}/videos` }, start: { fetchPlaylist: true } }; // Anything else is a page: a Wayback pages channel scoped to it (its captures through the evidence stage). const target = lead.url.replace(/^https?:\/\//, ""); return { fields: { name, handling: "transcribe", url: `https://web.archive.org/web/*/${target}*` }, start: {} }; } /** * Set a lead's role and disposition. never-archive feeds its name's hash to the case's private names and keeps * the lead only as the hash; archive creates its channel (on no site) and starts the first fetch. */ export async function decideLead(caseId: string, d: LeadDecision): Promise<{ lead: CaseLead; created?: { slug: string; jobIds: string[] } }> { const disposition = d.disposition === null || d.disposition === "" ? undefined : d.disposition; if (disposition !== undefined && !isLeadDisposition(disposition)) { throw new CaseError(`not a disposition: ${JSON.stringify(d.disposition)} (one of ${LEAD_DISPOSITIONS.join(", ")})`, 400); } const role = typeof d.role === "string" ? d.role.replace(/\s+/g, " ").trim().slice(0, 300) : undefined; const hashes = await privateHashes(caseId); if (role) assertNoPrivateNames("the lead's role note", [{ id: d.key.startsWith(HASH_KEY_PREFIX) ? "a withheld lead" : d.key, text: role }], hashes); if (d.key.startsWith(HASH_KEY_PREFIX)) { // A withheld lead is never un-withheld here; only its role note can change. if (disposition && disposition !== "never-archive") throw new CaseError("a never-archive lead stays never-archive: its name is a private name now", 400); } const file = await leadsFile(caseId); const cand = d.key.startsWith(HASH_KEY_PREFIX) ? null : candidateOf(d.key, await readLeads(caseId), d.url, d.count); let created: { slug: string; jobIds: string[] } | undefined; if (disposition === "archive" && cand) { const prev = (await readLeads(caseId)).find((l) => l.key === d.key); if (!prev?.channel) { const name = (d.name ?? "").trim() || defaultChannelName(cand); const { fields, start } = channelFieldsFor(cand, name); // ON NO SITE: no `sites` is sent, ever (X never on a site; a site is the operator's). const a = await editorCall("/api/ops/create-channel", { method: "POST", body: { fields, ...start } }); if (!a.ok) throw new CaseError(`the editor would not create the channel: ${refusalText(a)}`, a.status >= 400 && a.status < 500 ? a.status : 502); created = { slug: String(a.body.slug), jobIds: Array.isArray(a.body.jobIds) ? a.body.jobIds.map(String) : [] }; } } if (disposition === "never-archive" && cand) await feedPrivateNameHash(caseId, nameHash(cand)); const lead = await withFileLock(file, async () => { const all = await readLeads(caseId); let i = all.findIndex((l) => l.key === d.key); const base: CaseLead = i >= 0 ? all[i] : cand ? { key: cand.key, url: cand.url, platform: cand.platform, count: cand.count ?? 0 } : (() => { throw new CaseError(`no lead ${d.key}`, 404); })(); let next: CaseLead = { ...base, ...(role !== undefined ? { role } : {}) }; if (disposition) next.disposition = disposition; else if (d.disposition === null || d.disposition === "") delete next.disposition; if (created) next.channel = created.slug; if (disposition === "never-archive" && cand) { // Kept only as its hash: no key, no URL, no channel. next = { key: `${HASH_KEY_PREFIX}${nameHash(cand)}`, url: "", platform: cand.platform, count: next.count, disposition: "never-archive", ...(next.role ? { role: next.role } : {}) }; const dup = all.findIndex((l) => l.key === next.key); if (dup >= 0 && dup !== i) { all.splice(dup, 1); if (dup < i) i--; } } if (i >= 0) all[i] = next; else all.push(next); await writeWhole(file, `${JSON.stringify(all, null, 2)}\n`); return next; }); return { lead, ...(created ? { created } : {}) }; } /** The older walk of an archived lead's channel (a social channel with posts now). */ export async function startOlderWalk(caseId: string, key: string): Promise<{ jobId: string; slug: string }> { const lead = (await readLeads(caseId)).find((l) => l.key === key); if (!lead?.channel) throw new CaseError(`${key} has no channel yet: archive it first`, 400); const jobId = await startJob("/api/ops/fetch-posts", { slug: lead.channel, older: true }); return { jobId, slug: lead.channel }; } function candidateOf(key: string, saved: CaseLead[], hintUrl?: string, hintCount?: number): (LeadCandidate & { count?: number }) | null { const s = saved.find((l) => l.key === key); const fromUrl = s?.url ? leadOf(s.url) : null; if (fromUrl) return { ...fromUrl, key, count: s?.count }; const hinted = hintUrl ? leadOf(hintUrl) : null; if (hinted && hinted.key === key) return { ...hinted, ...(Number.isFinite(hintCount) ? { count: Math.max(0, Math.floor(hintCount!)) } : {}) }; // A key straight from a scan (not saved yet): rebuild it from its URL shape. const url = key.startsWith("x:@") ? `https://x.com/${key.slice(3)}` : key.startsWith("youtube:") ? `https://www.youtube.com/${key.slice(8)}` : key.startsWith("bluesky:") ? `https://bsky.app/profile/${key.slice(8)}` : key.startsWith("reddit:u/") ? `https://www.reddit.com/user/${key.slice(9)}` : /^(tumblr|newgrounds|deviantart):/.test(key) ? `https://${key.split(":")[1]}.${key.split(":")[0]}.com/` : /^(instagram|tiktok):/.test(key) ? `https://www.${key.split(":")[0]}.com/${key.split(":")[1]}` : `https://${key}`; const c = leadOf(url); return c ? { ...c, key } : null; } function defaultChannelName(c: LeadCandidate): string { if (c.platform === "x") return `${c.name} (X)`; if (c.platform === "youtube") return c.name; if (c.platform === "web") return c.key.split("/")[0]; return `${c.name} (${c.platform})`; }