diff --git a/components/playback-provider.tsx b/components/playback-provider.tsx index bf7d004..63caa2b 100644 --- a/components/playback-provider.tsx +++ b/components/playback-provider.tsx @@ -1,6 +1,17 @@ "use client" -import * as React from "react" +import { + useState, + useEffect, + useCallback, + useRef, + RefObject, + createContext, + useContext, + ReactNode, + useSyncExternalStore, + useMemo, +} from "react" import { useConvex, useMutation, useQuery } from "convex/react" import Hls from "hls.js" import { toast } from "sonner" @@ -56,7 +67,7 @@ type PlaybackContextValue = { dolbyAtmosSupported: boolean | null } -const PlaybackContext = React.createContext(null) +const PlaybackContext = createContext(null) const VOLUME_STORAGE_KEY = "otunes:volume" const DEFAULT_VOLUME = 80 @@ -124,16 +135,16 @@ function songLoadKey(songId: string, settings: PlaybackLoadSettings) { return `${songId}:${settings.preferAtmos}:${settings.playbackQuality}:${settings.useHls ? "hls" : "file"}` } -function destroyHlsInstance(hlsRef: React.MutableRefObject) { +function destroyHlsInstance(hlsRef: RefObject) { hlsRef.current?.destroy() hlsRef.current = null } function adoptPreloadedPlayback( mainAudio: HTMLAudioElement, - mainHlsRef: React.MutableRefObject, + mainHlsRef: RefObject, preloadAudio: HTMLAudioElement, - preloadHlsRef: React.MutableRefObject + preloadHlsRef: RefObject ) { const preloadHls = preloadHlsRef.current if (preloadHls) { @@ -153,7 +164,7 @@ type AudioSourceCleanup = () => void function loadAudioSource( audio: HTMLAudioElement, - hlsRef: React.MutableRefObject, + hlsRef: RefObject, songId: string, settings: PlaybackLoadSettings, onReady: () => void @@ -205,28 +216,28 @@ function loadAudioSource( } export function usePlayback() { - const context = React.useContext(PlaybackContext) + const context = useContext(PlaybackContext) if (!context) { throw new Error("usePlayback must be used within PlaybackProvider") } return context } -export function PlaybackProvider({ children }: { children: React.ReactNode }) { +export function PlaybackProvider({ children }: { children: ReactNode }) { const convex = useConvex() const user = useQuery(api.auth.currentUser) const playback = useQuery(api.playback.getPlaybackState) - const audioRef = React.useRef(null) - const hlsRef = React.useRef(null) - const preloadAudioRef = React.useRef(null) - const preloadHlsRef = React.useRef(null) - const loadedSongKeyRef = React.useRef(null) - const preloadedSongKeyRef = React.useRef(null) - const playbackErrorHandledRef = React.useRef(false) - const isPlayingRef = React.useRef(false) - const autoPlayNextRef = React.useRef(false) - const intentionalLoadRef = React.useRef(false) - const ignoreAudioSyncRef = React.useRef(false) + const audioRef = useRef(null) + const hlsRef = useRef(null) + const preloadAudioRef = useRef(null) + const preloadHlsRef = useRef(null) + const loadedSongKeyRef = useRef(null) + const preloadedSongKeyRef = useRef(null) + const playbackErrorHandledRef = useRef(false) + const isPlayingRef = useRef(false) + const autoPlayNextRef = useRef(false) + const intentionalLoadRef = useRef(false) + const ignoreAudioSyncRef = useRef(false) const playInOrderMutation = useMutation(api.playback.playInOrder) const playShuffledMutation = useMutation(api.playback.playShuffled) const addToQueueNextMutation = useMutation(api.playback.addToQueueNext) @@ -242,21 +253,29 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { 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 [queueOpen, setQueueOpen] = React.useState(false) - const [isPlaying, setIsPlaying] = React.useState(false) - const [currentTime, setCurrentTime] = React.useState(0) - const [duration, setDuration] = React.useState(0) - const [dolbyAtmosSupported, setDolbyAtmosSupported] = React.useState< + const progressRestoredForSongRef = useRef | null>(null) + const lastSavedProgressRef = useRef(-1) + const prevIsPlayingRef = useRef(false) + + const [queueOpen, setQueueOpen] = useState(false) + const [isPlaying, setIsPlaying] = useState(false) + const [currentTime, setCurrentTime] = useState(0) + const [duration, setDuration] = useState(0) + const [progressToRestore, setProgressToRestore] = useState( + null + ) + const [dolbyAtmosSupported, setDolbyAtmosSupported] = useState< boolean | null >(null) - const volume = React.useSyncExternalStore( + const volume = useSyncExternalStore( subscribeVolume, readStoredVolume, () => DEFAULT_VOLUME ) - const setVolume = React.useCallback((nextVolume: number) => { + const setVolume = useCallback((nextVolume: number) => { const clamped = Math.min(100, Math.max(0, Math.round(nextVolume))) try { @@ -275,12 +294,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { const nextQueueSongId = queueSongIds.length > 1 ? queueSongIds[1] : null - React.useEffect(() => { - setCurrentTime(0) - setDuration(currentSong?.durationSeconds ?? 0) - }, [currentSong?.id, currentSong?.durationSeconds]) - - const seekTo = React.useCallback( + const seekTo = useCallback( (seconds: number) => { const audio = audioRef.current if (!audio) { @@ -298,11 +312,107 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [duration] ) - React.useEffect(() => { + 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] + ) + + 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(() => { + if (progressToRestore === null || progressToRestore <= 0) { + return + } + + const audio = audioRef.current + if (!audio || !currentSong) { + return + } + + const applyProgress = () => { + const maxDuration = + Number.isFinite(audio.duration) && audio.duration > 0 + ? audio.duration + : progressToRestore + const clamped = Math.min(progressToRestore, maxDuration) + audio.currentTime = clamped + setCurrentTime(clamped) + setProgressToRestore(null) + } + + if (audio.readyState >= HTMLMediaElement.HAVE_METADATA) { + applyProgress() + return + } + + audio.addEventListener("loadedmetadata", applyProgress, { once: true }) + return () => { + audio.removeEventListener("loadedmetadata", applyProgress) + } + }, [progressToRestore, currentSong?.id]) + + useEffect(() => { + const audio = audioRef.current + if (!audio || !currentSong) { + return + } + + if (prevIsPlayingRef.current === isPlaying) { + return + } + + prevIsPlayingRef.current = isPlaying + saveProgress(audio.currentTime) + }, [isPlaying, currentSong?.id, saveProgress]) + + useEffect(() => { + if (!isPlaying || !currentSong) { + return + } + + const interval = window.setInterval(() => { + const audio = audioRef.current + if (!audio) { + return + } + + saveProgress(audio.currentTime) + }, 5000) + + return () => { + window.clearInterval(interval) + } + }, [isPlaying, currentSong?.id, saveProgress]) + + useEffect(() => { + setDuration(currentSong?.durationSeconds ?? 0) + }, [currentSong?.id, currentSong?.durationSeconds]) + + useEffect(() => { isPlayingRef.current = isPlaying }, [isPlaying]) - const runWithoutAudioSync = React.useCallback((fn: () => void) => { + const runWithoutAudioSync = useCallback((fn: () => void) => { ignoreAudioSyncRef.current = true try { fn() @@ -311,15 +421,15 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { } }, []) - const destroyHls = React.useCallback(() => { + const destroyHls = useCallback(() => { destroyHlsInstance(hlsRef) }, []) - const destroyPreloadHls = React.useCallback(() => { + const destroyPreloadHls = useCallback(() => { destroyHlsInstance(preloadHlsRef) }, []) - const clearPreload = React.useCallback(() => { + const clearPreload = useCallback(() => { const preloadAudio = preloadAudioRef.current destroyPreloadHls() preloadedSongKeyRef.current = null @@ -329,7 +439,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { } }, [destroyPreloadHls]) - React.useEffect(() => { + useEffect(() => { const audio = new Audio() const preloadAudio = new Audio() preloadAudio.preload = "auto" @@ -366,7 +476,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { } }, [destroyHls, destroyPreloadHls]) - React.useEffect(() => { + useEffect(() => { const audio = audioRef.current if (!audio) { return @@ -374,7 +484,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { audio.volume = volume / 100 }, [volume]) - const attemptPlayback = React.useCallback( + const attemptPlayback = useCallback( ( audio: HTMLAudioElement, expectedLoadKey: string, @@ -416,7 +526,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [] ) - React.useEffect(() => { + useEffect(() => { const audio = audioRef.current const preloadAudio = preloadAudioRef.current if (!audio) { @@ -502,7 +612,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { attemptPlayback, ]) - React.useEffect(() => { + useEffect(() => { const preloadAudio = preloadAudioRef.current if (!preloadAudio || !nextQueueSongId || !currentSong) { clearPreload() @@ -557,7 +667,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { destroyPreloadHls, ]) - React.useEffect(() => { + useEffect(() => { const audio = audioRef.current if (!audio || !currentSong) { return @@ -591,7 +701,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { } }, [isPlaying, currentSong, attemptPlayback]) - React.useEffect(() => { + useEffect(() => { const audio = audioRef.current if (!audio) { return @@ -710,7 +820,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { attemptPlayback, ]) - React.useEffect(() => { + useEffect(() => { const audio = audioRef.current if (!audio) { return @@ -741,7 +851,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { } }, [currentSong]) - const playInOrder = React.useCallback( + const playInOrder = useCallback( async (songIds: Id<"songs">[]) => { if (songIds.length === 0) { return @@ -752,7 +862,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [playInOrderMutation] ) - const playShuffled = React.useCallback( + const playShuffled = useCallback( async (songIds: Id<"songs">[]) => { if (songIds.length === 0) { return @@ -763,7 +873,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [playShuffledMutation] ) - const addToQueueNext = React.useCallback( + const addToQueueNext = useCallback( async (songIds: Id<"songs">[]) => { if (songIds.length === 0) { return @@ -774,7 +884,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [addToQueueNextMutation] ) - const addToQueueLast = React.useCallback( + const addToQueueLast = useCallback( async (songIds: Id<"songs">[]) => { if (songIds.length === 0) { return @@ -785,7 +895,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [addToQueueLastMutation] ) - const playFromSong = React.useCallback( + const playFromSong = useCallback( async (songId: Id<"songs">, songIds: Id<"songs">[]) => { await playFromSongMutation({ songId, songIds }) setIsPlaying(true) @@ -793,7 +903,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [playFromSongMutation] ) - const playFromLibrarySong = React.useCallback( + const playFromLibrarySong = useCallback( async ( songId: Id<"songs">, sort: { @@ -807,7 +917,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [playFromLibrarySongMutation] ) - const playAlbum = React.useCallback( + const playAlbum = useCallback( async (albumId: Id<"albums">) => { const songIds = await convex.query(api.playlists.getAlbumSongIds, { albumId, @@ -817,7 +927,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [convex, playInOrder] ) - const playAlbumShuffled = React.useCallback( + const playAlbumShuffled = useCallback( async (albumId: Id<"albums">) => { const songIds = await convex.query(api.playlists.getAlbumSongIds, { albumId, @@ -827,7 +937,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [convex, playShuffled] ) - const playArtist = React.useCallback( + const playArtist = useCallback( async (artistId: Id<"artists">) => { const songIds = await convex.query( api.playlists.getOrderedArtistSongIds, @@ -840,7 +950,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [convex, playInOrder] ) - const playArtistShuffled = React.useCallback( + const playArtistShuffled = useCallback( async (artistId: Id<"artists">) => { const songIds = await convex.query( api.playlists.getOrderedArtistSongIds, @@ -853,7 +963,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [convex, playShuffled] ) - const playPlaylist = React.useCallback( + const playPlaylist = useCallback( async (playlistId: Id<"playlists">) => { const songIds = await convex.query(api.playlists.getPlaylistSongIds, { playlistId, @@ -863,7 +973,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [convex, playInOrder] ) - const playPlaylistShuffled = React.useCallback( + const playPlaylistShuffled = useCallback( async (playlistId: Id<"playlists">) => { const songIds = await convex.query(api.playlists.getPlaylistSongIds, { playlistId, @@ -873,11 +983,11 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) { [convex, playShuffled] ) - const toggleQueueOpen = React.useCallback(() => { + const toggleQueueOpen = useCallback(() => { setQueueOpen((open) => !open) }, []) - const value = React.useMemo( + const value = useMemo( () => ({ queueSongIds: playback?.queueSongIds ?? [], currentSong: playback?.currentSong ?? null, diff --git a/convex/playback.ts b/convex/playback.ts index e3f2119..9daebda 100644 --- a/convex/playback.ts +++ b/convex/playback.ts @@ -305,7 +305,19 @@ export const reorderQueue = mutation({ args: { songIds: v.array(v.id("songs")) }, handler: async (ctx, { songIds }) => { const userId = await requireAuth(ctx) - await ctx.db.patch(userId, { songQueue: songIds }) + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + const queue = user.songQueue ?? [] + const currentSongChanged = + songIds.length > 0 && songIds[0] !== queue[0] + + await ctx.db.patch(userId, { + songQueue: songIds, + ...(currentSongChanged ? { currentSongProgress: 0 } : {}), + }) }, }) @@ -394,3 +406,33 @@ export const skipPrevious = mutation({ }) }, }) + +export const getSongProgress = query({ + args: {}, + handler: async (ctx) => { + const userId = await getAuthUserId(ctx) + if (userId === null) { + throw new ConvexError("User not logged in") + } + + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + return user.currentSongProgress ?? 0 + }, +}) + +export const updateSongProgress = mutation({ + args: { progressSeconds: v.number() }, + handler: async (ctx, args) => { + const userId = await requireAuth(ctx) + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + await ctx.db.patch(userId, { currentSongProgress: args.progressSeconds }) + }, +})