201 lines
6.0 KiB
TypeScript
201 lines
6.0 KiB
TypeScript
import {
|
|
createDownloadQueue,
|
|
type DownloadedCover,
|
|
type DownloadedSong,
|
|
type DownloadIndex,
|
|
type DownloadStorage,
|
|
} from "@otunes/convex/client/download-queue"
|
|
import {
|
|
parseDownloadQuality,
|
|
songDownloadPath,
|
|
type DownloadQuality,
|
|
} from "@otunes/convex/download-quality"
|
|
|
|
// Like YouTube Music on the web, downloads live in this browser's IndexedDB
|
|
// and only play inside the app. Clearing site data removes them.
|
|
const DB_NAME = "otunes-downloads"
|
|
const AUDIO_STORE = "audio"
|
|
const SONG_STORE = "songs"
|
|
const REMEMBERED_QUALITY_KEY = "otunes:download-quality"
|
|
const INDEX_KEY = "otunes:download-index"
|
|
|
|
// Covers live in Cache Storage under their unsized path. The service worker
|
|
// (public/downloads-sw.js) serves them only when the network fails, so
|
|
// online browsing and new playlist artwork are unaffected.
|
|
const COVER_CACHE = "otunes-download-covers"
|
|
const COVER_SIZE = 512
|
|
|
|
function coverPath({ kind, id }: DownloadedCover) {
|
|
return `/api/${kind}/${id}/cover`
|
|
}
|
|
|
|
/** Lets downloaded covers show offline. */
|
|
export function registerDownloadsServiceWorker() {
|
|
void navigator.serviceWorker
|
|
?.register("/downloads-sw.js", { scope: "/" })
|
|
.catch(() => {})
|
|
}
|
|
|
|
let database: Promise<IDBDatabase> | null = null
|
|
|
|
function openDatabase() {
|
|
database ??= new Promise<IDBDatabase>((resolve, reject) => {
|
|
const request = indexedDB.open(DB_NAME, 1)
|
|
request.onupgradeneeded = () => {
|
|
request.result.createObjectStore(AUDIO_STORE)
|
|
request.result.createObjectStore(SONG_STORE, { keyPath: "songId" })
|
|
}
|
|
request.onsuccess = () => resolve(request.result)
|
|
request.onerror = () => {
|
|
database = null
|
|
reject(request.error)
|
|
}
|
|
})
|
|
return database
|
|
}
|
|
|
|
async function transaction(
|
|
mode: IDBTransactionMode,
|
|
run: (audio: IDBObjectStore, songs: IDBObjectStore) => void
|
|
) {
|
|
const db = await openDatabase()
|
|
await new Promise<void>((resolve, reject) => {
|
|
const tx = db.transaction([AUDIO_STORE, SONG_STORE], mode)
|
|
run(tx.objectStore(AUDIO_STORE), tx.objectStore(SONG_STORE))
|
|
tx.oncomplete = () => resolve()
|
|
tx.onerror = () => reject(tx.error)
|
|
tx.onabort = () => reject(tx.error)
|
|
})
|
|
}
|
|
|
|
function readRequest<T>(store: IDBObjectStore, key?: string) {
|
|
return new Promise<T>((resolve, reject) => {
|
|
const request = key === undefined ? store.getAll() : store.get(key)
|
|
request.onsuccess = () => resolve(request.result as T)
|
|
request.onerror = () => reject(request.error)
|
|
})
|
|
}
|
|
|
|
const storage: DownloadStorage = {
|
|
async list() {
|
|
const db = await openDatabase()
|
|
return readRequest<DownloadedSong[]>(
|
|
db.transaction(SONG_STORE).objectStore(SONG_STORE)
|
|
)
|
|
},
|
|
async save({ songId, requested, quality, albumId }, signal) {
|
|
const response = await fetch(songDownloadPath(songId, requested), {
|
|
signal,
|
|
})
|
|
if (!response.ok) {
|
|
throw new Error(`Download failed with ${response.status}`)
|
|
}
|
|
const blob = await response.blob()
|
|
signal.throwIfAborted()
|
|
const entry: DownloadedSong = { songId, quality, bytes: blob.size, albumId }
|
|
await transaction("readwrite", (audio, songs) => {
|
|
audio.put(blob, songId)
|
|
songs.put(entry)
|
|
})
|
|
return blob.size
|
|
},
|
|
async saveCover(cover) {
|
|
const cache = await caches.open(COVER_CACHE)
|
|
const key = coverPath(cover)
|
|
if (await cache.match(key)) return
|
|
const response = await fetch(`${key}?size=${COVER_SIZE}`)
|
|
if (!response.ok) throw new Error(`Cover failed with ${response.status}`)
|
|
await cache.put(key, response)
|
|
},
|
|
async pruneCovers(keep) {
|
|
const cache = await caches.open(COVER_CACHE)
|
|
const kept = new Set(keep.map(coverPath))
|
|
for (const request of await cache.keys()) {
|
|
if (!kept.has(new URL(request.url).pathname)) await cache.delete(request)
|
|
}
|
|
},
|
|
async readIndex() {
|
|
try {
|
|
const raw = localStorage.getItem(INDEX_KEY)
|
|
if (raw) return JSON.parse(raw) as DownloadIndex
|
|
} catch {
|
|
// A missing or unreadable index starts empty.
|
|
}
|
|
return { collections: [], otherSongIds: [] }
|
|
},
|
|
async writeIndex(index) {
|
|
localStorage.setItem(INDEX_KEY, JSON.stringify(index))
|
|
},
|
|
async remove(songIds) {
|
|
if (songIds.length === 0) return
|
|
for (const songId of songIds) revokeAudioUrl(songId)
|
|
await transaction("readwrite", (audio, songs) => {
|
|
for (const songId of songIds) {
|
|
audio.delete(songId)
|
|
songs.delete(songId)
|
|
}
|
|
})
|
|
},
|
|
}
|
|
|
|
export const downloadQueue = createDownloadQueue(storage)
|
|
|
|
/** Asks the browser not to evict downloads when storage runs low. */
|
|
export function requestPersistentStorage() {
|
|
void navigator.storage?.persist?.().catch(() => false)
|
|
}
|
|
|
|
// Object URLs keep blobs alive, so only the few in use (playing and preloaded) stay open.
|
|
const MAX_AUDIO_URLS = 3
|
|
const audioUrls = new Map<string, string>()
|
|
|
|
function revokeAudioUrl(songId: string) {
|
|
const url = audioUrls.get(songId)
|
|
if (url) {
|
|
URL.revokeObjectURL(url)
|
|
audioUrls.delete(songId)
|
|
}
|
|
}
|
|
|
|
/** A playable URL for a downloaded song, or null when it is not downloaded. */
|
|
export async function downloadedAudioUrl(songId: string) {
|
|
const existing = audioUrls.get(songId)
|
|
if (existing) {
|
|
audioUrls.delete(songId)
|
|
audioUrls.set(songId, existing)
|
|
return existing
|
|
}
|
|
const db = await openDatabase()
|
|
const blob = await readRequest<Blob | undefined>(
|
|
db.transaction(AUDIO_STORE).objectStore(AUDIO_STORE),
|
|
songId
|
|
)
|
|
if (!blob) return null
|
|
const url = URL.createObjectURL(blob)
|
|
audioUrls.set(songId, url)
|
|
while (audioUrls.size > MAX_AUDIO_URLS) {
|
|
revokeAudioUrl(audioUrls.keys().next().value!)
|
|
}
|
|
return url
|
|
}
|
|
|
|
export function readRememberedDownloadQuality() {
|
|
try {
|
|
return parseDownloadQuality(localStorage.getItem(REMEMBERED_QUALITY_KEY))
|
|
} catch {
|
|
return undefined
|
|
}
|
|
}
|
|
|
|
/** Pass undefined to ask every time again. */
|
|
export function writeRememberedDownloadQuality(
|
|
quality: DownloadQuality | undefined
|
|
) {
|
|
try {
|
|
if (quality) localStorage.setItem(REMEMBERED_QUALITY_KEY, quality)
|
|
else localStorage.removeItem(REMEMBERED_QUALITY_KEY)
|
|
} catch {
|
|
// Without storage the prompt simply shows every time.
|
|
}
|
|
}
|