Files
harbour-grumpydove/src/pushservice.cpp
T

224 lines
7.5 KiB
C++

#include "pushservice.h"
#include "enginebridge.h"
#include <QCoreApplication>
#include <QDBusConnection>
#include <QDBusInterface>
#include <QDBusPendingCall>
#include <QDBusPendingCallWatcher>
#include <QDBusPendingReply>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QSettings>
#include <QStandardPaths>
#include <QThread>
#include <QTimer>
#include <QUuid>
extern "C" int gd_engine_run(void);
static const char *kServizio = "org.unifiedpush.Connector.harbour-grumpydove";
static const char *kOggetto = "/org/unifiedpush/Connector";
static const char *kDistributore = "org.unifiedpush.Distributor.Foghorn";
static const char *kPercorsoDistributore = "/org/unifiedpush/Distributor";
static const char *kInterfacciaDistributore = "org.unifiedpush.Distributor2";
PushService::PushService(QObject *parent) : QObject(parent)
{
QSettings s;
m_token = s.value(QStringLiteral("push/token")).toString();
m_endpoint = s.value(QStringLiteral("push/endpoint")).toString();
}
void PushService::start()
{
QDBusConnection bus = QDBusConnection::sessionBus();
if (!bus.isConnected()) {
qWarning() << "push: nessun bus di sessione";
return;
}
// Il processo possiede il nome (non si registra): è così che il
// distributore sa a chi consegnare.
if (!bus.registerService(QString::fromLatin1(kServizio)))
qWarning() << "push: nome già posseduto da un altro processo";
bus.registerObject(QString::fromLatin1(kOggetto), this,
QDBusConnection::ExportAllSlots);
// Il token è l'identità verso il distributore e va scritto su disco prima
// della registrazione: NewEndpoint può arrivare prima che Register
// ritorni.
if (m_token.isEmpty()) {
m_token = QUuid::createUuid().toString();
m_token.remove(QLatin1Char('{'));
m_token.remove(QLatin1Char('}'));
QSettings s;
s.setValue(QStringLiteral("push/token"), m_token);
}
registra();
}
void PushService::registra()
{
QDBusInterface distributore(QString::fromLatin1(kDistributore),
QString::fromLatin1(kPercorsoDistributore),
QString::fromLatin1(kInterfacciaDistributore),
QDBusConnection::sessionBus());
if (!distributore.isValid()) {
qWarning() << "push: distributore non disponibile (FogHorn assente?)";
return;
}
QVariantMap args;
args[QStringLiteral("service")] = QString::fromLatin1(kServizio);
args[QStringLiteral("token")] = m_token;
args[QStringLiteral("description")] = QStringLiteral("GrumpyDove");
// Asincrono: la risposta può arrivare dopo NewEndpoint, e bloccarsi qui
// sarebbe un abbraccio mortale.
QDBusPendingCall call = distributore.asyncCallWithArgumentList(
QStringLiteral("Register"), { args });
auto *watcher = new QDBusPendingCallWatcher(call, this);
connect(watcher, &QDBusPendingCallWatcher::finished, this,
[this](QDBusPendingCallWatcher *w) {
QDBusPendingReply<QVariantMap> r = *w;
w->deleteLater();
if (r.isError()) {
qWarning() << "push: Register:" << r.error().message();
return;
}
const QVariantMap m = r.value();
qDebug() << "push: registrazione"
<< m.value(QStringLiteral("success")).toString()
<< m.value(QStringLiteral("reason")).toString();
});
}
QVariantMap PushService::NewEndpoint(const QVariantMap &args)
{
const QString nuovo = args.value(QStringLiteral("endpoint")).toString();
if (!nuovo.isEmpty() && nuovo != m_endpoint) {
m_endpoint = nuovo;
QSettings s;
s.setValue(QStringLiteral("push/endpoint"), nuovo);
qDebug() << "push: endpoint ricevuto";
emit endpointChanged(nuovo);
}
QVariantMap r;
r[QStringLiteral("success")] = true;
return r;
}
QVariantMap PushService::Message(const QVariantMap &args)
{
// Il push non porta dati: dice solo che c'è qualcosa da guardare (il
// servizio Mozilla rifiuta un corpo non cifrato, quindi questa catena
// funziona con ntfy/FogHorn).
emit pushReceived();
QVariantMap r;
r[QStringLiteral("id")] = args.value(QStringLiteral("id"));
return r;
}
QVariantMap PushService::Unregistered(const QVariantMap &args)
{
Q_UNUSED(args)
m_endpoint.clear();
QSettings s;
s.remove(QStringLiteral("push/endpoint"));
emit endpointChanged(QString());
QVariantMap r;
r[QStringLiteral("success")] = true;
return r;
}
void notificaSistema(const QString &titolo, const QString &testo)
{
QDBusInterface n(QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("/org/freedesktop/Notifications"),
QStringLiteral("org.freedesktop.Notifications"),
QDBusConnection::sessionBus());
if (!n.isValid()) {
qWarning() << "notifica: servizio non disponibile";
return;
}
n.call(QStringLiteral("Notify"),
QStringLiteral("harbour-grumpydove"),
0u,
QStringLiteral("harbour-grumpydove"),
titolo, testo,
QStringList(),
QVariantMap(),
8000);
}
void preparaPercorsiMotore()
{
// Come in main(): la sandbox non lascia vedere ~/Mail né scrivere sotto
// HOME, quindi Maildir, log, rubrica e liste dei filtri stanno nella
// cartella dati dell'app. HOME non si tocca, o si perde il tema.
const QString dati = QStandardPaths::writableLocation(
QStandardPaths::AppDataLocation);
struct { const char *env; const char *sotto; } cartelle[] = {
{ "GRUMPYDOVE_MAIL", "/Mail" },
{ "GRUMPYDOVE_LOG", "/log" },
{ "GRUMPYDOVE_BOOKS", "/books" },
{ "GRUMPYDOVE_FILING", "/filing" },
};
for (const auto &c : cartelle) {
const QString percorso = dati + QString::fromLatin1(c.sotto);
QDir().mkpath(percorso);
qputenv(c.env, QFile::encodeName(percorso));
}
}
namespace {
// QThread::create() arriva in Qt 5.10; qui il target è Qt 5.6: il ciclo del
// motore va in una sottoclasse con run().
class ThreadMotore : public QThread
{
public:
void run() override { gd_engine_run(); }
};
}
int risveglioPush(int argc, char *argv[])
{
static int uno = 1;
QCoreApplication::setOrganizationName(QStringLiteral("harbour"));
QCoreApplication::setApplicationName(QStringLiteral("grumpydove"));
QCoreApplication app(uno, argv);
Q_UNUSED(argc)
preparaPercorsiMotore();
// Il motore entra in gd_engine_run e da lì nel suo ciclo: gira in un
// thread suo, mentre qui si aspetta l'esito.
EngineBridge bridge;
EngineBridge::setInstance(&bridge);
ThreadMotore motore;
motore.start();
// Tetto di sicurezza: un risveglio non deve restare appeso.
QTimer::singleShot(60000, &app, [&app]() {
qWarning() << "push: tempo scaduto";
app.exit(2);
});
// Si aspetta che il motore abbia letto le cartelle, poi si controlla.
QObject::connect(&bridge, &EngineBridge::ready, &app, [&app, &bridge]() {
static bool gia = false;
if (gia) return; // ready() arriva più volte
gia = true;
QObject::connect(&bridge, &EngineBridge::mailChecked, &app, [&app]() {
notificaSistema(QStringLiteral("Posta nuova"),
QStringLiteral("Tocca per leggere i messaggi"));
app.exit(0);
});
bridge.checkMail();
});
return app.exec();
}