Compare commits

..
30 changed files with 713 additions and 68 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
# Mobile build variants
EAS profiles set `APP_VARIANT` to select the app identity in `app.config.ts`.
Both iOS bundle identifiers and Android package names use these values:
| Profile | App name | Identifier |
| --- | --- | --- |
| development | oTunes (Development) | com.abunchofknowitalls.otunes.development |
| preview | oTunes (Preview) | com.abunchofknowitalls.otunes.preview |
| production | oTunes | com.abunchofknowitalls.otunes |
Build with `eas build --profile development`, `--profile preview`, or
`--profile production` from this directory.
For local builds and Metro, select the same variant explicitly:
```sh
APP_VARIANT=development pnpm ios
APP_VARIANT=development pnpm android
APP_VARIANT=development pnpm start
```
An unset `APP_VARIANT` keeps the production identity. Unknown variants fail
configuration. URL schemes are `otunes-development`, `otunes-preview`, and
`otunes` respectively, allowing the apps to be installed together.
+31
View File
@@ -0,0 +1,31 @@
import type { ConfigContext, ExpoConfig } from "expo/config"
export default ({ config }: ConfigContext): ExpoConfig => {
const variant = process.env.APP_VARIANT ?? "production"
if (!["development", "preview", "production"].includes(variant)) {
throw new Error(`Unsupported APP_VARIANT: ${variant}`)
}
const suffix = variant === "production" ? "" : `.${variant}`
const nameSuffix =
variant === "development"
? " (Development)"
: variant === "preview"
? " (Preview)"
: ""
return {
...config,
name: `${config.name}${nameSuffix}`,
slug: config.slug!,
scheme: variant === "production" ? "otunes" : `otunes-${variant}`,
ios: {
...config.ios,
bundleIdentifier: `${config.ios!.bundleIdentifier}${suffix}`,
},
android: {
...config.android,
package: `${config.android!.package}${suffix}`,
},
}
}
@@ -183,7 +183,7 @@ export default function AlbumScreen() {
<Ionicons
name="ellipsis-horizontal"
size={22}
color={palette.foreground}
color={palette.isDark ? "#fff" : "#000"}
/>
</Pressable>
</MediaActionMenu>
@@ -297,7 +297,7 @@ function PlaylistContent({
<Ionicons
name="ellipsis-horizontal"
size={22}
color={palette.foreground}
color={palette.isDark ? "#fff" : "#000"}
/>
</Pressable>
</MediaActionMenu>
+17 -3
View File
@@ -1,8 +1,10 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import { Ionicons } from "@expo/vector-icons"
import { useAction, useMutation, useQuery } from "convex/react"
import { Image } from "expo-image"
import * as ImagePicker from "expo-image-picker"
import { useState } from "react"
import { router } from "expo-router"
import {
Platform,
Pressable,
@@ -374,8 +376,13 @@ function QualitySection({ user }: { user: CurrentUser }) {
<SettingsCard title="Spatial Audio">
<SwitchRow
title="Prefer Dolby Atmos"
subtitle="Use Atmos versions when they are available."
value={user.preferAtmos ?? false}
subtitle={
dolbyAtmosSupported
? "Use Atmos versions when they are available."
: "This device does not support Dolby Atmos playback."
}
disabled={!dolbyAtmosSupported}
value={dolbyAtmosSupported && (user.preferAtmos ?? false)}
onValueChange={(checked) =>
void updateAtmos({ preferAtmos: checked }).catch((error: Error) =>
showError(error.message)
@@ -459,7 +466,7 @@ function UsersSection({
<SettingsCard title="Sign Up">
<SwitchRow
title="Disable account creation"
subtitle="Stop people from registering themselves. Admins can still create accounts from the web app."
subtitle="Stop people from registering themselves. Admins can still create accounts."
value={appSettings?.disableAccountCreation ?? false}
onValueChange={(checked) =>
void setDisableCreation({ disabled: checked }).catch(
@@ -473,6 +480,10 @@ function UsersSection({
title="People"
subtitle="Manage who can access this server."
>
<Button
title="Create account"
onPress={() => router.push("/(app)/create-account")}
/>
<View style={styles.userList}>
{users.map((user, index) => (
<View
@@ -636,10 +647,12 @@ function SwitchRow({
subtitle,
value,
onValueChange,
disabled,
}: {
title: string
subtitle?: string
value: boolean
disabled?: boolean
onValueChange: (checked: boolean) => void
}) {
const colors = useThemeColors()
@@ -656,6 +669,7 @@ function SwitchRow({
</View>
<Switch
value={value}
disabled={disabled}
onValueChange={onValueChange}
{...(Platform.OS === "android"
? {
+15 -4
View File
@@ -75,14 +75,25 @@ export default function AppLayout() {
gestureDirection: "vertical",
}}
/>
<Stack.Screen
name="create-account"
options={{
title: "Create account",
presentation: "modal",
headerLargeTitle: false,
headerTransparent: false,
headerStyle: { backgroundColor: "#000" },
headerTintColor: "#fff",
contentStyle: { backgroundColor: "#000" },
}}
/>
<Stack.Screen
name="player"
options={{
headerShown: false,
presentation:
Platform.OS === "ios"
? "transparentModal"
: "fullScreenModal",
// Keep the library visible behind the custom swipe animation.
presentation: "transparentModal",
contentStyle: { backgroundColor: "transparent" },
animation: "slide_from_bottom",
gestureEnabled: true,
gestureDirection: "vertical",
+199
View File
@@ -0,0 +1,199 @@
import { useAction, useQuery } from "convex/react"
import { ConvexError } from "convex/values"
import { router, Stack } from "expo-router"
import { useEffect, useRef, useState } from "react"
import {
KeyboardAvoidingView,
Platform,
ScrollView,
StyleSheet,
Switch,
Text,
View,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { toast } from "sonner-native"
import { Button, Input, LoadingView } from "@/components/ui/primitives"
import { colors, spacing } from "@/lib/theme"
import { api } from "@otunes/convex/_generated/api"
export default function CreateAccountScreen() {
const user = useQuery(api.auth.currentUser)
const createUser = useAction(api.users.adminCreateUser)
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [isAdmin, setIsAdmin] = useState(false)
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
const pending = useRef(false)
const mounted = useRef(true)
useEffect(() => {
mounted.current = true
return () => {
mounted.current = false
}
}, [])
async function handleCreate() {
if (pending.current || !user?.isAdmin) return
setError(null)
if (!name.trim() || !email.trim().includes("@") || password.length < 8) {
setError(
"Enter a name, valid email, and password of at least 8 characters."
)
return
}
pending.current = true
setSubmitting(true)
try {
await createUser({
name: name.trim(),
email: email.trim().toLowerCase(),
password,
isAdmin,
})
toast.success("Account created")
if (mounted.current) router.back()
} catch (error) {
if (!mounted.current) return
setError(
error instanceof ConvexError && typeof error.data === "string"
? error.data
: "Could not create account. Try again."
)
} finally {
pending.current = false
if (mounted.current) setSubmitting(false)
}
}
return (
<SafeAreaView edges={["bottom", "left", "right"]} style={styles.screen}>
<Stack.Screen
options={{
gestureEnabled: !submitting,
}}
/>
{user === undefined ? (
<LoadingView />
) : !user?.isAdmin ? (
<Text style={[styles.text, styles.message]}>
Admin access required.
</Text>
) : (
<KeyboardAvoidingView
style={styles.screen}
behavior={Platform.OS === "ios" ? "padding" : undefined}
keyboardVerticalOffset={Platform.OS === "ios" ? 100 : 0}
>
<ScrollView
contentContainerStyle={styles.form}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
>
<View style={styles.field}>
<Text style={styles.label}>Name</Text>
<Input
accessibilityLabel="Name"
value={name}
onChangeText={setName}
autoCapitalize="words"
autoComplete="off"
editable={!submitting}
style={styles.input}
/>
</View>
<View style={styles.field}>
<Text style={styles.label}>Email</Text>
<Input
accessibilityLabel="Email"
value={email}
onChangeText={setEmail}
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
autoComplete="off"
editable={!submitting}
style={styles.input}
/>
</View>
<View style={styles.field}>
<Text style={styles.label}>Password</Text>
<Input
accessibilityLabel="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
autoCapitalize="none"
autoCorrect={false}
autoComplete="new-password"
placeholder="At least 8 characters"
editable={!submitting}
style={styles.input}
/>
</View>
<View style={styles.row}>
<Text style={styles.text}>Grant admin access</Text>
<Switch
accessibilityLabel="Grant admin access"
trackColor={{
false: colors.dark.muted,
true: colors.dark.primary,
}}
thumbColor={colors.dark.foreground}
value={isAdmin}
onValueChange={setIsAdmin}
disabled={submitting}
/>
</View>
{error ? (
<Text accessibilityRole="alert" style={styles.error}>
{error}
</Text>
) : null}
<Button
title={submitting ? "Creating account…" : "Create account"}
disabled={submitting}
onPress={() => void handleCreate()}
tint={{
background: colors.dark.primary,
foreground: colors.dark.primaryForeground,
}}
/>
</ScrollView>
</KeyboardAvoidingView>
)}
</SafeAreaView>
)
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: "#000" },
form: { padding: spacing.lg, gap: spacing.lg },
field: { gap: spacing.sm },
label: {
color: colors.dark.mutedForeground,
fontSize: 12,
fontWeight: "600",
textTransform: "uppercase",
letterSpacing: 0.6,
},
text: { color: colors.dark.foreground, fontSize: 16, flexShrink: 1 },
input: {
backgroundColor: colors.dark.muted,
color: colors.dark.foreground,
borderColor: colors.dark.border,
},
row: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: spacing.md,
minHeight: 48,
},
message: { padding: spacing.lg },
error: { color: colors.dark.destructive, fontSize: 14, lineHeight: 20 },
})
+10 -2
View File
@@ -1,3 +1,4 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import { NavigationBar } from "expo-navigation-bar"
import { MusicEntityView } from "@/components/music-entity-view"
import { Stack, useRouter } from "expo-router"
@@ -91,6 +92,7 @@ export default function PlayerScreen() {
} = usePlayback()
const { volume, setVolume, available: volumeAvailable } = useSystemVolume()
const [showQueue, setShowQueue] = useState(false)
const [isDismissing, setIsDismissing] = useState(false)
const [stageHeight, setStageHeight] = useState(0)
const [scrubTime, setScrubTime] = useState<number | null>(null)
const user = useCachedQuery(api.auth.currentUser)
@@ -103,7 +105,7 @@ export default function PlayerScreen() {
? playbackFormat(
playbackInfo.files,
user.playbackQuality,
user.preferAtmos ?? false
dolbyAtmosSupported && (user.preferAtmos ?? false)
)
: null
@@ -162,6 +164,7 @@ export default function PlayerScreen() {
event.translationY > DISMISS_DISTANCE ||
event.velocityY > DISMISS_VELOCITY
) {
scheduleOnRN(setIsDismissing, true)
dismissY.value = withTiming(
windowHeight,
{ duration: 220 },
@@ -221,7 +224,11 @@ export default function PlayerScreen() {
{Platform.OS === "android" ? (
<>
<Stack.Screen
options={{ statusBarStyle: colors.isDark ? "light" : "dark" }}
options={{
statusBarStyle: colors.isDark ? "light" : "dark",
// The swipe already animates the player offscreen.
animation: isDismissing ? "none" : "slide_from_bottom",
}}
/>
<NavigationBar style={colors.isDark ? "light" : "dark"} />
</>
@@ -391,6 +398,7 @@ export default function PlayerScreen() {
<PlayerSlider
accessibilityLabel="Volume"
commitHoldMs={0}
animateValueChanges
value={volume}
maximumValue={1}
fillColor={colors.sliderFill}
+9 -2
View File
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, type ReactNode } from "react"
import { StyleSheet, View } from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import Animated, {
cancelAnimation,
interpolate,
interpolateColor,
useAnimatedStyle,
@@ -35,6 +36,7 @@ export function PlayerSlider({
trailing,
accessibilityLabel,
commitHoldMs = COMMIT_HOLD_MS,
animateValueChanges = false,
}: {
value: number
maximumValue: number
@@ -47,6 +49,7 @@ export function PlayerSlider({
leading?: ReactNode
trailing?: ReactNode
accessibilityLabel: string
animateValueChanges?: boolean
/** Seeking needs a hold while playback catches up; system volume does not. */
commitHoldMs?: number
}) {
@@ -60,8 +63,11 @@ export function PlayerSlider({
useEffect(() => {
if (dragging.value || Date.now() < holdUntil.current) return
fraction.value = clamp(value / max)
}, [dragging, fraction, max, value])
const next = clamp(value / max)
fraction.value = animateValueChanges
? withTiming(next, { duration: 160 })
: next
}, [animateValueChanges, dragging, fraction, max, value])
const callbacks = useRef({
onValueChange,
@@ -100,6 +106,7 @@ export function PlayerSlider({
active.value = withSpring(1, { duration: 250, dampingRatio: 0.8 })
})
.onStart(() => {
cancelAnimation(fraction)
dragging.value = true
startFraction.value = fraction.value
scheduleOnRN(start)
+13 -3
View File
@@ -1,6 +1,8 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import {
createAudioPlaylist,
setAudioModeAsync,
setIsAudioActiveAsync,
type AudioMetadata,
type AudioPlaylist,
type AudioPlaylistStatus,
@@ -313,7 +315,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
? JSON.stringify([
user._id,
user.playbackQuality,
user.preferAtmos ?? false,
dolbyAtmosSupported && (user.preferAtmos ?? false),
])
: ""
@@ -625,7 +627,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
}
if (!isCurrentLoad()) return
const loadKey = `${user.playbackQuality}:${user.preferAtmos ?? false}:${cookieHeader}`
const loadKey = `${user.playbackQuality}:${dolbyAtmosSupported && (user.preferAtmos ?? false)}:${cookieHeader}`
const needsRebuild =
loadedLoadKeyRef.current !== loadKey ||
nativePlaylistNeedsRebuild(
@@ -667,7 +669,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const plan = playbackStreamPlan(
song.files,
user.playbackQuality,
user.preferAtmos ?? false
dolbyAtmosSupported && (user.preferAtmos ?? false)
)
sources.set(
song.id,
@@ -773,6 +775,14 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
playlist.play()
} else {
playlist.pause()
// Enable audio for the restored queue without starting playback.
try {
await setIsAudioActiveAsync(true)
} catch {
if (isCurrentLoad()) {
showError("Audio playback could not be initialized.")
}
}
}
}
+9
View File
@@ -5,13 +5,22 @@
},
"build": {
"development": {
"env": {
"APP_VARIANT": "development"
},
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"env": {
"APP_VARIANT": "preview"
},
"distribution": "internal"
},
"production": {
"env": {
"APP_VARIANT": "production"
},
"autoIncrement": true
}
},
+13 -1
View File
@@ -1,10 +1,12 @@
import { requireOptionalNativeModule, type EventEmitter } from "expo"
import { useFocusEffect } from "expo-router"
import { useCallback, useEffect, useState } from "react"
import { AppState } from "react-native"
import { AppState, Platform } from "react-native"
type VolumeState = { volume: number; available: boolean }
type VolumeEvents = { onVolumeChange: (state: VolumeState) => void }
interface SystemVolumeModule extends EventEmitter<VolumeEvents> {
setPlayerVisible?(visible: boolean): Promise<void>
getState(): Promise<VolumeState>
setVolume(volume: number): Promise<void>
}
@@ -18,6 +20,16 @@ export function useSystemVolume() {
available: false,
})
useFocusEffect(
useCallback(() => {
if (Platform.OS !== "ios" || !native?.setPlayerVisible) return
void native.setPlayerVisible(true).catch(() => {})
return () => {
void native.setPlayerVisible?.(false).catch(() => {})
}
}, [])
)
useEffect(() => {
if (!native) return
let active = true
+7
View File
@@ -38,6 +38,13 @@ export function useAppNavigation() {
const router = useRouter()
const push = useCallback((path: string) => {
if (activeSegmentsRef.current.includes("player")) {
// Leave the root player modal before navigating into the library stack.
router.dismiss()
router.navigate(tabPath("library", path))
return
}
router.push(tabPath(getActiveTabFromRef(), path))
}, [router])
+4
View File
@@ -0,0 +1,4 @@
import { Platform } from "react-native"
// Android Dolby decoder reports do not reliably indicate working Atmos playback.
export const dolbyAtmosSupported = Platform.OS === "ios"
+5 -2
View File
@@ -1,3 +1,5 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import { Platform } from "react-native"
import type { AudioSource } from "expo-audio"
export type PlaybackQuality = "low" | "medium" | "high" | "lossless"
@@ -50,8 +52,9 @@ export function songPlayUrl(
preferAtmos: boolean | undefined
) {
const params = new URLSearchParams()
if (Platform.OS === "ios") params.set("losslessFormat", "alac")
if (quality) params.set("quality", quality)
if (preferAtmos) params.set("preferAtmos", "true")
if (dolbyAtmosSupported && preferAtmos) params.set("preferAtmos", "true")
const query = params.toString()
return `${serverUrl}/api/song/${songId}/play${query ? `?${query}` : ""}`
}
@@ -64,7 +67,7 @@ export function songHlsPlaylistUrl(
) {
const params = new URLSearchParams()
if (quality) params.set("quality", quality)
if (preferAtmos) params.set("preferAtmos", "true")
if (dolbyAtmosSupported && preferAtmos) params.set("preferAtmos", "true")
const query = params.toString()
return `${serverUrl}/api/song/${songId}/play/hls${query ? `?${query}` : ""}`
}
@@ -7,24 +7,38 @@ public class AudioOutputModule: Module {
View(AudioOutputView.self) {
Prop("tint") { (view: AudioOutputView, color: UIColor) in
view.picker.tintColor = color
view.icon.tintColor = color
}
}
}
}
final class AudioOutputView: ExpoView {
let picker = AVRoutePickerView()
private let picker = AVRoutePickerView()
let icon = UIImageView(
image: UIImage(
systemName: "airplay.audio",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 27, weight: .semibold)
)
)
required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
picker.prioritizesVideoDevices = false
picker.backgroundColor = .clear
// Hide only the native glyph. Making the picker transparent prevents taps.
picker.tintColor = .clear
picker.activeTintColor = .clear
addSubview(picker)
icon.contentMode = .center
icon.isUserInteractionEnabled = false
icon.isAccessibilityElement = false
addSubview(icon)
}
override func layoutSubviews() {
super.layoutSubviews()
picker.frame = bounds
icon.frame = bounds
}
}
+10 -3
View File
@@ -13,13 +13,20 @@ final class SystemVolume: Module {
Events("onVolumeChange")
AsyncFunction("getState") { () -> [String: Any] in
self.prepareVolumeView()
return self.state()
}.runOnQueue(.main)
AsyncFunction("setPlayerVisible") { (visible: Bool) in
if visible {
self.prepareVolumeView()
} else {
self.volumeView?.removeFromSuperview()
self.volumeView = nil
}
}.runOnQueue(.main)
AsyncFunction("setVolume") { (value: Double) in
self.prepareVolumeView()
guard value.isFinite,
guard value.isFinite, self.volumeView?.window != nil,
let slider = self.volumeView?.subviews.compactMap({ $0 as? UISlider }).first
else { return }
slider.setValue(Float(min(1, max(0, value))), animated: false)
+5 -1
View File
@@ -1,5 +1,6 @@
"use client"
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import { Plus } from "lucide-react"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
@@ -17,7 +18,10 @@ export default function Page() {
return (
<div className="flex h-svh flex-col">
<header className="flex items-center justify-between gap-2 border-b px-4 py-3">
<h1 className="text-lg font-semibold">Playlists</h1>
<div className="flex min-w-0 items-center gap-2">
<MobileSidebarTrigger />
<h1 className="text-lg font-semibold">Playlists</h1>
</div>
<Button
variant="secondary"
size="sm"
+3 -1
View File
@@ -1,5 +1,6 @@
"use client"
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import { Suspense, useCallback, useEffect, useRef, useState } from "react"
import { SearchIcon } from "lucide-react"
import { usePathname, useSearchParams } from "next/navigation"
@@ -212,7 +213,8 @@ function SearchPageContent() {
return (
<div className="flex h-svh flex-col">
<header className="flex items-center justify-center border-b px-4 py-3">
<header className="flex items-center justify-center gap-2 border-b px-4 py-3">
<MobileSidebarTrigger />
<div className="relative w-full max-w-xl">
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
<input
+9 -25
View File
@@ -1,6 +1,7 @@
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { audioContentTypeForPath } from "@/lib/audio-content-type"
import { seekableLosslessFile } from "@/lib/server-lossless"
import { getConvexClient } from "@/lib/convex-server"
import { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream"
import { NextRequest, NextResponse, userAgent } from "next/server"
@@ -122,11 +123,7 @@ export async function GET(
}))!
const quality = request.nextUrl.searchParams.get("quality") as
| "low"
| "medium"
| "high"
| "lossless"
| null
"low" | "medium" | "high" | "lossless" | null
const preferAtmos =
request.nextUrl.searchParams.get("preferAtmos") === "true"
@@ -157,7 +154,11 @@ export async function GET(
const metadata = await music.parseFile(song.files[originalCodec])
if (!transcodeNeeded && originalCodec === "lossless") {
if (browser.name === "Safari" && metadata.format.codec === "ALAC") {
// Native iOS playback does not identify itself as Safari.
const acceptsAlac =
browser.name === "Safari" ||
request.nextUrl.searchParams.get("losslessFormat") === "alac"
if (acceptsAlac && metadata.format.codec === "ALAC") {
try {
return await streamFileResponse(
request,
@@ -169,26 +170,9 @@ export async function GET(
}
}
const ffmpegArgs = [
"-nostdin",
"-i",
song.files[originalCodec],
"-f",
"flac",
"pipe:1",
]
try {
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
const stream = ffmpegToReadableStream(ffmpegProcess)
return new NextResponse(stream, {
status: 200,
headers: {
"Content-Type": "audio/flac",
"Cache-Control": "no-cache",
},
})
const file = await seekableLosslessFile(song.files[originalCodec])
return await streamFileResponse(request, file, "audio/flac")
} catch {
return new Response("Server Error", { status: 500 })
}
+7 -3
View File
@@ -1,5 +1,6 @@
"use client"
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
@@ -391,9 +392,12 @@ export function AlbumView({
<p className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
Album
</p>
<h1 className="text-3xl font-bold tracking-tight sm:text-4xl">
{album.title}
</h1>
<div className="flex min-w-0 items-center justify-center gap-2 sm:justify-start md:contents">
<MobileSidebarTrigger />
<h1 className="text-3xl font-bold tracking-tight sm:text-4xl">
{album.title}
</h1>
</div>
<Link
href={"/artist/" + album.artist.id}
className="inline-block text-lg font-semibold text-primary hover:underline"
+5 -3
View File
@@ -35,6 +35,7 @@ import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar"
import { ThemeToggle } from "@/components/theme-toggle"
import Image from "next/image"
@@ -63,6 +64,7 @@ const library = [
]
export function AppSidebar() {
const { setOpenMobile } = useSidebar()
const pathname = usePathname()
const router = useRouter()
const { signOut } = useAuthActions()
@@ -120,7 +122,7 @@ export function AppSidebar() {
{browse.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton isActive={pathname === item.path} asChild>
<Link href={item.path}>
<Link href={item.path} onClick={() => setOpenMobile(false)}>
<item.icon />
<span>{item.title}</span>
</Link>
@@ -144,7 +146,7 @@ export function AppSidebar() {
}
asChild
>
<Link href={item.path}>
<Link href={item.path} onClick={() => setOpenMobile(false)}>
<item.icon />
<span>{item.title}</span>
</Link>
@@ -162,7 +164,7 @@ export function AppSidebar() {
{playlistNav.map((item) => (
<SidebarMenuItem key={item.path}>
<SidebarMenuButton isActive={pathname === item.path} asChild>
<Link href={item.path}>
<Link href={item.path} onClick={() => setOpenMobile(false)}>
<item.icon />
<span>{item.title}</span>
</Link>
+7 -3
View File
@@ -1,5 +1,6 @@
"use client"
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import * as React from "react"
import Image from "next/image"
import { Play, Shuffle } from "lucide-react"
@@ -79,9 +80,12 @@ export function ArtistView({
</div>
<div className="flex min-w-0 flex-1 flex-col gap-4">
<h1 className="min-w-0 truncate text-3xl font-bold tracking-tight sm:text-4xl lg:text-5xl">
{artist.name}
</h1>
<div className="flex min-w-0 items-center gap-2 md:contents">
<MobileSidebarTrigger />
<h1 className="min-w-0 truncate text-3xl font-bold tracking-tight sm:text-4xl lg:text-5xl">
{artist.name}
</h1>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button
@@ -1,3 +1,4 @@
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import { Skeleton } from "@/components/ui/skeleton"
import { albumGridClassName } from "@/lib/album-grid-classes"
import { TRACK_LIST_CONTAINER } from "@/lib/selection-range-styles"
@@ -21,6 +22,7 @@ function LoadingRegion({
export function PageHeader({ title }: { title: string }) {
return (
<header className="flex items-center gap-2 border-b px-4 py-3">
<MobileSidebarTrigger />
<h1 className="text-lg font-semibold">{title}</h1>
</header>
)
@@ -0,0 +1,23 @@
"use client"
import { Menu } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useSidebar } from "@/components/ui/sidebar"
export function MobileSidebarTrigger() {
const { openMobile, setOpenMobile } = useSidebar()
return (
<Button
variant="ghost"
size="icon"
className="size-11 shrink-0 md:hidden"
aria-label="Open sidebar"
aria-expanded={openMobile}
onClick={() => setOpenMobile(true)}
>
<Menu />
</Button>
)
}
+7 -3
View File
@@ -1,5 +1,6 @@
"use client"
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import { stationArtistId } from "@/lib/station-artist"
import * as React from "react"
import Image from "next/image"
@@ -544,9 +545,12 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
<p className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
Playlist
</p>
<h1 className="text-3xl font-bold tracking-tight sm:text-4xl">
{playlist.title}
</h1>
<div className="flex min-w-0 items-center justify-center gap-2 sm:justify-start md:contents">
<MobileSidebarTrigger />
<h1 className="text-3xl font-bold tracking-tight sm:text-4xl">
{playlist.title}
</h1>
</div>
<p className="text-lg font-semibold text-primary">
{playlist.owner.name}
</p>
+9 -2
View File
@@ -1,5 +1,6 @@
"use client"
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import { stationArtistId } from "@/lib/station-artist"
import { useEffect, useMemo, useState, useRef, MouseEvent } from "react"
import Image from "next/image"
@@ -362,7 +363,10 @@ export function SongsView() {
return (
<div className="flex h-svh flex-col">
<header className="flex items-center justify-between gap-2 border-b px-4 py-3">
<h1 className="text-lg font-semibold">Songs</h1>
<div className="flex min-w-0 items-center gap-2">
<MobileSidebarTrigger />
<h1 className="text-lg font-semibold">Songs</h1>
</div>
</header>
<SongListSkeleton />
</div>
@@ -372,7 +376,10 @@ export function SongsView() {
return (
<div className="flex h-svh flex-col">
<header className="flex items-center justify-between gap-2 border-b px-4 py-3">
<h1 className="text-lg font-semibold">Songs</h1>
<div className="flex min-w-0 items-center gap-2">
<MobileSidebarTrigger />
<h1 className="text-lg font-semibold">Songs</h1>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm" aria-label="Sort songs">
+82
View File
@@ -0,0 +1,82 @@
import { spawn } from "node:child_process"
import { createHash } from "node:crypto"
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
const conversions = new Map<string, Promise<string>>()
// A completed FLAC file has a duration and supports byte ranges. Piped FLAC does not.
export async function seekableLosslessFile(source: string): Promise<string> {
if (path.extname(source).toLowerCase() === ".flac") return source
const stat = await fs.stat(source)
const key = createHash("sha256")
.update(`${source}:${stat.size}:${stat.mtimeMs}`)
.digest("hex")
const existing = conversions.get(key)
if (existing) return existing
const conversion = convert(source, key)
conversions.set(key, conversion)
try {
return await conversion
} finally {
conversions.delete(key)
}
}
async function convert(source: string, key: string): Promise<string> {
const dir = path.join(os.tmpdir(), "otunes-lossless")
await fs.mkdir(dir, { recursive: true })
const cutoff = Date.now() - 30 * 60 * 1000
await Promise.all(
(await fs.readdir(dir))
.filter((name) => name.endsWith(".flac"))
.map(async (name) => {
const file = path.join(dir, name)
const stat = await fs.stat(file).catch(() => null)
if (stat && stat.mtimeMs < cutoff) await fs.rm(file, { force: true })
})
)
const output = path.join(dir, `${key}.flac`)
try {
await fs.access(output)
return output
} catch {
// Publish only completed conversions so range requests always see a complete file.
}
const temporary = path.join(
await fs.mkdtemp(path.join(dir, "convert-")),
"audio.flac"
)
try {
await new Promise<void>((resolve, reject) => {
const child = spawn(
"ffmpeg",
[
"-nostdin",
"-v",
"error",
"-i",
source,
"-map",
"0:a:0",
"-c:a",
"flac",
temporary,
],
{ stdio: "ignore" }
)
child.on("error", reject)
child.on("close", (code) => {
if (code === 0) resolve()
else reject(new Error(`Lossless conversion failed: ${code}`))
})
})
await fs.rename(temporary, output)
return output
} finally {
await fs.rm(path.dirname(temporary), { recursive: true, force: true })
}
}
+166
View File
@@ -159,3 +159,169 @@ diff --git a/build/Audio.types.d.ts b/build/Audio.types.d.ts
+ /** MIME type for streams whose URL has no file extension, such as HLS. */
+ mimeType?: string;
/**
diff --git a/android/src/main/java/expo/modules/audio/BaseAudioPlayer.kt b/android/src/main/java/expo/modules/audio/BaseAudioPlayer.kt
--- a/android/src/main/java/expo/modules/audio/BaseAudioPlayer.kt
+++ b/android/src/main/java/expo/modules/audio/BaseAudioPlayer.kt
@@ -159,8 +159,16 @@
super.sharedObjectDidRelease()
// Run on GlobalScope (not appContext.mainQueue) so that reloading doesn't cancel the release process
GlobalScope.launch(Dispatchers.Main) {
- releasePlayer()
+ release()
}
+ }
+
+ private var released = false
+
+ fun release() {
+ if (released) return
+ released = true
+ releasePlayer()
}
protected open fun releasePlayer() {
diff --git a/android/src/main/java/expo/modules/audio/AudioModule.kt b/android/src/main/java/expo/modules/audio/AudioModule.kt
--- a/android/src/main/java/expo/modules/audio/AudioModule.kt
+++ b/android/src/main/java/expo/modules/audio/AudioModule.kt
@@ -1105,6 +1105,7 @@
runOnMain {
playlist.clearLockScreenControls()
playlists.remove(playlist.id)
+ playlist.release()
releaseAudioFocusIfUnused()
}
}
diff --git a/android/src/main/java/expo/modules/audio/service/MetadataInjectingPlayer.kt b/android/src/main/java/expo/modules/audio/service/MetadataInjectingPlayer.kt
--- a/android/src/main/java/expo/modules/audio/service/MetadataInjectingPlayer.kt
+++ b/android/src/main/java/expo/modules/audio/service/MetadataInjectingPlayer.kt
@@ -1,5 +1,14 @@
package expo.modules.audio.service
+import androidx.media3.common.AudioAttributes
+import androidx.media3.common.DeviceInfo
+import androidx.media3.common.MediaItem
+import androidx.media3.common.PlaybackException
+import androidx.media3.common.PlaybackParameters
+import androidx.media3.common.Timeline
+import androidx.media3.common.TrackSelectionParameters
+import androidx.media3.common.Tracks
+import androidx.media3.common.VideoSize
import android.os.Handler
import android.os.Looper
import androidx.core.net.toUri
@@ -81,7 +90,114 @@
private inner class MetadataForwardingListener(
private val listener: Player.Listener
- ) : Player.Listener by listener {
+ ) : Player.Listener {
+ // Kotlin delegation does not forward Java default methods on Player.Listener.
+ // Forward each callback so MediaSession receives timeline and duration changes.
+ override fun onTimelineChanged(timeline: Timeline, reason: Int) =
+ listener.onTimelineChanged(timeline, reason)
+
+ override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) =
+ listener.onMediaItemTransition(mediaItem, reason)
+
+ override fun onTracksChanged(tracks: Tracks) =
+ listener.onTracksChanged(tracks)
+
+ override fun onPlaylistMetadataChanged(mediaMetadata: MediaMetadata) =
+ listener.onPlaylistMetadataChanged(mediaMetadata)
+
+ override fun onIsLoadingChanged(isLoading: Boolean) =
+ listener.onIsLoadingChanged(isLoading)
+
+ override fun onLoadingChanged(isLoading: Boolean) =
+ listener.onLoadingChanged(isLoading)
+
+ override fun onAvailableCommandsChanged(availableCommands: Player.Commands) =
+ listener.onAvailableCommandsChanged(availableCommands)
+
+ override fun onTrackSelectionParametersChanged(parameters: TrackSelectionParameters) =
+ listener.onTrackSelectionParametersChanged(parameters)
+
+ override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) =
+ listener.onPlayerStateChanged(playWhenReady, playbackState)
+
+ override fun onPlaybackStateChanged(playbackState: Int) =
+ listener.onPlaybackStateChanged(playbackState)
+
+ override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) =
+ listener.onPlayWhenReadyChanged(playWhenReady, reason)
+
+ override fun onPlaybackSuppressionReasonChanged(playbackSuppressionReason: Int) =
+ listener.onPlaybackSuppressionReasonChanged(playbackSuppressionReason)
+
+ override fun onIsPlayingChanged(isPlaying: Boolean) =
+ listener.onIsPlayingChanged(isPlaying)
+
+ override fun onRepeatModeChanged(repeatMode: Int) =
+ listener.onRepeatModeChanged(repeatMode)
+
+ override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) =
+ listener.onShuffleModeEnabledChanged(shuffleModeEnabled)
+
+ override fun onPlayerError(error: PlaybackException) =
+ listener.onPlayerError(error)
+
+ override fun onPlayerErrorChanged(error: PlaybackException?) =
+ listener.onPlayerErrorChanged(error)
+
+ override fun onPositionDiscontinuity(reason: Int) =
+ listener.onPositionDiscontinuity(reason)
+
+ override fun onPositionDiscontinuity(oldPosition: Player.PositionInfo, newPosition: Player.PositionInfo, reason: Int) =
+ listener.onPositionDiscontinuity(oldPosition, newPosition, reason)
+
+ override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters) =
+ listener.onPlaybackParametersChanged(playbackParameters)
+
+ override fun onSeekBackIncrementChanged(seekBackIncrementMs: Long) =
+ listener.onSeekBackIncrementChanged(seekBackIncrementMs)
+
+ override fun onSeekForwardIncrementChanged(seekForwardIncrementMs: Long) =
+ listener.onSeekForwardIncrementChanged(seekForwardIncrementMs)
+
+ override fun onMaxSeekToPreviousPositionChanged(maxSeekToPreviousPositionMs: Long) =
+ listener.onMaxSeekToPreviousPositionChanged(maxSeekToPreviousPositionMs)
+
+ override fun onAudioSessionIdChanged(audioSessionId: Int) =
+ listener.onAudioSessionIdChanged(audioSessionId)
+
+ override fun onAudioAttributesChanged(audioAttributes: AudioAttributes) =
+ listener.onAudioAttributesChanged(audioAttributes)
+
+ override fun onVolumeChanged(volume: Float) =
+ listener.onVolumeChanged(volume)
+
+ override fun onSkipSilenceEnabledChanged(skipSilenceEnabled: Boolean) =
+ listener.onSkipSilenceEnabledChanged(skipSilenceEnabled)
+
+ override fun onDeviceInfoChanged(deviceInfo: DeviceInfo) =
+ listener.onDeviceInfoChanged(deviceInfo)
+
+ override fun onDeviceVolumeChanged(volume: Int, muted: Boolean) =
+ listener.onDeviceVolumeChanged(volume, muted)
+
+ override fun onVideoSizeChanged(videoSize: VideoSize) =
+ listener.onVideoSizeChanged(videoSize)
+
+ override fun onSurfaceSizeChanged(width: Int, height: Int) =
+ listener.onSurfaceSizeChanged(width, height)
+
+ override fun onRenderedFirstFrame() =
+ listener.onRenderedFirstFrame()
+
+ override fun onCues(cues: List<androidx.media3.common.text.Cue>) =
+ listener.onCues(cues)
+
+ override fun onCues(cueGroup: androidx.media3.common.text.CueGroup) =
+ listener.onCues(cueGroup)
+
+ override fun onMetadata(metadata: androidx.media3.common.Metadata) =
+ listener.onMetadata(metadata)
+
override fun onMediaMetadataChanged(mediaMetadata: MediaMetadata) {
listener.onMediaMetadataChanged(this@MetadataInjectingPlayer.mediaMetadata)
}
+3 -3
View File
@@ -6,7 +6,7 @@ settings:
patchedDependencies:
expo-audio@58.0.10:
hash: e01ad6e484db76d810c2df5bf9c376eccf8d4c5359736b626868ea8bd8dac566
hash: f7f102c0f17b28e763d828acd4f138d62809f5be576e316a13008c27e84968c5
path: patches/expo-audio@58.0.10.patch
importers:
@@ -63,7 +63,7 @@ importers:
version: 58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3)
expo-audio:
specifier: ~58.0.10
version: 58.0.10(patch_hash=e01ad6e484db76d810c2df5bf9c376eccf8d4c5359736b626868ea8bd8dac566)(expo-asset@58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3))(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)
version: 58.0.10(patch_hash=f7f102c0f17b28e763d828acd4f138d62809f5be576e316a13008c27e84968c5)(expo-asset@58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3))(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)
expo-blur:
specifier: ~58.0.5
version: 58.0.5(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)
@@ -11073,7 +11073,7 @@ snapshots:
- supports-color
- typescript
expo-audio@58.0.10(patch_hash=e01ad6e484db76d810c2df5bf9c376eccf8d4c5359736b626868ea8bd8dac566)(expo-asset@58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3))(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0):
expo-audio@58.0.10(patch_hash=f7f102c0f17b28e763d828acd4f138d62809f5be576e316a13008c27e84968c5)(expo-asset@58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3))(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0):
dependencies:
expo: 58.0.17(@babel/core@7.29.7)(@expo/dom-webview@58.0.2)(@expo/metro-runtime@58.0.15)(expo-router@58.0.25)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3)
expo-asset: 58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3)