feat: ntfy desktop notifier with systemd user service

This commit is contained in:
pyrschtjag committed 2026-11-03 09:05:20 +04:00
1 parent 39c23187d1
commit 651cdfd5bf
2 files changed
+93 -139

No files matched your search

+3 -2
View File
@@ -1,6 +1,7 @@
subscribe:
- host:
last_id:
password_base64:
token:
#user:
#password:
topic:
user:
Regular → Executable
+90 -137
View File
@@ -1,168 +1,121 @@
#!/usr/bin/env python3
import asyncio
import aiohttp
import json
import yaml
import subprocess
import os
import time
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 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
def notify(urgency, title, message):
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)
subprocess.run(["notify-send", "-u", urgency, "--", title, message], check=True)
except Exception as e:
print(f"Error saving last_id to {CONFIG_PATH}: {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):
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}")
msg = f"Config not found at {CONFIG_PATH}"
print(msg, flush=True)
notify("critical", "ntfy-notify", msg)
return []
try:
with open(CONFIG_PATH, 'r') as f:
with open(CONFIG_PATH) 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}")
print(f"Error parsing config: {e}", flush=True)
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', '')}\""
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
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)
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):
"""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:
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:
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)
data = json.loads(line)
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)
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(subscribe_and_listen(subs))
asyncio.run(main(subs))
else:
print("Config error or empty subscriptions. Waiting 5 minutes before retry...")
print("Config error or empty subscriptions. Retry in 5 minutes...", flush=True)
time.sleep(300)