- A web app manifest with the name, the colours, the display mode and the icons (also a maskable one), so a browser offers to install it; Settings has an Install button where the browser lets the page ask. - A service worker keeps the files of the app (the page, its scripts and styles, the manifest and the icons) so it opens at once, and shows its own page when the server cannot be reached. It never touches /api/: nothing from the API is kept, answered from a cache, or asked for by the worker. Files that failed, and anything that is not a file of the app, are not kept; the scripts it keeps are capped. - A new version waits until the page says it may take over: a line says a new version is ready and its button reloads the page after the new worker took over. - The server gives the manifest its type (application/manifest+json); the worker and the manifest are asked again every time, and the policy of the page needs no change.
121 lines
5 KiB
JavaScript
121 lines
5 KiB
JavaScript
// The service worker of Sonda.
|
|
//
|
|
// It keeps the files of the app (the page, its scripts and styles, the manifest and the icons) so that the app opens at
|
|
// once and, when the server cannot be reached, shows the page of the app instead of an error of the browser.
|
|
//
|
|
// It never touches the API. What comes from /api/ is private (the catalog, the covers, the songs, what a person did, and
|
|
// the address of a song carries the session): it is not kept, not answered from a cache, and not even asked for by the
|
|
// worker; the browser does it as if the worker were not there.
|
|
//
|
|
// A new version of the worker waits until the page tells it to take over (the page shows "a new version is ready" and
|
|
// a button), so that nobody is switched to new files in the middle of a song.
|
|
|
|
const VERSION = 'v1'
|
|
const CACHE = `sonda-shell-${VERSION}`
|
|
const PREFIX = 'sonda-shell-'
|
|
// How many files under /assets/ are kept. The scripts and styles have a hash in their name, so a new build brings
|
|
// new names: the oldest go, the page and its icons stay.
|
|
const MAX_ASSETS = 120
|
|
const KEPT = ['/', '/manifest.webmanifest', '/favicon.svg', '/icon-192.png', '/icon-512.png', '/icon-maskable-512.png', '/apple-touch-icon.png']
|
|
const OFFLINE =
|
|
'<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +
|
|
'<title>Sonda</title><body style="font-family:system-ui,sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem;line-height:1.5">' +
|
|
'<h1>Sonda</h1><p>The server cannot be reached, and this page was not kept on this device yet.</p>' +
|
|
'<p>Open Sonda once while you are connected to it, and the app will open from then on even when the server is far.</p></body></html>'
|
|
|
|
const isAsset = (url) => url.pathname.startsWith('/assets/')
|
|
|
|
/** Keeps the page and what it names under /assets/. */
|
|
async function keepShell() {
|
|
const cache = await caches.open(CACHE)
|
|
// The page is asked again from the server, not from the cache of the browser.
|
|
const page = await fetch('/', { cache: 'reload' })
|
|
if (page.ok) {
|
|
await cache.put('/', page.clone())
|
|
const html = await page.text()
|
|
const names = [...html.matchAll(/(?:src|href)="(\/assets\/[^"]+)"/g)].map((m) => m[1])
|
|
await Promise.all(
|
|
names.concat(KEPT.slice(1)).map(async (name) => {
|
|
try {
|
|
const res = await fetch(name)
|
|
if (res.ok) await cache.put(name, res)
|
|
} catch {
|
|
// A file that cannot be had now is simply not kept: the app still works online.
|
|
}
|
|
}),
|
|
)
|
|
}
|
|
}
|
|
|
|
/** Takes the oldest files of /assets/ out when there are more than MAX_ASSETS. */
|
|
async function trim(cache) {
|
|
const assets = (await cache.keys()).filter((r) => isAsset(new URL(r.url)))
|
|
for (const r of assets.slice(0, Math.max(0, assets.length - MAX_ASSETS))) await cache.delete(r)
|
|
}
|
|
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(keepShell())
|
|
})
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
(async () => {
|
|
for (const name of await caches.keys()) {
|
|
if (name.startsWith(PREFIX) && name !== CACHE) await caches.delete(name)
|
|
}
|
|
await self.clients.claim()
|
|
})(),
|
|
)
|
|
})
|
|
|
|
self.addEventListener('message', (event) => {
|
|
if (event.data && event.data.type === 'SKIP_WAITING') self.skipWaiting()
|
|
})
|
|
|
|
/** A link inside the app: the server first, so that an update shows at once, and the kept page when it cannot be reached. */
|
|
async function page(request) {
|
|
try {
|
|
const res = await fetch(request)
|
|
if (res.ok) (await caches.open(CACHE)).put('/', res.clone())
|
|
return res
|
|
} catch {
|
|
const kept = await (await caches.open(CACHE)).match('/')
|
|
return kept || new Response(OFFLINE, { status: 503, headers: { 'Content-Type': 'text/html; charset=utf-8' } })
|
|
}
|
|
}
|
|
|
|
/** A script or a style: the one that is kept, else from the server, and kept. Its name has a hash, so it never changes. */
|
|
async function asset(request) {
|
|
const cache = await caches.open(CACHE)
|
|
const hit = await cache.match(request)
|
|
if (hit) return hit
|
|
const res = await fetch(request)
|
|
if (res.ok) {
|
|
await cache.put(request, res.clone())
|
|
await trim(cache)
|
|
}
|
|
return res
|
|
}
|
|
|
|
/** An icon or the manifest: the server first, and the kept one when it cannot be reached. Nothing new is kept. */
|
|
async function other(request) {
|
|
try {
|
|
return await fetch(request)
|
|
} catch (err) {
|
|
const kept = await (await caches.open(CACHE)).match(request)
|
|
if (kept) return kept
|
|
throw err
|
|
}
|
|
}
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const request = event.request
|
|
const url = new URL(request.url)
|
|
// Not its business: anything but a GET to its own server, a song being read in pieces, and the whole API.
|
|
if (request.method !== 'GET' || url.origin !== self.location.origin || request.headers.has('range')) return
|
|
if (url.pathname === '/api' || url.pathname.startsWith('/api/')) return
|
|
|
|
if (request.mode === 'navigate') event.respondWith(page(request))
|
|
else if (isAsset(url)) event.respondWith(asset(request))
|
|
else event.respondWith(other(request))
|
|
})
|