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