import { test } from "node:test"; import assert from "node:assert/strict"; import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import { execFileSync } from "node:child_process"; import { tmpdir } from "node:os"; import path from "node:path"; import type { ChannelConfig } from "../lib/channelConfig"; import type { MediaProbe } from "../lib/mediaImport"; import type { AttemptOutcome } from "../ytdlp/runOneYtdlp"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/landMedia.test.ts // // The landing import-media and record-live share (controller/landMedia.ts), the // import job's run, the pending "Do not clean", and the guard that keeps a later // download from clobbering a longer landed recording. A temp corpus; ffprobe, // the remux and the audio extraction are stubs that read a fake "media" file // (`format=;seconds=`), except one case that runs the real ffmpeg. const ROOT = await mkdtemp(path.join(tmpdir(), "land-media-")); const CORPUS = path.join(ROOT, "transcripts"); const OUTSIDE = path.join(ROOT, "outside"); process.env.TRANSCRIPTS_DIR = CORPUS; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await mkdir(CORPUS, { recursive: true }); await mkdir(OUTSIDE, { recursive: true }); await writeFile(process.env.SETTINGS_FILE, "{}"); const { getPaths } = await import("../lib/paths"); const { landMediaFile, transcriptionHandoffLines } = await import("./landMedia"); const { importMediaJobQueueKey, importMediaRun, resolveImportTarget } = await import("./importMedia"); const { mediaImportSidecar } = await import("../lib/mediaImport-server"); const { loadSavedVideo } = await import("../lib/savedVideo-server"); const { isDoNotClean } = await import("../lib/doNotClean-server"); const { addPendingKeep, applyPendingKeep, loadPendingKeep } = await import("../lib/pendingKeep-server"); const { keepVideosByIds } = await import("./keepVideosMatching"); const { prepareLandedGuard, settleLandedGuard } = await import("../ytdlp/landedGuard"); const { planSavedContainer } = await import("../ytdlp/savedAlternates"); const paths = getPaths(); test.after(() => rm(ROOT, { recursive: true, force: true })); const SLUG = "synth-rumble"; const CONFIG = { handling: "transcribe", url: "https://rumble.com/c/Synth", platform: "rumble", name: "Synth" } as ChannelConfig; await mkdir(path.join(CORPUS, "channels", SLUG, "data"), { recursive: true }); await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG)); await mkdir(paths.savedVideosDir, { recursive: true }); // A fake media file: its "probe" is its text. async function fake(name: string, format: string, seconds: number, dir = OUTSIDE): Promise { const f = path.join(dir, name); await writeFile(f, `format=${format};seconds=${seconds};${"x".repeat(64)}`); return f; } async function fakeProbe(file: string): Promise { const text = await readFile(file, "utf8").catch(() => ""); const m = /format=([^;]+);seconds=([\d.]+)/.exec(text); if (!m) return null; return { formatName: m[1]!, seconds: Number(m[2]), videoCodec: "h264", audioCodec: "aac" }; } const remuxed: string[] = []; const deps = { probe: fakeProbe, // The stub "remux": the same bytes, now an mp4. remux: async (src: string, dest: string) => { remuxed.push(src); await writeFile(dest, (await readFile(src, "utf8")).replace(/format=[^;]+/, "format=mov,mp4,m4a")); }, transcode: async (o: { videoDir: string; sourcePath: string; fmt: string }) => { await copyFile(o.sourcePath, path.join(o.videoDir, `audio.${o.fmt}`)); }, freeBytes: async () => 1e15, }; const signal = new AbortController().signal; const log: string[] = []; const onLog = (s: string) => void log.push(s); async function record(id: string, meta: Record = {}): Promise { const dir = path.join(CORPUS, "channels", SLUG, "data", id); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: `embed-${id}`, extractor: "RumbleEmbed", title: id, ...meta })); return dir; } test("a live recording's MPEG-TS lands as an mp4 in the store, with audio, the archive line and provenance", async () => { const dir = await record("v1live"); const src = await fake("v1.from-start.mp4.part", "mpegts", 3600); const r = await landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v1live", sourcePath: src, via: "import-media", move: true, url: "https://rumble.com/v1live-x.html", onLog, signal, deps }); assert.equal(r.kept, "new"); assert.equal(r.finalized, "remuxed"); assert.equal(r.audio, "extracted"); assert.equal(r.moved, true); assert.ok(remuxed.includes(src)); await assert.rejects(stat(src), "the original is gone once the copy verified"); const pointer = await loadSavedVideo(dir); assert.equal(pointer?.file, "source-media.mp4"); assert.equal(pointer?.keepReason, "pin"); assert.equal(pointer?.origin?.requestedBy, "import-media"); assert.ok((await readdir(dir)).includes("audio.mp3")); const prov = await mediaImportSidecar.load(dir); assert.equal(prov?.entries[0]?.source.name, "v1.from-start.mp4.part"); assert.equal(prov?.entries[0]?.kept, "new"); const archive = await readFile(path.join(CORPUS, "channels", SLUG, "archive"), "utf8"); assert.match(archive, /^RumbleEmbed embed-v1live$/m); // No staging left behind. const slugStore = path.join(paths.savedVideosDir, SLUG); assert.deepEqual((await readdir(slugStore)).filter((n) => n.startsWith(".")), []); }); test("keep the longer: a shorter file is not landed, the store and the original stay", async () => { const dir = await record("v2"); const long = await fake("long.mp4", "mov,mp4,m4a", 5000); await landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v2", sourcePath: long, via: "import-media", onLog, signal, deps }); const short = await fake("short.mp4", "mov,mp4,m4a", 4000); const r = await landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v2", sourcePath: short, via: "import-media", move: true, onLog, signal, deps }); assert.equal(r.kept, "existing"); assert.equal(r.existingSeconds, 5000); assert.equal(r.audio, "kept-existing"); await stat(short); // not moved: nothing was landed from it const pointer = await loadSavedVideo(dir); assert.match(await readFile(path.join(pointer!.dir, pointer!.file), "utf8"), /seconds=5000/); // attach-media's provenance: the directory, the entry, the copied bytes' sha256. assert.equal(pointer?.origin?.kind, "local-archive"); assert.equal(pointer?.origin?.entry, "long.mp4"); assert.match(pointer?.sha256 ?? "", /^[0-9a-f]{64}$/); assert.equal(pointer?.origin?.sha256, pointer?.sha256); // replace lands it anyway. const r2 = await landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v2", sourcePath: short, via: "import-media", replace: true, onLog, signal, deps }); assert.equal(r2.kept, "new"); }); test("a dry run writes nothing; an unreadable file and one inside the archive are refused", async () => { const dir = await record("v3"); const src = await fake("v3.ts", "mpegts", 100); const r = await landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v3", sourcePath: src, via: "import-media", move: true, dryRun: true, onLog, signal, deps }); assert.equal(r.dryRun, true); assert.equal(await loadSavedVideo(dir), null); await stat(src); await writeFile(path.join(OUTSIDE, "junk.mp4"), "not media"); await assert.rejects( landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v3", sourcePath: path.join(OUTSIDE, "junk.mp4"), via: "import-media", onLog, signal, deps }), /ffprobe cannot read/, ); const inside = await fake("audio.mp3", "mp3", 10, dir); await assert.rejects( landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v3", sourcePath: inside, via: "import-media", onLog, signal, deps }), /inside the archive/, ); }); test("import: a record by hand for a file with no source page, marked Do not clean; never over a record", async () => { const src = await fake("Old Talk.mkv", "matroska,webm", 900); const req = { slug: SLUG, path: src, meta: { title: "An old talk", date: "2019-05-01" }, doNotClean: true, note: "keep it" }; const target = await resolveImportTarget(paths, req); assert.ok(!("error" in target) && target.kind === "meta" && target.id === "old-talk"); const s = await importMediaRun({ paths, request: req, channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "when-required" }, target: target as never, onLog, signal, deps: { land: deps, handoff: async () => ({ workersPaused: true, laneEnabled: true, laneHeld: false, ruleCoversChannel: true, channelPaused: false, hasTranscript: false, transcribeJob: false }), }, }); assert.equal(s.record, "by-hand"); assert.equal(s.kept, "new"); const dir = path.join(CORPUS, "channels", SLUG, "data", "old-talk"); const info = JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8")); assert.equal(info.title, "An old talk"); assert.equal(info.upload_date, "20190501"); assert.ok(await isDoNotClean(dir)); assert.ok(log.some((l) => /waits behind the pause/.test(l)), "the hand-off says the pause holds it"); const again = await resolveImportTarget(paths, req); assert.match((again as { error: string }).error, /already has a record old-talk/); }); test("import: a record made for a file that does not land is removed again", async () => { const bad = path.join(OUTSIDE, "Broken Thing.mp4"); await writeFile(bad, "not media at all"); const req = { slug: SLUG, path: bad, meta: { title: "Broken" } }; const target = await resolveImportTarget(paths, req); await assert.rejects( importMediaRun({ paths, request: req, channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "when-required" }, target: target as never, onLog, signal, deps: { land: deps } }), /ffprobe cannot read/, ); await assert.rejects(stat(path.join(CORPUS, "channels", SLUG, "data", "broken-thing"))); }); test("import by url: one metadata pass makes the record under the URL id", async () => { const req = { slug: SLUG, path: await fake("rec.mp4.part", "mpegts", 1200), url: "https://rumble.com/v9abcde-a-stream.html" }; const target = await resolveImportTarget(paths, req); assert.ok(!("error" in target) && target.kind === "url" && target.id === "v9abcde" && !target.exists); const calls: string[][] = []; const refresh = async (cwd: string, args: string[]): Promise => { calls.push(args); const dir = path.join(cwd, "data", "v9abcde"); await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "v8embed", extractor: "RumbleEmbed", title: "A stream", live_status: "was_live" })); return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; }; const s = await importMediaRun({ paths, request: req, channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "when-required" }, target: target as never, onLog, signal, deps: { refresh, land: deps, handoff: async () => ({ workersPaused: false, laneEnabled: false, laneHeld: false, ruleCoversChannel: false, channelPaused: false, hasTranscript: false, transcribeJob: false }) }, }); assert.equal(s.record, "created"); assert.equal(calls.length, 1); assert.ok(calls[0]!.includes("--skip-download"), "metadata only"); assert.ok(calls[0]!.includes("--impersonate"), "Rumble's own args"); const archive = await readFile(path.join(CORPUS, "channels", SLUG, "archive"), "utf8"); assert.match(archive, /^RumbleEmbed v8embed$/m); }); test("review 4 B: an import by an X page's address (t.co included) is X's: X's queue on any channel, and never asked of yt-dlp outside an X job", async () => { const urlTarget = (url: string) => ({ kind: "url" as const, id: "1", url, platform: "unknown", exists: false }); for (const url of ["https://t.co/AbC123", "https://x.com/u/status/1", "https://mobile.twitter.com/u/status/1"]) { assert.equal(importMediaJobQueueKey(SLUG, urlTarget(url)), "platform:twitter", url); } assert.equal(importMediaJobQueueKey(SLUG, urlTarget("https://rumble.com/v9abcde-a-stream.html")), `import-media:${SLUG}`); assert.equal(importMediaJobQueueKey(SLUG, { kind: "id", id: "1" }), `import-media:${SLUG}`); // The belt: outside a job on X's queue, no metadata pass is asked of an X address. const calls: string[][] = []; const refresh = async (_cwd: string, args: string[]): Promise => { calls.push(args); return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; }; const req = { slug: SLUG, path: await fake("x.mp4", "mov,mp4,m4a", 30), url: "https://t.co/AbC123" }; await assert.rejects( importMediaRun({ paths, request: req, channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "when-required" }, target: { kind: "url", id: "AbC123", url: req.url, platform: "unknown", exists: false } as never, onLog, signal, deps: { refresh, land: deps }, }), /asks X, and X is asked only by the editor's own jobs/, ); assert.equal(calls.length, 0, "yt-dlp was not asked"); await assert.rejects(stat(path.join(CORPUS, "channels", SLUG, "data", "AbC123")), "no record dir was made"); }); test("the store's root: the corpus default is made when missing; an override or a dangling link is refused", async () => { const { ensureStoreRoot } = await import("./landMedia"); const { symlink } = await import("node:fs/promises"); const base = path.join(ROOT, "roots"); await mkdir(base, { recursive: true }); const def = path.join(base, "saved-videos"); await ensureStoreRoot({ savedVideosDir: def }, def, "x"); assert.ok((await stat(def)).isDirectory()); await assert.rejects(ensureStoreRoot({ savedVideosDir: def }, path.join(base, "elsewhere"), "nothing landed"), /is not there \(is its drive mounted\?\) — nothing landed/); const dangling = path.join(base, "moved-store"); await symlink(path.join(base, "unmounted", "saved-videos"), dangling); await assert.rejects(ensureStoreRoot({ savedVideosDir: dangling }, dangling, "x"), /is not there/); }); test("the hand-off never lifts a pause, and says what takes the video", () => { const base = { workersPaused: false, laneEnabled: true, laneHeld: false, ruleCoversChannel: true, channelPaused: false, hasTranscript: false, transcribeJob: false }; assert.match(transcriptionHandoffLines(base)[0]!, /lane's rules take this channel/); assert.match(transcriptionHandoffLines({ ...base, laneHeld: true })[0]!, /waits behind the pause \(the transcription lane is held\); nothing here lifts it/); assert.match(transcriptionHandoffLines({ ...base, ruleCoversChannel: false })[0]!, /does not take this channel/); assert.match(transcriptionHandoffLines({ ...base, transcribeJob: true, workersPaused: true })[0]!, /transcribe-one job .* workers are paused/); assert.match(transcriptionHandoffLines({ ...base, hasTranscript: true })[0]!, /already on disk/); }); test("pending keep: an id not held is pending, and marked when its record lands", async () => { const r = await keepVideosByIds({ paths, channelSlug: SLUG, ids: ["v1live", "vnotyet"], note: "Huck — keep" }); assert.deepEqual(r.marked, ["v1live"]); assert.deepEqual(r.pending, ["vnotyet"]); assert.deepEqual((await loadPendingKeep(paths, SLUG)).map((e) => e.id), ["vnotyet"]); assert.equal(await applyPendingKeep(paths, SLUG, "vnotyet"), false, "no dir yet: still pending"); const dir = await record("vnotyet"); assert.equal(await applyPendingKeep(paths, SLUG, "vnotyet", onLog), true); assert.ok(await isDoNotClean(dir)); assert.deepEqual(await loadPendingKeep(paths, SLUG), []); const dry = await keepVideosByIds({ paths, channelSlug: SLUG, ids: ["vlater"], dryRun: true }); assert.deepEqual(dry.pending, ["vlater"]); assert.deepEqual(await loadPendingKeep(paths, SLUG), [], "a dry run records nothing"); await addPendingKeep(paths, SLUG, ["vlater"], "n"); assert.equal((await loadPendingKeep(paths, SLUG))[0]?.note, "n"); }); test("a later download shorter than the landed recording does not clobber it; a longer one wins", async () => { const dir = await record("v1live"); // landed in the first test: audio.mp3 of 3600 s const measure = async (f: string) => (await fakeProbe(f))?.seconds ?? null; // Shorter download. const plan = await prepareLandedGuard(dir, onLog); assert.deepEqual(plan?.asides, ["audio.mp3"]); assert.ok((await readdir(dir)).includes("audio.mp3.landed-kept")); await fake("audio.mp3", "mp3", 3000, dir); await settleLandedGuard(plan!, { measure }, onLog); assert.match(await readFile(path.join(dir, "audio.mp3"), "utf8"), /seconds=3600/, "the landed audio stays"); assert.ok(!(await readdir(dir)).includes("audio.mp3.landed-kept")); // Longer download. const plan2 = await prepareLandedGuard(dir, onLog); await fake("audio.mp3", "mp3", 4000, dir); await settleLandedGuard(plan2!, { measure }, onLog); assert.match(await readFile(path.join(dir, "audio.mp3"), "utf8"), /seconds=4000/); // No new audio: the landed one comes back. const plan3 = await prepareLandedGuard(dir, onLog); await settleLandedGuard(plan3!, { measure }, onLog); assert.match(await readFile(path.join(dir, "audio.mp3"), "utf8"), /seconds=4000/); const prov = await mediaImportSidecar.load(dir); assert.deepEqual(prov?.challenges?.map((c) => c.kept), ["landed", "download"]); // The container: a shorter download does not become the active one (it is // kept beside it — ytdlp/savedAlternates.test.ts); an explicit persist does. const newer = await fake("source-media.mp4", "mov,mp4", 100, dir); assert.equal((await planSavedContainer({ videoDir: dir, newContainer: newer, explicit: false, deps: { measure } }))?.active, "existing"); assert.equal((await planSavedContainer({ videoDir: dir, newContainer: newer, explicit: true, deps: { measure } }))?.active, "download"); // A video that was never landed is an ordinary download. assert.equal(await prepareLandedGuard(await record("plain"), onLog), null); }); test("the real ffmpeg: an MPEG-TS remuxed with -c copy into an mp4 of the same length", async (t) => { const ts = path.join(OUTSIDE, "real.ts"); try { execFileSync(paths.ffmpegBin, [ "-v", "error", "-f", "lavfi", "-i", "testsrc=duration=3:size=160x120:rate=10", "-f", "lavfi", "-i", "sine=duration=3", "-c:v", "libx264", "-c:a", "aac", "-f", "mpegts", ts, ]); } catch { t.skip("no ffmpeg with libx264 here"); return; } await record("vreal"); const r = await landMediaFile({ paths: { ...paths, monorepoRoot: ROOT }, slug: SLUG, channelConfig: CONFIG, videoId: "vreal", sourcePath: ts, via: "record-live", move: true, audio: false, onLog, signal, deps: { freeBytes: async () => 1e15 }, }); assert.equal(r.finalized, "remuxed"); assert.ok(r.container?.endsWith("source-media.mp4")); assert.ok(Math.abs((r.newSeconds ?? 0) - 3) < 0.5); const fmt = execFileSync(paths.ffprobeBin, ["-v", "error", "-show_entries", "format=format_name", "-of", "csv=p=0", r.container!]).toString(); assert.match(fmt, /mp4/); });