339 lines
10 KiB
TypeScript
339 lines
10 KiB
TypeScript
"use client"
|
|
|
|
import * as React from "react"
|
|
import { useConvex, useQuery } from "convex/react"
|
|
import { toast } from "sonner"
|
|
|
|
import { AudioFormatBadge } from "@/components/audio-format-badge"
|
|
import { Button } from "@/components/ui/button"
|
|
import { Checkbox } from "@/components/ui/checkbox"
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/components/ui/dialog"
|
|
import { Label } from "@/components/ui/label"
|
|
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
|
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
|
import { useDownloadsVersion } from "@/hooks/use-downloads"
|
|
import {
|
|
downloadQueue,
|
|
readRememberedDownloadQuality,
|
|
registerDownloadsServiceWorker,
|
|
requestPersistentStorage,
|
|
writeRememberedDownloadQuality,
|
|
} from "@/lib/downloads"
|
|
import { api } from "@otunes/convex/_generated/api"
|
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
|
import type {
|
|
CollectionRef,
|
|
DownloadableSong,
|
|
DownloadSource,
|
|
} from "@otunes/convex/client/download-queue"
|
|
import { FAVORITES_ID } from "@otunes/convex/client/download-queue"
|
|
import {
|
|
DOWNLOAD_OPTIONS_PATH,
|
|
DOWNLOAD_QUALITY_DETAILS,
|
|
DOWNLOAD_QUALITY_LABELS,
|
|
formatBytes,
|
|
type DownloadOptionsResponse,
|
|
type DownloadQuality,
|
|
type SizedDownloadOption,
|
|
} from "@otunes/convex/download-quality"
|
|
|
|
/** Songs on their own, or an album or playlist that stays downloaded as a whole. */
|
|
export type DownloadTarget =
|
|
| {
|
|
kind: "songs"
|
|
songIds: string[]
|
|
title: string
|
|
/** Removing takes the songs out of only this download. */
|
|
from?: DownloadSource
|
|
}
|
|
| (CollectionRef & { title: string; songIds: string[] })
|
|
|
|
/** The Favorites playlist has no ID, so downloads use this one. */
|
|
export const FAVORITES_DOWNLOAD_ID = FAVORITES_ID
|
|
|
|
type DownloadsContextValue = {
|
|
/** Asks for a quality (unless remembered) and starts downloading. */
|
|
requestDownload: (target: DownloadTarget) => Promise<void>
|
|
removeDownload: (target: DownloadTarget) => Promise<void>
|
|
}
|
|
|
|
const DownloadsContext = React.createContext<DownloadsContextValue | null>(null)
|
|
|
|
export function useDownloads() {
|
|
const context = React.useContext(DownloadsContext)
|
|
if (!context) {
|
|
throw new Error("useDownloads must be used within DownloadsProvider")
|
|
}
|
|
return context
|
|
}
|
|
|
|
async function fetchDownloadOptions(songIds: string[]) {
|
|
const response = await fetch(DOWNLOAD_OPTIONS_PATH, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ songIds }),
|
|
})
|
|
if (!response.ok) {
|
|
throw new Error("Could not reach the server to download")
|
|
}
|
|
return (await response.json()) as DownloadOptionsResponse
|
|
}
|
|
|
|
function startDownload(
|
|
target: DownloadTarget,
|
|
songs: DownloadableSong[],
|
|
quality: DownloadQuality
|
|
) {
|
|
requestPersistentStorage()
|
|
if (target.kind === "songs") {
|
|
return downloadQueue.enqueue(songs, quality)
|
|
}
|
|
return downloadQueue.downloadCollection(
|
|
{ kind: target.kind, id: target.id, title: target.title, quality },
|
|
songs
|
|
)
|
|
}
|
|
|
|
function optionDetail(option: SizedDownloadOption, songCount: number) {
|
|
if (option.fallbackCount === 0) {
|
|
return DOWNLOAD_QUALITY_DETAILS[option.quality]
|
|
}
|
|
const included = songCount - option.fallbackCount
|
|
return `${included} of ${songCount} songs, ${option.fallbackCount} in High`
|
|
}
|
|
|
|
function QualityLabel({ quality }: { quality: DownloadQuality }) {
|
|
if (quality === "lossless" || quality === "atmos") {
|
|
return (
|
|
<AudioFormatBadge format={quality} backgroundColor="var(--popover)" />
|
|
)
|
|
}
|
|
return (
|
|
<span className="text-[13px] font-medium">
|
|
{DOWNLOAD_QUALITY_LABELS[quality]}
|
|
</span>
|
|
)
|
|
}
|
|
|
|
function DownloadQualityDialog({
|
|
pending,
|
|
onClose,
|
|
}: {
|
|
pending: { target: DownloadTarget; response: DownloadOptionsResponse } | null
|
|
onClose: () => void
|
|
}) {
|
|
const [quality, setQuality] = React.useState<DownloadQuality>("high")
|
|
const [remember, setRemember] = React.useState(false)
|
|
const options = pending?.response.options ?? []
|
|
const songCount = pending?.response.songs.length ?? 0
|
|
|
|
async function handleDownload() {
|
|
if (!pending) return
|
|
if (remember) writeRememberedDownloadQuality(quality)
|
|
onClose()
|
|
await startDownload(pending.target, pending.response.songs, quality)
|
|
}
|
|
|
|
return (
|
|
<Dialog open={pending !== null} onOpenChange={(open) => !open && onClose()}>
|
|
<DialogContent className="gap-3 sm:max-w-sm">
|
|
<DialogHeader>
|
|
<DialogTitle className="truncate">
|
|
Download “{pending?.target.title}”
|
|
</DialogTitle>
|
|
</DialogHeader>
|
|
<RadioGroup
|
|
value={quality}
|
|
onValueChange={(value) => setQuality(value as DownloadQuality)}
|
|
className="gap-0"
|
|
>
|
|
{options.map((option) => (
|
|
<Label
|
|
key={option.quality}
|
|
htmlFor={`download-${option.quality}`}
|
|
className="grid cursor-pointer grid-cols-[auto_1fr_auto] items-center gap-3 rounded-md px-1 py-2 font-normal has-data-[state=checked]:bg-muted"
|
|
>
|
|
<RadioGroupItem
|
|
value={option.quality}
|
|
id={`download-${option.quality}`}
|
|
/>
|
|
<span className="flex min-w-0 flex-col gap-0.5">
|
|
<QualityLabel quality={option.quality} />
|
|
<span className="text-xs text-muted-foreground">
|
|
{optionDetail(option, songCount)}
|
|
</span>
|
|
</span>
|
|
<span className="text-xs text-muted-foreground tabular-nums">
|
|
{option.estimated ? "~" : ""}
|
|
{formatBytes(option.bytes)}
|
|
</span>
|
|
</Label>
|
|
))}
|
|
</RadioGroup>
|
|
<div className="flex items-center gap-2">
|
|
<Checkbox
|
|
id="download-remember"
|
|
checked={remember}
|
|
onCheckedChange={(checked) => setRemember(checked === true)}
|
|
/>
|
|
<Label htmlFor="download-remember" className="font-normal">
|
|
Remember my choice
|
|
</Label>
|
|
</div>
|
|
<DialogFooter>
|
|
<Button variant="ghost" onClick={onClose}>
|
|
Cancel
|
|
</Button>
|
|
<Button onClick={() => void handleDownload()}>Download</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|
|
|
|
const SYNC_BATCH_SIZE = 200
|
|
|
|
/** Keeps a downloaded playlist's songs in step with the playlist. */
|
|
function useSyncDownloadedPlaylist(
|
|
id: string,
|
|
songIds: readonly string[] | undefined
|
|
) {
|
|
const convex = useConvex()
|
|
React.useEffect(() => {
|
|
if (!songIds) return
|
|
void downloadQueue
|
|
.syncCollection({ kind: "playlist", id }, songIds, async (added) => {
|
|
const songs: DownloadableSong[] = []
|
|
for (let start = 0; start < added.length; start += SYNC_BATCH_SIZE) {
|
|
const batch = await convex.query(api.library.getSongsForPlayback, {
|
|
ids: added.slice(start, start + SYNC_BATCH_SIZE) as Id<"songs">[],
|
|
})
|
|
for (const song of batch) if (song) songs.push(song)
|
|
}
|
|
return songs
|
|
})
|
|
.catch(() => {})
|
|
}, [convex, id, songIds])
|
|
}
|
|
|
|
function PlaylistSync({ id }: { id: string }) {
|
|
const songIds = useQuery(api.playlists.getPlaylistSongIds, {
|
|
playlistId: id as Id<"playlists">,
|
|
})
|
|
useSyncDownloadedPlaylist(id, songIds)
|
|
return null
|
|
}
|
|
|
|
function FavoritesSync() {
|
|
const favorites = useCachedQuery(api.favorites.getUserFavorites)
|
|
const songIds = React.useMemo(
|
|
() => favorites?.favoriteSongs.flat(),
|
|
[favorites]
|
|
)
|
|
useSyncDownloadedPlaylist(FAVORITES_DOWNLOAD_ID, songIds)
|
|
return null
|
|
}
|
|
|
|
function DownloadSync() {
|
|
useDownloadsVersion()
|
|
return downloadQueue
|
|
.collections()
|
|
.filter((collection) => collection.kind === "playlist")
|
|
.map((collection) =>
|
|
collection.id === FAVORITES_DOWNLOAD_ID ? (
|
|
<FavoritesSync key={collection.id} />
|
|
) : (
|
|
<PlaylistSync key={collection.id} id={collection.id} />
|
|
)
|
|
)
|
|
}
|
|
|
|
/** Reports failed songs once per burst instead of once per song. */
|
|
function useFailureToasts() {
|
|
React.useEffect(() => {
|
|
let failed = 0
|
|
let timer: ReturnType<typeof setTimeout> | null = null
|
|
const unsubscribe = downloadQueue.onFailure(() => {
|
|
failed += 1
|
|
timer ??= setTimeout(() => {
|
|
toast.error(
|
|
failed === 1
|
|
? "A song could not be downloaded"
|
|
: `${failed} songs could not be downloaded`
|
|
)
|
|
failed = 0
|
|
timer = null
|
|
}, 1000)
|
|
})
|
|
return () => {
|
|
unsubscribe()
|
|
if (timer) clearTimeout(timer)
|
|
}
|
|
}, [])
|
|
}
|
|
|
|
export function DownloadsProvider({ children }: { children: React.ReactNode }) {
|
|
const [pending, setPending] = React.useState<{
|
|
target: DownloadTarget
|
|
response: DownloadOptionsResponse
|
|
} | null>(null)
|
|
|
|
useFailureToasts()
|
|
React.useEffect(() => {
|
|
void downloadQueue.load().catch(() => {})
|
|
registerDownloadsServiceWorker()
|
|
}, [])
|
|
|
|
const requestDownload = React.useCallback(async (target: DownloadTarget) => {
|
|
if (target.songIds.length === 0) return
|
|
if (target.songIds.every((id) => downloadQueue.getDownloaded(id))) {
|
|
// Already on this device: just give them back to their downloads.
|
|
await downloadQueue.enqueue(
|
|
target.songIds.map((id) => ({ id, files: {} })),
|
|
"high"
|
|
)
|
|
return
|
|
}
|
|
try {
|
|
const response = await fetchDownloadOptions(target.songIds)
|
|
const remembered = readRememberedDownloadQuality()
|
|
if (remembered) {
|
|
await startDownload(target, response.songs, remembered)
|
|
toast(`Downloading ${target.title}`)
|
|
} else {
|
|
setPending({ target, response })
|
|
}
|
|
} catch (error) {
|
|
toast.error(error instanceof Error ? error.message : "Download failed")
|
|
}
|
|
}, [])
|
|
|
|
const removeDownload = React.useCallback(async (target: DownloadTarget) => {
|
|
if (target.kind === "songs") {
|
|
await downloadQueue.removeSongs(target.songIds, target.from)
|
|
} else await downloadQueue.removeCollection(target)
|
|
}, [])
|
|
|
|
const value = React.useMemo(
|
|
() => ({ requestDownload, removeDownload }),
|
|
[requestDownload, removeDownload]
|
|
)
|
|
|
|
return (
|
|
<DownloadsContext.Provider value={value}>
|
|
{children}
|
|
<DownloadSync />
|
|
<DownloadQualityDialog
|
|
pending={pending}
|
|
onClose={() => setPending(null)}
|
|
/>
|
|
</DownloadsContext.Provider>
|
|
)
|
|
}
|