diff --git a/AGENTS.md b/AGENTS.md index 29ae8f5..bafcece 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,6 +32,7 @@ and §7.9 (Messaging) and §8.1 (the frozen one). | `interfaces/ImsdMessages.Ui*.cppm` | `imsd-messages-ui`: the window on Crafter.Graphics, driven from the GLib main loop. | | `implementations/main.cpp` | The executable `imsd-messages`. | | `tests//main.cpp` | One test per directory, declared in `project.cpp`. | +| `utilities/` | `fake-imsd.py`: imsd's Messaging interface on the session bus, for benches. | | `assets/` | The bundled font (Noto Sans, OFL 1.1). | | `packaging/` | `build-libevdev.sh`: libevdev into a prefix. | diff --git a/implementations/main.cpp b/implementations/main.cpp index 303064a..b2cd358 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -46,7 +46,10 @@ struct Options { std::optional uri; std::optional dataDir; std::optional screenshot; + double screenshotAfter = 2.5; // seconds after start std::optional quitAfter; // seconds + std::optional prefill; // typed into the opened conversation's field + bool sendDraft = false; // and sent, as if the button were tapped std::string country; std::string error; }; @@ -56,7 +59,7 @@ struct Options { // a running instance, whose window is not this one. What configures a // process (its store, its country code) is not among them: beside a // running instance that instance's own stands. -bool WindowFlags(const Options& o) { return o.screenshot.has_value(); } +bool WindowFlags(const Options& o) { return o.screenshot || o.prefill || o.sendDraft; } // A bench clock's seconds, which its timer takes as a guint of // milliseconds: what is not such a number is the error. @@ -83,7 +86,10 @@ Options Parse(std::span args) { i += 2; } else if (a == "--data-dir" && i + 1 < args.size()) o.dataDir = fs::path(args[++i]); else if (a == "--screenshot" && i + 1 < args.size()) o.screenshot = fs::path(args[++i]); + else if (a == "--screenshot-after" && i + 1 < args.size()) o.screenshotAfter = Seconds(a, args[++i], o.error); else if (a == "--quit-after" && i + 1 < args.size()) o.quitAfter = Seconds(a, args[++i], o.error); + else if (a == "--prefill" && i + 1 < args.size()) o.prefill = args[++i]; + else if (a == "--send-draft") o.sendDraft = true; else if (a == "--country" && i + 1 < args.size()) o.country = args[++i]; else if (IsSmsUri(a)) o.uri = std::string(a); else o.error = std::format("unknown argument: {}", a); @@ -95,6 +101,7 @@ Options Parse(std::span args) { const auto utf8 = [](const std::string& s) { return g_utf8_validate(s.data(), static_cast(s.size()), nullptr) != FALSE; }; if (o.send && !(utf8(o.send->first) && utf8(o.send->second))) o.error = "--send: NUMBER and TEXT have to be UTF-8"; if (o.uri && !utf8(*o.uri)) o.error = "the sms: link has to be UTF-8"; + if (o.prefill && !utf8(*o.prefill)) o.error = "--prefill: the text has to be UTF-8"; // A country code as the ITU's length rule reads one (none begins with 0, // and CountryCodeOf gives it back from a number that begins with it): a // completed key is made of it as it is, and read by that rule. @@ -264,7 +271,7 @@ int main(int argc, char** argv) { return 0; } if (o.help) { - std::println("imsd-messages [--daemon|--headless] [--send NUMBER TEXT] [--quit] [--session] [--data-dir DIR] [--country CC] [--screenshot FILE.png] [--quit-after SECONDS] [sms:NUMBER] [--version]"); + std::println("imsd-messages [--daemon|--headless] [--send NUMBER TEXT] [--quit] [--session] [--data-dir DIR] [--country CC] [--screenshot FILE.png] [--screenshot-after SECONDS] [--quit-after SECONDS] [--prefill TEXT] [--send-draft] [sms:NUMBER] [--version]"); return 0; } @@ -381,6 +388,7 @@ int main(int argc, char** argv) { const std::string recipient = SmsUriRecipient(*o.uri); const std::string key = ConversationKey(recipient, sync.CountryCode()); if (!key.empty()) app->Open(key, DialledNumber(recipient)); + if (o.prefill) app->Prefill(*o.prefill); } else if (!o.daemon) { app->Show(); } @@ -394,8 +402,14 @@ int main(int argc, char** argv) { g_main_loop_unref(loop); return 1; } - // The screenshot renders and saves without the compositor, 2.5 s after - // start (600 ms later where the window has to be made first). + // The bench's tap on Send, 1.5 s after start. + if (o.sendDraft) g_timeout_add(1500, [](gpointer data) -> gboolean { + static_cast(data)->SendDraft(); + return G_SOURCE_REMOVE; + }, &*app); + // The screenshot renders and saves without the compositor, + // --screenshot-after seconds after start (600 ms later where the + // window has to be made first). struct ScreenshotJob { Ui::App* app; fs::path path; @@ -403,7 +417,7 @@ int main(int argc, char** argv) { std::optional screenshotJob; if (o.screenshot) { screenshotJob.emplace(&*app, *o.screenshot); - g_timeout_add(2500, [](gpointer data) -> gboolean { + g_timeout_add(static_cast(o.screenshotAfter * 1000), [](gpointer data) -> gboolean { ScreenshotJob& job = *static_cast(data); job.app->ScreenshotThenQuit(job.path); return G_SOURCE_REMOVE; diff --git a/interfaces/ImsdMessages.Ui-App.cppm b/interfaces/ImsdMessages.Ui-App.cppm index 937a29e..8312c98 100644 --- a/interfaces/ImsdMessages.Ui-App.cppm +++ b/interfaces/ImsdMessages.Ui-App.cppm @@ -199,6 +199,13 @@ export namespace ImsdMessages::Ui { Dirty(); } + // Puts text into the open conversation's field (the bench's typing). + void Prefill(std::string_view text) { + if (!view) return; + ComposeInsert(view->compose, text); + Dirty(); + } + // The address a text from the open conversation is sent to (Model's // SendAddress: as the user typed or a link gave it, else the latest // message's, never the key); "" when none is known or it belongs to diff --git a/utilities/fake-imsd.py b/utilities/fake-imsd.py new file mode 100755 index 0000000..e416914 --- /dev/null +++ b/utilities/fake-imsd.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +"""fake-imsd.py — net.catcrafts.IMS1's Messaging interface on the session bus, +with the answers chosen on the command line, for benching imsd-messages +without a phone: a registered daemon that accepts sends, a store to list +and delete, texts injected while the app runs, and the refusals. + + fake-imsd.py [--unregistered] [--disabled] [--deny] [--fail-sends] [--ppi TEL] + [--operator ID] [--inject FROM TEXT [FROM TEXT ...]] + [--inject-after SECONDS] [--subscribe-delay SECONDS] + +Run imsd-messages with --session against it. --deny answers Subscribe, List, +Delete and Send with AccessDenied (polkit's refusal); --fail-sends makes every +Send end in `failed`. Texts given with --inject are stored at start, or +delivered as Received after --inject-after seconds when that is given. +--subscribe-delay answers Subscribe that many seconds late: the app before +imsd's status is in. +""" +import argparse, datetime, random, sys, time +import gi +gi.require_version('Gio', '2.0'); gi.require_version('GLib', '2.0') +from gi.repository import Gio, GLib + +BUS = 'net.catcrafts.IMS1'; PATH = '/net/catcrafts/IMS1'; IFACE = 'net.catcrafts.IMS1.Messaging'; BASE = 'net.catcrafts.IMS1' +XML = f""" + + + + + + + + + + + + + +""" + +def log(*a): print('fake-imsd:', *a, flush=True) + +class Fake: + def __init__(self, args): + self.args = args; self.store = {}; self.subscribers = set(); self.sent = 0; self.n = 0; self.started = int(time.time()); self.run = f'{random.getrandbits(32):08x}'; self.conn = None # the run token, imsd's first id field + def message(self, sender, text, received): + d = {'operator': GLib.Variant('s', self.args.operator)} if self.args.operator else {} # the SIM a text arrived under, as imsd records it + return d | {'from': GLib.Variant('s', sender), 'text': GLib.Variant('s', text), + 'timestamp': GLib.Variant('s', datetime.datetime.fromtimestamp(received).astimezone().isoformat(timespec='seconds')), # imsd's form: ISO 8601 with the offset + 'received': GLib.Variant('x', received), 'sc': GLib.Variant('s', '+31624000000'), 'class': GLib.Variant('i', -1), + 'pid': GLib.Variant('y', 0), 'dcs': GLib.Variant('y', 0), 'segments': GLib.Variant('i', 1), 'message-waiting': GLib.Variant('b', False), + 'pdu': GLib.Variant('ay', b'')} + def inject(self, sender, text): + self.n += 1; now = int(time.time()); mid = f'ims-sms-in-{self.run}-{now}-{self.n}' + self.store[mid] = self.message(sender, text, now) + log('stored', mid, 'from', sender) + for name in list(self.subscribers): + self.conn.emit_signal(name, PATH, IFACE, 'Received', GLib.Variant('(sa{sv})', (mid, self.store[mid]))) + log('Received ->', name, mid) + return False + def status(self): + d = {'enabled': GLib.Variant('b', not self.args.disabled), 'smsc': GLib.Variant('s', '+31653131313'), + 'registered': GLib.Variant('b', not self.args.unregistered), 'subscribers': GLib.Variant('u', len(self.subscribers))} + if self.args.ppi: d['ppi'] = GLib.Variant('s', self.args.ppi) # in both GetStatus answers, as imsd gives it + if self.args.operator: d['operator'] = GLib.Variant('s', self.args.operator) # the Messaging answer's alone + return d + def on_call(self, conn, sender, path, iface, method, params, inv): + gated = method in ('Send', 'Subscribe', 'List', 'Delete') + if gated and self.args.deny: + log(method, 'refused for', sender); inv.return_dbus_error('org.freedesktop.DBus.Error.AccessDenied', f'{sender} is not authorized for net.catcrafts.IMS1.Messaging'); return + if method == 'GetStatus' and iface == BASE: + # the frozen interface's status: the subscriber's own number as a tel: URI (--ppi '' for a network that gives none) + d = {'registered': GLib.Variant('b', not self.args.unregistered)} + if self.args.ppi: d['ppi'] = GLib.Variant('s', self.args.ppi) + inv.return_value(GLib.Variant('(a{sv})', (d,))) + elif method == 'GetStatus': + inv.return_value(GLib.Variant('(a{sv})', (self.status(),))) + elif method == 'Subscribe': + def subscribed(): + self.subscribers.add(sender); log(sender, 'subscribed', f'({len(self.subscribers)})') + Gio.bus_watch_name_on_connection(conn, sender, Gio.BusNameWatcherFlags.NONE, None, lambda c, n: (self.subscribers.discard(n), log(n, 'unsubscribed'))) + inv.return_value(None) + if self.args.subscribe_delay > 0: GLib.timeout_add(int(self.args.subscribe_delay * 1000), subscribed) + else: subscribed() + elif method == 'List': + items = sorted(self.store.items(), key=lambda kv: kv[1]['received'].get_int64()) + inv.return_value(GLib.Variant('(a(sa{sv}))', ([(k, v) for k, v in items],))) + log('List ->', len(items)) + elif method == 'Delete': + mid = params.unpack()[0] + if mid not in self.store: inv.return_dbus_error('org.freedesktop.DBus.Error.FileNotFound', f'no stored message {mid}'); return + del self.store[mid]; log('deleted', mid); inv.return_value(None) + elif method == 'Send': + if self.args.disabled: inv.return_dbus_error('org.freedesktop.DBus.Error.NotSupported', 'SMS over IP is off'); return + number, text, options = params.unpack(); self.sent += 1; mid = f'ims-sms-{self.run}-{self.started}-{self.sent}' # imsd's form: the run token, its start second and a counter + log('Send', mid, 'to', number, repr(text), 'status-report' if options.get('status-report') else '') + inv.return_value(GLib.Variant('(s)', (mid,))) + targets = set(self.subscribers) | {sender} + def state(st, reason): + for name in list(targets): + conn.emit_signal(name, PATH, IFACE, 'StateChanged', GLib.Variant('(sss)', (mid, st, reason))) + log('StateChanged ->', st, reason or ''); return False + if self.args.unregistered: GLib.timeout_add(100, state, 'failed', 'imsd is not registered') + elif self.args.fail_sends: GLib.timeout_add(800, state, 'failed', 'RP-ERROR cause 38 (network out of order)') + else: + GLib.timeout_add(800, state, 'sent', datetime.datetime.now().astimezone().isoformat(timespec='seconds')) # a stamp for imsd's reason ("n segment(s) accepted by the SC at "), which the app logs as it comes + if options.get('status-report'): GLib.timeout_add(2500, state, 'delivered', '') + else: + inv.return_dbus_error('org.freedesktop.DBus.Error.UnknownMethod', 'no such method') + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--unregistered', action='store_true'); ap.add_argument('--disabled', action='store_true') + ap.add_argument('--ppi', default='tel:+31612345678', help="the ppi of both GetStatus answers, the subscriber's own number; '' for none") + ap.add_argument('--operator', default='20408', metavar='ID', help="the SIM's operator in the Messaging GetStatus and in each text: MCC then MNC; '' for none") + ap.add_argument('--deny', action='store_true'); ap.add_argument('--fail-sends', action='store_true') + ap.add_argument('--subscribe-delay', type=float, default=0.0, metavar='SECONDS', help='answer Subscribe this many seconds late: the app before the status is in') + ap.add_argument('--inject', nargs='+', default=[], metavar='FROM TEXT'); ap.add_argument('--inject-after', type=float, default=None) + args = ap.parse_args() + if len(args.inject) % 2: ap.error('--inject takes FROM TEXT pairs') + fake = Fake(args) + info = Gio.DBusNodeInfo.new_for_xml(XML) + def on_bus(conn, name): + fake.conn = conn + for i in info.interfaces: conn.register_object(PATH, i, fake.on_call, None, None) + log('owning', BUS, 'on the session bus') + pairs = list(zip(args.inject[::2], args.inject[1::2])) + if args.inject_after is None: + for s, t in pairs: fake.inject(s, t) + else: + for k, (s, t) in enumerate(pairs): GLib.timeout_add(int(args.inject_after * 1000) + 300 * k, fake.inject, s, t) + Gio.bus_own_name(Gio.BusType.SESSION, BUS, Gio.BusNameOwnerFlags.NONE, on_bus, None, lambda c, n: (log('lost the name', n), sys.exit(1))) + GLib.MainLoop().run() + +if __name__ == '__main__': main()