Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
494 lines
15 KiB
TypeScript
494 lines
15 KiB
TypeScript
import { useConvex, useQuery } from "convex/react"
|
|
import {
|
|
createContext,
|
|
useCallback,
|
|
useContext,
|
|
useEffect,
|
|
useMemo,
|
|
useState,
|
|
useSyncExternalStore,
|
|
type ReactNode,
|
|
} from "react"
|
|
import {
|
|
Alert,
|
|
Modal,
|
|
Platform,
|
|
Pressable,
|
|
StyleSheet,
|
|
Switch,
|
|
Text,
|
|
View,
|
|
} from "react-native"
|
|
import { toast } from "sonner-native"
|
|
|
|
import { AndroidSheet } from "@/components/android-sheet"
|
|
import { AudioFormatBadge } from "@/components/audio-format-badge"
|
|
import { useCacheScope } from "@/contexts/persistent-cache"
|
|
import { useServerConfig } from "@/contexts/server-config"
|
|
import { useBackgroundDownloads } from "@/hooks/use-background-downloads"
|
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
|
import { getAuthCookieHeader } from "@/lib/auth-cookies"
|
|
import {
|
|
downloadQueueFor,
|
|
readRememberedDownloadQuality,
|
|
writeRememberedDownloadQuality,
|
|
} from "@/lib/downloads"
|
|
import { loadPlaybackSongs } from "@/lib/playback-files"
|
|
import { downloadQualitySupported } from "@/lib/playback-capabilities"
|
|
import type { ServerConfig } from "@/lib/server-config"
|
|
import { showError } from "@/lib/toast"
|
|
import { useThemeColors } from "@/lib/theme"
|
|
import { api } from "@otunes/convex/_generated/api"
|
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
|
import type {
|
|
CollectionRef,
|
|
DownloadableSong,
|
|
DownloadSource,
|
|
DownloadQueue,
|
|
SongDownloadState,
|
|
} from "@otunes/convex/client/download-queue"
|
|
import { FAVORITES_ID } from "@otunes/convex/client/download-queue"
|
|
import {
|
|
DOWNLOAD_OPTIONS_PATH,
|
|
DOWNLOAD_QUALITY_DETAILS,
|
|
DOWNLOAD_QUALITY_LABELS,
|
|
formatBytes,
|
|
type DownloadOptionsResponse,
|
|
type DownloadQuality,
|
|
type SizedDownloadOption,
|
|
} from "@otunes/convex/download-quality"
|
|
|
|
/** Songs on their own, or an album or playlist that stays downloaded as a whole. */
|
|
export type DownloadTarget =
|
|
| {
|
|
kind: "songs"
|
|
songIds: string[]
|
|
title: string
|
|
/** Removing takes the songs out of only this download. */
|
|
from?: DownloadSource
|
|
}
|
|
| (CollectionRef & { title: string; songIds: string[] })
|
|
|
|
/** The Favorites playlist has no ID, so downloads use this one. */
|
|
export const FAVORITES_DOWNLOAD_ID = FAVORITES_ID
|
|
|
|
type DownloadsContextValue = {
|
|
queue: DownloadQueue | null
|
|
/** Asks for a quality (unless remembered) and starts downloading. */
|
|
requestDownload: (target: DownloadTarget) => Promise<void>
|
|
removeDownload: (target: DownloadTarget) => Promise<void>
|
|
}
|
|
|
|
const DownloadsContext = createContext<DownloadsContextValue | null>(null)
|
|
|
|
export function useDownloads() {
|
|
const context = useContext(DownloadsContext)
|
|
if (!context) {
|
|
throw new Error("useDownloads must be used within DownloadsProvider")
|
|
}
|
|
return context
|
|
}
|
|
|
|
const noopSubscribe = () => () => {}
|
|
|
|
/** Re-renders on every download change. Prefer the narrower hooks in lists. */
|
|
export function useDownloadsVersion() {
|
|
const { queue } = useDownloads()
|
|
return useSyncExternalStore(
|
|
queue?.subscribe ?? noopSubscribe,
|
|
() => queue?.getVersion() ?? 0
|
|
)
|
|
}
|
|
|
|
/**
|
|
* 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?.downloadState(songId, from) ?? "none"
|
|
)
|
|
}
|
|
|
|
/** Whether an album or playlist is downloaded. */
|
|
export function useIsCollectionDownloaded(ref: CollectionRef) {
|
|
const { queue } = useDownloads()
|
|
return useSyncExternalStore(
|
|
queue?.subscribe ?? noopSubscribe,
|
|
() => queue?.getCollection(ref) !== undefined
|
|
)
|
|
}
|
|
|
|
/**
|
|
* 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,
|
|
config.convexUrl
|
|
)
|
|
if (!cookieHeader) throw new Error("Sign in to download")
|
|
const response = await fetch(`${config.serverUrl}${DOWNLOAD_OPTIONS_PATH}`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json", Cookie: cookieHeader },
|
|
body: JSON.stringify({
|
|
songIds,
|
|
losslessFormat: Platform.OS === "ios" ? "alac" : undefined,
|
|
}),
|
|
})
|
|
if (!response.ok) {
|
|
throw new Error("Could not reach the server to download")
|
|
}
|
|
return (await response.json()) as DownloadOptionsResponse
|
|
}
|
|
|
|
function startDownload(
|
|
queue: DownloadQueue,
|
|
target: DownloadTarget,
|
|
songs: DownloadableSong[],
|
|
quality: DownloadQuality
|
|
) {
|
|
if (target.kind === "songs") return queue.enqueue(songs, quality)
|
|
return queue.downloadCollection(
|
|
{ kind: target.kind, id: target.id, title: target.title, quality },
|
|
songs
|
|
)
|
|
}
|
|
|
|
function optionDetail(option: SizedDownloadOption, songCount: number) {
|
|
if (option.fallbackCount === 0) {
|
|
return DOWNLOAD_QUALITY_DETAILS[option.quality]
|
|
}
|
|
const included = songCount - option.fallbackCount
|
|
return `${included} of ${songCount} songs, ${option.fallbackCount} in High`
|
|
}
|
|
|
|
/** Centered popup asking which quality to download a target at. */
|
|
function DownloadQualityPopup({
|
|
pending,
|
|
onClose,
|
|
onPick,
|
|
}: {
|
|
pending: { target: DownloadTarget; response: DownloadOptionsResponse } | null
|
|
onClose: () => void
|
|
onPick: (quality: DownloadQuality, remember: boolean) => void
|
|
}) {
|
|
const colors = useThemeColors()
|
|
const [remember, setRemember] = useState(false)
|
|
const songCount = pending?.response.songs.length ?? 0
|
|
|
|
return (
|
|
<Modal
|
|
visible={pending !== null}
|
|
animationType="fade"
|
|
transparent
|
|
onRequestClose={onClose}
|
|
>
|
|
<AndroidSheet>
|
|
<Pressable style={styles.overlay} onPress={onClose}>
|
|
<Pressable
|
|
style={[
|
|
styles.popup,
|
|
{ backgroundColor: colors.card, borderColor: colors.border },
|
|
]}
|
|
onPress={(event) => event.stopPropagation()}
|
|
>
|
|
<Text style={[styles.title, { color: colors.foreground }]}>
|
|
Download Quality
|
|
</Text>
|
|
<Text
|
|
style={[styles.subtitle, { color: colors.mutedForeground }]}
|
|
numberOfLines={1}
|
|
>
|
|
{pending?.target.title}
|
|
</Text>
|
|
{pending?.response.options
|
|
.filter((option) => downloadQualitySupported(option.quality))
|
|
.map((option) => (
|
|
<Pressable
|
|
key={option.quality}
|
|
accessibilityRole="button"
|
|
style={[styles.row, { borderBottomColor: colors.border }]}
|
|
onPress={() => onPick(option.quality, remember)}
|
|
>
|
|
<View style={styles.rowText}>
|
|
{option.quality === "lossless" ||
|
|
option.quality === "atmos" ? (
|
|
<AudioFormatBadge
|
|
format={option.quality}
|
|
color={colors.foreground}
|
|
backgroundColor={colors.card}
|
|
/>
|
|
) : (
|
|
<Text
|
|
style={[styles.label, { color: colors.foreground }]}
|
|
>
|
|
{DOWNLOAD_QUALITY_LABELS[option.quality]}
|
|
</Text>
|
|
)}
|
|
<Text
|
|
style={{ color: colors.mutedForeground, fontSize: 12 }}
|
|
>
|
|
{optionDetail(option, songCount)}
|
|
</Text>
|
|
</View>
|
|
<Text
|
|
style={[styles.size, { color: colors.mutedForeground }]}
|
|
>
|
|
{option.estimated ? "~" : ""}
|
|
{formatBytes(option.bytes)}
|
|
</Text>
|
|
</Pressable>
|
|
))}
|
|
<View style={styles.rememberRow}>
|
|
<Text style={{ color: colors.foreground, fontSize: 15 }}>
|
|
Remember my choice
|
|
</Text>
|
|
<Switch value={remember} onValueChange={setRemember} />
|
|
</View>
|
|
</Pressable>
|
|
</Pressable>
|
|
</AndroidSheet>
|
|
</Modal>
|
|
)
|
|
}
|
|
|
|
/** Keeps a downloaded playlist's songs in step with the playlist. */
|
|
function useSyncDownloadedPlaylist(
|
|
queue: DownloadQueue,
|
|
id: string,
|
|
songIds: readonly string[] | undefined
|
|
) {
|
|
const convex = useConvex()
|
|
const cacheScope = useCacheScope()
|
|
useEffect(() => {
|
|
if (!songIds) return
|
|
void queue
|
|
.syncCollection({ kind: "playlist", id }, songIds, async (added) => {
|
|
const songs = await loadPlaybackSongs(
|
|
convex,
|
|
cacheScope,
|
|
added as Id<"songs">[]
|
|
)
|
|
return songs.filter((song) => song !== null)
|
|
})
|
|
.catch(() => {})
|
|
}, [cacheScope, convex, id, queue, songIds])
|
|
}
|
|
|
|
function PlaylistSync({ queue, id }: { queue: DownloadQueue; id: string }) {
|
|
const songIds = useQuery(api.playlists.getPlaylistSongIds, {
|
|
playlistId: id as Id<"playlists">,
|
|
})
|
|
useSyncDownloadedPlaylist(queue, id, songIds)
|
|
return null
|
|
}
|
|
|
|
function FavoritesSync({ queue }: { queue: DownloadQueue }) {
|
|
const favorites = useCachedQuery(api.favorites.getUserFavorites)
|
|
const songIds = useMemo(() => favorites?.favoriteSongs.flat(), [favorites])
|
|
useSyncDownloadedPlaylist(queue, FAVORITES_DOWNLOAD_ID, songIds)
|
|
return null
|
|
}
|
|
|
|
function DownloadSync({ queue }: { queue: DownloadQueue }) {
|
|
useSyncExternalStore(queue.subscribe, queue.getVersion)
|
|
return queue
|
|
.collections()
|
|
.filter((collection) => collection.kind === "playlist")
|
|
.map((collection) =>
|
|
collection.id === FAVORITES_DOWNLOAD_ID ? (
|
|
<FavoritesSync key={collection.id} queue={queue} />
|
|
) : (
|
|
<PlaylistSync key={collection.id} queue={queue} id={collection.id} />
|
|
)
|
|
)
|
|
}
|
|
|
|
export function DownloadsProvider({ children }: { children: ReactNode }) {
|
|
const { config } = useServerConfig()
|
|
const convex = useConvex()
|
|
const cacheScope = useCacheScope()
|
|
const queue = useMemo(
|
|
() => (config ? downloadQueueFor(config) : null),
|
|
[config]
|
|
)
|
|
const [pending, setPending] = useState<{
|
|
target: DownloadTarget
|
|
response: DownloadOptionsResponse
|
|
} | null>(null)
|
|
const keepDownloading = useBackgroundDownloads(queue)
|
|
|
|
useEffect(() => {
|
|
if (!queue) return
|
|
void queue.load().catch(() => {})
|
|
// Reports failed songs once per burst instead of once per song.
|
|
let failed = 0
|
|
let timer: ReturnType<typeof setTimeout> | null = null
|
|
const unsubscribe = queue.onFailure(() => {
|
|
failed += 1
|
|
timer ??= setTimeout(() => {
|
|
showError(
|
|
failed === 1
|
|
? "A song could not be downloaded"
|
|
: `${failed} songs could not be downloaded`
|
|
)
|
|
failed = 0
|
|
timer = null
|
|
}, 1000)
|
|
})
|
|
return () => {
|
|
unsubscribe()
|
|
if (timer) clearTimeout(timer)
|
|
}
|
|
}, [queue])
|
|
|
|
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(
|
|
convex,
|
|
cacheScope,
|
|
target.songIds as Id<"songs">[]
|
|
).catch(() => {})
|
|
const response = await fetchDownloadOptions(config, target.songIds)
|
|
const remembered = await readRememberedDownloadQuality()
|
|
if (remembered) {
|
|
await startDownload(queue, target, response.songs, remembered)
|
|
keepDownloading()
|
|
toast(`Downloading ${target.title}`)
|
|
} else {
|
|
setPending({ target, response })
|
|
}
|
|
} catch (error) {
|
|
showError(error instanceof Error ? error.message : "Download failed")
|
|
}
|
|
},
|
|
[cacheScope, config, convex, keepDownloading, queue]
|
|
)
|
|
|
|
const removeDownload = useCallback(
|
|
async (target: DownloadTarget) => {
|
|
if (!queue) return
|
|
if (target.kind === "songs") {
|
|
await queue.removeSongs(target.songIds, target.from)
|
|
} else await queue.removeCollection(target)
|
|
},
|
|
[queue]
|
|
)
|
|
|
|
const handlePick = useCallback(
|
|
(quality: DownloadQuality, remember: boolean) => {
|
|
if (!pending || !queue) return
|
|
setPending(null)
|
|
if (remember) void writeRememberedDownloadQuality(quality)
|
|
void startDownload(
|
|
queue,
|
|
pending.target,
|
|
pending.response.songs,
|
|
quality
|
|
).then(keepDownloading)
|
|
},
|
|
[keepDownloading, pending, queue]
|
|
)
|
|
|
|
const value = useMemo(
|
|
() => ({ queue, requestDownload, removeDownload }),
|
|
[queue, requestDownload, removeDownload]
|
|
)
|
|
|
|
return (
|
|
<DownloadsContext.Provider value={value}>
|
|
{children}
|
|
{queue ? <DownloadSync queue={queue} /> : null}
|
|
<DownloadQualityPopup
|
|
pending={pending}
|
|
onClose={() => setPending(null)}
|
|
onPick={handlePick}
|
|
/>
|
|
</DownloadsContext.Provider>
|
|
)
|
|
}
|
|
|
|
const styles = StyleSheet.create({
|
|
overlay: {
|
|
flex: 1,
|
|
backgroundColor: "rgba(0,0,0,0.6)",
|
|
justifyContent: "center",
|
|
alignItems: "center",
|
|
padding: 24,
|
|
},
|
|
popup: {
|
|
width: "100%",
|
|
maxWidth: 420,
|
|
borderRadius: 16,
|
|
borderWidth: 1,
|
|
padding: 16,
|
|
},
|
|
title: { fontSize: 18, fontWeight: "700" },
|
|
subtitle: { fontSize: 13, marginBottom: 4 },
|
|
row: {
|
|
flexDirection: "row",
|
|
alignItems: "center",
|
|
gap: 12,
|
|
paddingVertical: 12,
|
|
borderBottomWidth: StyleSheet.hairlineWidth,
|
|
},
|
|
rowText: { flex: 1, minWidth: 0, gap: 2 },
|
|
label: { fontSize: 15, fontWeight: "500" },
|
|
size: { fontSize: 13, fontVariant: ["tabular-nums"] },
|
|
rememberRow: {
|
|
flexDirection: "row",
|
|
alignItems: "center",
|
|
justifyContent: "space-between",
|
|
paddingTop: 12,
|
|
},
|
|
})
|