+
+
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)}
{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 2e796df..7de6477 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 e1a2eb1..2f967aa 100644
--- a/apps/web/components/playlist-view.tsx
+++ b/apps/web/components/playlist-view.tsx
@@ -9,7 +9,13 @@ import { useMutation } from "convex/react"
import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } 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,
@@ -146,7 +152,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)
}
@@ -351,6 +377,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
{isSubscribed ? "Subscribed" : "Subscribe"}
) : null}
+
{!isFavorites ? (