From 9da758b19620430a27cb31ad7630aebfc66a844c Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Sat, 5 Sep 2026 16:35:37 -0400 Subject: [PATCH] perf: optimize app rendering and data loading (#18) - Virtualize mobile lists and defer queue loading - Split playback state from actions to reduce rerenders - Skip invalid or unnecessary Convex queries Reviewed-on: https://gitcoffee.dev/joshuafhiggins/otunes/pulls/18 --- apps/mobile/app/(app)/(tabs)/_layout.tsx | 7 +- .../app/(app)/(tabs)/home/album/[id].tsx | 160 +++-- .../app/(app)/(tabs)/home/artist/[id].tsx | 121 ++-- .../(app)/(tabs)/home/browse/playlists.tsx | 24 +- .../app/(app)/(tabs)/home/browse/songs.tsx | 4 +- .../app/(app)/(tabs)/home/playlist/[id].tsx | 114 +++- .../(app)/(tabs)/home/playlist/favorites.tsx | 91 ++- apps/mobile/app/(app)/(tabs)/home/queue.tsx | 71 +- .../mobile/app/(app)/(tabs)/home/settings.tsx | 185 ++++-- apps/mobile/app/(app)/(tabs)/search/index.tsx | 2 +- apps/mobile/app/server.tsx | 47 +- apps/mobile/components/cover-image.tsx | 2 +- apps/mobile/components/media-cards.tsx | 81 ++- apps/mobile/components/mini-player.tsx | 34 +- apps/mobile/components/search-results.tsx | 137 ++-- apps/mobile/contexts/add-to-playlist.tsx | 226 +++++-- apps/mobile/contexts/favorites.tsx | 146 +++- apps/mobile/contexts/playback.tsx | 520 +++++++++++---- apps/mobile/contexts/server-config.tsx | 35 +- apps/mobile/hooks/use-media-menu-actions.ts | 225 ++++--- apps/web/app/(app)/album/[id]/page.tsx | 21 +- apps/web/app/(app)/artist/[id]/page.tsx | 31 +- apps/web/app/(app)/layout.tsx | 4 +- .../app/(app)/library/artists/[id]/page.tsx | 11 +- apps/web/app/(app)/library/artists/page.tsx | 6 +- apps/web/app/(app)/page.tsx | 10 +- apps/web/app/(app)/playlist/[id]/page.tsx | 9 +- apps/web/app/(app)/recently-added/page.tsx | 2 +- apps/web/app/(app)/recently-played/page.tsx | 2 +- apps/web/app/(app)/search/page.tsx | 6 + .../[id]/play/hls/segment/[segment]/route.ts | 23 +- apps/web/app/layout.tsx | 10 +- .../components/add-to-playlist-provider.tsx | 81 ++- apps/web/components/album-view.tsx | 3 +- apps/web/components/app-sidebar.tsx | 19 +- apps/web/components/artist-view.tsx | 13 +- apps/web/components/artists-view.tsx | 2 +- apps/web/components/favorites-provider.tsx | 108 ++- apps/web/components/lazy-queue-panel.tsx | 15 + apps/web/components/options-modal.tsx | 36 +- apps/web/components/playback-provider.tsx | 310 ++++++--- apps/web/components/player-bar.tsx | 9 +- apps/web/components/playlist-view.tsx | 68 +- apps/web/components/queue-panel.tsx | 5 +- apps/web/components/search-song-item.tsx | 1 + .../web/components/search-top-result-card.tsx | 8 +- apps/web/components/songs-view.tsx | 5 +- apps/web/components/theme-toggle.tsx | 8 +- apps/web/components/ui/carousel.tsx | 11 +- apps/web/hooks/use-mobile.ts | 25 +- apps/web/hooks/use-mounted.ts | 15 + apps/web/lib/serve-cover.ts | 6 +- apps/web/lib/server-hls.ts | 73 +- apps/web/next.config.ts | 1 + packages/convex/convex/actions.ts | 212 +++--- packages/convex/convex/auth.ts | 49 +- packages/convex/convex/crons.ts | 10 +- packages/convex/convex/favorites.ts | 178 ++--- packages/convex/convex/library.ts | 623 +++++++++++------- packages/convex/convex/playback.ts | 168 ++++- packages/convex/convex/playlists.ts | 182 ++--- packages/convex/convex/schema.ts | 14 +- packages/convex/convex/types.ts | 2 - packages/convex/convex/users.ts | 97 ++- packages/convex/playback-stream.ts | 9 +- 65 files changed, 3130 insertions(+), 1603 deletions(-) create mode 100644 apps/web/components/lazy-queue-panel.tsx create mode 100644 apps/web/hooks/use-mounted.ts diff --git a/apps/mobile/app/(app)/(tabs)/_layout.tsx b/apps/mobile/app/(app)/(tabs)/_layout.tsx index efee656..12682ca 100644 --- a/apps/mobile/app/(app)/(tabs)/_layout.tsx +++ b/apps/mobile/app/(app)/(tabs)/_layout.tsx @@ -4,7 +4,7 @@ import { DynamicColorIOS, Platform, useColorScheme } from "react-native" import { useMemo } from "react" import { TabBottomAccessory } from "@/components/mini-player" -import { usePlayback } from "@/contexts/playback" +import { usePlaybackQueue } from "@/contexts/playback" import { appleMusic, colors } from "@/lib/theme" function useRouterTheme() { @@ -76,7 +76,7 @@ function useNativeTabColors() { export default function TabsLayout() { const routerTheme = useRouterTheme() const tabColors = useNativeTabColors() - const { currentSong, queueSongIds } = usePlayback() + const { currentSong, queueSongIds } = usePlaybackQueue() const showBottomAccessory = Boolean(currentSong && queueSongIds.length > 0) return ( @@ -84,8 +84,7 @@ export default function TabsLayout() { } : "skip" ) - const { playAlbum, playAlbumShuffled, playFromSong } = usePlayback() - const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } = useFavorites() - const { handleAlbumDetailAction, handleAlbumTrackAction, isAlbumFavorite: isAlbumFav } = - useMediaMenuActions() - const coverUri = config && album ? albumCoverUrl(config.serverUrl, album.id) : "" - const backgroundColor = useCoverBackgroundColor(coverUri, album?.cover != null, colors.background) + const { playAlbum, playAlbumShuffled, playFromSong } = usePlaybackActions() + const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } = + useFavorites() + const { + handleAlbumDetailAction, + handleAlbumTrackAction, + isAlbumFavorite: isAlbumFav, + } = useMediaMenuActions() + const coverUri = + config && album ? albumCoverUrl(config.serverUrl, album.id) : "" + const backgroundColor = useCoverBackgroundColor( + coverUri, + album?.cover != null, + colors.background + ) if (album === undefined || !config) { return ( @@ -72,7 +81,9 @@ export default function AlbumScreen() { ) } - const songIds = album.tracks.map((track: BrowseAlbumTrack) => track.id as Id<"songs">) + const songIds = album.tracks.map( + (track: BrowseAlbumTrack) => track.id as Id<"songs"> + ) const metadata = formatMetadata(album.genre, album.year) return ( @@ -87,67 +98,84 @@ export default function AlbumScreen() { favorited={isAlbumFav(album.id)} share={{ type: "album", albumId: album.id }} onAction={(action) => - void handleAlbumDetailAction(album.id as Id<"albums">, songIds, action) + void handleAlbumDetailAction( + album.id as Id<"albums">, + songIds, + action + ) } > - + ), }} /> - track.id} style={{ flex: 1, backgroundColor }} contentContainerStyle={{ paddingBottom: contentBottomInset }} contentInsetAdjustmentBehavior="automatic" - > - - - {album.title} - push(`/artist/${album.artist.id}`)}> - {album.artist.name} - - {metadata ? ( - {metadata} - ) : null} - - void toggleAlbumFavorite(album.id)} - hitSlop={8} - style={[styles.iconAction, { backgroundColor: colors.muted }]} - > - - - @@ -594,7 +610,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { isFavorites ? "Unfavorite" : "Remove from Playlist" } isActive={song.id === activeTrackId} - isSelected={isSelected(song.id)} selectionPosition={selectionPositions[index]} isFavorite={isSongFavorite(song.id)} selectedCount={ @@ -609,11 +624,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { setActiveTrackId(song.id) }} onToggleFavorite={() => { + const wasFavorite = isSongFavorite(song.id) void toggleSongFavorite(song.id as Id<"songs">) - if (isFavorites && isSongFavorite(song.id)) { - setSongs((current) => - current.filter((item) => item.id !== song.id) - ) + if (isFavorites && wasFavorite) { + setHiddenFavoriteIds((current) => { + const next = new Set(current) + next.add(song.id) + return next + }) } }} onPrepareContextMenu={() => prepareContextMenu(song.id)} diff --git a/apps/web/components/queue-panel.tsx b/apps/web/components/queue-panel.tsx index e0b4363..f255859 100644 --- a/apps/web/components/queue-panel.tsx +++ b/apps/web/components/queue-panel.tsx @@ -243,13 +243,14 @@ export function QueuePanel() { { initialNumItems: initialPageSize } ) - const queueSongs = results ?? [] + const queueSongs = React.useMemo(() => results ?? [], [results]) const selectableQueue = React.useMemo( () => toSelectableQueue(queueSongs), [queueSongs] ) const [dragIndex, setDragIndex] = React.useState(null) + const currentQueueSongId = queueSongIds[0] React.useEffect(() => { if (!queueOpen || queueSongIds.length === 0) { @@ -261,7 +262,7 @@ export function QueuePanel() { }) return () => cancelAnimationFrame(frame) - }, [queueOpen, queueSongIds[0]]) + }, [queueOpen, queueSongIds.length, currentQueueSongId]) React.useEffect(() => { if (!shouldPaginate) { diff --git a/apps/web/components/search-song-item.tsx b/apps/web/components/search-song-item.tsx index e8398f9..3023ab2 100644 --- a/apps/web/components/search-song-item.tsx +++ b/apps/web/components/search-song-item.tsx @@ -45,6 +45,7 @@ export function SearchSongItem({ song }: { song: BrowseSong }) { src={albumCoverUrl(song.album.id)} alt={song.album.title} fill + sizes="44px" className="object-cover" /> diff --git a/apps/web/components/search-top-result-card.tsx b/apps/web/components/search-top-result-card.tsx index 4299877..0d9065c 100644 --- a/apps/web/components/search-top-result-card.tsx +++ b/apps/web/components/search-top-result-card.tsx @@ -79,7 +79,13 @@ export function SearchTopResultCard({ result }: { result: TopResult }) { image.rounded ? "rounded-full" : "rounded-md" )} > - {image.alt} + {image.alt}

{resultTitle(result)}

diff --git a/apps/web/components/songs-view.tsx b/apps/web/components/songs-view.tsx index e32e933..e5de43f 100644 --- a/apps/web/components/songs-view.tsx +++ b/apps/web/components/songs-view.tsx @@ -88,7 +88,7 @@ function SongCover({ src={albumCoverUrl(song.album.id)} alt={song.album.title} fill - sizes="(max-width: 640px) 50vw, (max-width: 1024px) 25vw, 16vw" + sizes="40px" className="object-cover" />
@@ -111,7 +111,6 @@ function SongCover({ function SongRow({ song, - index, isSelected, selectionPosition, isFavorite, @@ -124,7 +123,6 @@ function SongRow({ onPlay, }: { song: BrowseSong - index: number isSelected: boolean selectionPosition: SelectionRangePosition isFavorite: boolean @@ -448,7 +446,6 @@ export function SongsView() { { - setMounted(true) - }, []) + const mounted = useMounted() const isDark = mounted && resolvedTheme === "dark" diff --git a/apps/web/components/ui/carousel.tsx b/apps/web/components/ui/carousel.tsx index 7bea93a..6ffa896 100644 --- a/apps/web/components/ui/carousel.tsx +++ b/apps/web/components/ui/carousel.tsx @@ -95,12 +95,19 @@ function Carousel({ React.useEffect(() => { if (!api) return - onSelect(api) api.on("reInit", onSelect) api.on("select", onSelect) + let active = true + queueMicrotask(() => { + if (active) { + onSelect(api) + } + }) return () => { - api?.off("select", onSelect) + active = false + api.off("reInit", onSelect) + api.off("select", onSelect) } }, [api, onSelect]) diff --git a/apps/web/hooks/use-mobile.ts b/apps/web/hooks/use-mobile.ts index 2b0fe1d..eaf1273 100644 --- a/apps/web/hooks/use-mobile.ts +++ b/apps/web/hooks/use-mobile.ts @@ -1,19 +1,18 @@ import * as React from "react" const MOBILE_BREAKPOINT = 768 +const MOBILE_QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)` + +function subscribe(listener: () => void) { + const mediaQuery = window.matchMedia(MOBILE_QUERY) + mediaQuery.addEventListener("change", listener) + return () => mediaQuery.removeEventListener("change", listener) +} + +function getSnapshot() { + return window.matchMedia(MOBILE_QUERY).matches +} export function useIsMobile() { - const [isMobile, setIsMobile] = React.useState(undefined) - - React.useEffect(() => { - const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`) - const onChange = () => { - setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) - } - mql.addEventListener("change", onChange) - setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) - return () => mql.removeEventListener("change", onChange) - }, []) - - return !!isMobile + return React.useSyncExternalStore(subscribe, getSnapshot, () => false) } diff --git a/apps/web/hooks/use-mounted.ts b/apps/web/hooks/use-mounted.ts new file mode 100644 index 0000000..79a18e5 --- /dev/null +++ b/apps/web/hooks/use-mounted.ts @@ -0,0 +1,15 @@ +"use client" + +import * as React from "react" + +const subscribe = () => () => {} +const getClientSnapshot = () => true +const getServerSnapshot = () => false + +export function useMounted() { + return React.useSyncExternalStore( + subscribe, + getClientSnapshot, + getServerSnapshot + ) +} diff --git a/apps/web/lib/serve-cover.ts b/apps/web/lib/serve-cover.ts index 59f2b73..550c394 100644 --- a/apps/web/lib/serve-cover.ts +++ b/apps/web/lib/serve-cover.ts @@ -8,6 +8,8 @@ export const PLACEHOLDER_PATH = path.join( ) const COVER_IMAGE_SIZES = new Set([64, 128, 192, 256, 384, 512, 768, 1024]) +const COVER_CACHE_CONTROL = + "public, max-age=300, stale-while-revalidate=86400" const MIME_TYPES: Record = { ".jpg": "image/jpeg", @@ -53,7 +55,7 @@ export async function serveCoverFile( return new Response(new Uint8Array(data), { headers: { "Content-Type": "image/webp", - "Cache-Control": "public, max-age=86400, immutable", + "Cache-Control": COVER_CACHE_CONTROL, }, }) } catch { @@ -66,7 +68,7 @@ export async function serveCoverFile( return new Response(data, { headers: { "Content-Type": contentTypeFor(coverPath), - "Cache-Control": "public, max-age=86400, immutable", + "Cache-Control": COVER_CACHE_CONTROL, }, }) } catch { diff --git a/apps/web/lib/server-hls.ts b/apps/web/lib/server-hls.ts index f22d375..df3b876 100644 --- a/apps/web/lib/server-hls.ts +++ b/apps/web/lib/server-hls.ts @@ -1,23 +1,27 @@ import type { Doc } from "@otunes/convex/_generated/dataModel" import crypto from "node:crypto" import fs from "node:fs/promises" -import os from "node:os" import path from "node:path" import { spawn } from "node:child_process" import * as music from "music-metadata" export const HLS_SEGMENT_SECONDS = 6 +const HLS_MAX_IDLE_MS = 30 * 60 * 1000 type HlsJob = { + key: string + lookupKey: string dir: string duration: number segmentCount: number - startedAt: number + lastTouchedAt: number processExited: boolean processExitCode: number | null } const jobs = new Map() +const jobsByLookup = new Map() +let lastCleanupAt = 0 export function qualityKbps(quality: string | null) { if (quality === "low") { @@ -50,6 +54,14 @@ function hlsCacheRoot() { return "/tmp/otunes" } +function hlsLookupKey( + songId: string, + quality: string | null, + preferAtmos: boolean +) { + return `${songId}:${quality ?? ""}:${preferAtmos ? "1" : "0"}` +} + async function hlsJobKey( song: Doc<"songs">, sourcePath: string, @@ -75,8 +87,44 @@ export function hlsSegmentPath(job: HlsJob, segmentIndex: number) { } async function touchHlsJob(job: HlsJob) { - const now = new Date() - await fs.utimes(job.dir, now, now).catch(() => {}) + job.lastTouchedAt = Date.now() + await fs.utimes(job.dir, new Date(job.lastTouchedAt), new Date(job.lastTouchedAt)).catch( + () => {} + ) +} + +function forgetJob(job: HlsJob) { + jobs.delete(job.key) + if (jobsByLookup.get(job.lookupKey) === job) { + jobsByLookup.delete(job.lookupKey) + } +} + +async function evictJob(job: HlsJob) { + forgetJob(job) + await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {}) +} + +async function cleanupIdleHlsJobs() { + const now = Date.now() + if (now - lastCleanupAt < 60_000) { + return + } + lastCleanupAt = now + + for (const job of [...jobs.values()]) { + if (now - job.lastTouchedAt > HLS_MAX_IDLE_MS) { + await evictJob(job) + } + } +} + +export function getExistingHlsJob( + songId: string, + quality: string | null, + preferAtmos: boolean +) { + return jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null } export async function waitForHlsSegment( @@ -114,15 +162,23 @@ export async function ensureHlsJob( quality: string | null, preferAtmos: boolean ) { + await cleanupIdleHlsJobs() + const kbps = qualityKbps(quality) const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos) const sourcePath = song.files[sourceCodec] const key = await hlsJobKey(song, sourcePath, kbps) + const lookupKey = hlsLookupKey(song._id, quality, preferAtmos) const existingJob = jobs.get(key) if (existingJob) { - await touchHlsJob(existingJob) - return existingJob + try { + await fs.access(existingJob.dir) + await touchHlsJob(existingJob) + return existingJob + } catch { + forgetJob(existingJob) + } } const metadata = await music.parseFile(sourcePath) @@ -132,14 +188,17 @@ export async function ensureHlsJob( await fs.mkdir(dir, { recursive: true }) const job: HlsJob = { + key, + lookupKey, dir, duration, segmentCount, - startedAt: Date.now(), + lastTouchedAt: Date.now(), processExited: false, processExitCode: null, } jobs.set(key, job) + jobsByLookup.set(lookupKey, job) await touchHlsJob(job) const ffmpegArgs = [ diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 5688811..3790c6a 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -5,6 +5,7 @@ const nextConfig: NextConfig = { output: "standalone", outputFileTracingRoot: path.join(__dirname, "../../"), images: { + minimumCacheTTL: 60, dangerouslyAllowSVG: true, contentDispositionType: "attachment", contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", diff --git a/packages/convex/convex/actions.ts b/packages/convex/convex/actions.ts index 878456b..6abfa86 100644 --- a/packages/convex/convex/actions.ts +++ b/packages/convex/convex/actions.ts @@ -1,6 +1,6 @@ "use node" -import { api } from "./_generated/api" +import { api, internal } from "./_generated/api" import * as fs from "node:fs/promises" import * as fsSync from "node:fs" @@ -9,7 +9,7 @@ import * as path from "node:path" import { ConvexError } from "convex/values" import type { Id } from "./_generated/dataModel" -import { action, type ActionCtx } from "./_generated/server" +import { action, internalAction, type ActionCtx } from "./_generated/server" const DATA_DIR = process.env.CONVEX_SITE_URL?.includes("127.0.0.1") ? "/Volumes/FastStorage/Apple Music" @@ -17,6 +17,13 @@ const DATA_DIR = process.env.CONVEX_SITE_URL?.includes("127.0.0.1") const HLS_CACHE_DIR = "/tmp/otunes" const HLS_MAX_IDLE_MS = 30 * 60 * 1000 +async function requireAdmin(ctx: ActionCtx) { + const user = await ctx.runQuery(api.auth.currentUser) + if (!user?.isAdmin) { + throw new ConvexError("Not authorized") + } +} + async function cleanHlsStreamsOlderThan(maxIdleMs: number) { const now = Date.now() let checked = 0 @@ -27,9 +34,10 @@ async function cleanHlsStreamsOlderThan(maxIdleMs: number) { try { entries = await fs.readdir(HLS_CACHE_DIR, { withFileTypes: true }) } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { throw error } + return { checked, removed, failed } } for (const entry of entries) { @@ -72,13 +80,16 @@ async function syncArtistCover( const onDisk = await coverPathIfExists(diskPath) if (onDisk !== null) { if (dbCover !== onDisk) { - await ctx.runMutation(api.library.updateArtistCover, { + await ctx.runMutation(internal.library.updateArtistCover, { id, cover: onDisk, }) } } else if (dbCover !== null && dbCover.includes(codec)) { - await ctx.runMutation(api.library.updateArtistCover, { id, cover: null }) + await ctx.runMutation(internal.library.updateArtistCover, { + id, + cover: null, + }) } } @@ -92,10 +103,16 @@ async function syncAlbumCover( const onDisk = await coverPathIfExists(diskPath) if (onDisk !== null) { if (dbCover !== onDisk) { - await ctx.runMutation(api.library.updateAlbumCover, { id, cover: onDisk }) + await ctx.runMutation(internal.library.updateAlbumCover, { + id, + cover: onDisk, + }) } } else if (dbCover !== null && dbCover.includes(codec)) { - await ctx.runMutation(api.library.updateAlbumCover, { id, cover: null }) + await ctx.runMutation(internal.library.updateAlbumCover, { + id, + cover: null, + }) } } @@ -103,27 +120,30 @@ async function purgeRemovedSongs(ctx: ActionCtx, ids: Id<"songs">[]) { if (ids.length === 0) { return } - await ctx.runMutation(api.library.purgeSongsFromUsersAndPlaylists, { ids }) + await ctx.runMutation(internal.library.purgeSongsFromUsersAndPlaylists, { + ids, + }) } async function purgeRemovedAlbums(ctx: ActionCtx, ids: Id<"albums">[]) { if (ids.length === 0) { return } - await ctx.runMutation(api.library.purgeAlbumsFromUsers, { ids }) + await ctx.runMutation(internal.library.purgeAlbumsFromUsers, { ids }) } async function purgeRemovedArtists(ctx: ActionCtx, ids: Id<"artists">[]) { if (ids.length === 0) { return } - await ctx.runMutation(api.library.purgeArtistsFromUsers, { ids }) + await ctx.runMutation(internal.library.purgeArtistsFromUsers, { ids }) } async function removeCodecFromDatabase(ctx: ActionCtx, codec: string) { - const allSongs = await ctx.runQuery(api.library.getSongs) + const allSongs = await ctx.runQuery(internal.library.getSongs) const songsToRemove: Id<"songs">[] = [] + const songsToUpdate: { id: Id<"songs">; files: Record }[] = [] for (const song of allSongs) { if (!(codec in song.files)) { continue @@ -133,44 +153,49 @@ async function removeCodecFromDatabase(ctx: ActionCtx, codec: string) { if (Object.keys(update).length === 0) { songsToRemove.push(song._id) } else { - await ctx.runMutation(api.library.changeFilesForSong, { + songsToUpdate.push({ id: song._id, files: update, }) } } + await ctx.runMutation(internal.library.changeFilesForSongs, { + songs: songsToUpdate, + }) await purgeRemovedSongs(ctx, songsToRemove) - await ctx.runMutation(api.library.removeSongs, { ids: songsToRemove }) + await ctx.runMutation(internal.library.removeSongs, { ids: songsToRemove }) - const allAlbums = await ctx.runQuery(api.library.getAlbums) - const albumsToRemove: Id<"albums">[] = [] - for (const album of allAlbums) { - const songsLeft = await ctx.runQuery(api.library.getSongsInAlbum, { - albumID: album._id, - }) - if (songsLeft.length === 0) { - albumsToRemove.push(album._id) - } - } + const allAlbums = await ctx.runQuery(internal.library.getAlbums) + const removedSongIds = new Set(songsToRemove) + const albumsWithSongs = new Set( + allSongs.flatMap((song) => + removedSongIds.has(song._id) ? [] : [song.album] + ) + ) + const albumsToRemove = allAlbums + .filter((album) => !albumsWithSongs.has(album._id)) + .map((album) => album._id) await purgeRemovedAlbums(ctx, albumsToRemove) - for (const albumId of albumsToRemove) { - await ctx.runMutation(api.library.removeAlbum, { id: albumId }) - } + await ctx.runMutation(internal.library.removeAlbums, { ids: albumsToRemove }) - const allArtists = await ctx.runQuery(api.library.getArtists) - for (const artist of allArtists) { - const albumsLeft = await ctx.runQuery(api.library.getAlbumsInArtist, { - artistID: artist._id, - }) - if (albumsLeft.length === 0) { - await purgeRemovedArtists(ctx, [artist._id]) - await ctx.runMutation(api.library.removeArtist, { id: artist._id }) - } - } + const allArtists = await ctx.runQuery(internal.library.getArtists) + const removedAlbumIds = new Set(albumsToRemove) + const artistsWithAlbums = new Set( + allAlbums.flatMap((album) => + removedAlbumIds.has(album._id) ? [] : [album.artist] + ) + ) + const artistsToRemove = allArtists + .filter((artist) => !artistsWithAlbums.has(artist._id)) + .map((artist) => artist._id) + await purgeRemovedArtists(ctx, artistsToRemove) + await ctx.runMutation(internal.library.removeArtists, { + ids: artistsToRemove, + }) } -export const updateLibrary = action({ +export const scheduledUpdateLibrary = internalAction({ args: {}, handler: async (ctx) => { const codecs = (await fs.readdir(DATA_DIR, { withFileTypes: true })) @@ -179,7 +204,7 @@ export const updateLibrary = action({ const dbCodecs = Array.from( new Map( - (await ctx.runQuery(api.library.getSongs)) + (await ctx.runQuery(internal.library.getSongs)) .map((song) => { return Object.keys(song.files) }) @@ -196,9 +221,9 @@ export const updateLibrary = action({ // Removals for (const codec of codecs) { - const dbArtists = await ctx.runQuery(api.library.getArtists) - const dbAlbums = await ctx.runQuery(api.library.getAlbums) - const dbSongs = await ctx.runQuery(api.library.getSongs) + const dbArtists = await ctx.runQuery(internal.library.getArtists) + const dbAlbums = await ctx.runQuery(internal.library.getAlbums) + const dbSongs = await ctx.runQuery(internal.library.getSongs) const dirtySongs = dbSongs .filter((song) => { @@ -218,43 +243,47 @@ export const updateLibrary = action({ const songsToDeleteIDs = songsToDelete.map((song) => song.id) await purgeRemovedSongs(ctx, songsToDeleteIDs) - await ctx.runMutation(api.library.removeSongs, { ids: songsToDeleteIDs }) - await ctx.runMutation(api.library.changeFilesForSongs, { + await ctx.runMutation(internal.library.removeSongs, { + ids: songsToDeleteIDs, + }) + await ctx.runMutation(internal.library.changeFilesForSongs, { songs: songsToUpdate, }) - const albumsToDelete = [] - for (const dbAlbum of dbAlbums) { - const songsLeft = await ctx.runQuery(api.library.getSongsInAlbum, { - albumID: dbAlbum._id, - }) - - if (songsLeft.length === 0) { - albumsToDelete.push(dbAlbum._id) - } - } + const deletedSongIds = new Set(songsToDeleteIDs) + const albumsWithSongs = new Set( + dbSongs.flatMap((song) => + deletedSongIds.has(song._id) ? [] : [song.album] + ) + ) + const albumsToDelete = dbAlbums + .filter((album) => !albumsWithSongs.has(album._id)) + .map((album) => album._id) await purgeRemovedAlbums(ctx, albumsToDelete) - await ctx.runMutation(api.library.removeAlbums, { ids: albumsToDelete }) + await ctx.runMutation(internal.library.removeAlbums, { + ids: albumsToDelete, + }) - const artistsToDelete = [] - for (const dbArtist of dbArtists) { - const artistsLeft = await ctx.runQuery(api.library.getAlbumsInArtist, { - artistID: dbArtist._id, - }) - - if (artistsLeft.length === 0) { - artistsToDelete.push(dbArtist._id) - } - } + const deletedAlbumIds = new Set(albumsToDelete) + const artistsWithAlbums = new Set( + dbAlbums.flatMap((album) => + deletedAlbumIds.has(album._id) ? [] : [album.artist] + ) + ) + const artistsToDelete = dbArtists + .filter((artist) => !artistsWithAlbums.has(artist._id)) + .map((artist) => artist._id) await purgeRemovedArtists(ctx, artistsToDelete) - await ctx.runMutation(api.library.removeArtists, { ids: artistsToDelete }) + await ctx.runMutation(internal.library.removeArtists, { + ids: artistsToDelete, + }) } // Additions for (const codec of codecs) { // Artists console.log(`${codec}: artists`) - let dbArtists = await ctx.runQuery(api.library.getArtists) + let dbArtists = await ctx.runQuery(internal.library.getArtists) const dbArtistFolders = dbArtists.map((artist) => artist.folder) const artists = ( await fs.readdir(`${DATA_DIR}/${codec}`, { withFileTypes: true }) @@ -312,21 +341,18 @@ export const updateLibrary = action({ } catch {} } } - await ctx.runMutation(api.library.createArtists, { + await ctx.runMutation(internal.library.createArtists, { artists: newArtists, }) - dbArtists = await ctx.runQuery(api.library.getArtists) + dbArtists = await ctx.runQuery(internal.library.getArtists) // Albums console.log(`${codec}: albums`) - let dbAlbums = await ctx.runQuery(api.library.getAlbums) + let dbAlbums = await ctx.runQuery(internal.library.getAlbums) const newAlbums = [] for (const dbArtist of dbArtists) { - const dbAlbumsInArtist = await ctx.runQuery( - api.library.getAlbumsInArtist, - { - artistID: dbArtist._id, - } + const dbAlbumsInArtist = dbAlbums.filter( + (album) => album.artist === dbArtist._id ) const dbAlbumFolders = dbAlbumsInArtist.map((album) => album.folder) @@ -379,16 +405,18 @@ export const updateLibrary = action({ folder: potentialAlbum, cover, year: metadata.common.year || 2026, - date: metadata.common.date || `01-01-${metadata.common.year || 2026}`, + date: + metadata.common.date || `01-01-${metadata.common.year || 2026}`, artist: dbArtist._id, }) } catch {} } } - await ctx.runMutation(api.library.createAlbums, { + await ctx.runMutation(internal.library.createAlbums, { albums: newAlbums, }) - dbAlbums = await ctx.runQuery(api.library.getAlbums) + dbAlbums = await ctx.runQuery(internal.library.getAlbums) + const dbSongs = await ctx.runQuery(internal.library.getSongs) const dbAlbumsArtists = dbAlbums.map((album) => { return { @@ -434,9 +462,9 @@ export const updateLibrary = action({ const newSongs = [] const updateSongs = [] for (const dbAlbum of dbAlbumsArtists) { - const dbSongsInAlbum = await ctx.runQuery(api.library.getSongsInAlbum, { - albumID: dbAlbum._id, - }) + const dbSongsInAlbum = dbSongs.filter( + (song) => song.album === dbAlbum._id + ) const dbAlreadyTracked = dbSongsInAlbum .filter((song) => codec in song.files) .map((song) => song.files[codec]) @@ -525,15 +553,17 @@ export const updateLibrary = action({ : metadata.common.disk.no, track: metadata.common.track.no || 0, year: metadata.common.year || 2026, - date: metadata.common.date || `01-01-${metadata.common.year || 2026}`, + date: + metadata.common.date || + `01-01-${metadata.common.year || 2026}`, genres: metadata.common.genre || [], }) } } catch {} } } - await ctx.runMutation(api.library.createSongs, { songs: newSongs }) - await ctx.runMutation(api.library.changeFilesForSongs, { + await ctx.runMutation(internal.library.createSongs, { songs: newSongs }) + await ctx.runMutation(internal.library.changeFilesForSongs, { songs: updateSongs, }) } @@ -542,7 +572,15 @@ export const updateLibrary = action({ }, }) -export const cleanupHlsStreams = action({ +export const updateLibrary = action({ + args: {}, + handler: async (ctx): Promise => { + await requireAdmin(ctx) + return ctx.runAction(internal.actions.scheduledUpdateLibrary) + }, +}) + +export const cleanupHlsStreams = internalAction({ args: {}, handler: async () => { return await cleanHlsStreamsOlderThan(HLS_MAX_IDLE_MS) @@ -552,11 +590,7 @@ export const cleanupHlsStreams = action({ export const adminCleanupHlsStreams = action({ args: {}, handler: async (ctx) => { - const user = await ctx.runQuery(api.auth.currentUser) - if (!user?.isAdmin) { - throw new ConvexError("Not authorized") - } - + await requireAdmin(ctx) return await cleanHlsStreamsOlderThan(HLS_MAX_IDLE_MS) }, }) diff --git a/packages/convex/convex/auth.ts b/packages/convex/convex/auth.ts index 83be786..870873e 100644 --- a/packages/convex/convex/auth.ts +++ b/packages/convex/convex/auth.ts @@ -2,6 +2,7 @@ import { convexAuth, getAuthUserId } from "@convex-dev/auth/server" import { ConvexError } from "convex/values" import { Password } from "@convex-dev/auth/providers/Password" import { query } from "./_generated/server" +import type { MutationCtx } from "./_generated/server" export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [ @@ -15,36 +16,34 @@ export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ }), ], callbacks: { - async afterUserCreatedOrUpdated(ctx, { userId, existingUserId }) { + async afterUserCreatedOrUpdated(ctx, { userId, existingUserId, profile }) { + const db = ctx.db as MutationCtx["db"] if (existingUserId === null) { - const settings = await ctx.db.query("appSettings").first() + const settings = await db.query("appSettings").first() if (settings?.disableAccountCreation) { - const sessions = await ctx.db + const sessions = await db .query("authSessions") - .filter((q) => q.eq(q.field("userId"), userId)) + .withIndex("userId", (q) => q.eq("userId", userId)) .collect() for (const session of sessions) { - await ctx.db.delete(session._id) + await db.delete(session._id) } - const accounts = await ctx.db + const accounts = await db .query("authAccounts") - .filter((q) => q.eq(q.field("userId"), userId)) + .withIndex("userIdAndProvider", (q) => q.eq("userId", userId)) .collect() for (const account of accounts) { - await ctx.db.delete(account._id) + await db.delete(account._id) } - await ctx.db.delete(userId) + await db.delete(userId) throw new ConvexError("Account creation is currently disabled") } - const users = await ctx.db.query("users").collect() - if (users.length === 1) { - await ctx.db.patch(userId, { isAdmin: true }) - } else { - await ctx.db.patch(userId, { isAdmin: false }) - } - - await ctx.db.patch(userId, { playbackQuality: "high" }) + const users = await db.query("users").take(2) + await db.patch(userId, { + isAdmin: users.length === 1 || profile.isAdmin === true, + playbackQuality: "high", + }) return } }, @@ -58,6 +57,20 @@ export const currentUser = query({ if (userId === null) { return null } - return await ctx.db.get(userId) + + const user = await ctx.db.get(userId) + if (!user) { + return null + } + + return { + _id: user._id, + name: user.name, + image: user.image, + email: user.email, + isAdmin: user.isAdmin, + playbackQuality: user.playbackQuality, + preferAtmos: user.preferAtmos, + } }, }) diff --git a/packages/convex/convex/crons.ts b/packages/convex/convex/crons.ts index 604dfea..d9e88f7 100644 --- a/packages/convex/convex/crons.ts +++ b/packages/convex/convex/crons.ts @@ -1,18 +1,12 @@ import { cronJobs } from "convex/server" -import { api } from "./_generated/api" +import { internal } from "./_generated/api" const crons = cronJobs() crons.interval( "update library file tracking", { minutes: 15 }, - api.actions.updateLibrary -) - -crons.interval( - "cleanup idle hls streams", - { minutes: 15 }, - api.actions.cleanupHlsStreams + internal.actions.scheduledUpdateLibrary ) export default crons diff --git a/packages/convex/convex/favorites.ts b/packages/convex/convex/favorites.ts index c4bfed3..ee5e79d 100644 --- a/packages/convex/convex/favorites.ts +++ b/packages/convex/convex/favorites.ts @@ -4,8 +4,8 @@ import { paginationOptsValidator } from "convex/server" import type { Doc, Id } from "./_generated/dataModel" import type { MutationCtx, QueryCtx } from "./_generated/server" import { mutation, query } from "./_generated/server" -import type { BrowsePlaylistDetail, BrowsePlaylistSummary, BrowseSong } from "./library" -import { paginateSlice } from "./library" +import type { BrowsePlaylistDetail, BrowsePlaylistSummary } from "./library" +import { browseSongsFromIds, paginateSlice } from "./library" function uniqueIds(ids: T[]): T[] { return [...new Set(ids)] @@ -103,65 +103,27 @@ async function cascadeUpFromSongs( const albumIds = new Set(songs.map((song) => song.album)) for (const albumId of albumIds) { - albums = await promoteAlbumIfAllSongsFavorited(ctx, favoriteSongs, albums, albumId) + albums = await promoteAlbumIfAllSongsFavorited( + ctx, + favoriteSongs, + albums, + albumId + ) } const artistIds = new Set(songs.map((song) => song.albumArtist)) for (const artistId of artistIds) { - artists = await promoteArtistIfAllAlbumsFavorited(ctx, albums, artists, artistId) + artists = await promoteArtistIfAllAlbumsFavorited( + ctx, + albums, + artists, + artistId + ) } return { favoriteAlbums: albums, favoriteArtists: artists } } -function toBrowseArtist(artist: Doc<"artists">) { - return { - id: artist._id, - name: artist.name, - photo: artist.cover, - } -} - -async function loadArtistMap(ctx: QueryCtx) { - const artists = await ctx.db.query("artists").collect() - return new Map(artists.map((artist) => [artist._id, artist])) -} - -async function loadAlbumMap(ctx: QueryCtx) { - const albums = await ctx.db.query("albums").collect() - return new Map(albums.map((album) => [album._id, album])) -} - -async function toBrowseSong( - ctx: QueryCtx, - songId: Id<"songs">, - artistMap: Map, Doc<"artists">>, - albumMap: Map, Doc<"albums">> -): Promise { - const song = await ctx.db.get("songs", songId) - if (!song) { - return null - } - - const album = albumMap.get(song.album) - const albumArtist = artistMap.get(song.albumArtist) - if (!album || !albumArtist) { - return null - } - - return { - id: song._id, - title: song.name, - artist: toBrowseArtist(albumArtist), - album: { - id: album._id, - title: album.name, - cover: album.cover, - }, - durationSeconds: Math.round(song.length), - } -} - export const getUserFavorites = query({ args: {}, handler: async (ctx) => { @@ -232,16 +194,7 @@ export const browseFavoritesPlaylistDetail = query({ return null } - const artistMap = await loadArtistMap(ctx) - const albumMap = await loadAlbumMap(ctx) - - const songs: BrowseSong[] = [] - for (const songId of summary.songIds) { - const song = await toBrowseSong(ctx, songId, artistMap, albumMap) - if (song) { - songs.push(song) - } - } + const songs = await browseSongsFromIds(ctx, summary.songIds) return { id: summary.id, @@ -265,16 +218,7 @@ export const browseFavoritesSongsPaginated = query({ } const slice = paginateSlice(summary.songIds, args.paginationOpts) - const artistMap = await loadArtistMap(ctx) - const albumMap = await loadAlbumMap(ctx) - - const page: BrowseSong[] = [] - for (const songId of slice.page) { - const song = await toBrowseSong(ctx, songId, artistMap, albumMap) - if (song) { - page.push(song) - } - } + const page = await browseSongsFromIds(ctx, slice.page) return { ...slice, @@ -323,15 +267,19 @@ export const favoriteSongs = mutation({ throw new ConvexError("User not found") } - const songs: Doc<"songs">[] = [] - for (const id of songIds) { - const song = await ctx.db.get("songs", id) - if (song) { - songs.push(song) - } - } + const uniqueRequestedIds = uniqueIds(songIds) + const loadedSongs = await Promise.all( + uniqueRequestedIds.map((id) => ctx.db.get("songs", id)) + ) + const songs = loadedSongs.filter( + (song): song is Doc<"songs"> => song !== null + ) + const validSongIds = songs.map((song) => song._id) - const favoriteSongs = uniqueIds([...(user.favoriteSongs ?? []), ...songIds]) + const favoriteSongs = uniqueIds([ + ...(user.favoriteSongs ?? []), + ...validSongIds, + ]) const cascaded = await cascadeUpFromSongs( ctx, favoriteSongs, @@ -351,48 +299,48 @@ export const favoriteSongs = mutation({ export const unfavoriteSong = mutation({ args: { songId: v.id("songs") }, handler: async (ctx, { songId }) => { - await unfavoriteSongHandler(ctx, songId) + await unfavoriteSongsHandler(ctx, [songId]) }, }) export const unfavoriteSongs = mutation({ args: { songIds: v.array(v.id("songs")) }, handler: async (ctx, { songIds }) => { - for (const songId of songIds) { - await unfavoriteSongHandler(ctx, songId) - } + await unfavoriteSongsHandler(ctx, songIds) }, }) -async function unfavoriteSongHandler(ctx: MutationCtx, songId: Id<"songs">) { +async function unfavoriteSongsHandler( + ctx: MutationCtx, + songIds: Id<"songs">[] +) { const userId = await requireAuth(ctx) const user = await ctx.db.get("users", userId) if (!user) { throw new ConvexError("User not found") } - const song = await ctx.db.get("songs", songId) - if (!song) { - return - } - - const favoriteSongs = (user.favoriteSongs ?? []).filter((id) => id !== songId) - let favoriteAlbums = user.favoriteAlbums ?? [] - let favoriteArtists = user.favoriteArtists ?? [] - - if (favoriteAlbums.includes(song.album)) { - favoriteAlbums = favoriteAlbums.filter((id) => id !== song.album) - } - - if (favoriteArtists.includes(song.albumArtist)) { - favoriteArtists = favoriteArtists.filter((id) => id !== song.albumArtist) - favoriteAlbums = favoriteAlbums.filter((id) => id !== song.album) - } + const removeSongs = new Set(songIds) + const loadedSongs = await Promise.all( + [...removeSongs].map((songId) => ctx.db.get("songs", songId)) + ) + const removeAlbums = new Set( + loadedSongs.flatMap((song) => (song ? [song.album] : [])) + ) + const removeArtists = new Set( + loadedSongs.flatMap((song) => (song ? [song.albumArtist] : [])) + ) await ctx.db.patch(userId, { - favoriteSongs, - favoriteAlbums, - favoriteArtists, + favoriteSongs: (user.favoriteSongs ?? []).filter( + (id) => !removeSongs.has(id) + ), + favoriteAlbums: (user.favoriteAlbums ?? []).filter( + (id) => !removeAlbums.has(id) + ), + favoriteArtists: (user.favoriteArtists ?? []).filter( + (id) => !removeArtists.has(id) + ), }) } @@ -446,8 +394,12 @@ export const unfavoriteAlbum = mutation({ const albumSongIds = await getSongIdsForAlbum(ctx, albumId) const removeSongs = new Set(albumSongIds) - const favoriteAlbums = (user.favoriteAlbums ?? []).filter((id) => id !== albumId) - const favoriteSongs = (user.favoriteSongs ?? []).filter((id) => !removeSongs.has(id)) + const favoriteAlbums = (user.favoriteAlbums ?? []).filter( + (id) => id !== albumId + ) + const favoriteSongs = (user.favoriteSongs ?? []).filter( + (id) => !removeSongs.has(id) + ) let favoriteArtists = user.favoriteArtists ?? [] if (favoriteArtists.includes(album.artist)) { @@ -502,9 +454,15 @@ export const unfavoriteArtist = mutation({ const removeSongs = new Set(songIds) await ctx.db.patch(userId, { - favoriteArtists: (user.favoriteArtists ?? []).filter((id) => id !== artistId), - favoriteAlbums: (user.favoriteAlbums ?? []).filter((id) => !removeAlbums.has(id)), - favoriteSongs: (user.favoriteSongs ?? []).filter((id) => !removeSongs.has(id)), + favoriteArtists: (user.favoriteArtists ?? []).filter( + (id) => id !== artistId + ), + favoriteAlbums: (user.favoriteAlbums ?? []).filter( + (id) => !removeAlbums.has(id) + ), + favoriteSongs: (user.favoriteSongs ?? []).filter( + (id) => !removeSongs.has(id) + ), }) }, }) diff --git a/packages/convex/convex/library.ts b/packages/convex/convex/library.ts index d53fa39..d3748e6 100644 --- a/packages/convex/convex/library.ts +++ b/packages/convex/convex/library.ts @@ -1,6 +1,6 @@ import { paginationOptsValidator } from "convex/server" import { getAuthUserId } from "@convex-dev/auth/server" -import { mutation, query } from "./_generated/server" +import { internalMutation, internalQuery, query } from "./_generated/server" import { v } from "convex/values" import type { Doc, Id } from "./_generated/dataModel" import type { QueryCtx } from "./_generated/server" @@ -113,6 +113,14 @@ async function loadArtistMap(ctx: QueryCtx) { return new Map(artists.map((artist) => [artist._id, artist])) } +async function loadArtistMapForIds(ctx: QueryCtx, artistIds: Id<"artists">[]) { + const ids = [...new Set(artistIds)] + const artists = await Promise.all(ids.map((id) => ctx.db.get("artists", id))) + return new Map( + artists.flatMap((artist) => (artist ? [[artist._id, artist] as const] : [])) + ) +} + function toBrowseArtist(artist: Doc<"artists">): BrowseArtist { return { id: artist._id, @@ -137,20 +145,36 @@ export async function browseSongsFromIds( ctx: QueryCtx, songIds: Id<"songs">[] ): Promise { - const songs: BrowseSong[] = [] - for (const songId of songIds) { - const song = await ctx.db.get("songs", songId) - if (!song) { - continue - } - const album = await ctx.db.get("albums", song.album) - const albumArtist = await ctx.db.get("artists", song.albumArtist) - if (!album || !albumArtist) { - continue - } - songs.push(toBrowseSong(song, album, albumArtist)) - } - return songs + const songs = await Promise.all( + songIds.map((songId) => ctx.db.get("songs", songId)) + ) + return browseSongDocs( + ctx, + songs.filter((song): song is Doc<"songs"> => song !== null) + ) +} + +async function browseSongDocs( + ctx: QueryCtx, + songs: Doc<"songs">[] +): Promise { + const albumIds = [...new Set(songs.map((song) => song.album))] + const albums = await Promise.all( + albumIds.map((albumId) => ctx.db.get("albums", albumId)) + ) + const albumMap = new Map( + albums.flatMap((album) => (album ? [[album._id, album] as const] : [])) + ) + const artistMap = await loadArtistMapForIds( + ctx, + songs.map((song) => song.albumArtist) + ) + + return songs.flatMap((song) => { + const album = albumMap.get(song.album) + const albumArtist = artistMap.get(song.albumArtist) + return album && albumArtist ? [toBrowseSong(song, album, albumArtist)] : [] + }) } function toBrowseSong( @@ -205,8 +229,7 @@ export function paginateSlice( paginationOpts: PaginationOptions ): PaginationResult { const cursor = paginationOpts.cursor - const start = - cursor && cursor.length > 0 ? Number.parseInt(cursor, 10) : 0 + const start = cursor && cursor.length > 0 ? Number.parseInt(cursor, 10) : 0 const safeStart = Number.isFinite(start) ? start : 0 const page = items.slice(safeStart, safeStart + paginationOpts.numItems) const next = safeStart + page.length @@ -237,12 +260,15 @@ export const browseArtistsPaginated = query({ export const browseAlbumsPaginated = query({ args: { paginationOpts: paginationOptsValidator }, handler: async (ctx, args) => { - const artistMap = await loadArtistMap(ctx) const result = await ctx.db .query("albums") .withIndex("by_name") .order("asc") .paginate(args.paginationOpts) + const artistMap = await loadArtistMapForIds( + ctx, + result.page.map((album) => album.artist) + ) return { ...result, @@ -289,7 +315,7 @@ export type SongsSortKey = "title" | "artist" | "album" export type SongsSortDirection = "asc" | "desc" type GroupedSongsCursor = { - groupIndex: number + groupCursor: string | null songIndex: number } @@ -302,25 +328,10 @@ function compareSongNames( return direction === "asc" ? comparison : -comparison } -function mapSongToBrowse( - song: Doc<"songs">, - artistMap: Map, Doc<"artists">>, - albumMap: Map, Doc<"albums">> -): BrowseSong | null { - const album = albumMap.get(song.album) - const albumArtist = artistMap.get(song.albumArtist) - if (!album || !albumArtist) { - return null - } - return toBrowseSong(song, album, albumArtist) -} - async function paginateSongsByTitle( ctx: QueryCtx, paginationOpts: PaginationOptions, - sortDirection: SongsSortDirection, - artistMap: Map, Doc<"artists">>, - albumMap: Map, Doc<"albums">> + sortDirection: SongsSortDirection ): Promise> { const result = await ctx.db .query("songs") @@ -330,10 +341,7 @@ async function paginateSongsByTitle( return { ...result, - page: result.page.flatMap((song) => { - const mapped = mapSongToBrowse(song, artistMap, albumMap) - return mapped ? [mapped] : [] - }), + page: await browseSongDocs(ctx, result.page), } } @@ -341,61 +349,83 @@ async function paginateSongsByGroup( ctx: QueryCtx, paginationOpts: PaginationOptions, sortDirection: SongsSortDirection, - artistMap: Map, Doc<"artists">>, - albumMap: Map, Doc<"albums">>, sortKey: "artist" | "album" ): Promise> { - const cursor: GroupedSongsCursor = paginationOpts.cursor - ? (JSON.parse(paginationOpts.cursor) as GroupedSongsCursor) - : { groupIndex: 0, songIndex: 0 } + let cursor: GroupedSongsCursor = { groupCursor: null, songIndex: 0 } + if (paginationOpts.cursor) { + const parsed = JSON.parse( + paginationOpts.cursor + ) as Partial + if ( + (typeof parsed.groupCursor === "string" || parsed.groupCursor === null) && + Number.isInteger(parsed.songIndex) && + (parsed.songIndex ?? -1) >= 0 + ) { + cursor = parsed as GroupedSongsCursor + } + } - const groups = - sortKey === "artist" - ? [...artistMap.values()].sort((a, b) => - compareSongNames(a.name, b.name, sortDirection) - ) - : [...albumMap.values()].sort((a, b) => - compareSongNames(a.name, b.name, sortDirection) - ) + const songDocs: Doc<"songs">[] = [] + let { groupCursor, songIndex } = cursor + let isDone = false - const page: BrowseSong[] = [] - let { groupIndex, songIndex } = cursor + while (songDocs.length < paginationOpts.numItems && !isDone) { + const groupResult = + sortKey === "artist" + ? await ctx.db + .query("artists") + .withIndex("by_name") + .order(sortDirection) + .paginate({ cursor: groupCursor, numItems: 1 }) + : await ctx.db + .query("albums") + .withIndex("by_name") + .order(sortDirection) + .paginate({ cursor: groupCursor, numItems: 1 }) + const group = groupResult.page[0] + if (!group) { + isDone = true + break + } - while (page.length < paginationOpts.numItems && groupIndex < groups.length) { - const group = groups[groupIndex] - const songs = await ctx.db - .query("songs") - .withIndex(sortKey === "artist" ? "by_artist" : "by_album", (q) => - sortKey === "artist" - ? q.eq("albumArtist", group._id as Id<"artists">) - : q.eq("album", group._id as Id<"albums">) - ) - .collect() + const songs = + sortKey === "artist" + ? await ctx.db + .query("songs") + .withIndex("by_artist", (q) => + q.eq("albumArtist", group._id as Id<"artists">) + ) + .collect() + : await ctx.db + .query("songs") + .withIndex("by_album", (q) => + q.eq("album", group._id as Id<"albums">) + ) + .collect() songs.sort((a, b) => compareSongNames(a.name, b.name, sortDirection)) - while (songIndex < songs.length && page.length < paginationOpts.numItems) { - const mapped = mapSongToBrowse(songs[songIndex], artistMap, albumMap) - if (mapped) { - page.push(mapped) - } + while ( + songIndex < songs.length && + songDocs.length < paginationOpts.numItems + ) { + songDocs.push(songs[songIndex]) songIndex++ } if (songIndex >= songs.length) { - groupIndex++ + groupCursor = groupResult.continueCursor || null songIndex = 0 + isDone = groupResult.isDone } } - const isDone = groupIndex >= groups.length - return { - page, + page: await browseSongDocs(ctx, songDocs), isDone, continueCursor: isDone ? "" - : JSON.stringify({ groupIndex, songIndex } satisfies GroupedSongsCursor), + : JSON.stringify({ groupCursor, songIndex } satisfies GroupedSongsCursor), } } @@ -413,38 +443,35 @@ export async function getSortedLibrarySongIds( return songs.map((song) => song._id) } - const artistMap = await loadArtistMap(ctx) - const albums = await ctx.db.query("albums").collect() - const albumMap = new Map(albums.map((album) => [album._id, album])) - - const groups = + const songs = await ctx.db.query("songs").collect() + const groupNames = sortKey === "artist" - ? [...artistMap.values()].sort((a, b) => - compareSongNames(a.name, b.name, sortDirection) + ? new Map( + [...(await loadArtistMap(ctx)).values()].map((artist) => [ + artist._id as string, + artist.name, + ]) ) - : [...albumMap.values()].sort((a, b) => - compareSongNames(a.name, b.name, sortDirection) + : new Map( + (await ctx.db.query("albums").collect()).map((album) => [ + album._id as string, + album.name, + ]) ) - - const songIds: Id<"songs">[] = [] - - for (const group of groups) { - const songs = await ctx.db - .query("songs") - .withIndex(sortKey === "artist" ? "by_artist" : "by_album", (q) => - sortKey === "artist" - ? q.eq("albumArtist", group._id as Id<"artists">) - : q.eq("album", group._id as Id<"albums">) - ) - .collect() - - songs.sort((a, b) => compareSongNames(a.name, b.name, sortDirection)) - for (const song of songs) { - songIds.push(song._id) - } - } - - return songIds + const validSongs = songs.filter((song) => + groupNames.has(sortKey === "artist" ? song.albumArtist : song.album) + ) + validSongs.sort((a, b) => { + const groupA = + groupNames.get(sortKey === "artist" ? a.albumArtist : a.album) ?? "" + const groupB = + groupNames.get(sortKey === "artist" ? b.albumArtist : b.album) ?? "" + return ( + compareSongNames(groupA, groupB, sortDirection) || + compareSongNames(a.name, b.name, sortDirection) + ) + }) + return validSongs.map((song) => song._id) } export const browseSongsPaginated = query({ @@ -454,26 +481,14 @@ export const browseSongsPaginated = query({ sortDirection: songsSortDirectionValidator, }, handler: async (ctx, args) => { - const artistMap = await loadArtistMap(ctx) - const albums = await ctx.db.query("albums").collect() - const albumMap = new Map(albums.map((album) => [album._id, album])) - if (args.sortKey === "title") { - return paginateSongsByTitle( - ctx, - args.paginationOpts, - args.sortDirection, - artistMap, - albumMap - ) + return paginateSongsByTitle(ctx, args.paginationOpts, args.sortDirection) } return paginateSongsByGroup( ctx, args.paginationOpts, args.sortDirection, - artistMap, - albumMap, args.sortKey ) }, @@ -482,11 +497,6 @@ export const browseSongsPaginated = query({ export const browseAlbumDetail = query({ args: { id: v.id("albums") }, handler: async (ctx, args): Promise => { - const summary = await browseAlbumSummaryHandler(ctx, args.id) - if (!summary) { - return null - } - const album = await ctx.db.get("albums", args.id) const artist = album ? await ctx.db.get("artists", album.artist) : null if (!album || !artist) { @@ -499,9 +509,13 @@ export const browseAlbumDetail = query({ .collect() songs.sort(compareAlbumSongs) + const primarySong = songs[0] return { - ...summary, + ...toBrowseAlbum(album, artist), + year: primarySong?.year ?? null, + genre: primarySong?.genres[0] ?? null, + releaseDate: album.date, tracks: songs.map((song) => toBrowseAlbumTrack(song, artist.name)), } }, @@ -584,19 +598,11 @@ export const browseArtistDetail = query({ .withIndex("by_artist", (q) => q.eq("artist", args.id)) .collect() - const recentlyAdded = [...albums] - .sort((a, b) => b._creationTime - a._creationTime) - .map((album) => toBrowseAlbum(album, artist)) - - const recentlyPlayed = [...albums] - .sort((a, b) => a.name.localeCompare(b.name)) - .map((album) => toBrowseAlbum(album, artist)) + albums.sort((a, b) => a.name.localeCompare(b.name)) return { artist: toBrowseArtist(artist), - albums: recentlyPlayed, - recentlyAdded, - recentlyPlayed, + albums: albums.map((album) => toBrowseAlbum(album, artist)), } }, }) @@ -732,40 +738,47 @@ export const searchLibrary = query({ }) export const browseRecentlyAdded = query({ - args: {}, - handler: async (ctx) => { - const artistMap = await loadArtistMap(ctx) - const albums = await ctx.db.query("albums").collect() + args: { limit: v.optional(v.number()) }, + handler: async (ctx, args) => { + const albumQuery = ctx.db.query("albums").order("desc") + const albums = args.limit + ? await albumQuery.take(args.limit) + : await albumQuery.collect() + const artistMap = await loadArtistMapForIds( + ctx, + albums.map((album) => album.artist) + ) - return albums - .flatMap((album) => { - const artist = artistMap.get(album.artist) - return artist ? [{ album, artist, addedAt: album._creationTime }] : [] - }) - .sort((a, b) => b.addedAt - a.addedAt) - .map(({ album, artist }) => toBrowseAlbum(album, artist)) + return albums.flatMap((album) => { + const artist = artistMap.get(album.artist) + return artist ? [toBrowseAlbum(album, artist)] : [] + }) }, }) export const browseRecentlyAddedPaginated = query({ args: { paginationOpts: paginationOptsValidator }, handler: async (ctx, args) => { - const artistMap = await loadArtistMap(ctx) - const albums = await ctx.db.query("albums").collect() + const result = await ctx.db + .query("albums") + .order("desc") + .paginate(args.paginationOpts) + const artistMap = await loadArtistMapForIds( + ctx, + result.page.map((album) => album.artist) + ) - const recentlyAdded = albums - .flatMap((album) => { + return { + ...result, + page: result.page.flatMap((album) => { const artist = artistMap.get(album.artist) - return artist ? [{ album, artist, addedAt: album._creationTime }] : [] - }) - .sort((a, b) => b.addedAt - a.addedAt) - .map(({ album, artist }) => toBrowseAlbum(album, artist)) - - return paginateSlice(recentlyAdded, args.paginationOpts) + return artist ? [toBrowseAlbum(album, artist)] : [] + }), + } }, }) -async function browseRecentlyPlayedItems(ctx: QueryCtx) { +async function browseRecentlyPlayedItems(ctx: QueryCtx, limit?: number) { const userId = await getAuthUserId(ctx) if (userId === null) { return [] @@ -776,50 +789,75 @@ async function browseRecentlyPlayedItems(ctx: QueryCtx) { return [] } - const recentlyPlayed = user.recentlyPlayed ?? [] + const recentlyPlayed = (user.recentlyPlayed ?? []).slice(0, limit) if (recentlyPlayed.length === 0) { return [] } - const artistMap = await loadArtistMap(ctx) - const items: (BrowseAlbum | PlaylistSummary)[] = [] + const loaded = await Promise.all( + recentlyPlayed.map(async (id) => { + const albumId = ctx.db.normalizeId("albums", id) + if (albumId !== null) { + const album = await ctx.db.get("albums", albumId) + return album ? ({ kind: "album", album } as const) : null + } - for (const id of recentlyPlayed) { - const albumId = ctx.db.normalizeId("albums", id) - if (albumId !== null) { - const album = await ctx.db.get("albums", albumId) - if (album) { - const artist = artistMap.get(album.artist) - if (artist) { - items.push(toBrowseAlbum(album, artist)) - } + const playlistId = ctx.db.normalizeId("playlists", id) + if (playlistId === null) { + return null + } + + const playlist = await ctx.db.get("playlists", playlistId) + return playlist ? ({ kind: "playlist", playlist } as const) : null + }) + ) + + const artistMap = await loadArtistMapForIds( + ctx, + loaded.flatMap((entry) => + entry?.kind === "album" ? [entry.album.artist] : [] + ) + ) + const ownerIds = [ + ...new Set( + loaded.flatMap((entry) => + entry?.kind === "playlist" ? [entry.playlist.owner] : [] + ) + ), + ] + const owners = await Promise.all( + ownerIds.map((ownerId) => ctx.db.get("users", ownerId)) + ) + const ownerMap = new Map( + owners.flatMap((owner) => (owner ? [[owner._id, owner] as const] : [])) + ) + + const items: (BrowseAlbum | PlaylistSummary)[] = [] + for (const entry of loaded) { + if (!entry) { + continue + } + if (entry.kind === "album") { + const artist = artistMap.get(entry.album.artist) + if (artist) { + items.push(toBrowseAlbum(entry.album, artist)) } continue } - - const playlistId = ctx.db.normalizeId("playlists", id) - if (playlistId === null) { - continue - } - - const playlist = await ctx.db.get("playlists", playlistId) - if (playlist) { - const owner = await ctx.db.get("users", playlist.owner) - items.push({ - id: playlist._id, - title: playlist.name, - owner: owner?.name ?? "Unknown", - cover: playlist.cover, - }) - } + items.push({ + id: entry.playlist._id, + title: entry.playlist.name, + owner: ownerMap.get(entry.playlist.owner)?.name ?? "Unknown", + cover: entry.playlist.cover, + }) } return items } export const browseRecentlyPlayed = query({ - args: {}, - handler: async (ctx) => browseRecentlyPlayedItems(ctx), + args: { limit: v.optional(v.number()) }, + handler: async (ctx, args) => browseRecentlyPlayedItems(ctx, args.limit), }) export const browseRecentlyPlayedPaginated = query({ @@ -830,21 +868,21 @@ export const browseRecentlyPlayedPaginated = query({ }, }) -export const getArtists = query({ +export const getArtists = internalQuery({ args: {}, handler: async (ctx) => { return await ctx.db.query("artists").collect() }, }) -export const getAlbums = query({ +export const getAlbums = internalQuery({ args: {}, handler: async (ctx) => { return await ctx.db.query("albums").collect() }, }) -export const getAlbumsInArtist = query({ +export const getAlbumsInArtist = internalQuery({ args: { artistID: v.id("artists") }, handler: async (ctx, args) => { return await ctx.db @@ -854,14 +892,14 @@ export const getAlbumsInArtist = query({ }, }) -export const getSongs = query({ +export const getSongs = internalQuery({ args: {}, handler: async (ctx) => { return await ctx.db.query("songs").collect() }, }) -export const getSongsInArtist = query({ +export const getSongsInArtist = internalQuery({ args: { artistID: v.id("artists") }, handler: async (ctx, args) => { return await ctx.db @@ -871,7 +909,7 @@ export const getSongsInArtist = query({ }, }) -export const getSongsInAlbum = query({ +export const getSongsInAlbum = internalQuery({ args: { albumID: v.id("albums") }, handler: async (ctx, args) => { return await ctx.db @@ -888,7 +926,7 @@ export const getArtist = query({ }, }) -export const getArtistByName = query({ +export const getArtistByName = internalQuery({ args: { name: v.string() }, handler: async (ctx, args) => { return await ctx.db @@ -905,7 +943,7 @@ export const getAlbum = query({ }, }) -export const getAlbumByName = query({ +export const getAlbumByName = internalQuery({ args: { name: v.string() }, handler: async (ctx, args) => { return await ctx.db @@ -915,15 +953,13 @@ export const getAlbumByName = query({ }, }) -export const getAlbumByAll = query({ +export const getAlbumByAll = internalQuery({ args: { folder: v.string(), artist: v.id("artists") }, handler: async (ctx, args) => { return await ctx.db .query("albums") .withIndex("by_all", (q) => - q - .eq("artist", args.artist) - .eq("folder", args.folder) + q.eq("artist", args.artist).eq("folder", args.folder) ) .first() }, @@ -943,9 +979,38 @@ export const getSong = query({ }, }) +function playbackCodecMap(files: Record) { + return Object.fromEntries(Object.keys(files).map((codec) => [codec, true])) +} + +export const getSongPlaybackInfo = query({ + args: { id: v.id("songs") }, + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx) + if (userId === null) { + return null + } + + const song = await ctx.db.get("songs", args.id) + if (!song) { + return null + } + + return { + id: song._id, + files: playbackCodecMap(song.files), + } + }, +}) + export const getSongsForPlayback = query({ args: { ids: v.array(v.id("songs")) }, handler: async (ctx, { ids }) => { + const userId = await getAuthUserId(ctx) + if (userId === null) { + return ids.map(() => null) + } + const songs = await Promise.all(ids.map((id) => ctx.db.get(id))) return songs.map((song, index) => { if (!song) { @@ -954,13 +1019,13 @@ export const getSongsForPlayback = query({ return { id: ids[index], title: song.name, - files: song.files, + files: playbackCodecMap(song.files), } }) }, }) -export const getSongByName = query({ +export const getSongByName = internalQuery({ args: { name: v.string() }, handler: async (ctx, args) => { return await ctx.db @@ -970,7 +1035,7 @@ export const getSongByName = query({ }, }) -export const getSongByAll = query({ +export const getSongByAll = internalQuery({ args: { name: v.string(), albumArtist: v.id("artists"), @@ -989,27 +1054,45 @@ export const getSongByAll = query({ }, }) -export const createArtist = mutation({ +export const createArtist = internalMutation({ args: { name: v.string(), folder: v.string(), cover: v.nullable(v.string()) }, handler: async (ctx, args) => { + const existing = await ctx.db + .query("artists") + .withIndex("by_folder", (q) => q.eq("folder", args.folder)) + .first() + if (existing) { + return existing._id + } return await ctx.db.insert("artists", args) }, }) -export const createArtists = mutation({ +export const createArtists = internalMutation({ args: { artists: v.array( - v.object({ name: v.string(), folder: v.string(), cover: v.nullable(v.string()) }) + v.object({ + name: v.string(), + folder: v.string(), + cover: v.nullable(v.string()), + }) ), }, handler: async (ctx, args) => { for (const artist of args.artists) { + const existing = await ctx.db + .query("artists") + .withIndex("by_folder", (q) => q.eq("folder", artist.folder)) + .first() + if (existing) { + continue + } await ctx.db.insert("artists", artist) } }, }) -export const createAlbum = mutation({ +export const createAlbum = internalMutation({ args: { name: v.string(), folder: v.string(), @@ -1019,11 +1102,20 @@ export const createAlbum = mutation({ artist: v.id("artists"), }, handler: async (ctx, args) => { + const existing = await ctx.db + .query("albums") + .withIndex("by_all", (q) => + q.eq("artist", args.artist).eq("folder", args.folder) + ) + .first() + if (existing) { + return existing._id + } return await ctx.db.insert("albums", args) }, }) -export const createAlbums = mutation({ +export const createAlbums = internalMutation({ args: { albums: v.array( v.object({ @@ -1038,12 +1130,21 @@ export const createAlbums = mutation({ }, handler: async (ctx, args) => { for (const album of args.albums) { + const existing = await ctx.db + .query("albums") + .withIndex("by_all", (q) => + q.eq("artist", album.artist).eq("folder", album.folder) + ) + .first() + if (existing) { + continue + } await ctx.db.insert("albums", album) } }, }) -export const updateAlbumName = mutation({ +export const updateAlbumName = internalMutation({ args: { id: v.id("albums"), newName: v.string(), @@ -1053,7 +1154,7 @@ export const updateAlbumName = mutation({ }, }) -export const createSong = mutation({ +export const createSong = internalMutation({ args: { name: v.string(), files: v.record(v.string(), v.string()), @@ -1068,11 +1169,26 @@ export const createSong = mutation({ genres: v.array(v.string()), }, handler: async (ctx, args) => { + const existing = await ctx.db + .query("songs") + .withIndex("by_all", (q) => + q + .eq("name", args.name) + .eq("albumArtist", args.albumArtist) + .eq("album", args.album) + ) + .first() + if (existing) { + await ctx.db.patch(existing._id, { + files: { ...existing.files, ...args.files }, + }) + return existing._id + } return await ctx.db.insert("songs", args) }, }) -export const createSongs = mutation({ +export const createSongs = internalMutation({ args: { songs: v.array( v.object({ @@ -1092,6 +1208,21 @@ export const createSongs = mutation({ }, handler: async (ctx, args) => { for (const song of args.songs) { + const existing = await ctx.db + .query("songs") + .withIndex("by_all", (q) => + q + .eq("name", song.name) + .eq("albumArtist", song.albumArtist) + .eq("album", song.album) + ) + .first() + if (existing) { + await ctx.db.patch(existing._id, { + files: { ...existing.files, ...song.files }, + }) + continue + } await ctx.db.insert("songs", song) } @@ -1099,7 +1230,7 @@ export const createSongs = mutation({ }, }) -export const purgeSongsFromUsersAndPlaylists = mutation({ +export const purgeSongsFromUsersAndPlaylists = internalMutation({ args: { ids: v.array(v.id("songs")) }, handler: async (ctx, args) => { const remove = new Set(args.ids) @@ -1117,16 +1248,40 @@ export const purgeSongsFromUsersAndPlaylists = mutation({ for (const user of await ctx.db.query("users").collect()) { const favoriteSongs = user.favoriteSongs + const songQueue = user.songQueue + const queueHistory = user.queueHistory + const patch: Partial< + Pick< + Doc<"users">, + "favoriteSongs" | "songQueue" | "queueHistory" | "currentSongProgress" + > + > = {} + if (favoriteSongs?.some((songId) => remove.has(songId))) { - await ctx.db.patch(user._id, { - favoriteSongs: favoriteSongs.filter((songId) => !remove.has(songId)), - }) + patch.favoriteSongs = favoriteSongs.filter( + (songId) => !remove.has(songId) + ) + } + if (songQueue?.some((songId) => remove.has(songId))) { + const currentRemoved = remove.has(songQueue[0]) + patch.songQueue = songQueue.filter((songId) => !remove.has(songId)) + if (currentRemoved) { + patch.currentSongProgress = 0 + } + } + if (queueHistory?.some((songId) => remove.has(songId))) { + patch.queueHistory = queueHistory.filter( + (songId) => !remove.has(songId) + ) + } + if (Object.keys(patch).length > 0) { + await ctx.db.patch(user._id, patch) } } }, }) -export const purgeAlbumsFromUsers = mutation({ +export const purgeAlbumsFromUsers = internalMutation({ args: { ids: v.array(v.id("albums")) }, handler: async (ctx, args) => { const remove = new Set(args.ids) @@ -1136,18 +1291,30 @@ export const purgeAlbumsFromUsers = mutation({ for (const user of await ctx.db.query("users").collect()) { const favoriteAlbums = user.favoriteAlbums + const recentlyPlayed = user.recentlyPlayed + const patch: Partial< + Pick, "favoriteAlbums" | "recentlyPlayed"> + > = {} if (favoriteAlbums?.some((albumId) => remove.has(albumId))) { - await ctx.db.patch(user._id, { - favoriteAlbums: favoriteAlbums.filter( - (albumId) => !remove.has(albumId) - ), - }) + patch.favoriteAlbums = favoriteAlbums.filter( + (albumId) => !remove.has(albumId) + ) + } + if ( + recentlyPlayed?.some((itemId) => remove.has(itemId as Id<"albums">)) + ) { + patch.recentlyPlayed = recentlyPlayed.filter( + (itemId) => !remove.has(itemId as Id<"albums">) + ) + } + if (Object.keys(patch).length > 0) { + await ctx.db.patch(user._id, patch) } } }, }) -export const purgeArtistsFromUsers = mutation({ +export const purgeArtistsFromUsers = internalMutation({ args: { ids: v.array(v.id("artists")) }, handler: async (ctx, args) => { const remove = new Set(args.ids) @@ -1168,14 +1335,14 @@ export const purgeArtistsFromUsers = mutation({ }, }) -export const removeArtist = mutation({ +export const removeArtist = internalMutation({ args: { id: v.id("artists") }, handler: async (ctx, args) => { return await ctx.db.delete("artists", args.id) }, }) -export const removeArtists = mutation({ +export const removeArtists = internalMutation({ args: { ids: v.array(v.id("artists")) }, handler: async (ctx, args) => { for (const id of args.ids) { @@ -1184,14 +1351,14 @@ export const removeArtists = mutation({ }, }) -export const removeAlbum = mutation({ +export const removeAlbum = internalMutation({ args: { id: v.id("albums") }, handler: async (ctx, args) => { return await ctx.db.delete("albums", args.id) }, }) -export const removeAlbums = mutation({ +export const removeAlbums = internalMutation({ args: { ids: v.array(v.id("albums")) }, handler: async (ctx, args) => { for (const id of args.ids) { @@ -1200,21 +1367,21 @@ export const removeAlbums = mutation({ }, }) -export const removeSong = mutation({ +export const removeSong = internalMutation({ args: { id: v.id("songs") }, handler: async (ctx, args) => { return await ctx.db.delete("songs", args.id) }, }) -export const changeFilesForSong = mutation({ +export const changeFilesForSong = internalMutation({ args: { id: v.id("songs"), files: v.record(v.string(), v.string()) }, handler: async (ctx, args) => { return await ctx.db.patch("songs", args.id, { files: args.files }) }, }) -export const changeFilesForSongs = mutation({ +export const changeFilesForSongs = internalMutation({ args: { songs: v.array( v.object({ id: v.id("songs"), files: v.record(v.string(), v.string()) }) @@ -1228,21 +1395,21 @@ export const changeFilesForSongs = mutation({ }, }) -export const updateArtistCover = mutation({ +export const updateArtistCover = internalMutation({ args: { id: v.id("artists"), cover: v.nullable(v.string()) }, handler: async (ctx, args) => { return await ctx.db.patch("artists", args.id, { cover: args.cover }) }, }) -export const updateAlbumCover = mutation({ +export const updateAlbumCover = internalMutation({ args: { id: v.id("albums"), cover: v.nullable(v.string()) }, handler: async (ctx, args) => { return await ctx.db.patch("albums", args.id, { cover: args.cover }) }, }) -export const removeSongs = mutation({ +export const removeSongs = internalMutation({ args: { ids: v.array(v.id("songs")) }, handler: async (ctx, args) => { for (const id of args.ids) { diff --git a/packages/convex/convex/playback.ts b/packages/convex/convex/playback.ts index b67cb08..119238d 100644 --- a/packages/convex/convex/playback.ts +++ b/packages/convex/convex/playback.ts @@ -7,6 +7,7 @@ import { mutation, query } from "./_generated/server" import type { QueueSong } from "./types" import { browseSongsFromIds, + compareAlbumSongs, getSortedLibrarySongIds, songsSortDirectionValidator, songsSortKeyValidator, @@ -99,6 +100,28 @@ function uniqueSongIds(songIds: Id<"songs">[]) { return [...new Set(songIds)] } +function haveSameSongCounts(first: Id<"songs">[], second: Id<"songs">[]) { + if (first.length !== second.length) { + return false + } + const counts = new Map, number>() + for (const songId of first) { + counts.set(songId, (counts.get(songId) ?? 0) + 1) + } + for (const songId of second) { + const count = counts.get(songId) + if (!count) { + return false + } + if (count === 1) { + counts.delete(songId) + } else { + counts.set(songId, count - 1) + } + } + return counts.size === 0 +} + function appendToQueueHistory( history: Id<"songs">[], songId: Id<"songs"> @@ -263,6 +286,7 @@ export const playShuffled = mutation({ const queue = shuffleArray(uniqueSongIds(songIds)) await setQueueState(ctx, userId, { songQueue: queue, + shuffleEnabled: true, resetHistory: true, }) await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId }) @@ -350,6 +374,135 @@ export const playFromSong = mutation({ }, }) +async function albumSongIds(ctx: MutationCtx, albumId: Id<"albums">) { + const songs = await ctx.db + .query("songs") + .withIndex("by_album", (q) => q.eq("album", albumId)) + .collect() + songs.sort(compareAlbumSongs) + return songs.map((song) => song._id) +} + +async function orderedArtistSongIds( + ctx: MutationCtx, + artistId: Id<"artists"> +) { + const songs = await ctx.db + .query("songs") + .withIndex("by_artist", (q) => q.eq("albumArtist", artistId)) + .collect() + + const albums = await ctx.db + .query("albums") + .withIndex("by_artist", (q) => q.eq("artist", artistId)) + .collect() + const albumMap = new Map(albums.map((album) => [album._id, album])) + + songs.sort((a, b) => { + const albumA = albumMap.get(a.album)?.name ?? "" + const albumB = albumMap.get(b.album)?.name ?? "" + if (albumA !== albumB) { + return albumA.localeCompare(albumB) + } + if (a.track !== b.track) { + return a.track - b.track + } + return a.name.localeCompare(b.name) + }) + + return songs.map((song) => song._id) +} + +async function playCollection( + ctx: MutationCtx, + options: { + songIds: Id<"songs">[] + shuffled: boolean + playlistId?: Id<"playlists"> + } +) { + const userId = await requireAuth(ctx) + const unique = uniqueSongIds(options.songIds) + if (unique.length === 0) { + return + } + + const queue = options.shuffled ? shuffleArray(unique) : unique + await setQueueState(ctx, userId, { + songQueue: queue, + shuffleEnabled: options.shuffled, + resetHistory: true, + }) + await recordPlaybackStart(ctx, userId, { + songIds: queue, + playlistId: options.playlistId, + }) +} + +export const playAlbum = mutation({ + args: { albumId: v.id("albums") }, + handler: async (ctx, { albumId }) => { + await playCollection(ctx, { + songIds: await albumSongIds(ctx, albumId), + shuffled: false, + }) + }, +}) + +export const playAlbumShuffled = mutation({ + args: { albumId: v.id("albums") }, + handler: async (ctx, { albumId }) => { + await playCollection(ctx, { + songIds: await albumSongIds(ctx, albumId), + shuffled: true, + }) + }, +}) + +export const playArtist = mutation({ + args: { artistId: v.id("artists") }, + handler: async (ctx, { artistId }) => { + await playCollection(ctx, { + songIds: await orderedArtistSongIds(ctx, artistId), + shuffled: false, + }) + }, +}) + +export const playArtistShuffled = mutation({ + args: { artistId: v.id("artists") }, + handler: async (ctx, { artistId }) => { + await playCollection(ctx, { + songIds: await orderedArtistSongIds(ctx, artistId), + shuffled: true, + }) + }, +}) + +export const playPlaylist = mutation({ + args: { playlistId: v.id("playlists") }, + handler: async (ctx, { playlistId }) => { + const playlist = await ctx.db.get("playlists", playlistId) + await playCollection(ctx, { + songIds: playlist?.songs ?? [], + shuffled: false, + playlistId, + }) + }, +}) + +export const playPlaylistShuffled = mutation({ + args: { playlistId: v.id("playlists") }, + handler: async (ctx, { playlistId }) => { + const playlist = await ctx.db.get("playlists", playlistId) + await playCollection(ctx, { + songIds: playlist?.songs ?? [], + shuffled: true, + playlistId, + }) + }, +}) + export const playFromLibrarySong = mutation({ args: { songId: v.id("songs"), @@ -440,8 +593,10 @@ export const reorderQueue = mutation({ } const queue = user.songQueue ?? [] - const currentSongChanged = - songIds.length > 0 && songIds[0] !== queue[0] + if (!haveSameSongCounts(queue, songIds)) { + throw new ConvexError("Invalid queue order") + } + const currentSongChanged = songIds.length > 0 && songIds[0] !== queue[0] const history = currentSongChanged && queue.length > 0 ? appendToQueueHistory(user.queueHistory ?? [], queue[0]) @@ -580,7 +735,10 @@ export const getSongProgress = query({ }) export const updateSongProgress = mutation({ - args: { progressSeconds: v.number() }, + args: { + songId: v.id("songs"), + progressSeconds: v.number(), + }, handler: async (ctx, args) => { const userId = await requireAuth(ctx) const user = await ctx.db.get(userId) @@ -588,6 +746,10 @@ export const updateSongProgress = mutation({ throw new ConvexError("User not found") } + if ((user.songQueue ?? [])[0] !== args.songId) { + return + } + await ctx.db.patch(userId, { currentSongProgress: args.progressSeconds }) }, }) diff --git a/packages/convex/convex/playlists.ts b/packages/convex/convex/playlists.ts index 7c91763..c90b733 100644 --- a/packages/convex/convex/playlists.ts +++ b/packages/convex/convex/playlists.ts @@ -5,63 +5,13 @@ import type { Doc, Id } from "./_generated/dataModel" import type { MutationCtx, QueryCtx } from "./_generated/server" import { mutation, query } from "./_generated/server" import type { - BrowseArtist, BrowsePlaylistDetail, BrowsePlaylistSummary, - BrowseSong, OwnedPlaylistForAdd, PlaylistSummary, SidebarPlaylists, } from "./library" -import { compareAlbumSongs, paginateSlice } from "./library" - -function toBrowseArtist(artist: Doc<"artists">): BrowseArtist { - return { - id: artist._id, - name: artist.name, - photo: artist.cover, - } -} - -async function loadArtistMap(ctx: QueryCtx) { - const artists = await ctx.db.query("artists").collect() - return new Map(artists.map((artist) => [artist._id, artist])) -} - -async function toBrowseSong( - ctx: QueryCtx, - songId: Id<"songs">, - artistMap: Map, Doc<"artists">>, - albumMap: Map, Doc<"albums">> -): Promise { - const song = await ctx.db.get("songs", songId) - if (!song) { - return null - } - - const album = albumMap.get(song.album) - const albumArtist = artistMap.get(song.albumArtist) - if (!album || !albumArtist) { - return null - } - - return { - id: song._id, - title: song.name, - artist: toBrowseArtist(albumArtist), - album: { - id: album._id, - title: album.name, - cover: album.cover, - }, - durationSeconds: Math.round(song.length), - } -} - -async function loadAlbumMap(ctx: QueryCtx) { - const albums = await ctx.db.query("albums").collect() - return new Map(albums.map((album) => [album._id, album])) -} +import { browseSongsFromIds, compareAlbumSongs, paginateSlice } from "./library" function toPlaylistSummary( playlist: Doc<"playlists">, @@ -75,6 +25,33 @@ function toPlaylistSummary( } } +async function loadPlaylists(ctx: QueryCtx, playlistIds: Id<"playlists">[]) { + const playlists = await Promise.all( + [...new Set(playlistIds)].map((playlistId) => + ctx.db.get("playlists", playlistId) + ) + ) + return playlists.filter( + (playlist): playlist is Doc<"playlists"> => playlist !== null + ) +} + +async function summarizePlaylists( + ctx: QueryCtx, + playlists: Doc<"playlists">[] +) { + const ownerIds = [...new Set(playlists.map((playlist) => playlist.owner))] + const owners = await Promise.all( + ownerIds.map((ownerId) => ctx.db.get("users", ownerId)) + ) + const ownerMap = new Map( + owners.flatMap((owner) => (owner ? [[owner._id, owner] as const] : [])) + ) + return playlists.map((playlist) => + toPlaylistSummary(playlist, ownerMap.get(playlist.owner)?.name ?? "Unknown") + ) +} + async function requireAuth(ctx: MutationCtx) { const userId = await getAuthUserId(ctx) if (userId === null) { @@ -145,18 +122,10 @@ export const browsePlaylistDetail = query({ return null } - const songs: BrowseSong[] = [] - if (args.includeSongs ?? true) { - const artistMap = await loadArtistMap(ctx) - const albumMap = await loadAlbumMap(ctx) - - for (const songId of summary.songIds) { - const song = await toBrowseSong(ctx, songId, artistMap, albumMap) - if (song) { - songs.push(song) - } - } - } + const songs = + (args.includeSongs ?? true) + ? await browseSongsFromIds(ctx, summary.songIds) + : [] return { id: summary.id, @@ -182,16 +151,7 @@ export const browsePlaylistSongsPaginated = query({ } const slice = paginateSlice(playlist.songs, args.paginationOpts) - const artistMap = await loadArtistMap(ctx) - const albumMap = await loadAlbumMap(ctx) - - const page: BrowseSong[] = [] - for (const songId of slice.page) { - const song = await toBrowseSong(ctx, songId, artistMap, albumMap) - if (song) { - page.push(song) - } - } + const page = await browseSongsFromIds(ctx, slice.page) return { ...slice, @@ -247,18 +207,10 @@ export const listSidebarPlaylists = query({ .map((playlist) => toPlaylistSummary(playlist, user.name)) .sort((a, b) => a.title.localeCompare(b.title)) - const subscribed: PlaylistSummary[] = [] - for (const playlistId of user.subscribedPlaylists ?? []) { - const playlist = await ctx.db.get("playlists", playlistId) - if (!playlist || playlist.owner === userId) { - continue - } - const owner = await ctx.db.get("users", playlist.owner) - subscribed.push( - toPlaylistSummary(playlist, owner?.name ?? "Unknown") - ) - } - + const subscribedDocs = ( + await loadPlaylists(ctx, user.subscribedPlaylists ?? []) + ).filter((playlist) => playlist.owner !== userId) + const subscribed = await summarizePlaylists(ctx, subscribedDocs) subscribed.sort((a, b) => a.title.localeCompare(b.title)) return { owned, subscribed } @@ -297,19 +249,14 @@ export const searchPlaylists = query({ } } - for (const playlistId of user.subscribedPlaylists ?? []) { - if (ownedIds.has(playlistId)) { - continue - } - const playlist = await ctx.db.get("playlists", playlistId) - if (!playlist || !playlist.name.toLowerCase().includes(queryText)) { - continue - } - const owner = await ctx.db.get("users", playlist.owner) - matches.push( - toPlaylistSummary(playlist, owner?.name ?? "Unknown") - ) - } + const subscribedDocs = ( + await loadPlaylists(ctx, user.subscribedPlaylists ?? []) + ).filter( + (playlist) => + !ownedIds.has(playlist._id) && + playlist.name.toLowerCase().includes(queryText) + ) + matches.push(...(await summarizePlaylists(ctx, subscribedDocs))) return matches.sort((a, b) => a.title.localeCompare(b.title)) }, @@ -338,19 +285,10 @@ export const listAllPlaylists = query({ toPlaylistSummary(playlist, user.name) ) - for (const playlistId of user.subscribedPlaylists ?? []) { - if (ownedIds.has(playlistId)) { - continue - } - const playlist = await ctx.db.get("playlists", playlistId) - if (!playlist) { - continue - } - const owner = await ctx.db.get("users", playlist.owner) - summaries.push( - toPlaylistSummary(playlist, owner?.name ?? "Unknown") - ) - } + const subscribedDocs = ( + await loadPlaylists(ctx, user.subscribedPlaylists ?? []) + ).filter((playlist) => !ownedIds.has(playlist._id)) + summaries.push(...(await summarizePlaylists(ctx, subscribedDocs))) return summaries.sort((a, b) => a.title.localeCompare(b.title)) }, @@ -488,6 +426,7 @@ export const reorderPlaylistSongs = mutation({ const existing = new Set(playlist.songs) if ( args.songIds.length !== playlist.songs.length || + new Set(args.songIds).size !== args.songIds.length || !args.songIds.every((songId) => existing.has(songId)) ) { throw new ConvexError("Invalid song order") @@ -504,11 +443,28 @@ export const deletePlaylist = mutation({ const users = await ctx.db.query("users").collect() for (const user of users) { const subscribed = user.subscribedPlaylists - if (!subscribed?.includes(args.playlistId)) { + const recentlyPlayed = user.recentlyPlayed + const isSubscribed = subscribed?.includes(args.playlistId) ?? false + const isRecentlyPlayed = + recentlyPlayed?.includes(args.playlistId) ?? false + if (!isSubscribed && !isRecentlyPlayed) { continue } await ctx.db.patch(user._id, { - subscribedPlaylists: subscribed.filter((id) => id !== args.playlistId), + ...(isSubscribed + ? { + subscribedPlaylists: subscribed!.filter( + (id) => id !== args.playlistId + ), + } + : {}), + ...(isRecentlyPlayed + ? { + recentlyPlayed: recentlyPlayed!.filter( + (id) => id !== args.playlistId + ), + } + : {}), }) } diff --git a/packages/convex/convex/schema.ts b/packages/convex/convex/schema.ts index 4ba4ca5..4ef725c 100644 --- a/packages/convex/convex/schema.ts +++ b/packages/convex/convex/schema.ts @@ -24,13 +24,21 @@ export default defineSchema({ favoriteSongs: v.optional(v.array(v.id("songs"))), songQueue: v.optional(v.array(v.id("songs"))), queueHistory: v.optional(v.array(v.id("songs"))), - recentlyPlayed: v.optional(v.array(v.union(v.id("playlists"), v.id("albums")))), + recentlyPlayed: v.optional( + v.array(v.union(v.id("playlists"), v.id("albums"))) + ), currentSongProgress: v.optional(v.number()), shuffleEnabled: v.optional(v.boolean()), repeatEnabled: v.optional( v.union(v.literal("always"), v.literal("once"), v.literal("none")) ), }).index("email", ["email"]), + authVerifiers: defineTable({ + sessionId: v.optional(v.id("authSessions")), + signature: v.optional(v.string()), + }) + .index("signature", ["signature"]) + .index("sessionId", ["sessionId"]), appSettings: defineTable({ disableAccountCreation: v.boolean(), }), @@ -38,7 +46,9 @@ export default defineSchema({ name: v.string(), folder: v.string(), cover: v.nullable(v.string()), - }).index("by_name", ["name"]), + }) + .index("by_name", ["name"]) + .index("by_folder", ["folder"]), albums: defineTable({ name: v.string(), folder: v.string(), diff --git a/packages/convex/convex/types.ts b/packages/convex/convex/types.ts index 42da5eb..f165925 100644 --- a/packages/convex/convex/types.ts +++ b/packages/convex/convex/types.ts @@ -46,8 +46,6 @@ export type BrowseAlbumSummary = Omit & { export type BrowseArtistDetail = { artist: BrowseArtist albums: BrowseAlbum[] - recentlyAdded: BrowseAlbum[] - recentlyPlayed: BrowseAlbum[] } export type PlaylistSummary = { diff --git a/packages/convex/convex/users.ts b/packages/convex/convex/users.ts index fb1c83d..8836f81 100644 --- a/packages/convex/convex/users.ts +++ b/packages/convex/convex/users.ts @@ -4,10 +4,10 @@ import { modifyAccountCredentials, } from "@convex-dev/auth/server" import { ConvexError, v } from "convex/values" -import { api } from "./_generated/api" -import { action, mutation, query } from "./_generated/server" +import { api, internal } from "./_generated/api" +import { action, internalQuery, mutation, query } from "./_generated/server" import type { Id } from "./_generated/dataModel" -import type { MutationCtx } from "./_generated/server" +import type { ActionCtx, MutationCtx } from "./_generated/server" const playbackQualityValidator = v.union( v.literal("low"), @@ -33,6 +33,14 @@ async function requireAdmin(ctx: MutationCtx) { return { userId, user } } +async function requireAdminAction(ctx: ActionCtx) { + const user = await ctx.runQuery(api.auth.currentUser) + if (!user?.isAdmin) { + throw new ConvexError("Not authorized") + } + return user +} + async function deleteUserAuthData(ctx: MutationCtx, userId: Id<"users">) { const sessions = await ctx.db .query("authSessions") @@ -50,7 +58,7 @@ async function deleteUserAuthData(ctx: MutationCtx, userId: Id<"users">) { const verifiers = await ctx.db .query("authVerifiers") - .filter((q) => q.eq(q.field("sessionId"), session._id)) + .withIndex("sessionId", (q) => q.eq("sessionId", session._id)) .collect() for (const verifier of verifiers) { await ctx.db.delete(verifier._id) @@ -61,7 +69,7 @@ async function deleteUserAuthData(ctx: MutationCtx, userId: Id<"users">) { const accounts = await ctx.db .query("authAccounts") - .filter((q) => q.eq(q.field("userId"), userId)) + .withIndex("userIdAndProvider", (q) => q.eq("userId", userId)) .collect() for (const account of accounts) { @@ -78,6 +86,52 @@ async function deleteUserAuthData(ctx: MutationCtx, userId: Id<"users">) { await ctx.db.delete(userId) } +async function deleteOwnedPlaylists(ctx: MutationCtx, userId: Id<"users">) { + const owned = await ctx.db + .query("playlists") + .withIndex("by_owner", (q) => q.eq("owner", userId)) + .collect() + if (owned.length === 0) { + return + } + + const ownedIds = new Set(owned.map((playlist) => playlist._id)) + const users = await ctx.db.query("users").collect() + for (const user of users) { + const subscribed = user.subscribedPlaylists + const recentlyPlayed = user.recentlyPlayed + const hasSubscription = + subscribed?.some((playlistId) => ownedIds.has(playlistId)) ?? false + const hasRecentlyPlayed = + recentlyPlayed?.some((itemId) => + ownedIds.has(itemId as Id<"playlists">) + ) ?? false + if (!hasSubscription && !hasRecentlyPlayed) { + continue + } + await ctx.db.patch(user._id, { + ...(hasSubscription + ? { + subscribedPlaylists: subscribed!.filter( + (playlistId) => !ownedIds.has(playlistId) + ), + } + : {}), + ...(hasRecentlyPlayed + ? { + recentlyPlayed: recentlyPlayed!.filter( + (itemId) => !ownedIds.has(itemId as Id<"playlists">) + ), + } + : {}), + }) + } + + for (const playlist of owned) { + await ctx.db.delete(playlist._id) + } +} + export const getAppSettings = query({ args: {}, handler: async (ctx) => { @@ -88,7 +142,7 @@ export const getAppSettings = query({ }, }) -export const getUserByEmail = query({ +export const getUserByEmail = internalQuery({ args: { email: v.string() }, handler: async (ctx, { email }) => { return await ctx.db @@ -98,6 +152,11 @@ export const getUserByEmail = query({ }, }) +export const getUser = internalQuery({ + args: { id: v.id("users") }, + handler: async (ctx, { id }) => ctx.db.get(id), +}) + export const listUsers = query({ args: {}, handler: async (ctx) => { @@ -109,7 +168,13 @@ export const listUsers = query({ if (!currentUser?.isAdmin) { return null } - return await ctx.db.query("users").collect() + const users = await ctx.db.query("users").collect() + return users.map((user) => ({ + _id: user._id, + name: user.name, + email: user.email, + isAdmin: user.isAdmin, + })) }, }) @@ -228,6 +293,7 @@ export const deleteUser = mutation({ if (userId === adminId) { throw new ConvexError("You cannot delete your own account") } + await deleteOwnedPlaylists(ctx, userId) await deleteUserAuthData(ctx, userId) }, }) @@ -257,12 +323,9 @@ export const adminChangeUserPassword = action({ newPassword: v.string(), }, handler: async (ctx, { userId, newPassword }) => { - const users = await ctx.runQuery(api.users.listUsers) - if (!users) { - throw new ConvexError("Not authorized") - } + await requireAdminAction(ctx) - const target = users.find((u) => u._id === userId) + const target = await ctx.runQuery(internal.users.getUser, { id: userId }) if (!target) { throw new ConvexError("User not found") } @@ -286,10 +349,7 @@ export const adminCreateUser = action({ isAdmin: v.optional(v.boolean()), }, handler: async (ctx, { name, email, password, isAdmin }) => { - const users = await ctx.runQuery(api.users.listUsers) - if (!users) { - throw new ConvexError("Not authorized") - } + await requireAdminAction(ctx) const trimmedName = name.trim() const trimmedEmail = email.trim().toLowerCase() @@ -304,14 +364,14 @@ export const adminCreateUser = action({ throw new ConvexError("Password must be at least 8 characters") } - const existing = await ctx.runQuery(api.users.getUserByEmail, { + const existing = await ctx.runQuery(internal.users.getUserByEmail, { email: trimmedEmail, }) if (existing) { throw new ConvexError("Email is already in use") } - const { user } = await createAccount(ctx, { + await createAccount(ctx, { provider: "password", account: { id: trimmedEmail, secret: password }, profile: { @@ -320,6 +380,5 @@ export const adminCreateUser = action({ isAdmin: isAdmin ?? false, }, }) - }, }) diff --git a/packages/convex/playback-stream.ts b/packages/convex/playback-stream.ts index b97862e..9e7a461 100644 --- a/packages/convex/playback-stream.ts +++ b/packages/convex/playback-stream.ts @@ -24,17 +24,18 @@ export type PlaybackStreamPlan = { } export function playbackStreamPlan( - files: Record, + files: Record, quality: PlaybackQuality | undefined, preferAtmos: boolean ): PlaybackStreamPlan { const playbackQuality = quality ?? "medium" const kbps = playbackQuality === "lossless" ? 0 : qualityKbps(playbackQuality) + const effectivePreferAtmos = preferAtmos && "atmos" in files let transcodeNeeded = true - if (preferAtmos && "atmos" in files) { + if (effectivePreferAtmos) { transcodeNeeded = false } else if (kbps === 0 && "lossless" in files) { transcodeNeeded = false @@ -44,8 +45,8 @@ export function playbackStreamPlan( return { playbackQuality, - preferAtmos, + preferAtmos: effectivePreferAtmos, transcodeNeeded, - useHls: transcodeNeeded && !preferAtmos, + useHls: transcodeNeeded, } }