167 lines
5.5 KiB
Python
167 lines
5.5 KiB
Python
"""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 mobile Clients aus.
|
||
|
||
Optional kann mit ``group_id`` auf die Clients einer Gruppe eingeschränkt
|
||
werden. Angesprochen werden alle mobilen Clients mit gültigem FCM-Token,
|
||
unabhängig davon, ob der Broker sie noch als verbunden führt. Gerade auf
|
||
iOS bleibt der Verbindungsstatus häufig veraltet, obwohl der Push-Kanal
|
||
weiterhin funktioniert.
|
||
"""
|
||
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()
|
||
stats = store.mobile_push_stats(g.tenant_id)
|
||
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,
|
||
# Der Button soll alle registrierten mobilen Clients erreichen – auch
|
||
# solche, die der Broker noch als verbunden führt (typisch bei iOS).
|
||
include_connected=True,
|
||
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)
|
||
|
||
current_app.logger.info(
|
||
'FCM-Wake manuell: tenant=%s group=%s tokens=%s verbunden=%s '
|
||
'candidates=%s sent=%s failed=%s',
|
||
g.tenant_id, group_id, stats['valid_tokens'], stats['connected'],
|
||
len(candidates), int(result.get('sent') or 0),
|
||
int(result.get('failed') or 0)
|
||
)
|
||
|
||
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),
|
||
'valid_tokens': stats['valid_tokens'],
|
||
'connected': stats['connected'],
|
||
'error': result.get('error'),
|
||
})
|