Spaces:
Running on T4
Running on T4
Download backend/app/integrations/push.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 3.66 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/integrations/push.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/app/integrations/push.py
-
curl -L -o push.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/integrations/push.py
3.66 kB
| """Push notifications through Firebase Cloud Messaging (HTTP v1), which also delivers to APNs. | |
| Without FCM settings (dev, tests) sending is logged and skipped. send() returns the tokens FCM reports as | |
| unregistered or invalid so the caller can delete those device rows. | |
| """ | |
| import asyncio | |
| import logging | |
| from functools import lru_cache | |
| import httpx | |
| from app.core.config import Settings, get_settings | |
| log = logging.getLogger(__name__) | |
| _SCOPE = "https://www.googleapis.com/auth/firebase.messaging" | |
| _DEAD_TOKEN_CODES = {"UNREGISTERED", "INVALID_ARGUMENT"} | |
| class PushClient: | |
| def __init__(self, settings: Settings): | |
| self.project_id = settings.fcm_project_id | |
| self.service_account_file = settings.fcm_service_account_file | |
| self._credentials = None | |
| def configured(self) -> bool: | |
| return bool(self.project_id and self.service_account_file) | |
| def _access_token(self) -> str: | |
| from google.auth.transport.requests import Request | |
| from google.oauth2 import service_account | |
| if self._credentials is None: | |
| self._credentials = service_account.Credentials.from_service_account_file( | |
| self.service_account_file, scopes=[_SCOPE]) | |
| if not self._credentials.valid: | |
| self._credentials.refresh(Request()) | |
| return self._credentials.token | |
| async def send(self, tokens: list[str], data: dict, notification: dict | None = None) -> list[str]: | |
| """Sends one message per token. Never raises; returns the tokens that should be forgotten.""" | |
| if not tokens: | |
| return [] | |
| if not self.configured: | |
| log.info("push not configured; skipping %s to %d device(s)", data.get("type"), len(tokens)) | |
| return [] | |
| try: | |
| access_token = await asyncio.to_thread(self._access_token) | |
| except Exception: | |
| log.exception("push: could not get an FCM access token") | |
| return [] | |
| url = f"https://fcm.googleapis.com/v1/projects/{self.project_id}/messages:send" | |
| payload_data = {k: str(v) for k, v in data.items()} # FCM data values must be strings | |
| async with httpx.AsyncClient(timeout=10, headers={"Authorization": f"Bearer {access_token}"}) as client: | |
| results = await asyncio.gather( | |
| *(self._send_one(client, url, token, payload_data, notification) for token in tokens)) | |
| return [token for token, dead in zip(tokens, results, strict=True) if dead] | |
| async def _send_one(self, client: httpx.AsyncClient, url: str, token: str, data: dict, | |
| notification: dict | None) -> bool: | |
| message: dict = {"token": token, "data": data} | |
| if notification: | |
| message["notification"] = notification | |
| try: | |
| response = await client.post(url, json={"message": message}) | |
| except httpx.HTTPError: | |
| log.warning("push: request failed", exc_info=True) | |
| return False | |
| if response.is_success: | |
| return False | |
| codes = _error_codes(response) | |
| log.warning("push: FCM returned %s %s", response.status_code, codes) | |
| return bool(codes & _DEAD_TOKEN_CODES) | |
| def _error_codes(response: httpx.Response) -> set[str]: | |
| try: | |
| error = response.json().get("error", {}) | |
| except ValueError: | |
| return set() | |
| # The FCM error code (UNREGISTERED, INVALID_ARGUMENT, ...) is in details, not in the generic status. | |
| return {d["errorCode"] for d in error.get("details", []) if isinstance(d, dict) and d.get("errorCode")} | |
| def get_push_client() -> PushClient: | |
| return PushClient(get_settings()) | |