Files
ntfy-notify/ntfy-notify.py
T

121 lines
4.4 KiB
Python
Raw Normal View History

2026-11-03 08:38:59 +04:00
#!/usr/bin/env python3
import asyncio
import base64
2026-11-03 08:38:59 +04:00
import json
import os
import subprocess
import tempfile
2026-11-03 08:38:59 +04:00
import time
import aiohttp
import yaml
2026-11-03 08:38:59 +04:00
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.join(SCRIPT_DIR, "config.yml")
POLL_INTERVAL = 10
2026-11-03 08:38:59 +04:00
def notify(urgency, title, message):
try:
subprocess.run(["notify-send", "-u", urgency, "--", title, message], check=True)
except Exception as e:
print(f"notify-send failed: {e}", flush=True)
def save_last_id(topic, message_id):
2026-11-03 08:38:59 +04:00
try:
with open(CONFIG_PATH) as f:
2026-11-03 08:38:59 +04:00
content = yaml.safe_load(f) or {}
changed = False
for sub in content.get("subscribe", []):
if sub.get("topic") == topic:
sub["last_id"] = str(message_id)
changed = True
if not changed:
return
fd, tmp = tempfile.mkstemp(dir=SCRIPT_DIR)
with os.fdopen(fd, "w") as f:
yaml.safe_dump(content, f, allow_unicode=True, default_flow_style=False)
os.replace(tmp, CONFIG_PATH)
2026-11-03 08:38:59 +04:00
except Exception as e:
print(f"Error saving last_id: {e}", flush=True)
def make_auth_header(user, password, token):
if token:
return {"Authorization": f"Bearer {token}"}
if user and password:
raw = f"{user}:{password}".encode()
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
return {}
2026-11-03 08:38:59 +04:00
def load_config():
if not os.path.exists(CONFIG_PATH):
msg = f"Config not found at {CONFIG_PATH}"
print(msg, flush=True)
notify("critical", "ntfy-notify", msg)
2026-11-03 08:38:59 +04:00
return []
try:
with open(CONFIG_PATH) as f:
2026-11-03 08:38:59 +04:00
config = yaml.safe_load(f) or {}
except Exception as e:
print(f"Error parsing config: {e}", flush=True)
2026-11-03 08:38:59 +04:00
return []
subs = []
for sub in config.get("subscribe", []):
topic = sub.get("topic")
host = str(sub.get("host") or "").strip().rstrip("/")
if not topic or not host:
print(f"Skipping subscription (topic={topic!r}, host={host!r})", flush=True)
continue
subs.append({
"topic": topic,
"url": f"{host}/{topic}/json",
"since": str(sub["last_id"]) if sub.get("last_id") else "1h",
"headers": make_auth_header(sub.get("user"), sub.get("password"), sub.get("token")),
})
return subs
def show(data):
priority = data.get("priority", 3)
urgency = "low" if priority in (1, 2) else "critical" if priority in (4, 5) else "normal"
notify(urgency, data.get("title") or data.get("topic", "ntfy"), data.get("message", ""))
2026-11-03 08:38:59 +04:00
async def handle_subscription(sub):
since = sub["since"]
timeout = aiohttp.ClientTimeout(total=30)
async with aiohttp.ClientSession(headers=sub["headers"], timeout=timeout) as session:
while True:
try:
params = {"since": since, "poll": "1"}
async with session.get(sub["url"], params=params) as resp:
if resp.status != 200:
body = (await resp.text())[:200]
print(f"[{sub['topic']}] HTTP {resp.status}: {body}", flush=True)
else:
async for line in resp.content:
line = line.strip()
if not line:
continue
2026-11-03 08:38:59 +04:00
try:
data = json.loads(line)
2026-11-03 08:38:59 +04:00
except json.JSONDecodeError:
continue
if data.get("event") != "message":
continue
show(data)
since = data["id"]
await asyncio.to_thread(save_last_id, sub["topic"], since)
except Exception as e:
print(f"[{sub['topic']}] network error: {e}", flush=True)
await asyncio.sleep(POLL_INTERVAL)
async def main(subs):
print("NTFY: watching:", ", ".join(s["topic"] for s in subs), flush=True)
await asyncio.gather(*(handle_subscription(s) for s in subs))
2026-11-03 08:38:59 +04:00
if __name__ == "__main__":
while True:
subs = load_config()
if subs:
asyncio.run(main(subs))
2026-11-03 08:38:59 +04:00
else:
print("Config error or empty subscriptions. Retry in 5 minutes...", flush=True)
time.sleep(300)