142 lines
4.5 KiB
Python
142 lines
4.5 KiB
Python
#!/usr/bin/env python3
|
|
# Watcher IMAP per harbour-grumpydove.
|
|
#
|
|
# La posta non ha un servizio push: il telefono non può tenere aperta una
|
|
# connessione IMAP quando è in tasca. Questo watcher fa il lavoro che
|
|
# l'app non può fare — guarda la casella dal server — e quando arriva
|
|
# qualcosa manda un push vuoto all'endpoint UnifiedPush del telefono.
|
|
#
|
|
# Il push non porta dati: dice solo "guarda". L'app si sveglia, controlla la
|
|
# posta e pubblica la notifica (vedi src/pushservice.cpp).
|
|
#
|
|
# Config: /etc/gd-push-watcher.conf (0600), formato chiave=valore:
|
|
# endpoint=https://ntfy.sh/UP?topic=xxxx (dall'app: Account > Push)
|
|
# host=pop.tophost.it
|
|
# user=carlo@example.it
|
|
# password=...
|
|
# cartella=INBOX
|
|
#
|
|
# Uso:
|
|
# gd-push-watcher.py --config /etc/gd-push-watcher.conf --una-volta
|
|
# gd-push-watcher.py --config /etc/gd-push-watcher.conf # ciclo
|
|
import argparse
|
|
import imaplib
|
|
import os
|
|
import shutil
|
|
import ssl
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
|
|
def leggi_config(percorso):
|
|
conf = {}
|
|
for riga in Path(percorso).read_text(encoding="utf-8").splitlines():
|
|
riga = riga.strip()
|
|
if not riga or riga.startswith("#") or "=" not in riga:
|
|
continue
|
|
chiave, valore = riga.split("=", 1)
|
|
conf[chiave.strip()] = valore.strip()
|
|
return conf
|
|
|
|
|
|
def invia_push(endpoint, titolo="Posta nuova"):
|
|
# Corpo in chiaro come fa FMD: questa catena funziona con ntfy/FogHorn,
|
|
# non con il servizio Mozilla (che rifiuta un corpo non cifrato).
|
|
corpo = b'{"message": "gd wakeup", "priority": 5}'
|
|
richiesta = urllib.request.Request(
|
|
endpoint,
|
|
data=corpo,
|
|
headers={
|
|
"Content-Type": "application/json",
|
|
"TTL": "86400",
|
|
"Urgency": "high",
|
|
},
|
|
method="POST",
|
|
)
|
|
with urllib.request.urlopen(richiesta, timeout=15) as risposta:
|
|
return risposta.status
|
|
|
|
|
|
def non_letti(conf):
|
|
host = conf["host"]
|
|
utente = conf["user"]
|
|
password = conf["password"]
|
|
cartella = conf.get("cartella", "INBOX")
|
|
porta = int(conf.get("porta", "993"))
|
|
sicurezza = conf.get("sicurezza", "tls").lower()
|
|
|
|
if sicurezza == "starttls":
|
|
m = imaplib.IMAP4(host, int(conf.get("porta", "143")))
|
|
m.starttls(ssl.create_default_context())
|
|
else:
|
|
m = imaplib.IMAP4_SSL(host, porta, ssl_context=ssl.create_default_context())
|
|
try:
|
|
m.login(utente, password)
|
|
m.select(cartella, readonly=True)
|
|
tipologia, dati = m.search(None, "UNSEEN")
|
|
if tipologia != "OK":
|
|
return None
|
|
elenco = dati[0].split()
|
|
return len(elenco)
|
|
finally:
|
|
try:
|
|
m.close()
|
|
except Exception:
|
|
pass
|
|
m.logout()
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description="Watcher IMAP che manda un push")
|
|
p.add_argument("--config", default="/etc/gd-push-watcher.conf")
|
|
p.add_argument("--una-volta", action="store_true",
|
|
help="un solo giro, per provare")
|
|
p.add_argument("--ogni", type=int, default=60,
|
|
help="secondi fra un controllo e l'altro (default 60)")
|
|
argomenti = p.parse_args()
|
|
|
|
conf = leggi_config(argomenti.config)
|
|
for chiave in ("endpoint", "host", "user", "password"):
|
|
if not conf.get(chiave):
|
|
print(f"config: manca {chiave}", file=sys.stderr)
|
|
return 2
|
|
|
|
# Il conteggio precedente sta accanto alla config: se il servizio
|
|
# riparte, non rimanda un push per messaggi già segnalati.
|
|
stato = Path(argomenti.config + ".stato")
|
|
|
|
def giro():
|
|
attuale = non_letti(conf)
|
|
if attuale is None:
|
|
return None
|
|
prima = -1
|
|
if stato.exists():
|
|
try:
|
|
prima = int(stato.read_text().strip() or "-1")
|
|
except ValueError:
|
|
prima = -1
|
|
stato.write_text(str(attuale), encoding="utf-8")
|
|
if prima >= 0 and attuale > prima:
|
|
codice = invia_push(conf["endpoint"])
|
|
print(f"push inviato ({attuale - prima} nuovi, HTTP {codice})",
|
|
flush=True)
|
|
return attuale
|
|
|
|
if argomenti.una_volta:
|
|
attuale = giro()
|
|
print(f"non letti: {attuale}")
|
|
return 0 if attuale is not None else 1
|
|
|
|
while True:
|
|
try:
|
|
giro()
|
|
except Exception as errore: # un giro storto non ferma il servizio
|
|
print(f"errore: {errore}", file=sys.stderr, flush=True)
|
|
time.sleep(max(15, argomenti.ogni))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|