Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 05118299509c98ee202ebd05bcaacb1eb1e04415
parent 77297ec6ca8eb0f3c0aba62607f740e2424704cd
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 07:36:09 -0400

common: the deleted-video fallback (release 29 E2) — one gone reading (lib/sourceGone.ts: deleted or private, refresh's, now shared by refresh's delta, compose, missingEvidenceWindows, fetch-windows' door and find-copy); a Wayback CDX client with archive.org's manners (lib/waybackClient.ts); controller/findCopy.ts: per gone recording a cited window needs, the newest 200 Wayback capture of its page, else an archive.org mirror naming its YouTube id (an original video file preferred), its windows handed to fetch-windows with the copy's URL and the copy in each window's provenance (ClipProvenance.copy); compose accepts a cited moment whose source is gone and has no media as its words only, flagged sourceGone on the citation and the moment (a live one is still refused); prepare and reports check say so as a warning; MomentArticle and CitationCard show "Source deleted"; the archive.org fake gains a mirror and field:value searches

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/bin/reports-check.ts | 5+++++
Mcommon/bin/reports-prepare.ts | 6++++++
Mcommon/components/citations/CitationCard.tsx | 21+++++++++++++++++----
Mcommon/components/report/MomentArticle.tsx | 11+++++++++++
Mcommon/controller/fetchWindows.test.ts | 15+++++++++++++++
Mcommon/controller/fetchWindows.ts | 5+++++
Acommon/controller/findCopy.test.ts | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/findCopy.ts | 387+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/archiveOrgClient.ts | 9+++++++++
Mcommon/lib/clipWindow.ts | 18++++++++++++++++++
Mcommon/lib/report/draft/refresh/delta.ts | 6+++---
Mcommon/lib/report/views.ts | 14++++++++++++++
Acommon/lib/sourceGone-server.ts | 33+++++++++++++++++++++++++++++++++
Acommon/lib/sourceGone.test.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/sourceGone.ts | 31+++++++++++++++++++++++++++++++
Acommon/lib/waybackClient.test.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackClient.ts | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/composeReports.test.ts | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/composeReports.ts | 49+++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/publish/missingEvidenceWindows.test.ts | 2++
Mcommon/publish/reportMedia.test.ts | 36++++++++++++++++++++++++++++++++++++
Mcommon/publish/reportMedia.ts | 47++++++++++++++++++++++++++++++++++++++---------
Mcommon/testing/archiveOrg/fakeArchiveOrg.mjs | 37++++++++++++++++++++++++++++++++++++-
Mcommon/ytdlp/fetchWindowManaged.ts | 4++++
24 files changed, 1233 insertions(+), 21 deletions(-)

diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts @@ -66,6 +66,7 @@ import { resolveReports, } from "../publish/composeReports"; import { articlesWorkHost, siteReportHost, type ReportHost } from "../publish/reportHost"; +import { SOURCE_GONE_LABELS } from "../lib/sourceGone"; type Out = { log: (s: string) => void; error: (s: string) => void }; @@ -116,6 +117,10 @@ export async function checkMain( for (const line of formatComposeReportsProblems(resolved.allowed)) { out.log(` allowed (--allow-missing-media): ${line}`); } + // A gone source's moment with no media is a warning: its words only. + for (const g of resolved.sourceGone) { + out.log(` warning: ${g.moment}: ${SOURCE_GONE_LABELS[g.state].toLowerCase()} — its words only (cited by ${g.citations.join(", ")})`); + } for (const r of resolved.reports) { const scores = Object.values(r.citations ?? {}) .map((c) => (c.kind === "video" || c.kind === "audio" || c.kind === "post" ? c.verification?.quoteScore : undefined)) diff --git a/common/bin/reports-prepare.ts b/common/bin/reports-prepare.ts @@ -63,6 +63,12 @@ export async function main( out.error(`reports prepare: ${(err as Error).message}`); return opts.signal?.aborted ? 1 : 2; } + // A gone source's moment with no media is a warning: compose shows its words + // only, marked "source deleted" (release 29 E2). + if (index.warnings?.length) { + out.log(`reports prepare ${who}: warning: ${index.warnings.length} moment(s) whose source is gone show their words only:`); + for (const line of formatReportMediaProblems(index.warnings)) out.log(` ${line}`); + } if (opts.only && opts.article) return onlyArticle(opts.article, index, opts, out); if (index.problems.length > 0) { out.error(`reports prepare ${who}: ${index.problems.length} problem(s):`); diff --git a/common/components/citations/CitationCard.tsx b/common/components/citations/CitationCard.tsx @@ -13,6 +13,7 @@ import { type SpanCitationView, } from "../../lib/report/views"; import { cn } from "../../lib/utils"; +import { SOURCE_GONE_LABELS } from "../../lib/sourceGone"; import { VerificationBadge } from "./VerificationBadge"; // ONE CITATION, as a reader sees it — kind-aware, from a resolved view @@ -135,10 +136,17 @@ function Picture({ c, variant }: { c: CitationView; variant: CitationCardVariant function SpanLinks({ c }: { c: SpanCitationView }) { return ( <> - <a href={c.href} className={linkClass}> - <Play className="size-3 shrink-0" aria-hidden /> - Play {spanLabel(c.start, c.end)} - </a> + {c.sourceGone ? ( + // Nothing to play: the moment's page has its words. + <a href={c.href} className={linkClass}> + Open {spanLabel(c.start, c.end)} + </a> + ) : ( + <a href={c.href} className={linkClass}> + <Play className="size-3 shrink-0" aria-hidden /> + Play {spanLabel(c.start, c.end)} + </a> + )} <RecordLinks r={c.record} /> {c.record.corpusUrl && ( <a href={c.record.corpusUrl} className={linkClass}> @@ -269,6 +277,11 @@ export function CitationCard({ </span> )} {c.label && <span className="truncate normal-case tracking-normal">· {c.label}</span>} + {(c.kind === "video" || c.kind === "audio" || c.kind === "post") && c.sourceGone && ( + <span data-source-gone={c.sourceGone} className="normal-case tracking-normal"> + · {SOURCE_GONE_LABELS[c.sourceGone]} + </span> + )} </div> <div className="font-medium leading-snug text-foreground break-words">{title}</div> {meta.length > 0 && <div className="font-mono text-xs text-muted-foreground">{meta.join(" · ")}</div>} diff --git a/common/components/report/MomentArticle.tsx b/common/components/report/MomentArticle.tsx @@ -3,6 +3,7 @@ import { VerdictChip } from "./VerdictChip"; import { formatTimestamp } from "../../lib/vtt"; import { CITATION_KIND_LABELS, spanLabel, type MomentPageView, type RecordView } from "../../lib/report/views"; import { ExternalLinkText, Eyebrow, dateLabel, textLink } from "./parts"; +import { SOURCE_GONE_LABELS } from "../../lib/sourceGone"; // ONE CITED MOMENT, from its view (common/lib/report/views.ts): a span's // self-hosted evidence clip (video, or audio with its poster) or a post's @@ -47,6 +48,16 @@ export default function MomentArticle({ {meta && <p className="font-mono text-xs text-muted-foreground">{meta}</p>} </header> + {view.sourceGone && ( + // The source is gone and no copy of the moment is published: its words + // only (release 29 E2). + <p + data-source-gone={view.sourceGone} + className="rounded-lg border border-dashed border-border px-3 py-2 text-sm text-muted-foreground" + > + {SOURCE_GONE_LABELS[view.sourceGone]} + </p> + )} {clip && view.kind === "video" && ( <video data-evidence-clip="" diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -17,6 +17,7 @@ import { type FetchWindowsDeps, type FetchWindowsItem, } from "./fetchWindows"; +import { parseClipProvenance } from "../lib/clipWindow"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import type { SiteSettings } from "../lib/settings"; @@ -421,3 +422,17 @@ test("a cached unpadded window does not cover a padded ask: it is fetched, its p const again = await go(paths, [padded, item("v1", "/exact", 10, 20)], harness()); assert.deepEqual([again.cached.length, again.fetched.length], [2, 0]); }); + +test("a window of a gone recording fetched from a copy (find-copy) records which copy in its sidecar", async () => { + const paths = await corpus(); + const copy = { from: "wayback" as const, url: "https://web.archive.org/web/20260125093000/https://www.youtube.com/watch?v=v1" }; + const r = await go(paths, [{ slug: "c", id: "v1", from: 10, to: 20, webpageUrl: copy.url, copy }], harness()); + assert.equal(r.fetched.length, 1); + const clips = path.join(paths.channelsDir, "c", "data", "v1", "clips"); + const sidecar = JSON.parse(await readFile(path.join(clips, "10.00-20.00.json"), "utf8")) as { copy?: unknown; ytdlp?: { args: string[] } }; + assert.deepEqual(sidecar.copy, copy); + // The copy's URL is what yt-dlp was given. + assert.equal(sidecar.ytdlp?.args.at(-1), copy.url); + assert.deepEqual(parseClipProvenance(sidecar)?.copy, copy); + assert.equal(parseClipProvenance({ requestedBy: "x", copy: { from: "elsewhere", url: copy.url } })?.copy, undefined); +}); diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -4,6 +4,7 @@ import type { ChannelConfig } from "../lib/channelConfig"; import type { SiteSettings } from "../lib/settings"; import { getSettings } from "../lib/settings"; import type { DownloadFailureClass } from "../lib/availability"; +import type { ClipCopy } from "../lib/clipWindow"; import { resolveCookiePolicy } from "../lib/cookiePolicy"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { detectPlatform } from "../lib/platform"; @@ -127,6 +128,9 @@ export type FetchWindowsItem = { pad?: number; // The page URL when the caller has it; else resolved as the single fetch does. webpageUrl?: string; + // The copy of a gone recording `webpageUrl` is (release 29 E2, find-copy): + // recorded in the window's provenance. + copy?: ClipCopy; }; export type FetchWindowsFailureClass = @@ -527,6 +531,7 @@ export async function fetchWindows({ reason: item.reason, pad: item.pad, requestedAt, + ...(item.copy ? { copy: item.copy } : {}), }, cookiePolicy: resolveCookiePolicy(settings, config), maxHeight, diff --git a/common/controller/findCopy.test.ts b/common/controller/findCopy.test.ts @@ -0,0 +1,209 @@ +// find-copy (release 29 E2) over the fake Wayback and the fake archive.org on +// loopback, through the real polite clients: per gone recording, Wayback first, +// archive.org second, none → its words only; the fetch-windows items carry the +// copy's URL and the copy; one recording at a time; a dry run starts nothing. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/findCopy.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { startFakeWayback } from "../testing/web/fakeWayback.mjs"; +import { ITEMS, startFakeArchiveOrg } from "../testing/archiveOrg/fakeArchiveOrg.mjs"; +import { ArchiveOrgClient } from "../lib/archiveOrgClient"; +import { WaybackClient } from "../lib/waybackClient"; +import type { MissingEvidenceWindows, UnfetchableEvidenceWindow } from "../publish/reportMedia"; +import type { ReportHost } from "../publish/reportHost"; +import type { Paths } from "../lib/paths"; +import type { FetchWindowsItem } from "./fetchWindows"; +import { + findArchiveOrgMirrors, + findCopies, + pickMirrorFile, + runFindCopy, + youtubeIdOf, + youtubeIdQuery, +} from "./findCopy"; + +const CH = "synth-kitchen"; +const watch = (id: string) => `https://video.example/watch?v=${id}`; + +// A second mirror, for a recording the Wayback has no capture of. +const OTHER_MIRROR = { + metadata: { + identifier: "youtube-otherupload1", + title: "Another lost upload", + mediatype: "movies", + description: "Mirror of https://video.example/watch?v=otherupload1", + }, + files: [ + { name: "Another lost upload-otherupload1.mkv", source: "original", format: "Matroska", size: "4000" }, + { name: "Another lost upload-otherupload1.mp4", source: "original", format: "MPEG4", size: "3000" }, + ], +}; + +const gone = (id: string, from: number, clip: string): UnfetchableEvidenceWindow => ({ + slug: CH, + id, + from, + to: from + 10, + clipId: clip, + citations: [clip], + reason: `the words of ${id}`, + why: "gone", + gone: "deleted", + message: "the source says the video is deleted", +}); + +const NEED: MissingEvidenceWindows = { + siteId: "articles", + missing: [], + onDisk: 0, + problems: [], + unfetchable: [ + gone("gone-video-05", 0, "a#c1"), + gone("gone-video-05", 30, "a#c2"), + gone("otherupload1", 5, "a#c3"), + gone("nothing00001", 5, "a#c4"), + { ...gone("elsewhere001", 1, "a#c5"), why: "not-in-site", gone: undefined }, + ], +}; + +async function fakes(o: { waybackBusy?: number } = {}) { + const wb = await startFakeWayback({ busyTimes: o.waybackBusy ?? 0 }); + const ia = await startFakeArchiveOrg({ items: [...ITEMS, OTHER_MIRROR] }); + const deps = { + wayback: new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }), + archive: new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 }), + missing: async () => NEED, + webpageUrl: async (_p: Paths, _slug: string, id: string) => watch(id), + }; + return { wb, ia, deps, close: async () => Promise.all([wb.close(), ia.close()]) }; +} + +const opts = (deps: unknown) => ({ paths: {} as Paths, host: { id: "articles" } as ReportHost, deps: deps as never }); + +test("youtubeIdOf and the mirror query", () => { + assert.equal(youtubeIdOf("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "x"), "dQw4w9WgXcQ"); + assert.equal(youtubeIdOf("https://youtu.be/dQw4w9WgXcQ?t=4", "x"), "dQw4w9WgXcQ"); + assert.equal(youtubeIdOf("https://www.youtube.com/shorts/dQw4w9WgXcQ", "x"), "dQw4w9WgXcQ"); + assert.equal(youtubeIdOf(null, "dQw4w9WgXcQ"), "dQw4w9WgXcQ"); + assert.equal(youtubeIdOf(null, "a/b"), null); + assert.match(youtubeIdQuery("dQw4w9WgXcQ"), /^identifier:\(youtube-dQw4w9WgXcQ\) OR originalurl:\(\*dQw4w9WgXcQ\*\)/); + assert.throws(() => youtubeIdQuery("no spaces allowed"), /not a YouTube id/); +}); + +test("pickMirrorFile: a file naming the id, an original before a derivative, mp4 before webm; a dump of many is no pick", () => { + const f = (name: string, source: string) => ({ name, source }); + assert.deepEqual(pickMirrorFile({ files: [f("x-ID12345.webm", "original"), f("x-ID12345.mp4", "derivative")] }, "ID12345"), { + file: "x-ID12345.webm", + source: "original", + }); + assert.equal(pickMirrorFile({ files: [f("a.mp4", "original"), f("b.webm", "original")] }, "ID12345"), null); + assert.equal(pickMirrorFile({ files: [f("only.mkv", "original"), f("only.mp4", "derivative")] }, "ID12345")?.file, "only.mkv"); + assert.equal(pickMirrorFile({ files: [f("notes.txt", "original")] }, "ID12345"), null); +}); + +test("archive-search by YouTube id: each mirror's direct file URL, an original preferred", async () => { + const { deps, close } = await fakes(); + try { + const r = await findArchiveOrgMirrors("gone-video-05", { client: deps.archive }); + assert.equal(r.found, 1); + assert.deepEqual(r.mirrors, [ + { + identifier: "youtube-gone-video-05", + title: "The old oven review", + file: "The old oven review-gone-video-05.webm", + url: "https://archive.org/download/youtube-gone-video-05/The%20old%20oven%20review-gone-video-05.webm", + source: "original", + size: 3000000, + }, + ]); + assert.deepEqual((await findArchiveOrgMirrors("nothing00001", { client: deps.archive })).mirrors, []); + } finally { + await close(); + } +}); + +test("find-copy: Wayback first, archive.org second, none → words only; one recording at a time", async () => { + const { wb, ia, deps, close } = await fakes(); + try { + const lines: string[] = []; + const r = await findCopies({ ...opts(deps), onLog: (l) => lines.push(l) }); + assert.deepEqual( + r.recordings.map((x) => [x.id, x.outcome, x.copy?.from ?? null, x.windows.length]), + [ + ["gone-video-05", "fetch", "wayback", 2], + ["otherupload1", "fetch", "archive.org", 1], + ["nothing00001", "text-only", null, 1], + ], + ); + const first = r.recordings[0]!; + assert.equal(first.copy!.url, `https://web.archive.org/web/20260125093000/${watch("gone-video-05")}`); + assert.deepEqual(first.tried.map((t) => [t.from, t.found]), [["wayback", true]], "archive.org not asked once Wayback had it"); + assert.deepEqual(r.recordings[2]!.tried.map((t) => [t.from, t.found]), [ + ["wayback", false], + ["archive.org", false], + ]); + assert.equal(r.recordings[1]!.copy!.url, "https://archive.org/download/youtube-otherupload1/Another%20lost%20upload-otherupload1.mp4"); + // Per recording, the CDX first; the archive.org search only when it had none. + assert.deepEqual( + wb.requests.map((q) => new URL(q.path, "http://x").searchParams.get("url")), + ["gone-video-05", "otherupload1", "nothing00001"].map(watch), + ); + assert.ok(ia.requests.every((q) => !q.includes("gone-video-05")), "no archive.org search for the one Wayback found"); + assert.equal(ia.requests.filter((q) => q.startsWith("/advancedsearch.php")).length, 2); + + // The items: each found copy's windows, its URL as webpageUrl, the copy. + assert.deepEqual( + r.items.map((i) => [i.id, i.from, i.to, i.clipId, i.webpageUrl === i.copy?.url, i.copy?.from]), + [ + ["gone-video-05", 0, 10, "a#c1", true, "wayback"], + ["gone-video-05", 30, 40, "a#c2", true, "wayback"], + ["otherupload1", 5, 15, "a#c3", true, "archive.org"], + ], + ); + assert.ok(lines.some((l) => l.includes("nothing00001") && l.includes("its words only"))); + } finally { + await close(); + } +}); + +test("runFindCopy: the found windows go to ONE fetch-windows call; a dry run and a run that finds nothing start none", async () => { + const { deps, close } = await fakes(); + try { + const calls: FetchWindowsItem[][] = []; + const start = async (items: FetchWindowsItem[]) => { + calls.push(items); + return { jobId: "J1" }; + }; + const dry = await runFindCopy({ ...opts(deps), dryRun: true, startFetch: start }); + assert.equal(calls.length, 0); + assert.equal(dry.items.length, 3); + const run = await runFindCopy({ ...opts(deps), startFetch: start }); + assert.equal(calls.length, 1); + assert.equal(calls[0]!.length, 3); + assert.deepEqual(run.fetch, { jobId: "J1" }); + const none = await runFindCopy({ + ...opts({ ...deps, missing: async () => ({ ...NEED, unfetchable: [NEED.unfetchable[3]] }) }), + startFetch: start, + }); + assert.equal(calls.length, 1); + assert.equal(none.fetch, undefined); + assert.equal(none.recordings[0]!.outcome, "text-only"); + } finally { + await close(); + } +}); + +test("a Wayback that keeps refusing stops the run there; the rest are left for a later run", async () => { + const { deps, close } = await fakes({ waybackBusy: 50 }); + try { + const r = await findCopies(opts(deps)); + assert.equal(r.recordings.length, 1); + assert.equal(r.recordings[0]!.outcome, "error"); + assert.match(r.stopped ?? "", /kept refusing/); + assert.deepEqual(r.items, []); + } finally { + await close(); + } +}); diff --git a/common/controller/findCopy.ts b/common/controller/findCopy.ts @@ -0,0 +1,387 @@ +// FIND A COPY OF A GONE RECORDING (release 29 E2) — the deleted-video fallback. +// +// A report cites a moment of a recording its platform no longer serves +// (deleted or made private: lib/sourceGone.ts). Its window cannot be fetched +// from its own page, so `missingEvidenceWindows` lists it as "unfetchable: +// gone". This looks for a copy, per recording, in order: +// +// 1. THE WAYBACK MACHINE: a capture of the recording's page that recorded a +// 200 (the CDX API, lib/waybackClient.ts) — the newest — whose replay URL +// `https://web.archive.org/web/<ts>/<page>` yt-dlp reads the video from; +// 2. ARCHIVE.ORG: a mirror that names the YouTube id (in its identifier, its +// title, its description or its original URL) and holds a video file — +// an original preferred — fetched by its direct URL +// `https://archive.org/download/<identifier>/<file>`. +// +// A copy found: the recording's cited windows go to fetch-windows with the +// copy's URL as each item's `webpageUrl` (controller/fetchWindows.ts), so the +// clips land in the recording's own `data/<id>/clips/`, and each window's +// sidecar records which copy (`copy: {from, url}`, lib/clipWindow.ts). None +// found: the windows are left, and compose shows the moments' words only, +// marked "source deleted". +// +// PACED: one recording at a time; every Wayback and archive.org request goes +// through the polite clients (one at a time, 2 s apart, 429s waited out). A +// lookup that archive.org keeps refusing stops the run there; the rest are +// left for a later run. The fetch is ONE fetch-windows job on the archive.org +// clip queue, which walks its windows one at a time — one stream. + +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { ClipCopy } from "../lib/clipWindow"; +import type { GoneState } from "../lib/sourceGone"; +import { loadAvailability } from "../lib/availability-server"; +import { archiveOrgClient, ArchiveOrgRequestError, type ArchiveOrgClient } from "../lib/archiveOrgClient"; +import { archiveOrgDownloadUrl } from "../lib/archiveOrgId"; +import { archiveOrgRestriction, searchArchiveOrgItems } from "./archiveOrgImport"; +import { isArchiveOrgVideoFileName, type ArchiveOrgItemMetadata } from "../lib/archiveOrg"; +import { waybackClient, type WaybackCapture } from "../lib/waybackClient"; +import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; +import { channelConfigPlatform } from "../lib/videoId"; +import { readChannelConfig } from "./channels"; +import { findVideoSourceUrl } from "./undownloadedVideos"; +import { missingEvidenceWindows, type EvidenceWindow, type MissingEvidenceWindows } from "../publish/reportMedia"; +import type { ReportHost } from "../publish/reportHost"; +import type { FetchWindowsItem } from "./fetchWindows"; + +// ─── A recording's page and its YouTube id ─── + +// The page a gone recording was served at: its metadata's `webpage_url`, else +// the one its availability check recorded, else the playlist's. +export async function recordWebpageUrl(paths: Paths, slug: string, id: string): Promise<string | null> { + const config = await readChannelConfig(paths, slug).catch(() => null); + const dirId = await resolveVideoDirId(paths.channelsDir, slug, id, config ? { platform: channelConfigPlatform(config) } : {}); + const dir = path.join(paths.channelsDir, slug, "data", dirId); + try { + const meta = JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8")) as { webpage_url?: unknown }; + if (typeof meta.webpage_url === "string" && /^https?:\/\//.test(meta.webpage_url)) return meta.webpage_url; + } catch { + // no metadata: the next source + } + const av = await loadAvailability(dir).catch(() => null); + if (av?.webpageUrl && /^https?:\/\//.test(av.webpageUrl)) return av.webpageUrl; + return config ? findVideoSourceUrl(paths, slug, dirId, config).catch(() => null) : null; +} + +const YOUTUBE_ID = /^[A-Za-z0-9_-]{6,20}$/; + +// The id a mirror would name: a watch URL's `v`, a youtu.be path, a +// /shorts/ or /live/ path — else the record's own id. +export function youtubeIdOf(watchUrl: string | null, recordId: string): string | null { + if (watchUrl) { + try { + const u = new URL(watchUrl); + const v = u.searchParams.get("v"); + if (v && YOUTUBE_ID.test(v)) return v; + const seg = u.pathname.split("/").filter(Boolean); + if (u.hostname.endsWith("youtu.be") && seg[0] && YOUTUBE_ID.test(seg[0])) return seg[0]; + const k = seg.findIndex((s) => s === "shorts" || s === "live" || s === "embed"); + if (k >= 0 && seg[k + 1] && YOUTUBE_ID.test(seg[k + 1])) return seg[k + 1]; + } catch { + // not a URL: the record's id + } + } + return YOUTUBE_ID.test(recordId) ? recordId : null; +} + +// ─── archive.org: a mirror by YouTube id ─── + +// archive.org's advanced search for a mirror of one YouTube upload: a +// mirroring tool's identifier (`youtube-<id>`), its original URL, or the id +// in its description or title. +export function youtubeIdQuery(id: string): string { + if (!YOUTUBE_ID.test(id)) throw new Error(`"${id}" is not a YouTube id`); + return `identifier:(youtube-${id}) OR originalurl:(*${id}*) OR description:("${id}") OR title:("${id}")`; +} + +const EXT_RANK = ["mp4", "webm", "mkv", "m4v", "mov"]; +const extOf = (name: string) => (/\.([A-Za-z0-9]{1,8})$/.exec(name)?.[1] ?? "").toLowerCase(); + +// The item's video file for the upload: among its video files (a file naming +// the id first, else every one when the item holds a single original video), +// an ORIGINAL before a derivative, then mp4, webm, mkv, … Null when the item +// holds none, or several originals none of which names the id (a channel +// dump: which file is the upload cannot be told). +export function pickMirrorFile( + item: Pick<ArchiveOrgItemMetadata, "files">, + youtubeId: string, +): { file: string; source: "original" | "derivative"; size?: number } | null { + const videos = item.files.filter( + (f) => isArchiveOrgVideoFileName(f.name) && (f.source === "original" || f.source === "derivative"), + ); + const named = videos.filter((f) => f.name.includes(youtubeId)); + const originals = videos.filter((f) => f.source === "original"); + const pool = named.length > 0 ? named : originals.length === 1 ? videos : []; + if (pool.length === 0) return null; + const rank = (f: { name: string; source?: string }) => + (f.source === "original" ? 0 : 100) + (EXT_RANK.includes(extOf(f.name)) ? EXT_RANK.indexOf(extOf(f.name)) : EXT_RANK.length); + const best = [...pool].sort((a, b) => rank(a) - rank(b))[0]!; + const size = best.size && /^\d+$/.test(best.size) ? Number(best.size) : undefined; + return { file: best.name, source: best.source === "original" ? "original" : "derivative", ...(size !== undefined ? { size } : {}) }; +} + +export type ArchiveOrgMirror = { + identifier: string; + title?: string; + file: string; + // The file's direct download URL. + url: string; + source: "original" | "derivative"; + size?: number; +}; + +export type ArchiveOrgMirrorSearch = { + youtubeId: string; + query: string; + found: number; + mirrors: ArchiveOrgMirror[]; + // Items the search found that are not a usable mirror, and why. + skipped: { identifier: string; why: string }[]; +}; + +const textOf = (v: unknown): string => + typeof v === "string" ? v : Array.isArray(v) ? v.filter((x) => typeof x === "string").join(" ") : ""; + +// archive.org mirrors of one YouTube upload: the search (one request), then +// each hit's metadata (one request each, cached), at most `limit` items. An +// item that does not name the id, is restricted, or holds no video file the +// upload can be told by is skipped, with why. +export async function findArchiveOrgMirrors( + youtubeId: string, + o: { client?: ArchiveOrgClient; signal?: AbortSignal; limit?: number } = {}, +): Promise<ArchiveOrgMirrorSearch> { + const client = o.client ?? archiveOrgClient; + const query = youtubeIdQuery(youtubeId); + const hits = await searchArchiveOrgItems(query, { client, rows: o.limit ?? 10, ...(o.signal ? { signal: o.signal } : {}) }); + const mirrors: ArchiveOrgMirror[] = []; + const skipped: { identifier: string; why: string }[] = []; + for (const hit of hits.items) { + const item = await client.itemMetadata(hit.identifier, o.signal); + const meta = item.metadata as Record<string, unknown>; + const said = [item.metadata.identifier, textOf(meta.title), textOf(meta.description), textOf(meta.originalurl), ...item.files.map((f) => f.name)].join(" "); + if (!said.includes(youtubeId)) { + skipped.push({ identifier: hit.identifier, why: "it does not name the id" }); + continue; + } + if (archiveOrgRestriction(item).item) { + skipped.push({ identifier: hit.identifier, why: "archive.org restricts it" }); + continue; + } + const pick = pickMirrorFile(item, youtubeId); + if (!pick) { + skipped.push({ identifier: hit.identifier, why: "no video file of the upload can be told in it" }); + continue; + } + const title = textOf(meta.title) || hit.title; + mirrors.push({ + identifier: item.metadata.identifier, + ...(title ? { title } : {}), + file: pick.file, + url: archiveOrgDownloadUrl(item.metadata.identifier, pick.file), + source: pick.source, + ...(pick.size !== undefined ? { size: pick.size } : {}), + }); + } + // Originals first, then the search's order. + mirrors.sort((a, b) => (a.source === b.source ? 0 : a.source === "original" ? -1 : 1)); + return { youtubeId, query, found: hits.found, mirrors, skipped }; +} + +// ─── Wayback: the captures of a page ─── + +export type WaybackLookup = { url: string; captures: WaybackCapture[] }; + +// The captures of a page (every one, or only the 200s). Throws +// ArchiveOrgRequestError when the CDX API keeps refusing. +export async function waybackLookup( + url: string, + o: { client?: { captures: typeof waybackClient.captures }; okOnly?: boolean; limit?: number; signal?: AbortSignal } = {}, +): Promise<WaybackLookup> { + const client = o.client ?? waybackClient; + const captures = await client.captures(url, { + ...(o.okOnly ? { okOnly: true } : {}), + ...(o.limit ? { limit: o.limit } : {}), + ...(o.signal ? { signal: o.signal } : {}), + }); + return { url, captures }; +} + +// ─── find-copy ─── + +export type FindCopyAttempt = { + from: ClipCopy["from"]; + found: boolean; + url?: string; + // What was found or why not, in a phrase. + detail?: string; + error?: string; +}; + +export type FindCopyRecording = { + slug: string; + id: string; + gone: GoneState; + watchUrl: string | null; + youtubeId: string | null; + // The cited windows of the recording. + windows: EvidenceWindow[]; + tried: FindCopyAttempt[]; + copy?: ClipCopy; + // fetch a copy found: its windows go to fetch-windows + // text-only no copy: the moments show their words only ("source deleted") + // error a lookup failed: a later run tries again + outcome: "fetch" | "text-only" | "error"; +}; + +export type FindCopyResult = { + host: string; + recordings: FindCopyRecording[]; + // The fetch-windows items: each found copy's windows, its URL as the item's + // webpageUrl and the copy for the provenance. + items: FetchWindowsItem[]; + // Why the run stopped before its last recording, when it did. + stopped?: string; +}; + +export type FindCopyDeps = { + wayback: { captures: typeof waybackClient.captures }; + archive: ArchiveOrgClient; + missing: (paths: Paths, host: ReportHost) => Promise<MissingEvidenceWindows>; + webpageUrl: (paths: Paths, slug: string, id: string) => Promise<string | null>; +}; + +const DEFAULT_DEPS: FindCopyDeps = { + wayback: waybackClient, + archive: archiveOrgClient, + missing: (paths, host) => missingEvidenceWindows(paths, host), + webpageUrl: recordWebpageUrl, +}; + +// Look for a copy of every gone recording the host's reports cite: Wayback, +// then archive.org, one recording at a time. Nothing is fetched here; the +// answer's `items` are what fetch-windows is given (the caller starts it). +export async function findCopies(opts: { + paths: Paths; + host: ReportHost; + signal?: AbortSignal; + onLog?: (line: string) => void; + deps?: Partial<FindCopyDeps>; +}): Promise<FindCopyResult> { + const deps: FindCopyDeps = { ...DEFAULT_DEPS, ...opts.deps }; + const log = (line: string) => opts.onLog?.(line); + const need = await deps.missing(opts.paths, opts.host); + const byRecording = new Map<string, { slug: string; id: string; gone: GoneState; windows: EvidenceWindow[] }>(); + for (const w of need.unfetchable) { + if (w.why !== "gone" || !w.gone) continue; + const key = `${w.slug}/${w.id}`; + const r = byRecording.get(key) ?? { slug: w.slug, id: w.id, gone: w.gone, windows: [] }; + r.windows.push(w); + byRecording.set(key, r); + } + const result: FindCopyResult = { host: opts.host.id, recordings: [], items: [] }; + log(`find-copy ${opts.host.id}: ${byRecording.size} gone recording(s) cited, ${[...byRecording.values()].reduce((n, r) => n + r.windows.length, 0)} window(s).`); + + for (const r of byRecording.values()) { + if (opts.signal?.aborted) { + result.stopped = "cancelled"; + break; + } + const watchUrl = await deps.webpageUrl(opts.paths, r.slug, r.id); + const youtubeId = youtubeIdOf(watchUrl, r.id); + const rec: FindCopyRecording = { ...r, watchUrl, youtubeId, tried: [], outcome: "text-only" }; + result.recordings.push(rec); + let refused: string | undefined; + + // 1. The Wayback Machine: the newest capture of the page that recorded a 200. + if (watchUrl) { + try { + const { captures } = await waybackLookup(watchUrl, { client: deps.wayback, okOnly: true, ...(opts.signal ? { signal: opts.signal } : {}) }); + const ok = captures.filter((c) => c.status === "200"); + const newest = ok[ok.length - 1]; + if (newest) { + rec.copy = { from: "wayback", url: newest.replayUrl }; + rec.tried.push({ from: "wayback", found: true, url: newest.replayUrl, detail: `${ok.length} capture(s) of the page; the newest, ${newest.timestamp}` }); + } else { + rec.tried.push({ from: "wayback", found: false, detail: "no capture of the page" }); + } + } catch (e) { + rec.tried.push({ from: "wayback", found: false, error: (e as Error).message }); + if (e instanceof ArchiveOrgRequestError && e.rateLimited) refused = (e as Error).message; + } + } else { + rec.tried.push({ from: "wayback", found: false, detail: "the recording's page is not known" }); + } + + // 2. archive.org: a mirror naming the YouTube id. + if (!rec.copy && !refused) { + if (youtubeId) { + try { + const found = await findArchiveOrgMirrors(youtubeId, { client: deps.archive, ...(opts.signal ? { signal: opts.signal } : {}) }); + const m = found.mirrors[0]; + if (m) { + rec.copy = { from: "archive.org", url: m.url }; + rec.tried.push({ from: "archive.org", found: true, url: m.url, detail: `${m.identifier}: ${m.file} (${m.source})` }); + } else { + rec.tried.push({ + from: "archive.org", + found: false, + detail: found.found ? `${found.found} item(s), none a mirror (${found.skipped.map((s) => `${s.identifier}: ${s.why}`).join("; ")})` : "no item names the id", + }); + } + } catch (e) { + rec.tried.push({ from: "archive.org", found: false, error: (e as Error).message }); + if (e instanceof ArchiveOrgRequestError && e.rateLimited) refused = (e as Error).message; + } + } else { + rec.tried.push({ from: "archive.org", found: false, detail: "no YouTube id to search for" }); + } + } + + if (rec.copy) { + rec.outcome = "fetch"; + for (const w of r.windows) { + result.items.push({ + slug: w.slug, + id: w.id, + from: w.from, + to: w.to, + clipId: w.clipId, + ...(w.reason ? { reason: w.reason.slice(0, 400) } : {}), + webpageUrl: rec.copy.url, + copy: rec.copy, + }); + } + } else if (rec.tried.some((t) => t.error)) { + rec.outcome = "error"; + } + log( + ` ${r.slug}/${r.id} (${r.gone}, ${r.windows.length} window(s)): ` + + rec.tried.map((t) => `${t.from} ${t.found ? `found — ${t.detail}` : t.error ? `failed — ${t.error}` : `none — ${t.detail}`}`).join("; ") + + ` → ${rec.outcome === "fetch" ? `fetch from the ${rec.copy!.from === "wayback" ? "Wayback capture" : "archive.org file"}` : rec.outcome === "text-only" ? "its words only" : "try again later"}`, + ); + if (refused) { + result.stopped = `archive.org kept refusing (${refused}); the rest are left for a later run`; + log(`find-copy: ${result.stopped}.`); + break; + } + } + return result; +} + +// find-copy, whole: the lookups, then (unless `dryRun`) ONE fetch-windows of +// every found copy's windows through `startFetch` (the editor's job). A run +// with nothing found starts nothing. +export async function runFindCopy<T>(opts: { + paths: Paths; + host: ReportHost; + dryRun?: boolean; + signal?: AbortSignal; + onLog?: (line: string) => void; + deps?: Partial<FindCopyDeps>; + startFetch: (items: FetchWindowsItem[]) => Promise<T>; +}): Promise<FindCopyResult & { fetch?: T }> { + const found = await findCopies(opts); + if (opts.dryRun || found.items.length === 0) return found; + return { ...found, fetch: await opts.startFetch(found.items) }; +} diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts @@ -194,6 +194,15 @@ export class ArchiveOrgClient { ); } + // A body as text, through the same chain, gap and back-off (the Wayback + // CDX API answers an empty body as often as `[]`: lib/waybackClient.ts). + getText(url: string, accept: string, signal?: AbortSignal): Promise<string> { + return this.serial(async () => { + const res = await this.getOnce(url, accept, signal); + return res.text(); + }); + } + getJson(url: string, signal?: AbortSignal): Promise<unknown> { return this.serial(async () => { const res = await this.getOnce(url, "application/json", signal); diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts @@ -156,8 +156,24 @@ export type ClipProvenance = { // a window cut from the video's saved container (release 21 D2, // lib/savedVideoWindow-server.ts). Absent on every fetched window. source?: ClipWindowSource; + // WHICH COPY a window of a gone recording was fetched from (release 29 E2, + // controller/findCopy.ts): a Wayback Machine capture of its page, or an + // archive.org mirror's file — and its URL. Absent when the window came from + // the recording's own page. + copy?: ClipCopy; }; +export const CLIP_COPY_SOURCES = ["wayback", "archive.org"] as const; +export type ClipCopy = { from: (typeof CLIP_COPY_SOURCES)[number]; url: string }; + +export function coerceClipCopy(v: unknown): ClipCopy | undefined { + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + const r = v as Record<string, unknown>; + if (!(CLIP_COPY_SOURCES as readonly unknown[]).includes(r.from)) return undefined; + if (typeof r.url !== "string" || !/^https?:\/\//.test(r.url)) return undefined; + return { from: r.from as ClipCopy["from"], url: r.url }; +} + export const CLIP_WINDOW_SOURCES = ["saved-video"] as const; export type ClipWindowSource = (typeof CLIP_WINDOW_SOURCES)[number]; @@ -198,6 +214,8 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null { if ((CLIP_WINDOW_SOURCES as readonly unknown[]).includes(r.source)) { out.source = r.source as ClipWindowSource; } + const copy = coerceClipCopy(r.copy); + if (copy) out.copy = copy; return out; } diff --git a/common/lib/report/draft/refresh/delta.ts b/common/lib/report/draft/refresh/delta.ts @@ -21,6 +21,7 @@ import { enumerateOf, type EnumeratedRow } from "../tasks/trace"; import type { CorpusToolsLike } from "../tasks/types"; import { queryKey } from "./basis"; import type { CitedQuote, MatchedRow, QuoteRecheck, RefreshBasis, RefreshDelta, RefreshQuery } from "./types"; +import { goneState } from "../../../sourceGone"; export type CandidateScope = { channels: string[]; from?: string; to?: string }; @@ -191,8 +192,6 @@ export type QuoteReaders = { postTextOf?: (channel: string, id: string) => Promise<string | null>; }; -// The states a recording is "gone" in, for the delta's `deleted`. -const GONE_STATES = new Set(["deleted", "private"]); const isEn = (name: string) => /(^|[./])en\.vtt$/.test(name) || /\.en\.vtt$/.test(name); const isEnOrig = (name: string) => /en-orig/.test(name); @@ -227,7 +226,8 @@ export async function recheckQuotes(cited: readonly CitedQuote[], readers: Quote out.push({ ...base, status: "missing", message: rec ? `${key} has no transcript now` : `${key} is not in the archive now` }); continue; } - const state = rec.state && GONE_STATES.has(rec.state) ? rec.state : undefined; + // A recording "gone" from its platform: the one reading (lib/sourceGone.ts). + const state = goneState(rec.state) ?? undefined; const t = c.start ?? 0; const cite = { t, end: c.end ?? t }; // The primary first, then every other track: the words on any of them stand. diff --git a/common/lib/report/views.ts b/common/lib/report/views.ts @@ -64,6 +64,7 @@ import type { Claim, Report, ReportKind, ReportSlidesSpec, SlideSpec } from "./s import { reportCitationNumbers } from "./uses"; import { SITE_REPORTS_BASE, type ReportBase } from "./routes"; import { resolveVerdicts, VERDICTS, type Verdict, type VerdictStyle } from "./verdicts"; +import type { GoneState } from "../sourceGone"; export const REPORT_VIEWS_VERSION = 1; @@ -237,6 +238,10 @@ export type SpanCitationView = CitationViewCommon & { record: RecordView; // A still for the card: a site-root path or an http(s) URL. poster?: string; + // The recording is gone from its platform and no copy of the moment is + // published: the moment is its words only, said in plain words + // (SOURCE_GONE_LABELS, lib/sourceGone.ts). Release 29 E2. + sourceGone?: GoneState; }; export type PostCitationView = CitationViewCommon & { @@ -249,6 +254,8 @@ export type PostCitationView = CitationViewCommon & { // The captured screenshot of the post: a site-root path. shot?: string; thread?: boolean; + // The post is deleted and was never captured: its words only. + sourceGone?: GoneState; }; // A sentence of a document. The document itself (its byline and its archive @@ -460,6 +467,9 @@ export type MomentPageView = { cues?: CueLineView[]; // A post. post?: MomentPostView; + // The source is gone and no media of the moment is published (a span with + // no clip, a post with no shot): the page says so in plain words. + sourceGone?: GoneState; citedIn: CitedInView[]; }; @@ -477,6 +487,8 @@ export type ReportViewResolver = { record: (c: SpanCitation | PostCitation) => RecordView; poster?: (c: SpanCitation) => string | undefined; post?: (c: PostCitation) => { author?: string; text?: string; shot?: string } | undefined; + // A cited moment whose source is gone and whose media is not published. + sourceGone?: (c: SpanCitation | PostCitation) => GoneState | undefined; downloads?: ReportDownloads; history?: ReportHistoryRef; // The report's feeds (absolute URLs), carried only by a report with entries. @@ -539,6 +551,7 @@ export function buildReportPageView(report: Report, resolve: ReportViewResolver) end: Number(formatMomentSeconds(c.end)), record: resolve.record(c), poster: resolve.poster?.(c), + sourceGone: resolve.sourceGone?.(c), }); break; } @@ -556,6 +569,7 @@ export function buildReportPageView(report: Report, resolve: ReportViewResolver) text: post?.text, shot: post?.shot, thread: c.thread, + sourceGone: resolve.sourceGone?.(c), }); break; } diff --git a/common/lib/sourceGone-server.ts b/common/lib/sourceGone-server.ts @@ -0,0 +1,33 @@ +// The disk half of the gone reading (./sourceGone.ts): a recording's video +// directory, a post's availability sidecar. +// +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import { stateFromAvailability } from "./availability"; +import { resolveEffectiveAvailability } from "./availability-server"; +import { readPostAvailability } from "./posts-server"; +import { resolveVideoDir } from "./videoDir-server.mjs"; +import { goneState, type GoneState } from "./sourceGone"; + +// A recording's video directory → its gone state, or null (live, or never +// resolved: a missing or unreadable availability is NOT gone). +export async function sourceGoneState(videoDir: string): Promise<GoneState | null> { + const a = await resolveEffectiveAvailability(videoDir).catch(() => null); + return goneState(stateFromAvailability(a)); +} + +// The same by channel and record id (the record's directory resolved as every +// reader resolves it). +export async function recordGoneState(channelsDir: string, slug: string, id: string): Promise<GoneState | null> { + const dir = await resolveVideoDir(channelsDir, slug, id).catch(() => null); + return dir ? sourceGoneState(dir) : null; +} + +// A post is gone when the channel's posts-availability.json says `deleted` +// (a deleted-post sweep or a capture saw it so). Anything else — available, +// an unreachable account, an error, never checked — is not. +export async function postGoneState(channelsDir: string, slug: string, id: string): Promise<"deleted" | null> { + const map = await readPostAvailability(path.join(channelsDir, slug)).catch(() => ({}) as Record<string, { availability: string }>); + return map[id]?.availability === "deleted" ? "deleted" : null; +} diff --git a/common/lib/sourceGone.test.ts b/common/lib/sourceGone.test.ts @@ -0,0 +1,62 @@ +// The one gone reading (release 29 E2): deleted or private is gone; members- +// only, an error probe, an unlisted video and no availability at all are not. +// A post is gone when posts-availability.json says deleted. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/sourceGone.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { goneState, GONE_STATES, SOURCE_GONE_LABELS } from "./sourceGone"; +import { postGoneState, recordGoneState, sourceGoneState } from "./sourceGone-server"; + +test("goneState: deleted and private, nothing else", () => { + assert.deepEqual([...GONE_STATES], ["deleted", "private"]); + assert.equal(goneState("deleted"), "deleted"); + assert.equal(goneState("private"), "private"); + for (const s of ["available", "members_only", "unlisted", "maybe_missing", "error", "", null, undefined]) { + assert.equal(goneState(s), null, String(s)); + } + assert.equal(SOURCE_GONE_LABELS.deleted, "Source deleted"); +}); + +test("sourceGoneState reads the video's availability as refresh does; recordGoneState by channel and id; postGoneState", async () => { + const channels = await mkdtemp(path.join(os.tmpdir(), "source-gone-")); + try { + const dir = path.join(channels, "demo", "data", "v1"); + await mkdir(dir, { recursive: true }); + assert.equal(await sourceGoneState(dir), null, "never checked: not gone"); + const write = (availability: string) => + writeFile(path.join(dir, "availability.json"), JSON.stringify({ checkedAt: "2026-10-01T00:00:00.000Z", availability })); + for (const [a, want] of [ + ["deleted", "deleted"], + ["private", "private"], + ["members_only", null], + ["needs_auth", null], + ["error", null], + ["unlisted", null], + ["public", null], + ] as const) { + await write(a); + assert.equal(await sourceGoneState(dir), want, a); + } + await write("deleted"); + assert.equal(await recordGoneState(channels, "demo", "v1"), "deleted"); + assert.equal(await recordGoneState(channels, "demo", "nope"), null); + + assert.equal(await postGoneState(channels, "demo", "p1"), null, "no sidecar"); + await writeFile( + path.join(channels, "demo", "posts-availability.json"), + JSON.stringify({ + p1: { availability: "deleted", checkedAt: "2026-10-01T00:00:00.000Z" }, + p2: { availability: "account_unavailable", checkedAt: "2026-10-01T00:00:00.000Z" }, + }), + ); + assert.equal(await postGoneState(channels, "demo", "p1"), "deleted"); + assert.equal(await postGoneState(channels, "demo", "p2"), null, "an unreachable account is not a deleted post"); + } finally { + await rm(channels, { recursive: true, force: true }); + } +}); diff --git a/common/lib/sourceGone.ts b/common/lib/sourceGone.ts @@ -0,0 +1,31 @@ +// IS THIS SOURCE GONE? — the one reading (release 29 E2). +// +// A recording is gone from its platform when its effective availability +// (availability-server.ts resolveEffectiveAvailability: the explicit check or +// the last download's outcome, whichever is newer) reads, as a viewer state +// (availability.ts stateFromAvailability), `deleted` or `private`. Members-only +// is not gone: a member's cookies fetch it. An `error` probe is not gone: it +// never saw the video. +// +// The reading R4's refresh made first (draft/refresh/delta.ts), shared by every +// caller since: refresh's delta, compose (a cited moment of a gone source with +// no media is a text-only moment, `sourceGone`), the evidence windows a site +// still needs (reportMedia.ts missingEvidenceWindows, "unfetchable: gone"), +// fetch-windows' door and find-copy. A post is gone when posts-availability.json +// says `deleted` (sourceGone-server.ts postGoneState). +// +// Pure: client-safe, no node: imports. + +export const GONE_STATES = ["deleted", "private"] as const; +export type GoneState = (typeof GONE_STATES)[number]; + +// A viewer state (or anything) as a gone state, or null when it is not one. +export function goneState(state: string | null | undefined): GoneState | null { + return state === "deleted" || state === "private" ? state : null; +} + +// What a reader is told about a gone source: plain words. +export const SOURCE_GONE_LABELS: Readonly<Record<GoneState, string>> = Object.freeze({ + deleted: "Source deleted", + private: "Source made private", +}); diff --git a/common/lib/waybackClient.test.ts b/common/lib/waybackClient.test.ts @@ -0,0 +1,80 @@ +// The Wayback CDX client (release 29 E2), over the fake Wayback on loopback +// (common/testing/web/fakeWayback.mjs) through archive.org's polite client: +// the JSON answer and its empty forms, the 200 filter, a 429 waited out. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackClient.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { startFakeWayback } from "../testing/web/fakeWayback.mjs"; +import { parseCdxJson, waybackCdxUrl, WaybackClient, waybackReplayUrl } from "./waybackClient"; +import { ArchiveOrgRequestError } from "./archiveOrgClient"; + +const BREAD = "https://video.example/watch?v=bread-day-01"; +const GONE = "https://video.example/watch?v=gone-video-05"; + +test("parseCdxJson: the header names the columns; [] and an empty body are none; anything else is an error", () => { + const rows = parseCdxJson( + JSON.stringify([ + ["urlkey", "timestamp", "original", "mimetype", "statuscode", "digest", "length"], + ["example,video)/watch?v=x", "20260106120000", "https://video.example/watch?v=x", "text/html", "200", "D", "1"], + ["example,video)/watch?v=x", "not-a-time", "https://video.example/watch?v=x", "text/html", "200", "D", "1"], + ]), + ); + assert.deepEqual(rows, [ + { + timestamp: "20260106120000", + original: "https://video.example/watch?v=x", + status: "200", + mimetype: "text/html", + replayUrl: "https://web.archive.org/web/20260106120000/https://video.example/watch?v=x", + }, + ]); + assert.deepEqual(parseCdxJson("[]"), []); + assert.deepEqual(parseCdxJson(""), []); + assert.deepEqual(parseCdxJson('[["urlkey","timestamp","original"]]'), []); + assert.throws(() => parseCdxJson("<html>busy</html>"), /did not answer JSON/); + assert.throws(() => parseCdxJson('{"a":1}'), /not a list/); + assert.equal(waybackReplayUrl("20260101000000", "https://a.example/x"), "https://web.archive.org/web/20260101000000/https://a.example/x"); + assert.equal( + waybackCdxUrl("https://a.example/x?v=1", { okOnly: true, limit: 5 }), + "https://web.archive.org/cdx/search/cdx?url=https%3A%2F%2Fa.example%2Fx%3Fv%3D1&output=json&filter=statuscode%3A200&limit=5", + ); +}); + +test("captures: every one oldest first, only the 200s, none for an uncaptured page", async () => { + const wb = await startFakeWayback(); + try { + const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + assert.deepEqual((await c.captures(BREAD)).map((x) => [x.timestamp, x.status]), [ + ["20260106120000", "200"], + ["20260301080000", "302"], + ]); + assert.deepEqual((await c.captures(BREAD, { okOnly: true })).map((x) => x.timestamp), ["20260106120000"]); + const gone = await c.captures(GONE, { okOnly: true }); + assert.equal(gone[0]!.replayUrl, `https://web.archive.org/web/20260125093000/${GONE}`); + assert.deepEqual(await c.captures("https://video.example/watch?v=never"), []); + assert.equal(c.requests, 4); + } finally { + await wb.close(); + } +}); + +test("a 429 is waited out (Retry-After) and asked again; one that persists stops with rateLimited", async () => { + const wb = await startFakeWayback({ busyTimes: 1 }); + try { + const waits: number[] = []; + const c = new WaybackClient({ fetch: wb.fetch, sleep: async (ms) => void waits.push(ms) }, { minGapMs: 0 }); + assert.equal((await c.captures(GONE)).length, 1); + assert.deepEqual(waits, [1_000]); + } finally { + await wb.close(); + } + const busy = await startFakeWayback({ busyTimes: 10 }); + try { + const c = new WaybackClient({ fetch: busy.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 3 }); + await assert.rejects(c.captures(GONE), (e: unknown) => e instanceof ArchiveOrgRequestError && e.rateLimited); + } finally { + await busy.close(); + } +}); diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts @@ -0,0 +1,118 @@ +// THE WAYBACK MACHINE'S CDX API (release 29 E2): which captures web.archive.org +// holds of a URL — the deleted-video fallback asks it for a gone recording's +// watch page (controller/findCopy.ts, `pnpm ops wayback-lookup`). +// +// web.archive.org is archive.org's, and is asked with archive.org's manners: +// the same polite client (lib/archiveOrgClient.ts) — one request at a time, a +// 2 s gap, the project's User-Agent, 429/503 waited out (Retry-After, else 5 s, +// 10 s, … capped) a few times and then stopped — as its own instance, so a +// Wayback lookup and an archive.org import each keep their own gap. +// +// A capture's replay URL is `https://web.archive.org/web/<timestamp>/<url>`: +// the page as captured, which is also what yt-dlp's Wayback extractor reads +// a YouTube watch page's video from. + +import { + ArchiveOrgClient, + ArchiveOrgRequestError, + type ArchiveOrgClientDeps, + type ArchiveOrgClientOpts, +} from "./archiveOrgClient"; + +export const WAYBACK_ORIGIN = "https://web.archive.org"; + +export type WaybackCapture = { + // YYYYMMDDhhmmss + timestamp: string; + // The URL as captured. + original: string; + // The HTTP status the capture recorded ("200", "302", "-" for a revisit). + status: string; + mimetype?: string; + // The capture's page on web.archive.org. + replayUrl: string; +}; + +export function waybackReplayUrl(timestamp: string, original: string): string { + return `${WAYBACK_ORIGIN}/web/${timestamp}/${original}`; +} + +export function waybackCdxUrl(url: string, o: { limit?: number; okOnly?: boolean } = {}): string { + const q = new URLSearchParams(); + q.set("url", url); + q.set("output", "json"); + if (o.okOnly) q.set("filter", "statuscode:200"); + if (o.limit) q.set("limit", String(o.limit)); + return `${WAYBACK_ORIGIN}/cdx/search/cdx?${q.toString()}`; +} + +// The CDX API's JSON answer: a header row naming the columns, then one row per +// capture. `[]`, an empty body or a header alone: no captures. Anything else +// that is not that shape is an error (the API changed, or answered a page). +export function parseCdxJson(body: string): WaybackCapture[] { + const text = body.trim(); + if (!text) return []; + let raw: unknown; + try { + raw = JSON.parse(text); + } catch { + throw new Error(`the CDX API did not answer JSON (${text.slice(0, 80)})`); + } + if (!Array.isArray(raw)) throw new Error("the CDX API's answer is not a list"); + if (raw.length === 0) return []; + const [header, ...rows] = raw as unknown[][]; + if (!Array.isArray(header)) throw new Error("the CDX API's answer has no header row"); + const col = (name: string) => header.indexOf(name); + const ts = col("timestamp"); + const orig = col("original"); + const st = col("statuscode"); + const mt = col("mimetype"); + if (ts < 0 || orig < 0) throw new Error("the CDX API's header names no timestamp or original"); + const out: WaybackCapture[] = []; + for (const row of rows) { + if (!Array.isArray(row)) continue; + const timestamp = String(row[ts] ?? ""); + const original = String(row[orig] ?? ""); + if (!/^\d{14}$/.test(timestamp) || !original) continue; + const mimetype = mt >= 0 && typeof row[mt] === "string" ? (row[mt] as string) : undefined; + out.push({ + timestamp, + original, + status: st >= 0 ? String(row[st] ?? "") : "", + ...(mimetype ? { mimetype } : {}), + replayUrl: waybackReplayUrl(timestamp, original), + }); + } + return out; +} + +export class WaybackClient { + private readonly http: ArchiveOrgClient; + + constructor(deps: ArchiveOrgClientDeps = {}, opts: ArchiveOrgClientOpts = {}) { + this.http = new ArchiveOrgClient(deps, opts); + } + + // Requests sent (each attempt), for tests and logs. + get requests(): number { + return this.http.requests; + } + + // The captures of `url`, oldest first: every capture, or (`okOnly`) only the + // ones that recorded a 200. Throws ArchiveOrgRequestError when the API kept + // refusing (`rateLimited`) or answered an error. + async captures( + url: string, + o: { limit?: number; okOnly?: boolean; signal?: AbortSignal } = {}, + ): Promise<WaybackCapture[]> { + const body = await this.http.getText(waybackCdxUrl(url, o), "application/json", o.signal); + try { + return parseCdxJson(body); + } catch (e) { + throw new ArchiveOrgRequestError(`${(e as Error).message} for ${url}`, null, false); + } + } +} + +// THE process's Wayback client: one chain, one gap. +export const waybackClient = new WaybackClient(); diff --git a/common/publish/composeReports.test.ts b/common/publish/composeReports.test.ts @@ -512,6 +512,55 @@ test("a citation without prepared media fails compose with the list, unless --al } }); +test("a gone source with no prepared media is its words only, marked sourceGone; a live one is still refused", async () => { + // The recording deleted on its platform (lib/sourceGone.ts reads + // availability.json), the post deleted in posts-availability.json; neither + // has prepared media. + const avail = path.join(paths.channelsDir, VIDEOS, "data", "abc123", "availability.json"); + const postsAvail = path.join(paths.channelsDir, SOCIAL, "posts-availability.json"); + writeJson(avail, { checkedAt: "2026-10-01T00:00:00.000Z", availability: "deleted" }); + writeJson(postsAvail, { "3kabc": { availability: "deleted", checkedAt: "2026-10-01T00:00:00.000Z" } }); + seedMedia("cited", [`${VIDEOS}/abc123/10.00-20.00`, `${SOCIAL}/3kabc`]); + try { + await compose("cited"); + const span = readJson<Record<string, unknown>>(pub("m", VIDEOS, "abc123", "10.00-20.00", "moment.json")); + assert.equal(span.sourceGone, "deleted"); + assert.equal(span.clip, undefined); + assert.ok(Array.isArray(span.cues) && (span.cues as unknown[]).length > 0, "its words are there"); + const post = readJson<Record<string, unknown> & { post: { shot?: string } }>(pub("m", SOCIAL, "3kabc", "moment.json")); + assert.equal(post.sourceGone, "deleted"); + assert.equal(post.post.shot, undefined); + const view = readJson<{ citations: Record<string, { sourceGone?: string }> }>(pub("pages", REPORT, "page.json")); + assert.equal(view.citations.c01.sourceGone, "deleted"); + assert.equal(view.citations.p01.sourceGone, "deleted"); + // A moment of a live recording with media keeps its clip, unmarked. + assert.equal(view.citations.c02.sourceGone, undefined); + assert.ok(!existsSync(pub("media", "clips", VIDEOS, "abc123"))); + + // Made private reads as gone too; live again (no availability): refused. + writeJson(avail, { checkedAt: "2026-10-01T00:00:00.000Z", availability: "private" }); + await compose("cited"); + assert.equal(readJson<Record<string, unknown>>(pub("m", VIDEOS, "abc123", "10.00-20.00", "moment.json")).sourceGone, "private"); + rmSync(avail); + rmSync(postsAvail); + await assert.rejects(compose("cited"), (e: unknown) => { + assert.ok(e instanceof ComposeReportsError); + assert.deepEqual( + e.problems.map((p) => [p.kind, p.moment]), + [ + ["missing-media", `${VIDEOS}/abc123/10.00-20.00`], + ["missing-media", `${SOCIAL}/3kabc`], + ], + ); + return true; + }); + } finally { + rmSync(avail, { force: true }); + rmSync(postsAvail, { force: true }); + seedMedia("cited"); + } +}); + test("a report's video: copied beside its page and named in the view; a missing or oversize one fails compose", async () => { const dir = path.join(paths.sitesDir, "cited", "reports", REPORT); const file = path.join(dir, "report.json"); diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -150,6 +150,8 @@ import { publishReportHistory, readReportHistoryView, reportHistoryRef, storeHis import { hostCorpusLink, siteReportHost, type ReportHost } from "./reportHost"; import type { ReportHistoryRef, ReportHistoryView } from "../lib/report/revisions"; import { LEGACY_SITE_REPORTS_DIR, SITE_REPORTS_BASE, reportBaseDir, type ReportBase } from "../lib/report/routes"; +import { SOURCE_GONE_LABELS, type GoneState } from "../lib/sourceGone"; +import { postGoneState, recordGoneState } from "../lib/sourceGone-server"; // The public dir's entries this stage owns for a host serving its reports // under `base`: its reports, the moments, the cited media. Every compose @@ -264,6 +266,8 @@ export type ComposedReports = { moments: string[]; // Media problems let through by `allowMissingMedia`. allowed: ComposeReportsProblem[]; + // The moments published with their words only, their source gone. + sourceGone?: SourceGoneMoment[]; // The reports whose revision history was published. histories?: string[]; }; @@ -504,8 +508,13 @@ export type ResolvedSiteReports = { mediaOf: Map<string, ReportMediaEntry>; cacheDir: string; allowed: ComposeReportsProblem[]; + // The moments accepted with no media because their source is gone (a + // warning, never a problem): each shows its words only, marked. + sourceGone: SourceGoneMoment[]; }; +export type SourceGoneMoment = { moment: string; state: GoneState; citations: string[] }; + export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promise<ResolvedSiteReports> { const { site, ...rest } = opts; return resolveReports({ ...rest, host: siteReportHost(opts.paths, site) }); @@ -659,6 +668,8 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol const citedIn = buildCitedIn(reports); const momentInfo = new Map(citedMoments(reports).map((m) => [m.key, m])); const mediaOf = new Map<string, ReportMediaEntry>(); + // moment key → its source's gone state, for a moment accepted with no media. + const sourceGone = new Map<string, GoneState>(); for (const key of Object.keys(citedIn)) { const m = momentInfo.get(key); if (!m || refusedChannel.has(m.moment.channel)) continue; @@ -667,6 +678,18 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol const missing = (kind: ComposeReportsProblemKind, message: string) => problems.push({ kind, moment: key, message: `${message} (cited by ${[...new Set(citedBy)].join(", ")})` }); if (!entry) { + // A SOURCE GONE FROM ITS PLATFORM with no media prepared (release 29 E2): + // accepted as a text-only moment, marked — the recording deleted or made + // private (lib/sourceGone.ts), the post deleted in posts-availability.json. + // A live source with no media is still refused. + const gone = + m.kind === "post" + ? await postGoneState(paths.channelsDir, m.moment.channel, m.moment.id) + : await recordGoneState(paths.channelsDir, m.moment.channel, m.moment.id); + if (gone) { + sourceGone.set(key, gone); + continue; + } missing("missing-media", "no prepared media — run Prepare evidence media (archilyzer reports prepare)"); continue; } @@ -787,6 +810,10 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol const post = postsByChannel.get(c.channel)?.get(c.id); return post ? { author: postAuthor(post), text: post.text, shot: postShot(c) } : undefined; }, + sourceGone: (c) => { + const k = momentKeyOf(c); + return k ? sourceGone.get(k) : undefined; + }, downloads: opts.downloads?.(report.id), history: opts.history?.(report.id), feeds: opts.feeds?.(report.id), @@ -820,6 +847,7 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol ...(c.speaker ? { speaker: c.speaker } : {}), ...(c.date ? { date: c.date } : {}), ...(c.verification ? { verification: c.verification } : {}), + ...(sourceGone.has(key) ? { sourceGone: sourceGone.get(key)! } : {}), citedIn: citedInViews(entries, views, host.base), } as const; if (c.kind === "post") { @@ -868,7 +896,13 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol }); } moments.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)); - return { reports, views, index, moments, mediaOf, cacheDir, allowed }; + const gone = [...sourceGone].map(([moment, state]) => ({ + moment, + state, + citations: [...new Set(citedIn[moment].map((e) => `${e.reportId}#${e.citationId}`))], + })); + for (const g of gone) log(`[reports] warning: ${g.moment}: ${SOURCE_GONE_LABELS[g.state].toLowerCase()} — its words only (cited by ${g.citations.join(", ")})`); + return { reports, views, index, moments, mediaOf, cacheDir, allowed, sourceGone: gone }; } // ─── The stage ─── @@ -937,7 +971,7 @@ export async function composeHostReports(opts: ComposeHostReportsOptions): Promi if (historyProblems.length > 0) throw new ComposeReportsError(historyProblems, composedReportsNoun(host)); // A timeline's feeds link absolutely: a site with no public URL publishes none. const siteUrl = host.siteUrl; - const { reports, views, index, moments, mediaOf, cacheDir, allowed } = await resolveReports({ + const { reports, views, index, moments, mediaOf, cacheDir, allowed, sourceGone } = await resolveReports({ ...opts, history: (id) => histories.get(id)?.ref, feeds: siteUrl ? (id) => reportFeedUrls(siteUrl, id, base) : undefined, @@ -1009,9 +1043,16 @@ export async function composeHostReports(opts: ComposeHostReportsOptions): Promi } log( `[reports] ${reports.length} report(s), ${moments.length} moment page(s), ${copied} media file(s)` + - `${allowed.length ? `, ${allowed.length} without media` : ""}.`, + `${allowed.length ? `, ${allowed.length} without media` : ""}` + + `${sourceGone.length ? `, ${sourceGone.length} whose source is gone (words only)` : ""}.`, ); - return { reports: index.reports, moments: moments.map((m) => m.key), allowed, histories: [...histories.keys()] }; + return { + reports: index.reports, + moments: moments.map((m) => m.key), + allowed, + ...(sourceGone.length ? { sourceGone } : {}), + histories: [...histories.keys()], + }; } // A clip's published path: the moment's (lib/report/views.ts), `.m4a` for a diff --git a/common/publish/missingEvidenceWindows.test.ts b/common/publish/missingEvidenceWindows.test.ts @@ -124,6 +124,8 @@ test("on disk, to fetch, and what no window can fill", async () => { elsewhere: "not-in-site", }); assert.match(r.unfetchable.find((u) => u.id === "gone1")!.message, /deleted/); + // Release 29 E2: the one gone reading (lib/sourceGone.ts) names which. + assert.equal(r.unfetchable.find((u) => u.id === "gone1")!.gone, "deleted"); // The refusal names both keys that would let the site cite the channel. assert.match(r.unfetchable.find((u) => u.id === "elsewhere")!.message, /`channels` nor its `citedChannels`/); }); diff --git a/common/publish/reportMedia.test.ts b/common/publish/reportMedia.test.ts @@ -281,3 +281,39 @@ test("a cited-only channel's moment is prepared; a channel in neither key is not ); assert.match(index.problems[0].message, /"elsewhere" is in neither this site's `channels` nor its `citedChannels`/); }); + +// RELEASE 29 E2: a gone source with no media is a WARNING (`source-gone`), never +// a problem — compose shows its words only. A live one with no media is still +// a problem. +test("a gone recording or a deleted, never-captured post with no media is a warning, not a problem", async () => { + const GSITE = "gone-site"; + writeJson(path.join(videoDir(CH, "gone2"), "availability.json"), { checkedAt: "2026-10-01T00:00:00.000Z", availability: "deleted" }); + writeJson(path.join(paths.channelsDir, X, "posts-availability.json"), { + "333": { availability: "deleted", checkedAt: "2026-10-01T00:00:00.000Z" }, + }); + writeJson(path.join(paths.sitesDir, GSITE, "site.json"), { title: "Gone", channels: [{ slug: CH }, { slug: X }], reports: ["g1"] }); + writeJson( + path.join(paths.sitesDir, GSITE, "reports", "g1", "report.json"), + report("g1", { + g01: { kind: "video", channel: CH, id: "gone2", start: 1, end: 2, quote: "gone" }, + g02: { kind: "post", channel: X, id: "333", quote: "deleted" }, + g03: { kind: "video", channel: CH, id: "missing2", start: 1, end: 2, quote: "live, no media" }, + }), + ); + const lines: string[] = []; + const index = await prepareReportMedia({ siteId: GSITE, settings: PUBLIC, onLog: (l) => lines.push(l) }); + assert.deepEqual( + (index.warnings ?? []).map((w) => [w.kind, w.moment, w.citations]), + [ + ["source-gone", `${CH}/gone2/1.00-2.00`, ["g1#g01"]], + ["source-gone", `${X}/333`, ["g1#g02"]], + ], + ); + assert.match(index.warnings![0].message, /deleted.*words only.*Source deleted/); + assert.deepEqual( + index.problems.map((p) => [p.kind, p.moment]), + [["missing-media", `${CH}/missing2/1.00-2.00`]], + ); + assert.ok(lines.some((l) => l.startsWith(` ! ${CH}/gone2/`))); + assert.ok(lines.some((l) => /1 problem\(s\), 2 warning\(s\)/.test(l))); +}); diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts @@ -65,9 +65,9 @@ import { momentKey, momentOf, momentProblem, type Moment } from "../lib/citation import type { CitationPad } from "../lib/citations/schema"; import { parseReport } from "../lib/report/validate"; import { isReportId, type Report } from "../lib/report/schema"; -import { isPermanentlyGone } from "../lib/availability"; -import { loadAvailability } from "../lib/availability-server"; import { resolveVideoDir } from "../lib/videoDir-server.mjs"; +import { SOURCE_GONE_LABELS, type GoneState } from "../lib/sourceGone"; +import { postGoneState, sourceGoneState } from "../lib/sourceGone-server"; import { MAX_CLIP_WINDOW_SECONDS } from "../lib/clipWindow"; import { citedEvidenceSpan, @@ -159,7 +159,11 @@ export type ReportMediaProblemKind = | "missing-media" | "unreachable" | "too-big" - | "cut-failed"; + | "cut-failed" + // A WARNING, never a problem (release 29 E2): a cited moment whose source is + // gone (lib/sourceGone.ts) and whose media is not on disk. Compose takes it + // as a text-only moment marked "source deleted". + | "source-gone"; export type ReportMediaProblem = { kind: ReportMediaProblemKind; @@ -180,6 +184,9 @@ export type ReportMediaIndex = { preparedAt: string; moments: Record<string, ReportMediaEntry>; problems: ReportMediaProblem[]; + // What does not fail the run: a gone source's moment with no media + // (`source-gone`). Absent when there is none. + warnings?: ReportMediaProblem[]; }; // One cited moment and everything that cites it. @@ -292,6 +299,11 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi problems.push({ kind, moment: m.key, citations: m.citedBy, message }); log(` ✗ ${m.key}: ${message}`); }; + const warnings: ReportMediaProblem[] = []; + const warnGone = (m: CitedMoment, message: string) => { + warnings.push({ kind: "source-gone", moment: m.key, citations: m.citedBy, message }); + log(` ! ${m.key}: ${message}`); + }; const posts: CitedMoment[] = []; for (const m of moments) { @@ -339,6 +351,11 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi fail(m, "unreachable", `${r.message}; the channel's media is ${where.status}${where.detail ? ` (${where.detail})` : ""}`); continue; } + const gone = await sourceGoneState(await resolveVideoDir(paths.channelsDir, slug, m.moment.id)); + if (gone) { + warnGone(m, `the source says the video is ${gone} and no copy is on disk: the moment shows its words only, marked "${SOURCE_GONE_LABELS[gone]}" (pnpm ops find-copy looks for a copy)`); + continue; + } fail(m, "missing-media", `${r.message} — fetch the window or persist the video in the editor`); continue; } @@ -359,7 +376,12 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi } for (const miss of copiedPosts.missing) { const m = postMoment.get(`${miss.channel}/${miss.id}`); - if (m) fail(m, "missing-media", miss.message); + if (!m) continue; + if (await postGoneState(paths.channelsDir, miss.channel, miss.id)) { + warnGone(m, `the post is deleted and was never captured: the moment shows its words only, marked "${SOURCE_GONE_LABELS.deleted}"`); + continue; + } + fail(m, "missing-media", miss.message); } // The cache holds what the manifest names: a clip no moment names goes. @@ -372,6 +394,7 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi preparedAt: (opts.now?.() ?? new Date()).toISOString(), moments: Object.fromEntries(Object.keys(entries).sort().map((k) => [k, entries[k]])), problems, + ...(warnings.length > 0 ? { warnings } : {}), }; await writeJsonAtomic(storeMediaIndexFile(host), index, { mkdir: true }); const bytes = Object.values(entries).reduce( @@ -380,7 +403,9 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi ); log( `${Object.keys(entries).length} of ${moments.length} moment(s) prepared (${mib(bytes)}); ` + - `${problems.length} problem(s).`, + `${problems.length} problem(s)` + + (warnings.length ? `, ${warnings.length} warning(s) (a gone source's moment shows its words only)` : "") + + ".", ); return index; } @@ -442,7 +467,9 @@ export async function readStoreMediaIndex(store: Pick<ReportStore, "stagingDir"> // not-in-site the channel is not one of the site's (prepare's not-in-site) // unreachable the channel's media is on a drive that is not answering — // not missing, and a fetch would write beside the wrong thing -// gone availability.json says deleted, private or members-only +// gone the source says the video is deleted or private (the one +// reading, lib/sourceGone.ts; `gone` names which) — no window +// can be fetched from it; find-copy looks for a copy // audio-only a feed record: its media is the episode's audio, which a // download fetches; a window selector has no picture to pick // too-long longer than one window may be — persist the video instead @@ -468,6 +495,8 @@ export type UnfetchableReason = "not-in-site" | "unreachable" | "gone" | "audio- export type UnfetchableEvidenceWindow = EvidenceWindow & { why: UnfetchableReason; + // A `gone` window: what the source says (lib/sourceGone.ts). + gone?: GoneState; message: string; }; @@ -545,9 +574,9 @@ export async function missingEvidenceWindows(paths: Paths, siteOrHost: string | unfetchable("unreachable", `the channel's media is ${where.status}${where.detail ? ` (${where.detail})` : ""}`); continue; } - const availability = (await loadAvailability(await resolveVideoDir(paths.channelsDir, slug, id)))?.availability; - if (isPermanentlyGone(availability)) { - unfetchable("gone", `the source says the video is ${availability}`); + const gone = await sourceGoneState(await resolveVideoDir(paths.channelsDir, slug, id)); + if (gone) { + out.unfetchable.push({ ...window, why: "gone", gone, message: `the source says the video is ${gone}` }); continue; } if (audioOnly) { diff --git a/common/testing/archiveOrg/fakeArchiveOrg.mjs b/common/testing/archiveOrg/fakeArchiveOrg.mjs @@ -13,7 +13,12 @@ // Routes: // GET /advancedsearch.php?q=…&rows=N items whose identifier, title or // subject contains every word of q -// (`*` matches all), identifier order +// (`*` matches all), identifier order; +// a q of `field:value` clauses joined by +// OR (release 29: a YouTube id search) +// matches an item whose metadata field +// contains any clause's value (quotes, +// parentheses, `*` and `\` dropped) // GET /metadata/<id> the item, or {} (archive.org's answer // for an unknown id) // opts.busyTimes the first N requests answer 429 @@ -50,6 +55,26 @@ export const ITEMS = [ }, files: [{ name: "members.mp4", source: "original", format: "MPEG4", size: "5000" }], }, + // A mirror of a recording deleted on its platform (release 29): the corpus's + // GONE_RECORD, uploaded by a mirroring tool with the id in its identifier, + // its description and its original URL. Not "bakery": the search tests + // count those. + { + metadata: { + identifier: "youtube-gone-video-05", + title: "The old oven review", + date: "2026-01-20", + mediatype: "movies", + collection: ["opensource_movies"], + description: "Mirror of https://video.example/watch?v=gone-video-05", + originalurl: "https://video.example/watch?v=gone-video-05", + }, + files: [ + { name: "The old oven review-gone-video-05.webm", source: "original", format: "WebM", size: "3000000", length: "20.0" }, + { name: "The old oven review-gone-video-05.mp4", source: "derivative", format: "h.264", original: "The old oven review-gone-video-05.webm", size: "2000000" }, + { name: "The old oven review-gone-video-05.info.json", source: "original", format: "JSON", size: "1500" }, + ], + }, { metadata: { identifier: "synth-radio-tape-01", @@ -88,8 +113,18 @@ export async function startFakeArchiveOrg(opts = {}) { const q = u.searchParams.get("q") ?? ""; const rows = Number(u.searchParams.get("rows") ?? 50); const want = q.trim() === "*" ? [] : words(q); + const clauses = q.split(/\s+OR\s+/).map((c) => c.trim().replace(/^\(+|\)+$/g, "")); + const fielded = clauses.length > 0 && clauses.every((c) => /^[a-z_]+:/i.test(c)); + const fieldMatch = (it) => + clauses.some((c) => { + const i = c.indexOf(":"); + const field = c.slice(0, i); + const value = c.slice(i + 1).replace(/["()*\\]/g, "").trim().toLowerCase(); + return value !== "" && flat(it.metadata[field]).toLowerCase().includes(value); + }); const hits = items .filter((it) => { + if (fielded) return fieldMatch(it); const hay = new Set(words(`${it.metadata.identifier} ${flat(it.metadata.title)} ${flat(it.metadata.subject)}`)); return want.every((w) => hay.has(w)); }) diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts @@ -34,6 +34,7 @@ import { clipsDirFor, clipWindowFile, clipWindowName, + type ClipCopy, type ClipProvenance, } from "../lib/clipWindow"; import { @@ -92,6 +93,8 @@ export type FetchWindowProvenance = { reason?: string; pad?: number; requestedAt?: string; + // The copy of a gone recording the URL is (release 29 E2, find-copy). + copy?: ClipCopy; }; export type FetchWindowOpts = { @@ -353,6 +356,7 @@ export async function fetchWindowManaged( ...(typeof opts.provenance.pad === "number" ? { pad: opts.provenance.pad } : {}), + ...(opts.provenance.copy ? { copy: opts.provenance.copy } : {}), bytes: st.size, fetchedAt: new Date().toISOString(), ytdlp: { args },