Firebase Cloud Messaging 1. Versuch

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

No files matched your search

+51 -2
View File
@@ -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
View File
@@ -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
+150
View File
@@ -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'),
})
+47 -1
View File
@@ -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()
+277
View File
@@ -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()
+87 -5
View File
@@ -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):
+34
View File
@@ -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
+5 -2
View File
@@ -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
+103
View File
@@ -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 -9
View File
@@ -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
View File
@@ -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)