72 lines
2.2 KiB
Python
72 lines
2.2 KiB
Python
"""NTFY push notification plugin."""
|
|
|
|
import logging
|
|
import threading
|
|
|
|
import httpx
|
|
|
|
logger = logging.getLogger("plugins.ntfy")
|
|
|
|
EVENT_TAGS = {
|
|
"start": "red_circle",
|
|
"stop": "white_check_mark",
|
|
"error": "rotating_light",
|
|
"upload": "outbox_tray",
|
|
}
|
|
|
|
|
|
def _post(url: str, title: str, message: str, token: str, priority: str, tags: str):
|
|
params = {"title": title, "priority": priority or "default"}
|
|
if tags:
|
|
params["tags"] = tags
|
|
headers = {"Content-Type": "text/plain; charset=utf-8"}
|
|
if token:
|
|
headers["Authorization"] = f"Bearer {token}"
|
|
try:
|
|
resp = httpx.post(url, params=params, content=message.encode("utf-8"),
|
|
headers=headers, timeout=10.0)
|
|
if resp.status_code >= 400:
|
|
logger.warning("NTFY-Benachrichtigung fehlgeschlagen: HTTP %s %s",
|
|
resp.status_code, resp.text[:200])
|
|
except Exception as e:
|
|
logger.warning("NTFY-Benachrichtigung fehlgeschlagen: %s", e)
|
|
|
|
|
|
def send_notification(
|
|
url: str,
|
|
title: str,
|
|
message: str,
|
|
token: str = "",
|
|
priority: str = "default",
|
|
tags: str = "",
|
|
):
|
|
if not url:
|
|
return
|
|
threading.Thread(
|
|
target=_post,
|
|
args=(url, title, message, token, priority, tags),
|
|
daemon=True,
|
|
).start()
|
|
|
|
|
|
class NtfyNotifier:
|
|
def __init__(self, config):
|
|
self.config = config
|
|
|
|
def _should_notify(self, event: str, job_ntfy_enabled: bool) -> bool:
|
|
if not job_ntfy_enabled:
|
|
return False
|
|
url = self.config.get("ntfy", "url", default="")
|
|
if not url:
|
|
return False
|
|
events = self.config.get("ntfy", "events", default="error") or ""
|
|
return event in [e.strip() for e in events.split(",")]
|
|
|
|
def notify(self, event: str, title: str, message: str, job_ntfy_enabled: bool = False, priority: str = "default"):
|
|
if not self._should_notify(event, job_ntfy_enabled):
|
|
return
|
|
url = self.config.get("ntfy", "url", default="")
|
|
token = self.config.get("ntfy", "token", default="")
|
|
tag = EVENT_TAGS.get(event, "")
|
|
send_notification(url, title, message, token=token, priority=priority, tags=tag)
|