import { parseLocalRecordingDetails } from "../lib/localRecordingDetails"; import type { Paths } from "../lib/paths"; import { channelQueueKey } from "../lib/queueKeys"; import { importLocalMedia, type LocalMediaPreview, type LocalMediaSelection } from "./localMediaImport"; import { runManagedFunction, type RunManagedFunctionOpts } from "../jobs/streamCommand"; export type LocalMediaJobRequest = { sourceToken: string; selected: readonly LocalMediaSelection[]; // New recordings left for a later run (selectAllNew): said in the job's log. remaining?: number; }; // One job imports at most this many recordings. export const LOCAL_MEDIA_IMPORT_MAX = 1000; // EVERY NEW RECORDING of a fresh preview, at most LOCAL_MEDIA_IMPORT_MAX of them: // the first in the preview's order (the scan's sorted file names, so a re-run // after an import takes the next ones), and how many new ones are left over. // Review fix 7 (lane/local-media): over the cap it was a generic refusal. export function selectAllNew(preview: LocalMediaPreview): { request: LocalMediaJobRequest; remaining: number } { const all = preview.candidates .filter((c) => c.status === "new" && c.fingerprint) .map((c) => ({ media: c.media, fingerprint: c.fingerprint! })); const selected = all.slice(0, LOCAL_MEDIA_IMPORT_MAX); const remaining = all.length - selected.length; return { request: { sourceToken: preview.sourceToken, selected, ...(remaining > 0 ? { remaining } : {}) }, remaining }; } // Keep the managed job's body testable with synthetic sources, without starting // the application's registry or snapshot timers. The production entry point // below always uses runManagedFunction, including its enqueue/start guards. export function localMediaJobOptions(paths: Paths, slug: string, request: LocalMediaJobRequest): RunManagedFunctionOpts { if (!request || typeof request.sourceToken !== "string" || !Array.isArray(request.selected) || request.selected.length === 0 || request.selected.length > LOCAL_MEDIA_IMPORT_MAX || request.selected.some(s => !s || typeof s.media !== "string" || typeof s.fingerprint !== "string") || new Set(request.selected.map(s => s.media)).size !== request.selected.length) { throw new Error("Select between 1 and 1000 distinct recordings from a fresh preview"); } if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) || slug.endsWith(".")) throw new Error("Invalid channel slug"); // A caller must not be able to mutate a request while it waits in the queue. const selected = request.selected.map(({ media, fingerprint, preparation }) => { if (preparation !== undefined && (!preparation || typeof preparation.sourceFingerprint !== "string")) { throw new Error("Invalid recording preparation"); } return {media, fingerprint, ...(preparation ? {preparation: { sourceFingerprint: preparation.sourceFingerprint, details: parseLocalRecordingDetails(preparation.details), }} : {})}; }); const sourceToken = request.sourceToken; const remaining = typeof request.remaining === "number" && Number.isSafeInteger(request.remaining) && request.remaining > 0 ? request.remaining : 0; const leftOverLine = remaining ? `${remaining} more new recording(s) were not selected (one import takes at most ${LOCAL_MEDIA_IMPORT_MAX}); import again after this one to take the next ${Math.min(remaining, LOCAL_MEDIA_IMPORT_MAX)}.` : null; return { kind: "import-local-media", queueKey: channelQueueKey(slug), paths, channelSlug: slug, // No spec: replaying persisted names/tokens after source edits is misleading. // The operator takes a new preview to retry or continue a drained batch. fn: async (onLog, signal, setProgress, ctx) => { setProgress({ metric: "entries", initial: 0, target: selected.length, current: 0 }); if (leftOverLine) onLog(leftOverLine); onLog("Rechecking selected external recordings before import..."); const result = await importLocalMedia(paths, slug, { sourceToken, selected, signal, drainSignal: ctx.drainSignal, onRecord: (record, completed) => { // JSON quoting prevents filenames with newlines from forging log lines. // Absolute library roots never enter these progress messages. onLog(JSON.stringify({ recording: record.media, status: record.status, reason: record.reason, warnings: record.warnings, incomplete: record.incomplete })); setProgress({ metric: "entries", initial: 0, target: selected.length, current: completed }); }, }); const imported = result.records.filter(r => r.status === "imported").length; const occupied = result.records.filter(r => r.status === "occupied").length; const rejected = result.records.length - imported - occupied; onLog(`Imported ${imported}; already occupied ${occupied}; rejected ${rejected}; unprocessed ${selected.length - result.records.length}.`); if (leftOverLine) onLog(leftOverLine); // What works today: the records are searchable after the next index build. if (result.needsIndexUpdate) onLog("Import complete. The imported recordings are searchable after the next index build (`pnpm ops build-index`, or a site build)."); // The existing managed-job completion hook requests a channel snapshot, // including on failure/cancellation. This job does not build/publish a site. if (result.cancelled) { onLog("Import cancelled."); return; } if (result.drained) onLog("Import stopped between recordings. Preview again to continue."); if (rejected || result.records.some(r => r.stagingCleanupFailed)) { throw new Error("Some selected recordings require review. Saved records were retained; preview again before retrying."); } }, }; } export async function startLocalMediaImportJob(paths: Paths, slug: string, request: LocalMediaJobRequest) { return runManagedFunction(localMediaJobOptions(paths, slug, request)); }