Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
230 lines
7.4 KiB
TypeScript
230 lines
7.4 KiB
TypeScript
import AsyncStorage from "@react-native-async-storage/async-storage"
|
|
import { Directory, 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)
|
|
}
|
|
|
|
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
|
|
)
|
|
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 path = songDownloadPath(songId, requested, {
|
|
losslessFormat: Platform.OS === "ios" ? "alac" : undefined,
|
|
})
|
|
const file = await File.downloadFileAsync(
|
|
`${config.serverUrl}${path}`,
|
|
partial,
|
|
{ headers: { Cookie: cookieHeader }, signal }
|
|
)
|
|
signal.throwIfAborted()
|
|
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)
|
|
}
|