316 lines
10 KiB
TypeScript
316 lines
10 KiB
TypeScript
import AsyncStorage from "@react-native-async-storage/async-storage"
|
|
import { Directory, DownloadTask, File, Paths } from "expo-file-system"
|
|
import { Platform } from "react-native"
|
|
|
|
import {
|
|
createDownloadQueue,
|
|
type DownloadedCover,
|
|
type DownloadedSong,
|
|
type DownloadIndex,
|
|
type DownloadQueue,
|
|
type DownloadStorage,
|
|
} from "@otunes/convex/client/download-queue"
|
|
import {
|
|
parseDownloadQuality,
|
|
songDownloadPath,
|
|
type DownloadQuality,
|
|
} from "@otunes/convex/download-quality"
|
|
import { getAuthCookieHeader } from "@/lib/auth-cookies"
|
|
import type { ServerConfig } from "@/lib/server-config"
|
|
|
|
const REMEMBERED_QUALITY_KEY = "otunes.download-quality"
|
|
const PARTIAL_SUFFIX = ".partial"
|
|
|
|
const COVERS_FOLDER = "covers"
|
|
const COVER_SIZE = 1024
|
|
|
|
// Each song is a folder named `<songId>.<quality>.<albumId>` holding one audio
|
|
// file, named by the server so it keeps the right extension. Folders end in
|
|
// `.partial` until their download completes. Covers are files named
|
|
// `<kind>-<id>` in the `covers` folder.
|
|
function serverDirectory(config: ServerConfig) {
|
|
const host = config.hostname.replace(/[^a-z0-9.-]/gi, "_")
|
|
return new Directory(Paths.document, "downloads", host)
|
|
}
|
|
|
|
function songFolderName(song: {
|
|
songId: string
|
|
quality: DownloadQuality
|
|
albumId?: string
|
|
}) {
|
|
return [song.songId, song.quality, song.albumId].filter(Boolean).join(".")
|
|
}
|
|
|
|
function parseSongFolder(name: string) {
|
|
const [songId, rawQuality, albumId, ...rest] = name.split(".")
|
|
const quality = parseDownloadQuality(rawQuality)
|
|
if (!songId || !quality || rest.length > 0) return null
|
|
return { songId, quality, albumId: albumId || undefined }
|
|
}
|
|
|
|
function songFolders(root: Directory) {
|
|
if (!root.exists) return []
|
|
return root
|
|
.list()
|
|
.filter(
|
|
(entry): entry is Directory =>
|
|
entry instanceof Directory && entry.name !== COVERS_FOLDER
|
|
)
|
|
}
|
|
|
|
function coverFileName({ kind, id }: DownloadedCover) {
|
|
return `${kind}-${id}`
|
|
}
|
|
|
|
// Saved covers by their server URL, for `downloadedCoverUri`.
|
|
const savedCoverUris = new Map<string, string>()
|
|
|
|
function coverUrl(config: ServerConfig, { kind, id }: DownloadedCover) {
|
|
return `${config.serverUrl}/api/${kind}/${id}/cover`
|
|
}
|
|
|
|
function audioFile(folder: Directory) {
|
|
return folder.list().find((entry): entry is File => entry instanceof File)
|
|
}
|
|
|
|
type SongDownload = {
|
|
url: string
|
|
destination: Directory
|
|
headers: Record<string, string>
|
|
signal: AbortSignal
|
|
/** Checks and keeps the downloaded file, returning its size. */
|
|
finish: (file: File) => number
|
|
}
|
|
|
|
// Whether a continued processing task keeps the app running in the
|
|
// background (iOS 26+, see `useBackgroundDownloads`).
|
|
let keptRunning = false
|
|
const regularSessionDownloads = new Set<() => void>()
|
|
|
|
/**
|
|
* While a continued task keeps the app running, songs download through the
|
|
* regular session: iOS treats background session downloads started from the
|
|
* background as deferrable until Wi-Fi and power. When the task ends, running
|
|
* songs restart in the background session before iOS suspends the app.
|
|
*/
|
|
export function setKeptRunning(running: boolean) {
|
|
keptRunning = running
|
|
if (!running) for (const handOff of regularSessionDownloads) handOff()
|
|
}
|
|
|
|
/**
|
|
* Downloads through an iOS URL session. The background one keeps going while
|
|
* the app is suspended and wakes it when done; iOS keeps the app awake until
|
|
* `finish` returns (up to 25 seconds). Downloads still running when iOS
|
|
* terminates the app are lost.
|
|
*/
|
|
async function runDownloadTask(
|
|
{ url, destination, headers, signal, finish }: SongDownload,
|
|
sessionType: "foreground" | "background"
|
|
) {
|
|
const task = new DownloadTask(url, destination, {
|
|
headers,
|
|
signal,
|
|
sessionType,
|
|
deferBackgroundSessionCompletion: sessionType === "background",
|
|
})
|
|
const handOff = () => task.cancel()
|
|
if (sessionType === "foreground") regularSessionDownloads.add(handOff)
|
|
try {
|
|
const file = await task.downloadAsync()
|
|
if (!file) throw new Error("Download paused")
|
|
return finish(file)
|
|
} finally {
|
|
regularSessionDownloads.delete(handOff)
|
|
if (task.state === "completed") {
|
|
await task.acknowledgeBackgroundCompletionAsync().catch(() => {})
|
|
}
|
|
task.release()
|
|
}
|
|
}
|
|
|
|
async function downloadOnIOS(download: SongDownload) {
|
|
if (keptRunning) {
|
|
try {
|
|
return await runDownloadTask(download, "foreground")
|
|
} catch (error) {
|
|
// Still running means a real failure; otherwise it was handed off.
|
|
if (keptRunning || download.signal.aborted) throw error
|
|
}
|
|
}
|
|
return runDownloadTask(download, "background")
|
|
}
|
|
|
|
/** Android keeps the app running with a foreground service instead. */
|
|
async function downloadInForeground(download: SongDownload) {
|
|
const { url, destination, headers, signal, finish } = download
|
|
return finish(
|
|
await File.downloadFileAsync(url, destination, { headers, signal })
|
|
)
|
|
}
|
|
|
|
function createStorage(config: ServerConfig): DownloadStorage {
|
|
const root = serverDirectory(config)
|
|
const indexFile = new File(root, "index.json")
|
|
const coversFolder = new Directory(root, COVERS_FOLDER)
|
|
|
|
// Remembers the covers saved in earlier launches.
|
|
if (coversFolder.exists) {
|
|
for (const entry of coversFolder.list()) {
|
|
const dash = entry.name.indexOf("-")
|
|
const kind = entry.name.slice(0, dash)
|
|
if (entry instanceof File && (kind === "album" || kind === "playlist")) {
|
|
const cover = { kind, id: entry.name.slice(dash + 1) } as const
|
|
savedCoverUris.set(coverUrl(config, cover), entry.uri)
|
|
}
|
|
}
|
|
}
|
|
|
|
function foldersFor(songIds: ReadonlySet<string>) {
|
|
return songFolders(root).filter((folder) => {
|
|
const name = folder.name.replace(PARTIAL_SUFFIX, "")
|
|
const parsed = parseSongFolder(name)
|
|
return parsed !== null && songIds.has(parsed.songId)
|
|
})
|
|
}
|
|
|
|
return {
|
|
async list() {
|
|
const songs: DownloadedSong[] = []
|
|
for (const folder of songFolders(root)) {
|
|
const parsed = parseSongFolder(folder.name)
|
|
const file = parsed ? audioFile(folder) : undefined
|
|
if (!parsed || !file) {
|
|
// Interrupted downloads from an earlier launch.
|
|
folder.delete()
|
|
continue
|
|
}
|
|
songs.push({ ...parsed, bytes: file.size ?? 0 })
|
|
}
|
|
return songs
|
|
},
|
|
async save({ songId, requested, quality, albumId }, signal) {
|
|
const cookieHeader = await getAuthCookieHeader(
|
|
config.serverUrl,
|
|
config.convexUrl,
|
|
{ refresh: Platform.OS !== "ios" }
|
|
)
|
|
if (!cookieHeader) throw new Error("Sign in to download")
|
|
|
|
root.create({ intermediates: true, idempotent: true })
|
|
const name = songFolderName({ songId, quality, albumId })
|
|
const partial = new Directory(root, `${name}${PARTIAL_SUFFIX}`)
|
|
if (partial.exists) partial.delete()
|
|
partial.create()
|
|
try {
|
|
const url = `${config.serverUrl}${songDownloadPath(songId, requested, {
|
|
losslessFormat: Platform.OS === "ios" ? "alac" : undefined,
|
|
})}`
|
|
const download =
|
|
Platform.OS === "ios" ? downloadOnIOS : downloadInForeground
|
|
return await download({
|
|
url,
|
|
destination: partial,
|
|
headers: { Cookie: cookieHeader },
|
|
signal,
|
|
finish(file) {
|
|
signal.throwIfAborted()
|
|
// A lapsed sign-in redirects to the sign-in page instead of failing.
|
|
if (file.extension === ".html") {
|
|
throw new Error("Sign in to download")
|
|
}
|
|
partial.rename(name)
|
|
return file.size ?? 0
|
|
},
|
|
})
|
|
} catch (error) {
|
|
if (partial.exists) partial.delete()
|
|
throw error
|
|
}
|
|
},
|
|
async saveCover(cover) {
|
|
const file = new File(coversFolder, coverFileName(cover))
|
|
if (file.exists) return
|
|
coversFolder.create({ intermediates: true, idempotent: true })
|
|
const url = coverUrl(config, cover)
|
|
await File.downloadFileAsync(`${url}?size=${COVER_SIZE}`, file)
|
|
savedCoverUris.set(url, file.uri)
|
|
},
|
|
async pruneCovers(keep) {
|
|
if (!coversFolder.exists) return
|
|
const kept = new Set(keep.map(coverFileName))
|
|
for (const entry of coversFolder.list()) {
|
|
if (kept.has(entry.name)) continue
|
|
entry.delete()
|
|
for (const [url, uri] of savedCoverUris) {
|
|
if (uri === entry.uri) savedCoverUris.delete(url)
|
|
}
|
|
}
|
|
},
|
|
async readIndex() {
|
|
if (indexFile.exists) {
|
|
try {
|
|
return JSON.parse(await indexFile.text()) as DownloadIndex
|
|
} catch {
|
|
// An unreadable index starts empty.
|
|
}
|
|
}
|
|
return { collections: [], otherSongIds: [] }
|
|
},
|
|
async writeIndex(index) {
|
|
root.create({ intermediates: true, idempotent: true })
|
|
if (!indexFile.exists) indexFile.create()
|
|
await indexFile.write(JSON.stringify(index))
|
|
},
|
|
async remove(songIds) {
|
|
for (const folder of foldersFor(new Set(songIds))) folder.delete()
|
|
},
|
|
}
|
|
}
|
|
|
|
const queues = new Map<string, DownloadQueue>()
|
|
|
|
/** Downloads are kept per server, since song IDs only mean something there. */
|
|
export function downloadQueueFor(config: ServerConfig) {
|
|
let queue = queues.get(config.hostname)
|
|
if (!queue) {
|
|
queue = createDownloadQueue(createStorage(config))
|
|
queues.set(config.hostname, queue)
|
|
}
|
|
return queue
|
|
}
|
|
|
|
/** The local file for a downloaded song, for the player to use offline. */
|
|
export function downloadedAudioUri(config: ServerConfig, songId: string) {
|
|
const song = downloadQueueFor(config).getDownloaded(songId)
|
|
if (!song) return null
|
|
const folder = new Directory(serverDirectory(config), songFolderName(song))
|
|
return folder.exists ? (audioFile(folder)?.uri ?? null) : null
|
|
}
|
|
|
|
/**
|
|
* The saved copy of a cover URL (`albumCoverUrl` or `playlistCoverUrl`,
|
|
* without size), for showing while the network copy loads or fails.
|
|
*/
|
|
export function downloadedCoverUri(url: string) {
|
|
return savedCoverUris.get(url.split("?")[0]) ?? null
|
|
}
|
|
|
|
export async function readRememberedDownloadQuality() {
|
|
try {
|
|
return parseDownloadQuality(
|
|
await AsyncStorage.getItem(REMEMBERED_QUALITY_KEY)
|
|
)
|
|
} catch {
|
|
return undefined
|
|
}
|
|
}
|
|
|
|
/** Pass undefined to ask every time again. */
|
|
export async function writeRememberedDownloadQuality(
|
|
quality: DownloadQuality | undefined
|
|
) {
|
|
if (quality) await AsyncStorage.setItem(REMEMBERED_QUALITY_KEY, quality)
|
|
else await AsyncStorage.removeItem(REMEMBERED_QUALITY_KEY)
|
|
}
|