commit bfe6522daeae596d08f42489bca7833827b32dbc
parent 49c7c02ccd62715d532f6d7023415e8921594c50
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 16 Oct 2026 01:48:33 -0400
common: find-copy's scope mode — every gone video of a channel or a site with no media (and no transcript, or all) looked for the article mode's way (lookForCopy, shared), at most max per run, none-found recorded; fetch-copies brings each copy's WHOLE audio into the video's own record (audio.<fmt>, tiered; metadata untouched; wayback.json / archiveorg.json; paced as archive.org); copy-attempts.json gains attempts (fetched | none-found | failed) under the file's lock, a terminal one keeping a video out 30 days; archive.org refresh skips a record that is not archive.org's; tests over the fakes and a synthetic corpus, the snapshot moving the audio to the transcription lane
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
12 files changed, 1733 insertions(+), 84 deletions(-)
diff --git a/common/controller/archiveOrgRefresh.test.ts b/common/controller/archiveOrgRefresh.test.ts
@@ -165,3 +165,20 @@ test("refresh: an unknown channel is refused", async () => {
await assert.rejects(refreshArchiveOrgRecords({ paths, slug: "no-such-channel" }), /not found/);
});
});
+
+// Release 31 (lane C): a gone YouTube video whose AUDIO came from an
+// archive.org mirror carries the mirror's archiveorg.json — but it is the
+// original's record, and its title and date are never the mirror's.
+test("refresh: a record that is not archive.org's own (its audio from an archive.org copy) is left alone", async () => {
+ await withCorpus(async (paths, dataDir) => {
+ const id = "Pqr678stu_4";
+ await mkdir(path.join(dataDir, id), { recursive: true });
+ await writeFile(path.join(dataDir, id, "archiveorg.json"), JSON.stringify(oldProvenance(RAW)));
+ const info = JSON.stringify({ id, extractor_key: "Youtube", title: "The original's own title", upload_date: "20200101", webpage_url: `https://www.youtube.com/watch?v=${id}` });
+ await writeFile(path.join(dataDir, id, "metadata.info.json"), info);
+ const r = await refreshArchiveOrgRecords({ paths, slug: SLUG });
+ assert.equal(r.fileRecords, 3, "the three archive.org file records, not the YouTube one");
+ assert.ok(!r.changed.some((c) => c.id === id));
+ assert.equal(await readFile(path.join(dataDir, id, "metadata.info.json"), "utf8"), info);
+ });
+});
diff --git a/common/controller/archiveOrgRefresh.ts b/common/controller/archiveOrgRefresh.ts
@@ -23,6 +23,7 @@ import path from "node:path";
import { getPaths, type Paths } from "../lib/paths";
import { readJsonFile } from "../lib/jsonFile-server";
import { assertChannelTextReadable } from "../lib/channelMedia";
+import { detectPlatform } from "../lib/platform";
import { archiveOrgMetadataPatch, withFileNameFields } from "../lib/archiveOrg";
import { loadArchiveOrgProvenance, writeArchiveOrgProvenance } from "../lib/archiveOrg-server";
import { patchMetadataInfo } from "../lib/metadataHistory-server";
@@ -46,6 +47,14 @@ export type ArchiveOrgRefreshResult = {
failed: { id: string; error: string }[];
};
+// archive.org's own record: yt-dlp's (or the import's) extractor is
+// `ArchiveOrg`, or its page is an archive.org page.
+export function isArchiveOrgRecordInfo(info: Record<string, unknown>): boolean {
+ const key = String(info.extractor_key ?? info.extractor ?? "");
+ if (/^archive\.?org$/i.test(key)) return true;
+ return typeof info.webpage_url === "string" && detectPlatform(info.webpage_url) === "archiveorg";
+}
+
export async function refreshArchiveOrgRecords(opts: {
slug: string;
paths?: Paths;
@@ -65,6 +74,15 @@ export async function refreshArchiveOrgRecords(opts: {
const videoDir = path.join(dataDir, id);
const prov = await loadArchiveOrgProvenance(videoDir);
if (!prov?.file) continue;
+ const read = await readJsonFile(path.join(videoDir, "metadata.info.json"));
+ const info =
+ read.ok && read.value && typeof read.value === "object" && !Array.isArray(read.value)
+ ? (read.value as Record<string, unknown>)
+ : null;
+ // A record that is not archive.org's own — a gone YouTube video whose
+ // AUDIO came from an archive.org copy (release 31, fetch-copies) — keeps
+ // its original's metadata: nothing here is about it.
+ if (info && !isArchiveOrgRecordInfo(info)) continue;
result.fileRecords++;
try {
const next = withFileNameFields(prov);
@@ -72,11 +90,6 @@ export async function refreshArchiveOrgRecords(opts: {
result.sidecars++;
if (!opts.dryRun) await writeArchiveOrgProvenance(videoDir, next);
}
- const read = await readJsonFile(path.join(videoDir, "metadata.info.json"));
- const info =
- read.ok && read.value && typeof read.value === "object" && !Array.isArray(read.value)
- ? (read.value as Record<string, unknown>)
- : null;
if (!info) continue;
const full = archiveOrgMetadataPatch(next, info);
const patch: Record<string, unknown> = {};
diff --git a/common/controller/fetchCopies.test.ts b/common/controller/fetchCopies.test.ts
@@ -0,0 +1,223 @@
+// fetch-copies (release 31, lane C): each gone video's whole audio from the
+// copy find-copy found, into its own record — the copy's provenance and a
+// `fetched` attempt written, a source-side failure recorded (never ours), a
+// rate limit stopping the run with the backoff recorded, a video that holds
+// media by its turn skipped, the gap between fetches — and the transcription
+// lane then sees the audio: the snapshot moves the video from noTranscript
+// (where a gone video's download never comes) to downloadedNoTranscript.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchCopies.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { ClipCopy } from "../lib/clipWindow";
+import { loadCopyAttempts } from "../lib/copyAttempts-server";
+import { loadArchiveOrgProvenance } from "../lib/archiveOrg-server";
+import { ArchiveOrgClient } from "../lib/archiveOrgClient";
+import { GONE_AVAILABILITY } from "../testing/draft/corpus.mjs";
+import { startFakeArchiveOrg } from "../testing/archiveOrg/fakeArchiveOrg.mjs";
+import { FetchWindowError } from "../ytdlp/fetchWindowManaged";
+import type { FetchCopyOpts } from "../ytdlp/fetchCopyManaged";
+import { copyAttemptFields, fetchCopies, writeCopyProvenance, type FetchCopiesDeps, type FetchCopyItem } from "./fetchCopies";
+import { generateChannelSnapshot } from "./channelSnapshot";
+
+const SLUG = "alpha";
+const GONE_A = "goneAAAAAA1";
+const GONE_B = "goneBBBBBB2";
+const GONE_C = "goneCCCCCC3";
+const watch = (id: string) => `https://www.youtube.com/watch?v=${id}`;
+const wayback = (id: string): ClipCopy => ({ from: "wayback", url: `https://web.archive.org/web/20240102030405/${watch(id)}` });
+const mirror = (id: string): ClipCopy => ({ from: "archive.org", url: `https://archive.org/download/youtube-${id}/An%20upload-${id}.mp4` });
+
+async function corpus() {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "fetch-copies-"));
+ const paths = {
+ channelsDir: path.join(dir, "channels"),
+ transcriptsDir: dir,
+ savedVideosDir: path.join(dir, "saved-videos"),
+ ytdlpBin: "/nonexistent/yt-dlp",
+ } as Paths;
+ const channelDir = path.join(paths.channelsDir, SLUG);
+ await mkdir(path.join(channelDir, "data"), { recursive: true });
+ await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "youtube", url: "https://www.youtube.com/@alpha/videos", audioFormat: "mp3" }));
+ await writeFile(path.join(channelDir, "playlist"), [GONE_A, GONE_B, GONE_C].map(watch).join("\n"));
+ for (const id of [GONE_A, GONE_B, GONE_C]) {
+ const v = path.join(channelDir, "data", id);
+ await mkdir(v, { recursive: true });
+ await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id, title: `Original ${id}`, webpage_url: watch(id), duration: 300, extractor_key: "Youtube" }));
+ await writeFile(path.join(v, "availability.json"), JSON.stringify({ ...GONE_AVAILABILITY, webpageUrl: watch(id) }));
+ }
+ return { dir, paths, dataDir: path.join(channelDir, "data"), close: () => rm(dir, { recursive: true, force: true }) };
+}
+
+// A fetch that writes the audio (as fetchCopyManaged would), or fails as told.
+function fakeFetch(fail: Record<string, Error> = {}) {
+ const calls: FetchCopyOpts[] = [];
+ return {
+ calls,
+ fetchCopy: async (o: FetchCopyOpts) => {
+ calls.push(o);
+ const e = fail[o.videoId];
+ if (e) throw e;
+ await writeFile(path.join(o.videoDir, "audio.mp3"), "audio");
+ return { audioFile: "audio.mp3", bytes: 5, args: [] };
+ },
+ };
+}
+
+function deps(over: Partial<FetchCopiesDeps> = {}) {
+ const events: string[] = [];
+ const d: Partial<FetchCopiesDeps> = {
+ assertMediaReachable: async () => undefined,
+ sleep: async (ms) => void events.push(`sleep ${ms}`),
+ cooldownRemainingMs: async () => 0,
+ heldRefusal: async () => null,
+ recordBackoff: async (p, _paths, cls) => void events.push(`backoff ${p} ${cls}`),
+ recordClean: async () => null,
+ // Wayback's sidecar is built from the URL alone (no request); archive.org's
+ // would ask the item — the test's own fake is given where it is needed.
+ writeProvenance: async (dir, copy, o) => (copy.from === "wayback" ? writeCopyProvenance(dir, copy, o) : undefined),
+ now: () => new Date("2026-10-16T00:00:00.000Z"),
+ ...over,
+ };
+ return { d, events };
+}
+
+test("each copy's audio into its own record: wayback.json, a fetched attempt, the original's metadata kept; the gap between fetches", async () => {
+ const c = await corpus();
+ try {
+ const f = fakeFetch();
+ const { d, events } = deps({ fetchCopy: f.fetchCopy });
+ const items: FetchCopyItem[] = [
+ { slug: SLUG, id: GONE_A, copy: wayback(GONE_A) },
+ { slug: SLUG, id: GONE_B, copy: wayback(GONE_B) },
+ { slug: SLUG, id: GONE_A, copy: mirror(GONE_A) }, // the same recording again: dropped
+ ];
+ const r = await fetchCopies({ paths: c.paths, items, gapMs: 1234, deps: d });
+ assert.deepEqual(r.fetched.map((x) => x.id), [GONE_A, GONE_B]);
+ assert.deepEqual(events, ["sleep 1234"], "one gap, between the two fetches");
+ const dirA = path.join(c.dataDir, GONE_A);
+ assert.equal(f.calls[0]!.videoDir, dirA, "the ORIGINAL record's dir");
+ const wb = JSON.parse(await readFile(path.join(dirA, "wayback.json"), "utf8"));
+ assert.equal(wb.originalUrl, watch(GONE_A));
+ assert.equal(wb.captureTs, "20240102030405");
+ const attempts = (await loadCopyAttempts(dirA))?.attempts ?? [];
+ assert.deepEqual(attempts.map((a) => [a.outcome, a.source, a.captureTs, a.audioFile]), [["fetched", "wayback", "20240102030405", "audio.mp3"]]);
+ assert.equal(JSON.parse(await readFile(path.join(dirA, "metadata.info.json"), "utf8")).title, `Original ${GONE_A}`);
+ } finally {
+ await c.close();
+ }
+});
+
+test("archive.org copy: archiveorg.json from the item (the fake), the attempt names its identifier and file", async () => {
+ const c = await corpus();
+ const ia = await startFakeArchiveOrg({
+ items: [
+ {
+ metadata: { identifier: `youtube-${GONE_C}`, title: `An upload ${GONE_C}`, mediatype: "movies", originalurl: watch(GONE_C) },
+ files: [{ name: `An upload-${GONE_C}.mp4`, source: "original", format: "MPEG4", size: "3000", length: "300" }],
+ },
+ ],
+ });
+ try {
+ const client = new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 });
+ const f = fakeFetch();
+ const { d } = deps({ fetchCopy: f.fetchCopy, writeProvenance: (dir, copy, o) => writeCopyProvenance(dir, copy, { ...o, client }) });
+ const r = await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_C, copy: mirror(GONE_C) }], deps: d });
+ assert.equal(r.fetched.length, 1);
+ const dir = path.join(c.dataDir, GONE_C);
+ const prov = await loadArchiveOrgProvenance(dir);
+ assert.equal(prov?.identifier, `youtube-${GONE_C}`);
+ assert.equal(prov?.file, `An upload-${GONE_C}.mp4`);
+ const a = (await loadCopyAttempts(dir))?.attempts?.[0];
+ assert.deepEqual([a?.outcome, a?.source, a?.identifier, a?.file], ["fetched", "archive.org", `youtube-${GONE_C}`, `An upload-${GONE_C}.mp4`]);
+ assert.equal(JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8")).title, `Original ${GONE_C}`, "the metadata is not the mirror's");
+ } finally {
+ await ia.close();
+ await c.close();
+ }
+});
+
+test("a copy that failed at its source is recorded (failed + attempt); our own failure is not; a 429 stops the run and backs archive.org off", async () => {
+ const c = await corpus();
+ try {
+ const f = fakeFetch({
+ [GONE_A]: new FetchWindowError("ERROR: HTTP Error 404: Not Found", "unknown", "error"),
+ [GONE_B]: new FetchWindowError("ERROR: ffmpeg exited with code 1", "unknown", "error"),
+ [GONE_C]: new FetchWindowError("ERROR: HTTP Error 429: Too Many Requests", "rate_limit", "error"),
+ });
+ const { d, events } = deps({ fetchCopy: f.fetchCopy });
+ const items = [GONE_A, GONE_B, GONE_C].map((id) => ({ slug: SLUG, id, copy: wayback(id) }));
+ const r = await fetchCopies({ paths: c.paths, items: [...items, { slug: SLUG, id: "afterStop01", copy: wayback("afterStop01") }], gapMs: 0, deps: d });
+ assert.deepEqual(r.failed.map((x) => [x.item.id, x.class]), [[GONE_A, "unknown"], [GONE_B, "unknown"], [GONE_C, "rate_limit"]]);
+ assert.equal(r.stopped, "rate-limit");
+ assert.deepEqual(r.notAttempted.map((x) => x.id), ["afterStop01"]);
+ assert.ok(events.includes("backoff archiveorg rate_limit"));
+ const a = await loadCopyAttempts(path.join(c.dataDir, GONE_A));
+ assert.deepEqual(a?.failed.map((x) => x.url), [wayback(GONE_A).url]);
+ assert.deepEqual(a?.attempts?.map((x) => x.outcome), ["failed"]);
+ assert.equal(await loadCopyAttempts(path.join(c.dataDir, GONE_B)), null, "ffmpeg is ours: nothing held against the copy");
+ assert.equal(await loadCopyAttempts(path.join(c.dataDir, GONE_C)), null, "a rate limit says nothing about the copy");
+ } finally {
+ await c.close();
+ }
+});
+
+test("a video holding media by its turn is skipped; an unreachable channel fails its items; a cooldown stops before any request", async () => {
+ const c = await corpus();
+ try {
+ await writeFile(path.join(c.dataDir, GONE_A, "source-media.mp4"), "x");
+ const f = fakeFetch();
+ const r1 = await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_A, copy: wayback(GONE_A) }], deps: deps({ fetchCopy: f.fetchCopy }).d });
+ assert.deepEqual(r1.skipped.map((s) => s.id), [GONE_A]);
+ const r2 = await fetchCopies({
+ paths: c.paths,
+ items: [{ slug: SLUG, id: GONE_B, copy: wayback(GONE_B) }],
+ deps: deps({ fetchCopy: f.fetchCopy, assertMediaReachable: async () => Promise.reject(new Error("the drive is not mounted")) }).d,
+ });
+ assert.deepEqual(r2.failed.map((x) => x.class), ["unreachable"]);
+ const r3 = await fetchCopies({
+ paths: c.paths,
+ items: [{ slug: SLUG, id: GONE_B, copy: wayback(GONE_B) }],
+ deps: deps({ fetchCopy: f.fetchCopy, cooldownRemainingMs: async () => 60_000 }).d,
+ });
+ assert.equal(r3.stopped, "cooldown");
+ assert.equal(f.calls.length, 0, "nothing was fetched");
+ } finally {
+ await c.close();
+ }
+});
+
+test("copyAttemptFields: an archive.org copy's item and file, a Wayback copy's capture", () => {
+ assert.deepEqual(copyAttemptFields(mirror("x0000000001")), {
+ source: "archive.org",
+ url: mirror("x0000000001").url,
+ identifier: "youtube-x0000000001",
+ file: "An upload-x0000000001.mp4",
+ });
+ assert.equal(copyAttemptFields(wayback("x0000000001")).captureTs, "20240102030405");
+ assert.equal(copyAttemptFields({ from: "wayback", url: `https://web.archive.org/web/${watch("x")}` }).captureTs, undefined);
+});
+
+test("the transcription lane picks the audio up: the snapshot moves a gone video from noTranscript to downloadedNoTranscript", async () => {
+ const c = await corpus();
+ try {
+ const before = await generateChannelSnapshot(c.paths, SLUG);
+ assert.ok(before.buckets.noTranscript.includes(GONE_A));
+ assert.ok(before.excludedFromDownload?.deleted.includes(GONE_A), "gone: out of the download lane");
+ assert.ok(!before.undownloadedIds.includes(GONE_A));
+ const f = fakeFetch();
+ await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_A, copy: wayback(GONE_A) }], deps: deps({ fetchCopy: f.fetchCopy }).d });
+ const after = await generateChannelSnapshot(c.paths, SLUG);
+ assert.ok(!after.buckets.noTranscript.includes(GONE_A));
+ assert.ok(after.buckets.downloadedNoTranscript.includes(GONE_A), "the transcription lane's first bucket");
+ assert.ok(after.backfill?.transcription?.ids.includes(GONE_A), "and its work list");
+ assert.ok(after.excludedFromDownload?.deleted.includes(GONE_A), "still gone on its platform");
+ } finally {
+ await c.close();
+ }
+});
diff --git a/common/controller/fetchCopies.ts b/common/controller/fetchCopies.ts
@@ -0,0 +1,359 @@
+// FETCH THE WHOLE AUDIO OF GONE VIDEOS FROM THEIR COPIES, AS ONE PACED JOB
+// (release 31, lane C; the `fetch-copies` kind).
+//
+// find-copy's scope mode (publish/findCopy.ts findWholeCopies) found a copy of
+// each gone video — the Wayback Machine holding it, or an archive.org mirror
+// of it — and hands the list here. Each item goes through fetchCopyManaged
+// (ytdlp/fetchCopyManaged.ts) into its ORIGINAL record's `audio.<fmt>`, one at
+// a time, and then:
+//
+// wayback.json / archiveorg.json the copy's provenance, through the
+// existing writers (lib/wayback-server.ts ensureWaybackProvenance — from
+// the URL alone; lib/archiveOrg-server.ts
+// ensureArchiveOrgProvenanceSidecar — the item's metadata, cached).
+// metadata.info.json is NOT touched: the record stays the original's.
+// copy-attempts.json a `fetched` attempt (what the video page's "Audio
+// from a copy" line reads), or a `failed` one when the copy failed at its
+// source (lib/copyAttempts-server.ts isSourceSideCopyFailure; also in
+// `failed`, so no find-copy picks that copy again).
+//
+// PACED: archive.org serves both kinds of copy, so the run is paced as the
+// `archiveorg` platform — its hold and cooldown asked before every fetch, a 429
+// recorded against it and the run stopped, a success recorded clean — and
+// WHOLE_COPY_MIN_GAP_SECONDS lies between two fetches. A whole file is one
+// long request, never a burst.
+//
+// A JOB OF THIS KIND SPANS CHANNELS, so runManagedFunction's media guard has
+// no channel to ask; each channel's media reachability (it WRITES audio) is
+// asked here, once, before its first item.
+
+import path from "node:path";
+import { readdir } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { ClipCopy } from "../lib/clipWindow";
+import type { JobProgress } from "../jobs/registry";
+import { parseArchiveOrgUrl } from "../lib/archiveOrgId";
+import { parseWaybackUrl } from "../lib/wayback";
+import { ensureWaybackProvenance } from "../lib/wayback-server";
+import { ensureArchiveOrgProvenanceSidecar } from "../lib/archiveOrg-server";
+import type { ArchiveOrgClient } from "../lib/archiveOrgClient";
+import { assertChannelMediaReachable } from "../lib/channelMedia";
+import {
+ isSourceSideCopyFailure,
+ recordCopyAttempt,
+ recordFailedCopy,
+ type CopyAttempt,
+ type FailedCopy,
+} from "../lib/copyAttempts-server";
+import { channelConfigPlatform } from "../lib/videoId";
+import { resolveVideoDirId } from "../lib/videoDir-server.mjs";
+import {
+ heldPlatformRefusal,
+ platformCooldownRemainingMs,
+ recordDownloadBackoff,
+ recordPlatformClean,
+} from "../jobs/downloadBackoff";
+import { FetchWindowError } from "../ytdlp/fetchWindowManaged";
+import { fetchCopyManaged, holdsMedia, type FetchCopyOpts, type FetchCopyResult } from "../ytdlp/fetchCopyManaged";
+import { readChannelConfig } from "./channels";
+
+// The least time between two whole-copy fetches.
+export const WHOLE_COPY_MIN_GAP_SECONDS = 30;
+
+// The platform a copy's fetch is paced and backed off as.
+export const COPY_PLATFORM = "archiveorg";
+
+export type FetchCopyItem = {
+ slug: string;
+ id: string;
+ copy: ClipCopy;
+};
+
+export type FetchCopiesFailure = { item: FetchCopyItem; class: string; message: string };
+
+export type FetchCopiesResult = {
+ fetched: (FetchCopyItem & { audioFile: string; bytes: number })[];
+ // Already holding audio or video when its turn came: nothing fetched.
+ skipped: (FetchCopyItem & { why: string })[];
+ failed: FetchCopiesFailure[];
+ notAttempted: FetchCopyItem[];
+ stopped?: "rate-limit" | "cooldown" | "held" | "drain" | "cancel";
+};
+
+export type FetchCopiesDeps = {
+ fetchCopy: (opts: FetchCopyOpts) => Promise<FetchCopyResult>;
+ readChannelConfig: (paths: Paths, slug: string) => Promise<ChannelConfig | null>;
+ assertMediaReachable: (paths: Paths, slug: string) => Promise<unknown>;
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
+ cooldownRemainingMs: (platform: string, paths: Paths) => Promise<number>;
+ heldRefusal: (platform: string, paths: Paths) => Promise<string | null>;
+ recordBackoff: (platform: string, paths: Paths, failureClass: "rate_limit" | "network") => Promise<void>;
+ recordClean: (platform: string, paths: Paths) => Promise<string | null>;
+ recordFailedCopy: (videoDir: string, failed: FailedCopy) => Promise<void>;
+ recordCopyAttempt: (videoDir: string, attempt: CopyAttempt) => Promise<void>;
+ // The copy's provenance sidecar (wayback.json / archiveorg.json).
+ writeProvenance: (videoDir: string, copy: ClipCopy, o: { onLog: (s: string) => void; signal: AbortSignal }) => Promise<void>;
+ now: () => Date;
+};
+
+function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
+ if (ms <= 0 || signal?.aborted) return Promise.resolve();
+ return new Promise((resolve) => {
+ const onAbort = () => {
+ clearTimeout(t);
+ resolve();
+ };
+ const t = setTimeout(() => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve();
+ }, ms);
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
+// wayback.json from the capture URL (none when the URL names no capture
+// timestamp); archiveorg.json from the item (cached by the client).
+export async function writeCopyProvenance(
+ videoDir: string,
+ copy: ClipCopy,
+ o: { onLog: (s: string) => void; signal: AbortSignal; client?: ArchiveOrgClient },
+): Promise<void> {
+ if (copy.from === "wayback") {
+ await ensureWaybackProvenance(videoDir, copy.url, { onLog: o.onLog });
+ return;
+ }
+ const ref = parseArchiveOrgUrl(copy.url);
+ if (ref) {
+ await ensureArchiveOrgProvenanceSidecar(videoDir, ref, {
+ onLog: o.onLog,
+ signal: o.signal,
+ ...(o.client ? { client: o.client } : {}),
+ });
+ }
+}
+
+const DEFAULT_DEPS: FetchCopiesDeps = {
+ fetchCopy: fetchCopyManaged,
+ readChannelConfig,
+ assertMediaReachable: (paths, slug) => assertChannelMediaReachable(paths, slug),
+ sleep: abortableSleep,
+ cooldownRemainingMs: (platform, paths) => platformCooldownRemainingMs(platform, paths),
+ heldRefusal: (platform, paths) => heldPlatformRefusal(platform, "This batch", paths),
+ recordBackoff: (platform, paths, cls) => recordDownloadBackoff(platform, paths, cls),
+ recordClean: (platform, paths) => recordPlatformClean(platform, paths),
+ recordFailedCopy,
+ recordCopyAttempt,
+ writeProvenance: writeCopyProvenance,
+ now: () => new Date(),
+};
+
+// What a copy attempt names of its copy: the archive.org item and file, the
+// Wayback capture's timestamp.
+export function copyAttemptFields(copy: ClipCopy): Pick<CopyAttempt, "source" | "url" | "identifier" | "file" | "captureTs"> {
+ const out: Pick<CopyAttempt, "source" | "url" | "identifier" | "file" | "captureTs"> = { source: copy.from, url: copy.url };
+ if (copy.from === "archive.org") {
+ const ref = parseArchiveOrgUrl(copy.url);
+ if (ref?.identifier) out.identifier = ref.identifier;
+ if (ref?.file) out.file = ref.file;
+ } else {
+ const ts = parseWaybackUrl(copy.url)?.captureTs;
+ if (ts) out.captureTs = ts;
+ }
+ return out;
+}
+
+export const fetchCopyItemLabel = (item: FetchCopyItem) => `${item.slug}/${item.id} (${item.copy.from})`;
+
+export async function fetchCopies({
+ paths,
+ items,
+ gapMs,
+ onLog,
+ signal,
+ drainSignal,
+ setProgress,
+ deps: depsOverride,
+}: {
+ paths: Paths;
+ items: FetchCopyItem[];
+ // The pause between two fetches; absent = WHOLE_COPY_MIN_GAP_SECONDS.
+ gapMs?: number;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+ drainSignal?: AbortSignal;
+ setProgress?: (snap: JobProgress) => void;
+ deps?: Partial<FetchCopiesDeps>;
+}): Promise<FetchCopiesResult> {
+ const deps: FetchCopiesDeps = { ...DEFAULT_DEPS, ...depsOverride };
+ const log = (line: string) => onLog?.(line.endsWith("\n") ? line : `${line}\n`);
+ const fetchLog = (line: string) => onLog?.(line);
+ const fetchSignal = signal ?? new AbortController().signal;
+ const gap = gapMs ?? WHOLE_COPY_MIN_GAP_SECONDS * 1000;
+ // One item per recording: the first ask wins.
+ const seen = new Set<string>();
+ const work = items.filter((i) => {
+ const k = `${i.slug}\0${i.id}`;
+ if (seen.has(k)) return false;
+ seen.add(k);
+ return true;
+ });
+ const result: FetchCopiesResult = { fetched: [], skipped: [], failed: [], notAttempted: [] };
+ log(`Fetch copies: ${work.length} gone video(s), each one's whole audio from its copy.`);
+ let done = 0;
+ const progress = () => setProgress?.({ metric: "downloads", initial: 0, target: work.length, current: done });
+ progress();
+
+ const configs = new Map<string, ChannelConfig | null>();
+ const reachable = new Map<string, string | null>();
+ const fail = (item: FetchCopyItem, cls: string, message: string) => {
+ result.failed.push({ item, class: cls, message });
+ log(` ✗ ${fetchCopyItemLabel(item)}: ${cls} — ${message}`);
+ };
+ const interrupted = (): FetchCopiesResult["stopped"] | null =>
+ signal?.aborted ? "cancel" : drainSignal?.aborted ? "drain" : null;
+ const stop = (why: NonNullable<FetchCopiesResult["stopped"]>, from: number) => {
+ result.stopped = why;
+ result.notAttempted.push(...work.slice(from));
+ };
+ let networkAttempts = 0;
+
+ for (let i = 0; i < work.length; i++) {
+ const item = work[i]!;
+ const why = interrupted();
+ if (why) {
+ stop(why, i);
+ break;
+ }
+ const label = fetchCopyItemLabel(item);
+ if (!configs.has(item.slug)) configs.set(item.slug, await deps.readChannelConfig(paths, item.slug).catch(() => null));
+ const config = configs.get(item.slug) ?? null;
+ if (!config) {
+ fail(item, "unknown-channel", `no channel "${item.slug}"`);
+ done++;
+ progress();
+ continue;
+ }
+ if (!reachable.has(item.slug)) {
+ reachable.set(
+ item.slug,
+ await deps.assertMediaReachable(paths, item.slug).then(
+ () => null,
+ (e: unknown) => (e as Error).message,
+ ),
+ );
+ }
+ const unreachable = reachable.get(item.slug);
+ if (unreachable) {
+ fail(item, "unreachable", unreachable);
+ done++;
+ progress();
+ continue;
+ }
+ const dirId = await resolveVideoDirId(paths.channelsDir, item.slug, item.id, { platform: channelConfigPlatform(config) });
+ const videoDir = path.join(paths.channelsDir, item.slug, "data", dirId);
+ const entries = await readdir(videoDir).catch(() => null);
+ if (!entries) {
+ fail(item, "no-record", `no directory for ${item.id}`);
+ done++;
+ progress();
+ continue;
+ }
+ if (holdsMedia(entries)) {
+ result.skipped.push({ ...item, why: "it already holds audio or video" });
+ log(` = ${label}: already holds audio or video; nothing fetched.`);
+ done++;
+ progress();
+ continue;
+ }
+
+ if (networkAttempts > 0 && gap > 0) {
+ log(`Sleeping ${Math.round(gap / 1000)}s before the next copy...`);
+ await deps.sleep(gap, signal);
+ const after = interrupted();
+ if (after) {
+ stop(after, i);
+ break;
+ }
+ }
+ const held = await deps.heldRefusal(COPY_PLATFORM, paths);
+ if (held) {
+ log(` ${label}: ${held} — stopping; the rest are left for a later run.`);
+ stop("held", i);
+ break;
+ }
+ const cooldownMs = await deps.cooldownRemainingMs(COPY_PLATFORM, paths);
+ if (cooldownMs > 0) {
+ log(
+ ` ${label}: archive.org is in a rate-limit cooldown (${Math.ceil(cooldownMs / 1000)}s remaining) — ` +
+ `stopping; the rest are left for a later run.`,
+ );
+ stop("cooldown", i);
+ break;
+ }
+
+ log(` ${label}: fetching ${item.copy.url}…`);
+ networkAttempts++;
+ try {
+ const r = await deps.fetchCopy({
+ paths,
+ channelConfig: config,
+ videoDir,
+ videoId: dirId,
+ copy: item.copy,
+ onLog: fetchLog,
+ signal: fetchSignal,
+ });
+ try {
+ await deps.writeProvenance(videoDir, item.copy, { onLog: fetchLog, signal: fetchSignal });
+ } catch (e) {
+ log(` ${label}: the copy's provenance was not written (${(e as Error).message}).`);
+ }
+ await deps
+ .recordCopyAttempt(videoDir, {
+ at: deps.now().toISOString(),
+ outcome: "fetched",
+ ...copyAttemptFields(item.copy),
+ audioFile: r.audioFile,
+ })
+ .catch((e: unknown) => log(` ${label}: copy-attempts.json not written (${(e as Error).message}).`));
+ result.fetched.push({ ...item, audioFile: r.audioFile, bytes: r.bytes });
+ const clean = await deps.recordClean(COPY_PLATFORM, paths).catch(() => null);
+ if (clean) log(clean);
+ } catch (e) {
+ const message = (e as Error).message;
+ const cls = e instanceof FetchWindowError ? e.failureClass : "unknown";
+ fail(item, cls, message);
+ if (cls === "rate_limit") {
+ await deps.recordBackoff(COPY_PLATFORM, paths, "rate_limit").catch(() => {});
+ log(` archive.org rate-limited this run — stopping; the rest are left for a later run.`);
+ done++;
+ progress();
+ stop("rate-limit", i + 1);
+ break;
+ }
+ // A COPY THAT FAILED AT ITS SOURCE is recorded, as fetch-windows records
+ // a window's: never picked again by find-copy (`failed`), and a terminal
+ // attempt for the scope mode. Our own side (the extraction, a disk) is
+ // not held against the copy.
+ if (!fetchSignal.aborted && isSourceSideCopyFailure(cls, message)) {
+ const at = deps.now().toISOString();
+ await deps.recordFailedCopy(videoDir, { ...item.copy, at, error: message }).catch(() => {});
+ await deps
+ .recordCopyAttempt(videoDir, { at, outcome: "failed", ...copyAttemptFields(item.copy), error: message })
+ .catch(() => {});
+ log(` ${label}: the ${item.copy.from} copy failed at its source — find-copy will not pick it again.`);
+ }
+ }
+ done++;
+ progress();
+ }
+
+ log(
+ `Fetch copies: ${result.fetched.length} fetched, ${result.skipped.length} already held media, ` +
+ `${result.failed.length} failed` +
+ (result.notAttempted.length ? `, ${result.notAttempted.length} not attempted (stopped: ${result.stopped})` : "") +
+ ".",
+ );
+ return result;
+}
diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts
@@ -103,6 +103,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = {
"bench-verdicts": { label: "Verdict bench", drainable: false },
// find-copy (release 29 E2): the lookups, then one fetch-windows job.
"find-copy": { label: "Find copies", drainable: false },
+ // fetch-copies (release 31): gone videos' whole audio from their copies.
+ "fetch-copies": { label: "Fetch copies", drainable: true },
};
test("added kinds carry their pinned label and drainability", () => {
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -972,6 +972,21 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
replayable: false,
queueKeyStrategy: "custom",
},
+ // fetch-copies (release 31, lane C): the WHOLE audio of gone videos from the
+ // copies find-copy's scope mode found (controller/fetchCopies.ts), each into
+ // its own record's audio.<fmt>, one at a time on archive.org's download
+ // queue. It writes audio (needsMedia); a list spanning channels starts with
+ // no channelSlug and the controller asks each channel's media guard.
+ // Drainable: it stops between videos, and a re-run skips any that hold
+ // media by then.
+ "fetch-copies": {
+ kind: "fetch-copies",
+ label: "Fetch copies",
+ drainable: true,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsMedia: true,
+ },
"bench-verdicts": {
kind: "bench-verdicts",
label: "Verdict bench",
@@ -1168,6 +1183,8 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([
"check-maybe-missing",
"attach-media",
"prepare-playable",
+ // A gone video's audio from a copy, and the copy's provenance (release 31).
+ "fetch-copies",
]);
export function isIngestKind(kind: string | undefined): boolean {
diff --git a/common/lib/copyAttempts-server.ts b/common/lib/copyAttempts-server.ts
@@ -5,29 +5,90 @@
// next (Wayback → archive.org → the next mirror). Written by fetch-windows
// (controller/fetchWindows.ts) on an item's failure; read by find-copy.
//
+// AND EVERY WHOLE-COPY ATTEMPT (release 31, lane C): find-copy's scope mode
+// (`{slug | siteId, gone}`) looks for a copy of a gone video's WHOLE audio and
+// fetch-copies brings it home into the record. Each run's answer for the video
+// is appended to `attempts`: `fetched` (the audio is the copy's — the video
+// page's "Audio from a copy" line reads it), `none-found` (neither Wayback nor
+// archive.org holds it) or `failed` (the copy's fetch failed at its source).
+// The last two are TERMINAL: the scope mode skips a video whose newest
+// terminal attempt is younger than COPY_ATTEMPT_RETRY_DAYS, unless
+// `retryFailed`. A lookup that errored (a rate limit, archive.org down) is not
+// an attempt and is never recorded.
+//
// SERVER-ONLY (node:fs).
-import { coerceClipCopy, type ClipCopy } from "./clipWindow";
+import { CLIP_COPY_SOURCES, coerceClipCopy, type ClipCopy } from "./clipWindow";
+import { withJsonFileLock } from "./jsonFile-server";
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.
+export const COPY_ATTEMPT_OUTCOMES = ["fetched", "none-found", "failed"] as const;
+export type CopyAttemptOutcome = (typeof COPY_ATTEMPT_OUTCOMES)[number];
+
+// One whole-copy attempt (release 31). `source`/`url` name the copy (absent
+// for none-found: every source was asked); an archive.org copy names its item
+// and file, a Wayback copy its capture's timestamp when the URL carries one.
+export type CopyAttempt = {
+ at: string;
+ outcome: CopyAttemptOutcome;
+ source?: ClipCopy["from"];
+ url?: string;
+ identifier?: string;
+ file?: string;
+ captureTs?: string;
+ // The audio file a fetch wrote (`audio.<fmt>`).
+ audioFile?: string;
+ // What was asked and found, in a phrase (none-found).
+ detail?: string;
+ error?: string;
+};
+
+export type CopyAttempts = { failed: FailedCopy[]; attempts?: CopyAttempt[] };
+
+// How long a terminal whole-copy attempt (none-found, failed) keeps a video
+// out of find-copy's scope mode: archives fill in slowly, and asking archive.org
+// about the same id every night is the scraper shape the clients exist to avoid.
+export const COPY_ATTEMPT_RETRY_DAYS = 30;
+
+// The newest few, one per URL; the newest few attempts.
const KEEP = 20;
+const optStr = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined);
+
+function coerceCopyAttempt(v: unknown): CopyAttempt | null {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return null;
+ const r = v as Record<string, unknown>;
+ if (typeof r.at !== "string" || !(COPY_ATTEMPT_OUTCOMES as readonly unknown[]).includes(r.outcome)) return null;
+ const out: CopyAttempt = { at: r.at, outcome: r.outcome as CopyAttemptOutcome };
+ if ((CLIP_COPY_SOURCES as readonly unknown[]).includes(r.source)) out.source = r.source as ClipCopy["from"];
+ const url = optStr(r.url);
+ if (url && /^https?:\/\//.test(url)) out.url = url;
+ for (const k of ["identifier", "file", "captureTs", "audioFile", "detail", "error"] as const) {
+ const x = optStr(r[k]);
+ if (x) out[k] = x;
+ }
+ return out;
+}
+
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 v = value as { failed?: unknown; attempts?: unknown } | null;
+ if (!v || typeof v !== "object") return null;
+ if (!Array.isArray(v.failed) && !Array.isArray(v.attempts)) return null;
const failed: FailedCopy[] = [];
- for (const f of v.failed) {
+ for (const f of Array.isArray(v.failed) ? 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 };
+ const out: CopyAttempts = { failed };
+ if (Array.isArray(v.attempts)) {
+ out.attempts = v.attempts.map(coerceCopyAttempt).filter((a): a is CopyAttempt => a !== null);
+ }
+ return out;
}
export const copyAttemptsSidecar = sidecar(COPY_ATTEMPTS_FILENAME, sidecarField(coerceCopyAttempts));
@@ -47,12 +108,53 @@ export function isSourceSideCopyFailure(failureClass: string | undefined, messag
);
}
+export async function loadCopyAttempts(videoDir: string): Promise<CopyAttempts | null> {
+ return copyAttemptsSidecar.load(videoDir).catch(() => null);
+}
+
export async function readFailedCopies(videoDir: string): Promise<FailedCopy[]> {
- return (await copyAttemptsSidecar.load(videoDir).catch(() => null))?.failed ?? [];
+ return (await loadCopyAttempts(videoDir))?.failed ?? [];
+}
+
+// Both writers read, change and write the file under its lock (fetch-windows
+// and fetch-copies may finish on one recording at once), and each keeps what
+// the other wrote.
+async function updateCopyAttempts(videoDir: string, fn: (prev: CopyAttempts) => CopyAttempts): Promise<void> {
+ await withJsonFileLock(copyAttemptsSidecar.path(videoDir), async () => {
+ const prev = (await loadCopyAttempts(videoDir)) ?? { failed: [] };
+ await copyAttemptsSidecar.write(videoDir, fn(prev));
+ });
}
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 });
+ await updateCopyAttempts(videoDir, (prev) => ({
+ ...prev,
+ failed: [...prev.failed.filter((f) => f.url !== failed.url), { ...failed, error: failed.error.slice(0, 400) }].slice(-KEEP),
+ }));
+}
+
+// Append one whole-copy attempt (release 31), the newest KEEP kept.
+export async function recordCopyAttempt(videoDir: string, attempt: CopyAttempt): Promise<void> {
+ const a: CopyAttempt = { ...attempt, ...(attempt.error ? { error: attempt.error.slice(0, 400) } : {}), ...(attempt.detail ? { detail: attempt.detail.slice(0, 400) } : {}) };
+ await updateCopyAttempts(videoDir, (prev) => ({ ...prev, attempts: [...(prev.attempts ?? []), a].slice(-KEEP) }));
+}
+
+// The newest attempt that brought the copy's audio home, or null.
+export function latestFetchedCopy(c: CopyAttempts | null | undefined): CopyAttempt | null {
+ return [...(c?.attempts ?? [])].reverse().find((a) => a.outcome === "fetched") ?? null;
+}
+
+// The newest attempt when it is TERMINAL (none-found, failed) and younger
+// than `days`, else null — what keeps a video out of find-copy's scope mode
+// for a while.
+export function recentTerminalAttempt(
+ c: CopyAttempts | null | undefined,
+ now: number = Date.now(),
+ days: number = COPY_ATTEMPT_RETRY_DAYS,
+): CopyAttempt | null {
+ const last = c?.attempts?.at(-1);
+ if (!last || last.outcome === "fetched") return null;
+ const at = Date.parse(last.at);
+ if (!Number.isFinite(at)) return null;
+ return now - at < days * 86_400_000 ? last : null;
}
diff --git a/common/lib/copyAttempts.test.ts b/common/lib/copyAttempts.test.ts
@@ -8,7 +8,19 @@ 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, isSourceSideCopyFailure, readFailedCopies, recordFailedCopy } from "./copyAttempts-server";
+import { readFile, writeFile } from "node:fs/promises";
+import {
+ COPY_ATTEMPTS_FILENAME,
+ COPY_ATTEMPT_RETRY_DAYS,
+ coerceCopyAttempts,
+ isSourceSideCopyFailure,
+ latestFetchedCopy,
+ loadCopyAttempts,
+ readFailedCopies,
+ recentTerminalAttempt,
+ recordCopyAttempt,
+ 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-"));
@@ -41,3 +53,47 @@ test("isSourceSideCopyFailure: the copy's 404/410/403 or unreachability, never o
assert.equal(isSourceSideCopyFailure("unknown", "ERROR: ffmpeg exited with code 1"), false);
assert.equal(isSourceSideCopyFailure("unknown", "No space left on device"), false);
});
+
+// Release 31 (lane C): the whole-copy attempts beside the failed copies.
+test("recordCopyAttempt and recordFailedCopy keep each other's entries; a file of the older shape still reads", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "copy-attempts-"));
+ try {
+ await writeFile(path.join(dir, COPY_ATTEMPTS_FILENAME), JSON.stringify({ failed: [{ from: "wayback", url: "https://web.archive.org/web/1/x", at: "1", error: "404" }] }));
+ assert.equal((await loadCopyAttempts(dir))?.attempts, undefined, "release 29's file: no attempts");
+ await recordCopyAttempt(dir, { at: "2026-10-01T00:00:00.000Z", outcome: "none-found", detail: "wayback none; archive.org none" });
+ await recordFailedCopy(dir, { from: "archive.org", url: "https://archive.org/download/a/b.mp4", at: "3", error: "403" });
+ await recordCopyAttempt(dir, {
+ at: "2026-10-02T00:00:00.000Z",
+ outcome: "fetched",
+ source: "archive.org",
+ url: "https://archive.org/download/a/c.mp4",
+ identifier: "a",
+ file: "c.mp4",
+ audioFile: "audio.mp3",
+ });
+ const c = await loadCopyAttempts(dir);
+ assert.deepEqual(c?.failed.map((f) => f.at), ["1", "3"]);
+ assert.deepEqual(c?.attempts?.map((a) => a.outcome), ["none-found", "fetched"]);
+ assert.equal(latestFetchedCopy(c)?.identifier, "a");
+ assert.equal(recentTerminalAttempt(c), null, "the newest attempt fetched: not terminal");
+ const raw = JSON.parse(await readFile(path.join(dir, COPY_ATTEMPTS_FILENAME), "utf8"));
+ assert.equal(raw.attempts.length, 2);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("recentTerminalAttempt: the newest attempt when none-found or failed and younger than the retry window", () => {
+ const now = Date.parse("2026-10-16T00:00:00.000Z");
+ const day = 86_400_000;
+ const at = (daysAgo: number) => new Date(now - daysAgo * day).toISOString();
+ const c = (outcome: "fetched" | "none-found" | "failed", daysAgo: number) =>
+ coerceCopyAttempts({ attempts: [{ at: at(daysAgo), outcome }] });
+ assert.equal(recentTerminalAttempt(c("none-found", 3), now)?.outcome, "none-found");
+ assert.equal(recentTerminalAttempt(c("failed", COPY_ATTEMPT_RETRY_DAYS - 1), now)?.outcome, "failed");
+ assert.equal(recentTerminalAttempt(c("none-found", COPY_ATTEMPT_RETRY_DAYS + 1), now), null, "old enough to ask again");
+ assert.equal(recentTerminalAttempt(c("fetched", 1), now), null);
+ assert.equal(recentTerminalAttempt(null, now), null);
+ assert.equal(coerceCopyAttempts({ attempts: [{ at: "x", outcome: "maybe" }] })?.attempts?.length, 0, "an unknown outcome is dropped");
+ assert.equal(coerceCopyAttempts({ nothing: true }), null);
+});
diff --git a/common/publish/findCopy.ts b/common/publish/findCopy.ts
@@ -48,7 +48,23 @@ 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 {
+ COPY_ATTEMPT_RETRY_DAYS,
+ loadCopyAttempts,
+ readFailedCopies,
+ recentTerminalAttempt,
+ recordCopyAttempt,
+ type CopyAttempt,
+ type CopyAttempts,
+ type FailedCopy,
+} from "../lib/copyAttempts-server";
+import { sourceGoneState } from "../lib/sourceGone-server";
+import { assertChannelTextReadable } from "../lib/channelMedia";
+import { isVideoTranscribed, readVideoFiles } from "../lib/videoStatus";
+import { getSite } from "../lib/site";
+import { listChannelVideoIds } from "../controller/keptVideos";
+import { holdsMedia } from "../ytdlp/fetchCopyManaged";
+import type { FetchCopyItem } from "../controller/fetchCopies";
import { archiveOrgClient, ArchiveOrgRequestError, type ArchiveOrgClient } from "../lib/archiveOrgClient";
import { archiveOrgDownloadUrl } from "../lib/archiveOrgId";
import { archiveOrgRestriction, searchArchiveOrgItems } from "../controller/archiveOrgImport";
@@ -354,6 +370,100 @@ const DEFAULT_DEPS: FindCopyDeps = {
const describeAttempt = (t: FindCopyAttempt) =>
`${t.from} ${t.found ? `found — ${t.detail}` : t.error ? `failed — ${t.error}` : `none — ${t.detail}`}`;
+// ONE RECORDING'S LOOKUP, shared by the article mode and the scope mode:
+// Wayback when it holds the video (and no fetch from it failed before), then
+// an archive.org mirror of the upload, of its length, not failed before. A
+// lookup archive.org kept refusing sets `refused` (the caller stops its run).
+// No YouTube id: nothing is asked.
+export type CopyLookup = {
+ tried: FindCopyAttempt[];
+ copy?: ClipCopy;
+ // The archive.org mirror the copy is (its item and file).
+ mirror?: ArchiveOrgMirror;
+ // The capture timestamp a Wayback copy is dated by.
+ captureTs?: string;
+ refused?: string;
+};
+
+export async function lookForCopy(o: {
+ youtubeId: string | null;
+ duration: number | null;
+ failedBefore: ClipCopy[];
+ retryFailed?: boolean;
+ deps: Pick<FindCopyDeps, "wayback" | "archive">;
+ signal?: AbortSignal;
+}): Promise<CopyLookup> {
+ const { youtubeId, deps, signal } = o;
+ const sig = signal ? { signal } : {};
+ const out: CopyLookup = { tried: [] };
+ const failedUrls = new Set(o.retryFailed ? [] : o.failedBefore.map((f) => f.url));
+ const lookupFailed = (from: ClipCopy["from"], e: unknown) => {
+ if (signal?.aborted) return;
+ out.tried.push({ from, found: false, error: (e as Error).message });
+ if (e instanceof ArchiveOrgRequestError && e.rateLimited) out.refused = (e as Error).message;
+ };
+ if (!youtubeId) {
+ out.tried.push({ from: "wayback", found: false, detail: "not a YouTube recording: no copy is looked for" });
+ return out;
+ }
+ // 1. The Wayback Machine — when it holds the video, and no fetch from it failed before.
+ if (!o.retryFailed && o.failedBefore.some((f) => f.from === "wayback")) {
+ out.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);
+ out.copy = { from: "wayback", url };
+ if (newest) out.captureTs = newest.timestamp;
+ out.tried.push({ from: "wayback", found: true, url, detail: `the video is archived${newest ? `; its page captured ${newest.timestamp}` : ""}` });
+ } else {
+ out.tried.push({ from: "wayback", found: false, detail: "the video is not archived (its page may be)" });
+ }
+ } catch (e) {
+ lookupFailed("wayback", e);
+ }
+ }
+
+ // 2. archive.org: a mirror OF the upload, of its length, not failed before.
+ if (!out.copy && !out.refused && !signal?.aborted) {
+ try {
+ const found = await findArchiveOrgMirrors(youtubeId, { client: deps.archive, duration: o.duration, ...sig });
+ const m = found.mirrors.find((x) => !failedUrls.has(x.url));
+ if (m) {
+ out.copy = { from: "archive.org", url: m.url };
+ out.mirror = m;
+ out.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;
+ out.tried.push({
+ from: "archive.org",
+ found: false,
+ 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) {
+ lookupFailed("archive.org", e);
+ }
+ }
+ return out;
+}
+
// 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).
@@ -370,7 +480,6 @@ export async function findCopies(opts: {
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) {
@@ -388,73 +497,12 @@ export async function findCopies(opts: {
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(opts.retryFailed ? [] : 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;
- };
-
- 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 (!opts.retryFailed && 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);
- }
- }
-
- // 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, 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}; ${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 usable mirror` : "no item names the id",
- ...(failed ? [`${failed} mirror(s) failed before`] : []),
- ...found.skipped.map((s) => `${s.identifier}: ${s.why}`),
- ].join("; "),
- });
- }
- } catch (e) {
- lookupFailed("archive.org", e);
- }
- }
- }
+ const look = await lookForCopy({ youtubeId, duration: facts.duration, failedBefore, retryFailed: opts.retryFailed, deps, signal });
+ rec.tried.push(...look.tried);
+ if (look.copy) rec.copy = look.copy;
+ const refused = look.refused;
if (signal?.aborted) break;
if (rec.copy) {
@@ -512,3 +560,327 @@ export async function runFindCopy<T>(opts: {
if (opts.dryRun || opts.signal?.aborted || found.items.length === 0) return found;
return { ...found, fetch: await opts.startFetch(found.items) };
}
+
+// ─── find-copy, scope mode: every gone video of a channel or a site (release 31) ───
+//
+// The article mode above fetches the cited WINDOWS of gone recordings. This
+// mode brings a gone video's WHOLE audio home into its own record, so the
+// transcription lane transcribes it like any other: `{slug | siteId, gone:
+// "no-transcript" | "all", dryRun?, max?, retryFailed?}`.
+//
+// THE CANDIDATES: every video dir of the channel (or of every channel in the
+// site's pool, `site.json` `channels`, in its order) that is gone by THE one
+// reading (lib/sourceGone-server.ts sourceGoneState: deleted or private), that
+// holds no audio or video yet (ytdlp/fetchCopyManaged.ts holdsMedia), and — for
+// "no-transcript" — no transcript (lib/videoStatus.ts isVideoTranscribed);
+// "all" takes the transcribed ones too, after every untranscribed one. A video
+// whose newest copy attempt is terminal (none-found, failed) and younger than
+// COPY_ATTEMPT_RETRY_DAYS is left out, unless `retryFailed`. A channel whose
+// text cannot be read is named and skipped (an unmounted drive is not an empty
+// channel). The cheap checks (one readdir) come first; the availability is read
+// only for what passes them.
+//
+// THE LOOKUPS are the article mode's (lookForCopy), one video at a time, at
+// most `max` of them per run (a non-YouTube video costs none and is listed);
+// archive.org refusing stops the run. Not a dry run: a video neither source
+// holds is recorded `none-found` in its copy-attempts.json, and the copies
+// found go to ONE fetch-copies job (controller/fetchCopies.ts) — through
+// `startFetch`, the editor's. A dry run asks the same questions and records
+// and fetches nothing.
+
+export const GONE_SCOPES = ["no-transcript", "all"] as const;
+export type GoneScope = (typeof GONE_SCOPES)[number];
+
+// Lookups per run: a small default, and a ceiling.
+export const FIND_COPY_DEFAULT_MAX = 10;
+export const FIND_COPY_MAX_LIMIT = 200;
+
+export type WholeCopyScope = { slug: string } | { siteId: string };
+
+export type GoneCandidate = {
+ slug: string;
+ id: string;
+ videoDir: string;
+ gone: GoneState;
+ noTranscript: boolean;
+};
+
+export type GoneEnumeration = {
+ channels: string[];
+ candidates: GoneCandidate[];
+ skipped: {
+ // Gone or not, already holding audio or video (not asked whether gone).
+ media: number;
+ // Holding a transcript, in "no-transcript" mode (not asked whether gone).
+ transcript: number;
+ // Gone, with a recent terminal copy attempt.
+ recent: { slug: string; id: string; at: string; outcome: string }[];
+ // Channels whose text cannot be read.
+ unreadable: { slug: string; error: string }[];
+ };
+};
+
+export type GoneEnumerationDeps = {
+ listIds: (paths: Paths, slug: string) => Promise<string[]>;
+ assertTextReadable: (paths: Paths, slug: string) => Promise<unknown>;
+ goneState: (videoDir: string) => Promise<GoneState | null>;
+ copyAttempts: (videoDir: string) => Promise<CopyAttempts | null>;
+};
+
+const DEFAULT_ENUM_DEPS: GoneEnumerationDeps = {
+ listIds: listChannelVideoIds,
+ assertTextReadable: (paths, slug) => assertChannelTextReadable(paths, slug),
+ goneState: sourceGoneState,
+ copyAttempts: loadCopyAttempts,
+};
+
+export async function enumerateGoneVideos(opts: {
+ paths: Paths;
+ slugs: string[];
+ gone: GoneScope;
+ retryFailed?: boolean;
+ now?: number;
+ signal?: AbortSignal;
+ deps?: Partial<GoneEnumerationDeps>;
+}): Promise<GoneEnumeration> {
+ const deps: GoneEnumerationDeps = { ...DEFAULT_ENUM_DEPS, ...opts.deps };
+ const now = opts.now ?? Date.now();
+ const out: GoneEnumeration = {
+ channels: [...opts.slugs],
+ candidates: [],
+ skipped: { media: 0, transcript: 0, recent: [], unreadable: [] },
+ };
+ const untranscribed: GoneCandidate[] = [];
+ const transcribed: GoneCandidate[] = [];
+ for (const slug of opts.slugs) {
+ if (opts.signal?.aborted) break;
+ try {
+ await deps.assertTextReadable(opts.paths, slug);
+ } catch (e) {
+ out.skipped.unreadable.push({ slug, error: (e as Error).message });
+ continue;
+ }
+ const ids = (await deps.listIds(opts.paths, slug)).sort();
+ for (const id of ids) {
+ if (opts.signal?.aborted) break;
+ const videoDir = path.join(opts.paths.channelsDir, slug, "data", id);
+ const files = await readVideoFiles(videoDir);
+ if (holdsMedia(files.entries)) {
+ out.skipped.media++;
+ continue;
+ }
+ const noTranscript = !isVideoTranscribed(files);
+ if (!noTranscript && opts.gone === "no-transcript") {
+ out.skipped.transcript++;
+ continue;
+ }
+ const gone = await deps.goneState(videoDir).catch(() => null);
+ if (!gone) continue;
+ if (!opts.retryFailed) {
+ const recent = recentTerminalAttempt(await deps.copyAttempts(videoDir).catch(() => null), now);
+ if (recent) {
+ out.skipped.recent.push({ slug, id, at: recent.at, outcome: recent.outcome });
+ continue;
+ }
+ }
+ (noTranscript ? untranscribed : transcribed).push({ slug, id, videoDir, gone, noTranscript });
+ }
+ }
+ out.candidates = [...untranscribed, ...transcribed];
+ return out;
+}
+
+export type WholeCopyCandidate = {
+ slug: string;
+ id: string;
+ gone: GoneState;
+ noTranscript: boolean;
+ watchUrl: string | null;
+ youtubeId: string | null;
+ failedBefore: ClipCopy[];
+ tried: FindCopyAttempt[];
+ copy?: ClipCopy;
+ // What the copy is, in a phrase: the archive.org item and file, or the
+ // Wayback capture.
+ via?: string;
+ // fetch a copy found: its whole audio goes to fetch-copies
+ // none-found neither source holds it (recorded, not a dry run)
+ // not-youtube not a YouTube recording: nothing is looked for
+ // error a lookup failed: a later run asks again
+ outcome: "fetch" | "none-found" | "not-youtube" | "error";
+};
+
+export type FindWholeCopiesResult = {
+ scope: WholeCopyScope;
+ gone: GoneScope;
+ dryRun: boolean;
+ max: number;
+ channels: string[];
+ // Gone videos that qualified (before `max`).
+ eligible: number;
+ skipped: GoneEnumeration["skipped"];
+ looked: WholeCopyCandidate[];
+ // Qualifying YouTube videos left for a later run by `max`.
+ left: number;
+ items: FetchCopyItem[];
+ stopped?: string;
+};
+
+export type FindWholeCopiesDeps = Pick<FindCopyDeps, "wayback" | "archive" | "facts" | "failedCopies"> & {
+ enumerate: GoneEnumerationDeps;
+ recordAttempt: (videoDir: string, attempt: CopyAttempt) => Promise<void>;
+ siteChannels: (paths: Paths, siteId: string) => string[];
+ now: () => Date;
+};
+
+const DEFAULT_WHOLE_DEPS: FindWholeCopiesDeps = {
+ wayback: waybackClient,
+ archive: archiveOrgClient,
+ facts: recordFacts,
+ failedCopies: readFailedCopies,
+ enumerate: DEFAULT_ENUM_DEPS,
+ recordAttempt: recordCopyAttempt,
+ siteChannels: (paths, siteId) => getSite(siteId, paths).channels.map((c) => c.slug),
+ now: () => new Date(),
+};
+
+export function wholeCopyScopeLabel(scope: WholeCopyScope): string {
+ return "slug" in scope ? `channel ${scope.slug}` : `site ${scope.siteId}`;
+}
+
+export async function findWholeCopies(opts: {
+ paths: Paths;
+ scope: WholeCopyScope;
+ gone: GoneScope;
+ dryRun?: boolean;
+ max?: number;
+ retryFailed?: boolean;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ deps?: Partial<Omit<FindWholeCopiesDeps, "enumerate">> & { enumerate?: Partial<GoneEnumerationDeps> };
+}): Promise<FindWholeCopiesResult> {
+ const deps: FindWholeCopiesDeps = {
+ ...DEFAULT_WHOLE_DEPS,
+ ...opts.deps,
+ enumerate: { ...DEFAULT_ENUM_DEPS, ...opts.deps?.enumerate },
+ };
+ const log = (line: string) => opts.onLog?.(line);
+ const signal = opts.signal;
+ const dryRun = opts.dryRun === true;
+ const max = Math.min(FIND_COPY_MAX_LIMIT, Math.max(1, Math.floor(opts.max ?? FIND_COPY_DEFAULT_MAX)));
+ const slugs = "slug" in opts.scope ? [opts.scope.slug] : deps.siteChannels(opts.paths, opts.scope.siteId);
+ const found = await enumerateGoneVideos({
+ paths: opts.paths,
+ slugs,
+ gone: opts.gone,
+ retryFailed: opts.retryFailed,
+ now: deps.now().getTime(),
+ ...(signal ? { signal } : {}),
+ deps: deps.enumerate,
+ });
+ const result: FindWholeCopiesResult = {
+ scope: opts.scope,
+ gone: opts.gone,
+ dryRun,
+ max,
+ channels: found.channels,
+ eligible: found.candidates.length,
+ skipped: found.skipped,
+ looked: [],
+ left: 0,
+ items: [],
+ };
+ log(
+ `find-copy ${wholeCopyScopeLabel(opts.scope)} (gone: ${opts.gone}${dryRun ? ", dry run" : ""}): ` +
+ `${found.candidates.length} gone video(s) with no media` +
+ `${opts.gone === "no-transcript" ? " and no transcript" : ""} in ${found.channels.length} channel(s); ` +
+ `at most ${max} looked up.` +
+ (found.skipped.recent.length ? ` ${found.skipped.recent.length} left out: a copy attempt in the last ${COPY_ATTEMPT_RETRY_DAYS} days found none or failed.` : ""),
+ );
+ for (const u of found.skipped.unreadable) log(` ${u.slug}: skipped — ${u.error}`);
+
+ let lookups = 0;
+ for (let i = 0; i < found.candidates.length; i++) {
+ const c = found.candidates[i]!;
+ if (signal?.aborted) break;
+ const facts = await deps.facts(opts.paths, c.slug, c.id);
+ const youtubeId = youtubeIdOf(facts.webpageUrl);
+ if (youtubeId && lookups >= max) {
+ result.left++;
+ continue;
+ }
+ const failedBefore = (await deps.failedCopies(facts.videoDir).catch(() => [] as FailedCopy[])).map(({ from, url }) => ({ from, url }));
+ const rec: WholeCopyCandidate = {
+ slug: c.slug,
+ id: c.id,
+ gone: c.gone,
+ noTranscript: c.noTranscript,
+ watchUrl: facts.webpageUrl,
+ youtubeId,
+ failedBefore,
+ tried: [],
+ outcome: youtubeId ? "none-found" : "not-youtube",
+ };
+ if (youtubeId) lookups++;
+ const look = await lookForCopy({ youtubeId, duration: facts.duration, failedBefore, retryFailed: opts.retryFailed, deps, signal });
+ rec.tried = look.tried;
+ if (signal?.aborted) break;
+ result.looked.push(rec);
+ if (look.copy) {
+ rec.copy = look.copy;
+ rec.outcome = "fetch";
+ rec.via = look.mirror
+ ? `archive.org ${look.mirror.identifier} / ${look.mirror.file}`
+ : `the Wayback Machine${look.captureTs ? `, captured ${look.captureTs}` : ""}`;
+ result.items.push({ slug: c.slug, id: c.id, copy: look.copy });
+ } else if (look.tried.some((t) => t.error)) {
+ rec.outcome = "error";
+ } else if (youtubeId && !dryRun) {
+ await deps
+ .recordAttempt(facts.videoDir, {
+ at: deps.now().toISOString(),
+ outcome: "none-found",
+ detail: look.tried.map(describeAttempt).join("; "),
+ })
+ .catch((e: unknown) => log(` ${c.slug}/${c.id}: copy-attempts.json not written (${(e as Error).message}).`));
+ }
+ log(
+ ` ${c.slug}/${c.id} (${c.gone}${c.noTranscript ? ", no transcript" : ""}): ` +
+ rec.tried.map(describeAttempt).join("; ") +
+ ` → ${
+ rec.outcome === "fetch"
+ ? `${dryRun ? "would fetch" : "fetch"} its audio from ${rec.via}`
+ : rec.outcome === "none-found"
+ ? `none found${dryRun ? "" : " (recorded)"}`
+ : rec.outcome === "not-youtube"
+ ? "not looked for"
+ : "try again later"
+ }`,
+ );
+ if (look.refused) {
+ result.stopped = `archive.org kept refusing (${look.refused}); the rest are left for a later run`;
+ log(`find-copy: ${result.stopped}.`);
+ break;
+ }
+ }
+ if (signal?.aborted) {
+ result.stopped = "cancelled; the rest are left for a later run";
+ log(`find-copy: ${result.stopped}.`);
+ }
+ if (result.left > 0) log(`find-copy: ${result.left} more gone video(s) are left for a later run (max ${max}).`);
+ log(
+ `find-copy: ${result.items.length} cop${result.items.length === 1 ? "y" : "ies"} found` +
+ `${dryRun ? " (dry run: nothing fetched or recorded)" : ""}.`,
+ );
+ return result;
+}
+
+// The scope mode, whole: the lookups, then (unless `dryRun`, or the run was
+// cancelled) ONE fetch-copies of every copy found through `startFetch`.
+export async function runFindWholeCopies<T>(
+ opts: Parameters<typeof findWholeCopies>[0] & { startFetch: (items: FetchCopyItem[]) => Promise<T> },
+): Promise<FindWholeCopiesResult & { fetch?: T }> {
+ const found = await findWholeCopies(opts);
+ if (opts.dryRun || opts.signal?.aborted || found.items.length === 0) return found;
+ return { ...found, fetch: await opts.startFetch(found.items) };
+}
diff --git a/common/publish/findCopyScope.test.ts b/common/publish/findCopyScope.test.ts
@@ -0,0 +1,209 @@
+// find-copy's scope mode (release 31, lane C) over a synthetic corpus on disk,
+// the fake Wayback and the fake archive.org: every gone video of a channel or
+// a site with no media (and, for "no-transcript", no transcript) — gone by the
+// one reading — untranscribed first; a recent terminal attempt keeps one out
+// unless `retryFailed`; `max` caps the lookups; a dry run records and fetches
+// nothing; a run records `none-found` and hands every copy found to ONE fetch.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/findCopyScope.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { startFakeWayback } from "../testing/web/fakeWayback.mjs";
+import { startFakeArchiveOrg, type FakeArchiveOrgItem } from "../testing/archiveOrg/fakeArchiveOrg.mjs";
+import { GONE_AVAILABILITY } from "../testing/draft/corpus.mjs";
+import { ArchiveOrgClient } from "../lib/archiveOrgClient";
+import { WaybackClient } from "../lib/waybackClient";
+import { loadCopyAttempts, recordCopyAttempt } from "../lib/copyAttempts-server";
+import type { Paths } from "../lib/paths";
+import type { FetchCopyItem } from "../controller/fetchCopies";
+import { enumerateGoneVideos, findWholeCopies, runFindWholeCopies } from "./findCopy";
+
+const NOW = new Date("2026-10-16T00:00:00.000Z");
+const WB = "wbArchived1"; // the Wayback Machine holds the video
+const IA = "iaMirrored1"; // an archive.org mirror of it
+const NONE = "noCopyAny01"; // no copy anywhere
+const TRANS = "transcribd1"; // gone, transcribed; the Wayback Machine holds it
+const MEDIA = "hasAudio001"; // gone, audio already on disk
+const LIVE = "stillLive01"; // not gone
+const RECENT = "triedBefor1"; // gone, none found two days ago
+const BETA = "betaGone001"; // gone, on the second channel; nothing holds it
+const RUMBLE = "v5rumble"; // gone, a Rumble record
+const watch = (id: string) => `https://www.youtube.com/watch?v=${id}`;
+
+const MIRROR: FakeArchiveOrgItem = {
+ metadata: { identifier: `youtube-${IA}`, title: `An upload ${IA}`, mediatype: "movies", originalurl: watch(IA) },
+ files: [{ name: `An upload-${IA}.mp4`, source: "original", format: "MPEG4", size: "3000", length: "300.0" }],
+};
+
+async function writeVideo(channelDir: string, id: string, o: { gone?: boolean; files?: Record<string, string>; page?: string } = {}) {
+ const v = path.join(channelDir, "data", id);
+ await mkdir(v, { recursive: true });
+ const page = o.page ?? watch(id);
+ await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id, title: `Original ${id}`, webpage_url: page, duration: 300 }));
+ if (o.gone !== false) await writeFile(path.join(v, "availability.json"), JSON.stringify({ ...GONE_AVAILABILITY, webpageUrl: page }));
+ for (const [name, body] of Object.entries(o.files ?? {})) await writeFile(path.join(v, name), body);
+ return v;
+}
+
+async function corpus() {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "find-copy-scope-"));
+ const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, sitesDir: path.join(dir, "sites") } as Paths;
+ const alpha = path.join(paths.channelsDir, "alpha");
+ const beta = path.join(paths.channelsDir, "beta");
+ for (const ch of [alpha, beta]) {
+ await mkdir(path.join(ch, "data"), { recursive: true });
+ await writeFile(path.join(ch, "config.json"), JSON.stringify({ handling: "youtube", url: "https://www.youtube.com/@x/videos" }));
+ }
+ for (const id of [WB, IA, NONE]) await writeVideo(alpha, id);
+ await writeVideo(alpha, TRANS, { files: { "transcript.en.vtt": "WEBVTT\n\n00:00.000 --> 00:01.000\nhello\n" } });
+ await writeVideo(alpha, MEDIA, { files: { "audio.mp3": "x" } });
+ await writeVideo(alpha, LIVE, { gone: false });
+ const recentDir = await writeVideo(alpha, RECENT);
+ await recordCopyAttempt(recentDir, { at: new Date(NOW.getTime() - 2 * 86_400_000).toISOString(), outcome: "none-found" });
+ await writeVideo(alpha, RUMBLE, { page: "https://rumble.com/v5rumble-a-stream.html" });
+ await writeVideo(beta, BETA);
+ return { dir, paths, alpha, beta, close: () => rm(dir, { recursive: true, force: true }) };
+}
+
+async function fakes() {
+ const wb = await startFakeWayback({ videos: [WB, TRANS] });
+ const ia = await startFakeArchiveOrg({ items: [MIRROR] });
+ const deps = {
+ wayback: new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }),
+ archive: new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 }),
+ siteChannels: () => ["beta", "alpha"],
+ now: () => NOW,
+ };
+ return { wb, ia, deps, close: async () => Promise.all([wb.close(), ia.close()]) };
+}
+
+test("the candidates: gone by the one reading, no media, no transcript (or, for all, transcribed ones after), a recent attempt left out", async () => {
+ const c = await corpus();
+ try {
+ const nt = await enumerateGoneVideos({ paths: c.paths, slugs: ["beta", "alpha"], gone: "no-transcript", now: NOW.getTime() });
+ assert.deepEqual(nt.candidates.map((x) => x.id), [BETA, IA, NONE, RUMBLE, WB]);
+ assert.equal(nt.skipped.media, 1);
+ assert.equal(nt.skipped.transcript, 1);
+ assert.deepEqual(nt.skipped.recent.map((r) => [r.id, r.outcome]), [[RECENT, "none-found"]]);
+ const all = await enumerateGoneVideos({ paths: c.paths, slugs: ["alpha"], gone: "all", now: NOW.getTime(), retryFailed: true });
+ assert.deepEqual(all.candidates.map((x) => [x.id, x.noTranscript]), [
+ [IA, true],
+ [NONE, true],
+ [RECENT, true],
+ [RUMBLE, true],
+ [WB, true],
+ [TRANS, false],
+ ]);
+ // An unreadable channel is named and skipped, never read as empty.
+ const unreadable = await enumerateGoneVideos({
+ paths: c.paths,
+ slugs: ["alpha"],
+ gone: "all",
+ deps: { assertTextReadable: async () => Promise.reject(new Error("its data/ is not readable")) },
+ });
+ assert.deepEqual(unreadable.skipped.unreadable, [{ slug: "alpha", error: "its data/ is not readable" }]);
+ assert.equal(unreadable.candidates.length, 0);
+ } finally {
+ await c.close();
+ }
+});
+
+test("a dry run of a site: the source each would use, nothing recorded, nothing fetched", async () => {
+ const c = await corpus();
+ const f = await fakes();
+ try {
+ const r = await findWholeCopies({ paths: c.paths, scope: { siteId: "jx" }, gone: "no-transcript", dryRun: true, deps: f.deps });
+ assert.deepEqual(r.looked.map((x) => [x.id, x.outcome]), [
+ [BETA, "none-found"],
+ [IA, "fetch"],
+ [NONE, "none-found"],
+ [RUMBLE, "not-youtube"],
+ [WB, "fetch"],
+ ]);
+ assert.equal(r.looked.find((x) => x.id === IA)?.via, `archive.org youtube-${IA} / An upload-${IA}.mp4`);
+ assert.match(r.looked.find((x) => x.id === WB)?.via ?? "", /^the Wayback Machine/);
+ assert.deepEqual(r.items.map((i) => [i.id, i.copy.from]), [[IA, "archive.org"], [WB, "wayback"]]);
+ assert.equal(await loadCopyAttempts(path.join(c.alpha, "data", NONE)), null, "a dry run records nothing");
+ let started = 0;
+ const run = await runFindWholeCopies({
+ paths: c.paths,
+ scope: { siteId: "jx" },
+ gone: "no-transcript",
+ dryRun: true,
+ deps: f.deps,
+ startFetch: async () => void started++,
+ });
+ assert.equal(run.items.length, 2);
+ assert.equal(started, 0, "a dry run starts no fetch");
+ } finally {
+ await f.close();
+ await c.close();
+ }
+});
+
+test("a run: none-found recorded (and then left out), ONE fetch of every copy found; max caps the lookups, not the non-YouTube ones", async () => {
+ const c = await corpus();
+ const f = await fakes();
+ try {
+ const fetches: FetchCopyItem[][] = [];
+ const r = await runFindWholeCopies({
+ paths: c.paths,
+ scope: { slug: "alpha" },
+ gone: "no-transcript",
+ max: 2,
+ deps: f.deps,
+ startFetch: async (items) => {
+ fetches.push(items);
+ return "job-1";
+ },
+ });
+ // Alpha's untranscribed, in id order: IA, NONE (two lookups), then RUMBLE
+ // (no lookup), then WB left by max.
+ assert.deepEqual(r.looked.map((x) => [x.id, x.outcome]), [[IA, "fetch"], [NONE, "none-found"], [RUMBLE, "not-youtube"]]);
+ assert.equal(r.left, 1);
+ assert.equal(r.fetch, "job-1");
+ assert.deepEqual(fetches.map((items) => items.map((i) => i.id)), [[IA]]);
+ const none = await loadCopyAttempts(path.join(c.alpha, "data", NONE));
+ assert.equal(none?.attempts?.[0]?.outcome, "none-found");
+ assert.match(none?.attempts?.[0]?.detail ?? "", /wayback none/);
+ // The next run leaves NONE out (a recent terminal attempt) and reaches WB.
+ const again = await findWholeCopies({ paths: c.paths, scope: { slug: "alpha" }, gone: "no-transcript", max: 5, deps: f.deps });
+ assert.ok(!again.looked.some((x) => x.id === NONE));
+ assert.ok(again.skipped.recent.some((x) => x.id === NONE));
+ assert.ok(again.looked.some((x) => x.id === WB && x.outcome === "fetch"));
+ } finally {
+ await f.close();
+ await c.close();
+ }
+});
+
+test("archive.org refusing stops the run there; a cancelled run starts no fetch", async () => {
+ const c = await corpus();
+ const wb = await startFakeWayback({ videos: [] });
+ const ia = await startFakeArchiveOrg({ items: [MIRROR], busyTimes: 50 });
+ try {
+ const deps = {
+ wayback: new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }),
+ archive: new ArchiveOrgClient({ fetch: ia.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }),
+ now: () => NOW,
+ };
+ const r = await findWholeCopies({ paths: c.paths, scope: { slug: "alpha" }, gone: "no-transcript", deps });
+ assert.equal(r.looked.length, 1);
+ assert.equal(r.looked[0]!.outcome, "error");
+ assert.match(r.stopped ?? "", /archive.org kept refusing/);
+ assert.equal(await loadCopyAttempts(path.join(c.alpha, "data", IA)), null, "an error is not an attempt");
+ const ctl = new AbortController();
+ ctl.abort();
+ let started = 0;
+ await runFindWholeCopies({ paths: c.paths, scope: { slug: "alpha" }, gone: "no-transcript", signal: ctl.signal, deps, startFetch: async () => void started++ });
+ assert.equal(started, 0);
+ } finally {
+ await wb.close();
+ await ia.close();
+ await c.close();
+ }
+});
diff --git a/common/ytdlp/fetchCopyManaged.test.ts b/common/ytdlp/fetchCopyManaged.test.ts
@@ -0,0 +1,121 @@
+// fetchCopyManaged (release 31, lane C) against a fake yt-dlp: a gone video's
+// whole audio from a copy lands in its OWN record as audio.<fmt> — the
+// record's metadata untouched, no cookies or channel args sent to archive.org,
+// the scratch never left behind, the file tiered when the channel has a media
+// tier — and a failure is classified as every fetch's is.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/fetchCopyManaged.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, readlink, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { COPY_PART_BASENAME, fetchCopyManaged, holdsMedia } from "./fetchCopyManaged";
+import { FetchWindowError } from "./fetchWindowManaged";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetchcopy-"));
+const BIN = path.join(ROOT, "fake-ytdlp.mjs");
+const ARGS_LOG = path.join(ROOT, "argv.jsonl");
+process.env.FAKE_ARGS_LOG = ARGS_LOG;
+
+// FAKE_MODE=ok: the download, then the extraction (the source container left
+// behind as a stray, which the caller clears). =gone: the copy's 404.
+// =ratelimit: a 429. =noout: exit 0 with nothing written.
+await writeFile(
+ BIN,
+ `#!/usr/bin/env node
+import { appendFileSync, writeFileSync } from "node:fs";
+const args = process.argv.slice(2);
+appendFileSync(process.env.FAKE_ARGS_LOG, JSON.stringify(args) + "\\n");
+const mode = process.env.FAKE_MODE;
+const out = args[args.indexOf("-o") + 1];
+const fmt = args[args.indexOf("--audio-format") + 1];
+if (mode === "gone") { process.stderr.write("ERROR: [generic] x: Unable to download webpage: HTTP Error 404: Not Found\\n"); process.exit(1); }
+if (mode === "ratelimit") { process.stderr.write("ERROR: [generic] x: HTTP Error 429: Too Many Requests\\n"); process.exit(1); }
+if (mode === "noout") process.exit(0);
+writeFileSync(out.replace("%(ext)s", "webm"), "video bytes");
+writeFileSync(out.replace("%(ext)s", fmt), "audio bytes");
+`,
+);
+await chmod(BIN, 0o755);
+
+const META = JSON.stringify({ id: "gone0000001", title: "The original's title", upload_date: "20240101", webpage_url: "https://www.youtube.com/watch?v=gone0000001" });
+
+async function record(name: string, o: { tier?: boolean } = {}) {
+ const channelDir = path.join(ROOT, name);
+ const videoDir = path.join(channelDir, "data", "gone0000001");
+ await mkdir(videoDir, { recursive: true });
+ if (o.tier) await mkdir(path.join(channelDir, "media"));
+ await writeFile(path.join(videoDir, "metadata.info.json"), META);
+ return videoDir;
+}
+
+const WAYBACK = { from: "wayback" as const, url: "https://web.archive.org/web/20240102030405/https://www.youtube.com/watch?v=gone0000001" };
+
+function opts(videoDir: string, config: Partial<ChannelConfig> = {}) {
+ return {
+ paths: { ytdlpBin: BIN } as unknown as Paths,
+ channelConfig: { cookiesFromBrowser: "firefox", ytdlpExtraArgs: ["--write-info-json"], ...config } as ChannelConfig,
+ videoDir,
+ videoId: "gone0000001",
+ copy: WAYBACK,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ };
+}
+
+async function lastArgv(): Promise<string[]> {
+ const lines = (await readFile(ARGS_LOG, "utf8")).trim().split("\n");
+ return JSON.parse(lines.at(-1)!) as string[];
+}
+
+test("the copy's audio lands as the record's audio.<fmt>; metadata untouched; no cookies or channel args; no scratch left", async () => {
+ process.env.FAKE_MODE = "ok";
+ const dir = await record("ok");
+ const r = await fetchCopyManaged(opts(dir, { audioFormat: "m4a" } as Partial<ChannelConfig>));
+ assert.equal(r.audioFile, "audio.m4a");
+ assert.equal(await readFile(path.join(dir, "audio.m4a"), "utf8"), "audio bytes");
+ assert.equal(await readFile(path.join(dir, "metadata.info.json"), "utf8"), META, "the original's metadata stays");
+ assert.deepEqual((await readdir(dir)).sort(), ["audio.m4a", "metadata.info.json"], "the scratch and the stray container are gone");
+ const argv = await lastArgv();
+ assert.ok(!argv.join(" ").includes("--cookies-from-browser"), "no cookies to a copy");
+ assert.ok(!argv.includes("--write-info-json"), "the channel's extra args are not sent");
+ assert.deepEqual(argv.slice(argv.indexOf("-f"), argv.indexOf("-f") + 5), ["-f", "ba/b", "-x", "--audio-format", "m4a"]);
+ assert.ok(argv.indexOf("--no-write-info-json") < argv.indexOf("-o"));
+ assert.equal(argv[argv.indexOf("-o") + 1], path.join(dir, `${COPY_PART_BASENAME}.%(ext)s`));
+ assert.equal(argv.at(-1), WAYBACK.url);
+});
+
+test("a channel with a media tier: the audio is tiered (a relative link in data/<id>/)", async () => {
+ process.env.FAKE_MODE = "ok";
+ const dir = await record("tiered", { tier: true });
+ await fetchCopyManaged(opts(dir));
+ const st = await lstat(path.join(dir, "audio.mp3"));
+ assert.ok(st.isSymbolicLink(), "audio.mp3 is the tier's link");
+ assert.equal(await readlink(path.join(dir, "audio.mp3")), "../../media/gone0000001/audio.mp3");
+});
+
+test("a failure is classified (the copy's 404 per-video, a 429 a rate limit) and leaves nothing; success with no file throws", async () => {
+ const dir = await record("fail");
+ process.env.FAKE_MODE = "gone";
+ await assert.rejects(fetchCopyManaged(opts(dir)), (e: unknown) => e instanceof FetchWindowError && /404/.test(e.message));
+ process.env.FAKE_MODE = "ratelimit";
+ await assert.rejects(fetchCopyManaged(opts(dir)), (e: unknown) => e instanceof FetchWindowError && e.failureClass === "rate_limit");
+ process.env.FAKE_MODE = "noout";
+ await assert.rejects(fetchCopyManaged(opts(dir)), /wrote no mp3 audio/);
+ assert.deepEqual(await readdir(dir), ["metadata.info.json"]);
+});
+
+test("a record already holding audio is never fetched over; holdsMedia names audio, a source container, a saved-video pointer", async () => {
+ process.env.FAKE_MODE = "ok";
+ const dir = await record("held");
+ await writeFile(path.join(dir, "audio.opus"), "x");
+ await assert.rejects(fetchCopyManaged(opts(dir)), /already holds audio/);
+ assert.equal(holdsMedia(["metadata.info.json", "audio.mp3"]), true);
+ assert.equal(holdsMedia(["source-media.mp4"]), true);
+ assert.equal(holdsMedia(["saved-video.json"]), true);
+ assert.equal(holdsMedia(["metadata.info.json", "audio.copy-part.mp3", "audio.mp3.part", "transcript.en.vtt"]), false);
+});
diff --git a/common/ytdlp/fetchCopyManaged.ts b/common/ytdlp/fetchCopyManaged.ts
@@ -0,0 +1,158 @@
+// FETCH A GONE VIDEO'S WHOLE AUDIO FROM A COPY into its OWN record (release 31,
+// lane C).
+//
+// find-copy's scope mode found a copy of a deleted or private YouTube upload —
+// the Wayback Machine holding the video, or an archive.org mirror of it
+// (publish/findCopy.ts) — and fetch-copies (controller/fetchCopies.ts) brings
+// the audio home: `data/<id>/audio.<fmt>` of the ORIGINAL record, where the
+// transcription lane finds it like any other downloaded audio
+// (channelSnapshot's downloadedNoTranscript; the lane does not ask whether the
+// platform still serves the video).
+//
+// AN EXPLICIT RECORD, like fetchWindowManaged: the caller names the video dir,
+// so a Wayback replay URL or an archive.org file URL — whose own ids are not
+// the record's — never decides where the bytes land.
+//
+// WHAT IT DELIBERATELY DOES NOT DO: write metadata.info.json, subtitles, a
+// thumbnail or an archive line. The record's metadata is the ORIGINAL's (its
+// title, date and page stay; a copy's are often worse — release 24's
+// persist-provenance rule), so this is not downloadOneManaged, whose prefetch
+// rewrites that file from whatever the URL's extractor says. The argv is
+// assembled here, in full, with the writers negated last.
+//
+// AUDIO ONLY: `-f ba/b` (a Wayback copy or a mirror is usually ONE file of
+// unknown height holding both streams; `b` takes it) and yt-dlp's own
+// extraction (`-x --audio-format <the channel's audioFormat>`), the source
+// container discarded. The file is written under a two-segment scratch name
+// (`audio.copy-part.<ext>`, which no reader takes for finished audio:
+// lib/mediaFiles.ts isRealAudioFile) and renamed into place, then handed to the
+// media tier's hook (lib/mediaTier-server.ts) like every finished media file.
+//
+// NO COOKIES and none of the channel's platform args or extra args: the copy
+// is archive.org's, not the channel's platform's, and the channel's browser
+// cookies have no business going to it. Paced like archive.org's clients
+// (`--sleep-requests 2`).
+
+import path from "node:path";
+import { readdir, rename, rm, stat } from "node:fs/promises";
+import {
+ classifyDownloadFailure,
+ parseUnavailableFromStderr,
+} from "../lib/availability";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { Paths } from "../lib/paths";
+import type { ClipCopy } from "../lib/clipWindow";
+import { isRealAudioFile, isSourceMediaFile } from "../lib/mediaFiles";
+import { SAVED_VIDEO_POINTER_FILENAME } from "../lib/savedVideo";
+import { tierMediaFile } from "../lib/mediaTier-server";
+import { runOneYtdlp } from "./runOneYtdlp";
+import { FULL_LOG_PROGRESS_ARGS } from "./downloadOneManaged";
+import { FetchWindowError } from "./fetchWindowManaged";
+
+// The scratch base the download and the extraction write under.
+export const COPY_PART_BASENAME = "audio.copy-part";
+
+// archive.org's own pace (lib/archiveOrgClient.ts: 2 s between requests).
+export const COPY_SLEEP_REQUESTS_SECONDS = 2;
+
+export type FetchCopyOpts = {
+ paths: Paths;
+ channelConfig: ChannelConfig;
+ // channels/<slug>/data/<id> — the ORIGINAL record's directory.
+ videoDir: string;
+ videoId: string;
+ copy: ClipCopy;
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+};
+
+export type FetchCopyResult = {
+ // `audio.<fmt>`, in the video dir (a tier link when the channel has a tier).
+ audioFile: string;
+ bytes: number;
+ args: string[];
+};
+
+// Whether a video dir's entries already hold its audio or video: finished
+// audio, a persisted source container, or a saved-video pointer. A copy is
+// never fetched over any of them.
+export function holdsMedia(entries: readonly string[]): boolean {
+ return entries.some((e) => isRealAudioFile(e) || isSourceMediaFile(e) || e === SAVED_VIDEO_POINTER_FILENAME);
+}
+
+export function copyAudioFormat(config: ChannelConfig): string {
+ return config.audioFormat ?? "mp3";
+}
+
+export function fetchCopyArgs(videoDir: string, copy: ClipCopy, audioFormat: string): string[] {
+ return [
+ "--ignore-config",
+ "--no-playlist",
+ "--sleep-requests",
+ String(COPY_SLEEP_REQUESTS_SECONDS),
+ "-f",
+ "ba/b",
+ "-x",
+ "--audio-format",
+ audioFormat,
+ ...FULL_LOG_PROGRESS_ARGS,
+ "--no-write-info-json",
+ "--no-write-description",
+ "--no-write-thumbnail",
+ "--no-write-subs",
+ "--no-write-auto-subs",
+ "--no-download-archive",
+ "-o",
+ path.join(videoDir, `${COPY_PART_BASENAME}.%(ext)s`),
+ "--",
+ copy.url,
+ ];
+}
+
+async function scratchFiles(videoDir: string): Promise<string[]> {
+ return (await readdir(videoDir).catch(() => [] as string[])).filter((f) => f.startsWith(`${COPY_PART_BASENAME}.`));
+}
+
+async function clearScratch(videoDir: string): Promise<void> {
+ for (const f of await scratchFiles(videoDir)) await rm(path.join(videoDir, f), { force: true }).catch(() => {});
+}
+
+export async function fetchCopyManaged(opts: FetchCopyOpts): Promise<FetchCopyResult> {
+ const { videoDir } = opts;
+ const fmt = copyAudioFormat(opts.channelConfig);
+ const audioFile = `audio.${fmt}`;
+ const existing = (await readdir(videoDir).catch(() => [] as string[])).filter(isRealAudioFile);
+ if (existing.length > 0) {
+ throw new Error(`${opts.videoId} already holds audio (${existing.join(", ")}); nothing is fetched over it`);
+ }
+ await clearScratch(videoDir);
+ const args = fetchCopyArgs(videoDir, opts.copy, fmt);
+ const outcome = await runOneYtdlp(
+ { ytdlpBin: opts.paths.ytdlpBin, onLog: opts.onLog, signal: opts.signal },
+ videoDir,
+ args,
+ );
+ if (outcome.exitCode !== 0) {
+ await clearScratch(videoDir);
+ const tail = outcome.stderrTail.trim().split("\n").slice(-4).join(" / ");
+ const availability = parseUnavailableFromStderr(outcome.stderrTail);
+ throw new FetchWindowError(
+ `yt-dlp failed fetching the ${opts.copy.from} copy of ${opts.videoId} (exit ${outcome.exitCode ?? "null"}): ${tail}`,
+ classifyDownloadFailure(outcome.stderrTail, availability),
+ availability,
+ );
+ }
+ // The extraction's output: `audio.copy-part.<fmt>`. Anything else left is
+ // the source container yt-dlp kept or a stray, and goes.
+ const produced = `${COPY_PART_BASENAME}.${fmt}`;
+ const st = await stat(path.join(videoDir, produced)).catch(() => null);
+ if (!st?.isFile() || st.size === 0) {
+ await clearScratch(videoDir);
+ throw new Error(`yt-dlp reported success but wrote no ${fmt} audio for ${opts.videoId}`);
+ }
+ await rename(path.join(videoDir, produced), path.join(videoDir, audioFile));
+ await clearScratch(videoDir);
+ await tierMediaFile(videoDir, audioFile, { onLog: opts.onLog });
+ opts.onLog(`Fetched the ${opts.copy.from} copy of ${opts.videoId} into ${audioFile} (${st.size} bytes).\n`);
+ return { audioFile, bytes: st.size, args };
+}