2234 lines
77 KiB
JavaScript
2234 lines
77 KiB
JavaScript
/*
|
|
* Mobile Views: Dispatcher-Mobil & Gruppen
|
|
*/
|
|
const appUrl = window.CMBNET_APP_URL || ((path) => `/${String(path || '').replace(/^\/+/, '')}`);
|
|
const tenant = window.CMBNET_TENANT || '';
|
|
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';
|
|
|
|
const DEFAULT_SETTINGS = {
|
|
opacity: 0.7,
|
|
weight: 20,
|
|
baseLayer: 'osm',
|
|
// Die automatische Übertragung der Eigenposition ist bewusst opt-in.
|
|
// Bestehende gespeicherte Einstellungen bleiben unverändert.
|
|
autoSendPosition: false
|
|
};
|
|
|
|
const AUTO_POSITION_INTERVAL_MS = 30000;
|
|
const NAVIGATION_MAX_AGE_MS = 30 * 60 * 1000;
|
|
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 = {
|
|
unbearbeitet: '#1f6feb',
|
|
zugewiesen: '#d62828',
|
|
erledigt: '#2e9e4f'
|
|
};
|
|
|
|
const state = {
|
|
settings: {...DEFAULT_SETTINGS},
|
|
streets: [],
|
|
streetById: new Map(),
|
|
groups: [],
|
|
groupById: new Map(),
|
|
accounts: [],
|
|
accountById: new Map(),
|
|
me: null,
|
|
currentGroupId: null,
|
|
polylinesByStreetId: new Map(),
|
|
groupMarkers: new Map(),
|
|
currentPolyline: null,
|
|
currentStreetId: null,
|
|
ws: null,
|
|
authenticated: false,
|
|
outbox: [],
|
|
reconnectTimer: null,
|
|
lastWsSeq: null,
|
|
chatMessages: [],
|
|
chatKeys: new Set(),
|
|
userMarker: null,
|
|
userHeading: null,
|
|
lastCompassHeading: null,
|
|
lastCompassAt: 0,
|
|
absoluteCompassAvailable: false,
|
|
lastGpsHeading: null,
|
|
lastGpsAt: 0,
|
|
orientationListenersBound: false,
|
|
orientationPermissionRequested: false,
|
|
watchId: null,
|
|
positionSendTimerId: null,
|
|
navigationTimerId: null,
|
|
lastKnownPosition: null,
|
|
lastPositionSentAt: 0,
|
|
authWaiters: [],
|
|
fcmToken: null,
|
|
fcmMessaging: null,
|
|
fcmInitializing: false
|
|
};
|
|
|
|
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
|
const audioCtx = new AudioContext();
|
|
|
|
let map, osmLayer, aerialLayer, currentBaseLayer;
|
|
|
|
document.addEventListener('DOMContentLoaded', initMobile);
|
|
|
|
async function initMobile() {
|
|
loadSettings();
|
|
initMap();
|
|
bindTabs();
|
|
bindButtons();
|
|
registerServiceWorker();
|
|
initPwaInstall();
|
|
initNotifications();
|
|
initPushWakeListener();
|
|
|
|
if (viewMode === 'mobile_dispatcher') {
|
|
try {
|
|
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) {
|
|
await loadGroupData(firstGroup.id);
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
} else if (viewMode === 'mobile_group') {
|
|
try {
|
|
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 = groupDisplayName(group);
|
|
await loadGroupData(group.id);
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
}
|
|
|
|
startGeolocation();
|
|
startNavigationButtonWatcher();
|
|
connectWebSocket();
|
|
window.addEventListener('beforeunload', () => {
|
|
if (state.watchId !== null && navigator.geolocation) {
|
|
navigator.geolocation.clearWatch(state.watchId);
|
|
}
|
|
if (state.positionSendTimerId !== null) {
|
|
clearInterval(state.positionSendTimerId);
|
|
}
|
|
if (state.navigationTimerId !== null) {
|
|
clearInterval(state.navigationTimerId);
|
|
}
|
|
if (state.ws) state.ws.close();
|
|
});
|
|
|
|
// ``pagehide`` wird auf mobilen Browsern zuverlässiger ausgelöst als
|
|
// ``beforeunload``, wenn die PWA verlassen oder eingefroren wird.
|
|
window.addEventListener('pagehide', () => {
|
|
if (state.ws) state.ws.close();
|
|
});
|
|
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (document.hidden) {
|
|
// Im Hintergrund kann die View nicht bedient werden und mobile
|
|
// Browser frieren die Verbindung ohnehin ein. Das saubere
|
|
// Schließen markiert den Client sofort als offline, sodass der
|
|
// manuelle Wake-Button ihn über FCM erreichen kann.
|
|
if (state.reconnectTimer) {
|
|
clearTimeout(state.reconnectTimer);
|
|
state.reconnectTimer = null;
|
|
}
|
|
if (state.ws) {
|
|
const ws = state.ws;
|
|
state.ws = null;
|
|
state.authenticated = false;
|
|
try { ws.close(); } catch (error) {}
|
|
}
|
|
setMobileWsStatus('getrennt', 'disconnected');
|
|
return;
|
|
}
|
|
|
|
// Beim Zurückkehren sofort wieder verbinden und die Token-
|
|
// Registrierung auffrischen (verhindert veraltete Tokens).
|
|
syncPushRegistration();
|
|
connectWebSocket();
|
|
});
|
|
}
|
|
|
|
function fetchJson(url, options={}) {
|
|
return fetch(url, {credentials:'same-origin', ...options}).then(r => {
|
|
if (!r.ok) throw new Error(r.status);
|
|
return r.json();
|
|
});
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 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)
|
|
.then(registration => {
|
|
cachePolylineScript();
|
|
if ('Notification' in window
|
|
&& Notification.permission === 'granted') {
|
|
initFirebasePush(registration);
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.warn('Service Worker konnte nicht registriert werden.', error);
|
|
});
|
|
});
|
|
}
|
|
|
|
function cachePolylineScript() {
|
|
// Das Polyline-Skript ist mandantenabhängig (str2pl-<tenant>.js oder
|
|
// str2pl.js) und kann deshalb nicht statisch im Service Worker
|
|
// vorabgespeichert werden. Der Client meldet die tatsächlich geladene
|
|
// Datei nach der Registrierung zum Caching an.
|
|
const script = document.querySelector('script[src*="str2pl"]');
|
|
if (!script || !script.src) return;
|
|
|
|
navigator.serviceWorker.ready
|
|
.then(registration => {
|
|
const worker = registration.active
|
|
|| registration.waiting
|
|
|| registration.installing;
|
|
if (worker) {
|
|
worker.postMessage({type: 'CACHE_URLS', urls: [script.src]});
|
|
}
|
|
})
|
|
.catch(() => {});
|
|
}
|
|
|
|
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(appTitle, {
|
|
body: 'Benachrichtigungen sind aktiviert.',
|
|
icon: window.CMBNET_ICON_URL || undefined,
|
|
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];
|
|
const reason = event.data.reason || 'wake';
|
|
handlePushWake(reason, 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}
|
|
: {};
|
|
// ``fetchJson`` verwirft den Fehlertext des Servers. Für den Wake-
|
|
// Button ist er aber entscheidend (z. B. fehlendes firebase-admin).
|
|
const response = await fetch(`${apiBase}/push/wake`, {
|
|
method: 'POST',
|
|
credentials: 'same-origin',
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: JSON.stringify(body)
|
|
});
|
|
const result = await response.json().catch(() => ({}));
|
|
const sent = Number(result.sent) || 0;
|
|
const tokens = Number(result.valid_tokens) || 0;
|
|
const connected = Number(result.connected) || 0;
|
|
const candidates = Number(result.candidates) || 0;
|
|
if (sent > 0) {
|
|
showMobileToast(`${sent} mobile Clients geweckt.`);
|
|
} else if (!response.ok) {
|
|
showMobileToast(
|
|
`Wecken fehlgeschlagen: ${result.error || `HTTP ${response.status}`}`,
|
|
true
|
|
);
|
|
} else if (tokens === 0) {
|
|
showMobileToast('Keine mobilen Clients mit Push-Token registriert.');
|
|
} else if (candidates === 0) {
|
|
showMobileToast(
|
|
'Kein passender Client für dieses Aufwachsignal '
|
|
+ `(registriert: ${tokens}, verbunden: ${connected}).`
|
|
);
|
|
} else {
|
|
const firstError = result.error
|
|
|| (Array.isArray(result.errors)
|
|
&& result.errors[0]
|
|
&& result.errors[0].error)
|
|
|| '';
|
|
const detail = firstError
|
|
? ` Grund: ${String(firstError).slice(0, 240)}`
|
|
: '';
|
|
showMobileToast(
|
|
`Wecken fehlgeschlagen: ${Number(result.failed) || 0} Fehler `
|
|
+ `bei ${candidates} Empfängern.${detail}`,
|
|
true
|
|
);
|
|
}
|
|
} 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);
|
|
if (raw) {
|
|
const saved = JSON.parse(raw);
|
|
state.settings.opacity = typeof saved.opacity === 'number' ? saved.opacity : DEFAULT_SETTINGS.opacity;
|
|
state.settings.weight = typeof saved.weight === 'number' ? saved.weight : DEFAULT_SETTINGS.weight;
|
|
state.settings.baseLayer = saved.baseLayer === 'aerial' ? 'aerial' : 'osm';
|
|
state.settings.autoSendPosition = saved.autoSendPosition === true;
|
|
}
|
|
} catch(e) {}
|
|
}
|
|
|
|
function saveSettings() {
|
|
try {
|
|
localStorage.setItem(storageKey, JSON.stringify(state.settings));
|
|
} catch(e) {}
|
|
}
|
|
|
|
function updatePositionSharingUi() {
|
|
if (viewMode !== 'mobile_group') return;
|
|
|
|
const toggle = document.getElementById('mobileAutoPositionToggle');
|
|
if (toggle) toggle.checked = state.settings.autoSendPosition;
|
|
|
|
const button = document.getElementById('mobileSendPositionBtn');
|
|
if (!button) return;
|
|
button.hidden = state.settings.autoSendPosition;
|
|
button.disabled = false;
|
|
button.textContent = 'Position senden';
|
|
}
|
|
|
|
function canSendWs() {
|
|
return Boolean(state.ws
|
|
&& state.ws.readyState === WebSocket.OPEN
|
|
&& state.authenticated);
|
|
}
|
|
|
|
function sendWsMessage(message, queueWhenOffline = true) {
|
|
const data = JSON.stringify(message);
|
|
|
|
if (canSendWs()) {
|
|
try {
|
|
state.ws.send(data);
|
|
return true;
|
|
} catch (error) {
|
|
// Nach einem Sendefehler wird die Nachricht unten gepuffert.
|
|
}
|
|
}
|
|
|
|
if (queueWhenOffline) {
|
|
state.outbox.push(data);
|
|
if (state.outbox.length > WS_OUTBOX_LIMIT) {
|
|
state.outbox.splice(0, state.outbox.length - WS_OUTBOX_LIMIT);
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function flushWsOutbox() {
|
|
if (!canSendWs() || !state.outbox.length) return;
|
|
|
|
const pending = state.outbox;
|
|
state.outbox = [];
|
|
for (let index = 0; index < pending.length; index += 1) {
|
|
try {
|
|
state.ws.send(pending[index]);
|
|
} catch (error) {
|
|
state.outbox = pending.slice(index).concat(state.outbox);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
function sendOwnPosition(lat, lon, automatic = false) {
|
|
if (viewMode !== 'mobile_group' || currentRole !== 'Gruppe') return false;
|
|
if (!state.currentGroupId) return false;
|
|
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return false;
|
|
|
|
const sent = sendWsMessage({
|
|
code: 300,
|
|
msg: JSON.stringify({
|
|
group_id: state.currentGroupId,
|
|
lat,
|
|
lon,
|
|
ts: Date.now(),
|
|
actor: currentAccountId,
|
|
automatic: automatic === true
|
|
})
|
|
}, !automatic);
|
|
|
|
if (!sent && automatic) return false;
|
|
state.lastPositionSentAt = Date.now();
|
|
return true;
|
|
}
|
|
|
|
function sendAutomaticPosition(force = false) {
|
|
if (viewMode !== 'mobile_group' || !state.settings.autoSendPosition) return false;
|
|
if (!state.lastKnownPosition) return false;
|
|
if (!force && Date.now() - state.lastPositionSentAt < AUTO_POSITION_INTERVAL_MS) return false;
|
|
return sendOwnPosition(
|
|
state.lastKnownPosition.lat,
|
|
state.lastKnownPosition.lon,
|
|
true
|
|
);
|
|
}
|
|
|
|
function sendPositionNow() {
|
|
if (viewMode !== 'mobile_group' || state.settings.autoSendPosition) return;
|
|
|
|
const button = document.getElementById('mobileSendPositionBtn');
|
|
if (!navigator.geolocation) {
|
|
alert('Eigenposition ist auf diesem Gerät nicht verfügbar.');
|
|
return;
|
|
}
|
|
|
|
if (button) {
|
|
button.disabled = true;
|
|
button.textContent = 'Sende …';
|
|
}
|
|
|
|
navigator.geolocation.getCurrentPosition((position) => {
|
|
const lat = Number(position.coords.latitude);
|
|
const lon = Number(position.coords.longitude);
|
|
const previous = state.lastKnownPosition;
|
|
state.lastKnownPosition = {
|
|
lat,
|
|
lon,
|
|
accuracy: position.coords.accuracy
|
|
};
|
|
updateHeadingFromGps(position, previous);
|
|
updateOwnPositionMarker(lat, lon);
|
|
|
|
const sent = sendOwnPosition(lat, lon, false);
|
|
if (button) {
|
|
button.disabled = false;
|
|
button.textContent = sent ? 'Gesendet' : 'Position senden';
|
|
}
|
|
|
|
if (!sent) {
|
|
alert('Eigenposition konnte nicht gesendet werden. Keine Verbindung zum Server.');
|
|
return;
|
|
}
|
|
|
|
setTimeout(() => {
|
|
if (button && !button.hidden) button.textContent = 'Position senden';
|
|
}, 2000);
|
|
}, (error) => {
|
|
console.warn(error);
|
|
if (button) {
|
|
button.disabled = false;
|
|
button.textContent = 'Position senden';
|
|
}
|
|
alert('Eigenposition konnte nicht ermittelt werden.');
|
|
}, {enableHighAccuracy: true, maximumAge: 0, timeout: 10000});
|
|
}
|
|
|
|
function updateOwnPositionMarker(lat, lon) {
|
|
if (state.userMarker && Number.isFinite(lat) && Number.isFinite(lon)) {
|
|
state.userMarker.setLatLng([lat, lon]);
|
|
}
|
|
}
|
|
|
|
function initMap() {
|
|
map = L.map('mobileMap', {zoomControl: false, preferCanvas: true});
|
|
map.setView([51.0, 10.0], 6);
|
|
osmLayer = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 19});
|
|
aerialLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {maxZoom: 19});
|
|
setBaseLayer(state.settings.baseLayer, false);
|
|
map.on('zoomend', updateAllPolylineStyles);
|
|
}
|
|
|
|
function setBaseLayer(name, persist=true) {
|
|
if (currentBaseLayer) map.removeLayer(currentBaseLayer);
|
|
currentBaseLayer = name === 'aerial' ? aerialLayer : osmLayer;
|
|
currentBaseLayer.addTo(map);
|
|
state.settings.baseLayer = name === 'aerial' ? 'aerial' : 'osm';
|
|
const sel = document.getElementById('mobileBaseLayerSelect');
|
|
if (sel) sel.value = state.settings.baseLayer;
|
|
if (persist) saveSettings();
|
|
}
|
|
|
|
function bindTabs() {
|
|
document.querySelectorAll('.mobile-tab').forEach(btn => {
|
|
btn.addEventListener('click', () => {
|
|
document.querySelectorAll('.mobile-tab').forEach(b => {b.classList.remove('active'); b.setAttribute('aria-selected','false');});
|
|
document.querySelectorAll('.mobile-tab-panel').forEach(p => p.classList.remove('active'));
|
|
btn.classList.add('active');
|
|
btn.setAttribute('aria-selected','true');
|
|
const panel = document.getElementById(`tab-${btn.dataset.tab}`);
|
|
if (panel) panel.classList.add('active');
|
|
if (btn.dataset.tab === 'chat') {
|
|
const cont = document.getElementById('mobileChatMessages');
|
|
if (cont) cont.scrollTop = cont.scrollHeight;
|
|
} else if (btn.dataset.tab === 'map') {
|
|
refreshMobileMap();
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function refreshMobileMap() {
|
|
if (!map) return;
|
|
|
|
// Während der Chat-Ansicht ist der Kartencontainer display:none. Beim
|
|
// Zurückwechseln muss Leaflet die Größe neu messen. Zusätzlich werden die
|
|
// Kacheln neu angefordert, da sie im versteckten Zustand nicht aktualisiert
|
|
// wurden.
|
|
requestAnimationFrame(() => {
|
|
if (!map) return;
|
|
map.invalidateSize({pan: false});
|
|
if (currentBaseLayer && typeof currentBaseLayer.redraw === 'function') {
|
|
currentBaseLayer.redraw();
|
|
}
|
|
});
|
|
}
|
|
|
|
function bindButtons() {
|
|
const logout = document.getElementById('mobileLogout');
|
|
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);
|
|
|
|
const settingsBtn = document.getElementById('mobileSettingsBtn');
|
|
if (settingsBtn) settingsBtn.addEventListener('click', openSettingsDialog);
|
|
|
|
const workBtn = document.getElementById('mobileWorkBtn');
|
|
if (workBtn) workBtn.addEventListener('click', openStreetStateDialog);
|
|
|
|
const navigateBtn = document.getElementById('mobileNavigateBtn');
|
|
if (navigateBtn) navigateBtn.addEventListener('click', openGroupNavigation);
|
|
|
|
const chatForm = document.getElementById('mobileChatForm');
|
|
if (chatForm) {
|
|
chatForm.addEventListener('submit', (e) => {
|
|
e.preventDefault();
|
|
sendChat();
|
|
});
|
|
}
|
|
|
|
const groupSel = document.getElementById('mobileGroupSelect');
|
|
if (groupSel) {
|
|
groupSel.addEventListener('change', () => {
|
|
loadGroupData(groupSel.value);
|
|
});
|
|
}
|
|
|
|
// Settings
|
|
const opacitySlider = document.getElementById('mobileOpacitySlider');
|
|
if (opacitySlider) {
|
|
opacitySlider.addEventListener('input', (e) => {
|
|
state.settings.opacity = Number(e.target.value);
|
|
const out = document.getElementById('mobileOpacityValue');
|
|
if (out) out.textContent = state.settings.opacity.toFixed(2);
|
|
updateAllPolylineStyles();
|
|
saveSettings();
|
|
});
|
|
}
|
|
const weightSlider = document.getElementById('mobileWeightSlider');
|
|
if (weightSlider) {
|
|
weightSlider.addEventListener('input', (e) => {
|
|
state.settings.weight = Number(e.target.value);
|
|
const out = document.getElementById('mobileWeightValue');
|
|
if (out) out.textContent = `${state.settings.weight} m`;
|
|
updateAllPolylineStyles();
|
|
saveSettings();
|
|
});
|
|
}
|
|
const baseSel = document.getElementById('mobileBaseLayerSelect');
|
|
if (baseSel) {
|
|
baseSel.addEventListener('change', (e) => setBaseLayer(e.target.value));
|
|
}
|
|
const autoPositionToggle = document.getElementById('mobileAutoPositionToggle');
|
|
if (autoPositionToggle) {
|
|
autoPositionToggle.addEventListener('change', () => {
|
|
state.settings.autoSendPosition = autoPositionToggle.checked;
|
|
saveSettings();
|
|
updatePositionSharingUi();
|
|
syncPushRegistration();
|
|
if (state.settings.autoSendPosition && state.lastKnownPosition) {
|
|
state.lastPositionSentAt = 0;
|
|
sendAutomaticPosition();
|
|
}
|
|
});
|
|
}
|
|
const sendPositionBtn = document.getElementById('mobileSendPositionBtn');
|
|
if (sendPositionBtn) {
|
|
sendPositionBtn.addEventListener('click', sendPositionNow);
|
|
}
|
|
const wakeBtn = document.getElementById('mobileWakeBtn');
|
|
if (wakeBtn) {
|
|
wakeBtn.addEventListener('click', wakeMobileClientsFromUi);
|
|
}
|
|
updatePositionSharingUi();
|
|
}
|
|
|
|
function indexGroups() {
|
|
state.groupById.clear();
|
|
state.groups.forEach(g => {
|
|
g.id = Number(g.id);
|
|
g.last_pos_ts = parseFlexibleTimestamp(g.last_pos_at);
|
|
state.groupById.set(g.id, g);
|
|
});
|
|
}
|
|
|
|
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);
|
|
if (!Number.isFinite(id)) return null;
|
|
return state.groups.find(group =>
|
|
Array.isArray(group.account_ids)
|
|
&& group.account_ids.some(value => Number(value) === 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) {
|
|
return groupDisplayName(group) || 'Gruppe';
|
|
}
|
|
|
|
const accountName = getAccountDisplayName(receiverId);
|
|
if (accountName) return accountName;
|
|
|
|
return 'Unbekannt';
|
|
}
|
|
|
|
|
|
function buildGroupSelect() {
|
|
const sel = document.getElementById('mobileGroupSelect');
|
|
if (!sel) return;
|
|
sel.innerHTML = '';
|
|
state.groups.forEach(g => {
|
|
const opt = document.createElement('option');
|
|
opt.value = g.id;
|
|
opt.textContent = `${g.aliasname || g.id} (${g.state || 'offen'})`;
|
|
sel.appendChild(opt);
|
|
});
|
|
}
|
|
|
|
async function loadGroupData(groupId) {
|
|
groupId = Number(groupId);
|
|
state.currentGroupId = groupId;
|
|
const sel = document.getElementById('mobileGroupSelect');
|
|
if (sel && viewMode === 'mobile_dispatcher') sel.value = String(groupId);
|
|
updateNavigationButton();
|
|
|
|
clearPolylines();
|
|
if (state.currentPolyline) {
|
|
map.removeLayer(state.currentPolyline);
|
|
state.currentPolyline = null;
|
|
}
|
|
state.currentStreetId = null;
|
|
|
|
try {
|
|
const streets = await fetchJson(`${apiBase}/init/groups/${groupId}/streets`);
|
|
state.streets = Array.isArray(streets) ? streets : [];
|
|
indexStreets();
|
|
buildStreetList();
|
|
if (state.streets.length) {
|
|
const first = state.streets[0];
|
|
state.currentStreetId = first.id;
|
|
loadStreetPolyline(first);
|
|
fitToPositionAndPolyline();
|
|
updateWorkButton();
|
|
} else {
|
|
updateWorkButton();
|
|
}
|
|
} catch(e) {
|
|
console.error(e);
|
|
}
|
|
|
|
// Gruppenpositionen in allen mobilen Ansichten anzeigen.
|
|
showAllGroupPositions();
|
|
}
|
|
|
|
function indexStreets() {
|
|
state.streetById.clear();
|
|
state.streets.forEach(s => {
|
|
s.id = Number(s.id);
|
|
state.streetById.set(s.id, s);
|
|
});
|
|
}
|
|
|
|
function buildStreetList() {
|
|
const list = document.getElementById('mobileStreetList');
|
|
if (!list) return;
|
|
list.innerHTML = '';
|
|
state.streets.forEach(street => {
|
|
const li = document.createElement('li');
|
|
const btn = document.createElement('button');
|
|
btn.type = 'button';
|
|
btn.className = 'mobile-street-item';
|
|
if (state.currentStreetId == street.id) btn.classList.add('active');
|
|
btn.textContent = `${mobileStreetDisplayName(street)} (${street.state || 'unbearbeitet'})`;
|
|
btn.addEventListener('click', () => {
|
|
selectStreet(street);
|
|
closeMobileStreetSelect();
|
|
});
|
|
li.appendChild(btn);
|
|
list.appendChild(li);
|
|
});
|
|
}
|
|
|
|
function selectStreet(street) {
|
|
state.currentStreetId = street.id;
|
|
if (state.currentPolyline) {
|
|
map.removeLayer(state.currentPolyline);
|
|
state.currentPolyline = null;
|
|
}
|
|
loadStreetPolyline(street);
|
|
fitToPositionAndPolyline();
|
|
updateWorkButton();
|
|
buildStreetList();
|
|
}
|
|
|
|
function mobileStreetDisplayName(street) {
|
|
if (!street) return '';
|
|
const zusatz = String(street.zusatz || '').trim();
|
|
return zusatz ? `${street.name} ${zusatz}` : String(street.name || '');
|
|
}
|
|
|
|
function getStreetFragments() {
|
|
if (typeof STRASSE2POLYLINES !== 'undefined') return STRASSE2POLYLINES;
|
|
if (typeof Strasse2Polylines !== 'undefined') return Strasse2Polylines;
|
|
return window.STRASSE2POLYLINES || window.Strasse2Polylines || {};
|
|
}
|
|
|
|
function findStreetSegments(fragments, street) {
|
|
if (!street || !street.name) return null;
|
|
|
|
const name = String(street.name).trim();
|
|
const zusatz = String(street.zusatz || '').trim();
|
|
const keys = zusatz ? [`${name} ${zusatz}`, name] : [name];
|
|
|
|
for (const key of keys) {
|
|
if (Array.isArray(fragments[key])) return fragments[key];
|
|
|
|
const lower = key.toLowerCase();
|
|
const matchingKey = Object.keys(fragments).find(
|
|
candidate => candidate.toLowerCase() === lower
|
|
);
|
|
if (matchingKey && Array.isArray(fragments[matchingKey])) {
|
|
return fragments[matchingKey];
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function loadStreetPolyline(street) {
|
|
const currentStreet = street
|
|
|| state.streetById.get(Number(state.currentStreetId));
|
|
if (!currentStreet) return;
|
|
|
|
const fragments = getStreetFragments();
|
|
const segments = findStreetSegments(fragments, currentStreet);
|
|
if (!Array.isArray(segments)) return;
|
|
const color = STREET_COLORS[currentStreet.state] || STREET_COLORS.unbearbeitet;
|
|
const style = {
|
|
color,
|
|
opacity: state.settings.opacity,
|
|
weight: state.settings.weight,
|
|
lineCap: 'round',
|
|
lineJoin: 'round'
|
|
};
|
|
|
|
// Jedes Segment wird als eigene Polyline gezeichnet. Eine gemeinsame
|
|
// LatLng-Liste würde die Segmentgrenzen mit einer zusätzlichen Linie
|
|
// verbinden, die im Straßenverlauf nicht existiert.
|
|
const group = L.featureGroup();
|
|
segments.forEach(seg => {
|
|
if (!Array.isArray(seg)) return;
|
|
const latlngs = [];
|
|
seg.forEach(pt => {
|
|
if (!Array.isArray(pt) || pt.length < 2) return;
|
|
// try lat,lng or lng,lat
|
|
const a = Number(pt[0]), b = Number(pt[1]);
|
|
if (!Number.isFinite(a) || !Number.isFinite(b)) return;
|
|
if (Math.abs(a) <= 90 && Math.abs(b) <= 180) latlngs.push([a,b]);
|
|
else if (Math.abs(b) <= 90 && Math.abs(a) <= 180) latlngs.push([b,a]);
|
|
});
|
|
if (latlngs.length >= 2) {
|
|
L.polyline(latlngs, style).addTo(group);
|
|
}
|
|
});
|
|
if (!group.getLayers().length) return;
|
|
state.currentPolyline = group.addTo(map);
|
|
}
|
|
|
|
function clearPolylines() {
|
|
state.polylinesByStreetId.forEach(lines => {
|
|
if (Array.isArray(lines)) lines.forEach(l => map.removeLayer(l));
|
|
});
|
|
state.polylinesByStreetId.clear();
|
|
}
|
|
|
|
function updateAllPolylineStyles() {
|
|
if (state.currentPolyline) {
|
|
state.currentPolyline.setStyle({opacity: state.settings.opacity, weight: state.settings.weight});
|
|
}
|
|
}
|
|
|
|
function fitToPositionAndPolyline() {
|
|
const bounds = L.latLngBounds([]);
|
|
if (state.currentPolyline) {
|
|
// Seit der segmentweisen Darstellung ist currentPolyline eine
|
|
// FeatureGroup; getBounds() umfasst alle Teilpolylines.
|
|
const polylineBounds = typeof state.currentPolyline.getBounds === 'function'
|
|
? state.currentPolyline.getBounds()
|
|
: null;
|
|
if (polylineBounds && polylineBounds.isValid()) bounds.extend(polylineBounds);
|
|
}
|
|
if (state.userMarker) {
|
|
bounds.extend(state.userMarker.getLatLng());
|
|
}
|
|
if (bounds.isValid()) {
|
|
map.fitBounds(bounds, {padding: [40, 40], maxZoom: 17});
|
|
}
|
|
}
|
|
|
|
function updateWorkButton() {
|
|
const btn = document.getElementById('mobileWorkBtn');
|
|
if (!btn) return;
|
|
btn.disabled = !state.currentStreetId;
|
|
}
|
|
|
|
function openStreetSelectDialog() {
|
|
buildStreetList();
|
|
const dlg = document.getElementById('mobileStreetSelectDialog');
|
|
if (dlg && typeof dlg.showModal === 'function') dlg.showModal();
|
|
else if (dlg) dlg.show();
|
|
}
|
|
|
|
function closeMobileStreetSelect() {
|
|
const dlg = document.getElementById('mobileStreetSelectDialog');
|
|
if (dlg && dlg.open) dlg.close();
|
|
}
|
|
|
|
function openStreetStateDialog() {
|
|
const street = state.streetById.get(Number(state.currentStreetId));
|
|
if (!street) {
|
|
alert('Bitte erst eine Straße auswählen.');
|
|
return;
|
|
}
|
|
document.getElementById('mobileStreetStateTitle').textContent = `Straße: ${mobileStreetDisplayName(street)}`;
|
|
document.getElementById('mobileStreetStateSelect').value = street.state || 'unbearbeitet';
|
|
fillMobileStreetGroupSelect(street.group_id);
|
|
updateMobileStreetGroupVisibility();
|
|
const dlg = document.getElementById('mobileStreetStateDialog');
|
|
if (dlg && typeof dlg.showModal === 'function') dlg.showModal();
|
|
else if (dlg) dlg.show();
|
|
}
|
|
|
|
function closeMobileStreetState() {
|
|
const dlg = document.getElementById('mobileStreetStateDialog');
|
|
if (dlg && dlg.open) dlg.close();
|
|
}
|
|
|
|
function fillMobileStreetGroupSelect(selected) {
|
|
const sel = document.getElementById('mobileStreetGroupSelect');
|
|
if (!sel) return;
|
|
sel.innerHTML = '';
|
|
const empty = document.createElement('option');
|
|
empty.value = '';
|
|
empty.textContent = '-';
|
|
sel.appendChild(empty);
|
|
state.groups.forEach(g => {
|
|
const opt = document.createElement('option');
|
|
opt.value = g.id;
|
|
opt.textContent = g.aliasname || g.id;
|
|
if (Number(selected) === g.id) opt.selected = true;
|
|
sel.appendChild(opt);
|
|
});
|
|
}
|
|
|
|
function updateMobileStreetGroupVisibility() {
|
|
const stateSel = document.getElementById('mobileStreetStateSelect');
|
|
const groupSel = document.getElementById('mobileStreetGroupSelect');
|
|
const label = document.getElementById('mobileStreetGroupLabel');
|
|
const enabled = stateSel && stateSel.value === 'zugewiesen';
|
|
if (groupSel) groupSel.disabled = !enabled;
|
|
if (label) label.style.opacity = enabled ? '1' : '0.5';
|
|
}
|
|
|
|
document.getElementById('mobileStreetStateSelect')?.addEventListener('change', updateMobileStreetGroupVisibility);
|
|
|
|
function saveMobileStreetState() {
|
|
const street = state.streetById.get(Number(state.currentStreetId));
|
|
if (!street) return;
|
|
const newState = document.getElementById('mobileStreetStateSelect').value;
|
|
if (!STREET_STATES.includes(newState)) return;
|
|
let groupId = null;
|
|
if (newState === 'zugewiesen') {
|
|
groupId = Number(document.getElementById('mobileStreetGroupSelect').value) || null;
|
|
if (!groupId) { alert('Bitte eine Gruppe auswählen.'); return; }
|
|
} else if (newState === 'erledigt' && street.group_id) {
|
|
groupId = Number(street.group_id);
|
|
}
|
|
sendWsMessage({
|
|
code: 100,
|
|
msg: JSON.stringify({name: street.name, state: newState, actor: currentAccountId, street_id: street.id, group_id: groupId})
|
|
});
|
|
closeMobileStreetState();
|
|
}
|
|
|
|
function openSettingsDialog() {
|
|
updatePositionSharingUi();
|
|
const opacitySlider = document.getElementById('mobileOpacitySlider');
|
|
const weightSlider = document.getElementById('mobileWeightSlider');
|
|
if (opacitySlider) { opacitySlider.value = state.settings.opacity; document.getElementById('mobileOpacityValue').textContent = state.settings.opacity.toFixed(2); }
|
|
if (weightSlider) { weightSlider.value = state.settings.weight; document.getElementById('mobileWeightValue').textContent = `${state.settings.weight} m`; }
|
|
const baseSel = document.getElementById('mobileBaseLayerSelect');
|
|
if (baseSel) baseSel.value = state.settings.baseLayer;
|
|
const dlg = document.getElementById('mobileSettingsDialog');
|
|
if (dlg && typeof dlg.showModal === 'function') dlg.showModal();
|
|
else if (dlg) dlg.show();
|
|
}
|
|
|
|
function closeMobileSettings() {
|
|
const dlg = document.getElementById('mobileSettingsDialog');
|
|
if (dlg && dlg.open) dlg.close();
|
|
}
|
|
|
|
function startGeolocation() {
|
|
if (!navigator.geolocation) return;
|
|
if (state.userMarker) {
|
|
map.removeLayer(state.userMarker);
|
|
state.userMarker = null;
|
|
}
|
|
|
|
const icon = L.divIcon({
|
|
className: 'mobile-user-marker',
|
|
html: '<div class="mobile-user-heading"></div><div class="mobile-user-dot"></div>',
|
|
iconSize: [16, 16],
|
|
iconAnchor: [8, 8]
|
|
});
|
|
state.userMarker = L.marker(map.getCenter(), {icon, interactive: false}).addTo(map);
|
|
applyUserHeading(state.userHeading);
|
|
|
|
state.watchId = navigator.geolocation.watchPosition((pos) => {
|
|
const lat = Number(pos.coords.latitude);
|
|
const lon = Number(pos.coords.longitude);
|
|
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return;
|
|
|
|
const previous = state.lastKnownPosition;
|
|
state.lastKnownPosition = {
|
|
lat,
|
|
lon,
|
|
accuracy: pos.coords.accuracy
|
|
};
|
|
|
|
updateHeadingFromGps(pos, previous);
|
|
updateOwnPositionMarker(lat, lon);
|
|
|
|
if (viewMode === 'mobile_group') {
|
|
sendAutomaticPosition();
|
|
}
|
|
}, (err) => {
|
|
console.warn(err);
|
|
}, {enableHighAccuracy: true, maximumAge: 2000, timeout: 10000});
|
|
|
|
// Auch bei einem stehengebliebenen Gerät regelmäßig die zuletzt bekannte
|
|
// Position senden, damit die Anzeige im Dispatcher nicht veraltet.
|
|
if (viewMode === 'mobile_group') {
|
|
state.positionSendTimerId = setInterval(
|
|
() => sendAutomaticPosition(),
|
|
AUTO_POSITION_INTERVAL_MS
|
|
);
|
|
}
|
|
|
|
setupDeviceOrientation();
|
|
}
|
|
|
|
function normalizeHeading(value) {
|
|
if (value === null || value === undefined || value === '') return null;
|
|
const heading = Number(value);
|
|
if (!Number.isFinite(heading)) return null;
|
|
return ((heading % 360) + 360) % 360;
|
|
}
|
|
|
|
function applyUserHeading(heading) {
|
|
const normalized = normalizeHeading(heading);
|
|
if (normalized === null) return;
|
|
|
|
state.userHeading = normalized;
|
|
const markerElement = state.userMarker && state.userMarker.getElement();
|
|
if (markerElement) {
|
|
markerElement.style.setProperty('--user-heading', `${normalized}deg`);
|
|
}
|
|
}
|
|
|
|
function bearingBetween(from, to) {
|
|
if (!from || !to) return null;
|
|
const lat1 = Number(from.lat);
|
|
const lon1 = Number(from.lon);
|
|
const lat2 = Number(to.lat);
|
|
const lon2 = Number(to.lon);
|
|
if (![lat1, lon1, lat2, lon2].every(Number.isFinite)) return null;
|
|
|
|
const toRad = (value) => value * Math.PI / 180;
|
|
const y = Math.sin(toRad(lon2 - lon1)) * Math.cos(toRad(lat2));
|
|
const x = Math.cos(toRad(lat1)) * Math.sin(toRad(lat2))
|
|
- Math.sin(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.cos(toRad(lon2 - lon1));
|
|
return normalizeHeading(Math.atan2(y, x) * 180 / Math.PI);
|
|
}
|
|
|
|
function updateHeadingFromGps(position, previous) {
|
|
const coords = position && position.coords;
|
|
if (!coords) return;
|
|
|
|
let heading = normalizeHeading(coords.heading);
|
|
if (heading === null && previous && state.lastKnownPosition) {
|
|
const moved = L.latLng(previous.lat, previous.lon)
|
|
.distanceTo(L.latLng(state.lastKnownPosition.lat, state.lastKnownPosition.lon));
|
|
if (moved >= 3) {
|
|
heading = bearingBetween(previous, state.lastKnownPosition);
|
|
}
|
|
}
|
|
if (heading === null) return;
|
|
|
|
state.lastGpsHeading = heading;
|
|
state.lastGpsAt = Date.now();
|
|
|
|
// Der Kompass hat Vorrang. GPS dient als Rückfallebene, solange keine
|
|
// aktuelle Kompassrichtung vorliegt (z. B. ohne Sensorfreigabe).
|
|
if (Date.now() - state.lastCompassAt > 10000) {
|
|
applyUserHeading(heading);
|
|
}
|
|
}
|
|
|
|
function handleOrientation(event) {
|
|
const hasCompassHeading = typeof event.webkitCompassHeading === 'number'
|
|
&& Number.isFinite(event.webkitCompassHeading);
|
|
const isAbsolute = hasCompassHeading
|
|
|| event.type === 'deviceorientationabsolute'
|
|
|| event.absolute === true;
|
|
|
|
let heading = null;
|
|
if (hasCompassHeading) {
|
|
heading = event.webkitCompassHeading;
|
|
} else if (typeof event.alpha === 'number'
|
|
&& Number.isFinite(event.alpha)
|
|
&& (isAbsolute || !state.absoluteCompassAvailable)) {
|
|
// DeviceOrientationEvent.alpha dreht gegen den Uhrzeigersinn.
|
|
// Relative Werte dienen nur als Rückfall, solange keine absolute
|
|
// Kompassrichtung verfügbar ist.
|
|
heading = 360 - event.alpha;
|
|
}
|
|
|
|
const normalized = normalizeHeading(heading);
|
|
if (normalized === null) return;
|
|
|
|
if (isAbsolute) state.absoluteCompassAvailable = true;
|
|
state.lastCompassHeading = normalized;
|
|
state.lastCompassAt = Date.now();
|
|
applyUserHeading(normalized);
|
|
}
|
|
|
|
function setupDeviceOrientation() {
|
|
if (!window.DeviceOrientationEvent || state.orientationListenersBound) return;
|
|
|
|
const addListeners = () => {
|
|
if (state.orientationListenersBound) return;
|
|
window.addEventListener('deviceorientationabsolute', handleOrientation, true);
|
|
window.addEventListener('deviceorientation', handleOrientation, true);
|
|
state.orientationListenersBound = true;
|
|
};
|
|
|
|
if (typeof DeviceOrientationEvent.requestPermission === 'function') {
|
|
// iOS verlangt die Freigabe aus einer Nutzergeste. Die erste Berührung
|
|
// der Karte bzw. Seite wird dafür verwendet.
|
|
const requestPermission = () => {
|
|
if (state.orientationPermissionRequested) return;
|
|
state.orientationPermissionRequested = true;
|
|
DeviceOrientationEvent.requestPermission()
|
|
.then((result) => {
|
|
if (result === 'granted') addListeners();
|
|
})
|
|
.catch((error) => {
|
|
console.warn('Kompassfreigabe nicht erteilt.', error);
|
|
});
|
|
};
|
|
document.addEventListener('click', requestPermission, {once: true, passive: true});
|
|
} else {
|
|
addListeners();
|
|
}
|
|
}
|
|
|
|
function showAllGroupPositions() {
|
|
// Remove old markers
|
|
state.groupMarkers.forEach(m => map.removeLayer(m));
|
|
state.groupMarkers.clear();
|
|
|
|
state.groups.forEach(group => {
|
|
if (group.last_lat !== null && group.last_lat !== undefined && group.last_lon !== null && group.last_lon !== undefined) {
|
|
const lat = Number(group.last_lat), lon = Number(group.last_lon);
|
|
if (!isFinite(lat) || !isFinite(lon)) return;
|
|
const color = getGroupColor(group.id);
|
|
const icon = L.divIcon({
|
|
className: 'mobile-group-marker',
|
|
html: `<div class="mobile-group-dot" style="--marker-color:${color}"></div>`,
|
|
iconSize: [32, 32],
|
|
iconAnchor: [16, 16]
|
|
});
|
|
const marker = L.marker([lat, lon], {icon}).addTo(map);
|
|
marker.on('click', () => openMobileGroupInfo(group.id));
|
|
state.groupMarkers.set(group.id, marker);
|
|
}
|
|
});
|
|
|
|
updateNavigationButton();
|
|
}
|
|
|
|
function formatGroupPositionAge(group, now = Date.now()) {
|
|
const timestamp = getGroupPositionTimestamp(group);
|
|
if (!timestamp) return 'unbekannt';
|
|
|
|
const age = Math.max(0, now - timestamp);
|
|
if (age <= GROUP_POSITION_LIVE_MS) return 'live';
|
|
if (age <= GROUP_POSITION_RECENT_MS) return 'aktuell';
|
|
|
|
const totalMinutes = Math.floor(age / 60000);
|
|
const hours = Math.floor(totalMinutes / 60);
|
|
const minutes = totalMinutes % 60;
|
|
return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')} alt`;
|
|
}
|
|
|
|
function openMobileGroupInfo(groupId) {
|
|
const group = state.groupById.get(Number(groupId));
|
|
if (!group) return;
|
|
|
|
const alias = String(group.aliasname || '').trim();
|
|
const aliasElement = document.getElementById('mobileGroupInfoAlias');
|
|
if (aliasElement) {
|
|
aliasElement.textContent = alias || `Gruppe ${group.id}`;
|
|
}
|
|
|
|
const ageElement = document.getElementById('mobileGroupInfoAge');
|
|
if (ageElement) {
|
|
ageElement.textContent = formatGroupPositionAge(group);
|
|
const timestamp = getGroupPositionTimestamp(group);
|
|
ageElement.title = timestamp
|
|
? `Letzte Positionsmeldung: ${new Date(timestamp).toLocaleString('de-DE')}`
|
|
: 'Keine Positionsmeldung vorhanden';
|
|
}
|
|
|
|
const dialog = document.getElementById('mobileGroupInfoDialog');
|
|
if (dialog && !dialog.open) {
|
|
if (typeof dialog.showModal === 'function') dialog.showModal();
|
|
else dialog.show();
|
|
}
|
|
}
|
|
|
|
function closeMobileGroupInfo() {
|
|
const dialog = document.getElementById('mobileGroupInfoDialog');
|
|
if (dialog && dialog.open) dialog.close();
|
|
}
|
|
|
|
function getGroupColor(id) {
|
|
const hue = Math.round((Number(id) * 137.508) % 360);
|
|
return `hsl(${hue}, 72%, 45%)`;
|
|
}
|
|
|
|
function getGroupCoordinates(group) {
|
|
if (!group) return null;
|
|
const hasLat = group.last_lat !== null && group.last_lat !== undefined && String(group.last_lat).trim() !== '';
|
|
const hasLon = group.last_lon !== null && group.last_lon !== undefined && String(group.last_lon).trim() !== '';
|
|
if (!hasLat || !hasLon) return null;
|
|
|
|
const lat = Number(group.last_lat);
|
|
const lon = Number(group.last_lon);
|
|
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
|
|
return {lat, lon};
|
|
}
|
|
|
|
function getGroupPositionTimestamp(group) {
|
|
if (!group) return null;
|
|
|
|
const parsed = parseFlexibleTimestamp(group.last_pos_at);
|
|
if (parsed) {
|
|
group.last_pos_ts = parsed;
|
|
return parsed;
|
|
}
|
|
|
|
return Number.isFinite(group.last_pos_ts) && group.last_pos_ts > 0
|
|
? group.last_pos_ts
|
|
: null;
|
|
}
|
|
|
|
function isGroupPositionFresh(group, now = Date.now()) {
|
|
if (!getGroupCoordinates(group)) return false;
|
|
const timestamp = getGroupPositionTimestamp(group);
|
|
if (!timestamp) return false;
|
|
return Math.max(0, now - timestamp) < NAVIGATION_MAX_AGE_MS;
|
|
}
|
|
|
|
function updateNavigationButton() {
|
|
if (viewMode !== 'mobile_dispatcher') return;
|
|
|
|
const button = document.getElementById('mobileNavigateBtn');
|
|
if (!button) return;
|
|
|
|
const group = state.groupById.get(Number(state.currentGroupId));
|
|
const visible = isGroupPositionFresh(group);
|
|
button.hidden = !visible;
|
|
|
|
if (visible) {
|
|
const name = groupDisplayName(group);
|
|
const label = name === 'Gruppe'
|
|
? 'Navigation starten'
|
|
: `Navigation zu ${name} starten`;
|
|
button.title = label;
|
|
button.setAttribute('aria-label', label);
|
|
}
|
|
}
|
|
|
|
function startNavigationButtonWatcher() {
|
|
if (viewMode !== 'mobile_dispatcher') return;
|
|
|
|
const button = document.getElementById('mobileNavigateBtn');
|
|
if (!button) return;
|
|
|
|
updateNavigationButton();
|
|
if (state.navigationTimerId !== null) {
|
|
clearInterval(state.navigationTimerId);
|
|
}
|
|
state.navigationTimerId = setInterval(updateNavigationButton, NAVIGATION_REFRESH_MS);
|
|
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (!document.hidden) updateNavigationButton();
|
|
});
|
|
}
|
|
|
|
function detectNavigationPlatform() {
|
|
const userAgent = navigator.userAgent || '';
|
|
const platform = navigator.platform || '';
|
|
const maxTouchPoints = Number(navigator.maxTouchPoints) || 0;
|
|
const isIpadOs = platform === 'MacIntel' && maxTouchPoints > 1;
|
|
|
|
if (/iPad|iPhone|iPod/i.test(userAgent) || isIpadOs) return 'ios';
|
|
if (/Android/i.test(userAgent)) return 'android';
|
|
return 'other';
|
|
}
|
|
|
|
function buildNavigationUrl(lat, lon) {
|
|
const coordinates = `${lat},${lon}`;
|
|
const platform = detectNavigationPlatform();
|
|
|
|
if (platform === 'ios') {
|
|
return `https://maps.apple.com/?daddr=${coordinates}&dirflg=d`;
|
|
}
|
|
if (platform === 'android') {
|
|
return `https://www.google.com/maps/dir/?api=1&destination=${coordinates}&travelmode=driving`;
|
|
}
|
|
return `geo:${coordinates}?q=${coordinates}(Zielort)`;
|
|
}
|
|
|
|
function openGroupNavigation() {
|
|
const group = state.groupById.get(Number(state.currentGroupId));
|
|
if (!isGroupPositionFresh(group)) {
|
|
updateNavigationButton();
|
|
return;
|
|
}
|
|
|
|
const coordinates = getGroupCoordinates(group);
|
|
if (!coordinates) {
|
|
updateNavigationButton();
|
|
return;
|
|
}
|
|
|
|
window.location.href = buildNavigationUrl(coordinates.lat, coordinates.lon);
|
|
}
|
|
|
|
function setMobileWsStatus(label, status) {
|
|
const element = document.getElementById('mobileWsStatus');
|
|
if (!element) return;
|
|
|
|
element.textContent = `CMB ${label}`;
|
|
element.title = `WebSocket: ${label}`;
|
|
element.classList.remove('is-connected', 'is-connecting', 'is-disconnected', 'is-error');
|
|
element.classList.add(`is-${status}`);
|
|
}
|
|
|
|
function scheduleMobileReconnect() {
|
|
// Im Hintergrund nicht in einer Reconnect-Schleife hängen bleiben. Die
|
|
// Verbindung wird beim nächsten Sichtbarwerden wieder aufgebaut.
|
|
if (document.hidden) return;
|
|
if (state.reconnectTimer) return;
|
|
state.reconnectTimer = setTimeout(() => {
|
|
state.reconnectTimer = null;
|
|
connectWebSocket();
|
|
}, 3000);
|
|
}
|
|
|
|
function checkWsSequence(message) {
|
|
if (!Object.prototype.hasOwnProperty.call(message, 'seq')) return;
|
|
|
|
const seq = Number(message.seq);
|
|
if (!Number.isFinite(seq) || seq <= 0) return;
|
|
|
|
const lastSeq = state.lastWsSeq;
|
|
if (lastSeq !== null && seq !== lastSeq + 1) {
|
|
const text = `Die WebSocket-Verbindung hat Nachrichten verloren `
|
|
+ `(erwartet: ${lastSeq + 1}, empfangen: ${seq}). `
|
|
+ 'Bitte lade die Seite neu, damit alle Änderungen sichtbar werden.';
|
|
if (typeof window.showReloadNotice === 'function') {
|
|
window.showReloadNotice(text);
|
|
} else {
|
|
alert(`${text}\n\nBitte die Webseite neu laden.`);
|
|
}
|
|
}
|
|
|
|
// Bei einer Dublette nicht rückwärts zählen; so löst nicht jede folgende
|
|
// Nachricht erneut einen vermeintlichen Sprung aus.
|
|
state.lastWsSeq = lastSeq === null ? seq : Math.max(lastSeq, seq);
|
|
}
|
|
|
|
function connectWebSocket() {
|
|
if (state.ws && (state.ws.readyState === WebSocket.OPEN || state.ws.readyState === WebSocket.CONNECTING)) return;
|
|
|
|
setMobileWsStatus('verbinde …', 'connecting');
|
|
fetchJson(`${apiBase}/auth/ws-token`).then(res => {
|
|
const token = res.token;
|
|
const ws = new WebSocket(wsUrl);
|
|
state.ws = ws;
|
|
ws.addEventListener('open', () => {
|
|
// Der Server bestätigt den Handshake mit Code 0. Bis dahin werden
|
|
// fachliche Nachrichten im Outbox-Puffer gesammelt.
|
|
state.authenticated = false;
|
|
setMobileWsStatus('Anmeldung …', 'connecting');
|
|
ws.send(JSON.stringify({
|
|
code: 0,
|
|
msg: {
|
|
token: token,
|
|
client_type: clientType
|
|
},
|
|
client_id: window.CMBNET_CLIENT_ID
|
|
|| window.CMBNET_CLIENT_SESSION_ID
|
|
|| ''
|
|
}));
|
|
|
|
// Fallback für ältere Server, die noch keine Code-0-Bestätigung
|
|
// senden. Die Code-0-Nachricht wurde bereits als erstes gesendet,
|
|
// daher ist die Reihenfolge auf dem Socket weiterhin korrekt.
|
|
setTimeout(() => {
|
|
if (state.ws === ws
|
|
&& ws.readyState === WebSocket.OPEN
|
|
&& !state.authenticated) {
|
|
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);
|
|
});
|
|
ws.addEventListener('message', handleWs);
|
|
ws.addEventListener('close', event => {
|
|
if (state.ws !== ws) return;
|
|
console.warn('[WS] Verbindung geschlossen', {
|
|
code: event.code,
|
|
reason: event.reason,
|
|
wasClean: event.wasClean
|
|
});
|
|
state.authenticated = false;
|
|
setMobileWsStatus('getrennt', 'disconnected');
|
|
scheduleMobileReconnect();
|
|
});
|
|
ws.addEventListener('error', event => {
|
|
if (state.ws !== ws) return;
|
|
console.warn('[WS] Verbindungsfehler', event);
|
|
setMobileWsStatus('Fehler', 'error');
|
|
});
|
|
}).catch(() => {
|
|
setMobileWsStatus('Token-Fehler', 'error');
|
|
scheduleMobileReconnect();
|
|
});
|
|
}
|
|
|
|
function sendChat() {
|
|
const input = document.getElementById('mobileChatInput');
|
|
if (!input) return;
|
|
const text = input.value.trim();
|
|
if (!text) return;
|
|
|
|
if (viewMode === 'mobile_group' && state.currentGroupId) {
|
|
sendWsMessage({code: 2000, msg: JSON.stringify({group_id: state.currentGroupId, text})});
|
|
} else if (viewMode === 'mobile_dispatcher') {
|
|
// For dispatcher mobile, could send 1000 broadcast or 1100 - follow general behavior
|
|
sendWsMessage({code: 1000, msg: JSON.stringify({text})});
|
|
}
|
|
input.value = '';
|
|
}
|
|
|
|
function addChatEntry(entry) {
|
|
const key = `${entry.code}|${entry.sender_id}|${entry.ts}|${entry.text}`;
|
|
if (state.chatKeys.has(key)) return false;
|
|
state.chatKeys.add(key);
|
|
state.chatMessages.push(entry);
|
|
renderChat();
|
|
return true;
|
|
}
|
|
|
|
function renderChat() {
|
|
const cont = document.getElementById('mobileChatMessages');
|
|
if (!cont) return;
|
|
cont.innerHTML = '';
|
|
state.chatMessages.slice().sort((a,b) => a.ts - b.ts).forEach(entry => {
|
|
const card = document.createElement('div');
|
|
card.className = 'mobile-chat-card';
|
|
if (entry.sender_id == currentAccountId) card.classList.add('own');
|
|
const meta = document.createElement('div');
|
|
meta.className = 'mobile-chat-meta';
|
|
meta.textContent = new Date(entry.ts).toLocaleString('de-DE');
|
|
const fromto = document.createElement('div');
|
|
fromto.className = 'mobile-chat-fromto';
|
|
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;
|
|
card.append(meta, fromto, text);
|
|
cont.appendChild(card);
|
|
});
|
|
cont.scrollTop = cont.scrollHeight;
|
|
}
|
|
|
|
function playSound() {
|
|
try {
|
|
if (audioCtx.state === 'suspended') audioCtx.resume();
|
|
const osc = audioCtx.createOscillator();
|
|
const gain = audioCtx.createGain();
|
|
osc.connect(gain);
|
|
gain.connect(audioCtx.destination);
|
|
osc.frequency.setValueAtTime(880, audioCtx.currentTime);
|
|
osc.frequency.exponentialRampToValueAtTime(440, audioCtx.currentTime + 0.15);
|
|
gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
|
|
gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.3);
|
|
osc.start(audioCtx.currentTime);
|
|
osc.stop(audioCtx.currentTime + 0.3);
|
|
} catch(e) {}
|
|
}
|
|
|
|
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 || appTitle, options);
|
|
return;
|
|
}
|
|
}
|
|
new Notification(senderName || appTitle, options);
|
|
} catch (error) {
|
|
// Benachrichtigungen sind optional.
|
|
}
|
|
}
|
|
|
|
function showIncomingChatDialog(text, senderName) {
|
|
const dialog = document.getElementById('mobileNotificationDialog');
|
|
if (!dialog) return;
|
|
|
|
const title = document.getElementById('mobileNotificationTitle');
|
|
const body = document.getElementById('mobileNotificationText');
|
|
if (title) title.textContent = senderName || 'Neue Nachricht';
|
|
if (body) body.textContent = text || '';
|
|
|
|
if (!dialog.open) {
|
|
if (typeof dialog.showModal === 'function') dialog.showModal();
|
|
else if (typeof dialog.show === 'function') dialog.show();
|
|
}
|
|
}
|
|
|
|
function closeMobileNotification() {
|
|
const dialog = document.getElementById('mobileNotificationDialog');
|
|
if (dialog && dialog.open) dialog.close();
|
|
}
|
|
|
|
function openMobileChatFromNotification() {
|
|
closeMobileNotification();
|
|
const chatTab = document.querySelector('.mobile-tab[data-tab="chat"]');
|
|
if (chatTab) chatTab.click();
|
|
}
|
|
|
|
function extractText(msg) {
|
|
if (!msg) return '';
|
|
if (typeof msg === 'object') {
|
|
if (msg.text) return String(msg.text);
|
|
if (msg.msg) return extractText(msg.msg);
|
|
return '';
|
|
}
|
|
if (typeof msg === 'string') {
|
|
try {
|
|
const p = JSON.parse(msg);
|
|
if (typeof p === 'object') return extractText(p);
|
|
} catch(e) {}
|
|
const idx = msg.indexOf(':');
|
|
if (idx > 0 && idx < 80) return msg.slice(idx+1).trim();
|
|
return 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 parseFlexibleTimestamp(value) {
|
|
if (value === null || value === undefined || value === '') return null;
|
|
if (typeof value === 'number') return normalizeTs(value);
|
|
|
|
const text = String(value).trim();
|
|
if (/^\d+(?:\.\d+)?$/.test(text)) return normalizeTs(Number(text));
|
|
|
|
let iso = text.replace(' ', 'T');
|
|
if (!/[zZ]|[+-]\d{2}:?\d{2}$/.test(iso)) {
|
|
iso += 'Z';
|
|
}
|
|
|
|
const parsed = Date.parse(iso);
|
|
return Number.isNaN(parsed) ? null : parsed;
|
|
}
|
|
|
|
function applyMobileStreetUpdate(payload) {
|
|
if (!payload) return;
|
|
|
|
const streetId = Number(payload.street_id);
|
|
const hasGroup = Object.prototype.hasOwnProperty.call(payload, 'group_id');
|
|
const newGroupId = hasGroup && payload.group_id !== null && payload.group_id !== ''
|
|
? Number(payload.group_id)
|
|
: null;
|
|
const ownGroupId = Number(state.currentGroupId) || null;
|
|
|
|
let street = Number.isFinite(streetId) ? state.streetById.get(streetId) : null;
|
|
if (!street && payload.name) {
|
|
street = state.streets.find(item => item.name === payload.name) || null;
|
|
}
|
|
|
|
if (!street) {
|
|
// Eine Straße kann durch eine Zuweisung neu in der Gruppe auftauchen.
|
|
// Der Broker liefert Name, ID, Status und Zielgruppe im Payload mit.
|
|
if (ownGroupId && newGroupId === ownGroupId
|
|
&& Number.isFinite(streetId) && payload.name) {
|
|
street = {
|
|
id: streetId,
|
|
name: payload.name,
|
|
state: payload.state || 'zugewiesen',
|
|
group_id: ownGroupId
|
|
};
|
|
state.streets.push(street);
|
|
state.streetById.set(street.id, street);
|
|
} else {
|
|
console.warn('[WS] Code 100: Straße nicht im lokalen Zustand', payload);
|
|
return;
|
|
}
|
|
} else {
|
|
if (payload.state) street.state = payload.state;
|
|
if (hasGroup) street.group_id = newGroupId;
|
|
|
|
const index = state.streets.indexOf(street);
|
|
if (ownGroupId && hasGroup && newGroupId !== ownGroupId && index >= 0) {
|
|
// Die Straße wurde einer anderen Gruppe zugewiesen und gehört
|
|
// nicht mehr zur ToDo-Liste dieser Webview.
|
|
state.streets.splice(index, 1);
|
|
state.streetById.delete(street.id);
|
|
} else if (ownGroupId && newGroupId === ownGroupId && index < 0) {
|
|
state.streets.push(street);
|
|
state.streetById.set(street.id, street);
|
|
}
|
|
}
|
|
|
|
const isCurrent = state.currentStreetId == street.id;
|
|
if (isCurrent && state.streetById.has(street.id)) {
|
|
if (state.currentPolyline) {
|
|
state.currentPolyline.setStyle({
|
|
color: STREET_COLORS[street.state] || STREET_COLORS.unbearbeitet
|
|
});
|
|
}
|
|
|
|
const dialog = document.getElementById('mobileStreetStateDialog');
|
|
if (dialog && dialog.open) {
|
|
document.getElementById('mobileStreetStateTitle').textContent =
|
|
`Straße: ${mobileStreetDisplayName(street)}`;
|
|
document.getElementById('mobileStreetStateSelect').value =
|
|
street.state || 'unbearbeitet';
|
|
fillMobileStreetGroupSelect(street.group_id);
|
|
updateMobileStreetGroupVisibility();
|
|
}
|
|
} else if (isCurrent && !state.streetById.has(street.id)) {
|
|
if (state.currentPolyline) {
|
|
map.removeLayer(state.currentPolyline);
|
|
state.currentPolyline = null;
|
|
}
|
|
state.currentStreetId = null;
|
|
closeMobileStreetState();
|
|
if (state.streets.length) {
|
|
selectStreet(state.streets[0]);
|
|
}
|
|
}
|
|
|
|
buildStreetList();
|
|
updateWorkButton();
|
|
}
|
|
|
|
function applyMobileGroupStateUpdate(message) {
|
|
const payload = typeof message.msg === 'string'
|
|
? JSON.parse(message.msg)
|
|
: message.msg;
|
|
if (!payload) return;
|
|
|
|
const groupId = Number(payload.group_id ?? message.receiver_id);
|
|
const group = state.groupById.get(groupId);
|
|
if (!group) {
|
|
console.warn('[WS] Code 200: Gruppe nicht im lokalen Zustand', payload);
|
|
return;
|
|
}
|
|
|
|
if (payload.state) group.state = payload.state;
|
|
|
|
if (viewMode === 'mobile_dispatcher') {
|
|
const select = document.getElementById('mobileGroupSelect');
|
|
const option = select
|
|
? select.querySelector(`option[value="${group.id}"]`)
|
|
: null;
|
|
if (option) {
|
|
option.textContent = `${group.aliasname || group.id} (${group.state || 'offen'})`;
|
|
}
|
|
updateNavigationButton();
|
|
}
|
|
}
|
|
|
|
function handleWs(event) {
|
|
let message;
|
|
try { message = JSON.parse(event.data); } catch(e) { return; }
|
|
|
|
checkWsSequence(message);
|
|
console.debug('[WS RX]', message);
|
|
|
|
if (message.code === 0) {
|
|
state.authenticated = true;
|
|
setMobileWsStatus('verbunden', 'connected');
|
|
flushWsOutbox();
|
|
resolveWsAuthentication();
|
|
// Token-Aktualität erhalten, damit die FCM-Aufbewahrung auch bei
|
|
// lange laufenden PWAs nicht abläuft.
|
|
syncPushRegistration();
|
|
} else if (message.code === 1) {
|
|
setMobileWsStatus('verbunden', 'connected');
|
|
if (state.ws && state.ws.readyState === WebSocket.OPEN) {
|
|
state.ws.send(JSON.stringify({code: 2, msg: 'pong'}));
|
|
}
|
|
} else if (message.code === 99) {
|
|
const text = typeof message.msg === 'string'
|
|
? message.msg
|
|
: extractText(message.msg);
|
|
if (typeof window.showReloadNotice === 'function') {
|
|
window.showReloadNotice(text);
|
|
} else {
|
|
alert(`${text}\n\nBitte die Webseite neu laden.`);
|
|
}
|
|
} else if (message.code === 100) {
|
|
// Street update
|
|
try {
|
|
const p = typeof message.msg === 'string' ? JSON.parse(message.msg) : message.msg;
|
|
applyMobileStreetUpdate(p);
|
|
} catch(e) {
|
|
console.warn('[WS] Code 100 konnte nicht verarbeitet werden', e, message.msg);
|
|
}
|
|
} else if (message.code === 200) {
|
|
// Group state update
|
|
try {
|
|
applyMobileGroupStateUpdate(message);
|
|
} catch(e) {
|
|
console.warn('[WS] Code 200 konnte nicht verarbeitet werden', e, message.msg);
|
|
}
|
|
} else if (message.code === 300) {
|
|
// Group position
|
|
try {
|
|
const p = typeof message.msg === 'string' ? JSON.parse(message.msg) : message.msg;
|
|
const gid = Number(p.group_id || message.receiver_id);
|
|
const g = state.groupById.get(gid);
|
|
const lat = Number(p.lat);
|
|
const lon = Number(p.lon);
|
|
if (g && Number.isFinite(lat) && Number.isFinite(lon)
|
|
&& p.lat !== null && p.lon !== null) {
|
|
g.last_lat = lat;
|
|
g.last_lon = lon;
|
|
g.last_pos_ts = parseFlexibleTimestamp(p.ts) || Date.now();
|
|
g.last_pos_at = new Date(g.last_pos_ts).toISOString();
|
|
showAllGroupPositions();
|
|
} else if (!g) {
|
|
console.warn('[WS] Code 300: Gruppe nicht im lokalen Zustand', p);
|
|
}
|
|
} catch(e) {}
|
|
} else if (Number(message.code) >= 1000) {
|
|
// Chat messages
|
|
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 gid = Number(payload?.group_id ?? message.receiver_id);
|
|
const ownGroupId = Number(state.currentGroupId);
|
|
if (Number.isFinite(gid) && gid > 0 && ownGroupId && gid !== ownGroupId) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
const senderName = getSenderName(message, payload);
|
|
const isNewMessage = addChatEntry({
|
|
sender_id: message.sender_id,
|
|
code: message.code,
|
|
ts: normalizeTs(message.ts) || Date.now(),
|
|
text,
|
|
fromName: senderName,
|
|
toName: getReceiverName(message, payload)
|
|
});
|
|
|
|
// Wiederholt zugestellte Nachrichten (z. B. nach einem Reconnect)
|
|
// dürfen weder Ton noch Dialog oder Systembenachrichtigung erneut
|
|
// auslösen.
|
|
if (isNewMessage && Number(message.sender_id) !== currentAccountId) {
|
|
playSound();
|
|
// In-App-Dialog und, sofern erlaubt, Systembenachrichtigung.
|
|
showIncomingChatDialog(text, senderName);
|
|
showChatPopup(text, senderName);
|
|
}
|
|
}
|
|
}
|
|
|
|
window.openMobileStreetSelect = openStreetSelectDialog;
|
|
window.closeMobileStreetSelect = closeMobileStreetSelect;
|
|
window.closeMobileStreetState = closeMobileStreetState;
|
|
window.saveMobileStreetState = saveMobileStreetState;
|
|
window.closeMobileSettings = closeMobileSettings;
|
|
window.closeMobileInstall = closeMobileInstall;
|
|
window.closeMobileNotification = closeMobileNotification;
|
|
window.openMobileChatFromNotification = openMobileChatFromNotification;
|