From 37c4348a9d301535c764a12bc16bad222cc0b2c2 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Tue, 23 Jun 2026 22:45:01 -0400 Subject: [PATCH] fix(mobile): playback --- apps/mobile/app/server.tsx | 4 +- apps/mobile/contexts/playback.tsx | 63 +++++++++++++++++-------------- apps/mobile/lib/auth-cookies.ts | 39 +++++++++++++++++++ apps/mobile/lib/server-config.ts | 27 ++++++++++--- apps/mobile/lib/urls.ts | 26 +++++++++++++ 5 files changed, 124 insertions(+), 35 deletions(-) create mode 100644 apps/mobile/lib/auth-cookies.ts diff --git a/apps/mobile/app/server.tsx b/apps/mobile/app/server.tsx index c43b33d..77d19dc 100644 --- a/apps/mobile/app/server.tsx +++ b/apps/mobile/app/server.tsx @@ -27,7 +27,9 @@ export default function ServerScreen() { const ok = await setServerHostname(hostname) setSubmitting(false) if (!ok) { - setError("Enter a valid server address, e.g. music.example.com or localhost:3000") + setError( + "Enter a valid server address, e.g. music.example.com, localhost:3000" + ) return } router.replace("/signin") diff --git a/apps/mobile/contexts/playback.tsx b/apps/mobile/contexts/playback.tsx index e0224ce..d165767 100644 --- a/apps/mobile/contexts/playback.tsx +++ b/apps/mobile/contexts/playback.tsx @@ -21,9 +21,10 @@ import { useServerConfig } from "@/contexts/server-config" import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowseSong } from "@otunes/convex/types" +import { playbackStreamPlan } from "@otunes/convex/playback-stream" +import { getAuthCookieHeader } from "@/lib/auth-cookies" import { showError } from "@/lib/toast" -import type { PlaybackQuality } from "@/lib/urls" -import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/urls" +import { songAudioSource } from "@/lib/urls" type RepeatMode = "none" | "once" | "always" @@ -73,16 +74,6 @@ type PlaybackContextValue = { const PlaybackContext = createContext(null) -function playbackLoadSettings(user: { - preferAtmos?: boolean - playbackQuality?: PlaybackQuality -}) { - const preferAtmos = user.preferAtmos ?? false - const playbackQuality = user.playbackQuality ?? "medium" - const useHls = playbackQuality !== "lossless" && !preferAtmos - return { preferAtmos, playbackQuality, useHls } -} - export function usePlayback() { const context = useContext(PlaybackContext) if (!context) { @@ -316,23 +307,38 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { return } - const settings = playbackLoadSettings(user) - const loadKey = `${currentSong.id}:${settings.playbackQuality}:${settings.useHls ? "hls" : "file"}` + const song = await convex.query(api.library.getSong, { + id: currentSong.id, + }) + if (!song) { + return + } + + const plan = playbackStreamPlan( + song.files, + user.playbackQuality, + user.preferAtmos ?? false + ) + const loadKey = `${currentSong.id}:${plan.playbackQuality}:${plan.useHls ? "hls" : "file"}` if (loadedSongKeyRef.current === loadKey) return - const uri = settings.useHls - ? songHlsPlaylistUrl( - config.serverUrl, - currentSong.id, - settings.playbackQuality, - settings.preferAtmos - ) - : songPlayUrl( - config.serverUrl, - currentSong.id, - settings.playbackQuality, - settings.preferAtmos - ) + const cookieHeader = await getAuthCookieHeader( + config.serverUrl, + config.convexUrl + ) + if (!cookieHeader) { + showError("Your session has expired. Please sign in again.") + return + } + + const source = songAudioSource( + config.serverUrl, + currentSong.id, + plan.playbackQuality, + plan.preferAtmos, + plan.useHls, + { cookieHeader, songTitle: currentSong.title } + ) const player = ensurePlayer() loadedSongKeyRef.current = loadKey @@ -344,7 +350,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { pendingSeekRef.current = null } - player.replace(uri) + player.replace(source) player.volume = volume if (isPlayingRef.current || autoPlayNextRef.current) { @@ -372,6 +378,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { progressToRestore, currentSong, user, + convex, ]) useEffect(() => { diff --git a/apps/mobile/lib/auth-cookies.ts b/apps/mobile/lib/auth-cookies.ts new file mode 100644 index 0000000..66ef8a8 --- /dev/null +++ b/apps/mobile/lib/auth-cookies.ts @@ -0,0 +1,39 @@ +import { authStorageKey, secureGetItem } from "@/lib/auth-storage" + +const JWT_STORAGE_KEY = "__convexAuthJWT" +const REFRESH_STORAGE_KEY = "__convexAuthRefreshToken" + +function isConvexAuthLocalHost(host: string) { + return /(localhost|127\.0\.0\.1):\d+/.test(host) +} + +function authCookieNames(serverUrl: string) { + const host = new URL(serverUrl).host + const prefix = isConvexAuthLocalHost(host) ? "" : "__Host-" + return { + jwt: `${prefix}${JWT_STORAGE_KEY}`, + refresh: `${prefix}${REFRESH_STORAGE_KEY}`, + } +} + +export async function getAuthCookieHeader( + serverUrl: string, + convexUrl: string +): Promise { + const [jwt, refreshToken] = await Promise.all([ + secureGetItem(authStorageKey(JWT_STORAGE_KEY, convexUrl)), + secureGetItem(authStorageKey(REFRESH_STORAGE_KEY, convexUrl)), + ]) + + if (!jwt) { + return null + } + + const names = authCookieNames(serverUrl) + const parts = [`${names.jwt}=${jwt}`] + if (refreshToken) { + parts.push(`${names.refresh}=${refreshToken}`) + } + + return parts.join("; ") +} diff --git a/apps/mobile/lib/server-config.ts b/apps/mobile/lib/server-config.ts index 4ddcb10..0aa754b 100644 --- a/apps/mobile/lib/server-config.ts +++ b/apps/mobile/lib/server-config.ts @@ -1,7 +1,5 @@ -export type PlaybackQuality = "low" | "medium" | "high" | "lossless" - export type ServerConfig = { - /** Raw hostname the user entered, e.g. `music.example.com` or `localhost:3000` */ + /** Raw hostname the user entered, e.g. `music.example.com` or `192.168.86.25:3000` */ hostname: string /** Base URL for the Next.js server, e.g. `https://music.example.com` */ serverUrl: string @@ -11,9 +9,23 @@ export type ServerConfig = { const SERVER_CONFIG_KEY = "otunes.server-config" const LEGACY_SERVER_CONFIG_KEY = "otunes:server-config" +const LOCAL_CONVEX_PORT = "3210" + +function parseHostPort(hostname: string): { host: string; port?: string } { + const colonIndex = hostname.lastIndexOf(":") + if (colonIndex === -1) { + return { host: hostname } + } + const host = hostname.slice(0, colonIndex) + const port = hostname.slice(colonIndex + 1) + if (!/^\d+$/.test(port)) { + return { host: hostname } + } + return { host, port } +} function isLocalHost(hostname: string): boolean { - const host = hostname.split(":")[0]?.toLowerCase() ?? "" + const host = parseHostPort(hostname).host.toLowerCase() return ( host === "localhost" || host === "127.0.0.1" || @@ -32,9 +44,12 @@ function buildServerUrl(hostname: string): string { } function buildConvexUrl(hostname: string): string { - const [host, port] = hostname.split(":") - const convexHost = `convex.${host}` + const { host, port } = parseHostPort(hostname) const protocol = isLocalHost(hostname) ? "http" : "https" + if (isLocalHost(hostname)) { + return `${protocol}://${host}:${LOCAL_CONVEX_PORT}` + } + const convexHost = `convex.${host}` return port ? `${protocol}://${convexHost}:${port}` : `${protocol}://${convexHost}` } diff --git a/apps/mobile/lib/urls.ts b/apps/mobile/lib/urls.ts index abc54a2..8f6b9ed 100644 --- a/apps/mobile/lib/urls.ts +++ b/apps/mobile/lib/urls.ts @@ -1,3 +1,5 @@ +import type { AudioSource } from "expo-audio" + export type PlaybackQuality = "low" | "medium" | "high" | "lossless" export function artistCoverUrl(serverUrl: string, artistId: string) { @@ -37,3 +39,27 @@ export function songHlsPlaylistUrl( const query = params.toString() return `${serverUrl}/api/song/${songId}/play/hls${query ? `?${query}` : ""}` } + +export function songAudioSource( + serverUrl: string, + songId: string, + quality: PlaybackQuality | undefined, + preferAtmos: boolean | undefined, + useHls: boolean, + options?: { cookieHeader?: string | null; songTitle?: string } +): AudioSource { + const uri = useHls + ? songHlsPlaylistUrl(serverUrl, songId, quality, preferAtmos) + : songPlayUrl(serverUrl, songId, quality, preferAtmos) + + const headers = options?.cookieHeader + ? { Cookie: options.cookieHeader } + : undefined + const name = options?.songTitle + + if (headers || name) { + return { uri, ...(name ? { name } : {}), ...(headers ? { headers } : {}) } + } + + return uri +}