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
@@ -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'),
|
||||
})
|
||||
Reference in new issue
Block a user