Mobile Views jetzt als PWA

This commit is contained in:
concierge committed 2026-10-29 08:08:23 +01:00
1 parent d8692ab20e
commit b41c3bc3a6
11 files changed
+785 -37

No files matched your search

+257
View File
@@ -0,0 +1,257 @@
/*
* 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-v1';
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/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>CMBNet – 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>CMBNet 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;
})());
});
+349 -30
View File
@@ -28,6 +28,9 @@ const state = {
streetById: new Map(),
groups: [],
groupById: new Map(),
accounts: [],
accountById: new Map(),
me: null,
currentGroupId: null,
polylinesByStreetId: new Map(),
groupMarkers: new Map(),
@@ -55,12 +58,22 @@ async function initMobile() {
initMap();
bindTabs();
bindButtons();
registerServiceWorker();
initPwaInstall();
initNotifications();
if (viewMode === 'mobile_dispatcher') {
try {
const groups = await fetchJson(`${apiBase}/init/groups`);
const [groups, accounts, me] = await Promise.all([
fetchJson(`${apiBase}/init/groups`),
fetchJson(`${apiBase}/init/accounts`).catch(() => []),
fetchJson(`${apiBase}/init/me`).catch(() => null)
]);
state.groups = Array.isArray(groups) ? groups : [];
state.accounts = Array.isArray(accounts) ? accounts : [];
state.me = me;
indexGroups();
indexAccounts();
buildGroupSelect();
const firstGroup = state.groups[0];
if (firstGroup) {
@@ -71,13 +84,20 @@ async function initMobile() {
}
} else if (viewMode === 'mobile_group') {
try {
const group = await fetchJson(`${apiBase}/groups/me`);
const [group, accounts, me] = await Promise.all([
fetchJson(`${apiBase}/groups/me`),
fetchJson(`${apiBase}/init/accounts`).catch(() => []),
fetchJson(`${apiBase}/init/me`).catch(() => null)
]);
state.accounts = Array.isArray(accounts) ? accounts : [];
state.me = me;
indexAccounts();
if (group && group.id) {
state.groups = [group];
state.currentGroupId = group.id;
indexGroups();
const nameEl = document.getElementById('groupNameDisplay');
if (nameEl) nameEl.textContent = group.aliasname || group.id || 'Gruppe';
if (nameEl) nameEl.textContent = groupDisplayName(group);
await loadGroupData(group.id);
}
} catch (e) {
@@ -102,6 +122,143 @@ function fetchJson(url, options={}) {
});
}
/* ------------------------------------------------------------------ */
/* Progressive Web App */
/* ------------------------------------------------------------------ */
let deferredInstallPrompt = null;
function isStandaloneMode() {
return window.matchMedia('(display-mode: standalone)').matches
|| window.navigator.standalone === true;
}
function isIosDevice() {
return /iphone|ipad|ipod/i.test(navigator.userAgent)
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
}
function registerServiceWorker() {
if (!('serviceWorker' in navigator)) return;
const swUrl = window.CMBNET_SW_URL || '/sw.js';
window.addEventListener('load', () => {
navigator.serviceWorker.register(swUrl).catch(error => {
console.warn('Service Worker konnte nicht registriert werden.', error);
});
});
}
function initPwaInstall() {
const button = document.getElementById('mobileInstallBtn');
if (!button) return;
if (isStandaloneMode()) {
button.hidden = true;
return;
}
// Unter iOS gibt es kein beforeinstallprompt. Dort zeigen wir den Button
// dauerhaft an und erklären die Installation über das Teilen-Menü.
if (isIosDevice()) button.hidden = false;
window.addEventListener('beforeinstallprompt', event => {
event.preventDefault();
deferredInstallPrompt = event;
button.hidden = false;
});
window.addEventListener('appinstalled', () => {
deferredInstallPrompt = null;
button.hidden = true;
});
button.addEventListener('click', async () => {
if (deferredInstallPrompt) {
const prompt = deferredInstallPrompt;
deferredInstallPrompt = null;
prompt.prompt();
try {
const choice = await prompt.userChoice;
if (choice.outcome === 'accepted') button.hidden = true;
} catch (error) {
// Der Dialog kann abgelehnt oder geschlossen werden.
}
return;
}
const dialog = document.getElementById('mobileInstallDialog');
const iosHint = document.getElementById('mobileInstallIosHint');
const genericHint = document.getElementById('mobileInstallGenericHint');
if (iosHint) iosHint.hidden = !isIosDevice();
if (genericHint) genericHint.hidden = isIosDevice();
if (dialog && typeof dialog.showModal === 'function') {
dialog.showModal();
} else if (dialog) {
dialog.show();
}
});
}
function closeMobileInstall() {
const dialog = document.getElementById('mobileInstallDialog');
if (dialog && dialog.open) dialog.close();
}
function initNotifications() {
const button = document.getElementById('mobileNotifyBtn');
if (!button) return;
button.addEventListener('click', requestNotifications);
updateNotificationUi();
}
function updateNotificationUi() {
const button = document.getElementById('mobileNotifyBtn');
if (!button) return;
if (!('Notification' in window)) {
button.textContent = 'Nicht verfügbar';
button.disabled = true;
return;
}
const permission = Notification.permission;
button.classList.toggle('is-active', permission === 'granted');
button.disabled = permission === 'denied';
if (permission === 'granted') {
button.textContent = 'Aktiv';
} else if (permission === 'denied') {
button.textContent = 'Blockiert';
} else {
button.textContent = 'Aktivieren';
}
}
async function requestNotifications() {
if (!('Notification' in window)) return;
try {
const permission = await Notification.requestPermission();
updateNotificationUi();
if (permission === 'granted' && navigator.serviceWorker) {
const registration = await navigator.serviceWorker.getRegistration();
if (registration && registration.showNotification) {
await registration.showNotification('CMBNet', {
body: 'Benachrichtigungen sind aktiviert.',
icon: window.CMBNET_ICON_URL || undefined,
tag: 'cmbnet-permission'
});
}
}
} catch (error) {
console.warn('Benachrichtigungen konnten nicht aktiviert werden.', error);
}
}
function loadSettings() {
try {
const raw = localStorage.getItem(storageKey);
@@ -219,6 +376,130 @@ function indexGroups() {
});
}
function indexAccounts() {
state.accountById.clear();
state.accounts.forEach(account => {
const id = Number(account.id);
if (!Number.isFinite(id)) return;
account.id = id;
state.accountById.set(id, account);
});
}
function groupDisplayName(group) {
if (!group) return 'Gruppe';
const alias = group.aliasname && String(group.aliasname).trim();
return alias || 'Gruppe';
}
function findGroupForAccount(accountId) {
const id = Number(accountId);
return state.groups.find(group => Number(group.account_id) === id) || null;
}
/**
* Formatiert "Accountname" bzw. "Accountname (Gruppe: Alias)".
*/
function formatPersonName(name, role, groupAlias) {
const base = String(name || '').trim() || 'Unbekannt';
const alias = groupAlias && String(groupAlias).trim();
if (alias) return `${base} (Gruppe: ${alias})`;
if (role === 'Gruppe') return `${base} (Gruppe)`;
return base;
}
function getAccount(accountId) {
const id = Number(accountId);
if (!Number.isFinite(id)) return null;
return state.accountById.get(id) || null;
}
function getAccountDisplayName(accountId) {
const id = Number(accountId);
if (!Number.isFinite(id)) return null;
const account = getAccount(id);
if (account) {
const group = findGroupForAccount(id);
return formatPersonName(account.name, account.role, group ? group.aliasname : null);
}
if (state.me && Number(state.me.id) === id) {
const group = findGroupForAccount(id);
return formatPersonName(
state.me.name,
state.me.role,
group ? group.aliasname : null
);
}
return null;
}
function getSenderName(message, payload) {
const payloadSender = payload && typeof payload.sender === 'object'
? payload.sender
: null;
if (payloadSender && payloadSender.name) {
return formatPersonName(
payloadSender.name,
payloadSender.role,
payloadSender.group_alias
);
}
const senderId = Number(message.sender_id);
const known = getAccountDisplayName(senderId);
if (known) return known;
if (state.me && senderId === Number(state.me.id)) {
return formatPersonName(state.me.name, state.me.role, null);
}
return 'Unbekannt';
}
function getReceiverName(message, payload) {
const code = Number(message.code);
if (code === 1000 || (payload && payload.broadcast)) return 'alle';
const payloadSender = payload && typeof payload.sender === 'object'
? payload.sender
: null;
const senderRole = payloadSender?.role || getAccount(message.sender_id)?.role;
if (code === 2000 && senderRole === 'Gruppe') {
// Gruppen senden mit Code 2000 an Dispatcher und Beobachter.
return 'Dispatcher';
}
let receiverId = Number(message.receiver_id);
if (!Number.isFinite(receiverId) || receiverId <= 0) {
if (payload && payload.group_id !== undefined) {
receiverId = Number(payload.group_id);
} else if (payload && payload.receiver_id !== undefined) {
receiverId = Number(payload.receiver_id);
}
}
if (!Number.isFinite(receiverId) || receiverId <= 0) return 'alle';
let group = state.groupById.get(receiverId);
if (!group && receiverId === Number(state.currentGroupId) && state.groups.length) {
group = state.groups[0];
}
if (group) {
const accountName = getAccountDisplayName(group.account_id);
return accountName || groupDisplayName(group) || 'Gruppe';
}
const accountName = getAccountDisplayName(receiverId);
if (accountName) return accountName;
return 'Unbekannt';
}
function buildGroupSelect() {
const sel = document.getElementById('mobileGroupSelect');
if (!sel) return;
@@ -599,7 +880,11 @@ function renderChat() {
meta.textContent = new Date(entry.ts).toLocaleString('de-DE');
const fromto = document.createElement('div');
fromto.className = 'mobile-chat-fromto';
fromto.textContent = entry.senderName || `ID ${entry.sender_id}`;
const fromName = entry.fromName
|| getSenderName({sender_id: entry.sender_id}, null);
const toName = entry.toName
|| (Number(entry.code) === 1000 ? 'alle' : 'Unbekannt');
fromto.textContent = `${fromName} -> ${toName}`;
const text = document.createElement('div');
text.className = 'mobile-chat-text';
text.textContent = entry.text;
@@ -625,12 +910,29 @@ function playSound() {
} catch(e) {}
}
function showChatPopup(text) {
// Try to show notification if possible
if ('Notification' in window && Notification.permission === 'granted') {
try { new Notification('CMBNet Nachricht', {body: text}); } catch(e) {}
} else if ('Notification' in window && Notification.permission !== 'denied') {
Notification.requestPermission();
async function showChatPopup(text, senderName) {
if (!('Notification' in window) || Notification.permission !== 'granted') return;
const options = {
body: text,
icon: window.CMBNET_ICON_URL || undefined,
badge: window.CMBNET_ICON_URL || undefined,
tag: 'cmbnet-chat',
renotify: true,
data: {url: window.location.href}
};
try {
if (navigator.serviceWorker) {
const registration = await navigator.serviceWorker.getRegistration();
if (registration && registration.showNotification) {
await registration.showNotification(senderName || 'CMBNet', options);
return;
}
}
new Notification(senderName || 'CMBNet', options);
} catch (error) {
// Benachrichtigungen sind optional.
}
}
@@ -653,6 +955,23 @@ function extractText(msg) {
return String(msg);
}
function parseMessagePayload(value) {
if (value && typeof value === 'object') return value;
if (typeof value !== 'string') return null;
try {
const parsed = JSON.parse(value);
return parsed && typeof parsed === 'object' ? parsed : null;
} catch (e) {
return null;
}
}
function normalizeTs(value) {
const number = Number(value);
if (!Number.isFinite(number) || number <= 0) return null;
return number < 1e12 ? number * 1000 : number;
}
function handleWs(event) {
let message;
try { message = JSON.parse(event.data); } catch(e) { return; }
@@ -692,31 +1011,30 @@ function handleWs(event) {
} catch(e) {}
} else if (message.code === 2000 || message.code === 1000 || message.code === 1100) {
// Chat messages
const text = extractText(message.msg);
const entry = {
sender_id: message.sender_id,
code: message.code,
ts: message.ts || Date.now(),
text,
senderName: undefined
};
// For gruppe view, broker should only send relevant messages; still check
const payload = parseMessagePayload(message.msg);
const text = extractText(payload ?? message.msg);
// Im Gruppen-View nur Nachrichten an alle oder an die eigene Gruppe.
if (viewMode === 'mobile_group') {
const p = typeof message.msg === 'string' ? JSON.parse(message.msg) : message.msg;
const gid = Number(p?.group_id || message.receiver_id);
if (message.code === 1100 && gid && gid !== state.currentGroupId) {
return; // should not happen if broker filters, but be safe
}
if (message.code === 2000 && gid && gid !== state.currentGroupId && message.sender_id !== currentAccountId) {
// Check if it's from our group
const isFromOurGroup = state.groups.some(g => g.account_id && false); // simplified
const gid = Number(payload?.group_id ?? message.receiver_id);
const ownGroupId = Number(state.currentGroupId);
if (Number.isFinite(gid) && gid > 0 && ownGroupId && gid !== ownGroupId) {
return;
}
}
const wasEmpty = state.chatMessages.length === 0;
addChatEntry(entry);
addChatEntry({
sender_id: message.sender_id,
code: message.code,
ts: normalizeTs(message.ts) || Date.now(),
text,
fromName: getSenderName(message, payload),
toName: getReceiverName(message, payload)
});
if (Number(message.sender_id) !== currentAccountId) {
playSound();
showChatPopup(text);
showChatPopup(text, getSenderName(message, payload));
// Switch to chat tab
document.querySelectorAll('.mobile-tab').forEach(b => {
if (b.dataset.tab === 'chat') b.click();
@@ -730,3 +1048,4 @@ window.closeMobileStreetSelect = closeMobileStreetSelect;
window.closeMobileStreetState = closeMobileStreetState;
window.saveMobileStreetState = saveMobileStreetState;
window.closeMobileSettings = closeMobileSettings;
window.closeMobileInstall = closeMobileInstall;