commit ea50edfe47e36370b599d4a86b0ba1778221e224
parent e280fd19492a91e5d1cf8612838764cdcb44a6e4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 11:58:56 -0400
chat: fetch one video's live chat replay — `pnpm ops fetch-chat` and Media tools → Fetch live chat
The chat-only yt-dlp pass the managed download runs for a chat-only channel,
for any one archived video: the same argv (liveChatOnlyArgs, now exported —
the channel's cookies and the platform's live pace), on the platform's
download queue, the held-platform and cooldown refusals and the backoff
record the metadata refresh uses, then live_chat.cues.json. YouTube only: any
other platform answers "no chat fetcher for <platform>" (info, no job), as do
a chat already here and fresh and a video never live; a raw replay on disk
with stale cues is normalized without a fetch; a pass that finds no replay
ends done and says so.
Registers the fetch-chat kind (needsMedia: it writes the raw replay; ingest)
and the find-clips kind the next commit runs.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 667 insertions(+), 6 deletions(-)
diff --git a/common/controller/fetchLiveChat.test.ts b/common/controller/fetchLiveChat.test.ts
@@ -0,0 +1,224 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { AttemptOutcome } from "../ytdlp/runOneYtdlp";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchLiveChat.test.ts
+//
+// One video's chat replay (release 36, lane A). The yt-dlp runner is a stub
+// that records its argv and writes the JSON-lines replay where the
+// `subtitle:` template says — no yt-dlp, no network. Every case is a temp
+// corpus; the job cases run through the real registry over it.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "fetch-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, "{}");
+
+const { getPaths } = await import("../lib/paths");
+const {
+ CHAT_PLATFORMS,
+ fetchLiveChat,
+ liveChatPlan,
+ noChatFetcherSentence,
+ runFetchChatJob,
+} = await import("./fetchLiveChat");
+const { liveChatOnlyArgs } = await import("../ytdlp/downloadOneManaged");
+
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-stream";
+const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig;
+const NO_COOKIES = { cookies: undefined, mode: "when-required" } as const;
+
+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";
+
+async function video(id: string, meta: Record<string, unknown>): Promise<string> {
+ const dir = path.join(CORPUS, "channels", SLUG, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG));
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: "Synth stream", ...meta }));
+ return dir;
+}
+
+// The stub: records the argv, writes the replay under the subtitle template.
+function stubRunner(o: { writes?: string | null; exitCode?: number; stderr?: string } = {}) {
+ const calls: { cwd: string; args: string[] }[] = [];
+ const run = async (cwd: string, args: string[]): Promise<AttemptOutcome> => {
+ calls.push({ cwd, args });
+ const i = args.findIndex((a) => a.startsWith("subtitle:"));
+ if (o.writes !== null && (o.exitCode ?? 0) === 0) {
+ const base = args[i + 0].slice("subtitle:".length);
+ await writeFile(path.join(cwd, `${base}.live_chat.json`), o.writes ?? REPLAY);
+ }
+ return { exitCode: o.exitCode ?? 0, stderrTail: o.stderr ?? "", archiveLine: null, formatLine: null };
+ };
+ return { run, calls };
+}
+
+const log = () => {
+ const lines: string[] = [];
+ return { lines, onLog: (s: string) => lines.push(s) };
+};
+
+test("the chat pass is the managed download's chat-only command line, paced", () => {
+ const url = "https://www.youtube.com/watch?v=abc";
+ const args = liveChatOnlyArgs(CONFIG, undefined, url, 7);
+ assert.deepEqual(args.slice(0, 2), ["--ignore-config", "--restrict-filenames"]);
+ assert.ok(args.includes("--skip-download"));
+ assert.deepEqual(args.slice(args.indexOf("--sub-langs"), args.indexOf("--sub-langs") + 2), ["--sub-langs", "live_chat"]);
+ assert.ok(args.includes("--no-write-info-json"), "the metadata on disk is never rewritten");
+ assert.equal(args[args.indexOf("--sleep-requests") + 1], "7", "the platform's pace");
+ assert.deepEqual(args.slice(-2), ["--", url]);
+ assert.ok(CHAT_PLATFORMS.has("youtube"));
+});
+
+test("plan: YouTube fetches; another platform has no fetcher; a never-live video has no replay", async () => {
+ await video("yt1", { webpage_url: "https://www.youtube.com/watch?v=yt1", was_live: true });
+ assert.deepEqual(await liveChatPlan(paths, SLUG, "yt1", CONFIG), {
+ kind: "fetch",
+ url: "https://www.youtube.com/watch?v=yt1",
+ platform: "youtube",
+ });
+ await video("tw1", { webpage_url: "https://www.twitch.tv/videos/123" });
+ const tw = await liveChatPlan(paths, SLUG, "tw1", CONFIG);
+ assert.deepEqual(tw, { kind: "no-fetcher", platform: "twitch" });
+ assert.equal(noChatFetcherSentence("twitch"), "no chat fetcher for twitch: only YouTube's chat replay is fetched");
+ await video("nl1", { webpage_url: "https://www.youtube.com/watch?v=nl1", live_status: "not_live" });
+ assert.equal((await liveChatPlan(paths, SLUG, "nl1", CONFIG)).kind, "not-live");
+ assert.equal((await liveChatPlan(paths, SLUG, "nope", CONFIG)).kind, "refused");
+ assert.equal((await liveChatPlan(paths, SLUG, "../x", CONFIG)).kind, "refused");
+});
+
+test("a fetch writes the replay and its cues; a second plan says fresh", async () => {
+ const dir = await video("yt2", { webpage_url: "https://www.youtube.com/watch?v=yt2", was_live: true });
+ const { run, calls } = stubRunner();
+ const l = log();
+ const r = await fetchLiveChat({
+ paths,
+ slug: SLUG,
+ videoId: "yt2",
+ videoUrl: "https://www.youtube.com/watch?v=yt2",
+ channelConfig: CONFIG,
+ cookiePolicy: NO_COOKIES,
+ onLog: l.onLog,
+ signal: new AbortController().signal,
+ run,
+ paceSeconds: 3,
+ });
+ assert.equal(r.status, "fetched");
+ assert.equal(r.status === "fetched" && r.messages, 3);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].cwd, path.join(CORPUS, "channels", SLUG));
+ const cues = JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8"));
+ assert.equal(cues.source, "live_chat");
+ assert.equal(cues.cues.length, 3);
+ assert.equal(cues.cues[0].start, 12);
+ assert.match(l.lines.join(""), /3 message\(s\) in live_chat\.cues\.json/);
+ assert.equal((await liveChatPlan(paths, SLUG, "yt2", CONFIG)).kind, "fresh");
+});
+
+test("a pass that writes nothing is an answer, not a failure", async () => {
+ const dir = await video("yt3", { webpage_url: "https://www.youtube.com/watch?v=yt3" });
+ const { run } = stubRunner({ writes: null });
+ const l = log();
+ const r = await fetchLiveChat({
+ paths, slug: SLUG, videoId: "yt3", videoUrl: "https://www.youtube.com/watch?v=yt3",
+ channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run,
+ });
+ assert.deepEqual(r, { status: "none" });
+ assert.match(l.lines.join(""), /No chat replay for yt3/);
+ assert.deepEqual((await readdir(dir)).sort(), ["metadata.info.json"]);
+});
+
+test("a rate-limited pass records the cooldown and fails; an auth gate retries once with cookies", async () => {
+ await video("yt4", { webpage_url: "https://www.youtube.com/watch?v=yt4" });
+ let backoffs = 0;
+ const limited = stubRunner({ exitCode: 1, stderr: "ERROR: [youtube] yt4: HTTP Error 429: Too Many Requests" });
+ await assert.rejects(
+ fetchLiveChat({
+ paths, slug: SLUG, videoId: "yt4", videoUrl: "https://www.youtube.com/watch?v=yt4",
+ channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: new AbortController().signal,
+ run: limited.run, onPlatformBackoff: () => void backoffs++,
+ }),
+ /rate-limited the chat fetch/,
+ );
+ assert.equal(backoffs, 1);
+
+ const calls: string[][] = [];
+ const authThenOk = async (cwd: string, args: string[]): Promise<AttemptOutcome> => {
+ calls.push(args);
+ if (calls.length === 1) {
+ return { exitCode: 1, stderrTail: "ERROR: [youtube] yt4: Sign in to confirm your age", archiveLine: null, formatLine: null };
+ }
+ const base = args[args.findIndex((a) => a.startsWith("subtitle:"))].slice("subtitle:".length);
+ await writeFile(path.join(cwd, `${base}.live_chat.json`), REPLAY);
+ return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
+ };
+ const r = await fetchLiveChat({
+ paths, slug: SLUG, videoId: "yt4", videoUrl: "https://www.youtube.com/watch?v=yt4",
+ channelConfig: CONFIG, cookiePolicy: { cookies: "firefox", mode: "when-required" },
+ onLog: () => {}, signal: new AbortController().signal, run: authThenOk,
+ });
+ assert.equal(r.status, "fetched");
+ assert.equal(calls.length, 2);
+ assert.ok(!calls[0].includes("--cookies-from-browser"));
+ assert.ok(calls[1].includes("--cookies-from-browser"));
+});
+
+test("the job: refusals before any job (info for a skip), a fetch job, a normalize-only job", async () => {
+ await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG));
+ const tw = await runFetchChatJob({ paths, slug: SLUG, videoId: "tw1", channelConfig: CONFIG, cookiePolicy: NO_COOKIES });
+ assert.deepEqual(tw, { ok: false, info: true, error: "no chat fetcher for twitch: only YouTube's chat replay is fetched" });
+ const fresh = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES });
+ assert.ok(!fresh.ok && fresh.info && /already here/.test(fresh.error));
+ const missing = await runFetchChatJob({ paths, slug: SLUG, videoId: "nope", channelConfig: CONFIG, cookiePolicy: NO_COOKIES });
+ assert.ok(!missing.ok && !missing.info);
+
+ const dir = await video("yt5", { webpage_url: "https://www.youtube.com/watch?v=yt5", was_live: true });
+ const { run, calls } = stubRunner();
+ const job = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt5", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run });
+ assert.ok(job.ok, JSON.stringify(job));
+ void job.stream.cancel();
+ const done = await job.done;
+ assert.equal(done.status, "done");
+ assert.equal(calls.length, 1);
+ assert.ok((await readdir(dir)).includes("live_chat.cues.json"));
+
+ // The raw replay on disk with stale cues: normalized, no spawn.
+ const dir6 = await video("yt6", { webpage_url: "https://www.youtube.com/watch?v=yt6", was_live: true });
+ await writeFile(path.join(dir6, "transcript.live_chat.json"), REPLAY);
+ await writeFile(path.join(dir6, "live_chat.cues.json"), "{}");
+ const old = new Date(Date.now() - 60_000);
+ await utimes(path.join(dir6, "live_chat.cues.json"), old, old);
+ const spawn = stubRunner();
+ const norm = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt6", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run });
+ assert.ok(norm.ok);
+ void norm.stream.cancel();
+ assert.equal((await norm.done).status, "done");
+ assert.equal(spawn.calls.length, 0, "no network for a replay already here");
+ assert.equal(JSON.parse(await readFile(path.join(dir6, "live_chat.cues.json"), "utf8")).cues.length, 3);
+});
diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts
@@ -0,0 +1,312 @@
+// ONE VIDEO'S LIVE CHAT REPLAY, AND NOTHING ELSE — `pnpm ops fetch-chat
+// {slug, id}` (release 36, lane A), and the chat step of the find-clips job.
+//
+// The chat-only yt-dlp pass already existed, but only inside the managed
+// download's filter branch (a channel whose `rejectedLivestreams` is
+// "chat-only"): a video already archived for its media had no way to fetch
+// its chat alone. This runs THE SAME command line (downloadOneManaged.ts
+// liveChatOnlyArgs: the channel's args, its cookies and the platform's live
+// pace, then the refusals that keep it from fetching anything else), then
+// normalizes what landed into live_chat.cues.json (normalizeLiveChat — which
+// also tiers the raw replay, the one big file here, into media/).
+//
+// PACED LIKE EVERY YOUTUBE REQUEST: the job sits on the platform's DOWNLOAD
+// queue, so it waits behind a sync or a download on that platform rather than
+// bursting beside one; the argv carries the platform's live `--sleep-requests`;
+// a held platform or one in a rate-limit cooldown is refused before any job
+// exists (`info: true` — nothing is wrong, the source is resting); a
+// rate-limited pass records the platform's cooldown; a clean one settles it.
+// Cookies follow the channel's policy exactly as the metadata refresh's do:
+// up front for "always", once on an auth failure for "when-required".
+//
+// WHAT IS NOT A FAILURE:
+// - a video on another platform: no fetcher for its chat ("no chat fetcher
+// for twitch") — refused before a job, `info: true`;
+// - the chat already here and fresh (isLiveChatCuesFresh) — the same;
+// - a raw replay already here whose cues are stale: normalized, no network;
+// - a pass that writes nothing: chat replay is off for that stream, or it
+// was never live. The job ends `done` and says so.
+//
+// `needsMedia` (jobs/jobKinds.ts): it WRITES the raw replay, which is a
+// tierable big file, and the normalizer moves it into the channel's media/.
+
+import path from "node:path";
+import { readFile, readdir, stat } from "node:fs/promises";
+import {
+ AUTH_RETRY_CLASSES,
+ classifyDownloadFailure,
+ parseUnavailableFromStderr,
+} from "../lib/availability";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { assertChannelTextReadable } from "../lib/channelMedia";
+import {
+ DEFAULT_COOKIE_MODE,
+ alwaysCookies,
+ authRetryCookies,
+ type ResolvedCookiePolicy,
+} from "../lib/cookiePolicy";
+import { detectPlatform } from "../lib/platform";
+import type { Paths } from "../lib/paths";
+import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys";
+import { LIVE_CHAT_CUES_FILENAME, LIVE_CHAT_FILENAME, META_FILENAME } from "../lib/videoStatus";
+import {
+ heldPlatformRefusal,
+ platformCooldownRemainingMs,
+ recordDownloadBackoff,
+ recordPlatformClean,
+} from "../jobs/downloadBackoff";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { liveChatOnlyArgs } from "../ytdlp/downloadOneManaged";
+import { runOneYtdlp, type AttemptOutcome } from "../ytdlp/runOneYtdlp";
+import { isLiveChatCuesFresh, normalizeLiveChat, readNormalizedLiveChat } from "./normalizeLiveChat";
+import { isVideoIdSegment, notFetchedRefusal } from "./refreshVideoMetadata";
+import { findVideoSourceUrl } from "./undownloadedVideos";
+
+export const FETCH_CHAT_JOB_KIND = "fetch-chat";
+
+// The platforms whose chat replay a fetcher exists for. yt-dlp writes a
+// `live_chat` subtitle track for YouTube only.
+export const CHAT_PLATFORMS: ReadonlySet<string> = new Set(["youtube"]);
+
+/** What the chat of one video needs, from the disk and its metadata alone. */
+export type LiveChatPlan =
+ | { kind: "fresh"; cuesPath: string }
+ // The raw replay is here; its cues are missing or stale: normalize only.
+ | { kind: "normalize" }
+ | { kind: "no-fetcher"; platform: string }
+ // The metadata says the video was never live: there is no replay to ask for.
+ | { kind: "not-live"; liveStatus: string }
+ | { kind: "fetch"; url: string; platform: string }
+ | { kind: "refused"; error: string };
+
+async function isDirectory(p: string): Promise<boolean> {
+ return stat(p).then((s) => s.isDirectory(), () => false);
+}
+
+async function liveStatusOf(videoDir: string): Promise<string | null> {
+ try {
+ const meta = JSON.parse(await readFile(path.join(videoDir, META_FILENAME), "utf8")) as {
+ live_status?: unknown;
+ was_live?: unknown;
+ };
+ if (meta.was_live === true) return "was_live";
+ return typeof meta.live_status === "string" ? meta.live_status : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The sentence for a video whose chat has no fetcher. */
+export function noChatFetcherSentence(platform: string): string {
+ return `no chat fetcher for ${platform}: only YouTube's chat replay is fetched`;
+}
+
+export async function liveChatPlan(
+ paths: Paths,
+ slug: string,
+ videoId: string,
+ config: ChannelConfig,
+): Promise<LiveChatPlan> {
+ if (!isVideoIdSegment(videoId)) {
+ return { kind: "refused", error: `"${videoId}" is not a video id (one path segment)` };
+ }
+ const videoDir = path.join(paths.channelsDir, slug, "data", videoId);
+ if (!(await isDirectory(videoDir))) return { kind: "refused", error: notFetchedRefusal(videoId, slug) };
+ const fresh = await isLiveChatCuesFresh(videoDir);
+ if (fresh.fresh) return { kind: "fresh", cuesPath: fresh.cuesPath };
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (entries.includes(LIVE_CHAT_FILENAME) && entries.includes(META_FILENAME)) return { kind: "normalize" };
+ const url = await findVideoSourceUrl(paths, slug, videoId, config);
+ if (!url) {
+ return {
+ kind: "refused",
+ error: "Could not determine the video URL: no metadata.info.json and the playlist does not contain a matching entry.",
+ };
+ }
+ const platform = detectPlatform(url) ?? "unknown";
+ if (!CHAT_PLATFORMS.has(platform)) return { kind: "no-fetcher", platform };
+ const live = await liveStatusOf(videoDir);
+ if (live === "not_live") return { kind: "not-live", liveStatus: live };
+ return { kind: "fetch", url, platform };
+}
+
+function succeeded(exitCode: number | null): boolean {
+ // yt-dlp: 0 = clean, 101 = a clean stop.
+ return exitCode === 0 || exitCode === 101;
+}
+
+function tail(stderr: string): string {
+ return stderr.trim().split("\n").slice(-3).join(" / ");
+}
+
+export type ChatRunner = (cwd: string, args: string[]) => Promise<AttemptOutcome>;
+
+export type FetchLiveChatOpts = {
+ paths: Paths;
+ slug: string;
+ videoId: string;
+ videoUrl: string;
+ channelConfig: ChannelConfig;
+ cookiePolicy?: ResolvedCookiePolicy;
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+ onPlatformBackoff?: () => Promise<void> | void;
+ onPlatformClean?: () => Promise<string | null> | string | null;
+ // Test seams: the spawn, and the platform pace in the argv.
+ run?: ChatRunner;
+ paceSeconds?: number;
+};
+
+export type FetchLiveChatResult =
+ | { status: "fetched"; messages: number; cuesPath: string }
+ | { status: "none" };
+
+/** The pass, then the normalize. Throws on a failed pass (the job ends `failed`). */
+export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveChatResult> {
+ const channelDir = path.join(opts.paths.channelsDir, opts.slug);
+ const videoDir = path.join(channelDir, "data", opts.videoId);
+ const policy: ResolvedCookiePolicy = opts.cookiePolicy ?? { cookies: undefined, mode: DEFAULT_COOKIE_MODE };
+ const run: ChatRunner =
+ opts.run ??
+ ((cwd, args) => runOneYtdlp({ ytdlpBin: opts.paths.ytdlpBin, onLog: opts.onLog, signal: opts.signal }, cwd, args));
+ if (!(await isDirectory(videoDir))) throw new Error(notFetchedRefusal(opts.videoId, opts.slug));
+ const pass = (cookies: string | undefined) =>
+ run(channelDir, liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl, opts.paceSeconds));
+
+ opts.onLog(`Fetching the live chat replay of ${opts.videoId} from ${opts.videoUrl} (no media)\n`);
+ const firstCookies = alwaysCookies(policy);
+ let outcome = await pass(firstCookies);
+ if (!succeeded(outcome.exitCode) && !opts.signal.aborted) {
+ const cls = parseUnavailableFromStderr(outcome.stderrTail);
+ const retryCookies = authRetryCookies(policy);
+ if (
+ classifyDownloadFailure(outcome.stderrTail, cls) !== "rate_limit" &&
+ AUTH_RETRY_CLASSES.has(cls) &&
+ retryCookies !== undefined &&
+ !firstCookies
+ ) {
+ opts.onLog(`The chat fetch needs a login (${cls}); retrying with --cookies-from-browser ${retryCookies}\n`);
+ outcome = await pass(retryCookies);
+ }
+ }
+ if (opts.signal.aborted) throw new Error("Cancelled");
+ if (!succeeded(outcome.exitCode)) {
+ const cls = parseUnavailableFromStderr(outcome.stderrTail);
+ if (classifyDownloadFailure(outcome.stderrTail, cls) === "rate_limit") {
+ await opts.onPlatformBackoff?.();
+ throw new Error(
+ `The source rate-limited the chat fetch of ${opts.videoId}; a per-platform cooldown has been recorded. ` +
+ `(${tail(outcome.stderrTail)})`,
+ );
+ }
+ throw new Error(`yt-dlp could not fetch the chat of ${opts.videoId} (exit ${outcome.exitCode ?? "null"}): ${tail(outcome.stderrTail)}`);
+ }
+ try {
+ const line = await opts.onPlatformClean?.();
+ if (line) opts.onLog(line);
+ } catch {
+ /* shared-state write is best-effort */
+ }
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (!entries.includes(LIVE_CHAT_FILENAME)) {
+ opts.onLog(`No chat replay for ${opts.videoId}: the source has none (chat replay off, or never live). Nothing written.\n`);
+ return { status: "none" };
+ }
+ return normalizeChat(opts, videoDir);
+}
+
+async function normalizeChat(
+ opts: Pick<FetchLiveChatOpts, "slug" | "videoId" | "channelConfig" | "onLog">,
+ videoDir: string,
+): Promise<FetchLiveChatResult> {
+ const out = await normalizeLiveChat({
+ videoDir,
+ channelSlug: opts.slug,
+ ...(opts.channelConfig.name ? { configName: opts.channelConfig.name } : {}),
+ force: true,
+ log: (m) => opts.onLog(`${m}\n`),
+ });
+ if (out.status === "skipped") {
+ throw new Error(`the chat of ${opts.videoId} could not be normalized (${out.reason})`);
+ }
+ const doc = await readNormalizedLiveChat(out.cuesPath);
+ const messages = doc?.cues?.length ?? 0;
+ opts.onLog(`Live chat of ${opts.videoId}: ${messages} message(s) in ${LIVE_CHAT_CUES_FILENAME}\n`);
+ return { status: "fetched", messages, cuesPath: out.cuesPath };
+}
+
+export type FetchChatJobOpts = {
+ paths: Paths;
+ slug: string;
+ videoId: string;
+ channelConfig: ChannelConfig;
+ cookiePolicy: ResolvedCookiePolicy;
+ queueKey?: string;
+ afterRun?: () => void | Promise<void>;
+ run?: ChatRunner;
+};
+
+// Every refusal before any job, in the sentences the rest of the app uses.
+export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamActionResult> {
+ const { paths, slug, videoId, channelConfig } = opts;
+ try {
+ await assertChannelTextReadable(paths, slug, channelConfig);
+ } catch (err) {
+ return { ok: false, error: (err as Error).message };
+ }
+ const plan = await liveChatPlan(paths, slug, videoId, channelConfig);
+ switch (plan.kind) {
+ case "refused":
+ return { ok: false, error: plan.error };
+ case "fresh":
+ return { ok: false, info: true, error: `the live chat of ${videoId} is already here (${LIVE_CHAT_CUES_FILENAME}, fresh)` };
+ case "no-fetcher":
+ return { ok: false, info: true, error: noChatFetcherSentence(plan.platform) };
+ case "not-live":
+ return { ok: false, info: true, error: `${videoId} was never live (live_status ${plan.liveStatus}): there is no chat replay` };
+ case "normalize":
+ case "fetch":
+ break;
+ }
+ if (plan.kind === "fetch") {
+ const held = await heldPlatformRefusal(plan.platform, "The chat fetch", paths);
+ if (held) return { ok: false, info: true, error: held };
+ const remainingMs = await platformCooldownRemainingMs(plan.platform, paths);
+ if (remainingMs > 0) {
+ return {
+ ok: false,
+ info: true,
+ error: `${plan.platform} is in a rate-limit cooldown (${Math.ceil(remainingMs / 1000)}s remaining). Fetch the chat once the cooldown lapses.`,
+ };
+ }
+ }
+ const videoDir = path.join(paths.channelsDir, slug, "data", videoId);
+ return runManagedFunction({
+ kind: FETCH_CHAT_JOB_KIND,
+ queueKey: resolveQueueKey(downloadQueueKey(channelConfig), opts.queueKey),
+ paths,
+ channelSlug: slug,
+ videoId,
+ fn: async (onLog, signal) => {
+ if (plan.kind === "normalize") {
+ onLog(`The chat replay of ${videoId} is on disk; normalizing it (no network).`);
+ await normalizeChat({ slug, videoId, channelConfig, onLog }, videoDir);
+ } else {
+ await fetchLiveChat({
+ paths,
+ slug,
+ videoId,
+ videoUrl: plan.url,
+ channelConfig,
+ cookiePolicy: opts.cookiePolicy,
+ onLog,
+ signal,
+ onPlatformBackoff: () => recordDownloadBackoff(plan.platform, paths),
+ onPlatformClean: () => recordPlatformClean(plan.platform, paths),
+ ...(opts.run ? { run: opts.run } : {}),
+ });
+ }
+ await opts.afterRun?.();
+ },
+ });
+}
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -681,6 +681,40 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
needsMedia: false,
needsText: true,
},
+ // ONE VIDEO'S LIVE CHAT REPLAY (release 36 lane A, controller/
+ // fetchLiveChat.ts — `pnpm ops fetch-chat`, and the find-clips job's chat
+ // step): the chat-only yt-dlp pass, then live_chat.cues.json. On the
+ // platform download queue, paced and cookie-aware like the metadata
+ // refresh. `needsMedia`: it WRITES the raw replay, a tierable big file the
+ // normalizer moves into media/. An ingest kind: the index reads the cues.
+ // Not replayable: a retry is the same ops call, which re-asks the plan.
+ "fetch-chat": {
+ kind: "fetch-chat",
+ label: "Fetch live chat",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "platform",
+ needsMedia: true,
+ },
+ // FIND CLIPS (release 36 lane A, controller/findClips.ts — the video page's
+ // Find clips, `pnpm ops find-clips`): the clip finder's chain for one video,
+ // each step skipped when its output exists — persist the source, the corpus
+ // transcript, word timings, the chat replay, diarization — then umtool's
+ // `POST /api/report/clips {mode: "new"}`, followed to the end. Its steps
+ // are jobs of their own (persist-videos, transcribe-one, fetch-chat,
+ // backfill-channel) on their own queues, waited on from here; the word
+ // timings run in this job on a worker lease. Its own queue (`find-clips`),
+ // so it never holds a queue its steps need. `needsMedia`: the word timings
+ // read the audio. Not replayable: the button asks again, and the steps
+ // already done are skipped.
+ "find-clips": {
+ kind: "find-clips",
+ label: "Find clips",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsMedia: true,
+ },
// An Odysee video's record (or the channel's listing) read from its page in
// a headless browser (release 32 R9, controller/browserLookupJob.ts), when
// yt-dlp's lookup is refused. On the platform download queue, so it never
@@ -1243,6 +1277,9 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([
"prepare-playable",
// A gone video's audio from a copy, and the copy's provenance (release 31).
"fetch-copies",
+ // One video's live chat replay, normalized into the cues the index reads
+ // (release 36 lane A).
+ "fetch-chat",
]);
export function isIngestKind(kind: string | undefined): boolean {
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -546,10 +546,29 @@ async function fetchLiveChatOnly(
channelDir: string,
cookies: string | undefined,
): Promise<AttemptOutcome> {
- return runOneYtdlp(opts, channelDir, [
+ return runOneYtdlp(
+ opts,
+ channelDir,
+ liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl),
+ );
+}
+
+// The chat-only pass's argv, run in the channel dir: the channel's own args
+// (its cookies and the platform's live pace) and then the refusals. Exported
+// for the one-video chat fetch (release 36 lane A, controller/fetchLiveChat.ts
+// — `pnpm ops fetch-chat`), so the two passes are one command line.
+export function liveChatOnlyArgs(
+ channelConfig: ChannelConfig,
+ cookies: string | undefined,
+ videoUrl: string,
+ paceSeconds?: number,
+): string[] {
+ return [
"--ignore-config",
"--restrict-filenames",
- ...channelConfigArgs(opts.channelConfig, cookies),
+ ...(paceSeconds !== undefined
+ ? channelConfigArgs(channelConfig, cookies, paceSeconds)
+ : channelConfigArgs(channelConfig, cookies)),
"--skip-download",
"--write-subs",
"--no-write-auto-subs",
@@ -559,10 +578,10 @@ async function fetchLiveChatOnly(
"--no-write-description",
"--no-write-thumbnail",
"--no-download-archive",
- ...outputArgsForUrl(opts.videoUrl),
+ ...outputArgsForUrl(videoUrl),
"--",
- opts.videoUrl,
- ]);
+ videoUrl,
+ ];
}
// Did the chat pass actually leave a chat behind? A stream with chat replay
diff --git a/editor/app/api/ops/fetch-chat/route.ts b/editor/app/api/ops/fetch-chat/route.ts
@@ -0,0 +1,23 @@
+import { fetchChatAction } from "../../../channels/[slug]/videos/[id]/mediaToolsActions";
+import { jobResponse, ops, optString, reqSlug, reqVideoId } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, id, queueKey? } -> { ok: true, jobId }
+//
+// ONE video's live chat replay, and nothing else (release 36, lane A;
+// controller/fetchLiveChat.ts): the chat-only yt-dlp pass the managed download
+// runs for a chat-only channel — the channel's cookies and the platform's live
+// pace — on the platform's download queue, then live_chat.cues.json. The video
+// page's Media tools → "Fetch live chat", and the find-clips job's chat step.
+//
+// Answered without a job, `info: true` (a skip, not an error): a video on a
+// platform with no chat fetcher ("no chat fetcher for twitch"), a chat already
+// here and fresh, a video that was never live, a held platform or one in a
+// rate-limit cooldown. Refused: an id with no data/<id>/, a channel whose text
+// cannot be read. A pass that finds no replay ends `done` and says so.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "id", "queueKey"], async (body) =>
+ jobResponse(await fetchChatAction(reqSlug(body, "slug"), reqVideoId(body, "id"), optString(body, "queueKey"))),
+ );
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx
@@ -8,6 +8,7 @@ import { cancelJobAction } from "../../../../../jobs/actions";
import {
archiveOrgRefreshAction,
attachVideoMediaAction,
+ fetchChatAction,
playableVideoAction,
waybackRefreshAction,
type RecordsRefreshResult,
@@ -41,6 +42,16 @@ export function VideoMediaTools({
<summary className="cursor-pointer text-sm font-semibold">Media tools</summary>
<div className="mt-3 flex flex-col gap-4">
<AttachFromArchive slug={slug} videoId={videoId} saved={saved} />
+ <div className="flex flex-col gap-2">
+ <h4 className="text-sm font-semibold">Live chat replay</h4>
+ <StreamActionLog
+ trigger={() => fetchChatAction(slug, videoId)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Fetch live chat"
+ runningLabel="Fetching the chat…"
+ label={`Fetch live chat of ${videoId}`}
+ />
+ </div>
{saved && (
<div className="flex flex-col gap-2">
<h4 className="text-sm font-semibold">Playable copy</h4>
diff --git a/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts b/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts
@@ -14,6 +14,9 @@
// this record with it; answered in the request
// archiveOrg `archilyzer archive-org refresh <slug>` — the channel's
// archive.org file records (offline); answered in the request
+// chat `pnpm ops fetch-chat` (release 36 lane A) — this video's live
+// chat replay alone, paced, into live_chat.cues.json — the
+// `fetch-chat` job
//
// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file).
@@ -22,7 +25,11 @@ import { revalidatePath } from "next/cache";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { refreshWaybackRecords } from "yt-dlp-transcript-common/controller/waybackRefresh";
import { refreshArchiveOrgRecords } from "yt-dlp-transcript-common/controller/archiveOrgRefresh";
-import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { runFetchChatJob } from "yt-dlp-transcript-common/controller/fetchLiveChat";
+import { resolveCookiePolicy } from "yt-dlp-transcript-common/lib/cookiePolicy";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { safeRevalidate } from "../../../../lib/safeRevalidate";
import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
import { attachMediaAction } from "../../attachMediaActions";
import { preparePlayableAction } from "../../playableActions";
@@ -46,6 +53,22 @@ export async function attachVideoMediaAction(
});
}
+export async function fetchChatAction(slug: string, videoId: string, queueKey?: string): Promise<StreamActionResult> {
+ if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` };
+ const paths = getPaths();
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `Channel "${slug}" not found` };
+ return runFetchChatJob({
+ paths,
+ slug,
+ videoId,
+ channelConfig: config,
+ cookiePolicy: resolveCookiePolicy(getSettings(), config),
+ ...(queueKey !== undefined ? { queueKey } : {}),
+ afterRun: () => safeRevalidate([`/channels/${slug}/videos/${videoId}`]),
+ });
+}
+
export async function playableVideoAction(slug: string, videoId: string, dryRun = false): Promise<StreamActionResult> {
return preparePlayableAction(slug, { ids: [videoId], ...(dryRun ? { dryRun: true } : {}) });
}
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -41,6 +41,7 @@
// pnpm ops sync --json '{"slug":"the-quartering"}' --wait
// pnpm ops metadata-scan --json '{"slug":"the-quartering"}'
// pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait
+// pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait
// pnpm ops browser-lookup --json '{"slug":"demo-odysee","ids":["<claimId>"]}' --wait
// pnpm ops browser-lookup --json '{"slug":"demo-odysee","listing":true,"scrolls":5}' --wait
// pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait
@@ -491,6 +492,10 @@ const ACTIONS = [
// scope?, max?, force?}); one audio-audit job per channel. The damaged ones
// are the report's corruptHeldAudio bucket, which retry-bucket refetches.
"audio-audit",
+ // THE CLIP FINDER, ROUND TWO (release 36, lane A): one video's live chat
+ // replay alone ({slug, id}), paced, into live_chat.cues.json, as a fetch-chat
+ // job on the platform's download queue.
+ "fetch-chat",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -1131,6 +1136,13 @@ export function usage() {
' {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the',
' transcripts/ repo\'s own history.',
"",
+ 'fetch-chat fetches ONE video\'s live chat replay and nothing else: {"slug",',
+ ' "id"} — the chat-only yt-dlp pass (the channel\'s cookies, the platform\'s',
+ " pace) on the platform's download queue, then live_chat.cues.json. YouTube",
+ ' only: another platform answers "no chat fetcher for <platform>" (info, no',
+ " job), as do a chat already here and fresh and a video never live. A pass",
+ " that finds no replay ends done and says so.",
+ "",
'refresh-metadata re-reads ONE video\'s metadata.info.json from its source',
' (no subtitles, no media) on the platform\'s queue: {"slug", "id"}. The',
' job\'s log ends with what the source now says — live_status, formats,',