Download src/lib/offcloud.ts from Zero124/VR-MEDIA: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/spaces/Zero124/VR-MEDIA/resolve/main/src/lib/offcloud.ts
- Command line
-
hf download hf://spaces/Zero124/VR-MEDIA/src/lib/offcloud.ts
-
curl -L -o offcloud.ts https://huggingface.co/spaces/Zero124/VR-MEDIA/resolve/main/src/lib/offcloud.ts
14.8 kB
| // Offcloud API client — real integration with mock fallback. | |
| // Design: metadata-first streaming gateway. We never persist video binaries, | |
| // only their stream URLs + metadata. | |
| // | |
| // API reference (verified against offcloud-api GitHub + production StremThru adapter): | |
| // - Auth: ?key=<API_KEY> on every request (or Authorization: Bearer <KEY>) | |
| // - Validate key: GET /api/account/info?key=<KEY> | |
| // - List instant downloads: GET /api/instant/history?key=<KEY> | |
| // - List cloud downloads: GET /api/cloud/history?key=<KEY> | |
| // - List files in a download: GET /api/cloud/explore/<requestId>?key=<KEY>&format=detailed | |
| // - Plain URL list: GET /api/cloud/list/<requestId>?key=<KEY> | |
| import { db } from "./db"; | |
| const OFFCLOUD_BASE = "https://offcloud.com/api"; | |
| export interface OffcloudFile { | |
| id: string; | |
| offcloudId: string; | |
| name: string; | |
| folderPath: string; | |
| streamUrl: string; | |
| size: string; | |
| duration?: number; | |
| addedAt?: Date; | |
| isMock?: boolean; | |
| } | |
| export interface OffcloudConnectionResult { | |
| connected: boolean; | |
| mode: "real" | "mock" | "disconnected"; | |
| accountId?: string; | |
| email?: string; | |
| plan?: string; | |
| cachedItems?: number; | |
| error?: string; | |
| } | |
| /** | |
| * Read the Offcloud API key. Checks HF Space Secret first (env var), then | |
| * the Settings table (set via the UI). | |
| */ | |
| export async function getApiKey(): Promise<string | null> { | |
| // HF Space Secret takes priority — it survives DB resets. | |
| if (process.env.OFFCLOUD_API_KEY && process.env.OFFCLOUD_API_KEY.trim()) { | |
| return process.env.OFFCLOUD_API_KEY.trim(); | |
| } | |
| // Fall back to the Settings table (set via /settings UI). | |
| try { | |
| const setting = await db.setting.findUnique({ where: { key: "offcloud_api_key" } }); | |
| if (setting?.value && setting.value !== "***set***") return setting.value; | |
| } catch { | |
| // DB might not be initialized yet — ignore. | |
| } | |
| return null; | |
| } | |
| /** | |
| * Test the Offcloud connection by calling /api/account/info. | |
| * This is the lightweight key-validation endpoint. | |
| */ | |
| export async function testConnection(): Promise<OffcloudConnectionResult> { | |
| const key = await getApiKey(); | |
| if (!key) { | |
| return { connected: false, mode: "disconnected" }; | |
| } | |
| try { | |
| const res = await fetch(`${OFFCLOUD_BASE}/account/info?key=${encodeURIComponent(key)}`, { | |
| method: "GET", | |
| headers: { | |
| "User-Agent": "VRMediaServer/2.0", | |
| "Accept": "application/json", | |
| }, | |
| signal: AbortSignal.timeout(10000), | |
| }); | |
| if (!res.ok) { | |
| const text = await res.text().catch(() => ""); | |
| return { | |
| connected: false, | |
| mode: "mock", | |
| error: `Offcloud returned HTTP ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`, | |
| }; | |
| } | |
| const data = await res.json(); | |
| // Offcloud returns {"error": "NOAUTH"} or {"error": "..."} on auth failure. | |
| if (data.error) { | |
| return { | |
| connected: false, | |
| mode: "mock", | |
| error: `Offcloud auth error: ${data.error}`, | |
| }; | |
| } | |
| // Successful response: { user_id, is_premium, expiration_date, can_download, ... } | |
| // Count cached items via /api/instant/history (best-effort, non-fatal). | |
| let cachedItems: number | undefined; | |
| try { | |
| const historyRes = await fetch( | |
| `${OFFCLOUD_BASE}/instant/history?key=${encodeURIComponent(key)}`, | |
| { signal: AbortSignal.timeout(10000) } | |
| ); | |
| if (historyRes.ok) { | |
| const historyData = await historyRes.json(); | |
| const items = Array.isArray(historyData) ? historyData : (historyData.requests ?? []); | |
| cachedItems = items.length; | |
| } | |
| } catch { | |
| // Non-fatal — connection test still passes. | |
| } | |
| return { | |
| connected: true, | |
| mode: "real", | |
| accountId: data.user_id ?? data.userId ?? "unknown", | |
| email: data.email ?? undefined, | |
| plan: data.is_premium ? "premium" : "free", | |
| cachedItems, | |
| }; | |
| } catch (err) { | |
| return { | |
| connected: false, | |
| mode: "mock", | |
| error: err instanceof Error ? err.message : "Unknown error reaching Offcloud", | |
| }; | |
| } | |
| } | |
| /** | |
| * Scan Offcloud for video files. Walks both instant downloads and cloud downloads, | |
| * enumerates files in each, and returns only video files. | |
| * | |
| * When `allowMock` is true (the default, for backwards compatibility) a no-key or | |
| * failed scan falls back to a realistic mock library so the UI is demoable. | |
| * The multi-source scan engine passes `allowMock: false` when another real | |
| * source (e.g. TeraBox or Blomp) is configured, so mock data never mixes with | |
| * real data. | |
| */ | |
| export async function scanLibrary( | |
| opts: { allowMock?: boolean } = {} | |
| ): Promise<{ files: OffcloudFile[]; mode: "real" | "mock" | "error" }> { | |
| const allowMock = opts.allowMock !== false; | |
| const key = await getApiKey(); | |
| if (!key) { | |
| return allowMock | |
| ? { files: getMockLibrary(), mode: "mock" } | |
| : { files: [], mode: "error" }; | |
| } | |
| try { | |
| const files = await scanRealLibrary(key); | |
| if (files.length > 0) { | |
| return { files, mode: "real" }; | |
| } | |
| // Real library is empty — return empty (NOT mock) so the UI shows | |
| // "No videos found" instead of fake sample data. | |
| return { files: [], mode: "real" }; | |
| } catch (err) { | |
| console.warn("[offcloud] real scan failed:", err); | |
| return allowMock | |
| ? { files: getMockLibrary(), mode: "mock" } | |
| : { files: [], mode: "error" }; | |
| } | |
| } | |
| /** | |
| * Real Offcloud scan: pull both instant-download and cloud-download histories, | |
| * then enumerate files in each cached item. | |
| */ | |
| async function scanRealLibrary(key: string): Promise<OffcloudFile[]> { | |
| const out: OffcloudFile[] = []; | |
| // ---- 1. Instant downloads (the "cached" items) ---- | |
| try { | |
| const res = await fetch(`${OFFCLOUD_BASE}/instant/history?key=${encodeURIComponent(key)}`, { | |
| signal: AbortSignal.timeout(15000), | |
| }); | |
| if (res.ok) { | |
| const data = await res.json(); | |
| const items: any[] = Array.isArray(data) ? data : (data.requests ?? []); | |
| for (const item of items) { | |
| const requestId = item.requestId ?? item.id; | |
| if (!requestId) continue; | |
| const files = await exploreCachedItem(key, requestId, item); | |
| out.push(...files); | |
| } | |
| } | |
| } catch (err) { | |
| console.warn("[offcloud] instant/history failed:", err); | |
| } | |
| // ---- 2. Cloud downloads (magnet/torrent to cloud) ---- | |
| try { | |
| const res = await fetch(`${OFFCLOUD_BASE}/cloud/history?key=${encodeURIComponent(key)}`, { | |
| signal: AbortSignal.timeout(15000), | |
| }); | |
| if (res.ok) { | |
| const data = await res.json(); | |
| const items: any[] = Array.isArray(data) ? data : (data.requests ?? []); | |
| for (const item of items) { | |
| // Only include items that finished downloading. | |
| const status = (item.status ?? "").toLowerCase(); | |
| if (status && status !== "downloaded" && status !== "complete") continue; | |
| const requestId = item.requestId ?? item.id; | |
| if (!requestId) continue; | |
| const files = await exploreCachedItem(key, requestId, item); | |
| out.push(...files); | |
| } | |
| } | |
| } catch (err) { | |
| console.warn("[offcloud] cloud/history failed:", err); | |
| } | |
| return out; | |
| } | |
| /** | |
| * Enumerate files in a single cached item via /api/cloud/explore/<requestId>. | |
| * Returns an array of OffcloudFile for each video file found. | |
| */ | |
| async function exploreCachedItem( | |
| key: string, | |
| requestId: string, | |
| historyItem: any | |
| ): Promise<OffcloudFile[]> { | |
| const out: OffcloudFile[] = []; | |
| try { | |
| const res = await fetch( | |
| `${OFFCLOUD_BASE}/cloud/explore/${requestId}?key=${encodeURIComponent(key)}&format=detailed`, | |
| { signal: AbortSignal.timeout(10000) } | |
| ); | |
| if (!res.ok) return out; | |
| const data = await res.json(); | |
| const files: any[] = Array.isArray(data) ? data : (data.files ?? []); | |
| // Derive a folder path from the original URL or filename. | |
| const originalUrl = historyItem.originalLink ?? historyItem.originalUrl ?? historyItem.url ?? ""; | |
| let folderPath = `/offcloud/${requestId}`; | |
| try { | |
| if (originalUrl) { | |
| const u = new URL(originalUrl); | |
| folderPath = `/offcloud${u.pathname}`; | |
| } | |
| } catch { | |
| // Not a URL — use as-is. | |
| if (originalUrl) folderPath = `/offcloud/${originalUrl}`; | |
| } | |
| const addedAt = historyItem.createdOn | |
| ? new Date(historyItem.createdOn) | |
| : historyItem.creationDate | |
| ? new Date(historyItem.creationDate * 1000) | |
| : new Date(); | |
| for (const file of files) { | |
| const url: string = file.url ?? file.downloadUrl ?? file.link ?? ""; | |
| const name: string = file.name ?? file.filename ?? file.path?.split("/").pop() ?? "unknown"; | |
| if (!url || !isVideoFilename(name) || !isVideoFilename(url)) continue; | |
| const size = formatSize(file.size); | |
| out.push({ | |
| id: `${requestId}:${encodeURIComponent(url)}`, | |
| offcloudId: requestId, | |
| name, | |
| folderPath, | |
| streamUrl: url, | |
| size, | |
| addedAt, | |
| }); | |
| } | |
| } catch (err) { | |
| console.warn(`[offcloud] explore ${requestId} failed:`, err); | |
| } | |
| return out; | |
| } | |
| /** | |
| * Get fresh stream URLs for a cached item. Offcloud URLs can expire, so callers | |
| * should refresh before handing them to DEOVR. | |
| */ | |
| export async function refreshStreamUrl(offcloudId: string): Promise<string[] | null> { | |
| const key = await getApiKey(); | |
| if (!key) return null; | |
| try { | |
| const res = await fetch( | |
| `${OFFCLOUD_BASE}/cloud/explore/${offcloudId}?key=${encodeURIComponent(key)}&format=detailed`, | |
| { signal: AbortSignal.timeout(10000) } | |
| ); | |
| if (!res.ok) return null; | |
| const data = await res.json(); | |
| const files: any[] = Array.isArray(data) ? data : (data.files ?? []); | |
| return files | |
| .map((f) => f.url ?? f.downloadUrl ?? f.link) | |
| .filter((u): u is string => typeof u === "string" && u.length > 0); | |
| } catch { | |
| return null; | |
| } | |
| } | |
| function isVideoFilename(nameOrUrl: string): boolean { | |
| return /\.(mp4|mkv|webm|mov|m4v|avi|ts|wmv|flv|mpg|mpeg)$/i.test(nameOrUrl); | |
| } | |
| function formatSize(bytes: unknown): string { | |
| if (typeof bytes !== "number" || 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]}`; | |
| } | |
| // ============================================================ | |
| // MOCK LIBRARY — realistic VR content for demo / dev mode. | |
| // ============================================================ | |
| function getMockLibrary(): OffcloudFile[] { | |
| const now = Date.now(); | |
| const day = 86400000; | |
| return [ | |
| { | |
| id: "mock-1", offcloudId: "oc-9001", | |
| name: "Beach_Sunset_AR_VR180_SBS_8K.mp4", | |
| folderPath: "/VR/Passthrough/Beach", | |
| streamUrl: "https://offcloud.com/mock/oc-9001/Beach_Sunset_AR_VR180_SBS_8K.mp4", | |
| size: "8.4 GB", duration: 1242, addedAt: new Date(now - day * 2), isMock: true, | |
| }, | |
| { | |
| id: "mock-2", offcloudId: "oc-9002", | |
| name: "Quest3_Passthrough_180VR_Living_Room.mp4", | |
| folderPath: "/VR/Passthrough/Indoor", | |
| streamUrl: "https://offcloud.com/mock/oc-9002/Quest3_Passthrough_180VR_Living_Room.mp4", | |
| size: "5.2 GB", duration: 856, addedAt: new Date(now - day * 5), isMock: true, | |
| }, | |
| { | |
| id: "mock-3", offcloudId: "oc-9003", | |
| name: "DualFisheye_Skydive_8K.mp4", | |
| folderPath: "/VR/Fisheye/Outdoor", | |
| streamUrl: "https://offcloud.com/mock/oc-9003/DualFisheye_Skydive_8K.mp4", | |
| size: "12.1 GB", duration: 2100, addedAt: new Date(now - day * 8), isMock: true, | |
| }, | |
| { | |
| id: "mock-4", offcloudId: "oc-9004", | |
| name: "VR180_SBS_7K_Concert_Live.mp4", | |
| folderPath: "/VR/VR180/Concert", | |
| streamUrl: "https://offcloud.com/mock/oc-9004/VR180_SBS_7K_Concert_Live.mp4", | |
| size: "9.7 GB", duration: 3600, addedAt: new Date(now - day * 1), isMock: true, | |
| }, | |
| { | |
| id: "mock-5", offcloudId: "oc-9005", | |
| name: "VR360_SBS_6K_Space_Walk.mp4", | |
| folderPath: "/VR/VR360/Space", | |
| streamUrl: "https://offcloud.com/mock/oc-9005/VR360_SBS_6K_Space_Walk.mp4", | |
| size: "11.3 GB", duration: 1850, addedAt: new Date(now - day * 12), isMock: true, | |
| }, | |
| { | |
| id: "mock-6", offcloudId: "oc-9006", | |
| name: "MixedReality_Kitchen_Cooking_Class.mp4", | |
| folderPath: "/VR/Passthrough/MR", | |
| streamUrl: "https://offcloud.com/mock/oc-9006/MixedReality_Kitchen_Cooking_Class.mp4", | |
| size: "6.8 GB", duration: 1500, addedAt: new Date(now - day * 3), isMock: true, | |
| }, | |
| { | |
| id: "mock-7", offcloudId: "oc-9007", | |
| name: "Fisheye180_Diving_5K.mp4", | |
| folderPath: "/VR/Fisheye/Underwater", | |
| streamUrl: "https://offcloud.com/mock/oc-9007/Fisheye180_Diving_5K.mp4", | |
| size: "7.2 GB", duration: 1980, addedAt: new Date(now - day * 6), isMock: true, | |
| }, | |
| { | |
| id: "mock-8", offcloudId: "oc-9008", | |
| name: "City_Tour_OU_4K.mp4", | |
| folderPath: "/VR/OU/City", | |
| streamUrl: "https://offcloud.com/mock/oc-9008/City_Tour_OU_4K.mp4", | |
| size: "3.5 GB", duration: 720, addedAt: new Date(now - day * 9), isMock: true, | |
| }, | |
| { | |
| id: "mock-9", offcloudId: "oc-9009", | |
| name: "Concert_Front_Row_VR180_SBS_8K.mp4", | |
| folderPath: "/VR/VR180/Concert", | |
| streamUrl: "https://offcloud.com/mock/oc-9009/Concert_Front_Row_VR180_SBS_8K.mp4", | |
| size: "10.2 GB", duration: 2700, addedAt: new Date(now - day * 4), isMock: true, | |
| }, | |
| { | |
| id: "mock-10", offcloudId: "oc-9010", | |
| name: "Nature_Walk_180VR_SBS_5K.mp4", | |
| folderPath: "/VR/VR180/Nature", | |
| streamUrl: "https://offcloud.com/mock/oc-9010/Nature_Walk_180VR_SBS_5K.mp4", | |
| size: "4.6 GB", duration: 960, addedAt: new Date(now - day * 7), isMock: true, | |
| }, | |
| { | |
| id: "mock-11", offcloudId: "oc-9011", | |
| name: "Yoga_Class_MR_Passthrough.mp4", | |
| folderPath: "/VR/Passthrough/Yoga", | |
| streamUrl: "https://offcloud.com/mock/oc-9011/Yoga_Class_MR_Passthrough.mp4", | |
| size: "5.9 GB", duration: 1800, addedAt: new Date(now - day * 11), isMock: true, | |
| }, | |
| { | |
| id: "mock-12", offcloudId: "oc-9012", | |
| name: "Mountain_Hike_VR360_SBS_8K.mp4", | |
| folderPath: "/VR/VR360/Outdoor", | |
| streamUrl: "https://offcloud.com/mock/oc-9012/Mountain_Hike_VR360_SBS_8K.mp4", | |
| size: "13.5 GB", duration: 2400, addedAt: new Date(now - day * 15), isMock: true, | |
| }, | |
| ]; | |
| } | |