#!/usr/bin/env python3 import asyncio import aiohttp import json import yaml import subprocess import os import time import base64 SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) CONFIG_PATH = os.path.join(SCRIPT_DIR, "config.yml") def update_config_last_id(topic, message_id): """Finds the specific topic in the config file and updates its last_id.""" if not os.path.exists(CONFIG_PATH): return try: with open(CONFIG_PATH, 'r') as f: content = yaml.safe_load(f) or {} if content and 'subscribe' in content: updated = False for sub in content['subscribe']: if sub.get('topic') == topic: sub['last_id'] = str(message_id) updated = True if updated: with open(CONFIG_PATH, 'w') as f: yaml.safe_dump(content, f, allow_unicode=True, default_flow_style=False) except Exception as e: print(f"Error saving last_id to {CONFIG_PATH}: {e}") def load_config(): if not os.path.exists(CONFIG_PATH): message = f"Config not found at {CONFIG_PATH}" print(message) try: subprocess.run(["notify-send", "-u", "critical", "ntfy-notify", message], check=True) except Exception as e: print(f"Warning: Could not send desktop notification: {e}") return [] try: with open(CONFIG_PATH, 'r') as f: config = yaml.safe_load(f) or {} subscriptions = [] for sub in config.get('subscribe', []): topic = sub.get('topic') command = sub.get('command') host = sub.get('host') if not host or not str(host).strip(): print(f"Host is missing or empty for topic '{topic}'. Exiting.") return [] host = host.rstrip('/') if topic: last_id = sub.get('last_id') # If last_id exists, poll for messages since that ID. # Adding poll=1 bypasses Nginx reverse proxy buffering issues. if last_id: url = f"{host}/{topic}/json?since={last_id}&poll=1" else: # Fallback for the first run: fetch last 1 hour of messages url = f"{host}/{topic}/json?since=1h&poll=1" encoded_password = sub.get('password_base64') if encoded_password: try: decrypted_password = base64.b64decode(encoded_password.encode('utf-8')).decode('utf-8') except Exception: print("Error: Failed to decode password_base64.") decrypted_password = None else: decrypted_password = sub.get('password') subscriptions.append({ 'url': url, 'topic': topic, 'command': command, 'user': sub.get('user'), 'password': decrypted_password, 'if_condition': sub.get('if', {}), 'base_url': f"{host}/{topic}/json" # Keep clean URL for dynamic dynamic queries }) return subscriptions except Exception as e: print(f"Error loading or parsing config: {e}") return [] def run_command(data): """Formats the command and executes it via subprocess.""" priority = data.get('priority', 3) urgency = "low" if priority in [1, 2] else "critical" if priority in [4, 5] else "normal" command = f"notify-send -u {urgency} \"{data.get('title', '')}\" \"{data.get('message', '')}\"" try: subprocess.run(command, shell=True, check=True) except Exception as e: print(f"Error executing command: {e}") async def subscribe_and_listen(subscriptions): if not subscriptions: print("No valid subscriptions found in config. Exiting.") return subscription_topics = ', '.join([sub['topic'] for sub in subscriptions]) print(f"NTFY: Watching for subscriptions: {subscription_topics}") tasks = [asyncio.create_task(handle_subscription(sub)) for sub in subscriptions] await asyncio.gather(*tasks) async def handle_subscription(sub): """Handles a single ntfy subscription stream via reliable polling.""" current_url = sub['url'] while True: auth = aiohttp.BasicAuth(sub['user'], sub['password']) if sub.get('user') else None try: async with aiohttp.ClientSession() as session: async with session.get(current_url, auth=auth) as response: if response.status != 200: print(f"HTTP Error {response.status} for {sub['topic']}. Retrying...") await asyncio.sleep(10) continue async for line in response.content: if line: try: line_str = line.decode('utf-8').strip() if not line_str: continue data = json.loads(line_str) if data.get('event') == 'message': msg_id = data.get('id') if msg_id: # Save new last_id into the config file safely using threads await asyncio.to_thread(update_config_last_id, sub['topic'], msg_id) # Update current execution context URL for the next poll step current_url = f"{sub['base_url']}?since={msg_id}&poll=1" run_command(data) except json.JSONDecodeError: pass except Exception as e: print(f"An error occurred for {sub['topic']}: {e}") except Exception as e: print(f"Network error for {sub['topic']}: {e}") # Poll the server every 10 seconds await asyncio.sleep(10) if __name__ == "__main__": while True: subs = load_config() if subs: asyncio.run(subscribe_and_listen(subs)) else: print("Config error or empty subscriptions. Waiting 5 minutes before retry...") time.sleep(300)