Coverage for api/push.py: 76.19%
255 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:03 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:03 +0000
1"""
2Web Push notifications API.
4User-managed push subscriptions and team follows. Backs SB-51 (slice 5 of
5the mobile app epic SB-44).
7Endpoints:
8- GET /api/push/vapid-public-key — unauthenticated
9- POST /api/users/me/push-subscriptions — register a device
10- GET /api/users/me/push-subscriptions — list user's devices
11- DELETE /api/users/me/push-subscriptions/{id} — revoke
12- POST /api/users/me/apns-devices — register an iOS device (SB-1236)
13- GET /api/users/me/apns-devices — list user's iOS devices
14- DELETE /api/users/me/apns-devices/{id} — revoke an iOS device
15- POST /api/users/me/fcm-devices — register an Android device (SB-1463)
16- GET /api/users/me/fcm-devices — list user's Android devices
17- DELETE /api/users/me/fcm-devices/{id} — revoke an Android device
18- POST /api/users/me/team-follows — follow {team_id}: every age group; with
19 age_group_id, that squad only (SB-1618)
20- GET /api/users/me/team-follows — list follows + team/club + age group
21- DELETE /api/users/me/team-follows/{team_id} — unfollow the team (all rows), or
22 ?age_group_id=N for one squad (SB-1608)
23- GET /api/users/me/notification-preferences — per-event opt-in flags (SB-57)
24- PUT /api/users/me/notification-preferences — update per-event opt-in flags (SB-57)
25- POST /api/users/me/notifications/test — send a test push (web + iOS + Android)
26"""
28from __future__ import annotations
30from typing import Annotated, Any, Literal
32import structlog
33from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
34from pydantic import BaseModel, Field, StringConstraints
36from auth import get_current_user_required
37from dao.apns_device_dao import ApnsDeviceDAO
38from dao.bracket_follow_dao import BracketFollowDAO
39from dao.fcm_device_dao import FcmDeviceDAO
40from dao.match_dao import SupabaseConnection
41from dao.notification_preferences_dao import NotificationPreferencesDAO
42from dao.push_send_log_dao import PushSendLogDAO
43from dao.push_subscription_dao import PushSubscriptionDAO
44from dao.team_follow_dao import TeamFollowDAO
45from notifications.apns_sender import is_configured as apns_is_configured
46from notifications.apns_sender import send_apns
47from notifications.fcm_sender import is_configured as fcm_is_configured
48from notifications.fcm_sender import send_fcm
49from notifications.preferences import EVENT_TYPES
50from notifications.web_push_sender import (
51 get_public_key as get_vapid_public_key,
52)
53from notifications.web_push_sender import (
54 is_configured as push_is_configured,
55)
56from notifications.web_push_sender import (
57 send_push,
58)
60logger = structlog.get_logger(__name__)
62router = APIRouter(prefix="/api", tags=["push-notifications"])
65# ---------------------------------------------------------------------------
66# Lazy connection + DAO singletons
67# ---------------------------------------------------------------------------
69_connection: SupabaseConnection | None = None
72def _conn() -> SupabaseConnection:
73 global _connection
74 if _connection is None:
75 _connection = SupabaseConnection()
76 return _connection
79def _sub_dao() -> PushSubscriptionDAO:
80 return PushSubscriptionDAO(_conn())
83def _apns_dao() -> ApnsDeviceDAO:
84 return ApnsDeviceDAO(_conn())
87def _fcm_dao() -> FcmDeviceDAO:
88 return FcmDeviceDAO(_conn())
91def _follow_dao() -> TeamFollowDAO:
92 return TeamFollowDAO(_conn())
95def _bracket_follow_dao() -> BracketFollowDAO:
96 return BracketFollowDAO(_conn())
99def _log_dao() -> PushSendLogDAO:
100 return PushSendLogDAO(_conn())
103def _prefs_dao() -> NotificationPreferencesDAO:
104 return NotificationPreferencesDAO(_conn())
107def _user_id(user: dict[str, Any]) -> str:
108 """auth.py's current_user dict uses either 'user_id' or 'id'."""
109 uid = user.get("user_id") or user.get("id")
110 if not uid: 110 ↛ 111line 110 didn't jump to line 111 because the condition on line 110 was never true
111 raise HTTPException(status_code=401, detail="Missing user identity")
112 return str(uid)
115# ---------------------------------------------------------------------------
116# Rate limiter (reuse the fail-open Redis pattern from club_notifications)
117# ---------------------------------------------------------------------------
120def _check_test_rate_limit(user_id: str) -> None:
121 """10 test sends per minute per user. Fail-open via the existing helper."""
122 try:
123 from api.club_notifications import check_rate_limit
124 except Exception:
125 return # if the helper isn't importable, skip (defense-in-depth)
126 if not check_rate_limit(f"push:test:{user_id}", max_per_minute=10):
127 raise HTTPException(
128 status_code=status.HTTP_429_TOO_MANY_REQUESTS,
129 detail="Too many test notifications — try again in a minute.",
130 )
133# ---------------------------------------------------------------------------
134# Pydantic models
135# ---------------------------------------------------------------------------
138class PushSubscriptionKeys(BaseModel):
139 """The two keys returned by the browser's PushManager.subscribe()."""
141 p256dh: str = Field(..., min_length=1, max_length=200)
142 auth: str = Field(..., min_length=1, max_length=100)
145class PushSubscriptionIn(BaseModel):
146 """Body of POST /api/users/me/push-subscriptions."""
148 endpoint: str = Field(..., min_length=1, max_length=2000)
149 keys: PushSubscriptionKeys
150 device_label: str | None = Field(None, max_length=100)
151 user_agent: str | None = Field(None, max_length=500)
154class ApnsDeviceIn(BaseModel):
155 """Body of POST /api/users/me/apns-devices (SB-1236).
157 device_token is the hex string of the token from
158 registerForRemoteNotifications() — 64 chars today; Apple says not to
159 assume a fixed length, hence the range.
160 """
162 device_token: str = Field(..., pattern=r"^[0-9a-fA-F]{64,200}$")
163 environment: Literal["sandbox", "production"]
164 device_label: str | None = Field(None, max_length=100)
165 app_version: str | None = Field(None, max_length=50)
168class FcmDeviceIn(BaseModel):
169 """Body of POST /api/users/me/fcm-devices (SB-1463).
171 fid is the Firebase Installation ID from FirebaseInstallations.getId()
172 (~22 chars of base64url today). FCM v1 addresses devices by it;
173 registration tokens are deprecated. Stripped, then capped well under the
174 unique index's btree row limit.
175 """
177 fid: Annotated[
178 str,
179 StringConstraints(strip_whitespace=True, min_length=1, max_length=255, pattern=r"^[A-Za-z0-9_:\-]+$"),
180 ]
181 app_version: str | None = Field(None, max_length=50)
182 device_label: str | None = Field(None, max_length=100)
185class TeamFollowIn(BaseModel):
186 """Body of POST /api/users/me/team-follows.
188 Without age_group_id: every age group of the team (what the mobile apps
189 send). With it: that squad only (SB-1618), from any club.
190 """
192 team_id: int = Field(..., ge=1)
193 age_group_id: int | None = Field(None, ge=1)
196class BracketFollowIn(BaseModel):
197 """Body of POST /api/users/me/bracket-follows.
199 A bracket is (tournament_id, tournament_group, age_group_id) — e.g.
200 "Bracket A · U14". Following it delivers a push at fulltime for every
201 match in that bracket/age-group.
202 """
204 tournament_id: int = Field(..., ge=1)
205 tournament_group: str = Field(..., min_length=1, max_length=100)
206 age_group_id: int = Field(..., ge=1)
209# ---------------------------------------------------------------------------
210# Public: VAPID public key (no auth)
211# ---------------------------------------------------------------------------
214@router.get("/push/vapid-public-key")
215def get_vapid_public_key_endpoint() -> dict[str, str]:
216 """Return the VAPID public key the browser needs to subscribe.
218 Public information — no authentication required. Returns 503 if the
219 backend isn't configured for push yet (SB-50 hasn't landed).
220 """
221 if not push_is_configured():
222 raise HTTPException(
223 status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
224 detail="Push notifications are not configured on this server.",
225 )
226 key = get_vapid_public_key()
227 if not key:
228 raise HTTPException(
229 status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
230 detail="VAPID public key not available.",
231 )
232 return {"publicKey": key}
235# ---------------------------------------------------------------------------
236# Push subscriptions
237# ---------------------------------------------------------------------------
240@router.post(
241 "/users/me/push-subscriptions",
242 status_code=status.HTTP_201_CREATED,
243)
244def register_subscription(
245 payload: PushSubscriptionIn,
246 current_user: dict[str, Any] = Depends(get_current_user_required),
247) -> dict[str, Any]:
248 """Register (or update) a push subscription for the current user."""
249 user_id = _user_id(current_user)
250 row = _sub_dao().upsert(
251 user_id=user_id,
252 endpoint=payload.endpoint,
253 p256dh_key=payload.keys.p256dh,
254 auth_key=payload.keys.auth,
255 device_label=payload.device_label,
256 user_agent=payload.user_agent,
257 )
258 if not row:
259 raise HTTPException(
260 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
261 detail="Failed to register push subscription.",
262 )
263 # Never echo the keys back — they're write-only from the API's view.
264 return {
265 "id": row.get("id"),
266 "device_label": row.get("device_label"),
267 "created_at": row.get("created_at"),
268 "last_seen_at": row.get("last_seen_at"),
269 }
272@router.get("/users/me/push-subscriptions")
273def list_subscriptions(
274 current_user: dict[str, Any] = Depends(get_current_user_required),
275) -> dict[str, list[dict]]:
276 user_id = _user_id(current_user)
277 return {"subscriptions": _sub_dao().list_by_user(user_id)}
280@router.delete(
281 "/users/me/push-subscriptions/{subscription_id}",
282 status_code=status.HTTP_204_NO_CONTENT,
283)
284def delete_subscription(
285 subscription_id: str,
286 current_user: dict[str, Any] = Depends(get_current_user_required),
287) -> Response:
288 user_id = _user_id(current_user)
289 deleted = _sub_dao().delete_by_id(user_id, subscription_id)
290 if not deleted:
291 raise HTTPException(
292 status_code=status.HTTP_404_NOT_FOUND,
293 detail="Subscription not found.",
294 )
295 return Response(status_code=status.HTTP_204_NO_CONTENT)
298# ---------------------------------------------------------------------------
299# APNs devices (native iOS, SB-1236)
300# ---------------------------------------------------------------------------
303@router.post(
304 "/users/me/apns-devices",
305 status_code=status.HTTP_201_CREATED,
306)
307def register_apns_device(
308 payload: ApnsDeviceIn,
309 current_user: dict[str, Any] = Depends(get_current_user_required),
310) -> dict[str, Any]:
311 """Register (or update) an iOS device for the current user."""
312 user_id = _user_id(current_user)
313 row = _apns_dao().upsert(
314 user_id=user_id,
315 # Hex is case-insensitive; one spelling per token keeps UNIQUE honest.
316 device_token=payload.device_token.lower(),
317 environment=payload.environment,
318 device_label=payload.device_label,
319 app_version=payload.app_version,
320 )
321 if not row:
322 raise HTTPException(
323 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
324 detail="Failed to register device.",
325 )
326 # Never echo the token back — write-only from the API's view.
327 return {
328 "id": row.get("id"),
329 "environment": row.get("environment"),
330 "bundle_id": row.get("bundle_id"),
331 "device_label": row.get("device_label"),
332 "app_version": row.get("app_version"),
333 "created_at": row.get("created_at"),
334 "last_seen_at": row.get("last_seen_at"),
335 }
338@router.get("/users/me/apns-devices")
339def list_apns_devices(
340 current_user: dict[str, Any] = Depends(get_current_user_required),
341) -> dict[str, list[dict]]:
342 user_id = _user_id(current_user)
343 return {"devices": _apns_dao().list_by_user(user_id)}
346@router.delete(
347 "/users/me/apns-devices/{device_id}",
348 status_code=status.HTTP_204_NO_CONTENT,
349)
350def delete_apns_device(
351 device_id: str,
352 current_user: dict[str, Any] = Depends(get_current_user_required),
353) -> Response:
354 user_id = _user_id(current_user)
355 deleted = _apns_dao().delete_for_user(user_id, device_id)
356 if not deleted:
357 raise HTTPException(
358 status_code=status.HTTP_404_NOT_FOUND,
359 detail="Device not found.",
360 )
361 return Response(status_code=status.HTTP_204_NO_CONTENT)
364# ---------------------------------------------------------------------------
365# FCM devices (native Android, SB-1463)
366# ---------------------------------------------------------------------------
369@router.post(
370 "/users/me/fcm-devices",
371 status_code=status.HTTP_201_CREATED,
372)
373def register_fcm_device(
374 payload: FcmDeviceIn,
375 current_user: dict[str, Any] = Depends(get_current_user_required),
376) -> dict[str, Any]:
377 """Register (or update) an Android device for the current user."""
378 user_id = _user_id(current_user)
379 row = _fcm_dao().upsert(
380 user_id=user_id,
381 fid=payload.fid,
382 device_label=payload.device_label,
383 app_version=payload.app_version,
384 )
385 if not row:
386 raise HTTPException(
387 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
388 detail="Failed to register device.",
389 )
390 # Never echo the fid back — write-only from the API's view.
391 return {
392 "id": row.get("id"),
393 "device_label": row.get("device_label"),
394 "app_version": row.get("app_version"),
395 "created_at": row.get("created_at"),
396 "last_seen_at": row.get("last_seen_at"),
397 }
400@router.get("/users/me/fcm-devices")
401def list_fcm_devices(
402 current_user: dict[str, Any] = Depends(get_current_user_required),
403) -> dict[str, list[dict]]:
404 user_id = _user_id(current_user)
405 return {"devices": _fcm_dao().list_by_user(user_id)}
408@router.delete(
409 "/users/me/fcm-devices/{device_id}",
410 status_code=status.HTTP_204_NO_CONTENT,
411)
412def delete_fcm_device(
413 device_id: str,
414 current_user: dict[str, Any] = Depends(get_current_user_required),
415) -> Response:
416 user_id = _user_id(current_user)
417 deleted = _fcm_dao().delete_for_user(user_id, device_id)
418 if not deleted:
419 raise HTTPException(
420 status_code=status.HTTP_404_NOT_FOUND,
421 detail="Device not found.",
422 )
423 return Response(status_code=status.HTTP_204_NO_CONTENT)
426# ---------------------------------------------------------------------------
427# Team follows
428# ---------------------------------------------------------------------------
431@router.post(
432 "/users/me/team-follows",
433 status_code=status.HTTP_201_CREATED,
434)
435def follow_team(
436 payload: TeamFollowIn,
437 current_user: dict[str, Any] = Depends(get_current_user_required),
438) -> dict[str, Any]:
439 user_id = _user_id(current_user)
440 dao = _follow_dao()
441 if payload.age_group_id is None:
442 ok = dao.follow(user_id, payload.team_id)
443 else:
444 plays = dao.team_plays_age_group(payload.team_id, payload.age_group_id)
445 if plays is None:
446 raise HTTPException(
447 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
448 detail="Failed to follow team.",
449 )
450 if not plays:
451 raise HTTPException(
452 status_code=status.HTTP_400_BAD_REQUEST,
453 detail="That team doesn't play in that age group.",
454 )
455 ok = dao.follow_squad(user_id, payload.team_id, payload.age_group_id)
456 if not ok:
457 raise HTTPException(
458 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
459 detail="Failed to follow team.",
460 )
461 return {"team_id": payload.team_id, "age_group_id": payload.age_group_id, "following": True}
464@router.get("/users/me/team-follows")
465def list_team_follows(
466 current_user: dict[str, Any] = Depends(get_current_user_required),
467) -> dict[str, list[dict]]:
468 user_id = _user_id(current_user)
469 return {"follows": _follow_dao().list_for_user(user_id)}
472@router.delete(
473 "/users/me/team-follows/{team_id}",
474 status_code=status.HTTP_204_NO_CONTENT,
475)
476def unfollow_team(
477 team_id: int,
478 current_user: dict[str, Any] = Depends(get_current_user_required),
479 age_group_id: Annotated[int | None, Query(ge=1)] = None,
480) -> Response:
481 """Without age_group_id, every follow of the team goes (what the mobile apps
482 send). With it, only that squad's follow does."""
483 user_id = _user_id(current_user)
484 _follow_dao().unfollow(user_id, team_id, age_group_id) # idempotent
485 return Response(status_code=status.HTTP_204_NO_CONTENT)
488# ---------------------------------------------------------------------------
489# Bracket follows
490# ---------------------------------------------------------------------------
493@router.post(
494 "/users/me/bracket-follows",
495 status_code=status.HTTP_201_CREATED,
496)
497def follow_bracket(
498 payload: BracketFollowIn,
499 current_user: dict[str, Any] = Depends(get_current_user_required),
500) -> dict[str, Any]:
501 user_id = _user_id(current_user)
502 ok = _bracket_follow_dao().follow(
503 user_id,
504 payload.tournament_id,
505 payload.tournament_group,
506 payload.age_group_id,
507 )
508 if not ok:
509 raise HTTPException(
510 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
511 detail="Failed to follow bracket.",
512 )
513 return {
514 "tournament_id": payload.tournament_id,
515 "tournament_group": payload.tournament_group,
516 "age_group_id": payload.age_group_id,
517 "following": True,
518 }
521@router.get("/users/me/bracket-follows")
522def list_bracket_follows(
523 current_user: dict[str, Any] = Depends(get_current_user_required),
524) -> dict[str, list[dict]]:
525 user_id = _user_id(current_user)
526 return {"follows": _bracket_follow_dao().list_for_user(user_id)}
529@router.delete(
530 "/users/me/bracket-follows",
531 status_code=status.HTTP_204_NO_CONTENT,
532)
533def unfollow_bracket(
534 tournament_id: int,
535 tournament_group: str,
536 age_group_id: int,
537 current_user: dict[str, Any] = Depends(get_current_user_required),
538) -> Response:
539 """Unfollow a bracket. Composite key via query params (no single id).
541 Idempotent — returns 204 even if the user wasn't following.
542 """
543 user_id = _user_id(current_user)
544 _bracket_follow_dao().unfollow(
545 user_id, tournament_id, tournament_group, age_group_id
546 )
547 return Response(status_code=status.HTTP_204_NO_CONTENT)
550# ---------------------------------------------------------------------------
551# Notification preferences (SB-57)
552# ---------------------------------------------------------------------------
555class NotificationPreferencesIn(BaseModel):
556 """Body of PUT /api/users/me/notification-preferences."""
558 preferences: dict[str, bool] = Field(
559 ...,
560 description=(
561 "Map of event_type → enabled. Unknown event types are ignored. "
562 f"Known event types: {', '.join(EVENT_TYPES)}."
563 ),
564 )
567@router.get("/users/me/notification-preferences")
568def get_notification_preferences(
569 current_user: dict[str, Any] = Depends(get_current_user_required),
570) -> dict[str, dict[str, bool]]:
571 user_id = _user_id(current_user)
572 return {"preferences": _prefs_dao().get_preferences(user_id)}
575@router.put("/users/me/notification-preferences")
576def update_notification_preferences(
577 payload: NotificationPreferencesIn,
578 current_user: dict[str, Any] = Depends(get_current_user_required),
579) -> dict[str, dict[str, bool]]:
580 # Reject unknown event types up front rather than silently dropping them —
581 # surfaces client bugs faster.
582 unknown = [k for k in payload.preferences if k not in EVENT_TYPES]
583 if unknown:
584 raise HTTPException(
585 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
586 detail=f"Unknown event types: {', '.join(unknown)}",
587 )
588 user_id = _user_id(current_user)
589 merged = _prefs_dao().set_preferences(user_id, payload.preferences)
590 return {"preferences": merged}
593# ---------------------------------------------------------------------------
594# Test notification
595# ---------------------------------------------------------------------------
598@router.post("/users/me/notifications/test")
599def send_test_notification(
600 current_user: dict[str, Any] = Depends(get_current_user_required),
601) -> dict[str, Any]:
602 """Fire a test push to all of the current user's subscriptions, iOS
603 devices and Android devices.
605 Useful for verifying setup end-to-end after enabling notifications.
606 Rate limited 10/min per user. Each platform is used only if configured;
607 503 only when none is.
608 """
609 user_id = _user_id(current_user)
610 _check_test_rate_limit(user_id)
612 web_configured = push_is_configured()
613 apns_configured = apns_is_configured()
614 fcm_configured = fcm_is_configured()
615 if not web_configured and not apns_configured and not fcm_configured:
616 raise HTTPException(
617 status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
618 detail="Push notifications are not configured on this server.",
619 )
621 subs: list[dict] = []
622 full_subs: list[dict] = []
623 if web_configured:
624 subs = _sub_dao().list_by_user(user_id)
625 # list_by_user doesn't return keys; we need the full row for sending.
626 # Fetch fresh from the table including keys.
627 try:
628 full_rows = (
629 _conn()
630 .get_client()
631 .table("push_subscriptions")
632 .select("id, endpoint, p256dh_key, auth_key")
633 .eq("user_id", user_id)
634 .execute()
635 )
636 full_subs = full_rows.data or []
637 except Exception:
638 logger.exception("test_push_fetch_subs_failed", user_id=user_id)
639 raise HTTPException(
640 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
641 detail="Failed to load subscriptions.",
642 ) from None
644 apns_dao = _apns_dao()
645 devices = apns_dao.list_for_user_ids([user_id]) if apns_configured else []
647 # Built only when configured: nothing to send, so no connection needed.
648 fcm_dao = _fcm_dao() if fcm_configured else None
649 fcm_devices = fcm_dao.list_for_user_ids([user_id]) if fcm_dao is not None else []
651 if not full_subs and not devices and not fcm_devices:
652 return {"sent": 0, "failed": 0, "expired": 0, "subscriptions": 0, "apns_devices": 0, "fcm_devices": 0}
654 payload = {
655 "title": "✅ Missing Table — test notification",
656 "body": "Push notifications are working on this device.",
657 "icon": "/pwa/icon-192.png",
658 "badge": "/pwa/icon-192.png",
659 "tag": "mt-test",
660 "data": {"url": "/", "test": True},
661 }
663 sent = 0
664 failed = 0
665 expired = 0
666 log_dao = _log_dao()
667 sub_dao = _sub_dao()
668 for sub in full_subs:
669 result = send_push(sub, payload)
670 log_dao.log(
671 subscription_id=sub.get("id"),
672 user_id=user_id,
673 match_id=None,
674 event_type="test",
675 status=result.status,
676 http_status=result.http_status,
677 error=result.error,
678 )
679 if result.ok: 679 ↛ 681line 679 didn't jump to line 681 because the condition on line 679 was always true
680 sent += 1
681 elif result.expired:
682 expired += 1
683 sub_dao.delete_by_endpoint(sub["endpoint"])
684 else:
685 failed += 1
687 for device in devices:
688 result = send_apns(device, payload)
689 log_dao.log(
690 subscription_id=None,
691 user_id=user_id,
692 match_id=None,
693 event_type="test",
694 status=result.status,
695 http_status=result.http_status,
696 error=result.error,
697 apns_device_id=device.get("id"),
698 platform="apns",
699 )
700 if result.ok:
701 sent += 1
702 elif result.expired:
703 expired += 1
704 apns_dao.delete_by_token(device["device_token"])
705 else:
706 failed += 1
708 if fcm_dao is not None:
709 for device in fcm_devices:
710 result = send_fcm(device, payload)
711 log_dao.log(
712 subscription_id=None,
713 user_id=user_id,
714 match_id=None,
715 event_type="test",
716 status=result.status,
717 http_status=result.http_status,
718 error=result.error,
719 fcm_device_id=device.get("id"),
720 platform="fcm",
721 )
722 if result.ok:
723 sent += 1
724 elif result.expired:
725 expired += 1
726 fcm_dao.delete_by_fid(device["fid"])
727 else:
728 failed += 1
730 # subscription/device counts BEFORE we removed expired ones (for the UI summary)
731 return {
732 "sent": sent,
733 "failed": failed,
734 "expired": expired,
735 "subscriptions": len(subs),
736 "apns_devices": len(devices),
737 "fcm_devices": len(fcm_devices),
738 }