import { test } from "node:test"; import assert from "node:assert/strict"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync, } from "node:fs"; import os from "node:os"; import path from "node:path"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/manualDownloads.test.ts // // A MANUAL-DOWNLOADS CHANNEL IN runYtdlp (2026-10-29, lib/manualDownloads.ts): // the batch downloads refuse, a sync and a full sweep read the listing and // download nothing, and a single video still downloads. Against a fake yt-dlp // that lists two videos and records every call. getPaths() memoizes, so the // env is set before anything imports it. const ROOT = mkdtempSync(path.join(os.tmpdir(), "manual-downloads-")); process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); writeFileSync( process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0, sleepBetweenDownloadsSeconds: 0 }) + "\n", ); const CALLS = path.join(ROOT, "calls.log"); const BIN = path.join(ROOT, "fake-ytdlp.sh"); writeFileSync( BIN, [ "#!/bin/sh", `echo "$*" >> "${CALLS}"`, 'case "$*" in', " *--flat-playlist*)", " echo https://www.youtube.com/watch?v=aaaaaaaaaaa", " echo https://www.youtube.com/watch?v=bbbbbbbbbbb", " ;;", "esac", "exit 0", "", ].join("\n"), ); chmodSync(BIN, 0o755); process.env.YTDLP_BIN = BIN; const MANUAL = { handling: "transcribe", url: "https://www.youtube.com/@manual/videos", downloadMode: "manual" } as const; const AUTO = { handling: "transcribe", url: "https://www.youtube.com/@auto/videos" } as const; // A channel whose stored playlist lists a hundred videos, of which the fake's // listing (two) is far less than the shrink guard lets Sync accept. const SHRINK = { handling: "transcribe", url: "https://www.youtube.com/@shrink/videos", downloadMode: "manual" } as const; for (const [slug, config] of [["manual", MANUAL], ["auto", AUTO], ["shrink", SHRINK]] as const) { mkdirSync(path.join(ROOT, "channels", slug, "data"), { recursive: true }); writeFileSync(path.join(ROOT, "channels", slug, "config.json"), JSON.stringify(config)); // An empty saved playlist: an automatic download-missing has nothing to fetch. writeFileSync(path.join(ROOT, "channels", slug, "playlist"), ""); } const SHRINK_PLAYLIST = Array.from({ length: 100 }, (_, i) => `https://www.youtube.com/watch?v=shrink${String(i).padStart(5, "0")}`); writeFileSync(path.join(ROOT, "channels", "shrink", "playlist"), SHRINK_PLAYLIST.join("\n") + "\n"); const { runYtdlp } = await import("./runYtdlp"); const { getPaths } = await import("../lib/paths"); function calls(): string[] { if (!existsSync(CALLS)) return []; return readFileSync(CALLS, "utf8").split("\n").filter(Boolean); } function resetCalls(): void { writeFileSync(CALLS, ""); } function run( slug: "manual" | "auto", mode: Parameters[0]["mode"], extra: Partial[0]> = {}, ): Promise { return runYtdlp({ channelSlug: slug, mode, channelConfig: (slug === "manual" ? MANUAL : AUTO) as never, paths: getPaths(), onLog: () => {}, signal: new AbortController().signal, ...extra, }); } test("the batch downloads refuse on a manual channel, before asking the source anything", async () => { resetCalls(); for (const mode of ["download-missing", "download-from-playlist", "retry-bucket"] as const) { await assert.rejects( run("manual", mode, { bucketIds: ["aaaaaaaaaaa"] }), /manual downloads: only videos you add are downloaded/, mode, ); } assert.deepEqual(calls(), []); }); test("an automatic channel's download-missing still runs", async () => { await run("auto", "download-missing"); }); test("a manual channel's sync records the newest page and downloads nothing", async () => { resetCalls(); await run("manual", "sync", { forceFullSweep: false }); const made = calls(); assert.equal(made.length, 1, "one listing page, nothing else"); assert.match(made[0], /--flat-playlist/); // The page is recorded: the roster knows both listed videos. const roster = readFileSync(path.join(ROOT, "channels", "manual", "roster.json"), "utf8"); assert.match(roster, /aaaaaaaaaaa/); assert.match(roster, /bbbbbbbbbbb/); // And it is evidence for the pre-clean check (lane verify-resume): what // the page returned, dated, never a complete listing. const ev = JSON.parse(readFileSync(path.join(ROOT, "channels", "manual", "listing-evidence.json"), "utf8")); assert.ok(ev.seen.aaaaaaaaaaa && ev.seen.bbbbbbbbbbb); assert.deepEqual( ev.attempts.map((a: { source: string; complete: boolean; count: number }) => [a.source, a.complete, a.count]), [["sync-paged", false, 2]], ); // And the sync is a sync: its stamp is written. const cfg = JSON.parse(readFileSync(path.join(ROOT, "channels", "manual", "config.json"), "utf8")); assert.ok(cfg.lastSyncedAt); assert.equal(cfg.downloadMode, "manual"); }); test("a manual channel's full sweep refreshes the playlist and downloads nothing", async () => { resetCalls(); await run("manual", "sync", { forceFullSweep: true }); const made = calls(); assert.ok(made.length >= 1); for (const c of made) assert.match(c, /--flat-playlist/, `only listings: ${c}`); const playlist = readFileSync(path.join(ROOT, "channels", "manual", "playlist"), "utf8"); assert.match(playlist, /aaaaaaaaaaa/); assert.match(playlist, /bbbbbbbbbbb/); // The accepted whole listing is evidence, and complete. const ev = JSON.parse(readFileSync(path.join(ROOT, "channels", "manual", "listing-evidence.json"), "utf8")); const full = ev.attempts.filter((a: { source: string }) => a.source === "sync-full"); assert.equal(full.length, 1); assert.equal(full[0].complete, true); assert.equal(full[0].count, 2); }); test("a single video still downloads on a manual channel", async () => { resetCalls(); await run("manual", "download-one-audio", { singleVideoUrl: "https://www.youtube.com/watch?v=aaaaaaaaaaa", }); assert.ok( calls().some((c) => !c.includes("--flat-playlist") && c.includes("aaaaaaaaaaa")), "the one video was asked for", ); }); test("a normally ended full listing the shrink guard holds back: Sync does not apply it, but it is complete evidence", async () => { await runYtdlp({ channelSlug: "shrink", mode: "sync", channelConfig: SHRINK as never, paths: getPaths(), onLog: () => {}, signal: new AbortController().signal, forceFullSweep: true, }); // The guard's own behaviour is unchanged: the stored playlist is not cut. const playlist = readFileSync(path.join(ROOT, "channels", "shrink", "playlist"), "utf8").split("\n").filter(Boolean); assert.deepEqual(playlist, SHRINK_PLAYLIST); // But the listing really did end normally and omit 98 videos: it is the // complete listing every older sighting must answer to. const ev = JSON.parse(readFileSync(path.join(ROOT, "channels", "shrink", "listing-evidence.json"), "utf8")); const full = ev.attempts.filter((a: { source: string }) => a.source === "sync-full"); assert.equal(full.at(-1).complete, true); assert.deepEqual(ev.lastComplete.ids, ["aaaaaaaaaaa", "bbbbbbbbbbb"]); });