259 lines
7.5 KiB
JavaScript
259 lines
7.5 KiB
JavaScript
/*
|
||
* CMBNet Service Worker
|
||
*
|
||
* Wird an der App-Wurzel ausgeliefert (z. B. /sw.js oder /cmbnet/sw.js),
|
||
* damit er sowohl die mobilen Views als auch die statischen Assets
|
||
* kontrolliert. Der Cache-Name wird pro App-Wurzel gebildet.
|
||
*/
|
||
const VERSION = 'cmbnet-pwa-v12';
|
||
const BASE = new URL('./', self.location).href;
|
||
const SHELL_CACHE = `${VERSION}-shell`;
|
||
const TILE_CACHE = `${VERSION}-tiles`;
|
||
const MAX_TILES = 400;
|
||
|
||
const PRECACHE_PATHS = [
|
||
'static/css/pico.min.css',
|
||
'static/css/leaflet.css',
|
||
'static/css/style.css',
|
||
'static/css/admin.css',
|
||
'static/css/mobile.css',
|
||
'static/js/leaflet.js',
|
||
'static/js/str2pl.js',
|
||
'static/js/reload_notice.js',
|
||
'static/js/views/mobile.js',
|
||
'static/img/logo.png',
|
||
'static/img/icon-192.png',
|
||
'static/img/icon-512.png',
|
||
'static/img/apple-touch-icon.png',
|
||
'favicon.ico'
|
||
];
|
||
|
||
const PRECACHE_URLS = PRECACHE_PATHS.map(path => new URL(path, BASE).href);
|
||
|
||
const TILE_HOSTS = new Set([
|
||
'tile.openstreetmap.org',
|
||
'a.tile.openstreetmap.org',
|
||
'b.tile.openstreetmap.org',
|
||
'c.tile.openstreetmap.org',
|
||
'server.arcgisonline.com',
|
||
'services.arcgisonline.com'
|
||
]);
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Installation und Aktivierung */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
self.addEventListener('install', event => {
|
||
event.waitUntil((async () => {
|
||
const cache = await caches.open(SHELL_CACHE);
|
||
await Promise.allSettled(
|
||
PRECACHE_URLS.map(async url => {
|
||
try {
|
||
const response = await fetch(new Request(url, {cache: 'reload'}));
|
||
if (response && (response.ok || response.type === 'opaque')) {
|
||
await cache.put(url, response);
|
||
}
|
||
} catch (error) {
|
||
// Einzelne fehlende Assets dürfen die Installation nicht
|
||
// verhindern.
|
||
}
|
||
})
|
||
);
|
||
await self.skipWaiting();
|
||
})());
|
||
});
|
||
|
||
self.addEventListener('activate', event => {
|
||
event.waitUntil((async () => {
|
||
const keys = await caches.keys();
|
||
await Promise.all(
|
||
keys
|
||
.filter(key => key !== SHELL_CACHE && key !== TILE_CACHE)
|
||
.map(key => caches.delete(key))
|
||
);
|
||
await self.clients.claim();
|
||
})());
|
||
});
|
||
|
||
self.addEventListener('message', event => {
|
||
if (event.data && event.data.type === 'SKIP_WAITING') {
|
||
self.skipWaiting();
|
||
}
|
||
});
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Fetch-Strategien */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
self.addEventListener('fetch', event => {
|
||
const request = event.request;
|
||
if (request.method !== 'GET') return;
|
||
|
||
const url = new URL(request.url);
|
||
|
||
// API- und WebSocket-Aufrufe nie cachen.
|
||
if (url.pathname.includes('/api/') || url.pathname.includes('/ws')) {
|
||
return;
|
||
}
|
||
|
||
// Das Manifest wird immer frisch vom Server geladen.
|
||
if (url.pathname.endsWith('/manifest.webmanifest')) {
|
||
return;
|
||
}
|
||
|
||
if (isTileRequest(url)) {
|
||
event.respondWith(handleTile(request));
|
||
return;
|
||
}
|
||
|
||
if (request.mode === 'navigate') {
|
||
event.respondWith(handleNavigation(request));
|
||
return;
|
||
}
|
||
|
||
if (url.origin === self.location.origin) {
|
||
event.respondWith(handleAsset(request));
|
||
}
|
||
});
|
||
|
||
function isTileRequest(url) {
|
||
if (TILE_HOSTS.has(url.hostname)) return true;
|
||
return /\/tile\/\d+\/\d+\/\d+/.test(url.pathname)
|
||
|| /\/MapServer\/tile\//.test(url.pathname);
|
||
}
|
||
|
||
async function handleNavigation(request) {
|
||
const cache = await caches.open(SHELL_CACHE);
|
||
|
||
try {
|
||
const response = await fetch(request);
|
||
if (response && response.ok) {
|
||
cache.put(request, response.clone()).catch(() => {});
|
||
}
|
||
return response;
|
||
} catch (error) {
|
||
const cached = await cache.match(request, {ignoreSearch: true});
|
||
if (cached) return cached;
|
||
|
||
return new Response(offlineHtml(), {
|
||
status: 503,
|
||
headers: {'Content-Type': 'text/html; charset=utf-8'}
|
||
});
|
||
}
|
||
}
|
||
|
||
async function handleAsset(request) {
|
||
const cache = await caches.open(SHELL_CACHE);
|
||
const cached = await cache.match(request);
|
||
|
||
const network = fetch(request)
|
||
.then(response => {
|
||
if (response && (response.ok || response.type === 'opaque')) {
|
||
cache.put(request, response.clone()).catch(() => {});
|
||
}
|
||
return response;
|
||
})
|
||
.catch(() => null);
|
||
|
||
if (cached) {
|
||
// Im Hintergrund aktualisieren (stale-while-revalidate).
|
||
network.catch(() => {});
|
||
return cached;
|
||
}
|
||
|
||
const response = await network;
|
||
if (response) return response;
|
||
|
||
return new Response('', {
|
||
status: 504,
|
||
statusText: 'Offline'
|
||
});
|
||
}
|
||
|
||
async function handleTile(request) {
|
||
const cache = await caches.open(TILE_CACHE);
|
||
const cached = await cache.match(request);
|
||
if (cached) return cached;
|
||
|
||
try {
|
||
const response = await fetch(request);
|
||
if (response && (response.ok || response.type === 'opaque')) {
|
||
await cache.put(request, response.clone());
|
||
trimTileCache(cache);
|
||
}
|
||
return response;
|
||
} catch (error) {
|
||
return new Response('', {
|
||
status: 504,
|
||
statusText: 'Offline'
|
||
});
|
||
}
|
||
}
|
||
|
||
async function trimTileCache(cache) {
|
||
try {
|
||
const keys = await cache.keys();
|
||
if (keys.length <= MAX_TILES) return;
|
||
const excess = keys.length - MAX_TILES;
|
||
for (let i = 0; i < excess; i += 1) {
|
||
await cache.delete(keys[i]);
|
||
}
|
||
} catch (error) {
|
||
// Cache-Bereinigung ist optional.
|
||
}
|
||
}
|
||
|
||
function offlineHtml() {
|
||
return `<!DOCTYPE html>
|
||
<html lang="de">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<title>20*C+M+B+27 – offline</title>
|
||
<style>
|
||
body{font-family:system-ui,-apple-system,sans-serif;margin:0;min-height:100dvh;
|
||
display:flex;align-items:center;justify-content:center;background:#f7f9fc;color:#1f2937}
|
||
main{max-width:22rem;padding:2rem;text-align:center}
|
||
h1{font-size:1.2rem;margin:0 0 .5rem}
|
||
p{margin:0;color:#4b5563;font-size:.95rem}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<main>
|
||
<h1>Keine Verbindung</h1>
|
||
<p>20*C+M+B+27 ist offline nicht erreichbar. Bitte prüfe die Netzwerkverbindung und lade die Seite erneut.</p>
|
||
</main>
|
||
</body>
|
||
</html>`;
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Benachrichtigungen */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
self.addEventListener('notificationclick', event => {
|
||
event.notification.close();
|
||
|
||
const target = event.notification.data && event.notification.data.url
|
||
? event.notification.data.url
|
||
: BASE;
|
||
|
||
event.waitUntil((async () => {
|
||
const clientList = await self.clients.matchAll({
|
||
type: 'window',
|
||
includeUncontrolled: true
|
||
});
|
||
|
||
for (const client of clientList) {
|
||
if (client.url.startsWith(BASE) && 'focus' in client) {
|
||
return client.focus();
|
||
}
|
||
}
|
||
|
||
if (self.clients.openWindow) {
|
||
return self.clients.openWindow(target);
|
||
}
|
||
return null;
|
||
})());
|
||
});
|