Files
otunes/apps/web/lib/downloads.ts
T

246 lines
7.6 KiB
TypeScript

import {
createDownloadQueue,
FAVORITES_ID,
type DownloadedCollection,
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`
}
export const DOWNLOADS_PATH = "/library/downloads"
export const OTHER_DOWNLOADS_PATH = "/library/downloads/other"
/** Search param marking album and playlist pages opened from Downloads. */
export const FROM_DOWNLOADS_PARAM = "from=downloads"
export function downloadedCollectionPath({ kind, id }: DownloadedCollection) {
if (kind === "album") return `/album/${id}?${FROM_DOWNLOADS_PARAM}`
if (id === FAVORITES_ID) return `/playlist/favorites?${FROM_DOWNLOADS_PARAM}`
return `/playlist/${id}?${FROM_DOWNLOADS_PARAM}`
}
// Saved pages are specific to the signed-in user (public/downloads-sw.js).
const OFFLINE_PAGE_CACHE = "otunes-offline-pages"
/**
* Lets downloaded covers show offline. In production builds the worker also
* keeps pages and app code so the app opens offline.
*/
export function registerDownloadsServiceWorker() {
const url =
process.env.NODE_ENV === "production"
? "/downloads-sw.js?offline-app"
: "/downloads-sw.js"
void navigator.serviceWorker?.register(url, { scope: "/" }).catch(() => {})
}
/**
* Saves the Downloads pages and every downloaded album and playlist page, so
* they open even after a reload or launch without a connection.
*/
export function saveDownloadPagesForOffline(paths: string[]) {
void navigator.serviceWorker?.ready
.then((registration) =>
registration.active?.postMessage({ type: "save-pages", paths })
)
.catch(() => {})
}
/** Forgets saved pages, on sign-out. */
export async function clearOfflinePages() {
await globalThis.caches?.delete(OFFLINE_PAGE_CACHE).catch(() => false)
}
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 blob = await downloadedAudioBlob(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
}
/** A downloaded song's audio file, or null when it is not downloaded. */
export async function downloadedAudioBlob(songId: string) {
const db = await openDatabase()
const blob = await readRequest<Blob | undefined>(
db.transaction(AUDIO_STORE).objectStore(AUDIO_STORE),
songId
)
return blob ?? null
}
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.
}
}