import { test } from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdir, mkdtemp, readFile, readdir, rm, 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/chatOnlyStored.test.ts // // REVIEW-1 F2: THE CHAT-ONLY PASS OVER A CHAT ALREADY ON DISK. A title-filter // rejection of a livestream on a `chat-only` channel runs a yt-dlp pass with // `--sub-langs live_chat`. yt-dlp's own "already present" skip sees only the // plain `transcript.live_chat.json`, so over a chat stored compressed the pass // fetched the whole replay again and landed a second copy beside it. Now the // pass asks the disk first (either form) and normalizes what is here. The // yt-dlp is a temp node script that logs every argv; no network. const ID = "Zz0chatonly"; const VIDEO = `https://www.youtube.com/watch?v=${ID}`; const CHAT = "transcript.live_chat.json"; // The fake: the metadata prefetch writes meta.json as the info json; a chat // pass writes a NEW plain chat (what yt-dlp would, not seeing a .zst). 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 arg = (f) => { const i = argv.indexOf(f); return i < 0 ? undefined : argv[i + 1]; }; 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 (arg("--sub-langs") === "live_chat") { fs.writeFileSync(path.join(dir, "${CHAT}"), fs.readFileSync(path.join(root, "refetched.json"))); process.exit(0); } console.error("fake: unknown invocation " + argv.join(" ")); process.exit(2); `; function chatLine(sec: number, text: string): string { return JSON.stringify({ replayChatItemAction: { actions: [{ addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text }] }, authorName: { simpleText: "v" } } } } }], videoOffsetTimeMsec: String(sec * 1000), }, }); } const WHOLE = [chatLine(5, "first"), chatLine(9, "second"), chatLine(20, "third")].join("\n") + "\n"; const TRIMMED = chatLine(5, "first") + "\n"; const META = { id: ID, title: "A stream", live_status: "was_live", was_live: true, duration: 3600, webpage_url: VIDEO }; async function runWith(seed: "stored" | "plain" | "none") { const root = await mkdtemp(path.join(tmpdir(), "chat-only-stored-")); 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 writeFile(path.join(root, "refetched.json"), TRIMMED); 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)); if (seed !== "none") { await writeFile(path.join(videoDir, CHAT), WHOLE); if (seed === "stored") await storeFixture(videoDir, CHAT); } let log = ""; const record = await downloadOneManaged({ channelSlug: "c", channelConfig: { handling: "youtube", url: "https://www.youtube.com/@c/streams", downloadFilter: { include: "^nothing matches this$", rejectedLivestreams: "chat-only" }, } 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, argvs, chatPasses: argvs.filter((a) => a.includes("live_chat")), files: (await readdir(videoDir)).sort(), cleanup: () => rm(root, { recursive: true, force: true }), }; } for (const seed of ["stored", "plain"] as const) { test(`a chat-only video whose chat is on disk (${seed}) is not fetched again: normalized from what is here`, async () => { const r = await runWith(seed); try { assert.deepEqual(r.chatPasses, [], `no --sub-langs live_chat pass: ${JSON.stringify(r.argvs)}`); assert.equal(r.record.status, "chat-only", r.log); assert.match(r.log, /already on disk; not fetched again/); assert.equal(await readStoredText(r.videoDir, CHAT, "utf8"), WHOLE, "the whole capture, not a re-fetch"); assert.ok(r.files.includes("live_chat.cues.json"), `normalized: ${r.files.join(", ")}`); // Exactly the form that was there. assert.deepEqual( r.files.filter((f) => f.startsWith("transcript.live_chat")), seed === "stored" ? [`${CHAT}.zst`] : [CHAT], ); } finally { await r.cleanup(); } }); } test("a chat-only video with no chat on disk still runs the chat pass (the control)", async () => { const r = await runWith("none"); try { assert.equal(r.chatPasses.length, 1, JSON.stringify(r.argvs)); assert.equal(r.record.status, "chat-only", r.log); assert.equal(await readStoredText(r.videoDir, CHAT, "utf8"), TRIMMED); } finally { await r.cleanup(); } });