// 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. — 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 = {}) { 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 { 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.; 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)); 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//)", 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); });