56 lines
1.4 KiB
Python
56 lines
1.4 KiB
Python
import logging
|
|
from django.conf import settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_app = None
|
|
|
|
|
|
def _get_app():
|
|
global _app
|
|
if _app is not None:
|
|
return _app
|
|
|
|
credentials_file = settings.FIREBASE_CREDENTIALS_FILE
|
|
if not credentials_file:
|
|
return None
|
|
|
|
import firebase_admin
|
|
from firebase_admin import credentials
|
|
|
|
try:
|
|
cred = credentials.Certificate(credentials_file)
|
|
_app = firebase_admin.initialize_app(cred)
|
|
except Exception:
|
|
logger.exception("Failed to initialise Firebase app")
|
|
return None
|
|
|
|
return _app
|
|
|
|
|
|
def send_notification(fcm_token, *, title, body, data=None):
|
|
"""
|
|
Send a single FCM push notification.
|
|
Silently no-ops if Firebase is not configured (e.g. in development).
|
|
`data` values must all be strings.
|
|
"""
|
|
if not fcm_token:
|
|
return
|
|
|
|
app = _get_app()
|
|
if app is None:
|
|
logger.debug("FCM not configured — skipping notification: %s", title)
|
|
return
|
|
|
|
from firebase_admin import messaging
|
|
|
|
message = messaging.Message(
|
|
notification=messaging.Notification(title=title, body=body),
|
|
data={k: str(v) for k, v in (data or {}).items()},
|
|
token=fcm_token,
|
|
)
|
|
try:
|
|
messaging.send(message)
|
|
except Exception:
|
|
logger.exception("Failed to send FCM notification to token %s", fcm_token[:10])
|