// find-copy (release 29 E2, and its review) over the fake Wayback and the fake // archive.org on loopback, through the real polite clients: per gone YouTube // recording, the Wayback Machine when it holds the VIDEO (yt-dlp's videoinfo // check, not a page capture), else an archive.org mirror OF the upload (its // identifier, a file name or its original URL names the id) whose file has the // record's length; a copy that failed before is not picked again; a record // whose page is not YouTube is not looked for; the fetch-windows items carry // the copy's URL and the copy; a dry run and a cancelled run start 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 { startFakeArchiveOrg, type FakeArchiveOrgItem } from "../testing/archiveOrg/fakeArchiveOrg.mjs"; import { ArchiveOrgClient } from "../lib/archiveOrgClient"; import { WaybackClient } from "../lib/waybackClient"; import type { CopyAttempt, FailedCopy } from "../lib/copyAttempts-server"; 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, mirrorNamesId, pickMirrorFile, runFindCopy, WAYBACK_PAGE_ONLY, youtubeIdOf, youtubeIdQuery, type RecordFacts, } from "./findCopy"; const CH = "synth-kitchen"; const WB = "waybackVid1"; // its video in the Wayback Machine const IA = "mirroredV01"; // a mirror on archive.org const COMP = "compiledV01"; // only a compilation mentions it const NONE = "nothing0001"; // no copy anywhere const watch = (id: string) => `https://www.youtube.com/watch?v=${id}`; const mirror = (id: string, seconds: string, extra: Partial = {}): FakeArchiveOrgItem => ({ metadata: { identifier: `youtube-${id}`, title: `An upload ${id}`, mediatype: "movies", originalurl: watch(id), ...extra }, files: [ { name: `An upload-${id}.mkv`, source: "original", format: "Matroska", size: "4000", length: seconds }, { name: `An upload-${id}.mp4`, source: "original", format: "MPEG4", size: "3000", length: seconds }, ], }); // A compilation that cites COMP in its description and holds one video: not a mirror of it. const COMPILATION: FakeArchiveOrgItem = { metadata: { identifier: "best-moments-2026", title: "Best moments", mediatype: "movies", description: `Clips from https://www.youtube.com/watch?v=${COMP} and others` }, files: [{ name: "best-moments.mp4", source: "original", format: "MPEG4", size: "9000", length: "3600" }], }; const ITEMS = [mirror(IA, "600.0"), mirror(WB, "300.0"), COMPILATION]; 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(WB, 0, "a#c1"), gone(WB, 30, "a#c2"), gone(IA, 5, "a#c3"), gone(COMP, 5, "a#c4"), gone(NONE, 5, "a#c5"), gone("v5abcde", 5, "a#c6"), // a Rumble record { ...gone("elsewhere001", 1, "a#c7"), why: "not-in-site", gone: undefined }, ], }; const FACTS: Record = { [WB]: { webpageUrl: watch(WB), duration: 300, videoDir: `/x/${WB}` }, [IA]: { webpageUrl: watch(IA), duration: 598, videoDir: `/x/${IA}` }, [COMP]: { webpageUrl: watch(COMP), duration: 3600, videoDir: `/x/${COMP}` }, [NONE]: { webpageUrl: watch(NONE), duration: 100, videoDir: `/x/${NONE}` }, v5abcde: { webpageUrl: "https://rumble.com/v5abcde-a-stream.html", duration: 100, videoDir: "/x/v5abcde" }, }; async function fakes( o: { waybackBusy?: number; failed?: Record; need?: MissingEvidenceWindows; videos?: string[]; streams?: string[]; streamBusy?: number; items?: FakeArchiveOrgItem[] } = {}, ) { const wb = await startFakeWayback({ busyTimes: o.waybackBusy ?? 0, videos: o.videos ?? [WB], ...(o.streams ? { streams: o.streams } : {}), streamBusyTimes: o.streamBusy ?? 0, }); const ia = await startFakeArchiveOrg({ items: o.items ?? ITEMS }); const recorded: { dir: string; attempt: CopyAttempt }[] = []; const deps = { wayback: new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }), archive: new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 }), missing: async () => o.need ?? NEED, facts: async (_p: Paths, _slug: string, id: string) => FACTS[id]!, failedCopies: async (dir: string) => o.failed?.[dir] ?? [], recordAttempt: async (dir: string, attempt: CopyAttempt) => void recorded.push({ dir, attempt }), now: () => new Date("2026-10-17T00:00:00Z"), }; return { wb, ia, deps, recorded, 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: a YouTube page's id only — never a Rumble or Twitch record's own id", () => { assert.equal(youtubeIdOf("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), "dQw4w9WgXcQ"); assert.equal(youtubeIdOf("https://youtu.be/dQw4w9WgXcQ?t=4"), "dQw4w9WgXcQ"); assert.equal(youtubeIdOf("https://m.youtube.com/shorts/dQw4w9WgXcQ"), "dQw4w9WgXcQ"); assert.equal(youtubeIdOf("https://rumble.com/v5abcde-a-stream.html"), null); assert.equal(youtubeIdOf("https://www.twitch.tv/videos/12345678901"), null); assert.equal(youtubeIdOf("https://video.example/watch?v=dQw4w9WgXcQ"), null); assert.equal(youtubeIdOf(null), null); assert.match(youtubeIdQuery("dQw4w9WgXcQ"), /^identifier:\(youtube-dQw4w9WgXcQ\) OR originalurl:\(\*dQw4w9WgXcQ\*\)/); assert.throws(() => youtubeIdQuery("not-eleven"), /not a YouTube id/); }); test("a mirror is OF the upload by its identifier, a file name or its original URL — a description is not enough", () => { assert.equal(mirrorNamesId(mirror(IA, "600"), IA), "its identifier"); assert.equal(mirrorNamesId({ metadata: { identifier: "x" }, files: [{ name: `a-${IA}.mp4` }] }, IA), "a file's name"); assert.equal(mirrorNamesId({ metadata: { identifier: "x", originalurl: watch(IA) } as never, files: [] }, IA), "its original URL"); assert.equal(mirrorNamesId(COMPILATION, COMP), null); }); test("pickMirrorFile: a file naming the id, an original before a derivative, mp4 before webm; the record's length must agree", () => { const f = (name: string, source: string, length?: string, original?: string) => ({ name, source, ...(length ? { length } : {}), ...(original ? { original } : {}) }); assert.deepEqual(pickMirrorFile({ files: [f("x-ID123456789.webm", "original", "60"), f("x-ID123456789.mp4", "derivative")] }, "ID123456789"), { file: "x-ID123456789.webm", source: "original", seconds: 60, }); assert.equal(pickMirrorFile({ files: [f("a.mp4", "original"), f("b.webm", "original")] }, "ID123456789"), null); assert.equal(pickMirrorFile({ files: [f("only.mkv", "original", "100"), f("only.mp4", "derivative", undefined, "only.mkv")] }, "ID123456789")?.file, "only.mkv"); // Within 5 s (or 2 %) of the record; a derivative takes its original's length. assert.equal(pickMirrorFile({ files: [f("only.mkv", "original", "100")] }, "ID123456789", 104)?.file, "only.mkv"); assert.equal(pickMirrorFile({ files: [f("only.mkv", "original", "100")] }, "ID123456789", 120), null, "another length: another video"); assert.equal(pickMirrorFile({ files: [f("only.mkv", "original")] }, "ID123456789", 100), null, "a length that cannot be checked"); assert.equal(pickMirrorFile({ files: [f("notes.txt", "original")] }, "ID123456789"), null); }); test("archive-search by YouTube id: the mirror's direct file URL; a compilation that mentions the id is rejected", async () => { const { deps, close } = await fakes(); try { const r = await findArchiveOrgMirrors(IA, { client: deps.archive, duration: 598 }); assert.deepEqual(r.mirrors.map((m) => [m.identifier, m.file, m.source, m.namedBy, m.seconds]), [ [`youtube-${IA}`, `An upload-${IA}.mp4`, "original", "its identifier", 600], ]); assert.equal(r.mirrors[0]!.url, `https://archive.org/download/youtube-${IA}/An%20upload-${IA}.mp4`); const comp = await findArchiveOrgMirrors(COMP, { client: deps.archive }); assert.equal(comp.found, 1, "the search finds it"); assert.deepEqual(comp.mirrors, []); assert.match(comp.skipped[0]!.why, /mentions the id but is not of it/); } finally { await close(); } }); test("find-copy: the Wayback video, else an archive.org mirror, else words only; a non-YouTube record is not looked for", async () => { const { wb, ia, deps, recorded, 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]), [ [WB, "fetch", "wayback", 2], [IA, "fetch", "archive.org", 1], [COMP, "text-only", null, 1], [NONE, "text-only", null, 1], ["v5abcde", "text-only", null, 1], ], ); // Wayback: the URL yt-dlp's extractor takes; archive.org not asked once it had the video. assert.equal(r.recordings[0]!.copy!.url, `https://web.archive.org/web/${watch(WB)}`); assert.deepEqual(r.recordings[0]!.tried.map((t) => [t.from, t.found]), [["wayback", true]]); // A page captured with no video is not a copy: IA's page has none, the video index says no. assert.deepEqual(r.recordings[1]!.tried.map((t) => [t.from, t.found]), [ ["wayback", false], ["archive.org", true], ]); assert.equal(r.recordings[1]!.copy!.url, `https://archive.org/download/youtube-${IA}/An%20upload-${IA}.mp4`); // The Rumble record: no request at all. assert.match(r.recordings[4]!.tried[0]!.detail ?? "", /not a YouTube recording/); const vids = wb.requests.filter((q) => q.path.startsWith("/__wb/videoinfo")).map((q) => new URL(q.path, "http://x").searchParams.get("vid")); assert.deepEqual(vids, [WB, IA, COMP, NONE]); assert.ok(!ia.requests.some((q) => q.includes(WB)), "no archive.org search for the one Wayback had"); assert.ok(!ia.requests.some((q) => q.includes("v5abcde"))); assert.deepEqual( r.items.map((i) => [i.id, i.from, i.to, i.clipId, i.webpageUrl === i.copy?.url, i.copy?.from]), [ [WB, 0, 10, "a#c1", true, "wayback"], [WB, 30, 40, "a#c2", true, "wayback"], [IA, 5, 15, "a#c3", true, "archive.org"], ], ); assert.ok(lines.some((l) => l.includes(COMP) && l.includes("its words only"))); // The found check asked for WB's stream once (a ranged GET at yt-dlp's URL). const probes = wb.requests.filter((q) => q.path.startsWith("/web/2id_/")); assert.deepEqual(probes.map((q) => q.path), [`/web/2id_/https://rr1---sn-fake.googlevideo.com/videoplayback?itag=18&id=${WB}`]); // (R8) The YouTube recordings neither source holds are recorded none-found; the Rumble one is not. assert.deepEqual(recorded.map((x) => [x.dir, x.attempt.outcome]), [ [`/x/${COMP}`, "none-found"], [`/x/${NONE}`, "none-found"], ]); } finally { await close(); } }); test("the Wayback found check: a video the index lists whose stream 404s is 'page captured, no video' — none found, recorded, never a copy", async () => { // WB is in the video index, but Wayback holds no bytes for its format (the live case). const { wb, deps, recorded, close } = await fakes({ streams: [], items: [], need: { ...NEED, unfetchable: NEED.unfetchable.slice(0, 1) } }); try { const lines: string[] = []; const r = await findCopies({ ...opts(deps), onLog: (l) => lines.push(l) }); assert.equal(r.recordings[0]!.outcome, "text-only"); assert.deepEqual(r.items, [], "nothing goes to fetch-windows"); const t = r.recordings[0]!.tried[0]!; assert.deepEqual([t.from, t.found], ["wayback", false]); assert.equal(t.error, undefined, "not a lookup error"); assert.match(t.detail ?? "", new RegExp(`^${WAYBACK_PAGE_ONLY} \\(the video index lists 1 format\\(s\\); 1 probed, HTTP 404\\)$`)); assert.equal(wb.requests.filter((q) => q.path.startsWith("/web/2id_/")).length, 1); assert.equal(recorded.length, 1); assert.equal(recorded[0]!.attempt.outcome, "none-found"); assert.match(recorded[0]!.attempt.detail ?? "", /wayback none — page captured, no video/); assert.ok(lines.some((l) => l.includes("page captured, no video") && l.includes("its words only"))); // A dry run records nothing. const dry = await runFindCopy({ ...opts(deps), dryRun: true, startFetch: async () => null }); assert.equal(dry.recordings[0]!.outcome, "text-only"); assert.equal(recorded.length, 1); } finally { await close(); } // Page only on Wayback, a mirror on archive.org: the mirror is the copy. const both = await fakes({ streams: [], need: { ...NEED, unfetchable: NEED.unfetchable.slice(0, 1) } }); try { const r = await findCopies(opts(both.deps)); assert.equal(r.recordings[0]!.copy?.from, "archive.org"); assert.match(r.recordings[0]!.tried[0]!.detail ?? "", /^page captured, no video/); assert.equal(both.recorded.length, 0); } finally { await both.close(); } // A probe Wayback keeps refusing is a lookup error (tried again later), never none-found. const busy = await fakes({ streamBusy: 50, need: { ...NEED, unfetchable: NEED.unfetchable.slice(0, 1) } }); try { const r = await findCopies(opts(busy.deps)); assert.equal(r.recordings[0]!.outcome, "error"); assert.match(r.stopped ?? "", /kept refusing/); assert.equal(busy.recorded.length, 0); } finally { await busy.close(); } }); test("a copy that failed before is not picked again: Wayback falls through to archive.org, a failed mirror to none", async () => { // WB also has a mirror (ITEMS: youtube-WB, 300 s). const failedWayback: FailedCopy = { from: "wayback", url: `https://web.archive.org/web/${watch(WB)}`, at: "2026-10-15T00:00:00Z", error: "HTTP 404" }; const one = await fakes({ failed: { [`/x/${WB}`]: [failedWayback] }, need: { ...NEED, unfetchable: NEED.unfetchable.slice(0, 2) } }); try { const r = await findCopies(opts(one.deps)); assert.equal(r.recordings[0]!.copy?.from, "archive.org"); assert.deepEqual(r.recordings[0]!.tried.map((t) => [t.from, t.found]), [ ["wayback", false], ["archive.org", true], ]); assert.match(r.recordings[0]!.tried[0]!.detail ?? "", /failed before/); assert.equal(one.wb.requests.length, 0, "the Wayback is not asked again"); // retryFailed (the release 29 live fix: a failure later found to be ours) // tries the recorded copy again, and still lists it. const again = await findCopies({ ...opts(one.deps), retryFailed: true }); assert.equal(again.recordings[0]!.copy?.from, "wayback"); assert.deepEqual(again.recordings[0]!.failedBefore.map((f) => f.from), ["wayback"]); } finally { await one.close(); } const mirrorUrl = `https://archive.org/download/youtube-${WB}/An%20upload-${WB}.mp4`; const both = await fakes({ failed: { [`/x/${WB}`]: [failedWayback, { from: "archive.org", url: mirrorUrl, at: "2026-10-15T01:00:00Z", error: "403" }] }, need: { ...NEED, unfetchable: NEED.unfetchable.slice(0, 1) }, }); try { const r = await findCopies(opts(both.deps)); assert.equal(r.recordings[0]!.outcome, "text-only"); assert.match(r.recordings[0]!.tried[1]!.detail ?? "", /1 mirror\(s\) failed before/); assert.deepEqual(r.items, []); } finally { await both.close(); } }); test("runFindCopy: the found windows go to ONE fetch-windows call; a dry run, a cancelled 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 ctl = new AbortController(); ctl.abort(); const cancelled = await runFindCopy({ ...opts(deps), signal: ctl.signal, startFetch: start }); assert.equal(calls.length, 1, "cancelled: no fetch"); assert.match(cancelled.stopped ?? "", /cancelled/); const none = await runFindCopy({ ...opts({ ...deps, missing: async () => ({ ...NEED, unfetchable: [NEED.unfetchable[4]] }) }), 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(); } });