// 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/ thumbnails // /api/feeds/deovr/ single-video DeoVR JSON (deeplink target) // /api/stream// 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, "'"); } 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:// 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 { 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) => `${esc(b)}` ) .join(""); return ``; }) .join("\n"); const emptyHtml = `

No playable videos yet. Run a scan from the dashboard, then reload this page.

`; const pager = pageCount > 1 ? `
${page > 1 ? `Previous` : ""} Page ${page} of ${pageCount} ${page < pageCount ? `Next` : ""}
` : ""; // 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 ` VR mode

VR mode

${cards.length} of ${playable.length} shown VR mode is ON — tap to turn off
${cards.length ? cardsHtml : emptyHtml}
${pager}

Video

Which player should open this?

Nothing happened? Open the DeoVR link directly — that works inside DeoVR's own browser.

  1. In PLAY'A open Web, tap Add Website.
  2. Enter ${esc(host)} and press Connect (only needed once).
  3. Sign in with your server username and password.
  4. Your whole library appears inside PLAY'A with thumbnails — open this title from there.

PLAY'A cannot be handed a single video by a web page, so the library route above is the dependable one.

`; } /** 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 ? ` ` : ``; // 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 ` Sign in - VR mode

Sign in for VR mode

${ credentials ? "Your server username and password." : "Your API key. It is stored in the Space secret too." }

${fields}

Typing is awkward in a headset. You can skip it by bookmarking this address with ?token=YOUR_API_KEY on the end.

`; }