import { test } from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import { downloadOneManaged } from "./downloadOneManaged"; import { storeFixture } from "../testing/storedTextFixture"; import { readStoredText } from "../lib/storedText-server"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/captionsRefetch.test.ts // // A MANAGED RE-DOWNLOAD OVER A CAPTION STORED COMPRESSED (REVIEW-1 F1 of the // captions lane). Main's rule is kept: a re-download fetches the captions // again and the new file replaces the old one. Over a stored track the new // file lands beside it, and after the pass each such track is settled: the // same content keeps the stored form (the new copy dropped, nothing moves); // new content with cues replaces it, only once whole; nothing, a `.part`, an // empty or cue-less file leaves the stored track untouched. The job log says // which, per track. The yt-dlp is a temp node script; no network. const ID = "Zz0capRefet"; const VIDEO = `https://www.youtube.com/watch?v=${ID}`; const EN = "transcript.en.vtt"; // The prefetch writes the info json; the subtitle pass copies whatever the // scenario put in `landing/` into the video dir (what yt-dlp would write, not // seeing a .zst), or exits 1 as for a video that is gone. Any other pass (an // audio download) writes audio.mp3. const FAKE_YTDLP = `#!/usr/bin/env node const fs = require("node:fs"); const path = require("node:path"); const argv = process.argv.slice(2); const root = process.env.FAKE_ROOT; fs.appendFileSync(path.join(root, "argv.log"), JSON.stringify(argv) + "\\n"); const has = (f) => argv.includes(f); const dir = path.join("data", "${ID}"); fs.mkdirSync(dir, { recursive: true }); if (has("--skip-download") && has("--write-info-json") && has("--no-write-subs")) { fs.copyFileSync(path.join(root, "meta.json"), path.join(dir, "metadata.info.json")); process.exit(0); } if (has("--write-subs")) { if (fs.existsSync(path.join(root, "gone"))) { console.error("ERROR: [youtube] ${ID}: Video unavailable. This video has been removed by the uploader"); process.exit(1); } for (const n of fs.readdirSync(path.join(root, "landing"))) fs.copyFileSync(path.join(root, "landing", n), path.join(dir, n)); process.exit(0); } fs.writeFileSync(path.join(dir, "audio.mp3"), "AUDIO"); process.exit(0); `; const vtt = (words: string) => `WEBVTT\n\n00:00:00.000 --> 00:00:02.000\n${words}\n\n00:00:02.000 --> 00:00:04.000\n${words} again\n`; const OLD = vtt("the stored words"); const META = { id: ID, title: "A video", duration: 600, upload_date: "20260101", webpage_url: VIDEO, automatic_captions: { en: [{ ext: "vtt" }] }, }; async function runWith(landing: Record, opts: { gone?: boolean; handling?: "youtube" | "transcribe" } = {}) { const root = await mkdtemp(path.join(tmpdir(), "captions-refetch-")); const ytdlp = path.join(root, "fake-ytdlp.cjs"); await writeFile(ytdlp, FAKE_YTDLP); await chmod(ytdlp, 0o755); await writeFile(path.join(root, "meta.json"), JSON.stringify(META)); await mkdir(path.join(root, "landing")); for (const [n, t] of Object.entries(landing)) await writeFile(path.join(root, "landing", n), t); if (opts.gone) await writeFile(path.join(root, "gone"), ""); process.env.FAKE_ROOT = root; const paths = { transcriptsDir: root, channelsDir: path.join(root, "channels"), savedVideosDir: path.join(root, "saved-videos"), ytdlpBin: ytdlp, ffmpegBin: path.join(root, "no-ffmpeg"), ffprobeBin: path.join(root, "no-ffprobe"), } as Paths; const videoDir = path.join(paths.channelsDir, "c", "data", ID); await mkdir(videoDir, { recursive: true }); await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify(META)); await writeFile(path.join(videoDir, EN), OLD); await storeFixture(videoDir, EN); const storedMtime = (await stat(path.join(videoDir, `${EN}.zst`))).mtimeMs; let log = ""; const record = await downloadOneManaged({ channelSlug: "c", channelConfig: { handling: opts.handling ?? "youtube", url: "https://www.youtube.com/@c/videos" } as ChannelConfig, paths, videoUrl: VIDEO, onLog: (s) => { log += s; }, signal: new AbortController().signal, }); const argvs = (await readFile(path.join(root, "argv.log"), "utf8").catch(() => "")) .split("\n") .filter(Boolean) .map((l) => JSON.parse(l) as string[]); return { record, log, videoDir, storedMtime, subPasses: argvs.filter((a) => a.includes("--write-subs")), captions: (await readdir(videoDir)).filter((f) => f.startsWith("transcript.") && !f.endsWith(".json")).sort(), cleanup: () => rm(root, { recursive: true, force: true }), }; } test("the caption is asked for again (main's re-download rule): no stored track left out of --sub-langs", async () => { const r = await runWith({ [EN]: OLD }); try { assert.equal(r.subPasses.length, 1, r.log); const langs = r.subPasses[0][r.subPasses[0].indexOf("--sub-langs") + 1]; assert.ok(!/-en\b/.test(langs), `no exclusion: ${langs}`); } finally { await r.cleanup(); } }); test("fetched again with the SAME content: the stored form stays, its mtime unchanged; the new copy dropped", async () => { const r = await runWith({ [EN]: OLD }); try { assert.deepEqual(r.captions, [`${EN}.zst`]); assert.equal((await stat(path.join(r.videoDir, `${EN}.zst`))).mtimeMs, r.storedMtime, "nothing moved: the index sees nothing"); assert.match(r.log, /Captions transcript\.en\.vtt: fetched again with the same content; the stored track is kept/); } finally { await r.cleanup(); } }); test("fetched again with NEW content that has cues: it is the track, and the stored one is gone", async () => { const NEW = vtt("the corrected manual words"); const r = await runWith({ [EN]: NEW }); try { assert.deepEqual(r.captions, [EN]); assert.equal(await readFile(path.join(r.videoDir, EN), "utf8"), NEW); assert.match(r.log, /Captions transcript\.en\.vtt: fetched again with new content; the new track replaces the stored one \(2 cues/); } finally { await r.cleanup(); } }); test("a video that is gone returns nothing: the stored caption stays", async () => { const r = await runWith({}, { gone: true }); try { assert.deepEqual(r.captions, [`${EN}.zst`]); assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD); assert.match(r.log, /Captions transcript\.en\.vtt: nothing was fetched; the stored track is kept/); } finally { await r.cleanup(); } }); test("a fetch that left a .part: the stored track untouched", async () => { const r = await runWith({ [`${EN}.part`]: "WEBVTT\n\n00:00:00.000 --> 00:0" }); try { assert.ok(r.captions.includes(`${EN}.zst`)); assert.ok(!r.captions.includes(EN)); assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD); assert.match(r.log, /Captions transcript\.en\.vtt: the fetch did not finish \(a \.part\); the stored track is kept/); } finally { await r.cleanup(); } }); for (const [what, body] of [["an empty file", ""], ["a header with no cue", "WEBVTT\n\n"]] as const) { test(`fetched again as ${what}: dropped, the stored track untouched`, async () => { const r = await runWith({ [EN]: body }); try { assert.deepEqual(r.captions, [`${EN}.zst`]); assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD); assert.match(r.log, /Captions transcript\.en\.vtt: fetched again with no cues; dropped, the stored track is kept/); } finally { await r.cleanup(); } }); } test("a track that is NEW (not stored before) is not settled: it lands as yt-dlp wrote it", async () => { const ORIG = vtt("what was said"); const r = await runWith({ [EN]: OLD, "transcript.en-orig.vtt": ORIG }); try { assert.deepEqual(r.captions, ["transcript.en-orig.vtt", `${EN}.zst`]); assert.doesNotMatch(r.log, /Captions transcript\.en-orig\.vtt/); } finally { await r.cleanup(); } }); test("replaceAutoSubs's audio download (transcribe handling) asks for no caption and leaves the stored one untouched", async () => { const r = await runWith({ [EN]: vtt("must not land") }, { handling: "transcribe" }); try { assert.equal(r.subPasses.length, 0, "no subtitle pass"); assert.ok(r.captions.includes(`${EN}.zst`)); assert.ok(!r.captions.includes(EN)); assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD); assert.doesNotMatch(r.log, /Captions transcript\.en\.vtt/); } finally { await r.cleanup(); } }); // REVIEW-2 N1: the new plain file and its dir are fsynced BEFORE the stored // copy goes (yt-dlp never fsyncs; a power cut must not leave a zero-length // caption and no stored form). The seam runs between the two. test("replaced: the new file is synced while the stored copy is still there; only then the stored copy goes", async () => { const { setRefetchSyncedHookForTest, settleRefetchedCaptions } = await import("../lib/storedText-write-server"); const { mkdtemp: mk } = await import("node:fs/promises"); const dir = path.join(await mk(path.join(tmpdir(), "settle-order-")), "channels", "c", "data", "v1"); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, EN), OLD); await storeFixture(dir, EN); await writeFile(path.join(dir, EN), vtt("new words")); const seen: string[][] = []; setRefetchSyncedHookForTest(async (d) => void seen.push((await readdir(d)).sort())); try { const out = await settleRefetchedCaptions(dir, ["en"]); assert.equal(out[0].status, "replaced"); } finally { setRefetchSyncedHookForTest(undefined); } assert.deepEqual(seen, [[".stored-text.lock", EN, `${EN}.zst`]], "synced with both forms on disk (under the file's lock)"); assert.deepEqual((await readdir(dir)).sort(), [EN]); await rm(path.dirname(path.dirname(path.dirname(path.dirname(dir)))), { recursive: true, force: true }); });