VR-MEDIA / src /lib /blomp.ts
Zero124's picture
VR Media Server 2.0 — latest build (custom Blomp thumbnail auto-detection + full pipeline)
5c0175e
Raw History Blame Contribute Delete
36 kB
// Blomp integration — OpenStack Swift (Keystone v2). // // Blomp is an object-storage provider with a documented OpenStack Swift API. // Unlike S3, objects are private by default, so this server authenticates with // the account email/password, lists containers/objects, and proxies downloads // with the Swift `X-Auth-Token` header. // // Auth: POST https://authenticate.blomp.com/v2.0/tokens // Tenant: "storage" (the only tenant on Blomp) // API: OpenStack Swift object store // Docs: https://docs.openstack.org/api-ref/object-store/ // // Blomp containers are typically named after the account email. The configured // container is optional: when omitted we auto-detect the email-named container // (or the only container on the account). // // Note: Blomp has a ~5 GiB object limit for uploads via Swift — irrelevant // here: the only writes this server performs are small thumbnail images // (found on the public web by video title) pushed by the auto thumbnail // uploader (src/lib/thumb-uploader.ts). Videos are never uploaded, // overwritten or deleted; large files may be stored as Static Large Objects, // which Swift serves transparently. import { createHash } from "node:crypto"; import { db } from "./db"; import type { CustomThumbImage } from "./custom-thumbs"; import type { SourceFile } from "./types"; const DEFAULT_AUTH_URL = "https://authenticate.blomp.com"; /** * Default object-name prefix for Blomp. The scanner starts here, then (when no * root is configured) auto-detects every other folder that actually contains * videos, so users normally never have to set a root at all. Users can still * point it anywhere else (or at "/" for the whole container). */ export const DEFAULT_BLOMP_ROOT = "/deovr"; const TENANT_NAME = "storage"; const MAX_FILES = 5000; /** Hard cap on raw objects read from one container listing (videos + images). */ const MAX_OBJECTS = 20000; const PAGE_SIZE = 1000; // Blomp deliberately refuses Swift account-level container listings with 403. // The account's container is deterministic (the login email), so callers must // fall back to that instead of treating the 403 as a connection failure. const ACCOUNT_LISTING_HINT = "Blomp blocks account-level container listing; using the configured or email-named container."; class BlompHttpError extends Error { readonly status: number; constructor(message: string, status: number) { super(message); this.name = "BlompHttpError"; this.status = status; } } /** True for the expected 403 on `GET <storageUrl>?format=json`. */ function isAccountListingForbidden(err: unknown): err is BlompHttpError { return err instanceof BlompHttpError && err.status === 403; } const BLOMP_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"; /** Settings that must never be returned to the browser in clear text. */ export const BLOMP_SECRET_KEYS = ["blomp_password"] as const; export interface BlompConfig { email: string | null; password: string | null; /** Optional container override. Empty = auto-detect. */ container: string | null; /** Object-name prefix to scan, displayed with a leading slash. */ root: string; /** True when no root was configured: scans auto-detect folders with videos. */ autoRoot: boolean; authUrl: string; configured: boolean; } export interface BlompConnectionResult { connected: boolean; configured: boolean; email: string | null; container: string | null; root: string; /** True when no root is configured and scans auto-detect video folders. */ autoRoot: boolean; containers?: string[]; error?: string; } export interface BlompScanResult { files: SourceFile[]; /** Image objects found anywhere in the container (custom thumbnails). */ images: CustomThumbImage[]; /** Every folder that exists in the container, display form ("/gta"). */ folders: string[]; container: string | null; /** Display form of the scanned root(s), e.g. "/deovr" or "/deovr, /Movies". */ root: string; /** Every folder the scan actually read, in display form. Empty in auto mode = none found. */ roots: string[]; error?: string; } export interface BlompAuthState { token: string; storageUrl: string; expiresAt: number; } export interface BlompContainer { name: string; count: number; bytes: number; } interface BlompObject { name: string; bytes: number; lastModified: string | null; contentType: string | null; } // --------------------------------------------------------------------------- // Settings helpers // --------------------------------------------------------------------------- async function readBlompSettings(): Promise<Record<string, string>> { try { const rows = await db.setting.findMany(); const out: Record<string, string> = {}; for (const row of rows) { if (row.key.startsWith("blomp_")) out[row.key] = row.value; } return out; } catch { // DB may not be initialized yet. return {}; } } function envOr(value: string | undefined, fallback: string | null | undefined): string | null { const v = value?.trim() || fallback?.trim() || ""; return v || null; } /** Display form: always starts with "/", no trailing slash except root. */ function normalizeRoot(root: string | null | undefined): string { let out = (root ?? "").trim(); if (!out || out === "/") return "/"; out = out.replace(/^\/+/, "").replace(/\/+$/, ""); return out ? `/${out}` : "/"; } /** Swift prefix form: no leading/trailing slash. */ function rootPrefix(root: string): string { return root.replace(/^\/+/, "").replace(/\/+$/, ""); } function normalizeContainer(container: string | null | undefined): string | null { const out = (container ?? "").trim().replace(/^\/+|\/+$/g, ""); return out || null; } export async function getBlompConfig(): Promise<BlompConfig> { const settings = await readBlompSettings(); const env = process.env; const email = envOr(env.BLOMP_EMAIL, settings.blomp_email); const password = envOr(env.BLOMP_PASSWORD, settings.blomp_password); const container = normalizeContainer(envOr(env.BLOMP_CONTAINER, settings.blomp_container)); // No configured root = auto-detect: start at the /deovr default, then scan // every folder that actually holds videos. An explicit "/" still means the // whole container, so keep the raw value to distinguish the two cases. const explicitRoot = envOr(env.BLOMP_ROOT, settings.blomp_root); const root = normalizeRoot(explicitRoot ?? DEFAULT_BLOMP_ROOT); const authUrl = envOr(env.BLOMP_AUTH_URL, null) ?? DEFAULT_AUTH_URL; return { email, password, container, root, autoRoot: !explicitRoot, authUrl: authUrl.replace(/\/+$/, ""), configured: !!(email && password), }; } /** True when an account email + password are available. */ export async function isBlompConfigured(): Promise<boolean> { const cfg = await getBlompConfig(); return cfg.configured; } // --------------------------------------------------------------------------- // Authentication (Keystone v2) // --------------------------------------------------------------------------- let authCache: (BlompAuthState & { key: string }) | null = null; function credentialsKey(cfg: BlompConfig): string { return createHash("sha256") .update(`${cfg.email ?? ""}\u0000${cfg.password ?? ""}\u0000${cfg.authUrl}`) .digest("hex"); } function tokenEndpoint(authUrl: string): string { const base = authUrl.replace(/\/+$/, ""); if (base.endsWith("/tokens")) return base; if (base.endsWith("/v2.0")) return `${base}/tokens`; return `${base}/v2.0/tokens`; } function authErrorMessage(data: unknown, status: number): string { const obj = data as Record<string, any> | null; const message = obj?.unauthorized?.message || obj?.error?.message || obj?.error_description || obj?.message || obj?.error; return typeof message === "string" && message ? message : `Blomp authentication failed (HTTP ${status})`; } function pickStorageUrl(catalog: any[], authUrl: string): string { const objectStore = catalog?.find((entry) => entry?.type === "object-store"); const endpoints: any[] = Array.isArray(objectStore?.endpoints) ? objectStore.endpoints : []; const endpoint = endpoints.find((entry) => entry?.interface === "public") ?? endpoints.find((entry) => entry?.publicURL || entry?.url) ?? endpoints[0]; const storageUrl = endpoint?.publicURL || endpoint?.url; if (typeof storageUrl !== "string" || !storageUrl) { throw new Error(`Blomp returned no object-store endpoint from ${authUrl}`); } return storageUrl.replace(/\/+$/, ""); } async function authenticate(cfg: BlompConfig, force = false): Promise<BlompAuthState> { if (!cfg.email || !cfg.password) { throw new Error("Blomp is not configured — enter your account email and password."); } const key = credentialsKey(cfg); const now = Date.now(); if ( !force && authCache && authCache.key === key && authCache.expiresAt - now > 5 * 60 * 1000 ) { return authCache; } const endpoint = tokenEndpoint(cfg.authUrl); const body = JSON.stringify({ auth: { tenantName: TENANT_NAME, passwordCredentials: { username: cfg.email, password: cfg.password, }, }, }); let res: Response; try { res = await fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": BLOMP_UA, }, body, signal: AbortSignal.timeout(20000), }); } catch (err) { throw new Error( `Blomp authentication request failed: ${err instanceof Error ? err.message : "network error"}` ); } const text = await res.text(); let data: any = null; try { data = text ? JSON.parse(text) : null; } catch { // Keystone errors are normally JSON, but a proxy may return HTML. } if (!res.ok) { throw new Error(authErrorMessage(data, res.status)); } const token = data?.access?.token?.id; if (!token) { throw new Error("Blomp did not return an auth token. Check your email and password."); } const expiresRaw = data?.access?.token?.expires; const parsedExpires = expiresRaw ? Date.parse(String(expiresRaw)) : NaN; const expiresAt = Number.isFinite(parsedExpires) && parsedExpires > now ? parsedExpires : now + 60 * 60 * 1000; const storageUrl = pickStorageUrl(data?.access?.serviceCatalog, endpoint); authCache = { token: String(token), storageUrl, expiresAt, key }; return authCache; } /** Current auth token + storage URL. Used by the stream proxy headers. */ export async function getBlompAuth(): Promise<BlompAuthState> { const cfg = await getBlompConfig(); return authenticate(cfg); } /** Drop cached auth/status after settings change or 401. */ export function clearBlompCache(): void { authCache = null; statusCache = null; } // --------------------------------------------------------------------------- // Swift request helpers // --------------------------------------------------------------------------- function objectPath(container: string, objectName: string): string { const safeContainer = encodeURIComponent(container); const safeObject = objectName .split("/") .map((segment) => encodeURIComponent(segment)) .join("/"); return `${safeContainer}/${safeObject}`; } /** Canonical, token-free URL for a Swift object. */ export function blompObjectUrl(storageUrl: string, container: string, objectName: string): string { return `${storageUrl.replace(/\/+$/, "")}/${objectPath(container, objectName)}`; } async function swiftFetch( url: string, init: RequestInit = {}, retryOn401 = true ): Promise<Response> { const auth = await getBlompAuth(); const headers = new Headers(init.headers); headers.set("X-Auth-Token", auth.token); headers.set("User-Agent", BLOMP_UA); headers.set("Accept", "application/json, text/plain, */*"); const res = await fetch(url, { ...init, headers, signal: init.signal ?? AbortSignal.timeout(25000) }); if (res.status === 401 && retryOn401) { try { await res.body?.cancel(); } catch { // Ignore. } clearBlompCache(); return swiftFetch(url, init, false); } return res; } async function readJson(res: Response): Promise<any> { const text = await res.text(); if (!text) return null; try { return JSON.parse(text); } catch { throw new Error("Blomp returned a non-JSON response"); } } /** List all containers on the account. */ export async function listBlompContainers(): Promise<BlompContainer[]> { const auth = await getBlompAuth(); const url = `${auth.storageUrl}?format=json`; const res = await swiftFetch(url); if (!res.ok) { const body = await res.text().catch(() => ""); throw new BlompHttpError( `Blomp container list failed (HTTP ${res.status})${body ? `: ${body.slice(0, 160)}` : ""}`, res.status ); } const data = await readJson(res); if (!Array.isArray(data)) { throw new Error("Blomp returned an unexpected container list"); } return data.map((entry: any) => ({ name: String(entry?.name ?? ""), count: Number(entry?.count ?? 0) || 0, bytes: Number(entry?.bytes ?? 0) || 0, })).filter((entry) => entry.name); } /** * Resolve the container to scan. * * Blomp returns 403 for Swift account-level container listings, so we must not * depend on that call. The account container is the login email; an explicit * container setting always wins. When a listing happens to be available we use * it to recover the exact casing/name, otherwise `verifyBlompContainer` below * confirms the chosen container directly. */ export async function resolveBlompContainer( cfg?: BlompConfig, containers?: BlompContainer[] ): Promise<string> { const config = cfg ?? (await getBlompConfig()); if (!config.configured) throw new Error("Blomp is not configured."); if (config.container) return config.container; if (containers?.length) { const emailMatch = config.email ? containers.find((entry) => entry.name.toLowerCase() === config.email!.toLowerCase()) : undefined; if (emailMatch) return emailMatch.name; if (containers.length === 1) return containers[0].name; const available = containers.map((entry) => entry.name).join(", "); throw new Error(`Multiple Blomp containers found — set one explicitly. Available: ${available}`); } if (config.email) return config.email; const list = containers ?? (await listBlompContainers()); if (list.length === 1) return list[0].name; if (list.length === 0) { throw new Error("No Blomp containers found. Upload some files to Blomp first."); } const available = list.map((entry) => entry.name).join(", "); throw new Error(`Multiple Blomp containers found — set one explicitly. Available: ${available}`); } /** * Confirm a container is reachable without using the forbidden account-level * listing. The account listing is blocked, but listing one object inside the * container is exactly what the dashboard and the scanner do. */ async function verifyBlompContainer(container: string): Promise<void> { const auth = await getBlompAuth(); const url = new URL(`${auth.storageUrl.replace(/\/+$/, "")}/${encodeURIComponent(container)}`); url.searchParams.set("format", "json"); url.searchParams.set("limit", "1"); const res = await swiftFetch(url.toString()); if (res.status === 404) { throw new Error( `Blomp container "${container}" was not found. Use the email address of your Blomp account, or set the container explicitly.` ); } if (!res.ok) { const body = await res.text().catch(() => ""); throw new BlompHttpError( `Blomp container check failed (HTTP ${res.status})${body ? `: ${body.slice(0, 160)}` : ""}`, res.status ); } // A 204/empty response is valid for an empty container. A 200 must be a // Swift JSON listing. const data = await readJson(res); if (data !== null && !Array.isArray(data)) { throw new Error("Blomp returned an unexpected container listing"); } } async function listObjectPage( container: string, prefix: string, marker: string | null ): Promise<{ objects: BlompObject[]; /** Pseudo-directory entries ("folder exists" proofs), raw Swift form. */ subdirs: string[]; rawCount: number; lastRawName: string | null; }> { const auth = await getBlompAuth(); // Container listing endpoint (no trailing slash — a trailing slash would be // parsed as an empty object name by some Swift deployments). const url = new URL(`${auth.storageUrl.replace(/\/+$/, "")}/${encodeURIComponent(container)}`); url.searchParams.set("format", "json"); url.searchParams.set("limit", String(PAGE_SIZE)); if (prefix) url.searchParams.set("prefix", prefix); if (marker) url.searchParams.set("marker", marker); const res = await swiftFetch(url.toString()); if (res.status === 404) { throw new Error(`Blomp container "${container}" was not found`); } if (!res.ok) { const body = await res.text().catch(() => ""); throw new Error(`Blomp object list failed (HTTP ${res.status})${body ? `: ${body.slice(0, 160)}` : ""}`); } const data = await readJson(res); if (!Array.isArray(data)) { throw new Error("Blomp returned an unexpected object list"); } const objects: BlompObject[] = []; // Pseudo-directory entries (Swift `subdir` items) prove a folder exists on // the drive — even while empty — so the auto thumbnail uploader can target // it without ever creating anything. const subdirs: string[] = []; // Swift pagination markers must be the LAST name in the raw listing, which // includes those pseudo-directory entries that we skip for scanning. let lastRawName: string | null = null; for (const entry of data as any[]) { const name = String(entry?.name ?? entry?.subdir ?? ""); if (name) lastRawName = name; if (entry?.subdir) { subdirs.push(String(entry.subdir)); continue; } if (!name || name.endsWith("/")) continue; objects.push({ name, bytes: Number(entry?.bytes ?? 0) || 0, lastModified: entry?.last_modified ? String(entry.last_modified) : null, contentType: entry?.content_type ? String(entry.content_type) : null, }); } return { objects, subdirs, rawCount: data.length, lastRawName }; } /** * List every object under a prefix, plus every folder that exists there: * all ancestor folders of real objects and Swift pseudo-directory entries * (folders that exist even while empty). Display form, e.g. "/gta". */ async function listAllObjects( container: string, prefix: string ): Promise<{ objects: BlompObject[]; folders: string[] }> { const out: BlompObject[] = []; const folders = new Set<string>(); const seen = new Set<string>(); let marker: string | null = null; /** Remember a folder and every ancestor of it ("/a/b" also remembers "/a"). */ const rememberFolder = (displayPath: string): void => { const segments = displayPath.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean); for (let i = 1; i <= segments.length; i++) { folders.add(`/${segments.slice(0, i).join("/")}`); } }; for (let page = 0; page < 100; page++) { const { objects, subdirs, rawCount, lastRawName } = await listObjectPage(container, prefix, marker); for (const object of objects) { rememberFolder(dirName(object.name)); if (seen.has(object.name)) continue; seen.add(object.name); out.push(object); if (out.length >= MAX_OBJECTS) break; } for (const subdir of subdirs) rememberFolder(subdir); if (out.length >= MAX_OBJECTS) break; if (rawCount < PAGE_SIZE) break; // Advance using the raw listing entry (may be a pseudo-directory). if (!lastRawName || lastRawName === marker) break; marker = lastRawName; } return { objects: out, folders: [...folders].sort() }; } // --------------------------------------------------------------------------- // Scanning // --------------------------------------------------------------------------- function isVideoName(name: string): boolean { return /\.(mp4|mkv|webm|mov|m4v|avi|ts|m2ts|mts|wmv|flv|mpg|mpeg|3gp)$/i.test(name); } /** Image objects usable as user-supplied custom thumbnails. */ function isImageName(name: string): boolean { return /\.(jpe?g|png|webp|gif|bmp|avif)$/i.test(name); } function baseName(objectName: string): string { const parts = objectName.split("/"); return parts[parts.length - 1] || objectName; } function dirName(objectName: string): string { const idx = objectName.lastIndexOf("/"); if (idx <= 0) return "/"; return `/${objectName.slice(0, idx)}`; } function formatSize(bytes: number): string { if (!Number.isFinite(bytes) || bytes <= 0) return "—"; const units = ["B", "KB", "MB", "GB", "TB"]; let i = 0; let size = bytes; while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; } return `${size.toFixed(1)} ${units[i]}`; } function parseObjectPath(sourceId: string | null | undefined): { container: string; object: string } | null { const value = (sourceId ?? "").trim(); if (!value) return null; const idx = value.indexOf("/"); if (idx <= 0 || idx >= value.length - 1) return null; return { container: value.slice(0, idx), object: value.slice(idx + 1) }; } /** * Top-level folder a folderPath belongs to: "/deovr/sub" -> "/deovr". * Auto-detection reports top-level roots so the DEOVR tab stays short. */ function topLevelRoot(folderPath: string | null | undefined): string { const seg = (folderPath ?? "").replace(/^\/+/, "").split("/")[0]; return seg ? `/${seg}` : "/"; } /** Dedupe detected roots, keeping the /deovr default first. */ function orderRoots(roots: string[]): string[] { const unique = [...new Set(roots.filter(Boolean))]; const preferred = DEFAULT_BLOMP_ROOT.toLowerCase(); return unique.sort((a, b) => { const ap = a.toLowerCase() === preferred ? 0 : 1; const bp = b.toLowerCase() === preferred ? 0 : 1; return ap - bp || a.localeCompare(b); }); } /** Display form for one or more detected roots. */ function formatRoots(roots: string[]): string { if (roots.length === 0) return DEFAULT_BLOMP_ROOT; if (roots.length <= 3) return roots.join(", "); return `${roots.slice(0, 3).join(", ")} +${roots.length - 3} more`; } /** * Walk a Blomp container and return video objects, thumbnail images and the * folders that exist on the drive. * * With an explicit root, only that prefix is read for videos. With no * configured root the whole container is read once and the folders that * actually contain videos are reported as the roots - so /deovr is the * starting default, but a library kept in /VR, /Movies or anywhere else is * still discovered automatically. * * Images (custom thumbnails) are ALWAYS collected from the whole container, * regardless of the configured root, so a thumbnail uploaded anywhere in the * drive still matches its video by name. Folder paths are collected the same * way — they are the destinations the auto thumbnail uploader may use, and it * must never create a folder that is not in this list. */ export async function scanBlompLibrary(): Promise<BlompScanResult> { const cfg = await getBlompConfig(); if (!cfg.configured) { return { files: [], images: [], folders: [], container: cfg.container, root: cfg.root, roots: [], error: "Blomp is not configured.", }; } try { const auth = await getBlompAuth(); // Do not list account containers here: Blomp always answers that call // with 403. The container is the login email unless explicitly configured. const container = await resolveBlompContainer(cfg); // Videos honour the configured root, but images must be discoverable from // any folder, so the listing always covers the whole container and the // root filter is applied afterwards. const videoPrefix = cfg.autoRoot ? "" : rootPrefix(cfg.root); const { objects, folders: rawFolders } = await listAllObjects(container, ""); const files: SourceFile[] = []; // videos const images: CustomThumbImage[] = []; // custom thumbnails, any folder const seen = new Set<string>(); for (const object of objects) { if (object.name.startsWith(".file-segments/") || object.name.includes("/.file-segments/")) continue; const key = `${container}/${object.name}`; if (seen.has(key)) continue; // Custom thumbnails: images live anywhere in the drive. if (isImageName(object.name)) { if (images.length >= MAX_FILES) continue; seen.add(key); images.push({ container, objectName: object.name, baseName: baseName(object.name), folderPath: dirName(object.name), bytes: object.bytes, lastModified: object.lastModified, contentType: object.contentType, }); continue; } // Videos: respect the configured root (auto mode = whole container). if (!isVideoName(object.name)) continue; if (videoPrefix && object.name !== videoPrefix && !object.name.startsWith(`${videoPrefix}/`)) continue; seen.add(key); files.push({ source: "blomp", sourceId: key, sourcePath: key, name: baseName(object.name), folderPath: dirName(object.name), streamUrl: blompObjectUrl(auth.storageUrl, container, object.name), size: formatSize(object.bytes), addedAt: object.lastModified && Number.isFinite(Date.parse(object.lastModified)) ? new Date(object.lastModified) : undefined, }); if (files.length >= MAX_FILES) break; } const roots = cfg.autoRoot ? orderRoots(files.map((file) => topLevelRoot(file.folderPath))) : [cfg.root]; // Folders the auto thumbnail uploader may target: every folder that // exists on the drive (from real objects + pseudo-dirs), minus // hidden/system ones. const folders = rawFolders.filter( (path) => !path.split("/").some((seg) => seg && seg.startsWith(".")) ); return { files, images, folders, container, root: formatRoots(roots), roots }; } catch (err) { return { files: [], images: [], folders: [], container: cfg.container, root: cfg.root, roots: [], error: err instanceof Error ? err.message : "Unknown Blomp scan error", }; } } /** * Refresh a playable Blomp object URL. Blomp object URLs are stable; the auth * token is sent separately by the stream proxy. This still authenticates first * so a stale/expired account is reported early. * * `sourceId` / `sourcePath` are stored as `<container>/<objectName>`. */ export async function refreshBlompStreamUrl(file: { sourceId?: string | null; sourcePath?: string | null; }): Promise<string | null> { try { const cfg = await getBlompConfig(); if (!cfg.configured) return null; const parsed = parseObjectPath(file.sourcePath) ?? parseObjectPath(file.sourceId); if (!parsed) return null; const auth = await getBlompAuth(); return blompObjectUrl(auth.storageUrl, parsed.container, parsed.object); } catch (err) { console.warn("[blomp] failed to refresh object URL:", err); return null; } } /** Auth headers for the streaming proxy. */ export async function blompUpstreamHeaders(): Promise<Record<string, string>> { const auth = await getBlompAuth(); return { "X-Auth-Token": auth.token, "User-Agent": BLOMP_UA, Accept: "*/*", }; } // --------------------------------------------------------------------------- // Uploads — generated poster thumbnails only // --------------------------------------------------------------------------- /** Result of a Swift object PUT. */ export interface BlompPutResult { ok: boolean; status: number; /** True when the object already existed (HTTP 412 from If-None-Match). */ exists: boolean; error?: string; } /** * Upload a small object into the configured container. * * Used exclusively by the auto thumbnail uploader to push a thumbnail image * found on the web; nothing else in this server writes to Blomp. * `If-None-Match: *` makes * the PUT fail with 412 instead of overwriting an object that already exists * (e.g. a poster the user uploaded manually between listings) — a 412 is * reported as `{ ok: false, exists: true }`, never as an error. */ export async function putBlompObject(opts: { /** Object name inside the container, e.g. "gta/Trip to Mars.jpg". */ objectName: string; bytes: Buffer; contentType: string; /** Send If-None-Match: * (default). Disable only for the 400-fallback retry. */ ifNoneMatch?: boolean; }): Promise<BlompPutResult> { const attemptPut = async (withGuard: boolean): Promise<Response> => { const cfg = await getBlompConfig(); if (!cfg.configured) throw new Error("Blomp is not configured."); const container = await resolveBlompContainer(cfg); const auth = await getBlompAuth(); const url = `${auth.storageUrl.replace(/\/+$/, "")}/${objectPath(container, opts.objectName)}`; const headers: Record<string, string> = { "Content-Type": opts.contentType }; if (withGuard) headers["If-None-Match"] = "*"; return swiftFetch(url, { method: "PUT", headers, body: new Uint8Array(opts.bytes), }); }; try { let res = await attemptPut(opts.ifNoneMatch !== false); // Some Swift builds reject the conditional header outright; retry once // without it (the uploader's HEAD pre-check already made an overwrite // very unlikely). if (res.status === 400 && opts.ifNoneMatch !== false) { try { await res.body?.cancel(); } catch { // Ignore. } res = await attemptPut(false); } if (res.status === 201 || res.status === 200) { return { ok: true, status: res.status, exists: false }; } if (res.status === 412) { return { ok: false, status: 412, exists: true }; } const body = await res.text().catch(() => ""); return { ok: false, status: res.status, exists: false, error: `Blomp upload failed (HTTP ${res.status})${body ? `: ${body.slice(0, 160)}` : ""}`, }; } catch (err) { return { ok: false, status: 0, exists: false, error: err instanceof Error ? err.message : "Blomp upload failed", }; } } /** * Does an object already exist in the configured container? * Returns null when the answer is unknown (auth or network problem) — callers * then proceed to the guarded PUT, which cannot overwrite either. */ export async function blompObjectExists(objectName: string): Promise<boolean | null> { try { const cfg = await getBlompConfig(); if (!cfg.configured) return null; const container = await resolveBlompContainer(cfg); const auth = await getBlompAuth(); const url = `${auth.storageUrl.replace(/\/+$/, "")}/${objectPath(container, objectName)}`; const res = await swiftFetch(url, { method: "HEAD" }); if (res.status === 200) return true; if (res.status === 404) return false; return null; } catch { return null; } } // --------------------------------------------------------------------------- // Connection status // --------------------------------------------------------------------------- let statusCache: { at: number; result: BlompConnectionResult } | null = null; export async function testBlompConnection(opts: { force?: boolean } = {}): Promise<BlompConnectionResult> { if (!opts.force && statusCache && Date.now() - statusCache.at < 30_000) { return statusCache.result; } const cfg = await getBlompConfig(); const base: Omit<BlompConnectionResult, "connected"> = { configured: cfg.configured, email: cfg.email, container: cfg.container, root: cfg.root, autoRoot: cfg.autoRoot, }; let result: BlompConnectionResult; if (!cfg.configured) { result = { ...base, connected: false }; } else { try { // Blomp's account-level container listing is intentionally 403, so // resolve the deterministic container and probe it directly instead. const container = await resolveBlompContainer(cfg); await verifyBlompContainer(container); result = { ...base, connected: true, container, containers: [container], }; } catch (err) { result = { ...base, connected: false, error: err instanceof Error ? err.message : "Unknown Blomp error", }; } } statusCache = { at: Date.now(), result }; return result; } // --------------------------------------------------------------------------- // Diagnostics / disconnect // --------------------------------------------------------------------------- export async function debugBlomp(): Promise<Record<string, unknown>> { const cfg = await getBlompConfig(); const redacted = { email: cfg.email, configured: cfg.configured, hasPassword: !!cfg.password, container: cfg.container, root: cfg.root, autoRoot: cfg.autoRoot, authUrl: cfg.authUrl, }; let containers: string[] | undefined; let entries: { name: string; bytes: number; contentType: string | null }[] | undefined; const notes: string[] = []; let error: string | undefined; try { let list: BlompContainer[] | undefined; try { list = await listBlompContainers(); containers = list.map((entry) => entry.name); } catch (err) { if (!isAccountListingForbidden(err)) throw err; notes.push(ACCOUNT_LISTING_HINT); } const container = await resolveBlompContainer(cfg, list); await verifyBlompContainer(container); if (!containers) containers = [container]; if (cfg.autoRoot) { notes.push( `No root configured: starting at ${DEFAULT_BLOMP_ROOT} and auto-detecting every folder that contains videos.` ); } const { objects } = await listAllObjects(container, cfg.autoRoot ? "" : rootPrefix(cfg.root)); entries = objects.slice(0, 25).map((object) => ({ name: object.name, bytes: object.bytes, contentType: object.contentType, })); } catch (err) { error = err instanceof Error ? err.message : "Unknown Blomp error"; } return { config: redacted, containers, entries, notes, error, timestamp: new Date().toISOString(), }; } /** Remove the saved Blomp password but keep email/container/root preferences. */ export async function disconnectBlomp(): Promise<void> { await db.setting.deleteMany({ where: { key: { in: ["blomp_password"] } } }); clearBlompCache(); }
// Blomp integration — OpenStack Swift (Keystone v2).
//
// Blomp is an object-storage provider with a documented OpenStack Swift API.
// Unlike S3, objects are private by default, so this server authenticates with
// the account email/password, lists containers/objects, and proxies downloads
// with the Swift `X-Auth-Token` header.
//
// Auth: POST https://authenticate.blomp.com/v2.0/tokens
// Tenant: "storage" (the only tenant on Blomp)
// API: OpenStack Swift object store
// Docs: https://docs.openstack.org/api-ref/object-store/
//
// Blomp containers are typically named after the account email. The configured
// container is optional: when omitted we auto-detect the email-named container
// (or the only container on the account).
//
// Note: Blomp has a ~5 GiB object limit for uploads via Swift — irrelevant
// here: the only writes this server performs are small thumbnail images
// (found on the public web by video title) pushed by the auto thumbnail
// uploader (src/lib/thumb-uploader.ts). Videos are never uploaded,
// overwritten or deleted; large files may be stored as Static Large Objects,
// which Swift serves transparently.
import { createHash } from "node:crypto";
import { db } from "./db";
import type { CustomThumbImage } from "./custom-thumbs";
import type { SourceFile } from "./types";
const DEFAULT_AUTH_URL = "https://authenticate.blomp.com";
/**
* Default object-name prefix for Blomp. The scanner starts here, then (when no
* root is configured) auto-detects every other folder that actually contains
* videos, so users normally never have to set a root at all. Users can still
* point it anywhere else (or at "/" for the whole container).
*/
export const DEFAULT_BLOMP_ROOT = "/deovr";
const TENANT_NAME = "storage";
const MAX_FILES = 5000;
/** Hard cap on raw objects read from one container listing (videos + images). */
const MAX_OBJECTS = 20000;
const PAGE_SIZE = 1000;
// Blomp deliberately refuses Swift account-level container listings with 403.
// The account's container is deterministic (the login email), so callers must
// fall back to that instead of treating the 403 as a connection failure.
const ACCOUNT_LISTING_HINT =
"Blomp blocks account-level container listing; using the configured or email-named container.";
class BlompHttpError extends Error {
readonly status: number;
constructor(message: string, status: number) {
super(message);
this.name = "BlompHttpError";
this.status = status;
}
}
/** True for the expected 403 on `GET <storageUrl>?format=json`. */
function isAccountListingForbidden(err: unknown): err is BlompHttpError {
return err instanceof BlompHttpError && err.status === 403;
}
const BLOMP_UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
/** Settings that must never be returned to the browser in clear text. */
export const BLOMP_SECRET_KEYS = ["blomp_password"] as const;
export interface BlompConfig {
email: string | null;
password: string | null;
/** Optional container override. Empty = auto-detect. */
container: string | null;
/** Object-name prefix to scan, displayed with a leading slash. */
root: string;
/** True when no root was configured: scans auto-detect folders with videos. */
autoRoot: boolean;
authUrl: string;
configured: boolean;
}
export interface BlompConnectionResult {
connected: boolean;
configured: boolean;
email: string | null;
container: string | null;
root: string;
/** True when no root is configured and scans auto-detect video folders. */
autoRoot: boolean;
containers?: string[];
error?: string;
}
export interface BlompScanResult {
files: SourceFile[];
/** Image objects found anywhere in the container (custom thumbnails). */
images: CustomThumbImage[];
/** Every folder that exists in the container, display form ("/gta"). */
folders: string[];
container: string | null;