557 lines
15 KiB
TypeScript
557 lines
15 KiB
TypeScript
"use client"
|
|
|
|
import * as React from "react"
|
|
import { useConvex, useMutation, useQuery } from "convex/react"
|
|
import { toast } from "sonner"
|
|
|
|
import { api } from "@/convex/_generated/api"
|
|
import type { Id } from "@/convex/_generated/dataModel"
|
|
import type { BrowseSong } from "@/convex/library"
|
|
import { songPlayUrl } from "@/lib/song-play-url"
|
|
|
|
type RepeatMode = "none" | "once" | "always"
|
|
|
|
type PlaybackContextValue = {
|
|
queue: BrowseSong[]
|
|
currentSong: BrowseSong | null
|
|
shuffleEnabled: boolean
|
|
repeatEnabled: RepeatMode
|
|
queueOpen: boolean
|
|
isPlaying: boolean
|
|
volume: number
|
|
currentTime: number
|
|
duration: number
|
|
seekTo: (seconds: number) => void
|
|
setQueueOpen: (open: boolean) => void
|
|
toggleQueueOpen: () => 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>
|
|
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 = React.createContext<PlaybackContextValue | null>(null)
|
|
|
|
const VOLUME_STORAGE_KEY = "otunes:volume"
|
|
const DEFAULT_VOLUME = 80
|
|
|
|
const volumeListeners = new Set<() => void>()
|
|
|
|
function subscribeVolume(listener: () => void) {
|
|
volumeListeners.add(listener)
|
|
const onStorage = (event: StorageEvent) => {
|
|
if (event.key === null || event.key === VOLUME_STORAGE_KEY) {
|
|
listener()
|
|
}
|
|
}
|
|
window.addEventListener("storage", onStorage)
|
|
return () => {
|
|
volumeListeners.delete(listener)
|
|
window.removeEventListener("storage", onStorage)
|
|
}
|
|
}
|
|
|
|
function notifyVolumeChange() {
|
|
for (const listener of volumeListeners) {
|
|
listener()
|
|
}
|
|
}
|
|
|
|
function readStoredVolume(): number {
|
|
try {
|
|
const stored = localStorage.getItem(VOLUME_STORAGE_KEY)
|
|
if (stored === null) {
|
|
return DEFAULT_VOLUME
|
|
}
|
|
|
|
const parsed = Number(stored)
|
|
if (!Number.isFinite(parsed)) {
|
|
return DEFAULT_VOLUME
|
|
}
|
|
|
|
return Math.min(100, Math.max(0, Math.round(parsed)))
|
|
} catch {
|
|
return DEFAULT_VOLUME
|
|
}
|
|
}
|
|
|
|
export function usePlayback() {
|
|
const context = React.useContext(PlaybackContext)
|
|
if (!context) {
|
|
throw new Error("usePlayback must be used within PlaybackProvider")
|
|
}
|
|
return context
|
|
}
|
|
|
|
export function PlaybackProvider({ children }: { children: React.ReactNode }) {
|
|
const convex = useConvex()
|
|
const user = useQuery(api.auth.currentUser)
|
|
const playback = useQuery(api.playback.getPlaybackState)
|
|
const audioRef = React.useRef<HTMLAudioElement | null>(null)
|
|
const loadedSongIdRef = React.useRef<string | null>(null)
|
|
const playbackErrorHandledRef = React.useRef(false)
|
|
const isPlayingRef = React.useRef(false)
|
|
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 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 [queueOpen, setQueueOpen] = React.useState(false)
|
|
const [isPlaying, setIsPlaying] = React.useState(false)
|
|
const [currentTime, setCurrentTime] = React.useState(0)
|
|
const [duration, setDuration] = React.useState(0)
|
|
const volume = React.useSyncExternalStore(
|
|
subscribeVolume,
|
|
readStoredVolume,
|
|
() => DEFAULT_VOLUME
|
|
)
|
|
|
|
const setVolume = React.useCallback((nextVolume: number) => {
|
|
const clamped = Math.min(100, Math.max(0, Math.round(nextVolume)))
|
|
|
|
try {
|
|
localStorage.setItem(VOLUME_STORAGE_KEY, String(clamped))
|
|
notifyVolumeChange()
|
|
} catch {
|
|
// Ignore storage failures (private browsing, quota, etc.)
|
|
}
|
|
}, [])
|
|
|
|
const currentSong = playback?.currentSong ?? null
|
|
const isPlaybackActive = Boolean(currentSong && isPlaying)
|
|
const repeatEnabled = playback?.repeatEnabled ?? "none"
|
|
|
|
React.useEffect(() => {
|
|
setCurrentTime(0)
|
|
setDuration(currentSong?.durationSeconds ?? 0)
|
|
}, [currentSong?.id, currentSong?.durationSeconds])
|
|
|
|
const seekTo = React.useCallback((seconds: number) => {
|
|
const audio = audioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
|
|
const maxDuration =
|
|
Number.isFinite(audio.duration) && audio.duration > 0
|
|
? audio.duration
|
|
: duration
|
|
const clamped = Math.max(0, Math.min(seconds, maxDuration || 0))
|
|
audio.currentTime = clamped
|
|
setCurrentTime(clamped)
|
|
}, [duration])
|
|
|
|
React.useEffect(() => {
|
|
isPlayingRef.current = isPlaying
|
|
}, [isPlaying])
|
|
|
|
React.useEffect(() => {
|
|
const audio = new Audio()
|
|
audioRef.current = audio
|
|
|
|
return () => {
|
|
audio.pause()
|
|
audio.removeAttribute("src")
|
|
audioRef.current = null
|
|
loadedSongIdRef.current = null
|
|
}
|
|
}, [])
|
|
|
|
React.useEffect(() => {
|
|
const audio = audioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
audio.volume = volume / 100
|
|
}, [volume])
|
|
|
|
React.useEffect(() => {
|
|
const audio = audioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
|
|
if (!currentSong) {
|
|
audio.pause()
|
|
audio.removeAttribute("src")
|
|
loadedSongIdRef.current = null
|
|
return
|
|
}
|
|
|
|
if (user === undefined || !user) {
|
|
return
|
|
}
|
|
|
|
if (loadedSongIdRef.current === currentSong.id) {
|
|
return
|
|
}
|
|
|
|
const url = songPlayUrl(
|
|
currentSong.id,
|
|
user.playbackQuality ?? "medium",
|
|
user.preferAtmos ?? false
|
|
)
|
|
|
|
playbackErrorHandledRef.current = false
|
|
audio.pause()
|
|
|
|
const onCanPlay = () => {
|
|
audio.removeEventListener("canplay", onCanPlay)
|
|
if (isPlayingRef.current) {
|
|
void audio.play().catch(() => {
|
|
setIsPlaying(false)
|
|
})
|
|
}
|
|
}
|
|
|
|
audio.addEventListener("canplay", onCanPlay)
|
|
audio.src = url
|
|
audio.load()
|
|
loadedSongIdRef.current = currentSong.id
|
|
|
|
return () => {
|
|
audio.removeEventListener("canplay", onCanPlay)
|
|
}
|
|
}, [currentSong?.id, user === undefined])
|
|
|
|
React.useEffect(() => {
|
|
const audio = audioRef.current
|
|
if (!audio || !currentSong) {
|
|
return
|
|
}
|
|
|
|
if (!isPlaying) {
|
|
audio.pause()
|
|
return
|
|
}
|
|
|
|
if (audio.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA) {
|
|
void audio.play().catch(() => {
|
|
setIsPlaying(false)
|
|
})
|
|
return
|
|
}
|
|
|
|
const onCanPlay = () => {
|
|
audio.removeEventListener("canplay", onCanPlay)
|
|
if (isPlayingRef.current) {
|
|
void audio.play().catch(() => {
|
|
setIsPlaying(false)
|
|
})
|
|
}
|
|
}
|
|
|
|
audio.addEventListener("canplay", onCanPlay)
|
|
return () => {
|
|
audio.removeEventListener("canplay", onCanPlay)
|
|
}
|
|
}, [isPlaying, currentSong])
|
|
|
|
React.useEffect(() => {
|
|
const audio = audioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
|
|
const handleEnded = () => {
|
|
if (repeatEnabled === "once") {
|
|
audio.currentTime = 0
|
|
void audio.play()
|
|
return
|
|
}
|
|
|
|
void skipNextMutation()
|
|
}
|
|
|
|
const handleError = () => {
|
|
if (!currentSong || playbackErrorHandledRef.current) {
|
|
return
|
|
}
|
|
playbackErrorHandledRef.current = true
|
|
|
|
const { error } = audio
|
|
if (error) {
|
|
console.error("Audio playback error:", {
|
|
code: error.code,
|
|
message: error.message,
|
|
src: audio.src,
|
|
})
|
|
}
|
|
|
|
audio.pause()
|
|
audio.removeAttribute("src")
|
|
loadedSongIdRef.current = null
|
|
setIsPlaying(false)
|
|
|
|
toast.error("Playback error", {
|
|
description: "Could not play this track. The queue has been cleared.",
|
|
})
|
|
void clearQueueMutation()
|
|
}
|
|
|
|
audio.addEventListener("ended", handleEnded)
|
|
audio.addEventListener("error", handleError)
|
|
|
|
return () => {
|
|
audio.removeEventListener("ended", handleEnded)
|
|
audio.removeEventListener("error", handleError)
|
|
}
|
|
}, [repeatEnabled, currentSong, skipNextMutation, clearQueueMutation])
|
|
|
|
React.useEffect(() => {
|
|
const audio = audioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
|
|
const syncDuration = () => {
|
|
if (Number.isFinite(audio.duration) && audio.duration > 0) {
|
|
setDuration(audio.duration)
|
|
} else if (currentSong) {
|
|
setDuration(currentSong.durationSeconds)
|
|
}
|
|
}
|
|
|
|
const syncTime = () => {
|
|
setCurrentTime(audio.currentTime)
|
|
}
|
|
|
|
audio.addEventListener("timeupdate", syncTime)
|
|
audio.addEventListener("durationchange", syncDuration)
|
|
audio.addEventListener("loadedmetadata", syncDuration)
|
|
audio.addEventListener("seeked", syncTime)
|
|
|
|
return () => {
|
|
audio.removeEventListener("timeupdate", syncTime)
|
|
audio.removeEventListener("durationchange", syncDuration)
|
|
audio.removeEventListener("loadedmetadata", syncDuration)
|
|
audio.removeEventListener("seeked", syncTime)
|
|
}
|
|
}, [currentSong])
|
|
|
|
const playInOrder = React.useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) {
|
|
return
|
|
}
|
|
await playInOrderMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[playInOrderMutation]
|
|
)
|
|
|
|
const playShuffled = React.useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) {
|
|
return
|
|
}
|
|
await playShuffledMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[playShuffledMutation]
|
|
)
|
|
|
|
const addToQueueNext = React.useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) {
|
|
return
|
|
}
|
|
await addToQueueNextMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[addToQueueNextMutation]
|
|
)
|
|
|
|
const addToQueueLast = React.useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) {
|
|
return
|
|
}
|
|
await addToQueueLastMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[addToQueueLastMutation]
|
|
)
|
|
|
|
const playFromSong = React.useCallback(
|
|
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
|
|
await playFromSongMutation({ songId, songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[playFromSongMutation]
|
|
)
|
|
|
|
const playAlbum = React.useCallback(
|
|
async (albumId: Id<"albums">) => {
|
|
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
|
albumId,
|
|
})
|
|
await playInOrder(songIds)
|
|
},
|
|
[convex, playInOrder]
|
|
)
|
|
|
|
const playAlbumShuffled = React.useCallback(
|
|
async (albumId: Id<"albums">) => {
|
|
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
|
albumId,
|
|
})
|
|
await playShuffled(songIds)
|
|
},
|
|
[convex, playShuffled]
|
|
)
|
|
|
|
const playArtist = React.useCallback(
|
|
async (artistId: Id<"artists">) => {
|
|
const songIds = await convex.query(api.playlists.getOrderedArtistSongIds, {
|
|
artistId,
|
|
})
|
|
await playInOrder(songIds)
|
|
},
|
|
[convex, playInOrder]
|
|
)
|
|
|
|
const playArtistShuffled = React.useCallback(
|
|
async (artistId: Id<"artists">) => {
|
|
const songIds = await convex.query(api.playlists.getOrderedArtistSongIds, {
|
|
artistId,
|
|
})
|
|
await playShuffled(songIds)
|
|
},
|
|
[convex, playShuffled]
|
|
)
|
|
|
|
const playPlaylist = React.useCallback(
|
|
async (playlistId: Id<"playlists">) => {
|
|
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
|
playlistId,
|
|
})
|
|
await playInOrder(songIds)
|
|
},
|
|
[convex, playInOrder]
|
|
)
|
|
|
|
const playPlaylistShuffled = React.useCallback(
|
|
async (playlistId: Id<"playlists">) => {
|
|
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
|
playlistId,
|
|
})
|
|
await playShuffled(songIds)
|
|
},
|
|
[convex, playShuffled]
|
|
)
|
|
|
|
const toggleQueueOpen = React.useCallback(() => {
|
|
setQueueOpen((open) => !open)
|
|
}, [])
|
|
|
|
const value = React.useMemo<PlaybackContextValue>(
|
|
() => ({
|
|
queue: playback?.queue ?? [],
|
|
currentSong: playback?.currentSong ?? null,
|
|
shuffleEnabled: playback?.shuffleEnabled ?? false,
|
|
repeatEnabled: playback?.repeatEnabled ?? "none",
|
|
queueOpen,
|
|
isPlaying: isPlaybackActive,
|
|
volume,
|
|
currentTime,
|
|
duration,
|
|
seekTo,
|
|
setQueueOpen,
|
|
toggleQueueOpen,
|
|
setIsPlaying,
|
|
setVolume,
|
|
playInOrder,
|
|
playShuffled,
|
|
addToQueueNext,
|
|
addToQueueLast,
|
|
playFromSong,
|
|
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 () => {
|
|
await skipPreviousMutation()
|
|
},
|
|
}),
|
|
[
|
|
playback,
|
|
queueOpen,
|
|
isPlaybackActive,
|
|
volume,
|
|
currentTime,
|
|
duration,
|
|
seekTo,
|
|
toggleQueueOpen,
|
|
setVolume,
|
|
playInOrder,
|
|
playShuffled,
|
|
addToQueueNext,
|
|
addToQueueLast,
|
|
playFromSong,
|
|
playAlbum,
|
|
playAlbumShuffled,
|
|
playArtist,
|
|
playArtistShuffled,
|
|
playPlaylist,
|
|
playPlaylistShuffled,
|
|
toggleShuffleMutation,
|
|
cycleRepeatMutation,
|
|
clearQueueMutation,
|
|
reorderQueueMutation,
|
|
skipToQueueIndexMutation,
|
|
skipNextMutation,
|
|
skipPreviousMutation,
|
|
]
|
|
)
|
|
|
|
return (
|
|
<PlaybackContext.Provider value={value}>{children}</PlaybackContext.Provider>
|
|
)
|
|
}
|