File size: 7,709 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
// 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 });
  }
}