// STAND-INS (release 35 O1): a montage clip whose window the editor REFUSED — // a Rumble embed lookup that answers 403 on every try, a recording gone from // its platform — cut from another upload of the same moment instead. // // A clip is a candidate when all three hold: // - its window is still missing on disk (the bench's own cache check, the // corpus's clips/ included); // - the editor refused it: a fetch-windows job of a run recorded in // fetch-runs.json failed that window (its log's `✗` line — not a rate // limit, our own drive or our own cut), or the editor could not resolve it; // - its instance in phrase-scan.json has an alternate that is public (or not // known to be otherwise) and was not refused itself. An older scan with no // `alternates` is scanned again (phraseScanMany over the same settings, // through the cue-text cache) to find them. // The first alternate wins: YouTube, then Odysee / cornbreadman, then the rest. // // THE SWITCH IS ON THE CLIP, AND IT IS REVERSIBLE. The clip takes the // alternate's channel, video and moment (the cut is the alternate's phrase, the // window keeps the clip's own margins), and records where it came from: // fallbackFrom: {channel, video, start, end, cutStart, cutEnd, cite, note, // platform, reason} // with `note` "from the YouTube upload: the Rumble copy refused (403)". Restore // puts every one of those fields back. Its montage ruling and its voice-match // row are keyed by the moment (clipMomentKey), so both move to the new key and // back. The manifest is written through replaceManifest (the lock, the auto // snapshot the Cut tab's Undo takes back, the atomic write). import path from "node:path"; import { readFile } from "node:fs/promises"; import { momentKey, clipMomentKey } from "umtool-report-to-video/montage-rulings"; import { phraseScanMany } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs"; import { readVoiceMatch, writeVoiceMatch } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; import { manifestToken, replaceManifest, StaleToken } from "./manifest.mjs"; import { moveMontageRuling } from "./montageRulings.mjs"; import { projectCache } from "./serve.mjs"; import { channelsDirFor, hasShadowChannels } from "../projects/report.mjs"; import { phraseTextCacheDir } from "../phrase-finder/scan.mjs"; import { followRun, lastStartedRun, readFetchRuns } from "./fetchWindows.mjs"; export const PHRASE_SCAN_FILE = "phrase-scan.json"; /** Failure classes that say nothing about the recording: never a reason for a stand-in. */ export const NOT_A_REFUSAL = new Set(["rate_limit", "unreachable", "cut-failed", "cancelled", "cancel"]); /** An alternate whose availability is one of these may stand in. */ export const STAND_IN_AVAILABILITY = new Set(["public", "unknown"]); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const r2 = (x) => Number(Number(x).toFixed(2)); const PLATFORM_NAMES = { youtube: "YouTube", rumble: "Rumble", odysee: "Odysee", twitch: "Twitch", kick: "Kick", bitchute: "BitChute" }; export const platformName = (p) => (p ? (PLATFORM_NAMES[String(p).toLowerCase()] ?? String(p).charAt(0).toUpperCase() + String(p).slice(1)) : "other"); /** YouTube first, then Odysee / cornbreadman, then anything else. */ export const alternateRank = (a) => (a?.platform === "youtube" ? 0 : a?.platform === "odysee" || a?.slug === "cornbreadman" ? 1 : 2); /** * The alternates that may stand in, best first. `refused` is a set of * `/` the editor already refused. * @param {{ slug: string, videoId: string, start: number, end: number, platform: string | null, availability: string | null }[]} alternates * @param {{ refused?: Set, not?: { slug: string, videoId: string } | null }} [opts] */ export function eligibleAlternates(alternates, { refused = new Set(), not = null } = {}) { return (Array.isArray(alternates) ? alternates : []) .map((a, k) => ({ a, k })) .filter(({ a }) => isObj(a) && a.slug && a.videoId && Number.isFinite(Number(a.start)) && Number.isFinite(Number(a.end))) .filter(({ a }) => a.availability == null || STAND_IN_AVAILABILITY.has(String(a.availability))) .filter(({ a }) => !refused.has(`${a.slug}/${a.videoId}`) && !(not && a.slug === not.slug && a.videoId === not.videoId)) .sort((x, y) => alternateRank(x.a) - alternateRank(y.a) || x.k - y.k) .map(({ a }) => a); } /** "403" when the editor's words say so, else the failure's class. */ export const refusalWords = (r) => (/\b403\b/.test(String(r?.message ?? "")) ? "403" : String(r?.class ?? "refused")); /** * The clip cut from `alt` instead. Pure. The cut is the alternate's phrase; the * window keeps the clip's own margins either side of its cut. * @param {Record} clip * @param {{ slug: string, videoId: string, start: number, end: number, platform: string | null }} alt * @param {{ manifest?: Record | null, refusal?: { class?: string, message?: string } | null, fromPlatform?: string | null }} [opts] */ export function standInClip(clip, alt, { manifest = null, refusal = null, fromPlatform = null } = {}) { const channel = clip.channel ?? manifest?.provenance?.channelSlug ?? null; const cutStart = Number.isFinite(Number(clip.cutStart)) ? Number(clip.cutStart) : Number(clip.start); const cutEnd = Number.isFinite(Number(clip.cutEnd)) ? Number(clip.cutEnd) : Number(clip.end); const before = Math.max(0, cutStart - Number(clip.start)); const after = Math.max(0, Number(clip.end) - cutEnd); const was = fromPlatform ?? clip.montage?.platform ?? null; const words = refusalWords(refusal); const next = { ...clip, channel: alt.slug, video: alt.videoId, start: r2(Math.max(0, Number(alt.start) - before)), end: r2(Number(alt.end) + after), cutStart: r2(alt.start), cutEnd: r2(alt.end), ...(clip.cite !== undefined ? { cite: r2(alt.start) } : {}), note: `from the ${platformName(alt.platform)} upload: the ${platformName(was)} copy refused (${words})`, fallbackFrom: { channel, ...(clip.channel ? {} : { ownChannel: false }), video: clip.video, start: clip.start, end: clip.end, cutStart: clip.cutStart ?? null, cutEnd: clip.cutEnd ?? null, cite: clip.cite ?? null, note: clip.note ?? null, platform: was, reason: words, }, }; if (isObj(clip.montage)) next.montage = { ...clip.montage, platform: alt.platform ?? null }; return next; } /** * The clip as it was before its stand-in. Pure; a clip with no `fallbackFrom` * comes back unchanged. * @param {Record} clip */ export function restoredClip(clip) { const f = clip?.fallbackFrom; if (!isObj(f)) return clip; const { fallbackFrom: _f, ...rest } = clip; const out = { ...rest, video: f.video, start: f.start, end: f.end }; // A clip that named no channel of its own took the manifest's, and goes back to naming none. if (f.ownChannel === false) delete out.channel; else out.channel = f.channel; for (const k of ["cutStart", "cutEnd", "cite", "note"]) { if (f[k] === null || f[k] === undefined) delete out[k]; else out[k] = f[k]; } if (isObj(clip.montage)) { out.montage = { ...clip.montage, platform: f.platform ?? null }; } return out; } /** * Every window the editor refused, by clip id — the newest word on each: * failed windows of the recorded runs' ended jobs, and the editor's unresolved. * @param {{ runs: any[] }} doc fetch-runs.json * @returns {Map} */ export function refusedWindows(doc) { const out = new Map(); for (const run of doc?.runs ?? []) { for (const u of run.summary?.unresolved ?? []) { if (u.clipId) out.set(u.clipId, { slug: u.slug, id: u.id, class: "unresolved", message: u.error, jobId: null, at: run.at }); } for (const [jobId, j] of Object.entries(run.jobs ?? {})) { for (const f of j?.failed ?? []) { if (!f.clipId || NOT_A_REFUSAL.has(f.class)) continue; out.set(f.clipId, { slug: f.slug, id: f.id, class: f.class, message: f.message, jobId, at: j.at ?? run.at }); } } } return out; } const instanceKey = (i) => momentKey({ channel: i.slug, video: i.videoId, at: i.start }); /** * The phrase scan's instances by moment key, alternates and all. An older scan * with no `alternates` is scanned again over its own settings (`rescan: true`). * @returns {Promise<{ byKey: Map, source: "scan" | "rescan" | "none", why?: string }>} */ export async function instancesByKey(projectDir, { channelsDir, cacheDir = phraseTextCacheDir(), rescan = true } = {}) { let scan; try { scan = JSON.parse(await readFile(path.join(projectDir, PHRASE_SCAN_FILE), "utf8")); } catch { return { byKey: new Map(), source: "none", why: `no ${PHRASE_SCAN_FILE} beside the manifest` }; } const listed = [...(scan.instances ?? []), ...(scan.skippedByCap ?? [])]; const hasAlternates = listed.some((i) => Array.isArray(i?.alternates)); if (hasAlternates || !rescan) { return { byKey: new Map(listed.map((i) => [instanceKey(i), i])), source: "scan" }; } if (!scan.phrase || !Array.isArray(scan.channels)) return { byKey: new Map(), source: "none", why: `${PHRASE_SCAN_FILE} names no phrase and channels to scan again` }; const [again] = await phraseScanMany({ channelsDir, channels: scan.channels, prefer: scan.prefer ?? null, exclude: scan.exclude ?? null, phrases: [{ id: "p", phrase: scan.phrase }], cacheDir, }); return { byKey: new Map(again.instances.map((i) => [instanceKey(i), i])), source: "rescan" }; } /** * What can be switched, what is switched, and what cannot be helped. * @param {{ id: string, dir: string }} project * @param {{ cfg?: { url: string, token: string, fetch?: typeof fetch } | null, cacheDir?: string, rescan?: boolean }} [opts] */ export async function standInPlan(project, { cfg = null, cacheDir = phraseTextCacheDir(), rescan = true } = {}) { const manifest = JSON.parse(await readFile(path.join(project.dir, "video.manifest.json"), "utf8")); let runs = await readFetchRuns(project.dir); // Jobs still running when last asked: ask once more (best effort). const last = lastStartedRun(runs); if (cfg?.token && last) { await followRun(cfg, project.dir, last).catch(() => null); runs = await readFetchRuns(project.dir); } const refused = refusedWindows(runs); const refusedVideos = new Set([...refused.values()].map((r) => `${r.slug}/${r.id}`)); const cache = await projectCache(project, manifest); const clips = (manifest.timeline ?? []).filter((e) => isObj(e) && e.type === "clip"); const switched = clips.filter((c) => isObj(c.fallbackFrom)).map((c) => ({ clipId: c.id, channel: c.channel, video: c.video, from: c.fallbackFrom })); const wanted = clips.filter((c) => !isObj(c.fallbackFrom) && refused.has(c.id) && !cache.isFetched(c)); const out = { project: project.id, candidates: [], switched, none: [], refused: refused.size, source: "none", why: null }; if (!wanted.length) return out; const shadowExists = await hasShadowChannels(project.dir); const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists }); const inst = await instancesByKey(project.dir, { channelsDir, cacheDir, rescan }); out.source = inst.source; out.why = inst.why ?? null; for (const c of wanted) { const r = refused.get(c.id); const key = clipMomentKey(c, manifest); const i = key ? inst.byKey.get(key) : null; const channel = c.channel ?? manifest.provenance?.channelSlug ?? null; const alts = i ? eligibleAlternates(i.alternates, { refused: refusedVideos, not: { slug: channel, videoId: c.video } }) : []; if (!alts.length) { out.none.push({ clipId: c.id, refusal: r, why: !i ? inst.why ?? "its instance is not in the phrase scan" : "no public alternate that was not refused too" }); continue; } out.candidates.push({ clipId: c.id, key, channel, video: c.video, refusal: r, alternate: alts[0], others: alts.slice(1) }); } return out; } /** Write the manifest with `edit(manifest)` applied, through replaceManifest (one retry on a stale read). */ async function rewrite(dir, op, edit) { for (let attempt = 0; ; attempt++) { const token = await manifestToken(dir); const manifest = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); const result = edit(manifest); if (!result) return null; try { await replaceManifest(dir, manifest, { token, op }); return result; } catch (e) { if (e instanceof StaleToken && attempt === 0) continue; throw e; } } } /** Move a voice-match row to another key (as it is), when the target has none. */ async function moveVoiceRow(dir, from, to) { const doc = await readVoiceMatch(dir); if (!doc || !from || !to || from === to || !doc.clips[from] || doc.clips[to]) return false; doc.clips[to] = doc.clips[from]; delete doc.clips[from]; await writeVoiceMatch(dir, doc); return true; } /** * Switch the candidates (all, or the clip ids given) to their stand-ins. * @param {{ id: string, dir: string }} project * @param {{ clips?: string[] | null, cfg?: any, cacheDir?: string, rescan?: boolean }} [opts] */ export async function applyStandIns(project, { clips = null, cfg = null, cacheDir = phraseTextCacheDir(), rescan = true } = {}) { const plan = await standInPlan(project, { cfg, cacheDir, rescan }); const chosen = plan.candidates.filter((c) => !clips || clips.includes(c.clipId)); if (clips) { const unknown = clips.filter((id) => !plan.candidates.some((c) => c.clipId === id)); if (unknown.length) throw new Error(`no stand-in for ${unknown.join(", ")} (not refused, already on disk, already switched, or no public alternate)`); } if (!chosen.length) return { switched: [], plan }; const moves = []; await rewrite(project.dir, "stand-in", (m) => { for (const c of chosen) { const k = (m.timeline ?? []).findIndex((e) => isObj(e) && e.id === c.clipId); if (k < 0) continue; const before = m.timeline[k]; const next = standInClip(before, c.alternate, { manifest: m, refusal: c.refusal }); m.timeline[k] = next; moves.push({ clipId: c.clipId, from: clipMomentKey(before, m), to: clipMomentKey(next, m), alternate: c.alternate }); } return moves; }); for (const mv of moves) { mv.ruling = mv.from && mv.to ? await moveMontageRuling(project.dir, mv.from, mv.to) : false; mv.voice = await moveVoiceRow(project.dir, mv.from, mv.to); } return { switched: moves, plan }; } /** * Put a switched clip back as it was; its ruling and voice row move back. * @param {{ id: string, dir: string }} project * @param {string} clipId */ export async function restoreStandIn(project, clipId) { const mv = await rewrite(project.dir, "restore-stand-in", (m) => { const k = (m.timeline ?? []).findIndex((e) => isObj(e) && e.id === clipId); if (k < 0) throw new Error(`no clip ${clipId}`); const before = m.timeline[k]; if (!isObj(before.fallbackFrom)) throw new Error(`${clipId} has no stand-in to restore`); const next = restoredClip(before); m.timeline[k] = next; return { clipId, from: clipMomentKey(before, m), to: clipMomentKey(next, m) }; }); mv.ruling = mv.from && mv.to ? await moveMontageRuling(project.dir, mv.from, mv.to) : false; mv.voice = await moveVoiceRow(project.dir, mv.from, mv.to); return mv; }