feat: downloads page, Other Downloaded Songs, and per-download song removal

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
joshuafhigginsandClaude Opus 5.5 committed 2026-11-19 18:24:24 -05:00 Verified
1 parent c1a8ad691a
commit 13b5bd7874
58 files changed
+1543 -227

No files matched your search

@@ -0,0 +1 @@
export { default } from "../../home/downloads"
@@ -0,0 +1 @@
export { default } from "../../home/downloads/other"
@@ -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() {
+8
View File
@@ -217,6 +217,14 @@ function TabsContent() {
<NativeTabs.Trigger.Icon sf="clock" />
<NativeTabs.Trigger.Label>Recently Played</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(downloads)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="arrow.down.circle" />
<NativeTabs.Trigger.Label>Downloads</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
</NativeTabs>
{!keyboardVisible ? <AndroidMiniPlayer /> : null}
{tabletLayout ? <TabletMiniPlayer /> : null}
@@ -22,11 +22,17 @@ import {
DiscHeader,
} from "@/components/collection-list"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import { DownloadHeaderButton } from "@/components/download-header-button"
import {
DownloadHeaderButton,
DownloadedQuality,
} from "@/components/download-header-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import {
useDownloads,
useIsCollectionDownloaded,
useIsSongDownloaded,
useSongDownloadState,
useToggleSongDownload,
} from "@/contexts/downloads"
import { CoverImage } from "@/components/cover-image"
@@ -64,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 {
@@ -109,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(
@@ -308,7 +324,11 @@ export default function AlbumScreen() {
<Button
title="Play"
icon="play"
onPress={() => void playAlbum(album.id, songIds)}
onPress={() =>
void (fromDownloads
? playInOrder(songIds, playOrigin)
: playAlbum(album.id, songIds))
}
style={styles.playButton}
tint={{
background: palette.accent,
@@ -319,7 +339,11 @@ export default function AlbumScreen() {
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playAlbumShuffled(album.id, songIds)}
onPress={() =>
void (fromDownloads
? playShuffled(songIds, playOrigin)
: playAlbumShuffled(album.id, songIds))
}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
@@ -402,6 +426,11 @@ export default function AlbumScreen() {
</>
) : null}
</View>
<DownloadedQuality
collection={downloadTarget}
color={palette.secondaryForeground}
backgroundColor={palette.background}
/>
</CollectionHero>
</MusicEntityView>
<CollectionDivider color={palette.divider} />
@@ -481,7 +510,13 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
}) {
const Row = Platform.OS !== "web" ? SongSwipeRow : Pressable
const { config } = useServerConfig()
const downloaded = useIsSongDownloaded(track.id)
const downloadRef = useMemo(
() => ({ kind: "album" as const, id: album.id }),
[album.id]
)
const downloadState = useSongDownloadState(track.id, downloadRef)
const downloaded = downloadState === "here"
const toggleDownload = useToggleSongDownload()
return (
<MediaContextMenu
preview={
@@ -517,6 +552,8 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
backgroundColor={palette.background}
onPlayNext={() => void onAction(track, album, "play-next")}
onAddToQueue={() => void onAction(track, album, "play-last")}
downloaded={downloaded}
onDownload={() => toggleDownload(track, downloaded, downloadRef)}
style={styles.trackRow}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
>
@@ -547,7 +584,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
</Text>
) : null}
</View>
{downloaded ? (
{downloaded || downloadState === "device" ? (
<Ionicons
name="arrow-down-circle"
size={14}
@@ -0,0 +1,176 @@
import { useMemo } from "react"
import {
FlatList,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import { Stack } from "expo-router"
import { CoverImage } from "@/components/cover-image"
import { tabContentBottomInset } from "@/components/player"
import {
FAVORITES_DOWNLOAD_ID,
useDownloads,
useDownloadsVersion,
} from "@/contexts/downloads"
import { useServerConfig } from "@/contexts/server-config"
import { useMediaGridLayout } from "@/hooks/use-media-grid-layout"
import { useAppNavigation } from "@/lib/app-navigation"
import {
FROM_DOWNLOADS_PARAM,
OTHER_DOWNLOADS_TITLE,
} from "@/lib/downloads-navigation"
import { radius, spacing, useThemeColors } from "@/lib/theme"
import { albumCoverUrl, playlistCoverUrl } from "@/lib/urls"
import type { DownloadedCollection } from "@otunes/convex/client/download-queue"
import { formatBytes } from "@otunes/convex/download-quality"
type Card =
| { kind: "other"; songCount: number; bytes: number }
| { kind: "collection"; collection: DownloadedCollection; bytes: number }
function songCount(count: number) {
return count === 1 ? "1 song" : `${count} songs`
}
function collectionPath({ 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}`
}
/** Downloaded albums and playlists, newest first, after Other Downloaded Songs. */
export default function DownloadsScreen() {
const colors = useThemeColors()
const { config } = useServerConfig()
const { queue } = useDownloads()
const version = useDownloadsVersion()
const { push } = useAppNavigation()
const { columns, cardWidth, onLayout, horizontalPadding, gap } =
useMediaGridLayout()
const cards = useMemo<Card[]>(() => {
if (!queue) return []
const breakdown = queue.breakdown()
const bytesByCollection = new Map(
breakdown.collections.map((row) => [row.collection, row.bytes])
)
const other: Card[] =
breakdown.otherSongs.songIds.length > 0
? [
{
kind: "other",
songCount: breakdown.otherSongs.songIds.length,
bytes: breakdown.otherSongs.bytes,
},
]
: []
return [
...other,
...queue
.collections()
.reverse()
.map((collection): Card => ({
kind: "collection",
collection,
bytes: bytesByCollection.get(collection) ?? 0,
})),
]
// version invalidates the lookup when downloads change.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [queue, version])
function renderItem({ item }: ListRenderItemInfo<Card>) {
if (!config) return null
const isOther = item.kind === "other"
const collection = isOther ? null : item.collection
const isFavorites = collection?.id === FAVORITES_DOWNLOAD_ID
const title = collection?.title ?? OTHER_DOWNLOADS_TITLE
const subtitle = isOther
? `${songCount(item.songCount)} · ${formatBytes(item.bytes)}`
: `${collection!.kind === "album" ? "Album" : "Playlist"} · ${formatBytes(item.bytes)}`
const coverUri = !collection
? ""
: collection.kind === "album"
? albumCoverUrl(config.serverUrl, collection.id)
: playlistCoverUrl(config.serverUrl, collection.id)
return (
<Pressable
accessibilityRole="button"
style={[styles.card, { width: cardWidth }]}
onPress={() =>
push(collection ? collectionPath(collection) : "/downloads/other")
}
>
<CoverImage
uri={coverUri}
hasCover={collection !== null && !isFavorites}
placeholderIcon={isOther ? "arrow-down" : "star"}
style={{
width: cardWidth,
height: cardWidth,
borderRadius: radius.md,
}}
/>
<Text
style={[styles.title, { color: colors.foreground }]}
numberOfLines={1}
>
{title}
</Text>
<Text
style={[styles.subtitle, { color: colors.mutedForeground }]}
numberOfLines={1}
>
{subtitle}
</Text>
</Pressable>
)
}
return (
<>
<Stack.Screen options={{ title: "Downloads", headerLargeTitle: true }} />
<FlatList
key={columns}
onLayout={onLayout}
data={cards}
keyExtractor={(card) =>
card.kind === "other"
? "other"
: `${card.collection.kind}:${card.collection.id}`
}
renderItem={renderItem}
numColumns={columns}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{
paddingTop: spacing.lg,
paddingHorizontal: horizontalPadding,
paddingBottom: tabContentBottomInset,
gap,
}}
columnWrapperStyle={columns > 1 ? { gap } : undefined}
contentInsetAdjustmentBehavior="automatic"
ListEmptyComponent={
<View style={styles.empty}>
<Text style={{ color: colors.mutedForeground }}>
Nothing downloaded on this device.
</Text>
</View>
}
/>
</>
)
}
const styles = StyleSheet.create({
card: { gap: spacing.xs },
title: { fontSize: 14, fontWeight: "600" },
subtitle: { fontSize: 12, fontVariant: ["tabular-nums"] },
empty: { alignItems: "center", paddingTop: spacing.xl },
})
@@ -0,0 +1,152 @@
import { useCallback, useMemo } from "react"
import {
FlatList,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { useSwipeRowGroup } from "@/components/ios-swipe-to-remove-row"
import type { MediaAction } from "@/components/media-context-menu"
import { contentBottomInset, SongListRow } from "@/components/player"
import { Button } from "@/components/ui/primitives"
import { useDownloads, useDownloadsVersion } from "@/contexts/downloads"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { OTHER_DOWNLOADS_TITLE } from "@/lib/downloads-navigation"
import { longListProps } from "@/lib/list"
import { useSongs } from "@/lib/song-cache"
import { spacing, useThemeColors } from "@/lib/theme"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import type { BrowseSong } from "@otunes/convex/types"
const PLAY_ORIGIN = downloadsQueueOrigin("other")
/** Songs downloaded on their own. Playback here always uses the downloads. */
export default function OtherDownloadsScreen() {
const colors = useThemeColors()
const { queue } = useDownloads()
const version = useDownloadsVersion()
const songIds = useMemo(
() =>
(queue?.otherSongIds() ?? [])
.filter((songId) => queue?.getDownloaded(songId))
.reverse() as Id<"songs">[],
// version invalidates the lookup when downloads change.
// eslint-disable-next-line react-hooks/exhaustive-deps
[queue, version]
)
const cachedSongs = useSongs(songIds)
const songs = useMemo(
() => cachedSongs.filter((song): song is BrowseSong => song != null),
[cachedSongs]
)
const playableIds = useMemo(() => songs.map((song) => song.id), [songs])
const { playFromSong, playInOrder, playShuffled } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const swipeGroup = useSwipeRowGroup()
const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, playableIds, PLAY_ORIGIN),
[playFromSong, playableIds]
)
const handleAction = useCallback(
(song: BrowseSong, action: MediaAction) =>
void handleSongAction(song, action, "other"),
[handleSongAction]
)
const renderItem = useCallback(
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
<SongListRow
song={song}
favorited={isSongFavorite(song.id)}
downloadFrom="other"
swipe={{
group: swipeGroup,
backgroundColor: colors.background,
onPlayNext: () => handleAction(song, "play-next"),
onAddToQueue: () => handleAction(song, "play-last"),
}}
onPlay={handlePlaySong}
onAction={handleAction}
/>
),
[
colors.background,
handleAction,
handlePlaySong,
isSongFavorite,
swipeGroup,
]
)
return (
<>
<Stack.Screen
options={{ title: OTHER_DOWNLOADS_TITLE, headerLargeTitle: false }}
/>
<FlatList
{...longListProps}
data={songs}
keyExtractor={(song) => song.id}
renderItem={renderItem}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
onScrollBeginDrag={swipeGroup.closeOpenRow}
ListHeaderComponent={
songs.length > 0 ? (
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(playableIds, PLAY_ORIGIN)}
style={styles.play}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playShuffled(playableIds, PLAY_ORIGIN)}
style={[styles.shuffle, { backgroundColor: colors.card }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
) : undefined
}
ListEmptyComponent={
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
Songs you download on their own appear here.
</Text>
}
/>
</>
)
}
const styles = StyleSheet.create({
actions: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
padding: spacing.lg,
},
play: { flex: 1 },
shuffle: {
width: 48,
height: 48,
borderRadius: 24,
alignItems: "center",
justifyContent: "center",
},
empty: { padding: spacing.lg, textAlign: "center" },
})
@@ -44,7 +44,13 @@ import {
import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player"
import { DownloadHeaderButton } from "@/components/download-header-button"
import {
DownloadHeaderButton,
DownloadedQuality,
} from "@/components/download-header-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import type { CollectionRef } from "@otunes/convex/client/download-queue"
import {
FAVORITES_DOWNLOAD_ID,
useDownloads,
@@ -182,8 +188,14 @@ function PlaylistContent({
const router = useRouter()
const isFocused = useIsFocused()
const colors = useThemeColors()
const { playPlaylist, playPlaylistShuffled, playFromSong } =
usePlaybackActions()
const {
playPlaylist,
playPlaylistShuffled,
playFromSong,
playInOrder,
playShuffled,
} = usePlaybackActions()
const fromDownloads = useOpenedFromDownloads()
const { isSongFavorite } = useFavorites()
const { handleSongAction, handlePlaylistDetailAction } = useMediaMenuActions()
const { requestDownload, removeDownload } = useDownloads()
@@ -199,21 +211,25 @@ function PlaylistContent({
const { filteredSongs, onQueryChange, onSearchSubmit } =
usePlaylistSearch(songs)
const swipeGroup = useSwipeRowGroup()
const downloadTarget = useMemo(
const downloadRef = useMemo(
() => ({
kind: "playlist" as const,
id: playlistId ?? FAVORITES_DOWNLOAD_ID,
title: playlist.title,
songIds,
}),
[playlist.title, playlistId, songIds]
[playlistId]
)
const downloadTarget = useMemo(
() => ({ ...downloadRef, title: playlist.title, songIds }),
[downloadRef, playlist.title, songIds]
)
const playOrigin = fromDownloads
? downloadsQueueOrigin(`playlist:${downloadRef.id}`)
: `playlist:${playlistId}`
const playlistDownloaded = useIsCollectionDownloaded(downloadTarget)
const handlePlaySong = useCallback(
(song: BrowseSong) =>
void playFromSong(song.id, songIds, `playlist:${playlistId}`),
[playFromSong, songIds, playlistId]
(song: BrowseSong) => void playFromSong(song.id, songIds, playOrigin),
[playFromSong, songIds, playOrigin]
)
const handleRemoveSong = useCallback(
@@ -237,18 +253,34 @@ function PlaylistContent({
const handleSongMenuAction = useCallback(
(song: BrowseSong, action: MediaAction) => {
if (action === "remove-from-playlist") void handleRemoveSong(song.id)
else void handleSongAction(song, action)
else void handleSongAction(song, action, downloadRef)
},
[handleRemoveSong, handleSongAction]
[downloadRef, handleRemoveSong, handleSongAction]
)
const handlePlay = useCallback(() => {
if (playlistId) void playPlaylist(playlistId, songIds)
}, [playPlaylist, playlistId, songIds])
if (fromDownloads) void playInOrder(songIds, playOrigin)
else if (playlistId) void playPlaylist(playlistId, songIds)
}, [
fromDownloads,
playInOrder,
playOrigin,
playPlaylist,
playlistId,
songIds,
])
const handleShuffle = useCallback(() => {
if (playlistId) void playPlaylistShuffled(playlistId, songIds)
}, [playPlaylistShuffled, playlistId, songIds])
if (fromDownloads) void playShuffled(songIds, playOrigin)
else if (playlistId) void playPlaylistShuffled(playlistId, songIds)
}, [
fromDownloads,
playShuffled,
playOrigin,
playPlaylistShuffled,
playlistId,
songIds,
])
const handleSubscribeToggle = useCallback(async () => {
if (!playlistId) return
@@ -370,6 +402,7 @@ function PlaylistContent({
removable={canEdit}
palette={palette}
swipeGroup={swipeGroup}
downloadRef={downloadRef}
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
onRemove={handleRemoveSong}
@@ -377,6 +410,7 @@ function PlaylistContent({
),
[
canEdit,
downloadRef,
handlePlaySong,
handleRemoveSong,
handleSongMenuAction,
@@ -431,6 +465,7 @@ function PlaylistContent({
isSubscribed={isSubscribed}
showSubscribe={!playlist.isOwner && playlistId !== null}
onSubscribeToggle={handleSubscribeToggle}
downloadRef={downloadRef}
onPlay={handlePlay}
onShuffle={handleShuffle}
/>
@@ -450,6 +485,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
removable,
palette,
swipeGroup,
downloadRef,
onPlay,
onAction,
onRemove,
@@ -459,6 +495,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
removable: boolean
palette: CoverPalette
swipeGroup: SwipeRowGroup
downloadRef: CollectionRef
onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void
onRemove: (songId: Id<"songs">) => Promise<boolean>
@@ -473,6 +510,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
palette={palette}
inset
removable={removable}
downloadFrom={downloadRef}
swipe={
Platform.OS !== "web"
? {
@@ -538,9 +576,11 @@ const PlaylistHero = memo(function PlaylistHero({
isSubscribed,
showSubscribe = false,
onSubscribeToggle,
downloadRef,
onPlay,
onShuffle,
}: {
downloadRef: CollectionRef
entityId: string
coverUri: string
hasCover: boolean
@@ -647,6 +687,11 @@ const PlaylistHero = memo(function PlaylistHero({
>
{ownerName}
</Text>
<DownloadedQuality
collection={downloadRef}
color={palette.secondaryForeground}
backgroundColor={palette.background}
/>
</CollectionHero>
<CollectionDivider color={palette.divider} />
</MusicEntityView>
@@ -16,7 +16,12 @@ import { CollectionDivider } from "@/components/collection-list"
import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player"
import { DownloadHeaderButton } from "@/components/download-header-button"
import {
DownloadHeaderButton,
DownloadedQuality,
} from "@/components/download-header-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import { FAVORITES_DOWNLOAD_ID } from "@/contexts/downloads"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
@@ -33,6 +38,7 @@ import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
const SCREEN_OPTIONS = { title: "", headerLargeTitle: false }
const DOWNLOAD_REF = { kind: "playlist", id: FAVORITES_DOWNLOAD_ID } as const
export default function FavoritesScreen() {
const colors = useThemeColors()
@@ -43,6 +49,10 @@ export default function FavoritesScreen() {
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const songIds = useMemo(() => songs.map((song) => song.id), [songs])
const fromDownloads = useOpenedFromDownloads()
const playOrigin = fromDownloads
? downloadsQueueOrigin("playlist:favorites")
: undefined
const screenOptions = useMemo(
() => ({
...SCREEN_OPTIONS,
@@ -68,21 +78,21 @@ export default function FavoritesScreen() {
}, [songs])
const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, songIds),
[playFromSong, songIds]
(song: BrowseSong) => void playFromSong(song.id, songIds, playOrigin),
[playFromSong, playOrigin, songIds]
)
const handleSongMenuAction = useCallback(
(song: BrowseSong, action: MediaAction) =>
void handleSongAction(song, action),
void handleSongAction(song, action, DOWNLOAD_REF),
[handleSongAction]
)
const handlePlay = useCallback(
() => void playInOrder(songIds),
[playInOrder, songIds]
() => void playInOrder(songIds, playOrigin),
[playInOrder, playOrigin, songIds]
)
const handleShuffle = useCallback(
() => void playShuffled(songIds),
[playShuffled, songIds]
() => void playShuffled(songIds, playOrigin),
[playShuffled, playOrigin, songIds]
)
const renderItem = useCallback(
@@ -92,6 +102,7 @@ export default function FavoritesScreen() {
favorited={isSongFavorite(song.id)}
playlistLabel="Add to Another Playlist"
inset
downloadFrom={DOWNLOAD_REF}
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
/>
@@ -185,6 +196,11 @@ const FavoritesHero = memo(function FavoritesHero({
<Text style={[styles.title, { color: colors.foreground }]}>
{title}
</Text>
<DownloadedQuality
collection={DOWNLOAD_REF}
color={colors.mutedForeground}
backgroundColor={colors.background}
/>
<View style={styles.actions}>
<Button
title="Play"
@@ -628,7 +628,7 @@ function DownloadsSection() {
<RememberedQualityCard />
{breakdown.collections.length > 0 ||
breakdown.singles.songIds.length > 0 ? (
breakdown.otherSongs.songIds.length > 0 ? (
<SettingsCard title="Downloaded">
{breakdown.collections.map(
({ collection, bytes, status, fallbackCount }) => (
@@ -695,27 +695,27 @@ function DownloadsSection() {
</View>
)
)}
{breakdown.singles.songIds.length > 0 ? (
{breakdown.otherSongs.songIds.length > 0 ? (
<View style={styles.storageRow}>
<View style={styles.optionCopy}>
<Text style={{ color: colors.foreground, fontSize: 15 }}>
Individual songs
Other Downloaded Songs
</Text>
<Text style={{ color: colors.mutedForeground, fontSize: 13 }}>
{songCount(breakdown.singles.songIds.length)}
{songCount(breakdown.otherSongs.songIds.length)}
</Text>
</View>
<Text style={[styles.storageSize, { color: colors.foreground }]}>
{formatBytes(breakdown.singles.bytes)}
{formatBytes(breakdown.otherSongs.bytes)}
</Text>
<Pressable
hitSlop={8}
accessibilityRole="button"
accessibilityLabel="Remove individually downloaded songs"
accessibilityLabel="Remove Other Downloaded Songs"
onPress={() =>
confirm(
"Remove individual songs?",
() => void queue.remove(breakdown.singles.songIds)
"Remove Other Downloaded Songs?",
() => void queue.removeOtherSongs()
)
}
>
@@ -0,0 +1 @@
export { default } from "../../home/downloads"
@@ -0,0 +1 @@
export { default } from "../../home/downloads/other"
@@ -30,6 +30,11 @@ const links = [
icon: "clock" as const,
},
{ title: "Favorites", href: "/playlist/favorites", icon: "star" as const },
{
title: "Downloads",
href: "/downloads",
icon: "arrow.down.circle" as const,
},
]
function LibraryIcon({ name }: { name: (typeof links)[number]["icon"] }) {
@@ -51,6 +56,7 @@ function LibraryIcon({ name }: { name: (typeof links)[number]["icon"] }) {
clock: "time",
sparkles: "sparkles",
star: "star",
"arrow.down.circle": "arrow-down-circle",
}
return (
<Ionicons
@@ -0,0 +1 @@
export { default } from "../../home/downloads"
@@ -0,0 +1 @@
export { default } from "../../home/downloads/other"
+3 -1
View File
@@ -66,6 +66,7 @@ export const CoverImage = memo(function CoverImage({
contentFit = "cover",
blurRadius,
placeholderVariant = "icon",
placeholderIcon = "musical-note",
}: {
uri: string
hasCover: boolean
@@ -73,6 +74,7 @@ export const CoverImage = memo(function CoverImage({
contentFit?: ImageContentFit
blurRadius?: number
placeholderVariant?: "icon" | "solid"
placeholderIcon?: keyof typeof Ionicons.glyphMap
}) {
const colors = useThemeColors()
const flatStyle = useMemo(() => StyleSheet.flatten(style) ?? {}, [style])
@@ -93,7 +95,7 @@ export const CoverImage = memo(function CoverImage({
>
{placeholderVariant === "icon" ? (
<Ionicons
name="musical-note"
name={placeholderIcon}
size={placeholderIconSize(flatStyle)}
color={colors.coverPlaceholderIcon}
/>
@@ -1,12 +1,16 @@
import { Ionicons } from "@expo/vector-icons"
import { Alert, Pressable } from "react-native"
import { Alert, Pressable, StyleSheet, Text, View } from "react-native"
import Svg, { Circle, Rect } from "react-native-svg"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import {
useDownloads,
useDownloadsVersion,
useIsCollectionDownloaded,
type DownloadTarget,
} from "@/contexts/downloads"
import type { CollectionRef } from "@otunes/convex/client/download-queue"
import { DOWNLOAD_QUALITY_LABELS } from "@otunes/convex/download-quality"
const SIZE = 22
const RADIUS = 9
@@ -108,3 +112,45 @@ export function DownloadHeaderButton({
</Pressable>
)
}
/** The quality an album or playlist was downloaded in, once downloaded. */
export function DownloadedQuality({
collection,
color,
backgroundColor,
}: {
collection: CollectionRef
color: string
backgroundColor: string
}) {
const { queue } = useDownloads()
const downloaded = useIsCollectionDownloaded(collection)
const quality = downloaded
? queue?.getCollection(collection)?.quality
: undefined
if (!quality) return null
return (
<View
style={styles.quality}
accessible
accessibilityLabel={`Downloaded in ${DOWNLOAD_QUALITY_LABELS[quality]}`}
>
<Ionicons name="arrow-down-circle" size={14} color={color} />
{quality === "lossless" || quality === "atmos" ? (
<AudioFormatBadge
format={quality}
color={color}
backgroundColor={backgroundColor}
/>
) : (
<Text style={{ color, fontSize: 13 }}>
{DOWNLOAD_QUALITY_LABELS[quality]}
</Text>
)}
</View>
)
}
const styles = StyleSheet.create({
quality: { flexDirection: "row", alignItems: "center", gap: 4 },
})
+19 -4
View File
@@ -4,7 +4,11 @@ import { MusicEntityView } from "@/components/music-entity-view"
import { collectionInset } from "@/components/collection-list"
import { CoverImage } from "@/components/cover-image"
import { Ionicons } from "@expo/vector-icons"
import { useIsSongDownloaded } from "@/contexts/downloads"
import {
useSongDownloadState,
useToggleSongDownload,
} from "@/contexts/downloads"
import type { DownloadSource } from "@otunes/convex/client/download-queue"
import { useServerConfig } from "@/contexts/server-config"
import type { BrowseSong } from "@otunes/convex/types"
import type { CoverPalette } from "@/lib/cover-palette"
@@ -35,6 +39,7 @@ export const SongRow = memo(function SongRow({
palette,
inset = false,
swipe,
downloadFrom,
}: {
song: BrowseSong
onPress?: () => void
@@ -52,10 +57,14 @@ export const SongRow = memo(function SongRow({
}
/** Album/playlist layout: the divider starts at the title, not the artwork. */
inset?: boolean
/** The download this row belongs to; removing only takes it out of that. */
downloadFrom?: DownloadSource
}) {
const { config } = useServerConfig()
const colors = useThemeColors()
const downloaded = useIsSongDownloaded(song.id)
const downloadState = useSongDownloadState(song.id, downloadFrom)
const downloaded = downloadState === "here"
const toggleDownload = useToggleSongDownload()
if (!config) return null
const foreground = palette?.foreground ?? colors.foreground
@@ -79,7 +88,7 @@ export const SongRow = memo(function SongRow({
{song.artist.name} · {song.album.title}
</Text>
</View>
{downloaded ? (
{downloaded || downloadState === "device" ? (
<Ionicons
name="arrow-down-circle"
size={14}
@@ -120,6 +129,8 @@ export const SongRow = memo(function SongRow({
onPlayNext={swipe.onPlayNext}
onAddToQueue={swipe.onAddToQueue}
onRemove={swipe.onRemove}
downloaded={downloaded}
onDownload={() => toggleDownload(song, downloaded, downloadFrom)}
backgroundColor={swipe.backgroundColor}
onPress={onPress}
style={rowStyle}
@@ -166,6 +177,7 @@ export const SongListRow = memo(function SongListRow({
inset,
swipe,
removable,
downloadFrom,
onPlay,
onAction,
}: {
@@ -183,11 +195,13 @@ export const SongListRow = memo(function SongListRow({
}
/** Shows "Remove from Playlist" in the context menu. */
removable?: boolean
/** The download this row belongs to; removing only takes it out of that. */
downloadFrom?: DownloadSource
onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void
}) {
const { config } = useServerConfig()
const downloaded = useIsSongDownloaded(song.id)
const downloaded = useSongDownloadState(song.id, downloadFrom) === "here"
const handlePress = useCallback(() => onPlay(song), [onPlay, song])
return (
@@ -196,6 +210,7 @@ export const SongListRow = memo(function SongListRow({
palette={palette}
inset={inset}
swipe={swipe}
downloadFrom={downloadFrom}
onPress={handlePress}
contextMenu={{
preview: config
+38 -14
View File
@@ -42,7 +42,8 @@ function impact() {
/**
* A tap competes with the swipe so dragging a moving row never starts playback.
* A full swipe commits the outer action: Add to Queue on the leading side, and
* Remove on the trailing side when `onRemove` is set.
* Remove on the trailing side when `onRemove` is set, else Download. Download
* turns into a red Remove Download once `downloaded`.
*/
export function SongSwipeRow({
children,
@@ -53,6 +54,8 @@ export function SongSwipeRow({
onPlayNext,
onAddToQueue,
onRemove,
onDownload,
downloaded = false,
}: {
children: ReactNode
style?: StyleProp<ViewStyle>
@@ -62,6 +65,8 @@ export function SongSwipeRow({
onPlayNext: () => void
onAddToQueue: () => void
onRemove?: () => void
onDownload?: () => void
downloaded?: boolean
}) {
const hasRemove = !!onRemove
const trailingWidth = hasRemove ? PAIRED_ACTION_WIDTH * 2 : ACTION_WIDTH
@@ -95,10 +100,10 @@ export function SongSwipeRow({
(side: number) => {
close()
if (side > 0) onAddToQueue()
// Without Remove, the trailing action is the Download placeholder.
else onRemove?.()
else if (onRemove) onRemove()
else onDownload?.()
},
[close, onAddToQueue, onRemove]
[close, onAddToQueue, onRemove, onDownload]
)
const tapRow = useCallback(() => {
if (open) close()
@@ -233,6 +238,7 @@ export function SongSwipeRow({
side={-1}
paired={hasRemove}
remove={hasRemove}
downloaded={downloaded}
x={x}
height={height}
progress={commitProgress}
@@ -244,11 +250,15 @@ export function SongSwipeRow({
side={-1}
secondary
paired
downloaded={downloaded}
x={x}
height={height}
progress={commitProgress}
open={open === -1}
onPress={close}
onPress={() => {
close()
onDownload?.()
}}
/>
)}
<GestureDetector gesture={gesture}>
@@ -259,7 +269,10 @@ export function SongSwipeRow({
accessibilityActions={[
{ name: "addToQueue", label: "Add to Queue" },
{ name: "playNext", label: "Play Next" },
{ name: "download", label: "Download" },
{
name: "download",
label: downloaded ? "Remove Download" : "Download",
},
...(hasRemove
? [{ name: "remove", label: "Remove from Playlist" }]
: []),
@@ -267,6 +280,10 @@ export function SongSwipeRow({
onAccessibilityAction={(event) => {
if (event.nativeEvent.actionName === "remove") activate(-1)
if (event.nativeEvent.actionName === "addToQueue") activate(1)
if (event.nativeEvent.actionName === "download") {
close()
onDownload?.()
}
if (event.nativeEvent.actionName === "playNext") {
close()
onPlayNext()
@@ -290,6 +307,7 @@ function SwipeAction({
secondary = false,
paired = side > 0,
remove = false,
downloaded = false,
x,
height,
progress,
@@ -300,6 +318,8 @@ function SwipeAction({
secondary?: boolean
paired?: boolean
remove?: boolean
/** Shows the download action as Remove Download. */
downloaded?: boolean
x: SharedValue<number>
height: SharedValue<number>
progress: SharedValue<number>
@@ -370,6 +390,8 @@ function SwipeAction({
},
],
}))
const removesDownload = side < 0 && !remove && downloaded
const destructive = remove || removesDownload
return (
<Animated.View
pointerEvents={open ? "auto" : "none"}
@@ -386,11 +408,13 @@ function SwipeAction({
accessibilityLabel={
remove
? "Remove from Playlist"
: side > 0
? secondary
? "Play Next"
: "Add to Queue"
: "Download"
: removesDownload
? "Remove Download"
: side > 0
? secondary
? "Play Next"
: "Add to Queue"
: "Download"
}
onPress={onPress}
style={styles.actionButton}
@@ -399,7 +423,7 @@ function SwipeAction({
style={[
styles.pill,
{
backgroundColor: remove
backgroundColor: destructive
? IS_ANDROID
? "#d32f2f"
: "#ff3b30"
@@ -416,7 +440,7 @@ function SwipeAction({
{IS_ANDROID ? (
<Ionicons
name={
remove
destructive
? "trash-outline"
: side < 0
? "arrow-down"
@@ -430,7 +454,7 @@ function SwipeAction({
) : (
<SymbolView
name={
remove
destructive
? "trash"
: side > 0
? secondary
+65 -6
View File
@@ -10,6 +10,7 @@ import {
type ReactNode,
} from "react"
import {
Alert,
Modal,
Platform,
Pressable,
@@ -40,7 +41,9 @@ import type { Id } from "@otunes/convex/_generated/dataModel"
import type {
CollectionRef,
DownloadableSong,
DownloadSource,
DownloadQueue,
SongDownloadState,
} from "@otunes/convex/client/download-queue"
import {
DOWNLOAD_OPTIONS_PATH,
@@ -54,7 +57,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. */
@@ -88,12 +97,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 {
const { queue } = useDownloads()
return useSyncExternalStore(
queue?.subscribe ?? noopSubscribe,
() => queue?.getDownloaded(songId) !== undefined
() => queue?.downloadState(songId, from) ?? "none"
)
}
@@ -106,6 +121,41 @@ export function useIsCollectionDownloaded(ref: CollectionRef) {
)
}
/**
* For swipe actions: downloads a song, or asks before removing its download
* (from `from` only, when given).
*/
export function useToggleSongDownload() {
const { requestDownload, removeDownload } = useDownloads()
return useCallback(
(
song: { id: string; title: string },
downloaded: boolean,
from?: DownloadSource
) => {
const target = {
kind: "songs" as const,
songIds: [song.id],
title: song.title,
from,
}
if (!downloaded) {
void requestDownload(target)
return
}
Alert.alert("Remove download?", song.title, [
{ text: "Cancel", style: "cancel" },
{
text: "Remove",
style: "destructive",
onPress: () => void removeDownload(target),
},
])
},
[requestDownload, removeDownload]
)
}
async function fetchDownloadOptions(config: ServerConfig, songIds: string[]) {
const cookieHeader = await getAuthCookieHeader(
config.serverUrl,
@@ -323,6 +373,14 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
const requestDownload = useCallback(
async (target: DownloadTarget) => {
if (!config || !queue || target.songIds.length === 0) return
if (target.songIds.every((id) => queue.getDownloaded(id))) {
// Already on this device: just give them back to their downloads.
await queue.enqueue(
target.songIds.map((id) => ({ id, files: {} })),
"high"
)
return
}
try {
// Caches titles and formats so downloads can be queued offline.
void loadPlaybackSongs(
@@ -348,8 +406,9 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
const removeDownload = useCallback(
async (target: DownloadTarget) => {
if (!queue) return
if (target.kind === "songs") await queue.remove(target.songIds)
else await queue.removeCollection(target)
if (target.kind === "songs") {
await queue.removeSongs(target.songIds, target.from)
} else await queue.removeCollection(target)
},
[queue]
)
+12 -5
View File
@@ -24,6 +24,7 @@ import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import * as playbackQueue from "@otunes/convex/client/playback-queue"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import { getPlaybackStore } from "@otunes/convex/client/playback-store"
import { isDownloadsQueueOrigin } from "@otunes/convex/download-quality"
import { rememberSongs, useSong, useSongs } from "@/lib/song-cache"
import { donateMusicPlay, type MusicEntityKind } from "@/lib/app-intents"
import { showError } from "@/lib/toast"
@@ -43,8 +44,9 @@ type PlaybackContextValue = {
seekTo: (seconds: number) => void
waitForPlaybackReady: (playing?: boolean) => Promise<void>
setIsPlaying: (playing: boolean) => void
playInOrder: (songIds: Id<"songs">[]) => Promise<void>
playShuffled: (songIds: Id<"songs">[]) => Promise<void>
/** An origin from `downloadsQueueOrigin` plays downloads in any quality. */
playInOrder: (songIds: Id<"songs">[], origin?: string) => Promise<void>
playShuffled: (songIds: Id<"songs">[], origin?: string) => Promise<void>
addToQueueNext: (songIds: Id<"songs">[]) => Promise<void>
addToQueueLast: (songIds: Id<"songs">[]) => Promise<void>
playFromSong: (
@@ -245,6 +247,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const queueOriginRef = useRef<string | undefined>(undefined)
const playRequestRef = useRef(0)
const [queueStartVersion, setQueueStartVersion] = useState(0)
// Queues started from the Downloads page play downloads in any quality.
const [fromDownloads, setFromDownloads] = useState(false)
const queueSongIds = playback.queue
const queueHistorySongIds = playback.history
@@ -280,6 +284,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
repeatEnabled,
currentSong,
queueStartVersion,
fromDownloads,
})
const { resetProgress } = useProgressPersistence({
@@ -310,6 +315,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
queueOriginRef.current =
recorded.origin ??
(recorded.playlistId ? `playlist:${recorded.playlistId}` : undefined)
setFromDownloads(isDownloadsQueueOrigin(recorded.origin))
resetQueuePlayback()
store.update(playbackQueue.clearQueue)
store.update(recipe)
@@ -363,10 +369,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
)
const playSongs = useCallback(
(shuffled: boolean) => async (songIds: Id<"songs">[]) => {
(shuffled: boolean) => async (songIds: Id<"songs">[], origin?: string) => {
if (songIds.length === 0) return
startPlayback((state) =>
playbackQueue.startQueue(state, songIds, shuffled)
startPlayback(
(state) => playbackQueue.startQueue(state, songIds, shuffled),
{ origin }
)
},
[startPlayback]
+10 -3
View File
@@ -2,6 +2,7 @@ import { useConvex } from "convex/react"
import { useCallback } from "react"
import type { MediaAction } from "@/components/media-context-menu"
import type { DownloadSource } from "@otunes/convex/client/download-queue"
import { useAddToPlaylist } from "@/contexts/add-to-playlist"
import { useDownloads } from "@/contexts/downloads"
import { useCacheScope } from "@/contexts/persistent-cache"
@@ -73,8 +74,9 @@ export function useMediaMenuActions() {
[addToQueueLast, addToQueueNext, playShuffled]
)
/** `from` limits removing a download to that album, playlist, or Other. */
const handleSongAction = useCallback(
async (song: BrowseSong, action: MediaAction) => {
async (song: BrowseSong, action: MediaAction, from?: DownloadSource) => {
const songIds = [song.id as Id<"songs">]
switch (action) {
case "create-station":
@@ -101,7 +103,12 @@ export function useMediaMenuActions() {
break
case "download":
case "remove-download": {
const target = { kind: "songs" as const, songIds, title: song.title }
const target = {
kind: "songs" as const,
songIds,
title: song.title,
from,
}
await (action === "download"
? requestDownload(target)
: removeDownload(target))
@@ -324,7 +331,7 @@ export function useMediaMenuActions() {
cover: album.cover,
},
}
await handleSongAction(song, action)
await handleSongAction(song, action, { kind: "album", id: album.id })
},
[handleSongAction]
)
+18 -7
View File
@@ -18,6 +18,7 @@ import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
import { playbackStreamPlan } from "@otunes/convex/playback-stream"
import { streamDownloadQuality } from "@otunes/convex/download-quality"
import * as playbackQueue from "@otunes/convex/client/playback-queue"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import type { PlaybackStore } from "@otunes/convex/client/playback-store"
@@ -72,6 +73,7 @@ export function useNativePlaylistSync({
repeatEnabled,
currentSong,
queueStartVersion,
fromDownloads,
}: {
store: PlaybackStore
queueSongIds: Id<"songs">[]
@@ -79,6 +81,8 @@ export function useNativePlaylistSync({
repeatEnabled: RepeatMode
currentSong: BrowseSong | null
queueStartVersion: number
/** Plays downloads in any quality, for queues started from Downloads. */
fromDownloads: boolean
}) {
const convex = useConvex()
const { config } = useServerConfig()
@@ -460,7 +464,7 @@ export function useNativePlaylistSync({
}
if (!isCurrentLoad()) return
const loadKey = `${user.playbackQuality}:${atmosEnabled(user)}:${cookieHeader}`
const loadKey = `${user.playbackQuality}:${atmosEnabled(user)}:${fromDownloads}:${cookieHeader}`
const needsRebuild =
loadedLoadKeyRef.current !== loadKey ||
nativePlaylistNeedsRebuild(
@@ -503,17 +507,23 @@ export function useNativePlaylistSync({
const sources = new Map<Id<"songs">, AudioSource>()
for (const song of songs) {
if (!song) return null
// Downloads play from this device, whatever the streaming quality.
const localUri = downloadedAudioUri(config, song.id)
if (localUri) {
sources.set(song.id, { uri: localUri, name: song.title })
continue
}
const plan = playbackStreamPlan(
song.files,
user.playbackQuality,
atmosEnabled(user)
)
// Downloads stand in for streams in the same quality, and always
// play in queues started from Downloads.
const download = downloadQueueFor(config).getDownloaded(song.id)
const localUri =
download &&
(fromDownloads || download.quality === streamDownloadQuality(plan))
? downloadedAudioUri(config, song.id)
: null
if (localUri) {
sources.set(song.id, { uri: localUri, name: song.title })
continue
}
sources.set(
song.id,
songAudioSource(
@@ -640,6 +650,7 @@ export function useNativePlaylistSync({
currentSongId,
currentSongSyncKey,
destroyPlaylist,
fromDownloads,
ensurePlaylist,
handlePlaybackLoadFailure,
historySyncKey,
+15
View File
@@ -0,0 +1,15 @@
import { useLocalSearchParams } from "expo-router"
export const OTHER_DOWNLOADS_TITLE = "Other Downloaded Songs"
/** Route param marking album and playlist screens opened from Downloads. */
export const FROM_DOWNLOADS_PARAM = "from=downloads"
/**
* True on album and playlist screens opened from Downloads, where playback
* uses the downloads whatever their quality.
*/
export function useOpenedFromDownloads() {
const { from } = useLocalSearchParams<{ from?: string }>()
return from === "downloads"
}
+13 -13
View File
@@ -4,8 +4,8 @@ import { Platform } from "react-native"
import {
createDownloadQueue,
type DownloadedCollection,
type DownloadedSong,
type DownloadIndex,
type DownloadQueue,
type DownloadStorage,
} from "@otunes/convex/client/download-queue"
@@ -47,7 +47,7 @@ function audioFile(folder: Directory) {
function createStorage(config: ServerConfig): DownloadStorage {
const root = serverDirectory(config)
const collectionsFile = new File(root, "collections.json")
const indexFile = new File(root, "index.json")
function foldersFor(songIds: ReadonlySet<string>) {
return songFolders(root).filter((folder) => {
@@ -101,20 +101,20 @@ function createStorage(config: ServerConfig): DownloadStorage {
throw error
}
},
async readCollections() {
if (!collectionsFile.exists) return []
try {
return JSON.parse(
await collectionsFile.text()
) as DownloadedCollection[]
} catch {
return []
async readIndex() {
if (indexFile.exists) {
try {
return JSON.parse(await indexFile.text()) as DownloadIndex
} catch {
// An unreadable index starts empty.
}
}
return { collections: [], otherSongIds: [] }
},
async writeCollections(collections) {
async writeIndex(index) {
root.create({ intermediates: true, idempotent: true })
if (!collectionsFile.exists) collectionsFile.create()
await collectionsFile.write(JSON.stringify(collections))
if (!indexFile.exists) indexFile.create()
await indexFile.write(JSON.stringify(index))
},
async remove(songIds) {
for (const folder of foldersFor(new Set(songIds))) folder.delete()
+2
View File
@@ -13,6 +13,8 @@ export const tabStackScreenTitles: Record<string, string> = {
"recently-played": "Recently Played",
"recently-added": "Recently Added",
settings: "Settings",
"downloads/index": "Downloads",
"downloads/other": "Other Downloaded Songs",
}
export function useStackScreenOptions(
+1
View File
@@ -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<
@@ -0,0 +1,7 @@
"use client"
import { OtherDownloadsView } from "@/components/other-downloads-view"
export default function Page() {
return <OtherDownloadsView />
}
@@ -0,0 +1,7 @@
"use client"
import { DownloadsView } from "@/components/downloads-view"
export default function Page() {
return <DownloadsView />
}
+35 -14
View File
@@ -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({
<AudioFormatBadge format="atmos" />
</>
) : null}
<DownloadedQuality collection={downloadRef} />
</div>
</div>
@@ -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
))
}
>
<Shuffle />
@@ -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))
}
>
<Play className="fill-current" />
@@ -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)}
+2
View File
@@ -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() {
+34 -1
View File
@@ -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 (
<span
className="inline-flex items-center gap-1"
aria-label={`Downloaded in ${DOWNLOAD_QUALITY_LABELS[quality]}`}
>
<ArrowDownToLine className="size-3.5" aria-hidden />
{quality === "lossless" || quality === "atmos" ? (
<AudioFormatBadge format={quality} />
) : (
DOWNLOAD_QUALITY_LABELS[quality]
)}
</span>
)
}
+19 -3
View File
@@ -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(
+7 -9
View File
@@ -151,7 +151,7 @@ export function DownloadsSettings() {
) : null}
{breakdown.collections.length > 0 ||
breakdown.singles.songIds.length > 0 ? (
breakdown.otherSongs.songIds.length > 0 ? (
<div className="divide-y text-sm">
{breakdown.collections.map(
({ collection, bytes, status, fallbackCount }) => (
@@ -194,24 +194,22 @@ export function DownloadsSettings() {
</div>
)
)}
{breakdown.singles.songIds.length > 0 ? (
{breakdown.otherSongs.songIds.length > 0 ? (
<div className="flex items-center gap-3 py-2">
<div className="min-w-0 flex-1">
<p>Individual songs</p>
<p>Other Downloaded Songs</p>
<p className="text-xs text-muted-foreground">
{songCount(breakdown.singles.songIds.length)}
{songCount(breakdown.otherSongs.songIds.length)}
</p>
</div>
<span className="tabular-nums">
{formatBytes(breakdown.singles.bytes)}
{formatBytes(breakdown.otherSongs.bytes)}
</span>
<Button
variant="ghost"
size="icon-sm"
aria-label="Remove individually downloaded songs"
onClick={() =>
void downloadQueue.remove(breakdown.singles.songIds)
}
aria-label="Remove Other Downloaded Songs"
onClick={() => void downloadQueue.removeOtherSongs()}
>
<Trash2 />
</Button>
+152
View File
@@ -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 (
<div className="flex size-full items-center justify-center bg-muted">
<Star className="size-1/4 fill-primary text-primary" />
</div>
)
}
return (
<Image
src={
collection.kind === "album"
? albumCoverUrl(collection.id)
: playlistCoverUrl(collection.id)
}
alt={collection.title}
fill
sizes="(max-width: 640px) 50vw, (max-width: 1024px) 25vw, 16vw"
className="object-cover"
/>
)
}
function DownloadCard({
href,
title,
subtitle,
cover,
}: {
href: string
title: string
subtitle: string
cover: React.ReactNode
}) {
return (
<Link href={href} className="group flex flex-col gap-2">
<div className="relative aspect-square overflow-hidden rounded-lg ring-1 ring-foreground/10">
{cover}
</div>
<div className="min-w-0">
<p className="truncate text-sm font-medium group-hover:underline">
{title}
</p>
<p className="truncate text-xs text-muted-foreground tabular-nums">
{subtitle}
</p>
</div>
</Link>
)
}
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 (
<div className="flex h-svh flex-col">
<PageHeader title="Downloads" />
{empty ? (
<div className="flex flex-1 items-center justify-center p-6 pb-28">
<p className="text-sm text-muted-foreground">
Nothing downloaded in this browser.
</p>
</div>
) : (
<div className="flex-1 overflow-y-auto p-6 pb-28">
<div className={albumGridClassName}>
{otherSongs.songIds.length > 0 ? (
<DownloadCard
href={OTHER_DOWNLOADS_PATH}
title={OTHER_DOWNLOADS_TITLE}
subtitle={`${songCount(otherSongs.songIds.length)} · ${formatBytes(otherSongs.bytes)}`}
cover={
<Image
src="/placeholder-downloads.svg"
alt=""
fill
className="object-cover"
unoptimized
/>
}
/>
) : null}
{rows.map(({ collection, bytes }) => (
<DownloadCard
key={`${collection.kind}:${collection.id}`}
href={collectionHref(collection)}
title={collection.title}
subtitle={`${collection.kind === "album" ? "Album" : "Playlist"} · ${formatBytes(bytes)}`}
cover={<CollectionCover collection={collection} />}
/>
))}
</div>
</div>
)}
</div>
)
}
@@ -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 (
<div className="flex h-svh flex-col">
<PageHeader title={OTHER_DOWNLOADS_TITLE} />
<ScrollArea className="min-h-0 flex-1 [&_[data-slot=scroll-area-viewport]>div]:block!">
<div
className="w-full pb-28"
onClick={(event) => {
if (event.target === event.currentTarget) clearSelection()
}}
>
{songIds.length === 0 ? (
<p className="p-6 text-sm text-muted-foreground">
Songs you download on their own appear here.
</p>
) : (
<>
<div className="flex gap-2 px-6 py-4">
<Button
className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90"
onClick={() => void playInOrder(playableIds, PLAY_ORIGIN)}
disabled={playableIds.length === 0}
>
<Play className="fill-current" />
Play
</Button>
<Button
variant="secondary"
size="icon"
className="rounded-full"
aria-label="Shuffle"
onClick={() => void playShuffled(playableIds, PLAY_ORIGIN)}
disabled={playableIds.length === 0}
>
<Shuffle />
</Button>
</div>
<LibraryTrackListHeader />
<VirtualList
count={songs.length}
estimateSize={estimateSongRowSize}
getItemKey={(index) => songs[index].id}
renderItem={(index) => (
<TrackRow
variant="library"
song={songs[index]}
index={index}
selectionPosition={selectionPositions[index]}
isFavorite={isSongFavorite(songs[index].id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
onToggleFavorite={handleToggleFavorite}
onPrepareContextMenu={prepareContextMenu}
onMediaAction={handleMediaAction}
/>
)}
/>
</>
)}
</div>
</ScrollArea>
</div>
)
}
+65 -27
View File
@@ -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<void>
playShuffled: (songIds: Id<"songs">[]) => Promise<void>
/** An origin from `downloadsQueueOrigin` plays downloads in any quality. */
playInOrder: (songIds: Id<"songs">[], origin?: string) => Promise<void>
playShuffled: (songIds: Id<"songs">[], origin?: string) => Promise<void>
addToQueueNext: (songIds: Id<"songs">[]) => Promise<void>
addToQueueLast: (songIds: Id<"songs">[]) => Promise<void>
playFromSong: (
@@ -190,44 +195,53 @@ type PlaybackLoadSettings = {
useHls: boolean
}
function playbackLoadSettings(
function userStreamPlan(
user: {
preferAtmos?: boolean
playbackQuality?: PlaybackQuality
},
dolbyAtmosSupported: boolean | null,
files: Record<string, unknown>
): 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<string, unknown> | undefined
files: Record<string, unknown> | 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"
+33 -12
View File
@@ -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 }) {
<p className="text-lg font-semibold text-primary">
{playlist.owner.name}
</p>
<p className="text-sm text-muted-foreground empty:hidden">
<DownloadedQuality collection={downloadRef} />
</p>
</div>
<div className="flex flex-wrap items-center justify-center gap-2 sm:justify-start">
@@ -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
+2 -2
View File
@@ -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,
+9 -3
View File
@@ -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 ? (
<ArrowDownToLine className="size-3.5" aria-label="Downloaded" />
) : null}
{formatDuration(song.durationSeconds)}
+33 -5
View File
@@ -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
)
}
+19 -4
View File
@@ -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<string>
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]
)
}
+9 -8
View File
@@ -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<IDBDatabase> | 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
+13
View File
@@ -0,0 +1,13 @@
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" width="100" height="100"><style>:root {
--icon: rgba(60, 60, 67, 0.18);
--bg: #e3e3e3;
color-scheme: light dark;
}
@media (prefers-color-scheme: dark) {
:root {
--icon: rgba(235, 235, 245, 0.16);
--bg: #323232;
}
}
</style><path fill="var(--bg)" d="M0 0h100v100H0z"></path><path fill="none" stroke="var(--icon)" stroke-width="7" stroke-linecap="round" stroke-linejoin="round" d="M50 27v38M33 49l17 17 17-17M31 75h38"></path></svg>

After

Width:  |  Height:  |  Size: 614 B

+178 -43
View File
@@ -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<DownloadedCollection, "kind" | "id">
/** 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<DownloadedSong[]>
@@ -42,8 +65,8 @@ export type DownloadStorage = {
signal: AbortSignal
): Promise<number>
remove(songIds: readonly string[]): Promise<void>
readCollections(): Promise<DownloadedCollection[]>
writeCollections(collections: DownloadedCollection[]): Promise<void>
readIndex(): Promise<DownloadIndex>
writeIndex(index: DownloadIndex): Promise<void>
}
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<typeof createDownloadQueue>
function collectionKey({ kind, id }: CollectionRef) {
@@ -90,6 +115,7 @@ export function createDownloadQueue(
) {
const downloaded = new Map<string, DownloadedSong>()
const collections = new Map<string, DownloadedCollection>()
const otherSongIds = new Set<string>()
const waiting: { song: DownloadableSong; quality: DownloadQuality }[] = []
const running = new Map<string, AbortController>()
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<string>()
/** 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<DownloadedCollection, "songIds">,
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<string>()
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,
}
},
}
+29 -1
View File
@@ -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. */