File size: 3,253 Bytes
79ebb0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8615d6b
 
 
 
 
 
79ebb0d
 
8615d6b
79ebb0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8615d6b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""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)