// Scan engine — orchestrates multi-source discovery (Offcloud + TeraBox + // Blomp) followed by the 11-layer detection pipeline. // // Invoked by /api/scan, /api/offcloud/scan, /api/terabox/scan and // /api/blomp/scan. Runs in the background and updates QueueItem rows as each // step progresses. import { db } from "./db"; import { scanLibrary, getApiKey } from "./offcloud"; import { scanTeraboxLibrary, isTeraboxConfigured } from "./terabox"; import { scanBlompLibrary, isBlompConfigured } from "./blomp"; import { applyBlompCustomThumbnails } from "./custom-thumbs"; import type { CustomThumbImage } from "./custom-thumbs"; import { detectionStreamUrl, normalizeSource, pickFreshUrl, providerIdOf, refreshVideoStreamUrls, } from "./sources"; import { runDetection } from "./detection/classifier"; import type { QueueStep, SourceFile, VideoSource } from "./types"; const STEP_ORDER: { step: QueueStep; label: string }[] = [ { step: "metadata", label: "Container Metadata" }, { step: "filename", label: "Filename Intelligence" }, { step: "stream", label: "Stream Analysis" }, { step: "alpha", label: "Alpha Channel" }, { step: "mask", label: "Mask Track" }, { step: "frame", label: "Frame Analysis" }, { step: "depth", label: "Depth Detection" }, { step: "classify", label: "Classification & Confidence" }, ]; export type ScanTarget = VideoSource | "all"; export interface SourceScanInfo { source: VideoSource; status: "scanned" | "mock" | "not_configured" | "error" | "skipped"; found: number; error?: string; } export interface ScanStartResult { started: boolean; queuedCount: number; sources: SourceScanInfo[]; } let scanRunning = false; /** * Run a library scan across one or both sources. Safe to call repeatedly — if a * scan is already in progress, returns the current queue state instead of * starting a duplicate. */ export async function startScan(opts: { source?: ScanTarget } = {}): Promise { const target: ScanTarget = opts.source ?? "all"; if (scanRunning) { const queued = await db.queueItem.count({ where: { status: { in: ["queued", "running"] } } }); return { started: false, queuedCount: queued, sources: [] }; } const wantOffcloud = target === "all" || target === "offcloud"; const wantTerabox = target === "all" || target === "terabox"; const wantBlomp = target === "all" || target === "blomp"; // Read all three configs regardless of the target: mock mode must only be // used when NO real source is configured, even during a single-source scan. const [offcloudKey, teraboxReady, blompReady] = await Promise.all([ getApiKey(), isTeraboxConfigured(), isBlompConfigured(), ]); const files: SourceFile[] = []; const sources: SourceScanInfo[] = []; // Blomp images (custom thumbnails) collected by the scan, applied after the // video upserts below so brand-new videos are matched in the same pass. let blompImages: CustomThumbImage[] = []; let blompFolders: string[] = []; let blompScanOk = false; // ---- Offcloud ---- if (wantOffcloud) { if (offcloudKey) { const result = await scanLibrary({ allowMock: false }); files.push( ...result.files.map((f) => ({ source: "offcloud", sourceId: f.offcloudId, sourcePath: null, name: f.name, folderPath: f.folderPath, streamUrl: f.streamUrl, size: f.size, duration: f.duration, addedAt: f.addedAt, isMock: f.isMock, })) ); sources.push({ source: "offcloud", status: result.mode === "real" ? "scanned" : "error", found: result.files.length, error: result.mode === "error" ? "Offcloud scan failed" : undefined, }); } else if (!teraboxReady && !blompReady) { // Nothing is configured at all — keep the demo library working. const result = await scanLibrary({ allowMock: true }); files.push( ...result.files.map((f) => ({ source: "offcloud", sourceId: f.offcloudId, sourcePath: null, name: f.name, folderPath: f.folderPath, streamUrl: f.streamUrl, size: f.size, duration: f.duration, addedAt: f.addedAt, isMock: f.isMock, })) ); sources.push({ source: "offcloud", status: "mock", found: result.files.length }); } else { sources.push({ source: "offcloud", status: "not_configured", found: 0 }); } } else { sources.push({ source: "offcloud", status: "skipped", found: 0 }); } // ---- TeraBox ---- if (wantTerabox) { if (teraboxReady) { const result = await scanTeraboxLibrary(); files.push(...result.files); sources.push({ source: "terabox", status: result.error ? "error" : "scanned", found: result.files.length, error: result.error, }); } else { sources.push({ source: "terabox", status: "not_configured", found: 0 }); } } else { sources.push({ source: "terabox", status: "skipped", found: 0 }); } // ---- Blomp ---- if (wantBlomp) { if (blompReady) { const result = await scanBlompLibrary(); files.push(...result.files); if (!result.error) { blompImages = result.images; blompFolders = result.folders; blompScanOk = true; } sources.push({ source: "blomp", status: result.error ? "error" : "scanned", found: result.files.length, error: result.error, }); } else { sources.push({ source: "blomp", status: "not_configured", found: 0 }); } } else { sources.push({ source: "blomp", status: "skipped", found: 0 }); } // ---- Upsert videos + queue items ---- let queuedCount = 0; for (const f of files) { const videoId = await upsertVideo(f); // Skip queueing if the video is already ready and scanned recently. const existingVideo = await db.video.findUnique({ where: { id: videoId } }); if ( existingVideo?.status === "ready" && existingVideo.lastScannedAt && Date.now() - existingVideo.lastScannedAt.getTime() < 24 * 3600 * 1000 ) { continue; } const alreadyQueued = await db.queueItem.findFirst({ where: { videoId, status: { in: ["queued", "running"] } }, }); if (alreadyQueued) continue; await db.queueItem.create({ data: { videoId, status: "queued", currentStep: null, stepProgress: 0 }, }); queuedCount++; } // ---- Custom thumbnails (Blomp images named like the videos) ---- // Runs after the upserts so videos discovered by this very scan are // matched too. An empty image listing only withdraws existing matches when // the listing actually returned objects (same paranoia as deletions). if (blompScanOk) { try { const listingNonEmpty = blompImages.length > 0 || files.some((f) => f.source === "blomp"); const thumbs = await applyBlompCustomThumbnails(blompImages, { trustEmpty: listingNonEmpty, }); if (!thumbs.skipped && thumbs.applied + thumbs.removed > 0) { console.log( `[scan] custom thumbnails: ${thumbs.matched} matched, ${thumbs.applied} applied, ${thumbs.removed} withdrawn` ); } } catch (err) { console.warn( `[scan] custom thumbnail matching failed: ${ err instanceof Error ? err.message : String(err) }` ); } } // ---- Auto thumbnail upload (generate posters, push to Blomp) ---- // Mirrors what the Blomp sync does, so a manual scan behaves like a sync // cycle that just discovered the library. if (blompScanOk) { try { const { runBlompThumbUploadPass } = await import("./thumb-uploader"); void runBlompThumbUploadPass({ folders: blompFolders, imageFolders: blompImages.map((image) => image.folderPath), trigger: "manual", }).catch(() => {}); } catch { // Never fail the scan over the thumbnail pass. } } // Kick off the background processor (non-blocking). scanRunning = true; processQueue() .catch((err) => console.error("[scan] queue processor crashed:", err)) .finally(() => { scanRunning = false; }); return { started: true, queuedCount, sources }; } async function upsertVideo(f: SourceFile): Promise { const existing = f.source === "offcloud" ? await db.video.findFirst({ where: { source: "offcloud", name: f.name, OR: [{ sourceId: f.sourceId }, { offcloudId: f.sourceId }], }, }) : await db.video.findFirst({ where: { source: f.source, sourceId: f.sourceId } }); // Must match the fingerprint format used by each source's auto-sync engine, // otherwise a manual scan would make the next poll think the bytes changed. const contentHash = f.source === "offcloud" ? `${f.size}|${f.duration ?? ""}` : `${f.size}|${f.addedAt ? f.addedAt.toISOString() : ""}`; if (existing) { await db.video.update({ where: { id: existing.id }, data: { source: f.source, sourceId: f.sourceId, sourcePath: f.sourcePath ?? existing.sourcePath, // offcloudId is required in the legacy schema. For TeraBox/Blomp rows // it mirrors the provider id so old rows/foreign keys stay valid. offcloudId: f.sourceId, name: f.name, streamUrl: f.streamUrl || existing.streamUrl, folderPath: f.folderPath, size: f.size, duration: f.duration ?? existing.duration, addedAt: f.addedAt ?? existing.addedAt, // A manual scan is a fresh observation of this object: restore rows // that were hidden after deletion and keep the presence clock current. availability: "available", missingSince: null, lastSeenAt: new Date(), contentKey: f.sourceId, contentHash, status: existing.status === "ready" ? "ready" : "pending", }, }); return existing.id; } const created = await db.video.create({ data: { source: f.source, sourceId: f.sourceId, sourcePath: f.sourcePath ?? null, offcloudId: f.sourceId, name: f.name, folderPath: f.folderPath, streamUrl: f.streamUrl, size: f.size, duration: f.duration ?? null, addedAt: f.addedAt ?? null, status: "pending", availability: "available", lastSeenAt: new Date(), contentKey: f.sourceId, contentHash, }, }); return created.id; } /** * Start draining the detection queue unless a worker is already running. * Called by the sync engine whenever new content has been queued. */ export async function ensureQueueProcessing( mode: "real" | "mock" = "real" ): Promise { if (scanRunning) return; scanRunning = true; try { await processQueue(mode); } catch (err) { console.warn("[scan] queue worker stopped:", err); } finally { scanRunning = false; } } /** True while the detection worker is processing the queue. */ export function isQueueRunning(): boolean { return scanRunning; } /** * Process queued items one at a time. Each item refreshes its provider URL, * then runs the full 11-layer detection pipeline, updating QueueItem at every * step. * * Sequential on purpose — concurrent ffprobe/ffmpeg calls against the same * cloud CDN can trigger rate limiting. */ export async function processQueue(_mode: "real" | "mock" = "real"): Promise { while (true) { const next = await db.queueItem.findFirst({ where: { status: "queued", video: { availability: "available" } }, orderBy: { createdAt: "asc" }, }); if (!next) break; const video = await db.video.findUnique({ where: { id: next.videoId } }); if (!video) { await db.queueItem.update({ where: { id: next.id }, data: { status: "error", errorMessage: "Video not found", finishedAt: new Date() }, }); continue; } try { await db.queueItem.update({ where: { id: next.id }, data: { status: "running", startedAt: new Date() }, }); await db.video.update({ where: { id: video.id }, data: { status: "scanning" } }); // ---- Refresh the provider URL before probing ---- let streamUrl = video.streamUrl; try { const freshUrls = await refreshVideoStreamUrls(video); const fresh = pickFreshUrl(freshUrls, video); if (fresh) { streamUrl = fresh; await db.video.update({ where: { id: video.id }, data: { streamUrl: fresh } }); } } catch (err) { console.warn(`[scan] stream refresh failed for ${video.id}:`, err); } if (!streamUrl) { throw new Error( `${normalizeSource(video.source)} did not return a playable URL for this file` ); } // ---- Progress ticks (visual feedback only) ---- for (let i = 0; i < STEP_ORDER.length; i++) { const { step } = STEP_ORDER[i]; await db.queueItem.update({ where: { id: next.id }, data: { currentStep: step, stepProgress: Math.round((i / STEP_ORDER.length) * 100) }, }); await new Promise((r) => setTimeout(r, 80)); } // TeraBox/Blomp need authenticated proxy headers that ffprobe can't send, // so detection runs against our local /api/stream proxy instead. const probeUrl = await detectionStreamUrl({ ...video, streamUrl }); const result = await runDetection({ videoId: video.id, filename: video.name, folderPath: video.folderPath, streamUrl: probeUrl, duration: video.duration, }); await db.video.update({ where: { id: video.id }, data: { projection: result.classification.projection, stereo: result.classification.stereo, lensType: result.classification.lensType, resolutionTier: result.classification.resolutionTier, contentType: result.classification.contentType, passthrough: result.classification.passthrough, codec: result.container.codec, bitrate: result.container.bitrate, fps: result.container.fps, width: result.container.width, height: result.container.height, duration: result.container.duration ?? video.duration, containerMeta: JSON.stringify(result.report.layers[0]), filenameMeta: JSON.stringify(result.report.layers[5]), folderMeta: JSON.stringify(result.report.layers[6]), feedMeta: JSON.stringify(result.report.layers[7]), frameMeta: JSON.stringify(result.report.layers[9]), depthMeta: JSON.stringify(result.report.layers[10]), thumbnailMeta: JSON.stringify(result.report.layers[8]), detectionReport: JSON.stringify(result.report), passthroughScore: result.confidence.passthrough, projectionScore: result.confidence.projection, confidence: result.confidence.overall, feedValid: result.feedValid, feedErrors: JSON.stringify(result.feedErrors), questCompatible: result.questCompatible, status: "ready", lastScannedAt: new Date(), }, }); await db.queueItem.update({ where: { id: next.id }, data: { status: "done", currentStep: "classify", stepProgress: 100, finishedAt: new Date(), }, }); // Blomp auto thumbnails are NOT tied to detection: the web search // needs only the video title, and the pass fired by the sync/scanner // already covers every indexed video. Nothing to do here. } catch (err) { const msg = err instanceof Error ? err.message : "Unknown error"; await db.video.update({ where: { id: video.id }, data: { status: "error", errorMessage: msg }, }); await db.queueItem.update({ where: { id: next.id }, data: { status: "error", errorMessage: msg, finishedAt: new Date() }, }); } } } /** Helper for the Queue view — returns queue items with the step list expanded. */ export async function getQueueView() { const items = await db.queueItem.findMany({ where: { status: { in: ["queued", "running"] } }, orderBy: { createdAt: "asc" }, take: 50, include: { video: true }, }); return items.map((q) => ({ id: q.id, videoId: q.videoId, videoName: q.video?.name ?? "Unknown", source: normalizeSource(q.video?.source), status: q.status, currentStep: q.currentStep, stepProgress: q.stepProgress, startedAt: q.startedAt?.toISOString() ?? null, errorMessage: q.errorMessage, steps: STEP_ORDER.map((s, idx) => { const currentIdx = STEP_ORDER.findIndex((x) => x.step === q.currentStep); let status: "pending" | "running" | "done" | "error" = "pending"; if (q.status === "error") status = "error"; else if (q.status === "done") status = "done"; else if (idx < currentIdx) status = "done"; else if (idx === currentIdx) status = "running"; return { step: s.step, label: s.label, status }; }), })); } /** Reset videos (optionally only one source) so the next scan re-analyzes them. */ export async function resetVideos(source: ScanTarget = "all"): Promise { const where = source === "all" ? {} : { source }; const videos = await db.video.findMany({ where, select: { id: true } }); for (const v of videos) { await db.video.update({ where: { id: v.id }, data: { status: "pending", lastScannedAt: null }, }); await db.queueItem.deleteMany({ where: { videoId: v.id } }); } return videos.length; } /** * Re-run detection for a single video (Inspector "Re-analyze" + manual * corrections). Refreshes the provider URL and persists the full report. */ export async function analyzeVideo(id: string): Promise { const video = await db.video.findUnique({ where: { id } }); if (!video) throw new Error("Video not found"); await db.video.update({ where: { id }, data: { status: "scanning" } }); try { let streamUrl = video.streamUrl; try { const fresh = pickFreshUrl(await refreshVideoStreamUrls(video), video); if (fresh) { streamUrl = fresh; await db.video.update({ where: { id }, data: { streamUrl: fresh } }); } } catch (err) { console.warn(`[analyze] stream refresh failed for ${id}:`, err); } const probeUrl = await detectionStreamUrl({ ...video, streamUrl }); if (!probeUrl) throw new Error("No playable stream URL for this video"); const result = await runDetection({ videoId: id, filename: video.name, folderPath: video.folderPath, streamUrl: probeUrl, duration: video.duration, }); await db.video.update({ where: { id }, data: { projection: result.classification.projection, stereo: result.classification.stereo, lensType: result.classification.lensType, resolutionTier: result.classification.resolutionTier, contentType: result.classification.contentType, passthrough: result.classification.passthrough, codec: result.container.codec, bitrate: result.container.bitrate, fps: result.container.fps, width: result.container.width, height: result.container.height, duration: result.container.duration ?? video.duration, containerMeta: JSON.stringify(result.report.layers[0]), filenameMeta: JSON.stringify(result.report.layers[5]), folderMeta: JSON.stringify(result.report.layers[6]), feedMeta: JSON.stringify(result.report.layers[7]), frameMeta: JSON.stringify(result.report.layers[9]), depthMeta: JSON.stringify(result.report.layers[10]), thumbnailMeta: JSON.stringify(result.report.layers[8]), detectionReport: JSON.stringify(result.report), passthroughScore: result.confidence.passthrough, projectionScore: result.confidence.projection, confidence: result.confidence.overall, feedValid: result.feedValid, feedErrors: JSON.stringify(result.feedErrors), questCompatible: result.questCompatible, status: "ready", lastScannedAt: new Date(), errorMessage: null, }, }); } catch (err) { const msg = err instanceof Error ? err.message : "Unknown error"; await db.video.update({ where: { id }, data: { status: "error", errorMessage: msg } }); throw err; } } /** Re-export for callers that only need the provider id helper. */ export { providerIdOf };