Download src/lib/vr-mode.ts from Zero124/VR-MEDIA: direct link, hf CLI and curl.
- Browser
- Download file 20.3 kB
-
https://huggingface.co/spaces/Zero124/VR-MEDIA/resolve/main/src/lib/vr-mode.ts
- Command line
-
hf download hf://spaces/Zero124/VR-MEDIA/src/lib/vr-mode.ts
-
curl -L -o vr-mode.ts https://huggingface.co/spaces/Zero124/VR-MEDIA/resolve/main/src/lib/vr-mode.ts
20.3 kB
| // VR mode -- the headset-facing face of this server. | |
| // | |
| // Modelled on how sites like SLR do it: one normal web dashboard for a desktop | |
| // browser, and a separate, much simpler page for the browsers built into DeoVR | |
| // and PLAY'A. Big thumbnails, huge tap targets, lazy-loaded images, and a small | |
| // picker asking which player should open the video. | |
| // | |
| // This module only *links* to endpoints that already exist: | |
| // /api/thumbnail/<id> thumbnails | |
| // /api/feeds/deovr/<id> single-video DeoVR JSON (deeplink target) | |
| // /api/stream/<id>/<tokens> the actual video | |
| // /api/playa/v2/* PLAY'A's native protocol | |
| // No DeoVR or PLAY'A streaming behaviour is changed by anything in here. | |
| import type { Video } from "@prisma/client"; | |
| import { db } from "@/lib/db"; | |
| import { readEnv } from "@/lib/env"; | |
| import { buildDeovrTokens, passthroughMethod } from "@/lib/deovr"; | |
| import { withThumbVersion } from "@/lib/custom-thumbs"; | |
| export type VrClient = "deovr" | "playa" | "browser"; | |
| /** | |
| * Both apps ship their own browser and both put their name in the user agent, | |
| * which is how a site can tell it is being viewed inside a headset app. | |
| */ | |
| export function detectVrClient(userAgent: string | null): VrClient { | |
| const ua = (userAgent || "").toLowerCase(); | |
| if (ua.includes("deovr")) return "deovr"; | |
| if (ua.includes("playa") || ua.includes("play'a")) return "playa"; | |
| return "browser"; | |
| } | |
| export function vrModePageSize(): number { | |
| const raw = Number(readEnv("VR_MODE_PAGE_SIZE") || 60); | |
| if (!Number.isFinite(raw)) return 60; | |
| return Math.min(300, Math.max(6, Math.round(raw))); | |
| } | |
| function esc(value: string): string { | |
| return value | |
| .replace(/&/g, "&") | |
| .replace(/</g, "<") | |
| .replace(/>/g, ">") | |
| .replace(/"/g, """) | |
| .replace(/'/g, "'"); | |
| } | |
| function formatDuration(seconds: number | null | undefined): string { | |
| const total = Math.max(0, Math.round(seconds || 0)); | |
| if (!total) return ""; | |
| const h = Math.floor(total / 3600); | |
| const m = Math.floor((total % 3600) / 60); | |
| const s = total % 60; | |
| const pad = (n: number) => String(n).padStart(2, "0"); | |
| return h ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`; | |
| } | |
| type Card = { | |
| id: string; | |
| title: string; | |
| duration: string; | |
| badges: string[]; | |
| tags: string[]; | |
| thumbnail: string; | |
| deovrJson: string; | |
| deovrDeeplink: string; | |
| stream: string; | |
| }; | |
| function projectionLabel(v: Video): { label: string; tag: string } { | |
| if (v.lensType === "fisheye" || v.lensType === "dual_fisheye") | |
| return { label: "Fisheye", tag: "fisheye" }; | |
| const projection = v.manualProjection || v.projection || "flat"; | |
| if (projection === "vr180") return { label: "VR180", tag: "vr180" }; | |
| if (projection === "vr360") return { label: "VR360", tag: "vr360" }; | |
| return { label: "Flat", tag: "flat" }; | |
| } | |
| function stereoLabel(v: Video): { label: string; tag: string } | null { | |
| const stereo = v.manualStereo || v.stereo || "mono"; | |
| if (stereo === "sbs") return { label: "SBS 3D", tag: "sbs" }; | |
| if (stereo === "ou" || stereo === "top_bottom" || stereo === "tb") | |
| return { label: "Over-under 3D", tag: "tb" }; | |
| return null; | |
| } | |
| function toCard(v: Video, baseUrl: string, token: string): Card { | |
| const q = token ? `?token=${encodeURIComponent(token)}` : ""; | |
| const method = passthroughMethod(v); | |
| const projection = v.manualProjection || v.projection || "flat"; | |
| const stereo = v.manualStereo || v.stereo || "mono"; | |
| const tokens = buildDeovrTokens(v, projection, stereo, method); | |
| const proj = projectionLabel(v); | |
| const stereoInfo = stereoLabel(v); | |
| const badges: string[] = [proj.label]; | |
| const tags: string[] = [proj.tag]; | |
| if (stereoInfo) { | |
| badges.push(stereoInfo.label); | |
| tags.push(stereoInfo.tag); | |
| } | |
| if (method !== "none") { | |
| badges.push(method === "alpha" ? "Passthrough (alpha)" : "Passthrough"); | |
| tags.push("passthrough"); | |
| } | |
| if (v.resolutionTier) { | |
| badges.push(v.resolutionTier.toUpperCase()); | |
| tags.push(v.resolutionTier.toLowerCase()); | |
| } | |
| const deovrJson = `${baseUrl}/api/feeds/deovr/${v.id}${q}`; | |
| return { | |
| id: v.id, | |
| title: v.name.replace(/\.[^.]+$/, ""), | |
| duration: formatDuration(v.duration), | |
| badges, | |
| tags, | |
| thumbnail: withThumbVersion(`${baseUrl}/api/thumbnail/${v.id}${q}`, v.customThumbHash), | |
| deovrJson, | |
| // Documented DeoVR deeplink form: deovr://<full https url of the json> | |
| deovrDeeplink: `deovr://${deovrJson}`, | |
| stream: `${baseUrl}/api/stream/${v.id}/${tokens}${q}`, | |
| }; | |
| } | |
| const STYLES = ` | |
| :root{color-scheme:dark} | |
| *{box-sizing:border-box} | |
| body{margin:0;background:#0F0F0F;color:#EEEEEE; | |
| font-family:Roboto,-apple-system,"Segoe UI",Arial,sans-serif; | |
| font-size:18px;line-height:1.45;-webkit-text-size-adjust:100%} | |
| a{color:#3EA6FF;text-decoration:none} | |
| header{position:sticky;top:0;z-index:5;background:#0D0D0D; | |
| border-bottom:1px solid #272727;padding:16px 20px} | |
| .brand{display:flex;align-items:center;gap:12px;flex-wrap:wrap} | |
| .brand h1{font-size:22px;font-weight:500;margin:0} | |
| .dot{width:10px;height:10px;border-radius:40px;background:#FF0033} | |
| .muted{color:#AAAAAA;font-size:15px} | |
| .tools{display:flex;gap:10px;margin-top:12px;flex-wrap:wrap;align-items:center} | |
| input[type=search]{flex:1;min-width:220px;background:#181818;border:1px solid #303030; | |
| color:#EEEEEE;border-radius:20px;padding:12px 18px;font-size:17px;outline:none} | |
| input[type=search]:focus{border-color:#065FD4} | |
| .chip{background:#212121;border:1px solid #303030;color:#EEEEEE;border-radius:20px; | |
| padding:10px 18px;font-size:15px;cursor:pointer} | |
| .chip.on{background:#EEEEEE;color:#0F0F0F;border-color:#EEEEEE} | |
| .switch{display:inline-flex;align-items:center;gap:10px;margin-left:auto; | |
| padding:12px 22px;border-radius:40px;background:#065FD4;color:#fff; | |
| font-size:16px;font-weight:600;text-decoration:none;white-space:nowrap; | |
| border:1px solid rgba(255,255,255,.18)} | |
| .switch:hover{background:#3EA6FF} | |
| .switch .sdot{width:10px;height:10px;border-radius:50%;background:#2BA640; | |
| box-shadow:0 0 0 4px rgba(43,166,64,.25)} | |
| main{padding:20px} | |
| .grid{display:grid;gap:20px;grid-template-columns:repeat(auto-fill,minmax(300px,1fr))} | |
| .card{background:#181818;border:1px solid #212121;border-radius:8px;overflow:hidden; | |
| cursor:pointer;text-align:left;padding:0;color:inherit;font:inherit;width:100%} | |
| .card:hover,.card:focus{border-color:#3EA6FF;outline:none} | |
| .thumb{position:relative;aspect-ratio:16/9;background:#0D0D0D} | |
| .thumb img{width:100%;height:100%;object-fit:cover;display:block} | |
| .time{position:absolute;right:8px;bottom:8px;background:rgba(0,0,0,.8); | |
| border-radius:4px;padding:2px 7px;font-size:14px} | |
| .meta{padding:12px 14px} | |
| .meta .name{font-size:17px;font-weight:500;margin:0 0 8px; | |
| display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden} | |
| .badges{display:flex;gap:6px;flex-wrap:wrap} | |
| .badge{background:#272727;color:#BBAADD;border-radius:4px;padding:2px 8px;font-size:13px} | |
| .badge.pt{color:#FF5577} | |
| .pager{display:flex;justify-content:center;gap:14px;padding:28px 0} | |
| .btn{display:inline-block;background:#065FD4;color:#fff;border:none;border-radius:20px; | |
| padding:14px 24px;font-size:17px;cursor:pointer;text-align:center} | |
| .btn:hover{background:#3EA6FF} | |
| .btn.ghost{background:#212121;color:#EEEEEE;border:1px solid #303030} | |
| .btn.block{display:block;width:100%;margin-bottom:10px} | |
| .overlay{position:fixed;inset:0;background:rgba(0,0,0,.82);display:none; | |
| align-items:center;justify-content:center;padding:20px;z-index:20} | |
| .overlay.open{display:flex} | |
| .sheet{background:#181818;border:1px solid #303030;border-radius:8px; | |
| max-width:520px;width:100%;padding:22px;max-height:90vh;overflow-y:auto} | |
| .sheet h2{font-size:19px;font-weight:500;margin:0 0 4px} | |
| .sheet .sub{color:#AAAAAA;font-size:14px;margin:0 0 18px} | |
| .steps{background:#0F0F0F;border:1px solid #272727;border-radius:8px; | |
| padding:14px 16px;margin:14px 0;display:none} | |
| .steps ol{margin:0;padding-left:22px} | |
| .steps li{margin-bottom:8px;font-size:15px} | |
| .host{font-family:ui-monospace,monospace;color:#3EA6FF;word-break:break-all} | |
| .hint{display:none;color:#f5a623;font-size:14px;margin-top:10px} | |
| footer{padding:24px 20px 40px;color:#606060;font-size:14px;text-align:center} | |
| `; | |
| export type VrModePageInput = { | |
| baseUrl: string; | |
| token: string; | |
| client: VrClient; | |
| page: number; | |
| }; | |
| export async function buildVrModePage(input: VrModePageInput): Promise<string> { | |
| const { baseUrl, token, client } = input; | |
| const pageSize = vrModePageSize(); | |
| const rows = await db.video.findMany({ | |
| where: { availability: "available" }, | |
| orderBy: { addedAt: "desc" }, | |
| }); | |
| const playable = rows.filter((v: Video) => !!v.streamUrl); | |
| const pageCount = Math.max(1, Math.ceil(playable.length / pageSize)); | |
| const page = Math.min(Math.max(1, input.page), pageCount); | |
| const slice = playable.slice((page - 1) * pageSize, page * pageSize); | |
| const cards = slice.map((v: Video) => toCard(v, baseUrl, token)); | |
| const host = baseUrl.replace(/^https?:\/\//, ""); | |
| const q = token ? `?token=${encodeURIComponent(token)}` : ""; | |
| const pageLink = (n: number) => | |
| `/vr${token ? `?token=${encodeURIComponent(token)}&page=${n}` : `?page=${n}`}`; | |
| const cardsHtml = cards | |
| .map((c) => { | |
| const badges = c.badges | |
| .map( | |
| (b) => | |
| `<span class="badge${b.startsWith("Passthrough") ? " pt" : ""}">${esc(b)}</span>` | |
| ) | |
| .join(""); | |
| return `<button class="card" type="button" | |
| data-title="${esc(c.title)}" | |
| data-tags="${esc(c.tags.join(" "))}" | |
| data-json="${esc(c.deovrJson)}" | |
| data-deeplink="${esc(c.deovrDeeplink)}" | |
| data-stream="${esc(c.stream)}"> | |
| <div class="thumb"> | |
| <img src="${esc(c.thumbnail)}" alt="" loading="lazy" decoding="async"> | |
| ${c.duration ? `<span class="time">${esc(c.duration)}</span>` : ""} | |
| </div> | |
| <div class="meta"> | |
| <p class="name">${esc(c.title)}</p> | |
| <div class="badges">${badges}</div> | |
| </div> | |
| </button>`; | |
| }) | |
| .join("\n"); | |
| const emptyHtml = `<p class="muted">No playable videos yet. Run a scan from the dashboard, | |
| then reload this page.</p>`; | |
| const pager = | |
| pageCount > 1 | |
| ? `<div class="pager"> | |
| ${page > 1 ? `<a class="btn ghost" href="${pageLink(page - 1)}">Previous</a>` : ""} | |
| <span class="muted">Page ${page} of ${pageCount}</span> | |
| ${page < pageCount ? `<a class="btn ghost" href="${pageLink(page + 1)}">Next</a>` : ""} | |
| </div>` | |
| : ""; | |
| // Client-side script: plain ES5-ish, no template literals, so it behaves the | |
| // same in the older WebViews some headset apps embed. | |
| const script = ` | |
| var CLIENT = ${JSON.stringify(client)}; | |
| var HOST = ${JSON.stringify(host)}; | |
| var TOTAL = ${cards.length}; | |
| var current = null; | |
| var overlay = document.getElementById('picker'); | |
| function openPicker(card) { | |
| current = card; | |
| document.getElementById('pick-title').textContent = card.getAttribute('data-title'); | |
| document.getElementById('playa-steps').style.display = 'none'; | |
| document.getElementById('deovr-hint').style.display = 'none'; | |
| overlay.classList.add('open'); | |
| } | |
| function closePicker() { overlay.classList.remove('open'); current = null; } | |
| var cards = document.querySelectorAll('.card'); | |
| for (var i = 0; i < cards.length; i++) { | |
| cards[i].addEventListener('click', function () { openPicker(this); }); | |
| } | |
| overlay.addEventListener('click', function (e) { if (e.target === overlay) closePicker(); }); | |
| document.getElementById('pick-cancel').addEventListener('click', closePicker); | |
| // DeoVR: inside its own browser a JSON link opens the player directly; from any | |
| // other browser the registered deovr:// deeplink does the same job. | |
| document.getElementById('btn-deovr').addEventListener('click', function () { | |
| if (!current) return; | |
| if (CLIENT === 'deovr') { | |
| window.location.href = current.getAttribute('data-json'); | |
| } else { | |
| window.location.href = current.getAttribute('data-deeplink'); | |
| document.getElementById('deovr-hint').style.display = 'block'; | |
| } | |
| }); | |
| document.getElementById('btn-deovr-json').addEventListener('click', function () { | |
| if (current) window.location.href = current.getAttribute('data-json'); | |
| }); | |
| // PLAY'A has no per-video handoff from a web page, so the reliable route is its | |
| // native library (this server's PLAY'A API). Shown as steps, with a best-effort | |
| // direct-play attempt for its built-in browser underneath. | |
| document.getElementById('btn-playa').addEventListener('click', function () { | |
| document.getElementById('playa-steps').style.display = 'block'; | |
| }); | |
| document.getElementById('btn-playa-web').addEventListener('click', function () { | |
| if (current) window.location.href = current.getAttribute('data-stream'); | |
| }); | |
| document.getElementById('btn-copy-host').addEventListener('click', function () { | |
| try { | |
| navigator.clipboard.writeText(HOST); | |
| this.textContent = 'Copied ' + HOST; | |
| } catch (e) { | |
| this.textContent = HOST; | |
| } | |
| }); | |
| // Search + filter chips. | |
| var search = document.getElementById('q'); | |
| var chips = document.querySelectorAll('.chip'); | |
| function activeTag() { | |
| for (var i = 0; i < chips.length; i++) { | |
| if (chips[i].className.indexOf('on') >= 0) return chips[i].getAttribute('data-tag'); | |
| } | |
| return 'all'; | |
| } | |
| function applyFilter() { | |
| var term = (search.value || '').toLowerCase(); | |
| var tag = activeTag(); | |
| var shown = 0; | |
| for (var i = 0; i < cards.length; i++) { | |
| var card = cards[i]; | |
| var hitText = card.getAttribute('data-title').toLowerCase().indexOf(term) >= 0; | |
| var hitTag = tag === 'all' || card.getAttribute('data-tags').indexOf(tag) >= 0; | |
| var show = hitText && hitTag; | |
| card.style.display = show ? '' : 'none'; | |
| if (show) shown++; | |
| } | |
| document.getElementById('count').textContent = shown + ' of ' + TOTAL + ' shown'; | |
| } | |
| search.addEventListener('input', applyFilter); | |
| for (var c = 0; c < chips.length; c++) { | |
| chips[c].addEventListener('click', function () { | |
| for (var k = 0; k < chips.length; k++) chips[k].className = 'chip'; | |
| this.className = 'chip on'; | |
| applyFilter(); | |
| }); | |
| } | |
| `; | |
| return `<!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>VR mode</title> | |
| <style>${STYLES}</style> | |
| </head> | |
| <body> | |
| <header> | |
| <div class="brand"> | |
| <span class="dot"></span> | |
| <h1>VR mode</h1> | |
| <span class="muted" id="count">${cards.length} of ${playable.length} shown</span> | |
| <a class="switch" href="/vr/exit"><span class="sdot"></span>VR mode is ON — tap to turn off</a> | |
| </div> | |
| <div class="tools"> | |
| <input id="q" type="search" placeholder="Search titles" autocomplete="off"> | |
| <button class="chip on" data-tag="all" type="button">All</button> | |
| <button class="chip" data-tag="vr180" type="button">VR180</button> | |
| <button class="chip" data-tag="vr360" type="button">VR360</button> | |
| <button class="chip" data-tag="passthrough" type="button">Passthrough</button> | |
| <button class="chip" data-tag="flat" type="button">Flat</button> | |
| </div> | |
| </header> | |
| <main> | |
| <div class="grid"> | |
| ${cards.length ? cardsHtml : emptyHtml} | |
| </div> | |
| ${pager} | |
| </main> | |
| <footer> | |
| Tap any thumbnail to choose a player. | |
| <a href="/vr/exit">Turn VR mode off</a> | |
| <a href="/?desktop=1">Dashboard (VR stays on)</a> | |
| </footer> | |
| <div class="overlay" id="picker"> | |
| <div class="sheet"> | |
| <h2 id="pick-title">Video</h2> | |
| <p class="sub">Which player should open this?</p> | |
| <button class="btn block" id="btn-deovr" type="button">Play in DeoVR</button> | |
| <p class="hint" id="deovr-hint"> | |
| Nothing happened? <a href="#" id="btn-deovr-json">Open the DeoVR link directly</a> | |
| — that works inside DeoVR's own browser. | |
| </p> | |
| <button class="btn block ghost" id="btn-playa" type="button">Play in PLAY'A</button> | |
| <div class="steps" id="playa-steps"> | |
| <ol> | |
| <li>In PLAY'A open <strong>Web</strong>, tap <strong>Add Website</strong>.</li> | |
| <li>Enter <span class="host">${esc(host)}</span> and press <strong>Connect</strong> | |
| (only needed once).</li> | |
| <li>Sign in with your server username and password.</li> | |
| <li>Your whole library appears inside PLAY'A with thumbnails — open this | |
| title from there.</li> | |
| </ol> | |
| <button class="btn ghost block" id="btn-copy-host" type="button" | |
| style="margin-top:12px">Copy server address</button> | |
| <button class="btn ghost block" id="btn-playa-web" type="button"> | |
| Or try playing it in PLAY'A's browser | |
| </button> | |
| <p class="muted" style="margin:6px 0 0;font-size:13px"> | |
| PLAY'A cannot be handed a single video by a web page, so the library route | |
| above is the dependable one. | |
| </p> | |
| </div> | |
| <button class="btn block ghost" id="pick-cancel" type="button">Cancel</button> | |
| </div> | |
| </div> | |
| <script>${script}</script> | |
| </body> | |
| </html>`; | |
| } | |
| /** Small friendly page instead of a JSON 401 when a headset has no credential. */ | |
| export function vrModeSignInPage(opts?: { credentials?: boolean }): string { | |
| const credentials = opts?.credentials !== false; | |
| const inputStyle = | |
| "width:100%;box-sizing:border-box;margin:0 0 12px;padding:16px 18px;" + | |
| "font-size:20px;border-radius:10px;border:1px solid #303030;" + | |
| "background:#212121;color:#eeeeee"; | |
| const fields = credentials | |
| ? `<input id="u" style="${inputStyle}" placeholder="Username" autocomplete="username" autocapitalize="none"> | |
| <input id="p" style="${inputStyle}" type="password" placeholder="Password" autocomplete="current-password">` | |
| : `<input id="k" style="${inputStyle}" type="password" placeholder="API key" autocomplete="off">`; | |
| // Concatenation, never template literals: this string is already inside one. | |
| const script = ` | |
| var CRED = ${credentials ? "true" : "false"}; | |
| var msg = document.getElementById('msg'); | |
| function val(id) { var el = document.getElementById(id); return el ? el.value : ''; } | |
| function submit() { | |
| msg.style.color = '#aaaaaa'; | |
| msg.textContent = 'Signing in...'; | |
| var body = CRED | |
| ? { username: val('u'), password: val('p') } | |
| : { apiKey: val('k') }; | |
| fetch('/api/auth/login', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify(body) | |
| }).then(function (r) { | |
| return r.json().catch(function () { return {}; }).then(function (d) { | |
| return { ok: r.ok, d: d }; | |
| }); | |
| }).then(function (res) { | |
| if (res.ok && res.d && res.d.ok) { | |
| window.location.href = '/vr?remember=1'; | |
| return; | |
| } | |
| msg.style.color = '#e1002d'; | |
| msg.textContent = (res.d && res.d.error) || 'Sign in failed'; | |
| }).catch(function () { | |
| msg.style.color = '#e1002d'; | |
| msg.textContent = 'Network error -- is the Space awake?'; | |
| }); | |
| } | |
| document.getElementById('go').addEventListener('click', submit); | |
| document.addEventListener('keydown', function (e) { | |
| if (e.key === 'Enter') submit(); | |
| }); | |
| `; | |
| return `<!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>Sign in - VR mode</title> | |
| <style>${STYLES}</style> | |
| </head> | |
| <body> | |
| <main style="max-width:560px;margin:0 auto;padding-top:48px"> | |
| <h1 style="font-size:26px;font-weight:500;margin-bottom:4px">Sign in for VR mode</h1> | |
| <p class="muted" style="margin-top:0">${ | |
| credentials | |
| ? "Your server username and password." | |
| : "Your API key. It is stored in the Space secret too." | |
| }</p> | |
| ${fields} | |
| <button class="btn" id="go" type="button" style="width:100%;font-size:20px;padding:16px">Sign in</button> | |
| <p id="msg" class="muted" style="min-height:24px;margin-top:14px"></p> | |
| <p class="muted" style="font-size:14px;line-height:1.7;margin-top:24px"> | |
| Typing is awkward in a headset. You can skip it by bookmarking this address | |
| with <span class="host">?token=YOUR_API_KEY</span> on the end. | |
| </p> | |
| </main> | |
| <script>${script}</script> | |
| </body> | |
| </html>`; | |
| } | |