commit fcbc356fdfe4656e1202b184fc65e29a75f2bfbc
parent dfc72d0c4dca6fbec6eaf24bda66d776f4e21ebd
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 12:47:36 -0500
Merge main (fc5f479e) into lane/remote-archive
lane/local-media beside this lane. Four conflicts, each kept both ways:
fetchWindows.test (the media-403 tests and the local-media backstop),
channelConfigSchema.test's key count (47: localMedia and this lane's three),
the metadata scan's door (the remote-only refusal, then the local-media one),
and channels/actions.ts's imports. Generated docs regenerate unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
125 files changed, 5562 insertions(+), 93 deletions(-)
diff --git a/CHANNEL.md b/CHANNEL.md
@@ -60,6 +60,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). |
| `wayback` | config | A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture's original URL. Each capture imported (`pnpm ops import-page`, the channel page's **Import a capture**) becomes a page record in the channel's posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org's pace; absent, nothing is imported unasked. Release 37 lane F: a target's `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages". |
| `xSearch` | config | An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X's search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window's span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl's search, resumable, at the older walk's pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped. |
+| `localMedia` | config | Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports. |
#### `downloadFilter`
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -144,6 +144,11 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `attach-media` | attach-media copies each held video's file out of a LOCAL archive into the saved-video store, as its source container (nothing fetched): {"slug", "source"} — an absolute path to a directory, a .zip (read in place) or a .7z. The id is the folder's trailing "(<id>)", else the file's yt-dlp suffix; "items": \[{"id", "path"}\] names exact files (path inside the source), "match" narrows the folders by regex. "createRecords": true writes a record for a video the channel does not hold; "replace": true re-attaches over a saved container. "fillDates": true gives a held record attach-media made (saved-video.json origin "local-archive") that has no upload\_date the date from its folder's description.txt, through the metadata history ("dated" in the log and summary); a record with a date, or one attach-media did not make, is never touched. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous, and dated) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | `pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa\|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait` |
| `import-media` | import-media makes ONE file from outside the archive a normal transcribed item: {"slug", "path"} (absolute) and which record — "url" (the source page: one metadata-only pass makes or refreshes the record, under the id the archive keys it by — Rumble's URL id), "id" (a record already here) or "meta": {"title", "date"?, "duration"?, "description"?} (by hand). ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to mp4 (+faststart), never re-encoded. It lands in the saved-video store only when longer than a container already there ("replace": true lands it anyway), then audio.<fmt>, the archive line and media-import.json. "move": true removes the original once the copy verifies; "audio": false lands the container only; "transcribe": true queues a transcribe-one job (held by any pause; without it the transcription lane takes it by its rules); "doNotClean": true marks it, with "note". "dryRun": true says what it would do and writes nothing. A directory, a .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only). | `pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait`<br>`pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait` |
| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'` |
+| `local-media-configure` | local-media-configure gives a video channel a LOCAL MEDIA LIBRARY: {"slug", "sourceId", "directory"} — a stable lowercase id and an absolute directory on the editor server whose recordings stay where they are (never copied, moved or deleted). Written through the channel config; a channel that already has one is refused, and so is queued or running channel work. Playback is not set. Synchronous. | `pnpm ops local-media-configure --json '{"slug":"demo-local","sourceId":"library-1","directory":"/mnt/recordings"}'` |
+| `local-media-preview` | local-media-preview scans the library and writes nothing: {"slug"} -> {preview: {sourceToken, counts, candidates}}. Each .mp4 directly in the directory (not its subdirectories) with its same-named .info.json and .vtt (or .srt) is "new", "existing" (its record is held) or "issue" (with issues). The sourceToken and a candidate's fingerprint (or preparationFingerprint, when it has no .info.json) are what the other local-media actions take. An unreachable library is an error, never an empty preview. | `pnpm ops local-media-preview --json '{"slug":"demo-local"}'` |
+| `local-media-prepare` | local-media-prepare reviews details for a recording with no .info.json and writes nothing: {"slug", "sourceToken", "media", "sourceFingerprint" (the candidate's preparationFingerprint), "details": {"mode": "inspect" \| "manual", "title", "recordedDate"? (YYYY-MM-DD), "durationSeconds"? (manual)}} -> {review: {metadata, fingerprint}}. "inspect" measures the duration with ffprobe. Import it with local-media-import, the review's fingerprint and "preparation": {"sourceFingerprint", "details"}. | `pnpm ops local-media-prepare --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","sourceFingerprint":"<fp>","details":{"mode":"inspect","title":"A talk"}}'` |
+| `local-media-import` | local-media-import imports library recordings as one job on the channel's queue: {"slug", "sourceToken", "selected": \[{"media", "fingerprint", "preparation"?}\]} from a preview, or {"slug", "allNew": true} for every "new" candidate of a fresh preview (the first 1000 in the scan's order, with "remaining" in the answer and the log when there are more). Each record gets metadata.info.json, transcript.en.vtt and external-media.json; the video stays in the library. Every selection is re-checked first (a changed file is stale; a held record is left unchanged). Drainable between recordings; searchable after the next index build. | `pnpm ops local-media-import --json '{"slug":"demo-local","allNew":true}' --wait` |
+| `local-media-link` | local-media-link links a record the channel already holds to its library original: {"slug", "sourceToken", "media", "fingerprint", "dryRun"?} for an "existing" candidate. Only when the library's .info.json and transcript match the record's byte for byte is external-media.json written ("attached"; "already-linked"; "conflict" keeps a different one). Nothing else changes, and no playback is granted. "dryRun" answers "ready" without writing. | `pnpm ops local-media-link --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","fingerprint":"<fp>","dryRun":true}'` |
| `live-preclip` | live-preclip transcribes and mines a recording WHILE it records: {"slug", "id", "action"?: "start" (default) \| "stop" \| "status" \| "finalize"}, and for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"? (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the umtool project, <id>-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/<id>/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` |
| `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (<id>-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` |
| `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | |
diff --git a/common/bin/compose-site.localMedia.test.ts b/common/bin/compose-site.localMedia.test.ts
@@ -0,0 +1,116 @@
+// Integration (lane/local-media re-review B1): a local recording's transcript
+// is composed only into a PRIVATE-audience site, through the REAL index build
+// and the REAL site compose, over a temp corpus — and stays out of a public
+// site's tree whatever site composed into public/ before it.
+//
+// One channel holding an online record and a local recording, on a public site
+// P and a private site V. public/transcripts/<slug> is ONE directory every site
+// composes into in turn; P must never ship the private tree V left there
+// (compose P, V, P), and V must never ship the shared tree P left (V, P, V).
+//
+// Run with: node_modules/.bin/tsx --test common/bin/compose-site.localMedia.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "compose-local-media-"));
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"),
+ EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"),
+ CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"),
+ SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"),
+ CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+ ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"),
+});
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { buildIndex } = await import("../controller/buildIndex");
+const { main: composeSite } = await import("./compose-site");
+const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata");
+
+const paths = getPaths();
+const CH = "mixed";
+const LOCAL = "local-" + "7".repeat(32);
+const quiet = () => {};
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+};
+
+writeJson(paths.settingsFile, {});
+writeJson(path.join(paths.channelsDir, CH, "config.json"), {
+ handling: "youtube", name: "Mixed", url: "https://www.youtube.com/@mixed/videos",
+ localMedia: { sourceId: "library-1", directory: path.join(ROOT, "library") },
+});
+const vtt = (text: string) => `WEBVTT\n\n00:00:01.000 --> 00:00:03.000\n${text}\n`;
+const online = path.join(paths.channelsDir, CH, "data", "onlinevideo");
+writeJson(path.join(online, "metadata.info.json"), {
+ id: "onlinevideo", title: "Online", upload_date: "20260601", duration: 120,
+ webpage_url: "https://www.youtube.com/watch?v=onlinevideo", extractor_key: "Youtube",
+});
+writeFileSync(path.join(online, "transcript.en.vtt"), vtt("an online cue"));
+const local = path.join(paths.channelsDir, CH, "data", LOCAL);
+writeJson(path.join(local, "metadata.info.json"), prepareManualLocalRecordingMetadata({ id: LOCAL, filename: "talk.mp4", title: "A private talk" }));
+writeFileSync(path.join(local, "transcript.en.vtt"), vtt("a private local cue"));
+const site = (siteId: string, extra: Record<string, unknown> = {}) =>
+ writeJson(path.join(paths.sitesDir, siteId, "site.json"), {
+ siteId, siteTitle: siteId, siteDescription: "fixture", headerTitle: siteId, homeTagline: "",
+ socialLinks: [], groups: [{ id: "default", name: "All channels", selectedByDefault: true }],
+ defaultGroupId: "default", channels: [{ slug: CH, groupId: "default" }],
+ siteUrl: `https://${siteId}.example.test`, archives: false, ...extra,
+ });
+site("pub");
+site("priv", { audience: "private" });
+await buildIndex({ paths, onLog: quiet });
+
+// Every file under public/transcripts/<CH>, read whole: a local id or its cue
+// anywhere in it (a page, the manifest's slugToPage) is a leak.
+function transcriptTree(): string {
+ const dir = path.join(paths.exportTranscriptsDir, CH);
+ return readdirSync(dir).map((f) => readFileSync(path.join(dir, f), "utf8")).join("\n");
+}
+async function compose(siteId: string): Promise<string> {
+ const log = console.log;
+ console.log = quiet;
+ try {
+ await composeSite({ siteId, paths });
+ } finally {
+ console.log = log;
+ }
+ return transcriptTree();
+}
+const assertPublic = (tree: string, when: string) => {
+ assert.doesNotMatch(tree, new RegExp(LOCAL), `${when}: no local id in the public site's tree`);
+ assert.doesNotMatch(tree, /a private local cue/, `${when}: no local cue`);
+ assert.match(tree, /an online cue/, `${when}: the online record is there`);
+};
+const assertPrivate = (tree: string, when: string) => {
+ assert.match(tree, new RegExp(LOCAL), `${when}: the private site carries the local recording`);
+ assert.match(tree, /a private local cue/, `${when}: and its cue`);
+ assert.match(tree, /an online cue/, `${when}: and the online record`);
+};
+
+test("compose P, V, P: the public site never ships the private tree the private site left", async () => {
+ assertPublic(await compose("pub"), "P first");
+ assertPrivate(await compose("priv"), "then V");
+ assertPublic(await compose("pub"), "P again, shared tree unchanged");
+ assertPublic(await compose("pub"), "P a third time, its own compose last");
+});
+
+test("compose V, P, V: the private site never ships the shared tree the public site left", async () => {
+ assertPrivate(await compose("priv"), "V first");
+ assertPublic(await compose("pub"), "then P");
+ assertPrivate(await compose("priv"), "V again, private tree unchanged");
+});
diff --git a/common/bin/compose-site.ts b/common/bin/compose-site.ts
@@ -21,10 +21,12 @@
// reports, site.json (no channels) and corpus.json (`site.scope: "cited"`) —
// see composeCitedSite.
+import { writeJsonAtomic } from "../lib/jsonFile-server";
+import { isLocalRecord } from "../lib/localMedia";
import path from "node:path";
import { cp, link, mkdir, rm, readdir, access, readFile, writeFile, stat, rename } from "node:fs/promises";
import type { Dirent } from "node:fs";
-import { getPaths, type Paths } from "../lib/paths";
+import { getPaths, sharedPrivateTranscriptsDir, type Paths } from "../lib/paths";
import { dirSignature } from "../lib/dirSignature";
import { getSite, resolveSocialLinks, resolveHubUrl, type Site } from "../lib/site";
import { getSettings } from "../lib/settings";
@@ -770,6 +772,33 @@ async function writeComposeCache(p: string, cache: ComposeCache): Promise<void>
// under a constant signature and the contract stays unconditional.
export const MANIFEST_ONLY_SIGNATURE = "manifest-only";
+// A ledger entry for a destination being copied right now (reconcileChannelTree).
+const COPY_IN_PROGRESS = "copy in progress";
+
+// The ledger of what each public/<tree>/<slug> was last copied from: beside the
+// index, never in public/ (it names staging paths).
+export function composeTreesLedgerPath(paths: Pick<Paths, "exportIndexDir">): string {
+ return path.join(paths.exportIndexDir, "compose-trees.json");
+}
+
+// WHICH TRANSCRIPT TREE A SITE COPIES (lane/local-media slice 1 ruling). The
+// shared tree leaves local recordings out; a channel that holds one also has a
+// full tree under sharedPrivateTranscriptsDir. A PRIVATE-audience site copies
+// that one where it exists; every other site, and every channel without one,
+// copies the shared tree. Fail-closed: a public site never reads the private root.
+export function transcriptsSourceFor(
+ paths: Pick<Paths, "exportSharedDir" | "exportSharedTranscriptsDir">,
+ privateSite: boolean,
+): (slug: string) => Promise<string> {
+ return async (slug) => {
+ if (privateSite) {
+ const full = path.join(sharedPrivateTranscriptsDir(paths), slug);
+ if (await exists(full)) return full;
+ }
+ return path.join(paths.exportSharedTranscriptsDir, slug);
+ };
+}
+
export async function reconcileChannelTree(
kind: string,
srcRoot: string,
@@ -777,16 +806,42 @@ export async function reconcileChannelTree(
memberSlugs: string[],
prev: Record<string, string>,
log: (m: string) => void,
+ opts: {
+ // Where one member's tree comes from, when not `srcRoot/<slug>`: the
+ // transcripts of a private-audience site (transcriptsSourceFor).
+ srcFor?: (slug: string) => Promise<string>;
+ // WHAT EACH DESTINATION HOLDS (lane/local-media re-review B1). public/<tree>
+ // is ONE directory every site composes into in turn, while `prev` is THIS
+ // site's cache: once two sites copy a channel from different sources (the
+ // shared tree, a private site's full tree), `prev` cannot say what another
+ // site left there — a public site would trust, and ship, the private tree.
+ // The ledger records, per destination, the source dir and signature it was
+ // last copied from (outside public/, never published); a destination is
+ // trusted only when that record matches this compose's source. A copy in
+ // progress is recorded as such first, so a cut-short copy is never trusted.
+ // A destination with no record was copied before the ledger existed, from
+ // the shared tree (no other source existed): `prev` decides, and only when
+ // this compose's source is the shared tree too.
+ ledgerFile?: string;
+ } = {},
): Promise<Record<string, string>> {
+ const { srcFor, ledgerFile } = opts;
// A linked tree (a worktree's public/<tree> → the primary's) becomes this
// checkout's own before anything is copied into or pruned from it.
await ownDir(destRoot);
+ const ledger: Record<string, string> | null = ledgerFile
+ ? await readFile(ledgerFile, "utf8").then((raw) => JSON.parse(raw) as Record<string, string>, () => ({}))
+ : null;
+ const persistLedger = async () => {
+ if (ledgerFile && ledger) await writeJsonAtomic(ledgerFile, ledger);
+ };
const next: Record<string, string> = {};
const memberSet = new Set(memberSlugs);
let copied = 0;
let skipped = 0;
for (const slug of memberSlugs) {
- const src = path.join(srcRoot, slug);
+ const sharedSrc = path.join(srcRoot, slug);
+ const src = srcFor ? await srcFor(slug) : sharedSrc;
const dest = path.join(destRoot, slug);
// Exclude the per-channel manifest.json — its `generatedAt` churns every
// mutation build; the page files capture real content changes.
@@ -797,15 +852,27 @@ export async function reconcileChannelTree(
if (sig === "") {
// No source for this member — ensure no stale dest survives.
await rm(dest, { recursive: true, force: true });
+ if (ledger) delete ledger[dest];
continue;
}
- if (prev[slug] === sig && (await exists(dest))) {
+ const copiedFrom = `${src}\0${sig}`;
+ const trusted =
+ (await exists(dest)) &&
+ (ledger && dest in ledger
+ ? ledger[dest] === copiedFrom
+ : prev[slug] === sig && src === sharedSrc);
+ if (trusted) {
next[slug] = sig;
skipped++;
continue;
}
+ if (ledger) {
+ ledger[dest] = COPY_IN_PROGRESS;
+ await persistLedger();
+ }
await rm(dest, { recursive: true, force: true });
await cp(src, dest, { recursive: true });
+ if (ledger) ledger[dest] = copiedFrom;
next[slug] = sig;
copied++;
}
@@ -820,8 +887,10 @@ export async function reconcileChannelTree(
for (const e of entries) {
if (e.isDirectory() && !memberSet.has(e.name)) {
await rm(path.join(destRoot, e.name), { recursive: true, force: true });
+ if (ledger) delete ledger[path.join(destRoot, e.name)];
}
}
+ await persistLedger();
log(`[compose] ${kind}: ${copied} copied, ${skipped} unchanged.`);
return next;
}
@@ -886,9 +955,12 @@ export async function main(
// last (it is written below, every compose); another name, or none, and the
// site's own stages (summaries, stats, duplicates) are composed afresh.
//
- // The per-channel tree signatures stay trusted: those trees are copies of
- // the SHARED trees, the same bytes whichever site copied them, and a
- // channel another site pruned is re-copied because its directory is gone.
+ // The per-channel trees are trusted by what each destination was last
+ // copied FROM (reconcileChannelTree's ledger), not by this site's cache: a
+ // private-audience site copies a channel's FULL transcript tree where a
+ // public one copies the shared tree (transcriptsSourceFor), so the same
+ // destination can hold either; a channel another site pruned is re-copied
+ // because its directory is gone.
const cachePath = composeCachePath(paths, siteId);
const lastComposed = builtSiteIdIn(paths.exportPublicDir);
const cached = await readComposeCache(cachePath);
@@ -955,6 +1027,7 @@ export async function main(
memberSlugs,
cache.transcripts,
console.log,
+ { srcFor: transcriptsSourceFor(paths, isPrivateSite(site)), ledgerFile: composeTreesLedgerPath(paths) },
);
cache.subs = await reconcileChannelTree(
"subs",
@@ -963,6 +1036,7 @@ export async function main(
memberSlugs,
cache.subs,
console.log,
+ { ledgerFile: composeTreesLedgerPath(paths) },
);
// The social-post corpus: same shared-tree shape, same incremental reconcile.
// Only social member channels have a source dir; reconcileChannelTree treats a
@@ -983,6 +1057,7 @@ export async function main(
postsListed ? memberSlugs.filter((slug) => postsListed.has(slug)) : memberSlugs,
cache.posts ?? {},
console.log,
+ { ledgerFile: composeTreesLedgerPath(paths) },
);
// The AI-digest corpus: same shared-tree shape again. Sparse — only channels
// with at least one digest have a source dir, and reconcileChannelTree treats
@@ -994,6 +1069,7 @@ export async function main(
memberSlugs,
cache.digests ?? {},
console.log,
+ { ledgerFile: composeTreesLedgerPath(paths) },
);
// Subs also carries a per-site manifest.json (tiny — copied every build).
const subsManifestSrc = path.join(
@@ -1212,7 +1288,9 @@ export async function main(
}
const clusters = report.clusters
.filter((c) => clusterIsPublishable(c, dupOverrides))
- .map((c) => filterClusterToChannels(c, memberSet))
+ .map((c) => filterClusterToChannels(c, memberSet,
+ // A local recording only in a private-audience site's duplicates.
+ isPrivateSite(site) ? undefined : (r) => !isLocalRecord(r)))
.filter((c): c is NonNullable<typeof c> => c !== null);
if (clusters.length > 0) {
const filtered: DuplicateReport = {
diff --git a/common/components/SearchSessionContext.tsx b/common/components/SearchSessionContext.tsx
@@ -835,6 +835,8 @@ function useSearchSessionState() {
const passesFilter = useMemo(() => {
return (t: Summary) => {
if (committedChannels.has(channelKeyOf(t))) return false;
+ // Undated is outside any bounded range (lib/search/evalTree.ts).
+ if ((committedDateFrom || committedDateTo) && !t.uploadDate) return false;
if (committedDateFrom && t.uploadDate < committedDateFrom) return false;
if (committedDateTo && t.uploadDate > committedDateTo) return false;
if (t.isLivestream ? committedNol : committedNov) return false;
diff --git a/common/controller/adoptLocalMediaReference.test.ts b/common/controller/adoptLocalMediaReference.test.ts
@@ -0,0 +1,107 @@
+import test, {type TestContext} from "node:test";
+import assert from "node:assert/strict";
+import {mkdtemp,mkdir,writeFile,readFile,readdir,readlink,rm,symlink,link} from "node:fs/promises";
+import path from "node:path";
+import os from "node:os";
+import type {Paths} from "../lib/paths";
+import {previewLocalMedia} from "./localMediaImport";
+import {adoptLocalMediaReference} from "./adoptLocalMediaReference";
+async function fixture(t:TestContext) {
+ const root=await mkdtemp(path.join(os.tmpdir(),"adopt-local-"));t.after(()=>rm(root,{recursive:true,force:true}));
+ const paths={channelsDir:path.join(root,"channels")} as Paths;
+ const channel=path.join(paths.channelsDir,"sample"),record=path.join(channel,"data","video-1"),source=path.join(root,"source");
+ await mkdir(record,{recursive:true});await mkdir(source);
+ const config={handling:"youtube",platform:"youtube",localMedia:{sourceId:"library-1",directory:source}};
+ await writeFile(path.join(channel,"config.json"),JSON.stringify(config));
+ const metadata=JSON.stringify({id:"video-1",title:"Original",duration:3,upload_date:"20261031",webpage_url:"https://www.youtube.com/watch?v=video-1"});
+ const transcript="WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nOriginal cue\n";
+ const media="雪 % '$ recording.mp4",stem=media.slice(0,-4);
+ await writeFile(path.join(source,media),"original bytes");
+ await writeFile(path.join(source,stem+".info.json"),metadata);await writeFile(path.join(source,stem+".vtt"),transcript);
+ await writeFile(path.join(record,"metadata.info.json"),metadata);await writeFile(path.join(record,"transcript.en.vtt"),transcript);
+ await symlink(path.join(source,media),path.join(record,"local-preview.mp4"));
+ const p=await previewLocalMedia(paths,"sample");assert.equal(p.candidates[0].status,"existing");
+ const selection={sourceToken:p.sourceToken,media,fingerprint:p.candidates[0].fingerprint!};
+ const ref=path.join(record,"external-media.json");
+ return {root,paths,channel,record,source,metadata,transcript,media,stem,selection,ref,config};
+}
+test("preview writes nothing; attach adds only a reference, preserving all original files and prototype link",async t=>{
+ const f=await fixture(t);const before=(await readdir(f.record)).sort();
+ assert.equal((await adoptLocalMediaReference(f.paths,"sample",f.selection)).status,"ready");
+ assert.deepEqual((await readdir(f.record)).sort(),before);
+ assert.equal((await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true})).status,"attached");
+ assert.equal(await readFile(path.join(f.source,f.media),"utf8"),"original bytes");
+ assert.equal(await readFile(path.join(f.record,"metadata.info.json"),"utf8"),f.metadata);
+ assert.equal(await readFile(path.join(f.record,"transcript.en.vtt"),"utf8"),f.transcript);
+ assert.equal(await readlink(path.join(f.record,"local-preview.mp4")),path.join(f.source,f.media));
+ assert.deepEqual(JSON.parse(await readFile(f.ref,"utf8")),{version:1,kind:"external",sourceId:"library-1",relativePath:f.media});
+ assert.deepEqual((await readdir(f.record)).sort(),[...before,"external-media.json"].sort());
+});
+test("repeat application is already-linked without changing reference bytes",async t=>{
+ const f=await fixture(t);await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true});const before=await readFile(f.ref,"utf8");
+ assert.equal((await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true})).status,"already-linked");assert.equal(await readFile(f.ref,"utf8"),before);
+});
+for(const name of ["metadata.info.json","transcript.en.vtt"]) test(`refuse mismatched ${name}`,async t=>{
+ const f=await fixture(t);await writeFile(path.join(f.record,name),"different");
+ await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true}),/differs/);
+ await assert.rejects(readFile(f.ref));
+});
+test("corrupt or conflicting reference is preserved, never repaired automatically",async t=>{
+ const f=await fixture(t);for(const content of ["bad-json",JSON.stringify({version:1,kind:"external",sourceId:"other",relativePath:f.media})]) {
+ await writeFile(f.ref,content);assert.equal((await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true})).status,"conflict");assert.equal(await readFile(f.ref,"utf8"),content);
+ }
+});
+test("concurrent adoption publishes one complete reference",async t=>{
+ const f=await fixture(t);const results=await Promise.all([1,2].map(()=>adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true})));
+ assert.equal(results.filter(r=>r.status==="attached").length,1,JSON.stringify(results));assert.equal(results.filter(r=>r.status==="already-linked").length,1,JSON.stringify(results));
+ assert.equal(JSON.parse(await readFile(f.ref,"utf8")).relativePath,f.media);
+});
+test("source change since preview refuses attachment",async t=>{
+ const f=await fixture(t);await writeFile(path.join(f.source,f.stem+".vtt"),f.transcript+"\n00:00:02.000 --> 00:00:03.000\nNew\n");
+ await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true}));await assert.rejects(readFile(f.ref));
+});
+test("late metadata change prevents publication and cleans staging only",async t=>{
+ const f=await fixture(t);
+ await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true},{beforePublish:()=>writeFile(path.join(f.record,"metadata.info.json"),"competing edit")}));
+ assert.equal(await readFile(path.join(f.record,"metadata.info.json"),"utf8"),"competing edit");await assert.rejects(readFile(f.ref));
+ assert.equal((await readdir(f.channel)).some(n=>n.startsWith(".local-media-reference-")),false);
+});
+test("competing reference publication survives without overwrite",async t=>{
+ const f=await fixture(t);const r=await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true},{beforePublish:()=>writeFile(f.ref,"competing reference")});
+ assert.equal(r.status,"conflict");assert.equal(await readFile(f.ref,"utf8"),"competing reference");
+});
+test("cancellation before work or just before publication creates no reference",async t=>{
+ const f=await fixture(t);const c=new AbortController();c.abort();
+ await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true,signal:c.signal}));
+ const later=new AbortController();await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true,signal:later.signal},{beforePublish:async()=>later.abort()}));
+ await assert.rejects(readFile(f.ref));
+});
+test("configuration change during verification refuses publication",async t=>{
+ const f=await fixture(t);await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true},{beforePublish:()=>writeFile(path.join(f.channel,"config.json"),JSON.stringify({...f.config,localMedia:{...f.config.localMedia,sourceId:"changed"}}))}));
+ await assert.rejects(readFile(f.ref));
+});
+test("linked archive transcript is refused",async t=>{
+ const f=await fixture(t);await rm(path.join(f.record,"transcript.en.vtt"));await symlink(path.join(f.source,f.stem+".vtt"),path.join(f.record,"transcript.en.vtt"));
+ await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true}));await assert.rejects(readFile(f.ref));
+});
+
+test("reference read retries when hard-link cleanup changes inode metadata",async t=>{
+ const f=await fixture(t);await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true});
+ const extra=path.join(f.root,"staging-link.json");await link(f.ref,extra);
+ let hookRan=false;
+ const result=await adoptLocalMediaReference(f.paths,"sample",f.selection,{}, {
+ afterReferenceRead:async()=>{
+ hookRan=true;
+ await new Promise(r=>setTimeout(r,5));
+ await rm(extra); // Same publication cleanup race, forced during the read.
+ },
+ });
+ assert.equal(hookRan,true);assert.equal(result.status,"already-linked");
+});
+test("retry reads changed reference content instead of accepting stale bytes",async t=>{
+ const f=await fixture(t);await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true});
+ const result=await adoptLocalMediaReference(f.paths,"sample",f.selection,{}, {
+ afterReferenceRead:async()=>writeFile(f.ref,"conflicting writer"),
+ });
+ assert.equal(result.status,"conflict");assert.equal(await readFile(f.ref,"utf8"),"conflicting writer");
+});
+\ No newline at end of file
diff --git a/common/controller/adoptLocalMediaReference.ts b/common/controller/adoptLocalMediaReference.ts
@@ -0,0 +1,119 @@
+import { localTranscriptVtt, localTranscriptFingerprint } from "../lib/localMediaTranscript";
+import path from "node:path";
+import { constants } from "node:fs";
+import { lstat, open, realpath, mkdtemp, link, rm } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { previewLocalMedia } from "./localMediaImport";
+import { readChannelConfig } from "./channels";
+import { channelWriters } from "./channelWriters";
+import { onDrive } from "../lib/storageHealth";
+import { openExternalMedia } from "../lib/externalMediaResolver-server";
+import { localMediaFingerprint } from "../lib/localMediaScan";
+import { EXTERNAL_MEDIA_FILENAME, coerceExternalMediaReference } from "../lib/localMedia";
+import { writeExternalMediaReference } from "../lib/externalMedia-server";
+
+type Selection = { sourceToken: string; media: string; fingerprint: string };
+export type LocalMediaAdoptionResult = { status: "ready" | "attached" | "already-linked" | "conflict"; stagingCleanupFailed?: boolean };
+
+// Exact bounded bytes, not decoded-text equality: distinct malformed UTF-8
+// sequences must not compare equal merely because decoding replaced them.
+async function bytes(root: string, name: string, afterRead?: () => Promise<void>) {
+ if (!name || name === "." || name === ".." || /[\\/]/.test(name)) throw new Error("Invalid companion name");
+ const file=path.join(root,name), before=await lstat(file);
+ if (!before.isFile() || before.isSymbolicLink() || before.size>32*1024*1024) throw new Error("Expected bounded regular companion file");
+ const h=await open(file,constants.O_RDONLY | (constants.O_NOFOLLOW??0) | (constants.O_NONBLOCK??0));
+ try {
+ const s=await h.stat();
+ if (!s.isFile() || s.dev!==before.dev || s.ino!==before.ino || s.size!==before.size) throw new Error("Companion changed");
+ const buffer=Buffer.alloc(s.size+1); let n=0;
+ while(n<buffer.length) { const r=await h.read(buffer,n,buffer.length-n,n); if(!r.bytesRead) break; n+=r.bytesRead; }
+ await afterRead?.();
+ const after=await h.stat();
+ if(n!==s.size || after.size!==s.size || after.mtimeMs!==s.mtimeMs || after.ctimeMs!==s.ctimeMs) throw new Error("Companion changed");
+ return buffer.subarray(0,n);
+ } finally { await h.close(); }
+}
+
+// Separate from import: occupied records are NEVER silently merged by scanning.
+// This explicit operation requires exact existing metadata/transcript matches.
+// It publishes only a new sidecar and never changes/removes prototype links.
+export async function adoptLocalMediaReference(paths: Paths, slug: string,
+ selection: Selection, options: { apply?: boolean; signal?: AbortSignal } = {},
+ testHooks: { beforePublish?: () => Promise<void>; afterReferenceRead?: () => Promise<void> } = {}): Promise<LocalMediaAdoptionResult> {
+ if (!selection || typeof selection.sourceToken!=="string" || typeof selection.media!=="string" || typeof selection.fingerprint!=="string") throw new Error("Invalid selection");
+ async function verify() {
+ options.signal?.throwIfAborted();
+ if(channelWriters(slug,{includeQueued:true}).length) throw new Error("Finish channel work before attaching a reference");
+ const preview=await previewLocalMedia(paths,slug);
+ if(preview.sourceToken!==selection.sourceToken) throw new Error("Library configuration changed; preview again");
+ const row=preview.candidates.find(r=>r.media===selection.media);
+ if(!row || row.status!=="existing" || !row.directoryId || row.fingerprint!==selection.fingerprint) throw new Error("Existing selection changed or is not eligible");
+ const config=(await readChannelConfig(paths,slug))?.localMedia;
+ if(!config) throw new Error("Library unavailable");
+ const reference={version:1 as const,kind:"external" as const,sourceId:config.sourceId,relativePath:row.media};
+ // The closure has no writes and always closes its media handle, even if the
+ // storage watchdog times out before it settles. A late read cannot publish.
+ const source=await onDrive(config.directory,async()=>{
+ const root=await realpath(config.directory);
+ const media=await openExternalMedia({config,reference,purpose:"inspect"});
+ if(media.status!=="ready") throw new Error("Source unavailable");
+ try {
+ const first=await media.handle.stat();
+ const metadata=await bytes(root,row.metadata), transcript=await bytes(root,row.transcript);
+ const last=await media.handle.stat();
+ const fp=localMediaFingerprint(row.media,metadata.toString("utf8"),localTranscriptFingerprint(row.transcript,transcript.toString("utf8")),last);
+ if(fp!==selection.fingerprint || first.size!==last.size || first.mtimeMs!==last.mtimeMs || first.ctimeMs!==last.ctimeMs) throw new Error("Source changed; preview again");
+ return {metadata,transcript: /\.srt$/i.test(row.transcript) ? Buffer.from(localTranscriptVtt(row.transcript,transcript.toString("utf8")), "utf8") : transcript};
+ } finally { await media.handle.close(); }
+ });
+ const channel=path.join(paths.channelsDir,slug), data=path.join(channel,"data"), record=path.join(data,row.directoryId);
+ for(const dir of [channel,data,record]) { const s=await lstat(dir); if(!s.isDirectory() || s.isSymbolicLink()) throw new Error("Expected real archive directories"); }
+ const metadata=await bytes(record,"metadata.info.json"), transcript=await bytes(record,"transcript.en.vtt");
+ if(!metadata.equals(source.metadata) || !transcript.equals(source.transcript)) throw new Error("Existing metadata or transcript differs; manual review required");
+ // Repeat the configuration/relocation guards after the source reads too.
+ const after=await previewLocalMedia(paths,slug);
+ const match=after.candidates.find(r=>r.media===selection.media);
+ if(after.sourceToken!==selection.sourceToken || match?.status!=="existing" || match.fingerprint!==selection.fingerprint) throw new Error("Library changed during verification");
+ options.signal?.throwIfAborted();
+ return {channel,record,reference};
+ }
+ const checked=await verify();
+ async function existing():Promise<LocalMediaAdoptionResult | null> {
+ try { await lstat(path.join(checked.record,EXTERNAL_MEDIA_FILENAME)); }
+ catch(e) { if((e as NodeJS.ErrnoException).code==="ENOENT") return null; throw e; }
+ // Removing the winner's staging hard link updates the published inode's
+ // ctime too. A concurrent reader correctly rejects that unstable snapshot,
+ // but it must retry a bounded number of times before declaring a conflict.
+ // Keep all identity/size/mtime/ctime checks; never accept bytes from a read
+ // that changed, and never overwrite a reference even if all retries fail.
+ for (let attempt=0; attempt<3; attempt++) {
+ try {
+ const content=await bytes(checked.record,EXTERNAL_MEDIA_FILENAME,
+ attempt===0 ? testHooks.afterReferenceRead : undefined);
+ const stored=coerceExternalMediaReference(JSON.parse(content.toString("utf8")));
+ return {status:JSON.stringify(stored)===JSON.stringify(checked.reference)?"already-linked":"conflict"};
+ } catch { /* A fresh read may succeed once the competing publisher settles. */ }
+ }
+ return {status:"conflict"};
+ }
+ const found=await existing(); if(found) return found;
+ if(options.apply!==true) return {status:"ready"};
+ const stage=await mkdtemp(path.join(checked.channel,".local-media-reference-"));
+ let result:LocalMediaAdoptionResult={status:"conflict"};
+ try {
+ // Use the declared sidecar writer in our private staging directory, then a
+ // hard link publishes complete JSON without replacing any existing target.
+ // These are corpus-only hard links; never hard-link an original MP4.
+ await writeExternalMediaReference(stage,checked.reference);
+ await testHooks.beforePublish?.();
+ await verify();
+ options.signal?.throwIfAborted();
+ if(channelWriters(slug,{includeQueued:true}).length) throw new Error("Channel work started; retry later");
+ try { await link(path.join(stage,EXTERNAL_MEDIA_FILENAME),path.join(checked.record,EXTERNAL_MEDIA_FILENAME)); result={status:"attached"}; }
+ catch(e) { if((e as NodeJS.ErrnoException).code!=="EEXIST") throw e; result=(await existing())??{status:"conflict"}; }
+ return result;
+ } finally {
+ try { await rm(stage,{recursive:true,force:true}); }
+ catch { result.stagingCleanupFailed=true; }
+ }
+}
diff --git a/common/controller/archiveTranscripts.ts b/common/controller/archiveTranscripts.ts
@@ -19,6 +19,7 @@
// prettyPrint is overridden, staging rewrites each cues file instead of
// hard-linking it (slower, but bounded).
+import { LOCAL_RECORDING_ID_RE } from "../lib/localMedia";
import path from "node:path";
import {
access,
@@ -164,6 +165,14 @@ async function stageChannel(
} catch {
videoIds = [];
}
+ // A local recording (its dir is its `local-<32 hex>` id) is in no archive zip
+ // in lane/local-media slice 1: the zip is a published download, and the cache
+ // is one per channel across every site, public and private.
+ const localIds = videoIds.filter((id) => LOCAL_RECORDING_ID_RE.test(id));
+ if (localIds.length > 0) {
+ videoIds = videoIds.filter((id) => !LOCAL_RECORDING_ID_RE.test(id));
+ log(`Archive ${ch.slug}: ${localIds.length} local recording(s) left out of the zip`);
+ }
log(`Archive ${ch.slug}: scanning ${videoIds.length} videos`);
diff --git a/common/controller/attachMedia.ts b/common/controller/attachMedia.ts
@@ -53,7 +53,8 @@
// in flight and removes its staging file.
import path from "node:path";
-import { appendFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
+import { appendFile, lstat, mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
+import { EXTERNAL_MEDIA_FILENAME } from "../lib/localMedia";
import { createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import { Transform, type TransformCallback } from "node:stream";
@@ -441,12 +442,18 @@ export async function attachMedia(opts: AttachMediaOptions): Promise<AttachMedia
pointers.set(id, p);
}
}
+ // Held records linked to a local media library original: never attached.
+ const localMedia = new Set<string>();
+ for (const id of held) {
+ if (await lstat(path.join(dataDir, id, EXTERNAL_MEDIA_FILENAME)).then(() => true, () => false)) localMedia.add(id);
+ }
const folders = groupArchiveFolders(source.files);
const plan = planAttach({
folders,
held,
attached,
+ localMedia,
...(opts.createRecords ? { createRecords: true } : {}),
...(opts.replace ? { replace: true } : {}),
...(match ? { match } : {}),
diff --git a/common/controller/browserLookupJob.ts b/common/controller/browserLookupJob.ts
@@ -21,6 +21,7 @@
// The job's log ends with `summary: {json}` — the per-video statuses and the
// listing's counts — for the UI to read back into sentences.
+import { localMediaMetadataRefusal } from "../lib/localMedia";
import path from "node:path";
import { assertChannelTextReadable } from "../lib/channelMedia";
import type { ChannelConfig } from "../lib/channelConfig";
@@ -77,6 +78,11 @@ export async function runBrowserLookupJob(opts: BrowserLookupJobOpts): Promise<S
}
const bad = ids.filter((id) => !isVideoIdSegment(id));
if (bad.length) return { ok: false, error: `Not a video id: ${bad.join(", ")}.` };
+ // A local media library channel or a local recording (review fix 5).
+ for (const id of [undefined, ...ids]) {
+ const localRefusal = localMediaMetadataRefusal(slug, channelConfig, id);
+ if (localRefusal) return { ok: false, error: localRefusal };
+ }
if (opts.listing) {
const refusal = browserListingRefusal(channelConfig);
if (refusal) return { ok: false, error: refusal };
diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts
@@ -93,6 +93,7 @@ import {
siteSummariesDir,
siteSubsDir,
} from "../lib/site";
+import { isPrivateSite } from "../lib/siteSchema";
import {
type ChannelConfig,
type ChannelHandling,
@@ -107,7 +108,7 @@ import {
heldReason,
} from "../lib/channelMediaHold";
import { resolveChannelGroupId } from "../lib/channelGroups";
-import type { Paths } from "../lib/paths";
+import { sharedPrivateTranscriptsDir, type Paths } from "../lib/paths";
import {
CAPTION_TRACK_RULE_VERSION,
captionInputs,
@@ -175,6 +176,8 @@ import {
import { tagsForSite } from "../lib/curatedTags";
import { compileRecordedDateRule, deriveRecordedDate } from "../lib/recordedDate";
import { loadTranscribeOutcome } from "../lib/transcribeOutcome-server";
+import { localRecordingProblem } from "../lib/localRecordingMetadata";
+import { isLocalRecord } from "../lib/localMedia";
// v10: multi-site build. Shared per-channel transcript/subs pages are written
// once; per-site summaries + subs manifests are filtered selections. Bumped to
@@ -1108,18 +1111,34 @@ export async function buildIndex({
}
}
}
- if (!summary.uploadDate) {
+ if (!summary.uploadDate && summary.platform !== "local") {
log(`Skipping ${s.channelSlug}/${s.videoDir}: no upload_date`);
return;
}
+ // A local recording enters only when its marker validates — read
+ // from the metadata itself, since a fresh normalized summary does not
+ // carry it (lib/transcripts-server.ts, platformFromMetadata).
+ if (summary.platform === "local") {
+ const problem = await readFile(s.metaPath, "utf8")
+ .then((raw) => localRecordingProblem(JSON.parse(raw)))
+ .catch((e: unknown) => `unreadable metadata: ${(e as Error).message}`);
+ if (problem) {
+ log(`Skipping ${s.channelSlug}/${s.videoDir}: invalid local_recording metadata (${problem})`);
+ return;
+ }
+ }
// The channel's recorded-date rule, applied to the summary as it
// stands (a normalized one included): set when it reads a date, and
// never carried over from an older derivation.
- delete summary.recordedDate;
- const recordedRe = recordedDateRes.get(s.channelSlug);
- if (recordedRe) {
- const recorded = deriveRecordedDate(recordedRe, summary.title, summary.uploadDate);
- if (recorded) summary.recordedDate = recorded;
+ // A source-less recording's explicit date is not a title-derived
+ // publication fact. Keep it, including when a channel rule changes.
+ if (summary.platform !== "local") {
+ delete summary.recordedDate;
+ const recordedRe = recordedDateRes.get(s.channelSlug);
+ if (recordedRe) {
+ const recorded = deriveRecordedDate(recordedRe, summary.title, summary.uploadDate);
+ if (recorded) summary.recordedDate = recorded;
+ }
}
// A SALVAGE transcript says so on its record (release 30, lane Q):
// only a whisper transcript can be one, and only one carrying the
@@ -1570,12 +1589,18 @@ export async function buildIndex({
};
if (sharedNeedsBuild) {
- for (const channelSlug of Array.from(channelConfigs.keys()).sort()) {
- // A held channel's pages are left exactly as the last build wrote them:
- // not rewritten, not pruned, and (below) not removed. After a full rebuild
- // its records are gone, and a rewrite would publish it empty.
- if (held.has(channelSlug)) continue;
- const channelDir = path.join(transcriptsOutDir, channelSlug);
+ // One channel's transcript tree into `channelDir`. The SHARED tree (what every
+ // site copies) leaves local recordings out; a channel that holds one also
+ // gets a FULL tree under sharedPrivateTranscriptsDir, copied into private-
+ // audience sites only (lib/localMedia.ts isLocalRecord). `hashSlug` keys the
+ // page hashes, so the two trees never share a page's hash.
+ const writeTranscriptTree = async (
+ channelSlug: string,
+ channelDir: string,
+ hashSlug: string,
+ includeLocal: boolean,
+ ): Promise<{ sawLocal: boolean }> => {
+ let sawLocal = false;
await mkdir(channelDir, { recursive: true });
const writer = createPageWriter({
@@ -1583,22 +1608,26 @@ export async function buildIndex({
fileName: pageFileName,
maxPageBytes: maxTranscriptPageBytes,
ensureDir: false,
- getPrevHash: (idx) => pageHashes.get([channelSlug, idx])?.hash,
+ getPrevHash: (idx) => pageHashes.get([hashSlug, idx])?.hash,
setHash: (idx, record) => {
- pageHashes.put([channelSlug, idx], record);
+ pageHashes.put([hashSlug, idx], record);
},
onLog: log,
});
for (const { key } of byChannel.getRange({
start: [channelSlug],
- end: [channelSlug, ""],
+ end: [channelSlug, "\uffff"],
})) {
const ck = key as ChannelKey;
if (ck[0] !== channelSlug) continue;
const indexKey: IndexKey = [ck[1], ck[0], ck[2]];
const summary = sums.get(indexKey);
if (!summary) continue;
+ if (isLocalRecord(summary)) {
+ sawLocal = true;
+ if (!includeLocal) continue;
+ }
const cueList = cues.get(indexKey);
// `track` + `altTracks` only on a record that has an alternate, so every
// other record's page bytes are what they were.
@@ -1628,8 +1657,8 @@ export async function buildIndex({
pagesDeleted++;
}
for (const { key } of pageHashes.getRange({
- start: [channelSlug, pageCount],
- end: [channelSlug, Number.MAX_SAFE_INTEGER],
+ start: [hashSlug, pageCount],
+ end: [hashSlug, Number.MAX_SAFE_INTEGER],
})) {
pageHashes.remove(key as PageHashKey);
}
@@ -1646,6 +1675,38 @@ export async function buildIndex({
path.join(channelDir, "manifest.json"),
channelManifest,
);
+ return { sawLocal };
+ };
+
+ const privateTranscriptsOutDir = sharedPrivateTranscriptsDir(paths);
+ for (const channelSlug of Array.from(channelConfigs.keys()).sort()) {
+ // A held channel's pages are left exactly as the last build wrote them:
+ // not rewritten, not pruned, and (below) not removed. After a full rebuild
+ // its records are gone, and a rewrite would publish it empty.
+ if (held.has(channelSlug)) continue;
+ const { sawLocal } = await writeTranscriptTree(
+ channelSlug, path.join(transcriptsOutDir, channelSlug), channelSlug, false,
+ );
+ const privateHashSlug = `private:${channelSlug}`;
+ if (sawLocal) {
+ await writeTranscriptTree(
+ channelSlug, path.join(privateTranscriptsOutDir, channelSlug), privateHashSlug, true,
+ );
+ } else {
+ await rm(path.join(privateTranscriptsOutDir, channelSlug), { recursive: true, force: true });
+ for (const { key } of pageHashes.getRange({
+ start: [privateHashSlug, 0],
+ end: [privateHashSlug, Number.MAX_SAFE_INTEGER],
+ })) {
+ pageHashes.remove(key as PageHashKey);
+ }
+ }
+ }
+ // A private tree for a channel that is gone goes with it.
+ for (const e of await readdir(privateTranscriptsOutDir, { withFileTypes: true }).catch(() => [] as Dirent[])) {
+ if (!channelConfigs.has(e.name)) {
+ await rm(path.join(privateTranscriptsOutDir, e.name), { recursive: true, force: true });
+ }
}
await pageHashes.flushed;
@@ -1809,6 +1870,10 @@ export async function buildIndex({
if (!stored || stored.length === 0) continue;
const summary = sums.get(indexKey);
if (!summary) continue;
+ // A local recording's caption track is its transcript, carried in the
+ // transcript trees; the shared subs tree leaves it out for every site
+ // in lane/local-media slice 1 (no private subs variant).
+ if (isLocalRecord(summary)) continue;
const display = toDisplaySummary(summary, {
state: stateByIndexKey.get(indexKeyId(indexKey)),
});
@@ -2186,6 +2251,8 @@ export async function buildIndex({
const indexKey: IndexKey = [ck[1], ck[0], ck[2]];
const digest = digests.get(indexKey);
if (!digest) continue;
+ // Shared digests leave local recordings out for every site (slice 1).
+ if (isLocalRecord({ id: ck[2], platform: sums.get(indexKey)?.platform })) continue;
await digestWriter.push(JSON.stringify(digest), digest.id);
digestCount++;
}
@@ -2334,6 +2401,7 @@ export async function buildIndex({
.map((c) => c.slug)
.filter((slug) => !memberSlugs.includes(slug));
const slugSet = new Set(memberSlugs);
+ const sitePrivate = isPrivateSite(site);
const slugGroup = new Map<string, string>();
for (const m of site.channels) {
slugGroup.set(
@@ -2366,6 +2434,10 @@ export async function buildIndex({
// Only when the visibility rule withholds a member, so a site it does
// not touch keeps the fingerprint it had.
...(withheld.length > 0 ? { withheld } : {}),
+ // A private site carries local recordings a public one leaves out
+ // (lib/localMedia.ts isLocalRecord): flipping the audience rebuilds it.
+ // Only on a private site, so a public site keeps the fingerprint it had.
+ ...(sitePrivate ? { private: true } : {}),
});
const fpKey = `siteFp:${site.siteId}`;
if (
@@ -2429,11 +2501,18 @@ export async function buildIndex({
// streaming every member record — no second walk of the corpus. compose
// joins these to the site's effective vocabulary to write /tags.json.
const tagCounter = createTagCounter();
+ let localLeftOut = 0;
for (const { key, value } of sums.getRange({ reverse: true })) {
const ik = key as IndexKey;
if (!slugSet.has(ik[1])) continue;
const stored = value as TranscriptSummary;
+ // A local recording is built only into a PRIVATE-audience site (until
+ // slice 4): not in a public site's pages, counts or tags.
+ if (!sitePrivate && isLocalRecord(stored)) {
+ localLeftOut++;
+ continue;
+ }
// A tag scoped to other sites (curated `sites`) is not this site's:
// dropped from its summaries and its counts. A copy only when it moves —
// the stored value is the LMDB cursor's.
@@ -2453,6 +2532,11 @@ export async function buildIndex({
if (buffer.length >= pageSize) await flushPage();
}
await flushPage();
+ if (localLeftOut > 0) {
+ log(
+ `Site ${site.siteId}: ${localLeftOut} local recording(s) left out — a public site carries none until private playback (slice 4); a private-audience site carries them.`,
+ );
+ }
// Written even when empty (a tiny `{tags:{}}`), so a site that loses its
// last tagged video does not keep serving a stale count file. compose
diff --git a/common/controller/buildIndexLocalRecording.test.ts b/common/controller/buildIndexLocalRecording.test.ts
@@ -0,0 +1,213 @@
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "build-index-local-"));
+const PINNED: Record<string, string> = {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"),
+ EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"),
+ CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"),
+ SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"),
+ CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+ ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"),
+};
+Object.assign(process.env, PINNED);
+delete process.env.ARCHILYZER_INDEX_ALLOW_HELD;
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { buildIndex } = await import("./buildIndex");
+const { open } = await import("lmdb");
+
+const paths = getPaths();
+
+const { commitLocalMediaRecord } = await import("../lib/localMediaCommit-server");
+const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata");
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), {recursive: true});
+ writeFileSync(file, JSON.stringify(value));
+};
+const channel = "classroom";
+const dataDirectory = path.join(paths.channelsDir, channel, "data");
+const transcript = "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nSynthetic classroom discovery phrase\n";
+const first = "local-" + "a".repeat(32), second = "local-" + "b".repeat(32);
+const metadata = (id: string, recordedDate?: string) => prepareManualLocalRecordingMetadata({id,
+ filename: "Lesson 2020-01-01.mp4", recordedDate});
+async function commit(id: string, recordedDate?: string) {
+ return commitLocalMediaRecord({dataDirectory, directoryId: id,
+ metadata: JSON.stringify(metadata(id, recordedDate)), transcript,
+ reference: {version: 1, kind: "external", sourceId: "library-1", relativePath: "Lesson.mp4"}});
+}
+function summaries(): Array<{id: string; platform: string; uploadDate: string; recordedDate?: string; webpageUrl: string}> {
+ const root = open({path: paths.lmdbPath, maxDbs: 18, compression: true});
+ try {
+ const sums = root.openDB({name: "sums", encoding: "msgpack"});
+ return Array.from(sums.getRange(), ({value}) => value);
+ } finally { root.close(); }
+}
+// The FULL tree (local recordings included) a private-audience site copies;
+// the shared tree every other site copies leaves them out (review fix 3).
+function pages(root = path.join(paths.exportSharedDir, "private", "transcripts")): string {
+ const dir = path.join(root, channel);
+ return readdirSync(dir).filter(f => f.endsWith(".json")).map(f => readFileSync(path.join(dir,f),"utf8")).join("\n");
+}
+
+test("source-less commits reach real search pages; retries and title rules retain explicit facts", async () => {
+ writeFileSync(paths.settingsFile, "{}");
+ writeJson(path.join(paths.channelsDir,channel,"config.json"), {handling: "youtube", name: "Classroom"});
+ mkdirSync(dataDirectory, {recursive: true});
+ writeJson(path.join(paths.sitesDir,"localtest","site.json"), {
+ siteId: "localtest", siteTitle: "Test", siteDescription: "fixture", headerTitle: "Test", audience: "private",
+ homeTagline: "", socialLinks: [], groups: [{id:"default",name:"All",selectedByDefault:true}],
+ defaultGroupId: "default", channels: [{slug:channel,groupId:"default"}],
+ });
+ assert.deepEqual(await commit(first), {status:"imported"});
+ const logs: string[] = [];
+ await buildIndex({paths, onLog: line => logs.push(line)});
+ assert.deepEqual(summaries().map(s=>s.id), [first]);
+ assert.match(pages(), /Synthetic classroom discovery phrase/);
+ assert.match(pages(), /"platform":\s*"local"/);
+ assert.doesNotMatch(pages(), /youtube.com/);
+ // The shared tree, which a public site copies, carries no local recording.
+ assert.doesNotMatch(pages(paths.exportSharedTranscriptsDir), /"platform":\s*"local"/);
+ assert.deepEqual(await commit(first), {status:"occupied"});
+ assert.deepEqual(await commit(second, "2024-02-29"), {status:"imported"});
+ const online = path.join(dataDirectory,"online-no-date");
+ writeJson(path.join(online,"metadata.info.json"), {id:"online-no-date",title:"Undated online",extractor_key:"Youtube"});
+ writeFileSync(path.join(online,"transcript.en.vtt"),transcript);
+ await buildIndex({paths, onLog: line => logs.push(line)});
+ assert.equal(summaries().length, 2);
+ assert.ok(logs.some(line => line.includes("online-no-date: no upload_date")));
+ writeJson(path.join(paths.channelsDir,channel,"config.json"), {handling:"youtube",name:"Classroom",
+ recordedDate:{titlePattern:String.raw`(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})`}});
+ await buildIndex({paths, onLog: () => {}});
+ for (const summary of summaries()) {
+ assert.equal(summary.platform,"local");
+ // The recording date is a local recording's date (review B2); none, undated.
+ assert.equal(summary.uploadDate, summary.id === second ? "20240229" : "");
+ assert.equal(summary.webpageUrl, "");
+ assert.equal(summary.recordedDate, summary.id === second ? "20240229" : undefined);
+ }
+ assert.match(pages(), /"recordedDate":\s*"20240229"/);
+});
+
+test("invalid local metadata cannot create a corpus record", async () => {
+ const id="local-"+"c".repeat(32);
+ for (const value of [{...metadata(id),webpage_url:"https://example.com/video"}, {...metadata(id),id:first}]) {
+ await assert.rejects(commitLocalMediaRecord({dataDirectory,directoryId:id,metadata:JSON.stringify(value),transcript,
+ reference:{version:1,kind:"external",sourceId:"library-1",relativePath:"Lesson.mp4"}}));
+ }
+ assert.equal(readdirSync(dataDirectory).includes(id),false);
+});
+
+test("a malformed local_recording written past the importer is skipped with a log line, not thrown", async () => {
+ const id = "local-" + "d".repeat(32);
+ const dir = path.join(dataDirectory, id);
+ writeJson(path.join(dir, "metadata.info.json"), {...metadata(id), local_recording: {version: 99}});
+ writeFileSync(path.join(dir, "transcript.en.vtt"), transcript);
+ const logs: string[] = [];
+ await buildIndex({paths, onLog: line => logs.push(line)});
+ assert.ok(!summaries().some(s => s.id === id));
+ assert.ok(logs.some(line => line.includes(`${id}: invalid local_recording metadata`)), logs.join("\n"));
+ assert.ok(!logs.some(line => line.includes("Failed to process")), logs.join("\n"));
+ rmSync(dir, {recursive: true, force: true});
+});
+
+// Review B2: an undated local record (uploadDate "") through the index, the
+// summaries page order, the stats run and the recency index the lanes read.
+test("an undated local record pages last, keeps a stats row, and reads as unknown to the recency index", async () => {
+ const { siteSummariesDir } = await import("../lib/site");
+ const { buildStats } = await import("./buildStats");
+ const { openUploadDateIndex } = await import("./recencyIndex");
+ // The first test's undated ONLINE record is skipped by the index, and so,
+ // on main, re-"added" by every stats run: out of this one's count.
+ rmSync(path.join(dataDirectory, "online-no-date"), {recursive: true, force: true});
+ const online = path.join(dataDirectory, "onlinedated");
+ writeJson(path.join(online, "metadata.info.json"), {id: "onlinedated", title: "Dated online",
+ extractor_key: "Youtube", upload_date: "20250101", webpage_url: "https://www.youtube.com/watch?v=onlinedated"});
+ writeFileSync(path.join(online, "transcript.en.vtt"), transcript);
+ await buildIndex({paths, onLog: () => {}});
+ const dir = siteSummariesDir(paths, "localtest");
+ const listed: Array<{id: string; date: string}> = readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f)).sort()
+ .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8")));
+ // Newest first: the dated online record, the dated local one, then the undated one last.
+ assert.deepEqual(listed.map(r => r.id), ["onlinedated", second, first]);
+ assert.deepEqual(listed.map(r => r.date), ["2025-01-01", "2024-02-29", ""]);
+
+ const logs: string[] = [];
+ const once = await buildStats({paths, onLog: line => logs.push(line)});
+ assert.ok(once.added >= 3, JSON.stringify(once));
+ const twice = await buildStats({paths, onLog: () => {}});
+ // Without a row for the undated record it was "added" every run, and every
+ // site's stats bundle rewritten.
+ assert.equal(twice.added, 0, JSON.stringify(twice));
+ assert.equal(twice.shortCircuited, true, JSON.stringify(twice));
+
+ const recency = openUploadDateIndex(paths, [channel]);
+ try {
+ const dates = recency.datesBySlug.get(channel)!;
+ assert.equal(dates.get(first), "");
+ assert.equal(dates.get(second), "20240229");
+ assert.equal(dates.get("onlinedated"), "20250101");
+ } finally { await recency.close(); }
+ rmSync(online, {recursive: true, force: true});
+});
+
+// Review fix 3 (the publish boundary): a PUBLIC site's build leaves local
+// recordings out — its summaries, counts and stats — and says so once with the
+// count; a PRIVATE-audience site carries them; compose picks the private
+// transcript tree for the private site only; the hub's whole-pool stats have none.
+test("a public site leaves local recordings out and says so; a private one carries them", async () => {
+ const { siteSummariesDir, siteStatsDir } = await import("../lib/site");
+ const { buildStats } = await import("./buildStats");
+ const { transcriptsSourceFor } = await import("../bin/compose-site");
+ const online = path.join(dataDirectory, "onlinepublic");
+ writeJson(path.join(online, "metadata.info.json"), {id: "onlinepublic", title: "Online public", extractor_key: "Youtube",
+ upload_date: "20250102", webpage_url: "https://www.youtube.com/watch?v=onlinepublic"});
+ writeFileSync(path.join(online, "transcript.en.vtt"), transcript);
+ writeJson(path.join(paths.sitesDir, "publictest", "site.json"), {
+ siteId: "publictest", siteTitle: "Public", siteDescription: "fixture", headerTitle: "Public",
+ homeTagline: "", socialLinks: [], groups: [{id: "default", name: "All", selectedByDefault: true}],
+ defaultGroupId: "default", channels: [{slug: channel, groupId: "default"}],
+ });
+ const logs: string[] = [];
+ await buildIndex({paths, onLog: line => logs.push(line)});
+ const listed = (site: string) => {
+ const dir = siteSummariesDir(paths, site);
+ const ids = readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f))
+ .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8")) as Array<{id: string}>).map(r => r.id);
+ const manifest = JSON.parse(readFileSync(path.join(dir, "manifest.json"), "utf8")) as {totalCount: number};
+ return {ids, total: manifest.totalCount};
+ };
+ const pub = listed("publictest"), priv = listed("localtest");
+ assert.deepEqual(pub.ids, ["onlinepublic"]);
+ assert.equal(pub.total, 1);
+ assert.ok(priv.ids.includes(first) && priv.ids.includes(second) && priv.ids.includes("onlinepublic"), priv.ids.join());
+ assert.equal(logs.filter(l => /Site publictest: 2 local recording\(s\) left out/.test(l)).length, 1, logs.join("\n"));
+ assert.ok(!logs.some(l => /Site localtest: .* local recording/.test(l)));
+
+ // Compose's choice of transcript tree: the private one only for a private site.
+ assert.equal(await transcriptsSourceFor(paths, false)(channel), path.join(paths.exportSharedTranscriptsDir, channel));
+ assert.equal(await transcriptsSourceFor(paths, true)(channel), path.join(paths.exportSharedDir, "private", "transcripts", channel));
+ assert.equal(await transcriptsSourceFor(paths, true)("no-locals"), path.join(paths.exportSharedTranscriptsDir, "no-locals"));
+
+ const pool = path.join(ROOT, "pool-stats");
+ await buildStats({paths, onLog: () => {}, wholePoolStatsDir: pool});
+ const statsIds = (dir: string) => readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f))
+ .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8")) as Array<{id: string}>).map(r => r.id);
+ assert.deepEqual(statsIds(siteStatsDir(paths, "publictest")), ["onlinepublic"]);
+ assert.ok(statsIds(siteStatsDir(paths, "localtest")).includes(first));
+ assert.deepEqual(statsIds(pool), ["onlinepublic"]);
+ rmSync(online, {recursive: true, force: true});
+ rmSync(path.join(paths.sitesDir, "publictest"), {recursive: true, force: true});
+});
diff --git a/common/controller/buildStats.ts b/common/controller/buildStats.ts
@@ -31,6 +31,8 @@
// other scanned, when the other can publish truncated pages. The editor's build
// jobs share the "build" queue by default; the CLI is outside every queue.
+import { isLocalRecord } from "../lib/localMedia";
+import { isPrivateSite } from "../lib/siteSchema";
import path from "node:path";
import { createHash } from "node:crypto";
import {
@@ -551,7 +553,11 @@ export async function buildStats({
parsedMeta,
e.configName,
);
- if (!base.uploadDate) return;
+ // An undated LOCAL recording is indexed (lib/transcripts-server.ts,
+ // summarize), so it has a stats row too — without one it would count
+ // as "added" on every run and rewrite every site's bundle. Its row
+ // falls in no time bucket (chartAggregate.xLabelsForStat).
+ if (!base.uploadDate && base.platform !== "local") return;
// The key buildIndex stored this video's cues under, when it has a
// record: its uploadDate comes from transcript.cues.json when that
// is fresh, which the metadata's can differ from. The computed key
@@ -635,19 +641,22 @@ export async function buildStats({
const sites = listSites(paths);
const siteIds = new Set(sites.map((s) => s.siteId));
- const siteFingerprint = (slugs: string[]): string =>
+ const siteFingerprint = (slugs: string[], privateSite: boolean): string =>
JSON.stringify({
gen: generation,
max: STATS_MAX_PAGE_BYTES,
channels: slugs,
state: stateSignature,
+ // A private site's bundle carries local recordings (lib/localMedia.ts
+ // isLocalRecord); only there, so a public site keeps its fingerprint.
+ ...(privateSite ? { private: true } : {}),
});
// Decide which sites need a rebuild before paying to collect the dataset.
const plans = await Promise.all(
sites.map(async (site) => {
const slugs = site.channels.map((c) => c.slug);
- const fp = siteFingerprint(slugs);
+ const fp = siteFingerprint(slugs, isPrivateSite(site));
const outDir = siteStatsDir(paths, site.siteId);
const siteManifestPath = path.join(outDir, "manifest.json");
const stored = meta.get(`statsFp:${site.siteId}`) as string | undefined;
@@ -707,7 +716,10 @@ export async function buildStats({
}
signal?.throwIfAborted();
const slugSet = new Set(plan.slugs);
- const filtered = all.filter((s) => slugSet.has(s.channelSlug));
+ // A local recording only in a PRIVATE-audience site's bundle (until slice 4).
+ const sitePrivate = isPrivateSite(plan.site);
+ const filtered = all.filter((s) => slugSet.has(s.channelSlug) && (sitePrivate || !isLocalRecord(s)));
+ const siteCounts = countByChannel(filtered);
const { pageCount } = await writePages(
plan.outDir,
filtered,
@@ -717,7 +729,7 @@ export async function buildStats({
.map((slug) => ({
slug,
name: channels.get(slug)?.name ?? slug,
- count: perChannel.get(slug) ?? 0,
+ count: siteCounts.get(slug) ?? 0,
}))
.sort((a, b) => a.slug.localeCompare(b.slug));
const manifest: StatsManifest = {
@@ -748,10 +760,9 @@ export async function buildStats({
// bundles. Always rewritten when requested (stats records are small).
if (wholePoolStatsDir) {
const unlistedOnly = channelsOnlyOnUnlistedSites(sites);
- const pooled =
- unlistedOnly.size > 0
- ? all.filter((s) => !unlistedOnly.has(s.channelSlug))
- : all;
+ // The hub and homepage are public: no local recording (until slice 4).
+ const pooled = all.filter((s) => !unlistedOnly.has(s.channelSlug) && !isLocalRecord(s));
+ const poolCounts = countByChannel(pooled);
const { pageCount } = await writePages(
wholePoolStatsDir,
pooled,
@@ -762,7 +773,7 @@ export async function buildStats({
.map((slug) => ({
slug,
name: channels.get(slug)?.name ?? slug,
- count: perChannel.get(slug) ?? 0,
+ count: poolCounts.get(slug) ?? 0,
}))
.sort((a, b) => a.slug.localeCompare(b.slug));
const manifest: StatsManifest = {
@@ -817,3 +828,9 @@ export async function buildStats({
durationMs: Date.now() - t0,
};
}
+
+function countByChannel(stats: readonly VideoStat[]): Map<string, number> {
+ const out = new Map<string, number>();
+ for (const s of stats) out.set(s.channelSlug, (out.get(s.channelSlug) ?? 0) + 1);
+ return out;
+}
diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts
@@ -1062,3 +1062,47 @@ test("a skip-Shorts channel keeps its listed Shorts out of the work list and the
await rm(keeping.dir, { recursive: true, force: true });
}
});
+
+// lane/local-media review fix 4: a local media library's record is never a
+// replace-auto-captions candidate (the opt-in `autoSubsOnly` bucket the
+// transcription lane draws with `replaceAutoSubs`), nor in any download bucket,
+// even when its imported VTT sniffs as YouTube's speech recognition.
+test("a local recording, and a local library channel's record, are in no acquisition bucket", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "ttb-snap-local-"));
+ const ts = (s: number) => new Date(s * 1000).toISOString().slice(11, 23);
+ const asr = "WEBVTT\nKind: captions\nLanguage: en\n\n" + [1, 3, 5, 7, 9].map((a) =>
+ `${ts(a)} --> ${ts(a + 2)} align:start position:0%\nword<${ts(a)}><c> more</c>\n`).join("\n");
+ const local = "local-" + "c".repeat(32);
+ try {
+ const paths = { channelsDir: path.join(dir, "channels") } as Paths;
+ const record = async (slug: string, id: string, meta: unknown) => {
+ const videoDir = path.join(paths.channelsDir, slug, "data", id);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify(meta));
+ await writeFile(path.join(videoDir, "transcript.en.vtt"), asr);
+ };
+ const channel = async (slug: string, config: unknown) => {
+ await mkdir(path.join(paths.channelsDir, slug), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify(config));
+ await writeFile(path.join(paths.channelsDir, slug, "playlist"), "");
+ };
+ const lib = { sourceId: "library-1", directory: path.join(dir, "library") };
+ await channel("hybrid", { handling: "youtube", url: "https://www.youtube.com/@hybrid", localMedia: lib });
+ await record("hybrid", "onlineasr01", { id: "onlineasr01", webpage_url: "https://www.youtube.com/watch?v=onlineasr01" });
+ await record("hybrid", local, { id: local, title: "Talk", local_recording: { version: 1, titleSource: "filename", inspection: "manual", durationSource: "unknown" } });
+ await channel("archive", { handling: "youtube", sourceKind: "video", localMedia: lib });
+ await record("archive", "providerasr", { id: "providerasr", webpage_url: "https://www.youtube.com/watch?v=providerasr" });
+
+ const hybrid = await generateChannelSnapshot(paths, "hybrid");
+ assert.deepEqual(hybrid.buckets.autoSubsOnly, ["onlineasr01"], "the online control is a candidate");
+ const archive = await generateChannelSnapshot(paths, "archive");
+ assert.deepEqual(archive.buckets.autoSubsOnly, []);
+ for (const snap of [hybrid, archive]) {
+ for (const ids of [snap.buckets.downloadedNoTranscript, snap.buckets.partialDownloads, snap.undownloadedIds]) {
+ assert.ok(!ids.includes(local) && !ids.includes("providerasr"), JSON.stringify(ids));
+ }
+ }
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts
@@ -1,4 +1,5 @@
import { writeJsonAtomic } from "../lib/jsonFile-server";
+import { localMediaFetchRefusal } from "../lib/localMedia";
import path from "node:path";
import type { Dirent } from "node:fs";
import { lstat, readdir, readFile, stat } from "node:fs/promises";
@@ -1653,7 +1654,9 @@ export async function generateChannelSnapshot(
// provenance we can't prove ("unknown") is never a candidate, so a human
// caption track is never scheduled for replacement. The corrupt-full-source
// and failed-short-audio `continue`s above already excluded terminal videos.
- const asrVtt = files.hasYtVtt && vttProvenance === "asr";
+ // A local media library's record (lib/localMedia.ts) is never a
+ // replace-auto-captions candidate: it has no online source to fetch audio from.
+ const asrVtt = files.hasYtVtt && vttProvenance === "asr" && !localMediaFetchRefusal(slug, config, id);
if (asrVtt && files.hasWhisper) {
// Our transcript won; the old ASR VTT lingers as a backup. do-not-clean
// dirs are excluded so the count matches what the manual purge removes.
diff --git a/common/controller/configureLocalMedia.test.ts b/common/controller/configureLocalMedia.test.ts
@@ -0,0 +1,67 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { configureLocalMedia } from "./configureLocalMedia";
+import { readChannelConfig } from "./channels";
+import type { Paths } from "../lib/paths";
+
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-media-controller-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const source = path.join(root, "source");
+ const paths = { channelsDir: path.join(root, "channels") };
+ const channel = path.join(paths.channelsDir, "sample");
+ await mkdir(source); await mkdir(channel, { recursive: true });
+ const config = { handling: "youtube", platform: "youtube", localMedia: { sourceId: "library-1", directory: source } };
+ await writeFile(path.join(channel, "config.json"), JSON.stringify(config));
+ async function add(name: string, id = name) {
+ await writeFile(path.join(source, name + ".mp4"), "synthetic video");
+ await writeFile(path.join(source, name + ".info.json"), JSON.stringify({ id, title: "Synthetic", duration: 3, upload_date: "20261030", webpage_url: `https://www.youtube.com/watch?v=${id}` }));
+ await writeFile(path.join(source, name + ".vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nSynthetic cue\n");
+ }
+ return { root, source, paths, channel, config, add };
+}
+async function unconfigured(f: Awaited<ReturnType<typeof fixture>>) {
+ await writeFile(path.join(f.channel,"config.json"), JSON.stringify({handling:"youtube", platform:"youtube", name:"Preserved", lastSyncedAt:"2026-10-30T00:00:00Z"}));
+}
+
+test("initial setup preserves unrelated config, creates no records, and does not enable playback", async t => {
+ const f=await fixture(t); await unconfigured(f);
+ const result=await configureLocalMedia(f.paths as Paths,"sample",{sourceId:"external-1",directory:f.source,playback:true});
+ assert.deepEqual(result,{sourceId:"external-1",directory:f.source});
+ assert.equal((await readChannelConfig(f.paths as Paths,"sample"))?.name,"Preserved");
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+ assert.deepEqual(await readdir(f.source),[]);
+});
+
+test("an established library cannot be replaced or disabled by initial setup", async t => {
+ const f=await fixture(t);
+ const before=await readFile(path.join(f.channel,"config.json"),"utf8");
+ await assert.rejects(configureLocalMedia(f.paths as Paths,"sample",{sourceId:"different",directory:f.source}),/already has a library/);
+ assert.equal(await readFile(path.join(f.channel,"config.json"),"utf8"),before);
+});
+
+test("two concurrent setup attempts have one winner", async t => {
+ const f=await fixture(t); await unconfigured(f);
+ const results=await Promise.allSettled(["first","second"].map(sourceId=>configureLocalMedia(f.paths as Paths,"sample",{sourceId,directory:f.source})));
+ assert.equal(results.filter(r=>r.status==="fulfilled").length,1);
+ assert.equal(results.filter(r=>r.status==="rejected").length,1);
+});
+
+test("invalid paths, overlapping corpus and missing source are refused without changing config", async t => {
+ const f=await fixture(t); await unconfigured(f);
+ const before=await readFile(path.join(f.channel,"config.json"),"utf8");
+ for(const directory of ["relative",f.channel,f.root,path.join(f.root,"missing")]) {
+ await assert.rejects(configureLocalMedia(f.paths as Paths,"sample",{sourceId:"library",directory}));
+ }
+ await assert.rejects(configureLocalMedia(f.paths as Paths,"../sample",{sourceId:"library",directory:f.source}),/Invalid channel/);
+ assert.equal(await readFile(path.join(f.channel,"config.json"),"utf8"),before);
+});
+
+test("relocation blocks setup", async t => {
+ const f=await fixture(t); await unconfigured(f);
+ await writeFile(path.join(f.channel,".relocating.json"),JSON.stringify({target:path.join(f.root,"media"),scope:"media",phase:"copy",direction:"out"}));
+ await assert.rejects(configureLocalMedia(f.paths as Paths,"sample",{sourceId:"library",directory:f.source}));
+});
diff --git a/common/controller/configureLocalMedia.ts b/common/controller/configureLocalMedia.ts
@@ -0,0 +1,50 @@
+import path from "node:path";
+import { libraryLocationProblem } from "./localMediaLocation";
+import { lstat, realpath } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { coerceLocalMediaConfig } from "../lib/localMedia";
+import { patchChannelConfig, readChannelConfig } from "./channels";
+import { channelWriters } from "./channelWriters";
+import { assertChannelTextReadable, readRelocationMarker } from "../lib/channelMedia";
+
+function overlaps(a: string, b: string): boolean {
+ const rel = path.relative(a, b);
+ return !rel || rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
+}
+
+// Initial opt-in only. Changing an established source needs an explicit
+// reconciliation flow: the same relative names could identify different videos.
+// Keep this restriction in the controller, not just disabled form inputs.
+export async function configureLocalMedia(paths: Paths, slug: string, input: unknown) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) || slug.endsWith(".")) throw new Error("Invalid channel slug");
+ const parsed = coerceLocalMediaConfig(input);
+ if (!parsed || !path.isAbsolute(parsed.directory)) throw new Error("Enter a library ID and an absolute directory path on the editor server");
+ // This setup enables importing only; playback requires its own future flow.
+ const localMedia = { sourceId: parsed.sourceId, directory: parsed.directory };
+ const channel = path.join(paths.channelsDir, slug);
+ const info = await lstat(channel);
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("Channel must be a real directory");
+ const current = await readChannelConfig(paths, slug);
+ if (!current || current.sourceKind === "social") throw new Error("A video channel is required");
+ if (current.localMedia) throw new Error("This channel already has a library. Changing it requires reference reconciliation");
+ await assertChannelTextReadable(paths, slug, current);
+ if (await readRelocationMarker(paths, slug)) throw new Error("Finish channel relocation before configuring a library");
+ const source = await realpath(localMedia.directory);
+ if (!(await lstat(source)).isDirectory()) throw new Error("Library location must be a directory");
+ const corpus = await realpath(channel);
+ if (overlaps(source, corpus) || overlaps(corpus, source)) throw new Error("Library and channel directories must be separate");
+ const misplaced = await libraryLocationProblem(paths, source);
+ if (misplaced) throw new Error(misplaced);
+ const written = await patchChannelConfig(paths, slug, {}, {
+ derive: fresh => {
+ // Rechecked inside the existing config lock: concurrent setup requests
+ // cannot replace the winner, and stale config cannot erase other changes.
+ if (fresh.localMedia) throw new Error("This channel already has a library");
+ if (fresh.sourceKind === "social") throw new Error("A video channel is required");
+ if (channelWriters(slug, { includeQueued: true }).length) throw new Error("Finish or cancel channel work before configuring its library");
+ return { localMedia };
+ },
+ });
+ if (!written?.localMedia) throw new Error("Channel configuration is unavailable");
+ return written.localMedia;
+}
diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts
@@ -30,6 +30,7 @@
// `needsMedia` (jobs/jobKinds.ts): it WRITES the raw replay, which is a
// tierable big file, and the normalizer moves it into the channel's media/.
+import { localMediaFetchRefusal } from "../lib/localMedia";
import path from "node:path";
import { readFile, readdir, stat } from "node:fs/promises";
import {
@@ -112,6 +113,9 @@ export async function liveChatPlan(
}
const videoDir = path.join(paths.channelsDir, slug, "data", videoId);
if (!(await isDirectory(videoDir))) return { kind: "refused", error: notFetchedRefusal(videoId, slug) };
+ // A local media record has no chat to fetch (review fix 5), before any branch.
+ const localRefusal = localMediaFetchRefusal(slug, config, videoId);
+ if (localRefusal) return { kind: "refused", error: localRefusal };
const fresh = await isLiveChatCuesFresh(videoDir);
if (fresh.fresh) return { kind: "fresh", cuesPath: fresh.cuesPath };
const entries = await readdir(videoDir).catch(() => [] as string[]);
diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts
@@ -870,3 +870,18 @@ test("a media 403 that persists fails once, counts once toward the streak; a Rum
assert.equal(isTransientMedia403("x Server returned 403 Forbidden (access denied)", "rumble"), false);
assert.equal(isTransientMedia403("ERROR: [download] Got error: HTTP Error 403: Forbidden", "youtube"), false);
});
+
+// lane/local-media: the job-level backstop. A local library channel's item and
+// a local recording's are failed "local-media" before any URL is looked up.
+test("a local media library channel and a local recording fail local-media, and the run goes on", async () => {
+ const LOCAL = { ...CONFIG, url: undefined, localMedia: { sourceId: "library-1", directory: "/mnt/library" } };
+ const h = harness({ readChannelConfig: async (_p, slug) => (slug === "lib" ? LOCAL : CONFIG) });
+ const r = await go(
+ await corpus(),
+ [{ ...item("v1", "/ok"), slug: "lib" }, { ...item("v1", "/ok"), id: "local-" + "b".repeat(32) }, item("v2", "/ok")],
+ h,
+ );
+ assert.deepEqual(r.failed.map((f) => f.class), ["local-media", "local-media"]);
+ for (const f of r.failed) assert.match(f.message ?? "", /no online source, so no clip can be fetched/);
+ assert.equal(r.fetched.length, 1);
+});
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -1,4 +1,5 @@
import path from "node:path";
+import { localMediaFetchRefusal } from "../lib/localMedia";
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
@@ -251,7 +252,10 @@ export type FetchWindowsFailureClass =
// aside, not kept.
| "desynced"
// No page URL to fetch from.
- | "no-url";
+ | "no-url"
+ // A local media library channel or a local recording: no online source
+ // (lib/localMedia.ts localMediaFetchRefusal).
+ | "local-media";
export type FetchWindowsFailure = {
item: FetchWindowsItem;
@@ -772,6 +776,13 @@ export async function fetchWindows({
progress();
continue;
}
+ const localRefusal = localMediaFetchRefusal(item.slug, config, item.id);
+ if (localRefusal) {
+ fail(item, "local-media", localRefusal);
+ done += 1;
+ progress();
+ continue;
+ }
const unreadable = await textProblem(item.slug);
if (unreadable) {
fail(item, "unreachable", unreadable);
diff --git a/common/controller/findVideoSourceUrlLocal.test.ts b/common/controller/findVideoSourceUrlLocal.test.ts
@@ -0,0 +1,57 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { findVideoSourceUrl } from "./undownloadedVideos";
+import { defaultWebpageUrl } from "../lib/platform";
+
+// lane/local-media review fix 4: the one resolver every lane and door asks for a
+// video's page URL — the download lane, the replace-auto-captions unit (which
+// passes the channel with a transcribe-handling override), transcribe-one's
+// owed download, reacquire, persist-videos — answers NULL for a local record,
+// so `defaultWebpageUrl("local", id)` (which is "") never reaches yt-dlp.
+
+test("findVideoSourceUrl: null for a local recording, a local library channel and platform \"local\"", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "source-url-local-"));
+ try {
+ const paths = { channelsDir: path.join(dir, "channels") } as Paths;
+ const local = "local-" + "d".repeat(32);
+ const write = async (slug: string, config: ChannelConfig, id: string, meta: unknown, playlist = "") => {
+ await mkdir(path.join(paths.channelsDir, slug, "data", id), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify(config));
+ await writeFile(path.join(paths.channelsDir, slug, "playlist"), playlist);
+ await writeFile(path.join(paths.channelsDir, slug, "data", id, "metadata.info.json"), JSON.stringify(meta));
+ };
+ const lib = { sourceId: "library-1", directory: "/mnt/library" };
+ const hybrid: ChannelConfig = { handling: "youtube", platform: "youtube", url: "https://www.youtube.com/@h", localMedia: lib };
+ // A local recording in an online channel: a youtube platform would rebuild a URL from its id.
+ await write("hybrid", hybrid, local, { id: local, title: "Talk", local_recording: { version: 1 } },
+ `https://www.youtube.com/watch?v=${local}\n`);
+ assert.equal(await findVideoSourceUrl(paths, "hybrid", local, hybrid), null);
+ // The replace-auto-captions unit's override config: still null.
+ assert.equal(await findVideoSourceUrl(paths, "hybrid", local, { ...hybrid, handling: "transcribe" }), null);
+ // No config passed: read from disk, still null.
+ assert.equal(await findVideoSourceUrl(paths, "hybrid", local), null);
+ // A local library channel's provider-metadata record: no online source either.
+ const archive: ChannelConfig = { handling: "youtube", sourceKind: "video", localMedia: lib };
+ await write("archive", archive, "aaaaaaaaaaa", { id: "aaaaaaaaaaa", webpage_url: "https://www.youtube.com/watch?v=aaaaaaaaaaa" });
+ assert.equal(await findVideoSourceUrl(paths, "archive", "aaaaaaaaaaa", archive), null);
+ // A record carrying the local marker under any id.
+ await write("hybrid", hybrid, "markedonly", { id: "markedonly", local_recording: { version: 1 } });
+ assert.equal(await findVideoSourceUrl(paths, "hybrid", "markedonly", hybrid), null);
+ // A channel whose platform is "local": "" is not a URL.
+ const localPlatform: ChannelConfig = { handling: "youtube", platform: "local" };
+ await mkdir(path.join(paths.channelsDir, "lp", "data", "x1"), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, "lp", "config.json"), JSON.stringify(localPlatform));
+ assert.equal(defaultWebpageUrl("local", "x1"), "");
+ assert.equal(await findVideoSourceUrl(paths, "lp", "x1", localPlatform), null);
+ // An online record of the online channel is unchanged.
+ await write("hybrid", hybrid, "dQw4w9WgXcQ", { id: "dQw4w9WgXcQ", webpage_url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ" });
+ assert.equal(await findVideoSourceUrl(paths, "hybrid", "dQw4w9WgXcQ", hybrid), "https://www.youtube.com/watch?v=dQw4w9WgXcQ");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/importMedia.ts b/common/controller/importMedia.ts
@@ -28,6 +28,7 @@
// multi-GB copy never holds a platform's download queue. `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";
@@ -310,6 +311,10 @@ export async function runImportMediaJob(opts: ImportMediaJobOpts): Promise<Strea
}
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 };
diff --git a/common/controller/localMediaDoors.ts b/common/controller/localMediaDoors.ts
@@ -0,0 +1,25 @@
+import path from "node:path";
+import { lstat } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { EXTERNAL_MEDIA_FILENAME, localMediaFetchRefusal } from "../lib/localMedia";
+
+// THE DOORS THAT WRITE MEDIA INTO A RECORD (import-media, attach-media; review
+// fix 5): besides a local library channel or a local recording
+// (localMediaFetchRefusal's sentence), a record LINKED to a library original —
+// one with `external-media.json`, a provider id included — is refused: its
+// video is the library's, never a copy in the saved-video store. `lstat`, not
+// the sidecar's loader: a malformed reference must refuse too.
+export async function localMediaWriteRefusal(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ config: { localMedia?: unknown; url?: string | null } | null | undefined,
+ id?: string,
+): Promise<string | null> {
+ const fetch = localMediaFetchRefusal(slug, config, id);
+ if (fetch) return fetch;
+ if (!id || /[\\/]|^\.\.?$/.test(id)) return null;
+ const linked = await lstat(path.join(paths.channelsDir, slug, "data", id, EXTERNAL_MEDIA_FILENAME)).then(() => true, () => false);
+ return linked
+ ? `"${slug}/${id}" is linked to a local media library original (${EXTERNAL_MEDIA_FILENAME}), so no media is written into it.`
+ : null;
+}
diff --git a/common/controller/localMediaImport.test.ts b/common/controller/localMediaImport.test.ts
@@ -0,0 +1,218 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { previewLocalMedia, importLocalMedia } from "./localMediaImport";
+
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-media-controller-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const source = path.join(root, "source");
+ const paths = { channelsDir: path.join(root, "channels") };
+ const channel = path.join(paths.channelsDir, "sample");
+ await mkdir(source); await mkdir(channel, { recursive: true });
+ const config = { handling: "youtube", platform: "youtube", localMedia: { sourceId: "library-1", directory: source } };
+ await writeFile(path.join(channel, "config.json"), JSON.stringify(config));
+ async function add(name: string, id = name) {
+ await writeFile(path.join(source, name + ".mp4"), "synthetic video");
+ await writeFile(path.join(source, name + ".info.json"), JSON.stringify({ id, title: "Synthetic", duration: 3, upload_date: "20261030", webpage_url: `https://www.youtube.com/watch?v=${id}` }));
+ await writeFile(path.join(source, name + ".vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nSynthetic cue\n");
+ }
+ return { root, source, paths, channel, config, add };
+}
+function selection(preview: Awaited<ReturnType<typeof previewLocalMedia>>) {
+ return { sourceToken: preview.sourceToken, selected: preview.candidates.filter(r => r.status === "new").map(r => ({ media: r.media, fingerprint: r.fingerprint! })) };
+}
+async function sourceBytes(source: string) {
+ const out: Record<string,string> = {};
+ for (const name of (await readdir(source)).sort()) out[name] = (await readFile(path.join(source,name))).toString("base64");
+ return out;
+}
+test("preview creates nothing; import then rescan detects additions without changing sources", async (t) => {
+ const f = await fixture(t); await f.add("first");
+ const before = await sourceBytes(f.source);
+ const p = await previewLocalMedia(f.paths,"sample");
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+ assert.equal(p.counts.new,1);
+ const result = await importLocalMedia(f.paths,"sample",selection(p));
+ assert.equal(result.records[0].status,"imported"); assert.equal(result.needsIndexUpdate,true);
+ assert.deepEqual(await sourceBytes(f.source),before);
+ assert.deepEqual((await previewLocalMedia(f.paths,"sample")).counts,{discovered:1,new:0,existing:1,issues:0});
+ assert.equal((await importLocalMedia(f.paths,"sample",selection(p))).records[0].status,"occupied");
+ await f.add("second");
+ const next = await previewLocalMedia(f.paths,"sample");
+ assert.equal(next.counts.new,1); assert.equal(next.counts.existing,1);
+ assert.equal((await importLocalMedia(f.paths,"sample",selection(next))).records[0].status,"imported");
+ assert.equal((await previewLocalMedia(f.paths,"sample")).counts.existing,2);
+});
+test("changed transcript after preview is stale and no record is written", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ await writeFile(path.join(f.source,"first.vtt"),"WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nChanged text\n");
+ const result=await importLocalMedia(f.paths,"sample",selection(p));
+ assert.equal(result.records[0].status,"stale"); assert.equal(result.needsIndexUpdate,false);
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+test("source configuration change invalidates preview", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ await writeFile(path.join(f.channel,"config.json"),JSON.stringify({...f.config,localMedia:{...f.config.localMedia,sourceId:"different"}}));
+ await assert.rejects(importLocalMedia(f.paths,"sample",selection(p)),/configuration changed/);
+});
+test("duplicate introduced after preview blocks import", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ await f.add("duplicate","first");
+ const result=await importLocalMedia(f.paths,"sample",selection(p));
+ assert.equal(result.records[0].status,"issue"); assert.match(result.records[0].reason!,/Duplicate/);
+});
+test("incomplete destination is an issue, not an already imported success", async (t) => {
+ const f=await fixture(t); await f.add("first");
+ await mkdir(path.join(f.channel,"data","first"),{recursive:true});
+ const p=await previewLocalMedia(f.paths,"sample");
+ assert.equal(p.counts.issues,1); assert.equal(p.counts.existing,0);
+ assert.match(p.candidates[0].issues.join(),/incomplete/);
+});
+test("retired data layout refuses preview", async (t) => {
+ const f=await fixture(t); await f.add("first");
+ await writeFile(path.join(f.channel,"config.json"),JSON.stringify({...f.config,dataDir:path.join(f.root,"legacy")}));
+ await assert.rejects(previewLocalMedia(f.paths,"sample"));
+});
+test("source overlapping corpus is refused before writes", async (t) => {
+ const f=await fixture(t);
+ await writeFile(path.join(f.channel,"config.json"),JSON.stringify({...f.config,localMedia:{...f.config.localMedia,directory:f.root}}));
+ await assert.rejects(previewLocalMedia(f.paths,"sample"),/overlap|The library directory contains the corpus/);
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+test("cancellation and empty selection write nothing", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ const signal=AbortSignal.abort();
+ assert.equal((await importLocalMedia(f.paths,"sample",{...selection(p),signal})).cancelled,true);
+ assert.equal((await importLocalMedia(f.paths,"sample",{sourceToken:p.sourceToken,selected:[]})).needsIndexUpdate,false);
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+test("invented selection and missing media do not create records", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ await rm(path.join(f.source,"first.mp4"));
+ assert.equal((await importLocalMedia(f.paths,"sample",selection(p))).records[0].status,"stale");
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+test("duplicate selection and unsafe channel slug are rejected", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ const request=selection(p); request.selected.push(request.selected[0]);
+ await assert.rejects(importLocalMedia(f.paths,"sample",request),/selection/);
+ await assert.rejects(previewLocalMedia(f.paths,"../escape"),/slug/);
+});
+
+test("media-only relocation blocks import even while text is readable", async (t) => {
+ const f=await fixture(t); await f.add("first");
+ await writeFile(path.join(f.channel,".relocating.json"),JSON.stringify({ target:path.join(f.root,"other","media"),scope:"media",phase:"copy",direction:"out" }));
+ await assert.rejects(previewLocalMedia(f.paths,"sample"),/relocation/);
+ assert.deepEqual((await readdir(f.channel)).sort(),[".relocating.json","config.json"]);
+});
+test("missing source fails instead of reporting an empty successful preview", async (t) => {
+ const f=await fixture(t); await rm(f.source,{recursive:true});
+ await assert.rejects(previewLocalMedia(f.paths,"sample"));
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+
+import type { Paths } from "../lib/paths";
+import type { JobRunContext } from "../jobs/streamCommand";
+import { localMediaJobOptions, selectAllNew, LOCAL_MEDIA_IMPORT_MAX } from "./localMediaImportJob";
+import { getJobKind, isIngestKind } from "../jobs/jobKinds";
+
+function jobContext(drain = new AbortController()): JobRunContext {
+ return { drainSignal: drain.signal } as JobRunContext;
+}
+
+test("drain stops between publications and reports progress for completed records", async (t) => {
+ const f = await fixture(t); await f.add("first"); await f.add("second");
+ const p = await previewLocalMedia(f.paths, "sample");
+ const drain = new AbortController(); const statuses: string[] = [];
+ const result = await importLocalMedia(f.paths, "sample", {
+ ...selection(p), drainSignal: drain.signal,
+ onRecord: (row, completed) => { statuses.push(row.status); assert.equal(completed, 1); drain.abort(); },
+ });
+ assert.equal(result.drained, true); assert.equal(result.cancelled, false);
+ assert.deepEqual(statuses, ["imported"]);
+ assert.equal((await readdir(path.join(f.channel, "data"))).length, 1);
+});
+
+test("progress observer failure cannot reclassify a published record", async (t) => {
+ const f = await fixture(t); await f.add("first");
+ const p = await previewLocalMedia(f.paths, "sample");
+ const result = await importLocalMedia(f.paths, "sample", {
+ ...selection(p), onRecord: () => { throw new Error("display unavailable"); },
+ });
+ assert.deepEqual(result.records.map(r => r.status), ["imported"]);
+ assert.equal(result.needsIndexUpdate, true);
+});
+
+test("managed job owns its queued selection, reports progress, and declares ingest guards", async (t) => {
+ const f = await fixture(t); await f.add("first");
+ const p = await previewLocalMedia(f.paths, "sample"); const request = selection(p);
+ const job = localMediaJobOptions(f.paths as Paths, "sample", request);
+ request.selected[0].media = "changed-by-caller.mp4";
+ request.sourceToken = "changed";
+ assert.equal(job.queueKey, "channel:sample"); assert.equal(job.channelSlug, "sample");
+ assert.equal(job.spec, undefined);
+ assert.equal(getJobKind(job.kind)?.needsText, true);
+ assert.equal(getJobKind(job.kind)?.needsMedia, undefined);
+ assert.equal(getJobKind(job.kind)?.drainable, true);
+ assert.equal(getJobKind(job.kind)?.replayable, false);
+ assert.equal(isIngestKind(job.kind), true);
+ const log: string[] = []; const progress: number[] = [];
+ await job.fn(line => log.push(line), new AbortController().signal, snap => progress.push(snap.current!), jobContext());
+ assert.deepEqual(progress, [0, 1]);
+ assert.ok(log.some(line => line.includes("Imported 1")));
+ // Points at what exists today (the index build), never slice 4's button.
+ assert.ok(log.some(line => line.includes("searchable after the next index build (`pnpm ops build-index`")), log.join("\n"));
+ assert.ok(!log.some(line => line.includes("Update searchable library")));
+ assert.ok(log.every(line => !line.includes(f.source)));
+});
+
+test("managed job fails honestly for a stale selection after publishing another record", async (t) => {
+ const f = await fixture(t); await f.add("first"); await f.add("second");
+ const p = await previewLocalMedia(f.paths, "sample");
+ const job = localMediaJobOptions(f.paths as Paths, "sample", selection(p));
+ await writeFile(path.join(f.source, "second.vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nChanged\n");
+ const log: string[] = [];
+ await assert.rejects(job.fn(line => log.push(line), new AbortController().signal, () => {}, jobContext()), /require review/);
+ assert.deepEqual(await readdir(path.join(f.channel, "data")), ["first"]);
+ assert.ok(log.some(line => line.includes("Imported 1; already occupied 0; rejected 1")));
+});
+
+test("pre-start drain and cancellation write nothing; empty job request is rejected", async (t) => {
+ const f = await fixture(t); await f.add("first");
+ const p = await previewLocalMedia(f.paths, "sample");
+ const stop = new AbortController(); stop.abort();
+ const job = localMediaJobOptions(f.paths as Paths, "sample", selection(p));
+ await job.fn(() => {}, new AbortController().signal, () => {}, jobContext(stop));
+ await job.fn(() => {}, stop.signal, () => {}, jobContext());
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+ assert.throws(() => localMediaJobOptions(f.paths as Paths, "sample", {sourceToken: p.sourceToken, selected: []}), /Select between/);
+});
+
+// Review fix 7: over 1000 new recordings, "all new" takes the first 1000 in the
+// preview's (sorted) order and says how many are left, in the job's log too.
+test("selectAllNew takes the first 1000 new in order and counts the rest; the job log says so", async (t) => {
+ const candidates = Array.from({ length: 1003 }, (_, i) => ({
+ media: `r${String(i).padStart(4, "0")}.mp4`, fingerprint: `fp${i}`, status: i === 5 ? "issue" as const : "new" as const,
+ metadata: "", transcript: "", issues: [], warnings: [],
+ }));
+ const { request, remaining } = selectAllNew({ sourceToken: "t", candidates, counts: { discovered: 1003, new: 1002, existing: 0, issues: 1 } });
+ assert.equal(LOCAL_MEDIA_IMPORT_MAX, 1000);
+ assert.equal(request.selected.length, 1000);
+ assert.equal(request.selected[0].media, "r0000.mp4");
+ assert.ok(!request.selected.some((s) => s.media === "r0005.mp4"));
+ assert.equal(request.selected[999].media, "r1000.mp4");
+ assert.equal(remaining, 2);
+ assert.equal(request.remaining, 2);
+ assert.equal(selectAllNew({ sourceToken: "t", candidates: candidates.slice(0, 3), counts: { discovered: 3, new: 3, existing: 0, issues: 0 } }).request.remaining, undefined);
+
+ const f = await fixture(t); await f.add("first");
+ const p = await previewLocalMedia(f.paths, "sample");
+ const job = localMediaJobOptions(f.paths as Paths, "sample", { ...selection(p), remaining: 2 });
+ const log: string[] = [];
+ await job.fn(line => log.push(line), new AbortController().signal, () => {}, jobContext());
+ const said = log.filter(line => line.startsWith("2 more new recording(s) were not selected (one import takes at most 1000)"));
+ assert.equal(said.length, 2, log.join("\n"));
+});
diff --git a/common/controller/localMediaImport.ts b/common/controller/localMediaImport.ts
@@ -0,0 +1,287 @@
+import { localTranscriptVtt, localTranscriptFingerprint } from "../lib/localMediaTranscript";
+import { libraryLocationProblem, type LibraryLocationPaths } from "./localMediaLocation";
+import path from "node:path";
+import { createHash } from "node:crypto";
+import { prepareLocalRecordingMetadata, prepareManualLocalRecordingMetadata } from "../lib/localRecordingMetadata";
+import { probeLocalRecording } from "../lib/localRecordingProbe-server";
+import { localRecordingId, parseLocalRecordingDetails, type LocalRecordingDetails } from "../lib/localRecordingDetails";
+import { lstat, mkdir, readdir, realpath } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { channelConfigSchema } from "../lib/channelConfigSchema";
+import { readJsonFile } from "../lib/jsonFile-server";
+import { assertChannelTextReadable, readRelocationMarker } from "../lib/channelMedia";
+import { onDrive, stalledLocationForPath } from "../lib/storageHealth";
+import { scanLocalMedia, localMediaFingerprint, readLocalMediaText, type LocalMediaScan } from "../lib/localMediaScan";
+import { openExternalMedia } from "../lib/externalMediaResolver-server";
+import { commitLocalMediaRecord, type LocalMediaCommitResult } from "../lib/localMediaCommit-server";
+
+type ImportPaths = Pick<Paths, "channelsDir"> & Partial<Pick<Paths, "ffprobeBin">>;
+export type LocalMediaPreview = LocalMediaScan & { sourceToken: string };
+export type LocalMediaSelection = { media: string; fingerprint: string;
+ preparation?: { sourceFingerprint: string; details: LocalRecordingDetails };
+};
+export type LocalMediaImportResult = {
+ records: Array<{ media: string; status: "imported" | "occupied" | "failed" | "stale" | "issue"; reason?: string; incomplete?: boolean; warnings?: string[]; stagingCleanupFailed?: boolean }>;
+ cancelled: boolean;
+ drained: boolean;
+ needsIndexUpdate: boolean;
+};
+function inside(root: string, item: string) {
+ const rel = path.relative(root, item);
+ return !rel || rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
+}
+async function optionalStat(file: string) {
+ try { return await lstat(file); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
+}
+async function context(paths: ImportPaths, slug: string) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) || slug.endsWith(".")) throw new Error("Invalid channel slug");
+ const channel = path.join(paths.channelsDir, slug);
+ const channelInfo = await lstat(channel);
+ if (!channelInfo.isDirectory() || channelInfo.isSymbolicLink()) throw new Error("Channel must be a real directory");
+ const raw = await readJsonFile(path.join(channel, "config.json"));
+ const config = raw.ok ? channelConfigSchema.parse(raw.value) : null;
+ if (!config || config.sourceKind === "social" || !config.localMedia) throw new Error("Video channel has no valid local media source");
+ await assertChannelTextReadable(paths, slug, config);
+ // Imports are writers: conservatively refuse any relocation, even a media-only
+ // move that leaves text readable. Job integration must also declare its needs.
+ if (await readRelocationMarker(paths, slug)) throw new Error("Channel relocation is in progress");
+ if (!path.isAbsolute(config.localMedia.directory)) throw new Error("Source path is not absolute on this server");
+ if (stalledLocationForPath(config.localMedia.directory)) throw new Error("Source drive is not answering");
+ const source = await onDrive(config.localMedia.directory, () => realpath(config.localMedia!.directory));
+ // Also at use: a config can arrive by hand or by `pnpm ops channel-config`.
+ const misplaced = await libraryLocationProblem(paths as LibraryLocationPaths, source);
+ if (misplaced) throw new Error(misplaced);
+ const canonicalChannel = await realpath(channel);
+ // Never write corpus records into the external library, or scan corpus files
+ // as an external library. Compare canonical paths in BOTH directions.
+ if (inside(source, canonicalChannel) || inside(canonicalChannel, source)) throw new Error("Source and channel directories overlap");
+ const data = path.join(canonicalChannel, "data");
+ const dataInfo = await optionalStat(data);
+ if (dataInfo && (!dataInfo.isDirectory() || dataInfo.isSymbolicLink())) throw new Error("Channel data must be a real directory");
+ const sourceToken = createHash("sha256").update(JSON.stringify([config.localMedia, source, canonicalChannel])).digest("hex");
+ return { source, data, config: config.localMedia, sourceToken };
+}
+
+// No writes. Read config fresh and apply existing channel guards before walking
+// data/. An absent data directory is a new channel; other read errors propagate.
+export async function previewLocalMedia(paths: ImportPaths, slug: string): Promise<LocalMediaPreview> {
+ const c = await context(paths, slug);
+ const entries = await optionalStat(c.data) ? await readdir(c.data) : [];
+ const scan = await onDrive(c.source, () => scanLocalMedia({ sourceDirectory: c.source, existingDirectoryIds: entries }));
+ for (const row of scan.candidates) {
+ // A recording without provider metadata has the same reserved identity
+ // before and after subtitle generation. Never offer generation over an
+ // existing local record, even if that record is incomplete.
+ if (row.transcriptionNeedsDetails && entries.includes(localRecordingId(slug, c.config.sourceId, row.media))) {
+ row.generatedMetadata = true;
+ row.directoryId = localRecordingId(slug, c.config.sourceId, row.media);
+ row.recordId = row.directoryId;
+ row.status = "existing";
+ row.issues = [];
+ row.warnings.push("A local recording destination already exists; saved files were left unchanged, not reverified");
+ delete row.transcriptionFingerprint;
+ delete row.transcriptionNeedsDetails;
+ }
+ if (row.preparationFingerprint) {
+ row.generatedMetadata = true;
+ row.directoryId = localRecordingId(slug, c.config.sourceId, row.media);
+ row.recordId = row.directoryId;
+ if (entries.includes(row.directoryId)) {
+ // A generated record is reserved by library/name, so rescanning or a
+ // changed file cannot silently create another identity or overwrite it.
+ row.issues = [];
+ row.warnings.push("A local recording destination already exists; saved files were left unchanged, not reverified");
+ row.status = "existing";
+ delete row.preparationFingerprint;
+ }
+ }
+ if (!row.directoryId || !entries.includes(row.directoryId)) continue;
+ const dir = path.join(c.data, row.directoryId);
+ const info = await lstat(dir);
+ const metadata = info.isDirectory() && !info.isSymbolicLink() ? await optionalStat(path.join(dir, "metadata.info.json")) : null;
+ if (!metadata?.isFile() || metadata.isSymbolicLink()) {
+ row.issues.push("Destination is occupied or incomplete; manual review required"); row.status = "issue";
+ } else { row.savedRecordAvailable = true; }
+ }
+ scan.counts = { discovered: scan.candidates.length, new: 0, existing: 0, issues: 0 };
+ for (const row of scan.candidates) {
+ if (row.status === "issue") scan.counts.issues++; else scan.counts[row.status]++;
+ }
+ const after = await context(paths, slug);
+ if (after.sourceToken !== c.sourceToken) throw new Error("Source configuration changed during preview; rescan");
+ return { ...scan, sourceToken: c.sourceToken };
+}
+
+// Application service, intentionally independent of React. Caller selects only
+// media names + freshness tokens returned by preview. Roots/IDs are derived
+// from stored config and fresh scanning, never accepted from request paths.
+// The eventual managed-job wrapper must provide per-channel queueing and block
+// concurrent rename/delete/config edits. Directory reservation still protects
+// against two import calls racing to publish the same new record.
+export async function importLocalMedia(paths: ImportPaths, slug: string, request: {
+ sourceToken: string; selected: readonly LocalMediaSelection[]; signal?: AbortSignal;
+ // Drain finishes the current publication; cancellation may leave a reviewable
+ // partial record. Progress observers cannot change the outcome of a write.
+ drainSignal?: AbortSignal;
+ onRecord?: (record: LocalMediaImportResult["records"][number], completed: number) => void;
+}): Promise<LocalMediaImportResult> {
+ if (!Array.isArray(request.selected) || request.selected.length > 1000
+ || request.selected.some(s => !s || typeof s.media !== "string" || typeof s.fingerprint !== "string")
+ || new Set(request.selected.map(s => s.media)).size !== request.selected.length) {
+ throw new Error("Invalid or duplicate selection");
+ }
+ const out: LocalMediaImportResult = { records: [], cancelled: false, drained: false, needsIndexUpdate: false };
+ const record = (item: LocalMediaImportResult["records"][number]) => {
+ out.records.push(item);
+ // A failed progress display must never turn a successfully published record
+ // into a failed import or cause a second attempt to publish it.
+ try { request.onRecord?.(item, out.records.length); } catch { /* observer only */ }
+ };
+ if (request.signal?.aborted) return { ...out, cancelled: true };
+ if (request.drainSignal?.aborted) return { ...out, drained: true };
+ const preview = await previewLocalMedia(paths, slug);
+ if (preview.sourceToken !== request.sourceToken) throw new Error("Source configuration changed; rescan before importing");
+ for (const selection of request.selected) {
+ if (request.signal?.aborted) { out.cancelled = true; break; }
+ if (request.drainSignal?.aborted) { out.drained = true; break; }
+ const row = preview.candidates.find(candidate => candidate.media === selection.media);
+ if (selection.preparation) {
+ if (row?.status === "existing" && row.generatedMetadata) {
+ record({media: row.media, status: "occupied", reason: "Existing local record left unchanged"}); continue;
+ }
+ try {
+ const prepared = await preparedBytes(paths, slug, {
+ sourceToken: request.sourceToken, media: selection.media,
+ sourceFingerprint: selection.preparation.sourceFingerprint,
+ details: selection.preparation.details,
+ }, request.signal);
+ if (prepared.fingerprint !== selection.fingerprint) throw new Error("Reviewed details changed; prepare again");
+ const current = await context(paths, slug);
+ if (current.sourceToken !== request.sourceToken) throw new Error("Source configuration changed");
+ request.signal?.throwIfAborted();
+ await mkdir(current.data, {recursive: false}).catch(error => {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ });
+ const committed = await commitLocalMediaRecord({dataDirectory: current.data,
+ directoryId: prepared.metadata.id, metadata: JSON.stringify(prepared.metadata),
+ transcript: prepared.transcript, reference: prepared.reference, signal: request.signal});
+ if (committed.status === "imported") out.needsIndexUpdate = true;
+ record({media: selection.media, ...committed, warnings: row?.warnings});
+ } catch {
+ record({media: selection.media, status: "failed", reason: request.signal?.aborted
+ ? "cancelled" : "Prepared recording changed or is unavailable; preview and prepare again"});
+ }
+ continue;
+ }
+ if (!row || row.fingerprint !== selection.fingerprint) {
+ record({ media: selection.media, status: "stale", reason: "Source changed or disappeared; rescan" }); continue;
+ }
+ if (row.status === "issue") {
+ record({ media: row.media, status: "issue", reason: row.issues.join("; ") }); continue;
+ }
+ if (row.status === "existing") {
+ record({ media: row.media, status: "occupied", reason: "Existing record left unchanged" }); continue;
+ }
+ try {
+ const c = await context(paths, slug);
+ if (c.sourceToken !== request.sourceToken) throw new Error("Source configuration changed; rescan");
+ const reference = { version: 1, kind: "external", sourceId: c.config.sourceId, relativePath: row.media };
+ // No writes occur in the watchdog's closure: if it times out, a late
+ // operation may still finish. Its handle always closes inside the closure,
+ // so a timeout cannot leak a descriptor or later publish a record.
+ const bytes = await onDrive(c.source, async () => {
+ const opened = await openExternalMedia({ config: c.config, reference, purpose: "inspect" });
+ if (opened.status !== "ready") throw new Error("Source media unavailable or refused");
+ try {
+ const before = await opened.handle.stat();
+ const metadata = await readLocalMediaText(c.source, row.metadata);
+ const transcript = await readLocalMediaText(c.source, row.transcript);
+ const after = await opened.handle.stat();
+ if (localMediaFingerprint(row.media, metadata, localTranscriptFingerprint(row.transcript, transcript), before) !== selection.fingerprint
+ || localMediaFingerprint(row.media, metadata, localTranscriptFingerprint(row.transcript, transcript), after) !== selection.fingerprint) {
+ throw new Error("Source changed after preview; rescan");
+ }
+ return { metadata, transcript: localTranscriptVtt(row.transcript, transcript) };
+ } finally { await opened.handle.close(); }
+ });
+ request.signal?.throwIfAborted();
+ const current = await context(paths, slug);
+ if (current.sourceToken !== request.sourceToken) throw new Error("Source configuration changed; rescan");
+ await mkdir(current.data, { recursive: false }).catch(error => {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ });
+ const committed: LocalMediaCommitResult = await commitLocalMediaRecord({
+ dataDirectory: current.data, directoryId: row.directoryId!, ...bytes, reference, signal: request.signal,
+ });
+ if (committed.status === "imported") out.needsIndexUpdate = true;
+ record({ media: row.media, ...committed, warnings: row.warnings });
+ } catch (error) {
+ record({ media: row.media, status: "failed", reason: request.signal?.aborted ? "cancelled" : "Import refused; rescan and check source/channel availability" });
+ }
+ }
+ out.cancelled = request.signal?.aborted === true;
+ return out;
+}
+
+export type LocalRecordingPreparationRequest = {
+ sourceToken: string; media: string; sourceFingerprint: string; details: LocalRecordingDetails;
+};
+
+// Read-only preparation. The returned review is not a stored draft or a grant
+// to serve media. Import repeats inspection and all source checks in its normal
+// channel job, and compares the reviewed facts before committing any text.
+async function preparedBytes(paths: ImportPaths, slug: string,
+ request: LocalRecordingPreparationRequest, signal?: AbortSignal) {
+ if (!request || typeof request.sourceToken !== "string" || typeof request.media !== "string"
+ || typeof request.sourceFingerprint !== "string") throw new Error("Invalid preparation request");
+ const details = parseLocalRecordingDetails(request.details);
+ signal?.throwIfAborted();
+ const preview = await previewLocalMedia(paths, slug);
+ const row = preview.candidates.find(item => item.media === request.media);
+ if (preview.sourceToken !== request.sourceToken || !row?.preparationFingerprint
+ || row.preparationFingerprint !== request.sourceFingerprint) throw new Error("Recording is no longer eligible; preview again");
+ const c = await context(paths, slug);
+ if (c.sourceToken !== request.sourceToken) throw new Error("Library configuration changed");
+ const reference = {version: 1 as const, kind: "external" as const, sourceId: c.config.sourceId, relativePath: row.media};
+ const result = await onDrive(c.source, async () => {
+ const opened = await openExternalMedia({config: c.config, reference, purpose: "inspect"});
+ if (opened.status !== "ready") throw new Error("Recording unavailable");
+ try {
+ const before = await opened.handle.stat();
+ if (await optionalStat(path.join(c.source, row.metadata))) throw new Error("Metadata appeared; preview again");
+ const transcript = await readLocalMediaText(c.source, row.transcript);
+ if (localMediaFingerprint(row.media, "", localTranscriptFingerprint(row.transcript, transcript), before) !== request.sourceFingerprint) throw new Error("Source changed");
+ const input = {id: localRecordingId(slug, c.config.sourceId, row.media), filename: row.media,
+ title: details.title, recordedDate: details.recordedDate};
+ // Only server configuration chooses the executable. Inspection failure
+ // never silently turns into manual preparation.
+ const metadata = details.mode === "inspect"
+ ? prepareLocalRecordingMetadata({...input, probe: await probeLocalRecording({
+ file: path.join(c.source, row.media), ffprobeBin: paths.ffprobeBin ?? "ffprobe", signal})})
+ : prepareManualLocalRecordingMetadata({...input, durationSeconds: details.durationSeconds, fileSizeBytes: before.size});
+ const after = await opened.handle.stat();
+ const named = await lstat(path.join(c.source, row.media));
+ const currentTranscript = await readLocalMediaText(c.source, row.transcript);
+ if (!named.isFile() || named.isSymbolicLink()
+ || localMediaFingerprint(row.media, "", localTranscriptFingerprint(row.transcript, currentTranscript), after) !== request.sourceFingerprint
+ || localMediaFingerprint(row.media, "", localTranscriptFingerprint(row.transcript, currentTranscript), named) !== request.sourceFingerprint
+ || await optionalStat(path.join(c.source, row.metadata))) throw new Error("Source changed during preparation");
+ return {metadata, transcript: localTranscriptVtt(row.transcript, transcript), reference,
+ fingerprint: localMediaFingerprint(row.media, JSON.stringify(metadata), localTranscriptFingerprint(row.transcript, transcript), after)};
+ } finally { await opened.handle.close(); }
+ });
+ signal?.throwIfAborted();
+ const current = await context(paths, slug);
+ if (current.sourceToken !== request.sourceToken || await optionalStat(path.join(current.data, result.metadata.id))) {
+ throw new Error("Library changed or recording already occupied; preview again");
+ }
+ return result;
+}
+
+export async function prepareLocalMediaRecording(paths: ImportPaths, slug: string,
+ request: LocalRecordingPreparationRequest) {
+ const result = await preparedBytes(paths, slug, request);
+ // Never return archive paths or the whole transcript to the form.
+ return {metadata: result.metadata, fingerprint: result.fingerprint};
+}
diff --git a/common/controller/localMediaImportJob.ts b/common/controller/localMediaImportJob.ts
@@ -0,0 +1,96 @@
+import { parseLocalRecordingDetails } from "../lib/localRecordingDetails";
+import type { Paths } from "../lib/paths";
+import { channelQueueKey } from "../lib/queueKeys";
+import { importLocalMedia, type LocalMediaPreview, type LocalMediaSelection } from "./localMediaImport";
+import { runManagedFunction, type RunManagedFunctionOpts } from "../jobs/streamCommand";
+
+export type LocalMediaJobRequest = {
+ sourceToken: string;
+ selected: readonly LocalMediaSelection[];
+ // New recordings left for a later run (selectAllNew): said in the job's log.
+ remaining?: number;
+};
+
+// One job imports at most this many recordings.
+export const LOCAL_MEDIA_IMPORT_MAX = 1000;
+
+// EVERY NEW RECORDING of a fresh preview, at most LOCAL_MEDIA_IMPORT_MAX of them:
+// the first in the preview's order (the scan's sorted file names, so a re-run
+// after an import takes the next ones), and how many new ones are left over.
+// Review fix 7 (lane/local-media): over the cap it was a generic refusal.
+export function selectAllNew(preview: LocalMediaPreview): { request: LocalMediaJobRequest; remaining: number } {
+ const all = preview.candidates
+ .filter((c) => c.status === "new" && c.fingerprint)
+ .map((c) => ({ media: c.media, fingerprint: c.fingerprint! }));
+ const selected = all.slice(0, LOCAL_MEDIA_IMPORT_MAX);
+ const remaining = all.length - selected.length;
+ return { request: { sourceToken: preview.sourceToken, selected, ...(remaining > 0 ? { remaining } : {}) }, remaining };
+}
+
+// Keep the managed job's body testable with synthetic sources, without starting
+// the application's registry or snapshot timers. The production entry point
+// below always uses runManagedFunction, including its enqueue/start guards.
+export function localMediaJobOptions(paths: Paths, slug: string, request: LocalMediaJobRequest): RunManagedFunctionOpts {
+ if (!request || typeof request.sourceToken !== "string" || !Array.isArray(request.selected)
+ || request.selected.length === 0 || request.selected.length > LOCAL_MEDIA_IMPORT_MAX
+ || request.selected.some(s => !s || typeof s.media !== "string" || typeof s.fingerprint !== "string")
+ || new Set(request.selected.map(s => s.media)).size !== request.selected.length) {
+ throw new Error("Select between 1 and 1000 distinct recordings from a fresh preview");
+ }
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) || slug.endsWith(".")) throw new Error("Invalid channel slug");
+ // A caller must not be able to mutate a request while it waits in the queue.
+ const selected = request.selected.map(({ media, fingerprint, preparation }) => {
+ if (preparation !== undefined && (!preparation || typeof preparation.sourceFingerprint !== "string")) {
+ throw new Error("Invalid recording preparation");
+ }
+ return {media, fingerprint, ...(preparation ? {preparation: {
+ sourceFingerprint: preparation.sourceFingerprint, details: parseLocalRecordingDetails(preparation.details),
+ }} : {})};
+ });
+ const sourceToken = request.sourceToken;
+ const remaining = typeof request.remaining === "number" && Number.isSafeInteger(request.remaining) && request.remaining > 0
+ ? request.remaining : 0;
+ const leftOverLine = remaining
+ ? `${remaining} more new recording(s) were not selected (one import takes at most ${LOCAL_MEDIA_IMPORT_MAX}); import again after this one to take the next ${Math.min(remaining, LOCAL_MEDIA_IMPORT_MAX)}.`
+ : null;
+ return {
+ kind: "import-local-media",
+ queueKey: channelQueueKey(slug),
+ paths,
+ channelSlug: slug,
+ // No spec: replaying persisted names/tokens after source edits is misleading.
+ // The operator takes a new preview to retry or continue a drained batch.
+ fn: async (onLog, signal, setProgress, ctx) => {
+ setProgress({ metric: "entries", initial: 0, target: selected.length, current: 0 });
+ if (leftOverLine) onLog(leftOverLine);
+ onLog("Rechecking selected external recordings before import...");
+ const result = await importLocalMedia(paths, slug, {
+ sourceToken, selected, signal, drainSignal: ctx.drainSignal,
+ onRecord: (record, completed) => {
+ // JSON quoting prevents filenames with newlines from forging log lines.
+ // Absolute library roots never enter these progress messages.
+ onLog(JSON.stringify({ recording: record.media, status: record.status, reason: record.reason, warnings: record.warnings, incomplete: record.incomplete }));
+ setProgress({ metric: "entries", initial: 0, target: selected.length, current: completed });
+ },
+ });
+ const imported = result.records.filter(r => r.status === "imported").length;
+ const occupied = result.records.filter(r => r.status === "occupied").length;
+ const rejected = result.records.length - imported - occupied;
+ onLog(`Imported ${imported}; already occupied ${occupied}; rejected ${rejected}; unprocessed ${selected.length - result.records.length}.`);
+ if (leftOverLine) onLog(leftOverLine);
+ // What works today: the records are searchable after the next index build.
+ if (result.needsIndexUpdate) onLog("Import complete. The imported recordings are searchable after the next index build (`pnpm ops build-index`, or a site build).");
+ // The existing managed-job completion hook requests a channel snapshot,
+ // including on failure/cancellation. This job does not build/publish a site.
+ if (result.cancelled) { onLog("Import cancelled."); return; }
+ if (result.drained) onLog("Import stopped between recordings. Preview again to continue.");
+ if (rejected || result.records.some(r => r.stagingCleanupFailed)) {
+ throw new Error("Some selected recordings require review. Saved records were retained; preview again before retrying.");
+ }
+ },
+ };
+}
+
+export async function startLocalMediaImportJob(paths: Paths, slug: string, request: LocalMediaJobRequest) {
+ return runManagedFunction(localMediaJobOptions(paths, slug, request));
+}
diff --git a/common/controller/localMediaLifecycle.test.ts b/common/controller/localMediaLifecycle.test.ts
@@ -0,0 +1,123 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { createHash } from "node:crypto";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
+import { execa } from "execa";
+import type { Paths } from "../lib/paths";
+import { commitLocalMediaRecord } from "../lib/localMediaCommit-server";
+import { loadExternalMediaReference } from "../lib/externalMedia-server";
+import { deleteChannel } from "./channels";
+import { cleanExtraAudioFormats } from "./cleanExtraAudioFormats";
+import { archiveTranscripts, archiveCombinedTranscripts } from "./archiveTranscripts";
+
+// Real controllers, real ZIP files, synthetic external bytes. A private marker
+// in config/reference/metadata makes accidental whole-folder export observable.
+// The original media has no corpus symlink and no saved-video managed pointer.
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "external-lifecycle-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const source = path.join(root, "private-source-directory");
+ const corpus = path.join(root, "corpus");
+ const paths = {
+ transcriptsDir: corpus, channelsDir: path.join(corpus, "channels"),
+ savedVideosDir: path.join(corpus, "saved"), sitesDir: path.join(corpus, "sites"),
+ lmdbPath: path.join(corpus, "index.mdb"),
+ } as Paths;
+ const data = path.join(paths.channelsDir, "sample", "data");
+ await mkdir(data, { recursive: true }); await mkdir(source);
+ const media = "private-filename-sentinel.mp4";
+ const sourceId = "private-library-sentinel";
+ const reference = {version:1 as const,kind:"external" as const,sourceId,relativePath:media};
+ const transcript = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nPublic transcript cue\n";
+ const metadata = JSON.stringify({id:"record1",title:"Public title",duration:3,upload_date:"20261030",webpage_url:"https://www.youtube.com/watch?v=record1",_filename:path.join(source,media)});
+ await writeFile(path.join(source,media),"original external media sentinel");
+ await writeFile(path.join(source,"original.vtt"),transcript);
+ await writeFile(path.join(source,"original.info.json"),metadata);
+ await writeFile(path.join(paths.channelsDir,"sample","config.json"),JSON.stringify({handling:"youtube",platform:"youtube",name:"Public channel",audioFormat:"mp3",localMedia:{sourceId,directory:source}}));
+ assert.equal((await commitLocalMediaRecord({dataDirectory:data,directoryId:"record1",metadata,transcript,reference})).status,"imported");
+ const video = path.join(data,"record1");
+ async function hashes() {
+ const result:Record<string,string>={};
+ for(const name of (await readdir(source)).sort()) result[name]=createHash("sha256").update(await readFile(path.join(source,name))).digest("hex");
+ return result;
+ }
+ return {root,paths,source,sourceId,media,video,reference,hashes,before:await hashes()};
+}
+
+async function inspectZip(archive: string) {
+ const listing = await execa("unzip",["-Z1",archive]);
+ const files=listing.stdout.split(/\r?\n/).filter(name=>name && !name.endsWith("/"));
+ const entries:Record<string,string>={};
+ for(const name of files) entries[name]=(await execa("unzip",["-p",archive,name])).stdout;
+ return entries;
+}
+
+for(const includeMetadata of [true,false]) {
+ test(`per-channel ZIP excludes private source/reference fields (metadata=${includeMetadata})`,async t=>{
+ const f=await fixture(t);
+ const result=await archiveTranscripts({paths:f.paths,channelSlugs:["sample"],build:{format:"zip",includeMetadata},onLog:()=>{}});
+ assert.equal(result.totalTranscripts,1,JSON.stringify(result.skipped));
+ assert.equal(result.archives.length,1);
+ const entries=await inspectZip(result.archives[0].archivePath);
+ assert.deepEqual(Object.keys(entries).sort(),["sample/channel.json","sample/record1/transcript.cues.json"]);
+ const text=JSON.stringify(entries);
+ for(const secret of [f.source,f.sourceId,f.media,"external-media.json","localMedia","_filename","original external media sentinel"]) assert.equal(text.includes(secret),false,secret);
+ assert.match(entries["sample/record1/transcript.cues.json"],/Public transcript cue/);
+ assert.equal(JSON.parse(entries["sample/channel.json"]).name,"Public channel");
+ assert.deepEqual(await loadExternalMediaReference(f.video),f.reference);
+ assert.deepEqual(await f.hashes(),f.before);
+ });
+}
+
+test("combined ZIP exposes only public manifest and transcript entries",async t=>{
+ const f=await fixture(t);
+ const result=await archiveCombinedTranscripts({paths:f.paths,channelSlugs:["sample"],build:{format:"zip"},onLog:()=>{}});
+ assert.equal(result.totalTranscripts,1,JSON.stringify(result.skipped));
+ assert.ok(result.archivePath);
+ const entries=await inspectZip(result.archivePath);
+ assert.deepEqual(Object.keys(entries).sort(),["manifest.json","sample/channel.json","sample/record1/transcript.cues.json"]);
+ const text=JSON.stringify(entries);
+ for(const secret of [f.source,f.sourceId,f.media,"external-media.json","localMedia","_filename"]) assert.equal(text.includes(secret),false,secret);
+ assert.match(text,/Public transcript cue/);
+ assert.deepEqual(await f.hashes(),f.before);
+});
+
+test("extra-audio cleanup removes managed audio without touching external files or reference",async t=>{
+ const f=await fixture(t);
+ await writeFile(path.join(f.video,"audio.mp3"),"kept managed audio");
+ await writeFile(path.join(f.video,"audio.wav"),"redundant managed audio");
+ const result=await cleanExtraAudioFormats({paths:f.paths,channelSlug:"sample",onLog:()=>{}});
+ assert.equal(result.removedFiles,1);
+ assert.equal((await readdir(f.video)).includes("audio.wav"),false);
+ assert.equal(await readFile(path.join(f.video,"audio.mp3"),"utf8"),"kept managed audio");
+ assert.deepEqual(await loadExternalMediaReference(f.video),f.reference);
+ assert.deepEqual(await f.hashes(),f.before);
+});
+
+test("deleting a channel removes corpus references but preserves external source files",async t=>{
+ const f=await fixture(t);
+ await deleteChannel(f.paths,"sample");
+ assert.deepEqual(await readdir(f.paths.channelsDir),[]);
+ assert.deepEqual(await f.hashes(),f.before);
+});
+
+// Review fix 3: a local recording is in no archive zip in slice 1 (the zip is
+// a published download, cached once per channel across public and private sites).
+test("a local recording is left out of the channel's archive zip, and the log says so",async t=>{
+ const f=await fixture(t);
+ const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata");
+ const id="local-"+"9".repeat(32);
+ const data=path.join(f.paths.channelsDir,"sample","data");
+ assert.equal((await commitLocalMediaRecord({dataDirectory:data,directoryId:id,
+ metadata:JSON.stringify(prepareManualLocalRecordingMetadata({id,filename:"talk.mp4"})),
+ transcript:"WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nLocal only cue\n",
+ reference:{version:1,kind:"external",sourceId:f.sourceId,relativePath:"talk.mp4"}})).status,"imported");
+ const logs:string[]=[];
+ const result=await archiveTranscripts({paths:f.paths,channelSlugs:["sample"],build:{format:"zip",includeMetadata:true},onLog:l=>logs.push(l)});
+ const entries=await inspectZip(result.archives[0].archivePath);
+ assert.deepEqual(Object.keys(entries).sort(),["sample/channel.json","sample/record1/transcript.cues.json"]);
+ assert.equal(JSON.stringify(entries).includes("Local only cue"),false);
+ assert.ok(logs.some(l=>l.includes("1 local recording(s) left out of the zip")),logs.join("\n"));
+});
diff --git a/common/controller/localMediaLocation.test.ts b/common/controller/localMediaLocation.test.ts
@@ -0,0 +1,96 @@
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Review fix 2 (lane/local-media): a library may not lie inside the corpus, a
+// saved-video store, a channel's media tier, a storage location, or the
+// checkout. One sentence each, at configure time and at use (preview).
+// Synthetic dirs; nothing outside the temp root is touched.
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "local-media-location-"));
+const T = path.join(ROOT, "transcripts");
+const DRIVE = path.join(ROOT, "drive");
+const STORE = path.join(ROOT, "saved-videos");
+const OWN_STORE = path.join(ROOT, "own-store");
+const MEDIA = path.join(DRIVE, "media-tier", "other", "media");
+const LOCATION = path.join(ROOT, "cold");
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: T,
+ SAVED_VIDEOS_DIR: STORE,
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+});
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+writeFileSync(path.join(ROOT, "settings.json"), JSON.stringify({
+ storage: { locations: [{ id: "cold", label: "Cold drive", root: LOCATION, autoRepoint: false }], defaultLocationId: "cold" },
+}));
+const json = (file: string, value: unknown) => { mkdirSync(path.dirname(file), { recursive: true }); writeFileSync(file, JSON.stringify(value)); };
+json(path.join(T, "channels", "sample", "config.json"), { handling: "youtube", name: "Sample" });
+json(path.join(T, "channels", "other", "config.json"), { handling: "youtube", name: "Other", mediaDir: MEDIA, savedVideosDir: OWN_STORE });
+for (const d of [MEDIA, STORE, OWN_STORE, LOCATION, path.join(ROOT, "fine")]) mkdirSync(path.join(d, "lib"), { recursive: true });
+mkdirSync(path.join(T, "channels", "other", "data", "x", "lib"), { recursive: true });
+mkdirSync(path.join(T, "loose", "lib"), { recursive: true });
+
+const { getPaths } = await import("../lib/paths");
+const { libraryLocationProblem } = await import("./localMediaLocation");
+const { configureLocalMedia } = await import("./configureLocalMedia");
+const { previewLocalMedia } = await import("./localMediaImport");
+const paths = getPaths();
+
+test("each owned tree is refused with a sentence naming it; a directory outside all of them is fine", async () => {
+ const cases: Array<[string, RegExp]> = [
+ [path.join(MEDIA, "lib"), /inside channel "other"'s media directory/],
+ [path.join(OWN_STORE, "lib"), /inside channel "other"'s saved-video store/],
+ [path.join(STORE, "lib"), /inside the saved-video store/],
+ [path.join(T, "channels", "other", "data", "x", "lib"), /inside the corpus/],
+ [path.join(T, "loose", "lib"), /inside the corpus/],
+ [path.join(LOCATION, "lib"), /inside storage location "Cold drive"/],
+ [path.join(paths.monorepoRoot, "editor"), /inside the Archilyzer checkout/],
+ ];
+ for (const [dir, re] of cases) {
+ const problem = await libraryLocationProblem(paths, dir);
+ assert.ok(problem, dir);
+ assert.match(problem!, re);
+ assert.match(problem!, /; choose a directory outside it\.$/);
+ }
+ assert.equal(await libraryLocationProblem(paths, path.join(ROOT, "fine", "lib")), null);
+});
+
+test("configure refuses a misplaced library and leaves the config as it was", async () => {
+ const before = readFileSync(path.join(T, "channels", "sample", "config.json"), "utf8");
+ await assert.rejects(configureLocalMedia(paths, "sample", { sourceId: "library-1", directory: path.join(LOCATION, "lib") }),
+ /inside storage location "Cold drive"/);
+ assert.equal(readFileSync(path.join(T, "channels", "sample", "config.json"), "utf8"), before);
+});
+
+test("a misplaced library written into the config by hand is refused at preview", async () => {
+ json(path.join(T, "channels", "sample", "config.json"), { handling: "youtube", name: "Sample",
+ localMedia: { sourceId: "library-1", directory: path.join(STORE, "lib") } });
+ await assert.rejects(previewLocalMedia(paths, "sample"), /inside the saved-video store/);
+});
+
+// Re-review F1: a library that CONTAINS an owned tree is refused too.
+test("a library containing a channel's media dir, the store, a storage location or the checkout is refused", async () => {
+ const cases: Array<[string, RegExp]> = [
+ [path.join(DRIVE, "media-tier"), /contains channel "other"'s media directory/],
+ [ROOT, /contains channel "other"'s media directory/],
+ [path.dirname(paths.monorepoRoot), /contains the Archilyzer checkout/],
+ ];
+ for (const [dir, re] of cases) {
+ const problem = await libraryLocationProblem(paths, dir);
+ assert.ok(problem, dir);
+ assert.match(problem!, re);
+ assert.match(problem!, /; choose a directory that does not\.$/);
+ }
+ const { mkdirSync } = await import("node:fs");
+ const holder = path.join(ROOT, "holder");
+ mkdirSync(holder, { recursive: true });
+ const only = (root: string, what: RegExp) =>
+ libraryLocationProblem({ channelsDir: "/nonexistent-archilyzer-test/channels", savedVideosDir: root }, path.dirname(root), { channels: [] })
+ .then((p) => assert.match(p ?? "", what));
+ await only(path.join(holder, "store"), /contains the saved-video store/);
+ assert.match(await libraryLocationProblem({ channelsDir: "/nonexistent-archilyzer-test/channels" }, path.dirname(LOCATION), { channels: [] }) ?? "",
+ /contains storage location "Cold drive"/);
+});
diff --git a/common/controller/localMediaLocation.ts b/common/controller/localMediaLocation.ts
@@ -0,0 +1,75 @@
+import path from "node:path";
+import { realpath } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import { listChannelConfigs } from "./channels";
+
+// WHERE A LOCAL MEDIA LIBRARY MAY NOT LIVE (lane/local-media review fix 2).
+//
+// A library is a directory of recordings the archive does not own: never
+// written, moved or deleted by it. So it may not lie inside anything the
+// archive DOES own or manage — the corpus (every channel's text and its
+// in-place media), the saved-video store (the global one and a channel's own
+// `savedVideosDir`), a channel's media tier (`mediaDir`, on another drive), a
+// configured storage location (whose tree a relocation rewrites), or the
+// Archilyzer checkout — nor contain one. One sentence for each, naming it.
+//
+// Checked where the library is configured (configureLocalMedia, the New
+// channel form) AND where it is used (the import's context), since a config
+// can also arrive by hand or by `pnpm ops channel-config`. Every root is
+// optional: a caller holding only `channelsDir` gets the checks it can make.
+
+export type LibraryLocationPaths = Pick<Paths, "channelsDir"> &
+ Partial<Pick<Paths, "transcriptsDir" | "savedVideosDir" | "monorepoRoot">>;
+
+function inside(root: string, candidate: string): boolean {
+ const rel = path.relative(root, candidate);
+ return !rel || (rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
+}
+
+// The canonical form of a root: realpath when it exists (a symlinked drive
+// resolves to where its files are), else as written.
+async function canonical(dir: string): Promise<string> {
+ return realpath(dir).catch(() => path.resolve(dir));
+}
+
+/**
+ * Why `directory` may not be a library, or null. `directory` should already be
+ * canonical (realpath) — it is compared against canonical roots.
+ */
+export async function libraryLocationProblem(
+ paths: LibraryLocationPaths,
+ directory: string,
+ opts: { channels?: Array<{ slug: string; config: { mediaDir?: string; savedVideosDir?: string } }> } = {},
+): Promise<string | null> {
+ const lib = path.resolve(directory);
+ const channels = opts.channels ?? (await listChannelConfigs(paths as Paths).catch(() => []));
+ // What the archive owns, most specific first, so a sentence names the
+ // narrowest owner.
+ const owned: Array<{ what: string; root: string }> = [];
+ for (const { slug, config } of channels) {
+ if (config.mediaDir) owned.push({ what: `channel "${slug}"'s media directory`, root: await canonical(config.mediaDir) });
+ if (config.savedVideosDir) owned.push({ what: `channel "${slug}"'s saved-video store`, root: await canonical(config.savedVideosDir) });
+ }
+ if (paths.savedVideosDir) owned.push({ what: "the saved-video store", root: await canonical(paths.savedVideosDir) });
+ // The corpus root when known (getPaths() always has it); a caller holding
+ // only `channelsDir` gets that tree checked.
+ owned.push({ what: "the corpus", root: await canonical(paths.transcriptsDir ?? paths.channelsDir) });
+ let locations: Array<{ label: string; root: string }> = [];
+ try { locations = getSettings().storage?.locations ?? []; } catch { /* no settings: no locations */ }
+ for (const location of locations) {
+ if (location.root) owned.push({ what: `storage location "${location.label}"`, root: await canonical(location.root) });
+ }
+ if (paths.monorepoRoot) owned.push({ what: "the Archilyzer checkout", root: await canonical(paths.monorepoRoot) });
+ // Inside an owned tree: the scan would read the archive's own files as
+ // recordings, and a move or a clean could change them under the library.
+ for (const { what, root } of owned) {
+ if (inside(root, lib)) return `The library directory is inside ${what} (${root}); choose a directory outside it.`;
+ }
+ // CONTAINING one (re-review F1): the library is read-only, so nothing is lost,
+ // but a scan of it would offer archive-owned media as recordings.
+ for (const { what, root } of owned) {
+ if (inside(lib, root)) return `The library directory contains ${what} (${root}); choose a directory that does not.`;
+ }
+ return null;
+}
diff --git a/common/controller/localMediaPreparation.test.ts b/common/controller/localMediaPreparation.test.ts
@@ -0,0 +1,166 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm, symlink, chmod } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { execFileSync } from "node:child_process";
+import { previewLocalMedia, prepareLocalMediaRecording, importLocalMedia, type LocalRecordingPreparationRequest } from "./localMediaImport";
+import { localRecordingId, parseLocalRecordingDetails } from "../lib/localRecordingDetails";
+
+async function fixture(t: TestContext, realVideo = false) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-preparation-"));
+ t.after(() => rm(root, {recursive: true, force: true}));
+ const source = path.join(root, "originals");
+ const paths = {channelsDir: path.join(root, "channels"), ffprobeBin: "ffprobe"};
+ const channel = path.join(paths.channelsDir, "sample");
+ await mkdir(source); await mkdir(channel, {recursive: true});
+ const config = {handling: "youtube", localMedia: {sourceId: "library-1", directory: source}};
+ await writeFile(path.join(channel, "config.json"), JSON.stringify(config));
+ const media = "Classroom lesson.mp4";
+ const file = path.join(source, media);
+ if (realVideo) execFileSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "color=c=black:s=32x32:r=5", "-t", "1", "-c:v", "mpeg4", file], {timeout: 15000});
+ else await writeFile(file, "synthetic manual fixture");
+ const transcript = path.join(source, "Classroom lesson.vtt");
+ await writeFile(transcript, "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nSynthetic classroom phrase\n");
+ const sidecar = path.join(source, "Classroom lesson.info.json");
+ const preview = await previewLocalMedia(paths, "sample");
+ assert.ok(preview.candidates[0].preparationFingerprint);
+ const request: LocalRecordingPreparationRequest = {sourceToken: preview.sourceToken, media,
+ sourceFingerprint: preview.candidates[0].preparationFingerprint!, details: {mode: "manual", title: "Classroom lesson"}};
+ const selection = (review: {fingerprint: string}, input = request) => ({sourceToken: input.sourceToken,
+ selected: [{media, fingerprint: review.fingerprint, preparation: {sourceFingerprint: input.sourceFingerprint, details: input.details}}]});
+ return {root, source, paths, channel, file, transcript, sidecar, media, request, selection, config};
+}
+async function bytes(root: string) {
+ const result: Record<string, string> = {};
+ for (const name of await readdir(root)) result[name] = (await readFile(path.join(root, name))).toString("base64");
+ return result;
+}
+
+test("manual review writes nothing, then the normal importer saves local metadata and reference only", async t => {
+ const f = await fixture(t);
+ f.paths.ffprobeBin = path.join(f.root, "deliberately-absent");
+ const before = await bytes(f.source);
+ const review = await prepareLocalMediaRecording(f.paths, "sample", f.request);
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+ assert.equal(review.metadata.duration, undefined);
+ assert.equal(review.metadata.recorded_date, undefined);
+ assert.equal(review.metadata.local_recording.inspection, "manual");
+ assert.equal(JSON.stringify(review).includes(f.root), false);
+ const result = await importLocalMedia(f.paths, "sample", f.selection(review));
+ assert.equal(result.records[0].status, "imported");
+ assert.equal(result.needsIndexUpdate, true);
+ const dest = path.join(f.channel, "data", review.metadata.id);
+ assert.deepEqual((await readdir(dest)).sort(), ["external-media.json", "metadata.info.json", "transcript.en.vtt"]);
+ assert.deepEqual(JSON.parse(await readFile(path.join(dest, "metadata.info.json"), "utf8")), review.metadata);
+ assert.equal(await readFile(path.join(dest, "transcript.en.vtt"), "utf8"), await readFile(f.transcript, "utf8"));
+ assert.deepEqual(await bytes(f.source), before);
+ const after = await previewLocalMedia(f.paths, "sample");
+ assert.equal(after.candidates[0].status, "existing");
+ assert.equal(after.candidates[0].preparationFingerprint, undefined);
+ assert.equal((await importLocalMedia(f.paths, "sample", f.selection(review))).records[0].status, "occupied");
+ assert.deepEqual(await bytes(f.source), before);
+});
+
+test("inspection measures a real MP4, rechecks during import and never changes original bytes", async t => {
+ const f = await fixture(t, true), before = await bytes(f.source);
+ f.request.details = {mode: "inspect", title: "Science class", recordedDate: "2024-02-29"};
+ const review = await prepareLocalMediaRecording(f.paths, "sample", f.request);
+ assert.ok(review.metadata.duration! > 0);
+ assert.equal(review.metadata.local_recording.durationSource, "ffprobe");
+ assert.equal(review.metadata.recorded_date, "20240229");
+ assert.equal((await importLocalMedia(f.paths, "sample", f.selection(review))).records[0].status, "imported");
+ assert.deepEqual(await bytes(f.source), before);
+});
+
+test("changed media, transcript, or newly supplied metadata refuses a reviewed import", async t => {
+ for (const change of ["media", "transcript", "metadata"]) {
+ const f = await fixture(t);
+ const review = await prepareLocalMediaRecording(f.paths, "sample", f.request);
+ if (change === "media") await writeFile(f.file, "replacement recording with different bytes");
+ else if (change === "transcript") await writeFile(f.transcript, "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nEdited cue\n");
+ else await writeFile(f.sidecar, "{}");
+ const result = await importLocalMedia(f.paths, "sample", f.selection(review));
+ assert.equal(result.records[0].status, "failed", change);
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+ }
+});
+
+test("existing invalid metadata and missing transcripts never offer generation", async t => {
+ const f = await fixture(t);
+ await writeFile(f.sidecar, "not JSON");
+ assert.equal((await previewLocalMedia(f.paths, "sample")).candidates[0].preparationFingerprint, undefined);
+ await assert.rejects(prepareLocalMediaRecording(f.paths, "sample", f.request));
+ await rm(f.sidecar); await rm(f.transcript);
+ assert.equal((await previewLocalMedia(f.paths, "sample")).candidates[0].preparationFingerprint, undefined);
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+});
+
+test("source links, path requests, relocation and stale configuration are refused", async t => {
+ const f = await fixture(t);
+ await assert.rejects(prepareLocalMediaRecording(f.paths, "sample", {...f.request, media: "../outside.mp4"}));
+ await assert.rejects(prepareLocalMediaRecording(f.paths, "../sample", f.request));
+ await rm(f.file); await writeFile(path.join(f.root, "outside.mp4"), "outside");
+ await symlink(path.join(f.root, "outside.mp4"), f.file);
+ await assert.rejects(prepareLocalMediaRecording(f.paths, "sample", f.request));
+ const g = await fixture(t);
+ await writeFile(path.join(g.channel, "config.json"), JSON.stringify({...g.config, localMedia: {...g.config.localMedia, sourceId: "changed"}}));
+ await assert.rejects(prepareLocalMediaRecording(g.paths, "sample", g.request));
+ await writeFile(path.join(g.channel, "config.json"), JSON.stringify(g.config));
+ await writeFile(path.join(g.channel, ".relocating.json"), JSON.stringify({target:path.join(g.root,"other","media"),scope:"media",direction:"out",phase:"copy"}));
+ await assert.rejects(prepareLocalMediaRecording(g.paths, "sample", g.request), /relocation/);
+});
+
+test("missing ffprobe fails explicitly; manual preparation and stable identity remain available", async t => {
+ const f = await fixture(t);
+ f.paths.ffprobeBin = path.join(f.root, "absent-probe");
+ await assert.rejects(prepareLocalMediaRecording(f.paths, "sample", {...f.request, details: {...f.request.details, mode: "inspect"}}), /ffprobe is unavailable/);
+ const first = await prepareLocalMediaRecording(f.paths, "sample", f.request);
+ const second = await prepareLocalMediaRecording(f.paths, "sample", {...f.request, details: {mode:"manual",title:"Changed title",durationSeconds:3,recordedDate:"2026-01-01"}});
+ assert.equal(first.metadata.id, second.metadata.id);
+ assert.notEqual(first.fingerprint, second.fingerprint);
+ assert.equal(first.metadata.id, localRecordingId("sample", "library-1", f.media));
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+});
+
+test("modified form facts or cancelled import cannot publish the old review", async t => {
+ const f = await fixture(t);
+ const review = await prepareLocalMediaRecording(f.paths, "sample", f.request);
+ const changed = {...f.request, details: {...f.request.details, title: "Changed after review"}};
+ assert.equal((await importLocalMedia(f.paths, "sample", f.selection(review, changed))).records[0].status, "failed");
+ assert.equal((await importLocalMedia(f.paths, "sample", {...f.selection(review), signal: AbortSignal.abort()})).cancelled, true);
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+});
+
+test("replacement during probe cannot publish or return a usable review", async t => {
+ const f = await fixture(t);
+ const executable = path.join(f.root, "replace-probe");
+ await writeFile(executable, "#!/usr/bin/env node\n" +
+ `require('fs').writeFileSync(${JSON.stringify(f.file)}, 'changed during probe');` +
+ "process.stdout.write(JSON.stringify({format:{duration:1},streams:[{codec_type:'video'}]}));\n");
+ await chmod(executable, 0o755);
+ f.paths.ffprobeBin = executable;
+ await assert.rejects(prepareLocalMediaRecording(f.paths,"sample",{...f.request,details:{...f.request.details,mode:"inspect"}}));
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+});
+
+test("queued detail snapshots allow only intended fields and manual durations", () => {
+ const original = {mode: "manual", title: " Lesson ", durationSeconds: 4, file: "/untrusted", executable: "untrusted"};
+ const details = parseLocalRecordingDetails(original);
+ original.title = "changed";
+ assert.deepEqual(details, {mode: "manual", title: "Lesson", durationSeconds: 4});
+ for (const bad of [null, {}, {mode:"inspect",title:"Lesson",durationSeconds:4},
+ {mode:"manual",title:"Lesson",durationSeconds:-1}, {mode:"manual",title:"Lesson",recordedDate:3}]) {
+ assert.throws(() => parseLocalRecordingDetails(bad));
+ }
+});
+
+// Review fix 6: a local recording's id is unique across channels — the same
+// library id and file name in two channels are two records.
+test("localRecordingId includes the channel: same library and file in two channels, two ids", () => {
+ const a = localRecordingId("channel-a", "library-1", "talk.mp4");
+ const b = localRecordingId("channel-b", "library-1", "talk.mp4");
+ assert.notEqual(a, b);
+ assert.match(a, /^local-[0-9a-f]{32}$/);
+ assert.equal(a, localRecordingId("channel-a", "library-1", "talk.mp4"));
+});
diff --git a/common/controller/localMediaSrt.test.ts b/common/controller/localMediaSrt.test.ts
@@ -0,0 +1,77 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { previewLocalMedia, prepareLocalMediaRecording, importLocalMedia } from "./localMediaImport";
+import { adoptLocalMediaReference } from "./adoptLocalMediaReference";
+import { srtToVtt } from "../lib/localMediaTranscript";
+import { parseVtt } from "../lib/vtt";
+import type { Paths } from "../lib/paths";
+
+const SRT = "1\r\n00:00:01,125 --> 00:00:02,875\r\nA classroom phrase\r\nSecond line\r\n";
+async function fixture(t: TestContext, online = true) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-srt-"));
+ t.after(() => rm(root, {recursive:true, force:true}));
+ const source = path.join(root, "originals"), paths = {channelsDir: path.join(root,"channels")};
+ const channel = path.join(paths.channelsDir,"sample");
+ await mkdir(source); await mkdir(channel,{recursive:true});
+ await writeFile(path.join(channel,"config.json"),JSON.stringify({handling:"youtube",localMedia:{sourceId:"library-1",directory:source}}));
+ await writeFile(path.join(source,"lesson.mp4"),"synthetic video");
+ await writeFile(path.join(source,"lesson.srt"),SRT);
+ if(online) await writeFile(path.join(source,"lesson.info.json"),JSON.stringify({id:"lesson",title:"Lesson",duration:3,upload_date:"20260101",webpage_url:"https://www.youtube.com/watch?v=lesson"}));
+ const preview = () => previewLocalMedia(paths,"sample");
+ const p = await preview();
+ const selection = {sourceToken:p.sourceToken,selected:[{media:"lesson.mp4",fingerprint:p.candidates[0].fingerprint!}]};
+ return {source,paths,channel,preview,p,selection};
+}
+test("SRT import saves canonical VTT and preserves originals; retry and verification use the same conversion", async t => {
+ const f=await fixture(t);
+ const names=await readdir(f.source);
+ assert.equal(f.p.candidates[0].transcript,"lesson.srt");
+ assert.ok(f.p.candidates[0].warnings.some(w=>w.includes("SRT")));
+ assert.equal((await importLocalMedia(f.paths,"sample",f.selection)).records[0].status,"imported");
+ const record=path.join(f.channel,"data","lesson");
+ const vtt=await readFile(path.join(record,"transcript.en.vtt"),"utf8");
+ assert.equal(vtt,srtToVtt(SRT));
+ assert.deepEqual(parseVtt(vtt),[{start:1.125,end:2.875,text:"A classroom phrase Second line"}]);
+ assert.equal(await readFile(path.join(f.source,"lesson.srt"),"utf8"),SRT);
+ assert.deepEqual(await readdir(f.source),names);
+ assert.equal((await importLocalMedia(f.paths,"sample",f.selection)).records[0].status,"occupied");
+ await rm(path.join(record,"external-media.json"));
+ const p=await f.preview();
+ const linked=await adoptLocalMediaReference(f.paths as Paths,"sample",{sourceToken:p.sourceToken,media:"lesson.mp4",fingerprint:p.candidates[0].fingerprint!},{apply:true});
+ assert.equal(linked.status,"attached");
+});
+test("SRT works with reviewed manual metadata and cannot reuse a review after source text changes", async t => {
+ for(const changed of [false,true]) {
+ const f=await fixture(t,false), row=f.p.candidates[0];
+ const details={mode:"manual" as const,title:"Classroom"};
+ const request={sourceToken:f.p.sourceToken,media:row.media,sourceFingerprint:row.preparationFingerprint!,details};
+ const review=await prepareLocalMediaRecording(f.paths,"sample",request);
+ if(changed) await writeFile(path.join(f.source,"lesson.srt"),SRT.replace("1\r\n","9\r\n"));
+ const result=await importLocalMedia(f.paths,"sample",{sourceToken:request.sourceToken,selected:[{media:row.media,fingerprint:review.fingerprint,preparation:{sourceFingerprint:request.sourceFingerprint,details}}]});
+ assert.equal(result.records[0].status,changed?"failed":"imported");
+ if(!changed) assert.equal(await readFile(path.join(f.channel,"data",review.metadata.id,"transcript.en.vtt"),"utf8"),srtToVtt(SRT));
+ else assert.deepEqual(await readdir(f.channel),["config.json"]);
+ }
+});
+test("VTT takes precedence, including invalid VTT; newly added VTT invalidates an SRT selection", async t => {
+ const f=await fixture(t);
+ await writeFile(path.join(f.source,"lesson.vtt"),"WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nChosen VTT\n");
+ const p=await f.preview();
+ assert.equal(p.candidates[0].transcript,"lesson.vtt");
+ assert.equal((await importLocalMedia(f.paths,"sample",f.selection)).records[0].status,"stale");
+ await writeFile(path.join(f.source,"lesson.vtt"),"bad VTT");
+ assert.equal((await f.preview()).candidates[0].status,"issue");
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+test("malformed SRT and non-UTF8 input are review issues and cannot create a record", async t => {
+ const f=await fixture(t);
+ for(const bytes of [Buffer.from("bad subtitle"),Buffer.from([0xff,0xfe,0x31,0x00])]) {
+ await writeFile(path.join(f.source,"lesson.srt"),bytes);
+ assert.equal((await f.preview()).candidates[0].status,"issue");
+ assert.equal((await importLocalMedia(f.paths,"sample",f.selection)).needsIndexUpdate,false);
+ }
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
diff --git a/common/controller/localTranscriptionEligibility.test.ts b/common/controller/localTranscriptionEligibility.test.ts
@@ -0,0 +1,97 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm, symlink } from "node:fs/promises";
+import path from "node:path";
+import os from "node:os";
+import { previewLocalMedia, importLocalMedia } from "./localMediaImport";
+import { localRecordingId } from "../lib/localRecordingDetails";
+
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(os.tmpdir(), "local-transcription-eligibility-"));
+ t.after(() => rm(root, {recursive:true, force:true}));
+ const source = path.join(root, "source");
+ const paths = {channelsDir:path.join(root, "channels")};
+ const channel = path.join(paths.channelsDir, "sample");
+ await mkdir(source); await mkdir(channel, {recursive:true});
+ await writeFile(path.join(channel,"config.json"), JSON.stringify({handling:"youtube",localMedia:{sourceId:"library-1",directory:source}}));
+ await writeFile(path.join(source,"lesson.mp4"),"synthetic video fixture");
+ const preview = () => previewLocalMedia(paths,"sample");
+ return {source,paths,channel,preview};
+}
+const metadata = (id="lesson") => ({id,title:"Lesson",duration:10,upload_date:"20261103",webpage_url:"https://www.youtube.com/watch?v="+id});
+
+test("missing subtitles become transcription-eligible but remain blocked for import; preview writes nothing", async t => {
+ const f=await fixture(t);
+ const before=await readFile(path.join(f.source,"lesson.mp4"));
+ const preview=await f.preview(),row=preview.candidates[0];
+ assert.ok(row.transcriptionFingerprint);
+ assert.equal(row.transcriptionNeedsDetails,true);
+ assert.equal(row.status,"issue");
+ assert.equal(row.fingerprint,undefined);
+ assert.equal(row.preparationFingerprint,undefined);
+ const result=await importLocalMedia(f.paths,"sample",{sourceToken:preview.sourceToken,selected:[{media:row.media,fingerprint:row.transcriptionFingerprint!}]});
+ assert.equal(result.records.length,1);
+ assert.equal(result.records[0].status,"stale");
+ assert.deepEqual(await readFile(path.join(f.source,"lesson.mp4")),before);
+ assert.deepEqual(await readdir(f.source),["lesson.mp4"]);
+ assert.ok(!(await readdir(f.channel)).includes("data"));
+});
+
+test("valid provider metadata is retained; metadata and media changes invalidate the eligibility token", async t => {
+ const f=await fixture(t),file=path.join(f.source,"lesson.info.json");
+ await writeFile(file,JSON.stringify(metadata()));
+ const first=(await f.preview()).candidates[0];
+ assert.ok(first.transcriptionFingerprint);
+ assert.equal(first.transcriptionNeedsDetails,undefined);
+ assert.equal(first.directoryId,"lesson");
+ await writeFile(file,JSON.stringify({...metadata(),title:"Changed"}));
+ const second=(await f.preview()).candidates[0];
+ assert.notEqual(second.transcriptionFingerprint,first.transcriptionFingerprint);
+ await writeFile(path.join(f.source,"lesson.mp4"),"changed synthetic video fixture");
+ assert.notEqual((await f.preview()).candidates[0].transcriptionFingerprint,second.transcriptionFingerprint);
+});
+
+test("existing SRT or VTT blocks generation even when empty, malformed, a directory or a symlink", async t => {
+ const f=await fixture(t);
+ for(const ext of [".vtt",".srt"]) {
+ const target=path.join(f.source,"lesson"+ext);
+ for(const text of ["","malformed subtitles"]) {
+ await writeFile(target,text);
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+ assert.equal(await readFile(target,"utf8"),text);
+ }
+ await rm(target); await mkdir(target);
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+ await rm(target,{recursive:true});
+ await symlink(path.join(f.source,"absent-subtitle"),target);
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+ await rm(target);
+ }
+ assert.ok((await f.preview()).candidates[0].transcriptionFingerprint);
+});
+
+test("invalid metadata, source media links and duplicate identities cannot qualify", async t => {
+ const f=await fixture(t),file=path.join(f.source,"lesson.info.json");
+ for(const value of ["{",JSON.stringify({...metadata(),duration:0}),JSON.stringify({...metadata(),id:"other"})]) {
+ await writeFile(file,value);
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+ }
+ await writeFile(file,JSON.stringify(metadata()));
+ await writeFile(path.join(f.source,"duplicate.mp4"),"fixture");
+ await writeFile(path.join(f.source,"duplicate.info.json"),JSON.stringify(metadata()));
+ assert.ok((await f.preview()).candidates.every(row=>!row.transcriptionFingerprint));
+ await rm(path.join(f.source,"duplicate.mp4"));
+ await rm(path.join(f.source,"lesson.mp4"));
+ await symlink(file,path.join(f.source,"lesson.mp4"));
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+});
+
+test("occupied generated and provider identities are blocked even with incomplete saved records", async t => {
+ const f=await fixture(t);
+ const id=localRecordingId("sample","library-1","lesson.mp4");
+ await mkdir(path.join(f.channel,"data",id),{recursive:true});
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+ await writeFile(path.join(f.source,"lesson.info.json"),JSON.stringify(metadata()));
+ await mkdir(path.join(f.channel,"data","lesson"));
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+});
diff --git a/common/controller/refreshVideoMetadata.ts b/common/controller/refreshVideoMetadata.ts
@@ -43,6 +43,7 @@
// The job around it (queue, kind, refusals) is refreshVideoMetadataJob.ts;
// this module needs no registry, so a test drives it with a stub runner.
+import { localMediaMetadataRefusal } from "../lib/localMedia";
import path from "node:path";
import { readFile, stat } from "node:fs/promises";
import {
@@ -123,6 +124,9 @@ export async function resolveRefreshTarget(
if (!(await isDirectory(videoDir))) {
return { ok: false, error: notFetchedRefusal(videoId, slug) };
}
+ // A local media record has no source to read metadata from (review fix 5).
+ const localRefusal = localMediaMetadataRefusal(slug, config, videoId);
+ if (localRefusal) return { ok: false, error: localRefusal };
const url = await findVideoSourceUrl(paths, slug, videoId, config);
if (!url) {
return {
diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -305,7 +305,8 @@ export function fetchHooksOf(deps: ReportDraftDeps): FetchHooks {
const c = (await configs()).get(slug);
if (!c) return null;
const platform = platformOfConfig(c);
- return { kind: isPostsChannel(c) ? "posts" : "video", ...(platform ? { platform } : {}) };
+ const localLibrary = !!c.localMedia && !(typeof c.url === "string" && c.url.trim());
+ return { kind: isPostsChannel(c) ? "posts" : "video", ...(platform ? { platform } : {}), ...(localLibrary ? { localLibrary: true as const } : {}) };
},
platformRefusal: (platform) => platformRefusalOf(platform, paths),
bucketOf: async (slug) => {
diff --git a/common/controller/undownloadedVideos.ts b/common/controller/undownloadedVideos.ts
@@ -1,4 +1,6 @@
import path from "node:path";
+import { readChannelConfig } from "./channels";
+import { localMediaFetchRefusal } from "../lib/localMedia";
import { readFile } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
@@ -25,10 +27,17 @@ export async function findVideoSourceUrl(
config?: ChannelConfig,
): Promise<string | null> {
const channelRoot = path.join(paths.channelsDir, slug);
+ // A LOCAL RECORDING, or any record of a local media library channel, has no
+ // online source (lib/localMedia.ts): null, so no lane, door or download ever
+ // hands yt-dlp a URL built for it — `defaultWebpageUrl("local", id)` is "".
+ if (localMediaFetchRefusal(slug, config ?? (await readChannelConfig(paths, slug).catch(() => null)), videoId)) {
+ return null;
+ }
const metaPath = path.join(channelRoot, "data", videoId, "metadata.info.json");
try {
const raw = await readFile(metaPath, "utf8");
const parsed = JSON.parse(raw);
+ if (parsed?.local_recording !== undefined) return null;
if (typeof parsed?.webpage_url === "string" && parsed.webpage_url) {
return parsed.webpage_url;
}
@@ -46,6 +55,6 @@ export async function findVideoSourceUrl(
// playlist came up empty, so the exact original URL always wins when present.
// Requires a known platform — we don't blindly guess one.
const platform = config?.platform ?? detectPlatform(config?.url ?? null);
- if (platform) return defaultWebpageUrl(platform, videoId);
+ if (platform) return defaultWebpageUrl(platform, videoId) || null;
return null;
}
diff --git a/common/controller/videoTitles.test.ts b/common/controller/videoTitles.test.ts
@@ -1,3 +1,4 @@
+import { prepareManualLocalRecordingMetadata } from "../lib/localRecordingMetadata";
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdir, mkdtemp, rm, unlink, utimes, writeFile, readdir } from "node:fs/promises";
@@ -326,3 +327,26 @@ test("metadata titles are memoized per channel until data/ changes", async () =>
await rm(dir, { recursive: true, force: true });
}
});
+
+
+test("display identifies only valid local metadata matching the saved record", async () => {
+ const { dir, paths } = await fixture("local-display-");
+ try {
+ const id = "local-" + "a".repeat(32);
+ const local = prepareManualLocalRecordingMetadata({ id, filename: "lesson.mp4" });
+ await writeInfo(paths, id, local);
+ assert.equal((await readVideoMetadataForDisplay(paths, SLUG, id)).localRecording, true);
+ for (const info of [
+ { id, title: "Online record without URL", extractor_key: "Youtube" },
+ { ...local, webpage_url: "https://www.youtube.com/watch?v=abc" },
+ { ...local, local_recording: { ...local.local_recording, version: 99 } },
+ { ...local, id: "local-" + "b".repeat(32) },
+ ]) {
+ await writeInfo(paths, id, info);
+ assert.equal((await readVideoMetadataForDisplay(paths, SLUG, id)).localRecording, undefined);
+ }
+ assert.equal((await readVideoMetadataForDisplay(paths, SLUG, "missing")).localRecording, undefined);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/videoTitles.ts b/common/controller/videoTitles.ts
@@ -1,3 +1,4 @@
+import { requireLocalRecordingMetadata } from "../lib/localRecordingMetadata";
// What a channel's videos are CALLED, for the editor's per-channel video list
// and the video page — without downloading anything and without walking the
// corpus.
@@ -282,6 +283,8 @@ export async function readChannelVideoTitles(
}
export type VideoDisplayMetadata = {
+ // True only for validated source-less metadata, never inferred from an ID or missing URL.
+ localRecording?: true;
title?: string;
description?: string;
webpageUrl?: string;
@@ -309,7 +312,14 @@ export async function readVideoMetadataForDisplay(
path.join(channelDataDir(paths, channelSlug), id),
);
if (meta) {
+ let localRecording = false;
+ try {
+ localRecording = requireLocalRecordingMetadata(meta).id === id;
+ } catch {
+ // Ordinary provider metadata (including incomplete records) keeps its existing UI.
+ }
return {
+ ...(localRecording ? { localRecording: true as const } : {}),
title: str(meta.title),
description: str(meta.description),
webpageUrl: str(meta.webpage_url),
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -1520,6 +1520,22 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "custom",
needsMedia: true,
},
+ // A LOCAL MEDIA LIBRARY'S RECORDS (controller/localMediaImport.ts): the
+ // metadata, transcript and `external-media.json` of recordings that stay in
+ // the channel's `localMedia.directory`. Text: it writes corpus text only and
+ // never opens a managed big file, so a disconnected managed-media drive does
+ // not hold it (the library has its own read-only resolver and stall check,
+ // and the controller refuses every relocation marker). Drainable between
+ // recordings. An INGEST kind: it writes whole new records. On the channel's
+ // own queue. Not replayable: a retry needs a fresh preview's tokens.
+ "import-local-media": {
+ kind: "import-local-media",
+ label: "Import external media library",
+ drainable: true,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsText: true,
+ },
// PLAYABLE COPIES AND THEIR TORRENTS (release 21 D3,
// controller/preparePlayable.ts): each saved container remuxed losslessly
// into a browser's container, and one torrent per copy. Media: it reads the
@@ -1609,6 +1625,7 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([
"quick-availability-check",
"check-maybe-missing",
"attach-media",
+ "import-local-media",
"prepare-playable",
// A gone video's audio from a copy, and the copy's provenance (release 31).
"fetch-copies",
diff --git a/common/lib/attachMediaPlan.test.ts b/common/lib/attachMediaPlan.test.ts
@@ -190,3 +190,22 @@ test("records: title from the folder name, date and description from description
assert.equal(other.webpage_url, undefined);
assert.equal(other.extractor, undefined);
});
+
+// lane/local-media review fix 5: a held record linked to a local media library
+// original (its external-media.json) is never attached, replace or not.
+test("plan: a held record linked to a local media library is class local-media, never attach", () => {
+ const folders = groupArchiveFolders(ARCHIVE);
+ for (const replace of [false, true]) {
+ const plan = planAttach({
+ folders,
+ held: new Set(["aaaaaaaaaaa"]),
+ attached: new Set(["aaaaaaaaaaa"]),
+ localMedia: new Set(["aaaaaaaaaaa"]),
+ ...(replace ? { replace: true } : {}),
+ });
+ const row = plan.rows.find((r) => r.id === "aaaaaaaaaaa")!;
+ assert.equal(row.class, "local-media");
+ assert.equal(countAttachRows(plan.rows)["local-media"], 1);
+ assert.equal(countAttachRows(plan.rows).attach, 0);
+ }
+});
diff --git a/common/lib/attachMediaPlan.ts b/common/lib/attachMediaPlan.ts
@@ -1,3 +1,4 @@
+import { LOCAL_RECORDING_ID_RE } from "./localMedia";
// WHICH FILE OF A LOCAL ARCHIVE IS WHICH VIDEO (release 21 D1).
//
// The pure half of `attach-media` (controller/attachMedia.ts): given the file
@@ -231,6 +232,10 @@ export const ATTACH_ROW_CLASSES = [
"unmatched",
// More than one video file for one id: name the file with `items`.
"ambiguous",
+ // A held record linked to a local media library original (its
+ // `external-media.json`), or a local recording: never attached — its video
+ // is the library's (lane/local-media review fix 5).
+ "local-media",
] as const;
export type AttachRowClass = (typeof ATTACH_ROW_CLASSES)[number];
@@ -261,6 +266,8 @@ export function planAttach(opts: {
folders: readonly ArchiveFolder[];
held: ReadonlySet<string>;
attached: ReadonlySet<string>;
+ // Held records linked to a local media library original (class "local-media").
+ localMedia?: ReadonlySet<string>;
createRecords?: boolean;
replace?: boolean;
match?: RegExp;
@@ -270,6 +277,9 @@ export function planAttach(opts: {
files?: readonly SourceFile[];
}): AttachPlan {
const classify = (id: string, media: SourceFile, folder: string, source?: ArchiveFolder): AttachRow => {
+ if (opts.localMedia?.has(id) || LOCAL_RECORDING_ID_RE.test(id)) {
+ return { class: "local-media", id, folder, media, ...(source ? { source } : {}) };
+ }
if (opts.held.has(id)) {
if (opts.attached.has(id) && !opts.replace) {
return { class: "already-attached", id, folder, media, ...(source ? { source } : {}) };
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -1,3 +1,4 @@
+import { coerceLocalMediaConfig, type LocalMediaConfig } from "./localMedia";
import { PLATFORM_VALUES, type Platform } from "./platform";
import { coerceWaybackPagesConfig, type WaybackPagesConfig } from "./waybackPages/config";
import { coerceXSearchConfig, type XSearchConfig } from "./xSearch/config";
@@ -300,6 +301,8 @@ export type ChannelConfig = {
wayback?: WaybackPagesConfig;
// Release 38: an X search channel's query (lib/xSearch/config.ts).
xSearch?: XSearchConfig;
+ // External library inputs are not managed media. A config change never moves files.
+ localMedia?: LocalMediaConfig;
};
// In the order parseChannelConfig emits (and CHANNEL.md lists) them.
@@ -392,6 +395,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org\'s pace; absent, nothing is imported unasked. Release 37 lane F: a target\'s `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages".',
xSearch:
'An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X\'s search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window\'s span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl\'s search, resumable, at the older walk\'s pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped.',
+ localMedia:
+ "Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports.",
};
// Every key a config.json may carry, in emission order. The unknown-key oracle:
@@ -609,6 +614,7 @@ export const CHANNEL_CONFIG_COERCIONS: {
mirror: coerceMirrorConfig,
wayback: coerceWaybackPagesConfig,
xSearch: coerceXSearchConfig,
+ localMedia: coerceLocalMediaConfig,
};
// A channel's config.json as a ChannelConfig, or null when it is not a channel
diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts
@@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it",
assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]);
- assert.equal(CHANNEL_CONFIG_KEYS.length, 46); // 2026-11-11: `cleanAfterCaptureUnverified` (main), `remoteOnly`, `remoteArchive`, `remoteUrl` (demo epic D1)
+ assert.equal(CHANNEL_CONFIG_KEYS.length, 47); // 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl`
assert.equal(sameKeys, true);
assert.equal(fits, true);
for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k);
@@ -170,3 +170,19 @@ test("the zod schema and the client-safe parser agree, key order included", () =
assert.deepEqual(Object.keys(b ?? {}), Object.keys(a ?? {}));
}
});
+
+test("localMedia is opt-in and both parsers agree on valid and invalid inputs", () => {
+ for (const localMedia of [
+ { sourceId: "library-1", directory: "/mnt/library" },
+ { sourceId: "library-1", directory: "/mnt/library", playback: true },
+ { sourceId: "library-1", directory: "/mnt/library", playback: "true" },
+ { sourceId: "../escape", directory: "/mnt/library" },
+ { sourceId: "library-1", directory: "relative" },
+ ]) {
+ assert.deepEqual(parse({ handling: "youtube", localMedia }), parseChannelConfig({ handling: "youtube", localMedia }));
+ }
+ assert.deepEqual(parse({ handling: "youtube", localMedia: { sourceId: "library-1", directory: "/mnt/library" } })!.localMedia,
+ { sourceId: "library-1", directory: "/mnt/library" });
+ assert.equal("localMedia" in parse({ handling: "youtube" })!, false);
+ assert.equal("localMedia" in parse({ handling: "youtube", localMedia: { sourceId: "x", directory: "relative" } })!, false);
+});
diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts
@@ -89,6 +89,7 @@ export const channelConfigObjectSchema = z.object({
mirror: field("mirror"),
wayback: field("wayback"),
xSearch: field("xSearch"),
+ localMedia: field("localMedia"),
});
// Drop every own key whose value is `undefined` (the OMIT rule, above).
diff --git a/common/lib/chartAggregate.ts b/common/lib/chartAggregate.ts
@@ -79,6 +79,7 @@ export function applyFilters(
const platformSet =
f.platforms && f.platforms.length ? new Set(f.platforms) : null;
return stats.filter((s) => {
+ if ((f.dateFrom || f.dateTo) && !s.uploadDate) return false;
if (f.dateFrom && s.uploadDate < f.dateFrom) return false;
if (f.dateTo && s.uploadDate > f.dateTo) return false;
if (channelSet && !channelSet.has(s.channelSlug)) return false;
diff --git a/common/lib/duplicates.test.ts b/common/lib/duplicates.test.ts
@@ -562,3 +562,16 @@ test("a contained cluster (clip of a longer video) never shares", () => {
true,
);
});
+
+// lane/local-media review fix 3: a public site's duplicates keep no local recording.
+test("filterClusterToChannels takes a per-record rule: a local recording left out", () => {
+ const c = cluster([
+ ref({ slug: "a/1", channelSlug: "a", platform: "youtube" }),
+ ref({ slug: "a/local-" + "a".repeat(32), channelSlug: "a", platform: "local", id: "local-" + "a".repeat(32) }),
+ ref({ slug: "b/2", channelSlug: "b", platform: "rumble" }),
+ ]);
+ const out = filterClusterToChannels(c, new Set(["a", "b"]), (r) => r.platform !== "local");
+ assert.deepEqual(out?.videoRefs.map((r) => r.slug), ["a/1", "b/2"]);
+ assert.equal(filterClusterToChannels(c, new Set(["a"]), (r) => r.platform !== "local"), null);
+ assert.equal(filterClusterToChannels(c, new Set(["a", "b"]))?.videoRefs.length, 3);
+});
diff --git a/common/lib/duplicates.ts b/common/lib/duplicates.ts
@@ -725,9 +725,12 @@ export function strongerMatch(
export function filterClusterToChannels(
cluster: DuplicateCluster,
channelSlugs: Set<string>,
+ // A further per-record rule: a public site keeps no local recording
+ // (lib/localMedia.ts isLocalRecord; bin/compose-site.ts).
+ keepRef?: (ref: DuplicateVideoRef) => boolean,
): DuplicateCluster | null {
const videoRefs = cluster.videoRefs.filter((r) =>
- channelSlugs.has(r.channelSlug),
+ channelSlugs.has(r.channelSlug) && (keepRef ? keepRef(r) : true),
);
if (videoRefs.length < 2) return null;
return {
diff --git a/common/lib/externalMedia-server.test.ts b/common/lib/externalMedia-server.test.ts
@@ -0,0 +1,38 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { loadExternalMediaReference, writeExternalMediaReference, forgetExternalMediaReference } from "./externalMedia-server";
+import { dropSavedVideo, unpersistSavedVideo, loadSavedVideo } from "./savedVideo-server";
+import { EXTERNAL_MEDIA_FILENAME, type ExternalMediaReference } from "./localMedia";
+
+test("external sidecar round-trips; managed drop/unpersist ignore it; forgetting does not touch source", async (t) => {
+ const root = await mkdtemp(path.join(tmpdir(), "external-media-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const videoDir = path.join(root, "corpus");
+ const source = path.join(root, "external");
+ await mkdir(videoDir); await mkdir(source);
+ await writeFile(path.join(source, "original.mp4"), "externally owned bytes");
+ const value: ExternalMediaReference = { version: 1, kind: "external", sourceId: "library-1", relativePath: "original.mp4" };
+ await writeExternalMediaReference(videoDir, value);
+ assert.deepEqual(await loadExternalMediaReference(videoDir), value);
+ assert.equal(await loadSavedVideo(videoDir), null);
+ assert.equal(await dropSavedVideo(videoDir), 0);
+ assert.equal(await unpersistSavedVideo(videoDir), false);
+ assert.deepEqual(await loadExternalMediaReference(videoDir), value);
+ await forgetExternalMediaReference(videoDir);
+ assert.equal(await loadExternalMediaReference(videoDir), null);
+ assert.deepEqual(await readdir(source), ["original.mp4"]);
+ assert.equal(await readFile(path.join(source, "original.mp4"), "utf8"), "externally owned bytes");
+});
+test("invalid writes refuse; corrupt or future-version references load as null", async (t) => {
+ const root = await mkdtemp(path.join(tmpdir(), "external-media-invalid-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ await assert.rejects(writeExternalMediaReference(root, {} as ExternalMediaReference), /Invalid/);
+ assert.deepEqual(await readdir(root), []);
+ for (const body of ["{", JSON.stringify({ version: 2, kind: "external", sourceId: "x", relativePath: "a.mp4" })]) {
+ await writeFile(path.join(root, EXTERNAL_MEDIA_FILENAME), body);
+ assert.equal(await loadExternalMediaReference(root), null);
+ }
+});
diff --git a/common/lib/externalMedia-server.ts b/common/lib/externalMedia-server.ts
@@ -0,0 +1,17 @@
+import { sidecar, sidecarField } from "./sidecar-server";
+import { EXTERNAL_MEDIA_FILENAME, coerceExternalMediaReference, type ExternalMediaReference } from "./localMedia";
+
+// This sidecar has no saved-video pointer fields and no target-file operations.
+// Forgetting a reference removes only corpus metadata. It cannot remove, move,
+// or open the external recording because this module never resolves its path.
+// Keep resolution/playback in a separate, guarded read-only server module.
+const reference = sidecar(EXTERNAL_MEDIA_FILENAME, sidecarField(coerceExternalMediaReference));
+export const loadExternalMediaReference = reference.load;
+export const forgetExternalMediaReference = reference.remove;
+export async function writeExternalMediaReference(videoDir: string, value: ExternalMediaReference): Promise<void> {
+ // sidecar() validates reads but does not validate writes. Validate explicitly
+ // here so malformed references are never silently persisted by JS callers.
+ const parsed = coerceExternalMediaReference(value);
+ if (!parsed) throw new Error("Invalid external media reference");
+ await reference.write(videoDir, parsed);
+}
diff --git a/common/lib/externalMediaResolver-server.test.ts b/common/lib/externalMediaResolver-server.test.ts
@@ -0,0 +1,102 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, rm, symlink } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { openExternalMedia } from "./externalMediaResolver-server";
+
+// Synthetic roots only. The resolver accepts a config and reference so neither
+// tests nor this leaf need to open operator settings or the live corpus.
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "external-resolver-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const source = path.join(root, "source");
+ await mkdir(source);
+ await writeFile(path.join(source, "video.mp4"), "original bytes");
+ return { root, source, config: { sourceId: "library-1", directory: source },
+ reference: { version: 1, kind: "external", sourceId: "library-1", relativePath: "video.mp4" } };
+}
+async function linkOrSkip(t: TestContext, target: string, link: string, directory = false) {
+ try { await symlink(target, link, directory ? "junction" : "file"); return true; }
+ catch (error) {
+ if (process.platform === "win32" && (error as NodeJS.ErrnoException).code === "EPERM") {
+ t.skip("Windows symlink privilege unavailable; verify in Linux container"); return false;
+ }
+ throw error;
+ }
+}
+test("inspect opens read-only, reports size, and preserves original bytes", async (t) => {
+ const f = await fixture(t);
+ const got = await openExternalMedia({ ...f, purpose: "inspect" });
+ assert.equal(got.status, "ready");
+ if (got.status !== "ready") return;
+ try {
+ assert.equal(got.bytes, Buffer.byteLength("original bytes"));
+ assert.equal(await got.handle.readFile("utf8"), "original bytes");
+ await assert.rejects(got.handle.write(Buffer.from("overwrite"), 0, 9, 0));
+ } finally { await got.handle.close(); }
+ assert.equal(await readFile(path.join(f.source, "video.mp4"), "utf8"), "original bytes");
+});
+test("playback requires explicit opt-in; source mismatch is refused", async (t) => {
+ const f = await fixture(t);
+ assert.deepEqual(await openExternalMedia({ ...f, purpose: "playback" }), { status: "refused", reason: "playback-disabled" });
+ assert.deepEqual(await openExternalMedia({ ...f, reference: { ...f.reference, sourceId: "different" }, purpose: "inspect" }),
+ { status: "refused", reason: "source-mismatch" });
+ const got = await openExternalMedia({ ...f, config: { ...f.config, playback: true }, purpose: "playback" });
+ assert.equal(got.status, "ready");
+ if (got.status === "ready") await got.handle.close();
+});
+test("absolute and traversal references are refused before file access", async (t) => {
+ const f = await fixture(t);
+ for (const relativePath of ["../video.mp4", "/etc/video.mp4", "a/../../video.mp4", "C:/video.mp4", "a\\video.mp4"]) {
+ assert.deepEqual(await openExternalMedia({ ...f, reference: { ...f.reference, relativePath }, purpose: "inspect" }),
+ { status: "refused", reason: "invalid-reference" });
+ }
+});
+test("missing configuration and unsupported runtime purposes fail closed", async (t) => {
+ const f = await fixture(t);
+ assert.deepEqual(await openExternalMedia({ ...f, config: null, purpose: "inspect" }), { status: "refused", reason: "invalid-config" });
+ assert.deepEqual(await openExternalMedia({ ...f, purpose: "other" as "inspect" }), { status: "refused", reason: "playback-disabled" });
+});
+test("missing root or media is unavailable without changing the reference", async (t) => {
+ const f = await fixture(t);
+ const before = JSON.stringify(f.reference);
+ await rm(path.join(f.source, "video.mp4"));
+ assert.deepEqual(await openExternalMedia({ ...f, purpose: "inspect" }), { status: "refused", reason: "unavailable" });
+ await rm(f.source, { recursive: true });
+ assert.deepEqual(await openExternalMedia({ ...f, purpose: "inspect" }), { status: "refused", reason: "unavailable" });
+ assert.equal(JSON.stringify(f.reference), before);
+});
+test("directory masquerading as MP4 is not a regular file", async (t) => {
+ const f = await fixture(t);
+ await rm(path.join(f.source, "video.mp4")); await mkdir(path.join(f.source, "video.mp4"));
+ assert.deepEqual(await openExternalMedia({ ...f, purpose: "inspect" }), { status: "refused", reason: "not-regular" });
+});
+test("literal Unicode and percent paths resolve without URL decoding", async (t) => {
+ const f = await fixture(t);
+ const relativePath = "nested/A 'title' $money ⧸ %2e%2e.mp4";
+ await mkdir(path.join(f.source, "nested")); await writeFile(path.join(f.source, relativePath), "literal");
+ const got = await openExternalMedia({ ...f, reference: { ...f.reference, relativePath }, purpose: "inspect" });
+ assert.equal(got.status, "ready");
+ if (got.status === "ready") { try { assert.equal(await got.handle.readFile("utf8"), "literal"); } finally { await got.handle.close(); } }
+});
+test("final-file symlinks are rejected even when their target is within the library", async (t) => {
+ const f = await fixture(t);
+ if (!await linkOrSkip(t, path.join(f.source, "video.mp4"), path.join(f.source, "alias.mp4"))) return;
+ assert.deepEqual(await openExternalMedia({ ...f, reference: { ...f.reference, relativePath: "alias.mp4" }, purpose: "inspect" }), { status: "refused", reason: "unsafe-path" });
+});
+test("ancestor symlink escape and sibling-prefix trick are rejected", async (t) => {
+ const f = await fixture(t);
+ const sibling = f.source + "-outside";
+ await mkdir(sibling); await writeFile(path.join(sibling, "video.mp4"), "outside");
+ if (!await linkOrSkip(t, sibling, path.join(f.source, "escape"), true)) return;
+ assert.deepEqual(await openExternalMedia({ ...f, reference: { ...f.reference, relativePath: "escape/video.mp4" }, purpose: "inspect" }),
+ { status: "refused", reason: "unsafe-path" });
+});
+test("operator configured root may itself be a directory link", async (t) => {
+ const f = await fixture(t);
+ const link = path.join(f.root, "configured-root");
+ if (!await linkOrSkip(t, f.source, link, true)) return;
+ const got = await openExternalMedia({ ...f, config: { ...f.config, directory: link }, purpose: "inspect" });
+ assert.equal(got.status, "ready"); if (got.status === "ready") await got.handle.close();
+});
diff --git a/common/lib/externalMediaResolver-server.ts b/common/lib/externalMediaResolver-server.ts
@@ -0,0 +1,86 @@
+import path from "node:path";
+import { constants, type Stats } from "node:fs";
+import { lstat, open, realpath, stat, type FileHandle } from "node:fs/promises";
+import { coerceExternalMediaReference, coerceLocalMediaConfig } from "./localMedia";
+
+export type ExternalMediaOpenResult =
+ | { status: "ready"; handle: FileHandle; bytes: number }
+ | { status: "refused"; reason: "invalid-config" | "invalid-reference" | "source-mismatch"
+ | "playback-disabled" | "unsafe-path" | "not-regular" | "changed-during-open" | "unavailable" };
+
+function contained(root: string, candidate: string): boolean {
+ const relative = path.relative(root, candidate);
+ return !!relative && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
+}
+
+// Open EXTERNALLY OWNED media for reading only. No write, unlink, rename, or
+// source-directory creation is possible through this module. Returning the
+// verified handle (not a pathname to reopen) preserves file identity for the
+// caller's eventual stream. The caller MUST close a successful handle.
+//
+// Configuration comes from the operator, never a request's supplied root. A
+// playback opt-in is only one gate: HTTP authentication, site exposure policy,
+// channel guards and stalled-drive handling belong in the caller before this
+// low-level helper is used. This slice does not expose an HTTP route.
+//
+// TRUST MODEL: roots and their directory entries are operator-controlled.
+// Refuse symlinks beneath the canonical root, recheck identity after open, and
+// use O_NOFOLLOW when available. These checks defend against ordinary escapes
+// and replacements; portable Node path APIs are NOT equivalent to Linux
+// openat2(RESOLVE_BENEATH) against an adversary concurrently swapping ancestors.
+// Do not offer this resolver as a hostile multi-user filesystem sandbox.
+export async function openExternalMedia(options: {
+ config: unknown;
+ reference: unknown;
+ purpose: "inspect" | "playback";
+}): Promise<ExternalMediaOpenResult> {
+ const config = coerceLocalMediaConfig(options.config);
+ if (!config || !path.isAbsolute(config.directory)) return { status: "refused", reason: "invalid-config" };
+ const ref = coerceExternalMediaReference(options.reference);
+ if (!ref) return { status: "refused", reason: "invalid-reference" };
+ if (config.sourceId !== ref.sourceId) return { status: "refused", reason: "source-mismatch" };
+ // Unknown runtime purpose must fail closed, even for an untyped caller.
+ if (options.purpose !== "inspect" && (options.purpose !== "playback" || config.playback !== true)) {
+ return { status: "refused", reason: "playback-disabled" };
+ }
+ let handle: FileHandle | undefined;
+ try {
+ const root = await realpath(config.directory);
+ if (!(await stat(root)).isDirectory()) return { status: "refused", reason: "unsafe-path" };
+ const parts = ref.relativePath.split("/");
+ let candidate = root;
+ let before: Stats | undefined;
+ for (let index = 0; index < parts.length; index++) {
+ candidate = path.join(candidate, parts[index]);
+ if (!contained(root, candidate)) return { status: "refused", reason: "unsafe-path" };
+ const entry = await lstat(candidate);
+ if (entry.isSymbolicLink()) return { status: "refused", reason: "unsafe-path" };
+ if (index < parts.length - 1 && !entry.isDirectory()) return { status: "refused", reason: "unsafe-path" };
+ before = entry;
+ }
+ if (!before?.isFile()) return { status: "refused", reason: "not-regular" };
+ if (!contained(root, await realpath(candidate))) return { status: "refused", reason: "unsafe-path" };
+ // NONBLOCK avoids hanging if a regular file is replaced by a FIFO between
+ // lstat and open. File kind is checked again on the opened descriptor.
+ handle = await open(candidate, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
+ const opened = await handle.stat();
+ const after = await lstat(candidate);
+ if (!opened.isFile() || !after.isFile() || after.isSymbolicLink()
+ || opened.dev !== before.dev || opened.ino !== before.ino
+ || opened.dev !== after.dev || opened.ino !== after.ino
+ || opened.size !== before.size || opened.mtimeMs !== before.mtimeMs
+ || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs
+ || !contained(root, await realpath(candidate))) {
+ return { status: "refused", reason: "changed-during-open" };
+ }
+ const result: ExternalMediaOpenResult = { status: "ready", handle, bytes: opened.size };
+ handle = undefined; // Ownership transfers only on success; finally closes failures.
+ return result;
+ } catch {
+ // A missing, inaccessible or disconnected source is not an absent record.
+ // Return a bounded private-path-free status; never repair or delete it here.
+ return { status: "refused", reason: "unavailable" };
+ } finally {
+ if (handle) await handle.close();
+ }
+}
diff --git a/common/lib/localMedia.test.ts b/common/lib/localMedia.test.ts
@@ -0,0 +1,42 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { coerceLocalMediaConfig, coerceExternalMediaReference } from "./localMedia";
+
+test("source config preserves identity, trims root, and requires explicit playback opt-in", () => {
+ for (const playback of [undefined, false, "true", 1]) {
+ assert.deepEqual(coerceLocalMediaConfig({ sourceId: "library-1", directory: " /mnt/library ", playback }),
+ { sourceId: "library-1", directory: "/mnt/library" });
+ }
+ assert.deepEqual(coerceLocalMediaConfig({ sourceId: "library-1", directory: "D:\\Media", playback: true, secret: "ignored" }),
+ { sourceId: "library-1", directory: "D:\\Media", playback: true });
+});
+test("invalid config is omitted rather than enabling a fallback library", () => {
+ for (const value of [null, [], {}, { sourceId: "../x", directory: "/mnt/library" },
+ { sourceId: "UPPER", directory: "/mnt/library" }, { sourceId: "x", directory: "relative" },
+ { sourceId: "x", directory: "C:relative" }, { sourceId: "x", directory: "//server/share" },
+ { sourceId: "x", directory: "/mnt/\u0000bad" }]) assert.equal(coerceLocalMediaConfig(value), undefined);
+});
+const ref = (relativePath: string) => ({ version: 1, kind: "external", sourceId: "library-1", relativePath });
+test("references preserve literal Unicode and percent filenames; unknown fields cannot become managed pointers", () => {
+ const value = ref("Folder/A 'title' $money ⧸ | %2e%2e.mp4");
+ assert.deepEqual(coerceExternalMediaReference({ ...value, dir: "/outside", file: "owned.mp4" }), value);
+});
+test("references reject cross-platform traversal and unknown formats", () => {
+ for (const name of ["/absolute.mp4", "../a.mp4", "a/../b.mp4", "a/./b.mp4", "a//b.mp4", "C:/a.mp4",
+ "a\\b.mp4", "a.mp4:stream", "a\u0000.mp4", "a.vtt", "", "./a.mp4"]) {
+ assert.equal(coerceExternalMediaReference(ref(name)), null, name);
+ }
+ for (const value of [null, [], { ...ref("a.mp4"), version: 2 }, { ...ref("a.mp4"), kind: "managed" },
+ { ...ref("a.mp4"), sourceId: "../x" }]) assert.equal(coerceExternalMediaReference(value), null);
+});
+
+test("localMediaFetchRefusal: a library channel with no URL, or a local recording anywhere", async () => {
+ const { localMediaFetchRefusal } = await import("./localMedia");
+ const lib = { localMedia: { sourceId: "library-1", directory: "/mnt/library" } };
+ assert.equal(localMediaFetchRefusal("lib", lib),
+ '"lib" is a local media library channel with no online source, so no clip can be fetched for it.');
+ assert.equal(localMediaFetchRefusal("lib", { ...lib, url: "https://www.youtube.com/@x" }, "dQw4w9WgXcQ"), null);
+ assert.match(localMediaFetchRefusal("lib", { url: "https://www.youtube.com/@x" }, "local-" + "c".repeat(32))!, /is a local recording/);
+ assert.equal(localMediaFetchRefusal("yt", { url: "https://www.youtube.com/@x" }, "dQw4w9WgXcQ"), null);
+ assert.equal(localMediaFetchRefusal("nourl", {}), null);
+});
diff --git a/common/lib/localMedia.ts b/common/lib/localMedia.ts
@@ -0,0 +1,96 @@
+// Client-safe shapes only: no filesystem or zod imports. Channel forms and
+// the server schema must share these coercions without shipping server code.
+// A source ID identifies an operator-approved library, not ownership of it.
+export type LocalMediaConfig = {
+ sourceId: string;
+ directory: string;
+ playback?: true;
+};
+export const EXTERNAL_MEDIA_FILENAME = "external-media.json";
+export type ExternalMediaReference = {
+ version: 1;
+ kind: "external";
+ sourceId: string;
+ relativePath: string;
+};
+function record(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+export function isLocalMediaSourceId(value: unknown): value is string {
+ return typeof value === "string" && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(value);
+}
+export function coerceLocalMediaConfig(value: unknown): LocalMediaConfig | undefined {
+ if (!record(value) || !isLocalMediaSourceId(value.sourceId)
+ || typeof value.directory !== "string") return undefined;
+ const directory = value.directory.trim();
+ // Syntax only, on either OS. The server must still use its own path rules,
+ // realpath containment, and source access checks before scanning or serving.
+ // UNC roots are deferred; do not treat a drive-relative C:folder as absolute.
+ if (!directory || /[\x00-\x1f\x7f]/.test(directory)
+ || !(directory.startsWith("/") && !directory.startsWith("//")
+ || /^[A-Za-z]:[\\/]/.test(directory))) return undefined;
+ return { sourceId: value.sourceId, directory,
+ ...(value.playback === true ? { playback: true as const } : {}) };
+}
+export function coerceExternalMediaReference(value: unknown): ExternalMediaReference | null {
+ if (!record(value) || value.version !== 1 || value.kind !== "external"
+ || !isLocalMediaSourceId(value.sourceId) || typeof value.relativePath !== "string") return null;
+ const relativePath = value.relativePath;
+ // Store literal filenames using '/' separators, never URL-decode them.
+ // Reject both OSes' escape syntax regardless of the machine doing the read.
+ // No path normalization: it would conceal traversal or change a source name.
+ if (!relativePath || relativePath.length > 4096 || /[\\:\x00-\x1f\x7f]/.test(relativePath)
+ || relativePath.split("/").some((part) => !part || part === "." || part === "..")
+ || !/\.mp4$/i.test(relativePath)) return null;
+ return { version: 1, kind: "external", sourceId: value.sourceId, relativePath };
+}
+
+// A source-less recording's record id (lib/localRecordingDetails.ts assigns it).
+export const LOCAL_RECORDING_ID_RE = /^local-[0-9a-f]{32}$/;
+
+// A LOCAL MEDIA LIBRARY channel (a library and no online URL) or a local
+// recording in any channel has no online source: a clip window, a full-source
+// fetch or a report video's clip cannot be fetched for it. One sentence, the
+// same at every door (the editor's fetch-window and fetch-windows, the
+// fetch-windows job, the evidence planner, umtool's own fetch); null when the
+// fetch may go ahead. Private playback of the local originals is slice 4.
+export function localMediaFetchRefusal(
+ slug: string,
+ config: { localMedia?: unknown; url?: string | null } | null | undefined,
+ id?: string,
+): string | null {
+ const who = localMediaSubject(slug, config, id);
+ return who ? `${who} with no online source, so no clip can be fetched for it.` : null;
+}
+
+// The same rule for the doors that READ METADATA from the source (refresh
+// metadata, the metadata scan, the browser lookup): a sibling sentence.
+export function localMediaMetadataRefusal(
+ slug: string,
+ config: { localMedia?: unknown; url?: string | null } | null | undefined,
+ id?: string,
+): string | null {
+ const who = localMediaSubject(slug, config, id);
+ return who ? `${who} with no online source, so its metadata cannot be read from one.` : null;
+}
+
+function localMediaSubject(
+ slug: string,
+ config: { localMedia?: unknown; url?: string | null } | null | undefined,
+ id?: string,
+): string | null {
+ const localChannel = !!config?.localMedia && !config.url?.trim();
+ const localRecord = typeof id === "string" && LOCAL_RECORDING_ID_RE.test(id);
+ if (!localChannel && !localRecord) return null;
+ return localRecord ? `"${id}" is a local recording` : `"${slug}" is a local media library channel`;
+}
+
+// A record of a local media library's own (platform "local", or its
+// `local-<32 hex>` id where only the id is known). Until private playback
+// (slice 4) decides otherwise, such a record is built only into PRIVATE-audience
+// sites: a public site's shards, counts, stats, duplicates and reports leave it
+// out (controller/buildIndex.ts, controller/buildStats.ts, bin/compose-site.ts,
+// publish/composeReports.ts). Review ruling, lane/local-media slice 1.
+export function isLocalRecord(rec: { platform?: string | null; id?: string | null }): boolean {
+ return rec.platform === "local" || (typeof rec.id === "string" && LOCAL_RECORDING_ID_RE.test(rec.id));
+}
diff --git a/common/lib/localMediaCommit-server.test.ts b/common/lib/localMediaCommit-server.test.ts
@@ -0,0 +1,89 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile, lstat } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { commitLocalMediaRecord } from "./localMediaCommit-server";
+
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-media-commit-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const dataDirectory = path.join(root, "data"); await mkdir(dataDirectory);
+ const input = { dataDirectory, directoryId: "test-id",
+ metadata: JSON.stringify({ id: "test-id", title: "Synthetic", duration: 3, upload_date: "20261030", webpage_url: "https://www.youtube.com/watch?v=test-id" }),
+ transcript: "WEBVTT\r\n\r\n00:00:01.000 --> 00:00:02.000\r\nSynthetic cue\r\n",
+ reference: { version: 1, kind: "external", sourceId: "library-1", relativePath: "Original ⧸ $title.mp4" } };
+ return { root, input, target: path.join(dataDirectory, "test-id") };
+}
+test("publishes only canonical text/reference files, metadata last, preserving supplied bytes", async (t) => {
+ const f = await fixture(t);
+ const result = await commitLocalMediaRecord(f.input, { afterReserve: async () => {
+ assert.deepEqual(await readdir(f.target), []);
+ assert.deepEqual(await readdir(f.input.dataDirectory), ["test-id"]);
+ } });
+ assert.deepEqual(result, { status: "imported" });
+ assert.deepEqual((await readdir(f.target)).sort(), ["external-media.json", "metadata.info.json", "transcript.en.vtt"]);
+ assert.equal(await readFile(path.join(f.target, "metadata.info.json"), "utf8"), f.input.metadata);
+ assert.equal(await readFile(path.join(f.target, "transcript.en.vtt"), "utf8"), f.input.transcript);
+ assert.deepEqual(JSON.parse(await readFile(path.join(f.target, "external-media.json"), "utf8")), f.input.reference);
+ assert.deepEqual(await readdir(f.root), ["data"]);
+});
+test("retry never overwrites an imported record", async (t) => {
+ const f = await fixture(t); assert.deepEqual(await commitLocalMediaRecord(f.input), { status: "imported" });
+ await writeFile(path.join(f.target, "transcript.en.vtt"), "operator edit");
+ assert.deepEqual(await commitLocalMediaRecord(f.input), { status: "occupied" });
+ assert.equal(await readFile(path.join(f.target, "transcript.en.vtt"), "utf8"), "operator edit");
+});
+test("existing empty directory is occupied, not replaced by rename", async (t) => {
+ const f = await fixture(t); await mkdir(f.target);
+ assert.deepEqual(await commitLocalMediaRecord(f.input), { status: "occupied" });
+ assert.deepEqual(await readdir(f.target), []);
+});
+test("concurrent commits have exactly one winner", async (t) => {
+ const f = await fixture(t);
+ const results = await Promise.all([commitLocalMediaRecord(f.input), commitLocalMediaRecord(f.input)]);
+ assert.deepEqual(results.map(r => r.status).sort(), ["imported", "occupied"]);
+ assert.equal(await readFile(path.join(f.target, "metadata.info.json"), "utf8"), f.input.metadata);
+});
+test("competing file publication is preserved and metadata is not published", async (t) => {
+ const f = await fixture(t);
+ const result = await commitLocalMediaRecord(f.input, { afterReserve: () => writeFile(path.join(f.target, "transcript.en.vtt"), "other producer") });
+ assert.equal(result.status, "failed"); assert.equal(result.incomplete, true);
+ assert.equal(await readFile(path.join(f.target, "transcript.en.vtt"), "utf8"), "other producer");
+ await assert.rejects(lstat(path.join(f.target, "metadata.info.json")), { code: "ENOENT" });
+ assert.deepEqual(await commitLocalMediaRecord(f.input), { status: "occupied" });
+});
+test("cancellation before starting has no writes; cancellation after reservation leaves reviewable partial directory", async (t) => {
+ const f = await fixture(t);
+ const early = new AbortController(); early.abort();
+ await assert.rejects(commitLocalMediaRecord({ ...f.input, signal: early.signal }));
+ assert.deepEqual(await readdir(f.input.dataDirectory), []);
+ const late = new AbortController();
+ const result = await commitLocalMediaRecord({ ...f.input, signal: late.signal }, { afterReserve: async () => { late.abort(); } });
+ assert.deepEqual(result, { status: "failed", incomplete: true, reason: "cancelled" });
+ assert.deepEqual(await readdir(f.target), []);
+ assert.deepEqual(await readdir(f.root), ["data"]);
+});
+test("invalid input is rejected before creating a record or staging directory", async (t) => {
+ const f = await fixture(t);
+ for (const change of [{ directoryId: "../escape" }, { metadata: "{}" }, { transcript: "WEBVTT\n" }, { reference: {} }]) {
+ await assert.rejects(commitLocalMediaRecord({ ...f.input, ...change }));
+ }
+ assert.deepEqual(await readdir(f.root), ["data"]);
+ assert.deepEqual(await readdir(f.input.dataDirectory), []);
+});
+test("injected disk failure leaves no indexable record and never reports success", async (t) => {
+ const f = await fixture(t);
+ const result = await commitLocalMediaRecord(f.input, { afterReserve: async () => { throw Object.assign(new Error("disk full"), { code: "ENOSPC" }); } });
+ assert.deepEqual(result, { status: "failed", incomplete: true, reason: "ENOSPC" });
+ await assert.rejects(lstat(path.join(f.target, "metadata.info.json")), { code: "ENOENT" });
+});
+
+test("failure after publishing transcript still leaves metadata absent and preserves competing reference", async (t) => {
+ const f = await fixture(t);
+ const result = await commitLocalMediaRecord(f.input, { afterReserve: () => writeFile(path.join(f.target, "external-media.json"), "other reference") });
+ assert.equal(result.status, "failed"); assert.equal(result.incomplete, true);
+ assert.equal(await readFile(path.join(f.target, "transcript.en.vtt"), "utf8"), f.input.transcript);
+ assert.equal(await readFile(path.join(f.target, "external-media.json"), "utf8"), "other reference");
+ await assert.rejects(lstat(path.join(f.target, "metadata.info.json")), { code: "ENOENT" });
+});
diff --git a/common/lib/localMediaCommit-server.ts b/common/lib/localMediaCommit-server.ts
@@ -0,0 +1,118 @@
+import { requireLocalRecordingMetadata } from "./localRecordingMetadata";
+import path from "node:path";
+import { link, lstat, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
+import { coerceExternalMediaReference, EXTERNAL_MEDIA_FILENAME } from "./localMedia";
+import { writeExternalMediaReference } from "./externalMedia-server";
+import { extractVideoId } from "./videoId";
+import { parseVtt } from "./vtt";
+
+export type LocalMediaCommitResult = {
+ status: "imported" | "occupied" | "failed";
+ incomplete?: boolean;
+ reason?: string;
+ stagingCleanupFailed?: boolean;
+};
+
+// TRANSACTION PRIMITIVE, not the application importer. The future controller
+// must supply a guarded, corpus-owned real data directory and freshly read,
+// validated source bytes. This helper has no source-media path and cannot copy
+// or delete the MP4. It validates its immutable input again before any writes.
+//
+// WHY NOT rename(staging, destination): POSIX rename can replace an existing
+// empty directory. Instead, mkdir reserves the destination exclusively, then
+// link publishes each complete staged file WITHOUT replacing an existing name.
+// Metadata is linked LAST because the indexer's discovery requires it. Staging
+// is a sibling of data/, never inside the indexer's recording directory walk.
+// These hard links are between CORPUS files only, never to external media.
+//
+// Failure after reservation leaves a metadata-less partial record for explicit
+// review. Do not recursively roll it back: another producer might have written
+// there meanwhile. A retry returns occupied, never merges/overwrites. This is
+// fail-safe retry handling, not automatic recovery. The caller must surface it.
+// No portable multi-file transaction promises crash durability or protection
+// against an unrelated writer concurrently replacing ancestor directories.
+export async function commitLocalMediaRecord(options: {
+ dataDirectory: string;
+ directoryId: string;
+ metadata: string;
+ transcript: string;
+ reference: unknown;
+ signal?: AbortSignal;
+}, testHooks: { afterReserve?: () => Promise<void> } = {}): Promise<LocalMediaCommitResult> {
+ const { directoryId, metadata, transcript, signal } = options;
+ if (!path.isAbsolute(options.dataDirectory)
+ || !/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(directoryId)
+ || directoryId.endsWith(".") || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(directoryId)) {
+ throw new Error("Invalid corpus directory or recording ID");
+ }
+ const reference = coerceExternalMediaReference(options.reference);
+ if (!reference) throw new Error("Invalid external media reference");
+ if (Buffer.byteLength(metadata) > 32 * 1024 * 1024 || Buffer.byteLength(transcript) > 32 * 1024 * 1024) {
+ throw new Error("Import text exceeds 32 MiB");
+ }
+ let meta;
+ try { meta = JSON.parse(metadata.replace(/^\uFEFF/, "")); } catch { throw new Error("Invalid metadata JSON"); }
+ if (meta && typeof meta === "object" && "local_recording" in meta) {
+ const local = requireLocalRecordingMetadata(meta);
+ if (local.id !== directoryId) throw new Error("Local metadata identity does not match the recording");
+ } else if (!meta || typeof meta !== "object" || Array.isArray(meta) || "entries" in meta
+ || (meta._type !== undefined && meta._type !== "video")
+ || meta.id !== directoryId || typeof meta.webpage_url !== "string"
+ || !/^https?:\/\//i.test(meta.webpage_url) || extractVideoId(meta.webpage_url) !== directoryId
+ || typeof meta.title !== "string" || !meta.title.trim()
+ || typeof meta.duration !== "number" || !Number.isFinite(meta.duration) || meta.duration <= 0
+ || typeof meta.upload_date !== "string" || !/^\d{8}$/.test(meta.upload_date)) {
+ throw new Error("Metadata identity or required fields do not match the recording");
+ }
+ const text = transcript.replace(/^\uFEFF/, "");
+ const cues = parseVtt(text);
+ if (!/^WEBVTT(?:[ \t].*)?(?:\r?\n|$)/.test(text)
+ || !cues.some((cue) => cue.end > cue.start)
+ || cues.some((cue) => !Number.isFinite(cue.start) || !Number.isFinite(cue.end) || cue.start < 0 || cue.end < cue.start)) {
+ throw new Error("Transcript has no usable cues or has reversed intervals");
+ }
+ signal?.throwIfAborted();
+ const rootInfo = await lstat(options.dataDirectory);
+ if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink()) throw new Error("Corpus data directory must be a real directory");
+ const root = await realpath(options.dataDirectory);
+ const target = path.join(root, directoryId);
+ const stage = await mkdtemp(path.join(path.dirname(root), ".local-media-import-"));
+ let reserved = false;
+ let result: LocalMediaCommitResult = { status: "failed" };
+ try {
+ // Stage only validated immutable text, without serializing the original
+ // metadata/transcript again. Bytes supplied by the controller are retained.
+ await writeFile(path.join(stage, "metadata.info.json"), metadata, { flag: "wx" });
+ await writeFile(path.join(stage, "transcript.en.vtt"), transcript, { flag: "wx" });
+ // The declared sidecar's writer (lib/externalMedia-server.ts), into the
+ // private staging dir; the hard link below publishes it.
+ await writeExternalMediaReference(stage, reference);
+ signal?.throwIfAborted();
+ try { await mkdir(target); reserved = true; }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ result = { status: "occupied" };
+ return result;
+ }
+ // Fault-injection seam for transaction boundary tests; production callers
+ // do not supply hooks. It runs before any canonical file is published.
+ await testHooks.afterReserve?.();
+ for (const name of ["transcript.en.vtt", EXTERNAL_MEDIA_FILENAME, "metadata.info.json"]) {
+ signal?.throwIfAborted();
+ const current = await lstat(target);
+ if (!current.isDirectory() || current.isSymbolicLink()) throw new Error("Destination changed");
+ await link(path.join(stage, name), path.join(target, name));
+ }
+ result = { status: "imported" };
+ return result;
+ } catch (error) {
+ result = { status: "failed", incomplete: reserved,
+ reason: signal?.aborted ? "cancelled" : (error as NodeJS.ErrnoException).code || "publication-failed" };
+ return result;
+ } finally {
+ // Only our unique staging directory is eligible for cleanup. A cleanup
+ // failure must not turn a committed record into an apparent failed import.
+ try { await rm(stage, { recursive: true, force: true }); }
+ catch { result.stagingCleanupFailed = true; }
+ }
+}
diff --git a/common/lib/localMediaScan.test.ts b/common/lib/localMediaScan.test.ts
@@ -0,0 +1,174 @@
+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<string, string> = {};
+ 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); }
+});
+
+// The parser reads only hh:mm:ss.mmm cue timings until slice 2 lands its
+// short-form support (with a corpus regression check). Until then a short-form
+// VTT is held for review, never imported with missing or misread cues.
+test("short-form timestamps are held for review, not imported", 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, "issue");
+ assert.match(row.issues.join(), /no usable cues/);
+ assert.equal(row.fingerprint, undefined);
+});
+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:00:03.000 --> 00: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);
+});
diff --git a/common/lib/localMediaScan.ts b/common/lib/localMediaScan.ts
@@ -0,0 +1,228 @@
+import { localTranscriptVtt, localTranscriptFingerprint } from "./localMediaTranscript";
+import { createHash } from "node:crypto";
+import type { Stats } from "node:fs";
+import path from "node:path";
+import { lstat, open, readdir, realpath } from "node:fs/promises";
+import { extractVideoId } from "./videoId";
+import { parseVtt } from "./vtt";
+
+// Read-only discovery, not an executable import plan. The caller supplies the
+// destination inventory after applying channel storage guards; this leaf never
+// opens the live corpus. Import must revalidate inputs under its own lock.
+// "existing" means the directory is occupied, not that its contents match.
+export type LocalMediaCandidate = {
+ media: string; metadata: string; transcript: string;
+ savedRecordAvailable?: boolean;
+ recordId?: string; directoryId?: string; title?: string; cueCount?: number;
+ status: "new" | "existing" | "issue";
+ issues: string[];
+ warnings: string[];
+ fingerprint?: string;
+ // Present only when the MP4 and transcript are usable and the metadata file is
+ // absent. Invalid existing metadata is never replaced by generated details.
+ preparationFingerprint?: string;
+ generatedMetadata?: true;
+ // Read-only eligibility for future subtitle generation, never import authority.
+ // Set only when both matching subtitle companions are absent. Existing bad
+ // subtitles remain issues instead of being replaced by generated text.
+ transcriptionFingerprint?: string;
+ transcriptionNeedsDetails?: true;
+};
+export type LocalMediaScan = {
+ candidates: LocalMediaCandidate[];
+ counts: { discovered: number; new: number; existing: number; issues: number };
+};
+const MAX_TEXT_BYTES = 32 * 1024 * 1024;
+
+// Conservative portable names; never sanitize an identity into a collision.
+function safeId(v: unknown): v is string {
+ return typeof v === "string" && /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(v)
+ && !v.endsWith(".") && !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(v);
+}
+async function regularFile(root: string, name: string): Promise<string> {
+ const file = path.join(root, name);
+ const info = await lstat(file);
+ // Milestone one refuses source symlinks, even within the root. The configured
+ // root itself may be a mount/link. This is a preview over a trusted operator's
+ // directory, not a race-proof filesystem sandbox or a playback authorization.
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error("not a regular file; source links are unsupported");
+ const resolved = await realpath(file);
+ const relative = path.relative(root, resolved);
+ if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
+ throw new Error("file resolves outside source directory");
+ }
+ return resolved;
+}
+// Shared bounded reader for scan/import. Names come from a scan, never raw paths.
+export async function readLocalMediaText(root: string, name: string): Promise<string> {
+ if (!name || name === "." || name === ".." || /[\\/]/.test(name)) throw new Error("Expected a bare source filename");
+ if (/\.srt$/i.test(name)) {
+ let vttPresent = false;
+ try { await lstat(path.join(root, name.slice(0, -4) + ".vtt")); vttPresent = true; }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
+ if (vttPresent) throw new Error("Matching VTT appeared; preview again");
+ }
+ const handle = await open(await regularFile(root, name), "r");
+ try {
+ const before = await handle.stat();
+ if (!before.isFile() || before.size > MAX_TEXT_BYTES) throw new Error("not a text file or exceeds 32 MiB");
+ // Bound the actual read, too: a file can grow after stat. Never read MP4
+ // contents or allocate a buffer based on an unchecked sidecar's size.
+ const buffer = Buffer.alloc(before.size + 1);
+ let length = 0;
+ while (length < buffer.length) {
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
+ if (!bytesRead) break;
+ length += bytesRead;
+ }
+ const after = await handle.stat();
+ if (length !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs) {
+ throw new Error("file changed during scan; rescan");
+ }
+ try { return new TextDecoder("utf-8", {fatal: true, ignoreBOM: true}).decode(buffer.subarray(0, length)); }
+ catch { throw new Error("Text must use valid UTF-8 encoding"); }
+ } finally { await handle.close(); }
+}
+function reason(error: unknown): string {
+ // Filesystem errors carry absolute operator paths; report their code only.
+ const e = error as { code?: string; message?: string };
+ if (e.code) return e.code;
+ if (error instanceof SyntaxError) return "invalid JSON";
+ if (error instanceof TypeError) return "invalid metadata value or URL";
+ return e.message || "unreadable file";
+}
+export async function scanLocalMedia(options: {
+ sourceDirectory: string;
+ existingDirectoryIds: readonly string[];
+}): Promise<LocalMediaScan> {
+ if (!path.isAbsolute(options.sourceDirectory)) throw new Error("Source directory must be absolute");
+ const root = await realpath(options.sourceDirectory);
+ // Root errors propagate: an unavailable drive is never a successful empty
+ // scan. Per-candidate failures are collected so other recordings remain visible.
+ const names = (await readdir(root)).sort();
+ const existing = new Set(options.existingDirectoryIds);
+ const candidates: LocalMediaCandidate[] = [];
+ for (const media of names.filter((name) => /\.mp4$/i.test(name))) {
+ const base = media.slice(0, -4);
+ const row: LocalMediaCandidate = {
+ media, metadata: `${base}.info.json`, transcript: names.includes(`${base}.vtt`) ? `${base}.vtt` : names.includes(`${base}.srt`) ? `${base}.srt` : `${base}.vtt`,
+ status: "issue", issues: [], warnings: [],
+ };
+ candidates.push(row);
+ let mediaStat: Stats | undefined;
+ let metadataText = "";
+ let metadataMissing = false;
+ let transcriptText = "";
+ let metadataUsable = false;
+ try { mediaStat = await lstat(await regularFile(root, media)); }
+ catch (error) { row.issues.push(`Media: ${reason(error)}`); }
+ try {
+ metadataText = await readLocalMediaText(root, row.metadata);
+ const meta = JSON.parse(metadataText.replace(/^\uFEFF/, ""));
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)
+ || (meta._type !== undefined && meta._type !== "video") || "entries" in meta) {
+ throw new Error("expected video metadata, not a playlist or collection");
+ }
+ if (!safeId(meta.id)) throw new Error("missing or unsafe metadata id");
+ row.recordId = meta.id;
+ if (typeof meta.title !== "string" || !meta.title.trim()) throw new Error("missing title");
+ row.title = meta.title;
+ if (typeof meta.webpage_url !== "string") throw new Error("missing webpage_url");
+ const url = new URL(meta.webpage_url);
+ if (!["http:", "https:"].includes(url.protocol)) throw new Error("webpage_url must be HTTP or HTTPS");
+ const directoryId = extractVideoId(meta.webpage_url);
+ if (!safeId(directoryId)) throw new Error("URL has no safe canonical directory id");
+ row.directoryId = directoryId;
+ // The native metadata ID and canonical directory ID differ on some
+ // platforms. Keep both, use the existing resolver, and hold mismatches
+ // for review in this first slice rather than guessing at platform joins.
+ if (directoryId !== meta.id) row.issues.push("Metadata and canonical URL IDs differ; mapping requires review");
+ if (typeof meta.upload_date !== "string" || !/^\d{8}$/.test(meta.upload_date)) throw new Error("missing YYYYMMDD upload_date");
+ if (typeof meta.duration !== "number" || !Number.isFinite(meta.duration) || meta.duration <= 0) {
+ throw new Error("duration must be a positive number");
+ }
+ metadataUsable = row.issues.length === 0;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ // Confirm the companion itself is absent, not a failed read through a
+ // link or an unavailable ancestor. Other metadata errors stay blocked.
+ try { await lstat(path.join(root, row.metadata)); }
+ catch (check) { metadataMissing = (check as NodeJS.ErrnoException).code === "ENOENT"; }
+ }
+ row.issues.push(metadataMissing
+ ? "Metadata: matching .info.json file not found. Prepare recording details before import."
+ : `Metadata: ${reason(error)}`);
+ }
+ try {
+ transcriptText = await readLocalMediaText(root, row.transcript);
+ const text = localTranscriptVtt(row.transcript, transcriptText).replace(/^\uFEFF/, "");
+ if (!/^WEBVTT(?:[ \t].*)?(?:\r?\n|$)/.test(text)) throw new Error("missing WEBVTT header");
+ const cues = parseVtt(text);
+ if (!cues.length || cues.some((cue) => !Number.isFinite(cue.start)
+ || !Number.isFinite(cue.end) || cue.start < 0 || cue.end < cue.start)) {
+ throw new Error("no usable cues or invalid cue intervals");
+ }
+ if (!cues.some((cue) => cue.end > cue.start)) throw new Error("no positive-duration cues");
+ // Whisper-derived transcripts can contain isolated point cues. Keep the
+ // original timing and text: widening or dropping them would change the
+ // source. Warn visibly, while backwards intervals still block import.
+ const zeroDuration = cues.filter((cue) => cue.end === cue.start).length;
+ if (zeroDuration) row.warnings.push(
+ "Transcript: " + zeroDuration + " zero-duration cue(s); original timings preserved",
+ );
+ row.cueCount = cues.length;
+ if (/\.srt$/i.test(row.transcript)) row.warnings.push("Transcript: SRT will be converted to VTT on import; original unchanged");
+ else if (names.includes(`${base}.srt`)) row.warnings.push("Transcript: using matching VTT; SRT is not used");
+ } catch (error) { row.issues.push((error as NodeJS.ErrnoException).code === "ENOENT"
+ ? "Transcript: matching subtitle file not found. Add an SRT or VTT file, or generate a transcript if available."
+ : `Transcript: ${reason(error)}`); }
+ if (mediaStat && (metadataUsable || metadataMissing)) {
+ let absent = true;
+ for (const extension of [".vtt", ".srt"]) {
+ try { await lstat(path.join(root, base + extension)); absent = false; }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") absent = false; }
+ }
+ if (absent) {
+ row.transcriptionFingerprint = localMediaFingerprint(media, metadataText, "missing-subtitles-v1", mediaStat);
+ if (metadataMissing) row.transcriptionNeedsDetails = true;
+ }
+ }
+ if (!row.issues.length && mediaStat) row.fingerprint = localMediaFingerprint(media, metadataText, localTranscriptFingerprint(row.transcript, transcriptText), mediaStat);
+ if (metadataMissing && mediaStat && row.issues.length === 1 && row.cueCount) {
+ row.preparationFingerprint = localMediaFingerprint(media, "", localTranscriptFingerprint(row.transcript, transcriptText), mediaStat);
+ }
+ }
+ // Include invalid candidates in collisions: fixing a transcript later must
+ // not silently change which physical recording wins the same identity.
+ const identities = new Map<string, Set<LocalMediaCandidate>>();
+ for (const row of candidates) {
+ for (const id of new Set([row.recordId, row.directoryId])) {
+ if (!id) continue;
+ const group = identities.get(id) ?? new Set<LocalMediaCandidate>();
+ group.add(row); identities.set(id, group);
+ }
+ }
+ for (const group of identities.values()) {
+ if (group.size < 2) continue;
+ for (const row of group) {
+ if (!row.issues.includes("Duplicate identity in source scan")) row.issues.push("Duplicate identity in source scan");
+ }
+ }
+ const counts = { discovered: candidates.length, new: 0, existing: 0, issues: 0 };
+ for (const row of candidates) {
+ if (existing.has(row.directoryId!) || row.issues.includes("Duplicate identity in source scan")) {
+ delete row.transcriptionFingerprint;
+ delete row.transcriptionNeedsDetails;
+ }
+ row.status = row.issues.length ? "issue" : existing.has(row.directoryId!) ? "existing" : "new";
+ if (row.status === "issue") counts.issues++;
+ else counts[row.status]++;
+ }
+ return { candidates, counts };
+}
+
+// A freshness token, not authorization or a full-video checksum. Hash the exact
+// text bytes and MP4 filesystem identity without reading gigabytes of video.
+export function localMediaFingerprint(media: string, metadata: string, transcript: string, info: Pick<Stats, "dev" | "ino" | "size" | "mtimeMs" | "ctimeMs">): string {
+ return createHash("sha256").update(JSON.stringify([media, metadata, transcript, info.dev, info.ino, info.size, info.mtimeMs, info.ctimeMs])).digest("hex");
+}
diff --git a/common/lib/localMediaTranscript.test.ts b/common/lib/localMediaTranscript.test.ts
@@ -0,0 +1,25 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { srtToVtt, localTranscriptVtt, localTranscriptFingerprint } from "./localMediaTranscript";
+
+test("SRT preserves multiline Unicode dialogue, emphasis, overlaps and millisecond boundaries", () => {
+ const input = "\uFEFF1\r\n00:00:01,001 --> 00:00:03,999\r\n<i>Hello</i> & welcome\r\n録画\r\n\r\n2\r\n00:00:02,050 --> 00:00:04,500\r\nSecond line\r\n";
+ assert.equal(srtToVtt(input), "WEBVTT\n\n00:00:01.001 --> 00:00:03.999\n<i>Hello</i> & welcome\n録画\n\n00:00:02.050 --> 00:00:04.500\nSecond line\n");
+});
+test("VTT remains byte-for-byte text and SRT freshness includes unconverted source", () => {
+ const vtt = "\uFEFFWEBVTT\r\n\r\n00:00:01.000 --> 00:00:02.000\r\nHi\r\n";
+ assert.equal(localTranscriptVtt("lesson.vtt", vtt), vtt);
+ assert.equal(localTranscriptFingerprint("lesson.vtt",vtt), vtt);
+ const srt = "1\n00:00:01,000 --> 00:00:02,000\nHi\n";
+ assert.equal(srtToVtt(srt),srtToVtt(srt.replace("1\n","2\n")));
+ assert.notEqual(localTranscriptFingerprint("lesson.srt",srt),localTranscriptFingerprint("lesson.srt",srt.replace("1\n","2\n")));
+});
+test("malformed blocks, invalid clocks, reversed intervals and empty tracks fail without dropping cues", () => {
+ for (const input of ["", "WEBVTT", "1\n00:60:00,000 --> 01:01:00,000\nHi", "1\n00:00:02,000 --> 00:00:01,000\nHi", "1\n00:00:01,000 --> 00:00:02,000", "1\n00:00:01,000 --> 00:00:01,000\nHi", "1\n00:00:01,000 --> 00:00:02,000\nValid\n\ninvalid block", "1\n00:00:01,000 --> 00:00:02,000 X1:1\nUnsupported positioning"]) assert.throws(() => srtToVtt(input));
+});
+test("optional sequence numbers and long hours work; literal timestamp tags cannot change caption parsing", () => {
+ const result = srtToVtt("100:00:00,000 --> 100:00:01,000\n<00:00:00.500> <lesson>\n\n2\n100:00:01,000 --> 100:00:01,000\nPoint cue");
+ assert.ok(result.includes("100:00:00.000 --> 100:00:01.000"));
+ assert.ok(result.includes("<00:00:00.500> <lesson>"));
+ assert.ok(result.includes("100:00:01.000 --> 100:00:01.000"));
+});
diff --git a/common/lib/localMediaTranscript.ts b/common/lib/localMediaTranscript.ts
@@ -0,0 +1,37 @@
+// Conversion is confined to local imports. Existing VTT bytes stay unchanged.
+export function localTranscriptFingerprint(name: string, text: string): string {
+ return /\.srt$/i.test(name) ? JSON.stringify(["srt-v1", name, text]) : text;
+}
+
+export function localTranscriptVtt(name: string, text: string): string {
+ return /\.srt$/i.test(name) ? srtToVtt(text) : text;
+}
+
+// Reject malformed blocks rather than quietly dropping dialogue. No subprocess,
+// guessed duration, cue reordering, or timestamp stretching is involved.
+export function srtToVtt(source: string): string {
+ const text = source.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").trim();
+ if (!text || text.includes("\uFFFD") || text.includes("\0")) throw new Error("SRT is empty or has unsupported text encoding");
+ const timestamp = "(\\d{2,}):([0-5]\\d):([0-5]\\d),([0-9]{3})";
+ const timing = new RegExp("^" + timestamp + "[ \\t]+-->[ \\t]+" + timestamp + "[ \\t]*$");
+ const output: string[] = [];
+ let positive = false;
+ for (const block of text.split(/\n[ \t]*\n+/)) {
+ const lines = block.split("\n");
+ if (/^\d+[ \t]*$/.test(lines[0])) lines.shift();
+ const match = lines.shift()?.match(timing);
+ if (!match || !lines.some(line => line.trim())) throw new Error("SRT has an invalid timing line or empty cue");
+ const seconds = (offset: number) => Number(match[offset]) * 3600 + Number(match[offset + 1]) * 60 + Number(match[offset + 2]) + Number(match[offset + 3]) / 1000;
+ const start = seconds(1), end = seconds(5);
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) throw new Error("SRT has an invalid cue interval");
+ positive ||= end > start;
+ // Keep supported emphasis. Escape other angle brackets so literal dialogue
+ // cannot become VTT timestamps, cue markup, or a block directive.
+ const body = lines.map(line => line.replace(/&(?!amp;|lt;|gt;|nbsp;|lrm;|rlm;)/g, "&")
+ .replace(/<(?!\/?(?:b|i|u)>)/g, "<")).join("\n");
+ const stamp = (offset: number) => `${match[offset]}:${match[offset + 1]}:${match[offset + 2]}.${match[offset + 3]}`;
+ output.push(`${stamp(1)} --> ${stamp(5)}\n${body}`);
+ }
+ if (!positive) throw new Error("SRT has no positive-duration cues");
+ return "WEBVTT\n\n" + output.join("\n\n") + "\n";
+}
diff --git a/common/lib/localRecordingDetails.ts b/common/lib/localRecordingDetails.ts
@@ -0,0 +1,33 @@
+import { createHash } from "node:crypto";
+
+export type LocalRecordingDetails = {
+ mode: "inspect" | "manual";
+ title: string;
+ recordedDate?: string;
+ durationSeconds?: number;
+};
+
+// Stable within one channel's configured library. Changing editable facts or
+// retrying a queued import cannot create another ID. Renaming an original is a
+// different source selection; this is identity assignment, not deduplication.
+// The CHANNEL is part of it (lane/local-media review fix 6): two channels with
+// the same library id and file name are two records, never one id across the
+// corpus (an index key, a citation and a clip all name a record by its id).
+export function localRecordingId(channelSlug: string, sourceId: string, media: string): string {
+ return "local-" + createHash("sha256").update(JSON.stringify(["local-recording-v1", channelSlug, sourceId, media])).digest("hex").slice(0, 32);
+}
+
+export function parseLocalRecordingDetails(value: unknown): LocalRecordingDetails {
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid recording details");
+ const raw = value as Record<string, unknown>;
+ if ((raw.mode !== "manual" && raw.mode !== "inspect") || typeof raw.title !== "string"
+ || !raw.title.trim() || raw.title.length > 1000 || /[\x00-\x1f\x7f]/.test(raw.title)
+ || (raw.recordedDate !== undefined && typeof raw.recordedDate !== "string")
+ || (raw.durationSeconds !== undefined && (raw.mode !== "manual"
+ || typeof raw.durationSeconds !== "number" || !Number.isFinite(raw.durationSeconds) || raw.durationSeconds <= 0))) {
+ throw new Error("Invalid recording details");
+ }
+ return {mode: raw.mode, title: raw.title.trim(),
+ ...(raw.recordedDate !== undefined ? {recordedDate: raw.recordedDate as string} : {}),
+ ...(raw.durationSeconds !== undefined ? {durationSeconds: raw.durationSeconds as number} : {})};
+}
diff --git a/common/lib/localRecordingIntegration.test.ts b/common/lib/localRecordingIntegration.test.ts
@@ -0,0 +1,67 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { prepareManualLocalRecordingMetadata, prepareLocalRecordingMetadata, requireLocalRecordingMetadata, localRecordingProblem } from "./localRecordingMetadata";
+import { summarize, platformFromMetadata, toDisplaySummary } from "./transcripts-server";
+import { defaultWebpageUrl, PLATFORM_VALUES } from "./platform";
+
+const id = "local-" + "a".repeat(32);
+const manual = () => prepareManualLocalRecordingMetadata({id, filename: "Lesson.mp4"});
+
+test("source-less summaries keep unknown dates and duration without a fabricated provider", () => {
+ const value = manual();
+ assert.equal(requireLocalRecordingMetadata(value), value);
+ const summary = summarize("classroom", "20260101_original", value, "Classroom");
+ assert.equal(summary.platform, "local");
+ assert.equal(summary.id, id);
+ assert.equal(summary.webpageUrl, "");
+ assert.equal(summary.uploadDate, "");
+ assert.equal(summary.recordedDate, undefined);
+ assert.equal(summary.duration, 0); // Existing summary convention for unknown duration.
+ assert.equal(toDisplaySummary(summary).date, "");
+ assert.equal(defaultWebpageUrl("local", id), "");
+ assert.ok(PLATFORM_VALUES.includes("local"));
+});
+
+// Review B2: a local recording was never published, so its recording date is
+// its one date — the record sorts and filters by it — and it stays marked as a
+// recording date (recordedDate), never claimed from a provider.
+test("an explicit recording date is the record's date, and stays a recording date", () => {
+ const value = prepareLocalRecordingMetadata({id, filename: "Lesson.mp4", recordedDate: "2024-02-29",
+ probe: {format: {duration: "10.5"}, streams: [{codec_type: "video"}]}});
+ requireLocalRecordingMetadata(value);
+ const summary = summarize("classroom", id, value);
+ assert.equal(summary.recordedDate, "20240229");
+ assert.equal(summary.uploadDate, "20240229");
+ assert.equal(summary.webpageUrl, "");
+ assert.equal(summary.duration, 10.5);
+});
+
+test("a local marker is validated, not used to hide invalid or contradictory metadata", () => {
+ const value = manual();
+ for (const change of [
+ {id: "online-id"}, {title: ""}, {duration: -1}, {filesize: -1},
+ {webpage_url: "https://www.youtube.com/watch?v=anything"}, {upload_date: "20260101"},
+ {local_recording: {}}, {local_recording: {...value.local_recording, durationSource: "ffprobe"}},
+ {recorded_date: "20240230", local_recording: {...value.local_recording, recordedDateSource: "operator"}},
+ {local_recording: {...value.local_recording, privatePath: "/private/archive"}},
+ ]) {
+ assert.throws(() => requireLocalRecordingMetadata({...value, ...change}));
+ assert.ok(localRecordingProblem({...value, ...change}));
+ // Never a throw, and never relabelled as a provider: the index skips it.
+ assert.equal(platformFromMetadata({...value, ...change}), "local");
+ assert.equal(summarize("classroom", id, {...value, ...change}).webpageUrl,
+ "webpage_url" in change ? change.webpage_url : "");
+ }
+ assert.equal(localRecordingProblem(value), null);
+});
+
+test("online metadata retains its provider and date rules even with a local-looking ID", () => {
+ assert.equal(platformFromMetadata({id}), "youtube");
+ for (const [extractor, platform] of [["Youtube", "youtube"], ["Kick", "kick"], ["Rumble", "rumble"],
+ ["Twitch", "twitch"], ["LBRY", "odysee"], ["ArchiveOrg", "archiveorg"], ["BitChute", "bitchute"]]) {
+ assert.equal(platformFromMetadata({extractor_key: extractor}), platform);
+ }
+ const summary = summarize("online", "20260101_original", {id: "video", title: "Online"});
+ assert.equal(summary.uploadDate, "20260101");
+ assert.equal(summary.webpageUrl, "https://www.youtube.com/watch?v=video");
+});
diff --git a/common/lib/localRecordingMetadata.test.ts b/common/lib/localRecordingMetadata.test.ts
@@ -0,0 +1,82 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { prepareLocalRecordingMetadata, prepareManualLocalRecordingMetadata, localRecordingDuration } from "./localRecordingMetadata";
+const id = "local-FAKE-TEST-VALUEFAKE-TEST-VALUE";
+const probe = {format: {duration: "123.456", filename: "/private/archive/lesson.mp4",
+ tags: {creation_time: "2020-01-01", title: "unreviewed tag"}},
+ streams: [{codec_type: "video", disposition: {attached_pic: 0}}]};
+const prepare = (extra = {}) => prepareLocalRecordingMetadata({id, filename: "Classroom lesson.mp4", probe, ...extra});
+test("source-less metadata retains unknown provenance and dates without leaking probe paths", () => {
+ const result = prepare();
+ assert.equal(result.title, "Classroom lesson");
+ assert.equal(result.duration, 123.456);
+ assert.equal(result.local_recording.titleSource, "filename");
+ for (const key of ["upload_date", "recorded_date", "webpage_url", "original_url", "uploader", "timestamp", "extractor"]) assert.equal(key in result, false);
+ assert.equal(JSON.stringify(result).includes("/private"), false);
+ assert.equal(JSON.stringify(result).includes("2020"), false);
+});
+test("operator title/date are distinct from publication metadata and keep identity stable", () => {
+ const result = prepare({title: " Lab session ", recordedDate: "2024-02-29"});
+ assert.equal(result.id, prepare().id);
+ assert.equal(result.title, "Lab session");
+ assert.equal(result.recorded_date, "20240229");
+ assert.equal(result.local_recording.recordedDateSource, "operator");
+ assert.equal("upload_date" in result, false);
+ assert.equal("recorded_date" in prepare({recordedDate: " "}), false);
+});
+test("invalid calendar dates are refused rather than normalized", () => {
+ for (const recordedDate of ["2023-02-29", "2024-04-31", "2024-13-01", "0000-01-01", "yesterday"]) assert.throws(() => prepare({recordedDate}), /real YYYY-MM-DD/);
+});
+test("invalid media durations and audio/cover-only files are refused", () => {
+ for (const value of [undefined, null, true, "N/A", "0x10", "", "-1", 0, -1, Infinity]) {
+ assert.throws(() => localRecordingDuration({...probe, format: {duration: value}}), /duration/);
+ }
+ assert.throws(() => localRecordingDuration({...probe, streams: [{codec_type: "audio"}]}), /video stream/);
+ assert.throws(() => localRecordingDuration({...probe, streams: [{codec_type: "video", disposition: {attached_pic: 1}}]}), /video stream/);
+});
+test("unsafe filenames and identities are refused without sanitizing collisions", () => {
+ for (const filename of ["../lesson.mp4", "C:\\lesson.mp4", "lesson.mkv", "\u0000.mp4", ".mp4"]) assert.throws(() => prepare({filename}));
+ for (const badId of ["providerId", "../local-id", "local-abc"]) assert.throws(() => prepare({id: badId}), /identity/);
+});
+test("preparation is repeatable and does not modify the supplied inspection", () => {
+ const before = JSON.stringify(probe);
+ assert.deepEqual(prepare(), prepare());
+ assert.equal(JSON.stringify(probe), before);
+ assert.equal(prepare({filename: "授業 № 2.MP4"}).title, "授業 № 2");
+});
+
+const manual = (extra = {}) => prepareManualLocalRecordingMetadata({id, filename: "Lesson.mp4", ...extra});
+test("manual preparation needs no probe and leaves duration and date unknown", () => {
+ const metadata = manual({fileSizeBytes: 123456789});
+ assert.equal(metadata.filesize, 123456789);
+ assert.equal(metadata.local_recording.filesizeSource, "filesystem");
+ assert.equal(metadata.local_recording.inspection, "manual");
+ assert.equal(metadata.local_recording.durationSource, "unknown");
+ for (const key of ["duration", "recorded_date", "upload_date", "webpage_url", "timestamp"]) assert.equal(key in metadata, false);
+ assert.equal(metadata.id, prepare().id);
+});
+test("manual duration and date remain operator supplied, never measured or published", () => {
+ const metadata = manual({durationSeconds: 12.5, recordedDate: "2024-02-29", title: " My lesson "});
+ assert.equal(metadata.duration, 12.5);
+ assert.equal(metadata.recorded_date, "20240229");
+ assert.equal(metadata.title, "My lesson");
+ assert.equal(metadata.local_recording.durationSource, "operator");
+ assert.equal(metadata.local_recording.recordedDateSource, "operator");
+ assert.equal(prepare().local_recording.inspection, "ffprobe");
+ assert.equal(prepare().local_recording.durationSource, "ffprobe");
+});
+test("manual mode rejects invalid supplied values instead of replacing them with guesses", () => {
+ for (const durationSeconds of [0, -1, NaN, Infinity, "10", null]) assert.throws(() => manual({durationSeconds}), /duration/);
+ for (const fileSizeBytes of [-1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, "12", null]) assert.throws(() => manual({fileSizeBytes}), /file size/);
+ assert.throws(() => manual({recordedDate: "2023-02-29"}), /real YYYY-MM-DD/);
+ assert.throws(() => manual({filename: "../outside.mp4"}));
+});
+test("file dates and probe tags cannot silently become recording facts in manual mode", () => {
+ const metadata = manual({fileSizeBytes: 0, birthtime: "2020-01-01", mtime: "2021-01-01", probe});
+ assert.equal(metadata.filesize, 0);
+ assert.equal("duration" in metadata, false);
+ assert.equal("recorded_date" in metadata, false);
+ assert.equal(JSON.stringify(metadata).includes("2020"), false);
+ assert.equal(JSON.stringify(metadata).includes("/private"), false);
+ assert.deepEqual(manual(), manual());
+});
diff --git a/common/lib/localRecordingMetadata.ts b/common/lib/localRecordingMetadata.ts
@@ -0,0 +1,157 @@
+// Pure preparation only. No archive paths, filesystem writes, or online lookup.
+// The controller assigns a stable library/file identity, reused on retries.
+export type LocalRecordingMetadata = {
+ id: string;
+ title: string;
+ duration?: number;
+ filesize?: number;
+ recorded_date?: string;
+ local_recording: {
+ version: 1;
+ titleSource: "filename" | "operator";
+ inspection: "ffprobe" | "manual";
+ durationSource: "ffprobe" | "operator" | "unknown";
+ filesizeSource?: "filesystem";
+ recordedDateSource?: "operator";
+ };
+};
+function object(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? value as Record<string, unknown> : null;
+}
+function duration(value: unknown): number | null {
+ // ffprobe represents duration as a decimal string. Do not coerce null, booleans,
+ // hex, or an unavailable duration into a seemingly valid media measurement.
+ if (typeof value === "string" && !/^\d+(?:\.\d+)?$/.test(value)) return null;
+ if (typeof value !== "string" && typeof value !== "number") return null;
+ const number = Number(value);
+ return Number.isFinite(number) && number > 0 ? number : null;
+}
+export function localRecordingDuration(probe: unknown): number {
+ const raw = object(probe);
+ const streams = raw?.streams;
+ if (!Array.isArray(streams) || !streams.some(item => {
+ const stream = object(item);
+ return stream?.codec_type === "video" && object(stream.disposition)?.attached_pic !== 1;
+ })) throw new Error("No video stream found");
+ const seconds = duration(object(raw?.format)?.duration);
+ if (seconds === null) throw new Error("Media duration is unavailable; review the recording");
+ return seconds;
+}
+function recordingDate(value: string | undefined): string | undefined {
+ if (value === undefined || value.trim() === "") return undefined;
+ const date = value.trim();
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || date.slice(0, 4) === "0000") {
+ throw new Error("Recording date must be a real YYYY-MM-DD date");
+ }
+ const parsed = new Date(date + "T00:00:00Z");
+ if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
+ throw new Error("Recording date must be a real YYYY-MM-DD date");
+ }
+ return date.replace(/-/g, "");
+}
+type RecordingDetails = {
+ id: string;
+ filename: string;
+ title?: string;
+ recordedDate?: string;
+};
+function recordingDetails(input: RecordingDetails) {
+ // A separate namespace avoids interpreting local identities as provider IDs.
+ // It is assigned by the server, never derived from an editable title or date.
+ if (!/^local-[0-9a-f]{32}$/.test(input.id)) throw new Error("Invalid local recording identity");
+ if (!input.filename || /[\\/\x00-\x1f\x7f]/.test(input.filename)
+ || !/\.mp4$/i.test(input.filename)) throw new Error("Expected a bare MP4 filename");
+ const supplied = input.title?.trim();
+ const title = supplied || input.filename.slice(0, -4).trim();
+ if (!title || title.length > 1000 || /[\x00-\x1f\x7f]/.test(title)) throw new Error("Enter a valid title (up to 1000 characters)");
+ const date = recordingDate(input.recordedDate);
+ return { id: input.id, title, date, titleSource: supplied ? "operator" as const : "filename" as const };
+}
+export function prepareLocalRecordingMetadata(input: RecordingDetails & { probe: unknown }): LocalRecordingMetadata {
+ const details = recordingDetails(input);
+ return {
+ id: details.id, title: details.title, duration: localRecordingDuration(input.probe),
+ ...(details.date ? { recorded_date: details.date } : {}),
+ local_recording: {
+ version: 1, titleSource: details.titleSource, inspection: "ffprobe", durationSource: "ffprobe",
+ ...(details.date ? { recordedDateSource: "operator" as const } : {}),
+ },
+ };
+}
+
+// Explicit alternative, never a silent fallback after failed inspection. This
+// path needs neither a process nor a probe result. File size comes from the
+// controller's fresh stat, not the form. It cannot establish duration or dates.
+export function prepareManualLocalRecordingMetadata(input: RecordingDetails & {
+ durationSeconds?: number;
+ fileSizeBytes?: number;
+}): LocalRecordingMetadata {
+ const details = recordingDetails(input);
+ if (input.durationSeconds !== undefined && (typeof input.durationSeconds !== "number"
+ || !Number.isFinite(input.durationSeconds) || input.durationSeconds <= 0)) {
+ throw new Error("Enter a positive duration in seconds, or leave it unknown");
+ }
+ if (input.fileSizeBytes !== undefined && (!Number.isSafeInteger(input.fileSizeBytes) || input.fileSizeBytes < 0)) {
+ throw new Error("Invalid file size");
+ }
+ return {
+ id: details.id, title: details.title,
+ ...(input.durationSeconds !== undefined ? { duration: input.durationSeconds } : {}),
+ ...(input.fileSizeBytes !== undefined ? { filesize: input.fileSizeBytes } : {}),
+ ...(details.date ? { recorded_date: details.date } : {}),
+ local_recording: {
+ version: 1, titleSource: details.titleSource, inspection: "manual",
+ durationSource: input.durationSeconds === undefined ? "unknown" : "operator",
+ ...(input.fileSizeBytes !== undefined ? { filesizeSource: "filesystem" as const } : {}),
+ ...(details.date ? { recordedDateSource: "operator" as const } : {}),
+ },
+ };
+}
+
+// Validate persisted local metadata before it enters the corpus or a summary.
+// A local-looking ID alone is never enough to relabel an online recording.
+export function requireLocalRecordingMetadata(value: unknown): LocalRecordingMetadata {
+ const raw = object(value);
+ const mark = object(raw?.local_recording);
+ const invalid = () => { throw new Error("Invalid local recording metadata"); };
+ if (!raw || !mark) return invalid();
+ const keys = ["id", "title", "duration", "filesize", "recorded_date", "local_recording"];
+ const markKeys = ["version", "titleSource", "inspection", "durationSource", "filesizeSource", "recordedDateSource"];
+ if (Object.keys(raw).some(key => !keys.includes(key))
+ || Object.keys(mark).some(key => !markKeys.includes(key))
+ || mark.version !== 1 || !["filename", "operator"].includes(String(mark.titleSource))
+ || typeof raw.id !== "string" || !/^local-[0-9a-f]{32}$/.test(raw.id)
+ || typeof raw.title !== "string" || raw.title !== raw.title.trim()
+ || !raw.title || raw.title.length > 1000 || /[\x00-\x1f\x7f]/.test(raw.title)) return invalid();
+ if (raw.duration !== undefined && (typeof raw.duration !== "number"
+ || !Number.isFinite(raw.duration) || raw.duration <= 0)) return invalid();
+ if (mark.inspection === "ffprobe") {
+ if (raw.duration === undefined || mark.durationSource !== "ffprobe") return invalid();
+ } else if (mark.inspection === "manual") {
+ if (mark.durationSource !== (raw.duration === undefined ? "unknown" : "operator")) return invalid();
+ } else return invalid();
+ if (raw.filesize !== undefined) {
+ if (typeof raw.filesize !== "number" || !Number.isSafeInteger(raw.filesize)
+ || raw.filesize < 0 || mark.filesizeSource !== "filesystem") return invalid();
+ } else if (mark.filesizeSource !== undefined) return invalid();
+ if (raw.recorded_date !== undefined) {
+ if (typeof raw.recorded_date !== "string" || !/^\d{8}$/.test(raw.recorded_date)
+ || mark.recordedDateSource !== "operator") return invalid();
+ const date = raw.recorded_date;
+ recordingDate(date.slice(0, 4) + "-" + date.slice(4, 6) + "-" + date.slice(6));
+ } else if (mark.recordedDateSource !== undefined) return invalid();
+ return raw as LocalRecordingMetadata;
+}
+
+// The same rule as requireLocalRecordingMetadata, as a value: null when the
+// metadata is a valid local recording, else why not. For the readers that
+// must not throw on one bad file (platformFromMetadata, the index).
+export function localRecordingProblem(value: unknown): string | null {
+ try {
+ requireLocalRecordingMetadata(value);
+ return null;
+ } catch (error) {
+ return (error as Error).message || "Invalid local recording metadata";
+ }
+}
diff --git a/common/lib/localRecordingProbe-server.test.ts b/common/lib/localRecordingProbe-server.test.ts
@@ -0,0 +1,57 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, writeFile, chmod, rm, symlink } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { execFileSync } from "node:child_process";
+import { probeLocalRecording } from "./localRecordingProbe-server";
+import { prepareLocalRecordingMetadata } from "./localRecordingMetadata";
+
+test("real ffprobe inspects synthetic MP4 without changing it or requiring an online source", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "local-probe-"));
+ try {
+ const file = path.join(root, "Lesson one.mp4");
+ execFileSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "color=c=black:s=32x32:r=5", "-t", "1", "-c:v", "mpeg4", file], {timeout: 15000});
+ const before = await readFile(file);
+ const probe = await probeLocalRecording({file, ffprobeBin: "ffprobe"});
+ assert.ok(probe.format.duration > 0);
+ assert.deepEqual(await readFile(file), before);
+ const metadata = prepareLocalRecordingMetadata({id: "local-FAKE-TEST-VALUEFAKE-TEST-VALUE", filename: "Lesson one.mp4", probe});
+ assert.equal(metadata.title, "Lesson one");
+ assert.equal("upload_date" in metadata, false);
+ assert.equal("webpage_url" in metadata, false);
+ assert.equal(JSON.stringify(probe).includes(root), false);
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: path.join(root, "missing-tool")}), /ffprobe is unavailable.*editor server/);
+ const abort = new AbortController(); abort.abort();
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: "ffprobe", signal: abort.signal}));
+ const linked = path.join(root, "linked.mp4"); await symlink(file, linked);
+ await assert.rejects(probeLocalRecording({file: linked, ffprobeBin: "ffprobe"}), /regular MP4/);
+ } finally { await rm(root, {recursive: true, force: true}); }
+});
+
+test("corrupt MP4 and remote inputs fail without exposing private diagnostic paths", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "private-probe-"));
+ try {
+ const file = path.join(root, "bad.mp4"); await writeFile(file, "not a video");
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: "ffprobe"}), error => {
+ assert.ok(error instanceof Error); assert.equal(error.message.includes(root), false);
+ return /Media inspection failed/.test(error.message);
+ });
+ await assert.rejects(probeLocalRecording({file: "https://example.com/movie.mp4", ffprobeBin: "ffprobe"}), /absolute local/);
+ } finally { await rm(root, {recursive: true, force: true}); }
+});
+
+test("inspection bounds timeout, output, and invalid JSON from the executable", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "bounded-probe-"));
+ try {
+ const file = path.join(root, "sample.mp4"); await writeFile(file, "fixture");
+ const bin = path.join(root, "probe-fixture");
+ const script = async (body: string) => { await writeFile(bin, "#!/usr/bin/env node\n" + body + "\n"); await chmod(bin, 0o755); };
+ await script("setInterval(() => {}, 1000)");
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: bin, timeoutMs: 200}), /time limit/);
+ await script("process.stdout.write('x'.repeat(1024 * 1024))");
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: bin}), /output limit/);
+ await script("process.stdout.write('not JSON')");
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: bin}), /invalid data/);
+ } finally { await rm(root, {recursive: true, force: true}); }
+});
diff --git a/common/lib/localRecordingProbe-server.ts b/common/lib/localRecordingProbe-server.ts
@@ -0,0 +1,47 @@
+import { execFile } from "node:child_process";
+import path from "node:path";
+import { lstat } from "node:fs/promises";
+import { localRecordingDuration } from "./localRecordingMetadata";
+
+// Internal process adapter, not an HTTP action. The controller must first resolve
+// the file through the configured library and apply channel/storage guards.
+// ffprobeBin comes from Paths (FFPROBE_BIN), never from form input.
+export async function probeLocalRecording(options: {
+ file: string; ffprobeBin: string; signal?: AbortSignal; timeoutMs?: number;
+}): Promise<{ format: { duration: number }; streams: Array<{ codec_type: "video" }> }> {
+ if (!path.isAbsolute(options.file) || !/\.mp4$/i.test(options.file)) throw new Error("Expected an absolute local MP4 path");
+ options.signal?.throwIfAborted();
+ const before = await lstat(options.file);
+ if (!before.isFile() || before.isSymbolicLink()) throw new Error("Expected a regular MP4 file");
+ const timeout = options.timeoutMs ?? 15000;
+ if (!Number.isFinite(timeout) || timeout < 1 || timeout > 15000) throw new Error("Invalid inspection timeout");
+ const stdout = await new Promise<string>((resolve, reject) => {
+ execFile(options.ffprobeBin, ["-v", "error", "-protocol_whitelist", "file",
+ "-f", "mov", "-show_entries", "format=duration:stream=codec_type:stream_disposition=attached_pic",
+ "-of", "json", options.file], {
+ encoding: "utf8", timeout, maxBuffer: 256 * 1024, killSignal: "SIGKILL",
+ windowsHide: true, signal: options.signal,
+ }, (error, output) => {
+ if (!error) { resolve(output); return; }
+ // Never expose ffprobe stderr: it can contain full private source paths.
+ const code = (error as NodeJS.ErrnoException).code;
+ reject(new Error(options.signal?.aborted ? "Media inspection cancelled"
+ : code === "ENOENT" ? "ffprobe is unavailable on the editor server. Install FFmpeg with ffprobe, or configure FFPROBE_BIN."
+ : code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ? "Media inspection exceeded its output limit"
+ : error.killed ? "Media inspection exceeded its time limit"
+ : "Media inspection failed; check that the file is a readable MP4"));
+ });
+ });
+ const after = await lstat(options.file);
+ if (!after.isFile() || after.isSymbolicLink() || before.dev !== after.dev || before.ino !== after.ino
+ || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
+ throw new Error("Recording changed during inspection; preview again");
+ }
+ options.signal?.throwIfAborted();
+ let raw: unknown;
+ try { raw = JSON.parse(stdout); } catch { throw new Error("Media inspection returned invalid data"); }
+ const duration = localRecordingDuration(raw);
+ // Only facts needed by preparation cross this boundary. No tags, filenames,
+ // source URLs or embedded timestamps are copied into managed metadata.
+ return { format: { duration }, streams: [{ codec_type: "video" }] };
+}
diff --git a/common/lib/paths.ts b/common/lib/paths.ts
@@ -373,3 +373,11 @@ function findMonorepoRoot(): string {
}
return start;
}
+
+// The FULL per-channel transcript trees, local recordings included, written
+// beside the shared (public-safe) ones only for a channel that holds a local
+// recording, and copied into PRIVATE-audience sites only (lib/localMedia.ts
+// isLocalRecord; controller/buildIndex.ts, bin/compose-site.ts).
+export function sharedPrivateTranscriptsDir(paths: Pick<Paths, "exportSharedDir">): string {
+ return path.join(paths.exportSharedDir, "private", "transcripts");
+}
diff --git a/common/lib/platform.ts b/common/lib/platform.ts
@@ -3,6 +3,7 @@
// cached entries, so no transcriptStore.ts DB_VERSION bump is needed. Posts get
// their own IDB store rather than sharing the transcript cache.
export type Platform =
+ | "local" // A source-less recording, never detected from a provider URL.
| "youtube"
| "rumble"
| "odysee"
@@ -23,6 +24,7 @@ export type Platform =
| "webpage";
export const PLATFORM_VALUES: ReadonlyArray<Platform> = [
+ "local",
"youtube",
"rumble",
"odysee",
@@ -66,6 +68,7 @@ export { detectPlatform, sameXenforoForum };
// Odysee the canonical id is only the claim hash (the channel-name prefix is
// dropped by extractVideoId), so a reconstructed Odysee URL may not resolve.
export function defaultWebpageUrl(platform: Platform, id: string): string {
+ if (platform === "local") return "";
if (platform === "rumble") return `https://rumble.com/${id}`;
if (platform === "odysee") return `https://odysee.com/${id}`;
if (platform === "twitch") return `https://www.twitch.tv/videos/${id}`;
diff --git a/common/lib/report/draft/refresh/fetch.ts b/common/lib/report/draft/refresh/fetch.ts
@@ -30,7 +30,9 @@ export type RefreshHooks = {
editor: ResearchEditor;
jobOf: JobOf;
// A channel of this editor: what it is and on which platform; null: none.
- channelOf: (slug: string) => Promise<{ kind: "video" | "posts"; platform?: string } | null>;
+ // `localLibrary`: a local media library channel (a library, no URL) —
+ // nothing online to sync, so its sync is a routine skip.
+ channelOf: (slug: string) => Promise<{ kind: "video" | "posts"; platform?: string; localLibrary?: true } | null>;
// Why a fetch on this platform would be refused now (held, cooling down), or null.
platformRefusal?: (platform: string) => Promise<string | null>;
// A channel's "downloaded, not transcribed" recordings (its report's bucket), or null.
@@ -169,6 +171,7 @@ export async function fetchAndBuild(
const fetchChannel = async (slug: string): Promise<FetchStep[]> => {
const ch = await hooks.channelOf(slug).catch(() => null);
if (!ch) return [skip(slug, "sync", "not a channel of this editor")];
+ if (ch.localLibrary) return [skip(slug, "sync", "a local media library: nothing online to sync", true)];
const first = ch.kind === "posts" ? "fetch-posts" : "sync";
if (ch.platform && hooks.platformRefusal) {
const no = await hooks.platformRefusal(ch.platform).catch(() => null);
diff --git a/common/lib/report/draft/refresh/refresh.test.ts b/common/lib/report/draft/refresh/refresh.test.ts
@@ -536,3 +536,21 @@ test("R4.1 fetch: transcription held — transcribe-bucket is skipped and said (
assert.ok(r.warnings.some((w) => /^gone: sync cancelled — the job ended cancelled$/.test(w)), JSON.stringify(r.warnings));
assert.ok(!r.warnings.some((w) => /nothing new to transcribe/.test(w)));
});
+
+// lane/local-media: a local media library channel has nothing online to sync —
+// a routine skip, no job and no warning (it used to be a refused sync).
+test("fetch: a local media library channel's sync is a routine skip, not a refused job", async () => {
+ const calls: Call[] = [];
+ const hooks = {
+ editor: { async run(action: string, args: Record<string, unknown>) { calls.push({ action, args }); return { ok: true, jobId: "j" }; } },
+ jobOf: async () => ({ status: "done", endedAt: Date.now() }),
+ channelOf: async () => ({ kind: "video" as const, localLibrary: true as const }),
+ siteOf: async () => ({ site: null, reason: "no build" }),
+ pollMs: 1,
+ sleep: async () => {},
+ };
+ const r = await fetchAndBuild({ channels: ["library"] }, hooks);
+ assert.deepEqual(calls, []);
+ assert.deepEqual(r.fetch, [{ channel: "library", action: "sync", status: "skipped", reason: "a local media library: nothing online to sync", routine: true }]);
+ assert.deepEqual(r.warnings, []);
+});
diff --git a/common/lib/search/evalTree.test.ts b/common/lib/search/evalTree.test.ts
@@ -393,3 +393,14 @@ test("a transcripts leaf reads the record's alternate tracks; a hit only one hol
],
);
});
+
+// lane/local-media (review B2): an undated record — a local recording with no
+// recording date, uploadDate "" — is outside every bounded date range, from-
+// only and to-only alike, and inside an unbounded one.
+test("passesFilters: an undated record is outside any bounded date range", () => {
+ const rec = { uploadDate: "", isLivestream: false, ageRestricted: false };
+ assert.equal(passesFilters(rec, openFilters(), undefined), true);
+ assert.equal(passesFilters(rec, openFilters({ dateFrom: "20250101" }), undefined), false);
+ assert.equal(passesFilters(rec, openFilters({ dateTo: "20251231" }), undefined), false);
+ assert.equal(passesFilters(rec, openFilters({ dateFrom: "20250101", dateTo: "20251231" }), undefined), false);
+});
diff --git a/common/lib/search/evalTree.ts b/common/lib/search/evalTree.ts
@@ -364,7 +364,10 @@ export function passesFilters(
if (rec.ageRestricted ? !f.restricted : !f.allAges) return false;
// fav — presence on the source platform
if (!f.states.has(avail?.state ?? "available")) return false;
- // fdf / fdt — upload-date range (lexicographic on YYYYMMDD)
+ // fdf / fdt — upload-date range (lexicographic on YYYYMMDD). An undated
+ // record (an undated local recording, "") is outside ANY bounded range — not
+ // only a from-bounded one, which "" < from alone would make it.
+ if ((f.dateFrom || f.dateTo) && !rec.uploadDate) return false;
if (f.dateFrom && rec.uploadDate < f.dateFrom) return false;
if (f.dateTo && rec.uploadDate > f.dateTo) return false;
// tg — curated tags. OR across the selection (a video tagged either
diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -6,6 +6,7 @@ import path from "node:path";
import { SIDECAR_FILENAMES, sidecar, sidecarField } from "./sidecar-server";
import { SUB_FILE_RE } from "./videoStatus";
// Every sidecar module, so the enumeration below sees every declaration.
+import "./externalMedia-server";
import "./archiveOrg-server";
import "./audioIntegrity-server";
import "./attribution-server";
@@ -62,6 +63,7 @@ test("every declared sidecar filename escapes SUB_FILE_RE, and all eighteen are
"do-not-clean.json",
"download-outcome.json",
"exclude-truncated-check.json",
+ "external-media.json",
"find-clips.json",
"frame-scan.poker.json",
"metadata.history.json",
diff --git a/common/lib/transcripts-server.ts b/common/lib/transcripts-server.ts
@@ -1,3 +1,4 @@
+import { localRecordingProblem } from "./localRecordingMetadata";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { formatDate, formatDuration } from "./format";
@@ -12,6 +13,8 @@ import type { MediaType, VideoStat, VideoStatus } from "./stats";
import type { VideoState } from "./availability";
export type RawMetadata = {
+ local_recording?: unknown;
+ recorded_date?: string;
id?: string;
title?: string;
upload_date?: string;
@@ -87,7 +90,19 @@ export function loadRawMetadataFromDir(
// been — the generic extractor (a podcast episode imported by its enclosure
// URL) still lands there, and changing that would relabel records already
// published.
+//
+// A LOCAL RECORDING (lib/localRecordingMetadata.ts) carries a `local_recording`
+// marker and is "local" — even when the marker does not validate: relabelling
+// it as a provider would build a YouTube URL from a `local-…` id. Never a
+// throw (a dozen summarize() callers would fall over on one bad file): an
+// invalid marker is warned once per id here, and the index skips the record
+// with a log line (controller/buildIndex.ts, localRecordingProblem).
export function platformFromMetadata(meta: RawMetadata): Platform {
+ if (meta.local_recording !== undefined) {
+ const problem = localRecordingProblem(meta);
+ if (problem) warnInvalidLocalRecording(meta, problem);
+ return "local";
+ }
const key = meta.extractor_key ?? meta.extractor ?? "";
if (/^rumble/i.test(key)) return "rumble";
if (/^lbry/i.test(key)) return "odysee";
@@ -164,7 +179,13 @@ export function summarize(
id,
channelSlug,
title: meta.title ?? id,
- uploadDate: meta.upload_date ?? dateFromDir ?? "",
+ // A LOCAL RECORDING was never published: its one date is the recording
+ // date the operator gave (`recorded_date`), and that is the date it sorts,
+ // filters and shows by (lane/local-media slice 1, review B2). It keeps
+ // `recordedDate` too. With none it is UNDATED (""): indexed all the same,
+ // last in newest-first, outside any date-bounded filter.
+ uploadDate: platform === "local" ? meta.recorded_date ?? "" : meta.upload_date ?? dateFromDir ?? "",
+ ...(platform === "local" && meta.recorded_date ? { recordedDate: meta.recorded_date } : {}),
duration: meta.duration ?? 0,
channel: configName ?? meta.channel ?? meta.uploader ?? "",
description: meta.description ?? "",
@@ -292,3 +313,13 @@ export function toDisplaySummary(
: {}),
};
}
+
+const warnedLocalRecordings = new Set<string>();
+function warnInvalidLocalRecording(meta: RawMetadata, problem: string): void {
+ const key = typeof meta.id === "string" ? meta.id : JSON.stringify(meta.title ?? null);
+ if (warnedLocalRecordings.has(key)) return;
+ // Bounded: a long-lived server warns about at most this many ids.
+ if (warnedLocalRecordings.size >= 1000) return;
+ warnedLocalRecordings.add(key);
+ console.warn(`Invalid local_recording metadata for ${key}: ${problem}; the index skips it.`);
+}
diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts
@@ -69,6 +69,7 @@
// thrown together (ComposeReportsError), so a failed compose leaves no half
// set of reports behind.
+import { isLocalRecord } from "../lib/localMedia";
import { pageCaptureView, pageCopyLinks } from "../lib/waybackPages/view";
import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
@@ -646,6 +647,13 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
problems.push({ kind: "missing-record", citation: ref, report: report.id, message: `no record ${c.channel}/${c.id} (no metadata or transcript in its data dir)` });
continue;
}
+ // A local recording publishes only on a private host (lane/local-media
+ // slice 1 ruling; lib/localMedia.ts isLocalRecord): its quote and cues
+ // never reach a public site or the public articles.
+ if (host.audience !== "private" && isLocalRecord({ id: c.id, platform: (record.summary as { platform?: string } | null)?.platform })) {
+ problems.push({ kind: "not-visible", citation: ref, report: report.id, message: `${carrier} is public and may not carry the local recording ${c.channel}/${c.id} (local media is private until slice 4)` });
+ continue;
+ }
if (record.cues.length === 0) {
problems.push({ kind: "no-cues", citation: ref, report: report.id, message: `${c.channel}/${c.id} has no transcript cues to check the quote against` });
continue;
diff --git a/common/publish/composeReportsArticles.test.ts b/common/publish/composeReportsArticles.test.ts
@@ -262,3 +262,33 @@ test("nothing published: the stage writes nothing and clears the output root's r
assert.deepEqual(composed, { reports: [], moments: [], allowed: [] });
assert.deepEqual(filesUnder(OUT), []);
});
+
+// lane/local-media review fix 3: a local recording publishes only on a private
+// host — a public build refuses a citation of one; a private build carries it.
+test("refused: a local recording cited in a public build; a private build carries it", async () => {
+ const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata");
+ const LOCAL = "local-" + "f".repeat(32);
+ const dir = path.join(paths.channelsDir, LONE, "data", LOCAL);
+ writeJson(path.join(dir, "metadata.info.json"), prepareManualLocalRecordingMetadata({ id: LOCAL, filename: "talk.mp4", title: "A local talk" }));
+ writeFileSync(path.join(dir, "transcript.en.vtt"), readFileSync(path.join(paths.channelsDir, LONE, "data", "abc123", "transcript.en.vtt")));
+ seedArticle("art-local", { c01: { ...SPAN, id: LOCAL } });
+ await configureArticle("art-local", { published: true, audience: "public" }, paths);
+ try {
+ const pub = await articlesReportHost(paths, { audience: "public" });
+ await assert.rejects(composeHostReports({ paths, host: pub, publicDir: OUT, settings: {}, ...quiet }), (e: unknown) => {
+ assert.ok(e instanceof ComposeReportsError);
+ assert.deepEqual(
+ e.problems.filter((p) => p.citation === "art-local#c01").map((p) => [p.kind, p.message]),
+ [["not-visible", `the articles is public and may not carry the local recording ${LONE}/${LOCAL} (local media is private until slice 4)`]],
+ );
+ return true;
+ });
+ const priv = await articlesReportHost(paths, { audience: "private" });
+ const composed = await composeHostReports({ paths, host: priv, publicDir: OUT, settings: {}, ...quiet }).catch((e: unknown) => e);
+ const problems = composed instanceof ComposeReportsError ? composed.problems : [];
+ assert.deepEqual(problems.filter((p) => p.citation === "art-local#c01"), []);
+ } finally {
+ await configureArticle("art-local", { published: false }, paths);
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/publish/inputSig.test.ts b/common/publish/inputSig.test.ts
@@ -250,3 +250,30 @@ test("hubSig: the stamp, homepage.json, and each listed site's id + url + title"
rmSync(s.root, { recursive: true, force: true });
}
});
+
+// Re-review F2 (lane/local-media): a PRIVATE-audience site signs the transcript
+// tree it actually copies — a channel's full tree under shared/private where it
+// has one; a public site keeps signing the shared tree and does not move when
+// only the private tree does.
+test("a private site signs a member's private transcript tree; a public site does not see it", async () => {
+ const s = setup();
+ try {
+ (s.paths as { exportSharedDir: string }).exportSharedDir = path.join(s.root, ".export-index", "shared");
+ const privateTree = path.join(s.root, ".export-index", "shared", "private", "transcripts", "a");
+ s.write(path.join(privateTree, "page-0000.json"), "[1,\"local\"]");
+ const publicBefore = await s.sig();
+ s.write(path.join(privateTree, "page-0001.json"), "[\"another local\"]");
+ assert.equal(await s.sig(), publicBefore, "a public site does not sign the private tree");
+
+ (s.site as { audience?: string }).audience = "private";
+ const privateBefore = await s.sig();
+ s.write(path.join(privateTree, "page-0002.json"), "[\"a third local\"]");
+ assert.notEqual(await s.sig(), privateBefore, "a private site signs the tree it copies");
+ // A member with no private tree is still signed by its shared tree.
+ const before = await s.sig();
+ s.write(path.join(s.paths.exportSharedPostsDir, "x", "page-0009.json"), "[9]");
+ assert.notEqual(await s.sig(), before);
+ } finally {
+ rmSync(s.root, { recursive: true, force: true });
+ }
+});
diff --git a/common/publish/inputSig.ts b/common/publish/inputSig.ts
@@ -34,7 +34,7 @@ import path from "node:path";
import { open } from "lmdb";
import { dirSignature } from "../lib/dirSignature";
import { DUPLICATES_FILENAME, DUPLICATE_OVERRIDES_FILENAME } from "../lib/duplicates";
-import type { Paths } from "../lib/paths";
+import { sharedPrivateTranscriptsDir, type Paths } from "../lib/paths";
import { publishedMemberSlugs } from "../lib/postsVisibility";
import type { SiteSettings } from "../lib/settings";
import {
@@ -46,7 +46,7 @@ import {
siteIndexDir,
type Site,
} from "../lib/site";
-import { isCitedOnlyChannel, isListedSite } from "../lib/siteSchema";
+import { isCitedOnlyChannel, isListedSite, isPrivateSite } from "../lib/siteSchema";
import { INDEX_SCANNED_AT_KEY } from "../lib/stats";
import { readChannelConfig } from "../controller/channels";
import type { ChannelConfig } from "../lib/channelConfig";
@@ -112,9 +112,19 @@ export async function siteInputSig(i: SiteSigInputs): Promise<string> {
const indexDir = siteIndexDir(paths, site.siteId);
lines.push(`site-index\t${await dirSignature(indexDir, CHART_TEMPLATES)}`);
lines.push(`${CHART_TEMPLATES}\t${await fileBytesSig(path.join(indexDir, CHART_TEMPLATES))}`);
+ // The transcript tree a member's copy comes from: for a PRIVATE-audience
+ // site, a channel's full tree (local recordings included) where it has one —
+ // what compose copies (bin/compose-site.ts transcriptsSourceFor; re-review
+ // F2). Every other site, and a channel with none, signs the shared tree, so
+ // their signatures are unchanged.
+ const privateSite = isPrivateSite(site);
+ const transcriptsRoot = (slug: string): string =>
+ privateSite && existsSync(path.join(sharedPrivateTranscriptsDir(paths), slug))
+ ? sharedPrivateTranscriptsDir(paths)
+ : paths.exportSharedTranscriptsDir;
for (const slug of members) {
for (const [tree, root] of [
- ["transcripts", paths.exportSharedTranscriptsDir],
+ ["transcripts", transcriptsRoot(slug)],
["subs", paths.exportSharedSubsDir],
["posts", paths.exportSharedPostsDir],
["digests", paths.exportSharedDigestsDir],
@@ -130,7 +140,7 @@ export async function siteInputSig(i: SiteSigInputs): Promise<string> {
if (citedOnly.length > 0) lines.push(`cited-only\t${citedOnly.join(",")}`);
for (const slug of citedOnly) {
for (const [tree, root] of [
- ["transcripts", paths.exportSharedTranscriptsDir],
+ ["transcripts", transcriptsRoot(slug)],
["posts", paths.exportSharedPostsDir],
] as const) {
lines.push(`cited/${tree}/${slug}\t${await channelTreeSig(root, slug, cache)}`);
diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts
@@ -42,6 +42,7 @@
// a channel whose media tier is not reachable (lib/channelMedia.ts) is
// reported as unreachable, with the reason, rather than as missing.
+import { localMediaFetchRefusal } from "../lib/localMedia";
import type { Dirent } from "node:fs";
import { readdir, rm } from "node:fs/promises";
import path from "node:path";
@@ -498,7 +499,7 @@ export type EvidenceWindow = {
reason?: string;
};
-export type UnfetchableReason = "not-in-site" | "unreachable" | "gone" | "members-only" | "audio-only" | "too-long";
+export type UnfetchableReason = "not-in-site" | "unreachable" | "gone" | "members-only" | "audio-only" | "too-long" | "local-media";
export type UnfetchableEvidenceWindow = EvidenceWindow & {
why: UnfetchableReason;
@@ -568,6 +569,11 @@ export async function missingEvidenceWindows(
continue;
}
const config = await configOf(slug);
+ const localRefusal = localMediaFetchRefusal(slug, config, id);
+ if (localRefusal) {
+ unfetchable("local-media", localRefusal);
+ continue;
+ }
const audioOnly = isAudioOnlyPlatform(config?.platform);
const source = await resolveEvidenceSource({
channelsDir: paths.channelsDir,
diff --git a/common/publish/reportMediaLocal.test.ts b/common/publish/reportMediaLocal.test.ts
@@ -0,0 +1,67 @@
+// lane/local-media: a site's evidence read lists a cited local recording, and
+// every window of a local media library channel, as UNFETCHABLE ("local-media",
+// lib/localMedia.ts's sentence) — not missing, which a fetch would try to fill.
+// Synthetic ids; nothing is fetched or cut.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/reportMediaLocal.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "report-media-local-"));
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+});
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { missingEvidenceWindows } = await import("./reportMedia");
+
+const paths = getPaths();
+const SITE = "demo-site";
+const LIB = "library";
+const ONLINE = "online";
+const LOCAL_ID = "local-" + "e".repeat(32);
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+};
+writeJson(path.join(paths.channelsDir, LIB, "config.json"), {
+ handling: "youtube", name: "Library", localMedia: { sourceId: "library-1", directory: "/mnt/library" },
+});
+writeJson(path.join(paths.channelsDir, ONLINE, "config.json"), {
+ handling: "youtube", name: "Online", url: "https://www.youtube.com/@online",
+});
+for (const [ch, id] of [[LIB, LOCAL_ID], [LIB, "aaaaaaaaaaa"], [ONLINE, "bbbbbbbbbbb"]]) {
+ writeJson(path.join(paths.channelsDir, ch, "data", id, "metadata.info.json"), { id, duration: 600 });
+}
+writeJson(path.join(paths.sitesDir, SITE, "site.json"), {
+ title: "Demo", channels: [{ slug: LIB }, { slug: ONLINE }], search: false, reports: ["r1"],
+});
+writeJson(path.join(paths.sitesDir, SITE, "reports", "r1", "report.json"), {
+ format: "archilyzer-report", version: 1, id: "r1", kind: "sweep", title: "Report r1",
+ citations: {
+ c01: { kind: "video", channel: LIB, id: LOCAL_ID, start: 10, end: 12, quote: "one" },
+ c02: { kind: "video", channel: LIB, id: "aaaaaaaaaaa", start: 10, end: 12, quote: "two" },
+ c03: { kind: "video", channel: ONLINE, id: "bbbbbbbbbbb", start: 10, end: 12, quote: "three" },
+ },
+ sections: [{ id: "s1", title: "One", body: "[c01](cite:c01) [c02](cite:c02) [c03](cite:c03)" }],
+});
+
+test("a local recording and a local library channel's windows are unfetchable, the online one missing", async () => {
+ const r = await missingEvidenceWindows(paths, SITE);
+ assert.deepEqual(r.problems, []);
+ assert.deepEqual(r.unfetchable.map((w) => [w.id, w.why]).sort(), [["aaaaaaaaaaa", "local-media"], [LOCAL_ID, "local-media"]]);
+ for (const w of r.unfetchable) assert.match(w.message, /no online source, so no clip can be fetched for it\./);
+ assert.deepEqual(r.missing.map((w) => w.id), ["bbbbbbbbbbb"]);
+});
diff --git a/common/views/channelRow.ts b/common/views/channelRow.ts
@@ -80,6 +80,8 @@ export type ChannelRowView = {
// `config.name`, "" when unset.
name: string;
handling: ChannelConfig["handling"];
+ // Display-only wording; the pipeline handling value remains unchanged.
+ handlingLabel?: string;
// Whether the channel has a URL — Sync and Download need one.
hasUrl: boolean;
// A social (posts) channel: its Sync runs fetch-posts, never the yt-dlp
@@ -201,6 +203,7 @@ export function buildChannelRowView(i: ChannelRowInput): ChannelRowView {
slug: i.slug,
name: i.config.name ?? "",
handling: i.config.handling,
+ handlingLabel: i.config.localMedia && !i.config.url?.trim() ? "Local media" : i.config.handling,
hasUrl: Boolean(i.config.url),
social: isSocialChannel(i.config),
excludeFromBuild: i.config.excludeFromBuild === true,
diff --git a/common/views/pipeline/channelFlow.test.ts b/common/views/pipeline/channelFlow.test.ts
@@ -355,3 +355,25 @@ test("the flow says which corrupt full sources await full audio, and the salvage
assert.ok(plain.some((s) => s.label === "salvaged transcript"));
assert.ok(!plain.some((s) => s.label === "awaiting full audio"));
});
+
+test("local source satisfies configuration without claiming an online sync", () => {
+ const config: ChannelConfig = { handling: "youtube", localMedia: { sourceId: "archive", directory: "/library" } };
+ const stages = computeStageStatuses({ snapshot: snapshotOf(), failedVideoIds: [], config, runningJobs: [] });
+ assert.equal(stages.configure.tone, "neutral");
+ assert.match(stages.configure.summary, /Local archive configured/);
+ assert.match(stages.playlist.summary, /preview the library/);
+});
+
+test("an absent URL alone never implies a local archive", () => {
+ const stages = computeStageStatuses({ snapshot: snapshotOf(), failedVideoIds: [], config: { handling: "youtube" }, runningJobs: [] });
+ assert.equal(stages.configure.tone, "attention");
+ assert.equal(stages.configure.summary, "Channel has no URL — open to configure.");
+ assert.equal(stages.playlist.summary, "Never synced.");
+});
+
+test("adding a library to an online channel preserves all provider stage statuses", () => {
+ const input = { snapshot: snapshotOf(), failedVideoIds: [], config: CONFIG, runningJobs: [{ kind: "sync", status: "running" }] };
+ const online = computeStageStatuses(input);
+ const hybrid = computeStageStatuses({ ...input, config: { ...CONFIG, localMedia: { sourceId: "archive", directory: "/library" } } });
+ assert.deepEqual(hybrid, online);
+});
diff --git a/common/views/pipeline/stageStatus.ts b/common/views/pipeline/stageStatus.ts
@@ -250,6 +250,9 @@ export function computeStageStatuses(
// always reach the buttons; the summary line communicates idle/busy state
// instead of collapsing the controls out of sight. Configure collapses once
// the channel has a URL; Danger zone stays collapsed unless opened.
+ // A local library is a configured source, but does not imply an online sync.
+ // Channels with both retain their provider status and controls.
+ const localOnly = !!config.localMedia && !config.url;
const configure: StageStatus = {
id: "configure",
title: "Configure",
@@ -259,8 +262,10 @@ export function computeStageStatuses(
defaultOpen: true,
summary: config.url
? `${config.handling}${config.platform ? ` · ${config.platform}` : ""}`
- : "Channel has no URL — open to configure.",
- tone: config.url ? "neutral" : "attention",
+ : localOnly
+ ? "Local archive configured — no online URL required."
+ : "Channel has no URL — open to configure.",
+ tone: config.url || localOnly ? "neutral" : "attention",
};
const playlistRunning = runningByStage.has("playlist");
@@ -273,7 +278,9 @@ export function computeStageStatuses(
defaultOpen: true,
summary: playlistRunning
? "Running…"
- : config.lastSyncedAt
+ : localOnly
+ ? "Local archive — preview the library to discover recordings."
+ : config.lastSyncedAt
? `Last sync ${new Date(config.lastSyncedAt).toLocaleString()}`
: "Never synced.",
tone: pickTone({ running: playlistRunning, pending: 0, failed: 0 }),
diff --git a/editor/app/api/ops/_localMediaDoors.test.ts b/editor/app/api/ops/_localMediaDoors.test.ts
@@ -0,0 +1,86 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, readdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { callPost, setupOpsCorpus } from "./_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_localMediaDoors.test.ts"
+//
+// lane/local-media review fix 5: every door that would fetch, transcribe,
+// persist or write media refuses a local media library channel and a local
+// recording with lib/localMedia.ts's ONE sentence ("... with no online source,
+// so no clip can be fetched for it."), or its sibling for the metadata doors
+// ("... so its metadata cannot be read from one."), never a generic empty-URL
+// failure; and attach-media / import-media refuse a record linked to a library
+// original (external-media.json). Through each ops route; no job is queued and
+// no record changes.
+
+const corpus = await setupOpsCorpus(null);
+test.after(() => corpus.cleanup());
+const route = async (name: string) => (await import(`./${name}/route`)).POST;
+
+const LOCAL = "local-" + "e".repeat(32);
+const lib = { sourceId: "library-1", directory: path.join(corpus.root, "library") };
+await mkdir(lib.directory, { recursive: true });
+await corpus.writeChannelConfig("library", { name: "Library", handling: "youtube", url: undefined, sourceKind: "video", localMedia: lib });
+await corpus.writeChannelConfig("hybrid", { name: "Hybrid", handling: "youtube", url: "https://www.youtube.com/@hybrid", platform: "youtube", localMedia: lib });
+const record = async (slug: string, id: string, meta: unknown, extra: Record<string, string> = {}) => {
+ const dir = path.join(corpus.transcripts, "channels", slug, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(meta));
+ await writeFile(path.join(dir, "transcript.en.vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nA cue\n");
+ for (const [name, body] of Object.entries(extra)) await writeFile(path.join(dir, name), body);
+};
+await record("library", "aaaaaaaaaaa", { id: "aaaaaaaaaaa", title: "Provider", upload_date: "20200101", webpage_url: "https://www.youtube.com/watch?v=aaaaaaaaaaa" });
+await record("hybrid", LOCAL, { id: LOCAL, title: "Talk", local_recording: { version: 1, titleSource: "filename", inspection: "manual", durationSource: "unknown" } });
+await record("hybrid", "linkedrec01", { id: "linkedrec01", title: "Linked", upload_date: "20200101", webpage_url: "https://www.youtube.com/watch?v=linkedrec01" },
+ { "external-media.json": JSON.stringify({ version: 1, kind: "external", sourceId: "library-1", relativePath: "linked.mp4" }) });
+const FILE = path.join(corpus.root, "a-file.mp4");
+await writeFile(FILE, "not really a video");
+
+const FETCH = /with no online source, so no clip can be fetched for it\.$/;
+const METADATA = /with no online source, so its metadata cannot be read from one\.$/;
+const LINKED = /^"hybrid\/linkedrec01" is linked to a local media library original \(external-media\.json\), so no media is written into it\.$/;
+const CHANNEL = /^"library" is a local media library channel /;
+const RECORD = new RegExp(`^"${LOCAL}" is a local recording `);
+
+const DOORS: Array<[string, Record<string, unknown>, RegExp, RegExp]> = [
+ ["transcribe-one", { slug: "library", id: "aaaaaaaaaaa" }, CHANNEL, FETCH],
+ ["transcribe-one", { slug: "hybrid", id: LOCAL }, RECORD, FETCH],
+ ["prepare-playable", { slug: "library" }, CHANNEL, FETCH],
+ ["prepare-playable", { slug: "hybrid", ids: [LOCAL] }, RECORD, FETCH],
+ ["persist-videos", { items: [{ slug: "library", id: "aaaaaaaaaaa" }] }, CHANNEL, FETCH],
+ ["persist-videos", { items: [{ slug: "hybrid", id: LOCAL }] }, RECORD, FETCH],
+ ["refresh-metadata", { slug: "library", id: "aaaaaaaaaaa" }, CHANNEL, METADATA],
+ ["refresh-metadata", { slug: "hybrid", id: LOCAL }, RECORD, METADATA],
+ ["metadata-scan", { slug: "library" }, CHANNEL, METADATA],
+ ["browser-lookup", { slug: "library", listing: true }, CHANNEL, METADATA],
+ ["browser-lookup", { slug: "hybrid", ids: [LOCAL] }, RECORD, METADATA],
+ ["fetch-chat", { slug: "library", id: "aaaaaaaaaaa" }, CHANNEL, FETCH],
+ ["fetch-chat", { slug: "hybrid", id: LOCAL }, RECORD, FETCH],
+ ["live-clip", { slug: "library", id: "aaaaaaaaaaa", start: 1, end: 5 }, CHANNEL, FETCH],
+ ["live-clip", { slug: "hybrid", id: LOCAL, start: 1, end: 5 }, RECORD, FETCH],
+ ["import-media", { slug: "library", path: FILE, id: "aaaaaaaaaaa" }, CHANNEL, FETCH],
+ ["import-media", { slug: "hybrid", path: FILE, id: LOCAL }, RECORD, FETCH],
+ ["import-media", { slug: "hybrid", path: FILE, id: "linkedrec01" }, LINKED, LINKED],
+ ["attach-media", { slug: "library", source: corpus.root }, CHANNEL, FETCH],
+ ["attach-media", { slug: "hybrid", source: corpus.root, items: [{ id: LOCAL, path: "a-file.mp4" }] }, RECORD, FETCH],
+ ["attach-media", { slug: "hybrid", source: corpus.root, items: [{ id: "linkedrec01", path: "a-file.mp4" }] }, LINKED, LINKED],
+];
+
+test("every door refuses a local library channel, a local recording and (writers) a linked record, with the one sentence", async () => {
+ const before = await corpus.listJobIds();
+ const dirs = async () => (await readdir(path.join(corpus.transcripts, "channels", "hybrid", "data", "linkedrec01"))).sort();
+ const linkedBefore = await dirs();
+ for (const [name, body, who, sentence] of DOORS) {
+ const r = await callPost(await route(name), body);
+ const label = `${name} ${JSON.stringify(body)} -> ${r.status} ${JSON.stringify(r.body)}`;
+ assert.equal(r.body.ok, false, label);
+ assert.match(String(r.body.error), who, label);
+ assert.match(String(r.body.error), sentence, label);
+ assert.doesNotMatch(String(r.body.error), /Could not determine the video URL|no `url` configured/, label);
+ }
+ assert.deepEqual(await corpus.listJobIds(), before, "no job was queued");
+ assert.deepEqual(await dirs(), linkedBefore, "the linked record is unchanged");
+});
diff --git a/editor/app/api/ops/local-media-configure/route.ts b/editor/app/api/ops/local-media-configure/route.ts
@@ -0,0 +1,26 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { configureLocalMedia } from "yt-dlp-transcript-common/controller/configureLocalMedia";
+import { ops, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, sourceId, directory } -> { ok: true, localMedia }
+//
+// A LOCAL MEDIA LIBRARY for a video channel (controller/configureLocalMedia.ts;
+// the Local media page's Save library): `localMedia` = {sourceId, directory}
+// written through patchChannelConfig, the channel config lock and the schema.
+// Initial opt-in only — a channel that already has a library is refused (the
+// same names could identify different recordings), as are a social channel,
+// queued or running channel work, a relocation, a directory that does not
+// exist or overlaps the channel. Playback is never set here. Nothing is
+// scanned or imported. Synchronous; no job.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "sourceId", "directory"], async (body) => {
+ const localMedia = await configureLocalMedia(getPaths(), reqSlug(body, "slug"), {
+ sourceId: reqString(body, "sourceId"),
+ directory: reqString(body, "directory"),
+ });
+ return NextResponse.json({ ok: true, localMedia });
+ });
+}
diff --git a/editor/app/api/ops/local-media-import/route.test.ts b/editor/app/api/ops/local-media-import/route.test.ts
@@ -0,0 +1,147 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/local-media-import/route.test.ts"
+//
+// The Local media page's five ops twins, end to end over a temp corpus and a
+// synthetic library: configure, preview (writes nothing), prepare (writes
+// nothing), import (one job), and link (dry run, then apply). The library's
+// files are never changed.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "local-media-ops-"));
+// Set before the routes (and getPaths, which caches) are first imported.
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts");
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+const routes = {
+ "local-media-configure": (await import("../local-media-configure/route")).POST,
+ "local-media-preview": (await import("../local-media-preview/route")).POST,
+ "local-media-prepare": (await import("../local-media-prepare/route")).POST,
+ "local-media-import": (await import("./route")).POST,
+ "local-media-link": (await import("../local-media-link/route")).POST,
+};
+const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const CH = path.join(ROOT, "transcripts", "channels");
+const LIB = path.join(ROOT, "library");
+const VTT = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nA library cue\n";
+const info = (id: string) => JSON.stringify({
+ id, title: `Title ${id}`, webpage_url: `https://www.youtube.com/watch?v=${id}`,
+ upload_date: "20200102", duration: 12, extractor_key: "Youtube",
+});
+await mkdir(path.join(CH, "lib"), { recursive: true });
+await writeFile(path.join(CH, "lib", "config.json"), JSON.stringify({ handling: "youtube", name: "lib" }));
+await mkdir(LIB, { recursive: true });
+for (const id of ["aaaaaaaaaaa", "bbbbbbbbbbb"]) {
+ await writeFile(path.join(LIB, `${id}.mp4`), `mp4 ${id}`);
+ await writeFile(path.join(LIB, `${id}.info.json`), info(id));
+ await writeFile(path.join(LIB, `${id}.vtt`), VTT);
+}
+// No .info.json: a recording for Prepare details.
+await writeFile(path.join(LIB, "talk.mp4"), "mp4 talk");
+await writeFile(path.join(LIB, "talk.vtt"), VTT);
+// Held already, with the library's exact bytes: for Verify and link.
+await mkdir(path.join(CH, "lib", "data", "bbbbbbbbbbb"), { recursive: true });
+await writeFile(path.join(CH, "lib", "data", "bbbbbbbbbbb", "metadata.info.json"), info("bbbbbbbbbbb"));
+await writeFile(path.join(CH, "lib", "data", "bbbbbbbbbbb", "transcript.en.vtt"), VTT);
+
+type Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
+async function post(action: keyof typeof routes, body: Record<string, unknown>): Promise<{ status: number; json: Json }> {
+ const res = await routes[action](
+ new Request(`http://localhost/api/ops/${action}`, {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: (await res.json()) as Json };
+}
+async function waitJob(id: string): Promise<string | undefined> {
+ for (let i = 0; i < 200; i++) {
+ const status = getRegistry().get(id)?.status;
+ if (status === "done" || status === "failed") return status;
+ await new Promise((res) => setTimeout(res, 50));
+ }
+ return getRegistry().get(id)?.status;
+}
+
+test("refusals: unknown keys, a missing slug, no library yet, a bad directory", async () => {
+ assert.match((await post("local-media-preview", { slug: "lib", force: true })).json.error, /unknown key\(s\): force/);
+ assert.match((await post("local-media-configure", { sourceId: "x", directory: LIB })).json.error, /"slug" is required/);
+ assert.match((await post("local-media-preview", { slug: "lib" })).json.error, /no valid local media source/);
+ assert.match((await post("local-media-import", { slug: "lib", allNew: true })).json.error, /no valid local media source/);
+ const rel = await post("local-media-configure", { slug: "lib", sourceId: "library-1", directory: "relative" });
+ assert.equal(rel.json.ok, false);
+ assert.equal(JSON.parse(await readFile(path.join(CH, "lib", "config.json"), "utf8")).localMedia, undefined);
+});
+
+test("configure, preview, prepare, import and link, the library untouched", async () => {
+ const before = (await readdir(LIB)).sort();
+ const configured = await post("local-media-configure", { slug: "lib", sourceId: "library-1", directory: LIB });
+ assert.equal(configured.status, 200, JSON.stringify(configured.json));
+ assert.deepEqual(configured.json.localMedia, { sourceId: "library-1", directory: LIB });
+ assert.match((await post("local-media-configure", { slug: "lib", sourceId: "library-2", directory: LIB })).json.error, /already has a library/);
+
+ const previewed = await post("local-media-preview", { slug: "lib" });
+ assert.equal(previewed.status, 200, JSON.stringify(previewed.json));
+ const { preview } = previewed.json;
+ assert.deepEqual(preview.counts, { discovered: 3, new: 1, existing: 1, issues: 1 });
+ const byMedia = Object.fromEntries(preview.candidates.map((c: Json) => [c.media, c]));
+ assert.equal(byMedia["aaaaaaaaaaa.mp4"].status, "new");
+ assert.equal(byMedia["bbbbbbbbbbb.mp4"].status, "existing");
+ assert.ok(byMedia["talk.mp4"].preparationFingerprint);
+ assert.deepEqual(await readdir(path.join(CH, "lib", "data")), ["bbbbbbbbbbb"]);
+
+ const prepared = await post("local-media-prepare", {
+ slug: "lib", sourceToken: preview.sourceToken, media: "talk.mp4",
+ sourceFingerprint: byMedia["talk.mp4"].preparationFingerprint,
+ details: { mode: "manual", title: "A talk", recordedDate: "2021-03-04" },
+ });
+ assert.equal(prepared.status, 200, JSON.stringify(prepared.json));
+ assert.equal(prepared.json.review.metadata.title, "A talk");
+ assert.equal(prepared.json.review.metadata.recorded_date, "20210304");
+ assert.match((await post("local-media-prepare", { slug: "lib", sourceToken: preview.sourceToken, media: "talk.mp4",
+ sourceFingerprint: "x", details: { mode: "nope" } })).json.error, /"details"/);
+
+ const dry = await post("local-media-link", { slug: "lib", sourceToken: preview.sourceToken, media: "bbbbbbbbbbb.mp4",
+ fingerprint: byMedia["bbbbbbbbbbb.mp4"].fingerprint, dryRun: true });
+ assert.equal(dry.json.status, "ready", JSON.stringify(dry.json));
+ assert.deepEqual((await readdir(path.join(CH, "lib", "data", "bbbbbbbbbbb"))).sort(), ["metadata.info.json", "transcript.en.vtt"]);
+ const linked = await post("local-media-link", { slug: "lib", sourceToken: preview.sourceToken, media: "bbbbbbbbbbb.mp4",
+ fingerprint: byMedia["bbbbbbbbbbb.mp4"].fingerprint });
+ assert.equal(linked.json.status, "attached", JSON.stringify(linked.json));
+ assert.deepEqual(JSON.parse(await readFile(path.join(CH, "lib", "data", "bbbbbbbbbbb", "external-media.json"), "utf8")),
+ { version: 1, kind: "external", sourceId: "library-1", relativePath: "bbbbbbbbbbb.mp4" });
+
+ const started = await post("local-media-import", {
+ slug: "lib", sourceToken: preview.sourceToken,
+ selected: [
+ { media: "aaaaaaaaaaa.mp4", fingerprint: byMedia["aaaaaaaaaaa.mp4"].fingerprint },
+ { media: "talk.mp4", fingerprint: prepared.json.review.fingerprint,
+ preparation: { sourceFingerprint: byMedia["talk.mp4"].preparationFingerprint,
+ details: { mode: "manual", title: "A talk", recordedDate: "2021-03-04" } } },
+ ],
+ });
+ assert.equal(started.status, 200, JSON.stringify(started.json));
+ // Review fix 7: the answer says how many were taken and how many remain.
+ assert.equal(started.json.selected, 2);
+ assert.equal(started.json.remaining, 0);
+ assert.equal(await waitJob(started.json.jobId), "done");
+ const data = (await readdir(path.join(CH, "lib", "data"))).sort();
+ assert.equal(data.length, 3);
+ assert.ok(data.includes("aaaaaaaaaaa"));
+ const local = data.find((d) => d.startsWith("local-"))!;
+ assert.equal(JSON.parse(await readFile(path.join(CH, "lib", "data", local, "metadata.info.json"), "utf8")).title, "A talk");
+ assert.deepEqual((await readdir(path.join(CH, "lib", "data", "aaaaaaaaaaa"))).sort(),
+ ["external-media.json", "metadata.info.json", "transcript.en.vtt"]);
+
+ // Nothing new left: allNew says so rather than starting an empty job.
+ assert.match((await post("local-media-import", { slug: "lib", allNew: true })).json.error, /no new recording/);
+ assert.match((await post("local-media-import", { slug: "lib", allNew: true, selected: [] })).json.error, /takes no/);
+ assert.deepEqual((await readdir(LIB)).sort(), before);
+});
diff --git a/editor/app/api/ops/local-media-import/route.ts b/editor/app/api/ops/local-media-import/route.ts
@@ -0,0 +1,59 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { previewLocalMedia } from "yt-dlp-transcript-common/controller/localMediaImport";
+import { NextResponse } from "next/server";
+import { selectAllNew, startLocalMediaImportJob, type LocalMediaJobRequest } from "yt-dlp-transcript-common/controller/localMediaImportJob";
+import { OpsInputError, jobResponse, ops, optBool, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, sourceToken, selected: [{ media, fingerprint, preparation? }] }
+// | { slug, allNew: true }
+// -> { ok: true, jobId, selected, remaining }
+//
+// LOCAL LIBRARY RECORDINGS IMPORTED (jobs/localMediaImportJob.ts; the Local
+// media page's Import selected): one `import-local-media` job on the channel's
+// queue writes each selected recording's metadata.info.json, transcript.en.vtt
+// (an .srt converted) and external-media.json into data/<id>/. The video file
+// stays where it is and is never copied. `selected` is what a
+// local-media-preview answered (its `sourceToken`, each candidate's `media`
+// and `fingerprint`; a prepared one adds `preparation: {sourceFingerprint,
+// details}` with the prepare's fingerprint). `allNew: true` takes a fresh
+// preview here and selects its "new" candidates — the first 1000 in the scan's
+// order when there are more, with `remaining` the count left for the next run
+// (also said in the job's log). Every selection is
+// re-checked before its record is written: a changed file is "stale", an
+// occupied record is left unchanged. Drainable between recordings. The
+// imported records are searchable after the next index build.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "sourceToken", "selected", "allNew"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ const paths = getPaths();
+ let req: LocalMediaJobRequest;
+ let remaining = 0;
+ if (optBool(body, "allNew") === true) {
+ if (body.sourceToken !== undefined || body.selected !== undefined) {
+ throw new OpsInputError('"allNew" takes no "sourceToken" or "selected"');
+ }
+ const all = selectAllNew(await previewLocalMedia(paths, slug));
+ if (all.request.selected.length === 0) throw new OpsInputError("the library has no new recording to import");
+ req = all.request;
+ remaining = all.remaining;
+ } else {
+ if (typeof body.sourceToken !== "string" || !Array.isArray(body.selected)) {
+ throw new OpsInputError('"sourceToken" and "selected" (from local-media-preview) are required, or "allNew": true');
+ }
+ req = { sourceToken: body.sourceToken, selected: body.selected as LocalMediaJobRequest["selected"] };
+ }
+ let started;
+ try {
+ started = await startLocalMediaImportJob(paths, slug, req);
+ } catch (e) {
+ throw new OpsInputError((e as Error).message);
+ }
+ if (!started.ok) return jobResponse(started);
+ void started.stream.cancel();
+ // `selected` and `remaining`: over LOCAL_MEDIA_IMPORT_MAX new recordings,
+ // allNew takes the first ones and says how many are left for the next run.
+ return NextResponse.json({ ok: true, jobId: started.jobId, selected: req.selected.length, remaining });
+ });
+}
diff --git a/editor/app/api/ops/local-media-link/route.ts b/editor/app/api/ops/local-media-link/route.ts
@@ -0,0 +1,30 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { adoptLocalMediaReference } from "yt-dlp-transcript-common/controller/adoptLocalMediaReference";
+import { ops, optBool, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, sourceToken, media, fingerprint, dryRun? }
+// -> { ok: true, status: "attached" | "already-linked" | "conflict" | "ready" }
+//
+// VERIFY AND LINK one record the channel already holds to its local original
+// (controller/adoptLocalMediaReference.ts; the Local media page's Verify and
+// link): for a preview candidate that is "existing", the library's
+// .info.json and transcript are compared BYTE FOR BYTE with the record's
+// metadata.info.json and transcript.en.vtt (an .srt converted first), and
+// only on a match is external-media.json written beside them — never over one
+// already there ("conflict" keeps it). Nothing else in the record changes;
+// linking grants no playback. `dryRun` verifies and answers "ready" (or
+// "already-linked" / "conflict") without writing. Refused while the channel has
+// queued or running work. Synchronous; no job.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "sourceToken", "media", "fingerprint", "dryRun"], async (body) => {
+ const result = await adoptLocalMediaReference(getPaths(), reqSlug(body, "slug"), {
+ sourceToken: reqString(body, "sourceToken"),
+ media: reqString(body, "media"),
+ fingerprint: reqString(body, "fingerprint"),
+ }, { apply: optBool(body, "dryRun") !== true });
+ return NextResponse.json({ ok: true, ...result });
+ });
+}
diff --git a/editor/app/api/ops/local-media-prepare/route.ts b/editor/app/api/ops/local-media-prepare/route.ts
@@ -0,0 +1,40 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { channelWriters } from "yt-dlp-transcript-common/controller/channelWriters";
+import { prepareLocalMediaRecording } from "yt-dlp-transcript-common/controller/localMediaImport";
+import { parseLocalRecordingDetails } from "yt-dlp-transcript-common/lib/localRecordingDetails";
+import { OpsInputError, ops, opsFail, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, sourceToken, media, sourceFingerprint,
+// details: { mode: "inspect" | "manual", title, recordedDate?, durationSeconds? } }
+// -> { ok: true, review: { metadata, fingerprint } }
+//
+// LOCAL RECORDING DETAILS for a library recording with no .info.json
+// (controller/localMediaImport.ts prepareLocalMediaRecording; the Local media
+// page's Prepare details): a title, an optional recording date (YYYY-MM-DD)
+// and, by "inspect", the duration ffprobe measures, or by "manual" the one
+// given (or none). Writes nothing: the `review.fingerprint` is the
+// `fingerprint` local-media-import takes, with `preparation: {sourceFingerprint,
+// details}`, to import it. `sourceFingerprint` is the preview's
+// `preparationFingerprint`. Refused while the channel has queued or running
+// work. Synchronous; no job.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "sourceToken", "media", "sourceFingerprint", "details"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ let details;
+ try { details = parseLocalRecordingDetails(body.details); }
+ catch (e) { throw new OpsInputError(`"details": ${(e as Error).message}`); }
+ if (channelWriters(slug, { includeQueued: true }).length) {
+ return opsFail("wait for this channel's queued or running work to finish", 409);
+ }
+ const review = await prepareLocalMediaRecording(getPaths(), slug, {
+ sourceToken: reqString(body, "sourceToken"),
+ media: reqString(body, "media"),
+ sourceFingerprint: reqString(body, "sourceFingerprint"),
+ details,
+ });
+ return NextResponse.json({ ok: true, review });
+ });
+}
diff --git a/editor/app/api/ops/local-media-preview/route.ts b/editor/app/api/ops/local-media-preview/route.ts
@@ -0,0 +1,25 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { previewLocalMedia } from "yt-dlp-transcript-common/controller/localMediaImport";
+import { ops, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug } -> { ok: true, preview: { sourceToken, counts, candidates } }
+//
+// The channel's local media library SCANNED, writing nothing
+// (controller/localMediaImport.ts previewLocalMedia; the Local media page's
+// Preview library): every .mp4 directly in `localMedia.directory` (not its
+// subdirectories) with its same-named .info.json and .vtt/.srt, each a
+// candidate "new", "existing" (its record's directory is occupied) or "issue"
+// (with `issues`). A candidate's `fingerprint` (import, link) or
+// `preparationFingerprint` (prepare, for one with no .info.json) and the
+// preview's `sourceToken` are what the other local-media actions take; a
+// changed file or config makes them stale. An unreachable library is an
+// error, never an empty preview. Synchronous; no job.
+export async function POST(request: Request) {
+ return ops(request, ["slug"], async (body) => {
+ const preview = await previewLocalMedia(getPaths(), reqSlug(body, "slug"));
+ return NextResponse.json({ ok: true, preview });
+ });
+}
diff --git a/editor/app/channels/[slug]/attachMediaActions.ts b/editor/app/channels/[slug]/attachMediaActions.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaWriteRefusal } from "yt-dlp-transcript-common/controller/localMediaDoors";
import path from "node:path";
import { safeRevalidate } from "../../lib/safeRevalidate";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
@@ -41,6 +42,13 @@ export async function attachMediaAction(
if (!channelConfig) {
return { ok: false, error: `Channel "${slug}" not found` };
}
+ // A local media library channel, or a named item that is a local recording or
+ // linked to a library original (review fix 5); a walk's ids are refused in
+ // the job (controller/attachMedia.ts, class "local-media").
+ for (const id of [undefined, ...(opts.items ?? []).map((i) => i.id)]) {
+ const localRefusal = await localMediaWriteRefusal(paths, slug, channelConfig, id);
+ if (localRefusal) return { ok: false, error: localRefusal };
+ }
const source = opts.source.trim();
if (!path.isAbsolute(source)) {
return { ok: false, error: `"source" must be an absolute path (a directory, a .zip or a .7z)` };
diff --git a/editor/app/channels/[slug]/components/flow/AttentionStrip.tsx b/editor/app/channels/[slug]/components/flow/AttentionStrip.tsx
@@ -36,6 +36,8 @@ export type AttentionInput = {
failedVideoIds: string[];
generatedAt: string;
lastSyncedAt?: string;
+ // Local-only libraries are scanned explicitly, not synced from a provider.
+ onlineSyncApplicable?: boolean;
};
function ageInDays(iso: string | undefined): number | null {
@@ -93,16 +95,18 @@ export function collectAttention(input: AttentionInput): Chip[] {
});
}
}
- if (!input.lastSyncedAt) {
- chips.push({ label: "never synced", stage: "playlist", tone: "warning" });
- } else {
- const days = ageInDays(input.lastSyncedAt);
- if (days != null && days > STALE_SYNC_DAYS) {
- chips.push({
- label: `last synced ${Math.floor(days)} days ago`,
- stage: "playlist",
- tone: "warning",
- });
+ if (input.onlineSyncApplicable !== false) {
+ if (!input.lastSyncedAt) {
+ chips.push({ label: "never synced", stage: "playlist", tone: "warning" });
+ } else {
+ const days = ageInDays(input.lastSyncedAt);
+ if (days != null && days > STALE_SYNC_DAYS) {
+ chips.push({
+ label: `last synced ${Math.floor(days)} days ago`,
+ stage: "playlist",
+ tone: "warning",
+ });
+ }
}
}
diff --git a/editor/app/channels/[slug]/components/flow/OverviewPanel.tsx b/editor/app/channels/[slug]/components/flow/OverviewPanel.tsx
@@ -25,6 +25,7 @@ const TONE_DOT: Record<StageStatus["tone"], string> = {
};
export type ChannelEssentials = {
+ localArchive?: boolean;
handling: string;
platform?: string;
url?: string;
@@ -125,11 +126,14 @@ export function OverviewPanel({
aria-label="channel essentials"
className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1 text-sm"
>
- <Field label="Handling" value={essentials.handling} />
+ {essentials.localArchive && (
+ <Field label="Source" value={essentials.url ? "Online source and local library" : "Local archive"} />
+ )}
+ <Field label="Handling" value={essentials.localArchive && !essentials.url ? "Local media" : essentials.handling} />
<Field label="Platform" value={essentials.platform ?? "—"} />
<Field
label="URL"
- value={essentials.url ?? "no URL configured"}
+ value={essentials.url ?? (essentials.localArchive ? "Not required for a local archive" : "no URL configured")}
mono
/>
<Field
@@ -155,7 +159,9 @@ export function OverviewPanel({
) : (
"No report has been generated for this channel yet."
)}{" "}
- {lastSyncedAt
+ {essentials.localArchive && !essentials.url
+ ? "Local library scans are started from Local library."
+ : lastSyncedAt
? `Last synced ${formatTimestamp(lastSyncedAt)}.`
: "Never synced."}
</p>
diff --git a/editor/app/channels/[slug]/components/flow/StageSwitcher.tsx b/editor/app/channels/[slug]/components/flow/StageSwitcher.tsx
@@ -24,11 +24,13 @@ export function StageSwitcher({
stageOrder,
stages,
selected,
+ showLocalLibrary = false,
}: {
slug: string;
stageOrder: StageId[];
stages: Record<StageId, StageStatus>;
selected: StageId | null;
+ showLocalLibrary?: boolean;
}) {
return (
<nav
@@ -36,6 +38,9 @@ export function StageSwitcher({
className="flex flex-wrap items-center gap-1 border-b border-border pb-2"
>
<Tab href={`/channels/${slug}`} active={selected === null} label="Overview" />
+ {showLocalLibrary && (
+ <Tab href={`/channels/${slug}/local-media`} active={false} label="Local library" />
+ )}
{stageOrder.map((id) => {
const status = stages[id];
return (
diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts
@@ -22,6 +22,8 @@
//
// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file).
+import { localMediaWriteRefusal } from "yt-dlp-transcript-common/controller/localMediaDoors";
+import { localMediaFetchRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import { stat } from "node:fs/promises";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
@@ -62,6 +64,10 @@ export async function importMediaAction(body: Record<string, unknown>): Promise<
const paths = getPaths();
const config = await readChannelConfig(paths, req.slug);
if (!config) return { ok: false, error: `Channel "${req.slug}" not found` };
+ // Both branches (one file, or attach-media's walk): a local media library
+ // channel, a local recording, or a record linked to a library original.
+ const localRefusal = await localMediaWriteRefusal(paths, req.slug, config, req.id);
+ if (localRefusal) return { ok: false, error: localRefusal };
const st = await stat(req.path).catch(() => null);
if (!st) return { ok: false, error: `${req.path} is not there` };
if (isArchivePath(req.path, st.isDirectory())) {
@@ -150,7 +156,11 @@ export async function liveClipAction(body: Record<string, unknown>): Promise<Str
if (!parsed.ok) return parsed;
if (!isValidChannelSlug(parsed.value.slug)) return { ok: false, error: `"${parsed.value.slug}" is not a channel slug` };
const paths = getPaths();
- if (!(await readChannelConfig(paths, parsed.value.slug))) return { ok: false, error: `Channel "${parsed.value.slug}" not found` };
+ const config = await readChannelConfig(paths, parsed.value.slug);
+ if (!config) return { ok: false, error: `Channel "${parsed.value.slug}" not found` };
+ // Before the umtool checks: a local media record has no live source (review fix 5).
+ const localRefusal = localMediaFetchRefusal(parsed.value.slug, config, parsed.value.id);
+ if (localRefusal) return { ok: false, error: localRefusal };
return runLiveClipJob({ paths, request: parsed.value });
}
diff --git a/editor/app/channels/[slug]/local-media/LocalMediaPanel.tsx b/editor/app/channels/[slug]/local-media/LocalMediaPanel.tsx
@@ -0,0 +1,151 @@
+"use client";
+
+import Link from "next/link";
+import { LocalRecordingDetailsForm, type ReviewedLocalRecording } from "./LocalRecordingDetailsForm";
+import { useState, useTransition } from "react";
+import type { LocalMediaConfig } from "yt-dlp-transcript-common/lib/localMedia";
+import type { LocalMediaPreview } from "yt-dlp-transcript-common/controller/localMediaImport";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { cancelJobAction, drainJobAction } from "../../../jobs/actions";
+import { previewLibraryAction, importLibraryAction, linkExistingLibraryRecordingAction } from "./actions";
+
+const button = "rounded border border-border px-3 py-2 disabled:opacity-50";
+export function LocalMediaPanel({ slug, initialConfig }: { slug: string; initialConfig: LocalMediaConfig | null }) {
+ const config = initialConfig;
+ const [preview, setPreview] = useState<LocalMediaPreview | null>(null);
+ const [selected, setSelected] = useState<Set<string>>(new Set());
+ const [error, setError] = useState<string | null>(null);
+ const [pending, start] = useTransition();
+ const [running, setRunning] = useState(false);
+ const [jobId, setJobId] = useState<string | null>(null);
+ const [stopping, setStopping] = useState(false);
+ const [linkResults, setLinkResults] = useState<Record<string, string>>({});
+ const [linking, setLinking] = useState<string | null>(null);
+ const [detailsOpenRequest, setDetailsOpenRequest] = useState(0);
+ const [detailsMedia, setDetailsMedia] = useState<string | null>(null);
+ const [preparing, setPreparing] = useState(false);
+ const [prepared, setPrepared] = useState<Record<string, ReviewedLocalRecording>>({});
+ const busy = pending || running || linking !== null || preparing;
+ const detailsRow = preview?.candidates.find(row => row.media === detailsMedia && row.preparationFingerprint);
+ function canSelect(row: LocalMediaPreview["candidates"][number]) {
+ return row.status === "new" && !!row.fingerprint || !!row.preparationFingerprint && !!prepared[row.media];
+ }
+
+
+ // Results describe this explicit attempt, not a permanent guarantee that a
+ // file remains present. A fresh preview clears them and rechecks eligibility.
+ async function linkExisting(media: string, fingerprint: string) {
+ if (!preview || busy) return;
+ setLinking(media); setError(null);
+ try {
+ const response = await linkExistingLibraryRecordingAction(slug,
+ {sourceToken: preview.sourceToken, media, fingerprint});
+ const message = !response.ok ? response.error
+ : response.result.status === "conflict" ? "Conflict: the existing reference was preserved. Review it before continuing."
+ : response.result.status === "attached" || response.result.status === "already-linked"
+ ? (response.result.status === "attached" ? "Linked to local original." : "Already linked to this local original.")
+ + (response.result.stagingCleanupFailed ? " Temporary reference cleanup needs review." : "")
+ : "Not linked. Preview again before retrying.";
+ setLinkResults(previous => ({...previous, [media]: message}));
+ } catch {
+ // A lost response does not prove publication failed. Retrying is safe:
+ // the controller recognizes an identical already-published reference.
+ setLinkResults(previous => ({...previous, [media]: "No response from the editor. The link may have been saved; preview and retry to verify."}));
+ } finally { setLinking(null); }
+ }
+
+ return <section className="[&_button:enabled]:cursor-pointer [&_button:enabled:hover]:brightness-125 [&_button:disabled]:cursor-not-allowed space-y-4 rounded border border-border p-4">
+ {/* A library is added through the New channel form (Local Archive) or
+ `pnpm ops local-media-configure` (review fix 8); this route stays
+ reachable by URL for a channel without one, and says how. */}
+ {!config ? <div role="status" className="space-y-2">
+ <p>This channel has no local media library.</p>
+ <p className="text-sm text-muted-foreground">Add one with the New channel form (Local Archive) for a new channel, or for this one:</p>
+ <pre className="whitespace-pre-wrap break-all rounded bg-muted p-2 text-xs">{`pnpm ops local-media-configure --json '{"slug":"${slug}","sourceId":"library-1","directory":"/absolute/path/to/recordings"}'`}</pre>
+ </div> : <>
+ <p><strong>{config.sourceId}</strong> · <code className="break-all">{config.directory}</code></p>
+ <p className="text-sm text-muted-foreground">Each .mp4 directly in this directory, with a same-named .info.json and .vtt (or .srt). Subdirectories are not scanned.</p>
+ <button className={button} disabled={busy} onClick={() => {
+ setError(null); setPreview(null); setSelected(new Set()); setLinkResults({}); setPrepared({}); setDetailsMedia(null);
+ start(async () => {
+ try {
+ const result = await previewLibraryAction(slug);
+ if (result.ok) setPreview(result.preview); else setError(result.error);
+ } catch { setError("Could not contact the editor. Try again."); }
+ });
+ }}>{pending ? "Working…" : "Preview library"}</button>
+ </>}
+ {error && <p role="alert" className="text-destructive">{error}</p>}
+ {preview && <>
+ <p role="status">{preview.counts.discovered} discovered · {preview.counts.new} new · {preview.counts.existing} occupied · {preview.counts.issues} need review</p>
+ <div className="overflow-x-auto"><table className="w-full text-sm text-left">
+ <thead><tr><th>Select</th><th>Recording</th><th>Status</th><th>Cues / notes</th><th>Details / local reference</th></tr></thead>
+ <tbody>{preview.candidates.map(row => <tr key={row.media} className="border-t border-border">
+ <td><input type="checkbox" aria-label={`Import ${row.media}`} disabled={busy || !canSelect(row) || (!selected.has(row.media) && selected.size >= 1000)} checked={selected.has(row.media)} onChange={e => {
+ const next = new Set(selected); if (e.target.checked) next.add(row.media); else next.delete(row.media); setSelected(next);
+ }} /></td>
+ <td className="p-2"><span>{row.title ?? row.media}</span><br /><span className="text-xs text-muted-foreground break-all">{row.media}</span></td>
+ <td>{prepared[row.media] ? "Ready to import" : row.preparationFingerprint ? "Needs details" : row.status === "existing" ? "Occupied" : row.status === "issue" ? "Needs review" : "New"}</td>
+ <td className="p-2">{row.cueCount ?? "—"}{[...(prepared[row.media] ? ["Local recording details reviewed"] : row.issues), ...row.warnings].map((note, index) => <p key={index}>{note}</p>)}</td>
+ <td className="p-2">
+ {row.savedRecordAvailable && row.status !== "existing" && row.directoryId && <div>
+ <Link className={button + " inline-block"} href={"/channels/" + encodeURIComponent(slug) + "/videos/" + encodeURIComponent(row.directoryId)}>Open saved record</Link>
+ <p className="text-sm text-muted-foreground mt-2">Already held; not reverified.</p>
+ </div>}
+ {row.preparationFingerprint && <button type="button" className={button} disabled={busy}
+ aria-label={`Prepare details for ${row.media}`} onClick={() => {
+ setDetailsMedia(row.media); setDetailsOpenRequest(value => value + 1);
+ setSelected(previous => {const next = new Set(previous); next.delete(row.media); return next;});
+ }}>{prepared[row.media] ? "Edit details" : "Prepare details"}</button>}
+ {row.status === "existing" && row.fingerprint && <button type="button" className={button}
+ disabled={busy} aria-label={`Verify and link ${row.media}`}
+ onClick={() => { void linkExisting(row.media, row.fingerprint!); }}>
+ {linking === row.media ? "Verifying…" : "Verify and link"}
+ </button>}
+ {row.status === "existing" && row.generatedMetadata && row.directoryId && <div>
+ <Link className={button + " inline-block"} href={"/channels/" + encodeURIComponent(slug) + "/videos/" + encodeURIComponent(row.directoryId)}
+ aria-label={"Open saved record for " + row.media}>Open saved record</Link>
+ <p className="text-sm text-muted-foreground mt-2">Imported with prepared details; not reverified.</p>
+ </div>}
+ {linkResults[row.media] && <p role="status" className="mt-2">{linkResults[row.media]}</p>}
+ </td>
+ </tr>)}</tbody>
+ </table></div>
+ </>}
+ {detailsRow?.preparationFingerprint && preview && <LocalRecordingDetailsForm
+ key={preview.sourceToken + detailsRow.media + detailsRow.preparationFingerprint}
+ slug={slug} media={detailsRow.media} sourceToken={preview.sourceToken} sourceFingerprint={detailsRow.preparationFingerprint}
+ openRequest={detailsOpenRequest}
+ initialDetails={prepared[detailsRow.media]?.details}
+ disabled={busy} onBusy={setPreparing} onClose={() => setDetailsMedia(null)} onUse={review => {
+ setPrepared(previous => ({...previous, [detailsRow.media]: review}));
+ setSelected(previous => previous.size < 1000 ? new Set([...previous, detailsRow.media]) : previous);
+ setDetailsMedia(null);
+ }} />}
+ {config && <StreamActionLog
+ label="Import local media" buttonLabel={`Import selected (${selected.size})`} runningLabel="Importing…"
+ disabled={busy || detailsMedia !== null || !preview || selected.size === 0}
+ cancelAction={cancelJobAction}
+ extraControls={running && jobId ? <button className={button} disabled={stopping} onClick={async () => {
+ setStopping(true);
+ try { const result = await drainJobAction(jobId); if (!result.ok) { setStopping(false); setError("Could not request a stop. Check the job page."); } }
+ catch { setStopping(false); setError("Could not contact the editor."); }
+ }}>{stopping ? "Stop requested" : "Finish recording and stop"}</button> : undefined}
+ trigger={async () => {
+ if (!preview) return {ok: false as const, error: "Preview the library first"};
+ setRunning(true); setStopping(false); setError(null);
+ try {
+ const result = await importLibraryAction(slug, {sourceToken: preview.sourceToken, selected: preview.candidates.filter(row => selected.has(row.media) && canSelect(row)).map(row => {
+ const review = prepared[row.media];
+ return review && row.preparationFingerprint ? {media: row.media, fingerprint: review.fingerprint,
+ preparation: {sourceFingerprint: row.preparationFingerprint, details: review.details}}
+ : {media: row.media, fingerprint: row.fingerprint!};
+ })});
+ if (result.ok) setJobId(result.jobId); else setRunning(false);
+ return result;
+ } catch { setRunning(false); return {ok: false as const, error: "Could not contact the editor"}; }
+ }}
+ onSettled={() => { setRunning(false); setJobId(null); setPreview(null); setSelected(new Set()); setLinkResults({}); setPrepared({}); setDetailsMedia(null); }}
+ />}
+ </section>;
+}
diff --git a/editor/app/channels/[slug]/local-media/LocalRecordingDetailsForm.tsx b/editor/app/channels/[slug]/local-media/LocalRecordingDetailsForm.tsx
@@ -0,0 +1,78 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import type { LocalRecordingDetails } from "yt-dlp-transcript-common/lib/localRecordingDetails";
+import type { LocalRecordingMetadata } from "yt-dlp-transcript-common/lib/localRecordingMetadata";
+import { prepareLibraryRecordingAction } from "./actions";
+
+export type ReviewedLocalRecording = {fingerprint: string; details: LocalRecordingDetails};
+const input = "block w-full rounded border border-border bg-background p-2";
+const button = "rounded border border-border px-3 py-2 disabled:opacity-50";
+
+export function LocalRecordingDetailsForm({slug, media, sourceToken, sourceFingerprint, initialDetails, openRequest, disabled, onBusy, onUse, onClose}: {
+ slug: string; media: string; sourceToken: string; sourceFingerprint: string; disabled: boolean;
+ initialDetails?: LocalRecordingDetails;
+ openRequest: number;
+ onBusy: (value: boolean) => void; onUse: (review: ReviewedLocalRecording) => void; onClose: () => void;
+}) {
+ const headingRef = useRef<HTMLHeadingElement>(null);
+ useEffect(() => {
+ const heading = headingRef.current;
+ if (!heading) return;
+ heading.focus({preventScroll: true});
+ heading.scrollIntoView({block: "start", behavior: "instant"});
+ }, [openRequest]);
+ const [mode, setMode] = useState<"inspect" | "manual">(initialDetails?.mode ?? "inspect");
+ const [title, setTitle] = useState(initialDetails?.title ?? media.slice(0, -4));
+ const [date, setDate] = useState(initialDetails?.recordedDate ?? "");
+ const [duration, setDuration] = useState(initialDetails?.durationSeconds?.toString() ?? "");
+ const [error, setError] = useState<string | null>(null);
+ const [review, setReview] = useState<{metadata: LocalRecordingMetadata; fingerprint: string; details: LocalRecordingDetails} | null>(null);
+ function changed() { setReview(null); setError(null); }
+ return <form aria-label={`Prepare details for ${media}`} className="space-y-3 rounded border border-border p-4" onSubmit={async event => {
+ event.preventDefault();
+ if (disabled) return;
+ changed();
+ const details: LocalRecordingDetails = {mode, title,
+ ...(date ? {recordedDate: date} : {}),
+ ...(mode === "manual" && duration.trim() ? {durationSeconds: Number(duration)} : {})};
+ if (details.durationSeconds !== undefined && (!Number.isFinite(details.durationSeconds) || details.durationSeconds <= 0)) {
+ setError("Enter a positive duration in seconds or leave it unknown."); return;
+ }
+ onBusy(true);
+ try {
+ const result = await prepareLibraryRecordingAction(slug, {media, sourceToken, sourceFingerprint, details});
+ if (result.ok) setReview({...result.review, details}); else setError(result.error);
+ } catch { setError("Could not contact the editor. No import was requested; try preparing again."); }
+ finally { onBusy(false); }
+ }}>
+ <h3 ref={headingRef} tabIndex={-1} className="scroll-mt-32 font-semibold">Prepare recording details</h3>
+ <p className="break-all text-sm">{media}</p>
+ <fieldset disabled={disabled} className="space-y-3">
+ <legend className="sr-only">Recording details</legend>
+ <label className="block">Method
+ <select className={input} value={mode} onChange={e => {changed(); setMode(e.target.value as "inspect" | "manual");}}>
+ <option value="inspect">Inspect video with ffprobe</option>
+ <option value="manual">Enter details manually</option>
+ </select>
+ </label>
+ <p className="text-sm text-muted-foreground">{mode === "inspect"
+ ? "Reads video properties to measure duration. Requires ffprobe on the editor server; the Docker image includes it with FFmpeg."
+ : "Video properties will not be inspected. Duration and recording date may remain unknown. File size alone cannot establish either."}</p>
+ <label className="block">Title<input className={input} required maxLength={1000} value={title} onChange={e => {changed(); setTitle(e.target.value);}} /></label>
+ <label className="block">Recording date (optional)<input className={input} type="date" value={date} onChange={e => {changed(); setDate(e.target.value);}} /></label>
+ <p className="text-sm text-muted-foreground">The record sorts and filters by this date. Leave it empty if unknown: a file's dates often say when it was copied.</p>
+ {mode === "manual" && <label className="block">Duration in seconds (optional)<input className={input} type="number" min="0.001" step="any" value={duration} onChange={e => {changed(); setDuration(e.target.value);}} /></label>}
+ <button type="submit" className={button}>Review details</button>
+ <button type="button" className={`${button} ml-2`} onClick={onClose}>Cancel</button>
+ </fieldset>
+ {error && <p role="alert" className="text-destructive">{error}</p>}
+ {review && <section aria-label="Prepared recording details" className="space-y-2 border-t border-border pt-3">
+ <p><strong>{review.metadata.title}</strong></p>
+ <p>Duration: {review.metadata.duration === undefined ? "Unknown" : `${review.metadata.duration} seconds (${mode === "inspect" ? "measured" : "entered manually"})`}</p>
+ <p>Recording date: {review.metadata.recorded_date ? `${review.metadata.recorded_date.slice(0,4)}-${review.metadata.recorded_date.slice(4,6)}-${review.metadata.recorded_date.slice(6)} (entered manually)` : "Unknown"}</p>
+ {review.metadata.filesize !== undefined && <p>File size: {review.metadata.filesize.toLocaleString()} bytes</p>}
+ <button type="button" className={button} disabled={disabled} onClick={() => onUse({fingerprint: review.fingerprint, details: review.details})}>Use details for import</button>
+ </section>}
+ </form>;
+}
diff --git a/editor/app/channels/[slug]/local-media/actions.ts b/editor/app/channels/[slug]/local-media/actions.ts
@@ -0,0 +1,54 @@
+"use server";
+import { channelWriters } from "yt-dlp-transcript-common/controller/channelWriters";
+import { adoptLocalMediaReference } from "yt-dlp-transcript-common/controller/adoptLocalMediaReference";
+import { revalidatePath } from "next/cache";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { prepareLocalMediaRecording, type LocalRecordingPreparationRequest, previewLocalMedia } from "yt-dlp-transcript-common/controller/localMediaImport";
+import { startLocalMediaImportJob, type LocalMediaJobRequest } from "yt-dlp-transcript-common/controller/localMediaImportJob";
+
+// These are private editor actions, behind the same deployment access boundary
+// as the channel's existing actions. Do not expose them through the public export.
+// Client input is validated again by the controllers. No absolute source paths
+// are accepted for import; selections refer to the stored source and preview.
+export async function previewLibraryAction(slug: string) {
+ try { return { ok: true as const, preview: await previewLocalMedia(getPaths(), slug) }; }
+ catch (e) {
+ const message = (e as Error).message ?? "";
+ if (message.startsWith("The library directory is inside")) return { ok: false as const, error: message };
+ return { ok: false as const, error: "Could not scan the library. Check its mount, channel settings, and relocation status." };
+ }
+}
+
+export async function importLibraryAction(slug: string, request: LocalMediaJobRequest) {
+ try { return await startLocalMediaImportJob(getPaths(), slug, request); }
+ catch { return { ok: false as const, error: "Could not start the import. Preview the library again and check channel availability." }; }
+}
+
+// One occupied recording per explicit click, not a silent merge during preview.
+// The controller revalidates all client tokens and exact companion bytes, refuses
+// active channel writers, and publishes without replacing an existing reference.
+// This uses the same private editor access boundary as library configuration.
+export async function linkExistingLibraryRecordingAction(slug: string,
+ selection: {sourceToken: string; media: string; fingerprint: string}) {
+ let result;
+ try {
+ result = await adoptLocalMediaReference(getPaths(), slug, selection, {apply: true});
+ } catch {
+ return {ok: false as const, error: "Could not verify and link this recording. Preview again and check that source and archived metadata/transcript files match and the channel is idle."};
+ }
+ // Publication already happened. Cache invalidation failure must not turn a
+ // successful attachment into an apparent failure or encourage blind retries.
+ try { revalidatePath(`/channels/${slug}/local-media`); } catch { /* A manual refresh is sufficient. */ }
+ return {ok: true as const, result};
+}
+
+export async function prepareLibraryRecordingAction(slug: string, request: LocalRecordingPreparationRequest) {
+ try {
+ if (channelWriters(slug, {includeQueued: true}).length) {
+ return {ok: false as const, error: "Wait for channel work to finish before preparing details."};
+ }
+ return {ok: true as const, review: await prepareLocalMediaRecording(getPaths(), slug, request)};
+ } catch {
+ return {ok: false as const, error: "Could not prepare details. Check the title, date and duration, then preview again if the recording changed. Inspection requires ffprobe on the editor server; you can explicitly choose manual entry instead."};
+ }
+}
diff --git a/editor/app/channels/[slug]/local-media/page.tsx b/editor/app/channels/[slug]/local-media/page.tsx
@@ -0,0 +1,18 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { LocalMediaPanel } from "./LocalMediaPanel";
+
+export const dynamic = "force-dynamic";
+export default async function LocalMediaPage({ params }: { params: Promise<{ slug: string }> }) {
+ const { slug } = await params;
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) || slug.endsWith(".")) notFound();
+ const config = await readChannelConfig(getPaths(), slug);
+ if (!config || config.sourceKind === "social") notFound();
+ return <div className="flex flex-col gap-4">
+ <Link href={`/channels/${slug}`} className="underline">Back to channel</Link>
+ <h1 className="text-2xl font-semibold">Local media library</h1>
+ <LocalMediaPanel slug={slug} initialConfig={config.localMedia ?? null} />
+ </div>;
+}
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -996,6 +996,7 @@ export default async function ChannelDetailPage({
failedVideoIds={failedVideoIds}
generatedAt={snapshot.generatedAt}
lastSyncedAt={config.lastSyncedAt}
+ onlineSyncApplicable={!config.localMedia || !!config.url}
/>
<RunningJobsList jobs={runningJobs} hideChannelSlug />
@@ -1006,6 +1007,7 @@ export default async function ChannelDetailPage({
stageOrder={stageOrder}
stages={stages}
selected={selectedStage}
+ showLocalLibrary={!isSocialChannel(config) && !!config.localMedia}
/>
{selectedStage ? (
<section
@@ -1036,6 +1038,7 @@ export default async function ChannelDetailPage({
stageOrder={stageOrder}
stages={stages}
essentials={{
+ localArchive: !!config.localMedia,
handling: config.handling,
platform: config.platform,
url: config.url,
diff --git a/editor/app/channels/[slug]/persistActions.ts b/editor/app/channels/[slug]/persistActions.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaWriteRefusal } from "yt-dlp-transcript-common/controller/localMediaDoors";
import { safeRevalidate } from "../../lib/safeRevalidate";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
@@ -161,6 +162,12 @@ export async function persistVideosAction(
const { items, dryRun, ...opts } = input;
if (items.length === 0) return { ok: false, error: "No videos to persist." };
const paths = getPaths();
+ // A local media library channel, a local recording, or a record linked to a
+ // library original has nothing to persist from a source (review fix 5).
+ for (const item of items) {
+ const localRefusal = await localMediaWriteRefusal(paths, item.slug, await readChannelConfig(paths, item.slug).catch(() => null), item.id);
+ if (localRefusal) return { ok: false, error: localRefusal };
+ }
const planned = await persistVideos({
paths,
items,
diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaMetadataRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import { manualDownloadsRefusal } from "yt-dlp-transcript-common/lib/manualDownloads";
import { isSocialChannel, remoteOnlyRefusal } from "yt-dlp-transcript-common/lib/channelConfig";
import { fetchPostsAction } from "./socialActions";
@@ -450,6 +451,8 @@ export async function runMetadataScanAction(
}
const remoteOnly = remoteOnlyRefusal(slug, channelConfig);
if (remoteOnly) return { ok: false, info: true, error: remoteOnly };
+ const localRefusal = localMediaMetadataRefusal(slug, channelConfig);
+ if (localRefusal) return { ok: false, error: localRefusal };
if (!channelConfig.url) {
return { ok: false, error: "Channel has no `url` configured" };
}
diff --git a/editor/app/channels/[slug]/playableActions.ts b/editor/app/channels/[slug]/playableActions.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaFetchRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import path from "node:path";
import { safeRevalidate } from "../../lib/safeRevalidate";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
@@ -27,6 +28,11 @@ export async function preparePlayableAction(
if (!channelConfig) {
return { ok: false, error: `Channel "${slug}" not found` };
}
+ // A local media library channel, or a local recording among the ids.
+ for (const id of [undefined, ...(opts.ids ?? [])]) {
+ const localRefusal = localMediaFetchRefusal(slug, channelConfig, id);
+ if (localRefusal) return { ok: false, error: localRefusal };
+ }
if (opts.root !== undefined && !path.isAbsolute(opts.root)) {
return { ok: false, error: `"root" must be an absolute path` };
}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx
@@ -1,5 +1,7 @@
"use client";
+import Link from "next/link";
+
// THE ASSEMBLY, not the cards. Each chore card's body — its state, its server
// action, its copy — is its own module under ./cards/ (enumerated, with why each
// is a chore and not an operation, in ../lib/videoChoreCards.ts). What stays here
@@ -56,6 +58,7 @@ import {
export type { FetchedWindow, VideoFile };
type Props = {
+ localRecording?: boolean;
slug: string;
videoId: string;
files: VideoFile[];
@@ -117,6 +120,7 @@ type Props = {
};
export function VideoPanel({
+ localRecording = false,
slug,
videoId,
files,
@@ -189,7 +193,9 @@ export function VideoPanel({
: hasTranscript
? "Transcript present."
: noAudio
- ? "No audio yet — run the download pipeline (or use Audio + Whisper) to produce a transcript."
+ ? localRecording
+ ? "No imported transcript. Review this recording in the Local media library."
+ : "No audio yet — run the download pipeline (or use Audio + Whisper) to produce a transcript."
: "Audio ready, no transcript.";
const transcodeSummary =
transcodeSources.length > 0
@@ -220,11 +226,11 @@ export function VideoPanel({
<span className="text-muted-foreground"> — this recording's life cycle: its windows, every cut that uses it, what was checked, rendered and published</span>
</div>
)}
- <PipelineStatusStrip
+ {!localRecording && <PipelineStatusStrip
downloaded={!noAudio}
transcribed={hasTranscript}
downloadFailed={downloadFailed}
- />
+ />}
{downloadOutcome && <DownloadOutcomeBadge outcome={downloadOutcome} />}
{salvageShown && salvaged && (
<SalvagedTranscriptNotice
@@ -251,7 +257,7 @@ export function VideoPanel({
<IncompleteTranscriptBanner
slug={slug}
videoId={videoId}
- coverage={incompleteTranscript ? coverage : null}
+ coverage={!localRecording && incompleteTranscript ? coverage : null}
defaultQueueKey={defaultQueueKey}
existingQueues={existingQueues}
/>
@@ -259,7 +265,7 @@ export function VideoPanel({
slug={slug}
videoId={videoId}
flagged={
- downloadOutcome?.status === "failed-short-audio" &&
+ !localRecording && downloadOutcome?.status === "failed-short-audio" &&
!excludedFromTruncatedCheck
}
shortAudio={downloadOutcome?.shortAudio}
@@ -288,7 +294,14 @@ export function VideoPanel({
Media archived — cleanup will skip this video.
</div>
)}
- <PipelineStageCard
+ {localRecording ? (
+ <section aria-label="Local recording" className="rounded border p-4 flex flex-col gap-2">
+ <h3 className="font-semibold">Local recording</h3>
+ <p>This record was imported from your local library and has no online download source. The original video stays in your library.</p>
+ <Link className="underline" href={"/channels/" + encodeURIComponent(slug) + "/local-media"}>Open local media library</Link>
+ {incompleteTranscript && <p role="status">The imported transcript may not cover the full recording. Review the original subtitles; an online re-download is not available for this record.</p>}
+ </section>
+ ) : <PipelineStageCard
id="download"
title={noAudio ? "Download audio" : "Redownload audio"}
summary={downloadSummary}
@@ -313,7 +326,7 @@ export function VideoPanel({
storedMediaHost={storedMediaHost}
channelStoredUrl={channelStoredUrl}
/>
- </PipelineStageCard>
+ </PipelineStageCard>}
{transcodeSources.length > 0 && (
<PipelineStageCard
@@ -370,7 +383,7 @@ export function VideoPanel({
</div>
</PipelineStageCard>
- <SubtitleDeferralLine slug={slug} videoId={videoId} />
+ {!localRecording && <SubtitleDeferralLine slug={slug} videoId={videoId} />}
{hasTranscript && (
<PipelineStageCard
@@ -415,7 +428,7 @@ export function VideoPanel({
</PipelineStageCard>
)}
- {!hasTranscript && (
+ {!localRecording && !hasTranscript && (
<PipelineStageCard
id="mark-untranscribable"
title="Mark untranscribable"
@@ -427,7 +440,7 @@ export function VideoPanel({
</PipelineStageCard>
)}
- <PipelineStageCard
+ {!localRecording && <PipelineStageCard
id="source-video-persistence"
title="Source video"
summary={
@@ -447,7 +460,7 @@ export function VideoPanel({
savedVideo={savedVideo}
defaultQuality={sourceVideoQuality}
/>
- </PipelineStageCard>
+ </PipelineStageCard>}
{clipWindows.length > 0 && (
<PipelineStageCard
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -397,7 +397,7 @@ export default async function VideoDetailPage({
none, and the action refuses it rather than create one), and not
for an archive.org record or a Wayback copy: their metadata is not
yt-dlp's, and the action refuses them too. */}
- {dirData.files.length > 0 && !archiveOrg && !wayback && (
+ {!meta.localRecording && dirData.files.length > 0 && !archiveOrg && !wayback && (
<RefreshMetadataControl
slug={slug}
videoId={id}
@@ -407,7 +407,7 @@ export default async function VideoDetailPage({
)}
{/* Release 32 R9: an Odysee channel's record read from its page in a
headless browser, for when yt-dlp's lookup is refused. */}
- {BROWSER_LOOKUP_PLATFORMS.includes(config.platform ?? detectPagePlatform(config.url ?? null) ?? "") && (
+ {!meta.localRecording && BROWSER_LOOKUP_PLATFORMS.includes(config.platform ?? detectPagePlatform(config.url ?? null) ?? "") && (
<BrowserLookupControl slug={slug} videoId={id} />
)}
</header>
@@ -415,6 +415,7 @@ export default async function VideoDetailPage({
<RunningJobsList jobs={activeJobs} hideChannelSlug hideVideoId />
<VideoPanel
+ localRecording={meta.localRecording}
slug={slug}
videoId={id}
files={dirData.files}
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaFetchRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import path from "node:path";
import { lstat, readdir, readFile, rm, stat } from "node:fs/promises";
import { revalidatePath } from "next/cache";
@@ -261,6 +262,9 @@ export async function transcribeOneAction(
): Promise<StreamActionResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
+ // A local media record: nothing to transcribe from a source (slice 3's drafts).
+ const localRefusal = localMediaFetchRefusal(slug, r.config, videoId);
+ if (localRefusal) return { ok: false, error: localRefusal };
return queueTranscribeOne({
slug,
videoId,
@@ -722,6 +726,8 @@ export async function whisperVideoAction(
): Promise<WhisperVideoResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
+ const localRefusal = localMediaFetchRefusal(slug, r.config, videoId);
+ if (localRefusal) return { ok: false, error: localRefusal };
const paths = getPaths();
const videoDir = videoDirOf(slug, videoId);
const audioFormat = r.config.audioFormat ?? "mp3";
@@ -1609,6 +1615,9 @@ export async function fetchWindowAction(req: {
}
const r = await loadConfigOrError(slug);
if (!r.ok) return { ok: false, status: 404, error: r.error };
+ // Before the cache: a local library's recording has no window to hold.
+ const localRefusal = localMediaFetchRefusal(slug, r.config, req.videoId);
+ if (localRefusal) return { ok: false, status: 409, error: localRefusal };
const paths = getPaths();
// From here on the video is named by its directory: the cache, the job, the
// page revalidated (a Twitch record's v<n> is data/<n>/).
@@ -1969,6 +1978,8 @@ export async function fetchFullSourceAction(req: {
const { slug } = req;
const r = await loadConfigOrError(slug);
if (!r.ok) return { ok: false, status: 404, error: r.error };
+ const localRefusal = localMediaFetchRefusal(slug, r.config, req.videoId);
+ if (localRefusal) return { ok: false, status: 409, error: localRefusal };
const paths = getPaths();
const videoId = await recordDirIdOf(slug, req.videoId, r.config);
const videoDir = videoDirOf(slug, videoId);
diff --git a/editor/app/channels/[slug]/videos/fetchWindowLocalMedia.test.ts b/editor/app/channels/[slug]/videos/fetchWindowLocalMedia.test.ts
@@ -0,0 +1,70 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/channels/*/videos/fetchWindowLocalMedia.test.ts"
+//
+// The editor's fetch doors refuse a local media library channel and a local
+// recording with one sentence (lib/localMedia.ts localMediaFetchRefusal), before
+// the window cache and before any job: fetch-window, full source, and the
+// fetch-windows planner. Nothing reaches the network.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-window-local-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 }));
+const LOCAL_ID = "local-" + "a".repeat(32);
+async function channel(slug: string, config: Record<string, unknown>, ids: string[]) {
+ await mkdir(path.join(ROOT, "channels", slug), { recursive: true });
+ await writeFile(path.join(ROOT, "channels", slug, "config.json"), JSON.stringify(config));
+ for (const id of ids) {
+ await mkdir(path.join(ROOT, "channels", slug, "data", id), { recursive: true });
+ await writeFile(path.join(ROOT, "channels", slug, "data", id, "metadata.info.json"),
+ JSON.stringify({ id, title: id, webpage_url: `https://www.youtube.com/watch?v=${id}` }));
+ }
+}
+// A Local Archive channel (no URL), holding a provider-metadata record too.
+await channel("library", { name: "Library", handling: "youtube", sourceKind: "video",
+ localMedia: { sourceId: "library-1", directory: "/mnt/library" } }, [LOCAL_ID, "aaaaaaaaaaa"]);
+// An online channel with a library: its online records fetch as before, its local one does not.
+await channel("hybrid", { name: "Hybrid", handling: "youtube", url: "https://www.youtube.com/@hybrid",
+ localMedia: { sourceId: "library-1", directory: "/mnt/library" } }, [LOCAL_ID]);
+
+const { fetchWindowAction, fetchFullSourceAction } = await import("./[id]/videoActions");
+const { fetchWindowsAction } = await import("./fetchWindowsAction");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SENTENCE = /with no online source, so no clip can be fetched for it\./;
+
+test("fetch-window and full source refuse a local library channel and a local recording", async () => {
+ for (const [slug, videoId, who] of [["library", "aaaaaaaaaaa", /"library" is a local media library channel/],
+ ["library", LOCAL_ID, /is a local recording/], ["hybrid", LOCAL_ID, /is a local recording/]] as const) {
+ const w = await fetchWindowAction({ slug, videoId, from: 5, to: 15, provenance: { requestedBy: "test" } });
+ assert.equal(w.ok, false, JSON.stringify(w));
+ if (w.ok) continue;
+ assert.equal(w.status, 409);
+ assert.match(w.error, SENTENCE);
+ assert.match(w.error, who);
+ const f = await fetchFullSourceAction({ slug, videoId, provenance: { requestedBy: "test" } });
+ assert.equal(f.ok, false);
+ if (!f.ok) assert.match(f.error, SENTENCE);
+ }
+ // Nothing was made: no clips/ dir, no job.
+ assert.deepEqual(await readdir(path.join(ROOT, "channels", "library", "data", LOCAL_ID)), ["metadata.info.json"]);
+});
+
+test("the fetch-windows planner puts a local item in unresolved with the sentence", async () => {
+ const r = await fetchWindowsAction({
+ items: [{ slug: "library", id: "aaaaaaaaaaa", from: 5, to: 15 }, { slug: "hybrid", id: LOCAL_ID, from: 5, to: 15 }],
+ requestedBy: "test",
+ dryRun: true,
+ });
+ assert.ok(r.ok, JSON.stringify(r));
+ if (!r.ok) return;
+ assert.equal(r.unresolved.length, 2);
+ for (const u of r.unresolved) assert.match(u.error, SENTENCE);
+ assert.deepEqual(r.groups, []);
+});
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaFetchRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import path from "node:path";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
@@ -269,6 +270,11 @@ async function planFetchWindows(
});
continue;
}
+ const localRefusal = localMediaFetchRefusal(item.slug, config, item.id);
+ if (localRefusal) {
+ unresolved.push({ item, error: localRefusal });
+ continue;
+ }
// The item names a RECORD; its directory may be another id — a Twitch
// record's v<n> is data/<n>/ (release 23 F1). The item keeps its id.
const dirId = await resolveVideoDirId(paths.channelsDir, item.slug, item.id, {
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -1,6 +1,7 @@
"use server";
import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { prepareLocalArchiveChannel } from "./lib/prepareLocalArchiveChannel";
import { withRumbleDefaults } from "yt-dlp-transcript-common/lib/rumbleDefaults";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
@@ -232,7 +233,9 @@ export async function createChannelAction(
): Promise<ActionResult> {
const result = await createChannelFromForm(formData);
if (!result.ok) return { error: result.error, values: result.values };
- redirect(`/channels/${result.slug}`);
+ redirect(formData.get("localArchive") === "on"
+ ? `/channels/${result.slug}/local-media`
+ : `/channels/${result.slug}`);
}
export async function createChannelFromForm(
@@ -243,7 +246,11 @@ export async function createChannelFromForm(
const jobIds: string[] = [];
let parsed;
try {
- parsed = parseChannelForm(formData);
+ // Build local configuration from an allowlist before any channel/site writes.
+ // Hidden or stale online fields must not accidentally schedule network work.
+ parsed = formData.get("localArchive") === "on"
+ ? await prepareLocalArchiveChannel(getPaths(), formData)
+ : parseChannelForm(formData);
} catch (e) {
return fail((e as Error).message);
}
diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx
@@ -168,6 +168,10 @@ export function ChannelForm({
}: Props) {
const isEdit = !!initial;
const c = initial?.config;
+ // Creation choice only: existing channels can combine online and local media.
+ // Never infer a conversion or erase their online settings from this toggle.
+ const [localArchive, setLocalArchive] = useState(seedChecked(state, "localArchive", false));
+ const creatingLocal = !isEdit && localArchive;
// Edit mode's handling radios are uncontrolled: a radio group seeds from the
// VALUE it posted, not from whether its name was there.
const editHandling = seedValue(
@@ -225,7 +229,7 @@ export function ChannelForm({
isWaybackPagesUrl(url) ||
platform === "x-search";
// An X search channel (release 38): a query across accounts, never on a site.
- const isXSearch = isEdit ? Boolean(c?.xSearch) : platform === "x-search";
+ const isXSearch = isEdit ? Boolean(c?.xSearch) : !creatingLocal && platform === "x-search";
// A Wayback pages channel (release 37): captures of pages, no fetcher; its
// scope is its targets.
const isWaybackPages = isEdit ? c?.platform === "webpage" : platform === "webpage";
@@ -385,6 +389,37 @@ export function ChannelForm({
)}
</Section>
<Section title="Source">
+ {!isEdit && (
+ <label className="flex items-center gap-2 text-sm font-medium">
+ <input type="checkbox" name="localArchive" checked={localArchive}
+ disabled={probe.state === "loading"}
+ onChange={(event) => {
+ setLocalArchive(event.target.checked);
+ if (event.target.checked && !slugTouched) setSlug("");
+ }} />
+ Local Archive
+ </label>
+ )}
+ {creatingLocal ? (
+ <>
+ <p className="text-sm text-muted-foreground">
+ Use existing recordings and transcripts from a directory. No URL,
+ online fetching, download format or transcription settings are needed.
+ </p>
+ <Field label="Directory on the editor server" name="localDirectory"
+ state={state} required placeholder="/mnt/archives/creator"
+ hint="Docker: enter the path inside the container, using a read-only archive mount. Without Docker: enter an absolute directory the editor can read, such as /home/you/videos/creator. The directory must already exist." />
+ <Field label="Library ID" name="localSourceId" state={state}
+ required defaultValue="library-1"
+ hint="A stable identifier within this channel: lowercase letters, numbers, hyphens or underscores; start with a letter or number (up to 64 characters)." />
+ <p className="text-xs text-muted-foreground">
+ After creation, preview matching MP4, .info.json and .vtt files and
+ select recordings to import. Subdirectories are not scanned. Originals
+ stay in place.
+ </p>
+ </>
+ ) : (
+ <>
{isEdit ? (
<>
<fieldset className="flex flex-col gap-2">
@@ -687,11 +722,13 @@ export function ChannelForm({
value={c?.syncIntervalMinutes}
fullSweepValue={c?.fullSweepIntervalMinutes}
/>
+ </>
+ )}
</Section>
{/* Video-only sections. A social account has no audio, no download
format and no source video to retain, so they are hidden entirely
rather than shown as inert controls. */}
- {!isSocial && (
+ {!creatingLocal && !isSocial && (
<>
<Section title="Transcription">
<label className="flex flex-col gap-1 text-sm">
@@ -955,6 +992,7 @@ export function ChannelForm({
</Section>
</>
)}
+ {!creatingLocal && (
<CollapsibleSection title="Advanced">
<Fragment key={`args-${rumbleKey}`}>
<label className="flex flex-col gap-1 text-sm">
@@ -1156,6 +1194,7 @@ export function ChannelForm({
</span>
</label>
</CollapsibleSection>
+ )}
<div className="flex gap-2">
<button
type="submit"
diff --git a/editor/app/channels/components/ChannelsTable.tsx b/editor/app/channels/components/ChannelsTable.tsx
@@ -126,7 +126,7 @@ function cmp(a: ChannelRowView, b: ChannelRowView, key: ChannelSortKey): number
case "name":
return compareStrings(a.name, b.name);
case "handling":
- return compareStrings(a.handling, b.handling);
+ return compareStrings(a.handlingLabel ?? a.handling, b.handlingLabel ?? b.handling);
case "build":
return compareBools(a.excludeFromBuild, b.excludeFromBuild);
case "tier":
diff --git a/editor/app/channels/components/channelColumns.tsx b/editor/app/channels/components/channelColumns.tsx
@@ -149,7 +149,7 @@ export const CHANNEL_COLUMNS: Record<
sortKey: "handling",
cell: (c) => ({
className: "font-mono text-[11px] text-muted-foreground",
- content: c.handling,
+ content: c.handlingLabel ?? c.handling,
}),
},
build: {
diff --git a/editor/app/channels/lib/prepareLocalArchiveChannel.test.ts b/editor/app/channels/lib/prepareLocalArchiveChannel.test.ts
@@ -0,0 +1,74 @@
+import test, { type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readdir, readFile, writeFile, rm, symlink } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import { prepareLocalArchiveChannel } from "./prepareLocalArchiveChannel";
+
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-channel-setup-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const directory = path.join(root, "library");
+ await mkdir(directory);
+ const paths = { transcriptsDir: path.join(root, "corpus") } as Paths;
+ const form = new FormData();
+ for (const [key, value] of Object.entries({ name: " Example ", localSourceId: "library-1", localDirectory: directory })) form.set(key, value);
+ return { root, directory, paths, form };
+}
+
+test("local creation leaves playback off and ignores stale online fields; preparation writes nothing", async t => {
+ const f = await fixture(t);
+ await writeFile(path.join(f.directory, "original.mp4"), "original bytes");
+ for (const [key,value] of Object.entries({url:"https://example.com/account", platform:"twitter", sourceKind:"social", handling:"transcribe", fetchPostsNow:"on", fetchPlaylist:"on", prioritizeDownload:"on", syncIntervalMinutes:"1"})) f.form.set(key,value);
+ const result = await prepareLocalArchiveChannel(f.paths, f.form);
+ assert.deepEqual(result, { name:"Example", slug:"", config:{name:"Example", handling:"youtube", sourceKind:"video", localMedia:{sourceId:"library-1",directory:f.directory}, syncIntervalMinutes:0,fullSweepIntervalMinutes:0}, warnings:[] });
+ assert.equal("playback" in result.config.localMedia!, false);
+ assert.deepEqual(await readdir(f.root), ["library"]);
+ assert.equal(await readFile(path.join(f.directory,"original.mp4"),"utf8"),"original bytes");
+});
+
+test("invalid identity, relative path, missing directory and regular file fail before writes", async t => {
+ const f = await fixture(t);
+ await writeFile(path.join(f.root,"file"),"not a directory");
+ for (const directory of ["relative",path.join(f.root,"missing"),path.join(f.root,"file")]) {
+ f.form.set("localDirectory",directory);
+ await assert.rejects(prepareLocalArchiveChannel(f.paths,f.form));
+ }
+ f.form.set("localDirectory",f.directory);
+ f.form.set("localSourceId","../bad");
+ await assert.rejects(prepareLocalArchiveChannel(f.paths,f.form));
+ f.form.set("localSourceId","library-1");
+ f.form.set("name"," ");
+ await assert.rejects(prepareLocalArchiveChannel(f.paths,f.form),/Name is required/);
+ assert.deepEqual((await readdir(f.root)).sort(),["file","library"]);
+});
+
+test("corpus overlap is refused in either direction, including linked ancestors", async t => {
+ const f = await fixture(t);
+ await mkdir(f.paths.transcriptsDir);
+ await mkdir(path.join(f.paths.transcriptsDir,"nested"));
+ const alias = path.join(f.root,"alias");
+ await symlink(f.paths.transcriptsDir,alias,"dir");
+ for (const directory of [f.root,f.paths.transcriptsDir,path.join(f.paths.transcriptsDir,"nested"),alias]) {
+ f.form.set("localDirectory",directory);
+ await assert.rejects(prepareLocalArchiveChannel(f.paths,f.form),/must be separate|The library directory (is inside|contains) the corpus/);
+ }
+ const absentCorpus = {...f.paths,transcriptsDir:path.join(alias,"not-created")};
+ f.form.set("localDirectory",f.paths.transcriptsDir);
+ await assert.rejects(prepareLocalArchiveChannel(absentCorpus,f.form),/must be separate|The library directory is inside the corpus/);
+});
+
+test("operator-selected directory link and sibling-prefix paths are allowed", async t => {
+ const f = await fixture(t);
+ const alias = path.join(f.root,"library-link");
+ await symlink(f.directory,alias,"dir");
+ f.form.set("localDirectory",alias);
+ f.form.set("slug","explicit-slug");
+ assert.equal((await prepareLocalArchiveChannel(f.paths,f.form)).config.localMedia?.directory,alias);
+ assert.equal((await prepareLocalArchiveChannel(f.paths,f.form)).slug,"explicit-slug");
+ const sibling = path.join(f.root,"corpus-extra");
+ await mkdir(sibling);
+ f.form.set("localDirectory",sibling);
+ await prepareLocalArchiveChannel(f.paths,f.form);
+});
diff --git a/editor/app/channels/lib/prepareLocalArchiveChannel.ts b/editor/app/channels/lib/prepareLocalArchiveChannel.ts
@@ -0,0 +1,64 @@
+import path from "node:path";
+import { libraryLocationProblem } from "yt-dlp-transcript-common/controller/localMediaLocation";
+import { access, realpath, stat } from "node:fs/promises";
+import { constants } from "node:fs";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import { coerceLocalMediaConfig } from "yt-dlp-transcript-common/lib/localMedia";
+import type { ParsedChannelForm } from "../components/parseChannelForm";
+
+function contains(parent: string, child: string): boolean {
+ const relative = path.relative(parent, child);
+ return !relative || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
+}
+
+// First-run installs may not have a corpus yet. Resolve its existing ancestors
+// without creating anything, including when a parent is a directory symlink.
+async function prospectiveRealpath(directory: string): Promise<string> {
+ try { return await realpath(directory); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ const parent = path.dirname(directory);
+ if (parent === directory) throw error;
+ return path.join(await prospectiveRealpath(parent), path.basename(directory));
+ }
+}
+
+// Create-only preparation. Reuse the normal channel/site creation action after
+// validating the directory, rather than creating a half-configured channel and
+// asking the operator to retry a second setup action. This function writes nothing.
+export async function prepareLocalArchiveChannel(paths: Paths, form: FormData): Promise<ParsedChannelForm> {
+ const name = String(form.get("name") ?? "").trim();
+ if (!name) throw new Error("Name is required");
+ const slug = String(form.get("slug") ?? "").trim();
+ const localMedia = coerceLocalMediaConfig({
+ sourceId: String(form.get("localSourceId") ?? "").trim(),
+ directory: String(form.get("localDirectory") ?? "").trim(),
+ // Playback is never on by default: serving originals is its own opt-in.
+ });
+ if (!localMedia || !path.isAbsolute(localMedia.directory)) {
+ throw new Error("Enter a valid library ID and an absolute directory on the editor server");
+ }
+ let source: string;
+ try {
+ source = await realpath(localMedia.directory);
+ if (!(await stat(source)).isDirectory()) throw new Error("Not a directory");
+ await access(source, constants.R_OK | constants.X_OK);
+ } catch {
+ throw new Error("Library directory is unavailable or unreadable. In Docker, use the mounted path inside the container.");
+ }
+ const corpus = await prospectiveRealpath(path.resolve(paths.transcriptsDir));
+ const misplaced = await libraryLocationProblem(paths, source);
+ if (misplaced) throw new Error(misplaced);
+ if (contains(source, corpus) || contains(corpus, source)) {
+ throw new Error("Library and corpus directories must be separate");
+ }
+ return {
+ name, slug,
+ // Handling remains required by the video schema. With no URL and sync off,
+ // this compatibility value does not select an online source or start work.
+
+ config: { name, handling: "youtube", sourceKind: "video", localMedia,
+ syncIntervalMinutes: 0, fullSweepIntervalMinutes: 0 },
+ warnings: [],
+ };
+}
diff --git a/editor/e2e/local-media.spec.ts b/editor/e2e/local-media.spec.ts
@@ -0,0 +1,100 @@
+// LOCAL MEDIA LIBRARY, slice 1 (lane/local-media): a Local Archive channel made
+// from the New channel form, its library previewed, one recording with
+// provider metadata and one prepared by hand imported, and the local record's
+// page — all through the UI, against a synthetic library of a few bytes the
+// spec writes in the OS temp dir: a library may not lie inside the corpus or the
+// checkout (controller/localMediaLocation.ts).
+// Nothing is fetched; the library's files are never changed.
+
+import { test, expect } from "@playwright/test";
+import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { resetData, testPaths, writeChannelConfig } from "./helpers";
+
+const VTT = "WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nA synthetic library cue\n";
+
+test("a Local Archive channel imports a library recording and a prepared one, playback left off", async ({ page }) => {
+ await resetData("empty");
+ const library = join(tmpdir(), `archilyzer-e2e-local-library-${process.env.TEST_PARALLEL_INDEX ?? "0"}`);
+ await rm(library, { recursive: true, force: true });
+ await mkdir(library, { recursive: true });
+ await writeFile(join(library, "aaaaaaaaaaa.mp4"), "synthetic mp4 a");
+ await writeFile(join(library, "aaaaaaaaaaa.info.json"), JSON.stringify({
+ id: "aaaaaaaaaaa", title: "Library episode", webpage_url: "https://www.youtube.com/watch?v=aaaaaaaaaaa",
+ upload_date: "20200102", duration: 12, extractor_key: "Youtube",
+ }));
+ await writeFile(join(library, "aaaaaaaaaaa.vtt"), VTT);
+ await writeFile(join(library, "talk.mp4"), "synthetic mp4 talk");
+ await writeFile(join(library, "talk.vtt"), VTT);
+ const before = (await readdir(library)).sort();
+
+ await page.goto("/channels/new");
+ await page.getByLabel("Local Archive").check();
+ await page.locator('input[name="name"]').fill("Local Spec Library");
+ await page.locator('input[name="localDirectory"]').fill(library);
+ await page.getByRole("button", { name: "Create channel" }).click();
+ await expect(page).toHaveURL(/\/channels\/local-spec-library\/local-media$/);
+
+ const config = JSON.parse(await readFile(join(testPaths().transcriptsDir, "channels", "local-spec-library", "config.json"), "utf8"));
+ expect(config.localMedia).toEqual({ sourceId: "library-1", directory: library });
+ expect(config.url).toBeUndefined();
+
+ await page.getByRole("button", { name: "Preview library" }).click();
+ await expect(page.getByRole("status").filter({ hasText: "discovered" })).toHaveText(
+ "2 discovered · 1 new · 0 occupied · 1 need review",
+ );
+ await page.getByLabel("Import aaaaaaaaaaa.mp4").check();
+
+ await page.getByRole("button", { name: "Prepare details for talk.mp4" }).click();
+ const form = page.getByRole("form", { name: "Prepare details for talk.mp4" });
+ await form.getByLabel("Method").selectOption("manual");
+ await form.getByLabel("Title").fill("A prepared talk");
+ await form.getByLabel("Recording date (optional)").fill("2021-03-04");
+ await form.getByRole("button", { name: "Review details" }).click();
+ await expect(form.getByLabel("Prepared recording details")).toContainText("Recording date: 2021-03-04");
+ await form.getByRole("button", { name: "Use details for import" }).click();
+ await expect(page.getByLabel("Import talk.mp4")).toBeChecked();
+
+ await page.getByRole("button", { name: "Import selected (2)" }).click();
+ await expect(page.getByText(/Imported 2; already occupied 0; rejected 0/)).toBeVisible({ timeout: 30_000 });
+
+ const data = join(testPaths().transcriptsDir, "channels", "local-spec-library", "data");
+ const ids = (await readdir(data)).sort();
+ expect(ids).toHaveLength(2);
+ expect(ids).toContain("aaaaaaaaaaa");
+ const local = ids.find((id) => id.startsWith("local-"))!;
+ expect((await readdir(join(data, local))).sort()).toEqual(["external-media.json", "metadata.info.json", "transcript.en.vtt"]);
+ expect(JSON.parse(await readFile(join(data, local, "metadata.info.json"), "utf8")).title).toBe("A prepared talk");
+
+ // A local record's page names it a local recording, with no download card.
+ await page.goto(`/channels/local-spec-library/videos/${local}`);
+ await expect(page.getByLabel("Local recording")).toBeVisible();
+ await expect(page.getByRole("link", { name: "Open local media library" })).toBeVisible();
+ await expect(page.getByText("Download audio")).toHaveCount(0);
+
+ // The channel page offers its Local library tab (it has a library).
+ await page.goto("/channels/local-spec-library");
+ await expect(page.getByLabel("Local library stage tab")).toBeVisible();
+
+ // Playback stayed off, and the library was never touched.
+ const after = JSON.parse(await readFile(join(testPaths().transcriptsDir, "channels", "local-spec-library", "config.json"), "utf8"));
+ expect(after.localMedia.playback).toBeUndefined();
+ expect((await readdir(library)).sort()).toEqual(before);
+ await rm(library, { recursive: true, force: true });
+});
+
+// Review fix 8: the tab is only on a channel that has a library; a library is
+// added through the New channel form or `pnpm ops local-media-configure`, and
+// the route, reachable by URL, says so for a channel without one.
+test("a channel without a library has no Local library tab, and its route names the command", async ({ page }) => {
+ await resetData("empty");
+ await writeChannelConfig("plain-channel", { name: "Plain", url: "https://www.youtube.com/@plain" });
+ await page.goto("/channels/plain-channel");
+ await expect(page.getByLabel("Overview stage tab")).toBeVisible();
+ await expect(page.getByLabel("Local library stage tab")).toHaveCount(0);
+ await page.goto("/channels/plain-channel/local-media");
+ await expect(page.getByText("This channel has no local media library.")).toBeVisible();
+ await expect(page.getByText(/pnpm ops local-media-configure --json '\{"slug":"plain-channel"/)).toBeVisible();
+ await expect(page.getByRole("button", { name: "Save library" })).toHaveCount(0);
+});
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -9,6 +9,13 @@ import { salvageCaveat } from "yt-dlp-transcript-common/lib/salvageMark";
import { COPIES_NOT_AVAILABLE, describeCopies, loadMirrorScans, onlyHereIds } from "./mirrorCopies";
import { transcriptToMarkdown } from "yt-dlp-transcript-common/lib/transcriptToMarkdown";
import { formatDate, formatDuration } from "yt-dlp-transcript-common/lib/format";
+
+// A record's date as these listings print it. An undated record (a local
+// recording with no recording date has uploadDate "") says so, rather than
+// leaving an empty field a reader takes for a parse error.
+export function dateOrUndated(uploadDate: string): string {
+ return uploadDate ? formatDate(uploadDate) : "undated";
+}
import { manifestHasDigest } from "yt-dlp-transcript-common/lib/digests";
import type { VideoStat } from "yt-dlp-transcript-common/lib/stats";
import { momentUrl, momentBaseUrl, viewerPostUrl } from "yt-dlp-transcript-common/lib/momentUrl";
@@ -1720,7 +1727,7 @@ async function handleSearch(
`### ${h.title}\n` +
`- video_id: ${h.videoId} | channel: ${h.channelName}` +
(h.siteTitle ? ` | site: ${h.siteTitle}` : "") +
- ` | uploaded: ${formatDate(h.uploadDate)} | matches: ${h.matches}` +
+ ` | uploaded: ${dateOrUndated(h.uploadDate)} | matches: ${h.matches}` +
(includeSnippets && h.webpageUrl ? `\n- source: ${h.webpageUrl}` : "") +
(baseUrl ? `\n- moment_base: ${baseUrl}` : "") +
(h.mirrors && h.mirrors.length > 0
@@ -1864,7 +1871,7 @@ async function handleEnumerateMatches(
: "";
return (
`- ${h.videoId} | ${kind} | ${h.channelName} | ` +
- `${formatDate(h.uploadDate)} | ${h.matches} match(es) | ${h.title}${mirrors}`
+ `${dateOrUndated(h.uploadDate)} | ${h.matches} match(es) | ${h.title}${mirrors}`
);
});
@@ -2132,7 +2139,7 @@ async function handleGetTranscripts(
`## ${record.title || id}\n` +
`- video_id: ${id} | channel: ${ch.name}` +
(ch.siteTitle ? ` | site: ${ch.siteTitle}` : "") +
- ` | uploaded: ${formatDate(record.uploadDate)}` +
+ ` | uploaded: ${dateOrUndated(record.uploadDate)}` +
(record.webpageUrl ? `\n- source: ${record.webpageUrl}` : "") +
(baseUrl ? `\n- moment_base: ${baseUrl}` : "") +
// A salvage transcript (release 30, lane Q) is marked here too (release 32 R8).
@@ -2563,7 +2570,7 @@ async function describeOtherCopies(
`open it at 0:00 and locate the moment again`;
return (
`- ${s.id} (${s.channel}, ${s.platform}, ${formatDuration(s.duration)}, ` +
- `uploaded ${formatDate(s.uploadDate)}` +
+ `uploaded ${dateOrUndated(s.uploadDate)}` +
`${s.hasTranscript ? "" : ", NO transcript"}) — ${timing}`
);
});
@@ -3017,7 +3024,7 @@ function renderSpecResults(source: ShardSource, hits: SpecHit[]): string {
`### ${h.title}\n` +
`- video_id: ${h.videoId} | channel: ${h.channelName}` +
(h.siteTitle ? ` | site: ${h.siteTitle}` : "") +
- ` | uploaded: ${formatDate(h.uploadDate)} | matches: ${h.matches}` +
+ ` | uploaded: ${dateOrUndated(h.uploadDate)} | matches: ${h.matches}` +
(h.webpageUrl ? `\n- source: ${h.webpageUrl}` : "");
const snips = h.snippets
.map((s) => renderScopedSnippet(source, h, s))
diff --git a/mcp/src/undatedRecord.test.ts b/mcp/src/undatedRecord.test.ts
@@ -0,0 +1,11 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { dateOrUndated } from "./server";
+
+// lane/local-media (review B2): a local recording with no recording date has
+// uploadDate "", and the listings say "undated" rather than print an empty
+// field; a dated record prints exactly as before.
+test("dateOrUndated: an empty date is named, a real one formatted as before", () => {
+ assert.equal(dateOrUndated(""), "undated");
+ assert.equal(dateOrUndated("20240229"), "2024-02-29");
+});
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -144,6 +144,15 @@ An ARTICLE's "workspace files" are something else: the files of its research wor
Article tab's `source` view (`umtool/lib/pieces/tabs.mjs` ARTICLE_SECTION_TAB `source`,
`umtool/components/articles/WorkspacePanel.tsx`). Say which.
+**"Local media" means three things.** In umtool, `umtool/report-to-video/local-media.mjs`
+(`createLocalMedia`, `hasLocalMedia`, `validateLocalMedia`) is a report-video clip whose media is a
+FILE BESIDE THE MANIFEST (`src`, `cues`), nothing to do with the corpus; and
+`umtool/lib/research/media.ts` `localMediaFor` is the files on disk a research view can play for a
+corpus record (its clip windows, its saved video). In the corpus, a channel's `localMedia` config key (`common/lib/localMedia.ts`, CHANNEL.md) is
+a LOCAL MEDIA LIBRARY — a directory of recordings the archive imports text from and never owns —
+whose records are platform `"local"`, id `local-<32 hex>`, with `external-media.json`; umtool's guard
+for those is `umtool/report-to-video/local-recording.mjs`. Say which.
+
**Never name a sidecar `transcript.<x>.<y>`.** `common/lib/videoStatus.ts:88` —
`export const SUB_FILE_RE = /^transcript\.([^.]+)\.([^.]+)$/;` treats any such file as a
subtitle track. The exclusion list in `readSubTracks` is hardcoded. Use `ai-digest.json`,
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -53,6 +53,11 @@
// pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait
// pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait
// pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait
+// pnpm ops local-media-configure --json '{"slug":"demo-local","sourceId":"library-1","directory":"/mnt/recordings"}'
+// pnpm ops local-media-preview --json '{"slug":"demo-local"}'
+// pnpm ops local-media-prepare --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","sourceFingerprint":"<fp>","details":{"mode":"inspect","title":"A talk"}}'
+// pnpm ops local-media-import --json '{"slug":"demo-local","allNew":true}' --wait
+// pnpm ops local-media-link --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","fingerprint":"<fp>","dryRun":true}'
// pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'
// pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'
// pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'
@@ -452,6 +457,16 @@ const ACTIONS = [
// job; both land through the same code.
"import-media",
"record-live",
+ // A LOCAL MEDIA LIBRARY (controller/localMediaImport.ts): a directory of
+ // recordings that stay where they are, the channel's `localMedia`. Its
+ // config ({slug, sourceId, directory}), a scan writing nothing ({slug}),
+ // details for a recording with no .info.json, the import job, and the link
+ // of a record already held to its original. The local media page's twins.
+ "local-media-configure",
+ "local-media-preview",
+ "local-media-prepare",
+ "local-media-import",
+ "local-media-link",
// LIVE PRE-CLIP (plans/live-preclip.md): a recording in progress transcribed
// and mined while it records ({slug, id, action?: start | stop | status |
// finalize, everyMinutes?, maxChunkMinutes?, overlapSeconds?, scan?, mine?,
@@ -1793,6 +1808,49 @@ export function usage() {
' "dryRun": true says what it would do and writes nothing. A directory, a',
' .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only).',
"",
+ "local-media-configure gives a video channel a LOCAL MEDIA LIBRARY: {\"slug\",",
+ " \"sourceId\", \"directory\"} — a stable lowercase id and an absolute directory",
+ " on the editor server whose recordings stay where they are (never copied,",
+ " moved or deleted). Written through the channel config; a channel that",
+ " already has one is refused, and so is queued or running channel work.",
+ " Playback is not set. Synchronous.",
+ "",
+ "local-media-preview scans the library and writes nothing: {\"slug\"} ->",
+ " {preview: {sourceToken, counts, candidates}}. Each .mp4 directly in the",
+ " directory (not its subdirectories) with its same-named .info.json and",
+ " .vtt (or .srt) is \"new\", \"existing\" (its record is held) or \"issue\" (with",
+ " issues). The sourceToken and a candidate's fingerprint (or",
+ " preparationFingerprint, when it has no .info.json) are what the other",
+ " local-media actions take. An unreachable library is an error, never an",
+ " empty preview.",
+ "",
+ "local-media-prepare reviews details for a recording with no .info.json and",
+ " writes nothing: {\"slug\", \"sourceToken\", \"media\", \"sourceFingerprint\"",
+ " (the candidate's preparationFingerprint), \"details\": {\"mode\": \"inspect\"",
+ " | \"manual\", \"title\", \"recordedDate\"? (YYYY-MM-DD), \"durationSeconds\"?",
+ " (manual)}} -> {review: {metadata, fingerprint}}. \"inspect\" measures the",
+ " duration with ffprobe. Import it with local-media-import, the review's",
+ " fingerprint and \"preparation\": {\"sourceFingerprint\", \"details\"}.",
+ "",
+ "local-media-import imports library recordings as one job on the channel's",
+ " queue: {\"slug\", \"sourceToken\", \"selected\": [{\"media\", \"fingerprint\",",
+ " \"preparation\"?}]} from a preview, or {\"slug\", \"allNew\": true} for every",
+ " \"new\" candidate of a fresh preview (the first 1000 in the scan's order,",
+ " with \"remaining\" in the answer and the log when there are more). Each",
+ " record gets metadata.info.json,",
+ " transcript.en.vtt and external-media.json; the video stays in the",
+ " library. Every selection is re-checked first (a changed file is stale; a",
+ " held record is left unchanged). Drainable between recordings; searchable",
+ " after the next index build.",
+ "",
+ "local-media-link links a record the channel already holds to its library",
+ " original: {\"slug\", \"sourceToken\", \"media\", \"fingerprint\", \"dryRun\"?} for",
+ " an \"existing\" candidate. Only when the library's .info.json and",
+ " transcript match the record's byte for byte is external-media.json",
+ " written (\"attached\"; \"already-linked\"; \"conflict\" keeps a different one).",
+ " Nothing else changes, and no playback is granted. \"dryRun\" answers",
+ " \"ready\" without writing.",
+ "",
'record-live records a live stream until it ends, then lands it as',
' import-media lands a file: {"slug", "url"} (or "id" of a record here),',
' "fromStart"? (true: yt-dlp --live-from-start — Rumble\'s DVR playlist',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -1084,3 +1084,17 @@ test("archive-lookup is a POST to its route; import-page passes source through;
assert.match(usage(), /archive-lookup answers the copies of a page each archive source holds/);
assert.match(usage(), /excluded from the Wayback Machine \(cause/);
});
+
+// Local media libraries (lane/local-media slice 1): the Local media page's
+// five twins are POSTs to their own routes, each named in the usage.
+test("the local-media actions are POSTs to their routes, named in the usage", () => {
+ for (const action of ["local-media-configure", "local-media-preview", "local-media-prepare", "local-media-import", "local-media-link"]) {
+ const p = parseArgs([action, "--json", '{"slug":"demo-local"}']);
+ assert.equal(p.method, "POST");
+ assert.equal(p.path, `/api/ops/${action}`);
+ assert.deepEqual(p.body, { slug: "demo-local" });
+ assert.match(usage(), new RegExp(`\\n${action} `));
+ }
+ assert.equal(parseArgs(["local-media-import", "--json", '{"slug":"demo-local","allNew":true}', "--wait"]).wait, true);
+ assert.match(usage(), /Actions:.*record-live, local-media-configure, local-media-preview, local-media-prepare, local-media-import, local-media-link/);
+});
diff --git a/umtool/report-to-video/attribution.mjs b/umtool/report-to-video/attribution.mjs
@@ -119,7 +119,9 @@ export function attributionLine(entry, meta, provenance = {}) {
// A cut with no channel to name anywhere reproduces the old line exactly,
// rather than opening on a stray separator.
const head = [channel, title].filter((s) => String(s ?? "").length > 0).join(" · ");
- return `${head} · ${date} @ ${hms(at)}`;
+ // An undated recording (a local recording with no recording date: its
+ // uploadDate is "") drops the date, not leaves an empty field between dots.
+ return String(date ?? "").length > 0 ? `${head} · ${date} @ ${hms(at)}` : `${head} @ ${hms(at)}`;
}
/**
diff --git a/umtool/report-to-video/attribution.test.mjs b/umtool/report-to-video/attribution.test.mjs
@@ -10,6 +10,7 @@ import test from "node:test";
import {
attributionLine,
+ attributionParts,
channelName,
cleanTitle,
hms,
@@ -131,3 +132,12 @@ test("isCalendarDate / uploadDateToIso", () => {
assert.equal(uploadDateToIso("20250101"), "2025-01-01");
assert.equal(uploadDateToIso("2025-01-01"), "2025-01-01");
});
+
+// lane/local-media: an undated local recording's uploadDate is "".
+test("attributionLine: an undated recording drops the date, not leaves an empty field", () => {
+ assert.equal(
+ attributionLine({ start: 62 }, { title: "Lesson one", uploadDate: "", channel: "Classroom" }),
+ "Classroom · Lesson one @ 1:02",
+ );
+ assert.equal(attributionParts({ start: 62 }, { title: "Lesson one", uploadDate: "" }).date, "");
+});
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -125,6 +125,7 @@
//
// Requires: yt-dlp, ffmpeg/ffprobe, ImageMagick with Pango.
+import { localRecordingFetchRefusal } from "./local-recording.mjs";
import { presetManifest } from "./presets.mjs";
// The basic output mode (render.mode "basic"): the footage alone, cut and spliced in basic.mjs.
import { renderBasic } from "./basic.mjs";
@@ -1365,6 +1366,8 @@ async function fetchClip(entry, meta, render, local, opts) {
// thing in a build, and the two cuts overlap almost entirely.
const name = rawWindowName(entry.video, from, to);
const dest = path.join(rawDir, name);
+ const localRefusal = localRecordingFetchRefusal(entry.video, meta.platform);
+ if (localRefusal) throw new Error(localRefusal);
if (opts.noNetwork) throw new Error(`--no-network set and no local source covers ${name}`);
if (opts.skipFetch) throw new Error(`--skip-fetch set and no cached window covers ${name}`);
diff --git a/umtool/report-to-video/check-availability.mjs b/umtool/report-to-video/check-availability.mjs
@@ -36,6 +36,7 @@
// --allow-missing Exit 0 even when a source is gone (report only)
// --max-age <days> Reuse a recorded verdict younger than this (default: 0)
+import { localRecordingFetchRefusal } from "./local-recording.mjs";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { readFile, stat, writeFile } from "node:fs/promises";
@@ -107,7 +108,7 @@ export async function cueMeta(videoId, channelSlug) {
// The record's directory: a Twitch v<n> is data/<n>/ (release 23 F1b).
const p = path.join(await resolveVideoDir(CHANNELS_DIR, channelSlug, videoId), "transcript.cues.json");
const d = JSON.parse(await readFile(p, "utf8"));
- return { title: d.title, webpageUrl: d.webpageUrl, duration: d.duration };
+ return { title: d.title, webpageUrl: d.webpageUrl, duration: d.duration, ...(d.platform ? { platform: d.platform } : {}) };
}
/** A source's verdict, as the inbox, the CLI and the build read it: true, false, or null (not checked). */
@@ -221,6 +222,12 @@ export async function checkAvailability(manifestPath, {
};
continue;
}
+ // A local recording has no source to probe (an empty URL would read as dead).
+ const localRefusal = localRecordingFetchRefusal(w.video, meta.platform);
+ if (localRefusal) {
+ rows[i] = { ...w, ok: false, state: "local-media", title: meta.title, url: null, checkedAt: iso(), error: localRefusal };
+ continue;
+ }
probes.push({ i, w, meta, platform: detectPlatform(meta.webpageUrl) ?? "other" });
}
diff --git a/umtool/report-to-video/local-recording.mjs b/umtool/report-to-video/local-recording.mjs
@@ -0,0 +1,15 @@
+// A LOCAL RECORDING (a record the editor's local media import made, platform
+// "local", id `local-<32 hex>`) has no online source: umtool's own clip fetch
+// and its availability probe refuse it with the editor's sentence
+// (common/lib/localMedia.ts localMediaFetchRefusal), rather than run yt-dlp on
+// an empty URL. A local library channel's other records are refused at the
+// editor's doors, which umtool fetch goes through.
+
+export const LOCAL_RECORDING_ID_RE = /^local-[0-9a-f]{32}$/;
+
+/** @returns {string|null} why no clip can be fetched, or null when one may be. */
+export function localRecordingFetchRefusal(videoId, platform) {
+ const id = String(videoId ?? "");
+ if (platform !== "local" && !LOCAL_RECORDING_ID_RE.test(id)) return null;
+ return `"${id}" is a local recording with no online source, so no clip can be fetched for it.`;
+}
diff --git a/umtool/report-to-video/local-recording.test.mjs b/umtool/report-to-video/local-recording.test.mjs
@@ -0,0 +1,12 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { localRecordingFetchRefusal } from "./local-recording.mjs";
+
+test("a local recording is refused by id or by platform; anything else may fetch", () => {
+ const id = "local-" + "a".repeat(32);
+ assert.equal(localRecordingFetchRefusal(id, null),
+ `"${id}" is a local recording with no online source, so no clip can be fetched for it.`);
+ assert.match(localRecordingFetchRefusal("anything", "local"), /local recording with no online source/);
+ assert.equal(localRecordingFetchRefusal("dQw4w9WgXcQ", "youtube"), null);
+ assert.equal(localRecordingFetchRefusal("local-short", null), null);
+});
diff --git a/umtool/report-to-video/render-cards.mjs b/umtool/report-to-video/render-cards.mjs
@@ -1014,6 +1014,7 @@ export const SOURCE_TAG = {
restricted: "age-restricted",
"geo-blocked": "geo-blocked",
"no-cues": "no archived transcript",
+ "local-media": "local recording, not clipped",
maybe_missing: "source unreachable",
};