Files
otunes/apps/web/lib/server.ts
T
joshuafhigginsandClaude Opus 5.5 Verified f8e5dc7325 feat(desktop): ship the web UI as a static export
The static export now works away from the oTunes server. It picks a
server at /server (saved in localStorage), connects Convex to it, and
loads covers, avatars and streams from it. Streams and avatars pass the
session token as a `token` query parameter, which the song and avatar
routes accept alongside the cookie. The server allows any origin on /api.

Electron serves that export from 127.0.0.1:47836 and drops the bundled
Next.js server, the media gateway, symlink materializing and Sharp
pruning. The same export can ship in a Tauri app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:15:35 -05:00

66 lines
2.0 KiB
TypeScript

import type { ServerConfig } from "@otunes/convex/server-url"
import { useSyncExternalStore } from "react"
// The server build is served by the oTunes server, so media paths stay
// relative and the session cookie authenticates them. Static exports (desktop
// apps) are served locally and talk to a server the user picks at runtime.
export const staticExport = process.env.OTUNES_STATIC_EXPORT === "1"
const SERVER_KEY = "otunes.server"
function readServer(): ServerConfig | null {
if (!staticExport || typeof window === "undefined") return null
try {
return JSON.parse(localStorage.getItem(SERVER_KEY) ?? "null")
} catch {
return null
}
}
let server = readServer()
export function selectedServer() {
return server
}
export function saveServer(config: ServerConfig) {
localStorage.setItem(SERVER_KEY, JSON.stringify(config))
server = config
}
const noop = () => () => {}
/** The picked server in static exports. `null` while prerendering. */
export function useSelectedServer() {
return useSyncExternalStore(noop, selectedServer, () => null)
}
/** Origin of the oTunes server, for share links. */
export function serverOrigin() {
return server?.serverUrl ?? window.location.origin
}
/** Resolves an `/api/...` path against the oTunes server. */
export function serverUrl(path: string) {
return server ? `${server.serverUrl}${path}` : path
}
let mediaToken: string | null = null
/** Kept current by the auth provider in static exports. */
export function setMediaToken(token: string | null) {
mediaToken = token
}
/**
* URL for a song route, which needs a session. `<audio>` and native HLS cannot
* send headers, and exports have no cookie on the server's origin, so they
* pass the session token in the query. HLS segment URLs inherit it from the
* playlist URL.
*/
export function authedUrl(path: string) {
const url = serverUrl(path)
if (!server || !mediaToken) return url
return `${url}${url.includes("?") ? "&" : "?"}token=${encodeURIComponent(mediaToken)}`
}