thermograph/schemas.py
Emi Griffith 2f289f1cb6 Add PWA + Web Push delivery for weather alerts (#95)
Make the app installable and deliver existing alert notifications as OS
push, alongside the in-app bell.

Backend:
- PushSubscription model (per-device endpoint + keys, owned by a user) and
  register/unregister/test endpoints under /api/v2/push, cookie-auth scoped
  to the user like the subscription routes.
- push.py: VAPID key management (env -> data/vapid.json -> generated) and a
  pywebpush send helper that reports gone endpoints for pruning. No DB coupling.
- notify.py: after creating an in-app Notification, dispatch Web Push to the
  user's devices (guarded — a push failure never affects the in-app write;
  endpoints reported gone are pruned).
- Serve the .webmanifest with the correct media type.

Frontend:
- manifest.webmanifest + 192/maskable icons; <link rel="manifest"> on all pages.
- sw.js: push + notificationclick handlers (push-only; no fetch caching, so it
  doesn't fight the existing IndexedDB cache). Registered globally in nav.js in
  secure contexts.
- push-client.js + a "Notifications on this device" toggle and test-send on the
  /alerts page, subscribing through the existing cookie-aware apiFetch.

Push and service workers require a secure context, so this is active over HTTPS
(or http://localhost) and cleanly no-ops on a plain-HTTP LAN origin.
2026-07-15 23:21:06 +00:00

130 lines
3.3 KiB
Python

"""Pydantic request/response models for accounts, subscriptions, notifications.
The User* schemas are fastapi-users' base schemas extended with display_name; the
Subscription*/Notification* models are the app's first request bodies and shape the
JSON the frontend sends and receives.
"""
import uuid
from typing import Literal
from fastapi_users import schemas
from pydantic import BaseModel, Field, field_validator
import grading
# Canonical metric keys a subscription may watch (kept in lockstep with grading).
ALLOWED_METRICS = tuple(grading.CLIMO_METRICS)
DEFAULT_METRICS = ["tmax", "feels", "precip"]
# --- users (fastapi-users) ---------------------------------------------------
class UserRead(schemas.BaseUser[uuid.UUID]):
display_name: str | None = None
class UserCreate(schemas.BaseUserCreate):
display_name: str | None = None
class UserUpdate(schemas.BaseUserUpdate):
display_name: str | None = None
# --- subscriptions -----------------------------------------------------------
def _check_metrics(v: list[str]) -> list[str]:
if not v:
raise ValueError("pick at least one metric")
bad = [m for m in v if m not in ALLOWED_METRICS]
if bad:
raise ValueError(f"unknown metric(s): {', '.join(bad)}")
# de-dupe, preserve order
seen, out = set(), []
for m in v:
if m not in seen:
seen.add(m)
out.append(m)
return out
class SubscriptionIn(BaseModel):
lat: float = Field(ge=-90, le=90)
lon: float = Field(ge=-180, le=180)
label: str | None = None
threshold: int = Field(ge=95, le=99)
metrics: list[str] = Field(default_factory=lambda: list(DEFAULT_METRICS))
kind: Literal["observed", "forecast"] = "observed"
two_sided: bool = True
@field_validator("metrics")
@classmethod
def _metrics(cls, v):
return _check_metrics(v)
class SubscriptionPatch(BaseModel):
threshold: int | None = Field(default=None, ge=95, le=99)
metrics: list[str] | None = None
two_sided: bool | None = None
active: bool | None = None
@field_validator("metrics")
@classmethod
def _metrics(cls, v):
return _check_metrics(v) if v is not None else v
class SubscriptionOut(BaseModel):
id: int
cell_id: str
label: str | None
lat: float
lon: float
threshold: int
metrics: list[str]
kind: str
two_sided: bool
active: bool
last_notified_at: float | None
created_at: float
model_config = {"from_attributes": True}
# --- notifications -----------------------------------------------------------
class NotificationOut(BaseModel):
id: int
subscription_id: int
event_date: str
metric: str
direction: str
kind: str
percentile: float
value: float | None
grade: str | None
title: str
body: str | None
created_at: float
read_at: float | None
model_config = {"from_attributes": True}
class NotificationList(BaseModel):
notifications: list[NotificationOut]
unread_count: int
# --- web push ----------------------------------------------------------------
class PushKeys(BaseModel):
p256dh: str
auth: str
class PushSubscriptionIn(BaseModel):
"""Matches the browser's PushSubscription.toJSON() shape."""
endpoint: str
keys: PushKeys
class PushUnsubscribeIn(BaseModel):
endpoint: str