File size: 3,659 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""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

    @property
    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")}


@lru_cache
def get_push_client() -> PushClient:
    return PushClient(get_settings())