import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { ChannelConfig } from "../lib/channelConfig"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/storedText.chat.test.ts // // THE CHAT IS STILL FOUND BY EVERY READER AFTER IT IS COMPRESSED (lane // text-compress, slice 1). Each case builds a video dir whose raw replay is // `transcript.live_chat.json.zst` only — a real file, and a tier link into // the channel's `media/` — and asks every reader of the raw chat what it // sees. Before this slice the track vanished and the plan FETCHED the whole // replay again. Temp corpus, no network, no yt-dlp. const ROOT = await mkdtemp(path.join(tmpdir(), "stored-chat-")); const CORPUS = path.join(ROOT, "transcripts"); process.env.TRANSCRIPTS_DIR = CORPUS; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await mkdir(CORPUS, { recursive: true }); await writeFile(process.env.SETTINGS_FILE, "{}"); test.after(() => rm(ROOT, { recursive: true, force: true })); const { getPaths } = await import("../lib/paths"); const { liveChatPlan, renormalizeChatRefusal } = await import("./fetchLiveChat"); const { normalizeLiveChat, isLiveChatCuesFresh } = await import("./normalizeLiveChat"); const { readSubTracks } = await import("../lib/videoStatus"); const { trackOnDisk, subLangsForVideo } = await import("../ytdlp/runYtdlp"); const { youtubeHandlingArgs } = await import("../ytdlp/downloadOneManaged"); const { storeFixture } = await import("../testing/storedTextFixture"); const paths = getPaths(); const SLUG = "synth-chat"; const CONFIG = { handling: "youtube", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig; const CHAT = "transcript.live_chat.json"; function chatLine(sec: number, author: string, text: string): string { return JSON.stringify({ replayChatItemAction: { actions: [ { addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text }] }, authorName: { simpleText: author } } }, }, }, ], videoOffsetTimeMsec: String(sec * 1000), }, }); } const REPLAY = [chatLine(12, "viewer1", "lol"), chatLine(14, "viewer2", "LMAO"), chatLine(30, "viewer3", "W")].join("\n") + "\n"; const channelDir = path.join(CORPUS, "channels", SLUG); async function video(id: string, opts: { tiered?: boolean } = {}): Promise { const dir = path.join(channelDir, "data", id); await mkdir(dir, { recursive: true }); await writeFile(path.join(channelDir, "config.json"), JSON.stringify(CONFIG)); await writeFile( path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: "Synth stream", webpage_url: `https://www.youtube.com/watch?v=${id}`, was_live: true }), ); if (opts.tiered) { const media = path.join(channelDir, "media", id); await mkdir(media, { recursive: true }); await writeFile(path.join(media, CHAT), REPLAY); await symlink(path.join("..", "..", "media", id, CHAT), path.join(dir, CHAT)); } else { await writeFile(path.join(dir, CHAT), REPLAY); } return dir; } const cuesOf = async (dir: string) => JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")).cues; for (const tiered of [false, true]) { const how = tiered ? "a tier link" : "a real file"; test(`compressed as ${how}: the live_chat track is listed under its plain name`, async () => { const dir = await video(`list${tiered ? "t" : "r"}`, { tiered }); await storeFixture(dir, CHAT); assert.deepEqual( (await readSubTracks(dir)).map((t) => [t.track, t.filename]), [["live_chat", CHAT]], ); }); test(`compressed as ${how}: normalize reads it and writes the same cues`, async () => { const id = `norm${tiered ? "t" : "r"}`; const dir = await video(id, { tiered }); assert.equal((await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, force: true, tier: false })).status, "wrote"); const fromPlain = await cuesOf(dir); await storeFixture(dir, CHAT); // Fresh: the stored form carries the plain file's times exactly. assert.equal((await isLiveChatCuesFresh(dir)).fresh, true); assert.equal((await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, tier: false })).status, "fresh"); assert.equal((await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, force: true, tier: false })).status, "wrote"); assert.deepEqual(await cuesOf(dir), fromPlain); assert.equal(fromPlain.length, 3); }); test(`compressed as ${how}: the plan normalizes or says fresh — it NEVER fetches`, async () => { const id = `plan${tiered ? "t" : "r"}`; const dir = await video(id, { tiered }); await storeFixture(dir, CHAT); // No cues yet: the raw on disk is normalized, not fetched again. assert.deepEqual(await liveChatPlan(paths, SLUG, id, CONFIG), { kind: "normalize" }); await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, tier: false }); assert.equal((await liveChatPlan(paths, SLUG, id, CONFIG)).kind, "fresh"); // A re-normalize finds the raw chat on disk. assert.equal(await renormalizeChatRefusal(paths, SLUG, id), null); }); test(`compressed as ${how}: the missing-subs prefilter sees the chat on disk`, async () => { const dir = await video(`subs${tiered ? "t" : "r"}`, { tiered }); await storeFixture(dir, CHAT); const { readdir } = await import("node:fs/promises"); const entries = await readdir(dir); assert.equal(trackOnDisk(entries, "live_chat"), true); // And a fetch for another missing track leaves the chat out: yt-dlp's own // skip would not see the stored form and would fetch the replay again. assert.equal(subLangsForVideo(entries, "en.*,live_chat"), "en.*"); assert.equal(subLangsForVideo(["transcript.live_chat.json"], "en.*,live_chat"), "en.*,live_chat"); }); } test("a download over a stored chat leaves the chat out of its sub-langs", () => { const langs = (args: string[]) => args[args.indexOf("--sub-langs") + 1]; assert.equal(langs(youtubeHandlingArgs(CONFIG, false, false)), "en.*,live_chat"); assert.equal(langs(youtubeHandlingArgs(CONFIG, false, true)), "en.*"); }); test("with no chat in either form the plan still fetches (the control)", async () => { const id = "nochat"; const dir = await video(id); await rm(path.join(dir, CHAT)); assert.equal((await liveChatPlan(paths, SLUG, id, CONFIG)).kind, "fetch"); assert.notEqual(await renormalizeChatRefusal(paths, SLUG, id), null); });