From 91ff49b6882b6e8218cb08364ceacd96f1df07f3 Mon Sep 17 00:00:00 2001 From: Thomas Date: Fri, 30 Oct 2026 11:31:34 +0100 Subject: [PATCH] Positionsupdate und NAvigations Deeplink in mobilen Views --- CMBNet/cmbnet/ws/broker.py | 27 ++- CMBNet/static/css/mobile.css | 66 ++++++ CMBNet/static/js/sw.js | 2 +- CMBNet/static/js/views/mobile.js | 299 ++++++++++++++++++++++++- CMBNet/templates/dispatcher_mobil.html | 6 + CMBNet/templates/gruppen.html | 11 + 6 files changed, 395 insertions(+), 16 deletions(-) diff --git a/CMBNet/cmbnet/ws/broker.py b/CMBNet/cmbnet/ws/broker.py index c2d73b8..bdc56d2 100644 --- a/CMBNet/cmbnet/ws/broker.py +++ b/CMBNet/cmbnet/ws/broker.py @@ -542,28 +542,35 @@ class WebSocketBroker: # manipulierbare Client-Zeitangaben verfälscht wird. pos_at = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S') ts_ms = int(time.time() * 1000) + automatic = payload.get('automatic') is True db.execute( 'UPDATE groups SET last_lat = ?, last_lon = ?, last_pos_at = ?, ' 'updated_at = CURRENT_TIMESTAMP WHERE id = ? AND tenant_id = ?', (lat, lon, pos_at, group_id, tenant_id) ) - db.execute( - '''INSERT INTO group_state_history - (tenant_id, group_id, from_state, to_state, last_lat, last_lon, - last_pos_at, actor_account_id) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)''', - (tenant_id, group_id, group['state'], group['state'], - lat, lon, pos_at, sender['id']) - ) + # Automatische Positionsmeldungen der Gruppen-View aktualisieren nur + # die Live-Position. Die Historie und das Transaktionslog bleiben + # manuellen Positionsänderungen vorbehalten, damit sie nicht durch + # regelmäßige Telemetrie geflutet werden. + if not automatic: + db.execute( + '''INSERT INTO group_state_history + (tenant_id, group_id, from_state, to_state, last_lat, last_lon, + last_pos_at, actor_account_id) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)''', + (tenant_id, group_id, group['state'], group['state'], + lat, lon, pos_at, sender['id']) + ) db.commit() GroupsService.update_cache_entry(tenant_id, group_id, { 'last_lat': lat, 'last_lon': lon, 'last_pos_at': pos_at }) - self._log_business(tenant_id, sender['id'], 'group.position_change', 'group', - group_id, {'lat': lat, 'lon': lon}) + if not automatic: + self._log_business(tenant_id, sender['id'], 'group.position_change', 'group', + group_id, {'lat': lat, 'lon': lon}) message.receiver_id = group_id # Auch der Nachrichten-Zeitstempel wird serverseitig gesetzt, damit diff --git a/CMBNet/static/css/mobile.css b/CMBNet/static/css/mobile.css index c036e64..db89458 100644 --- a/CMBNet/static/css/mobile.css +++ b/CMBNet/static/css/mobile.css @@ -183,6 +183,67 @@ body.mobile-page main.container { z-index: 1000; } +.mobile-position-btn { + position: absolute; + top: 0.75rem; + left: 0.75rem; + width: auto; + margin: 0; + padding: 0.5rem 0.9rem; + border-radius: 999px; + border: 1px solid var(--mobile-accent); + background: var(--mobile-accent); + color: #fff; + box-shadow: 0 8px 24px rgba(37, 99, 235, 0.3); + font-size: 0.85rem; + font-weight: 600; + z-index: 900; +} + +.mobile-position-btn:hover, +.mobile-position-btn:focus-visible { + border-color: var(--mobile-accent); + background: var(--mobile-accent); + color: #fff; + filter: brightness(1.06); +} + +.mobile-nav-btn { + position: absolute; + top: 0.75rem; + right: 0.7rem; + width: 3rem; + height: 3rem; + border-radius: 50%; + border: none; + background: var(--mobile-accent); + color: #fff; + display: none; + align-items: center; + justify-content: center; + margin: 0; + padding: 0; + box-shadow: 0 8px 24px rgba(37, 99, 235, 0.35); + z-index: 1000; +} + +.mobile-nav-btn:not([hidden]) { + display: flex; +} + +.mobile-nav-btn:hover, +.mobile-nav-btn:focus-visible { + border-color: var(--mobile-accent); + background: var(--mobile-accent); + color: #fff; + filter: brightness(1.06); +} + +.mobile-nav-btn svg { + width: 1.35rem; + height: 1.35rem; +} + .mobile-chat-messages { flex: 1 1 auto; min-height: 0; @@ -299,6 +360,11 @@ html[data-theme="dark"] .mobile-chat-card.own { font-size: 0.85rem; } +.mobile-settings-row input[role="switch"] { + flex: 0 0 auto; + margin: 0; +} + .mobile-settings-button.is-active { background: var(--mobile-accent); border-color: var(--mobile-accent); diff --git a/CMBNet/static/js/sw.js b/CMBNet/static/js/sw.js index 14355d6..150748d 100644 --- a/CMBNet/static/js/sw.js +++ b/CMBNet/static/js/sw.js @@ -5,7 +5,7 @@ * damit er sowohl die mobilen Views als auch die statischen Assets * kontrolliert. Der Cache-Name wird pro App-Wurzel gebildet. */ -const VERSION = 'cmbnet-pwa-v4'; +const VERSION = 'cmbnet-pwa-v6'; const BASE = new URL('./', self.location).href; const SHELL_CACHE = `${VERSION}-shell`; const TILE_CACHE = `${VERSION}-tiles`; diff --git a/CMBNet/static/js/views/mobile.js b/CMBNet/static/js/views/mobile.js index 03de2bf..9352320 100644 --- a/CMBNet/static/js/views/mobile.js +++ b/CMBNet/static/js/views/mobile.js @@ -14,9 +14,14 @@ const appTitle = window.CMBNET_APP_TITLE || '20*C+M+B+27'; const DEFAULT_SETTINGS = { opacity: 0.7, weight: 20, - baseLayer: 'osm' + baseLayer: 'osm', + autoSendPosition: true }; +const AUTO_POSITION_INTERVAL_MS = 30000; +const NAVIGATION_MAX_AGE_MS = 30 * 60 * 1000; +const NAVIGATION_REFRESH_MS = 15000; + const STREET_STATES = ['unbearbeitet', 'zugewiesen', 'erledigt']; const STREET_COLORS = { unbearbeitet: '#1f6feb', @@ -45,7 +50,11 @@ const state = { chatKeys: new Set(), userMarker: null, userArrow: null, - watchId: null + watchId: null, + positionSendTimerId: null, + navigationTimerId: null, + lastKnownPosition: null, + lastPositionSentAt: 0 }; const AudioContext = window.AudioContext || window.webkitAudioContext; @@ -108,11 +117,18 @@ async function initMobile() { } 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(); }); } @@ -269,6 +285,7 @@ function loadSettings() { 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 !== false; } } catch(e) {} } @@ -279,6 +296,105 @@ function saveSettings() { } 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 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; + if (!state.ws || state.ws.readyState !== WebSocket.OPEN || !state.authenticated) return false; + + state.ws.send(JSON.stringify({ + code: 300, + msg: JSON.stringify({ + group_id: state.currentGroupId, + lat, + lon, + ts: Date.now(), + actor: currentAccountId, + automatic: automatic === true + }) + })); + 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); + state.lastKnownPosition = { + lat, + lon, + accuracy: position.coords.accuracy + }; + 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); @@ -327,6 +443,9 @@ function bindButtons() { 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) { @@ -368,12 +487,30 @@ function bindButtons() { 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(); + if (state.settings.autoSendPosition && state.lastKnownPosition) { + state.lastPositionSentAt = 0; + sendAutomaticPosition(); + } + }); + } + const sendPositionBtn = document.getElementById('mobileSendPositionBtn'); + if (sendPositionBtn) { + sendPositionBtn.addEventListener('click', sendPositionNow); + } + 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); }); } @@ -522,6 +659,7 @@ async function loadGroupData(groupId) { state.currentGroupId = groupId; const sel = document.getElementById('mobileGroupSelect'); if (sel && viewMode === 'mobile_dispatcher') sel.value = String(groupId); + updateNavigationButton(); clearPolylines(); if (state.currentPolyline) { @@ -741,6 +879,7 @@ function saveMobileStreetState() { } 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); } @@ -777,11 +916,30 @@ function startGeolocation() { state.userArrow = document.getElementById('mobileUserArrow'); state.watchId = navigator.geolocation.watchPosition((pos) => { - const latlng = [pos.coords.latitude, pos.coords.longitude]; - state.userMarker.setLatLng(latlng); + const lat = Number(pos.coords.latitude); + const lon = Number(pos.coords.longitude); + state.lastKnownPosition = { + lat, + lon, + accuracy: pos.coords.accuracy + }; + 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 + ); + } if (window.DeviceOrientationEvent) { window.addEventListener('deviceorientationabsolute', handleOrientation, true); @@ -821,6 +979,8 @@ function showAllGroupPositions() { state.groupMarkers.set(group.id, marker); } }); + + updateNavigationButton(); } function getGroupColor(id) { @@ -828,6 +988,116 @@ function getGroupColor(id) { 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 connectWebSocket() { if (state.ws && (state.ws.readyState === WebSocket.OPEN || state.ws.readyState === WebSocket.CONNECTING)) return; fetchJson(`${apiBase}/auth/ws-token`).then(res => { @@ -977,6 +1247,22 @@ function normalizeTs(value) { 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 handleWs(event) { let message; try { message = JSON.parse(event.data); } catch(e) { return; } @@ -1019,7 +1305,10 @@ function handleWs(event) { const gid = Number(p.group_id || message.receiver_id); const g = state.groupById.get(gid); if (g && p.lat && p.lon) { - g.last_lat = p.lat; g.last_lon = p.lon; + g.last_lat = p.lat; + g.last_lon = p.lon; + g.last_pos_ts = parseFlexibleTimestamp(p.ts) || Date.now(); + g.last_pos_at = new Date(g.last_pos_ts).toISOString(); if (viewMode === 'mobile_dispatcher') showAllGroupPositions(); } } catch(e) {} diff --git a/CMBNet/templates/dispatcher_mobil.html b/CMBNet/templates/dispatcher_mobil.html index 7c31790..fd7a7c1 100644 --- a/CMBNet/templates/dispatcher_mobil.html +++ b/CMBNet/templates/dispatcher_mobil.html @@ -38,6 +38,12 @@
+ diff --git a/CMBNet/templates/gruppen.html b/CMBNet/templates/gruppen.html index 641ae28..e675899 100644 --- a/CMBNet/templates/gruppen.html +++ b/CMBNet/templates/gruppen.html @@ -38,6 +38,8 @@
+ @@ -110,6 +112,15 @@ +
+ Eigenposition automatisch senden + +
+

+ Ist die automatische Versendung deaktiviert, kann die Position + über den Button in der Karte einmalig gesendet werden. +

Benachrichtigungen