feat: ntfy desktop notifier with systemd user service
This commit is contained in:
1 parent
39c23187d1
commit
651cdfd5bf
2 files changed
+94
-140
No files matched your search
+3
-2
@@ -1,6 +1,7 @@
|
|||||||
subscribe:
|
subscribe:
|
||||||
- host:
|
- host:
|
||||||
last_id:
|
last_id:
|
||||||
password_base64:
|
token:
|
||||||
|
#user:
|
||||||
|
#password:
|
||||||
topic:
|
topic:
|
||||||
user:
|
|
||||||
Regular → Executable
+91
-138
@@ -1,168 +1,121 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
import asyncio
|
import asyncio
|
||||||
import aiohttp
|
|
||||||
import json
|
|
||||||
import yaml
|
|
||||||
import subprocess
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import base64
|
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__))
|
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
CONFIG_PATH = os.path.join(SCRIPT_DIR, "config.yml")
|
CONFIG_PATH = os.path.join(SCRIPT_DIR, "config.yml")
|
||||||
|
POLL_INTERVAL = 10
|
||||||
|
|
||||||
def update_config_last_id(topic, message_id):
|
def notify(urgency, title, message):
|
||||||
"""Finds the specific topic in the config file and updates its last_id."""
|
|
||||||
if not os.path.exists(CONFIG_PATH):
|
|
||||||
return
|
|
||||||
try:
|
try:
|
||||||
with open(CONFIG_PATH, 'r') as f:
|
subprocess.run(["notify-send", "-u", urgency, "--", title, message], check=True)
|
||||||
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:
|
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():
|
def load_config():
|
||||||
if not os.path.exists(CONFIG_PATH):
|
if not os.path.exists(CONFIG_PATH):
|
||||||
message = f"Config not found at {CONFIG_PATH}"
|
msg = f"Config not found at {CONFIG_PATH}"
|
||||||
print(message)
|
print(msg, flush=True)
|
||||||
try:
|
notify("critical", "ntfy-notify", msg)
|
||||||
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 []
|
return []
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(CONFIG_PATH, 'r') as f:
|
with open(CONFIG_PATH) as f:
|
||||||
config = yaml.safe_load(f) or {}
|
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:
|
except Exception as e:
|
||||||
print(f"Error loading or parsing config: {e}")
|
print(f"Error parsing config: {e}", flush=True)
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def run_command(data):
|
subs = []
|
||||||
"""Formats the command and executes it via subprocess."""
|
for sub in config.get("subscribe", []):
|
||||||
priority = data.get('priority', 3)
|
topic = sub.get("topic")
|
||||||
urgency = "low" if priority in [1, 2] else "critical" if priority in [4, 5] else "normal"
|
host = str(sub.get("host") or "").strip().rstrip("/")
|
||||||
command = f"notify-send -u {urgency} \"{data.get('title', '')}\" \"{data.get('message', '')}\""
|
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:
|
def show(data):
|
||||||
subprocess.run(command, shell=True, check=True)
|
priority = data.get("priority", 3)
|
||||||
except Exception as e:
|
urgency = "low" if priority in (1, 2) else "critical" if priority in (4, 5) else "normal"
|
||||||
print(f"Error executing command: {e}")
|
notify(urgency, data.get("title") or data.get("topic", "ntfy"), data.get("message", ""))
|
||||||
|
|
||||||
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):
|
async def handle_subscription(sub):
|
||||||
"""Handles a single ntfy subscription stream via reliable polling."""
|
since = sub["since"]
|
||||||
current_url = sub['url']
|
timeout = aiohttp.ClientTimeout(total=30)
|
||||||
|
async with aiohttp.ClientSession(headers=sub["headers"], timeout=timeout) as session:
|
||||||
while True:
|
while True:
|
||||||
auth = aiohttp.BasicAuth(sub['user'], sub['password']) if sub.get('user') else None
|
try:
|
||||||
|
params = {"since": since, "poll": "1"}
|
||||||
try:
|
async with session.get(sub["url"], params=params) as resp:
|
||||||
async with aiohttp.ClientSession() as session:
|
if resp.status != 200:
|
||||||
async with session.get(current_url, auth=auth) as response:
|
body = (await resp.text())[:200]
|
||||||
if response.status != 200:
|
print(f"[{sub['topic']}] HTTP {resp.status}: {body}", flush=True)
|
||||||
print(f"HTTP Error {response.status} for {sub['topic']}. Retrying...")
|
else:
|
||||||
await asyncio.sleep(10)
|
async for line in resp.content:
|
||||||
continue
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
async for line in response.content:
|
continue
|
||||||
if line:
|
|
||||||
try:
|
try:
|
||||||
line_str = line.decode('utf-8').strip()
|
data = json.loads(line)
|
||||||
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:
|
except json.JSONDecodeError:
|
||||||
pass
|
continue
|
||||||
except Exception as e:
|
if data.get("event") != "message":
|
||||||
print(f"An error occurred for {sub['topic']}: {e}")
|
continue
|
||||||
except Exception as e:
|
show(data)
|
||||||
print(f"Network error for {sub['topic']}: {e}")
|
since = data["id"]
|
||||||
|
await asyncio.to_thread(save_last_id, sub["topic"], since)
|
||||||
# Poll the server every 10 seconds
|
except Exception as e:
|
||||||
await asyncio.sleep(10)
|
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__":
|
if __name__ == "__main__":
|
||||||
while True:
|
while True:
|
||||||
subs = load_config()
|
subs = load_config()
|
||||||
if subs:
|
if subs:
|
||||||
asyncio.run(subscribe_and_listen(subs))
|
asyncio.run(main(subs))
|
||||||
else:
|
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)
|
time.sleep(300)
|
||||||
Reference in new issue
Block a user