Files
Pingognito/backend/app/api_notifications.py

200 lines
8.2 KiB
Python

"""HTTP-Schnittstelle für Benachrichtigungen (Webhook, n8n, ntfy)."""
from __future__ import annotations
from typing import Any, Callable
from fastapi import APIRouter, HTTPException, Query, Request
from . import i18n
from .api_common import make_protokoll
from .api_i18n import req_lang
from .audit import AuditLog
from .notifications import EREIGNISSE, exportieren, importieren, maskiere, testen
def build_router(
db: Any,
get_store: Callable[[], Any],
audit: AuditLog,
) -> APIRouter:
"""Baut den Router für Benachrichtigungskanäle sowie Export/Import."""
router = APIRouter()
protokoll = make_protokoll(audit)
@router.get("/api/notifications/export")
def export_notifications(
http_request: Request,
mit_geheimnissen: bool = Query(
False, description="Passwörter und geheime Header im Klartext ausgeben"
),
) -> dict[str, Any]:
"""Export der Benachrichtigungskonfiguration als JSON."""
daten = exportieren(get_store(), mit_geheimnissen=mit_geheimnissen)
protokoll(
http_request, "notifications.exported", "notifications",
detail=("Export mit Geheimnissen" if mit_geheimnissen
else "Export ohne Geheimnisse (maskiert)"),
target="notifications",
)
return {"export": daten}
@router.post("/api/notifications/import")
def import_notifications(
payload: dict[str, Any], http_request: Request
) -> dict[str, Any]:
"""Übernimmt einen exportierten Konfigurationsstand."""
if not isinstance(payload, dict):
raise HTTPException(status_code=400, detail="Import erwartet ein Objekt")
anzahl, warnungen = importieren(get_store(), payload)
protokoll(
http_request, "notifications.imported", "notifications",
detail=f"{anzahl} Einträge übernommen, {len(warnungen)} Warnungen",
target="notifications",
)
return {"uebernommen": anzahl, "übernommen": anzahl, "warnungen": warnungen}
@router.get("/api/notifications")
def list_notifications(http_request: Request) -> dict[str, Any]:
"""Alle eingerichteten Benachrichtigungen (Secrets maskiert)."""
store = get_store()
lang = req_lang(http_request)
all_i18n = db.get_all_entry_i18n("notification")
eintraege = []
for b in store.alle():
d = maskiere(b)
ent = all_i18n.get(b.id)
if not ent and (b.name or b.template):
ent = i18n.sync_entry_translations(
db, "notification", b.id,
{"name": b.name, "template": b.template},
source_lang="auto",
)
d["i18n"] = ent or {}
if lang != "de" and d.get("letzter_fehler"):
d["letzter_fehler"] = i18n.translate_text(
str(d["letzter_fehler"]), lang, source_lang="de", db=db
)
eintraege.append(d)
return {
"notifications": eintraege,
"total": len(eintraege),
"ereignisse": list(EREIGNISSE),
}
@router.post("/api/notifications", status_code=201)
def create_notification(
payload: dict[str, Any], http_request: Request
) -> dict[str, Any]:
"""Legt eine Benachrichtigung an. Es wird dabei nichts versendet."""
daten = payload or {}
try:
neu = get_store().anlegen(
name=str(daten.get("name", "") or ""),
art=str(daten.get("art", "webhook") or "webhook"),
ziel=str(daten.get("ziel", "") or ""),
aktiv=bool(daten.get("aktiv", False)),
ereignisse=daten.get("ereignisse") or [],
min_severity=str(daten.get("min_severity", "info") or "info"),
template=str(daten.get("template", "") or ""),
headers=daten.get("headers") or {},
passwort=str(daten.get("passwort", "") or ""),
extern_erlaubt=bool(daten.get("extern_erlaubt", False)),
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
ent_i18n = i18n.sync_entry_translations(
db, "notification", neu.id,
{"name": neu.name, "template": neu.template},
source_lang=req_lang(http_request),
overrides=daten.get("i18n"),
)
protokoll(
http_request, "notification.created", "notifications",
detail=f"Benachrichtigung '{neu.name}' angelegt ({neu.art})",
target=neu.id,
)
d = maskiere(neu)
d["i18n"] = ent_i18n
return {"notification": d}
@router.put("/api/notifications/{notif_id}")
def update_notification(
notif_id: str, payload: dict[str, Any], http_request: Request
) -> dict[str, Any]:
"""Ändert eine Benachrichtigung."""
store = get_store()
if not store.hole(notif_id):
raise HTTPException(status_code=404, detail="Benachrichtigung nicht gefunden")
daten = payload or {}
erlaubt = (
"name", "art", "ziel", "aktiv", "ereignisse", "min_severity",
"template", "headers", "passwort", "extern_erlaubt",
)
aenderungen = {k: v for k, v in daten.items() if k in erlaubt}
try:
aktualisiert = store.aktualisieren(notif_id, **aenderungen)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if aktualisiert is None:
raise HTTPException(status_code=404, detail="Benachrichtigung nicht gefunden")
ent_i18n = i18n.sync_entry_translations(
db, "notification", notif_id,
{"name": aktualisiert.name, "template": aktualisiert.template},
source_lang=req_lang(http_request),
overrides=daten.get("i18n"),
)
protokoll(
http_request, "notification.updated", "notifications",
detail=f"Benachrichtigung '{aktualisiert.name}' geändert",
target=notif_id,
)
d = maskiere(aktualisiert)
d["i18n"] = ent_i18n
return {"notification": d}
@router.delete("/api/notifications/{notif_id}")
def delete_notification(notif_id: str, http_request: Request) -> dict[str, Any]:
"""Löscht eine Benachrichtigung."""
store = get_store()
eintrag = store.hole(notif_id)
if not store.loeschen(notif_id):
raise HTTPException(status_code=404, detail="Benachrichtigung nicht gefunden")
db.delete_entry_i18n("notification", notif_id)
protokoll(
http_request, "notification.deleted", "notifications",
detail=f"Benachrichtigung '{getattr(eintrag, 'name', notif_id)}' gelöscht",
target=notif_id,
)
return {"deleted": notif_id}
@router.post("/api/notifications/{notif_id}/test")
def test_notification(notif_id: str, http_request: Request) -> dict[str, Any]:
"""Sendet eine Testnachricht über den konfigurierten Kanal."""
store = get_store()
eintrag = store.hole(notif_id)
if not eintrag:
raise HTTPException(status_code=404, detail="Benachrichtigung nicht gefunden")
erfolg, fehler = testen(eintrag)
store.zustellung_vermerken(notif_id, erfolg, fehler)
protokoll(
http_request, "notification.tested", "notifications",
detail=("Testsendung erfolgreich" if erfolg
else f"Testsendung fehlgeschlagen: {fehler}"),
target=notif_id, result="ok" if erfolg else "fehler",
)
lang = req_lang(http_request)
if fehler and lang != "de":
fehler = i18n.translate_text(fehler, lang, source_lang="de", db=db)
notif_dict = maskiere(store.hole(notif_id) or eintrag)
if lang != "de" and notif_dict.get("letzter_fehler"):
notif_dict["letzter_fehler"] = i18n.translate_text(
str(notif_dict["letzter_fehler"]), lang, source_lang="de", db=db
)
return {
"erfolg": erfolg,
"fehler": fehler,
"notification": notif_dict,
}
return router