// 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/. // // `renormalize: true` (lane chat-clock) parses the raw already on disk again, // fresh or not, and never fetches: the one-video repair for a chat normalized // before a live capture was put on the recording's clock (normalizeLiveChat). import { localMediaFetchRefusal } from "../lib/localMedia"; import path from "node:path"; import { lstat, readFile, readdir, stat } from "node:fs/promises"; import { AUTH_RETRY_CLASSES, classifyDownloadFailure, parseUnavailableFromStderr, refusalAvailability, } from "../lib/availability"; import { recordFetchObservation } from "../lib/availability-server"; 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 { listingHas, storedFormsIn } from "../lib/storedText"; import { storedTextExists } from "../lib/storedText-server"; import { keepPlainAsCapture, putBackKeptCapture, setAsideStoredText } from "../lib/storedText-write-server"; import { decodeStoredBytes } from "../lib/storedText-server"; import { parseLiveChat } from "../lib/liveChat"; 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 = 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 } // `live`: the metadata says the stream is live now, so the pass captures // the chat as it is typed (on the capture's clock until normalizeLiveChat // puts it on the recording's). | { kind: "fetch"; url: string; platform: string; live?: boolean } | { kind: "refused"; error: string }; async function isDirectory(p: string): Promise { return stat(p).then((s) => s.isDirectory(), () => false); } async function liveStatusOf(videoDir: string): Promise { 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`; } // `replace` (fetch-chat's deliberate re-fetch over a STORED chat): what is on // disk does not answer — the plan is the fetch, or why there is none. export async function liveChatPlan( paths: Paths, slug: string, videoId: string, config: ChannelConfig, opts: { replace?: boolean } = {}, ): Promise { 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) }; // A local media record has no chat to fetch (review fix 5), before any branch. const localRefusal = localMediaFetchRefusal(slug, config, videoId); if (localRefusal) return { kind: "refused", error: localRefusal }; if (!opts.replace) { const fresh = await isLiveChatCuesFresh(videoDir); if (fresh.fresh) return { kind: "fresh", cuesPath: fresh.cuesPath }; const entries = await readdir(videoDir).catch(() => [] as string[]); // Either form of the raw (lib/storedText.ts): a compressed chat is ON DISK — // missing it here is a fetch of the whole replay again. if (listingHas(entries, 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, ...(live === "is_live" ? { live: true } : {}) }; } 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; export type FetchLiveChatOpts = { paths: Paths; slug: string; videoId: string; videoUrl: string; channelConfig: ChannelConfig; cookiePolicy?: ResolvedCookiePolicy; onLog: (s: string) => void; signal: AbortSignal; onPlatformBackoff?: () => Promise | void; onPlatformClean?: () => Promise | string | null; // The stream is live now (LiveChatPlan `live`): the log says it is a capture. capturingLive?: boolean; // Test seams: the spawn, and the platform pace in the argv. run?: ChatRunner; paceSeconds?: number; // THE DELIBERATE RE-FETCH over a chat stored compressed (fetch-chat // `replace`): the stored capture is KEPT under `chat-capture-kept..json.zst` // and never removed (lib/storedText-write-server.ts). A new replay with // messages becomes the chat; an empty one, or none, leaves the stored // capture the chat. replace?: boolean; }; // One capture, measured: bytes, messages, and the first and last message's // time (seconds into the stream). export type CaptureMeasure = { bytes: number; messages: number; firstSec: number | null; lastSec: number | null }; // What a `replace` did: the earlier capture (kept under `keptAs`, or put back // as the chat when `keptAs` is null) and the replay fetched (null: none). export type ReplaceReport = { earlier: CaptureMeasure & { keptAs: string | null }; fetched: (CaptureMeasure & { keptAs: string | null }) | null; }; export type FetchLiveChatResult = | { status: "fetched"; messages: number; cuesPath: string; replace?: ReplaceReport } | { status: "none"; replace?: ReplaceReport }; function measureChat(bytes: Buffer): CaptureMeasure { let cues: { start: number }[] = []; try { cues = parseLiveChat(bytes.toString("utf8")); } catch { cues = []; } return { bytes: bytes.length, messages: cues.length, firstSec: cues.length ? cues[0].start : null, lastSec: cues.length ? cues[cues.length - 1].start : null, }; } function describe(m: CaptureMeasure): string { const span = m.firstSec !== null && m.lastSec !== null ? `, ${m.firstSec.toFixed(0)}–${m.lastSec.toFixed(0)} s` : ""; return `${m.messages} message(s), ${m.bytes} bytes${span}`; } /** The pass, then the normalize. Throws on a failed pass (the job ends `failed`). */ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise { 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, observe: { paths: opts.paths, url: opts.videoUrl, channel: opts.slug }, }, 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)); // A REPLACE keeps the stored capture first, under a name no reader sees. let kept: string | null = null; if (opts.replace) { const set = await setAsideStoredText(videoDir, LIVE_CHAT_FILENAME); if (set === "busy") throw new Error(`The chat of ${opts.videoId} is being compressed or restored right now; nothing was fetched. Try again in a moment.`); kept = set.kept; if (kept) opts.onLog(`The stored chat capture of ${opts.videoId} is kept as ${kept} while the replay is fetched.\n`); } try { await passes(); } catch (err) { if (kept) await putBack(kept); throw err; } if (kept) return finishReplace(kept); const entries = await readdir(videoDir).catch(() => [] as string[]); if (!listingHas(entries, 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 putBack(k: string): Promise { const back = await putBackKeptCapture(videoDir, LIVE_CHAT_FILENAME, k); opts.onLog( back === true ? `The kept capture ${k} is the chat again.\n` : `The kept capture ${k} stays under that name (the chat's name is taken, or the file is busy); nothing was removed.\n`, ); } // After a clean pass over a kept capture: both measured, and the decision. async function finishReplace(k: string): Promise { const earlier = measureChat(await decodeStoredBytes(await readFile(path.join(videoDir, k)), k)); const entries = await readdir(videoDir).catch(() => [] as string[]); const partial = entries.some((e) => e.startsWith(`${LIVE_CHAT_FILENAME}.part`)); const landed = !partial && (await stat(path.join(videoDir, LIVE_CHAT_FILENAME)).then((st) => st.isFile(), () => false)); if (!landed) { opts.onLog(`No new chat replay for ${opts.videoId} came back${partial ? " whole (a .part is here)" : ""}. Earlier capture: ${describe(earlier)}.\n`); await putBack(k); return { status: "none", replace: { earlier: { ...earlier, keptAs: null }, fetched: null } }; } const fetched = measureChat(await readFile(path.join(videoDir, LIVE_CHAT_FILENAME))); opts.onLog(`Earlier capture (${k}): ${describe(earlier)}. Replay fetched now: ${describe(fetched)}.\n`); if (fetched.messages === 0) { const empty = await keepPlainAsCapture(videoDir, LIVE_CHAT_FILENAME); const emptyAs = empty !== "busy" ? empty.kept : null; opts.onLog( `The replay came back EMPTY (0 messages): the earlier capture stays the chat` + (emptyAs ? `; the empty replay is kept as ${emptyAs}.\n` : `.\n`), ); await putBack(k); return { status: "none", replace: { earlier: { ...earlier, keptAs: null }, fetched: { ...fetched, keptAs: emptyAs } } }; } opts.onLog( `The replay fetched now is the chat; the earlier capture is KEPT as ${k} and is never removed automatically` + (fetched.messages < earlier.messages ? ` (the replay has ${earlier.messages - fetched.messages} fewer message(s))` : "") + `.\n`, ); const out = await normalizeChat(opts, videoDir); return { ...out, replace: { earlier: { ...earlier, keptAs: k }, fetched: { ...fetched, keptAs: null } } }; } async function passes(): Promise { opts.onLog( opts.capturingLive ? `Capturing the live chat of ${opts.videoId} from ${opts.videoUrl} while it is live (no media); ` + `it is put on the broadcast's clock when it is normalized\n` : `Fetching the live chat replay of ${opts.videoId} from ${opts.videoUrl} (no media)\n`, ); const firstCookies = alwaysCookies(policy); let outcome = await pass(firstCookies); // A pass the platform refused for THIS video ("Join this channel …") is an // observation, recorded even when the cookie retry below then succeeds: a // members' cookie reading it is exactly what members-only means. if (!succeeded(outcome.exitCode)) await noteRefusal(videoDir, outcome.stderrTail, opts.onLog); 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 (!succeeded(outcome.exitCode)) await noteRefusal(videoDir, outcome.stderrTail, opts.onLog); } } 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 */ } } } // Best-effort: a failed write is logged, never the job's failure. async function noteRefusal(videoDir: string, stderrTail: string, onLog: (s: string) => void): Promise { const seen = refusalAvailability(stderrTail); if (!seen) return; try { if (await recordFetchObservation(videoDir, seen, new Date().toISOString())) { onLog(`Recorded the source's answer for this video: ${seen} (availability.json)\n`); } } catch (err) { onLog(`Could not record the availability (${seen}): ${(err as Error).message}\n`); } } async function normalizeChat( opts: Pick, videoDir: string, ): Promise { 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; run?: ChatRunner; // RE-NORMALIZE ONLY (lane chat-clock): parse the raw replay already on disk // again — e.g. a chat captured live and normalized before the chat was put // on the recording's clock — even when its cues are fresh. Never a fetch: // refused when no raw is here. No network; the job's kind still declares // `needsMedia`, so a raw that is a tier link onto an unreachable drive is // refused by runManagedFunction's guard like any other media reader. renormalize?: boolean; // THE DELIBERATE RE-FETCH (lib/storedText-write-server.ts): fetch the replay // again over a chat stored compressed. The stored capture is kept as // `chat-capture-kept..json.zst`, never removed; a replay with messages // becomes the chat, an empty one (or none) leaves the stored capture the // chat. Refused over a PLAIN chat (yt-dlp would keep it and fetch nothing). replace?: boolean; }; /** Why a re-fetch over the chat on disk cannot run, or null. Reads the disk only. */ export async function replaceChatRefusal(paths: Paths, slug: string, videoId: string): Promise { if (!isVideoIdSegment(videoId)) return `"${videoId}" is not a video id (one path segment)`; const videoDir = path.join(paths.channelsDir, slug, "data", videoId); if (!(await isDirectory(videoDir))) return notFetchedRefusal(videoId, slug); const forms = storedFormsIn(await readdir(videoDir).catch(() => [] as string[]), LIVE_CHAT_FILENAME); if (forms === "plain" || forms === "both") { return ( `${videoId}'s raw chat is a plain ${LIVE_CHAT_FILENAME} here: "replace" re-fetches over a chat stored ` + `compressed only (yt-dlp keeps a plain file and fetches nothing) — delete it on the video's files card first` ); } return null; } /** Why a re-normalize cannot run for this video, or null. Reads the disk only. */ export async function renormalizeChatRefusal( paths: Paths, slug: string, videoId: string, ): Promise { if (!isVideoIdSegment(videoId)) return `"${videoId}" is not a video id (one path segment)`; const videoDir = path.join(paths.channelsDir, slug, "data", videoId); if (!(await isDirectory(videoDir))) return notFetchedRefusal(videoId, slug); const here = (name: string) => lstat(path.join(videoDir, name)).then(() => true, () => false); if (!(await storedTextExists(videoDir, LIVE_CHAT_FILENAME))) { return ( `${videoId} has no raw chat on disk (${LIVE_CHAT_FILENAME}): "renormalize" reads only the file ` + `already here and never fetches — fetch-chat without it fetches the chat` ); } if (!(await here(META_FILENAME))) return `${videoId} has no ${META_FILENAME}: its chat cannot be normalized`; return null; } // Every refusal before any job, in the sentences the rest of the app uses. export async function runFetchChatJob(opts: FetchChatJobOpts): Promise { const { paths, slug, videoId, channelConfig } = opts; try { await assertChannelTextReadable(paths, slug, channelConfig); } catch (err) { return { ok: false, error: (err as Error).message }; } if (opts.renormalize && opts.replace) { return { ok: false, error: `"renormalize" reads the raw chat here and "replace" fetches it again: ask one` }; } if (opts.renormalize) { const refusal = await renormalizeChatRefusal(paths, slug, videoId); if (refusal) return { ok: false, error: refusal }; } if (opts.replace) { const refusal = await replaceChatRefusal(paths, slug, videoId); if (refusal) return { ok: false, error: refusal }; } const plan: LiveChatPlan = opts.renormalize ? { kind: "normalize" } : await liveChatPlan(paths, slug, videoId, channelConfig, { replace: opts.replace === true }); 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, // A replay already on disk is only normalized: no request, so no gap and // no network guard (plans/pacing-guard.md). ...(plan.kind === "normalize" ? { network: false as const } : {}), fn: async (onLog, signal) => { if (plan.kind === "normalize") { onLog( opts.renormalize ? `Re-normalizing the chat of ${videoId} from the raw on disk (no network).` : `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), ...(plan.live ? { capturingLive: true } : {}), ...(opts.run ? { run: opts.run } : {}), ...(opts.replace ? { replace: true } : {}), }); } await opts.afterRun?.(); }, }); }