51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any
|
|
|
|
from flask import current_app
|
|
|
|
|
|
def push_is_configured() -> bool:
|
|
return bool(
|
|
current_app.config.get("VAPID_PUBLIC_KEY")
|
|
and current_app.config.get("VAPID_PRIVATE_KEY")
|
|
and current_app.config.get("VAPID_SUBJECT")
|
|
)
|
|
|
|
|
|
def push_public_key() -> str | None:
|
|
return current_app.config.get("VAPID_PUBLIC_KEY") or None
|
|
|
|
|
|
def send_push_message(subscription: dict[str, Any], *, title: str, body: str, url: str) -> tuple[bool, str | None]:
|
|
if not push_is_configured():
|
|
return False, "Push ist noch nicht konfiguriert."
|
|
|
|
try:
|
|
from pywebpush import WebPushException, webpush
|
|
except Exception:
|
|
return False, "Die Push-Bibliothek ist noch nicht installiert."
|
|
|
|
payload = json.dumps(
|
|
{
|
|
"title": title,
|
|
"body": body,
|
|
"url": url,
|
|
"icon": "/static/brand/pwa-192.png",
|
|
"badge": "/static/brand/pwa-badge.png",
|
|
}
|
|
)
|
|
|
|
try:
|
|
webpush(
|
|
subscription_info=subscription,
|
|
data=payload,
|
|
vapid_private_key=current_app.config["VAPID_PRIVATE_KEY"],
|
|
vapid_claims={"sub": current_app.config["VAPID_SUBJECT"]},
|
|
)
|
|
except WebPushException as exc: # pragma: no cover - depends on live push endpoint
|
|
return False, str(exc)
|
|
|
|
return True, None
|