43 lines
1.4 KiB
JavaScript
43 lines
1.4 KiB
JavaScript
// Serves covers of downloaded music when the network fails, so they show
|
|
// offline. Everything else, and every request that succeeds online, passes
|
|
// through untouched. Covers are saved by lib/downloads.ts.
|
|
const COVER_CACHE = "otunes-download-covers"
|
|
const COVER_PATH = /^\/api\/(album|playlist)\/[^/]+\/cover$/
|
|
|
|
self.addEventListener("install", () => self.skipWaiting())
|
|
self.addEventListener("activate", (event) =>
|
|
event.waitUntil(self.clients.claim())
|
|
)
|
|
|
|
/** The saved cover's key for a cover request, also through `/_next/image`. */
|
|
function coverKey(url) {
|
|
if (url.origin !== self.location.origin) return null
|
|
if (url.pathname === "/_next/image") {
|
|
const inner = url.searchParams.get("url")
|
|
return inner ? coverKey(new URL(inner, self.location.origin)) : null
|
|
}
|
|
return COVER_PATH.test(url.pathname) ? url.pathname : null
|
|
}
|
|
|
|
async function savedCover(key) {
|
|
const cache = await caches.open(COVER_CACHE)
|
|
return cache.match(key)
|
|
}
|
|
|
|
self.addEventListener("fetch", (event) => {
|
|
if (event.request.method !== "GET") return
|
|
const key = coverKey(new URL(event.request.url))
|
|
if (!key) return
|
|
event.respondWith(
|
|
fetch(event.request).then(
|
|
async (response) =>
|
|
response.ok ? response : ((await savedCover(key)) ?? response),
|
|
async (error) => {
|
|
const saved = await savedCover(key)
|
|
if (saved) return saved
|
|
throw error
|
|
}
|
|
)
|
|
)
|
|
})
|