fix(mobile): playback

This commit is contained in:
joshuafhiggins authored and Joshua Higgins committed 2026-08-02 04:14:01 +00:00
1 parent f6c4049dd1
commit 37c4348a9d
5 files changed
+124 -35

No files matched your search

+3 -1
View File
@@ -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")
+35 -28
View File
@@ -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<PlaybackContextValue | null>(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(() => {
+39
View File
@@ -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<string | null> {
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("; ")
}
+21 -6
View File
@@ -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}`
}
+26
View File
@@ -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
}