// THE SOURCE BACKLOG on a report video's page (UI notes 2026-10-30, item 16): // for each channel the cut cites, how much of it the archive holds and has // transcribed -- "Sources: emberparadox 1,454/2,798 transcribed · Prioritize" // -- read from the EDITOR (`GET /api/ops/channel/`: its snapshot's // totals and bucket sizes, never a walk of the disk), and a watch that tells // the operator when that backlog is done ("Re-sweep when complete"). // // PRIORITIZE never writes settings: it asks the editor's own // `POST /api/ops/channel-priority {focus: {kind: "channels", slugs}}` -- the // focus every lane leads with -- with the channels already in focus kept // (the focus is ONE list; a site focus is not replaced from here). // // THE WATCH, umtool's own state beside the project, in lib/lifecycle.mjs's // discipline (one writer serialised in-process, whole file temp + rename, an // unreadable file never overwritten): // // /source-watch.json // { format: "umtool-source-watch", version: 1, // watch: { slugs, armedAt, firedAt?, fired?: [rows] } | null, // last?: { checkedAt, rows: [{ slug, listed, held, transcribed, undownloaded, untranscribed, done }] } } // // While a watch is armed, every read of the backlog (the page's, and the // Inbox's background check, lib/inbox/sourceWatch.ts) records what it saw // (no file is made for a project with no watch); the first read in which // every watched channel is done FIRES the watch, once: the Inbox raises a // `sources-complete` card (Re-sweep) until the operator clears or re-arms it. // // Plain ESM. import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { channelFor, clipsOf } from "../projects/report.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SOURCE_WATCH_FILE = "source-watch.json"; export const SOURCE_WATCH_FORMAT = "umtool-source-watch"; const SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/i; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); export class SourceWatchError extends Error { constructor(message, status = 400) { super(message); this.name = "SourceWatchError"; this.status = status; } } /** * The channels the cut cites, as the editor knows them (a clip's * `siteChannel` -- the archive's slug, the Rumble case -- else its channel, * else the cut's provenance channel), with how many clips cite each. Clips * that carry their own media (`src`) cite no channel. * * @param {Record} manifest * @returns {Array<{ slug: string, clips: number }>} */ export function citedChannels(manifest) { const n = new Map(); for (const e of clipsOf(manifest)) { if (e.src != null) continue; const slug = typeof e.siteChannel === "string" && e.siteChannel ? e.siteChannel : channelFor(manifest, e); if (typeof slug !== "string" || !SLUG_RE.test(slug)) continue; n.set(slug, (n.get(slug) ?? 0) + 1); } return [...n.entries()].map(([slug, clips]) => ({ slug, clips })).sort((a, b) => b.clips - a.clips || a.slug.localeCompare(b.slug)); } const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null); /** * One channel's backlog from the editor's `GET /api/ops/channel/` * answer: `listed` (on disk + not yet), `held` (a video directory), * `downloaded` (its media), `transcribed`, the two backlogs, and `done` -- * nothing listed left to download and nothing held left to transcribe. A * channel the editor has no report for answers nulls and is never `done`. * * @param {string} slug * @param {any} r the route's JSON */ export function backlogOf(slug, r) { const rep = isObj(r?.report) ? r.report : null; const totals = isObj(rep?.totals) ? rep.totals : {}; const held = num(totals.videos); const transcribed = num(totals.transcribed); const downloaded = num(totals.downloaded); const undownloaded = num(rep?.undownloaded); const untranscribed = num(rep?.buckets?.downloadedNoTranscript); const listed = held !== null && undownloaded !== null ? held + undownloaded : num(r?.counts?.playlistCount); const done = held !== null && undownloaded === 0 && untranscribed === 0; return { slug, name: typeof r?.config?.name === "string" ? r.config.name : null, listed, held, downloaded, transcribed, undownloaded, untranscribed, done, tier: typeof r?.priority?.tier === "string" ? r.priority.tier : null, generatedAt: typeof rep?.generatedAt === "string" ? rep.generatedAt : null, mediaStatus: typeof r?.media?.status === "string" ? r.media.status : null, }; } /** * The focus body that adds `slugs` to what is in focus now (`focus` as * `settings.channelPriority.focus` reads), or a refusal in words: a site's * focus is the editor's to change. * * @param {any} focus * @param {string[]} slugs */ export function focusBodyFor(focus, slugs) { const want = [...new Set(slugs.filter((s) => typeof s === "string" && SLUG_RE.test(s)))]; if (!want.length) throw new SourceWatchError("name the channels to prioritize"); if (isObj(focus) && focus.kind === "site") { throw new SourceWatchError(`the editor's focus is the site "${focus.siteId}" — change it on the editor's Channels page; Prioritize adds channels to a channel focus`, 409); } const had = isObj(focus) && focus.kind === "channels" && Array.isArray(focus.slugs) ? focus.slugs.filter((s) => typeof s === "string") : []; const slugsOut = [...new Set([...had, ...want])]; return { body: { focus: { kind: "channels", slugs: slugsOut } }, added: want.filter((s) => !had.includes(s)), already: want.filter((s) => had.includes(s)) }; } /** Which slugs are in focus now. */ export const focusedOf = (focus) => (isObj(focus) && focus.kind === "channels" && Array.isArray(focus.slugs) ? focus.slugs.filter((s) => typeof s === "string") : []); // ---- the watch ---------------------------------------------------------------- export const sourceWatchFile = (dir) => path.join(/* turbopackIgnore: true */ dir, SOURCE_WATCH_FILE); const rowOf = (r) => isObj(r) && typeof r.slug === "string" ? { slug: r.slug, listed: num(r.listed), held: num(r.held), transcribed: num(r.transcribed), undownloaded: num(r.undownloaded), untranscribed: num(r.untranscribed), done: r.done === true } : null; /** `{ doc: { watch, last }, error? }` -- missing is empty; unreadable is empty with `error`. */ export async function readSourceWatch(dir) { const empty = { watch: null, last: null }; let raw; try { raw = await readFile(/* turbopackIgnore: true */ sourceWatchFile(dir), "utf8"); } catch (err) { if (err?.code === "ENOENT") return { doc: empty }; return { doc: empty, error: `${SOURCE_WATCH_FILE} cannot be read: ${err?.message ?? err}` }; } let j; try { j = JSON.parse(raw); } catch (err) { return { doc: empty, error: `${SOURCE_WATCH_FILE} is not JSON: ${err.message}` }; } if (!isObj(j) || j.format !== SOURCE_WATCH_FORMAT) return { doc: empty, error: `${SOURCE_WATCH_FILE} is not a ${SOURCE_WATCH_FORMAT} file` }; const w = isObj(j.watch) && Array.isArray(j.watch.slugs) ? j.watch : null; const watch = w ? { slugs: w.slugs.filter((s) => typeof s === "string"), armedAt: typeof w.armedAt === "string" ? w.armedAt : "", ...(typeof w.firedAt === "string" ? { firedAt: w.firedAt, fired: Array.isArray(w.fired) ? w.fired.map(rowOf).filter(Boolean) : [] } : {}), } : null; const last = isObj(j.last) && typeof j.last.checkedAt === "string" && Array.isArray(j.last.rows) ? { checkedAt: j.last.checkedAt, rows: j.last.rows.map(rowOf).filter(Boolean) } : null; return { doc: { watch, last } }; } let chain = Promise.resolve(); function writeSourceWatch(dir, mutate) { const run = chain.then(async () => { const file = sourceWatchFile(dir); const read = await readSourceWatch(dir); if (read.error) throw new SourceWatchError(`${read.error}; fix or remove ${file} first`, 409); const doc = read.doc; const result = mutate(doc); const out = { format: SOURCE_WATCH_FORMAT, version: 1, watch: doc.watch, ...(doc.last ? { last: doc.last } : {}) }; await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(out, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); } catch (err) { await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); throw err; } return { ...result, doc: out }; }); chain = run.catch(() => {}); return run; } /** ARM: tell me when these channels' backlog is done (a new watch replaces the old, fired or not). */ export function armSourceWatch(dir, slugs, { now = null } = {}) { const want = [...new Set((slugs ?? []).filter((s) => typeof s === "string" && SLUG_RE.test(s)))]; if (!want.length) return Promise.reject(new SourceWatchError("the cut cites no channel to watch")); return writeSourceWatch(dir, (doc) => { doc.watch = { slugs: want, armedAt: now ?? new Date().toISOString() }; return { armed: want }; }); } /** CLEAR: no watch (the card goes); what was last seen stays. */ export function clearSourceWatch(dir) { return writeSourceWatch(dir, (doc) => { const had = doc.watch; doc.watch = null; return { cleared: !!had }; }); } /** * RECORD what a read of the backlog saw. A watch not yet fired FIRES when * every one of its channels was read and is done -- once; answers `{ fired }`. * * @param {string} dir * @param {ReturnType[]} rows */ export function recordSourceCheck(dir, rows, { now = null } = {}) { const stamp = now ?? new Date().toISOString(); return writeSourceWatch(dir, (doc) => { const kept = rows.map(rowOf).filter(Boolean); doc.last = { checkedAt: stamp, rows: kept }; const w = doc.watch; if (!w || w.firedAt) return { fired: false }; const by = new Map(kept.map((r) => [r.slug, r])); const all = w.slugs.length > 0 && w.slugs.every((s) => by.get(s)?.done === true); if (!all) return { fired: false }; w.firedAt = stamp; w.fired = w.slugs.map((s) => by.get(s)); return { fired: true }; }); } /** "1,454" */ export const thousands = (n) => (typeof n === "number" ? n.toLocaleString("en-US") : "?"); /** The line for one channel: `emberparadox 1,454/2,798 transcribed · 2,751 held`. */ export function backlogWords(r) { if (r.error) return `${r.slug}: ${r.error}`; if (r.held === null) return `${r.slug}: no report yet`; return `${r.slug} ${thousands(r.transcribed)}/${thousands(r.listed ?? r.held)} transcribed · ${thousands(r.held)} held${r.done ? " · complete" : ""}`; }