Coverage for api/club_notifications.py: 37.30%
161 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
1"""
2Club notification channels API.
4Per-club chat destinations for live-match notifications.
5- GET /api/clubs/{club_id}/notifications
6- PUT /api/clubs/{club_id}/notifications/{platform}
7- PATCH /api/clubs/{club_id}/notifications/{platform} (enabled only)
8- DELETE /api/clubs/{club_id}/notifications/{platform}
9- POST /api/clubs/{club_id}/notifications/{platform}/test
10- GET /api/notifications/platforms
12Permissions: admin OR (club_manager AND user_club_id == club_id).
13The `destination` value is never returned in full — callers only see the last
14four characters of a configured destination as `hint`. The full value stays
15write-only from the API's perspective.
16"""
18from __future__ import annotations
20import os
21import time
22from typing import Any
24import structlog
25from fastapi import APIRouter, Depends, HTTPException, Response, status
26from pydantic import BaseModel, Field
28from auth import get_current_user_required
29from dao.club_notifications_dao import ClubNotificationsDAO
30from dao.match_dao import SupabaseConnection
31from dao.notification_channels_dao import actor_id
32from notifications.adapters.base import InvalidDestinationError, UnsupportedPlatformError
33from notifications.registry import all_adapters, get_adapter, platform_ids
35logger = structlog.get_logger(__name__)
37router = APIRouter(prefix="/api/clubs", tags=["club-notifications"])
38platforms_router = APIRouter(prefix="/api/notifications", tags=["club-notifications"])
41# ---------------------------------------------------------------------------
42# Connection / DAO (lazy singleton)
43# ---------------------------------------------------------------------------
45_connection: SupabaseConnection | None = None
48def _dao() -> ClubNotificationsDAO:
49 global _connection
50 if _connection is None:
51 _connection = SupabaseConnection()
52 return ClubNotificationsDAO(_connection)
55# ---------------------------------------------------------------------------
56# Kill switch
57# ---------------------------------------------------------------------------
60def is_notifications_enabled() -> bool:
61 """False only when NOTIFICATIONS_ENABLED is explicitly off."""
62 return os.getenv("NOTIFICATIONS_ENABLED", "true").lower() not in {
63 "0",
64 "false",
65 "no",
66 "off",
67 }
70# ---------------------------------------------------------------------------
71# Redis-backed rate limiter (fail-open)
72# ---------------------------------------------------------------------------
74# Typed so mypy does not narrow it to None and call the cache branch unreachable.
75_redis_client: Any = None
78def _get_redis():
79 """Lazy Redis client. Returns None if Redis isn't reachable."""
80 global _redis_client
81 if _redis_client is not None:
82 return _redis_client
83 try:
84 import redis
86 url = os.getenv("REDIS_URL", "redis://localhost:6379/0")
87 client = redis.from_url(url, decode_responses=True, socket_timeout=1.0)
88 client.ping()
89 _redis_client = client
90 return _redis_client
91 except Exception as exc:
92 logger.warning("notifications_redis_unavailable", error=str(exc))
93 return None
96def check_rate_limit(key: str, max_per_minute: int) -> bool:
97 """Fixed-window counter. Returns True if the request is allowed.
99 Fail-open: any Redis failure returns True so the limiter never takes the
100 service down. The limiter is best-effort defense-in-depth, not a hard
101 quota.
102 """
103 client = _get_redis()
104 if client is None:
105 return True
107 bucket = int(time.time() // 60)
108 full_key = f"{key}:{bucket}"
109 try:
110 count = client.incr(full_key)
111 if count == 1:
112 client.expire(full_key, 65)
113 return count <= max_per_minute
114 except Exception as exc:
115 logger.warning("rate_limit_check_failed", key=key, error=str(exc))
116 return True
119def claim_once(key: str, ttl_seconds: int) -> bool:
120 """True the first time `key` is claimed within `ttl_seconds`, False after.
122 Fail-open like the limiter: with Redis down a repeat is possible, a missed
123 alert is not.
124 """
125 client = _get_redis()
126 if client is None:
127 return True
128 try:
129 return bool(client.set(key, "1", nx=True, ex=ttl_seconds))
130 except Exception as exc:
131 logger.warning("claim_once_failed", key=key, error=str(exc))
132 return True
135# ---------------------------------------------------------------------------
136# Permission guard
137# ---------------------------------------------------------------------------
140def ensure_club_access(current_user: dict, club_id: int) -> None:
141 """Raise 403 unless the caller is admin or a club_manager for this club."""
142 role = current_user.get("role")
143 if role == "admin":
144 return
145 if role == "club_manager" and current_user.get("club_id") == club_id:
146 return
147 raise HTTPException(
148 status_code=status.HTTP_403_FORBIDDEN,
149 detail="Requires admin or club_manager for this club",
150 )
153# ---------------------------------------------------------------------------
154# Validation
155# ---------------------------------------------------------------------------
158def _validate_platform(platform: str) -> None:
159 try:
160 get_adapter(platform)
161 except UnsupportedPlatformError:
162 raise HTTPException(
163 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
164 detail=f"platform must be one of {sorted(platform_ids())}",
165 ) from None
168def _validate_destination(platform: str, destination: str) -> None:
169 try:
170 get_adapter(platform).validate_destination(destination)
171 except InvalidDestinationError as exc:
172 raise HTTPException(
173 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
174 detail=str(exc),
175 ) from None
178# ---------------------------------------------------------------------------
179# Response / request models
180# ---------------------------------------------------------------------------
183class ChannelResponse(BaseModel):
184 platform: str
185 enabled: bool
186 configured: bool
187 hint: str | None = Field(None, description="Last 4 chars of destination; full value never exposed")
190class ChannelUpsert(BaseModel):
191 destination: str = Field(..., min_length=1, max_length=500)
192 enabled: bool = True
195class ChannelEnabled(BaseModel):
196 enabled: bool
199class PlatformInfo(BaseModel):
200 """What the setup UI needs to render and validate one platform."""
202 id: str
203 label: str
204 icon: str
205 placeholder: str
206 destination_label: str
207 hint: str
208 setup_steps: list[str]
209 destination_pattern: str
210 destination_error: str
211 invite_pattern: str
212 invite_error: str
213 capabilities: list[str]
214 min_player_age: int | None
215 age_note: str | None = None
216 player_setup_steps: list[str] = []
219class TestSendResponse(BaseModel):
220 success: bool
221 error: str | None = None
224def _to_response(row: dict) -> ChannelResponse:
225 destination = row.get("destination") or ""
226 hint = destination[-4:] if destination else None
227 return ChannelResponse(
228 platform=row["platform"],
229 enabled=bool(row["enabled"]),
230 configured=True,
231 hint=hint,
232 )
235# ---------------------------------------------------------------------------
236# Test-send
237# ---------------------------------------------------------------------------
240def _send_test_message(platform: str, destination: str) -> None:
241 """Send a test notification to verify a destination works.
243 Phase 5 wiring: delegates to the notification subsystem's sender helper
244 so behavior matches real live-event delivery.
245 """
246 from notifications.senders import send_to
248 send_to(
249 platform,
250 destination,
251 "✅ MissingTable notification test — your channel is configured correctly.",
252 )
255# ---------------------------------------------------------------------------
256# Endpoints
257# ---------------------------------------------------------------------------
260@platforms_router.get("/platforms", response_model=list[PlatformInfo])
261def list_platforms(
262 current_user: dict = Depends(get_current_user_required),
263) -> list[PlatformInfo]:
264 """Every platform a channel can be configured for, in display order."""
265 return [
266 PlatformInfo(
267 id=adapter.id,
268 label=adapter.label,
269 icon=adapter.icon,
270 placeholder=adapter.placeholder,
271 destination_label=adapter.destination_label,
272 hint=adapter.hint,
273 setup_steps=list(adapter.setup_steps),
274 destination_pattern=adapter.destination_pattern,
275 destination_error=adapter.destination_error,
276 invite_pattern=adapter.invite_pattern,
277 invite_error=adapter.invite_error,
278 capabilities=sorted(adapter.capabilities),
279 min_player_age=adapter.min_player_age,
280 age_note=adapter.age_note,
281 player_setup_steps=list(adapter.player_setup_steps),
282 )
283 for adapter in all_adapters()
284 ]
287@router.get(
288 "/{club_id}/notifications",
289 response_model=list[ChannelResponse],
290)
291def list_channels(
292 club_id: int,
293 current_user: dict = Depends(get_current_user_required),
294) -> list[ChannelResponse]:
295 ensure_club_access(current_user, club_id)
296 rows = _dao().list_by_club(club_id)
297 return [_to_response(row) for row in rows]
300@router.put(
301 "/{club_id}/notifications/{platform}",
302 response_model=ChannelResponse,
303)
304def upsert_channel(
305 club_id: int,
306 platform: str,
307 body: ChannelUpsert,
308 current_user: dict = Depends(get_current_user_required),
309) -> ChannelResponse:
310 ensure_club_access(current_user, club_id)
311 _validate_platform(platform)
312 _validate_destination(platform, body.destination)
314 row = _dao().upsert(
315 club_id,
316 platform,
317 body.destination,
318 body.enabled,
319 created_by=actor_id(current_user),
320 )
321 if row is None:
322 raise HTTPException(
323 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
324 detail="Failed to save notification channel",
325 )
326 return _to_response(row)
329@router.patch(
330 "/{club_id}/notifications/{platform}",
331 response_model=ChannelResponse,
332)
333def set_channel_enabled(
334 club_id: int,
335 platform: str,
336 body: ChannelEnabled,
337 current_user: dict = Depends(get_current_user_required),
338) -> ChannelResponse:
339 """Pause or resume a channel without re-entering its destination."""
340 ensure_club_access(current_user, club_id)
341 _validate_platform(platform)
342 row = _dao().set_enabled(club_id, platform, body.enabled)
343 if row is None:
344 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No channel configured")
345 return _to_response(row)
348@router.delete(
349 "/{club_id}/notifications/{platform}",
350 status_code=status.HTTP_204_NO_CONTENT,
351 response_class=Response,
352)
353def delete_channel(
354 club_id: int,
355 platform: str,
356 current_user: dict = Depends(get_current_user_required),
357):
358 ensure_club_access(current_user, club_id)
359 _validate_platform(platform)
360 _dao().delete(club_id, platform)
361 return Response(status_code=status.HTTP_204_NO_CONTENT)
364@router.post(
365 "/{club_id}/notifications/{platform}/test",
366 response_model=TestSendResponse,
367)
368def test_send_channel(
369 club_id: int,
370 platform: str,
371 current_user: dict = Depends(get_current_user_required),
372) -> TestSendResponse:
373 ensure_club_access(current_user, club_id)
374 _validate_platform(platform)
376 if not is_notifications_enabled():
377 raise HTTPException(
378 status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
379 detail="Notifications are disabled globally (NOTIFICATIONS_ENABLED=false)",
380 )
382 if not check_rate_limit(f"ratelimit:notify-test:{club_id}", max_per_minute=5):
383 raise HTTPException(
384 status_code=status.HTTP_429_TOO_MANY_REQUESTS,
385 detail="Rate limit exceeded: 5 test sends per minute per club",
386 )
388 row = _dao().get(club_id, platform)
389 if row is None:
390 raise HTTPException(
391 status_code=status.HTTP_404_NOT_FOUND,
392 detail=f"No {platform} channel configured for club {club_id}",
393 )
395 try:
396 _send_test_message(platform, row["destination"])
397 except Exception as exc:
398 logger.exception(
399 "test_send_failed",
400 club_id=club_id,
401 platform=platform,
402 error_type=type(exc).__name__,
403 )
404 return TestSendResponse(success=False, error=type(exc).__name__)
406 return TestSendResponse(success=True, error=None)