// IMPORT A FILE AS A NORMAL TRANSCRIBED ITEM — `pnpm ops import-media`, the // channel page's and the video page's "Import a file" (plans/live-capture.md). // // A file from outside the archive — a stream recorded by hand, a copy from an // external archive — becomes a video like any other: a record, its source // container in the saved-video store, audio., and the channel's pipeline // from there. Which record: // // url the source page. The record is created (or refreshed) by ONE // metadata-only yt-dlp pass — refreshVideoMetadata, the channel's // cookies and the platform's pace — under the id the archive names // it by (`dataDirIdForUrl`: Rumble's URL id, not the embed id the // metadata carries). A held platform, or one cooling down, refuses // a new record before any job; an existing one is landed without the // refresh. // id a record already here. // meta a record by hand ({title, date?, duration?, description?}) for a // file with no source page; its id is `id` when given, else the // file's name (importIdFromFilename). Never over an existing record. // // The landing is landMediaFile's (controller/landMedia.ts), shared with the // live recording: probe, keep the longer, finalize without re-encoding, // persist, move only after the verify, audio, archive line, provenance. // A directory, a .zip or a .7z is not a file: the editor action hands it to // attach-media's walk (controller/attachMedia.ts) instead. // // The job is `import-media` on its own queue (`import-media:`): a // multi-GB copy never holds a platform's download queue — except an import by // an X page's address (x.com, twitter.com, t.co), which asks X for its // metadata and so runs on X's queue on any channel (review 4 B). `needsMedia`: // it writes the container and the audio. import { localMediaWriteRefusal } from "./localMediaDoors"; import path from "node:path"; import { mkdir, readdir, rm, stat } from "node:fs/promises"; import type { ChannelConfig } from "../lib/channelConfig"; import { assertChannelTextReadable } from "../lib/channelMedia"; import type { ResolvedCookiePolicy } from "../lib/cookiePolicy"; import { writeJsonAtomic } from "../lib/jsonFile-server"; import { importIdFromFilename, manualRecordInfo, type ImportMediaRequest, } from "../lib/mediaImport"; import { withMetadataHistory } from "../lib/metadataHistory-server"; import { setDoNotClean } from "../lib/doNotClean-server"; import { applyPendingKeep } from "../lib/pendingKeep-server"; import type { Paths } from "../lib/paths"; import { detectPlatform } from "../lib/platform"; import { heldPlatformRefusal, platformCooldownRemainingMs, recordDownloadBackoff, recordPlatformClean, } from "../jobs/downloadBackoff"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { configForVideoUrl } from "../ytdlp/channelArgs"; import { dataDirIdForUrl } from "../ytdlp/runYtdlp"; import { landMediaFile, probeMedia, readHandoffFacts, transcriptionHandoffLines, type LandMediaDeps, type LandMediaResult, } from "./landMedia"; import { refreshVideoMetadata, type RefreshRunner } from "./refreshVideoMetadata"; import { X_QUEUE_KEY, isXUrl, xJobContextRefusal } from "../lib/xJobRule"; export const IMPORT_MEDIA_JOB_KIND = "import-media"; export const IMPORT_MEDIA_RESULT_MARKER = "@@import-media "; export function importMediaQueueKey(slug: string): string { return `import-media:${slug}`; } // THE JOB'S QUEUE (review 4 B): an import by an X page's address — x.com, // twitter.com, t.co (lib/xJobRule.ts isXUrl) — asks X for its metadata, so it // runs on X's queue, under the jar rule and X's job cap, on ANY channel. // Everything else on its own queue. export function importMediaJobQueueKey(slug: string, target: ImportTarget): string { return target.kind === "url" && isXUrl(target.url) ? X_QUEUE_KEY : importMediaQueueKey(slug); } // A path the action hands to attach-media's walk rather than landing itself. export function isArchivePath(p: string, isDirectory: boolean): boolean { return isDirectory || /\.(zip|7z)$/i.test(p); } export type ImportTarget = | { kind: "url"; id: string; url: string; platform: string; exists: boolean } | { kind: "id"; id: string } | { kind: "meta"; id: string }; async function isDir(p: string): Promise { return stat(p).then((s) => s.isDirectory(), () => false); } async function hasInfo(videoDir: string): Promise { return stat(path.join(videoDir, "metadata.info.json")).then((s) => s.isFile(), () => false); } // WHICH RECORD, OR WHY NOT — before any job, in the sentences the caller shows. export async function resolveImportTarget( paths: Paths, req: ImportMediaRequest, ): Promise { const dataDir = path.join(paths.channelsDir, req.slug, "data"); if (req.url) { const id = dataDirIdForUrl(req.url); if (!id) return { error: `No record id can be read from ${req.url}` }; if (req.id && req.id !== id) { return { error: `"id" ${req.id} is not the id ${req.url} is archived by (${id}); give one of them` }; } // X's addresses (t.co and X's media hosts too) are X's pace and holds. const platform = isXUrl(req.url) ? "twitter" : (detectPlatform(req.url) ?? "unknown"); return { kind: "url", id, url: req.url, platform, exists: await hasInfo(path.join(dataDir, id)) }; } if (req.meta) { const id = req.id ?? importIdFromFilename(path.basename(req.path)); if (await isDir(path.join(dataDir, id))) { return { error: `${req.slug} already has a record ${id}: import into it with {"id": "${id}"} and no "meta", or name a new id`, }; } return { kind: "meta", id }; } const id = req.id!; if (!(await isDir(path.join(dataDir, id)))) { return { error: `${req.slug} has no record ${id}: give the source page as "url", or describe it with "meta"` }; } return { kind: "id", id }; } export type ImportMediaJobOpts = { paths: Paths; request: ImportMediaRequest; channelConfig: ChannelConfig; cookiePolicy: ResolvedCookiePolicy; // After the landing, when the request asked `transcribe: true`: the editor // queues the transcribe-one job (held by any pause, as every one is). requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>; afterRun?: () => void | Promise; // The job running it, recorded on the do-not-clean mark it sets. jobId?: string; deps?: { refresh?: RefreshRunner; land?: LandMediaDeps; // Test seam: the hand-off's facts (default: the running editor's). handoff?: typeof readHandoffFacts; }; }; export type ImportMediaSummary = { slug: string; id: string; dryRun: boolean; record: "created" | "refreshed" | "existing" | "by-hand" | "would-create" | "would-refresh"; kept: LandMediaResult["kept"]; seconds: number | null; existingSeconds?: number | null; finalized: LandMediaResult["finalized"]; audio: LandMediaResult["audio"]; moved: boolean; container: string | null; transcribeJob?: string; }; // THE RUN, without the job around it (the job's `fn`, and the tests'). export async function importMediaRun( opts: ImportMediaJobOpts & { target: ImportTarget; onLog: (s: string) => void; signal: AbortSignal }, ): Promise { const { paths, request: req, target, onLog, signal } = opts; const say = (s: string) => onLog(s.endsWith("\n") ? s : `${s}\n`); const channelDir = path.join(paths.channelsDir, req.slug); const videoDir = path.join(channelDir, "data", target.id); let record: ImportMediaSummary["record"] = "existing"; say(`Import ${req.path} into ${req.slug}/${target.id}${req.dryRun ? " (dry run: nothing is written)" : ""}`); if (target.kind === "url") { const cfg = configForVideoUrl(opts.channelConfig, target.url); if (req.dryRun) { record = target.exists ? "would-refresh" : "would-create"; say(`Record: ${target.exists ? "refreshed" : "created"} from ${target.url} by one metadata-only pass (not run in a dry run).`); } else { const held = await heldPlatformRefusal(target.platform, "The metadata fetch", paths); const cooling = held ? 0 : await platformCooldownRemainingMs(target.platform, paths); if ((held || cooling > 0) && target.exists) { say(`Record: not refreshed — ${held ?? `${target.platform} is cooling down`}. The record on disk stands.`); } else if (held || cooling > 0) { throw new Error(held ?? `${target.platform} is in a rate-limit cooldown; import once it lapses`); } else { // THE BELT (review 4 B): an X address is asked of yt-dlp only inside // a job on X's queue — nothing else spaces it, jars it or counts it. if (isXUrl(target.url)) { const outside = xJobContextRefusal( `The metadata fetch of ${target.url}`, `pnpm ops import-media --json '{"slug":"${req.slug}","path":"…","url":"…"}' (it queues an X page on X's queue)`, ); if (outside) throw new Error(outside); } const created = !(await isDir(videoDir)); await mkdir(videoDir, { recursive: true }); try { await refreshVideoMetadata({ paths, slug: req.slug, videoId: target.id, videoUrl: target.url, channelConfig: cfg, cookiePolicy: opts.cookiePolicy, onLog, signal, requestedBy: IMPORT_MEDIA_JOB_KIND, onPlatformBackoff: () => recordDownloadBackoff(target.platform, paths), onPlatformClean: () => recordPlatformClean(target.platform, paths), ...(opts.deps?.refresh ? { run: opts.deps.refresh } : {}), }); record = target.exists ? "refreshed" : "created"; } catch (err) { // A record this run made and could not fill is not left half-made. if (created) { const left = await readdir(videoDir).catch(() => [] as string[]); if (left.every((n) => n === "metadata.history.json" || n.endsWith(".part"))) { await rm(videoDir, { recursive: true, force: true }); } } throw err; } } } } else if (target.kind === "meta") { record = req.dryRun ? "would-create" : "by-hand"; const probed = await (opts.deps?.land?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(paths, f, s)))(req.path, signal); const info = manualRecordInfo({ id: target.id, meta: req.meta!, seconds: probed?.seconds ?? null, fileName: path.basename(req.path), }); say(`Record: written by hand — "${String(info.title)}"${info.upload_date ? `, ${String(info.upload_date)}` : ""}.`); if (!req.dryRun) { await mkdir(videoDir, { recursive: true }); await withMetadataHistory(videoDir, { by: "import-media", requestedBy: IMPORT_MEDIA_JOB_KIND, onLog }, () => writeJsonAtomic(path.join(videoDir, "metadata.info.json"), info, { indent: 0, newline: false }), ); } } let landed: LandMediaResult; try { landed = await landMediaFile({ paths, slug: req.slug, channelConfig: opts.channelConfig, videoId: target.id, sourcePath: req.path, via: "import-media", ...(req.move ? { move: true } : {}), ...(req.replace ? { replace: true } : {}), ...(req.audio === false ? { audio: false } : {}), ...(target.kind === "url" ? { url: target.url } : {}), ...(req.note ? { note: req.note } : {}), ...(req.dryRun ? { dryRun: true } : {}), // A dry run of a record not made yet has no directory to read. ...(req.dryRun && record === "would-create" ? { recordMayBeMissing: true } : {}), onLog, signal, ...(opts.deps?.land ? { deps: opts.deps.land } : {}), }); } catch (err) { // A record this run made for a file that did not land is not left behind: // a data// with metadata is what every enumerator reads as "fetched". if (!req.dryRun && (record === "created" || record === "by-hand")) { const left = await readdir(videoDir).catch(() => [] as string[]); if (left.every((n) => n === "metadata.info.json" || n === "metadata.history.json")) { await rm(videoDir, { recursive: true, force: true }); say(`The record ${target.id} this import made is removed again (nothing landed).`); } } throw err; } if (req.doNotClean) { if (!req.dryRun) { await setDoNotClean(videoDir, true, { by: "import", via: "import-media", ...(opts.jobId ? { jobId: opts.jobId } : {}), ...(req.note ? { note: req.note } : {}), }); } say(`${req.dryRun ? "Would mark" : "Marked"} "Do not clean"${req.note ? `: ${req.note}` : ""}.`); } if (!req.dryRun) await applyPendingKeep(paths, req.slug, target.id, onLog, opts.jobId); let transcribeJob: string | undefined; if (!req.dryRun && landed.audio !== "skipped") { const facts = await (opts.deps?.handoff ?? readHandoffFacts)({ slug: req.slug, channelConfig: opts.channelConfig, videoDir, transcribeJob: req.transcribe === true, }); if (req.transcribe === true && !facts.hasTranscript && opts.requestTranscription) { const r = await opts.requestTranscription(req.slug, target.id); if (r.ok && r.jobId) transcribeJob = r.jobId; else say(`The transcribe-one job was not queued: ${r.error ?? "no job"}`); } for (const l of transcriptionHandoffLines(facts)) say(l); if (transcribeJob) say(`transcribe-one job ${transcribeJob}`); } const summary: ImportMediaSummary = { slug: req.slug, id: target.id, dryRun: req.dryRun === true, record, kept: landed.kept, seconds: landed.newSeconds, ...(landed.existingSeconds !== undefined ? { existingSeconds: landed.existingSeconds } : {}), finalized: landed.finalized, audio: landed.audio, moved: landed.moved, container: landed.container, ...(transcribeJob ? { transcribeJob } : {}), }; say(`${IMPORT_MEDIA_RESULT_MARKER}${JSON.stringify(summary)}`); return summary; } // Every refusal before any job; then the job. export async function runImportMediaJob(opts: ImportMediaJobOpts): Promise { const { paths, request: req } = opts; const st = await stat(req.path).catch(() => null); if (!st) return { ok: false, error: `${req.path} is not there` }; if (!st.isFile()) return { ok: false, error: `${req.path} is not a file` }; try { await assertChannelTextReadable(paths, req.slug, opts.channelConfig); } catch (err) { return { ok: false, error: (err as Error).message }; } const target = await resolveImportTarget(paths, req); if ("error" in target) return { ok: false, error: target.error, ...(target.info ? { info: true } : {}) }; // The record it would land in: never a local recording, a local library // channel's, or one linked to a library original (review fix 5). const localRefusal = await localMediaWriteRefusal(paths, req.slug, opts.channelConfig, target.id); if (localRefusal) return { ok: false, error: localRefusal }; if (target.kind === "url" && !target.exists && !req.dryRun) { const held = await heldPlatformRefusal(target.platform, "The metadata fetch", paths); if (held) return { ok: false, info: true, error: held }; const remainingMs = await platformCooldownRemainingMs(target.platform, paths); if (remainingMs > 0) { return { ok: false, info: true, error: `${target.platform} is in a rate-limit cooldown (${Math.ceil(remainingMs / 1000)}s remaining). Import once it lapses.`, }; } } return runManagedFunction({ kind: IMPORT_MEDIA_JOB_KIND, // An X page's address asks X: X's queue (importMediaJobQueueKey), and the // guards judge it by that address (lib/xJobRule.ts xJobAsksX). queueKey: importMediaJobQueueKey(req.slug, target), ...(target.kind === "url" ? { askParams: { url: target.url } } : {}), paths, channelSlug: req.slug, videoId: target.id, fn: async (onLog, signal, _progress, ctx) => { await importMediaRun({ ...opts, target, onLog, signal, jobId: ctx.jobId }); await opts.afterRun?.(); }, }); }