File size: 14,806 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 | // 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,
},
];
}
|