"""Web Push delivery via pywebpush + VAPID. Dead subscriptions (HTTP 404/410) are removed from the DB automatically. """ import json import os import base64 from sqlalchemy.orm import Session import config from database import PushSubscription def _vapid_claims(): return {"sub": config.VAPID_CLAIM_EMAIL} def _vapid_private_key(): """Resolve the VAPID private key from any of the supported formats: a file path, a raw PEM string, an escaped PEM (\\n), or base64-encoded PEM (handy for single-line secret stores like Hugging Face).""" val = config.VAPID_PRIVATE_KEY if not val: return None if os.path.isfile(val): with open(val, "r") as f: return f.read() if "BEGIN" in val: return val.replace("\\n", "\n") try: decoded = base64.b64decode(val).decode("utf-8") if "BEGIN" in decoded: return decoded except Exception: pass return val def send_push_to_user(db: Session, user_id: int, payload: dict) -> int: """Send a push notification to all of a user's subscriptions. Returns the number of successful sends. No-ops (with a log) if VAPID keys are not configured, so the app still runs in dev. """ if not config.VAPID_PRIVATE_KEY: print("[push] VAPID keys not configured; skipping push.") return 0 try: from pywebpush import webpush, WebPushException except ImportError: print("[push] pywebpush not installed; skipping push.") return 0 subs = db.query(PushSubscription).filter( PushSubscription.user_id == user_id ).all() sent = 0 for sub in subs: subscription_info = { "endpoint": sub.endpoint, "keys": {"p256dh": sub.p256dh, "auth": sub.auth}, } try: webpush( subscription_info=subscription_info, data=json.dumps(payload), vapid_private_key=_vapid_private_key(), vapid_claims=_vapid_claims(), ) sent += 1 except WebPushException as e: status = getattr(e.response, "status_code", None) if status in (404, 410): db.delete(sub) # subscription expired/gone else: print(f"[push] WebPushException: {e}") except Exception as e: print(f"[push] unexpected error: {e}") if subs: db.commit() return sent