File size: 21,445 Bytes
5c0175e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 | // 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<ScanStartResult> {
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<SourceFile>((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<SourceFile>((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<string> {
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<void> {
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<void> {
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<number> {
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<void> {
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 };
|