Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 7db6a56d4536624b19337c60bf1b88b7979dae04
parent f407a8231674eb5b662f0fbec17407a3978946a0
Author: Autistic Integrity <contributor@invalid>
Date:   Wed, 11 Nov 2026 06:14:28 -0500

local media: core import, as contributed (slice 1 of 5)

The contributed "local media libraries" patch (received as contrib/local-media
4b592640 over e19d52d2), the slice-1 subset only: the `localMedia` channel
config key and schema, the "local" platform, scan, import, commit, link
("adopt") and their tests, the import job kind, the editor's Local media page
with configure / preview / prepare-details / import / verify-and-link, and the
Local Archive option on the new-channel form. Taken as received; review fixes
follow in separate commits.

Left out for later slices: vtt.ts (slice 2), transcription drafts, model
download and the sample (slice 3), playback, FilePlayer/PlayerProvider, the
media route, viewer identities, localMediaSig and every publish-stage hunk,
plus the "Update searchable library" button (slice 4), the Docker overlay
(slice 5), and the root-level LOCAL_MEDIA_CHANGES.md / PRIVATE_LOCAL_DOCKER.md.

Integration done by the lane to land the subset on main f407a823 (no
behaviour of the patch changed):
- excised the draft-review branch and the transcription-draft functions from
  controller/localMediaImport.ts and jobs/localMediaImportJob.ts, the
  "transcribe-local-media" and "download-transcription-model" job kinds, and
  the playback, transcription and search-update parts of the local-media
  page, panel and actions;
- the two conflicts with main kept both sides (channelConfigSchema.test.ts:
  43 keys, main's `skipShorts` plus `localMedia`; channels/actions.ts: both
  imports);
- prepareLocalArchiveChannel returns main's new `warnings: []`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diffstat:
MCHANNEL.md | 1+
Acommon/controller/adoptLocalMediaReference.test.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/adoptLocalMediaReference.ts | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/buildIndex.ts | 16++++++++++------
Acommon/controller/buildIndexLocalRecording.test.ts | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/configureLocalMedia.test.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/configureLocalMedia.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/localMediaImport.test.ts | 190+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/localMediaImport.ts | 283+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/localMediaLifecycle.test.ts | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/localMediaPreparation.test.ts | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/localMediaSrt.test.ts | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/localTranscriptionEligibility.test.ts | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/videoTitles.test.ts | 24++++++++++++++++++++++++
Mcommon/controller/videoTitles.ts | 10++++++++++
Mcommon/jobs/jobKinds.ts | 13+++++++++++++
Acommon/jobs/localMediaImportJob.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/channelConfig.ts | 6++++++
Mcommon/lib/channelConfigSchema.test.ts | 18+++++++++++++++++-
Mcommon/lib/channelConfigSchema.ts | 1+
Acommon/lib/externalMedia-server.test.ts | 38++++++++++++++++++++++++++++++++++++++
Acommon/lib/externalMedia-server.ts | 17+++++++++++++++++
Acommon/lib/externalMediaResolver-server.test.ts | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/externalMediaResolver-server.ts | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localMedia.test.ts | 31+++++++++++++++++++++++++++++++
Acommon/lib/localMedia.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localMediaCommit-server.test.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localMediaCommit-server.ts | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localMediaScan.test.ts | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localMediaScan.ts | 228+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localMediaTranscript.test.ts | 25+++++++++++++++++++++++++
Acommon/lib/localMediaTranscript.ts | 37+++++++++++++++++++++++++++++++++++++
Acommon/lib/localRecordingDetails.ts | 30++++++++++++++++++++++++++++++
Acommon/lib/localRecordingIntegration.test.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localRecordingMetadata.test.ts | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localRecordingMetadata.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localRecordingProbe-server.test.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localRecordingProbe-server.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/platform.ts | 3+++
Mcommon/lib/sidecar-server.test.ts | 2++
Mcommon/lib/transcripts-server.ts | 10+++++++++-
Mcommon/views/channelRow.ts | 3+++
Mcommon/views/pipeline/channelFlow.test.ts | 22++++++++++++++++++++++
Mcommon/views/pipeline/stageStatus.ts | 13++++++++++---
Meditor/app/channels/[slug]/components/flow/AttentionStrip.tsx | 24++++++++++++++----------
Meditor/app/channels/[slug]/components/flow/OverviewPanel.tsx | 12+++++++++---
Meditor/app/channels/[slug]/components/flow/StageSwitcher.tsx | 5+++++
Aeditor/app/channels/[slug]/local-media/LocalMediaPanel.tsx | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/local-media/LocalRecordingDetailsForm.tsx | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/local-media/actions.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/local-media/page.tsx | 19+++++++++++++++++++
Meditor/app/channels/[slug]/page.tsx | 3+++
Meditor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx | 35++++++++++++++++++++++++-----------
Meditor/app/channels/[slug]/videos/[id]/page.tsx | 5+++--
Meditor/app/channels/actions.ts | 11+++++++++--
Meditor/app/channels/components/ChannelForm.tsx | 43+++++++++++++++++++++++++++++++++++++++++--
Meditor/app/channels/components/ChannelsTable.tsx | 2+-
Meditor/app/channels/components/channelColumns.tsx | 2+-
Aeditor/app/channels/lib/prepareLocalArchiveChannel.test.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/lib/prepareLocalArchiveChannel.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
60 files changed, 3527 insertions(+), 43 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -56,6 +56,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/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:01.000 --> 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:02.000 --> 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/buildIndex.ts b/common/controller/buildIndex.ts @@ -1102,18 +1102,22 @@ export async function buildIndex({ } } } - if (!summary.uploadDate) { + if (!summary.uploadDate && summary.platform !== "local") { log(`Skipping ${s.channelSlug}/${s.videoDir}: no upload_date`); 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 diff --git a/common/controller/buildIndexLocalRecording.test.ts b/common/controller/buildIndexLocalRecording.test.ts @@ -0,0 +1,106 @@ +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.000 --> 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(); } +} +function pages(): string { + const dir = path.join(paths.exportSharedTranscriptsDir, 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", + 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/); + 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"); + assert.equal(summary.uploadDate, ""); + 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); +}); 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:01.000 --> 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,47 @@ +import path from "node:path"; +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 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/localMediaImport.test.ts b/common/controller/localMediaImport.test.ts @@ -0,0 +1,190 @@ +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:01.000 --> 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:01.000 --> 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/); + 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 } from "../jobs/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"))); + assert.ok(log.some(line => line.includes('Click "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:01.000 --> 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/); +}); diff --git a/common/controller/localMediaImport.ts b/common/controller/localMediaImport.ts @@ -0,0 +1,283 @@ +import { localTranscriptVtt, localTranscriptFingerprint } from "../lib/localMediaTranscript"; +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)); + 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(c.config.sourceId, row.media))) { + row.generatedMetadata = true; + row.directoryId = localRecordingId(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(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(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/localMediaLifecycle.test.ts b/common/controller/localMediaLifecycle.test.ts @@ -0,0 +1,104 @@ +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:01.000 --> 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); +}); diff --git a/common/controller/localMediaPreparation.test.ts b/common/controller/localMediaPreparation.test.ts @@ -0,0 +1,156 @@ +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.000 --> 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.000 --> 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("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)); + } +}); 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:01.000 --> 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("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/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 @@ -1512,6 +1512,18 @@ const JOB_KINDS: Record<string, JobKindMeta> = { // On the channel's own queue (`channel:<slug>`): nothing is fetched, so no // platform queue is owed a turn. Not replayable: the archive it names is a // path on some drive, and a retry is a re-run. + // External files have their own read-only resolver/health checks. This job + // writes corpus text only, so a disconnected MANAGED-media drive is irrelevant. + // The controller additionally refuses every relocation marker. Fresh preview + // tokens are required for retry, so no replayable JobSpec is stored. + "import-local-media": { + kind: "import-local-media", + label: "Import external media library", + drainable: true, + replayable: false, + queueKeyStrategy: "custom", + needsText: true, + }, "attach-media": { kind: "attach-media", label: "Attach local media", @@ -1609,6 +1621,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/jobs/localMediaImportJob.ts b/common/jobs/localMediaImportJob.ts @@ -0,0 +1,70 @@ +import { parseLocalRecordingDetails } from "../lib/localRecordingDetails"; +import type { Paths } from "../lib/paths"; +import { channelQueueKey } from "../lib/queueKeys"; +import { importLocalMedia, type LocalMediaSelection } from "../controller/localMediaImport"; +import { runManagedFunction, type RunManagedFunctionOpts } from "./streamCommand"; + +export type LocalMediaJobRequest = { + sourceToken: string; + selected: readonly LocalMediaSelection[]; +}; + +// 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 > 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("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; + 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 }); + 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 (result.needsIndexUpdate) onLog("Import complete. Click \"Update searchable library\" on the Local media library page to make the imported recordings searchable on your selected site."); + // 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/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"; @@ -268,6 +269,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. @@ -348,6 +351,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: @@ -561,6 +566,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, 42); // 2026-10-30: `skipShorts` + assert.equal(CHANNEL_CONFIG_KEYS.length, 43); // 2026-10-30: `skipShorts`; 2026-11: opt-in `localMedia` 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 @@ -85,6 +85,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/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,31 @@ +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); +}); diff --git a/common/lib/localMedia.ts b/common/lib/localMedia.ts @@ -0,0 +1,46 @@ +// 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 }; +} 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:01.000 --> 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,115 @@ +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 { 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" }); + await writeFile(path.join(stage, EXTERNAL_MEDIA_FILENAME), JSON.stringify(reference, null, 2) + "\n", { flag: "wx" }); + 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,171 @@ +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); } +}); + +test("short timestamps produce index-compatible cues", async (t) => { + const root = await fixture(t); + await add(root, "short"); + await writeFile(path.join(root, "short.vtt"), "WEBVTT\n\n00:00.250 --> 00:01.910\nShort cue\n"); + const row = (await scan(root)).candidates[0]; + assert.equal(row.status, "new"); + assert.equal(row.cueCount, 1); + assert.deepEqual(row.warnings, []); +}); +test("isolated zero-duration cues warn without changing source; all-point transcripts remain blocked", async (t) => { + const root = await fixture(t); + await add(root, "mixed"); await add(root, "points"); + const point = "00:03.000 --> 00:03.000\nPoint cue\n"; + const mixed = VTT + "\n" + point; + await writeFile(path.join(root, "mixed.vtt"), mixed); + await writeFile(path.join(root, "points.vtt"), "WEBVTT\n\n" + point); + const result = await scan(root, ["mixed"]); + assert.equal(result.candidates[0].status, "existing"); + assert.equal(result.candidates[0].cueCount, 2); + assert.match(result.candidates[0].warnings.join(), /1 zero-duration/); + assert.equal(result.candidates[1].status, "issue"); + assert.match(result.candidates[1].issues.join(), /no positive-duration/); + assert.equal(await readFile(path.join(root, "mixed.vtt"), "utf8"), mixed); +}); 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> &amp; 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:01.000 --> 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> &lt;lesson&gt;\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("&lt;00:00:00.500> &lt;lesson&gt;")); + 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, "&amp;") + .replace(/<(?!\/?(?:b|i|u)>)/g, "&lt;")).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,30 @@ +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. +export function localRecordingId(sourceId: string, media: string): string { + return "local-" + createHash("sha256").update(JSON.stringify(["local-recording-v1", 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,58 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { prepareManualLocalRecordingMetadata, prepareLocalRecordingMetadata, requireLocalRecordingMetadata } 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")); +}); + +test("an explicit recording date stays distinct from publication 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, ""); + 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.throws(() => platformFromMetadata({...value, ...change})); + } +}); + +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,145 @@ +// 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; +} 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/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/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 { requireLocalRecordingMetadata } 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; @@ -88,6 +91,10 @@ export function loadRawMetadataFromDir( // URL) still lands there, and changing that would relabel records already // published. export function platformFromMetadata(meta: RawMetadata): Platform { + if (meta.local_recording !== undefined) { + requireLocalRecordingMetadata(meta); + 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 +171,8 @@ export function summarize( id, channelSlug, title: meta.title ?? id, - uploadDate: meta.upload_date ?? dateFromDir ?? "", + uploadDate: platform === "local" ? "" : 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 ?? "", 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 @@ -197,6 +199,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 @@ -249,6 +249,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", @@ -258,8 +261,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"); @@ -272,7 +277,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/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]/local-media/LocalMediaPanel.tsx b/editor/app/channels/[slug]/local-media/LocalMediaPanel.tsx @@ -0,0 +1,164 @@ +"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 { configureLibraryAction, 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, setConfig] = useState(initialConfig); + const [sourceId, setSourceId] = useState("library-1"); + const [directory, setDirectory] = useState(""); + 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"> + {!config ? <form className="space-y-3" onSubmit={event => { + event.preventDefault(); setError(null); + start(async () => { + try { + const result = await configureLibraryAction(slug, {sourceId, directory}); + if (result.ok) setConfig(result.config); else setError(result.error); + } catch { setError("Could not contact the editor. Try again."); } + }); + }}> + <label className="block">Library ID + <input required pattern="[a-z0-9][a-z0-9_-]{0,63}" value={sourceId} onChange={e => setSourceId(e.target.value)} className="block rounded border p-2 bg-background" /> + </label> + <label className="block">Library directory + <input required value={directory} onChange={e => setDirectory(e.target.value)} placeholder="/mnt/library" className="block w-full rounded border p-2 bg-background" /> + </label> + <p className="text-sm text-muted-foreground">Enter a directory readable by Archilyzer. When running directly, use its normal filesystem path. For Docker, use the mounted path inside the container, preferably read-only for original recordings. The saved library location cannot be changed from this screen.</p> + <button className={button} disabled={busy}>Save library</button> + </form> : <> + <p><strong>{config.sourceId}</strong> · <code className="break-all">{config.directory}</code></p> + <p className="text-sm text-muted-foreground">Scanning matches MP4, .info.json and .vtt or .srt files with the same base filename in this directory. A matching VTT takes priority. SRT is converted to VTT during import; the original stays unchanged. Subdirectories are not scanned. If metadata is missing but the MP4 and transcript are readable, you can prepare local recording details below.</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> + <p className="text-sm text-muted-foreground">Occupied means a destination already exists; its contents have not been verified. Select new recordings or prepare details for recordings with missing metadata. For an occupied recording with matching source metadata, “Verify and link” compares its metadata and transcript with the library, then saves a local reference only if they match. Original files and existing transcripts stay unchanged. Linking does not enable playback.</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">The destination is occupied. This preview has not reverified its saved transcript or reference.</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">Metadata was prepared during import. Verify and link requires matching source metadata; this preview has not reverified the saved files.</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,80 @@ +"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> + <p className="text-sm text-muted-foreground">This recording has no matching metadata file. Prepare details for a local recording without an online source. Your original files stay unchanged. Metadata is saved in Archilyzer only when you import.</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">Enter a date you know, or leave it unknown. This is not a publication date. File creation and modified dates can reflect copying or editing.</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>} + <p className="text-sm text-muted-foreground">Use these details to select the recording, then choose Import selected. The import rechecks the source before saving. Playback permission and updating the searchable library remain separate steps.</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,61 @@ +"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 { configureLocalMedia } from "yt-dlp-transcript-common/controller/configureLocalMedia"; +import { prepareLocalMediaRecording, type LocalRecordingPreparationRequest, previewLocalMedia } from "yt-dlp-transcript-common/controller/localMediaImport"; +import { startLocalMediaImportJob, type LocalMediaJobRequest } from "yt-dlp-transcript-common/jobs/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 configureLibraryAction(slug: string, input: unknown) { + try { + const config = await configureLocalMedia(getPaths(), slug, input); + revalidatePath(`/channels/${slug}/local-media`); + return { ok: true as const, config }; + } catch { + return { ok: false as const, error: "Could not configure the library. Check the server path, channel activity, and whether a library is already configured." }; + } +} + +export async function previewLibraryAction(slug: string) { + try { return { ok: true as const, preview: await previewLocalMedia(getPaths(), slug) }; } + catch { 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,19 @@ +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> + <p>Import metadata and transcripts for existing MP4 recordings. Video files stay in your library.</p> + <LocalMediaPanel slug={slug} initialConfig={config.localMedia ?? null} /> + </div>; +} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -993,6 +993,7 @@ export default async function ChannelDetailPage({ failedVideoIds={failedVideoIds} generatedAt={snapshot.generatedAt} lastSyncedAt={config.lastSyncedAt} + onlineSyncApplicable={!config.localMedia || !!config.url} /> <RunningJobsList jobs={runningJobs} hideChannelSlug /> @@ -1003,6 +1004,7 @@ export default async function ChannelDetailPage({ stageOrder={stageOrder} stages={stages} selected={selectedStage} + showLocalLibrary={!isSocialChannel(config)} /> {selectedStage ? ( <section @@ -1033,6 +1035,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]/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&apos;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/actions.ts b/editor/app/channels/actions.ts @@ -1,5 +1,6 @@ "use server"; +import { prepareLocalArchiveChannel } from "./lib/prepareLocalArchiveChannel"; import { withRumbleDefaults } from "yt-dlp-transcript-common/lib/rumbleDefaults"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; @@ -231,7 +232,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( @@ -242,7 +245,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. Local video playback starts enabled; you can turn it off on the library page. + </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,73 @@ +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 enables playback by default 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,playback:true}, syncIntervalMinutes:0,fullSweepIntervalMinutes:0} }); + 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/); + } + 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/); +}); + +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,61 @@ +import path from "node:path"; +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: true, + }); + 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)); + 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: [], + }; +}