VR-MEDIA / src /app /api /stream /[...id] /route.ts
Zero124's picture
VR Media Server 2.0 — latest build (custom Blomp thumbnail auto-detection + full pipeline)
5c0175e
Raw History Blame Contribute Delete
7.71 kB
// GET /api/stream/[...id] — streaming proxy from Offcloud / TeraBox / Blomp to
// DeoVR.
//
// DeoVR needs filename tokens in the URL to auto-detect projection/stereo and
// the `_ALPHA` alpha-passthrough trigger. The URL format is:
// /api/stream/<videoId>/<filename_with_tokens>
// e.g. /api/stream/abc123/video_180_SBS_FISHEYE_8K_ALPHA.mp4
//
// This is a CATCH-ALL route ([...id]) so the second "filename" segment resolves
// correctly (a plain [id] route only matches ONE segment and 404s on the
// filename). We use the FIRST segment as the videoId and let DeoVR read the
// filename tokens from the rest of the path.
//
// Nothing is downloaded locally — the provider response body is streamed
// straight through, including HTTP Range requests for instant seeking.
//
// TeraBox requires a browser User-Agent, the ndus cookie and a terabox.com
// Referer. Blomp requires the Swift X-Auth-Token from Keystone. Those headers
// are attached here (and re-attached across redirects).
import { NextRequest } from "next/server";
import { db } from "@/lib/db";
import {
fetchUpstream,
normalizeSource,
pickFreshUrl,
refreshVideoStreamUrls,
} from "@/lib/sources";
import { teraboxUpstreamHeaders } from "@/lib/terabox";
import { blompUpstreamHeaders } from "@/lib/blomp";
import { requireApiAuth } from "@/lib/auth-server";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
function extractVideoId(id: string[] | string | undefined): string {
if (Array.isArray(id)) return id[0] ?? "";
if (typeof id === "string") return id.split("/")[0];
return "";
}
async function freshStreamUrl(video: {
id: string;
source: string;
sourceId: string | null;
sourcePath: string | null;
offcloudId: string;
name: string;
streamUrl: string;
}): Promise<string> {
let streamUrl = video.streamUrl;
try {
const freshUrls = await refreshVideoStreamUrls(video);
const fresh = pickFreshUrl(freshUrls, video);
if (fresh) {
streamUrl = fresh;
await db.video.update({ where: { id: video.id }, data: { streamUrl: fresh } }).catch(() => {});
}
} catch (err) {
console.warn(`[stream] URL refresh failed for ${video.id}:`, err);
}
return streamUrl;
}
async function upstreamHeadersFor(
source: string,
range: string | null
): Promise<Record<string, string>> {
const normalized = normalizeSource(source);
let headers: Record<string, string>;
if (normalized === "terabox") {
headers = await teraboxUpstreamHeaders();
} else if (normalized === "blomp") {
try {
headers = await blompUpstreamHeaders();
} catch (err) {
// Auth is reported as an upstream 401/403 → 502 below; don't 500 here.
console.warn("[stream] Blomp auth header refresh failed:", err);
headers = {
"User-Agent": "VRMediaServer/2.0 (DEOVR Proxy)",
Accept: "*/*",
};
}
} else {
headers = {
"User-Agent": "VRMediaServer/2.0 (DEOVR Proxy)",
Accept: "*/*",
};
}
if (range) headers.Range = range;
return headers;
}
export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ id: string[] }> }
) {
// Middleware forwards credentialed requests here so the key stored in the
// app (not just the Space Secret) is accepted too.
const denied = await requireApiAuth(req);
if (denied) return denied;
const { id } = await params;
const videoId = extractVideoId(id);
// 1. Look up the video.
const video = await db.video.findUnique({ where: { id: videoId } });
if (!video) {
return new Response("Video not found", {
status: 404,
headers: { "Content-Type": "text/plain" },
});
}
// 2. Refresh the provider URL (Offcloud/TeraBox URLs expire; Blomp URLs are
// stable but re-resolved so auth failures surface early).
const streamUrl = await freshStreamUrl(video);
if (!streamUrl) {
return new Response("No playable stream URL for this video", {
status: 502,
headers: { "Content-Type": "text/plain" },
});
}
// 3. Build upstream request headers (forward Range for seeking).
const upstreamHeaders = await upstreamHeadersFor(video.source, req.headers.get("range"));
// 4. Fetch from the provider, preserving headers across redirects.
let upstream: Response;
try {
upstream = await fetchUpstream(streamUrl, {
headers: upstreamHeaders,
redirect: "manual",
});
} catch (err) {
console.error(`[stream] fetch failed for ${videoId}:`, err);
return new Response("Failed to fetch from the cloud provider", {
status: 502,
headers: { "Content-Type": "text/plain" },
});
}
// 5. Providers may return 200 (full file) or 206 (partial/range).
if (!upstream.ok && upstream.status !== 206) {
const status = upstream.status;
const text = await upstream.text().catch(() => "");
console.error(`[stream] upstream returned ${status} for ${videoId}: ${text.slice(0, 200)}`);
return new Response(`Upstream returned ${status}`, {
status: 502,
headers: { "Content-Type": "text/plain" },
});
}
// 6. Forward response headers.
const responseHeaders = new Headers();
const forward = [
"content-type",
"content-length",
"content-range",
"accept-ranges",
"last-modified",
"etag",
"cache-control",
];
for (const key of forward) {
const value = upstream.headers.get(key);
if (value) responseHeaders.set(key, value);
}
responseHeaders.set("Accept-Ranges", "bytes");
if (!responseHeaders.has("Content-Type")) {
responseHeaders.set("Content-Type", "video/mp4");
}
responseHeaders.set("Access-Control-Allow-Origin", "*");
responseHeaders.set("Access-Control-Allow-Headers", "Range");
responseHeaders.set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
// 7. Handle OPTIONS preflight.
if (req.method === "OPTIONS") {
return new Response(null, { status: 204, headers: responseHeaders });
}
// 8. Stream the body back to DEOVR (no local download).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = upstream.body as any;
return new Response(body, {
status: upstream.status,
statusText: upstream.statusText,
headers: responseHeaders,
});
}
// HEAD requests — DEOVR sometimes sends these to probe the video size.
export async function HEAD(
_req: NextRequest,
{ params }: { params: Promise<{ id: string[] }> }
) {
const { id } = await params;
const videoId = extractVideoId(id);
const video = await db.video.findUnique({ where: { id: videoId } });
if (!video) {
return new Response(null, { status: 404 });
}
const streamUrl = await freshStreamUrl(video);
if (!streamUrl) return new Response(null, { status: 502 });
try {
const upstream = await fetchUpstream(streamUrl, {
method: "HEAD",
headers: await upstreamHeadersFor(video.source, null),
redirect: "manual",
});
const responseHeaders = new Headers();
for (const key of ["content-type", "content-length", "accept-ranges"]) {
const value = upstream.headers.get(key);
if (value) responseHeaders.set(key, value);
}
responseHeaders.set("Accept-Ranges", "bytes");
if (!responseHeaders.has("Content-Type")) {
responseHeaders.set("Content-Type", "video/mp4");
}
return new Response(null, { status: upstream.ok ? 200 : 502, headers: responseHeaders });
} catch {
return new Response(null, { status: 502 });
}
}