Push: endpoint visibile in Account, watcher IMAP per il server
This commit is contained in:
1 parent
39c9608ecb
commit
4de759b3cf
4 files changed
+187
No files matched your search
@@ -0,0 +1,141 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,20 @@
|
||||
[Unit]
|
||||
Description=Watcher IMAP di harbour-grumpydove (manda il push al telefono)
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/local/bin/gd-push-watcher.py --config /etc/gd-push-watcher.conf --ogni 60
|
||||
Restart=always
|
||||
RestartSec=30
|
||||
# La config contiene la password della casella: leggibile solo da root.
|
||||
User=root
|
||||
NoNewPrivileges=yes
|
||||
PrivateTmp=yes
|
||||
ProtectSystem=strict
|
||||
ProtectHome=yes
|
||||
ReadWritePaths=/etc
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -165,6 +165,29 @@ Page {
|
||||
}
|
||||
}
|
||||
|
||||
SectionHeader { text: qsTr("Notifiche push") }
|
||||
|
||||
Label {
|
||||
width: parent.width - 2 * Theme.horizontalPageMargin
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
wrapMode: Text.Wrap
|
||||
font.pixelSize: Theme.fontSizeExtraSmall
|
||||
color: Theme.secondaryColor
|
||||
text: pushService.endpoint.length > 0
|
||||
? qsTr("Registrato. Questo è l'indirizzo da mettere nel watcher del server:")
|
||||
: qsTr("Non registrato: serve il distributore UnifiedPush (FogHorn). Senza push la posta si controlla ogni N minuti.")
|
||||
}
|
||||
|
||||
Label {
|
||||
width: parent.width - 2 * Theme.horizontalPageMargin
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
wrapMode: Text.WrapAnywhere
|
||||
visible: pushService.endpoint.length > 0
|
||||
text: pushService.endpoint
|
||||
font.pixelSize: Theme.fontSizeExtraSmall
|
||||
color: Theme.primaryColor
|
||||
}
|
||||
|
||||
SectionHeader { text: qsTr("Rubrica (CardDAV)") }
|
||||
|
||||
TextField {
|
||||
|
||||
@@ -16,6 +16,9 @@ class PushService : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_CLASSINFO("D-Bus Interface", "org.unifiedpush.Connector2")
|
||||
// L'endpoint serve all'utente: è quello che si mette nella configurazione
|
||||
// del watcher che manda i push.
|
||||
Q_PROPERTY(QString endpoint READ endpoint NOTIFY endpointChanged)
|
||||
|
||||
public:
|
||||
explicit PushService(QObject *parent = nullptr);
|
||||
|
||||
Reference in new issue
Block a user