FONDLED THE CODE

This commit is contained in:
Frank Schwenk
2026-06-10 12:40:22 +02:00
parent b5390b8ced
commit 648e62d2b4
3 changed files with 101 additions and 5 deletions
+55 -3
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
import logging
from typing import Any
import aiosqlite
@@ -9,6 +10,8 @@ from pywebpush import WebPushException, webpush
from server.db import utc_now_iso
from server.settings import settings
logger = logging.getLogger(__name__)
async def save_subscription(db: aiosqlite.Connection, sub: dict[str, Any]) -> None:
keys = sub.get("keys", {})
@@ -34,20 +37,42 @@ def _vapid_claims() -> dict[str, str]:
return {"sub": settings.vapid_claims_email}
def _endpoint_label(endpoint: str) -> str:
return endpoint[:60] + ("..." if len(endpoint) > 60 else "")
async def send_push(
db: aiosqlite.Connection,
payload: dict[str, Any],
) -> int:
tag = payload.get("tag", "?")
slot_id = payload.get("slot_id", "?")
if not settings.vapid_private_key or not settings.vapid_public_key:
logger.warning("Push skipped slot=%s tag=%s reason=vapid_not_configured", slot_id, tag)
return 0
subs = await get_subscriptions(db)
if not subs:
logger.warning("Push skipped slot=%s tag=%s reason=no_subscriptions", slot_id, tag)
return 0
sent = 0
failed = 0
dead: list[str] = []
logger.info(
"Push start slot=%s tag=%s subscriptions=%d title=%r",
slot_id,
tag,
len(subs),
payload.get("title"),
)
for sub in subs:
endpoint = sub["endpoint"]
subscription = {
"endpoint": sub["endpoint"],
"endpoint": endpoint,
"keys": {"p256dh": sub["p256dh"], "auth": sub["auth"]},
}
try:
@@ -58,15 +83,42 @@ async def send_push(
vapid_claims=_vapid_claims(),
)
sent += 1
logger.info("Push ok slot=%s endpoint=%s", slot_id, _endpoint_label(endpoint))
except WebPushException as exc:
if exc.response and exc.response.status_code in (404, 410):
dead.append(sub["endpoint"])
status = exc.response.status_code if exc.response else None
if status in (404, 410):
dead.append(endpoint)
logger.info(
"Push dead slot=%s endpoint=%s status=%s",
slot_id,
_endpoint_label(endpoint),
status,
)
else:
failed += 1
logger.warning(
"Push failed slot=%s endpoint=%s status=%s error=%s",
slot_id,
_endpoint_label(endpoint),
status,
exc,
)
for endpoint in dead:
await db.execute("DELETE FROM push_subscription WHERE endpoint = ?", (endpoint,))
if dead:
await db.commit()
logger.info("Push removed %d dead subscription(s)", len(dead))
logger.info(
"Push done slot=%s tag=%s sent=%d failed=%d dead=%d total=%d",
slot_id,
tag,
sent,
failed,
len(dead),
len(subs),
)
return sent