File size: 2,475 Bytes
a0c836f
 
 
 
 
 
6ad1942
 
a0c836f
 
 
 
 
 
 
 
 
 
 
6ad1942
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0c836f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ad1942
a0c836f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
87
"""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