imsd-messages/interfaces/ImsdMessages.Bus-Client.cppm

226 lines
10 KiB
Text
Raw Normal View History

// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
Bus: the GDBus client, imsd's dictionaries, the notifier and the owned name The GLib side of the app. Variant reads imsd's Received dictionary by key and type as its SmsVariant writes it (`to`, the number the text arrived for, a tel: URI read like the status's `ppi`; `operator`, the SIM it arrived under), the GetStatus one with the subscriber's own number and the SIM's operator in it (`ppi`, a tel: URI as the frozen interface gives it; `operator`), and maps a GError to the core's error kinds off GDBus's own mapping. Client is the Sync logic's transport: asynchronous calls with their continuations as user data — every reply guarded where it is delivered (OnCallDone), as are the signal handlers and the name watch's callbacks: a throw is a fault the events hear, not the end of the process — the calls behind imsd's polkit gate allow interaction: Subscribe, List and Delete wait two minutes; Send has no bound of the client's, since imsd sends the text once its prompt lets the call through, however late, and a Send given up on would be failed by Sync and be sent all the same; GetStatus ten seconds — (one call: the Messaging status carries the own number, imsd reading both from one snapshot; AGENTS.md §1 names both interfaces), the Messaging and RegistrationChanged signals, and a watch on net.catcrafts.IMS1 whose appeared callback is where Sync subscribes. Notifier shows one desktop notification per conversation and replaces it as more texts arrive: one Notify at a time per conversation, since the id to replace comes with the answer; its default action asks the app for that conversation; the body is escaped when the server renders markup (GetCapabilities, asked once; Plasma and GNOME do), so a text's '<' or '&' shows as typed. Instance owns net.catcrafts.ImsdMessages and serves org.freedesktop.Application there, the Desktop Entry Specification's interface of a running application: Activate, Open and ActivateAction, each with its platform data — sent empty and not read: nothing in the app can use an activation token yet — and one action, quit, any other refused (the object registered before the name is asked for, so a launch that forwards the moment the name is granted finds it; Own tells a name another instance holds from a request that failed or was refused, and keeps the error's words); it forwards a call to the owner. project.cpp computes the gio flags once for the bus library, the executable and the Decode test. Tested: tests/Decode (every key of imsd's Received dictionary, one with ten of them, GetStatus, the own number, the SIM's operator, the error kinds, the markup escape, the parameters of the instance's three calls).
2026-10-17 23:45:29 +02:00
// lint-disable-file no-char-pointer
/*
ImsdMessages.Bus:Client — the GDBus client of net.catcrafts.IMS1.Messaging,
the Sync logic's transport. Every call is asynchronous and answers on the
GLib main loop; the signals and the name watch feed ImsdEvents (Sync), the
watch's appeared callback being where Sync subscribes. One connection:
the system bus, or the session bus for `imsd --session`.
*/
module;
#include <gio/gio.h>
export module ImsdMessages.Bus:Client;
import std;
Bus: the GDBus client, imsd's dictionaries, the notifier and the owned name The GLib side of the app. Variant reads imsd's Received dictionary by key and type as its SmsVariant writes it (`to`, the number the text arrived for, a tel: URI read like the status's `ppi`; `operator`, the SIM it arrived under), the GetStatus one with the subscriber's own number and the SIM's operator in it (`ppi`, a tel: URI as the frozen interface gives it; `operator`), and maps a GError to the core's error kinds off GDBus's own mapping. Client is the Sync logic's transport: asynchronous calls with their continuations as user data — every reply guarded where it is delivered (OnCallDone), as are the signal handlers and the name watch's callbacks: a throw is a fault the events hear, not the end of the process — the calls behind imsd's polkit gate allow interaction: Subscribe, List and Delete wait two minutes; Send has no bound of the client's, since imsd sends the text once its prompt lets the call through, however late, and a Send given up on would be failed by Sync and be sent all the same; GetStatus ten seconds — (one call: the Messaging status carries the own number, imsd reading both from one snapshot; AGENTS.md §1 names both interfaces), the Messaging and RegistrationChanged signals, and a watch on net.catcrafts.IMS1 whose appeared callback is where Sync subscribes. Notifier shows one desktop notification per conversation and replaces it as more texts arrive: one Notify at a time per conversation, since the id to replace comes with the answer; its default action asks the app for that conversation; the body is escaped when the server renders markup (GetCapabilities, asked once; Plasma and GNOME do), so a text's '<' or '&' shows as typed. Instance owns net.catcrafts.ImsdMessages and serves org.freedesktop.Application there, the Desktop Entry Specification's interface of a running application: Activate, Open and ActivateAction, each with its platform data — sent empty and not read: nothing in the app can use an activation token yet — and one action, quit, any other refused (the object registered before the name is asked for, so a launch that forwards the moment the name is granted finds it; Own tells a name another instance holds from a request that failed or was refused, and keeps the error's words); it forwards a call to the owner. project.cpp computes the gio flags once for the bus library, the executable and the Decode test. Tested: tests/Decode (every key of imsd's Received dictionary, one with ten of them, GetStatus, the own number, the SIM's operator, the error kinds, the markup escape, the parameters of the instance's three calls).
2026-10-17 23:45:29 +02:00
import ImsdMessages;
import :Variant;
namespace ImsdMessages::Bus {
constexpr const char* imsdName = "net.catcrafts.IMS1";
constexpr const char* imsdPath = "/net/catcrafts/IMS1";
constexpr const char* imsdIface = "net.catcrafts.IMS1";
constexpr const char* messagingIface = "net.catcrafts.IMS1.Messaging";
constexpr gint callTimeoutMs = 10000;
// Subscribe, List and Delete sit behind imsd's polkit gate, which allows
// interaction: a rule that prompts gets two minutes.
constexpr gint gatedTimeoutMs = 120000;
// Send sits behind the gate too, and has no bound of the client's
// (GDBus: G_MAXINT): imsd waits on a prompt without one and sends the
// text once the prompt lets the call through, so a Send given up on
// here would be failed by Sync and be sent all the same. The call ends
// with imsd's answer, or with the bus's when imsd leaves it.
constexpr gint sendTimeoutMs = G_MAXINT;
}
export namespace ImsdMessages::Bus {
Bus: the GDBus client, imsd's dictionaries, the notifier and the owned name The GLib side of the app. Variant reads imsd's Received dictionary by key and type as its SmsVariant writes it (`to`, the number the text arrived for, a tel: URI read like the status's `ppi`; `operator`, the SIM it arrived under), the GetStatus one with the subscriber's own number and the SIM's operator in it (`ppi`, a tel: URI as the frozen interface gives it; `operator`), and maps a GError to the core's error kinds off GDBus's own mapping. Client is the Sync logic's transport: asynchronous calls with their continuations as user data — every reply guarded where it is delivered (OnCallDone), as are the signal handlers and the name watch's callbacks: a throw is a fault the events hear, not the end of the process — the calls behind imsd's polkit gate allow interaction: Subscribe, List and Delete wait two minutes; Send has no bound of the client's, since imsd sends the text once its prompt lets the call through, however late, and a Send given up on would be failed by Sync and be sent all the same; GetStatus ten seconds — (one call: the Messaging status carries the own number, imsd reading both from one snapshot; AGENTS.md §1 names both interfaces), the Messaging and RegistrationChanged signals, and a watch on net.catcrafts.IMS1 whose appeared callback is where Sync subscribes. Notifier shows one desktop notification per conversation and replaces it as more texts arrive: one Notify at a time per conversation, since the id to replace comes with the answer; its default action asks the app for that conversation; the body is escaped when the server renders markup (GetCapabilities, asked once; Plasma and GNOME do), so a text's '<' or '&' shows as typed. Instance owns net.catcrafts.ImsdMessages and serves org.freedesktop.Application there, the Desktop Entry Specification's interface of a running application: Activate, Open and ActivateAction, each with its platform data — sent empty and not read: nothing in the app can use an activation token yet — and one action, quit, any other refused (the object registered before the name is asked for, so a launch that forwards the moment the name is granted finds it; Own tells a name another instance holds from a request that failed or was refused, and keeps the error's words); it forwards a call to the owner. project.cpp computes the gio flags once for the bus library, the executable and the Decode test. Tested: tests/Decode (every key of imsd's Received dictionary, one with ten of them, GetStatus, the own number, the SIM's operator, the error kinds, the markup escape, the parameters of the instance's three calls).
2026-10-17 23:45:29 +02:00
class ImsdClient : public ImsdTransport {
public:
explicit ImsdClient(GDBusConnection* conn) : conn(conn) {}
~ImsdClient() override { Stop(); }
ImsdClient(const ImsdClient&) = delete;
ImsdClient& operator=(const ImsdClient&) = delete;
// Installs the signal subscriptions and the name watch.
void Start(ImsdEvents& e) {
events = &e;
messagingSub = g_dbus_connection_signal_subscribe(conn, imsdName, messagingIface, nullptr, imsdPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnMessagingSignal, this, nullptr);
baseSub = g_dbus_connection_signal_subscribe(conn, imsdName, imsdIface, "RegistrationChanged", imsdPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnBaseSignal, this, nullptr);
watch = g_bus_watch_name_on_connection(conn, imsdName, G_BUS_NAME_WATCHER_FLAGS_NONE, OnAppeared, OnVanished, this, nullptr);
}
void Stop() {
if (watch) g_bus_unwatch_name(watch);
if (messagingSub) g_dbus_connection_signal_unsubscribe(conn, messagingSub);
if (baseSub) g_dbus_connection_signal_unsubscribe(conn, baseSub);
watch = 0;
messagingSub = 0;
baseSub = 0;
events = nullptr;
}
void Subscribe(Done done) override {
Call("Subscribe", nullptr, nullptr, [done = std::move(done)](GVariant*, GError* err) {
done(err ? std::optional<BusError>(ErrorFrom(err)) : std::nullopt);
});
}
// The Messaging status, the subscriber's own number in it (`ppi`, as
// the frozen interface gives it: imsd reads both from one snapshot,
// so one call never lacks a number it has).
void GetStatus(std::function<void(StatusResult)> done) override {
Call("GetStatus", nullptr, G_VARIANT_TYPE("(a{sv})"), [done = std::move(done)](GVariant* reply, GError* err) {
if (err) {
done(std::unexpected(ErrorFrom(err)));
return;
}
GVariant* dict = g_variant_get_child_value(reply, 0);
Status s = StatusFromVariant(dict);
g_variant_unref(dict);
done(std::move(s));
});
}
void List(std::function<void(ListResult)> done) override {
Call("List", nullptr, G_VARIANT_TYPE("(a(sa{sv}))"), [done = std::move(done)](GVariant* reply, GError* err) {
if (err) {
done(std::unexpected(ErrorFrom(err)));
return;
}
std::vector<ReceivedMessage> out;
GVariant* array = g_variant_get_child_value(reply, 0);
GVariantIter it;
g_variant_iter_init(&it, array);
while (GVariant* item = g_variant_iter_next_value(&it)) {
const gchar* id = nullptr;
GVariant* dict = nullptr;
g_variant_get(item, "(&s@a{sv})", &id, &dict);
out.push_back(ReceivedFromVariant(id ? id : "", dict));
g_variant_unref(dict);
g_variant_unref(item);
}
g_variant_unref(array);
done(std::move(out));
});
}
void Delete(std::string id, Done done) override {
Call("Delete", g_variant_new("(s)", id.c_str()), nullptr, [done = std::move(done)](GVariant*, GError* err) {
done(err ? std::optional<BusError>(ErrorFrom(err)) : std::nullopt);
});
}
void Send(std::string number, std::string text, bool statusReport, std::function<void(SendResult)> done) override {
Call("Send", g_variant_new("(ss@a{sv})", number.c_str(), text.c_str(), SendOptions(statusReport)), G_VARIANT_TYPE("(s)"), [done = std::move(done)](GVariant* reply, GError* err) {
if (err) {
done(std::unexpected(ErrorFrom(err)));
return;
}
const gchar* id = nullptr;
g_variant_get(reply, "(&s)", &id);
done(std::string(id ? id : ""));
});
}
private:
// One pending call's continuation: exactly one of reply and err is
// set; both are freed by OnCallDone after it ran.
using Reply = std::function<void(GVariant* reply, GError* err)>;
struct Pending { // one call's continuation and the client that hears a throw out of it
Reply reply;
ImsdClient* client;
};
// A call on the Messaging interface; the client hears a throw out of
// the reply as a fault (OnCallDone).
void Call(const char* method, GVariant* params, const GVariantType* replyType, Reply reply) {
const std::string_view name = method;
const bool gated = name != "GetStatus";
g_dbus_connection_call(conn, imsdName, imsdPath, messagingIface, method, params, replyType, gated ? G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION : G_DBUS_CALL_FLAGS_NONE, name == "Send" ? sendTimeoutMs : gated ? gatedTimeoutMs : callTimeoutMs, nullptr, OnCallDone, new Pending{ std::move(reply), this });
}
// Every reply passes here, inside GLib's dispatch, which no try
// encloses: a throw out of the continuation (a read, an allocation;
// the store catches its writes) is the events' fault, not the end
// of the process.
static void OnCallDone(GObject* source, GAsyncResult* result, gpointer data) {
std::unique_ptr<Pending> pending(static_cast<Pending*>(data));
GError* err = nullptr;
GVariant* value = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &err);
try {
pending->reply(value, err);
} catch (const std::exception& e) {
if (pending->client->events) pending->client->events->OnFault(e.what());
}
if (value) g_variant_unref(value);
if (err) g_error_free(err);
}
// The signal handlers run inside GLib's dispatch, which no try
// encloses: a throw out of them is handed to the events as a fault
// and the process goes on.
static void OnMessagingSignal(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* signal, GVariant* params, gpointer data) {
ImsdClient& self = *static_cast<ImsdClient*>(data);
if (!self.events) return;
try {
const std::string_view name = signal;
if (name == "Received") {
const gchar* id = nullptr;
GVariant* dict = nullptr;
g_variant_get(params, "(&s@a{sv})", &id, &dict);
const ReceivedMessage m = ReceivedFromVariant(id ? id : "", dict);
g_variant_unref(dict);
self.events->OnReceived(m);
} else if (name == "StateChanged") {
const gchar* id = nullptr;
const gchar* state = nullptr;
const gchar* reason = nullptr;
g_variant_get(params, "(&s&s&s)", &id, &state, &reason);
self.events->OnStateChanged(id ? id : "", state ? state : "", reason ? reason : "");
}
} catch (const std::exception& e) {
self.events->OnFault(e.what());
}
}
static void OnBaseSignal(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar*, GVariant* params, gpointer data) {
ImsdClient& self = *static_cast<ImsdClient*>(data);
if (!self.events) return;
gboolean registered = FALSE;
g_variant_get(params, "(b)", &registered);
try {
self.events->OnRegistrationChanged(registered == TRUE);
} catch (const std::exception& e) {
self.events->OnFault(e.what());
}
}
// The name watch's callbacks, guarded as the replies and the signal
// handlers are.
static void OnAppeared(GDBusConnection*, const gchar*, const gchar*, gpointer data) {
ImsdClient& self = *static_cast<ImsdClient*>(data);
if (!self.events) return;
try {
self.events->OnImsdAppeared();
} catch (const std::exception& e) {
self.events->OnFault(e.what());
}
}
static void OnVanished(GDBusConnection*, const gchar*, gpointer data) {
ImsdClient& self = *static_cast<ImsdClient*>(data);
if (!self.events) return;
try {
self.events->OnImsdVanished();
} catch (const std::exception& e) {
self.events->OnFault(e.what());
}
}
GDBusConnection* conn;
ImsdEvents* events = nullptr;
guint messagingSub = 0;
guint baseSub = 0;
guint watch = 0;
};
}