diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/_layout.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/_layout.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/_layout.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/_layout.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/album/[id].tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/album/[id].tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/album/[id].tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/artist/[id].tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/artist/[id].tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/artist/[id].tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/artist/[id].tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/albums.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/albums.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/albums.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/albums.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/artists.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/artists.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/artists.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/artists.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/playlists.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/playlists.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/playlists.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/playlists.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/songs.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/songs.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/browse/songs.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/browse/songs.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/index.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/index.tsx new file mode 100644 index 0000000..b71b31f --- /dev/null +++ b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/index.tsx @@ -0,0 +1 @@ +export { default } from "../../home/downloads" diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/other.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/other.tsx new file mode 100644 index 0000000..e7ea56e --- /dev/null +++ b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/downloads/other.tsx @@ -0,0 +1 @@ +export { default } from "../../home/downloads/other" diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/index.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/index.tsx similarity index 91% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/index.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/index.tsx index 688cd25..9dd24d6 100644 --- a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/index.tsx +++ b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/index.tsx @@ -5,6 +5,7 @@ import Songs from "../home/browse/songs" import Playlists from "../home/browse/playlists" import Favorites from "../home/playlist/favorites" import RecentlyPlayed from "../home/recently-played" +import Downloads from "../home/downloads" import { TabletSectionContext } from "@/lib/tablet-navigation" const screens = { @@ -14,6 +15,7 @@ const screens = { playlists: Playlists, favorites: Favorites, recent: RecentlyPlayed, + downloads: Downloads, } export default function TabletSectionScreen() { diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/playlist/[id].tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/playlist/[id].tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/playlist/[id].tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/playlist/[id].tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/playlist/favorites.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/playlist/favorites.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/playlist/favorites.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/playlist/favorites.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/recently-added.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/recently-added.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/recently-added.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/recently-added.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/recently-played.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/recently-played.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/recently-played.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/recently-played.tsx diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/settings.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/settings.tsx similarity index 100% rename from apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/settings.tsx rename to apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent,downloads)/settings.tsx diff --git a/apps/mobile/app/(app)/(tabs)/_layout.tsx b/apps/mobile/app/(app)/(tabs)/_layout.tsx index 011f791..10b5378 100644 --- a/apps/mobile/app/(app)/(tabs)/_layout.tsx +++ b/apps/mobile/app/(app)/(tabs)/_layout.tsx @@ -217,6 +217,14 @@ function TabsContent() { Recently Played + {!keyboardVisible ? : null} {tabletLayout ? : null} diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx index 0f15715..09c4f05 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -22,6 +22,18 @@ import { DiscHeader, } from "@/components/collection-list" import { AudioFormatBadge } from "@/components/audio-format-badge" +import { + DownloadHeaderButton, + DownloadedQuality, +} from "@/components/download-header-button" +import { useOpenedFromDownloads } from "@/lib/downloads-navigation" +import { downloadsQueueOrigin } from "@otunes/convex/download-quality" +import { + useDownloads, + useIsCollectionDownloaded, + useSongDownloadState, + useToggleSongDownload, +} from "@/contexts/downloads" import { CoverImage } from "@/components/cover-image" import { @@ -58,7 +70,17 @@ export default function AlbumScreen() { api.library.browseAlbumDetail, typeof id === "string" ? { id: id as Id<"albums"> } : "skip" ) - const { playAlbum, playAlbumShuffled, playFromSong } = usePlaybackActions() + const { + playAlbum, + playAlbumShuffled, + playFromSong, + playInOrder, + playShuffled, + } = usePlaybackActions() + const fromDownloads = useOpenedFromDownloads() + const playOrigin = fromDownloads + ? downloadsQueueOrigin(`album:${id}`) + : `album:${id}` const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } = useFavorites() const { @@ -81,6 +103,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) { @@ -92,8 +125,8 @@ export default function AlbumScreen() { const playTrack = useCallback( (songId: Id<"songs">, ids: Id<"songs">[]) => - playFromSong(songId, ids, `album:${id}`), - [id, playFromSong] + playFromSong(songId, ids, playOrigin), + [playOrigin, playFromSong] ) const renderItem = useCallback( @@ -193,28 +226,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"> + ) + } + }} + > + + + + + ), }} /> @@ -278,7 +324,11 @@ export default function AlbumScreen() { + + + + Remove download? + + + Cancel + void removeDownload(target)} + > + Remove + + + + + + ) +} + +/** 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 new file mode 100644 index 0000000..5a775b9 --- /dev/null +++ b/apps/web/components/downloads-provider.tsx @@ -0,0 +1,338 @@ +"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, + registerDownloadsServiceWorker, + requestPersistentStorage, + writeRememberedDownloadQuality, +} from "@/lib/downloads" +import { api } from "@otunes/convex/_generated/api" +import type { Id } from "@otunes/convex/_generated/dataModel" +import type { + CollectionRef, + DownloadableSong, + DownloadSource, +} from "@otunes/convex/client/download-queue" +import { FAVORITES_ID } 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 + /** 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. */ +export const FAVORITES_DOWNLOAD_ID = FAVORITES_ID + +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(() => {}) + registerDownloadsServiceWorker() + }, []) + + 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() + 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.removeSongs(target.songIds, target.from) + } 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..9c0faa2 --- /dev/null +++ b/apps/web/components/downloads-settings.tsx @@ -0,0 +1,248 @@ +"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.otherSongs.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.otherSongs.songIds.length > 0 ? ( +
+
+

Other Downloaded Songs

+

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

+
+ + {formatBytes(breakdown.otherSongs.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/downloads-view.tsx b/apps/web/components/downloads-view.tsx new file mode 100644 index 0000000..14d3c99 --- /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/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/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 e4e9cf2..95ccc42 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -35,6 +35,11 @@ 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 { + 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" @@ -61,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: ( @@ -189,28 +195,79 @@ 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 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 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, + fromDownloads: boolean +): AudioSourceChoice | null { + const download = downloadQueue.getDownloaded(songId) + if (!user || !files) { + return download ? { kind: "download" } : null + } + const plan = userStreamPlan(user, dolbyAtmosSupported, files) + if ( + download && + (fromDownloads || download.quality === streamDownloadQuality(plan)) + ) { + return { kind: "download" } + } return { - preferAtmos: plan.preferAtmos, - playbackQuality: plan.playbackQuality, - useHls: plan.useHls, + kind: "stream", + settings: { + preferAtmos: plan.preferAtmos, + playbackQuality: plan.playbackQuality, + useHls: plan.useHls, + }, } } -function songLoadKey(songId: string, settings: PlaybackLoadSettings) { +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 +299,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 +316,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 +391,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 +519,17 @@ 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(() => {}) + }, []) + // Queues started from the Downloads page play downloads in any quality. + const [fromDownloads, setFromDownloads] = useState(false) const volume = useSyncExternalStore( subscribeVolume, readStoredVolume, @@ -759,18 +850,22 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { return } - if (!user || !currentSongDoc) { + const source = audioSourceChoice( + currentSongId, + user ? { playbackQuality, preferAtmos } : null, + dolbyAtmosSupported, + currentSongDoc?.files, + fromDownloads + ) + 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 +906,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { audio, hlsRef, currentSongId, - settings, + source, requestPlay ) @@ -826,6 +921,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { playbackQuality, preferAtmos, dolbyAtmosSupported, + downloadsVersion, + fromDownloads, runWithoutAudioSync, destroyHls, clearPreload, @@ -839,16 +936,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { return } - if (!user || !nextQueueSongDoc) { + const source = audioSourceChoice( + nextQueueSongId, + user ? { playbackQuality, preferAtmos } : null, + dolbyAtmosSupported, + nextQueueSongDoc?.files, + fromDownloads + ) + 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 +965,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { preloadAudio, preloadHlsRef, nextQueueSongId, - settings, + source, onPreloadReady ) @@ -888,6 +986,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { playbackQuality, preferAtmos, dolbyAtmosSupported, + downloadsVersion, + fromDownloads, clearPreload, destroyPreloadHls, ]) @@ -949,19 +1049,22 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { } const preloadAudio = preloadAudioRef.current + const nextSource = nextQueueSongId + ? audioSourceChoice( + nextQueueSongId, + user ?? null, + dolbyAtmosSupported, + nextQueueSongDoc?.files, + fromDownloads + ) + : 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 && @@ -1048,6 +1151,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { nextQueueSongDoc, user, dolbyAtmosSupported, + fromDownloads, store, destroyHls, runWithoutAudioSync, @@ -1109,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) @@ -1161,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] ) @@ -1393,8 +1503,25 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { skipPrevious, }) - const currentFormat = - currentSongDoc && user + 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" + ? 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..a4a8a42 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -18,7 +18,17 @@ import { } from "lucide-react" import { toast } from "sonner" +import { DownloadButton, DownloadedQuality } from "@/components/download-button" +import { + FAVORITES_DOWNLOAD_ID, + useDownloads, +} from "@/components/downloads-provider" import { useFavorites } from "@/components/favorites-provider" +import { + useIsCollectionDownloaded, + useOpenedFromDownloads, +} from "@/hooks/use-downloads" +import { downloadsQueueOrigin } from "@otunes/convex/download-quality" import { useCurrentSongId, usePlaybackActions, @@ -147,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 { @@ -156,9 +180,32 @@ 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( + () => ({ + ...downloadRef, + title: playlist.title, + songIds: playlistSongIds, + }), + [downloadRef, 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) } @@ -171,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) { @@ -342,6 +385,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {

{playlist.owner.name}

+

+ +

@@ -374,6 +420,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { {isSubscribed ? "Subscribed" : "Subscribe"} ) : null} + {!isFavorites ? (