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 { isExternalMediaRelativePath } from "./localMedia"; 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 { 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 { 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 { 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; // A name the library reference cannot hold (a control character, \ or :) // is held here: offered as new, its import could only fail. if (!isExternalMediaRelativePath(media)) { row.issues.push("Media: the file name has a control character, \\ or :, which a library reference cannot hold; rename the file"); } else { 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>(); 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(); 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): string { return createHash("sha256").update(JSON.stringify([media, metadata, transcript, info.dev, info.ino, info.size, info.mtimeMs, info.ctimeMs])).digest("hex"); }