- Replace mobile placeholder with Expo Router app (tabs, playback, auth, library) - Move Convex backend to @otunes/convex for web and mobile reuse - Update web app imports and API routes to use shared package
522 lines
15 KiB
TypeScript
522 lines
15 KiB
TypeScript
import { Audio, AVPlaybackStatus } from "expo-av"
|
|
import { useConvex, useMutation, useQuery } from "convex/react"
|
|
import {
|
|
createContext,
|
|
useCallback,
|
|
useContext,
|
|
useEffect,
|
|
useMemo,
|
|
useRef,
|
|
useState,
|
|
type ReactNode,
|
|
} from "react"
|
|
import AsyncStorage from "@react-native-async-storage/async-storage"
|
|
|
|
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 { showError } from "@/lib/toast"
|
|
import type { PlaybackQuality } from "@/lib/urls"
|
|
import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/urls"
|
|
|
|
type RepeatMode = "none" | "once" | "always"
|
|
|
|
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
|
|
const VOLUME_STORAGE_KEY = "otunes:volume"
|
|
const DEFAULT_VOLUME = 0.8
|
|
|
|
type PlaybackContextValue = {
|
|
queueSongIds: Id<"songs">[]
|
|
queueHistorySongIds: Id<"songs">[]
|
|
currentSong: BrowseSong | null
|
|
shuffleEnabled: boolean
|
|
repeatEnabled: RepeatMode
|
|
isPlaying: boolean
|
|
volume: number
|
|
currentTime: number
|
|
duration: number
|
|
seekTo: (seconds: number) => void
|
|
setIsPlaying: (playing: boolean) => void
|
|
setVolume: (volume: number) => void
|
|
playInOrder: (songIds: Id<"songs">[]) => Promise<void>
|
|
playShuffled: (songIds: Id<"songs">[]) => Promise<void>
|
|
addToQueueNext: (songIds: Id<"songs">[]) => Promise<void>
|
|
addToQueueLast: (songIds: Id<"songs">[]) => Promise<void>
|
|
playFromSong: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
|
|
playFromLibrarySong: (
|
|
songId: Id<"songs">,
|
|
sort: {
|
|
sortKey: "title" | "artist" | "album"
|
|
sortDirection: "asc" | "desc"
|
|
}
|
|
) => Promise<void>
|
|
playAlbum: (albumId: Id<"albums">) => Promise<void>
|
|
playAlbumShuffled: (albumId: Id<"albums">) => Promise<void>
|
|
playArtist: (artistId: Id<"artists">) => Promise<void>
|
|
playArtistShuffled: (artistId: Id<"artists">) => Promise<void>
|
|
playPlaylist: (playlistId: Id<"playlists">) => Promise<void>
|
|
playPlaylistShuffled: (playlistId: Id<"playlists">) => Promise<void>
|
|
toggleShuffle: () => Promise<void>
|
|
cycleRepeat: () => Promise<void>
|
|
clearQueue: () => Promise<void>
|
|
reorderQueue: (songIds: Id<"songs">[]) => Promise<void>
|
|
skipToQueueIndex: (index: number) => Promise<void>
|
|
skipNext: () => Promise<void>
|
|
skipPrevious: () => Promise<void>
|
|
}
|
|
|
|
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) {
|
|
throw new Error("usePlayback must be used within PlaybackProvider")
|
|
}
|
|
return context
|
|
}
|
|
|
|
export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|
const convex = useConvex()
|
|
const { config } = useServerConfig()
|
|
const user = useQuery(api.auth.currentUser)
|
|
const playback = useQuery(api.playback.getPlaybackState)
|
|
|
|
const soundRef = useRef<Audio.Sound | null>(null)
|
|
const loadedSongIdRef = useRef<string | null>(null)
|
|
const autoPlayNextRef = useRef(false)
|
|
const isPlayingRef = useRef(false)
|
|
const progressRestoredForSongRef = useRef<Id<"songs"> | null>(null)
|
|
const lastSavedProgressRef = useRef(-1)
|
|
|
|
const [isPlaying, setIsPlayingState] = useState(false)
|
|
const [currentTime, setCurrentTime] = useState(0)
|
|
const [duration, setDuration] = useState(0)
|
|
const [volume, setVolumeState] = useState(DEFAULT_VOLUME)
|
|
const [progressToRestore, setProgressToRestore] = useState<number | null>(null)
|
|
|
|
const playInOrderMutation = useMutation(api.playback.playInOrder)
|
|
const playShuffledMutation = useMutation(api.playback.playShuffled)
|
|
const addToQueueNextMutation = useMutation(api.playback.addToQueueNext)
|
|
const addToQueueLastMutation = useMutation(api.playback.addToQueueLast)
|
|
const playFromSongMutation = useMutation(api.playback.playFromSong)
|
|
const playFromLibrarySongMutation = useMutation(
|
|
api.playback.playFromLibrarySong
|
|
)
|
|
const toggleShuffleMutation = useMutation(api.playback.toggleShuffle)
|
|
const cycleRepeatMutation = useMutation(api.playback.cycleRepeat)
|
|
const clearQueueMutation = useMutation(api.playback.clearQueue)
|
|
const reorderQueueMutation = useMutation(api.playback.reorderQueue)
|
|
const skipToQueueIndexMutation = useMutation(api.playback.skipToQueueIndex)
|
|
const skipNextMutation = useMutation(api.playback.skipNext)
|
|
const skipPreviousMutation = useMutation(api.playback.skipPrevious)
|
|
const updateSongProgressMutation = useMutation(api.playback.updateSongProgress)
|
|
|
|
const currentSong = playback?.currentSong ?? null
|
|
const repeatEnabled = playback?.repeatEnabled ?? "none"
|
|
const queueLength = playback?.queueSongIds.length ?? 0
|
|
|
|
useEffect(() => {
|
|
void Audio.setAudioModeAsync({
|
|
playsInSilentModeIOS: true,
|
|
staysActiveInBackground: true,
|
|
shouldDuckAndroid: true,
|
|
})
|
|
void AsyncStorage.getItem(VOLUME_STORAGE_KEY).then((stored) => {
|
|
if (stored) {
|
|
const parsed = Number(stored)
|
|
if (Number.isFinite(parsed)) {
|
|
setVolumeState(Math.min(1, Math.max(0, parsed)))
|
|
}
|
|
}
|
|
})
|
|
return () => {
|
|
void soundRef.current?.unloadAsync()
|
|
}
|
|
}, [])
|
|
|
|
const setIsPlaying = useCallback((playing: boolean) => {
|
|
isPlayingRef.current = playing
|
|
setIsPlayingState(playing)
|
|
const sound = soundRef.current
|
|
if (!sound) return
|
|
if (playing) {
|
|
void sound.playAsync()
|
|
} else {
|
|
void sound.pauseAsync()
|
|
}
|
|
}, [])
|
|
|
|
const setVolume = useCallback((nextVolume: number) => {
|
|
const clamped = Math.min(1, Math.max(0, nextVolume))
|
|
setVolumeState(clamped)
|
|
void AsyncStorage.setItem(VOLUME_STORAGE_KEY, String(clamped))
|
|
void soundRef.current?.setVolumeAsync(clamped)
|
|
}, [])
|
|
|
|
const seekTo = useCallback(
|
|
async (seconds: number) => {
|
|
const sound = soundRef.current
|
|
if (!sound) return
|
|
const clamped = Math.max(0, Math.min(seconds, duration || 0))
|
|
await sound.setPositionAsync(clamped * 1000)
|
|
setCurrentTime(clamped)
|
|
},
|
|
[duration]
|
|
)
|
|
|
|
const saveProgress = useCallback(
|
|
(seconds: number) => {
|
|
const progressSeconds = Math.max(0, Math.floor(seconds))
|
|
if (progressSeconds === lastSavedProgressRef.current) return
|
|
lastSavedProgressRef.current = progressSeconds
|
|
void updateSongProgressMutation({ progressSeconds })
|
|
},
|
|
[updateSongProgressMutation]
|
|
)
|
|
|
|
const onPlaybackStatusUpdate = useCallback(
|
|
(status: AVPlaybackStatus) => {
|
|
if (!status.isLoaded) return
|
|
setCurrentTime(status.positionMillis / 1000)
|
|
if (status.durationMillis) {
|
|
setDuration(status.durationMillis / 1000)
|
|
}
|
|
if (status.didJustFinish) {
|
|
if (repeatEnabled === "once") {
|
|
void soundRef.current?.setPositionAsync(0)
|
|
void soundRef.current?.playAsync()
|
|
return
|
|
}
|
|
const shouldContinue =
|
|
repeatEnabled !== "none" || queueLength > 1
|
|
if (shouldContinue) {
|
|
autoPlayNextRef.current = true
|
|
isPlayingRef.current = true
|
|
setIsPlayingState(true)
|
|
}
|
|
void skipNextMutation()
|
|
.then(() => {
|
|
if (shouldContinue) {
|
|
autoPlayNextRef.current = true
|
|
isPlayingRef.current = true
|
|
setIsPlayingState(true)
|
|
}
|
|
})
|
|
.catch(() => {
|
|
autoPlayNextRef.current = false
|
|
isPlayingRef.current = false
|
|
setIsPlayingState(false)
|
|
})
|
|
}
|
|
},
|
|
[repeatEnabled, queueLength, skipNextMutation]
|
|
)
|
|
|
|
useEffect(() => {
|
|
if (!currentSong || !playback) return
|
|
if (progressRestoredForSongRef.current === currentSong.id) return
|
|
progressRestoredForSongRef.current = currentSong.id
|
|
lastSavedProgressRef.current = -1
|
|
setProgressToRestore(playback.currentSongProgress ?? 0)
|
|
}, [currentSong?.id, playback])
|
|
|
|
useEffect(() => {
|
|
async function loadSong() {
|
|
if (!config || !currentSong || user === undefined || !user) {
|
|
if (!currentSong) {
|
|
loadedSongIdRef.current = null
|
|
await soundRef.current?.unloadAsync()
|
|
soundRef.current = null
|
|
}
|
|
return
|
|
}
|
|
|
|
const settings = playbackLoadSettings(user)
|
|
const loadKey = `${currentSong.id}:${settings.playbackQuality}:${settings.useHls ? "hls" : "file"}`
|
|
if (loadedSongIdRef.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
|
|
)
|
|
|
|
await soundRef.current?.unloadAsync()
|
|
const { sound } = await Audio.Sound.createAsync(
|
|
{ uri },
|
|
{
|
|
shouldPlay: isPlayingRef.current || autoPlayNextRef.current,
|
|
volume,
|
|
progressUpdateIntervalMillis: 500,
|
|
},
|
|
onPlaybackStatusUpdate
|
|
)
|
|
soundRef.current = sound
|
|
loadedSongIdRef.current = loadKey
|
|
|
|
if (progressToRestore && progressToRestore > 0) {
|
|
await sound.setPositionAsync(progressToRestore * 1000)
|
|
setProgressToRestore(null)
|
|
}
|
|
|
|
setDuration(currentSong.durationSeconds)
|
|
}
|
|
|
|
void loadSong().catch(() => {
|
|
showError("Could not play this track. The queue has been cleared.")
|
|
void clearQueueMutation()
|
|
setIsPlayingState(false)
|
|
})
|
|
}, [
|
|
config,
|
|
currentSong?.id,
|
|
user?.playbackQuality,
|
|
user?.preferAtmos,
|
|
user === undefined,
|
|
volume,
|
|
onPlaybackStatusUpdate,
|
|
clearQueueMutation,
|
|
progressToRestore,
|
|
currentSong,
|
|
user,
|
|
])
|
|
|
|
useEffect(() => {
|
|
if (!isPlaying || !currentSong) return
|
|
const interval = setInterval(() => {
|
|
saveProgress(currentTime)
|
|
}, 5000)
|
|
return () => clearInterval(interval)
|
|
}, [isPlaying, currentSong?.id, currentTime, saveProgress])
|
|
|
|
const playInOrder = useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) return
|
|
await playInOrderMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[playInOrderMutation, setIsPlaying]
|
|
)
|
|
|
|
const playShuffled = useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) return
|
|
await playShuffledMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[playShuffledMutation, setIsPlaying]
|
|
)
|
|
|
|
const addToQueueNext = useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) return
|
|
await addToQueueNextMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[addToQueueNextMutation, setIsPlaying]
|
|
)
|
|
|
|
const addToQueueLast = useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) return
|
|
await addToQueueLastMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[addToQueueLastMutation, setIsPlaying]
|
|
)
|
|
|
|
const playFromSong = useCallback(
|
|
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
|
|
await playFromSongMutation({ songId, songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[playFromSongMutation, setIsPlaying]
|
|
)
|
|
|
|
const playFromLibrarySong = useCallback(
|
|
async (
|
|
songId: Id<"songs">,
|
|
sort: {
|
|
sortKey: "title" | "artist" | "album"
|
|
sortDirection: "asc" | "desc"
|
|
}
|
|
) => {
|
|
await playFromLibrarySongMutation({ songId, ...sort })
|
|
setIsPlaying(true)
|
|
},
|
|
[playFromLibrarySongMutation, setIsPlaying]
|
|
)
|
|
|
|
const playAlbum = useCallback(
|
|
async (albumId: Id<"albums">) => {
|
|
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
|
albumId,
|
|
})
|
|
await playInOrder(songIds)
|
|
},
|
|
[convex, playInOrder]
|
|
)
|
|
|
|
const playAlbumShuffled = useCallback(
|
|
async (albumId: Id<"albums">) => {
|
|
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
|
albumId,
|
|
})
|
|
await playShuffled(songIds)
|
|
},
|
|
[convex, playShuffled]
|
|
)
|
|
|
|
const playArtist = useCallback(
|
|
async (artistId: Id<"artists">) => {
|
|
const songIds = await convex.query(
|
|
api.playlists.getOrderedArtistSongIds,
|
|
{ artistId }
|
|
)
|
|
await playInOrder(songIds)
|
|
},
|
|
[convex, playInOrder]
|
|
)
|
|
|
|
const playArtistShuffled = useCallback(
|
|
async (artistId: Id<"artists">) => {
|
|
const songIds = await convex.query(
|
|
api.playlists.getOrderedArtistSongIds,
|
|
{ artistId }
|
|
)
|
|
await playShuffled(songIds)
|
|
},
|
|
[convex, playShuffled]
|
|
)
|
|
|
|
const playPlaylist = useCallback(
|
|
async (playlistId: Id<"playlists">) => {
|
|
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
|
playlistId,
|
|
})
|
|
await playInOrderMutation({ songIds, playlistId })
|
|
setIsPlaying(true)
|
|
},
|
|
[convex, playInOrderMutation, setIsPlaying]
|
|
)
|
|
|
|
const playPlaylistShuffled = useCallback(
|
|
async (playlistId: Id<"playlists">) => {
|
|
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
|
playlistId,
|
|
})
|
|
await playShuffledMutation({ songIds, playlistId })
|
|
setIsPlaying(true)
|
|
},
|
|
[convex, playShuffledMutation, setIsPlaying]
|
|
)
|
|
|
|
const value = useMemo<PlaybackContextValue>(
|
|
() => ({
|
|
queueSongIds: playback?.queueSongIds ?? [],
|
|
queueHistorySongIds: playback?.queueHistorySongIds ?? [],
|
|
currentSong: playback?.currentSong ?? null,
|
|
shuffleEnabled: playback?.shuffleEnabled ?? false,
|
|
repeatEnabled: playback?.repeatEnabled ?? "none",
|
|
isPlaying: Boolean(currentSong && isPlaying),
|
|
volume,
|
|
currentTime,
|
|
duration,
|
|
seekTo,
|
|
setIsPlaying,
|
|
setVolume,
|
|
playInOrder,
|
|
playShuffled,
|
|
addToQueueNext,
|
|
addToQueueLast,
|
|
playFromSong,
|
|
playFromLibrarySong,
|
|
playAlbum,
|
|
playAlbumShuffled,
|
|
playArtist,
|
|
playArtistShuffled,
|
|
playPlaylist,
|
|
playPlaylistShuffled,
|
|
toggleShuffle: async () => {
|
|
await toggleShuffleMutation()
|
|
},
|
|
cycleRepeat: async () => {
|
|
await cycleRepeatMutation()
|
|
},
|
|
clearQueue: async () => {
|
|
await clearQueueMutation()
|
|
setIsPlaying(false)
|
|
},
|
|
reorderQueue: async (songIds) => {
|
|
await reorderQueueMutation({ songIds })
|
|
},
|
|
skipToQueueIndex: async (index) => {
|
|
await skipToQueueIndexMutation({ index })
|
|
},
|
|
skipNext: async () => {
|
|
await skipNextMutation()
|
|
},
|
|
skipPrevious: async () => {
|
|
if (currentTime > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
|
|
await seekTo(0)
|
|
return
|
|
}
|
|
await skipPreviousMutation()
|
|
},
|
|
}),
|
|
[
|
|
playback,
|
|
currentSong,
|
|
isPlaying,
|
|
volume,
|
|
currentTime,
|
|
duration,
|
|
seekTo,
|
|
setIsPlaying,
|
|
setVolume,
|
|
playInOrder,
|
|
playShuffled,
|
|
addToQueueNext,
|
|
addToQueueLast,
|
|
playFromSong,
|
|
playFromLibrarySong,
|
|
playAlbum,
|
|
playAlbumShuffled,
|
|
playArtist,
|
|
playArtistShuffled,
|
|
playPlaylist,
|
|
playPlaylistShuffled,
|
|
toggleShuffleMutation,
|
|
cycleRepeatMutation,
|
|
clearQueueMutation,
|
|
reorderQueueMutation,
|
|
skipToQueueIndexMutation,
|
|
skipNextMutation,
|
|
skipPreviousMutation,
|
|
]
|
|
)
|
|
|
|
return (
|
|
<PlaybackContext.Provider value={value}>{children}</PlaybackContext.Provider>
|
|
)
|
|
}
|