thermograph/models.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

143 lines
6.7 KiB
Python

"""ORM tables for the account domain (data/accounts.sqlite).
``User`` / ``AccessToken`` are fastapi-users' base tables (UUID primary keys);
the access-token table backs a database session strategy, so logins survive a
process restart and are individually revocable. ``Subscription`` and
``Notification`` are our own, keyed to a user and cascading on delete.
"""
import time
import uuid
from fastapi_users_db_sqlalchemy import SQLAlchemyBaseUserTableUUID
from fastapi_users_db_sqlalchemy.access_token import SQLAlchemyBaseAccessTokenTableUUID
from fastapi_users_db_sqlalchemy.generics import GUID
from sqlalchemy import (
JSON,
Boolean,
CheckConstraint,
Float,
ForeignKey,
Index,
Integer,
String,
Text,
UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column
from db import Base
class User(SQLAlchemyBaseUserTableUUID, Base):
# Inherits id (UUID), email (unique), hashed_password, is_active,
# is_superuser, is_verified. One optional extra:
display_name: Mapped[str | None] = mapped_column(String(120), nullable=True)
class AccessToken(SQLAlchemyBaseAccessTokenTableUUID, Base):
# Inherits token (PK), user_id (FK -> user.id), created_at. Rows here ARE the
# sessions: DatabaseStrategy looks a cookie's token up in this table.
pass
class Subscription(Base):
__tablename__ = "subscription"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
user_id: Mapped[uuid.UUID] = mapped_column(
GUID, ForeignKey("user.id", ondelete="CASCADE"), nullable=False
)
# grid.snap(lat, lon)["id"] — the stable per-location key used across the app.
cell_id: Mapped[str] = mapped_column(String(40), nullable=False)
label: Mapped[str | None] = mapped_column(String(200), nullable=True)
lat: Mapped[float] = mapped_column(Float, nullable=False)
lon: Mapped[float] = mapped_column(Float, nullable=False)
# Unusualness cutoff the user picked; the low tail mirrors it at 100-threshold.
threshold: Mapped[int] = mapped_column(Integer, nullable=False)
# Grading metric keys this subscription watches, e.g. ["tmax", "feels", "precip"].
metrics: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
# 'observed' (a recorded day crossed) or 'forecast' (an upcoming day is projected to).
kind: Mapped[str] = mapped_column(String(16), nullable=False, default="observed")
# Also alert the cold/low tail for temperature-like metrics (precip stays one-sided).
two_sided: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
# Epoch seconds of the last notification emitted — enforces the weekly cap.
last_notified_at: Mapped[float | None] = mapped_column(Float, nullable=True)
created_at: Mapped[float] = mapped_column(Float, nullable=False, default=time.time)
__table_args__ = (
CheckConstraint("threshold BETWEEN 95 AND 99", name="ck_sub_threshold"),
CheckConstraint("kind IN ('observed','forecast')", name="ck_sub_kind"),
# One observed + one forecast subscription per location per user.
UniqueConstraint("user_id", "cell_id", "kind", name="uq_sub_user_cell_kind"),
Index("idx_sub_user", "user_id"),
Index("idx_sub_active", "active"),
)
class Notification(Base):
__tablename__ = "notification"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
user_id: Mapped[uuid.UUID] = mapped_column(
GUID, ForeignKey("user.id", ondelete="CASCADE"), nullable=False
)
subscription_id: Mapped[int] = mapped_column(
Integer, ForeignKey("subscription.id", ondelete="CASCADE"), nullable=False
)
event_date: Mapped[str] = mapped_column(String(10), nullable=False) # YYYY-MM-DD
metric: Mapped[str] = mapped_column(String(16), nullable=False)
direction: Mapped[str] = mapped_column(String(4), nullable=False) # 'high' | 'low'
kind: Mapped[str] = mapped_column(String(16), nullable=False, default="observed")
percentile: Mapped[float] = mapped_column(Float, nullable=False)
value: Mapped[float | None] = mapped_column(Float, nullable=True)
grade: Mapped[str | None] = mapped_column(String(40), nullable=True)
title: Mapped[str] = mapped_column(String(200), nullable=False)
body: Mapped[str | None] = mapped_column(Text, nullable=True)
# 'inapp' today; the seam for future 'email' / 'push' delivery.
channel: Mapped[str] = mapped_column(String(16), nullable=False, default="inapp")
created_at: Mapped[float] = mapped_column(Float, nullable=False, default=time.time)
read_at: Mapped[float | None] = mapped_column(Float, nullable=True) # NULL == unread
__table_args__ = (
# The dedup key: a given event (day+metric+direction+kind) notifies a
# subscription at most once, so re-running the evaluator never repeats it.
UniqueConstraint(
"subscription_id", "event_date", "metric", "direction", "kind",
name="uq_notif_event",
),
Index("idx_notif_user_created", "user_id", "created_at"),
Index("idx_notif_user_read", "user_id", "read_at"),
)
class PushSubscription(Base):
"""A single browser/device Web Push registration, owned by a user.
One row per device (a user with a phone + a laptop has two). The `endpoint`
is the push service URL the browser handed us; it's the natural identity, so
re-subscribing from the same device updates the keys in place rather than
duplicating. Rows are pruned when the push service reports the endpoint gone
(404/410) — see notify.py / api_accounts.py.
"""
__tablename__ = "push_subscription"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
user_id: Mapped[uuid.UUID] = mapped_column(
GUID, ForeignKey("user.id", ondelete="CASCADE"), nullable=False
)
# The push service URL (per-device). Unique — it identifies the device.
endpoint: Mapped[str] = mapped_column(Text, nullable=False)
# The two client keys from PushSubscription.toJSON().keys, used to encrypt the
# payload so only this device can read it.
p256dh: Mapped[str] = mapped_column(String(200), nullable=False)
auth: Mapped[str] = mapped_column(String(100), nullable=False)
# Best-effort label for a future "manage devices" view.
user_agent: Mapped[str | None] = mapped_column(String(300), nullable=True)
created_at: Mapped[float] = mapped_column(Float, nullable=False, default=time.time)
last_used_at: Mapped[float | None] = mapped_column(Float, nullable=True)
__table_args__ = (
UniqueConstraint("endpoint", name="uq_push_endpoint"),
Index("idx_push_user", "user_id"),
)