diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/_layout.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/_layout.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/_layout.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/_layout.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/album/[id].tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/album/[id].tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/album/[id].tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/artist/[id].tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/artist/[id].tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/artist/[id].tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/artist/[id].tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/albums.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/albums.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/albums.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/albums.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/artists.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/artists.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/artists.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/artists.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/playlists.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/playlists.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/playlists.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/playlists.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/songs.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/songs.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/songs.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/songs.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/index.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/index.tsx new file mode 100644 index 0000000..b71b31f --- /dev/null +++ b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/index.tsx @@ -0,0 +1 @@ +export { default } from "../../home/downloads" diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/other.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/other.tsx new file mode 100644 index 0000000..e7ea56e --- /dev/null +++ b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/other.tsx @@ -0,0 +1 @@ +export { default } from "../../home/downloads/other" diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/index.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/index.tsx similarity index 91% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/index.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/index.tsx index 688cd25..9dd24d6 100644 --- a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/index.tsx +++ b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/index.tsx @@ -5,6 +5,7 @@ import Songs from "../home/browse/songs" import Playlists from "../home/browse/playlists" import Favorites from "../home/playlist/favorites" import RecentlyPlayed from "../home/recently-played" +import Downloads from "../home/downloads" import { TabletSectionContext } from "@/lib/tablet-navigation" const screens = { @@ -14,6 +15,7 @@ const screens = { playlists: Playlists, favorites: Favorites, recent: RecentlyPlayed, + downloads: Downloads, } export default function TabletSectionScreen() { diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/playlist/[id].tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/playlist/[id].tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/playlist/[id].tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/playlist/[id].tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/playlist/favorites.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/playlist/favorites.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/playlist/favorites.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/playlist/favorites.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/recently-added.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/recently-added.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/recently-added.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/recently-added.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/recently-played.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/recently-played.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/recently-played.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/recently-played.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/settings.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/settings.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/settings.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/settings.tsx diff --git a/apps/mobile/app/(app)/(tabs)/_layout.tsx b/apps/mobile/app/(app)/(tabs)/_layout.tsx index 011f791..10b5378 100644 --- a/apps/mobile/app/(app)/(tabs)/_layout.tsx +++ b/apps/mobile/app/(app)/(tabs)/_layout.tsx @@ -217,6 +217,14 @@ function TabsContent() { Recently Played + {!keyboardVisible ? : null} {tabletLayout ? : null} diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx index bd97814..09c4f05 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -22,11 +22,17 @@ import { DiscHeader, } from "@/components/collection-list" import { AudioFormatBadge } from "@/components/audio-format-badge" -import { DownloadHeaderButton } from "@/components/download-header-button" +import { + DownloadHeaderButton, + DownloadedQuality, +} from "@/components/download-header-button" +import { useOpenedFromDownloads } from "@/lib/downloads-navigation" +import { downloadsQueueOrigin } from "@otunes/convex/download-quality" import { useDownloads, useIsCollectionDownloaded, - useIsSongDownloaded, + useSongDownloadState, + useToggleSongDownload, } from "@/contexts/downloads" import { CoverImage } from "@/components/cover-image" @@ -64,7 +70,17 @@ export default function AlbumScreen() { api.library.browseAlbumDetail, typeof id === "string" ? { id: id as Id<"albums"> } : "skip" ) - const { playAlbum, playAlbumShuffled, playFromSong } = usePlaybackActions() + const { + playAlbum, + playAlbumShuffled, + playFromSong, + playInOrder, + playShuffled, + } = usePlaybackActions() + const fromDownloads = useOpenedFromDownloads() + const playOrigin = fromDownloads + ? downloadsQueueOrigin(`album:${id}`) + : `album:${id}` const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } = useFavorites() const { @@ -109,8 +125,8 @@ export default function AlbumScreen() { const playTrack = useCallback( (songId: Id<"songs">, ids: Id<"songs">[]) => - playFromSong(songId, ids, `album:${id}`), - [id, playFromSong] + playFromSong(songId, ids, playOrigin), + [playOrigin, playFromSong] ) const renderItem = useCallback( @@ -308,7 +324,11 @@ export default function AlbumScreen() { diff --git a/apps/web/components/downloads-view.tsx b/apps/web/components/downloads-view.tsx new file mode 100644 index 0000000..4e9afc5 --- /dev/null +++ b/apps/web/components/downloads-view.tsx @@ -0,0 +1,152 @@ +"use client" + +import * as React from "react" +import Image from "next/image" +import Link from "next/link" +import { Star } from "lucide-react" + +import { FAVORITES_DOWNLOAD_ID } from "@/components/downloads-provider" +import { PageHeader } from "@/components/library-skeletons" +import { + FROM_DOWNLOADS_PARAM, + useDownloadsVersion, +} from "@/hooks/use-downloads" +import { albumGridClassName } from "@/lib/album-grid-classes" +import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls" +import { downloadQueue } from "@/lib/downloads" +import type { DownloadedCollection } from "@otunes/convex/client/download-queue" +import { formatBytes } from "@otunes/convex/download-quality" + +export const OTHER_DOWNLOADS_PATH = "/library/downloads/other" +export const OTHER_DOWNLOADS_TITLE = "Other Downloaded Songs" + +function collectionHref({ kind, id }: DownloadedCollection) { + if (kind === "album") return `/album/${id}?${FROM_DOWNLOADS_PARAM}` + if (id === FAVORITES_DOWNLOAD_ID) { + return `/playlist/favorites?${FROM_DOWNLOADS_PARAM}` + } + return `/playlist/${id}?${FROM_DOWNLOADS_PARAM}` +} + +function CollectionCover({ collection }: { collection: DownloadedCollection }) { + if (collection.id === FAVORITES_DOWNLOAD_ID) { + return ( +
+ +
+ ) + } + return ( + {collection.title} + ) +} + +function DownloadCard({ + href, + title, + subtitle, + cover, +}: { + href: string + title: string + subtitle: string + cover: React.ReactNode +}) { + return ( + +
+ {cover} +
+
+

+ {title} +

+

+ {subtitle} +

+
+ + ) +} + +function songCount(count: number) { + return count === 1 ? "1 song" : `${count} songs` +} + +/** Downloaded albums and playlists, newest first, after Other Downloaded Songs. */ +export function DownloadsView() { + const version = useDownloadsVersion() + const { otherSongs, rows } = React.useMemo(() => { + const breakdown = downloadQueue.breakdown() + const bytesByCollection = new Map( + breakdown.collections.map((row) => [row.collection, row.bytes]) + ) + return { + otherSongs: breakdown.otherSongs, + rows: downloadQueue + .collections() + .reverse() + .map((collection) => ({ + collection, + bytes: bytesByCollection.get(collection) ?? 0, + })), + } + // version invalidates the lookup when downloads change. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [version]) + + const empty = rows.length === 0 && otherSongs.songIds.length === 0 + + return ( +
+ + {empty ? ( +
+

+ Nothing downloaded in this browser. +

+
+ ) : ( +
+
+ {otherSongs.songIds.length > 0 ? ( + + } + /> + ) : null} + {rows.map(({ collection, bytes }) => ( + } + /> + ))} +
+
+ )} +
+ ) +} diff --git a/apps/web/components/other-downloads-view.tsx b/apps/web/components/other-downloads-view.tsx new file mode 100644 index 0000000..1902fa1 --- /dev/null +++ b/apps/web/components/other-downloads-view.tsx @@ -0,0 +1,158 @@ +"use client" + +import { useCallback, useMemo, type MouseEvent } from "react" +import { Play, Shuffle } from "lucide-react" + +import { OTHER_DOWNLOADS_TITLE } from "@/components/downloads-view" +import { useFavorites } from "@/components/favorites-provider" +import { PageHeader } from "@/components/library-skeletons" +import { usePlaybackActions } from "@/components/playback-provider" +import { LibraryTrackListHeader, TrackRow } from "@/components/track-row" +import { Button } from "@/components/ui/button" +import { ScrollArea } from "@/components/ui/scroll-area" +import { VirtualList } from "@/components/virtual-list" +import { useDownloadsVersion } from "@/hooks/use-downloads" +import { useTrackListMediaAction } from "@/hooks/use-media-actions" +import { useTrackSelection } from "@/hooks/use-track-selection" +import { downloadQueue } from "@/lib/downloads" +import { getSelectionRangePositions } from "@/lib/selection-range-styles" +import { stationArtistId } from "@/lib/station-artist" +import { useSongs } from "@/lib/song-cache" +import type { Id } from "@otunes/convex/_generated/dataModel" +import type { BrowseSong } from "@otunes/convex/types" +import { downloadsQueueOrigin } from "@otunes/convex/download-quality" + +const PLAY_ORIGIN = downloadsQueueOrigin("other") +const estimateSongRowSize = () => 56 + +/** Songs downloaded on their own. Playback here always uses the downloads. */ +export function OtherDownloadsView() { + const version = useDownloadsVersion() + const songIds = useMemo( + () => + downloadQueue + .otherSongIds() + .filter((songId) => downloadQueue.getDownloaded(songId)) + .reverse() as Id<"songs">[], + // version invalidates the lookup when downloads change. + // eslint-disable-next-line react-hooks/exhaustive-deps + [version] + ) + const cachedSongs = useSongs(songIds) + const songs = useMemo( + () => cachedSongs.filter((song): song is BrowseSong => song !== undefined), + [cachedSongs] + ) + const playableIds = useMemo( + () => songs.map((song) => song.id as Id<"songs">), + [songs] + ) + + const { isSongFavorite, toggleSongFavorite } = useFavorites() + const { playFromSong, playInOrder, playShuffled } = usePlaybackActions() + const { + selectedIds, + selectedCount, + handleSelect, + handlePointerDown, + prepareContextMenu, + clearSelection, + } = useTrackSelection(songs) + const selectedStationArtistId = useMemo( + () => stationArtistId(songs, selectedIds), + [songs, selectedIds] + ) + const selectionPositions = useMemo( + () => + getSelectionRangePositions( + songs.map((song) => song.id), + selectedIds + ), + [songs, selectedIds] + ) + const handleMediaAction = useTrackListMediaAction({ + selectedIds, + songs, + downloadFrom: "other", + }) + const handleRowSelect = useCallback( + (index: number, event: MouseEvent) => + handleSelect(songs[index].id, index, event), + [songs, handleSelect] + ) + const handleRowPlay = useCallback( + (index: number) => + void playFromSong(songs[index].id, playableIds, PLAY_ORIGIN), + [songs, playableIds, playFromSong] + ) + const handleToggleFavorite = useCallback( + (songId: string) => void toggleSongFavorite(songId as Id<"songs">), + [toggleSongFavorite] + ) + + return ( +
+ + +
{ + if (event.target === event.currentTarget) clearSelection() + }} + > + {songIds.length === 0 ? ( +

+ Songs you download on their own appear here. +

+ ) : ( + <> +
+ + +
+ + songs[index].id} + renderItem={(index) => ( + + )} + /> + + )} +
+
+
+ ) +} diff --git a/apps/web/components/playback-provider.tsx b/apps/web/components/playback-provider.tsx index 2ab0a58..95ccc42 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -36,6 +36,10 @@ import { useMediaSession } from "@/hooks/use-media-session" import { fetchCachedQuery } from "@otunes/convex/client/cached-query" import { supportsDolbyAtmosPlayback } from "@/lib/dolby-atmos-support" import { downloadedAudioUrl, downloadQueue } from "@/lib/downloads" +import { + isDownloadsQueueOrigin, + streamDownloadQuality, +} from "@otunes/convex/download-quality" import { flushPersistentCache } from "@/lib/persistent-cache" import * as playbackQueue from "@otunes/convex/client/playback-queue" import type { RepeatMode } from "@otunes/convex/client/playback-queue" @@ -62,8 +66,9 @@ type PlaybackContextValue = { toggleQueueOpen: () => void setIsPlaying: (playing: boolean) => void setVolume: (volume: number) => void - playInOrder: (songIds: Id<"songs">[]) => Promise - playShuffled: (songIds: Id<"songs">[]) => Promise + /** An origin from `downloadsQueueOrigin` plays downloads in any quality. */ + playInOrder: (songIds: Id<"songs">[], origin?: string) => Promise + playShuffled: (songIds: Id<"songs">[], origin?: string) => Promise addToQueueNext: (songIds: Id<"songs">[]) => Promise addToQueueLast: (songIds: Id<"songs">[]) => Promise playFromSong: ( @@ -190,44 +195,53 @@ type PlaybackLoadSettings = { useHls: boolean } -function playbackLoadSettings( +function userStreamPlan( user: { preferAtmos?: boolean playbackQuality?: PlaybackQuality }, dolbyAtmosSupported: boolean | null, files: Record -): PlaybackLoadSettings { +) { const preferAtmos = dolbyAtmosSupported === true && (user.preferAtmos ?? false) - const plan = playbackStreamPlan(files, user.playbackQuality, preferAtmos) - return { - preferAtmos: plan.preferAtmos, - playbackQuality: plan.playbackQuality, - useHls: plan.useHls, - } + return playbackStreamPlan(files, user.playbackQuality, preferAtmos) } /** Where a song plays from: this device's download, or the server. */ type AudioSourceChoice = { kind: "download" } | { kind: "stream"; settings: PlaybackLoadSettings } -/** Downloads play without the user or file info, so they also work offline. */ +/** + * Downloads stand in for streams in the same quality, and always play in + * queues started from Downloads. Without the user or file info (offline), + * any download plays. + */ function audioSourceChoice( songId: string, user: { preferAtmos?: boolean; playbackQuality?: PlaybackQuality } | null, dolbyAtmosSupported: boolean | null, - files: Record | undefined + files: Record | undefined, + fromDownloads: boolean ): AudioSourceChoice | null { - if (downloadQueue.getDownloaded(songId)) { - return { kind: "download" } - } + const download = downloadQueue.getDownloaded(songId) if (!user || !files) { - return null + return download ? { kind: "download" } : null + } + const plan = userStreamPlan(user, dolbyAtmosSupported, files) + if ( + download && + (fromDownloads || download.quality === streamDownloadQuality(plan)) + ) { + return { kind: "download" } } return { kind: "stream", - settings: playbackLoadSettings(user, dolbyAtmosSupported, files), + settings: { + preferAtmos: plan.preferAtmos, + playbackQuality: plan.playbackQuality, + useHls: plan.useHls, + }, } } @@ -514,6 +528,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { useEffect(() => { void downloadQueue.load().catch(() => {}) }, []) + // Queues started from the Downloads page play downloads in any quality. + const [fromDownloads, setFromDownloads] = useState(false) const volume = useSyncExternalStore( subscribeVolume, readStoredVolume, @@ -838,7 +854,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { currentSongId, user ? { playbackQuality, preferAtmos } : null, dolbyAtmosSupported, - currentSongDoc?.files + currentSongDoc?.files, + fromDownloads ) if (!source) { return @@ -905,6 +922,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { preferAtmos, dolbyAtmosSupported, downloadsVersion, + fromDownloads, runWithoutAudioSync, destroyHls, clearPreload, @@ -922,7 +940,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { nextQueueSongId, user ? { playbackQuality, preferAtmos } : null, dolbyAtmosSupported, - nextQueueSongDoc?.files + nextQueueSongDoc?.files, + fromDownloads ) if (!source) { return @@ -968,6 +987,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { preferAtmos, dolbyAtmosSupported, downloadsVersion, + fromDownloads, clearPreload, destroyPreloadHls, ]) @@ -1034,7 +1054,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { nextQueueSongId, user ?? null, dolbyAtmosSupported, - nextQueueSongDoc?.files + nextQueueSongDoc?.files, + fromDownloads ) : null if ( @@ -1130,6 +1151,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { nextQueueSongDoc, user, dolbyAtmosSupported, + fromDownloads, store, destroyHls, runWithoutAudioSync, @@ -1191,6 +1213,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { queueOriginRef.current = recorded.origin ?? (recorded.playlistId ? `playlist:${recorded.playlistId}` : undefined) + setFromDownloads(isDownloadsQueueOrigin(recorded.origin)) const previousSongId = store.getState().queue[0] store.update(playbackQueue.clearQueue) store.update(recipe) @@ -1243,21 +1266,26 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { ) const playInOrder = useCallback( - async (songIds: Id<"songs">[]) => { + async (songIds: Id<"songs">[], origin?: string) => { if (songIds.length === 0) { return } - startPlayback((state) => playbackQueue.startQueue(state, songIds, false)) + startPlayback( + (state) => playbackQueue.startQueue(state, songIds, false), + { origin } + ) }, [startPlayback] ) const playShuffled = useCallback( - async (songIds: Id<"songs">[]) => { + async (songIds: Id<"songs">[], origin?: string) => { if (songIds.length === 0) { return } - startPlayback((state) => playbackQueue.startQueue(state, songIds, true)) + startPlayback((state) => playbackQueue.startQueue(state, songIds, true), { + origin, + }) }, [startPlayback] ) @@ -1475,9 +1503,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { skipPrevious, }) - const currentDownload = currentSongId - ? downloadQueue.getDownloaded(currentSongId) - : undefined + const currentSource = currentSongId + ? audioSourceChoice( + currentSongId, + user ? { playbackQuality, preferAtmos } : null, + dolbyAtmosSupported, + currentSongDoc?.files, + fromDownloads + ) + : null + const currentDownload = + currentSource?.kind === "download" && currentSongId + ? downloadQueue.getDownloaded(currentSongId) + : undefined const currentFormat = currentDownload ? currentDownload.quality === "atmos" || currentDownload.quality === "lossless" diff --git a/apps/web/components/playlist-view.tsx b/apps/web/components/playlist-view.tsx index 1a0d93f..a4a8a42 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -18,13 +18,17 @@ import { } from "lucide-react" import { toast } from "sonner" -import { DownloadButton } from "@/components/download-button" +import { DownloadButton, DownloadedQuality } from "@/components/download-button" import { FAVORITES_DOWNLOAD_ID, useDownloads, } from "@/components/downloads-provider" import { useFavorites } from "@/components/favorites-provider" -import { useIsCollectionDownloaded } from "@/hooks/use-downloads" +import { + useIsCollectionDownloaded, + useOpenedFromDownloads, +} from "@/hooks/use-downloads" +import { downloadsQueueOrigin } from "@otunes/convex/download-quality" import { useCurrentSongId, usePlaybackActions, @@ -153,8 +157,22 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { rememberSongs(playlist.songs) }, [playlist.songs]) + const downloadRef = React.useMemo( + () => ({ + kind: "playlist" as const, + id: playlist.id ?? FAVORITES_DOWNLOAD_ID, + }), + [playlist.id] + ) + const fromDownloads = useOpenedFromDownloads() + const playOrigin = fromDownloads + ? downloadsQueueOrigin(`playlist:${downloadRef.id}`) + : `playlist:${playlist.id}` + function playAll(shuffled: boolean) { - if (playlist.id) { + if (fromDownloads) { + void (shuffled ? playShuffled : playInOrder)(playlistSongIds, playOrigin) + } else if (playlist.id) { const play = shuffled ? playPlaylistShuffled : playPlaylist void play(playlist.id, playlistSongIds) } else { @@ -162,17 +180,20 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { } } - const handleMediaAction = useTrackListMediaAction({ selectedIds, songs }) + const handleMediaAction = useTrackListMediaAction({ + selectedIds, + songs, + downloadFrom: downloadRef, + }) const { requestDownload, removeDownload } = useDownloads() const downloadTarget = React.useMemo( () => ({ - kind: "playlist" as const, - id: playlist.id ?? FAVORITES_DOWNLOAD_ID, + ...downloadRef, title: playlist.title, songIds: playlistSongIds, }), - [playlist.id, playlist.title, playlistSongIds] + [downloadRef, playlist.title, playlistSongIds] ) const playlistDownloaded = useIsCollectionDownloaded(downloadTarget) @@ -197,11 +218,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { } function handleRowPlay(index: number) { - void playFromSong( - filteredSongs[index].id, - playlistSongIds, - `playlist:${playlist.id}` - ) + void playFromSong(filteredSongs[index].id, playlistSongIds, playOrigin) } function handleToggleFavorite(songId: string) { @@ -368,6 +385,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {

{playlist.owner.name}

+

+ +

@@ -499,6 +519,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { selectedCount={selectedCount} selectionStationArtistId={selectedStationArtistId} playlistLabel={ADD_TO_ANOTHER_PLAYLIST} + downloadCollection={downloadRef} showFavoriteInMenu={!isFavorites} removeLabel={ isFavorites diff --git a/apps/web/components/search-song-item.tsx b/apps/web/components/search-song-item.tsx index fa29681..3276d5f 100644 --- a/apps/web/components/search-song-item.tsx +++ b/apps/web/components/search-song-item.tsx @@ -1,7 +1,7 @@ "use client" import { useDownloads } from "@/components/downloads-provider" -import { useIsSongDownloaded } from "@/hooks/use-downloads" +import { useSongDownloadState } from "@/hooks/use-downloads" import Image from "next/image" import Link from "next/link" import { useAddToPlaylist } from "@/components/add-to-playlist-provider" @@ -23,7 +23,7 @@ export function SearchSongItem({ song }: { song: BrowseSong }) { const { runQueueAction, createStation } = useQueueMediaActions() const songIds = [song.id as Id<"songs">] const { requestDownload, removeDownload } = useDownloads() - const downloaded = useIsSongDownloaded(song.id) + const downloaded = useSongDownloadState(song.id) === "here" const downloadTarget = { kind: "songs" as const, songIds, diff --git a/apps/web/components/track-row.tsx b/apps/web/components/track-row.tsx index 91b8a67..32eb139 100644 --- a/apps/web/components/track-row.tsx +++ b/apps/web/components/track-row.tsx @@ -28,9 +28,10 @@ import { type SelectionRangePosition, } from "@/lib/selection-range-styles" import { formatDuration } from "@/lib/format-duration" -import { useIsSongDownloaded } from "@/hooks/use-downloads" +import { useSongDownloadState } from "@/hooks/use-downloads" import { cn } from "@/lib/utils" import type { BrowseSong } from "@otunes/convex/types" +import type { DownloadSource } from "@otunes/convex/client/download-queue" /** * - `library`: favorite star, cover with play overlay, title, artist and album @@ -50,6 +51,8 @@ export type TrackRowProps = { trackNumber?: number /** Secondary line under the title, e.g. album track credits. */ subtitle?: string + /** The download this row belongs to; defaults to Other Downloaded Songs. */ + downloadCollection?: DownloadSource selectionPosition: SelectionRangePosition isActive?: boolean isNowPlaying?: boolean @@ -249,6 +252,7 @@ function TrackRowComponent({ index, trackNumber, subtitle, + downloadCollection, selectionPosition, isActive = false, isNowPlaying = false, @@ -271,7 +275,9 @@ function TrackRowComponent({ onDrop, }: TrackRowProps) { const inRange = isInSelectionRange(selectionPosition) - const isDownloaded = useIsSongDownloaded(song.id) + const downloadState = useSongDownloadState(song.id, downloadCollection) + const isDownloaded = downloadState === "here" + const showDownloaded = isDownloaded || downloadState === "device" const flush = variant === "library" || variant === "queue" const play = () => onPlay(index) const toggleFavorite = () => onToggleFavorite?.(song.id) @@ -310,7 +316,7 @@ function TrackRowComponent({ inRange ? "text-primary-foreground" : "text-muted-foreground" )} > - {isDownloaded ? ( + {showDownloaded ? ( ) : null} {formatDuration(song.durationSeconds)} diff --git a/apps/web/hooks/use-downloads.ts b/apps/web/hooks/use-downloads.ts index 117fc1b..72862ec 100644 --- a/apps/web/hooks/use-downloads.ts +++ b/apps/web/hooks/use-downloads.ts @@ -2,7 +2,11 @@ import { useMemo, useSyncExternalStore } from "react" -import type { CollectionRef } from "@otunes/convex/client/download-queue" +import type { + CollectionRef, + DownloadSource, + SongDownloadState, +} from "@otunes/convex/client/download-queue" import { downloadQueue } from "@/lib/downloads" /** Re-renders on every download change. Prefer the narrower hooks in lists. */ @@ -14,12 +18,18 @@ export function useDownloadsVersion() { ) } -/** Only re-renders when this song is downloaded or removed. */ -export function useIsSongDownloaded(songId: string) { +/** + * A song's download state as seen from `from` (see `downloadState`). Only + * re-renders when that state changes. + */ +export function useSongDownloadState( + songId: string, + from?: DownloadSource +): SongDownloadState { return useSyncExternalStore( downloadQueue.subscribe, - () => downloadQueue.getDownloaded(songId) !== undefined, - () => false + () => downloadQueue.downloadState(songId, from), + () => "none" ) } @@ -60,3 +70,21 @@ export function useIsCollectionDownloaded(ref: CollectionRef) { () => false ) } + +const noopSubscribe = () => () => {} + +/** Search param marking album and playlist pages opened from Downloads. */ +export const FROM_DOWNLOADS_PARAM = "from=downloads" + +/** + * True on album and playlist pages opened from Downloads, where playback uses + * the downloads whatever their quality. + */ +export function useOpenedFromDownloads() { + return useSyncExternalStore( + noopSubscribe, + () => + new URLSearchParams(window.location.search).get("from") === "downloads", + () => false + ) +} diff --git a/apps/web/hooks/use-media-actions.ts b/apps/web/hooks/use-media-actions.ts index f7dca4a..6e4c33b 100644 --- a/apps/web/hooks/use-media-actions.ts +++ b/apps/web/hooks/use-media-actions.ts @@ -14,6 +14,7 @@ import { stationArtistId } from "@/lib/station-artist" import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" import { fetchCachedQuery } from "@otunes/convex/client/cached-query" +import type { DownloadSource } from "@otunes/convex/client/download-queue" /** The song's title for one song, else a count. */ function songsTitle(songIds: readonly string[]) { @@ -35,7 +36,8 @@ export function useMediaActions() { ( action: MediaContextAction, songIds: Id<"songs">[], - stationArtist?: string + stationArtist?: string, + downloadFrom?: DownloadSource ) => { switch (action) { case "create-station": @@ -60,7 +62,12 @@ export function useMediaActions() { }) break case "remove-download": - void removeDownload({ kind: "songs", songIds, title: "" }) + void removeDownload({ + kind: "songs", + songIds, + title: "", + from: downloadFrom, + }) break } }, @@ -118,10 +125,13 @@ export function useTrackListMediaAction({ selectedIds, songs, artistId, + downloadFrom, }: { selectedIds: ReadonlySet songs?: { id: string; artist: { id: string } }[] artistId?: string + /** Removing a download only takes it out of this one. */ + downloadFrom?: DownloadSource }) { const { runSongsAction } = useMediaActions() @@ -132,8 +142,13 @@ export function useTrackListMediaAction({ const stationArtist = artistId ?? (songs ? stationArtistId(songs, new Set(targetIds)) : undefined) - runSongsAction(action, targetIds as Id<"songs">[], stationArtist) + runSongsAction( + action, + targetIds as Id<"songs">[], + stationArtist, + downloadFrom + ) }, - [selectedIds, songs, artistId, runSongsAction] + [selectedIds, songs, artistId, downloadFrom, runSongsAction] ) } diff --git a/apps/web/lib/downloads.ts b/apps/web/lib/downloads.ts index 72262a8..e85dd18 100644 --- a/apps/web/lib/downloads.ts +++ b/apps/web/lib/downloads.ts @@ -1,7 +1,7 @@ import { createDownloadQueue, - type DownloadedCollection, type DownloadedSong, + type DownloadIndex, type DownloadStorage, } from "@otunes/convex/client/download-queue" import { @@ -16,7 +16,7 @@ const DB_NAME = "otunes-downloads" const AUDIO_STORE = "audio" const SONG_STORE = "songs" const REMEMBERED_QUALITY_KEY = "otunes:download-quality" -const COLLECTIONS_KEY = "otunes:download-collections" +const INDEX_KEY = "otunes:download-index" let database: Promise | null = null @@ -81,16 +81,17 @@ const storage: DownloadStorage = { }) return blob.size }, - async readCollections() { + async readIndex() { try { - const raw = localStorage.getItem(COLLECTIONS_KEY) - return raw ? (JSON.parse(raw) as DownloadedCollection[]) : [] + const raw = localStorage.getItem(INDEX_KEY) + if (raw) return JSON.parse(raw) as DownloadIndex } catch { - return [] + // A missing or unreadable index starts empty. } + return { collections: [], otherSongIds: [] } }, - async writeCollections(collections) { - localStorage.setItem(COLLECTIONS_KEY, JSON.stringify(collections)) + async writeIndex(index) { + localStorage.setItem(INDEX_KEY, JSON.stringify(index)) }, async remove(songIds) { if (songIds.length === 0) return diff --git a/apps/web/public/placeholder-downloads.svg b/apps/web/public/placeholder-downloads.svg new file mode 100644 index 0000000..e71f686 --- /dev/null +++ b/apps/web/public/placeholder-downloads.svg @@ -0,0 +1,13 @@ + diff --git a/packages/convex/client/download-queue.ts b/packages/convex/client/download-queue.ts index facf039..dc5a32f 100644 --- a/packages/convex/client/download-queue.ts +++ b/packages/convex/client/download-queue.ts @@ -20,11 +20,34 @@ export type DownloadedCollection = { id: string title: string quality: DownloadQuality + /** Every song in the album or playlist, for syncing. */ songIds: string[] + /** Songs whose download was removed from this collection only. */ + removedSongIds?: string[] } export type CollectionRef = Pick +/** Where songs are removed from: one collection, or Other Downloaded Songs. */ +export type DownloadSource = CollectionRef | "other" + +/** The songs a collection keeps downloaded. */ +export function collectionSongIds(collection: DownloadedCollection) { + if (!collection.removedSongIds?.length) return collection.songIds + const removed = new Set(collection.removedSongIds) + return collection.songIds.filter((songId) => !removed.has(songId)) +} + +/** + * What a device remembers besides the audio: downloaded collections, and songs + * downloaded on their own ("Other Downloaded Songs"). A song leaves the other + * songs when its album is downloaded, but stays when a playlist holds it. + */ +export type DownloadIndex = { + collections: DownloadedCollection[] + otherSongIds: string[] +} + /** Where a platform keeps downloaded audio. */ export type DownloadStorage = { list(): Promise @@ -42,8 +65,8 @@ export type DownloadStorage = { signal: AbortSignal ): Promise remove(songIds: readonly string[]): Promise - readCollections(): Promise - writeCollections(collections: DownloadedCollection[]): Promise + readIndex(): Promise + writeIndex(index: DownloadIndex): Promise } export type DownloadableSong = { @@ -69,10 +92,12 @@ export type DownloadBreakdown = { /** Downloaded songs that fell back to High. */ fallbackCount: number }[] - /** Songs downloaded on their own, outside any album or playlist. */ - singles: { bytes: number; songIds: string[] } + /** Other Downloaded Songs: songs downloaded on their own. */ + otherSongs: { bytes: number; songIds: string[] } } +export type SongDownloadState = "here" | "device" | "removed" | "none" + export type DownloadQueue = ReturnType function collectionKey({ kind, id }: CollectionRef) { @@ -90,6 +115,7 @@ export function createDownloadQueue( ) { const downloaded = new Map() const collections = new Map() + const otherSongIds = new Set() const waiting: { song: DownloadableSong; quality: DownloadQuality }[] = [] const running = new Map() const listeners = new Set<() => void>() @@ -103,12 +129,16 @@ export function createDownloadQueue( } function load() { - loading ??= Promise.all([storage.list(), storage.readCollections()]).then( - ([songs, saved]) => { + loading ??= Promise.all([storage.list(), storage.readIndex()]).then( + ([songs, index]) => { for (const song of songs) downloaded.set(song.songId, song) - for (const collection of saved) { + for (const collection of index.collections) { collections.set(collectionKey(collection), collection) } + // Songs still queued when the app closed were never downloaded. + for (const songId of index.otherSongIds) { + if (downloaded.has(songId)) otherSongIds.add(songId) + } notify() }, (error) => { @@ -119,8 +149,11 @@ export function createDownloadQueue( return loading } - function saveCollections() { - return storage.writeCollections([...collections.values()]) + function saveIndex() { + return storage.writeIndex({ + collections: [...collections.values()], + otherSongIds: [...otherSongIds], + }) } function isQueued(songId: string) { @@ -155,6 +188,8 @@ export function createDownloadQueue( }, (error) => { if (controller.signal.aborted) return + // Load drops it from the saved index, since it never downloaded. + otherSongIds.delete(song.id) for (const listener of failureListeners) listener(song.id, error) } ) @@ -176,7 +211,9 @@ export function createDownloadQueue( } } - async function remove(songIds: readonly string[]) { + /** Cancels and deletes audio, leaving the index as it is. */ + async function deleteAudio(songIds: readonly string[]) { + if (songIds.length === 0) return const ids = new Set(songIds) for (let index = waiting.length - 1; index >= 0; index -= 1) { if (ids.has(waiting[index].song.id)) waiting.splice(index, 1) @@ -191,16 +228,50 @@ export function createDownloadQueue( pump() } - /** Song IDs held by any downloaded collection other than `except`. */ - function songsInOtherCollections(except: string) { - const held = new Set() + /** Song IDs kept by Other Downloaded Songs or a collection besides `except`. */ + function songsHeldElsewhere(except?: string) { + const held = new Set(otherSongIds) for (const [key, collection] of collections) { if (key === except) continue - for (const songId of collection.songIds) held.add(songId) + for (const songId of collectionSongIds(collection)) held.add(songId) } return held } + /** Deletes the audio of songs nothing holds anymore. */ + async function deleteUnheld(songIds: readonly string[]) { + const held = songsHeldElsewhere() + await deleteAudio(songIds.filter((songId) => !held.has(songId))) + } + + /** + * Gives songs back to collections they were removed from. Returns the songs + * no collection took back. + */ + function restoreToCollections(songIds: readonly string[]) { + const unclaimed = new Set(songIds) + for (const [key, collection] of collections) { + const removed = collection.removedSongIds + if (!removed?.some((songId) => unclaimed.has(songId))) continue + collections.set(key, { + ...collection, + removedSongIds: removed.filter((songId) => !unclaimed.has(songId)), + }) + for (const songId of removed) unclaimed.delete(songId) + } + return unclaimed + } + + /** Removes `songIds` from one collection's download. */ + function removeFromCollection(key: string, songIds: readonly string[]) { + const collection = collections.get(key) + if (!collection) return + const members = new Set(collection.songIds) + const removed = new Set(collection.removedSongIds) + for (const songId of songIds) if (members.has(songId)) removed.add(songId) + collections.set(key, { ...collection, removedSongIds: [...removed] }) + } + return { load, subscribe(listener: () => void) { @@ -220,35 +291,73 @@ export function createDownloadQueue( }, getDownloaded: (songId: string) => downloaded.get(songId), getCollection: (ref: CollectionRef) => collections.get(collectionKey(ref)), + /** + * How a song is downloaded as seen from `from`. "here" means that download + * holds it (outside a downloaded collection, Other Downloaded Songs does). + * "device" means only another download holds it, and "removed" means it + * was removed from the downloaded collection `from` but is still on the + * device. Menus offer Remove only for "here"; the downloaded icon shows + * for "here" and "device". + */ + downloadState(songId: string, from?: DownloadSource): SongDownloadState { + if (!downloaded.has(songId)) return "none" + const collection = + from && from !== "other" + ? collections.get(collectionKey(from)) + : undefined + if (collection) { + return collection.removedSongIds?.includes(songId) ? "removed" : "here" + } + return otherSongIds.has(songId) ? "here" : "device" + }, collections: () => [...collections.values()], isQueued, status, - /** Queues songs that are not downloaded or queued yet. */ + /** Songs downloaded on their own, in the order they were added. */ + otherSongIds: () => [...otherSongIds], + + /** + * Downloads songs on their own. Songs removed from a downloaded album or + * playlist go back to it; the rest join Other Downloaded Songs, including + * songs already on the device for another download. + */ async enqueue( songs: readonly DownloadableSong[], quality: DownloadQuality ) { await load() + const unclaimed = restoreToCollections(songs.map((song) => song.id)) + for (const songId of unclaimed) otherSongIds.add(songId) enqueueLoaded(songs, quality) notify() pump() + await saveIndex() }, - /** Downloads an album or playlist and remembers it for syncing. */ + /** + * Downloads an album or playlist and remembers it for syncing. An album + * takes its songs out of Other Downloaded Songs. + */ async downloadCollection( collection: Omit, songs: readonly DownloadableSong[] ) { await load() + if (collection.kind === "album") { + for (const song of songs) otherSongIds.delete(song.id) + } collections.set(collectionKey(collection), { - ...collection, + kind: collection.kind, + id: collection.id, + title: collection.title, + quality: collection.quality, songIds: songs.map((song) => song.id), }) enqueueLoaded(songs, collection.quality) notify() pump() - await saveCollections() + await saveIndex() }, /** @@ -267,15 +376,18 @@ export function createDownloadQueue( const before = new Set(collection.songIds) const after = new Set(songIds) const added = songIds.filter((songId) => !before.has(songId)) - const held = songsInOtherCollections(key) - const dropped = collection.songIds.filter( - (songId) => !after.has(songId) && !held.has(songId) - ) + const dropped = collection.songIds.filter((songId) => !after.has(songId)) if (added.length === 0 && dropped.length === 0) return - collections.set(key, { ...collection, songIds: [...songIds] }) - await saveCollections() - if (dropped.length > 0) await remove(dropped) + collections.set(key, { + ...collection, + songIds: [...songIds], + removedSongIds: collection.removedSongIds?.filter((songId) => + after.has(songId) + ), + }) + await saveIndex() + await deleteUnheld(dropped) if (added.length > 0) { enqueueLoaded(await loadSongs(added), collection.quality) notify() @@ -283,26 +395,49 @@ export function createDownloadQueue( } }, - /** Forgets a collection and removes its songs no other collection holds. */ + /** Forgets a collection and removes its songs nothing else holds. */ async removeCollection(ref: CollectionRef) { await load() const key = collectionKey(ref) const collection = collections.get(key) if (!collection) return collections.delete(key) - const held = songsInOtherCollections(key) - await saveCollections() - await remove(collection.songIds.filter((songId) => !held.has(songId))) + await saveIndex() + await deleteUnheld(collection.songIds) }, - /** Cancels queued songs and removes downloaded ones. */ - remove, + /** + * Removes song downloads from one download: `from` when it is a downloaded + * collection, else Other Downloaded Songs. A song stays on the device while + * anything else holds it. + */ + async removeSongs(songIds: readonly string[], from?: DownloadSource) { + await load() + if (from && from !== "other" && collections.has(collectionKey(from))) { + removeFromCollection(collectionKey(from), songIds) + } else { + for (const songId of songIds) otherSongIds.delete(songId) + } + notify() + await saveIndex() + await deleteUnheld(songIds) + }, + + /** Empties Other Downloaded Songs, keeping songs a collection holds. */ + async removeOtherSongs() { + await load() + const songIds = [...otherSongIds] + otherSongIds.clear() + await saveIndex() + await deleteUnheld(songIds) + }, async removeAll() { await load() collections.clear() - await saveCollections() - await remove([ + otherSongIds.clear() + await saveIndex() + await deleteAudio([ ...downloaded.keys(), ...running.keys(), ...waiting.map(({ song }) => song.id), @@ -324,12 +459,11 @@ export function createDownloadQueue( bytes += song.bytes } - const inCollections = new Set() const collectionRows = [...collections.values()].map((collection) => { let collectionBytes = 0 let fallbackCount = 0 - for (const songId of collection.songIds) { - inCollections.add(songId) + const songIds = collectionSongIds(collection) + for (const songId of songIds) { const song = downloaded.get(songId) if (!song) continue collectionBytes += song.bytes @@ -338,16 +472,17 @@ export function createDownloadQueue( return { collection, bytes: collectionBytes, - status: status(collection.songIds), + status: status(songIds), fallbackCount, } }) - const singles = { bytes: 0, songIds: [] as string[] } - for (const song of downloaded.values()) { - if (inCollections.has(song.songId)) continue - singles.bytes += song.bytes - singles.songIds.push(song.songId) + const otherSongs = { bytes: 0, songIds: [] as string[] } + for (const songId of otherSongIds) { + const song = downloaded.get(songId) + if (!song) continue + otherSongs.bytes += song.bytes + otherSongs.songIds.push(songId) } return { @@ -356,7 +491,7 @@ export function createDownloadQueue( queued: running.size + waiting.length, byQuality, collections: collectionRows.sort((a, b) => b.bytes - a.bytes), - singles, + otherSongs, } }, } diff --git a/packages/convex/download-quality.ts b/packages/convex/download-quality.ts index b445b2f..aca1b11 100644 --- a/packages/convex/download-quality.ts +++ b/packages/convex/download-quality.ts @@ -1,4 +1,4 @@ -import type { PlaybackSource } from "./playback-stream" +import type { PlaybackSource, PlaybackStreamPlan } from "./playback-stream" /** Qualities a listener can pick when downloading, lowest first. */ export const DOWNLOAD_QUALITIES = [ @@ -82,6 +82,34 @@ export function downloadPlan( } } +/** + * The download quality holding the same audio a stream plan plays, so a + * download can stand in for streaming. Low has no download equivalent. + */ +export function streamDownloadQuality( + plan: PlaybackStreamPlan +): DownloadQuality | undefined { + if (plan.preferAtmos) return "atmos" + if (!plan.transcodeNeeded) { + return plan.source === "lossless" ? "lossless" : "high" + } + if (plan.kbps === HIGH_KBPS) return "high" + if (plan.kbps === MEDIUM_KBPS) return "medium" + return undefined +} + +/** + * Queue origin for playback started from the Downloads page, where downloads + * play whatever their quality. `list` keeps origins of different lists apart. + */ +export function downloadsQueueOrigin(list: string) { + return `downloads:${list}` +} + +export function isDownloadsQueueOrigin(origin: string | undefined) { + return origin?.startsWith("downloads:") ?? false +} + export type DownloadOption = { quality: DownloadQuality /** How many of the songs fall back to High for this quality. */