Firebase Cloud Messaging 1. Versuch
This commit is contained in:
1 parent
f1fb926c2f
commit
4c8b11c4d5
25 files changed
+2111
-31
No files matched your search
@@ -139,6 +139,22 @@ Eine ausführliche Beschreibung des Protokolls, der Brokerlogik, der
|
||||
Nebenläufigkeit und der aktuellen Abweichungen steht in
|
||||
[`../doc/broker.md`](../doc/broker.md).
|
||||
|
||||
## FCM-Aufwachsignale für mobile PWA-Clients
|
||||
|
||||
Mobile Gruppen- und Dispatcher-Views können über Firebase Cloud Messaging
|
||||
(FCM) aus dem Hintergrund geweckt werden. FCM transportiert nur ein Signal;
|
||||
Nachrichten und Positionen bleiben in der WebSocket-Kommunikation bzw. in der
|
||||
Broker-Queue. Die Signale werden bei gequeueten Nachrichten, nach einem
|
||||
konfigurierbaren Offline-Timeout und über den Radar-Button im Desktop- und
|
||||
mobilen Dispatcher ausgelöst.
|
||||
|
||||
Die Architektur, Trigger, Grenzen auf Android/iOS und alle
|
||||
Konfigurationsvariablen stehen in
|
||||
[`docs/FCM_ARCHITEKTUR.md`](docs/FCM_ARCHITEKTUR.md). Die praktische
|
||||
Einrichtung von Firebase-Projekt, Web-App, VAPID-Schlüssel, Service-Account
|
||||
und PWA-Installation beschreibt
|
||||
[`docs/FCM_HOWTO.md`](docs/FCM_HOWTO.md).
|
||||
|
||||
## Externe Gruppenpositions-API
|
||||
|
||||
Externe Systeme können die Position einer Gruppe per HTTP-POST melden:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import json
|
||||
import os
|
||||
from flask import Flask, g, session, send_from_directory
|
||||
from flask import Flask, Response, g, session, send_from_directory
|
||||
from config import config
|
||||
from cmbnet.extensions import sock
|
||||
|
||||
@@ -102,6 +103,11 @@ def create_app(config_name=None):
|
||||
from cmbnet.utils.helpers import str2pl_asset, str2pl_asset_version
|
||||
app.jinja_env.globals['str2pl_asset'] = str2pl_asset
|
||||
app.jinja_env.globals['str2pl_asset_version'] = str2pl_asset_version
|
||||
|
||||
# Öffentliche FCM-Webkonfiguration für die mobilen Templates. Der
|
||||
# Service-Account-Schlüssel bleibt ausschließlich auf dem Server.
|
||||
from cmbnet.services.fcm_service import public_fcm_config
|
||||
app.jinja_env.globals['fcm_public_config'] = public_fcm_config
|
||||
|
||||
# Middleware registrieren
|
||||
app.wsgi_app = PrefixMiddleware(app.wsgi_app)
|
||||
@@ -147,6 +153,7 @@ def create_app(config_name=None):
|
||||
from cmbnet.api.auth import api_auth_bp
|
||||
from cmbnet.api.groups import api_groups_bp
|
||||
from cmbnet.api.positions import api_positions_bp
|
||||
from cmbnet.api.push import api_push_bp
|
||||
|
||||
app.register_blueprint(auth_bp, url_prefix='/<tenant>')
|
||||
app.register_blueprint(views_bp, url_prefix='/<tenant>')
|
||||
@@ -161,6 +168,7 @@ def create_app(config_name=None):
|
||||
app.register_blueprint(api_auth_bp, url_prefix='/<tenant>/api')
|
||||
app.register_blueprint(api_groups_bp, url_prefix='/<tenant>/api')
|
||||
app.register_blueprint(api_positions_bp, url_prefix='/<tenant>/api')
|
||||
app.register_blueprint(api_push_bp, url_prefix='/<tenant>/api')
|
||||
|
||||
# WebSocket Routes laden
|
||||
from cmbnet.ws import routes
|
||||
@@ -187,7 +195,17 @@ def create_app(config_name=None):
|
||||
app,
|
||||
interval=app.config.get('WS_BUS_POLL_INTERVAL', 0.5)
|
||||
)
|
||||
|
||||
|
||||
# FCM-Offline-Worker nur starten, wenn Firebase aktiviert ist. Er weckt
|
||||
# getrennte mobile Clients nach dem konfigurierten Offline-Timeout, damit
|
||||
# diese ein Positionsupdate senden können.
|
||||
if app.config.get('FCM_ENABLED'):
|
||||
from cmbnet.ws.push import push_wake_worker
|
||||
push_wake_worker.start(
|
||||
app,
|
||||
interval=app.config.get('FCM_WAKE_POLL_INTERVAL_SECONDS', 30)
|
||||
)
|
||||
|
||||
# Favicon explizit bedienen, damit /favicon.ico nicht als Tenant-Pfad
|
||||
# interpretiert wird.
|
||||
@app.route('/favicon.ico')
|
||||
@@ -208,6 +226,37 @@ def create_app(config_name=None):
|
||||
response.headers['Cache-Control'] = 'no-cache'
|
||||
return response
|
||||
|
||||
@app.route('/fcm-sw-config.js')
|
||||
def fcm_service_worker_config():
|
||||
"""Öffentliche Firebase-Konfiguration für den Service Worker.
|
||||
|
||||
Die Datei wird per ``importScripts`` vom Service Worker geladen. Sie
|
||||
enthält ausschließlich öffentliche Web-API-Schlüssel, niemals den
|
||||
Service-Account.
|
||||
"""
|
||||
payload = public_fcm_config()
|
||||
body = (
|
||||
'/* Automatisch erzeugt. Enthält keine Server-Geheimnisse. */\n'
|
||||
'self.CMBNET_FCM_CONFIG = '
|
||||
+ json.dumps(payload, ensure_ascii=False)
|
||||
+ ';\n'
|
||||
)
|
||||
response = Response(body, mimetype='application/javascript')
|
||||
response.headers['Cache-Control'] = 'no-cache'
|
||||
return response
|
||||
|
||||
@app.route('/wake')
|
||||
def wake():
|
||||
"""Ziel für den Klick auf ein FCM-Aufwachsignal.
|
||||
|
||||
Der Mandant kommt aus der bestehenden Session. So landet der Nutzer
|
||||
nach dem Öffnen der PWA wieder in seiner mobilen View, ohne dass
|
||||
FCM Mandant, Rolle oder Nachrichteninhalt transportieren muss.
|
||||
"""
|
||||
from flask import redirect, url_for
|
||||
tenant = session.get('tenant_code') or app.config['DEFAULT_TENANT']
|
||||
return redirect(url_for('views.index', tenant=tenant))
|
||||
|
||||
# Root redirect
|
||||
@app.route('/')
|
||||
def index():
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from .init import api_init_bp
|
||||
from .auth import api_auth_bp
|
||||
from .positions import api_positions_bp
|
||||
from .push import api_push_bp
|
||||
|
||||
api_bp = api_init_bp
|
||||
@@ -0,0 +1,150 @@
|
||||
"""HTTP-Endpunkte für FCM-Registrierung und manuelle Aufwachsignale."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from flask import Blueprint, current_app, g, jsonify, request, session
|
||||
|
||||
from cmbnet.auth import login_required, role_required
|
||||
from cmbnet.services.fcm_service import fcm_service, public_fcm_config
|
||||
from cmbnet.ws import broker, store
|
||||
from cmbnet.ws.client_types import normalize_client_type
|
||||
|
||||
api_push_bp = Blueprint('api_push', __name__)
|
||||
|
||||
TOKEN_RE = re.compile(r'^[A-Za-z0-9_\-:.=]{20,4096}$')
|
||||
|
||||
|
||||
def _json_body():
|
||||
data = request.get_json(silent=True)
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _platform_name(value):
|
||||
text = str(value or '').strip().lower()
|
||||
if text in ('ios', 'android', 'desktop'):
|
||||
return text
|
||||
return 'other'
|
||||
|
||||
|
||||
@api_push_bp.route('/push/config', methods=['GET'])
|
||||
@login_required
|
||||
def push_config(**kwargs):
|
||||
"""Liefert die öffentliche Firebase-Webkonfiguration."""
|
||||
return jsonify(public_fcm_config())
|
||||
|
||||
|
||||
@api_push_bp.route('/push/register', methods=['POST'])
|
||||
@login_required
|
||||
def register_push_token(**kwargs):
|
||||
"""Registriert bzw. aktualisiert das FCM-Token einer mobilen Webview."""
|
||||
account_id = session.get('account_id')
|
||||
role = session.get('role')
|
||||
data = _json_body()
|
||||
|
||||
token = str(data.get('token') or '').strip()
|
||||
if not TOKEN_RE.fullmatch(token):
|
||||
return jsonify({'ok': False, 'error': 'Ungültiges FCM-Token.'}), 400
|
||||
|
||||
client_type = normalize_client_type(data.get('client_type'), role)
|
||||
if client_type is None:
|
||||
return jsonify({
|
||||
'ok': False,
|
||||
'error': 'FCM ist für diese View oder Rolle nicht zugelassen.'
|
||||
}), 403
|
||||
|
||||
requested_client_id = str(data.get('client_id') or '').strip()
|
||||
if not requested_client_id:
|
||||
return jsonify({'ok': False, 'error': 'Client-ID fehlt.'}), 400
|
||||
client_id = broker.normalize_client_id(requested_client_id, account_id)
|
||||
|
||||
store.upsert_push_token(
|
||||
g.tenant_id,
|
||||
client_id,
|
||||
account_id,
|
||||
token,
|
||||
client_type,
|
||||
platform=_platform_name(data.get('platform')),
|
||||
auto_position=data.get('auto_position') is True,
|
||||
)
|
||||
current_app.logger.info(
|
||||
'FCM-Token registriert: tenant=%s client=%s type=%s',
|
||||
g.tenant_id, client_id, client_type
|
||||
)
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@api_push_bp.route('/push/register', methods=['DELETE'])
|
||||
@login_required
|
||||
def unregister_push_token(**kwargs):
|
||||
"""Entfernt ein FCM-Token, z. B. beim Abmelden."""
|
||||
data = _json_body()
|
||||
token = str(data.get('token') or '').strip()
|
||||
if not token:
|
||||
return jsonify({'ok': False, 'error': 'Token fehlt.'}), 400
|
||||
store.delete_push_token(
|
||||
g.tenant_id,
|
||||
token=token,
|
||||
account_id=session.get('account_id')
|
||||
)
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@api_push_bp.route('/push/wake', methods=['POST'])
|
||||
@role_required(['Dispatcher', 'Administrator'])
|
||||
def wake_mobile_clients(**kwargs):
|
||||
"""Löst manuell ein FCM-Aufwachsignal für offline mobile Clients aus.
|
||||
|
||||
Optional kann mit ``group_id`` auf die Clients einer Gruppe eingeschränkt
|
||||
werden. Es werden nur Clients angesprochen, die aktuell als getrennt
|
||||
gelten und ein gültiges FCM-Token besitzen.
|
||||
"""
|
||||
config = public_fcm_config()
|
||||
if not config.get('enabled'):
|
||||
return jsonify({
|
||||
'ok': False,
|
||||
'configured': False,
|
||||
'error': 'FCM ist nicht vollständig konfiguriert.'
|
||||
}), 503
|
||||
|
||||
data = _json_body()
|
||||
group_id = data.get('group_id')
|
||||
try:
|
||||
group_id = int(group_id) if group_id not in (None, '') else None
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'ok': False, 'error': 'Ungültige Gruppen-ID.'}), 400
|
||||
|
||||
current = store.now()
|
||||
cooldown = max(0, int(current_app.config.get(
|
||||
'FCM_MANUAL_WAKE_COOLDOWN_SECONDS', 15
|
||||
)))
|
||||
candidates = store.offline_mobile_wake_candidates(
|
||||
g.tenant_id,
|
||||
disconnected_before=current,
|
||||
re_wake_before=current - cooldown if cooldown else None,
|
||||
group_id=group_id,
|
||||
auto_position_only=False,
|
||||
limit=1000,
|
||||
)
|
||||
|
||||
tokens = [row['token'] for row in candidates]
|
||||
result = fcm_service.send_wake(tokens, reason='manual')
|
||||
sent_tokens = set(result.get('sent_tokens') or [])
|
||||
invalid_tokens = set(result.get('invalid_tokens') or [])
|
||||
|
||||
for row in candidates:
|
||||
if row['token'] in sent_tokens:
|
||||
store.set_client_wake_sent(
|
||||
g.tenant_id, row['client_id'], 'manual', current
|
||||
)
|
||||
for token in invalid_tokens:
|
||||
store.mark_push_token_invalid(token)
|
||||
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'configured': bool(result.get('configured')),
|
||||
'candidates': len(candidates),
|
||||
'sent': int(result.get('sent') or 0),
|
||||
'failed': int(result.get('failed') or 0),
|
||||
'error': result.get('error'),
|
||||
})
|
||||
@@ -32,18 +32,27 @@ def close_db(e=None):
|
||||
|
||||
|
||||
def ensure_ws_schema(db):
|
||||
"""Legt die Tabellen für den prozessübergreifenden Broker-Zustand an."""
|
||||
"""Legt die Tabellen für den prozessübergreifenden Broker-Zustand an.
|
||||
|
||||
``ws_clients`` wird bei bestehenden Installationen um die Spalten für
|
||||
Client-Typ und FCM-Aufwachsignale ergänzt. SQLite kennt kein
|
||||
``ADD COLUMN IF NOT EXISTS``; deshalb wird vorher ``PRAGMA table_info``
|
||||
ausgewertet.
|
||||
"""
|
||||
db.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS ws_clients (
|
||||
tenant_id INTEGER NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
account_id INTEGER NOT NULL,
|
||||
client_type TEXT,
|
||||
last_seq INTEGER NOT NULL DEFAULT 0,
|
||||
worker_id TEXT,
|
||||
authenticated INTEGER NOT NULL DEFAULT 0,
|
||||
connected_at REAL,
|
||||
disconnected_at REAL,
|
||||
queue_started_at REAL,
|
||||
last_wake_at REAL,
|
||||
last_wake_reason TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (tenant_id, client_id),
|
||||
@@ -51,6 +60,22 @@ def ensure_ws_schema(db):
|
||||
FOREIGN KEY (account_id) REFERENCES accounts(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ws_push_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
account_id INTEGER NOT NULL,
|
||||
token TEXT UNIQUE NOT NULL,
|
||||
client_type TEXT NOT NULL,
|
||||
platform TEXT,
|
||||
auto_position INTEGER NOT NULL DEFAULT 0,
|
||||
invalid INTEGER NOT NULL DEFAULT 0,
|
||||
created_at REAL NOT NULL,
|
||||
updated_at REAL NOT NULL,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
|
||||
FOREIGN KEY (account_id) REFERENCES accounts(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ws_client_queue (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
@@ -82,11 +107,32 @@ def ensure_ws_schema(db):
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_clients_account
|
||||
ON ws_clients(tenant_id, account_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_push_tokens_client
|
||||
ON ws_push_tokens(tenant_id, client_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_push_tokens_offline
|
||||
ON ws_push_tokens(tenant_id, invalid, client_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_client_queue_client
|
||||
ON ws_client_queue(tenant_id, client_id, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_client_queue_expires
|
||||
ON ws_client_queue(expires_at);
|
||||
''')
|
||||
|
||||
# Bestehende Datenbanken nachziehen. Die Spalten sind nullable bzw. haben
|
||||
# Defaults, damit laufende Clients ohne Datenverlust weiterarbeiten.
|
||||
client_columns = {
|
||||
row['name'] for row in db.execute('PRAGMA table_info(ws_clients)').fetchall()
|
||||
}
|
||||
for name, definition in (
|
||||
('client_type', 'TEXT'),
|
||||
('last_wake_at', 'REAL'),
|
||||
('last_wake_reason', 'TEXT'),
|
||||
):
|
||||
if name not in client_columns:
|
||||
db.execute(f'ALTER TABLE ws_clients ADD COLUMN {name} {definition}')
|
||||
db.execute(
|
||||
'CREATE INDEX IF NOT EXISTS idx_ws_clients_type '
|
||||
'ON ws_clients(tenant_id, client_type, disconnected_at)'
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
"""FCM-Signaldienst für mobile PWA-Clients.
|
||||
|
||||
FCM transportiert ausschließlich ein Aufwachsignal. Die fachlichen Inhalte
|
||||
bleiben in der persistenten WebSocket-Queue des Brokers. Das Modul kapselt
|
||||
die optionale ``firebase-admin``-Abhängigkeit, damit die Anwendung auch ohne
|
||||
Firebase-Konfiguration vollständig startet.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from flask import current_app, url_for
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _config_bool(value):
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return str(value or '').strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
|
||||
|
||||
def fcm_enabled(config=None):
|
||||
"""Gibt zurück, ob FCM in der aktuellen Konfiguration aktiviert ist."""
|
||||
config = config or current_app.config
|
||||
return _config_bool(config.get('FCM_ENABLED', False))
|
||||
|
||||
|
||||
def _web_config(config):
|
||||
"""Baut die öffentliche Firebase-Webkonfiguration.
|
||||
|
||||
Diese Werte sind bewusst öffentlich. Sie dürfen nicht mit dem
|
||||
Service-Account-Schlüssel verwechselt werden.
|
||||
"""
|
||||
project_id = str(config.get('FCM_WEB_PROJECT_ID')
|
||||
or config.get('FCM_PROJECT_ID') or '').strip()
|
||||
return {
|
||||
'apiKey': str(config.get('FCM_WEB_API_KEY', '')).strip(),
|
||||
'authDomain': str(
|
||||
config.get('FCM_WEB_AUTH_DOMAIN')
|
||||
or (f'{project_id}.firebaseapp.com' if project_id else '')
|
||||
).strip(),
|
||||
'projectId': project_id,
|
||||
'storageBucket': str(
|
||||
config.get('FCM_WEB_STORAGE_BUCKET')
|
||||
or (f'{project_id}.appspot.com' if project_id else '')
|
||||
).strip(),
|
||||
'messagingSenderId': str(
|
||||
config.get('FCM_WEB_MESSAGING_SENDER_ID', '')
|
||||
).strip(),
|
||||
'appId': str(config.get('FCM_WEB_APP_ID', '')).strip(),
|
||||
}
|
||||
|
||||
|
||||
def public_fcm_config(config=None):
|
||||
"""Liefert die für Browser und Service Worker bestimmte Konfiguration.
|
||||
|
||||
Der Service Worker benötigt nur die öffentlichen Firebase-Webdaten. Der
|
||||
Service-Account-Schlüssel bleibt ausschließlich auf dem Server.
|
||||
"""
|
||||
config = config or current_app.config
|
||||
firebase_config = _web_config(config)
|
||||
vapid_key = str(config.get('FCM_VAPID_KEY', '')).strip()
|
||||
required_web = (
|
||||
firebase_config['apiKey'],
|
||||
firebase_config['projectId'],
|
||||
firebase_config['messagingSenderId'],
|
||||
firebase_config['appId'],
|
||||
vapid_key,
|
||||
)
|
||||
enabled = fcm_enabled(config) and all(required_web)
|
||||
|
||||
try:
|
||||
icon_url = url_for('static', filename='img/icon-192.png')
|
||||
wake_url = url_for('wake')
|
||||
except Exception:
|
||||
# Die Funktion kann auch außerhalb eines Request-Kontexts aufgerufen
|
||||
# werden (z. B. in Tests). Dann bleiben die Pfade relativ.
|
||||
icon_url = '/static/img/icon-192.png'
|
||||
wake_url = '/wake'
|
||||
|
||||
return {
|
||||
'enabled': bool(enabled),
|
||||
'sdkVersion': str(config.get('FCM_WEB_SDK_VERSION', '10.14.1')),
|
||||
'vapidKey': vapid_key,
|
||||
'firebase': firebase_config,
|
||||
'title': str(config.get('DISPLAY_TITLE', '20*C+M+B+27')),
|
||||
'icon': icon_url,
|
||||
'wakeUrl': wake_url,
|
||||
'notificationTag': 'cmbnet-wake',
|
||||
}
|
||||
|
||||
|
||||
class FcmService:
|
||||
"""Kapselt Initialisierung und Versand von FCM-Signalen."""
|
||||
|
||||
def __init__(self):
|
||||
self._lock = threading.Lock()
|
||||
self._app = None
|
||||
self._initialized = False
|
||||
self._error = None
|
||||
|
||||
def _server_config(self):
|
||||
config = current_app.config
|
||||
if not fcm_enabled(config):
|
||||
return None, 'FCM ist deaktiviert.'
|
||||
if not (config.get('FCM_SERVICE_ACCOUNT_FILE')
|
||||
or config.get('FCM_SERVICE_ACCOUNT_JSON')):
|
||||
return None, 'FCM-Service-Account ist nicht konfiguriert.'
|
||||
return config, None
|
||||
|
||||
def server_ready(self):
|
||||
"""Prüft, ob der Server FCM grundsätzlich senden könnte."""
|
||||
_config, error = self._server_config()
|
||||
return error is None
|
||||
|
||||
def _ensure_app(self):
|
||||
"""Initialisiert firebase-admin genau einmal pro Workerprozess."""
|
||||
config, error = self._server_config()
|
||||
if error:
|
||||
return None, error
|
||||
if self._initialized:
|
||||
return self._app, self._error
|
||||
|
||||
with self._lock:
|
||||
if self._initialized:
|
||||
return self._app, self._error
|
||||
self._initialized = True
|
||||
try:
|
||||
import firebase_admin
|
||||
from firebase_admin import credentials
|
||||
except ImportError:
|
||||
self._error = (
|
||||
'firebase-admin ist nicht installiert. '
|
||||
'Bitte requirements.txt installieren.'
|
||||
)
|
||||
logger.warning(self._error)
|
||||
return None, self._error
|
||||
|
||||
try:
|
||||
try:
|
||||
self._app = firebase_admin.get_app('cmbnet')
|
||||
except ValueError:
|
||||
credential = self._load_credential(credentials, config)
|
||||
options = {}
|
||||
project_id = str(
|
||||
config.get('FCM_PROJECT_ID') or ''
|
||||
).strip()
|
||||
if project_id:
|
||||
options['projectId'] = project_id
|
||||
self._app = firebase_admin.initialize_app(
|
||||
credential, options, name='cmbnet'
|
||||
)
|
||||
except Exception as exc:
|
||||
self._error = f'FCM-Initialisierung fehlgeschlagen: {exc}'
|
||||
logger.exception(self._error)
|
||||
return None, self._error
|
||||
|
||||
return self._app, None
|
||||
|
||||
@staticmethod
|
||||
def _load_credential(credentials, config):
|
||||
inline = config.get('FCM_SERVICE_ACCOUNT_JSON')
|
||||
if inline:
|
||||
data = json.loads(inline)
|
||||
return credentials.Certificate(data)
|
||||
|
||||
path = Path(str(config.get('FCM_SERVICE_ACCOUNT_FILE', ''))).expanduser()
|
||||
if not path.is_absolute():
|
||||
path = Path(current_app.root_path).parent / path
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f'Service-Account-Datei fehlt: {path}')
|
||||
return credentials.Certificate(str(path))
|
||||
|
||||
def send_wake(self, tokens, reason='wake'):
|
||||
"""Sendet ein reines Daten-Signal an die angegebenen FCM-Tokens.
|
||||
|
||||
Rückgabe enthält Zähler und die von FCM als ungültig gemeldeten
|
||||
Tokens. Es werden keine Chat- oder Positionsdaten übertragen.
|
||||
"""
|
||||
tokens = [str(token).strip() for token in tokens if token]
|
||||
tokens = list(dict.fromkeys(tokens))
|
||||
result = {
|
||||
'configured': False,
|
||||
'requested': len(tokens),
|
||||
'sent': 0,
|
||||
'failed': 0,
|
||||
'sent_tokens': [],
|
||||
'invalid_tokens': [],
|
||||
}
|
||||
if not tokens:
|
||||
return result
|
||||
|
||||
app, error = self._ensure_app()
|
||||
if error or app is None:
|
||||
result['error'] = error
|
||||
return result
|
||||
|
||||
result['configured'] = True
|
||||
config = current_app.config
|
||||
ttl_seconds = max(
|
||||
60, int(config.get('FCM_SIGNAL_TTL_SECONDS', 600))
|
||||
)
|
||||
|
||||
from firebase_admin import messaging
|
||||
|
||||
data = {
|
||||
'type': 'cmbnet-wake',
|
||||
'reason': str(reason or 'wake'),
|
||||
}
|
||||
android = messaging.AndroidConfig(
|
||||
priority='high',
|
||||
ttl=timedelta(seconds=ttl_seconds),
|
||||
)
|
||||
webpush = messaging.WebpushConfig(
|
||||
headers={
|
||||
'Urgency': 'high',
|
||||
'TTL': str(ttl_seconds),
|
||||
}
|
||||
)
|
||||
|
||||
for start in range(0, len(tokens), 500):
|
||||
batch = tokens[start:start + 500]
|
||||
batch_result = self._send_batch(
|
||||
messaging, batch, data, android, webpush
|
||||
)
|
||||
result['sent'] += batch_result['sent']
|
||||
result['failed'] += batch_result['failed']
|
||||
result['sent_tokens'].extend(batch_result['sent_tokens'])
|
||||
result['invalid_tokens'].extend(batch_result['invalid_tokens'])
|
||||
|
||||
return result
|
||||
|
||||
def _send_batch(self, messaging, tokens, data, android, webpush):
|
||||
batch_result = {
|
||||
'sent': 0,
|
||||
'failed': 0,
|
||||
'sent_tokens': [],
|
||||
'invalid_tokens': [],
|
||||
}
|
||||
message = messaging.MulticastMessage(
|
||||
tokens=tokens,
|
||||
data=data,
|
||||
android=android,
|
||||
webpush=webpush,
|
||||
)
|
||||
try:
|
||||
response = messaging.send_each_for_multicast(message)
|
||||
responses = list(response.responses)
|
||||
except Exception as exc:
|
||||
logger.warning('FCM-Batchversand fehlgeschlagen: %s', exc)
|
||||
batch_result['failed'] += len(tokens)
|
||||
return batch_result
|
||||
|
||||
for token, send_response in zip(tokens, responses):
|
||||
if send_response.success:
|
||||
batch_result['sent'] += 1
|
||||
batch_result['sent_tokens'].append(token)
|
||||
continue
|
||||
batch_result['failed'] += 1
|
||||
exception = send_response.exception
|
||||
text = str(exception or '').upper()
|
||||
if (
|
||||
isinstance(exception, messaging.UnregisteredError)
|
||||
or 'UNREGISTERED' in text
|
||||
or 'INVALID_ARGUMENT' in text
|
||||
or 'SENDER_ID_MISMATCH' in text
|
||||
):
|
||||
batch_result['invalid_tokens'].append(token)
|
||||
return batch_result
|
||||
|
||||
|
||||
fcm_service = FcmService()
|
||||
@@ -32,8 +32,10 @@ from datetime import datetime, timedelta, timezone
|
||||
from threading import Event, Lock
|
||||
from flask import current_app
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.services.fcm_service import fcm_service
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.ws import store
|
||||
from cmbnet.ws.client_types import normalize_client_type
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
@@ -79,12 +81,17 @@ class WebSocketBroker:
|
||||
# ------------------------------------------------------------------
|
||||
# Verbindungen und Authentifizierung
|
||||
# ------------------------------------------------------------------
|
||||
def register_connection(self, tenant_id, account_id, client_id, ws, role=None, group_id=None):
|
||||
def register_connection(self, tenant_id, account_id, client_id, ws,
|
||||
role=None, group_id=None, client_type=None):
|
||||
"""Registriert eine neue, noch nicht authentifizierte Client-Verbindung.
|
||||
|
||||
Die Verbindung wird anhand der Client-ID verwaltet. Die Account-ID wird
|
||||
mitgeführt, damit Empfänger weiterhin über Rollen und Gruppen ermittelt
|
||||
werden können und ein Account mehrere Clients parallel betreiben kann.
|
||||
|
||||
``client_type`` ist ausschließlich ein FCM-Routing-Merkmal. Der Wert
|
||||
wird gegen die Rolle des Accounts geprüft; ein Dispatcher kann sich
|
||||
beispielsweise nicht als Gruppen-View ausgeben.
|
||||
"""
|
||||
if not client_id:
|
||||
return False
|
||||
@@ -104,13 +111,16 @@ class WebSocketBroker:
|
||||
existing_account = store.get_client_account(tenant_id, client_id)
|
||||
if existing_account is not None and existing_account != account_id:
|
||||
return False
|
||||
if not store.ensure_client(
|
||||
tenant_id, client_id, account_id, worker_id=self.worker_id
|
||||
):
|
||||
return False
|
||||
|
||||
if role is None:
|
||||
role = account['role']
|
||||
client_type = normalize_client_type(client_type, role)
|
||||
|
||||
if not store.ensure_client(
|
||||
tenant_id, client_id, account_id, worker_id=self.worker_id,
|
||||
client_type=client_type
|
||||
):
|
||||
return False
|
||||
|
||||
# Für Gruppen-Accounts die zugehörige Gruppe ermitteln. Ein Account der
|
||||
# Rolle "Gruppe" ist höchstens einer Gruppe zugeordnet.
|
||||
@@ -147,6 +157,7 @@ class WebSocketBroker:
|
||||
'client_id': client_id,
|
||||
'role': role,
|
||||
'group_id': group_id,
|
||||
'client_type': client_type,
|
||||
'last_ping': datetime.now(),
|
||||
'connected_at': time.monotonic(),
|
||||
'last_pong_at': None,
|
||||
@@ -513,8 +524,72 @@ class WebSocketBroker:
|
||||
)
|
||||
if queued:
|
||||
self.delivery_wakeup.set()
|
||||
# Mobile Clients, die als getrennt gelten, werden zusätzlich über
|
||||
# FCM geweckt. Der eigentliche Inhalt bleibt in der Queue.
|
||||
if message.code >= 99:
|
||||
self.wake_client(tenant_id, client_id, 'queue')
|
||||
return queued
|
||||
|
||||
def wake_client(self, tenant_id, client_id, reason='queue',
|
||||
cooldown_seconds=None):
|
||||
"""Sendet bei Bedarf ein FCM-Aufwachsignal an einen mobilen Client.
|
||||
|
||||
Die Methode ist bewusst idempotent und durch ``last_wake_at``
|
||||
gedrosselt. Sie wird sowohl beim Einreihen einer Nachricht als auch
|
||||
vom periodischen Offline-Worker aufgerufen.
|
||||
"""
|
||||
try:
|
||||
if not fcm_service.server_ready():
|
||||
return False
|
||||
|
||||
if cooldown_seconds is None:
|
||||
try:
|
||||
cooldown_seconds = int(current_app.config.get(
|
||||
'FCM_QUEUE_WAKE_COOLDOWN_SECONDS', 60
|
||||
))
|
||||
except (TypeError, ValueError):
|
||||
cooldown_seconds = 60
|
||||
|
||||
current = store.now()
|
||||
rows = store.claim_offline_mobile_wakes(
|
||||
tenant_id,
|
||||
disconnected_before=current,
|
||||
re_wake_before=current - max(0, cooldown_seconds),
|
||||
client_id=client_id,
|
||||
reason=reason,
|
||||
limit=1,
|
||||
)
|
||||
if not rows:
|
||||
return False
|
||||
|
||||
tokens = [row['token'] for row in rows]
|
||||
result = fcm_service.send_wake(tokens, reason=reason)
|
||||
for token in result.get('invalid_tokens') or []:
|
||||
store.mark_push_token_invalid(token)
|
||||
|
||||
if result.get('sent'):
|
||||
return True
|
||||
|
||||
# Ein fehlgeschlagenes Signal wird nicht als erfolgreich verbucht.
|
||||
# Der nächste Versuch darf aber erst nach dem Cooldown erfolgen, um
|
||||
# bei einem FCM-Ausfall keine Schleife zu erzeugen.
|
||||
for row in rows:
|
||||
store.set_client_wake_sent(
|
||||
tenant_id, row['client_id'], f'{reason}:failed', current
|
||||
)
|
||||
return False
|
||||
except Exception as exc:
|
||||
# Ein FCM-Problem darf das Einreihen und Ausliefern fachlicher
|
||||
# Nachrichten niemals verhindern.
|
||||
try:
|
||||
current_app.logger.warning(
|
||||
'FCM-Aufwachsignal fehlgeschlagen (tenant=%s, client=%s): %s',
|
||||
tenant_id, client_id, exc
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
def cleanup_client_queues(self):
|
||||
"""Räumt abgelaufene Queues und verwaiste Clients in der DB auf."""
|
||||
store.purge_expired_queue_rows()
|
||||
@@ -523,6 +598,13 @@ class WebSocketBroker:
|
||||
self._client_queue_timeout_message()
|
||||
)
|
||||
store.cleanup_clients(self._client_retention_seconds())
|
||||
try:
|
||||
token_retention = float(current_app.config.get(
|
||||
'FCM_PUSH_TOKEN_RETENTION_MINUTES', 1440
|
||||
)) * 60
|
||||
except (TypeError, ValueError):
|
||||
token_retention = 1440 * 60
|
||||
store.cleanup_orphan_push_tokens(max(3600.0, token_retention))
|
||||
|
||||
# Lokale Caches für inzwischen entfernte Clients bereinigen.
|
||||
for key in list(self.client_sequences):
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Zulässige Webview-Typen und ihre Rollenbindung.
|
||||
|
||||
Der Client-Typ steuert ausschließlich, ob der Broker für eine Webview
|
||||
FCM-Aufwachsignale einsetzen darf. Er ersetzt keine Rollenprüfung: Der Typ
|
||||
wird beim Code-0-Handshake zusätzlich zur Session-Rolle validiert.
|
||||
"""
|
||||
|
||||
GROUP_VIEW = 'group_view'
|
||||
DISPATCHER_MOBILE = 'dispatcher_mobile'
|
||||
|
||||
MOBILE_CLIENT_TYPES = frozenset({GROUP_VIEW, DISPATCHER_MOBILE})
|
||||
|
||||
CLIENT_TYPE_ROLES = {
|
||||
GROUP_VIEW: frozenset({'Gruppe'}),
|
||||
DISPATCHER_MOBILE: frozenset({'Dispatcher', 'Administrator'}),
|
||||
}
|
||||
|
||||
|
||||
def normalize_client_type(value, role=None):
|
||||
"""Gibt einen gültigen Client-Typ oder ``None`` zurück.
|
||||
|
||||
``None`` bedeutet: kein FCM für diese Webview. Ältere Clients ohne
|
||||
Typangabe bleiben damit kompatibel.
|
||||
"""
|
||||
text = str(value or '').strip().lower()
|
||||
if text not in MOBILE_CLIENT_TYPES:
|
||||
return None
|
||||
if role is not None and role not in CLIENT_TYPE_ROLES[text]:
|
||||
return None
|
||||
return text
|
||||
|
||||
|
||||
def is_mobile_client_type(value):
|
||||
return value in MOBILE_CLIENT_TYPES
|
||||
@@ -6,7 +6,8 @@ from datetime import datetime
|
||||
|
||||
|
||||
class WSMessage:
|
||||
def __init__(self, sender_id=None, receiver_id=None, code=0, msg="", ts=None, client_id=None):
|
||||
def __init__(self, sender_id=None, receiver_id=None, code=0, msg="", ts=None,
|
||||
client_id=None, client_type=None):
|
||||
self.sender_id = sender_id
|
||||
self.receiver_id = receiver_id
|
||||
self.code = code
|
||||
@@ -15,6 +16,7 @@ class WSMessage:
|
||||
# Nur für den Code-0-Handshake. Wird nicht an andere Clients
|
||||
# weitergegeben und deshalb auch nicht in to_dict() serialisiert.
|
||||
self.client_id = client_id
|
||||
self.client_type = client_type
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
@@ -38,7 +40,8 @@ class WSMessage:
|
||||
ts=data.get('ts'),
|
||||
# Ältere Clients senden noch session_id. Sie werden übergangsweise
|
||||
# als Client-ID akzeptiert.
|
||||
client_id=data.get('client_id') or data.get('session_id')
|
||||
client_id=data.get('client_id') or data.get('session_id'),
|
||||
client_type=data.get('client_type')
|
||||
)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Periodischer Worker für FCM-Aufwachsignale.
|
||||
|
||||
Der Worker läuft in jedem WSGI-Prozess. Die eigentliche Kandidatenauswahl
|
||||
wird über ``claim_offline_mobile_wakes`` in SQLite transaktional reserviert,
|
||||
damit mehrere Worker nicht dasselbe Signal senden.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.services.fcm_service import fcm_service
|
||||
from cmbnet.ws import store
|
||||
|
||||
|
||||
class PushWakeWorker:
|
||||
def __init__(self, interval=30):
|
||||
self.interval = max(5.0, float(interval or 30))
|
||||
self.app = None
|
||||
self.running = False
|
||||
self._thread = None
|
||||
self._stop = threading.Event()
|
||||
|
||||
def start(self, app=None, interval=None):
|
||||
if app is not None:
|
||||
self.app = app
|
||||
if interval is not None:
|
||||
self.interval = max(5.0, float(interval))
|
||||
if self.running or self.app is None:
|
||||
return
|
||||
|
||||
self.running = True
|
||||
self._stop.clear()
|
||||
self._thread = threading.Thread(
|
||||
target=self._run,
|
||||
name='cmbnet-fcm-wake',
|
||||
daemon=True,
|
||||
)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.running = False
|
||||
self._stop.set()
|
||||
if self._thread is not None:
|
||||
self._thread.join(timeout=2.0)
|
||||
self._thread = None
|
||||
|
||||
def _run(self):
|
||||
with self.app.app_context():
|
||||
while not self._stop.is_set() and self.running:
|
||||
try:
|
||||
self._run_once()
|
||||
except Exception as exc:
|
||||
try:
|
||||
self.app.logger.warning(
|
||||
'FCM-Offline-Worker fehlgeschlagen: %s', exc
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
self._stop.wait(self.interval)
|
||||
|
||||
def _run_once(self):
|
||||
config = self.app.config
|
||||
if not fcm_service.server_ready():
|
||||
return
|
||||
|
||||
try:
|
||||
offline_seconds = max(
|
||||
0.0,
|
||||
float(config.get('FCM_OFFLINE_WAKE_MINUTES', 5)) * 60
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
offline_seconds = 5 * 60
|
||||
|
||||
current = store.now()
|
||||
cutoff = current - offline_seconds
|
||||
db = get_db()
|
||||
tenant_rows = db.execute('SELECT id FROM tenants').fetchall()
|
||||
for tenant_row in tenant_rows:
|
||||
tenant_id = tenant_row['id']
|
||||
candidates = store.claim_offline_mobile_wakes(
|
||||
tenant_id,
|
||||
disconnected_before=cutoff,
|
||||
re_wake_before=cutoff,
|
||||
auto_position_only=True,
|
||||
reason='offline',
|
||||
limit=500,
|
||||
)
|
||||
if not candidates:
|
||||
continue
|
||||
|
||||
tokens = [row['token'] for row in candidates]
|
||||
result = fcm_service.send_wake(tokens, reason='offline')
|
||||
for token in result.get('invalid_tokens') or []:
|
||||
store.mark_push_token_invalid(token)
|
||||
if result.get('failed'):
|
||||
self.app.logger.warning(
|
||||
'FCM-Offline-Wake: %s von %s Signalen fehlgeschlagen '
|
||||
'(tenant=%s)', result.get('failed'), len(tokens), tenant_id
|
||||
)
|
||||
|
||||
|
||||
push_wake_worker = PushWakeWorker()
|
||||
@@ -17,15 +17,17 @@ from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
def _parse_auth_payload(value):
|
||||
"""Liefert (Token, Client-ID) aus dem Code-0-Payload.
|
||||
"""Liefert (Token, Client-ID, Client-Typ) aus dem Code-0-Payload.
|
||||
|
||||
Ältere Clients senden statt ``client_id`` noch ``session_id``. Der
|
||||
alte Schlüssel wird übergangsweise weiter akzeptiert.
|
||||
alte Schlüssel wird übergangsweise weiter akzeptiert. ``client_type``
|
||||
ist optional; ohne Angabe bleibt FCM für die Webview deaktiviert.
|
||||
"""
|
||||
if isinstance(value, dict):
|
||||
return (
|
||||
value.get('token'),
|
||||
value.get('client_id') or value.get('session_id')
|
||||
value.get('client_id') or value.get('session_id'),
|
||||
value.get('client_type')
|
||||
)
|
||||
|
||||
if isinstance(value, str):
|
||||
@@ -34,15 +36,16 @@ def _parse_auth_payload(value):
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except (TypeError, ValueError):
|
||||
return None, None
|
||||
return None, None, None
|
||||
if isinstance(data, dict):
|
||||
return (
|
||||
data.get('token'),
|
||||
data.get('client_id') or data.get('session_id')
|
||||
data.get('client_id') or data.get('session_id'),
|
||||
data.get('client_type')
|
||||
)
|
||||
return text, None
|
||||
return text, None, None
|
||||
|
||||
return None, None
|
||||
return None, None, None
|
||||
|
||||
|
||||
@sock.route('/<tenant>/ws')
|
||||
@@ -97,14 +100,19 @@ def ws(ws, tenant):
|
||||
ws.close()
|
||||
break
|
||||
|
||||
token, requested_client_id = _parse_auth_payload(msg.msg)
|
||||
token, requested_client_id, client_type = _parse_auth_payload(
|
||||
msg.msg
|
||||
)
|
||||
if not requested_client_id:
|
||||
requested_client_id = getattr(msg, 'client_id', None)
|
||||
if client_type is None:
|
||||
client_type = getattr(msg, 'client_type', None)
|
||||
client_id = broker.normalize_client_id(requested_client_id, account_id)
|
||||
msg.client_id = client_id
|
||||
|
||||
if not token or not broker.register_connection(
|
||||
tenant_id, account_id, client_id, ws
|
||||
tenant_id, account_id, client_id, ws,
|
||||
client_type=client_type
|
||||
):
|
||||
broker.log_incoming(
|
||||
tenant_id, msg, recipients=[],
|
||||
|
||||
+247
-7
@@ -47,12 +47,17 @@ def client_is_connected(tenant_id, client_id):
|
||||
return bool(row and row['disconnected_at'] is None)
|
||||
|
||||
|
||||
def ensure_client(tenant_id, client_id, account_id, worker_id=None):
|
||||
def ensure_client(tenant_id, client_id, account_id, worker_id=None,
|
||||
client_type=None):
|
||||
"""Registriert eine Client-ID bzw. aktualisiert ihren Verbindungsstatus.
|
||||
|
||||
Gibt ``False`` zurück, wenn die Client-ID bereits einem anderen Account
|
||||
gehört. Ein solcher Wechsel wäre ein Hinweis auf eine manipulierte
|
||||
Zuordnung und wird vom Broker abgelehnt.
|
||||
|
||||
``client_type`` wird bei jedem Reconnect aktualisiert. ``None`` lässt
|
||||
einen bereits bekannten Typ unverändert, damit ältere Clients ohne
|
||||
Typangabe ihre FCM-Berechtigung nicht verlieren.
|
||||
"""
|
||||
db = get_db()
|
||||
row = get_client(tenant_id, client_id)
|
||||
@@ -63,19 +68,20 @@ def ensure_client(tenant_id, client_id, account_id, worker_id=None):
|
||||
return False
|
||||
db.execute(
|
||||
'UPDATE ws_clients SET worker_id = ?, connected_at = ?, '
|
||||
'disconnected_at = NULL, authenticated = 0 '
|
||||
'disconnected_at = NULL, authenticated = 0, '
|
||||
'client_type = COALESCE(?, client_type) '
|
||||
'WHERE tenant_id = ? AND client_id = ?',
|
||||
(worker_id, current, tenant_id, client_id)
|
||||
(worker_id, current, client_type, tenant_id, client_id)
|
||||
)
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
db.execute(
|
||||
'INSERT INTO ws_clients '
|
||||
'(tenant_id, client_id, account_id, worker_id, connected_at, '
|
||||
' authenticated, last_seq) '
|
||||
'VALUES (?, ?, ?, ?, ?, 0, 0)',
|
||||
(tenant_id, client_id, account_id, worker_id, current)
|
||||
'(tenant_id, client_id, account_id, client_type, worker_id, '
|
||||
' connected_at, authenticated, last_seq) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?, 0, 0)',
|
||||
(tenant_id, client_id, account_id, client_type, worker_id, current)
|
||||
)
|
||||
db.commit()
|
||||
return True
|
||||
@@ -207,6 +213,236 @@ def client_ids_for_accounts(tenant_id, account_ids):
|
||||
return result
|
||||
|
||||
|
||||
def set_client_wake_sent(tenant_id, client_id, reason=None, timestamp=None):
|
||||
"""Vermerkt ein erfolgreich abgesetztes FCM-Aufwachsignal."""
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'UPDATE ws_clients SET last_wake_at = ?, last_wake_reason = ? '
|
||||
'WHERE tenant_id = ? AND client_id = ?',
|
||||
(timestamp if timestamp is not None else now(), reason, tenant_id, client_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def upsert_push_token(tenant_id, client_id, account_id, token, client_type,
|
||||
platform=None, auto_position=False):
|
||||
"""Speichert bzw. aktualisiert ein FCM-Token.
|
||||
|
||||
Das Token ist projektweit eindeutig. Meldet sich derselbe Browser nach
|
||||
einem Neuladen mit einer neuen Client-ID an, wird der bestehende Eintrag
|
||||
verschoben, statt ein zweites Token anzulegen. Ältere Tokens derselben
|
||||
Client-ID werden entfernt, damit nach einer Token-Rotation keine doppelten
|
||||
Wake-Signale entstehen.
|
||||
"""
|
||||
db = get_db()
|
||||
current = now()
|
||||
db.execute(
|
||||
'DELETE FROM ws_push_tokens '
|
||||
'WHERE tenant_id = ? AND client_id = ? AND token <> ?',
|
||||
(tenant_id, client_id, token)
|
||||
)
|
||||
db.execute(
|
||||
'''INSERT INTO ws_push_tokens
|
||||
(tenant_id, client_id, account_id, token, client_type,
|
||||
platform, auto_position, invalid, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
|
||||
ON CONFLICT(token) DO UPDATE SET
|
||||
tenant_id = excluded.tenant_id,
|
||||
client_id = excluded.client_id,
|
||||
account_id = excluded.account_id,
|
||||
client_type = excluded.client_type,
|
||||
platform = excluded.platform,
|
||||
auto_position = excluded.auto_position,
|
||||
invalid = 0,
|
||||
updated_at = excluded.updated_at''',
|
||||
(tenant_id, client_id, account_id, token, client_type,
|
||||
platform, 1 if auto_position else 0, current, current)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def delete_push_token(tenant_id, token=None, client_id=None, account_id=None):
|
||||
"""Entfernt ein FCM-Token gezielt über Token oder Client-ID."""
|
||||
clauses = ['tenant_id = ?']
|
||||
params = [tenant_id]
|
||||
if token:
|
||||
clauses.append('token = ?')
|
||||
params.append(token)
|
||||
if client_id:
|
||||
clauses.append('client_id = ?')
|
||||
params.append(client_id)
|
||||
if account_id is not None:
|
||||
clauses.append('account_id = ?')
|
||||
params.append(account_id)
|
||||
if len(clauses) == 1:
|
||||
return
|
||||
db = get_db()
|
||||
db.execute(
|
||||
f'DELETE FROM ws_push_tokens WHERE {" AND ".join(clauses)}',
|
||||
tuple(params)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_push_token(tenant_id, client_id):
|
||||
"""Liefert das zuletzt aktualisierte, gültige Token eines Clients."""
|
||||
return get_db().execute(
|
||||
'''SELECT * FROM ws_push_tokens
|
||||
WHERE tenant_id = ? AND client_id = ? AND invalid = 0
|
||||
ORDER BY updated_at DESC, id DESC LIMIT 1''',
|
||||
(tenant_id, client_id)
|
||||
).fetchone()
|
||||
|
||||
|
||||
def mark_push_token_invalid(token):
|
||||
"""Markiert ein von FCM abgelehntes Token als ungültig."""
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'UPDATE ws_push_tokens SET invalid = 1, updated_at = ? WHERE token = ?',
|
||||
(now(), token)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _offline_mobile_wake_query(tenant_id, disconnected_before,
|
||||
re_wake_before=None, group_id=None,
|
||||
auto_position_only=False, client_id=None,
|
||||
limit=500):
|
||||
sql = [
|
||||
'''SELECT c.tenant_id, c.client_id, c.account_id, c.client_type,
|
||||
c.disconnected_at, c.last_wake_at, c.last_wake_reason,
|
||||
p.token, p.platform, p.auto_position
|
||||
FROM ws_clients c
|
||||
JOIN ws_push_tokens p
|
||||
ON p.id = (
|
||||
SELECT p2.id FROM ws_push_tokens p2
|
||||
WHERE p2.tenant_id = c.tenant_id
|
||||
AND p2.client_id = c.client_id
|
||||
AND p2.invalid = 0
|
||||
ORDER BY p2.updated_at DESC, p2.id DESC
|
||||
LIMIT 1
|
||||
)
|
||||
WHERE c.tenant_id = ?
|
||||
AND c.client_type IN ('group_view', 'dispatcher_mobile')
|
||||
AND c.disconnected_at IS NOT NULL
|
||||
AND c.disconnected_at <= ?'''
|
||||
]
|
||||
params = [tenant_id, disconnected_before]
|
||||
|
||||
if client_id is not None:
|
||||
sql.append('AND c.client_id = ?')
|
||||
params.append(client_id)
|
||||
|
||||
if re_wake_before is not None:
|
||||
sql.append(
|
||||
'AND (c.last_wake_at IS NULL OR c.last_wake_at <= ?)'
|
||||
)
|
||||
params.append(re_wake_before)
|
||||
|
||||
if auto_position_only:
|
||||
sql.append("AND (c.client_type = 'dispatcher_mobile' OR p.auto_position = 1)")
|
||||
|
||||
if group_id is not None:
|
||||
sql.append(
|
||||
'''AND EXISTS (
|
||||
SELECT 1 FROM group_accounts ga
|
||||
WHERE ga.tenant_id = c.tenant_id
|
||||
AND ga.account_id = c.account_id
|
||||
AND ga.group_id = ?
|
||||
)'''
|
||||
)
|
||||
params.append(group_id)
|
||||
|
||||
sql.append('ORDER BY c.disconnected_at ASC LIMIT ?')
|
||||
params.append(max(1, int(limit)))
|
||||
return ' '.join(sql), tuple(params)
|
||||
|
||||
|
||||
def offline_mobile_wake_candidates(tenant_id, disconnected_before,
|
||||
re_wake_before=None, group_id=None,
|
||||
auto_position_only=False, client_id=None,
|
||||
limit=500):
|
||||
"""Liefert offline mobile Clients mit gültigem FCM-Token.
|
||||
|
||||
``disconnected_before`` ist der Spätzeitpunkt, zu dem die Trennung
|
||||
eingetreten sein muss (für den regulären Offline-Timeout).
|
||||
``re_wake_before`` verhindert zu häufige Wiederholungen; ``None`` hebt
|
||||
die Sperre auf (manueller Aufruf).
|
||||
``auto_position_only`` berücksichtigt nur Gruppen-Views, bei denen die
|
||||
automatische Positionsübertragung aktiviert ist.
|
||||
"""
|
||||
sql, params = _offline_mobile_wake_query(
|
||||
tenant_id,
|
||||
disconnected_before,
|
||||
re_wake_before=re_wake_before,
|
||||
group_id=group_id,
|
||||
auto_position_only=auto_position_only,
|
||||
client_id=client_id,
|
||||
limit=limit,
|
||||
)
|
||||
return get_db().execute(sql, params).fetchall()
|
||||
|
||||
|
||||
def claim_offline_mobile_wakes(tenant_id, disconnected_before,
|
||||
re_wake_before=None, group_id=None,
|
||||
auto_position_only=False, client_id=None,
|
||||
reason='offline', limit=500):
|
||||
"""Reserviert fällige Wake-Kandidaten prozessübergreifend.
|
||||
|
||||
Mehrere WSGI-Worker dürfen nicht dasselbe FCM-Signal senden. Deshalb
|
||||
werden die Kandidaten in einer ``BEGIN IMMEDIATE``-Transaktion gelesen
|
||||
und ihr ``last_wake_at`` sofort gesetzt. Der tatsächliche FCM-Versand
|
||||
erfolgt erst nach dem Commit.
|
||||
"""
|
||||
db = get_db()
|
||||
if db.in_transaction:
|
||||
db.commit()
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
try:
|
||||
sql, params = _offline_mobile_wake_query(
|
||||
tenant_id,
|
||||
disconnected_before,
|
||||
re_wake_before=re_wake_before,
|
||||
group_id=group_id,
|
||||
auto_position_only=auto_position_only,
|
||||
client_id=client_id,
|
||||
limit=limit,
|
||||
)
|
||||
rows = db.execute(sql, params).fetchall()
|
||||
current = now()
|
||||
for row in rows:
|
||||
db.execute(
|
||||
'UPDATE ws_clients SET last_wake_at = ?, last_wake_reason = ? '
|
||||
'WHERE tenant_id = ? AND client_id = ?',
|
||||
(current, reason, tenant_id, row['client_id'])
|
||||
)
|
||||
db.commit()
|
||||
return rows
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def cleanup_orphan_push_tokens(max_age_seconds):
|
||||
"""Entfernt ungültige sowie verwaiste, lange nicht aktualisierte Tokens."""
|
||||
db = get_db()
|
||||
cutoff = now() - max_age_seconds
|
||||
db.execute(
|
||||
'DELETE FROM ws_push_tokens WHERE invalid = 1'
|
||||
)
|
||||
db.execute(
|
||||
'''DELETE FROM ws_push_tokens
|
||||
WHERE updated_at < ?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM ws_clients c
|
||||
WHERE c.tenant_id = ws_push_tokens.tenant_id
|
||||
AND c.client_id = ws_push_tokens.client_id
|
||||
)''',
|
||||
(cutoff,)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def describe_connections(tenant_id):
|
||||
"""Liefert alle aktuell verbundenen Clients inklusive Account und Gruppe."""
|
||||
rows = get_db().execute(
|
||||
@@ -477,6 +713,10 @@ def cleanup_clients(retention_seconds):
|
||||
'DELETE FROM ws_client_queue WHERE tenant_id = ? AND client_id = ?',
|
||||
(tenant_id, client_id)
|
||||
)
|
||||
db.execute(
|
||||
'DELETE FROM ws_push_tokens WHERE tenant_id = ? AND client_id = ?',
|
||||
(tenant_id, client_id)
|
||||
)
|
||||
db.execute(
|
||||
'DELETE FROM ws_clients WHERE tenant_id = ? AND client_id = ?',
|
||||
(tenant_id, client_id)
|
||||
|
||||
@@ -46,6 +46,64 @@ class Config:
|
||||
# ``<hostname>:<pid>`` ein.
|
||||
WS_WORKER_ID = os.environ.get('CMBNET_WS_WORKER_ID', '')
|
||||
LATE_ENTRY_MAX_AGE_HOURS = int(os.environ.get('CMBNET_LATE_ENTRY_MAX_AGE_HOURS', '8'))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Firebase Cloud Messaging (nur Aufwachsignal, keine Nutzdaten)
|
||||
# ------------------------------------------------------------------
|
||||
FCM_ENABLED = os.environ.get(
|
||||
'CMBNET_FCM_ENABLED', '0'
|
||||
).strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
# Serverseitige Authentifizierung. Entweder eine JSON-Datei oder der
|
||||
# komplette Service-Account-Inhalt als Umgebungsvariable.
|
||||
FCM_SERVICE_ACCOUNT_FILE = os.environ.get(
|
||||
'CMBNET_FCM_SERVICE_ACCOUNT_FILE', ''
|
||||
).strip()
|
||||
FCM_SERVICE_ACCOUNT_JSON = os.environ.get(
|
||||
'CMBNET_FCM_SERVICE_ACCOUNT_JSON', ''
|
||||
).strip()
|
||||
FCM_PROJECT_ID = os.environ.get('CMBNET_FCM_PROJECT_ID', '').strip()
|
||||
|
||||
# Öffentliche Firebase-Webkonfiguration (kein Geheimnis).
|
||||
FCM_WEB_API_KEY = os.environ.get('CMBNET_FCM_WEB_API_KEY', '').strip()
|
||||
FCM_WEB_AUTH_DOMAIN = os.environ.get(
|
||||
'CMBNET_FCM_WEB_AUTH_DOMAIN', ''
|
||||
).strip()
|
||||
FCM_WEB_PROJECT_ID = os.environ.get(
|
||||
'CMBNET_FCM_WEB_PROJECT_ID', ''
|
||||
).strip()
|
||||
FCM_WEB_STORAGE_BUCKET = os.environ.get(
|
||||
'CMBNET_FCM_WEB_STORAGE_BUCKET', ''
|
||||
).strip()
|
||||
FCM_WEB_MESSAGING_SENDER_ID = os.environ.get(
|
||||
'CMBNET_FCM_WEB_MESSAGING_SENDER_ID', ''
|
||||
).strip()
|
||||
FCM_WEB_APP_ID = os.environ.get('CMBNET_FCM_WEB_APP_ID', '').strip()
|
||||
FCM_VAPID_KEY = os.environ.get('CMBNET_FCM_VAPID_KEY', '').strip()
|
||||
FCM_WEB_SDK_VERSION = os.environ.get(
|
||||
'CMBNET_FCM_WEB_SDK_VERSION', '10.14.1'
|
||||
).strip()
|
||||
|
||||
# Nach dieser Zeit ohne WebSocket-Verbindung darf ein mobiler Client
|
||||
# regelmäßig ein Aufwachsignal erhalten. Ein Signal bei einer neu
|
||||
# eingereihten Nachricht wird separat über das Queue-Cooldown begrenzt.
|
||||
FCM_OFFLINE_WAKE_MINUTES = float(os.environ.get(
|
||||
'CMBNET_FCM_OFFLINE_WAKE_MINUTES', '5'
|
||||
))
|
||||
FCM_QUEUE_WAKE_COOLDOWN_SECONDS = int(os.environ.get(
|
||||
'CMBNET_FCM_QUEUE_WAKE_COOLDOWN_SECONDS', '60'
|
||||
))
|
||||
FCM_MANUAL_WAKE_COOLDOWN_SECONDS = int(os.environ.get(
|
||||
'CMBNET_FCM_MANUAL_WAKE_COOLDOWN_SECONDS', '15'
|
||||
))
|
||||
FCM_SIGNAL_TTL_SECONDS = int(os.environ.get(
|
||||
'CMBNET_FCM_SIGNAL_TTL_SECONDS', '600'
|
||||
))
|
||||
FCM_WAKE_POLL_INTERVAL_SECONDS = float(os.environ.get(
|
||||
'CMBNET_FCM_WAKE_POLL_INTERVAL_SECONDS', '30'
|
||||
))
|
||||
FCM_PUSH_TOKEN_RETENTION_MINUTES = int(os.environ.get(
|
||||
'CMBNET_FCM_PUSH_TOKEN_RETENTION_MINUTES', '1440'
|
||||
))
|
||||
# Ausführliche Broker-Debugausgabe für eingehende Nachrichten und den
|
||||
# ermittelten Empfängerkreis. Kann im Betrieb über die Umgebungsvariable
|
||||
# CMBNET_WS_DEBUG_MESSAGES=0 abgeschaltet werden.
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
# FCM-Aufwachsignale für mobile PWA-Clients
|
||||
|
||||
## Zweck
|
||||
|
||||
Mobile Webviews sollen gezielt aus dem Hintergrund geholt werden, damit sie
|
||||
ihre WebSocket-Verbindung erneuern, die persistente Broker-Queue leeren und –
|
||||
bei aktivierter Positionsübertragung – mindestens ein Positionsupdate senden.
|
||||
Google Firebase Cloud Messaging (FCM) transportiert dabei **nur ein Signal**.
|
||||
Chat-Nachrichten, Positionsdaten, Mandanten, Rollen und URLs der Anwendung
|
||||
bleiben ausschließlich in der WebSocket-Kommunikation bzw. in der Datenbank.
|
||||
|
||||
Das Signal besteht aus einem Data-Payload mit den Feldern `type` und `reason`
|
||||
(z. B. `queue`, `offline`, `manual`). Diese Metadaten dienen nur der
|
||||
Protokollierung und der Entscheidung, ob ein sichtbarer Hinweis sinnvoll ist.
|
||||
Sie sind kein Anwendungsinhalt.
|
||||
|
||||
## Beteiligte Komponenten
|
||||
|
||||
| Komponente | Aufgabe |
|
||||
| --- | --- |
|
||||
| `cmbnet/ws/broker.py` | Erkennt nicht zustellbare Nachrichten und fordert ein Wake-Signal an. |
|
||||
| `cmbnet/ws/push.py` | Periodischer Worker für den Offline-Timeout. |
|
||||
| `cmbnet/services/fcm_service.py` | Firebase-Admin-Initialisierung und FCM-Versand. |
|
||||
| `cmbnet/api/push.py` | Token-Registrierung, Abmeldung und manueller Wake-Button. |
|
||||
| `static/js/sw.js` | Empfängt das FCM-Signal, weckt ein Fenster und zeigt ggf. eine Benachrichtigung. |
|
||||
| `static/js/views/mobile.js` | Registriert das Token, verbindet den WebSocket neu und sendet die Position. |
|
||||
| `templates/dispatcher*.html` | Radar-Button zum manuellen Wecken. |
|
||||
|
||||
## Ablauf
|
||||
|
||||
1. Die mobile PWA fordert nach Erlaubnis für Benachrichtigungen ein
|
||||
FCM-Token an. Das Token wird über `POST /<tenant>/api/push/register`
|
||||
zusammen mit Client-ID, Client-Typ und der Einstellung
|
||||
`auto_position` gespeichert.
|
||||
2. Der Broker puffert eine Nachricht für einen getrennten mobilen Client
|
||||
wie bisher in `ws_client_queue`.
|
||||
3. Zusätzlich prüft er, ob ein gültiges FCM-Token vorliegt und ob der Client
|
||||
als getrennt gilt. Wenn ja, sendet er ein FCM-Aufwachsignal.
|
||||
4. Der Service Worker wird durch FCM geweckt. Er kann selbst keine
|
||||
WebSocket-Verbindung betreiben. Deshalb übergibt er den Impuls per
|
||||
`postMessage` an ein bereits geöffnetes PWA-Fenster.
|
||||
5. Die PWA baut den WebSocket neu auf. Der Broker liefert die Queue und die
|
||||
Late Entries aus. Neue Nachrichten lösen wie bisher den In-App-Dialog aus.
|
||||
6. Bei aktivierter automatischer Positionsübertragung sendet die PWA
|
||||
mindestens eine Position. Zuerst wird eine frische Geolocation angefordert;
|
||||
schlägt das im Hintergrund fehl, wird die letzte bekannte Position
|
||||
verwendet.
|
||||
7. Der Service Worker wartet über einen `MessageChannel` bis zu 20 Sekunden
|
||||
auf die Bestätigung der PWA. Erst danach beendet er den Push-Event. Ist
|
||||
kein Fenster erreichbar, zeigt er eine allgemeine Benachrichtigung an.
|
||||
8. Ein Klick auf diese Benachrichtigung öffnet `/<prefix>/wake`. Die Route
|
||||
leitet anhand der bestehenden Session in die passende mobile View. FCM
|
||||
selbst enthält keine Mandanten- oder Rollen-URL.
|
||||
|
||||
## Trigger
|
||||
|
||||
### Gequeuete Nachricht
|
||||
|
||||
Sobald eine Nachricht mit Code `>= 99` für einen getrennten mobilen Client
|
||||
eingereiht wird, versucht der Broker ein FCM-Signal. Mehrere Nachrichten
|
||||
innerhalb des Queue-Cooldowns lösen nur ein Signal aus.
|
||||
|
||||
### Offline-Timeout
|
||||
|
||||
Ein periodischer Worker prüft getrennte Clients. Nach
|
||||
`CMBNET_FCM_OFFLINE_WAKE_MINUTES` (Default 5 Minuten) wird ein Signal gesendet,
|
||||
auch wenn keine Nachricht in der Queue liegt. Damit erhält die Gruppen-View
|
||||
die Gelegenheit, ein Positionsupdate zu senden. Für die Gruppen-View gilt das
|
||||
nur, wenn `auto_position` aktiviert ist; Dispatcher-Mobil-Clients werden
|
||||
ebenfalls berücksichtigt, haben aber keine automatische Positionsübertragung.
|
||||
|
||||
### Manuell
|
||||
|
||||
Der Radar-Button im Desktop-Dispatcher und im mobilen Dispatcher ruft
|
||||
`POST /<tenant>/api/push/wake` auf. Der mobile Dispatcher schränkt den Aufruf
|
||||
auf die aktuell ausgewählte Gruppe ein, sofern eine Gruppe gewählt ist. Der
|
||||
Desktop-Dispatcher weckt alle getrennten mobilen Clients. Ein kurzer Cooldown
|
||||
verhindert versehentliche Doppelklicks.
|
||||
|
||||
## Client-Typen
|
||||
|
||||
Nur diese Werte sind zugelassen:
|
||||
|
||||
- `group_view` für Accounts der Rolle `Gruppe`
|
||||
- `dispatcher_mobile` für Accounts der Rolle `Dispatcher` oder `Administrator`
|
||||
|
||||
Der Typ wird beim Code-0-Handshake vom Client mitgesendet und serverseitig
|
||||
gegen die Session-Rolle geprüft. Ohne gültigen Typ werden keine FCM-Tokens
|
||||
angenommen und keine Wake-Signale versendet. Der Observer-View und der
|
||||
Desktop-Dispatcher erhalten keine FCM-Behandlung.
|
||||
|
||||
## Datenbank
|
||||
|
||||
`ws_clients` wurde ergänzt um:
|
||||
|
||||
- `client_type`: Client-Typ für das FCM-Routing
|
||||
- `last_wake_at`, `last_wake_reason`: Drosselung und Nachvollziehbarkeit
|
||||
|
||||
Neue Tabelle `ws_push_tokens`:
|
||||
|
||||
- ein FCM-Token ist projektweit eindeutig
|
||||
- Zuordnung zu Mandant, Account, Client-ID und Client-Typ
|
||||
- `auto_position` für die periodische Positionsweckung
|
||||
- `invalid` für von FCM abgelehnte Tokens
|
||||
|
||||
Die Registrierung wird bei einem Reload mit neuer Client-ID auf die neue
|
||||
Client-ID verschoben. Nach einer Token-Rotation wird das alte Token derselben
|
||||
Webview entfernt. Verwaiste Tokens werden zusammen mit den Client-Queues
|
||||
aufgeräumt.
|
||||
|
||||
## Mehrere Worker
|
||||
|
||||
Jeder WSGI-Worker besitzt einen eigenen Push-Worker. Die Kandidatenauswahl
|
||||
erfolgt deshalb in einer SQLite-Transaktion (`BEGIN IMMEDIATE`). Der erste
|
||||
Worker reserviert die Clients über `last_wake_at`; alle anderen sehen sie in
|
||||
diesem Lauf nicht mehr. Der eigentliche FCM-Versand findet nach dem Commit
|
||||
statt. Das verhindert doppelte Signale bei mehreren Gunicorn-Workern.
|
||||
|
||||
## Konfiguration
|
||||
|
||||
Alle Werte sind optional; ohne `CMBNET_FCM_ENABLED=1` bleibt FCM vollständig
|
||||
inaktiv:
|
||||
|
||||
| Variable | Default | Bedeutung |
|
||||
| --- | --- | --- |
|
||||
| `CMBNET_FCM_ENABLED` | `0` | FCM aktivieren |
|
||||
| `CMBNET_FCM_SERVICE_ACCOUNT_FILE` | – | Pfad zum Service-Account-JSON |
|
||||
| `CMBNET_FCM_SERVICE_ACCOUNT_JSON` | – | Service Account als JSON-String |
|
||||
| `CMBNET_FCM_PROJECT_ID` | aus Credentials | Firebase-Projekt |
|
||||
| `CMBNET_FCM_WEB_API_KEY` | – | Öffentlicher Web-API-Key |
|
||||
| `CMBNET_FCM_WEB_AUTH_DOMAIN` | `<projekt>.firebaseapp.com` | Auth-Domain |
|
||||
| `CMBNET_FCM_WEB_PROJECT_ID` | `CMBNET_FCM_PROJECT_ID` | Web-Projekt-ID |
|
||||
| `CMBNET_FCM_WEB_STORAGE_BUCKET` | `<projekt>.appspot.com` | Storage-Bucket |
|
||||
| `CMBNET_FCM_WEB_MESSAGING_SENDER_ID` | – | Sender-ID |
|
||||
| `CMBNET_FCM_WEB_APP_ID` | – | Firebase-Web-App-ID |
|
||||
| `CMBNET_FCM_VAPID_KEY` | – | Web-Push-Zertifikat |
|
||||
| `CMBNET_FCM_WEB_SDK_VERSION` | `10.14.1` | Firebase-JS-Version |
|
||||
| `CMBNET_FCM_OFFLINE_WAKE_MINUTES` | `5` | Offline-Timeout |
|
||||
| `CMBNET_FCM_QUEUE_WAKE_COOLDOWN_SECONDS` | `60` | Cooldown je Queue-Wake |
|
||||
| `CMBNET_FCM_MANUAL_WAKE_COOLDOWN_SECONDS` | `15` | Cooldown für den Button |
|
||||
| `CMBNET_FCM_SIGNAL_TTL_SECONDS` | `600` | FCM-TTL |
|
||||
| `CMBNET_FCM_WAKE_POLL_INTERVAL_SECONDS` | `30` | Prüfintervall des Workers |
|
||||
| `CMBNET_FCM_PUSH_TOKEN_RETENTION_MINUTES` | `1440` | Aufbewahrung verwaister Tokens |
|
||||
|
||||
## Beschränkungen und Konsequenzen bei PWAs
|
||||
|
||||
### Allgemein
|
||||
|
||||
- Ein Service Worker kann keine dauerhafte WebSocket-Verbindung halten und
|
||||
keine Seite im Hintergrund starten. Das eigentliche Reconnecten und Senden
|
||||
übernimmt immer ein PWA-Fenster.
|
||||
- Ist die PWA vollständig geschlossen, kann FCM den Service Worker wecken,
|
||||
aber nicht zuverlässig ein Fenster öffnen. Dann bleibt nur eine sichtbare
|
||||
Benachrichtigung; der Nutzer muss sie antippen. Das ist eine Plattform- und
|
||||
keine Implementierungsgrenze.
|
||||
- Ein Wake-Signal ist eine Aufforderung, keine Garantie. Zustellung kann durch
|
||||
Netz, Energiesparmodus, Firebase oder das Betriebssystem verzögert oder
|
||||
zusammengefasst werden.
|
||||
- Ein Positionsupdate ist nur möglich, wenn die Seite tatsächlich läuft und
|
||||
der Browser Geolocation im Hintergrund erlaubt. Andernfalls wird die letzte
|
||||
bekannte Position verwendet oder das Update entfällt.
|
||||
- Die PWA muss über HTTPS ausgeliefert werden. Das Token ist ein
|
||||
installationsbezogenes Geheimnis und sollte nicht geloggt werden.
|
||||
- FCM ist ein Google-Dienst. Verfügbarkeit, Datenschutz und Netzwerkzugriffe
|
||||
müssen betrieblich bewertet werden.
|
||||
|
||||
### Android (Chrome/Edge)
|
||||
|
||||
- Web Push funktioniert in der installierten PWA und im Browser, sofern
|
||||
Benachrichtigungen erlaubt sind.
|
||||
- Chrome kann Hintergrundtabs einfrieren. Der Service Worker bleibt für
|
||||
Push-Events zuständig; die Seite wird beim `postMessage` möglicherweise
|
||||
erst verzögert aktiv.
|
||||
- Hersteller-Energiesparfunktionen und „App beenden“ verhindern Zustellungen.
|
||||
- `clients.openWindow` ist aus einem Push-Event nicht zuverlässig erlaubt;
|
||||
deshalb der Benachrichtigungs-Fallback.
|
||||
|
||||
### iOS/iPadOS (Safari)
|
||||
|
||||
- Web Push ist erst ab iOS/iPadOS 16.4 und nur für zum Home-Bildschirm
|
||||
hinzugefügte PWAs verfügbar. In einem normalen Safari-Tab wird kein
|
||||
FCM-Token registriert.
|
||||
- Benachrichtigungen müssen ausdrücklich erlaubt werden. Ohne Erlaubnis
|
||||
bleibt die App offline, bis sie manuell geöffnet wird.
|
||||
- iOS kann Hintergrund-Pushes stark drosseln oder zusammenfassen. Ein
|
||||
stilles Data-Push ist nicht garantiert; der sichtbare Benachrichtigungs-
|
||||
Fallback ist Teil des Designs.
|
||||
- Hintergrund-Geolocation ist stark eingeschränkt. Das garantierte
|
||||
„mindestens ein Positionsupdate“ gilt deshalb nur, solange die Seite nach
|
||||
dem Wake tatsächlich ausgeführt wird.
|
||||
- APNs/FCM können die Zustellung verweigern, wenn die PWA vom Nutzer
|
||||
entfernt oder die Benachrichtigungserlaubnis entzogen wurde.
|
||||
|
||||
### Konsequenz für die Bedienung
|
||||
|
||||
Die Funktion ist eine beschleunigte Synchronisierung, kein Ersatz für das
|
||||
Öffnen der App. Disponenten sollten bei zeitkritischen Lagen weiterhin den
|
||||
manuellen Radar-Button nutzen und die mobile Gruppe bei Bedarf zusätzlich
|
||||
telefonisch erreichen.
|
||||
@@ -0,0 +1,241 @@
|
||||
# Firebase/FCM einrichten – Howto
|
||||
|
||||
Dieses Dokument beschreibt die praktischen Schritte, um die im Code
|
||||
vorbereiteten FCM-Aufwachsignale für die mobilen PWA-Ansichten zu aktivieren.
|
||||
FCM überträgt ausschließlich das Signal; Nachrichten und Positionen laufen
|
||||
weiterhin über WebSocket und die Broker-Queue. Die Architektur und die
|
||||
Plattformgrenzen stehen in [`FCM_ARCHITEKTUR.md`](FCM_ARCHITEKTUR.md).
|
||||
|
||||
## Voraussetzungen
|
||||
|
||||
- Ein Google-Konto und Zugriff auf die [Firebase Console](https://console.firebase.google.com/).
|
||||
- Die CMBNet-Installation läuft über **HTTPS** (auch im Test). Web Push und
|
||||
Service Worker funktionieren nicht über eine reine HTTP-Adresse, außer auf
|
||||
`localhost`.
|
||||
- Die mobile Ansicht ist als PWA installiert (zum Home-Bildschirm
|
||||
hinzugefügt). Besonders auf iOS/iPadOS ist das Voraussetzung für Web Push.
|
||||
- Python-Umgebung der Anwendung kann Pakete installieren.
|
||||
|
||||
## 1. Firebase-Projekt anlegen
|
||||
|
||||
1. In der Firebase Console **Projekt hinzufügen** wählen.
|
||||
2. Projektnamen vergeben (z. B. `cmbnet-push`) und die Analytics-Option nach
|
||||
Bedarf aktivieren. Für FCM ist Analytics nicht erforderlich.
|
||||
3. Nach dem Anlegen die Projekt-ID notieren. Sie wird später als
|
||||
`CMBNET_FCM_PROJECT_ID` bzw. `CMBNET_FCM_WEB_PROJECT_ID` verwendet.
|
||||
|
||||
## 2. Web-App registrieren
|
||||
|
||||
1. In den **Projekteinstellungen → Allgemein** unter *Meine Apps* die
|
||||
Plattform **Web** (`</>`) hinzufügen.
|
||||
2. Einen Spitznamen vergeben und die App registrieren.
|
||||
3. Den angezeigten `firebaseConfig`-Block notieren. Er enthält ausschließlich
|
||||
öffentliche Werte:
|
||||
|
||||
```js
|
||||
{
|
||||
apiKey: "...",
|
||||
authDomain: "cmbnet-push.firebaseapp.com",
|
||||
projectId: "cmbnet-push",
|
||||
storageBucket: "cmbnet-push.appspot.com",
|
||||
messagingSenderId: "...",
|
||||
appId: "..."
|
||||
}
|
||||
```
|
||||
|
||||
Diese Werte sind **keine Geheimnisse** und werden vom Server an Browser
|
||||
und Service Worker ausgeliefert. Der Service-Account aus Schritt 4 darf
|
||||
dagegen niemals in eine Webseite oder in das Repository gelangen.
|
||||
|
||||
## 3. Cloud Messaging und VAPID-Schlüssel
|
||||
|
||||
1. In der Firebase Console unter **Cloud Messaging** die Web-Push-
|
||||
Konfiguration öffnen.
|
||||
2. Falls noch kein Schlüsselpaar existiert, unter *Web-Push-Zertifikate*
|
||||
ein Schlüsselpaar erzeugen.
|
||||
3. Den angezeigten **VAPID-Schlüssel** (öffentlicher Schlüssel) notieren. Er
|
||||
wird als `CMBNET_FCM_VAPID_KEY` benötigt.
|
||||
4. Die Web-Push-Konfiguration muss zum selben Firebase-Projekt wie die
|
||||
Web-App gehören.
|
||||
|
||||
## 4. Service-Account für den Server erzeugen
|
||||
|
||||
1. In der Firebase Console **Projekteinstellungen → Dienstkonten** öffnen.
|
||||
2. **Neuen privaten Schlüssel generieren** wählen und die JSON-Datei
|
||||
herunterladen.
|
||||
3. Die Datei außerhalb des Repositories ablegen, z. B.
|
||||
`/etc/cmbnet/firebase-service-account.json`, und nur für den
|
||||
Anwendungsbenutzer lesbar machen:
|
||||
|
||||
```bash
|
||||
sudo install -m 600 firebase-service-account.json \
|
||||
/etc/cmbnet/firebase-service-account.json
|
||||
```
|
||||
|
||||
4. Alternativ kann der JSON-Inhalt als eine Zeile in
|
||||
`CMBNET_FCM_SERVICE_ACCOUNT_JSON` gesetzt werden. Für den Dauerbetrieb ist
|
||||
eine Datei mit restriktiven Rechten vorzuziehen, weil Umgebungsvariablen
|
||||
leichter in Prozesslisten oder Logs auftauchen.
|
||||
|
||||
## 5. Python-Abhängigkeit installieren
|
||||
|
||||
FCM nutzt das optionale Paket `firebase-admin`. Es ist in
|
||||
`requirements.txt` eingetragen, muss aber in der aktiven Umgebung installiert
|
||||
sein:
|
||||
|
||||
```bash
|
||||
cd CMBNet
|
||||
source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Ohne dieses Paket startet die Anwendung weiterhin; FCM bleibt dann deaktiviert
|
||||
und protokolliert einen entsprechenden Hinweis.
|
||||
|
||||
## 6. Umgebungsvariablen setzen
|
||||
|
||||
Die Anwendung liest die Konfiguration aus Umgebungsvariablen (siehe
|
||||
`config.py`). Ein vollständiges Beispiel für einen Dienstmanager oder eine
|
||||
`.env`-Datei:
|
||||
|
||||
```bash
|
||||
CMBNET_FCM_ENABLED=1
|
||||
|
||||
# Serverseitiger Versand
|
||||
CMBNET_FCM_PROJECT_ID=cmbnet-push
|
||||
CMBNET_FCM_SERVICE_ACCOUNT_FILE=/etc/cmbnet/firebase-service-account.json
|
||||
# Alternativ statt der Datei:
|
||||
# CMBNET_FCM_SERVICE_ACCOUNT_JSON={"type":"service_account",...}
|
||||
|
||||
# Öffentliche Web-Konfiguration aus Schritt 2
|
||||
CMBNET_FCM_WEB_API_KEY=...
|
||||
CMBNET_FCM_WEB_AUTH_DOMAIN=cmbnet-push.firebaseapp.com
|
||||
CMBNET_FCM_WEB_PROJECT_ID=cmbnet-push
|
||||
CMBNET_FCM_WEB_STORAGE_BUCKET=cmbnet-push.appspot.com
|
||||
CMBNET_FCM_WEB_MESSAGING_SENDER_ID=...
|
||||
CMBNET_FCM_WEB_APP_ID=...
|
||||
|
||||
# Web-Push aus Schritt 3
|
||||
CMBNET_FCM_VAPID_KEY=...
|
||||
|
||||
# Optional: Zeitverhalten
|
||||
CMBNET_FCM_OFFLINE_WAKE_MINUTES=5
|
||||
CMBNET_FCM_QUEUE_WAKE_COOLDOWN_SECONDS=60
|
||||
CMBNET_FCM_MANUAL_WAKE_COOLDOWN_SECONDS=15
|
||||
CMBNET_FCM_WAKE_POLL_INTERVAL_SECONDS=30
|
||||
```
|
||||
|
||||
Die Datei mit den Umgebungsvariablen muss dieselben Rechte wie die
|
||||
Service-Account-Datei besitzen. Nach Änderungen den WSGI-Prozess neu starten;
|
||||
Python liest die Werte beim Start.
|
||||
|
||||
### Prüfen, ob die Konfiguration vollständig ist
|
||||
|
||||
`public_fcm_config()` aktiviert FCM nur, wenn `CMBNET_FCM_ENABLED` gesetzt ist
|
||||
**und** API-Key, Projekt-ID, Sender-ID, App-ID und VAPID-Schlüssel vorhanden
|
||||
sind. Prüfen lässt sich das über die vom Server erzeugte Datei:
|
||||
|
||||
```bash
|
||||
curl -s https://example.com/fcm-sw-config.js
|
||||
```
|
||||
|
||||
Erwartet wird ein JavaScript-Objekt mit `"enabled": true` und gefüllten
|
||||
`firebase`-Werten. Bei `"enabled": false` fehlt mindestens einer der oben
|
||||
genannten Werte oder `firebase-admin` ist nicht installiert.
|
||||
|
||||
## 7. Datenbankmigration
|
||||
|
||||
Beim nächsten Start führt `ensure_schema()` die idempotenten Migrationen aus.
|
||||
Neu sind die Spalten `ws_clients.client_type`, `ws_clients.last_wake_at`,
|
||||
`ws_clients.last_wake_reason` sowie die Tabelle `ws_push_tokens`. Eine
|
||||
manuelle Migration ist nicht nötig; ein Backup der SQLite-Datei vor dem
|
||||
ersten Start ist trotzdem empfehlenswert.
|
||||
|
||||
## 8. Mobile PWA installieren und Benachrichtigungen erlauben
|
||||
|
||||
1. Die mobile Ansicht (Gruppen-View bzw. mobiler Dispatcher) über HTTPS
|
||||
öffnen.
|
||||
2. Im Browsermenü **Zum Home-Bildschirm** bzw. **App installieren** wählen.
|
||||
3. Die PWA aus dem Home-Bildschirm starten.
|
||||
4. In den Einstellungen der mobilen Ansicht **Benachrichtigungen aktivieren**
|
||||
antippen und die Browserabfrage bestätigen.
|
||||
5. Danach lädt die Seite das Firebase-SDK, fordert ein FCM-Token an und
|
||||
registriert es über `POST /<tenant>/api/push/register`. Der Client-Typ
|
||||
(`group_view` bzw. `dispatcher_mobile`) wird dabei gegen die Rolle geprüft.
|
||||
|
||||
Auf iOS/iPadOS muss die App wirklich installiert sein; in einem normalen
|
||||
Safari-Tab wird kein Token registriert. Nach dem Entfernen der PWA vom
|
||||
Home-Bildschirm oder dem Entziehen der Benachrichtigungserlaubnis endet die
|
||||
Zustellung.
|
||||
|
||||
## 9. Funktion testen
|
||||
|
||||
### Token-Registrierung prüfen
|
||||
|
||||
Nach dem Aktivieren der Benachrichtigungen in der Datenbank nachsehen:
|
||||
|
||||
```bash
|
||||
sqlite3 instance/cmbnet.sqlite3 \
|
||||
"SELECT tenant_id, client_id, account_id, client_type, platform, auto_position, invalid
|
||||
FROM ws_push_tokens;"
|
||||
```
|
||||
|
||||
Es muss ein Eintrag für den mobilen Client vorhanden sein. Ein leeres Ergebnis
|
||||
bedeutet meist: keine HTTPS-Verbindung, keine installierte PWA, keine
|
||||
Benachrichtigungserlaubnis oder `enabled: false` in `fcm-sw-config.js`.
|
||||
|
||||
### Manuellen Wake auslösen
|
||||
|
||||
Im Desktop-Dispatcher oder im mobilen Dispatcher den Radar-Button antippen.
|
||||
Der Button ruft `POST /<tenant>/api/push/wake` auf. Die Antwort enthält
|
||||
`candidates`, `sent` und `failed`.
|
||||
|
||||
- `sent > 0`: FCM hat das Signal angenommen.
|
||||
- `candidates = 0`: kein getrennter mobiler Client mit gültigem Token.
|
||||
- HTTP 503: FCM ist nicht vollständig konfiguriert.
|
||||
- HTTP 403: Rolle darf nicht wecken (nur Dispatcher/Administrator).
|
||||
|
||||
Da nur getrennte Clients geweckt werden, muss die mobile PWA vor dem Test
|
||||
geschlossen oder die WebSocket-Verbindung unterbrochen sein.
|
||||
|
||||
### Offline-Timeout prüfen
|
||||
|
||||
`CMBNET_FCM_OFFLINE_WAKE_MINUTES` testweise auf `1` setzen, PWA schließen und
|
||||
nach ein bis zwei Minuten den Radar-Button im Desktop-Dispatcher verwenden.
|
||||
Bei aktiver automatischer Positionsübertragung sollte die Gruppen-View nach
|
||||
dem Wake eine neue Position senden. Der Service Worker zeigt nur dann eine
|
||||
Benachrichtigung, wenn kein PWA-Fenster erreichbar ist.
|
||||
|
||||
### FCM-Versand direkt prüfen
|
||||
|
||||
Bei aktiviertem Debug-Logging des WSGI-Servers erscheinen Warnungen, wenn
|
||||
`firebase-admin` fehlt, die Initialisierung scheitert oder FCM einen Batch
|
||||
ablehnt. Ungültige Tokens werden als `invalid` markiert und nicht mehr
|
||||
verwendet.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Ursache / Lösung |
|
||||
| --- | --- |
|
||||
| `fcm-sw-config.js` liefert `enabled: false` | `CMBNET_FCM_ENABLED` nicht gesetzt oder einer der Web-Werte/VAPID fehlt. |
|
||||
| Kein Token in `ws_push_tokens` | PWA nicht installiert, keine Benachrichtigungserlaubnis, kein HTTPS oder Client-Typ/Rolle passt nicht. |
|
||||
| `firebase-admin ist nicht installiert` im Log | `pip install -r requirements.txt` in der aktiven Umgebung ausführen. |
|
||||
| `FCM-Initialisierung fehlgeschlagen` | Service-Account-Datei fehlt, ist nicht lesbar oder gehört zu einem anderen Projekt. |
|
||||
| `SENDER_ID_MISMATCH` bzw. Token wird ungültig | Web-Konfiguration und Service-Account stammen aus verschiedenen Firebase-Projekten. |
|
||||
| Radar-Button meldet 0 Kandidaten | Der Client ist noch verbunden, hat kein Token oder wurde bereits innerhalb des Cooldowns geweckt. |
|
||||
| iOS erhält keine Push-Nachricht | PWA nicht installiert, iOS < 16.4 oder Benachrichtigungen nicht erlaubt. |
|
||||
| Benachrichtigung erscheint, aber keine Position | Kein PWA-Fenster aktiv oder Standort im Hintergrund nicht erlaubt; die letzte bekannte Position wird verwendet. |
|
||||
| Doppelte Wakes bei mehreren Workern | `CMBNET_FCM_WAKE_POLL_INTERVAL_SECONDS` und `CMBNET_WS_BUS_POLL_INTERVAL` prüfen; die Reservierung erfolgt über `last_wake_at`. |
|
||||
|
||||
## Sicherheit und Datenschutz
|
||||
|
||||
- Der Service-Account-Schlüssel bleibt auf dem Server und gehört nicht ins
|
||||
Repository, in Templates oder in Browser-JavaScript.
|
||||
- FCM-Tokens sind installationsbezogene Kennungen. Sie werden nicht geloggt
|
||||
und beim Abmelden über `DELETE /<tenant>/api/push/register` entfernt.
|
||||
- Das FCM-Signal enthält nur `type` und `reason`. Mandant, Rolle, Nachricht,
|
||||
Absender und Position werden nicht über Firebase übertragen.
|
||||
- Firebase ist ein externer Google-Dienst. Der Betrieb muss die daraus
|
||||
folgenden Datenschutz- und Verfügbarkeitsanforderungen bewerten.
|
||||
- Die PWA muss über HTTPS laufen; der Server sollte nur hinter dem
|
||||
Reverse-Proxy erreichbar sein.
|
||||
@@ -148,12 +148,19 @@ CREATE TABLE IF NOT EXISTS ws_clients (
|
||||
tenant_id INTEGER NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
account_id INTEGER NOT NULL,
|
||||
-- Vom Client gemeldeter Typ. Nur 'group_view' und 'dispatcher_mobile'
|
||||
-- sind für FCM-Aufwachsignale zugelassen.
|
||||
client_type TEXT,
|
||||
last_seq INTEGER NOT NULL DEFAULT 0,
|
||||
worker_id TEXT,
|
||||
authenticated INTEGER NOT NULL DEFAULT 0,
|
||||
connected_at REAL,
|
||||
disconnected_at REAL,
|
||||
queue_started_at REAL,
|
||||
-- Zeitpunkt und Grund des letzten FCM-Aufwachsignals. Verhindert, dass
|
||||
-- mehrere Worker denselben Client im Sekundentakt wecken.
|
||||
last_wake_at REAL,
|
||||
last_wake_reason TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (tenant_id, client_id),
|
||||
@@ -161,6 +168,25 @@ CREATE TABLE IF NOT EXISTS ws_clients (
|
||||
FOREIGN KEY (account_id) REFERENCES accounts(id)
|
||||
);
|
||||
|
||||
-- FCM-Registrierung pro Browserinstallation. Das Token ist projektweit
|
||||
-- eindeutig; ein Browser kann deshalb nur einem Mandanten gleichzeitig
|
||||
-- zugeordnet sein. Der eigentliche Inhalt bleibt in der WebSocket-Queue.
|
||||
CREATE TABLE IF NOT EXISTS ws_push_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
account_id INTEGER NOT NULL,
|
||||
token TEXT UNIQUE NOT NULL,
|
||||
client_type TEXT NOT NULL,
|
||||
platform TEXT,
|
||||
auto_position INTEGER NOT NULL DEFAULT 0,
|
||||
invalid INTEGER NOT NULL DEFAULT 0,
|
||||
created_at REAL NOT NULL,
|
||||
updated_at REAL NOT NULL,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
|
||||
FOREIGN KEY (account_id) REFERENCES accounts(id)
|
||||
);
|
||||
|
||||
-- Persistente Zustellaufträge pro Client. Jeder Worker liefert nur die
|
||||
-- Aufträge seiner eigenen, lokal verbundenen Clients aus.
|
||||
CREATE TABLE IF NOT EXISTS ws_client_queue (
|
||||
@@ -238,6 +264,12 @@ CREATE INDEX IF NOT EXISTS idx_api_tokens_tenant
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_messages_ts ON ws_messages_store(ts);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_clients_account
|
||||
ON ws_clients(tenant_id, account_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_clients_type
|
||||
ON ws_clients(tenant_id, client_type, disconnected_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_push_tokens_client
|
||||
ON ws_push_tokens(tenant_id, client_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_push_tokens_offline
|
||||
ON ws_push_tokens(tenant_id, invalid, client_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_client_queue_client
|
||||
ON ws_client_queue(tenant_id, client_id, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_client_queue_expires
|
||||
|
||||
@@ -4,6 +4,7 @@ flask-sock>=0.7.0
|
||||
simple-websocket>=1.0.0
|
||||
python-dateutil>=2.9.0
|
||||
packaging>=26.3
|
||||
firebase-admin>=6.5.0
|
||||
gevent>=26.9.0
|
||||
greenlet>=3.5.6
|
||||
gunicorn>=26.2.0
|
||||
@@ -237,6 +237,43 @@ html[data-theme="dark"] .mobile-ws-status.is-error {
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.18);
|
||||
}
|
||||
|
||||
.mobile-fab-wake {
|
||||
bottom: calc(12.5rem + env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.mobile-fab-wake.is-busy {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.mobile-toast {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
bottom: calc(4.8rem + env(safe-area-inset-bottom));
|
||||
transform: translate(-50%, 0.5rem);
|
||||
z-index: 3000;
|
||||
max-width: min(22rem, calc(100vw - 2rem));
|
||||
padding: 0.6rem 0.9rem;
|
||||
border-radius: 0.6rem;
|
||||
background: rgba(17, 24, 39, 0.94);
|
||||
color: #fff;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.35;
|
||||
text-align: center;
|
||||
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.28);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
|
||||
.mobile-toast.is-visible {
|
||||
opacity: 1;
|
||||
transform: translate(-50%, 0);
|
||||
}
|
||||
|
||||
.mobile-toast.is-error {
|
||||
background: rgba(153, 27, 27, 0.96);
|
||||
}
|
||||
|
||||
.mobile-work-btn {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
@@ -535,6 +572,9 @@ html[data-theme="dark"] .mobile-chat-card.own {
|
||||
.mobile-fab-secondary {
|
||||
bottom: calc(8.6rem + env(safe-area-inset-bottom));
|
||||
}
|
||||
.mobile-fab-wake {
|
||||
bottom: calc(12rem + env(safe-area-inset-bottom));
|
||||
}
|
||||
}
|
||||
|
||||
/* Im installierten Standalone-Modus keine Browserleisten berücksichtigen. */
|
||||
|
||||
+119
-1
@@ -5,11 +5,49 @@
|
||||
* damit er sowohl die mobilen Views als auch die statischen Assets
|
||||
* kontrolliert. Der Cache-Name wird pro App-Wurzel gebildet.
|
||||
*/
|
||||
const VERSION = 'cmbnet-pwa-v21';
|
||||
const VERSION = 'cmbnet-pwa-v23';
|
||||
const BASE = new URL('./', self.location).href;
|
||||
const SHELL_CACHE = `${VERSION}-shell`;
|
||||
const TILE_CACHE = `${VERSION}-tiles`;
|
||||
const MAX_TILES = 400;
|
||||
const FCM_WAKE_ACK_TIMEOUT_MS = 20000;
|
||||
|
||||
// Die Datei wird von Flask erzeugt und enthält nur die öffentliche
|
||||
// Firebase-Webkonfiguration. Fehlt sie, bleibt FCM in diesem Service Worker
|
||||
// einfach deaktiviert.
|
||||
try {
|
||||
importScripts(new URL('fcm-sw-config.js', self.location).href);
|
||||
} catch (error) {
|
||||
self.CMBNET_FCM_CONFIG = {enabled: false};
|
||||
}
|
||||
|
||||
const fcmConfig = self.CMBNET_FCM_CONFIG || {enabled: false};
|
||||
let fcmMessaging = null;
|
||||
|
||||
if (fcmConfig.enabled) {
|
||||
try {
|
||||
importScripts(
|
||||
`https://www.gstatic.com/firebasejs/${fcmConfig.sdkVersion}/firebase-app-compat.js`,
|
||||
`https://www.gstatic.com/firebasejs/${fcmConfig.sdkVersion}/firebase-messaging-compat.js`
|
||||
);
|
||||
if (!firebase.apps.length) {
|
||||
firebase.initializeApp(fcmConfig.firebase);
|
||||
}
|
||||
fcmMessaging = firebase.messaging();
|
||||
fcmMessaging.onBackgroundMessage(payload => {
|
||||
const reason = payload
|
||||
&& payload.data
|
||||
&& payload.data.reason
|
||||
? payload.data.reason
|
||||
: 'wake';
|
||||
return handleFcmWake(reason);
|
||||
});
|
||||
} catch (error) {
|
||||
// Ohne SDK bleibt die PWA voll funktionsfähig; nur Hintergrund-Wakes
|
||||
// über FCM stehen dann nicht zur Verfügung.
|
||||
console.warn('FCM im Service Worker nicht verfügbar:', error);
|
||||
}
|
||||
}
|
||||
|
||||
const PRECACHE_PATHS = [
|
||||
'static/css/pico.min.css',
|
||||
@@ -105,6 +143,78 @@ async function cacheUrls(urls) {
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* FCM-Aufwachsignal */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function handleFcmWake(reason) {
|
||||
const delivered = await wakeOpenClients(reason);
|
||||
if (!delivered) {
|
||||
await showWakeNotification(reason);
|
||||
}
|
||||
}
|
||||
|
||||
async function wakeOpenClients(reason) {
|
||||
const clientList = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
includeUncontrolled: true
|
||||
});
|
||||
const client = clientList.find(item => item.url.startsWith(BASE));
|
||||
if (!client || typeof client.postMessage !== 'function') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Der Service Worker kann keine WebSocket-Verbindung halten. Er
|
||||
// übergibt den Impuls an die geöffnete PWA und wartet auf deren
|
||||
// Rückmeldung. So bleibt er lange genug aktiv, dass die Seite die
|
||||
// Verbindung aufbauen und mindestens ein Positionsupdate senden kann.
|
||||
const channel = new MessageChannel();
|
||||
const ack = new Promise(resolve => {
|
||||
const timer = setTimeout(() => resolve(false), FCM_WAKE_ACK_TIMEOUT_MS);
|
||||
channel.port1.onmessage = event => {
|
||||
clearTimeout(timer);
|
||||
resolve(Boolean(event.data && event.data.ok));
|
||||
};
|
||||
channel.port1.start();
|
||||
});
|
||||
|
||||
try {
|
||||
client.postMessage(
|
||||
{type: 'cmbnet-wake', reason: reason || 'wake'},
|
||||
[channel.port2]
|
||||
);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ack;
|
||||
}
|
||||
|
||||
async function showWakeNotification(reason) {
|
||||
const body = reason === 'queue'
|
||||
? 'Neue Nachricht eingegangen. Tippe, um die App zu synchronisieren.'
|
||||
: 'Die mobile Ansicht wurde zur Synchronisierung aufgefordert.';
|
||||
const icon = fcmConfig.icon
|
||||
? new URL(fcmConfig.icon, BASE).href
|
||||
: new URL('static/img/icon-192.png', BASE).href;
|
||||
try {
|
||||
await self.registration.showNotification(fcmConfig.title || '20*C+M+B+27', {
|
||||
body,
|
||||
icon,
|
||||
badge: icon,
|
||||
tag: fcmConfig.notificationTag || 'cmbnet-wake',
|
||||
renotify: false,
|
||||
data: {
|
||||
type: 'cmbnet-wake',
|
||||
url: new URL(fcmConfig.wakeUrl || '', BASE).href
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
// Ohne Benachrichtigungsrecht kann kein sichtbarer Fallback erzeugt
|
||||
// werden. Der Push selbst bleibt ein reines Signal.
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Fetch-Strategien */
|
||||
/* ------------------------------------------------------------------ */
|
||||
@@ -277,6 +387,14 @@ self.addEventListener('notificationclick', event => {
|
||||
|
||||
for (const client of clientList) {
|
||||
if (client.url.startsWith(BASE) && 'focus' in client) {
|
||||
// Ein Klick auf ein Aufwachsignal soll die bereits laufende
|
||||
// PWA zusätzlich synchronisieren, ohne dass FCM Inhalte
|
||||
// übertragen musste.
|
||||
if (event.notification.data
|
||||
&& event.notification.data.type === 'cmbnet-wake'
|
||||
&& typeof client.postMessage === 'function') {
|
||||
client.postMessage({type: 'cmbnet-wake', reason: 'notification'});
|
||||
}
|
||||
return client.focus();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3475,6 +3475,10 @@ function bindStaticUi() {
|
||||
if (groupAssignmentButton && window.CMBNET_VIEW_MODE !== 'observer') {
|
||||
groupAssignmentButton.addEventListener('click', openGroupAssignmentModal);
|
||||
}
|
||||
const wakeMobileButton = document.getElementById('wakeMobileButton');
|
||||
if (wakeMobileButton && window.CMBNET_VIEW_MODE !== 'observer') {
|
||||
wakeMobileButton.addEventListener('click', wakeMobileClients);
|
||||
}
|
||||
const streetStateSelect = document.getElementById('streetStateSelect');
|
||||
if (streetStateSelect && window.CMBNET_VIEW_MODE !== 'observer') {
|
||||
streetStateSelect.addEventListener('change', updateStreetGroupVisibility);
|
||||
@@ -3522,6 +3526,35 @@ function sendSpeakerMessage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function wakeMobileClients() {
|
||||
const button = document.getElementById('wakeMobileButton');
|
||||
if (button) button.disabled = true;
|
||||
try {
|
||||
const response = await fetch(`${apiBase}/push/wake`, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: '{}'
|
||||
});
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(result.error || `HTTP ${response.status}`);
|
||||
}
|
||||
const sent = Number(result.sent) || 0;
|
||||
if (sent > 0) {
|
||||
setStreetSearchStatus(`${sent} mobile Clients geweckt.`);
|
||||
} else {
|
||||
setStreetSearchStatus('Keine offline mobilen Clients mit Push-Token gefunden.');
|
||||
}
|
||||
setTimeout(() => setStreetSearchStatus(''), 5000);
|
||||
} catch (error) {
|
||||
setStreetSearchStatus(`Wecken fehlgeschlagen: ${error.message}`, true);
|
||||
setTimeout(() => setStreetSearchStatus(''), 6000);
|
||||
} finally {
|
||||
if (button) button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function showSpeakerQr(text) {
|
||||
const dialog = document.getElementById('speakerQrModal');
|
||||
if (!dialog) return;
|
||||
|
||||
@@ -7,6 +7,10 @@ const apiBase = appUrl(`${tenant}/api`);
|
||||
const wsUrl = `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}${appUrl(`${tenant}/ws`)}`;
|
||||
const storageKey = `cmbnet:${tenant}:mobile`;
|
||||
const viewMode = window.CMBNET_VIEW_MODE || 'mobile_dispatcher';
|
||||
const clientType = window.CMBNET_CLIENT_TYPE
|
||||
|| (viewMode === 'mobile_group'
|
||||
? 'group_view'
|
||||
: (viewMode === 'mobile_dispatcher' ? 'dispatcher_mobile' : null));
|
||||
const currentAccountId = Number(window.CMBNET_ACCOUNT_ID) || null;
|
||||
const currentRole = window.CMBNET_ROLE || null;
|
||||
const appTitle = window.CMBNET_APP_TITLE || '20*C+M+B+27';
|
||||
@@ -24,6 +28,8 @@ const NAVIGATION_REFRESH_MS = 15000;
|
||||
const GROUP_POSITION_LIVE_MS = 30 * 1000;
|
||||
const GROUP_POSITION_RECENT_MS = 5 * 60 * 1000;
|
||||
const WS_OUTBOX_LIMIT = 200;
|
||||
const PUSH_WAKE_AUTH_TIMEOUT_MS = 25000;
|
||||
const scriptPromises = new Map();
|
||||
|
||||
const STREET_STATES = ['unbearbeitet', 'zugewiesen', 'erledigt'];
|
||||
const STREET_COLORS = {
|
||||
@@ -66,7 +72,11 @@ const state = {
|
||||
positionSendTimerId: null,
|
||||
navigationTimerId: null,
|
||||
lastKnownPosition: null,
|
||||
lastPositionSentAt: 0
|
||||
lastPositionSentAt: 0,
|
||||
authWaiters: [],
|
||||
fcmToken: null,
|
||||
fcmMessaging: null,
|
||||
fcmInitializing: false
|
||||
};
|
||||
|
||||
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
||||
@@ -84,6 +94,7 @@ async function initMobile() {
|
||||
registerServiceWorker();
|
||||
initPwaInstall();
|
||||
initNotifications();
|
||||
initPushWakeListener();
|
||||
|
||||
if (viewMode === 'mobile_dispatcher') {
|
||||
try {
|
||||
@@ -174,7 +185,13 @@ function registerServiceWorker() {
|
||||
const swUrl = window.CMBNET_SW_URL || '/sw.js';
|
||||
window.addEventListener('load', () => {
|
||||
navigator.serviceWorker.register(swUrl)
|
||||
.then(cachePolylineScript)
|
||||
.then(registration => {
|
||||
cachePolylineScript();
|
||||
if ('Notification' in window
|
||||
&& Notification.permission === 'granted') {
|
||||
initFirebasePush(registration);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.warn('Service Worker konnte nicht registriert werden.', error);
|
||||
});
|
||||
@@ -305,12 +322,262 @@ async function requestNotifications() {
|
||||
tag: 'cmbnet-permission'
|
||||
});
|
||||
}
|
||||
initFirebasePush(registration, true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Benachrichtigungen konnten nicht aktiviert werden.', error);
|
||||
}
|
||||
}
|
||||
|
||||
function platformName() {
|
||||
if (isIosDevice()) return 'ios';
|
||||
if (/android/i.test(navigator.userAgent)) return 'android';
|
||||
return 'desktop';
|
||||
}
|
||||
|
||||
function loadScriptOnce(url) {
|
||||
if (scriptPromises.has(url)) return scriptPromises.get(url);
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = url;
|
||||
script.async = true;
|
||||
script.onload = () => resolve();
|
||||
script.onerror = () => reject(new Error(`Skript konnte nicht geladen werden: ${url}`));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
scriptPromises.set(url, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function initFirebasePush(registration = null, force = false) {
|
||||
const config = window.CMBNET_FCM_CONFIG;
|
||||
if (!config || !config.enabled || !clientType) return;
|
||||
if (!('Notification' in window) || Notification.permission !== 'granted') return;
|
||||
|
||||
// iOS erlaubt Web Push für PWAs erst im installierten Standalone-Modus.
|
||||
if (isIosDevice() && !isStandaloneMode()) return;
|
||||
|
||||
if (state.fcmToken) {
|
||||
if (force) await syncPushRegistration();
|
||||
return;
|
||||
}
|
||||
if (state.fcmInitializing) return;
|
||||
|
||||
state.fcmInitializing = true;
|
||||
try {
|
||||
const base = `https://www.gstatic.com/firebasejs/${config.sdkVersion}`;
|
||||
await loadScriptOnce(`${base}/firebase-app-compat.js`);
|
||||
await loadScriptOnce(`${base}/firebase-messaging-compat.js`);
|
||||
if (!window.firebase) throw new Error('Firebase SDK nicht verfügbar.');
|
||||
|
||||
if (!firebase.apps.length) {
|
||||
firebase.initializeApp(config.firebase);
|
||||
}
|
||||
if (typeof firebase.messaging.isSupported === 'function'
|
||||
&& !firebase.messaging.isSupported()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const messaging = firebase.messaging();
|
||||
if (typeof messaging.onMessage === 'function') {
|
||||
messaging.onMessage(payload => {
|
||||
const reason = payload
|
||||
&& payload.data
|
||||
&& payload.data.reason
|
||||
? payload.data.reason
|
||||
: 'wake';
|
||||
handlePushWake(reason);
|
||||
});
|
||||
}
|
||||
|
||||
const swRegistration = registration && registration.active
|
||||
? registration
|
||||
: await navigator.serviceWorker.ready;
|
||||
const token = await messaging.getToken({
|
||||
vapidKey: config.vapidKey,
|
||||
serviceWorkerRegistration: swRegistration
|
||||
});
|
||||
if (!token) {
|
||||
console.warn('FCM hat kein Token geliefert.');
|
||||
return;
|
||||
}
|
||||
|
||||
state.fcmToken = token;
|
||||
state.fcmMessaging = messaging;
|
||||
await syncPushRegistration();
|
||||
} catch (error) {
|
||||
console.warn('Firebase-Push konnte nicht initialisiert werden.', error);
|
||||
} finally {
|
||||
state.fcmInitializing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function syncPushRegistration() {
|
||||
if (!state.fcmToken) return;
|
||||
try {
|
||||
await fetchJson(`${apiBase}/push/register`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
token: state.fcmToken,
|
||||
client_id: window.CMBNET_CLIENT_ID
|
||||
|| window.CMBNET_CLIENT_SESSION_ID
|
||||
|| '',
|
||||
client_type: clientType,
|
||||
platform: platformName(),
|
||||
auto_position: state.settings.autoSendPosition === true
|
||||
})
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('FCM-Token konnte nicht beim Server registriert werden.', error);
|
||||
}
|
||||
}
|
||||
|
||||
function initPushWakeListener() {
|
||||
if (!('serviceWorker' in navigator)) return;
|
||||
navigator.serviceWorker.addEventListener('message', event => {
|
||||
if (!event.data || event.data.type !== 'cmbnet-wake') return;
|
||||
const port = event.ports && event.ports[0];
|
||||
handlePushWake(event.data.reason || 'wake', port);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForWsAuthentication(timeoutMs = PUSH_WAKE_AUTH_TIMEOUT_MS) {
|
||||
if (state.authenticated) return Promise.resolve(true);
|
||||
return new Promise(resolve => {
|
||||
const waiter = {resolve, timer: null};
|
||||
waiter.timer = setTimeout(() => {
|
||||
const index = state.authWaiters.indexOf(waiter);
|
||||
if (index >= 0) state.authWaiters.splice(index, 1);
|
||||
resolve(false);
|
||||
}, timeoutMs);
|
||||
state.authWaiters.push(waiter);
|
||||
});
|
||||
}
|
||||
|
||||
function resolveWsAuthentication() {
|
||||
const waiters = state.authWaiters.splice(0);
|
||||
waiters.forEach(waiter => {
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.resolve(true);
|
||||
});
|
||||
}
|
||||
|
||||
async function handlePushWake(reason, port = null) {
|
||||
let ok = false;
|
||||
let positionSent = false;
|
||||
try {
|
||||
// Der Service Worker kann selbst keine WebSocket-Verbindung halten.
|
||||
// Er stößt hier den Reconnect an und wartet über den MessagePort, bis
|
||||
// die Authentifizierung abgeschlossen ist.
|
||||
connectWebSocket();
|
||||
ok = await waitForWsAuthentication();
|
||||
if (ok && viewMode === 'mobile_group' && state.settings.autoSendPosition) {
|
||||
positionSent = await sendWakePosition();
|
||||
}
|
||||
} finally {
|
||||
if (port) {
|
||||
port.postMessage({ok, positionSent, reason});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sendWakePosition() {
|
||||
if (!state.settings.autoSendPosition || viewMode !== 'mobile_group') {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
if (!navigator.geolocation) {
|
||||
return Promise.resolve(sendAutomaticPosition(true));
|
||||
}
|
||||
|
||||
return new Promise(resolve => {
|
||||
let settled = false;
|
||||
const finish = (sent) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve(Boolean(sent));
|
||||
};
|
||||
const fallback = setTimeout(() => {
|
||||
finish(sendAutomaticPosition(true));
|
||||
}, 8000);
|
||||
|
||||
navigator.geolocation.getCurrentPosition(position => {
|
||||
if (settled) return;
|
||||
clearTimeout(fallback);
|
||||
const lat = Number(position.coords.latitude);
|
||||
const lon = Number(position.coords.longitude);
|
||||
const previous = state.lastKnownPosition;
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
|
||||
finish(sendAutomaticPosition(true));
|
||||
return;
|
||||
}
|
||||
state.lastKnownPosition = {
|
||||
lat,
|
||||
lon,
|
||||
accuracy: position.coords.accuracy
|
||||
};
|
||||
updateHeadingFromGps(position, previous);
|
||||
updateOwnPositionMarker(lat, lon);
|
||||
finish(sendOwnPosition(lat, lon, true));
|
||||
}, () => {
|
||||
clearTimeout(fallback);
|
||||
finish(sendAutomaticPosition(true));
|
||||
}, {enableHighAccuracy: true, maximumAge: 60000, timeout: 8000});
|
||||
});
|
||||
}
|
||||
|
||||
function showMobileToast(message, isError = false) {
|
||||
let toast = document.getElementById('mobileToast');
|
||||
if (!toast) {
|
||||
toast = document.createElement('div');
|
||||
toast.id = 'mobileToast';
|
||||
toast.className = 'mobile-toast';
|
||||
toast.setAttribute('role', 'status');
|
||||
toast.setAttribute('aria-live', 'polite');
|
||||
document.body.appendChild(toast);
|
||||
}
|
||||
toast.textContent = message;
|
||||
toast.classList.toggle('is-error', Boolean(isError));
|
||||
toast.classList.add('is-visible');
|
||||
clearTimeout(showMobileToast._timer);
|
||||
showMobileToast._timer = setTimeout(() => {
|
||||
toast.classList.remove('is-visible');
|
||||
}, 4000);
|
||||
}
|
||||
|
||||
async function wakeMobileClientsFromUi() {
|
||||
const button = document.getElementById('mobileWakeBtn');
|
||||
if (button) {
|
||||
button.disabled = true;
|
||||
button.classList.add('is-busy');
|
||||
}
|
||||
try {
|
||||
const body = viewMode === 'mobile_dispatcher' && state.currentGroupId
|
||||
? {group_id: state.currentGroupId}
|
||||
: {};
|
||||
const result = await fetchJson(`${apiBase}/push/wake`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const sent = Number(result.sent) || 0;
|
||||
if (sent > 0) {
|
||||
showMobileToast(`${sent} mobile Clients geweckt.`);
|
||||
} else {
|
||||
showMobileToast('Keine offline mobilen Clients mit Push-Token gefunden.');
|
||||
}
|
||||
} catch (error) {
|
||||
showMobileToast(`Wecken fehlgeschlagen: ${error.message}`, true);
|
||||
} finally {
|
||||
if (button) {
|
||||
setTimeout(() => {
|
||||
button.disabled = false;
|
||||
button.classList.remove('is-busy');
|
||||
}, 800);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function loadSettings() {
|
||||
try {
|
||||
const raw = localStorage.getItem(storageKey);
|
||||
@@ -530,7 +797,23 @@ function refreshMobileMap() {
|
||||
|
||||
function bindButtons() {
|
||||
const logout = document.getElementById('mobileLogout');
|
||||
if (logout) logout.addEventListener('click', () => {window.location.href = window.CMBNET_LOGOUT_URL || appUrl('');});
|
||||
if (logout) {
|
||||
logout.addEventListener('click', () => {
|
||||
if (state.fcmToken) {
|
||||
// Das Token darf nach dem Abmelden keine weiteren
|
||||
// Aufwachsignale für dieses Konto erhalten. keepalive
|
||||
// erlaubt den Request noch während der Navigation.
|
||||
fetch(`${apiBase}/push/register`, {
|
||||
method: 'DELETE',
|
||||
credentials: 'same-origin',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({token: state.fcmToken}),
|
||||
keepalive: true
|
||||
}).catch(() => {});
|
||||
}
|
||||
window.location.href = window.CMBNET_LOGOUT_URL || appUrl('');
|
||||
});
|
||||
}
|
||||
|
||||
const todoBtn = document.getElementById('mobileTodoBtn');
|
||||
if (todoBtn) todoBtn.addEventListener('click', openStreetSelectDialog);
|
||||
@@ -590,6 +873,7 @@ function bindButtons() {
|
||||
state.settings.autoSendPosition = autoPositionToggle.checked;
|
||||
saveSettings();
|
||||
updatePositionSharingUi();
|
||||
syncPushRegistration();
|
||||
if (state.settings.autoSendPosition && state.lastKnownPosition) {
|
||||
state.lastPositionSentAt = 0;
|
||||
sendAutomaticPosition();
|
||||
@@ -600,6 +884,10 @@ function bindButtons() {
|
||||
if (sendPositionBtn) {
|
||||
sendPositionBtn.addEventListener('click', sendPositionNow);
|
||||
}
|
||||
const wakeBtn = document.getElementById('mobileWakeBtn');
|
||||
if (wakeBtn) {
|
||||
wakeBtn.addEventListener('click', wakeMobileClientsFromUi);
|
||||
}
|
||||
updatePositionSharingUi();
|
||||
}
|
||||
|
||||
@@ -1440,7 +1728,10 @@ function connectWebSocket() {
|
||||
setMobileWsStatus('Anmeldung …', 'connecting');
|
||||
ws.send(JSON.stringify({
|
||||
code: 0,
|
||||
msg: token,
|
||||
msg: {
|
||||
token: token,
|
||||
client_type: clientType
|
||||
},
|
||||
client_id: window.CMBNET_CLIENT_ID
|
||||
|| window.CMBNET_CLIENT_SESSION_ID
|
||||
|| ''
|
||||
@@ -1456,6 +1747,9 @@ function connectWebSocket() {
|
||||
state.authenticated = true;
|
||||
setMobileWsStatus('verbunden', 'connected');
|
||||
flushWsOutbox();
|
||||
// Ältere Server ohne Code-0-Bestätigung sollen ein
|
||||
// FCM-Wake nicht unnötig lange blockieren.
|
||||
resolveWsAuthentication();
|
||||
}
|
||||
}, 1500);
|
||||
});
|
||||
@@ -1772,6 +2066,7 @@ function handleWs(event) {
|
||||
state.authenticated = true;
|
||||
setMobileWsStatus('verbunden', 'connected');
|
||||
flushWsOutbox();
|
||||
resolveWsAuthentication();
|
||||
} else if (message.code === 1) {
|
||||
setMobileWsStatus('verbunden', 'connected');
|
||||
if (state.ws && state.ws.readyState === WebSocket.OPEN) {
|
||||
|
||||
@@ -50,6 +50,21 @@
|
||||
<div class="header-action-buttons">
|
||||
<button type="button" id="speakerButton" class="icon-button"
|
||||
title="Nachricht an alle senden" aria-label="Nachricht an alle senden">📢</button>
|
||||
<button type="button" id="wakeMobileButton" class="icon-button"
|
||||
title="Offline mobile Clients wecken"
|
||||
aria-label="Offline mobile Clients wecken">
|
||||
<svg viewBox="0 0 24 24" width="22" height="22"
|
||||
aria-hidden="true" focusable="false">
|
||||
<circle cx="12" cy="12" r="8.5" fill="none"
|
||||
stroke="currentColor" stroke-width="1.7"/>
|
||||
<circle cx="12" cy="12" r="4.5" fill="none"
|
||||
stroke="currentColor" stroke-width="1.4" opacity="0.65"/>
|
||||
<path d="M12 12 17.8 6.2" fill="none"
|
||||
stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round"/>
|
||||
<circle cx="12" cy="12" r="1.6" fill="currentColor"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button type="button" id="groupAssignmentButton"
|
||||
class="icon-button group-assignment-button"
|
||||
title="Gruppen-Accounts zuordnen"
|
||||
|
||||
@@ -55,6 +55,16 @@
|
||||
</svg>
|
||||
</button>
|
||||
<button type="button" id="mobileSettingsBtn" class="mobile-fab mobile-fab-secondary" title="Einstellungen" aria-label="Einstellungen">⚙</button>
|
||||
<button type="button" id="mobileWakeBtn" class="mobile-fab mobile-fab-secondary mobile-fab-wake"
|
||||
title="Mobile Clients wecken" aria-label="Mobile Clients wecken">
|
||||
<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true" focusable="false">
|
||||
<circle cx="12" cy="12" r="8.5" fill="none" stroke="currentColor" stroke-width="1.7"/>
|
||||
<circle cx="12" cy="12" r="4.5" fill="none" stroke="currentColor" stroke-width="1.4" opacity="0.65"/>
|
||||
<path d="M12 12 17.8 6.2" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round"/>
|
||||
<circle cx="12" cy="12" r="1.6" fill="currentColor"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button type="button" id="mobileWorkBtn" class="mobile-work-btn" title="Straße bearbeiten" aria-label="Straße bearbeiten">Bearbeiten</button>
|
||||
</section>
|
||||
|
||||
@@ -129,6 +139,10 @@
|
||||
<span>Benachrichtigungen</span>
|
||||
<button type="button" id="mobileNotifyBtn" class="secondary mobile-settings-button">Aktivieren</button>
|
||||
</div>
|
||||
<p class="mobile-dialog-hint">
|
||||
Hintergrund-Signale benötigen eine installierte PWA und die
|
||||
Erlaubnis für Benachrichtigungen.
|
||||
</p>
|
||||
</div>
|
||||
<footer>
|
||||
<button type="button" onclick="closeMobileSettings()">Schließen</button>
|
||||
@@ -150,6 +164,8 @@
|
||||
window.CMBNET_MANIFEST_URL = {{ url_for('views.manifest', tenant=session.tenant_code)|tojson }};
|
||||
window.CMBNET_ICON_URL = {{ url_for('static', filename='img/icon-192.png')|tojson }};
|
||||
window.CMBNET_VIEW_MODE = 'mobile_dispatcher';
|
||||
window.CMBNET_CLIENT_TYPE = 'dispatcher_mobile';
|
||||
window.CMBNET_FCM_CONFIG = {{ fcm_public_config()|tojson }};
|
||||
</script>
|
||||
<script src="{{ url_for('static', filename='js/leaflet.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename=str2pl_asset()) }}?v={{ str2pl_asset_version() }}"></script>
|
||||
|
||||
@@ -134,6 +134,10 @@
|
||||
<span>Benachrichtigungen</span>
|
||||
<button type="button" id="mobileNotifyBtn" class="secondary mobile-settings-button">Aktivieren</button>
|
||||
</div>
|
||||
<p class="mobile-dialog-hint">
|
||||
Hintergrund-Signale benötigen eine installierte PWA und die
|
||||
Erlaubnis für Benachrichtigungen.
|
||||
</p>
|
||||
</div>
|
||||
<footer>
|
||||
<button type="button" onclick="closeMobileSettings()">Schließen</button>
|
||||
@@ -155,6 +159,8 @@
|
||||
window.CMBNET_MANIFEST_URL = {{ url_for('views.manifest', tenant=session.tenant_code)|tojson }};
|
||||
window.CMBNET_ICON_URL = {{ url_for('static', filename='img/icon-192.png')|tojson }};
|
||||
window.CMBNET_VIEW_MODE = 'mobile_group';
|
||||
window.CMBNET_CLIENT_TYPE = 'group_view';
|
||||
window.CMBNET_FCM_CONFIG = {{ fcm_public_config()|tojson }};
|
||||
</script>
|
||||
<script src="{{ url_for('static', filename='js/leaflet.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename=str2pl_asset()) }}?v={{ str2pl_asset_version() }}"></script>
|
||||
|
||||
Reference in new issue
Block a user