-
+
{playlist.title}
diff --git a/apps/web/components/search-song-item.tsx b/apps/web/components/search-song-item.tsx
index 94100c1..30cfc78 100644
--- a/apps/web/components/search-song-item.tsx
+++ b/apps/web/components/search-song-item.tsx
@@ -2,6 +2,8 @@
import { useDownloads } from "@/components/downloads-provider"
import { useSongDownloadState } from "@/hooks/use-downloads"
+import { albumPath, artistPath } from "@/lib/routes"
+
import Image from "next/image"
import Link from "next/link"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
@@ -81,7 +83,7 @@ export function SearchSongItem({ song }: { song: SearchSong }) {
-
+
{song.title}
{song.artist.name}
diff --git a/apps/web/components/search-top-result-card.tsx b/apps/web/components/search-top-result-card.tsx
index 0d9065c..a3bcc8b 100644
--- a/apps/web/components/search-top-result-card.tsx
+++ b/apps/web/components/search-top-result-card.tsx
@@ -1,5 +1,7 @@
"use client"
+import { albumPath, artistPath } from "@/lib/routes"
+
import Image from "next/image"
import Link from "next/link"
@@ -12,11 +14,11 @@ export type TopResult = SearchTopResultItem
function resultHref(result: TopResult) {
switch (result.kind) {
case "song":
- return `/album/${result.item.album.id}`
+ return albumPath(result.item.album.id)
case "album":
- return `/album/${result.item.id}`
+ return albumPath(result.item.id)
case "artist":
- return `/artist/${result.item.id}`
+ return artistPath(result.item.id)
}
}
diff --git a/apps/web/components/server-form.tsx b/apps/web/components/server-form.tsx
new file mode 100644
index 0000000..64e99c6
--- /dev/null
+++ b/apps/web/components/server-form.tsx
@@ -0,0 +1,115 @@
+"use client"
+
+import { useState, type FormEvent } from "react"
+import Image from "next/image"
+import { Button } from "@/components/ui/button"
+import { Input } from "@/components/ui/input"
+import {
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from "@/components/ui/field"
+import { clearPersistentCache } from "@/lib/persistent-cache"
+import { saveServer, selectedServer } from "@/lib/server"
+import { parseServerHostname } from "@otunes/convex/server-url"
+
+// Picks the oTunes server for static exports (desktop apps). Saving reloads
+// the app so Convex connects to the new server.
+export function ServerForm() {
+ const [address, setAddress] = useState(() => selectedServer()?.hostname ?? "")
+ const [error, setError] = useState
(null)
+ const [submitting, setSubmitting] = useState(false)
+
+ async function connect(event: FormEvent) {
+ event.preventDefault()
+ const server = parseServerHostname(address)
+ if (!server) {
+ setError("Enter a hostname, like music.example.com.")
+ return
+ }
+ setError(null)
+ setSubmitting(true)
+ try {
+ // Opaque, but it fails when the Convex server cannot be reached.
+ await fetch(`${server.convexUrl}/version`, {
+ mode: "no-cors",
+ signal: AbortSignal.timeout(10000),
+ })
+ } catch {
+ setError("Could not reach the server. Check the address and try again.")
+ setSubmitting(false)
+ return
+ }
+ if (server.convexUrl !== selectedServer()?.convexUrl)
+ await clearPersistentCache()
+ saveServer(server)
+ window.location.replace("/signin")
+ }
+
+ return (
+
+
+
+
+ )
+}
diff --git a/apps/web/components/track-row.tsx b/apps/web/components/track-row.tsx
index c732512..d8ae7a8 100644
--- a/apps/web/components/track-row.tsx
+++ b/apps/web/components/track-row.tsx
@@ -1,5 +1,7 @@
"use client"
+import { albumPath, artistPath } from "@/lib/routes"
+
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
@@ -398,7 +400,7 @@ function TrackRowComponent({
event.stopPropagation()}
>
@@ -407,7 +409,7 @@ function TrackRowComponent({
event.stopPropagation()}
>
diff --git a/apps/web/lib/cover-urls.ts b/apps/web/lib/cover-urls.ts
index 8585295..9027ea3 100644
--- a/apps/web/lib/cover-urls.ts
+++ b/apps/web/lib/cover-urls.ts
@@ -1,7 +1,9 @@
+import { serverUrl } from "@/lib/server"
+
export type CoverImageSize = 64 | 128 | 192 | 256 | 384 | 512 | 768 | 1024
function withCoverImageSize(uri: string, size?: CoverImageSize) {
- return size ? `${uri}?size=${size}` : uri
+ return serverUrl(size ? `${uri}?size=${size}` : uri)
}
export function artistCoverUrl(artistId: string, size?: CoverImageSize) {
diff --git a/apps/web/lib/dolby-atmos-support.ts b/apps/web/lib/dolby-atmos-support.ts
index bc633e4..6dc4b7f 100644
--- a/apps/web/lib/dolby-atmos-support.ts
+++ b/apps/web/lib/dolby-atmos-support.ts
@@ -1,4 +1,4 @@
-const EC3_MIME = 'audio/x-m4a; codecs="ec-3"'
+const EC3_MIMES = ['audio/mp4; codecs="ec-3"', 'audio/x-m4a; codecs="ec-3"']
const AC4_MIME = 'audio/x-m4a; codecs="ac-4"'
function canPlayMime(audio: HTMLAudioElement, mime: string): boolean {
@@ -6,5 +6,8 @@ function canPlayMime(audio: HTMLAudioElement, mime: string): boolean {
}
export function supportsDolbyAtmosPlayback(audio: HTMLAudioElement): boolean {
- return canPlayMime(audio, EC3_MIME) || canPlayMime(audio, AC4_MIME)
+ return (
+ EC3_MIMES.some((mime) => canPlayMime(audio, mime)) ||
+ canPlayMime(audio, AC4_MIME)
+ )
}
diff --git a/apps/web/lib/downloads.ts b/apps/web/lib/downloads.ts
index 06c6c99..925388b 100644
--- a/apps/web/lib/downloads.ts
+++ b/apps/web/lib/downloads.ts
@@ -12,6 +12,8 @@ import {
songDownloadPath,
type DownloadQuality,
} from "@otunes/convex/download-quality"
+import { albumPath, playlistPath } from "@/lib/routes"
+import { authedUrl, serverUrl, staticExport } from "@/lib/server"
// Like YouTube Music on the web, downloads live in this browser's IndexedDB
// and only play inside the app. Clearing site data removes them.
@@ -38,21 +40,22 @@ export const OTHER_DOWNLOADS_PATH = "/library/downloads/other"
export const FROM_DOWNLOADS_PARAM = "from=downloads"
export function downloadedCollectionPath({ kind, id }: DownloadedCollection) {
- if (kind === "album") return `/album/${id}?${FROM_DOWNLOADS_PARAM}`
if (id === FAVORITES_ID) return `/playlist/favorites?${FROM_DOWNLOADS_PARAM}`
- return `/playlist/${id}?${FROM_DOWNLOADS_PARAM}`
+ const path = kind === "album" ? albumPath(id) : playlistPath(id)
+ return `${path}&${FROM_DOWNLOADS_PARAM}`
}
// Saved pages are specific to the signed-in user (public/downloads-sw.js).
const OFFLINE_PAGE_CACHE = "otunes-offline-pages"
/**
- * Lets downloaded covers show offline. In production builds the worker also
- * keeps pages and app code so the app opens offline.
+ * Lets downloaded covers show offline. In production server builds the worker
+ * also keeps pages and app code so the app opens offline. Static exports are
+ * served locally, so they always open.
*/
export function registerDownloadsServiceWorker() {
const url =
- process.env.NODE_ENV === "production"
+ process.env.NODE_ENV === "production" && !staticExport
? "/downloads-sw.js?offline-app"
: "/downloads-sw.js"
void navigator.serviceWorker?.register(url, { scope: "/" }).catch(() => {})
@@ -123,9 +126,12 @@ const storage: DownloadStorage = {
)
},
async save({ songId, requested, quality, albumId }, signal) {
- const response = await fetch(songDownloadPath(songId, requested), {
- signal,
- })
+ const response = await fetch(
+ authedUrl(songDownloadPath(songId, requested)),
+ {
+ signal,
+ }
+ )
if (!response.ok) {
throw new Error(`Download failed with ${response.status}`)
}
@@ -142,7 +148,7 @@ const storage: DownloadStorage = {
const cache = await caches.open(COVER_CACHE)
const key = coverPath(cover)
if (await cache.match(key)) return
- const response = await fetch(`${key}?size=${COVER_SIZE}`)
+ const response = await fetch(serverUrl(`${key}?size=${COVER_SIZE}`))
if (!response.ok) throw new Error(`Cover failed with ${response.status}`)
await cache.put(key, response)
},
diff --git a/apps/web/lib/media-links.ts b/apps/web/lib/media-links.ts
index cb112c8..ebe9089 100644
--- a/apps/web/lib/media-links.ts
+++ b/apps/web/lib/media-links.ts
@@ -1,4 +1,5 @@
import { toast } from "sonner"
+import { serverOrigin } from "@/lib/server"
import {
mediaShareUrl,
type MediaShareTarget,
@@ -7,9 +8,7 @@ import {
export type MediaShareContext = MediaShareTarget
export async function copyMediaShareLink(share: MediaShareContext) {
- await navigator.clipboard.writeText(
- mediaShareUrl(window.location.origin, share)
- )
+ await navigator.clipboard.writeText(mediaShareUrl(serverOrigin(), share))
toast.success("Link Copied")
}
diff --git a/apps/web/lib/routes.ts b/apps/web/lib/routes.ts
new file mode 100644
index 0000000..c040b66
--- /dev/null
+++ b/apps/web/lib/routes.ts
@@ -0,0 +1,17 @@
+// In-app routes pass ids as query parameters so the UI can be a static export.
+// Share links keep the `/album/
` form (see mediaShareUrl), which only the
+// server build serves, with link-preview metadata.
+
+export function albumPath(albumId: string, songId?: string) {
+ const query = new URLSearchParams({ id: albumId })
+ if (songId) query.set("s", songId)
+ return `/album?${query}`
+}
+
+export function artistPath(artistId: string) {
+ return `/artist?${new URLSearchParams({ id: artistId })}`
+}
+
+export function playlistPath(playlistId: string) {
+ return `/playlist?${new URLSearchParams({ id: playlistId })}`
+}
diff --git a/apps/web/lib/server-song.ts b/apps/web/lib/server-song.ts
index 1a2bc8b..9294201 100644
--- a/apps/web/lib/server-song.ts
+++ b/apps/web/lib/server-song.ts
@@ -2,15 +2,29 @@ import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
import { api } from "@otunes/convex/_generated/api"
import type { Doc, Id } from "@otunes/convex/_generated/dataModel"
import { fetchQuery } from "convex/nextjs"
+import type { NextRequest } from "next/server"
import { convexServerOptions } from "@/lib/convex-server"
import type { SongSource } from "@/lib/server-hls"
/**
- * Loads a song's file paths as the requesting listener, so Convex enforces auth
- * even if the proxy is bypassed. Throws when signed out or the song is missing.
+ * The listener's session, from the cookie or from a `token` query parameter
+ * (static exports on another origin).
*/
-export async function getSongSource(id: string): Promise {
- const token = await convexAuthNextjsToken()
+async function sessionToken(request: NextRequest) {
+ return (
+ request.nextUrl.searchParams.get("token") ?? (await convexAuthNextjsToken())
+ )
+}
+
+/**
+ * Loads a song's file paths as the requesting listener, so Convex enforces
+ * auth. Throws when signed out or missing.
+ */
+export async function getSongSource(
+ id: string,
+ request: NextRequest
+): Promise {
+ const token = await sessionToken(request)
const song = await fetchQuery(
api.library.getSongSource,
{ id: id as Id<"songs"> },
@@ -23,8 +37,11 @@ export async function getSongSource(id: string): Promise {
}
/** The song's stored lyrics tag, or null without lyrics. */
-export async function getSongLyrics(id: string): Promise {
- const token = await convexAuthNextjsToken()
+export async function getSongLyrics(
+ id: string,
+ request: NextRequest
+): Promise {
+ const token = await sessionToken(request)
return await fetchQuery(
api.lyrics.forSong,
{ id: id as Id<"songs"> },
@@ -36,9 +53,10 @@ const SOURCE_BATCH_SIZE = 200
/** `getSongSource` for many songs, in batches. Missing songs are left out. */
export async function getSongSources(
- ids: string[]
+ ids: string[],
+ request: NextRequest
): Promise<(SongSource & Pick, "album">)[]> {
- const token = await convexAuthNextjsToken()
+ const token = await sessionToken(request)
const batches: string[][] = []
for (let start = 0; start < ids.length; start += SOURCE_BATCH_SIZE) {
batches.push(ids.slice(start, start + SOURCE_BATCH_SIZE))
diff --git a/apps/web/lib/server.ts b/apps/web/lib/server.ts
new file mode 100644
index 0000000..8717088
--- /dev/null
+++ b/apps/web/lib/server.ts
@@ -0,0 +1,65 @@
+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 route that needs a session (songs, downloads). `