Firebase Cloud Messaging 1. Versuch

This commit is contained in:
concierge committed 2026-11-08 12:25:35 +01:00
1 parent f1fb926c2f
commit 4c8b11c4d5
25 files changed
+2111 -31

No files matched your search

+299 -4
View File
@@ -7,6 +7,10 @@ const apiBase = appUrl(`${tenant}/api`);
const wsUrl = `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}${appUrl(`${tenant}/ws`)}`;
const storageKey = `cmbnet:${tenant}:mobile`;
const viewMode = window.CMBNET_VIEW_MODE || 'mobile_dispatcher';
const clientType = window.CMBNET_CLIENT_TYPE
|| (viewMode === 'mobile_group'
? 'group_view'
: (viewMode === 'mobile_dispatcher' ? 'dispatcher_mobile' : null));
const currentAccountId = Number(window.CMBNET_ACCOUNT_ID) || null;
const currentRole = window.CMBNET_ROLE || null;
const appTitle = window.CMBNET_APP_TITLE || '20*C+M+B+27';
@@ -24,6 +28,8 @@ const NAVIGATION_REFRESH_MS = 15000;
const GROUP_POSITION_LIVE_MS = 30 * 1000;
const GROUP_POSITION_RECENT_MS = 5 * 60 * 1000;
const WS_OUTBOX_LIMIT = 200;
const PUSH_WAKE_AUTH_TIMEOUT_MS = 25000;
const scriptPromises = new Map();
const STREET_STATES = ['unbearbeitet', 'zugewiesen', 'erledigt'];
const STREET_COLORS = {
@@ -66,7 +72,11 @@ const state = {
positionSendTimerId: null,
navigationTimerId: null,
lastKnownPosition: null,
lastPositionSentAt: 0
lastPositionSentAt: 0,
authWaiters: [],
fcmToken: null,
fcmMessaging: null,
fcmInitializing: false
};
const AudioContext = window.AudioContext || window.webkitAudioContext;
@@ -84,6 +94,7 @@ async function initMobile() {
registerServiceWorker();
initPwaInstall();
initNotifications();
initPushWakeListener();
if (viewMode === 'mobile_dispatcher') {
try {
@@ -174,7 +185,13 @@ function registerServiceWorker() {
const swUrl = window.CMBNET_SW_URL || '/sw.js';
window.addEventListener('load', () => {
navigator.serviceWorker.register(swUrl)
.then(cachePolylineScript)
.then(registration => {
cachePolylineScript();
if ('Notification' in window
&& Notification.permission === 'granted') {
initFirebasePush(registration);
}
})
.catch(error => {
console.warn('Service Worker konnte nicht registriert werden.', error);
});
@@ -305,12 +322,262 @@ async function requestNotifications() {
tag: 'cmbnet-permission'
});
}
initFirebasePush(registration, true);
}
} catch (error) {
console.warn('Benachrichtigungen konnten nicht aktiviert werden.', error);
}
}
function platformName() {
if (isIosDevice()) return 'ios';
if (/android/i.test(navigator.userAgent)) return 'android';
return 'desktop';
}
function loadScriptOnce(url) {
if (scriptPromises.has(url)) return scriptPromises.get(url);
const promise = new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.async = true;
script.onload = () => resolve();
script.onerror = () => reject(new Error(`Skript konnte nicht geladen werden: ${url}`));
document.head.appendChild(script);
});
scriptPromises.set(url, promise);
return promise;
}
async function initFirebasePush(registration = null, force = false) {
const config = window.CMBNET_FCM_CONFIG;
if (!config || !config.enabled || !clientType) return;
if (!('Notification' in window) || Notification.permission !== 'granted') return;
// iOS erlaubt Web Push für PWAs erst im installierten Standalone-Modus.
if (isIosDevice() && !isStandaloneMode()) return;
if (state.fcmToken) {
if (force) await syncPushRegistration();
return;
}
if (state.fcmInitializing) return;
state.fcmInitializing = true;
try {
const base = `https://www.gstatic.com/firebasejs/${config.sdkVersion}`;
await loadScriptOnce(`${base}/firebase-app-compat.js`);
await loadScriptOnce(`${base}/firebase-messaging-compat.js`);
if (!window.firebase) throw new Error('Firebase SDK nicht verfügbar.');
if (!firebase.apps.length) {
firebase.initializeApp(config.firebase);
}
if (typeof firebase.messaging.isSupported === 'function'
&& !firebase.messaging.isSupported()) {
return;
}
const messaging = firebase.messaging();
if (typeof messaging.onMessage === 'function') {
messaging.onMessage(payload => {
const reason = payload
&& payload.data
&& payload.data.reason
? payload.data.reason
: 'wake';
handlePushWake(reason);
});
}
const swRegistration = registration && registration.active
? registration
: await navigator.serviceWorker.ready;
const token = await messaging.getToken({
vapidKey: config.vapidKey,
serviceWorkerRegistration: swRegistration
});
if (!token) {
console.warn('FCM hat kein Token geliefert.');
return;
}
state.fcmToken = token;
state.fcmMessaging = messaging;
await syncPushRegistration();
} catch (error) {
console.warn('Firebase-Push konnte nicht initialisiert werden.', error);
} finally {
state.fcmInitializing = false;
}
}
async function syncPushRegistration() {
if (!state.fcmToken) return;
try {
await fetchJson(`${apiBase}/push/register`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
token: state.fcmToken,
client_id: window.CMBNET_CLIENT_ID
|| window.CMBNET_CLIENT_SESSION_ID
|| '',
client_type: clientType,
platform: platformName(),
auto_position: state.settings.autoSendPosition === true
})
});
} catch (error) {
console.warn('FCM-Token konnte nicht beim Server registriert werden.', error);
}
}
function initPushWakeListener() {
if (!('serviceWorker' in navigator)) return;
navigator.serviceWorker.addEventListener('message', event => {
if (!event.data || event.data.type !== 'cmbnet-wake') return;
const port = event.ports && event.ports[0];
handlePushWake(event.data.reason || 'wake', port);
});
}
function waitForWsAuthentication(timeoutMs = PUSH_WAKE_AUTH_TIMEOUT_MS) {
if (state.authenticated) return Promise.resolve(true);
return new Promise(resolve => {
const waiter = {resolve, timer: null};
waiter.timer = setTimeout(() => {
const index = state.authWaiters.indexOf(waiter);
if (index >= 0) state.authWaiters.splice(index, 1);
resolve(false);
}, timeoutMs);
state.authWaiters.push(waiter);
});
}
function resolveWsAuthentication() {
const waiters = state.authWaiters.splice(0);
waiters.forEach(waiter => {
clearTimeout(waiter.timer);
waiter.resolve(true);
});
}
async function handlePushWake(reason, port = null) {
let ok = false;
let positionSent = false;
try {
// Der Service Worker kann selbst keine WebSocket-Verbindung halten.
// Er stößt hier den Reconnect an und wartet über den MessagePort, bis
// die Authentifizierung abgeschlossen ist.
connectWebSocket();
ok = await waitForWsAuthentication();
if (ok && viewMode === 'mobile_group' && state.settings.autoSendPosition) {
positionSent = await sendWakePosition();
}
} finally {
if (port) {
port.postMessage({ok, positionSent, reason});
}
}
}
function sendWakePosition() {
if (!state.settings.autoSendPosition || viewMode !== 'mobile_group') {
return Promise.resolve(false);
}
if (!navigator.geolocation) {
return Promise.resolve(sendAutomaticPosition(true));
}
return new Promise(resolve => {
let settled = false;
const finish = (sent) => {
if (settled) return;
settled = true;
resolve(Boolean(sent));
};
const fallback = setTimeout(() => {
finish(sendAutomaticPosition(true));
}, 8000);
navigator.geolocation.getCurrentPosition(position => {
if (settled) return;
clearTimeout(fallback);
const lat = Number(position.coords.latitude);
const lon = Number(position.coords.longitude);
const previous = state.lastKnownPosition;
if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
finish(sendAutomaticPosition(true));
return;
}
state.lastKnownPosition = {
lat,
lon,
accuracy: position.coords.accuracy
};
updateHeadingFromGps(position, previous);
updateOwnPositionMarker(lat, lon);
finish(sendOwnPosition(lat, lon, true));
}, () => {
clearTimeout(fallback);
finish(sendAutomaticPosition(true));
}, {enableHighAccuracy: true, maximumAge: 60000, timeout: 8000});
});
}
function showMobileToast(message, isError = false) {
let toast = document.getElementById('mobileToast');
if (!toast) {
toast = document.createElement('div');
toast.id = 'mobileToast';
toast.className = 'mobile-toast';
toast.setAttribute('role', 'status');
toast.setAttribute('aria-live', 'polite');
document.body.appendChild(toast);
}
toast.textContent = message;
toast.classList.toggle('is-error', Boolean(isError));
toast.classList.add('is-visible');
clearTimeout(showMobileToast._timer);
showMobileToast._timer = setTimeout(() => {
toast.classList.remove('is-visible');
}, 4000);
}
async function wakeMobileClientsFromUi() {
const button = document.getElementById('mobileWakeBtn');
if (button) {
button.disabled = true;
button.classList.add('is-busy');
}
try {
const body = viewMode === 'mobile_dispatcher' && state.currentGroupId
? {group_id: state.currentGroupId}
: {};
const result = await fetchJson(`${apiBase}/push/wake`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body)
});
const sent = Number(result.sent) || 0;
if (sent > 0) {
showMobileToast(`${sent} mobile Clients geweckt.`);
} else {
showMobileToast('Keine offline mobilen Clients mit Push-Token gefunden.');
}
} catch (error) {
showMobileToast(`Wecken fehlgeschlagen: ${error.message}`, true);
} finally {
if (button) {
setTimeout(() => {
button.disabled = false;
button.classList.remove('is-busy');
}, 800);
}
}
}
function loadSettings() {
try {
const raw = localStorage.getItem(storageKey);
@@ -530,7 +797,23 @@ function refreshMobileMap() {
function bindButtons() {
const logout = document.getElementById('mobileLogout');
if (logout) logout.addEventListener('click', () => {window.location.href = window.CMBNET_LOGOUT_URL || appUrl('');});
if (logout) {
logout.addEventListener('click', () => {
if (state.fcmToken) {
// Das Token darf nach dem Abmelden keine weiteren
// Aufwachsignale für dieses Konto erhalten. keepalive
// erlaubt den Request noch während der Navigation.
fetch(`${apiBase}/push/register`, {
method: 'DELETE',
credentials: 'same-origin',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({token: state.fcmToken}),
keepalive: true
}).catch(() => {});
}
window.location.href = window.CMBNET_LOGOUT_URL || appUrl('');
});
}
const todoBtn = document.getElementById('mobileTodoBtn');
if (todoBtn) todoBtn.addEventListener('click', openStreetSelectDialog);
@@ -590,6 +873,7 @@ function bindButtons() {
state.settings.autoSendPosition = autoPositionToggle.checked;
saveSettings();
updatePositionSharingUi();
syncPushRegistration();
if (state.settings.autoSendPosition && state.lastKnownPosition) {
state.lastPositionSentAt = 0;
sendAutomaticPosition();
@@ -600,6 +884,10 @@ function bindButtons() {
if (sendPositionBtn) {
sendPositionBtn.addEventListener('click', sendPositionNow);
}
const wakeBtn = document.getElementById('mobileWakeBtn');
if (wakeBtn) {
wakeBtn.addEventListener('click', wakeMobileClientsFromUi);
}
updatePositionSharingUi();
}
@@ -1440,7 +1728,10 @@ function connectWebSocket() {
setMobileWsStatus('Anmeldung …', 'connecting');
ws.send(JSON.stringify({
code: 0,
msg: token,
msg: {
token: token,
client_type: clientType
},
client_id: window.CMBNET_CLIENT_ID
|| window.CMBNET_CLIENT_SESSION_ID
|| ''
@@ -1456,6 +1747,9 @@ function connectWebSocket() {
state.authenticated = true;
setMobileWsStatus('verbunden', 'connected');
flushWsOutbox();
// Ältere Server ohne Code-0-Bestätigung sollen ein
// FCM-Wake nicht unnötig lange blockieren.
resolveWsAuthentication();
}
}, 1500);
});
@@ -1772,6 +2066,7 @@ function handleWs(event) {
state.authenticated = true;
setMobileWsStatus('verbunden', 'connected');
flushWsOutbox();
resolveWsAuthentication();
} else if (message.code === 1) {
setMobileWsStatus('verbunden', 'connected');
if (state.ws && state.ws.readyState === WebSocket.OPEN) {