Pabot's picture
Upload push.py
8615d6b verified
Raw History Blame Contribute Delete
3.25 kB
"""User notifications: the in-app bell (notifications table) + desktop Web Push.
Needs VAPID_PUBLIC_KEY + VAPID_PRIVATE_KEY (no-op without them). Sending runs in
a background thread so a slow push service never delays an API response. Dead
subscriptions (404/410 from the push service) are removed automatically.
"""
from __future__ import annotations
import json
import logging
import os
import threading
log = logging.getLogger("push")
VAPID_PUBLIC_KEY = os.environ.get("VAPID_PUBLIC_KEY", "").strip()
VAPID_PRIVATE_KEY = os.environ.get("VAPID_PRIVATE_KEY", "").strip()
VAPID_SUBJECT = os.environ.get("VAPID_SUBJECT", "https://contentfilter.ai").strip()
def push_enabled() -> bool:
return bool(VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY)
def _deliver(client, user_id: str, payload: dict) -> None:
from pywebpush import WebPushException, webpush
subs = (
client.table("push_subscriptions").select("endpoint,p256dh,auth")
.eq("user_id", user_id).execute().data or []
)
for s in subs:
try:
webpush(
subscription_info={"endpoint": s["endpoint"], "keys": {"p256dh": s["p256dh"], "auth": s["auth"]}},
data=json.dumps(payload),
vapid_private_key=VAPID_PRIVATE_KEY,
vapid_claims={"sub": VAPID_SUBJECT}, # fresh dict: webpush mutates it
ttl=86400,
)
except WebPushException as exc:
status = getattr(getattr(exc, "response", None), "status_code", None)
if status in (404, 410): # browser unsubscribed / expired
client.table("push_subscriptions").delete().eq("endpoint", s["endpoint"]).execute()
else:
log.warning("push failed (%s): %s", status, exc)
except Exception as exc: # noqa: BLE001
log.warning("push failed: %s", exc)
def send_push(
client, user_id: str | None, title: str, body: str, url: str = "/dashboard",
tag: str | None = None, kind: str | None = None,
) -> None:
"""Fire-and-forget desktop notification to all of the user's browsers.
`kind` lets the service worker pick the custom sound (frontend public/sw.js)."""
if not push_enabled() or not user_id:
return
payload = {"title": title, "body": body, "url": url, "tag": tag or url, "kind": kind}
def run() -> None:
try:
_deliver(client, str(user_id), payload)
except Exception: # noqa: BLE001
log.warning("push delivery error", exc_info=True)
threading.Thread(target=run, daemon=True).start()
def notify_user(
client, user_id: str | None, kind: str, title: str, body: str,
url: str = "/dashboard", tag: str | None = None,
) -> None:
"""In-app bell notification (notifications table) + desktop push, together.
kind: scan_done | scan_error | payment | low_credits."""
if not user_id:
return
try:
client.table("notifications").insert({
"user_id": str(user_id), "kind": kind, "title": title, "body": body, "url": url,
}).execute()
except Exception: # noqa: BLE001
log.warning("could not save bell notification", exc_info=True)
send_push(client, user_id, title, body, url, tag, kind)