= {
"recently-played": "Recently Played",
"recently-added": "Recently Added",
settings: "Settings",
+ "downloads/index": "Downloads",
+ "downloads/other": "Other Downloaded Songs",
}
export function useStackScreenOptions(
diff --git a/apps/mobile/lib/tablet-navigation.ts b/apps/mobile/lib/tablet-navigation.ts
index 7cd7d83..ff2a97c 100644
--- a/apps/mobile/lib/tablet-navigation.ts
+++ b/apps/mobile/lib/tablet-navigation.ts
@@ -7,6 +7,7 @@ export const tabletSections = [
{ name: "playlists", group: "(playlists)", title: "All Playlists" },
{ name: "favorites", group: "(favorites)", title: "Favorites" },
{ name: "recent", group: "(recent)", title: "Recently Played" },
+ { name: "downloads", group: "(downloads)", title: "Downloads" },
] as const
export const TabletSectionContext = createContext<
diff --git a/apps/web/app/(app)/library/downloads/other/page.tsx b/apps/web/app/(app)/library/downloads/other/page.tsx
new file mode 100644
index 0000000..1198176
--- /dev/null
+++ b/apps/web/app/(app)/library/downloads/other/page.tsx
@@ -0,0 +1,7 @@
+"use client"
+
+import { OtherDownloadsView } from "@/components/other-downloads-view"
+
+export default function Page() {
+ return
+}
diff --git a/apps/web/app/(app)/library/downloads/page.tsx b/apps/web/app/(app)/library/downloads/page.tsx
new file mode 100644
index 0000000..978e421
--- /dev/null
+++ b/apps/web/app/(app)/library/downloads/page.tsx
@@ -0,0 +1,7 @@
+"use client"
+
+import { DownloadsView } from "@/components/downloads-view"
+
+export default function Page() {
+ return
+}
diff --git a/apps/web/components/album-view.tsx b/apps/web/components/album-view.tsx
index 374a218..34ec288 100644
--- a/apps/web/components/album-view.tsx
+++ b/apps/web/components/album-view.tsx
@@ -9,10 +9,14 @@ import { Play, Share2, Shuffle } from "lucide-react"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import { MediaCollectionFooter } from "@/components/media-collection-footer"
-import { DownloadButton } from "@/components/download-button"
+import { DownloadButton, DownloadedQuality } from "@/components/download-button"
import { useDownloads } from "@/components/downloads-provider"
import { FavoriteMediaButton } from "@/components/favorite-media-button"
-import { useIsCollectionDownloaded } from "@/hooks/use-downloads"
+import {
+ useIsCollectionDownloaded,
+ useOpenedFromDownloads,
+} from "@/hooks/use-downloads"
+import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import { useFavorites } from "@/components/favorites-provider"
import {
useCurrentSongId,
@@ -115,7 +119,13 @@ export function AlbumView({
toggleAlbumFavorite,
} = useFavorites()
const currentSongId = useCurrentSongId()
- const { playFromSong, playAlbum, playAlbumShuffled } = usePlaybackActions()
+ const {
+ playFromSong,
+ playAlbum,
+ playAlbumShuffled,
+ playInOrder,
+ playShuffled,
+ } = usePlaybackActions()
const { runSongsAction } = useMediaActions()
const albumSongIds = React.useMemo(
() => album.tracks.map((track) => track.id as Id<"songs">),
@@ -188,9 +198,18 @@ export function AlbumView({
[album.tracks, album.artist, album.id, album.title, album.cover]
)
+ const downloadRef = React.useMemo(
+ () => ({ kind: "album" as const, id: album.id }),
+ [album.id]
+ )
+ const fromDownloads = useOpenedFromDownloads()
+ const playOrigin = fromDownloads
+ ? downloadsQueueOrigin(`album:${album.id}`)
+ : `album:${album.id}`
const handleMediaAction = useTrackListMediaAction({
selectedIds,
artistId: album.artist.id,
+ downloadFrom: downloadRef,
})
const { requestDownload, removeDownload } = useDownloads()
const downloadTarget = React.useMemo(
@@ -215,13 +234,9 @@ export function AlbumView({
const handleRowPlay = React.useCallback(
(index: number) => {
- void playFromSong(
- album.tracks[index].id,
- albumSongIds,
- `album:${album.id}`
- )
+ void playFromSong(album.tracks[index].id, albumSongIds, playOrigin)
},
- [album.tracks, album.id, albumSongIds, playFromSong]
+ [album.tracks, albumSongIds, playOrigin, playFromSong]
)
const handleToggleFavorite = React.useCallback(
@@ -293,6 +308,7 @@ export function AlbumView({
>
) : null}
+
@@ -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 (
+
+ )
+}
+
+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. */