import { readdir } from "node:fs/promises"; import path from "node:path"; import { readAllPosts } from "yt-dlp-transcript-common/lib/posts-server"; import { CASE_FILES, EXCLUDED_SENTENCE, evidenceLabel, type CaseEvidence, type FindingEvidence, type FindingRow, } from "yt-dlp-transcript-common/lib/research/caseTypes"; import { CHANNELS_DIR } from "../paths.mjs"; import { webpageChannels, type PagesChannel } from "../articles/importCapture"; import { corpusMediaUrl } from "../articles/article"; import { mutateFindings, readFindings, rowOf } from "./case-findings-store"; import { CaseError, labelOf, readJsonFile, stageDir, stageFile, withFileLock, writeWhole } from "./case-stage-files"; import { editorCall, jobState, refusalText, resultLine } from "./case-editor"; import { postsChannels, type PostsChannel } from "./case-leads"; // --------------------------------------------------------------------------- // STAGE 10, EVIDENCE CAPTURE (release 38 lane C): `/evidence.json`, // CaseEvidence[], one writer. // // wayback a target page at a chosen date: `wayback-lookup` to see // whether the archive will show it at all (a 403 is // EXCLUDED, "excluded from the Wayback Machine (cause // unknown)", a row of its own, never an error), then // `import-page {slug, url, at}` into a Wayback pages // channel (picked, or created on no site for the host) -- // the capture nearest the date, paced on archive.org's // queue by the editor. // forum-attachment a forum post's attachments and screenshot through // `capture-posts`, shown in EVERY surface as "forum // attachment, post #N, unverified" (forumAttachmentLabel): // a forum's joke culture means it is looked at before it // is described, and a finding it backs is quarantined until // an independent source agrees. // // A row can be attached to findings (their `evidence`, through the findings // writer). The case export (lane A's runExport) lists the rows in an Evidence // section (common/lib/research/caseEvidence.ts evidenceSection). // --------------------------------------------------------------------------- export const IMPORT_PAGE_MARKER = "@@import-page "; const MAX_ROWS = 500; const DATE = /^(\d{4})-?(\d{2})-?(\d{2})$/; /** A date as the editor's import-page takes it (YYYYMMDD), or null. */ export function evidenceDate(v: string): string | null { const m = DATE.exec(v.trim()); return m ? `${m[1]}${m[2]}${m[3]}` : null; } async function file(caseId: string) { return stageFile(await stageDir(caseId), CASE_FILES.evidence); } export async function readEvidence(caseId: string): Promise { const v = await readJsonFile(await file(caseId), [], labelOf(caseId, CASE_FILES.evidence)); if (!Array.isArray(v)) throw new CaseError(`${labelOf(caseId, CASE_FILES.evidence)} is not a list`, 409); return v.filter((r): r is CaseEvidence => !!r && typeof r === "object" && typeof (r as CaseEvidence).id === "string"); } async function mutateEvidence(caseId: string, fn: (rows: CaseEvidence[]) => T | Promise): Promise { const f = await file(caseId); return withFileLock(f, async () => { const rows = await readEvidence(caseId); const out = await fn(rows); await writeWhole(f, `${JSON.stringify(rows, null, 2)}\n`); return out; }); } const nextId = (rows: CaseEvidence[]) => `e${rows.reduce((n, r) => Math.max(n, Number(/^e(\d+)$/.exec(r.id)?.[1] ?? 0)), 0) + 1}`; const evidenceOf = (rows: CaseEvidence[], id: string) => { const r = rows.find((x) => x.id === id); if (!r) throw new CaseError(`no evidence ${id}`, 404); return r; }; // ── the view ── export type EvidenceRow = CaseEvidence & { label: string; fileUrls?: { name: string; url: string }[] }; export type EvidenceView = { rows: EvidenceRow[]; pagesChannels: PagesChannel[]; forumChannels: PostsChannel[]; findings: { row: string; quote: string }[] }; export function labelled(r: CaseEvidence): EvidenceRow { const out: EvidenceRow = { ...r, label: evidenceLabel(r) }; if (r.kind === "forum-attachment" && r.slug && r.post && r.files?.length) { out.fileUrls = r.files.map((name) => ({ name, url: corpusMediaUrl(path.join(CHANNELS_DIR, r.slug!, "posts-media", r.post!, name)) })); } return out; } export async function evidenceView(caseId: string): Promise { const rows = await readEvidence(caseId); const { rows: findings } = await readFindings(caseId); const forum = (await postsChannels(caseId)).filter((c) => c.platform === "xenforo"); return { rows: rows.map(labelled), pagesChannels: await webpageChannels(), forumChannels: forum, findings: findings.map((f) => ({ row: f.row, quote: f.quote.slice(0, 120) })), }; } // ── Wayback targets ── export async function addTargets(caseId: string, urls: string[], dates: string[], now = new Date()): Promise { const list = urls.map((u) => u.trim()).filter(Boolean); if (!list.length) throw new CaseError("name at least one page URL", 400); for (const u of list) if (!/^https?:\/\/[^\s]+$/.test(u)) throw new CaseError(`not an http(s) URL: ${u}`, 400); const ats = dates.map((d) => d.trim()).filter(Boolean); const parsed = ats.map((d) => evidenceDate(d) ?? (() => { throw new CaseError(`not a date: ${d} (YYYY-MM-DD)`, 400); })()); const at = now.toISOString(); return mutateEvidence(caseId, (rows) => { const added: CaseEvidence[] = []; for (const url of list) { for (const d of parsed.length ? parsed : [undefined]) { if (rows.some((r) => r.kind === "wayback" && r.url === url && r.at === d)) continue; if (rows.length >= MAX_ROWS) throw new CaseError(`a case holds at most ${MAX_ROWS} evidence rows`, 400); const row: CaseEvidence = { id: nextId(rows), kind: "wayback", url, ...(d ? { at: d } : {}), state: "planned", createdAt: at, updatedAt: at }; rows.push(row); added.push(row); } } return added; }); } /** Ask whether the Wayback Machine will show the target at all (no capture is fetched). */ export async function lookupTarget(caseId: string, id: string, now = new Date()): Promise { const row = evidenceOf(await readEvidence(caseId), id); if (row.kind !== "wayback") throw new CaseError(`${id} is not a Wayback target`, 400); const a = await editorCall("/api/ops/wayback-lookup", { method: "POST", body: { url: row.url, okOnly: true, limit: 500 } }); return mutateEvidence(caseId, (rows) => { const r = evidenceOf(rows, id); r.updatedAt = now.toISOString(); if (a.body.refusal === "excluded") { r.state = "excluded"; r.refusal = "excluded"; r.message = EXCLUDED_SENTENCE; } else if (!a.ok) { r.state = "failed"; r.message = refusalText(a); } else { const caps = Array.isArray(a.body.captures) ? (a.body.captures as { timestamp?: string }[]) : []; const near = nearestTs(caps.map((c) => String(c.timestamp ?? "")).filter(Boolean), r.at); delete r.refusal; r.message = caps.length ? `${caps.length} capture${caps.length === 1 ? "" : "s"}${near ? `; nearest ${near.slice(0, 4)}-${near.slice(4, 6)}-${near.slice(6, 8)}` : ""}` : "no captures listed"; if (r.state === "excluded" || r.state === "failed") r.state = "planned"; } return labelled(r); }); } function nearestTs(ts: string[], at?: string): string | undefined { if (!ts.length) return undefined; if (!at) return ts[ts.length - 1]; const want = Number(at.padEnd(14, "0")); return ts.reduce((best, t) => (Math.abs(Number(t.padEnd(14, "0")) - want) < Math.abs(Number(best.padEnd(14, "0")) - want) ? t : best)); } /** Import the capture nearest the row's date into a Wayback pages channel (picked, or created on no site). */ export async function captureTarget(caseId: string, id: string, into: { slug: string } | { create: { name: string } }, now = new Date()): Promise { const row = evidenceOf(await readEvidence(caseId), id); if (row.kind !== "wayback") throw new CaseError(`${id} is not a Wayback target`, 400); if (row.state === "excluded") throw new CaseError(`${row.url} is ${EXCLUDED_SENTENCE}`, 409); let slug: string; if ("create" in into) { const name = into.create.name.trim(); if (!name) throw new CaseError("give the new channel a name", 400); const host = new URL(row.url).hostname; // On no site: a site is the operator's to add. const made = await editorCall("/api/ops/create-channel", { method: "POST", body: { fields: { name, handling: "transcribe", url: `https://web.archive.org/web/*/${host}/*` } }, }); if (!made.ok) throw new CaseError(`the editor would not create the channel: ${refusalText(made)}`, made.status >= 400 && made.status < 500 ? made.status : 502); slug = String(made.body.slug); } else { slug = into.slug; if (!(await webpageChannels()).some((c) => c.slug === slug)) throw new CaseError(`${slug} is not a Wayback pages channel`, 400); } const a = await editorCall("/api/ops/import-page", { method: "POST", body: { slug, url: row.url, ...(row.at ? { at: row.at } : {}) } }); return mutateEvidence(caseId, (rows) => { const r = evidenceOf(rows, id); r.slug = slug; r.updatedAt = now.toISOString(); if (a.ok && typeof a.body.jobId === "string") { r.state = "queued"; r.job = a.body.jobId; delete r.message; delete r.refusal; } else if (a.body.refusal === "excluded") { r.state = "excluded"; r.refusal = "excluded"; r.message = EXCLUDED_SENTENCE; } else { r.state = "failed"; r.message = refusalText(a); } return labelled(r); }); } // ── forum attachments ── export async function addForumAttachment(caseId: string, slug: string, post: string, now = new Date()): Promise { if (!/^[A-Za-z0-9_.@-]+$/.test(slug) || !/^[A-Za-z0-9_.@-]+$/.test(post)) throw new CaseError("name a forum channel and a post id", 400); const posts = await readAllPosts(path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug)); const p = posts.find((x) => x.id === post); if (!p) throw new CaseError(`no post ${post} in ${slug}`, 404); const a = await editorCall("/api/ops/capture-posts", { method: "POST", body: { slug, ids: [post], shots: true, media: true } }); const at = now.toISOString(); return mutateEvidence(caseId, (rows) => { const existing = rows.find((r) => r.kind === "forum-attachment" && r.slug === slug && r.post === post); const r: CaseEvidence = existing ?? { id: nextId(rows), kind: "forum-attachment", url: p.url, slug, post, ...(p.forum?.position ? { position: p.forum.position } : {}), state: "planned", createdAt: at, updatedAt: at, }; r.updatedAt = at; if (a.ok && typeof a.body.jobId === "string") { r.state = "queued"; r.job = a.body.jobId; delete r.message; } else { r.state = "failed"; r.message = refusalText(a); } if (!existing) rows.push(r); return labelled(r); }); } async function capturedFiles(slug: string, post: string): Promise { const dir = path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug, "posts-media", post); const names = await readdir(/* turbopackIgnore: true */ dir).catch(() => [] as string[]); return names.filter((n) => !n.startsWith(".") && !n.endsWith(".json")).sort(); } // ── where a queued row is ── export async function refreshEvidence(caseId: string, id: string, now = new Date()): Promise { const row = evidenceOf(await readEvidence(caseId), id); if (row.state !== "queued" || !row.job) return labelled(row); const st = await jobState(row.job); if (!st.done) return labelled(row); const files = row.kind === "forum-attachment" && row.slug && row.post ? await capturedFiles(row.slug, row.post) : []; const res = row.kind === "wayback" ? resultLine<{ ok?: boolean; captureTs?: string; records?: string[]; refusal?: string; error?: string }>(st.tail, IMPORT_PAGE_MARKER) : null; return mutateEvidence(caseId, (rows) => { const r = evidenceOf(rows, id); r.updatedAt = now.toISOString(); if (r.kind === "wayback") { if (res?.ok) { r.state = "captured"; if (res.captureTs) r.captureTs = res.captureTs; if (res.records?.length) r.records = res.records; } else if (res?.refusal === "excluded") { r.state = "excluded"; r.refusal = "excluded"; r.message = EXCLUDED_SENTENCE; } else { r.state = "failed"; r.message = res?.error ?? `the import job ${st.status}`; if (res?.refusal) r.refusal = res.refusal; } } else if (st.status === "done" && files.length) { r.state = "captured"; r.files = files; } else { r.state = "failed"; r.message = st.status === "done" ? "the capture job finished with no file for the post" : `the capture job ${st.status}`; } return labelled(r); }); } // ── evidence for a finding ── export function findingEvidenceOf(r: CaseEvidence): FindingEvidence { if (r.kind === "forum-attachment") { return { kind: "forum-attachment", url: r.url, evidence: r.id, ...(r.post ? { post: r.post } : {}), ...(r.position ? { position: r.position } : {}) }; } const url = r.captureTs ? `https://web.archive.org/web/${r.captureTs}/${r.url}` : r.url; return { kind: "wayback", url, evidence: r.id, ...(r.captureTs ? { capturedAt: r.captureTs } : {}) }; } /** Attach an evidence row to a finding (both sides recorded). */ export async function attachEvidence(caseId: string, id: string, findingRow: string): Promise<{ evidence: EvidenceRow; finding: FindingRow }> { const r = evidenceOf(await readEvidence(caseId), id); if (r.state === "excluded") throw new CaseError(`${r.url} is ${EXCLUDED_SENTENCE}: there is nothing to attach`, 409); const fe = findingEvidenceOf(r); const { result: finding } = await mutateFindings(caseId, (rows) => { const f = rowOf(rows, findingRow); f.evidence = [...(f.evidence ?? []).filter((e) => e.evidence !== id), fe]; return f; }); const evidence = await mutateEvidence(caseId, (rows) => { const e = evidenceOf(rows, id); e.findings = [...new Set([...(e.findings ?? []), findingRow])]; return labelled(e); }); return { evidence, finding }; } // ── the export's Evidence section: common's (caseEvidence.ts), which lane A's export calls ── export { evidenceLine, evidenceSection } from "yt-dlp-transcript-common/lib/research/caseEvidence";