// FETCH A GONE VIDEO'S WHOLE AUDIO FROM A COPY into its OWN record (release 31, // lane C). // // find-copy's scope mode found a copy of a deleted or private YouTube upload — // the Wayback Machine holding the video, or an archive.org mirror of it // (publish/findCopy.ts) — and fetch-copies (controller/fetchCopies.ts) brings // the audio home: `data//audio.` of the ORIGINAL record, where the // transcription lane finds it like any other downloaded audio // (channelSnapshot's downloadedNoTranscript; the lane does not ask whether the // platform still serves the video). // // AN EXPLICIT RECORD, like fetchWindowManaged: the caller names the video dir, // so a Wayback replay URL or an archive.org file URL — whose own ids are not // the record's — never decides where the bytes land. // // WHAT IT DELIBERATELY DOES NOT DO: write metadata.info.json, subtitles, a // thumbnail or an archive line. The record's metadata is the ORIGINAL's (its // title, date and page stay; a copy's are often worse — release 24's // persist-provenance rule), so this is not downloadOneManaged, whose prefetch // rewrites that file from whatever the URL's extractor says. The argv is // assembled here, in full, with the writers negated last. // // AUDIO ONLY: `-f ba/b` (a Wayback copy or a mirror is usually ONE file of // unknown height holding both streams; `b` takes it) and yt-dlp's own // extraction (`-x --audio-format `), the source // container discarded. The file is written under a two-segment scratch name // (`audio.copy-part.`, which no reader takes for finished audio: // lib/mediaFiles.ts isRealAudioFile) and renamed into place, then handed to the // media tier's hook (lib/mediaTier-server.ts) like every finished media file. // // NO COOKIES and none of the channel's platform args or extra args: the copy // is archive.org's, not the channel's platform's, and the channel's browser // cookies have no business going to it. Paced like archive.org's clients // (`--sleep-requests 2`). import path from "node:path"; import { readdir, rename, rm, stat } from "node:fs/promises"; import { classifyDownloadFailure, parseUnavailableFromStderr, } from "../lib/availability"; import type { ChannelConfig } from "../lib/channelConfig"; import type { Paths } from "../lib/paths"; import type { ClipCopy } from "../lib/clipWindow"; import { isRealAudioFile, isSourceMediaFile } from "../lib/mediaFiles"; import { SAVED_VIDEO_POINTER_FILENAME } from "../lib/savedVideo"; import { tierMediaFile } from "../lib/mediaTier-server"; import { runOneYtdlp } from "./runOneYtdlp"; import { FULL_LOG_PROGRESS_ARGS } from "./downloadOneManaged"; import { FetchWindowError } from "./fetchWindowManaged"; // The scratch base the download and the extraction write under. export const COPY_PART_BASENAME = "audio.copy-part"; // archive.org's own pace (lib/archiveOrgClient.ts: 2 s between requests). export const COPY_SLEEP_REQUESTS_SECONDS = 2; export type FetchCopyOpts = { paths: Paths; channelConfig: ChannelConfig; // channels//data/ — the ORIGINAL record's directory. videoDir: string; videoId: string; copy: ClipCopy; onLog: (s: string) => void; signal: AbortSignal; }; export type FetchCopyResult = { // `audio.`, in the video dir (a tier link when the channel has a tier). audioFile: string; bytes: number; args: string[]; }; // Whether a video dir's entries already hold its audio or video: finished // audio, a persisted source container, or a saved-video pointer. A copy is // never fetched over any of them. export function holdsMedia(entries: readonly string[]): boolean { return entries.some((e) => isRealAudioFile(e) || isSourceMediaFile(e) || e === SAVED_VIDEO_POINTER_FILENAME); } export function copyAudioFormat(config: ChannelConfig): string { return config.audioFormat ?? "mp3"; } export function fetchCopyArgs(videoDir: string, copy: ClipCopy, audioFormat: string): string[] { return [ "--ignore-config", "--no-playlist", "--sleep-requests", String(COPY_SLEEP_REQUESTS_SECONDS), "-f", "ba/b", "-x", "--audio-format", audioFormat, ...FULL_LOG_PROGRESS_ARGS, "--no-write-info-json", "--no-write-description", "--no-write-thumbnail", "--no-write-subs", "--no-write-auto-subs", "--no-download-archive", "-o", path.join(videoDir, `${COPY_PART_BASENAME}.%(ext)s`), "--", copy.url, ]; } async function scratchFiles(videoDir: string): Promise { return (await readdir(videoDir).catch(() => [] as string[])).filter((f) => f.startsWith(`${COPY_PART_BASENAME}.`)); } async function clearScratch(videoDir: string): Promise { for (const f of await scratchFiles(videoDir)) await rm(path.join(videoDir, f), { force: true }).catch(() => {}); } export async function fetchCopyManaged(opts: FetchCopyOpts): Promise { const { videoDir } = opts; const fmt = copyAudioFormat(opts.channelConfig); const audioFile = `audio.${fmt}`; const existing = (await readdir(videoDir).catch(() => [] as string[])).filter(isRealAudioFile); if (existing.length > 0) { throw new Error(`${opts.videoId} already holds audio (${existing.join(", ")}); nothing is fetched over it`); } await clearScratch(videoDir); const args = fetchCopyArgs(videoDir, opts.copy, fmt); const outcome = await runOneYtdlp( { ytdlpBin: opts.paths.ytdlpBin, onLog: opts.onLog, signal: opts.signal, observe: { paths: opts.paths, url: opts.copy.url }, }, videoDir, args, ); if (outcome.exitCode !== 0) { await clearScratch(videoDir); const tail = outcome.stderrTail.trim().split("\n").slice(-4).join(" / "); const availability = parseUnavailableFromStderr(outcome.stderrTail); throw new FetchWindowError( `yt-dlp failed fetching the ${opts.copy.from} copy of ${opts.videoId} (exit ${outcome.exitCode ?? "null"}): ${tail}`, classifyDownloadFailure(outcome.stderrTail, availability), availability, ); } // The extraction's output: `audio.copy-part.`. Anything else left is // the source container yt-dlp kept or a stray, and goes. const produced = `${COPY_PART_BASENAME}.${fmt}`; const st = await stat(path.join(videoDir, produced)).catch(() => null); if (!st?.isFile() || st.size === 0) { await clearScratch(videoDir); throw new Error(`yt-dlp reported success but wrote no ${fmt} audio for ${opts.videoId}`); } await rename(path.join(videoDir, produced), path.join(videoDir, audioFile)); await clearScratch(videoDir); await tierMediaFile(videoDir, audioFile, { onLog: opts.onLog }); opts.onLog(`Fetched the ${opts.copy.from} copy of ${opts.videoId} into ${audioFile} (${st.size} bytes).\n`); return { audioFile, bytes: st.size, args }; }