"use server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSite, isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/lib/site"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { diskGate } from "yt-dlp-transcript-common/lib/diskSpace"; import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { clipWindowQueueKey } from "yt-dlp-transcript-common/lib/queueKeys"; import { platformQueueKey } from "yt-dlp-transcript-common/lib/platform"; import { articlesWorkHost, siteReportHost, type ReportHost } from "yt-dlp-transcript-common/publish/reportHost"; import { FIND_COPY_RESULT_MARKER, runFindCopy, runFindWholeCopies, type GoneScope, type WholeCopyScope, } from "yt-dlp-transcript-common/publish/findCopy"; import { fetchCopies, type FetchCopyItem } from "yt-dlp-transcript-common/controller/fetchCopies"; import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { requestChannelSnapshot } from "yt-dlp-transcript-common/jobs/snapshotScheduler"; import { runManagedFunction, type StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; import { fetchWindowsJobAction } from "./fetchWindowsAction"; import { safeRevalidate } from "../../../lib/safeRevalidate"; // FIND A COPY OF THE GONE RECORDINGS A REPORT CITES, and fetch their windows // from it (release 29 E2; the lookups are publish/findCopy.ts) — AS A JOB // (`find-copy`, its own queue): the lookups take seconds per recording, paced, // and a request must not hold them (nor start a fetch after its caller gave // up). A cancelled job starts no fetch. The windows of every copy found go to // ONE fetch-windows job on the archive.org clip queue — Wayback copies and // archive.org files are both archive.org's — so they are fetched one at a // time, paced, one stream. The job's log ends with // `@@find-copy {recordings, items, stopped?, fetchJobId?, refused?}`. const FIND_COPY_QUEUE = "find-copy"; // The archive.org clip queue: every copy's windows, one job, one stream. const FETCH_QUEUE = clipWindowQueueKey(platformQueueKey("archiveorg")); export async function findCopyAction(req: { article?: string; siteId?: string; dryRun?: boolean; // Try copies recorded as failed again (publish/findCopy.ts). retryFailed?: boolean; }): Promise { const paths = getPaths(); let host: ReportHost; try { if (req.article) { host = await articlesWorkHost(paths, [req.article], { only: true }); } else if (req.siteId) { if (!isValidSiteId(req.siteId)) return { ok: false, error: `"${req.siteId}" is not a valid site id` }; if (!listSiteIds(paths).includes(req.siteId)) return { ok: false, error: `No site "${req.siteId}"` }; host = siteReportHost(paths, getSite(req.siteId, paths)); } else { host = await articlesWorkHost(paths); } } catch (e) { return { ok: false, error: (e as Error).message }; } return runManagedFunction({ kind: "find-copy", queueKey: FIND_COPY_QUEUE, paths, fn: async (onLog, signal) => { let refused: string | undefined; const r = await runFindCopy({ paths, host, dryRun: req.dryRun, retryFailed: req.retryFailed, signal, onLog, startFetch: async (items) => { const res = await fetchWindowsJobAction({ items, requestedBy: "find-copy", manifest: host.id, queueKey: FETCH_QUEUE }); if (!res.ok) { refused = res.error; return null; } // Nobody reads the stream: the job's log is on disk. void res.stream.cancel().catch(() => {}); onLog(`find-copy: fetch-windows job ${res.jobId} fetches ${items.length} window(s) from the copies found.`); return res.jobId; }, }); const { fetch: fetchJobId, ...found } = r; onLog( `${FIND_COPY_RESULT_MARKER}${JSON.stringify({ ...found, dryRun: req.dryRun === true, ...(typeof fetchJobId === "string" ? { fetchJobId } : {}), ...(refused ? { refused } : {}), })}`, ); if (refused) throw new Error(`the fetch was refused: ${refused}`); if (signal.aborted) throw new Error("cancelled"); }, }); } // ─── The scope mode (release 31, lane C): every gone video's WHOLE audio ─── // // `{slug | siteId, gone: "no-transcript" | "all", dryRun?, max?, retryFailed?}` // (publish/findCopy.ts findWholeCopies): a find-copy job looks for a copy of // each gone video of the channel or the site's channels with no media, at most // `max` per run; the copies found go to ONE fetch-copies job on the archive.org // download queue (one stream to archive.org, behind its imports), which brings // each one's audio into its own record as `audio.`. Its log ends with // `@@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked, // left, items, stopped?, fetchJobId?, refused?}`. // The archive.org download queue: whole files, one at a time. const FETCH_COPIES_QUEUE = platformQueueKey("archiveorg"); export async function findWholeCopiesAction(req: { slug?: string; siteId?: string; gone: GoneScope; dryRun?: boolean; max?: number; retryFailed?: boolean; }): Promise { const paths = getPaths(); let scope: WholeCopyScope; if (req.slug) { if (!isValidChannelSlug(req.slug)) return { ok: false, error: `"${req.slug}" is not a valid channel slug` }; if (!(await readChannelConfig(paths, req.slug).catch(() => null))) return { ok: false, error: `No channel "${req.slug}"` }; scope = { slug: req.slug }; } else if (req.siteId) { if (!isValidSiteId(req.siteId)) return { ok: false, error: `"${req.siteId}" is not a valid site id` }; if (!listSiteIds(paths).includes(req.siteId)) return { ok: false, error: `No site "${req.siteId}"` }; scope = { siteId: req.siteId }; } else { return { ok: false, error: 'send "slug" or "siteId" with "gone"' }; } return runManagedFunction({ kind: "find-copy", queueKey: FIND_COPY_QUEUE, paths, fn: async (onLog, signal) => { let refused: string | undefined; const r = await runFindWholeCopies({ paths, scope, gone: req.gone, dryRun: req.dryRun, max: req.max, retryFailed: req.retryFailed, signal, onLog, startFetch: async (items) => { const res = await fetchCopiesJobAction({ items, requestedBy: "find-copy" }); if (!res.ok) { refused = res.error; return null; } void res.stream.cancel().catch(() => {}); onLog(`find-copy: fetch-copies job ${res.jobId} fetches the audio of ${items.length} gone video(s) from the copies found.`); return res.jobId; }, }); const { fetch: fetchJobId, ...found } = r; onLog( `${FIND_COPY_RESULT_MARKER}${JSON.stringify({ ...found, ...(typeof fetchJobId === "string" ? { fetchJobId } : {}), ...(refused ? { refused } : {}), })}`, ); if (refused) throw new Error(`the fetch was refused: ${refused}`); if (signal.aborted) throw new Error("cancelled"); }, }); } // ONE fetch-copies job (controller/fetchCopies.ts) for a list of gone videos // and their copies. A list of one channel carries it, so the media guard and // the report regeneration name it; one spanning channels asks each channel's // media guard in the controller and asks each changed channel's report here. export async function fetchCopiesJobAction(req: { items: FetchCopyItem[]; requestedBy: string; }): Promise { if (req.items.length === 0) return { ok: false, error: "No copies to fetch." }; const paths = getPaths(); // A whole file lands on the corpus (or its media) disk: the floor a click asks. const disk = await diskGate(paths, getSettings(), { mode: "manual", dir: paths.channelsDir }); if (!disk.ok) { return { ok: false, error: `Low disk space: ${formatBytes(disk.freeBytes)} free, ` + `${formatBytes(disk.thresholdBytes)} required. Free up space or lower the floor in Settings.`, }; } const slugs = [...new Set(req.items.map((i) => i.slug))]; return runManagedFunction({ kind: "fetch-copies", queueKey: FETCH_COPIES_QUEUE, paths, ...(slugs.length === 1 ? { channelSlug: slugs[0] } : {}), fn: async (onLog, signal, setProgress, ctx) => { onLog(`Requested by ${req.requestedBy}.`); const result = await fetchCopies({ paths, items: req.items, onLog, signal, drainSignal: ctx.drainSignal, setProgress, }); // The transcription lane draws from the snapshot: each channel that // gained audio has its report regenerated (downloadedNoTranscript). for (const slug of new Set(result.fetched.map((f) => f.slug))) requestChannelSnapshot(paths, slug); safeRevalidate([...new Set(result.fetched.map((f) => `/channels/${f.slug}/videos/${f.id}`))]); if (result.stopped && result.stopped !== "drain" && result.stopped !== "cancel") { throw new Error(`Stopped (${result.stopped}) with ${result.notAttempted.length} copy(ies) not attempted — run it again later.`); } if (result.failed.length > 0) throw new Error(`${result.failed.length} copy(ies) failed to fetch.`); }, }); }