From c1a8ad691afaea0a4348b06e347c8ed80c6bb76a Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Thu, 19 Nov 2026 13:06:57 -0500 Subject: [PATCH] feat: download music for offline playback on web and mobile Users pick Medium, High, Lossless, or Dolby Atmos per download (with optional "Remember my choice"). Songs without the picked format fall back to High, and Medium is always transcoded. Web stores audio in IndexedDB like YouTube Music; mobile stores files per server via expo-file-system. Downloaded playlists stay in sync, and settings break down storage by quality and by album or playlist. Co-Authored-By: Claude Opus 5.5 --- .../app/(app)/(tabs)/home/album/[id].tsx | 85 +++- .../app/(app)/(tabs)/home/playlist/[id].tsx | 75 +++- .../(app)/(tabs)/home/playlist/favorites.tsx | 21 +- .../mobile/app/(app)/(tabs)/home/settings.tsx | 337 +++++++++++++- apps/mobile/app/(app)/_layout.tsx | 127 +++--- .../components/download-header-button.tsx | 110 +++++ apps/mobile/components/media-cards.tsx | 8 + apps/mobile/components/media-context-menu.tsx | 23 + apps/mobile/components/media-menu.android.tsx | 2 + apps/mobile/components/player.tsx | 13 + apps/mobile/contexts/downloads.tsx | 424 ++++++++++++++++++ apps/mobile/hooks/use-media-menu-actions.ts | 61 ++- apps/mobile/hooks/use-native-playlist-sync.ts | 14 +- apps/mobile/lib/downloads.ts | 164 +++++++ apps/mobile/package.json | 1 + apps/web/app/(app)/layout.tsx | 27 +- apps/web/app/api/download/options/route.ts | 103 +++++ apps/web/app/api/song/[id]/download/route.ts | 150 +++++++ apps/web/components/album-card.tsx | 20 + apps/web/components/album-view.tsx | 24 + apps/web/components/download-button.tsx | 112 +++++ apps/web/components/downloads-provider.tsx | 319 +++++++++++++ apps/web/components/downloads-settings.tsx | 250 +++++++++++ apps/web/components/media-context-menu.tsx | 23 + apps/web/components/options-modal.tsx | 10 +- apps/web/components/playback-provider.tsx | 191 +++++--- apps/web/components/playlist-card.tsx | 20 + apps/web/components/playlist-view.tsx | 28 ++ apps/web/components/search-song-item.tsx | 16 + apps/web/components/track-row.tsx | 10 +- apps/web/hooks/use-downloads.ts | 62 +++ apps/web/hooks/use-media-actions.ts | 30 +- apps/web/lib/downloads.ts | 166 +++++++ apps/web/lib/server-audio-stream.ts | 10 +- apps/web/lib/server-song.ts | 21 + packages/convex/client/download-queue.ts | 363 +++++++++++++++ packages/convex/convex/library.ts | 15 + packages/convex/download-quality.ts | 150 +++++++ packages/convex/package.json | 8 + pnpm-lock.yaml | 3 + 40 files changed, 3420 insertions(+), 176 deletions(-) create mode 100644 apps/mobile/components/download-header-button.tsx create mode 100644 apps/mobile/contexts/downloads.tsx create mode 100644 apps/mobile/lib/downloads.ts create mode 100644 apps/web/app/api/download/options/route.ts create mode 100644 apps/web/app/api/song/[id]/download/route.ts create mode 100644 apps/web/components/download-button.tsx create mode 100644 apps/web/components/downloads-provider.tsx create mode 100644 apps/web/components/downloads-settings.tsx create mode 100644 apps/web/hooks/use-downloads.ts create mode 100644 apps/web/lib/downloads.ts create mode 100644 packages/convex/client/download-queue.ts create mode 100644 packages/convex/download-quality.ts diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx index 0f15715..bd97814 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -22,6 +22,12 @@ import { DiscHeader, } from "@/components/collection-list" import { AudioFormatBadge } from "@/components/audio-format-badge" +import { DownloadHeaderButton } from "@/components/download-header-button" +import { + useDownloads, + useIsCollectionDownloaded, + useIsSongDownloaded, +} from "@/contexts/downloads" import { CoverImage } from "@/components/cover-image" import { @@ -81,6 +87,17 @@ export default function AlbumScreen() { () => album?.tracks.map((track) => track.id as Id<"songs">) ?? [], [album] ) + const { requestDownload, removeDownload } = useDownloads() + const downloadTarget = useMemo( + () => ({ + kind: "album" as const, + id: typeof id === "string" ? id : "", + title: album?.title ?? "", + songIds, + }), + [album?.title, id, songIds] + ) + const albumDownloaded = useIsCollectionDownloaded(downloadTarget) useEffect(() => { if (album) { @@ -193,28 +210,41 @@ export default function AlbumScreen() { } : {}), headerRight: () => ( - - void handleAlbumDetailAction( - album.id as Id<"albums">, - songIds, - action, - album.artist.id as Id<"artists"> - ) - } - > - - - - + + + { + if (action === "download") { + void requestDownload(downloadTarget) + } else if (action === "remove-download") { + void removeDownload(downloadTarget) + } else { + void handleAlbumDetailAction( + album.id as Id<"albums">, + songIds, + action, + album.artist.id as Id<"artists"> + ) + } + }} + > + + + + + ), }} /> @@ -451,6 +481,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({ }) { const Row = Platform.OS !== "web" ? SongSwipeRow : Pressable const { config } = useServerConfig() + const downloaded = useIsSongDownloaded(track.id) return ( ) : null} + {downloaded ? ( + + ) : null} {formatDuration(track.durationSeconds)} @@ -527,6 +567,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({ const styles = StyleSheet.create({ empty: { flex: 1, alignItems: "center", justifyContent: "center" }, + headerActions: { flexDirection: "row", alignItems: "center", gap: 16 }, cover: { width: 220, height: 220, diff --git a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx index c3c7830..d2dd3bb 100644 --- a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx @@ -44,6 +44,12 @@ import { import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" import { contentBottomInset, SongListRow } from "@/components/player" +import { DownloadHeaderButton } from "@/components/download-header-button" +import { + FAVORITES_DOWNLOAD_ID, + useDownloads, + useIsCollectionDownloaded, +} from "@/contexts/downloads" import { useFavorites } from "@/contexts/favorites" import { usePlaybackActions } from "@/contexts/playback" import { useServerConfig } from "@/contexts/server-config" @@ -180,6 +186,7 @@ function PlaylistContent({ usePlaybackActions() const { isSongFavorite } = useFavorites() const { handleSongAction, handlePlaylistDetailAction } = useMediaMenuActions() + const { requestDownload, removeDownload } = useDownloads() const subscribe = useMutation(api.playlists.subscribeToPlaylist) const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist) const deletePlaylist = useMutation(api.playlists.deletePlaylist) @@ -192,6 +199,16 @@ function PlaylistContent({ const { filteredSongs, onQueryChange, onSearchSubmit } = usePlaylistSearch(songs) const swipeGroup = useSwipeRowGroup() + const downloadTarget = useMemo( + () => ({ + kind: "playlist" as const, + id: playlistId ?? FAVORITES_DOWNLOAD_ID, + title: playlist.title, + songIds, + }), + [playlist.title, playlistId, songIds] + ) + const playlistDownloaded = useIsCollectionDownloaded(downloadTarget) const handlePlaySong = useCallback( (song: BrowseSong) => @@ -275,6 +292,14 @@ function PlaylistContent({ } return } + if (action === "download") { + void requestDownload(downloadTarget) + return + } + if (action === "remove-download") { + void removeDownload(downloadTarget) + return + } void handlePlaylistDetailAction(songIds, action) } @@ -292,31 +317,42 @@ function PlaylistContent({ } : {}), headerRight: () => ( - - - - - + + + + + + + + ), } }, [ canEdit, colors.foreground, deletePlaylist, + downloadTarget, + playlistDownloaded, + requestDownload, + removeDownload, handlePlaylistDetailAction, palette.foreground, palette.isDark, @@ -620,6 +656,7 @@ const PlaylistHero = memo(function PlaylistHero({ const styles = StyleSheet.create({ emptyResults: { padding: spacing.lg, textAlign: "center" }, empty: { flex: 1, alignItems: "center", justifyContent: "center" }, + headerActions: { flexDirection: "row", alignItems: "center", gap: 16 }, listContent: { paddingBottom: contentBottomInset }, cover: { width: 200, diff --git a/apps/mobile/app/(app)/(tabs)/home/playlist/favorites.tsx b/apps/mobile/app/(app)/(tabs)/home/playlist/favorites.tsx index a19835c..2750246 100644 --- a/apps/mobile/app/(app)/(tabs)/home/playlist/favorites.tsx +++ b/apps/mobile/app/(app)/(tabs)/home/playlist/favorites.tsx @@ -16,6 +16,8 @@ import { CollectionDivider } from "@/components/collection-list" import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" import { contentBottomInset, SongListRow } from "@/components/player" +import { DownloadHeaderButton } from "@/components/download-header-button" +import { FAVORITES_DOWNLOAD_ID } from "@/contexts/downloads" import { useFavorites } from "@/contexts/favorites" import { usePlaybackActions } from "@/contexts/playback" import { useServerConfig } from "@/contexts/server-config" @@ -41,6 +43,23 @@ export default function FavoritesScreen() { const { isSongFavorite } = useFavorites() const { handleSongAction } = useMediaMenuActions() const songIds = useMemo(() => songs.map((song) => song.id), [songs]) + const screenOptions = useMemo( + () => ({ + ...SCREEN_OPTIONS, + headerRight: () => ( + + ), + }), + [colors.foreground, favorites?.title, songIds] + ) const { filteredSongs, onQueryChange, onSearchSubmit } = usePlaylistSearch(songs) @@ -104,7 +123,7 @@ export default function FavoritesScreen() { return ( <> - + @@ -75,6 +89,7 @@ const QUALITY_OPTIONS: { const SECTIONS: SectionConfig[] = [ { id: "profile", label: "Profile", icon: "person-circle-outline" }, { id: "quality", label: "Playback", icon: "volume-high-outline" }, + { id: "downloads", label: "Downloads", icon: "arrow-down-circle-outline" }, { id: "library", label: "Library", icon: "library-outline", admin: true }, { id: "users", label: "Users", icon: "people-outline", admin: true }, ] @@ -156,6 +171,7 @@ export default function SettingsScreen() { ) : null} {section === "quality" ? : null} + {section === "downloads" ? : null} {section === "library" && isAdmin ? : null} {section === "users" && isAdmin && allUsers ? ( @@ -432,6 +448,298 @@ function QualitySection({ user }: { user: CurrentUser }) { ) } +/** Shades of the text color, faintest for the smallest files. */ +const QUALITY_OPACITY: Record = { + medium: 0.25, + high: 0.45, + lossless: 0.7, + atmos: 1, +} + +function songCount(count: number) { + return count === 1 ? "1 song" : `${count} songs` +} + +function QualityName({ + quality, + color, + backgroundColor, +}: { + quality: DownloadQuality + color: string + backgroundColor: string +}) { + if (quality === "lossless" || quality === "atmos") { + return ( + + ) + } + return ( + + {DOWNLOAD_QUALITY_LABELS[quality]} + + ) +} + +function confirm(title: string, onConfirm: () => void) { + Alert.alert(title, undefined, [ + { text: "Cancel", style: "cancel" }, + { text: "Remove", style: "destructive", onPress: onConfirm }, + ]) +} + +function RememberedQualityCard() { + const colors = useThemeColors() + // undefined until read; null means ask every time. + const [remembered, setRemembered] = useState() + useEffect(() => { + void readRememberedDownloadQuality().then((quality) => + setRemembered(quality ?? null) + ) + }, []) + const options: { + value: DownloadQuality | null + label: string + detail: string + }[] = [ + { value: null, label: "Ask every time", detail: "Choose when downloading" }, + ...DOWNLOAD_QUALITIES.map((quality) => ({ + value: quality, + label: DOWNLOAD_QUALITY_LABELS[quality], + detail: DOWNLOAD_QUALITY_DETAILS[quality], + })), + ] + + return ( + + {options.map((option) => { + const selected = remembered === option.value + return ( + { + setRemembered(option.value) + void writeRememberedDownloadQuality(option.value ?? undefined) + }} + style={[ + styles.optionRow, + { + borderColor: selected ? colors.primary : colors.border, + backgroundColor: selected ? colors.muted : colors.card, + }, + ]} + > + + + {option.label} + + + {option.detail} + + + {selected ? ( + + ) : null} + + ) + })} + + ) +} + +function DownloadsSection() { + const colors = useThemeColors() + const { queue } = useDownloads() + const version = useDownloadsVersion() + const breakdown = useMemo( + () => queue?.breakdown(), + // version invalidates the breakdown when downloads change. + // eslint-disable-next-line react-hooks/exhaustive-deps + [queue, version] + ) + if (!queue || !breakdown) return null + const qualities = breakdown.byQuality.filter((entry) => entry.songs > 0) + + return ( + <> + + + {formatBytes(breakdown.bytes)} · {songCount(breakdown.songs)} + {breakdown.queued > 0 ? ` · ${breakdown.queued} downloading` : ""} + + {breakdown.songs > 0 ? ( + <> + + {qualities.map((entry) => ( + + ))} + + {qualities.map((entry) => ( + + + + + + + {songCount(entry.songs)} + + + {formatBytes(entry.bytes)} + + + ))} + + ) : null} + + + + + {breakdown.collections.length > 0 || + breakdown.singles.songIds.length > 0 ? ( + + {breakdown.collections.map( + ({ collection, bytes, status, fallbackCount }) => ( + + + + {collection.title} + + + + {collection.kind === "album" ? "Album" : "Playlist"} · + + + {fallbackCount > 0 ? ( + + ({fallbackCount} in High) + + ) : null} + {status.downloaded < status.total ? ( + + · {status.downloaded} of {status.total} + + ) : null} + + + + {formatBytes(bytes)} + + + confirm( + `Remove ${collection.title}?`, + () => void queue.removeCollection(collection) + ) + } + > + + + + ) + )} + {breakdown.singles.songIds.length > 0 ? ( + + + + Individual songs + + + {songCount(breakdown.singles.songIds.length)} + + + + {formatBytes(breakdown.singles.bytes)} + + + confirm( + "Remove individual songs?", + () => void queue.remove(breakdown.singles.songIds) + ) + } + > + + + + ) : null} + + + + + Remove download? + + + Cancel + void removeDownload(target)} + > + Remove + + + + + + ) +} diff --git a/apps/web/components/downloads-provider.tsx b/apps/web/components/downloads-provider.tsx new file mode 100644 index 0000000..2709353 --- /dev/null +++ b/apps/web/components/downloads-provider.tsx @@ -0,0 +1,319 @@ +"use client" + +import * as React from "react" +import { useConvex, useQuery } from "convex/react" +import { toast } from "sonner" + +import { AudioFormatBadge } from "@/components/audio-format-badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" +import { Label } from "@/components/ui/label" +import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group" +import { useCachedQuery } from "@/hooks/use-cached-query" +import { useDownloadsVersion } from "@/hooks/use-downloads" +import { + downloadQueue, + readRememberedDownloadQuality, + requestPersistentStorage, + writeRememberedDownloadQuality, +} from "@/lib/downloads" +import { api } from "@otunes/convex/_generated/api" +import type { Id } from "@otunes/convex/_generated/dataModel" +import type { + CollectionRef, + DownloadableSong, +} from "@otunes/convex/client/download-queue" +import { + DOWNLOAD_OPTIONS_PATH, + DOWNLOAD_QUALITY_DETAILS, + DOWNLOAD_QUALITY_LABELS, + formatBytes, + type DownloadOptionsResponse, + type DownloadQuality, + type SizedDownloadOption, +} from "@otunes/convex/download-quality" + +/** Songs on their own, or an album or playlist that stays downloaded as a whole. */ +export type DownloadTarget = + | { kind: "songs"; songIds: string[]; title: string } + | (CollectionRef & { title: string; songIds: string[] }) + +/** The Favorites playlist has no ID, so downloads use this one. */ +export const FAVORITES_DOWNLOAD_ID = "favorites" + +type DownloadsContextValue = { + /** Asks for a quality (unless remembered) and starts downloading. */ + requestDownload: (target: DownloadTarget) => Promise + removeDownload: (target: DownloadTarget) => Promise +} + +const DownloadsContext = React.createContext(null) + +export function useDownloads() { + const context = React.useContext(DownloadsContext) + if (!context) { + throw new Error("useDownloads must be used within DownloadsProvider") + } + return context +} + +async function fetchDownloadOptions(songIds: string[]) { + const response = await fetch(DOWNLOAD_OPTIONS_PATH, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ songIds }), + }) + if (!response.ok) { + throw new Error("Could not reach the server to download") + } + return (await response.json()) as DownloadOptionsResponse +} + +function startDownload( + target: DownloadTarget, + songs: DownloadableSong[], + quality: DownloadQuality +) { + requestPersistentStorage() + if (target.kind === "songs") { + return downloadQueue.enqueue(songs, quality) + } + return downloadQueue.downloadCollection( + { kind: target.kind, id: target.id, title: target.title, quality }, + songs + ) +} + +function optionDetail(option: SizedDownloadOption, songCount: number) { + if (option.fallbackCount === 0) { + return DOWNLOAD_QUALITY_DETAILS[option.quality] + } + const included = songCount - option.fallbackCount + return `${included} of ${songCount} songs, ${option.fallbackCount} in High` +} + +function QualityLabel({ quality }: { quality: DownloadQuality }) { + if (quality === "lossless" || quality === "atmos") { + return ( + + ) + } + return ( + + {DOWNLOAD_QUALITY_LABELS[quality]} + + ) +} + +function DownloadQualityDialog({ + pending, + onClose, +}: { + pending: { target: DownloadTarget; response: DownloadOptionsResponse } | null + onClose: () => void +}) { + const [quality, setQuality] = React.useState("high") + const [remember, setRemember] = React.useState(false) + const options = pending?.response.options ?? [] + const songCount = pending?.response.songs.length ?? 0 + + async function handleDownload() { + if (!pending) return + if (remember) writeRememberedDownloadQuality(quality) + onClose() + await startDownload(pending.target, pending.response.songs, quality) + } + + return ( + !open && onClose()}> + + + + Download “{pending?.target.title}” + + + setQuality(value as DownloadQuality)} + className="gap-0" + > + {options.map((option) => ( + + ))} + +
+ setRemember(checked === true)} + /> + +
+ + + + +
+
+ ) +} + +const SYNC_BATCH_SIZE = 200 + +/** Keeps a downloaded playlist's songs in step with the playlist. */ +function useSyncDownloadedPlaylist( + id: string, + songIds: readonly string[] | undefined +) { + const convex = useConvex() + React.useEffect(() => { + if (!songIds) return + void downloadQueue + .syncCollection({ kind: "playlist", id }, songIds, async (added) => { + const songs: DownloadableSong[] = [] + for (let start = 0; start < added.length; start += SYNC_BATCH_SIZE) { + const batch = await convex.query(api.library.getSongsForPlayback, { + ids: added.slice(start, start + SYNC_BATCH_SIZE) as Id<"songs">[], + }) + for (const song of batch) if (song) songs.push(song) + } + return songs + }) + .catch(() => {}) + }, [convex, id, songIds]) +} + +function PlaylistSync({ id }: { id: string }) { + const songIds = useQuery(api.playlists.getPlaylistSongIds, { + playlistId: id as Id<"playlists">, + }) + useSyncDownloadedPlaylist(id, songIds) + return null +} + +function FavoritesSync() { + const favorites = useCachedQuery(api.favorites.getUserFavorites) + const songIds = React.useMemo( + () => favorites?.favoriteSongs.flat(), + [favorites] + ) + useSyncDownloadedPlaylist(FAVORITES_DOWNLOAD_ID, songIds) + return null +} + +function DownloadSync() { + useDownloadsVersion() + return downloadQueue + .collections() + .filter((collection) => collection.kind === "playlist") + .map((collection) => + collection.id === FAVORITES_DOWNLOAD_ID ? ( + + ) : ( + + ) + ) +} + +/** Reports failed songs once per burst instead of once per song. */ +function useFailureToasts() { + React.useEffect(() => { + let failed = 0 + let timer: ReturnType | null = null + const unsubscribe = downloadQueue.onFailure(() => { + failed += 1 + timer ??= setTimeout(() => { + toast.error( + failed === 1 + ? "A song could not be downloaded" + : `${failed} songs could not be downloaded` + ) + failed = 0 + timer = null + }, 1000) + }) + return () => { + unsubscribe() + if (timer) clearTimeout(timer) + } + }, []) +} + +export function DownloadsProvider({ children }: { children: React.ReactNode }) { + const [pending, setPending] = React.useState<{ + target: DownloadTarget + response: DownloadOptionsResponse + } | null>(null) + + useFailureToasts() + React.useEffect(() => { + void downloadQueue.load().catch(() => {}) + }, []) + + const requestDownload = React.useCallback(async (target: DownloadTarget) => { + if (target.songIds.length === 0) return + try { + const response = await fetchDownloadOptions(target.songIds) + const remembered = readRememberedDownloadQuality() + if (remembered) { + await startDownload(target, response.songs, remembered) + toast(`Downloading ${target.title}`) + } else { + setPending({ target, response }) + } + } catch (error) { + toast.error(error instanceof Error ? error.message : "Download failed") + } + }, []) + + const removeDownload = React.useCallback(async (target: DownloadTarget) => { + if (target.kind === "songs") await downloadQueue.remove(target.songIds) + else await downloadQueue.removeCollection(target) + }, []) + + const value = React.useMemo( + () => ({ requestDownload, removeDownload }), + [requestDownload, removeDownload] + ) + + return ( + + {children} + + setPending(null)} + /> + + ) +} diff --git a/apps/web/components/downloads-settings.tsx b/apps/web/components/downloads-settings.tsx new file mode 100644 index 0000000..65dbd35 --- /dev/null +++ b/apps/web/components/downloads-settings.tsx @@ -0,0 +1,250 @@ +"use client" + +import * as React from "react" +import { Trash2 } from "lucide-react" + +import { AudioFormatBadge } from "@/components/audio-format-badge" +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogTrigger, +} from "@/components/ui/alert-dialog" +import { Button } from "@/components/ui/button" +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select" +import { useDownloadsVersion } from "@/hooks/use-downloads" +import { + downloadQueue, + readRememberedDownloadQuality, + writeRememberedDownloadQuality, +} from "@/lib/downloads" +import { + DOWNLOAD_QUALITIES, + DOWNLOAD_QUALITY_LABELS, + formatBytes, + type DownloadQuality, +} from "@otunes/convex/download-quality" + +const ASK_EVERY_TIME = "ask" + +/** Shades of the text color, darkest for the smallest files. */ +const QUALITY_OPACITY: Record = { + medium: 0.25, + high: 0.45, + lossless: 0.7, + atmos: 1, +} + +function QualityName({ quality }: { quality: DownloadQuality }) { + if (quality === "lossless" || quality === "atmos") { + return + } + return {DOWNLOAD_QUALITY_LABELS[quality]} +} + +function songCount(count: number) { + return count === 1 ? "1 song" : `${count} songs` +} + +function RememberedQualitySelect() { + const [value, setValue] = React.useState( + () => readRememberedDownloadQuality() ?? ASK_EVERY_TIME + ) + return ( +
+ Download quality + +
+ ) +} + +/** Storage used by downloads in this browser, by quality and by album or playlist. */ +export function DownloadsSettings() { + const version = useDownloadsVersion() + const breakdown = React.useMemo( + () => downloadQueue.breakdown(), + // version invalidates the breakdown when downloads change. + // eslint-disable-next-line react-hooks/exhaustive-deps + [version] + ) + const qualities = breakdown.byQuality.filter((entry) => entry.songs > 0) + + return ( +
+
+

Downloads

+ + {formatBytes(breakdown.bytes)} · {songCount(breakdown.songs)} + {breakdown.queued > 0 ? ` · ${breakdown.queued} downloading` : ""} + +
+ + + + {breakdown.songs > 0 ? ( +
+
+ {qualities.map((entry) => ( +
+ ))} +
+
+ {qualities.map((entry) => ( +
+ + + + + + {songCount(entry.songs)} + + + {formatBytes(entry.bytes)} + +
+ ))} +
+
+ ) : null} + + {breakdown.collections.length > 0 || + breakdown.singles.songIds.length > 0 ? ( +
+ {breakdown.collections.map( + ({ collection, bytes, status, fallbackCount }) => ( +
+
+

{collection.title}

+

+ + {collection.kind === "album" ? "Album" : "Playlist"} + + · + + {fallbackCount > 0 ? ( + ({fallbackCount} in High) + ) : null} + {status.downloaded < status.total ? ( + <> + · + + {status.downloaded} of {status.total} + + + ) : null} +

+
+ {formatBytes(bytes)} + +
+ ) + )} + {breakdown.singles.songIds.length > 0 ? ( +
+
+

Individual songs

+

+ {songCount(breakdown.singles.songIds.length)} +

+
+ + {formatBytes(breakdown.singles.bytes)} + + +
+ ) : null} +
+ ) : ( +

+ Nothing downloaded in this browser. +

+ )} + + {breakdown.songs > 0 || breakdown.queued > 0 ? ( + + + + + + + Remove all downloads? + + + Cancel + void downloadQueue.removeAll()} + > + Remove + + + + + ) : null} +
+ ) +} diff --git a/apps/web/components/media-context-menu.tsx b/apps/web/components/media-context-menu.tsx index f7d5346..bc7d59d 100644 --- a/apps/web/components/media-context-menu.tsx +++ b/apps/web/components/media-context-menu.tsx @@ -3,6 +3,8 @@ import * as React from "react" import Link from "next/link" import { + ArrowDownToLine, + CircleX, GalleryVerticalEnd, ListEnd, ListPlus, @@ -40,6 +42,8 @@ export type MediaContextAction = | "shuffle" | "create-station" | "favorite" + | "download" + | "remove-download" export type MediaContextNavigation = { artist?: { id: string } @@ -83,6 +87,7 @@ export function MediaContextMenuItems({ stationArtistId, navigation, share, + downloaded, }: { selectedCount: number onAction: (action: MediaContextAction) => void @@ -92,6 +97,8 @@ export function MediaContextMenuItems({ stationArtistId?: string navigation?: MediaContextNavigation share?: MediaShareContext + /** Shows Download, or Remove Download when true. Omit to hide both. */ + downloaded?: boolean }) { const { artist, album } = navigation ?? {} const showShare = shouldShowShare(share, selectedCount) @@ -117,6 +124,18 @@ export function MediaContextMenuItems({ {actionLabel(playlistLabel, selectedCount)} + {downloaded !== undefined ? ( + onAction(downloaded ? "remove-download" : "download")} + > + {actionLabel( + downloaded ? "Remove Download" : "Download", + selectedCount + )} + {downloaded ? : } + + ) : null} {menu.children} @@ -283,6 +304,7 @@ export function MediaContextMenu({ stationArtistId, navigation, share, + downloaded, inSelectionRange = false, trackRowTrigger = true, triggerClassName, @@ -324,6 +346,7 @@ export function MediaContextMenu({ stationArtistId={stationArtistId} navigation={navigation} share={share} + downloaded={downloaded} /> {children} diff --git a/apps/web/components/options-modal.tsx b/apps/web/components/options-modal.tsx index 3b2d326..36f12df 100644 --- a/apps/web/components/options-modal.tsx +++ b/apps/web/components/options-modal.tsx @@ -39,6 +39,7 @@ import { TableHeader, TableRow, } from "@/components/ui/table" +import { DownloadsSettings } from "@/components/downloads-settings" import { usePlayback } from "@/components/playback-provider" import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" @@ -46,7 +47,7 @@ import type { PlaybackQuality } from "@otunes/convex/playback-stream" import { resizeProfileImageToDataUrl } from "@/lib/resize-image" import { cn } from "@/lib/utils" -type Section = "profile" | "quality" | "users" | "library" +type Section = "profile" | "quality" | "downloads" | "users" | "library" type CurrentUser = { _id: Id<"users"> @@ -949,6 +950,12 @@ export function OptionsModal({ > Quality + setSection("downloads")} + > + Downloads + {isAdmin ? ( @@ -979,6 +986,7 @@ export function OptionsModal({
{activeSection === "profile" && } {activeSection === "quality" && } + {activeSection === "downloads" && } {activeSection === "library" && isAdmin ? ( ) : null} diff --git a/apps/web/components/playback-provider.tsx b/apps/web/components/playback-provider.tsx index e4e9cf2..2ab0a58 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -35,6 +35,7 @@ import { useCachedQuery } from "@/hooks/use-cached-query" 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 { flushPersistentCache } from "@/lib/persistent-cache" import * as playbackQueue from "@otunes/convex/client/playback-queue" import type { RepeatMode } from "@otunes/convex/client/playback-queue" @@ -207,10 +208,52 @@ function playbackLoadSettings( } } -function songLoadKey(songId: string, settings: PlaybackLoadSettings) { +/** 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. */ +function audioSourceChoice( + songId: string, + user: { preferAtmos?: boolean; playbackQuality?: PlaybackQuality } | null, + dolbyAtmosSupported: boolean | null, + files: Record | undefined +): AudioSourceChoice | null { + if (downloadQueue.getDownloaded(songId)) { + return { kind: "download" } + } + if (!user || !files) { + return null + } + return { + kind: "stream", + settings: playbackLoadSettings(user, dolbyAtmosSupported, files), + } +} + +function songLoadKey(songId: string, source: AudioSourceChoice) { + if (source.kind === "download") { + return `${songId}:download` + } + const { settings } = source return `${songId}:${settings.preferAtmos}:${settings.playbackQuality}:${settings.useHls ? "hls" : "file"}` } +/** + * True when `loadedKey` is this song from the other side of download vs + * stream. Finishing or removing a download keeps the loaded audio playing. + */ +function switchesDownloadSource( + loadedKey: string | null, + songId: string, + source: AudioSourceChoice +) { + if (!loadedKey?.startsWith(`${songId}:`)) { + return false + } + return (source.kind === "download") !== loadedKey.endsWith(":download") +} + function destroyHlsInstance(hlsRef: RefObject) { hlsRef.current?.destroy() hlsRef.current = null @@ -242,21 +285,11 @@ function loadAudioSource( audio: HTMLAudioElement, hlsRef: RefObject, songId: string, - settings: PlaybackLoadSettings, + source: AudioSourceChoice, onReady: () => void ): AudioSourceCleanup { let disposed = false let hlsInstance: Hls | null = null - const directUrl = songPlayPath( - songId, - settings.playbackQuality, - settings.preferAtmos - ) - const hlsUrl = songHlsPlaylistPath( - songId, - settings.playbackQuality, - settings.preferAtmos - ) const onReadyToPlay = () => { audio.removeEventListener("loadedmetadata", onReadyToPlay) @@ -269,6 +302,48 @@ function loadAudioSource( audio.addEventListener("loadeddata", onReadyToPlay) audio.addEventListener("canplay", onReadyToPlay) + const cleanup = () => { + disposed = true + audio.removeEventListener("loadedmetadata", onReadyToPlay) + audio.removeEventListener("loadeddata", onReadyToPlay) + audio.removeEventListener("canplay", onReadyToPlay) + if (hlsInstance && hlsRef.current === hlsInstance) { + hlsInstance.destroy() + hlsRef.current = null + } + } + + if (source.kind === "download") { + void downloadedAudioUrl(songId) + .catch(() => null) + .then((url) => { + if (disposed) { + return + } + if (!url) { + // Removed since it was chosen; the audio error handler reports it. + audio.removeAttribute("src") + audio.load() + return + } + audio.src = url + audio.load() + }) + return cleanup + } + + const { settings } = source + const directUrl = songPlayPath( + songId, + settings.playbackQuality, + settings.preferAtmos + ) + const hlsUrl = songHlsPlaylistPath( + songId, + settings.playbackQuality, + settings.preferAtmos + ) + const loadDirectSource = () => { if (disposed) { return @@ -302,16 +377,7 @@ function loadAudioSource( loadDirectSource() } - return () => { - disposed = true - audio.removeEventListener("loadedmetadata", onReadyToPlay) - audio.removeEventListener("loadeddata", onReadyToPlay) - audio.removeEventListener("canplay", onReadyToPlay) - if (hlsInstance && hlsRef.current === hlsInstance) { - hlsInstance.destroy() - hlsRef.current = null - } - } + return cleanup } export function usePlayback() { @@ -439,6 +505,15 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { getDolbyAtmosSnapshot, () => null ) + // Re-picks audio sources when songs finish downloading or are removed. + const downloadsVersion = useSyncExternalStore( + downloadQueue.subscribe, + downloadQueue.getVersion, + () => 0 + ) + useEffect(() => { + void downloadQueue.load().catch(() => {}) + }, []) const volume = useSyncExternalStore( subscribeVolume, readStoredVolume, @@ -759,18 +834,21 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { return } - if (!user || !currentSongDoc) { + const source = audioSourceChoice( + currentSongId, + user ? { playbackQuality, preferAtmos } : null, + dolbyAtmosSupported, + currentSongDoc?.files + ) + if (!source) { return } + const loadKey = songLoadKey(currentSongId, source) - const settings = playbackLoadSettings( - { playbackQuality, preferAtmos }, - dolbyAtmosSupported, - currentSongDoc.files - ) - const loadKey = songLoadKey(currentSongId, settings) - - if (loadedSongKeyRef.current === loadKey) { + if ( + loadedSongKeyRef.current === loadKey || + switchesDownloadSource(loadedSongKeyRef.current, currentSongId, source) + ) { return } @@ -811,7 +889,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { audio, hlsRef, currentSongId, - settings, + source, requestPlay ) @@ -826,6 +904,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { playbackQuality, preferAtmos, dolbyAtmosSupported, + downloadsVersion, runWithoutAudioSync, destroyHls, clearPreload, @@ -839,16 +918,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { return } - if (!user || !nextQueueSongDoc) { + const source = audioSourceChoice( + nextQueueSongId, + user ? { playbackQuality, preferAtmos } : null, + dolbyAtmosSupported, + nextQueueSongDoc?.files + ) + if (!source) { return } - - const settings = playbackLoadSettings( - { playbackQuality, preferAtmos }, - dolbyAtmosSupported, - nextQueueSongDoc.files - ) - const loadKey = songLoadKey(nextQueueSongId, settings) + const loadKey = songLoadKey(nextQueueSongId, source) if (preloadedSongKeyRef.current === loadKey) { return @@ -867,7 +946,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { preloadAudio, preloadHlsRef, nextQueueSongId, - settings, + source, onPreloadReady ) @@ -888,6 +967,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { playbackQuality, preferAtmos, dolbyAtmosSupported, + downloadsVersion, clearPreload, destroyPreloadHls, ]) @@ -949,19 +1029,21 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { } const preloadAudio = preloadAudioRef.current + const nextSource = nextQueueSongId + ? audioSourceChoice( + nextQueueSongId, + user ?? null, + dolbyAtmosSupported, + nextQueueSongDoc?.files + ) + : null if ( shouldContinuePlaying && preloadAudio && nextQueueSongId && - user && - nextQueueSongDoc + nextSource ) { - const settings = playbackLoadSettings( - user, - dolbyAtmosSupported, - nextQueueSongDoc.files - ) - const nextLoadKey = songLoadKey(nextQueueSongId, settings) + const nextLoadKey = songLoadKey(nextQueueSongId, nextSource) if ( preloadedSongKeyRef.current === nextLoadKey && @@ -1393,8 +1475,15 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { skipPrevious, }) - const currentFormat = - currentSongDoc && user + const currentDownload = currentSongId + ? downloadQueue.getDownloaded(currentSongId) + : undefined + const currentFormat = currentDownload + ? currentDownload.quality === "atmos" || + currentDownload.quality === "lossless" + ? currentDownload.quality + : null + : currentSongDoc && user ? playbackFormat( currentSongDoc.files, user.playbackQuality, diff --git a/apps/web/components/playlist-card.tsx b/apps/web/components/playlist-card.tsx index e65bcd9..2b1e71c 100644 --- a/apps/web/components/playlist-card.tsx +++ b/apps/web/components/playlist-card.tsx @@ -22,6 +22,8 @@ import { DropdownMenuContent, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" +import { useDownloads } from "@/components/downloads-provider" +import { useIsCollectionDownloaded } from "@/hooks/use-downloads" import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" import { api } from "@otunes/convex/_generated/api" import { fetchCachedQuery } from "@otunes/convex/client/cached-query" @@ -32,6 +34,9 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) { const { openAddPlaylistToPlaylist } = useAddToPlaylist() const { playPlaylist } = usePlaybackActions() const { runQueueAction } = useQueueMediaActions() + const { requestDownload, removeDownload } = useDownloads() + const downloadRef = { kind: "playlist" as const, id: playlist.id } + const downloaded = useIsCollectionDownloaded(downloadRef) async function handleCardAction(action: MediaContextAction) { switch (action) { @@ -52,6 +57,20 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) { void runQueueAction(action, songIds) break } + case "download": + case "remove-download": { + const songIds = await fetchCachedQuery( + convex, + cacheScope, + api.playlists.getPlaylistSongIds, + { playlistId: playlist.id as Id<"playlists"> } + ) + const target = { ...downloadRef, title: playlist.title, songIds } + void (action === "download" + ? requestDownload(target) + : removeDownload(target)) + break + } case "favorite": break } @@ -101,6 +120,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) { void handleCardAction(action)} share={{ type: "playlist", playlistId: playlist.id }} /> diff --git a/apps/web/components/playlist-view.tsx b/apps/web/components/playlist-view.tsx index 637ccac..1a0d93f 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -18,7 +18,13 @@ import { } from "lucide-react" import { toast } from "sonner" +import { DownloadButton } 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 { useCurrentSongId, usePlaybackActions, @@ -158,7 +164,27 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { const handleMediaAction = useTrackListMediaAction({ selectedIds, songs }) + const { requestDownload, removeDownload } = useDownloads() + const downloadTarget = React.useMemo( + () => ({ + kind: "playlist" as const, + id: playlist.id ?? FAVORITES_DOWNLOAD_ID, + title: playlist.title, + songIds: playlistSongIds, + }), + [playlist.id, playlist.title, playlistSongIds] + ) + const playlistDownloaded = useIsCollectionDownloaded(downloadTarget) + function handlePlaylistMediaAction(action: MediaContextAction) { + if (action === "download") { + void requestDownload(downloadTarget) + return + } + if (action === "remove-download") { + void removeDownload(downloadTarget) + return + } runSongsAction(action, playlistSongIds) } @@ -374,6 +400,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { {isSubscribed ? "Subscribed" : "Subscribe"} ) : null} + {!isFavorites ? (