Files
Sternsinger/CMBNet/static/js/sw.js
T

408 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* 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-v27';
const BASE = new URL('./', self.location).href;
const SHELL_CACHE = `${VERSION}-shell`;
const TILE_CACHE = `${VERSION}-tiles`;
const MAX_TILES = 400;
const FCM_WAKE_ACK_TIMEOUT_MS = 20000;
// Die Datei wird von Flask erzeugt und enthält nur die öffentliche
// Firebase-Webkonfiguration. Fehlt sie, bleibt FCM in diesem Service Worker
// einfach deaktiviert.
try {
importScripts(new URL('fcm-sw-config.js', self.location).href);
} catch (error) {
self.CMBNET_FCM_CONFIG = {enabled: false};
}
const fcmConfig = self.CMBNET_FCM_CONFIG || {enabled: false};
let fcmMessaging = null;
if (fcmConfig.enabled) {
try {
importScripts(
`https://www.gstatic.com/firebasejs/${fcmConfig.sdkVersion}/firebase-app-compat.js`,
`https://www.gstatic.com/firebasejs/${fcmConfig.sdkVersion}/firebase-messaging-compat.js`
);
if (!firebase.apps.length) {
firebase.initializeApp(fcmConfig.firebase);
}
fcmMessaging = firebase.messaging();
fcmMessaging.onBackgroundMessage(payload => {
const reason = payload
&& payload.data
&& payload.data.reason
? payload.data.reason
: 'wake';
return handleFcmWake(reason);
});
} catch (error) {
// Ohne SDK bleibt die PWA voll funktionsfähig; nur Hintergrund-Wakes
// über FCM stehen dann nicht zur Verfügung.
console.warn('FCM im Service Worker nicht verfügbar:', error);
}
}
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',
// str2pl.js bzw. str2pl-<tenant>.js wird nach der Registrierung gezielt
// vom Client angemeldet, weil die passende Datei vom Mandanten abhängt.
'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();
}
if (event.data && event.data.type === 'CACHE_URLS' && Array.isArray(event.data.urls)) {
event.waitUntil(cacheUrls(event.data.urls));
}
});
async function cacheUrls(urls) {
const cache = await caches.open(SHELL_CACHE);
await Promise.allSettled(
urls.map(async url => {
try {
const cached = await cache.match(url);
if (cached) return;
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 das Caching nicht verhindern.
}
})
);
}
/* ------------------------------------------------------------------ */
/* FCM-Aufwachsignal */
/* ------------------------------------------------------------------ */
async function handleFcmWake(reason) {
const delivered = await wakeOpenClients(reason);
if (!delivered) {
await showWakeNotification(reason);
}
}
async function wakeOpenClients(reason) {
const clientList = await self.clients.matchAll({
type: 'window',
includeUncontrolled: true
});
const client = clientList.find(item => item.url.startsWith(BASE));
if (!client || typeof client.postMessage !== 'function') {
return false;
}
// Der Service Worker kann keine WebSocket-Verbindung halten. Er
// übergibt den Impuls an die geöffnete PWA und wartet auf deren
// Rückmeldung. So bleibt er lange genug aktiv, dass die Seite die
// Verbindung aufbauen und mindestens ein Positionsupdate senden kann.
const channel = new MessageChannel();
const ack = new Promise(resolve => {
const timer = setTimeout(() => resolve(false), FCM_WAKE_ACK_TIMEOUT_MS);
channel.port1.onmessage = event => {
clearTimeout(timer);
resolve(Boolean(event.data && event.data.ok));
};
channel.port1.start();
});
try {
client.postMessage(
{type: 'cmbnet-wake', reason: reason || 'wake'},
[channel.port2]
);
} catch (error) {
return false;
}
return ack;
}
async function showWakeNotification(reason) {
const body = reason === 'queue'
? 'Neue Nachricht eingegangen. Tippe, um die App zu synchronisieren.'
: 'Die mobile Ansicht wurde zur Synchronisierung aufgefordert.';
const icon = fcmConfig.icon
? new URL(fcmConfig.icon, BASE).href
: new URL('static/img/icon-192.png', BASE).href;
try {
await self.registration.showNotification(fcmConfig.title || '20*C+M+B+27', {
body,
icon,
badge: icon,
tag: fcmConfig.notificationTag || 'cmbnet-wake',
renotify: false,
data: {
type: 'cmbnet-wake',
url: new URL(fcmConfig.wakeUrl || '', BASE).href
}
});
} catch (error) {
// Ohne Benachrichtigungsrecht kann kein sichtbarer Fallback erzeugt
// werden. Der Push selbst bleibt ein reines Signal.
}
}
/* ------------------------------------------------------------------ */
/* 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);
const url = new URL(request.url);
// Admin-Seiten können sensible Daten wie API-Zugriffstoken enthalten und
// werden deshalb nicht im Service-Worker-Cache abgelegt.
const cacheable = !url.pathname.includes('/admin/');
try {
const response = await fetch(request);
if (cacheable && response && response.ok) {
cache.put(request, response.clone()).catch(() => {});
}
return response;
} catch (error) {
if (cacheable) {
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) {
// Ein Klick auf ein Aufwachsignal soll die bereits laufende
// PWA zusätzlich synchronisieren, ohne dass FCM Inhalte
// übertragen musste.
if (event.notification.data
&& event.notification.data.type === 'cmbnet-wake'
&& typeof client.postMessage === 'function') {
client.postMessage({type: 'cmbnet-wake', reason: 'notification'});
}
return client.focus();
}
}
if (self.clients.openWindow) {
return self.clients.openWindow(target);
}
return null;
})());
});