Spaces:
Runtime error
Runtime error
File size: 5,183 Bytes
1ffd0a4 | 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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | """
FCM Notification Service β single source of truth for all push notifications.
All notification types (verification prompts, area alerts, strike warnings,
blacklist notices) are dispatched through this module. No other module should
call firebase_admin.messaging directly.
Failure policy: a failed FCM send is logged and returns False β it must
never crash the pipeline. FCM is best-effort for the demo.
"""
from __future__ import annotations
import asyncio
import logging
from firebase_admin import messaging
logger = logging.getLogger(__name__)
async def send_notification(
token: str,
title: str,
body: str,
data: dict[str, str] | None = None,
) -> bool:
"""Send a push notification to a single device token.
Args:
token: FCM device registration token.
title: Notification title shown on the device.
body: Notification body text.
data: Optional key-value payload delivered alongside the visual
notification. All values must be strings (FCM requirement).
Returns:
True on success, False on any failure (token invalid, quota, etc.).
"""
if not token:
logger.warning("send_notification called with empty token β skipped")
return False
message = messaging.Message(
notification=messaging.Notification(title=title, body=body),
data={k: str(v) for k, v in (data or {}).items()},
token=token,
)
try:
# messaging.send() is synchronous β run in thread to stay non-blocking.
await asyncio.to_thread(messaging.send, message)
return True
except messaging.UnregisteredError:
logger.warning("FCM token unregistered β device removed app: %.20sβ¦", token)
return False
except Exception as exc: # noqa: BLE001
logger.warning("FCM send failed: %s", exc)
return False
async def send_verification_prompt(
token: str,
crisis_id: str,
crisis_type: str,
location: str,
) -> bool:
"""Ask a nearby user to confirm or deny a reported crisis.
Payload delivered to the mobile app:
type = "verification_prompt"
crisis_id = <crisis document ID>
crisis_type = e.g. "flood"
"""
return await send_notification(
token=token,
title="Crisis reported near you",
body=f"A {crisis_type} has been reported near {location}. Can you confirm?",
data={
"type": "verification_prompt",
"crisis_id": crisis_id,
"crisis_type": crisis_type,
},
)
async def send_area_alert(
token: str,
crisis_type: str,
location: str,
action: str,
) -> bool:
"""Notify a user that a crisis is active in their area."""
return await send_notification(
token=token,
title=f"Crisis alert: {crisis_type} in {location}",
body=action,
data={"type": "area_alert", "crisis_type": crisis_type},
)
async def send_strike_warning(token: str, strikes_remaining: int) -> bool:
"""Warn a user that they are close to being blacklisted."""
return await send_notification(
token=token,
title="False report warning",
body=(
f"Warning: you have received {3 - strikes_remaining + 1} false report "
"strikes. One more false report will permanently block your account."
),
data={"type": "strike_warning"},
)
async def send_blacklist_notice(token: str) -> bool:
"""Notify a user that their account has been permanently blocked."""
return await send_notification(
token=token,
title="Account blocked",
body="Your account has been permanently blocked due to repeated false reports.",
data={"type": "blacklist_notice"},
)
async def send_ngo_alert(
token: str,
crisis_id: str,
crisis_type: str,
location: str,
severity: int,
response_plan_summary: str,
) -> bool:
"""Dispatch a real-time escalation alert to an NGO device.
This is a real notification to a real device β it is NOT simulated.
The NGO representative's device receives the push; tapping it opens
the crisis detail screen (handled by the mobile FCM handler).
Payload delivered to the app:
type = "ngo_escalation"
crisis_id = <crisis document ID>
crisis_type = e.g. "flood"
location = human-readable area name
severity = stringified int (FCM data values must be strings)
response_plan_summary = short summary of the planned response
"""
return await send_notification(
token=token,
title="\U0001f6a8 Crisis Alert β Response Required",
body=(
f"Confirmed {crisis_type} in {location}. "
f"Severity: {severity}/5. {response_plan_summary}"
),
data={
"type": "ngo_escalation",
"crisis_id": crisis_id,
"crisis_type": crisis_type,
"location": location,
"severity": str(severity),
"response_plan_summary": response_plan_summary,
},
)
|