import { test, type TestContext } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, mkdir, writeFile, readFile, readdir, rm, chmod, symlink } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { scanLocalMedia } from "./localMediaScan"; // Synthetic files only. No getPaths(), live corpus, network, or Docker volumes. // Tiny MP4 placeholders are intentional: discovery must never decode or copy // video bytes. Integration with ffprobe/playback belongs to a later slice. const VTT = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nA test sentence.\n"; const meta = (id: string) => ({ id, title: "Synthetic recording", duration: 3, upload_date: "20261029", webpage_url: `https://www.youtube.com/watch?v=${id}` }); async function fixture(t: TestContext) { const root = await mkdtemp(path.join(tmpdir(), "local-media-scan-")); t.after(() => rm(root, { recursive: true, force: true })); return root; } async function add(root: string, name: string, id = name) { await writeFile(path.join(root, `${name}.mp4`), "synthetic video bytes"); await writeFile(path.join(root, `${name}.info.json`), JSON.stringify(meta(id))); await writeFile(path.join(root, `${name}.vtt`), VTT); } const scan = (root: string, existingDirectoryIds: string[] = []) => scanLocalMedia({ sourceDirectory: root, existingDirectoryIds }); async function contents(root: string) { const result: Record = {}; for (const name of (await readdir(root)).sort()) result[name] = (await readFile(path.join(root, name))).toString("base64"); return result; } test("new, occupied destination, repeated scan, and later addition preserve all source bytes", async (t) => { const root = await fixture(t); await add(root, "first"); const before = await contents(root); assert.deepEqual((await scan(root)).counts, { discovered: 1, new: 1, existing: 0, issues: 0 }); const occupied = await scan(root, ["first"]); assert.deepEqual(occupied.counts, { discovered: 1, new: 0, existing: 1, issues: 0 }); assert.deepEqual(await scan(root, ["first"]), occupied); assert.deepEqual(await contents(root), before); await add(root, "second"); assert.deepEqual((await scan(root, ["first"])).counts, { discovered: 2, new: 1, existing: 1, issues: 0 }); }); test("Unicode, quotes, dollars, and spaces remain exact filenames", async (t) => { const root = await fixture(t); const name = "A 'title' $money ⧸ | (録画)"; await add(root, name, "safe-id"); const result = await scan(root); assert.equal(result.candidates[0].media, `${name}.mp4`); assert.equal(result.candidates[0].status, "new"); }); test("missing or mismatched companions are issues; unrelated playlist JSON is ignored", async (t) => { const root = await fixture(t); await writeFile(path.join(root, "alone.mp4"), "media"); await writeFile(path.join(root, "other.vtt"), VTT); await writeFile(path.join(root, "playlist.info.json"), '{"_type":"playlist"}'); const result = await scan(root); assert.equal(result.counts.discovered, 1); assert.equal(result.candidates[0].issues.length, 2); assert.deepEqual(result.candidates[0].issues, [ "Metadata: matching .info.json file not found. Prepare recording details before import.", "Transcript: matching subtitle file not found. Add an SRT or VTT file, or generate a transcript if available.", ]); assert.ok(!JSON.stringify(result).includes(root)); }); test("invalid JSON and matched playlist metadata are rejected", async (t) => { const root = await fixture(t); await add(root, "broken"); await add(root, "playlist"); await writeFile(path.join(root, "broken.info.json"), "{"); await writeFile(path.join(root, "playlist.info.json"), JSON.stringify({ ...meta("playlist"), _type: "playlist", entries: [] })); const result = await scan(root); assert.equal(result.counts.issues, 2); assert.match(result.candidates[0].issues.join(), /invalid JSON/); assert.match(result.candidates[1].issues.join(), /playlist/); }); test("duplicates invalidate both candidates even when one has a bad transcript", async (t) => { const root = await fixture(t); await add(root, "one", "shared"); await add(root, "two", "shared"); await writeFile(path.join(root, "two.vtt"), "WEBVTT\n"); const result = await scan(root, ["shared"]); assert.equal(result.counts.issues, 2); assert.ok(result.candidates.every((row) => row.issues.includes("Duplicate identity in source scan"))); }); test("header-only and reversed-interval transcripts are rejected", async (t) => { const root = await fixture(t); await add(root, "empty"); await add(root, "reverse"); await writeFile(path.join(root, "empty.vtt"), "WEBVTT\n"); await writeFile(path.join(root, "reverse.vtt"), VTT.replace("00:00:02.000", "00:00:00.000")); assert.equal((await scan(root)).counts.issues, 2); }); test("unsafe record IDs cannot become destinations", async (t) => { const root = await fixture(t); for (const [i, id] of ["..", "../escape", "a/b", "CON", "trailing."].entries()) await add(root, `item${i}`, id); assert.equal((await scan(root)).counts.issues, 5); }); test("native/canonical differences are retained but held for review", async (t) => { const root = await fixture(t); await add(root, "twitch", "v1234"); await writeFile(path.join(root, "twitch.info.json"), JSON.stringify({ ...meta("v1234"), webpage_url: "https://www.twitch.tv/videos/1234" })); const row = (await scan(root)).candidates[0]; assert.equal(row.recordId, "v1234"); assert.equal(row.directoryId, "1234"); assert.equal(row.status, "issue"); }); test("unavailable roots fail instead of reporting zero discoveries", async (t) => { const root = await fixture(t); await assert.rejects(scan(path.join(root, "missing")), { code: "ENOENT" }); await assert.rejects(scan("relative"), /absolute/); }); test("directory named .mp4 is not a media file", async (t) => { const root = await fixture(t); await mkdir(path.join(root, "directory.mp4")); assert.equal((await scan(root)).candidates[0].status, "issue"); }); test("oversized metadata is refused before parsing", async (t) => { const root = await fixture(t); await add(root, "large"); const { open } = await import("node:fs/promises"); const h = await open(path.join(root, "large.info.json"), "w"); try { await h.truncate(32 * 1024 * 1024 + 1); } finally { await h.close(); } assert.match((await scan(root)).candidates[0].issues.join(), /32 MiB/); }); test("source-file symlinks are refused, including escapes", async (t) => { const root = await fixture(t); const outside = await fixture(t); await add(root, "linked"); await writeFile(path.join(outside, "outside.mp4"), "outside"); await rm(path.join(root, "linked.mp4")); try { await symlink(path.join(outside, "outside.mp4"), path.join(root, "linked.mp4")); } catch (e) { if ((e as NodeJS.ErrnoException).code === "EPERM" && process.platform === "win32") { t.skip("Windows symlink privilege unavailable; run in Linux container"); return; } throw e; } assert.match((await scan(root)).candidates[0].issues.join(), /source links/); assert.equal(await readFile(path.join(outside, "outside.mp4"), "utf8"), "outside"); }); test("read-only source files remain readable and unchanged", async (t) => { const root = await fixture(t); await add(root, "readonly"); const before = await contents(root); const files = await readdir(root); try { for (const file of files) await chmod(path.join(root, file), 0o444); assert.equal((await scan(root)).counts.new, 1); assert.deepEqual(await contents(root), before); } finally { for (const file of files) await chmod(path.join(root, file), 0o644); } }); test("short timestamps produce index-compatible cues", async (t) => { const root = await fixture(t); await add(root, "short"); await writeFile(path.join(root, "short.vtt"), "WEBVTT\n\n00:00.250 --> 00:01.910\nShort cue\n"); const row = (await scan(root)).candidates[0]; assert.equal(row.status, "new"); assert.equal(row.cueCount, 1); assert.deepEqual(row.warnings, []); }); test("isolated zero-duration cues warn without changing source; all-point transcripts remain blocked", async (t) => { const root = await fixture(t); await add(root, "mixed"); await add(root, "points"); const point = "00:03.000 --> 00:03.000\nPoint cue\n"; const mixed = VTT + "\n" + point; await writeFile(path.join(root, "mixed.vtt"), mixed); await writeFile(path.join(root, "points.vtt"), "WEBVTT\n\n" + point); const result = await scan(root, ["mixed"]); assert.equal(result.candidates[0].status, "existing"); assert.equal(result.candidates[0].cueCount, 2); assert.match(result.candidates[0].warnings.join(), /1 zero-duration/); assert.equal(result.candidates[1].status, "issue"); assert.match(result.candidates[1].issues.join(), /no positive-duration/); assert.equal(await readFile(path.join(root, "mixed.vtt"), "utf8"), mixed); }); // A name a library reference cannot hold (coerceExternalMediaReference refuses // a control character, \ or :) is an issue in the preview: offered as new, its // import could only fail. No fingerprint of any kind is offered for it. test("a recording whose file name a reference cannot hold is held for review", async (t) => { const root = await fixture(t); for (const name of ["colon:name", "back\\slash", "tab\tname", "line\nbreak"]) await add(root, name, "id-" + name.length); await writeFile(path.join(root, "bare\u0001.mp4"), "synthetic video bytes"); await writeFile(path.join(root, "bare\u0001.vtt"), VTT); const result = await scan(root); assert.equal(result.candidates.length, 5); for (const row of result.candidates) { assert.equal(row.status, "issue", JSON.stringify(row.media)); assert.match(row.issues[0], /^Media: the file name has a control character/); assert.equal(row.fingerprint, undefined); assert.equal(row.preparationFingerprint, undefined); assert.equal(row.transcriptionFingerprint, undefined); } });