commit f16629a8309f0a7a94f67ff34aa1daeb67ce6c4d
parent cee3a6ae41aad64b16296e410ac90953d424b67c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 15 Oct 2026 07:44:31 -0400
common: find-copy lives in publish/ (it reads the reports' evidence windows and a report host; controller/ may not import publish/ — architecture.test.ts), its imports and references moved with it
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 604 insertions(+), 604 deletions(-)
diff --git a/common/controller/findCopy.test.ts b/common/controller/findCopy.test.ts
@@ -1,209 +0,0 @@
-// 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
@@ -1,387 +0,0 @@
-// 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/clipWindow.ts b/common/lib/clipWindow.ts
@@ -157,7 +157,7 @@ export type ClipProvenance = {
// 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
+ // publish/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;
diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts
@@ -1,6 +1,6 @@
// 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`).
+// watch page (publish/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
diff --git a/common/publish/findCopy.test.ts b/common/publish/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 publish/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 "./reportMedia";
+import type { ReportHost } from "./reportHost";
+import type { Paths } from "../lib/paths";
+import type { FetchWindowsItem } from "../controller/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/publish/findCopy.ts b/common/publish/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 "../controller/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 "../controller/channels";
+import { findVideoSourceUrl } from "../controller/undownloadedVideos";
+import { missingEvidenceWindows, type EvidenceWindow, type MissingEvidenceWindows } from "./reportMedia";
+import type { ReportHost } from "./reportHost";
+import type { FetchWindowsItem } from "../controller/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/editor/app/api/ops/archive-search/route.ts b/editor/app/api/ops/archive-search/route.ts
@@ -4,7 +4,7 @@ import {
ARCHIVE_ORG_SEARCH_MAX_ROWS,
searchArchiveOrgItems,
} from "yt-dlp-transcript-common/controller/archiveOrgImport";
-import { findArchiveOrgMirrors } from "yt-dlp-transcript-common/controller/findCopy";
+import { findArchiveOrgMirrors } from "yt-dlp-transcript-common/publish/findCopy";
import { OpsInputError, ops, opsFail, optPositiveInt, optString, reqString } from "../_lib";
export const dynamic = "force-dynamic";
@@ -22,7 +22,7 @@ export const dynamic = "force-dynamic";
//
// `youtubeId` (release 29 E2) looks for MIRRORS of one YouTube upload: items
// naming the id in their identifier, title, description or original URL
-// (controller/findCopy.ts), each read for its files (one request each), and
+// (publish/findCopy.ts), each read for its files (one request each), and
// answers each mirror's direct video file URL
// (`https://archive.org/download/<identifier>/<file>`, an original preferred).
// An item that does not name the id, is restricted, or holds no file the
diff --git a/editor/app/api/ops/find-copy/route.ts b/editor/app/api/ops/find-copy/route.ts
@@ -10,7 +10,7 @@ export const dynamic = "force-dynamic";
// outcome: fetch | text-only | error }], items, stopped?, jobId? }
//
// A COPY OF EVERY GONE RECORDING THE REPORTS CITE (release 29 E2,
-// controller/findCopy.ts): of one article (`article`), every published
+// publish/findCopy.ts): of one article (`article`), every published
// article (`articles`), or a site's reports (`siteId`), the cited windows
// whose recording is deleted or private ("unfetchable: gone"). Per recording,
// one at a time: the Wayback Machine (a capture of its page that recorded a
diff --git a/editor/app/api/ops/wayback-lookup/route.ts b/editor/app/api/ops/wayback-lookup/route.ts
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";
import { ArchiveOrgRequestError } from "yt-dlp-transcript-common/lib/archiveOrgClient";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
-import { recordWebpageUrl, waybackLookup } from "yt-dlp-transcript-common/controller/findCopy";
+import { recordWebpageUrl, waybackLookup } from "yt-dlp-transcript-common/publish/findCopy";
import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqSlug, reqVideoId } from "../_lib";
export const dynamic = "force-dynamic";
diff --git a/editor/app/channels/[slug]/videos/findCopyAction.ts b/editor/app/channels/[slug]/videos/findCopyAction.ts
@@ -5,11 +5,11 @@ import { getSite, isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/li
import { clipWindowQueueKey } from "yt-dlp-transcript-common/lib/queueKeys";
import { platformQueueKey } from "yt-dlp-transcript-common/lib/platform";
import { articlesWorkHost, siteReportHost, type ReportHost } from "yt-dlp-transcript-common/publish/reportHost";
-import { runFindCopy, type FindCopyResult } from "yt-dlp-transcript-common/controller/findCopy";
+import { runFindCopy, type FindCopyResult } from "yt-dlp-transcript-common/publish/findCopy";
import { fetchWindowsJobAction } from "./fetchWindowsAction";
// FIND A COPY OF THE GONE RECORDINGS A REPORT CITES, and fetch their windows
-// from it (release 29 E2; the lookups are controller/findCopy.ts). The windows
+// from it (release 29 E2; the lookups are publish/findCopy.ts). The windows
// of every copy found go to ONE fetch-windows job on the archive.org clip
// queue — Wayback captures and archive.org files are both archive.org's — so
// they are fetched one at a time, paced, one stream.