// Source helpers — everything that treats Offcloud, TeraBox and Blomp uniformly. // // The database stores `source` ("offcloud" | "terabox" | "blomp"), plus a // provider id (`sourceId`) and optional provider path (`sourcePath`). Offcloud // rows keep `offcloudId` populated for backward compatibility. import { refreshStreamUrl as refreshOffcloudStreamUrl } from "./offcloud"; import { refreshTeraboxStreamUrl } from "./terabox"; import { refreshBlompStreamUrl } from "./blomp"; import { getPrimaryApiKey } from "./auth"; import type { VideoSource } from "./types"; export const SOURCE_LABELS: Record = { offcloud: "Offcloud", terabox: "TeraBox", blomp: "Blomp", }; export function normalizeSource(source: string | null | undefined): VideoSource { if (source === "terabox") return "terabox"; if (source === "blomp") return "blomp"; return "offcloud"; } export function sourceLabel(source: string | null | undefined): string { return SOURCE_LABELS[normalizeSource(source)]; } /** * Sources whose upstream requests need provider-specific auth headers that * ffprobe/ffmpeg cannot send. These are always fetched through our own * token-authenticated /api/stream proxy. */ export function usesInternalProxy(source: string | null | undefined): boolean { return normalizeSource(source) !== "offcloud"; } export interface RefreshableVideo { id: string; source?: string | null; sourceId?: string | null; sourcePath?: string | null; offcloudId?: string | null; name?: string | null; streamUrl?: string | null; } export function providerIdOf(video: { sourceId?: string | null; offcloudId?: string | null; }): string { return video.sourceId ?? video.offcloudId ?? ""; } /** * Fetch fresh, playable stream URLs for a video from its provider. * Offcloud returns one URL per file in the cached request; TeraBox returns a * single refreshed dlink; Blomp returns a stable signed-by-header object URL. */ export async function refreshVideoStreamUrls(video: RefreshableVideo): Promise { const source = normalizeSource(video.source); if (source === "terabox") { const fresh = await refreshTeraboxStreamUrl({ fsId: providerIdOf(video), path: video.sourcePath ?? null, }); return fresh ? [fresh] : []; } if (source === "blomp") { const fresh = await refreshBlompStreamUrl({ sourceId: providerIdOf(video), sourcePath: video.sourcePath ?? null, }); return fresh ? [fresh] : []; } const urls = await refreshOffcloudStreamUrl(providerIdOf(video)); return urls ?? []; } /** Pick the refreshed URL that belongs to this specific file. */ export function pickFreshUrl( urls: string[], video: { name?: string | null; source?: string | null } ): string | null { if (urls.length === 0) return null; if (normalizeSource(video.source) !== "offcloud") return urls[0]; const name = video.name ?? ""; const match = urls.find((url) => { const filename = url.split("/").pop() ?? ""; try { return decodeURIComponent(filename) === name || filename === name; } catch { return filename === name; } }); return match ?? urls[0]; } /** * The key handed to our own token-authenticated internal URLs (detection, * thumbnails). This MUST be one of the keys the middleware/route guard accepts. * Using APP_PASSWORD directly broke detection whenever the Space only defined * APP_API_KEY: the internal URL carried the fallback key and got a 401. */ export function appPassword(): string { return getPrimaryApiKey(); } /** Base URL the server can use to call its own API routes. */ export function internalBaseUrl(): string { const configured = process.env.INTERNAL_BASE_URL?.trim(); if (configured) return configured.replace(/\/+$/, ""); return `http://127.0.0.1:${process.env.PORT || 3000}`; } /** * Token-authenticated proxy URL for a video. Used for ffprobe/ffmpeg, which * cannot send TeraBox cookies or Blomp auth headers — they fetch through our * own stream proxy. */ export function internalStreamUrl( videoId: string, filename: string = "video.mp4" ): string { const safeName = (filename || "video.mp4").replace(/[/\\?#]/g, "_"); return `${internalBaseUrl()}/api/stream/${videoId}/${encodeURIComponent(safeName)}?token=${encodeURIComponent(appPassword())}`; } /** * Fetch an upstream media URL while preserving our headers across redirects. * The default fetch implementation strips Cookie/Authorization on * cross-origin redirects, which breaks TeraBox dlinks that bounce to a CDN. */ export async function fetchUpstream( url: string, init: RequestInit, maxRedirects = 5 ): Promise { let current = url; for (let i = 0; i <= maxRedirects; i++) { const res = await fetch(current, { ...init, redirect: "manual" }); if (res.status >= 300 && res.status < 400) { const location = res.headers.get("location"); if (!location) return res; try { await res.body?.cancel(); } catch { // Ignore. } current = new URL(location, current).toString(); continue; } return res; } throw new Error("Too many upstream redirects"); } /** * URL handed to ffprobe / ffmpeg for detection. * TeraBox and Blomp go through the authenticated local proxy because ffprobe * cannot send the required cookies/headers; Offcloud URLs are public/signed. */ export async function detectionStreamUrl(video: RefreshableVideo & { streamUrl?: string | null }): Promise { if (usesInternalProxy(video.source)) { return internalStreamUrl(video.id, video.name ?? "video.mp4"); } return video.streamUrl ?? ""; }