// FIND A COPY OF A GONE RECORDING (release 29 E2) — the deleted-video fallback. // // A report cites a moment of a YouTube recording its platform no longer serves // (deleted or made private: lib/sourceGone.ts). Its window cannot be fetched // from its own page, so `missingEvidenceWindows` lists it as "unfetchable: // gone". This looks for a copy, per recording, in order: // // 1. THE WAYBACK MACHINE, when it holds the VIDEO — not merely a capture of // the watch page (YouTube answers "Video unavailable" with a 200, and most // page captures hold no video). The check is the one yt-dlp's // YoutubeWebArchive extractor makes before it fetches anything // (yt_dlp/extractor/archiveorg.py `_real_extract`: web.archive.org's // `__wb/videoinfo?vtype=youtube&vid=` has formats) AND (release 32 // R8) a format's stream answers a ranged GET (`/web/2id_/`, // lib/waybackClient.ts youtubeVideoStream): the index lists videos whose // bytes Wayback does not hold (the live case, 404 at the format URL), and // such a video is "page captured, no video" — none found, never a copy // that fails at its source; the copy's URL is // `https://web.archive.org/web//https://www.youtube.com/watch?v=`, // the form that extractor takes (the newest 200 capture's timestamp, when // the CDX names one); // 2. ARCHIVE.ORG: a mirror that is OF the upload — its identifier, a file's // name, or its `originalurl`/`source` names the YouTube id (a title or a // description that mentions it is not enough: a compilation does that) — // holding a video file whose length agrees with the record's duration; // fetched by its direct URL `https://archive.org/download//`. // // Only a record whose page is a YouTube URL is looked for: the id is the // page's, never guessed from a Twitch or Rumble record's own id. // // A COPY THAT FAILED AT ITS SOURCE is not picked again: fetch-windows records // a copy whose fetch failed source-side beside the recording // (lib/copyAttempts-server.ts), and the next run falls through — Wayback → // archive.org → the next mirror. `retryFailed` tries them again. // // A copy found: the recording's cited windows go to fetch-windows with the // copy's URL as each item's `webpageUrl` (controller/fetchWindows.ts), so the // clips land in the recording's own `data//clips/`, and each window's // sidecar records which copy (`copy: {from, url}`, lib/clipWindow.ts). None // found: the windows are left, and compose shows the moments' words only, // marked "source deleted" (once prepare says so). // // PACED: one recording at a time; every Wayback and archive.org request goes // through the polite clients (one at a time, 2 s apart, 429s waited out). A // lookup that archive.org keeps refusing stops the run there; the rest are // left for a later run. A cancelled run starts no fetch. The fetch is ONE // fetch-windows job on the archive.org clip queue, which walks its windows one // at a time — one stream. import { readFile } from "node:fs/promises"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { ClipCopy } from "../lib/clipWindow"; import type { GoneState } from "../lib/sourceGone"; import { loadAvailability } from "../lib/availability-server"; import { COPY_ATTEMPT_RETRY_DAYS, loadCopyAttempts, readFailedCopies, recentTerminalAttempt, recordCopyAttempt, type CopyAttempt, type CopyAttempts, type FailedCopy, } from "../lib/copyAttempts-server"; import { sourceGoneState } from "../lib/sourceGone-server"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { isVideoTranscribed, readVideoFiles } from "../lib/videoStatus"; import { getSite } from "../lib/site"; import { listChannelVideoIds } from "../controller/keptVideos"; import { holdsMedia } from "../ytdlp/fetchCopyManaged"; import type { FetchCopyItem } from "../controller/fetchCopies"; import { archiveOrgClient, ArchiveOrgRequestError, type ArchiveOrgClient } from "../lib/archiveOrgClient"; import { archiveOrgDownloadUrl } from "../lib/archiveOrgId"; import { archiveOrgRestriction, searchArchiveOrgItems } from "../controller/archiveOrgImport"; import { isArchiveOrgVideoFileName, parseArchiveOrgLength, type ArchiveOrgItemMetadata } from "../lib/archiveOrg"; import { waybackClient, waybackYoutubeUrl, type WaybackCapture } from "../lib/waybackClient"; import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; import { channelConfigPlatform } from "../lib/videoId"; import { readChannelConfig } from "../controller/channels"; import { findVideoSourceUrl } from "../controller/undownloadedVideos"; import { missingEvidenceWindows, type EvidenceWindow, type MissingEvidenceWindows } from "./reportMedia"; import type { ReportHost } from "./reportHost"; import type { FetchWindowsItem } from "../controller/fetchWindows"; // ─── A recording: its page, its length, its YouTube id ─── export type RecordFacts = { // The page it was served at: its metadata's `webpage_url`, else the one its // availability check recorded, else the playlist's. webpageUrl: string | null; // Its length in seconds, from its metadata. duration: number | null; // Its data directory (where the failed copies are recorded). videoDir: string; }; export async function recordFacts(paths: Paths, slug: string, id: string): Promise { const config = await readChannelConfig(paths, slug).catch(() => null); const dirId = await resolveVideoDirId(paths.channelsDir, slug, id, config ? { platform: channelConfigPlatform(config) } : {}); const videoDir = path.join(paths.channelsDir, slug, "data", dirId); let webpageUrl: string | null = null; let duration: number | null = null; try { const meta = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")) as { webpage_url?: unknown; duration?: unknown }; if (typeof meta.webpage_url === "string" && /^https?:\/\//.test(meta.webpage_url)) webpageUrl = meta.webpage_url; if (typeof meta.duration === "number" && Number.isFinite(meta.duration) && meta.duration > 0) duration = meta.duration; } catch { // no metadata: the next source } if (!webpageUrl) { const av = await loadAvailability(videoDir).catch(() => null); if (av?.webpageUrl && /^https?:\/\//.test(av.webpageUrl)) webpageUrl = av.webpageUrl; } if (!webpageUrl && config) webpageUrl = await findVideoSourceUrl(paths, slug, dirId, config).catch(() => null); return { webpageUrl, duration, videoDir }; } // The page alone (wayback-lookup's `{slug, id}`). export async function recordWebpageUrl(paths: Paths, slug: string, id: string): Promise { return (await recordFacts(paths, slug, id)).webpageUrl; } const YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/; const YOUTUBE_HOST = /^(?:(?:www|m|music)\.)?youtube\.com$|^youtu\.be$/; // The YouTube id of a YouTube page (a watch URL's `v`, a youtu.be path, a // /shorts/, /live/ or /embed/ path), or null — for any other page, whatever // the record's own id looks like. export function youtubeIdOf(pageUrl: string | null): string | null { if (!pageUrl) return null; let u: URL; try { u = new URL(pageUrl); } catch { return null; } const host = u.hostname.toLowerCase(); if (!YOUTUBE_HOST.test(host)) return null; const v = u.searchParams.get("v"); if (v && YOUTUBE_ID.test(v)) return v; const seg = u.pathname.split("/").filter(Boolean); if (host === "youtu.be") return seg[0] && YOUTUBE_ID.test(seg[0]) ? seg[0] : null; const k = seg.findIndex((s) => s === "shorts" || s === "live" || s === "embed"); return k >= 0 && seg[k + 1] && YOUTUBE_ID.test(seg[k + 1]) ? seg[k + 1] : null; } export function isYoutubeId(id: string): boolean { return YOUTUBE_ID.test(id); } // ─── archive.org: a mirror by YouTube id ─── // archive.org's advanced search for CANDIDATE mirrors of one YouTube upload // (each is then checked: findArchiveOrgMirrors). export function youtubeIdQuery(id: string): string { if (!YOUTUBE_ID.test(id)) throw new Error(`"${id}" is not a YouTube id`); return `identifier:(youtube-${id}) OR originalurl:(*${id}*) OR source:(*${id}*) OR description:("${id}") OR title:("${id}")`; } const EXT_RANK = ["mp4", "webm", "mkv", "m4v", "mov"]; const extOf = (name: string) => (/\.([A-Za-z0-9]{1,8})$/.exec(name)?.[1] ?? "").toLowerCase(); const textOf = (v: unknown): string => typeof v === "string" ? v : Array.isArray(v) ? v.filter((x) => typeof x === "string").join(" ") : ""; // Whether an item is OF the upload: its identifier, a file's name, or its // `originalurl`/`source` names the id. A title or description that mentions // it is not (a compilation or a reaction cites its sources there). export function mirrorNamesId(item: Pick, youtubeId: string): string | null { const meta = item.metadata as Record; if (item.metadata.identifier.includes(youtubeId)) return "its identifier"; if (item.files.some((f) => f.name.includes(youtubeId))) return "a file's name"; if (textOf(meta.originalurl).includes(youtubeId)) return "its original URL"; if (textOf(meta.source).includes(youtubeId)) return "its source"; return null; } // How far a mirror's file may run from the record's duration: 5 s, or 2 %. export function mirrorLengthTolerance(seconds: number): number { return Math.max(5, seconds * 0.02); } // The item's video file for the upload: among its video files (a file naming // the id first, else every one when the item holds a single original video), // an ORIGINAL before a derivative, then mp4, webm, mkv, … — and, when the // record's duration is known, only a file whose length agrees with it (a // derivative's length is its original's when it has none). Null when the item // holds none that qualifies, or several originals none of which names the id // (a channel dump: which file is the upload cannot be told). export function pickMirrorFile( item: Pick, youtubeId: string, duration: number | null = null, ): { file: string; source: "original" | "derivative"; size?: number; seconds?: number } | null { const videos = item.files.filter( (f) => isArchiveOrgVideoFileName(f.name) && (f.source === "original" || f.source === "derivative"), ); const named = videos.filter((f) => f.name.includes(youtubeId)); const originals = videos.filter((f) => f.source === "original"); let pool = named.length > 0 ? named : originals.length === 1 ? videos : []; const lengthOf = (f: (typeof videos)[number]): number | undefined => parseArchiveOrgLength(f.length) ?? parseArchiveOrgLength(item.files.find((o) => o.name === f.original)?.length); if (duration !== null) { pool = pool.filter((f) => { const s = lengthOf(f); return s !== undefined && Math.abs(s - duration) <= mirrorLengthTolerance(duration); }); } if (pool.length === 0) return null; const rank = (f: { name: string; source?: string }) => (f.source === "original" ? 0 : 100) + (EXT_RANK.includes(extOf(f.name)) ? EXT_RANK.indexOf(extOf(f.name)) : EXT_RANK.length); const best = [...pool].sort((a, b) => rank(a) - rank(b))[0]!; const size = best.size && /^\d+$/.test(best.size) ? Number(best.size) : undefined; const seconds = lengthOf(best); return { file: best.name, source: best.source === "original" ? "original" : "derivative", ...(size !== undefined ? { size } : {}), ...(seconds !== undefined ? { seconds } : {}), }; } export type ArchiveOrgMirror = { identifier: string; title?: string; file: string; // The file's direct download URL. url: string; source: "original" | "derivative"; size?: number; seconds?: number; // How the item names the upload. namedBy: string; }; export type ArchiveOrgMirrorSearch = { youtubeId: string; query: string; found: number; mirrors: ArchiveOrgMirror[]; // Items the search found that are not a usable mirror, and why. skipped: { identifier: string; why: string }[]; }; // archive.org mirrors of one YouTube upload: the search (one request), then // each hit's metadata (one request each, cached), at most `limit` items. An // item that is not OF the upload (mirrorNamesId), is restricted, or holds no // video file of it (of the record's length, when `duration` is given) is // skipped, with why. export async function findArchiveOrgMirrors( youtubeId: string, o: { client?: ArchiveOrgClient; signal?: AbortSignal; limit?: number; duration?: number | null } = {}, ): Promise { const client = o.client ?? archiveOrgClient; const query = youtubeIdQuery(youtubeId); const hits = await searchArchiveOrgItems(query, { client, rows: o.limit ?? 10, ...(o.signal ? { signal: o.signal } : {}) }); const mirrors: ArchiveOrgMirror[] = []; const skipped: { identifier: string; why: string }[] = []; const duration = o.duration ?? null; for (const hit of hits.items) { o.signal?.throwIfAborted(); const item = await client.itemMetadata(hit.identifier, o.signal); const namedBy = mirrorNamesId(item, youtubeId); if (!namedBy) { skipped.push({ identifier: hit.identifier, why: "it mentions the id but is not of it (no identifier, file name or original URL names it)" }); continue; } if (archiveOrgRestriction(item).item) { skipped.push({ identifier: hit.identifier, why: "archive.org restricts it" }); continue; } const pick = pickMirrorFile(item, youtubeId, duration); if (!pick) { skipped.push({ identifier: hit.identifier, why: duration !== null ? `no video file of the upload with its length (${Math.round(duration)} s) can be told in it` : "no video file of the upload can be told in it", }); continue; } const meta = item.metadata as Record; const title = textOf(meta.title) || hit.title; mirrors.push({ identifier: item.metadata.identifier, ...(title ? { title } : {}), file: pick.file, url: archiveOrgDownloadUrl(item.metadata.identifier, pick.file), source: pick.source, ...(pick.size !== undefined ? { size: pick.size } : {}), ...(pick.seconds !== undefined ? { seconds: pick.seconds } : {}), namedBy, }); } // Originals first, then the search's order. mirrors.sort((a, b) => (a.source === b.source ? 0 : a.source === "original" ? -1 : 1)); return { youtubeId, query, found: hits.found, mirrors, skipped }; } // ─── Wayback: the captures of a page ─── export type WaybackLookup = { url: string; captures: WaybackCapture[] }; // The captures of a page (every one, or only the 200s). Throws // ArchiveOrgRequestError when the CDX API keeps refusing. export async function waybackLookup( url: string, o: { client?: Pick; okOnly?: boolean; limit?: number; signal?: AbortSignal } = {}, ): Promise { const client = o.client ?? waybackClient; const captures = await client.captures(url, { ...(o.okOnly ? { okOnly: true } : {}), ...(o.limit ? { limit: o.limit } : {}), ...(o.signal ? { signal: o.signal } : {}), }); return { url, captures }; } // ─── find-copy ─── // The Wayback finding for a video the index lists but whose stream does not // answer (release 32 R8): none found, recorded as such. export const WAYBACK_PAGE_ONLY = "page captured, no video"; export type FindCopyAttempt = { from: ClipCopy["from"]; found: boolean; url?: string; // What was found or why not, in a phrase. detail?: string; error?: string; }; export type FindCopyRecording = { slug: string; id: string; gone: GoneState; watchUrl: string | null; youtubeId: string | null; // The cited windows of the recording. windows: EvidenceWindow[]; // Copies an earlier fetch failed from (not picked again). failedBefore: ClipCopy[]; tried: FindCopyAttempt[]; copy?: ClipCopy; // fetch a copy found: its windows go to fetch-windows // text-only no copy: the moments show their words only ("source deleted") // error a lookup failed: a later run tries again outcome: "fetch" | "text-only" | "error"; }; export type FindCopyResult = { host: string; recordings: FindCopyRecording[]; // The fetch-windows items: each found copy's windows, its URL as the item's // webpageUrl and the copy for the provenance. items: FetchWindowsItem[]; // Why the run stopped before its last recording, when it did. stopped?: string; }; export type FindCopyDeps = { wayback: Pick; archive: ArchiveOrgClient; missing: (paths: Paths, host: ReportHost) => Promise; facts: (paths: Paths, slug: string, id: string) => Promise; failedCopies: (videoDir: string) => Promise; // (release 32 R8) a YouTube recording neither source holds is recorded // `none-found` in its copy-attempts.json, as the scope mode records one. recordAttempt: (videoDir: string, attempt: CopyAttempt) => Promise; now: () => Date; }; const DEFAULT_DEPS: FindCopyDeps = { wayback: waybackClient, archive: archiveOrgClient, missing: (paths, host) => missingEvidenceWindows(paths, host), facts: recordFacts, failedCopies: readFailedCopies, recordAttempt: recordCopyAttempt, now: () => new Date(), }; const describeAttempt = (t: FindCopyAttempt) => `${t.from} ${t.found ? `found — ${t.detail}` : t.error ? `failed — ${t.error}` : `none — ${t.detail}`}`; // ONE RECORDING'S LOOKUP, shared by the article mode and the scope mode: // Wayback when it holds the video (and no fetch from it failed before), then // an archive.org mirror of the upload, of its length, not failed before. A // lookup archive.org kept refusing sets `refused` (the caller stops its run). // No YouTube id: nothing is asked. export type CopyLookup = { tried: FindCopyAttempt[]; copy?: ClipCopy; // The archive.org mirror the copy is (its item and file). mirror?: ArchiveOrgMirror; // The capture timestamp a Wayback copy is dated by. captureTs?: string; refused?: string; }; export async function lookForCopy(o: { youtubeId: string | null; duration: number | null; failedBefore: ClipCopy[]; retryFailed?: boolean; deps: Pick; signal?: AbortSignal; }): Promise { const { youtubeId, deps, signal } = o; const sig = signal ? { signal } : {}; const out: CopyLookup = { tried: [] }; const failedUrls = new Set(o.retryFailed ? [] : o.failedBefore.map((f) => f.url)); const lookupFailed = (from: ClipCopy["from"], e: unknown) => { if (signal?.aborted) return; out.tried.push({ from, found: false, error: (e as Error).message }); if (e instanceof ArchiveOrgRequestError && e.rateLimited) out.refused = (e as Error).message; }; if (!youtubeId) { out.tried.push({ from: "wayback", found: false, detail: "not a YouTube recording: no copy is looked for" }); return out; } // 1. The Wayback Machine — when it holds the video, and no fetch from it failed before. if (!o.retryFailed && o.failedBefore.some((f) => f.from === "wayback")) { out.tried.push({ from: "wayback", found: false, detail: "a fetch from its Wayback copy failed before" }); } else { try { const video = await deps.wayback.youtubeVideoStream(youtubeId, sig); if (video.stream) { // The newest capture of the page that recorded a 200 dates the copy. const { captures } = await waybackLookup(`https://www.youtube.com/watch?v=${youtubeId}`, { client: deps.wayback, okOnly: true, ...sig, }); const newest = captures.filter((c) => c.status === "200").at(-1); const url = waybackYoutubeUrl(youtubeId, newest?.timestamp); out.copy = { from: "wayback", url }; if (newest) out.captureTs = newest.timestamp; out.tried.push({ from: "wayback", found: true, url, detail: `the video is archived and its stream answers${newest ? `; its page captured ${newest.timestamp}` : ""}` }); } else if (video.formats > 0) { const statuses = [...new Set(video.probes.map((p) => p.status))].join(", "); out.tried.push({ from: "wayback", found: false, detail: `${WAYBACK_PAGE_ONLY} (the video index lists ${video.formats} format(s); ${video.probes.length} probed, HTTP ${statuses})`, }); } else { out.tried.push({ from: "wayback", found: false, detail: "the video is not archived (its page may be)" }); } } catch (e) { lookupFailed("wayback", e); } } // 2. archive.org: a mirror OF the upload, of its length, not failed before. if (!out.copy && !out.refused && !signal?.aborted) { try { const found = await findArchiveOrgMirrors(youtubeId, { client: deps.archive, duration: o.duration, ...sig }); const m = found.mirrors.find((x) => !failedUrls.has(x.url)); if (m) { out.copy = { from: "archive.org", url: m.url }; out.mirror = m; out.tried.push({ from: "archive.org", found: true, url: m.url, detail: `${m.identifier}: ${m.file} (${m.source}; ${m.namedBy} names the id${m.seconds !== undefined ? `; ${Math.round(m.seconds)} s` : ""})`, }); } else { const failed = found.mirrors.length; out.tried.push({ from: "archive.org", found: false, detail: [ found.found ? `${found.found} item(s), none a usable mirror` : "no item names the id", ...(failed ? [`${failed} mirror(s) failed before`] : []), ...found.skipped.map((s) => `${s.identifier}: ${s.why}`), ].join("; "), }); } } catch (e) { lookupFailed("archive.org", e); } } return out; } // Look for a copy of every gone recording the host's reports cite: Wayback, // then archive.org, one recording at a time. Nothing is fetched here; the // answer's `items` are what fetch-windows is given (the caller starts it). export async function findCopies(opts: { paths: Paths; host: ReportHost; // Try copies recorded as failed again (they are still listed, as // `failedBefore`): for a failure later found to be ours, not the copy's. retryFailed?: boolean; // Nothing recorded (runFindCopy's dry run). dryRun?: boolean; signal?: AbortSignal; onLog?: (line: string) => void; deps?: Partial; }): Promise { const deps: FindCopyDeps = { ...DEFAULT_DEPS, ...opts.deps }; const log = (line: string) => opts.onLog?.(line); const signal = opts.signal; const need = await deps.missing(opts.paths, opts.host); const byRecording = new Map(); for (const w of need.unfetchable) { if (w.why !== "gone" || !w.gone) continue; const key = `${w.slug}/${w.id}`; const r = byRecording.get(key) ?? { slug: w.slug, id: w.id, gone: w.gone, windows: [] }; r.windows.push(w); byRecording.set(key, r); } const result: FindCopyResult = { host: opts.host.id, recordings: [], items: [] }; log(`find-copy ${opts.host.id}: ${byRecording.size} gone recording(s) cited, ${[...byRecording.values()].reduce((n, r) => n + r.windows.length, 0)} window(s).`); for (const r of byRecording.values()) { if (signal?.aborted) break; const facts = await deps.facts(opts.paths, r.slug, r.id); const youtubeId = youtubeIdOf(facts.webpageUrl); const failedBefore = (await deps.failedCopies(facts.videoDir).catch(() => [] as FailedCopy[])).map(({ from, url }) => ({ from, url })); const rec: FindCopyRecording = { ...r, watchUrl: facts.webpageUrl, youtubeId, failedBefore, tried: [], outcome: "text-only" }; result.recordings.push(rec); const look = await lookForCopy({ youtubeId, duration: facts.duration, failedBefore, retryFailed: opts.retryFailed, deps, signal }); rec.tried.push(...look.tried); if (look.copy) rec.copy = look.copy; const refused = look.refused; if (signal?.aborted) break; if (rec.copy) { rec.outcome = "fetch"; for (const w of r.windows) { result.items.push({ slug: w.slug, id: w.id, from: w.from, to: w.to, clipId: w.clipId, ...(w.reason ? { reason: w.reason.slice(0, 400) } : {}), webpageUrl: rec.copy.url, copy: rec.copy, }); } } else if (rec.tried.some((t) => t.error)) { rec.outcome = "error"; } else if (youtubeId && !opts.dryRun) { await deps .recordAttempt(facts.videoDir, { at: deps.now().toISOString(), outcome: "none-found", detail: rec.tried.map(describeAttempt).join("; ") }) .catch((e: unknown) => log(` ${r.slug}/${r.id}: copy-attempts.json not written (${(e as Error).message}).`)); } log( ` ${r.slug}/${r.id} (${r.gone}, ${r.windows.length} window(s)): ` + rec.tried.map(describeAttempt).join("; ") + ` → ${rec.outcome === "fetch" ? `fetch from the ${rec.copy!.from === "wayback" ? "Wayback copy" : "archive.org file"}` : rec.outcome === "text-only" ? "its words only" : "try again later"}`, ); if (refused) { result.stopped = `archive.org kept refusing (${refused}); the rest are left for a later run`; log(`find-copy: ${result.stopped}.`); break; } } if (signal?.aborted) { result.stopped = "cancelled; the rest are left for a later run"; log(`find-copy: ${result.stopped}.`); } return result; } // The line a find-copy job's log ends with, then its result as JSON. export const FIND_COPY_RESULT_MARKER = "@@find-copy "; // find-copy, whole: the lookups, then (unless `dryRun`, or the run was // cancelled) ONE fetch-windows of every found copy's windows through // `startFetch` (the editor's job). A run with nothing found starts nothing. export async function runFindCopy(opts: { paths: Paths; host: ReportHost; dryRun?: boolean; retryFailed?: boolean; signal?: AbortSignal; onLog?: (line: string) => void; deps?: Partial; startFetch: (items: FetchWindowsItem[]) => Promise; }): Promise { const found = await findCopies(opts); if (opts.dryRun || opts.signal?.aborted || found.items.length === 0) return found; return { ...found, fetch: await opts.startFetch(found.items) }; } // ─── find-copy, scope mode: every gone video of a channel or a site (release 31) ─── // // The article mode above fetches the cited WINDOWS of gone recordings. This // mode brings a gone video's WHOLE audio home into its own record, so the // transcription lane transcribes it like any other: `{slug | siteId, gone: // "no-transcript" | "all", dryRun?, max?, retryFailed?}`. // // THE CANDIDATES: every video dir of the channel (or of every channel in the // site's pool, `site.json` `channels`, in its order) that is gone by THE one // reading (lib/sourceGone-server.ts sourceGoneState: deleted or private), that // holds no audio or video yet (ytdlp/fetchCopyManaged.ts holdsMedia), and — for // "no-transcript" — no transcript (lib/videoStatus.ts isVideoTranscribed); // "all" takes the transcribed ones too, after every untranscribed one. A video // whose newest copy attempt is terminal (none-found, failed) and younger than // COPY_ATTEMPT_RETRY_DAYS is left out, unless `retryFailed`. A channel whose // text cannot be read is named and skipped (an unmounted drive is not an empty // channel). The cheap checks (one readdir) come first; the availability is read // only for what passes them. // // THE LOOKUPS are the article mode's (lookForCopy), one video at a time, at // most `max` of them per run (a non-YouTube video costs none and is listed); // archive.org refusing stops the run. Not a dry run: a video neither source // holds is recorded `none-found` in its copy-attempts.json, and the copies // found go to ONE fetch-copies job (controller/fetchCopies.ts) — through // `startFetch`, the editor's. A dry run asks the same questions and records // and fetches nothing. export const GONE_SCOPES = ["no-transcript", "all"] as const; export type GoneScope = (typeof GONE_SCOPES)[number]; // Lookups per run: a small default, and a ceiling. export const FIND_COPY_DEFAULT_MAX = 10; export const FIND_COPY_MAX_LIMIT = 200; export type WholeCopyScope = { slug: string } | { siteId: string }; export type GoneCandidate = { slug: string; id: string; videoDir: string; gone: GoneState; noTranscript: boolean; }; export type GoneEnumeration = { channels: string[]; candidates: GoneCandidate[]; skipped: { // Gone or not, already holding audio or video (not asked whether gone). media: number; // Holding a transcript, in "no-transcript" mode (not asked whether gone). transcript: number; // Gone, with a recent terminal copy attempt. recent: { slug: string; id: string; at: string; outcome: string }[]; // Channels whose text cannot be read. unreadable: { slug: string; error: string }[]; }; }; export type GoneEnumerationDeps = { listIds: (paths: Paths, slug: string) => Promise; assertTextReadable: (paths: Paths, slug: string) => Promise; goneState: (videoDir: string) => Promise; copyAttempts: (videoDir: string) => Promise; }; const DEFAULT_ENUM_DEPS: GoneEnumerationDeps = { listIds: listChannelVideoIds, assertTextReadable: (paths, slug) => assertChannelTextReadable(paths, slug), goneState: sourceGoneState, copyAttempts: loadCopyAttempts, }; export async function enumerateGoneVideos(opts: { paths: Paths; slugs: string[]; gone: GoneScope; retryFailed?: boolean; now?: number; signal?: AbortSignal; deps?: Partial; }): Promise { const deps: GoneEnumerationDeps = { ...DEFAULT_ENUM_DEPS, ...opts.deps }; const now = opts.now ?? Date.now(); const out: GoneEnumeration = { channels: [...opts.slugs], candidates: [], skipped: { media: 0, transcript: 0, recent: [], unreadable: [] }, }; const untranscribed: GoneCandidate[] = []; const transcribed: GoneCandidate[] = []; for (const slug of opts.slugs) { if (opts.signal?.aborted) break; try { await deps.assertTextReadable(opts.paths, slug); } catch (e) { out.skipped.unreadable.push({ slug, error: (e as Error).message }); continue; } const ids = (await deps.listIds(opts.paths, slug)).sort(); for (const id of ids) { if (opts.signal?.aborted) break; const videoDir = path.join(opts.paths.channelsDir, slug, "data", id); const files = await readVideoFiles(videoDir); if (holdsMedia(files.entries)) { out.skipped.media++; continue; } const noTranscript = !isVideoTranscribed(files); if (!noTranscript && opts.gone === "no-transcript") { out.skipped.transcript++; continue; } const gone = await deps.goneState(videoDir).catch(() => null); if (!gone) continue; if (!opts.retryFailed) { const recent = recentTerminalAttempt(await deps.copyAttempts(videoDir).catch(() => null), now); if (recent) { out.skipped.recent.push({ slug, id, at: recent.at, outcome: recent.outcome }); continue; } } (noTranscript ? untranscribed : transcribed).push({ slug, id, videoDir, gone, noTranscript }); } } out.candidates = [...untranscribed, ...transcribed]; return out; } export type WholeCopyCandidate = { slug: string; id: string; gone: GoneState; noTranscript: boolean; watchUrl: string | null; youtubeId: string | null; failedBefore: ClipCopy[]; tried: FindCopyAttempt[]; copy?: ClipCopy; // What the copy is, in a phrase: the archive.org item and file, or the // Wayback capture. via?: string; // fetch a copy found: its whole audio goes to fetch-copies // none-found neither source holds it (recorded, not a dry run) // not-youtube not a YouTube recording: nothing is looked for // error a lookup failed: a later run asks again outcome: "fetch" | "none-found" | "not-youtube" | "error"; }; export type FindWholeCopiesResult = { scope: WholeCopyScope; gone: GoneScope; dryRun: boolean; max: number; channels: string[]; // Gone videos that qualified (before `max`). eligible: number; skipped: GoneEnumeration["skipped"]; looked: WholeCopyCandidate[]; // Qualifying YouTube videos left for a later run by `max`. left: number; items: FetchCopyItem[]; stopped?: string; }; export type FindWholeCopiesDeps = Pick & { enumerate: GoneEnumerationDeps; recordAttempt: (videoDir: string, attempt: CopyAttempt) => Promise; siteChannels: (paths: Paths, siteId: string) => string[]; now: () => Date; }; const DEFAULT_WHOLE_DEPS: FindWholeCopiesDeps = { wayback: waybackClient, archive: archiveOrgClient, facts: recordFacts, failedCopies: readFailedCopies, enumerate: DEFAULT_ENUM_DEPS, recordAttempt: recordCopyAttempt, siteChannels: (paths, siteId) => getSite(siteId, paths).channels.map((c) => c.slug), now: () => new Date(), }; export function wholeCopyScopeLabel(scope: WholeCopyScope): string { return "slug" in scope ? `channel ${scope.slug}` : `site ${scope.siteId}`; } export async function findWholeCopies(opts: { paths: Paths; scope: WholeCopyScope; gone: GoneScope; dryRun?: boolean; max?: number; retryFailed?: boolean; signal?: AbortSignal; onLog?: (line: string) => void; deps?: Partial> & { enumerate?: Partial }; }): Promise { const deps: FindWholeCopiesDeps = { ...DEFAULT_WHOLE_DEPS, ...opts.deps, enumerate: { ...DEFAULT_ENUM_DEPS, ...opts.deps?.enumerate }, }; const log = (line: string) => opts.onLog?.(line); const signal = opts.signal; const dryRun = opts.dryRun === true; const max = Math.min(FIND_COPY_MAX_LIMIT, Math.max(1, Math.floor(opts.max ?? FIND_COPY_DEFAULT_MAX))); const slugs = "slug" in opts.scope ? [opts.scope.slug] : deps.siteChannels(opts.paths, opts.scope.siteId); const found = await enumerateGoneVideos({ paths: opts.paths, slugs, gone: opts.gone, retryFailed: opts.retryFailed, now: deps.now().getTime(), ...(signal ? { signal } : {}), deps: deps.enumerate, }); const result: FindWholeCopiesResult = { scope: opts.scope, gone: opts.gone, dryRun, max, channels: found.channels, eligible: found.candidates.length, skipped: found.skipped, looked: [], left: 0, items: [], }; log( `find-copy ${wholeCopyScopeLabel(opts.scope)} (gone: ${opts.gone}${dryRun ? ", dry run" : ""}): ` + `${found.candidates.length} gone video(s) with no media` + `${opts.gone === "no-transcript" ? " and no transcript" : ""} in ${found.channels.length} channel(s); ` + `at most ${max} looked up.` + (found.skipped.recent.length ? ` ${found.skipped.recent.length} left out: a copy attempt in the last ${COPY_ATTEMPT_RETRY_DAYS} days found none or failed.` : ""), ); for (const u of found.skipped.unreadable) log(` ${u.slug}: skipped — ${u.error}`); let lookups = 0; for (let i = 0; i < found.candidates.length; i++) { const c = found.candidates[i]!; if (signal?.aborted) break; const facts = await deps.facts(opts.paths, c.slug, c.id); const youtubeId = youtubeIdOf(facts.webpageUrl); if (youtubeId && lookups >= max) { result.left++; continue; } const failedBefore = (await deps.failedCopies(facts.videoDir).catch(() => [] as FailedCopy[])).map(({ from, url }) => ({ from, url })); const rec: WholeCopyCandidate = { slug: c.slug, id: c.id, gone: c.gone, noTranscript: c.noTranscript, watchUrl: facts.webpageUrl, youtubeId, failedBefore, tried: [], outcome: youtubeId ? "none-found" : "not-youtube", }; if (youtubeId) lookups++; const look = await lookForCopy({ youtubeId, duration: facts.duration, failedBefore, retryFailed: opts.retryFailed, deps, signal }); rec.tried = look.tried; if (signal?.aborted) break; result.looked.push(rec); if (look.copy) { rec.copy = look.copy; rec.outcome = "fetch"; rec.via = look.mirror ? `archive.org ${look.mirror.identifier} / ${look.mirror.file}` : `the Wayback Machine${look.captureTs ? `, captured ${look.captureTs}` : ""}`; result.items.push({ slug: c.slug, id: c.id, copy: look.copy }); } else if (look.tried.some((t) => t.error)) { rec.outcome = "error"; } else if (youtubeId && !dryRun) { await deps .recordAttempt(facts.videoDir, { at: deps.now().toISOString(), outcome: "none-found", detail: look.tried.map(describeAttempt).join("; "), }) .catch((e: unknown) => log(` ${c.slug}/${c.id}: copy-attempts.json not written (${(e as Error).message}).`)); } log( ` ${c.slug}/${c.id} (${c.gone}${c.noTranscript ? ", no transcript" : ""}): ` + rec.tried.map(describeAttempt).join("; ") + ` → ${ rec.outcome === "fetch" ? `${dryRun ? "would fetch" : "fetch"} its audio from ${rec.via}` : rec.outcome === "none-found" ? `none found${dryRun ? "" : " (recorded)"}` : rec.outcome === "not-youtube" ? "not looked for" : "try again later" }`, ); if (look.refused) { result.stopped = `archive.org kept refusing (${look.refused}); the rest are left for a later run`; log(`find-copy: ${result.stopped}.`); break; } } if (signal?.aborted) { result.stopped = "cancelled; the rest are left for a later run"; log(`find-copy: ${result.stopped}.`); } if (result.left > 0) log(`find-copy: ${result.left} more gone video(s) are left for a later run (max ${max}).`); log( `find-copy: ${result.items.length} cop${result.items.length === 1 ? "y" : "ies"} found` + `${dryRun ? " (dry run: nothing fetched or recorded)" : ""}.`, ); return result; } // The scope mode, whole: the lookups, then (unless `dryRun`, or the run was // cancelled) ONE fetch-copies of every copy found through `startFetch`. export async function runFindWholeCopies( opts: Parameters[0] & { startFetch: (items: FetchCopyItem[]) => Promise }, ): Promise { const found = await findWholeCopies(opts); if (opts.dryRun || opts.signal?.aborted || found.items.length === 0) return found; return { ...found, fetch: await opts.startFetch(found.items) }; }