From c1a8ad691afaea0a4348b06e347c8ed80c6bb76a Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Thu, 19 Nov 2026 13:06:57 -0500 Subject: [PATCH 1/3] 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 ? (
@@ -303,10 +319,12 @@ export function AlbumView({ className="rounded-full" aria-label="Shuffle album" onClick={() => - void playAlbumShuffled( - album.id as Id<"albums">, - albumSongIds - ) + void (fromDownloads + ? playShuffled(albumSongIds, playOrigin) + : playAlbumShuffled( + album.id as Id<"albums">, + albumSongIds + )) } > @@ -315,7 +333,9 @@ export function AlbumView({ className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90" aria-label={`Play ${album.title}`} onClick={() => - void playAlbum(album.id as Id<"albums">, albumSongIds) + void (fromDownloads + ? playInOrder(albumSongIds, playOrigin) + : playAlbum(album.id as Id<"albums">, albumSongIds)) } > @@ -387,6 +407,7 @@ export function AlbumView({ : sectionTrackIndex + 1 } subtitle={track.artists?.join(", ")} + downloadCollection={downloadRef} isActive={track.id === activeTrackId} selectionPosition={selectionPositions[listIndex]} isFavorite={isSongFavorite(track.id)} diff --git a/apps/web/components/app-sidebar.tsx b/apps/web/components/app-sidebar.tsx index dc631fd..ed30562 100644 --- a/apps/web/components/app-sidebar.tsx +++ b/apps/web/components/app-sidebar.tsx @@ -1,6 +1,7 @@ "use client" import { + ArrowDownToLine, Disc3, House, LayoutGrid, @@ -62,6 +63,7 @@ const library = [ { title: "Albums", path: "/library/albums", icon: Disc3 }, { title: "Artists", path: "/library/artists", icon: Mic }, { title: "Songs", path: "/library/songs", icon: Music2 }, + { title: "Downloads", path: "/library/downloads", icon: ArrowDownToLine }, ] export function AppSidebar() { diff --git a/apps/web/components/download-button.tsx b/apps/web/components/download-button.tsx index 92c1b5d..33535c6 100644 --- a/apps/web/components/download-button.tsx +++ b/apps/web/components/download-button.tsx @@ -16,8 +16,15 @@ import { AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog" +import { AudioFormatBadge } from "@/components/audio-format-badge" import { Button } from "@/components/ui/button" -import { useCollectionDownload } from "@/hooks/use-downloads" +import { + useCollectionDownload, + useIsCollectionDownloaded, +} from "@/hooks/use-downloads" +import { downloadQueue } from "@/lib/downloads" +import type { CollectionRef } from "@otunes/convex/client/download-queue" +import { DOWNLOAD_QUALITY_LABELS } from "@otunes/convex/download-quality" const RING_RADIUS = 14 const RING_LENGTH = 2 * Math.PI * RING_RADIUS @@ -110,3 +117,29 @@ export function DownloadButton({ ) } + +/** The quality an album or playlist was downloaded in, once downloaded. */ +export function DownloadedQuality({ + collection, +}: { + collection: CollectionRef +}) { + const downloaded = useIsCollectionDownloaded(collection) + const quality = downloaded + ? downloadQueue.getCollection(collection)?.quality + : undefined + if (!quality) return null + return ( + + + {quality === "lossless" || quality === "atmos" ? ( + + ) : ( + DOWNLOAD_QUALITY_LABELS[quality] + )} + + ) +} diff --git a/apps/web/components/downloads-provider.tsx b/apps/web/components/downloads-provider.tsx index 2709353..12d7500 100644 --- a/apps/web/components/downloads-provider.tsx +++ b/apps/web/components/downloads-provider.tsx @@ -29,6 +29,7 @@ import type { Id } from "@otunes/convex/_generated/dataModel" import type { CollectionRef, DownloadableSong, + DownloadSource, } from "@otunes/convex/client/download-queue" import { DOWNLOAD_OPTIONS_PATH, @@ -42,7 +43,13 @@ import { /** Songs on their own, or an album or playlist that stays downloaded as a whole. */ export type DownloadTarget = - | { kind: "songs"; songIds: string[]; title: string } + | { + kind: "songs" + songIds: string[] + title: string + /** Removing takes the songs out of only this download. */ + from?: DownloadSource + } | (CollectionRef & { title: string; songIds: string[] }) /** The Favorites playlist has no ID, so downloads use this one. */ @@ -282,6 +289,14 @@ export function DownloadsProvider({ children }: { children: React.ReactNode }) { const requestDownload = React.useCallback(async (target: DownloadTarget) => { if (target.songIds.length === 0) return + if (target.songIds.every((id) => downloadQueue.getDownloaded(id))) { + // Already on this device: just give them back to their downloads. + await downloadQueue.enqueue( + target.songIds.map((id) => ({ id, files: {} })), + "high" + ) + return + } try { const response = await fetchDownloadOptions(target.songIds) const remembered = readRememberedDownloadQuality() @@ -297,8 +312,9 @@ export function DownloadsProvider({ children }: { children: React.ReactNode }) { }, []) const removeDownload = React.useCallback(async (target: DownloadTarget) => { - if (target.kind === "songs") await downloadQueue.remove(target.songIds) - else await downloadQueue.removeCollection(target) + if (target.kind === "songs") { + await downloadQueue.removeSongs(target.songIds, target.from) + } else await downloadQueue.removeCollection(target) }, []) const value = React.useMemo( diff --git a/apps/web/components/downloads-settings.tsx b/apps/web/components/downloads-settings.tsx index 65dbd35..9c0faa2 100644 --- a/apps/web/components/downloads-settings.tsx +++ b/apps/web/components/downloads-settings.tsx @@ -151,7 +151,7 @@ export function DownloadsSettings() { ) : null} {breakdown.collections.length > 0 || - breakdown.singles.songIds.length > 0 ? ( + breakdown.otherSongs.songIds.length > 0 ? (
{breakdown.collections.map( ({ collection, bytes, status, fallbackCount }) => ( @@ -194,24 +194,22 @@ export function DownloadsSettings() {
) )} - {breakdown.singles.songIds.length > 0 ? ( + {breakdown.otherSongs.songIds.length > 0 ? (
-

Individual songs

+

Other Downloaded Songs

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

- {formatBytes(breakdown.singles.bytes)} + {formatBytes(breakdown.otherSongs.bytes)} 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. */ -- 2.54.1 From 6ce30fe17c024b7a501b242509ab21738d2feb0b Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Thu, 19 Nov 2026 18:28:27 -0500 Subject: [PATCH 3/3] feat: keep album and playlist covers with downloads Co-Authored-By: Claude Opus 5.5 --- .../app/(app)/(tabs)/home/downloads/index.tsx | 2 +- apps/mobile/components/cover-image.tsx | 9 ++ apps/mobile/contexts/downloads.tsx | 3 +- apps/mobile/lib/downloads.ts | 91 ++++++++++++++++--- apps/web/app/api/download/options/route.ts | 1 + apps/web/components/downloads-provider.tsx | 5 +- apps/web/components/downloads-view.tsx | 2 +- apps/web/lib/downloads.ts | 37 +++++++- apps/web/lib/server-song.ts | 6 +- apps/web/public/downloads-sw.js | 42 +++++++++ packages/convex/client/download-queue.ts | 67 +++++++++++++- packages/convex/convex/library.ts | 12 ++- packages/convex/download-quality.ts | 2 +- 13 files changed, 254 insertions(+), 25 deletions(-) create mode 100644 apps/web/public/downloads-sw.js diff --git a/apps/mobile/app/(app)/(tabs)/home/downloads/index.tsx b/apps/mobile/app/(app)/(tabs)/home/downloads/index.tsx index a0fbe61..5880bdc 100644 --- a/apps/mobile/app/(app)/(tabs)/home/downloads/index.tsx +++ b/apps/mobile/app/(app)/(tabs)/home/downloads/index.tsx @@ -98,7 +98,7 @@ export default function DownloadsScreen() { ? "" : collection.kind === "album" ? albumCoverUrl(config.serverUrl, collection.id) - : playlistCoverUrl(config.serverUrl, collection.id) + : playlistCoverUrl(config.serverUrl, collection.id, null) return ( ({ uri: sourceUri }), [sourceUri]) + // A downloaded cover shows while the network copy loads, and offline. + const savedUri = hasCover ? downloadedCoverUri(uri) : null + const placeholder = useMemo( + () => (savedUri ? { uri: savedUri } : undefined), + [savedUri] + ) if (!hasCover) { return ( @@ -109,6 +116,8 @@ export const CoverImage = memo(function CoverImage({ source={source} style={[style, { backgroundColor: colors.coverPlaceholder }]} contentFit={contentFit} + placeholder={placeholder} + placeholderContentFit={contentFit} transition={150} blurRadius={blurRadius} onLoad={ diff --git a/apps/mobile/contexts/downloads.tsx b/apps/mobile/contexts/downloads.tsx index 7bd0c0c..7929b64 100644 --- a/apps/mobile/contexts/downloads.tsx +++ b/apps/mobile/contexts/downloads.tsx @@ -45,6 +45,7 @@ import type { DownloadQueue, SongDownloadState, } from "@otunes/convex/client/download-queue" +import { FAVORITES_ID } from "@otunes/convex/client/download-queue" import { DOWNLOAD_OPTIONS_PATH, DOWNLOAD_QUALITY_DETAILS, @@ -67,7 +68,7 @@ export type DownloadTarget = | (CollectionRef & { title: string; songIds: string[] }) /** The Favorites playlist has no ID, so downloads use this one. */ -export const FAVORITES_DOWNLOAD_ID = "favorites" +export const FAVORITES_DOWNLOAD_ID = FAVORITES_ID type DownloadsContextValue = { queue: DownloadQueue | null diff --git a/apps/mobile/lib/downloads.ts b/apps/mobile/lib/downloads.ts index e2ab1ce..69ab77b 100644 --- a/apps/mobile/lib/downloads.ts +++ b/apps/mobile/lib/downloads.ts @@ -4,6 +4,7 @@ import { Platform } from "react-native" import { createDownloadQueue, + type DownloadedCover, type DownloadedSong, type DownloadIndex, type DownloadQueue, @@ -20,25 +21,52 @@ import type { ServerConfig } from "@/lib/server-config" const REMEMBERED_QUALITY_KEY = "otunes.download-quality" const PARTIAL_SUFFIX = ".partial" -// Each song is a folder named `.` holding one audio file, -// named by the server so it keeps the right extension. Folders end in -// `.partial` until their download completes. +const COVERS_FOLDER = "covers" +const COVER_SIZE = 1024 + +// Each song is a folder named `..` holding one audio +// file, named by the server so it keeps the right extension. Folders end in +// `.partial` until their download completes. Covers are files named +// `-` in the `covers` folder. function serverDirectory(config: ServerConfig) { const host = config.hostname.replace(/[^a-z0-9.-]/gi, "_") return new Directory(Paths.document, "downloads", host) } +function songFolderName(song: { + songId: string + quality: DownloadQuality + albumId?: string +}) { + return [song.songId, song.quality, song.albumId].filter(Boolean).join(".") +} + function parseSongFolder(name: string) { - const dot = name.lastIndexOf(".") - const quality = parseDownloadQuality(name.slice(dot + 1)) - return quality ? { songId: name.slice(0, dot), quality } : null + const [songId, rawQuality, albumId, ...rest] = name.split(".") + const quality = parseDownloadQuality(rawQuality) + if (!songId || !quality || rest.length > 0) return null + return { songId, quality, albumId: albumId || undefined } } function songFolders(root: Directory) { if (!root.exists) return [] return root .list() - .filter((entry): entry is Directory => entry instanceof Directory) + .filter( + (entry): entry is Directory => + entry instanceof Directory && entry.name !== COVERS_FOLDER + ) +} + +function coverFileName({ kind, id }: DownloadedCover) { + return `${kind}-${id}` +} + +// Saved covers by their server URL, for `downloadedCoverUri`. +const savedCoverUris = new Map() + +function coverUrl(config: ServerConfig, { kind, id }: DownloadedCover) { + return `${config.serverUrl}/api/${kind}/${id}/cover` } function audioFile(folder: Directory) { @@ -48,6 +76,19 @@ function audioFile(folder: Directory) { function createStorage(config: ServerConfig): DownloadStorage { const root = serverDirectory(config) const indexFile = new File(root, "index.json") + const coversFolder = new Directory(root, COVERS_FOLDER) + + // Remembers the covers saved in earlier launches. + if (coversFolder.exists) { + for (const entry of coversFolder.list()) { + const dash = entry.name.indexOf("-") + const kind = entry.name.slice(0, dash) + if (entry instanceof File && (kind === "album" || kind === "playlist")) { + const cover = { kind, id: entry.name.slice(dash + 1) } as const + savedCoverUris.set(coverUrl(config, cover), entry.uri) + } + } + } function foldersFor(songIds: ReadonlySet) { return songFolders(root).filter((folder) => { @@ -72,7 +113,7 @@ function createStorage(config: ServerConfig): DownloadStorage { } return songs }, - async save({ songId, requested, quality }, signal) { + async save({ songId, requested, quality, albumId }, signal) { const cookieHeader = await getAuthCookieHeader( config.serverUrl, config.convexUrl @@ -80,7 +121,7 @@ function createStorage(config: ServerConfig): DownloadStorage { if (!cookieHeader) throw new Error("Sign in to download") root.create({ intermediates: true, idempotent: true }) - const name = `${songId}.${quality}` + const name = songFolderName({ songId, quality, albumId }) const partial = new Directory(root, `${name}${PARTIAL_SUFFIX}`) if (partial.exists) partial.delete() partial.create() @@ -101,6 +142,25 @@ function createStorage(config: ServerConfig): DownloadStorage { throw error } }, + async saveCover(cover) { + const file = new File(coversFolder, coverFileName(cover)) + if (file.exists) return + coversFolder.create({ intermediates: true, idempotent: true }) + const url = coverUrl(config, cover) + await File.downloadFileAsync(`${url}?size=${COVER_SIZE}`, file) + savedCoverUris.set(url, file.uri) + }, + async pruneCovers(keep) { + if (!coversFolder.exists) return + const kept = new Set(keep.map(coverFileName)) + for (const entry of coversFolder.list()) { + if (kept.has(entry.name)) continue + entry.delete() + for (const [url, uri] of savedCoverUris) { + if (uri === entry.uri) savedCoverUris.delete(url) + } + } + }, async readIndex() { if (indexFile.exists) { try { @@ -138,13 +198,18 @@ export function downloadQueueFor(config: ServerConfig) { export function downloadedAudioUri(config: ServerConfig, songId: string) { const song = downloadQueueFor(config).getDownloaded(songId) if (!song) return null - const folder = new Directory( - serverDirectory(config), - `${songId}.${song.quality}` - ) + const folder = new Directory(serverDirectory(config), songFolderName(song)) return folder.exists ? (audioFile(folder)?.uri ?? null) : null } +/** + * The saved copy of a cover URL (`albumCoverUrl` or `playlistCoverUrl`, + * without size), for showing while the network copy loads or fails. + */ +export function downloadedCoverUri(url: string) { + return savedCoverUris.get(url.split("?")[0]) ?? null +} + export async function readRememberedDownloadQuality() { try { return parseDownloadQuality( diff --git a/apps/web/app/api/download/options/route.ts b/apps/web/app/api/download/options/route.ts index 9fe59ee..78a27bc 100644 --- a/apps/web/app/api/download/options/route.ts +++ b/apps/web/app/api/download/options/route.ts @@ -88,6 +88,7 @@ export async function POST(request: NextRequest) { const response: DownloadOptionsResponse = { songs: songs.map((song) => ({ id: song._id, + albumId: song.album, files: Object.fromEntries( Object.keys(song.files).map((codec) => [codec, true as const]) ), diff --git a/apps/web/components/downloads-provider.tsx b/apps/web/components/downloads-provider.tsx index 12d7500..5a775b9 100644 --- a/apps/web/components/downloads-provider.tsx +++ b/apps/web/components/downloads-provider.tsx @@ -21,6 +21,7 @@ import { useDownloadsVersion } from "@/hooks/use-downloads" import { downloadQueue, readRememberedDownloadQuality, + registerDownloadsServiceWorker, requestPersistentStorage, writeRememberedDownloadQuality, } from "@/lib/downloads" @@ -31,6 +32,7 @@ import type { DownloadableSong, DownloadSource, } from "@otunes/convex/client/download-queue" +import { FAVORITES_ID } from "@otunes/convex/client/download-queue" import { DOWNLOAD_OPTIONS_PATH, DOWNLOAD_QUALITY_DETAILS, @@ -53,7 +55,7 @@ export type DownloadTarget = | (CollectionRef & { title: string; songIds: string[] }) /** The Favorites playlist has no ID, so downloads use this one. */ -export const FAVORITES_DOWNLOAD_ID = "favorites" +export const FAVORITES_DOWNLOAD_ID = FAVORITES_ID type DownloadsContextValue = { /** Asks for a quality (unless remembered) and starts downloading. */ @@ -285,6 +287,7 @@ export function DownloadsProvider({ children }: { children: React.ReactNode }) { useFailureToasts() React.useEffect(() => { void downloadQueue.load().catch(() => {}) + registerDownloadsServiceWorker() }, []) const requestDownload = React.useCallback(async (target: DownloadTarget) => { diff --git a/apps/web/components/downloads-view.tsx b/apps/web/components/downloads-view.tsx index 4e9afc5..14d3c99 100644 --- a/apps/web/components/downloads-view.tsx +++ b/apps/web/components/downloads-view.tsx @@ -41,7 +41,7 @@ function CollectionCover({ collection }: { collection: DownloadedCollection }) { src={ collection.kind === "album" ? albumCoverUrl(collection.id) - : playlistCoverUrl(collection.id) + : playlistCoverUrl(collection.id, null) } alt={collection.title} fill diff --git a/apps/web/lib/downloads.ts b/apps/web/lib/downloads.ts index e85dd18..4f7f89f 100644 --- a/apps/web/lib/downloads.ts +++ b/apps/web/lib/downloads.ts @@ -1,5 +1,6 @@ import { createDownloadQueue, + type DownloadedCover, type DownloadedSong, type DownloadIndex, type DownloadStorage, @@ -18,6 +19,23 @@ const SONG_STORE = "songs" const REMEMBERED_QUALITY_KEY = "otunes:download-quality" const INDEX_KEY = "otunes:download-index" +// Covers live in Cache Storage under their unsized path. The service worker +// (public/downloads-sw.js) serves them only when the network fails, so +// online browsing and new playlist artwork are unaffected. +const COVER_CACHE = "otunes-download-covers" +const COVER_SIZE = 512 + +function coverPath({ kind, id }: DownloadedCover) { + return `/api/${kind}/${id}/cover` +} + +/** Lets downloaded covers show offline. */ +export function registerDownloadsServiceWorker() { + void navigator.serviceWorker + ?.register("/downloads-sw.js", { scope: "/" }) + .catch(() => {}) +} + let database: Promise | null = null function openDatabase() { @@ -65,7 +83,7 @@ const storage: DownloadStorage = { db.transaction(SONG_STORE).objectStore(SONG_STORE) ) }, - async save({ songId, requested, quality }, signal) { + async save({ songId, requested, quality, albumId }, signal) { const response = await fetch(songDownloadPath(songId, requested), { signal, }) @@ -74,13 +92,28 @@ const storage: DownloadStorage = { } const blob = await response.blob() signal.throwIfAborted() - const entry: DownloadedSong = { songId, quality, bytes: blob.size } + const entry: DownloadedSong = { songId, quality, bytes: blob.size, albumId } await transaction("readwrite", (audio, songs) => { audio.put(blob, songId) songs.put(entry) }) return blob.size }, + async saveCover(cover) { + const cache = await caches.open(COVER_CACHE) + const key = coverPath(cover) + if (await cache.match(key)) return + const response = await fetch(`${key}?size=${COVER_SIZE}`) + if (!response.ok) throw new Error(`Cover failed with ${response.status}`) + await cache.put(key, response) + }, + async pruneCovers(keep) { + const cache = await caches.open(COVER_CACHE) + const kept = new Set(keep.map(coverPath)) + for (const request of await cache.keys()) { + if (!kept.has(new URL(request.url).pathname)) await cache.delete(request) + } + }, async readIndex() { try { const raw = localStorage.getItem(INDEX_KEY) diff --git a/apps/web/lib/server-song.ts b/apps/web/lib/server-song.ts index 38c5359..1ffe84d 100644 --- a/apps/web/lib/server-song.ts +++ b/apps/web/lib/server-song.ts @@ -1,6 +1,6 @@ import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server" import { api } from "@otunes/convex/_generated/api" -import type { Id } from "@otunes/convex/_generated/dataModel" +import type { Doc, Id } from "@otunes/convex/_generated/dataModel" import { fetchQuery } from "convex/nextjs" import { convexServerOptions } from "@/lib/convex-server" import type { SongSource } from "@/lib/server-hls" @@ -25,7 +25,9 @@ export async function getSongSource(id: string): Promise { const SOURCE_BATCH_SIZE = 200 /** `getSongSource` for many songs, in batches. Missing songs are left out. */ -export async function getSongSources(ids: string[]): Promise { +export async function getSongSources( + ids: string[] +): Promise<(SongSource & Pick, "album">)[]> { const token = await convexAuthNextjsToken() const batches: string[][] = [] for (let start = 0; start < ids.length; start += SOURCE_BATCH_SIZE) { diff --git a/apps/web/public/downloads-sw.js b/apps/web/public/downloads-sw.js new file mode 100644 index 0000000..888e0c5 --- /dev/null +++ b/apps/web/public/downloads-sw.js @@ -0,0 +1,42 @@ +// Serves covers of downloaded music when the network fails, so they show +// offline. Everything else, and every request that succeeds online, passes +// through untouched. Covers are saved by lib/downloads.ts. +const COVER_CACHE = "otunes-download-covers" +const COVER_PATH = /^\/api\/(album|playlist)\/[^/]+\/cover$/ + +self.addEventListener("install", () => self.skipWaiting()) +self.addEventListener("activate", (event) => + event.waitUntil(self.clients.claim()) +) + +/** The saved cover's key for a cover request, also through `/_next/image`. */ +function coverKey(url) { + if (url.origin !== self.location.origin) return null + if (url.pathname === "/_next/image") { + const inner = url.searchParams.get("url") + return inner ? coverKey(new URL(inner, self.location.origin)) : null + } + return COVER_PATH.test(url.pathname) ? url.pathname : null +} + +async function savedCover(key) { + const cache = await caches.open(COVER_CACHE) + return cache.match(key) +} + +self.addEventListener("fetch", (event) => { + if (event.request.method !== "GET") return + const key = coverKey(new URL(event.request.url)) + if (!key) return + event.respondWith( + fetch(event.request).then( + async (response) => + response.ok ? response : ((await savedCover(key)) ?? response), + async (error) => { + const saved = await savedCover(key) + if (saved) return saved + throw error + } + ) + ) +}) diff --git a/packages/convex/client/download-queue.ts b/packages/convex/client/download-queue.ts index dc5a32f..222c552 100644 --- a/packages/convex/client/download-queue.ts +++ b/packages/convex/client/download-queue.ts @@ -9,8 +9,13 @@ export type DownloadedSong = { /** The quality the file is in, after any fallback to High. */ quality: DownloadQuality bytes: number + /** Whose cover to keep for offline use. */ + albumId?: string } +/** Artwork kept on the device for downloaded songs and playlists. */ +export type DownloadedCover = { kind: "album" | "playlist"; id: string } + /** * An album or playlist downloaded as a whole. Playlists stay in sync: songs * added later download in `quality`, and songs taken out are removed. @@ -61,9 +66,14 @@ export type DownloadStorage = { songId: string requested: DownloadQuality quality: DownloadQuality + albumId?: string }, signal: AbortSignal ): Promise + /** Fetches and keeps a cover unless it is already kept. */ + saveCover(cover: DownloadedCover): Promise + /** Deletes every kept cover not in `keep`. */ + pruneCovers(keep: readonly DownloadedCover[]): Promise remove(songIds: readonly string[]): Promise readIndex(): Promise writeIndex(index: DownloadIndex): Promise @@ -72,6 +82,7 @@ export type DownloadStorage = { export type DownloadableSong = { id: string files: Record + albumId?: string } export type DownloadStatus = { @@ -100,6 +111,9 @@ export type SongDownloadState = "here" | "device" | "removed" | "none" export type DownloadQueue = ReturnType +/** The Favorites playlist has no ID or cover; downloads use this one. */ +export const FAVORITES_ID = "favorites" + function collectionKey({ kind, id }: CollectionRef) { return `${kind}:${id}` } @@ -139,6 +153,9 @@ export function createDownloadQueue( for (const songId of index.otherSongIds) { if (downloaded.has(songId)) otherSongIds.add(songId) } + // Retries covers that failed before (say, offline) and drops strays. + for (const cover of neededCovers()) saveCover(cover) + pruneCovers() notify() }, (error) => { @@ -178,13 +195,26 @@ export function createDownloadQueue( running.set(song.id, controller) void storage .save( - { songId: song.id, requested: quality, quality: actual }, + { + songId: song.id, + requested: quality, + quality: actual, + albumId: song.albumId, + }, controller.signal ) .then( (bytes) => { if (controller.signal.aborted) return - downloaded.set(song.id, { songId: song.id, quality: actual, bytes }) + downloaded.set(song.id, { + songId: song.id, + quality: actual, + bytes, + albumId: song.albumId, + }) + if (song.albumId) { + saveCover({ kind: "album", id: song.albumId }) + } }, (error) => { if (controller.signal.aborted) return @@ -211,6 +241,34 @@ export function createDownloadQueue( } } + /** Covers are best effort: a missing one falls back to the placeholder. */ + function saveCover(cover: DownloadedCover) { + void storage.saveCover(cover).catch(() => {}) + } + + /** Album covers of downloaded songs, and covers of downloaded playlists. */ + function neededCovers() { + const covers = new Map() + for (const song of downloaded.values()) { + if (song.albumId) { + covers.set(`album:${song.albumId}`, { kind: "album", id: song.albumId }) + } + } + for (const collection of collections.values()) { + if (collection.kind === "playlist" && collection.id !== FAVORITES_ID) { + covers.set(`playlist:${collection.id}`, { + kind: "playlist", + id: collection.id, + }) + } + } + return [...covers.values()] + } + + function pruneCovers() { + void storage.pruneCovers(neededCovers()).catch(() => {}) + } + /** Cancels and deletes audio, leaving the index as it is. */ async function deleteAudio(songIds: readonly string[]) { if (songIds.length === 0) return @@ -225,6 +283,7 @@ export function createDownloadQueue( } notify() await storage.remove([...ids]) + pruneCovers() pump() } @@ -347,6 +406,9 @@ export function createDownloadQueue( if (collection.kind === "album") { for (const song of songs) otherSongIds.delete(song.id) } + if (collection.kind === "playlist" && collection.id !== FAVORITES_ID) { + saveCover({ kind: "playlist", id: collection.id }) + } collections.set(collectionKey(collection), { kind: collection.kind, id: collection.id, @@ -404,6 +466,7 @@ export function createDownloadQueue( collections.delete(key) await saveIndex() await deleteUnheld(collection.songIds) + pruneCovers() }, /** diff --git a/packages/convex/convex/library.ts b/packages/convex/convex/library.ts index 8848cb2..d888382 100644 --- a/packages/convex/convex/library.ts +++ b/packages/convex/convex/library.ts @@ -1008,7 +1008,16 @@ export const getSongSources = query({ } const songs = await Promise.all(args.ids.map((id) => ctx.db.get(id))) return songs.flatMap((song) => - song ? [{ _id: song._id, files: song.files, length: song.length }] : [] + song + ? [ + { + _id: song._id, + files: song.files, + length: song.length, + album: song.album, + }, + ] + : [] ) }, }) @@ -1053,6 +1062,7 @@ export const getSongsForPlayback = query({ return { id: ids[index], title: song.name, + albumId: song.album, files: playbackCodecMap(song.files), } }) diff --git a/packages/convex/download-quality.ts b/packages/convex/download-quality.ts index aca1b11..b7b32d9 100644 --- a/packages/convex/download-quality.ts +++ b/packages/convex/download-quality.ts @@ -146,7 +146,7 @@ export type SizedDownloadOption = DownloadOption & { /** Server answer for a set of songs about to be downloaded. */ export type DownloadOptionsResponse = { - songs: { id: string; files: Record }[] + songs: { id: string; albumId: string; files: Record }[] options: SizedDownloadOption[] } -- 2.54.1