Archilyzer · Source

archilyzer

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

commit c578224a3744ef34262d4e42ee45174662fd9f8c
parent 5018ce06fc24ffd231e4ce39826144bf5e240c11
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 08:27:51 -0400

common: find-copy picks a copy that holds the video, and never the same failed copy twice (review 3, 4) — Wayback counts only when web.archive.org's video index has the YouTube video (__wb/videoinfo, the check yt-dlp's YoutubeWebArchive extractor makes), its URL the form that extractor takes; an archive.org mirror counts only when its identifier, a file name or its originalurl/source names the id (a title or description is not enough) and its file's length agrees with the record's duration (5 s or 2 %); only a record whose page is a YouTube URL is looked for; a copy whose fetch failed is recorded beside the recording (copy-attempts.json, by fetch-windows; not on a rate limit) and the next run falls through to archive.org or the next mirror; a cancelled run starts no fetch; the fake Wayback answers videoinfo

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

Diffstat:
Mcommon/controller/fetchWindows.test.ts | 15+++++++++++++++
Mcommon/controller/fetchWindows.ts | 17+++++++++++++++++
Acommon/lib/copyAttempts-server.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/copyAttempts.test.ts | 31+++++++++++++++++++++++++++++++
Mcommon/lib/waybackClient.test.ts | 19++++++++++++++++++-
Mcommon/lib/waybackClient.ts | 32++++++++++++++++++++++++++++++++
Mcommon/publish/findCopy.test.ts | 225+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Mcommon/publish/findCopy.ts | 335+++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------
Mcommon/testing/web/fakeWayback.d.mts | 3++-
Mcommon/testing/web/fakeWayback.mjs | 15+++++++++++++++
10 files changed, 547 insertions(+), 188 deletions(-)

diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -436,3 +436,18 @@ test("a window of a gone recording fetched from a copy (find-copy) records which assert.deepEqual(parseClipProvenance(sidecar)?.copy, copy); assert.equal(parseClipProvenance({ requestedBy: "x", copy: { from: "elsewhere", url: copy.url } })?.copy, undefined); }); + +test("a copy whose fetch failed is recorded beside the recording (find-copy will not pick it again); a rate limit is not", async () => { + const paths = await corpus(); + const recorded: [string, unknown][] = []; + const h = harness({ recordFailedCopy: async (dir, f) => void recorded.push([dir, f]) }); + const copy = { from: "archive.org" as const, url: "https://www.youtube.com/gone" }; + const r = await go(paths, [{ slug: "c", id: "v1", from: 10, to: 20, webpageUrl: copy.url, copy }], h); + assert.equal(r.failed.length, 1); + assert.equal(recorded.length, 1); + assert.equal(recorded[0]![0], path.join(paths.channelsDir, "c", "data", "v1")); + assert.deepEqual({ ...(recorded[0]![1] as object), at: undefined, error: undefined }, { ...copy, at: undefined, error: undefined }); + const limited = { ...copy, url: "https://www.youtube.com/429" }; + await go(paths, [{ slug: "c", id: "v2", from: 10, to: 20, webpageUrl: limited.url, copy: limited }], h); + assert.equal(recorded.length, 1, "a rate limit says nothing about the copy"); +}); diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -5,6 +5,7 @@ import type { SiteSettings } from "../lib/settings"; import { getSettings } from "../lib/settings"; import type { DownloadFailureClass } from "../lib/availability"; import type { ClipCopy } from "../lib/clipWindow"; +import { recordFailedCopy, type FailedCopy } from "../lib/copyAttempts-server"; import { resolveCookiePolicy } from "../lib/cookiePolicy"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { detectPlatform } from "../lib/platform"; @@ -131,6 +132,10 @@ export type FetchWindowsItem = { // The copy of a gone recording `webpageUrl` is (release 29 E2, find-copy): // recorded in the window's provenance. copy?: ClipCopy; + // Fetch from the recording's own page even though its availability says it + // is gone (a stale reading: made public again, a geo block read as removed). + // The editor's door refuses a gone recording's window without it. + force?: boolean; }; export type FetchWindowsFailureClass = @@ -207,6 +212,8 @@ export type FetchWindowsDeps = { // put the second one's first fetch right after the first one's last. gapRemainingMs: (key: string) => number; noteGap: (key: string, gapMs: number) => void; + // A find-copy copy whose fetch failed (lib/copyAttempts-server.ts). + recordFailedCopy: (videoDir: string, failed: FailedCopy) => Promise<void>; }; function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> { @@ -243,6 +250,7 @@ const DEFAULT_DEPS: FetchWindowsDeps = { recordClean: (platform, paths) => recordPlatformClean(platform, paths), gapRemainingMs: (key) => platformGapRemainingMs(key), noteGap: (key, gapMs) => notePlatformGap(key, gapMs), + recordFailedCopy, }; export function fetchWindowsItemLabel(item: FetchWindowsItem): string { @@ -548,6 +556,15 @@ export async function fetchWindows({ const cls: FetchWindowsFailureClass = e instanceof FetchWindowError ? e.failureClass : "unknown"; fail(item, cls, message); + // A COPY THAT FAILED (find-copy's, release 29 review) is recorded beside + // the recording, so the next find-copy falls through to another copy. A + // rate limit says nothing about the copy, and neither does a cancel. + if (item.copy && cls !== "rate_limit" && !fetchSignal.aborted) { + await deps + .recordFailedCopy(videoDir, { ...item.copy, at: new Date().toISOString(), error: message }) + .catch(() => {}); + log(` ${label}: the ${item.copy.from} copy failed — find-copy will not pick it again.`); + } done += 1; progress(); if (cls === "rate_limit") { diff --git a/common/lib/copyAttempts-server.ts b/common/lib/copyAttempts-server.ts @@ -0,0 +1,43 @@ +// THE COPIES OF A GONE RECORDING THAT FAILED (release 29 review): a window +// find-copy sent to fetch-windows from a copy (a Wayback capture, an +// archive.org file) whose fetch failed. `data/<id>/copy-attempts.json`, so a +// later find-copy does not pick the same copy again and falls through to the +// next (Wayback → archive.org → the next mirror). Written by fetch-windows +// (controller/fetchWindows.ts) on an item's failure; read by find-copy. +// +// SERVER-ONLY (node:fs). + +import { coerceClipCopy, type ClipCopy } from "./clipWindow"; +import { sidecar, sidecarField } from "./sidecar-server"; + +export const COPY_ATTEMPTS_FILENAME = "copy-attempts.json"; + +export type FailedCopy = ClipCopy & { at: string; error: string }; +export type CopyAttempts = { failed: FailedCopy[] }; + +// The newest few, one per URL. +const KEEP = 20; + +export function coerceCopyAttempts(value: unknown): CopyAttempts | null { + const v = value as { failed?: unknown } | null; + if (!v || typeof v !== "object" || !Array.isArray(v.failed)) return null; + const failed: FailedCopy[] = []; + for (const f of v.failed) { + const copy = coerceClipCopy(f); + const r = f as { at?: unknown; error?: unknown }; + if (copy && typeof r.at === "string") failed.push({ ...copy, at: r.at, error: typeof r.error === "string" ? r.error : "" }); + } + return { failed }; +} + +export const copyAttemptsSidecar = sidecar(COPY_ATTEMPTS_FILENAME, sidecarField(coerceCopyAttempts)); + +export async function readFailedCopies(videoDir: string): Promise<FailedCopy[]> { + return (await copyAttemptsSidecar.load(videoDir).catch(() => null))?.failed ?? []; +} + +export async function recordFailedCopy(videoDir: string, failed: FailedCopy): Promise<void> { + const prev = await readFailedCopies(videoDir); + const next = [...prev.filter((f) => f.url !== failed.url), { ...failed, error: failed.error.slice(0, 400) }].slice(-KEEP); + await copyAttemptsSidecar.write(videoDir, { failed: next }); +} diff --git a/common/lib/copyAttempts.test.ts b/common/lib/copyAttempts.test.ts @@ -0,0 +1,31 @@ +// The failed copies of a gone recording (release 29 review): appended one per +// URL, the newest kept, read back for find-copy. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/copyAttempts.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { COPY_ATTEMPTS_FILENAME, readFailedCopies, recordFailedCopy } from "./copyAttempts-server"; + +test("recordFailedCopy appends one per URL, newest last; readFailedCopies reads them", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "copy-attempts-")); + try { + assert.deepEqual(await readFailedCopies(dir), []); + await recordFailedCopy(dir, { from: "wayback", url: "https://web.archive.org/web/x", at: "1", error: "404" }); + await recordFailedCopy(dir, { from: "archive.org", url: "https://archive.org/download/a/b.mp4", at: "2", error: "403" }); + await recordFailedCopy(dir, { from: "wayback", url: "https://web.archive.org/web/x", at: "3", error: "410" }); + assert.deepEqual( + (await readFailedCopies(dir)).map((f) => [f.from, f.at, f.error]), + [ + ["archive.org", "2", "403"], + ["wayback", "3", "410"], + ], + ); + assert.equal(COPY_ATTEMPTS_FILENAME, "copy-attempts.json"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/waybackClient.test.ts b/common/lib/waybackClient.test.ts @@ -7,7 +7,7 @@ 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 { parseCdxJson, waybackCdxUrl, WaybackClient, waybackReplayUrl, waybackYoutubeUrl } from "./waybackClient"; import { ArchiveOrgRequestError } from "./archiveOrgClient"; const BREAD = "https://video.example/watch?v=bread-day-01"; @@ -78,3 +78,20 @@ test("a 429 is waited out (Retry-After) and asked again; one that persists stops await busy.close(); } }); + +test("youtubeVideoArchived: yt-dlp's check — the video index's formats, not a capture of the page", async () => { + const wb = await startFakeWayback({ videos: ["waybackVid1"] }); + try { + const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + assert.equal(await c.youtubeVideoArchived("waybackVid1"), true); + assert.equal(await c.youtubeVideoArchived("pageOnly001"), false); + assert.deepEqual(wb.requests.map((r) => r.path), [ + "/__wb/videoinfo?vtype=youtube&vid=waybackVid1", + "/__wb/videoinfo?vtype=youtube&vid=pageOnly001", + ]); + assert.equal(waybackYoutubeUrl("waybackVid1", "20200101000000"), "https://web.archive.org/web/20200101000000/https://www.youtube.com/watch?v=waybackVid1"); + assert.equal(waybackYoutubeUrl("waybackVid1"), "https://web.archive.org/web/https://www.youtube.com/watch?v=waybackVid1"); + } finally { + await wb.close(); + } +}); diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts @@ -86,6 +86,22 @@ export function parseCdxJson(body: string): WaybackCapture[] { return out; } +// What yt-dlp's YoutubeWebArchive extractor asks before it fetches anything +// (yt_dlp/extractor/archiveorg.py, `_real_extract`): the Wayback Machine's +// own index of the YouTube VIDEOS it holds. No formats there: "The requested +// video is not archived or indexed" — whatever captures of the watch page exist +// (YouTube serves "Video unavailable" with a 200, and most page captures hold +// no video). +export function waybackVideoInfoUrl(youtubeId: string): string { + return `${WAYBACK_ORIGIN}/__wb/videoinfo?${new URLSearchParams({ vtype: "youtube", vid: youtubeId }).toString()}`; +} + +// The replay URL yt-dlp's extractor takes for a YouTube video (its _VALID_URL: +// web.archive.org/web/<ts>/https://www.youtube.com/watch?v=<id>). +export function waybackYoutubeUrl(youtubeId: string, timestamp?: string): string { + return `${WAYBACK_ORIGIN}/web/${timestamp ?? ""}${timestamp ? "/" : ""}https://www.youtube.com/watch?v=${youtubeId}`; +} + export class WaybackClient { private readonly http: ArchiveOrgClient; @@ -98,6 +114,22 @@ export class WaybackClient { return this.http.requests; } + // Whether the Wayback Machine holds the YouTube VIDEO itself (formats in + // its videoinfo index — what yt-dlp asks), not only captures of its page. + async youtubeVideoArchived(youtubeId: string, o: { signal?: AbortSignal } = {}): Promise<boolean> { + const body = await this.http.getText(waybackVideoInfoUrl(youtubeId), "application/json", o.signal); + let raw: unknown; + try { + raw = body.trim() ? JSON.parse(body) : {}; + } catch { + throw new ArchiveOrgRequestError(`the Wayback video index did not answer JSON for ${youtubeId}`, null, false); + } + const formats = (raw as { formats?: unknown } | null)?.formats; + if (Array.isArray(formats)) return formats.length > 0; + // A dmux answer keeps its formats by kind. + return !!formats && typeof formats === "object" && Object.values(formats as Record<string, unknown>).some((v) => Array.isArray(v) && v.length > 0); + } + // 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. diff --git a/common/publish/findCopy.test.ts b/common/publish/findCopy.test.ts @@ -1,16 +1,21 @@ -// 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. +// 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 { ITEMS, startFakeArchiveOrg } from "../testing/archiveOrg/fakeArchiveOrg.mjs"; +import { startFakeArchiveOrg, type FakeArchiveOrgItem } from "../testing/archiveOrg/fakeArchiveOrg.mjs"; import { ArchiveOrgClient } from "../lib/archiveOrgClient"; import { WaybackClient } from "../lib/waybackClient"; +import type { FailedCopy } from "../lib/copyAttempts-server"; import type { MissingEvidenceWindows, UnfetchableEvidenceWindow } from "./reportMedia"; import type { ReportHost } from "./reportHost"; import type { Paths } from "../lib/paths"; @@ -18,28 +23,34 @@ import type { FetchWindowsItem } from "../controller/fetchWindows"; import { findArchiveOrgMirrors, findCopies, + mirrorNamesId, pickMirrorFile, runFindCopy, youtubeIdOf, youtubeIdQuery, + type RecordFacts, } 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", - }, +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"]> = {}): FakeArchiveOrgItem => ({ + metadata: { identifier: `youtube-${id}`, title: `An upload ${id}`, mediatype: "movies", originalurl: watch(id), ...extra }, 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" }, + { 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, @@ -60,71 +71,92 @@ const NEED: MissingEvidenceWindows = { 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 }, + 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 }, ], }; -async function fakes(o: { waybackBusy?: number } = {}) { - const wb = await startFakeWayback({ busyTimes: o.waybackBusy ?? 0 }); - const ia = await startFakeArchiveOrg({ items: [...ITEMS, OTHER_MIRROR] }); +const FACTS: Record<string, RecordFacts> = { + [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<string, FailedCopy[]>; need?: MissingEvidenceWindows } = {}) { + const wb = await startFakeWayback({ busyTimes: o.waybackBusy ?? 0, videos: [WB] }); + const ia = await startFakeArchiveOrg({ items: ITEMS }); 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), + missing: async () => o.need ?? NEED, + facts: async (_p: Paths, _slug: string, id: string) => FACTS[id]!, + failedCopies: async (dir: string) => o.failed?.[dir] ?? [], }; 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); +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("no spaces allowed"), /not a YouTube id/); + 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; 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", +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")] }, "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); + 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: each mirror's direct file URL, an original preferred", async () => { +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("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, - }, + 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.deepEqual((await findArchiveOrgMirrors("nothing00001", { client: deps.archive })).mirrors, []); + 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: Wayback first, archive.org second, none → words only; one recording at a time", async () => { +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, close } = await fakes(); try { const lines: string[] = []; @@ -132,43 +164,75 @@ test("find-copy: Wayback first, archive.org second, none → words only; one rec 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], + [WB, "fetch", "wayback", 2], + [IA, "fetch", "archive.org", 1], + [COMP, "text-only", null, 1], + [NONE, "text-only", null, 1], + ["v5abcde", "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: 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", false], + ["archive.org", true], ]); - 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); + 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"))); - // 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"], + [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("nothing00001") && l.includes("its words only"))); + assert.ok(lines.some((l) => l.includes(COMP) && 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 () => { +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"); + } 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[][] = []; @@ -183,8 +247,13 @@ test("runFindCopy: the found windows go to ONE fetch-windows call; a dry run and 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[3]] }) }), + ...opts({ ...deps, missing: async () => ({ ...NEED, unfetchable: [NEED.unfetchable[4]] }) }), startFetch: start, }); assert.equal(calls.length, 1); diff --git a/common/publish/findCopy.ts b/common/publish/findCopy.ts @@ -1,30 +1,45 @@ // 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 +// A report cites a moment of a YouTube 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>`. +// 1. THE WAYBACK MACHINE, when it holds the VIDEO — not merely a capture of +// the watch page (YouTube answers "Video unavailable" with a 200, and most +// page captures hold no video). The check is the one yt-dlp's +// YoutubeWebArchive extractor makes before it fetches anything +// (yt_dlp/extractor/archiveorg.py `_real_extract`: web.archive.org's +// `__wb/videoinfo?vtype=youtube&vid=<id>` has formats); the copy's URL is +// `https://web.archive.org/web/<ts>/https://www.youtube.com/watch?v=<id>`, +// the form that extractor takes (the newest 200 capture's timestamp, when +// the CDX names one); +// 2. ARCHIVE.ORG: a mirror that is OF the upload — its identifier, a file's +// name, or its `originalurl`/`source` names the YouTube id (a title or a +// description that mentions it is not enough: a compilation does that) — +// holding a video file whose length agrees with the record's duration; +// fetched by its direct URL `https://archive.org/download/<identifier>/<file>`. +// +// Only a record whose page is a YouTube URL is looked for: the id is the +// page's, never guessed from a Twitch or Rumble record's own id. +// +// A COPY THAT FAILED is not picked again: fetch-windows records a copy whose +// fetch failed beside the recording (lib/copyAttempts-server.ts), and the next +// run falls through — Wayback → archive.org → the next mirror. // // 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". +// marked "source deleted" (once prepare says so). // // 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. +// left for a later run. A cancelled run starts no fetch. 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"; @@ -32,11 +47,12 @@ 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 { readFailedCopies, type FailedCopy } from "../lib/copyAttempts-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 { isArchiveOrgVideoFileName, parseArchiveOrgLength, type ArchiveOrgItemMetadata } from "../lib/archiveOrg"; +import { waybackClient, waybackYoutubeUrl, type WaybackCapture } from "../lib/waybackClient"; import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; import { channelConfigPlatform } from "../lib/videoId"; import { readChannelConfig } from "../controller/channels"; @@ -45,80 +61,141 @@ import { missingEvidenceWindows, type EvidenceWindow, type MissingEvidenceWindow import type { ReportHost } from "./reportHost"; import type { FetchWindowsItem } from "../controller/fetchWindows"; -// ─── A recording's page and its YouTube id ─── +// ─── A recording: its page, its length, 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> { +export type RecordFacts = { + // The page it was served at: its metadata's `webpage_url`, else the one its + // availability check recorded, else the playlist's. + webpageUrl: string | null; + // Its length in seconds, from its metadata. + duration: number | null; + // Its data directory (where the failed copies are recorded). + videoDir: string; +}; + +export async function recordFacts(paths: Paths, slug: string, id: string): Promise<RecordFacts> { 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); + const videoDir = path.join(paths.channelsDir, slug, "data", dirId); + let webpageUrl: string | null = null; + let duration: number | null = null; 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; + const meta = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")) as { webpage_url?: unknown; duration?: unknown }; + if (typeof meta.webpage_url === "string" && /^https?:\/\//.test(meta.webpage_url)) webpageUrl = meta.webpage_url; + if (typeof meta.duration === "number" && Number.isFinite(meta.duration) && meta.duration > 0) duration = meta.duration; } 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; + if (!webpageUrl) { + const av = await loadAvailability(videoDir).catch(() => null); + if (av?.webpageUrl && /^https?:\/\//.test(av.webpageUrl)) webpageUrl = av.webpageUrl; + } + if (!webpageUrl && config) webpageUrl = await findVideoSourceUrl(paths, slug, dirId, config).catch(() => null); + return { webpageUrl, duration, videoDir }; } -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 - } +// The page alone (wayback-lookup's `{slug, id}`). +export async function recordWebpageUrl(paths: Paths, slug: string, id: string): Promise<string | null> { + return (await recordFacts(paths, slug, id)).webpageUrl; +} + +const YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/; +const YOUTUBE_HOST = /^(?:(?:www|m|music)\.)?youtube\.com$|^youtu\.be$/; + +// The YouTube id of a YouTube page (a watch URL's `v`, a youtu.be path, a +// /shorts/, /live/ or /embed/ path), or null — for any other page, whatever +// the record's own id looks like. +export function youtubeIdOf(pageUrl: string | null): string | null { + if (!pageUrl) return null; + let u: URL; + try { + u = new URL(pageUrl); + } catch { + return null; } - return YOUTUBE_ID.test(recordId) ? recordId : null; + const host = u.hostname.toLowerCase(); + if (!YOUTUBE_HOST.test(host)) return null; + const v = u.searchParams.get("v"); + if (v && YOUTUBE_ID.test(v)) return v; + const seg = u.pathname.split("/").filter(Boolean); + if (host === "youtu.be") return seg[0] && YOUTUBE_ID.test(seg[0]) ? seg[0] : null; + const k = seg.findIndex((s) => s === "shorts" || s === "live" || s === "embed"); + return k >= 0 && seg[k + 1] && YOUTUBE_ID.test(seg[k + 1]) ? seg[k + 1] : null; +} + +export function isYoutubeId(id: string): boolean { + return YOUTUBE_ID.test(id); } // ─── 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. +// archive.org's advanced search for CANDIDATE mirrors of one YouTube upload +// (each is then checked: findArchiveOrgMirrors). 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}")`; + return `identifier:(youtube-${id}) OR originalurl:(*${id}*) OR source:(*${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(); +const textOf = (v: unknown): string => + typeof v === "string" ? v : Array.isArray(v) ? v.filter((x) => typeof x === "string").join(" ") : ""; + +// Whether an item is OF the upload: its identifier, a file's name, or its +// `originalurl`/`source` names the id. A title or description that mentions +// it is not (a compilation or a reaction cites its sources there). +export function mirrorNamesId(item: Pick<ArchiveOrgItemMetadata, "metadata" | "files">, youtubeId: string): string | null { + const meta = item.metadata as Record<string, unknown>; + if (item.metadata.identifier.includes(youtubeId)) return "its identifier"; + if (item.files.some((f) => f.name.includes(youtubeId))) return "a file's name"; + if (textOf(meta.originalurl).includes(youtubeId)) return "its original URL"; + if (textOf(meta.source).includes(youtubeId)) return "its source"; + return null; +} + +// How far a mirror's file may run from the record's duration: 5 s, or 2 %. +export function mirrorLengthTolerance(seconds: number): number { + return Math.max(5, seconds * 0.02); +} // 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). +// an ORIGINAL before a derivative, then mp4, webm, mkv, … — and, when the +// record's duration is known, only a file whose length agrees with it (a +// derivative's length is its original's when it has none). Null when the item +// holds none that qualifies, 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 { + duration: number | null = null, +): { file: string; source: "original" | "derivative"; size?: number; seconds?: 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 : []; + let pool = named.length > 0 ? named : originals.length === 1 ? videos : []; + const lengthOf = (f: (typeof videos)[number]): number | undefined => + parseArchiveOrgLength(f.length) ?? parseArchiveOrgLength(item.files.find((o) => o.name === f.original)?.length); + if (duration !== null) { + pool = pool.filter((f) => { + const s = lengthOf(f); + return s !== undefined && Math.abs(s - duration) <= mirrorLengthTolerance(duration); + }); + } 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 } : {}) }; + const seconds = lengthOf(best); + return { + file: best.name, + source: best.source === "original" ? "original" : "derivative", + ...(size !== undefined ? { size } : {}), + ...(seconds !== undefined ? { seconds } : {}), + }; } export type ArchiveOrgMirror = { @@ -129,6 +206,9 @@ export type ArchiveOrgMirror = { url: string; source: "original" | "derivative"; size?: number; + seconds?: number; + // How the item names the upload. + namedBy: string; }; export type ArchiveOrgMirrorSearch = { @@ -140,39 +220,45 @@ export type ArchiveOrgMirrorSearch = { 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. +// item that is not OF the upload (mirrorNamesId), is restricted, or holds no +// video file of it (of the record's length, when `duration` is given) is +// skipped, with why. export async function findArchiveOrgMirrors( youtubeId: string, - o: { client?: ArchiveOrgClient; signal?: AbortSignal; limit?: number } = {}, + o: { client?: ArchiveOrgClient; signal?: AbortSignal; limit?: number; duration?: number | null } = {}, ): 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 }[] = []; + const duration = o.duration ?? null; for (const hit of hits.items) { + o.signal?.throwIfAborted(); 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" }); + const namedBy = mirrorNamesId(item, youtubeId); + if (!namedBy) { + skipped.push({ identifier: hit.identifier, why: "it mentions the id but is not of it (no identifier, file name or original URL names it)" }); continue; } if (archiveOrgRestriction(item).item) { skipped.push({ identifier: hit.identifier, why: "archive.org restricts it" }); continue; } - const pick = pickMirrorFile(item, youtubeId); + const pick = pickMirrorFile(item, youtubeId, duration); if (!pick) { - skipped.push({ identifier: hit.identifier, why: "no video file of the upload can be told in it" }); + skipped.push({ + identifier: hit.identifier, + why: + duration !== null + ? `no video file of the upload with its length (${Math.round(duration)} s) can be told in it` + : "no video file of the upload can be told in it", + }); continue; } + const meta = item.metadata as Record<string, unknown>; const title = textOf(meta.title) || hit.title; mirrors.push({ identifier: item.metadata.identifier, @@ -181,6 +267,8 @@ export async function findArchiveOrgMirrors( url: archiveOrgDownloadUrl(item.metadata.identifier, pick.file), source: pick.source, ...(pick.size !== undefined ? { size: pick.size } : {}), + ...(pick.seconds !== undefined ? { seconds: pick.seconds } : {}), + namedBy, }); } // Originals first, then the search's order. @@ -196,7 +284,7 @@ export type WaybackLookup = { url: string; captures: WaybackCapture[] }; // 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 } = {}, + o: { client?: Pick<typeof waybackClient, "captures">; okOnly?: boolean; limit?: number; signal?: AbortSignal } = {}, ): Promise<WaybackLookup> { const client = o.client ?? waybackClient; const captures = await client.captures(url, { @@ -226,6 +314,8 @@ export type FindCopyRecording = { youtubeId: string | null; // The cited windows of the recording. windows: EvidenceWindow[]; + // Copies an earlier fetch failed from (not picked again). + failedBefore: ClipCopy[]; tried: FindCopyAttempt[]; copy?: ClipCopy; // fetch a copy found: its windows go to fetch-windows @@ -245,19 +335,24 @@ export type FindCopyResult = { }; export type FindCopyDeps = { - wayback: { captures: typeof waybackClient.captures }; + wayback: Pick<typeof waybackClient, "captures" | "youtubeVideoArchived">; archive: ArchiveOrgClient; missing: (paths: Paths, host: ReportHost) => Promise<MissingEvidenceWindows>; - webpageUrl: (paths: Paths, slug: string, id: string) => Promise<string | null>; + facts: (paths: Paths, slug: string, id: string) => Promise<RecordFacts>; + failedCopies: (videoDir: string) => Promise<FailedCopy[]>; }; const DEFAULT_DEPS: FindCopyDeps = { wayback: waybackClient, archive: archiveOrgClient, missing: (paths, host) => missingEvidenceWindows(paths, host), - webpageUrl: recordWebpageUrl, + facts: recordFacts, + failedCopies: readFailedCopies, }; +const describeAttempt = (t: FindCopyAttempt) => + `${t.from} ${t.found ? `found — ${t.detail}` : t.error ? `failed — ${t.error}` : `none — ${t.detail}`}`; + // 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). @@ -270,6 +365,8 @@ export async function findCopies(opts: { }): Promise<FindCopyResult> { const deps: FindCopyDeps = { ...DEFAULT_DEPS, ...opts.deps }; const log = (line: string) => opts.onLog?.(line); + const signal = opts.signal; + const sig = signal ? { signal } : {}; 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) { @@ -283,61 +380,79 @@ export async function findCopies(opts: { 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" }; + if (signal?.aborted) break; + const facts = await deps.facts(opts.paths, r.slug, r.id); + const youtubeId = youtubeIdOf(facts.webpageUrl); + const failedBefore = (await deps.failedCopies(facts.videoDir).catch(() => [] as FailedCopy[])).map(({ from, url }) => ({ from, url })); + const failedUrls = new Set(failedBefore.map((f) => f.url)); + const rec: FindCopyRecording = { ...r, watchUrl: facts.webpageUrl, youtubeId, failedBefore, tried: [], outcome: "text-only" }; result.recordings.push(rec); let refused: string | undefined; + const lookupFailed = (from: ClipCopy["from"], e: unknown) => { + if (signal?.aborted) return; + rec.tried.push({ from, found: false, error: (e as Error).message }); + if (e instanceof ArchiveOrgRequestError && e.rateLimited) refused = (e as Error).message; + }; - // 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" }); + if (!youtubeId) { + rec.tried.push({ from: "wayback", found: false, detail: "not a YouTube recording: no copy is looked for" }); + } else { + // 1. The Wayback Machine — when it holds the video, and no fetch from it failed before. + if (failedBefore.some((f) => f.from === "wayback")) { + rec.tried.push({ from: "wayback", found: false, detail: "a fetch from its Wayback copy failed before" }); + } else { + try { + if (await deps.wayback.youtubeVideoArchived(youtubeId, sig)) { + // The newest capture of the page that recorded a 200 dates the copy. + const { captures } = await waybackLookup(`https://www.youtube.com/watch?v=${youtubeId}`, { + client: deps.wayback, + okOnly: true, + ...sig, + }); + const newest = captures.filter((c) => c.status === "200").at(-1); + const url = waybackYoutubeUrl(youtubeId, newest?.timestamp); + rec.copy = { from: "wayback", url }; + rec.tried.push({ from: "wayback", found: true, url, detail: `the video is archived${newest ? `; its page captured ${newest.timestamp}` : ""}` }); + } else { + rec.tried.push({ from: "wayback", found: false, detail: "the video is not archived (its page may be)" }); + } + } catch (e) { + lookupFailed("wayback", e); } - } 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) { + // 2. archive.org: a mirror OF the upload, of its length, not failed before. + if (!rec.copy && !refused && !signal?.aborted) { try { - const found = await findArchiveOrgMirrors(youtubeId, { client: deps.archive, ...(opts.signal ? { signal: opts.signal } : {}) }); - const m = found.mirrors[0]; + const found = await findArchiveOrgMirrors(youtubeId, { client: deps.archive, duration: facts.duration, ...sig }); + const m = found.mirrors.find((x) => !failedUrls.has(x.url)); 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})` }); + rec.tried.push({ + from: "archive.org", + found: true, + url: m.url, + detail: `${m.identifier}: ${m.file} (${m.source}; ${m.namedBy} names the id${m.seconds !== undefined ? `; ${Math.round(m.seconds)} s` : ""})`, + }); } else { + const failed = found.mirrors.length; 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", + detail: [ + found.found ? `${found.found} item(s), none a usable mirror` : "no item names the id", + ...(failed ? [`${failed} mirror(s) failed before`] : []), + ...found.skipped.map((s) => `${s.identifier}: ${s.why}`), + ].join("; "), }); } } 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; + lookupFailed("archive.org", e); } - } else { - rec.tried.push({ from: "archive.org", found: false, detail: "no YouTube id to search for" }); } } + if (signal?.aborted) break; if (rec.copy) { rec.outcome = "fetch"; for (const w of r.windows) { @@ -357,8 +472,8 @@ export async function findCopies(opts: { } 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"}`, + rec.tried.map(describeAttempt).join("; ") + + ` → ${rec.outcome === "fetch" ? `fetch from the ${rec.copy!.from === "wayback" ? "Wayback copy" : "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`; @@ -366,12 +481,16 @@ export async function findCopies(opts: { break; } } + if (signal?.aborted) { + result.stopped = "cancelled; the rest are left for a later run"; + log(`find-copy: ${result.stopped}.`); + } 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. +// find-copy, whole: the lookups, then (unless `dryRun`, or the run was +// cancelled) 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; @@ -382,6 +501,6 @@ export async function runFindCopy<T>(opts: { startFetch: (items: FetchWindowsItem[]) => Promise<T>; }): Promise<FindCopyResult & { fetch?: T }> { const found = await findCopies(opts); - if (opts.dryRun || found.items.length === 0) return found; + if (opts.dryRun || opts.signal?.aborted || found.items.length === 0) return found; return { ...found, fetch: await opts.startFetch(found.items) }; } diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts @@ -1,6 +1,7 @@ export type FakeWaybackCapture = { original: string; timestamp: string; statuscode: string; mimetype?: string }; export const CAPTURES: FakeWaybackCapture[]; +export const VIDEOS: string[]; export type FakeWayback = { base: string; @@ -9,4 +10,4 @@ export type FakeWayback = { close(): Promise<void>; }; -export function startFakeWayback(opts?: { captures?: FakeWaybackCapture[]; busyTimes?: number; downTimes?: number }): Promise<FakeWayback>; +export function startFakeWayback(opts?: { captures?: FakeWaybackCapture[]; videos?: string[]; busyTimes?: number; downTimes?: number }): Promise<FakeWayback>; diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs @@ -14,6 +14,10 @@ // then one row per capture of <u> (oldest first); no captures: `[]` (the real API's empty answer) // without output=json: the same rows space-separated, one per line // GET /web/<timestamp>[id_|if_]/<original> the capture (text/html), 404 for an unknown one +// GET /__wb/videoinfo?vtype=youtube&vid=<id> (release 29 review) what yt-dlp's +// YoutubeWebArchive extractor asks: `{formats: [...]}` for an id in +// opts.videos (default VIDEOS), `{}` for any other — the video itself +// archived, not only its watch page // opts.busyTimes: the first N CDX requests answer 429 (Retry-After: 1); opts.downTimes: then 503s. import http from "node:http"; @@ -37,8 +41,12 @@ const urlkey = (u) => { } }; +// YouTube ids whose video (not only its page) the fake archive holds. +export const VIDEOS = ["gone-video-05"]; + export async function startFakeWayback(opts = {}) { const captures = opts.captures ?? CAPTURES; + const videos = opts.videos ?? VIDEOS; const requests = []; let busy = opts.busyTimes ?? 0; let down = opts.downTimes ?? 0; @@ -71,6 +79,13 @@ export async function startFakeWayback(opts = {}) { if (u.searchParams.get("output") === "json") return send(200, "application/json", JSON.stringify(rows.length ? [HEADER, ...rows] : [])); return send(200, "text/plain", rows.map((r) => r.join(" ")).join("\n") + (rows.length ? "\n" : "")); } + if (u.pathname === "/__wb/videoinfo") { + const vid = u.searchParams.get("vid") ?? ""; + const body = videos.includes(vid) + ? { formats: [{ url: `https://rr1---sn-fake.googlevideo.com/videoplayback?itag=18&id=${vid}`, ext: "mp4" }] } + : {}; + return send(200, "application/json", JSON.stringify(body)); + } const m = /^\/web\/(\d{14})(?:id_|if_)?\/(.+)$/.exec(u.pathname + u.search); if (m) { const c = captures.find((x) => x.timestamp === m[1] && x.original === m[2]);