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"; import { storedNameOf } from "../lib/storedText"; import { decodeStoredBytes } from "../lib/storedText-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) { 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 { if (await lstat(path.join(root, name)).then(() => true, () => false)) return bytes(root, name); const stored = storedNameOf(name); if (!(await lstat(path.join(root, stored)).then(() => true, () => false))) return bytes(root, name); return decodeStoredBytes(await bytes(root, stored), path.join(root, stored)); } // 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; afterReferenceRead?: () => Promise } = {}): Promise { 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 captionBytes(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 { 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; } } }