#!/usr/bin/env python3 import asyncio import base64 import json import os import subprocess import tempfile import time import aiohttp import yaml SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) CONFIG_PATH = os.path.join(SCRIPT_DIR, "config.yml") POLL_INTERVAL = 10 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): try: with open(CONFIG_PATH) as f: 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) 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 {} 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) return [] try: with open(CONFIG_PATH) as f: config = yaml.safe_load(f) or {} except Exception as e: print(f"Error parsing config: {e}", flush=True) 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", "")) 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 try: data = json.loads(line) 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)) if __name__ == "__main__": while True: subs = load_config() if subs: asyncio.run(main(subs)) else: print("Config error or empty subscriptions. Retry in 5 minutes...", flush=True) time.sleep(300)