Spaces:
Sleeping

VR-MEDIA / src /lib /custom-thumbs.ts
Zero124's picture
VR Media Server 2.0 — latest build (custom Blomp thumbnail auto-detection + full pipeline)
5c0175e
Raw History Blame Contribute Delete
19.3 kB
// Custom thumbnails matched from cloud-drive images (Blomp first).
//
// Users can upload their own poster images to their cloud drive — anywhere in
// the drive — named like the video. The Blomp sync lists every image object in
// the container, matches them to indexed videos by filename, and stores the
// match on the Video row. /api/thumbnail/<id> then serves the user's own
// image — the exact bytes they uploaded, never re-encoded — instead of the
// ffmpeg middle-frame extraction.
//
// Matching rules (applied per video, from ANY folder of the drive):
// Tier 1 — the image name (minus its extension) equals the video name
// minus its extension, or equals the video's full filename:
// "Trip to Mars.mp4" <-> "trip_to_mars.JPG"
// "Trip to Mars.mp4" <-> "Trip to Mars.mp4.png"
// Tier 2 — the video base name plus a poster word:
// "Trip to Mars.mp4" <-> "Trip to Mars - poster.webp"
// words: poster | cover | thumb | thumbnail | folder
// Comparison is case-insensitive; runs of spaces, dots, underscores and
// hyphens fold to a single space, so "My_Video", "my.video" and "MY VIDEO"
// are the same name.
//
// When several images match one video we prefer: tier 1 over tier 2, then an
// image that lives in the same folder as the video, then JPEG > PNG > WebP >
// GIF > BMP > AVIF, then the larger file, then the lexicographically first
// object name (purely for determinism).
//
// Serving: bytes are downloaded once with the Swift auth token (same headers
// as the stream proxy) and cached in THUMBNAIL_DIR as custom-<id>.img plus a
// custom-<id>.meta.json sidecar holding the fingerprint and sniffed MIME
// type. A changed hash on the drive invalidates the cache automatically, and
// the ?v=<hash> parameter appended to thumbnail URLs busts browser / DeoVR /
// PLAY'A caches.
import { createHash } from "node:crypto";
import {
existsSync,
mkdirSync,
readFileSync,
renameSync,
unlinkSync,
writeFileSync,
} from "node:fs";
import { join } from "node:path";
import { db } from "./db";
import { blompUpstreamHeaders, refreshBlompStreamUrl } from "./blomp";
import { fetchUpstream } from "./sources";
const THUMB_DIR = process.env.THUMBNAIL_DIR || "/data/thumbnails";
/** Refuse to cache absurd "thumbnails" (e.g. a 2 GB file named video.jpg). */
const MAX_IMAGE_BYTES = 25 * 1024 * 1024;
/** Poster words accepted after the plain video name (tier 2). */
const POSTER_SUFFIXES = ["poster", "cover", "thumb", "thumbnail", "folder"] as const;
/** Preferred image formats when several candidates match. */
const EXTENSION_RANK: Record<string, number> = {
jpg: 0,
jpeg: 0,
png: 1,
webp: 2,
gif: 3,
bmp: 4,
avif: 5,
};
const IMAGE_EXT_RE = /\.(jpe?g|png|webp|gif|bmp|avif)$/i;
// ---------------------------------------------------------------------------
// Type shapes
// ---------------------------------------------------------------------------
/** An image object discovered on a connected cloud drive. */
export interface CustomThumbImage {
/** Source provider, e.g. "blomp". */
container: string;
/** Full object name inside the container, e.g. "posters/trip.jpg". */
objectName: string;
/** File name with extension, e.g. "trip.jpg". */
baseName: string;
/** Display form of the containing folder, e.g. "/posters". */
folderPath: string;
bytes: number;
lastModified: string | null;
contentType: string | null;
}
/** A video row as far as the matcher cares. */
export interface ThumbMatchVideo {
id: string;
name: string;
folderPath: string;
customThumbPath?: string | null;
customThumbHash?: string | null;
}
/** Result of one thumbnail reconcile pass. */
export interface ThumbApplyResult {
/** Videos that currently have a matching image. */
matched: number;
/** New or changed matches written to the DB. */
applied: number;
/** Previously matched thumbnails withdrawn (image deleted upstream). */
removed: number;
/** Matches that were already current. */
unchanged: number;
/** Set when the pass was skipped and why; null when it ran. */
skipped: string | null;
}
/** Video fields needed to fetch/serve a custom thumbnail. */
export interface CustomThumbRef {
id: string;
customThumbSource: string | null;
customThumbPath: string | null;
customThumbHash: string | null;
}
/** Served bytes for a custom thumbnail. */
export interface CustomThumbBytes {
buf: Buffer;
mime: string;
hash: string;
}
// ---------------------------------------------------------------------------
// Name normalization + matching (pure functions — unit-testable)
// ---------------------------------------------------------------------------
function stripExtension(name: string): string {
const idx = name.lastIndexOf(".");
return idx > 0 ? name.slice(0, idx) : name;
}
/**
* Canonical matching key for a file name: case-folded, Unicode NFC, with runs
* of spaces / dots / underscores / hyphens collapsed to a single space.
*/
export function thumbKey(name: string): string {
return name
.normalize("NFC")
.toLowerCase()
.replace(/[\s._\-]+/g, " ")
.trim();
}
function folderKeyOf(folderPath: string | null | undefined): string {
return thumbKey(folderPath ?? "");
}
/** Lowercased image extension of a file name, or "". */
export function imageExtension(baseName: string): string {
const m = IMAGE_EXT_RE.exec(baseName);
return m ? m[1].toLowerCase() : "";
}
interface IndexedImage {
image: CustomThumbImage;
extRank: number;
folderKey: string;
}
export type ThumbIndex = Map<string, IndexedImage[]>;
/** Index images by their normalized name key for O(1) lookup. */
export function buildThumbIndex(images: CustomThumbImage[]): ThumbIndex {
const byKey: ThumbIndex = new Map();
for (const image of images) {
const key = thumbKey(stripExtension(image.baseName));
if (!key) continue;
const ext = imageExtension(image.baseName);
const entry: IndexedImage = {
image,
extRank: EXTENSION_RANK[ext] ?? 9,
folderKey: folderKeyOf(image.folderPath),
};
const list = byKey.get(key);
if (list) list.push(entry);
else byKey.set(key, [entry]);
}
return byKey;
}
interface Candidate {
tier: number;
sameFolder: number;
extRank: number;
bytes: number;
image: CustomThumbImage;
}
/** Strict preference order between two candidate images for one video. */
function beats(a: Candidate, b: Candidate): boolean {
if (a.tier !== b.tier) return a.tier < b.tier;
if (a.sameFolder !== b.sameFolder) return a.sameFolder > b.sameFolder;
if (a.extRank !== b.extRank) return a.extRank < b.extRank;
if (a.bytes !== b.bytes) return a.bytes > b.bytes;
return a.image.objectName < b.image.objectName;
}
/**
* Best image for one video from a prebuilt index, or null.
* Pure: no DB, no network.
*/
export function findBestThumbImage(
video: { name: string; folderPath: string },
index: ThumbIndex
): CustomThumbImage | null {
const baseKey = thumbKey(stripExtension(video.name));
const fullKey = thumbKey(video.name);
const videoFolder = folderKeyOf(video.folderPath);
const tier1 = [...new Set([baseKey, fullKey].filter(Boolean))];
const tier2 = tier1.flatMap((key) => POSTER_SUFFIXES.map((suffix) => `${key} ${suffix}`));
let best: Candidate | null = null;
const tiers: readonly (readonly [readonly string[], number])[] = [
[tier1, 1],
[tier2, 2],
];
for (const [keys, tier] of tiers) {
for (const key of keys) {
const list = index.get(key);
if (!list) continue;
for (const entry of list) {
const candidate: Candidate = {
tier,
sameFolder: entry.folderKey === videoFolder ? 1 : 0,
extRank: entry.extRank,
bytes: entry.image.bytes,
image: entry.image,
};
if (best === null || beats(candidate, best)) best = candidate;
}
}
}
return best !== null ? best.image : null;
}
/** Stable fingerprint of a drive image: identity of the bytes, not the URL. */
export function customThumbHashOf(image: CustomThumbImage): string {
return createHash("sha1")
.update(`${image.objectName}|${image.bytes}|${image.lastModified ?? ""}`)
.digest("hex");
}
// ---------------------------------------------------------------------------
// Reconcile pass (called by the Blomp sync + the manual scan)
// ---------------------------------------------------------------------------
/**
* Match cloud-drive images to indexed Blomp videos and persist the result.
*
* - New/changed match: stores source/path/hash and drops the stale disk cache.
* - Image gone: clears the fields so the video falls back to the auto frame.
* - Unchanged: no writes at all.
*
* `opts.trustEmpty` must be true for an empty image listing to withdraw
* existing matches — a failed listing must never hide thumbnails, exactly
* like the video deletion logic refuses empty listings.
*/
export async function applyBlompCustomThumbnails(
images: CustomThumbImage[],
opts: { trustEmpty?: boolean } = {}
): Promise<ThumbApplyResult> {
const result: ThumbApplyResult = {
matched: 0,
applied: 0,
removed: 0,
unchanged: 0,
skipped: null,
};
if (images.length === 0 && !opts.trustEmpty) {
result.skipped = "image listing was empty (not trusted)";
return result;
}
const index = buildThumbIndex(images);
const videos = await db.video.findMany({
where: { source: "blomp", availability: "available" },
select: {
id: true,
name: true,
folderPath: true,
customThumbPath: true,
customThumbHash: true,
},
});
for (const video of videos) {
const best = findBestThumbImage(video, index);
if (best) {
result.matched++;
const path = `${best.container}/${best.objectName}`;
const hash = customThumbHashOf(best);
if (video.customThumbPath === path && video.customThumbHash === hash) {
result.unchanged++;
continue;
}
await db.video.update({
where: { id: video.id },
data: {
customThumbSource: "blomp",
customThumbPath: path,
customThumbHash: hash,
customThumbAt: new Date(),
},
});
// The cached bytes belong to the previous match/hash — drop them.
clearCustomThumbnail(video.id);
result.applied++;
} else if (video.customThumbPath) {
await db.video.update({
where: { id: video.id },
data: {
customThumbSource: null,
customThumbPath: null,
customThumbHash: null,
customThumbMime: null,
customThumbAt: null,
},
});
clearCustomThumbnail(video.id);
result.removed++;
}
}
return result;
}
// ---------------------------------------------------------------------------
// Disk cache + serving
// ---------------------------------------------------------------------------
function ensureThumbDir(): void {
try {
if (!existsSync(THUMB_DIR)) mkdirSync(THUMB_DIR, { recursive: true });
} catch {
// Read-only FS: downloads will fail and we fall back to auto frames.
}
}
function customCachePath(id: string): string {
return join(THUMB_DIR, `custom-${id}.img`);
}
function customMetaPath(id: string): string {
return join(THUMB_DIR, `custom-${id}.meta.json`);
}
/** Short-lived negative cache so a Blomp outage cannot make every card wait
* for a 30s download timeout. Cleared by the next successful download (and
* by clearCustomThumbnail when the match changes). */
const DOWNLOAD_RETRY_MS = 60_000;
function customFailedPath(id: string): string {
return join(THUMB_DIR, `custom-${id}.failed.json`);
}
function markDownloadFailed(id: string): void {
try {
ensureThumbDir();
writeFileSync(customFailedPath(id), JSON.stringify({ at: Date.now() }));
} catch {
// Best-effort only.
}
}
function downloadFailedRecently(id: string): boolean {
try {
if (!existsSync(customFailedPath(id))) return false;
const marker = JSON.parse(readFileSync(customFailedPath(id), "utf8")) as { at?: number };
if (!marker?.at || Date.now() - marker.at > DOWNLOAD_RETRY_MS) return false;
return true;
} catch {
return false;
}
}
interface CustomMeta {
hash: string;
mime: string;
bytes: number;
at: string;
}
/** Drop the cached custom-thumbnail bytes + sidecars for a video. */
export function clearCustomThumbnail(id: string): void {
for (const path of [customCachePath(id), customMetaPath(id), customFailedPath(id)]) {
try {
unlinkSync(path);
} catch {
// Not there — fine.
}
}
}
/** Sniff the MIME type from magic bytes; null when not a known image. */
export function sniffImageMime(buf: Buffer): string | null {
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
return "image/jpeg";
}
if (buf.length >= 8 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
return "image/png";
}
if (
buf.length >= 12 &&
buf.toString("ascii", 0, 4) === "RIFF" &&
buf.toString("ascii", 8, 12) === "WEBP"
) {
return "image/webp";
}
if (buf.length >= 6) {
const head = buf.toString("ascii", 0, 6);
if (head === "GIF87a" || head === "GIF89a") return "image/gif";
}
if (buf.length >= 2 && buf[0] === 0x42 && buf[1] === 0x4d) {
return "image/bmp";
}
if (
buf.length >= 12 &&
buf.toString("ascii", 4, 8) === "ftyp" &&
/avif|avis/.test(buf.toString("ascii", 8, 12))
) {
return "image/avif";
}
return null;
}
function imageContentTypeOf(header: string | null): string | null {
const type = (header ?? "").split(";")[0].trim().toLowerCase();
return type.startsWith("image/") ? type : null;
}
/** Read the cached bytes when they match the expected fingerprint. */
function readCachedCustomThumbnail(id: string, expectedHash: string | null): CustomThumbBytes | null {
try {
const metaPath = customMetaPath(id);
const cachePath = customCachePath(id);
if (!existsSync(metaPath) || !existsSync(cachePath)) return null;
const meta = JSON.parse(readFileSync(metaPath, "utf8")) as CustomMeta;
if (!meta?.hash || !meta?.mime) return null;
if (expectedHash && meta.hash !== expectedHash) return null; // stale
const buf = readFileSync(cachePath);
if (buf.length === 0) return null;
return { buf, mime: meta.mime, hash: meta.hash };
} catch {
return null;
}
}
/**
* Ensure the custom thumbnail for a video is downloaded and cached.
* Returns the exact bytes + MIME type, or null when no custom thumbnail is
* set / the download failed (caller falls back to the auto-extracted frame).
*/
export async function ensureCustomThumbnail(video: CustomThumbRef): Promise<CustomThumbBytes | null> {
if (!video.customThumbPath) return null;
const cached = readCachedCustomThumbnail(video.id, video.customThumbHash);
if (cached) return cached;
// Only Blomp is wired up for now; future sources plug in here.
if (video.customThumbSource && video.customThumbSource !== "blomp") return null;
// A recent failure means Blomp is likely unreachable — fall back to the
// auto-extracted frame immediately instead of hanging every card render.
if (downloadFailedRecently(video.id)) return null;
try {
const url = await refreshBlompStreamUrl({
sourcePath: video.customThumbPath,
sourceId: video.customThumbPath,
});
if (!url) {
markDownloadFailed(video.id);
return null;
}
const headers = await blompUpstreamHeaders();
const res = await fetchUpstream(url, { headers, signal: AbortSignal.timeout(30000) });
if (!res.ok) {
console.warn(`[custom-thumbs] download failed (HTTP ${res.status}) for ${video.customThumbPath}`);
markDownloadFailed(video.id);
return null;
}
const declared = Number(res.headers.get("content-length") ?? "0");
if (declared > MAX_IMAGE_BYTES) {
console.warn(`[custom-thumbs] ${video.customThumbPath} is too large (${declared} bytes) — skipped`);
return null;
}
const buf = Buffer.from(await res.arrayBuffer());
if (buf.length === 0 || buf.length > MAX_IMAGE_BYTES) return null;
const mime = sniffImageMime(buf) ?? imageContentTypeOf(res.headers.get("content-type"));
if (!mime) {
// Not an image after all — do not cache, fall back to the auto frame.
console.warn(`[custom-thumbs] ${video.customThumbPath} is not a recognized image — skipped`);
return null;
}
ensureThumbDir();
// Atomic-ish write: temp file + rename, so a concurrent reader never
// sees a half-written image.
const tmp = `${customCachePath(video.id)}.tmp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
writeFileSync(tmp, buf);
renameSync(tmp, customCachePath(video.id));
const meta: CustomMeta = {
hash: video.customThumbHash ?? "",
mime,
bytes: buf.length,
at: new Date().toISOString(),
};
writeFileSync(customMetaPath(video.id), JSON.stringify(meta));
// Success clears the failure marker.
try {
unlinkSync(customFailedPath(video.id));
} catch {
// Was not there.
}
// Best-effort: remember the sniffed type on the row for the inspector.
try {
await db.video.update({ where: { id: video.id }, data: { customThumbMime: mime } });
} catch {
// Row may be gone — harmless.
}
return { buf, mime, hash: meta.hash };
} catch (err) {
console.warn(
`[custom-thumbs] download failed: ${err instanceof Error ? err.message : String(err)}`
);
markDownloadFailed(video.id);
return null;
}
}
// ---------------------------------------------------------------------------
// Cache-busting version parameter
// ---------------------------------------------------------------------------
/**
* Short, URL-safe version of a custom-thumbnail fingerprint. "auto" when the
* video has no custom thumbnail (URL stays stable for that common case).
*/
export function customThumbVersion(hash: string | null | undefined): string {
const clean = (hash ?? "").replace(/[^a-zA-Z0-9]/g, "");
return clean.slice(0, 10) || "auto";
}
/**
* Append the cache-busting ?v= parameter to a thumbnail URL. No-op when the
* video has no custom thumbnail, so existing caches stay valid.
*/
export function withThumbVersion(url: string, hash: string | null | undefined): string {
const version = customThumbVersion(hash);
if (version === "auto") return url;
return `${url}${url.includes("?") ? "&" : "?"}v=${version}`;
}