Revert "feat: replace Web Push with ntfy for medication reminders"
This reverts commit 1cada42370.
This commit is contained in:
+17
-12
@@ -16,6 +16,7 @@ from server.auth import create_token, require_auth, verify_pin
|
||||
from server.config_loader import load_meds_config, slot_to_dict, today_str
|
||||
from server.db import ensure_schema, get_db, new_id, utc_now_iso
|
||||
from server.messages import pick
|
||||
from server.push import save_subscription, send_slot_reminder
|
||||
from server.scheduler import schedule_snooze, start_scheduler
|
||||
from server.settings import settings
|
||||
from server.slots import build_today
|
||||
@@ -72,18 +73,9 @@ async def auth_pin(payload: dict[str, Any]) -> JSONResponse:
|
||||
return JSONResponse({"token": create_token()}, headers=NO_STORE)
|
||||
|
||||
|
||||
@app.get("/api/notify-config")
|
||||
async def notify_config(_: dict = Depends(require_auth)) -> JSONResponse:
|
||||
base = settings.ntfy_url.rstrip("/") if settings.ntfy_url else ""
|
||||
topic = settings.ntfy_topic
|
||||
return JSONResponse(
|
||||
{
|
||||
"topic": topic,
|
||||
"subscribe_url": f"{base}/{topic}" if base and topic else "",
|
||||
"configured": bool(base and topic),
|
||||
},
|
||||
headers=NO_STORE,
|
||||
)
|
||||
@app.get("/api/vapid-public-key")
|
||||
async def vapid_public_key() -> JSONResponse:
|
||||
return JSONResponse({"key": settings.vapid_public_key}, headers=NO_STORE)
|
||||
|
||||
|
||||
@app.get("/api/config")
|
||||
@@ -174,6 +166,19 @@ async def get_stats(_: dict = Depends(require_auth)) -> JSONResponse:
|
||||
return JSONResponse(stats, headers=NO_STORE)
|
||||
|
||||
|
||||
@app.post("/api/push/subscribe")
|
||||
async def push_subscribe(payload: dict[str, Any], _: dict = Depends(require_auth)) -> JSONResponse:
|
||||
sub = payload.get("subscription")
|
||||
if not sub or not sub.get("endpoint"):
|
||||
raise HTTPException(status_code=400, detail="Invalid subscription")
|
||||
db = await get_db()
|
||||
try:
|
||||
await save_subscription(db, sub)
|
||||
finally:
|
||||
await db.close()
|
||||
return JSONResponse({"ok": True}, headers=NO_STORE)
|
||||
|
||||
|
||||
@app.post("/api/snooze")
|
||||
async def post_snooze(payload: dict[str, Any], _: dict = Depends(require_auth)) -> JSONResponse:
|
||||
slot_id = str(payload.get("slot_id", ""))
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
from server.settings import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _publish_url() -> str | None:
|
||||
if not settings.ntfy_url or not settings.ntfy_topic:
|
||||
return None
|
||||
return f"{settings.ntfy_url.rstrip('/')}/{settings.ntfy_topic}"
|
||||
|
||||
|
||||
def _click_base() -> str:
|
||||
return settings.ntfy_click_url.rstrip("/")
|
||||
|
||||
|
||||
async def send_slot_reminder(
|
||||
slot_id: str,
|
||||
title: str,
|
||||
body: str,
|
||||
*,
|
||||
silent: bool = True,
|
||||
) -> int:
|
||||
url = _publish_url()
|
||||
if not url:
|
||||
logger.warning(
|
||||
"Notify skipped slot=%s reason=ntfy_not_configured (NTFY_URL + NTFY_TOPIC)",
|
||||
slot_id,
|
||||
)
|
||||
return 0
|
||||
|
||||
click_base = _click_base()
|
||||
headers: dict[str, str] = {
|
||||
"Title": title,
|
||||
"Click": f"{click_base}/?slot={slot_id}",
|
||||
"Priority": "2" if silent else "3",
|
||||
"Tags": "pill",
|
||||
"Actions": json.dumps(
|
||||
[
|
||||
{
|
||||
"action": "view",
|
||||
"label": "Genommen ✓",
|
||||
"url": f"{click_base}/?action=take&slot={slot_id}",
|
||||
},
|
||||
{
|
||||
"action": "view",
|
||||
"label": "+15 Min",
|
||||
"url": f"{click_base}/?action=snooze&slot={slot_id}&minutes=15",
|
||||
},
|
||||
{
|
||||
"action": "view",
|
||||
"label": "+30 Min",
|
||||
"url": f"{click_base}/?action=snooze&slot={slot_id}&minutes=30",
|
||||
},
|
||||
]
|
||||
),
|
||||
}
|
||||
if settings.ntfy_token:
|
||||
headers["Authorization"] = f"Bearer {settings.ntfy_token}"
|
||||
|
||||
logger.info("Notify start slot=%s title=%r topic=%s", slot_id, title, settings.ntfy_topic)
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
resp = await client.post(url, content=body.encode("utf-8"), headers=headers)
|
||||
resp.raise_for_status()
|
||||
except httpx.HTTPError as exc:
|
||||
logger.warning("Notify failed slot=%s error=%s", slot_id, exc)
|
||||
return 0
|
||||
|
||||
logger.info("Notify ok slot=%s", slot_id)
|
||||
return 1
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import aiosqlite
|
||||
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", {})
|
||||
await db.execute(
|
||||
"""
|
||||
INSERT INTO push_subscription (endpoint, p256dh, auth, created_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(endpoint) DO UPDATE SET p256dh=excluded.p256dh, auth=excluded.auth
|
||||
""",
|
||||
(sub["endpoint"], keys.get("p256dh", ""), keys.get("auth", ""), utc_now_iso()),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def get_subscriptions(db: aiosqlite.Connection) -> list[dict[str, str]]:
|
||||
cur = await db.execute("SELECT endpoint, p256dh, auth FROM push_subscription")
|
||||
rows = await cur.fetchall()
|
||||
await cur.close()
|
||||
return [{"endpoint": r[0], "p256dh": r[1], "auth": r[2]} for r in rows]
|
||||
|
||||
|
||||
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": endpoint,
|
||||
"keys": {"p256dh": sub["p256dh"], "auth": sub["auth"]},
|
||||
}
|
||||
try:
|
||||
webpush(
|
||||
subscription_info=subscription,
|
||||
data=json.dumps(payload),
|
||||
vapid_private_key=settings.vapid_private_key,
|
||||
vapid_claims=_vapid_claims(),
|
||||
)
|
||||
sent += 1
|
||||
logger.info("Push ok slot=%s endpoint=%s", slot_id, _endpoint_label(endpoint))
|
||||
except WebPushException as exc:
|
||||
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
|
||||
|
||||
|
||||
async def send_slot_reminder(
|
||||
db: aiosqlite.Connection,
|
||||
slot_id: str,
|
||||
title: str,
|
||||
body: str,
|
||||
*,
|
||||
silent: bool = True,
|
||||
) -> int:
|
||||
payload = {
|
||||
"title": title,
|
||||
"body": body,
|
||||
"slot_id": slot_id,
|
||||
"silent": silent,
|
||||
"tag": f"med-{slot_id}",
|
||||
}
|
||||
return await send_push(db, payload)
|
||||
+3
-3
@@ -13,7 +13,7 @@ from server.ai import generate_daily_motivation, generate_roast_of_the_day
|
||||
from server.config_loader import load_meds_config, slot_to_dict, today_str
|
||||
from server.db import get_db, utc_now_iso
|
||||
from server.messages import pick
|
||||
from server.notify import send_slot_reminder
|
||||
from server.push import send_slot_reminder
|
||||
from server.slots import build_today, get_log_for_day, mark_missed_for_overdue
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -37,7 +37,7 @@ async def _remind_slot(slot_id: str) -> None:
|
||||
return
|
||||
title = f"{slot.label} — Med-Time!"
|
||||
body = pick("reminder", label=slot.label, med=slot.meds[0].name if slot.meds else "Medis")
|
||||
sent = await send_slot_reminder(slot_id, title, body)
|
||||
sent = await send_slot_reminder(db, slot_id, title, body)
|
||||
logger.info("Reminder finished slot=%s day=%s sent=%d", slot_id, day, sent)
|
||||
finally:
|
||||
await db.close()
|
||||
@@ -76,7 +76,7 @@ async def _evening_check() -> None:
|
||||
logger.info("Evening check marked missed slots=%s", ",".join(marked))
|
||||
for slot_id in marked:
|
||||
body = pick("missed")
|
||||
sent = await send_slot_reminder(slot_id, "Verpasst?", body)
|
||||
sent = await send_slot_reminder(db, slot_id, "Verpasst?", body)
|
||||
logger.info("Evening reminder slot=%s sent=%d", slot_id, sent)
|
||||
finally:
|
||||
await db.close()
|
||||
|
||||
+3
-4
@@ -10,10 +10,9 @@ class Settings(BaseSettings):
|
||||
jwt_secret: str = "dev-secret-change-me"
|
||||
jwt_expire_days: int = 90
|
||||
|
||||
ntfy_url: str = "https://ntfy.schwenk.online"
|
||||
ntfy_topic: str = "takeyourmeds"
|
||||
ntfy_token: str = ""
|
||||
ntfy_click_url: str = "https://medis.schwenk.online"
|
||||
vapid_private_key: str = ""
|
||||
vapid_public_key: str = ""
|
||||
vapid_claims_email: str = "mailto:admin@schwenk.online"
|
||||
|
||||
openrouter_api_key: str = ""
|
||||
openrouter_model: str = "google/gemini-2.0-flash-001"
|
||||
|
||||
Reference in New Issue
Block a user