diff --git a/interfaces/ImsdMessages-Model.cppm b/interfaces/ImsdMessages-Model.cppm index b90e7e2..b120c98 100644 --- a/interfaces/ImsdMessages-Model.cppm +++ b/interfaces/ImsdMessages-Model.cppm @@ -1,11 +1,209 @@ // SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +/* +ImsdMessages:Model — what a message and a conversation are to the app, and +the app's status as the banner reads it. Plain data and pure functions; the +store persists Message, the bus layer fills ReceivedMessage from imsd's +dictionary, the window draws the rest. +*/ export module ImsdMessages:Model; import std; +import :Number; +import :Time; export namespace ImsdMessages { // The app's version: the one source for --version, the metainfo and the // package. A bump is a commit that changes only this line. inline constexpr std::string_view version = "0.1.0"; + + enum class Direction : std::uint8_t { Incoming, Outgoing }; + + // The life of a message as the UI shows it: a received text is Received; + // one of ours is Pending until imsd's StateChanged says sent or failed, + // or the app fails it, and a status report may move a sent one on to + // delivered, delivery-pending or delivery-failed. + enum class MessageState : std::uint8_t { Received, Pending, Sent, Failed, Delivered, DeliveryPending, DeliveryFailed }; + + // imsd's StateChanged `state` word; nullopt for one this version does + // not know, which the caller logs and ignores. + std::optional StateFromImsd(std::string_view state) { + if (state == "sent") return MessageState::Sent; + if (state == "failed") return MessageState::Failed; + if (state == "delivered") return MessageState::Delivered; + if (state == "delivery-pending") return MessageState::DeliveryPending; + if (state == "delivery-failed") return MessageState::DeliveryFailed; + return std::nullopt; + } + + // The caption under an outgoing bubble. Words, not glyphs: the bundled + // font has no check marks. + std::string_view StateCaption(MessageState state) { + switch (state) { + case MessageState::Received: return ""; + case MessageState::Pending: return "Sending…"; + case MessageState::Sent: return "Sent"; + case MessageState::Failed: return "Failed"; + case MessageState::Delivered: return "Delivered"; + case MessageState::DeliveryPending: return "Delivery pending"; + case MessageState::DeliveryFailed: return "Delivery failed"; + } + return ""; + } + + // A received text as imsd's Received signal and List reply describe it + // (imsd AGENTS.md §8.4), GLib-free. + struct ReceivedMessage { + std::string imsdId; + std::string from; + std::string text; + std::string timestamp; // the service centre's, ISO 8601 with its offset + std::int64_t received = 0; // arrival at imsd, epoch seconds + std::string sc; + std::string to; // the subscriber it arrived for: the registration's own number at receipt, "" when it gave none + std::string simOperator; // the operator of the SIM it arrived under (imsd's `operator`), "" when imsd gave none + std::int32_t smsClass = -1; + std::uint8_t pid = 0; + std::uint8_t dcs = 0; + std::int32_t segments = 1; + bool messageWaiting = false; + std::optional portDst; + std::optional portSrc; + std::vector data; + std::vector pdu; + friend bool operator==(const ReceivedMessage&, const ReceivedMessage&) = default; + }; + + // One message of a conversation as the app stores and shows it. + struct Message { + std::uint64_t id = 0; // the store's row id + std::string conversation; // the key (ImsdMessages:Number) + std::string peer; // the address as the network or the user gave it + SimPlan plan; // the SIM's plan when the row was written (Number's SimPlan): a non-international peer is dialled under that plan alone + Direction direction = Direction::Incoming; + std::string text; + std::int64_t sortTime = 0; // the SC's stamp of a received text (else its arrival); the send time of ours + std::int64_t received = 0; // arrival at imsd, or the send time + MessageState state = MessageState::Received; + std::string stateReason; // the reason of the last state change: imsd's, or why the app failed it + bool read = false; + std::string imsdId; // imsd's: ims-sms-in---, or ims-sms--- once Send answered + std::int32_t segments = 1; + std::int32_t smsClass = -1; + bool messageWaiting = false; + std::optional portDst; + std::optional portSrc; + std::vector data; // 8-bit payload (imsd's `data`), never shown raw + friend bool operator==(const Message&, const Message&) = default; + }; + + // The message of a received text. The conversation key comes from the + // sender's address completed with the code of the number the text + // arrived for (`to`, the subscriber's own number at receipt — the + // record's, since a status read later may be another SIM's) or, + // lacking one, of the service centre that delivered it. The row's plan + // is the own number's code — none when the centre's stood in — and the + // operator of the SIM it arrived under. The sort time is the service + // centre's stamp, else the arrival. + Message MessageFromReceived(const ReceivedMessage& r) { + Message m; + const std::string ownCode = CountryCodeOf(r.to); + const std::string code = !ownCode.empty() ? ownCode : CountryCodeOf(r.sc); + m.conversation = NormalizeNumber(r.from, code); + m.peer = r.from; + m.plan = { ownCode, r.simOperator }; + m.direction = Direction::Incoming; + m.text = r.text; + const std::optional stamp = ParseIso8601(r.timestamp); + m.sortTime = stamp ? stamp->epoch : r.received; + m.received = r.received; + m.state = MessageState::Received; + m.imsdId = r.imsdId; + m.segments = r.segments; + m.smsClass = r.smsClass; + m.messageWaiting = r.messageWaiting; + m.portDst = r.portDst; + m.portSrc = r.portSrc; + m.data = r.data; + return m; + } + + // A short message type 0 (TS 23.040 9.2.3.9, TP-PID 0x40): the phone + // acknowledges it and discards its content, neither stored nor shown. + bool IsType0(const ReceivedMessage& r) { return r.pid == 0x40; } + + struct Conversation { + std::string key; + std::string lastText; + std::int64_t lastTime = 0; + Direction lastDirection = Direction::Incoming; + MessageState lastState = MessageState::Received; + std::uint64_t lastId = 0; + std::uint32_t unread = 0; + std::uint32_t count = 0; + friend bool operator==(const Conversation&, const Conversation&) = default; + }; + + // The conversations of a set of messages, newest first; the last message + // is the latest by sort time, then by id. + std::vector GroupConversations(std::span messages) { + std::unordered_map index; + std::vector out; + for (const Message& m : messages) { + auto [it, inserted] = index.try_emplace(m.conversation, out.size()); + if (inserted) out.push_back({ .key = m.conversation }); + Conversation& c = out[it->second]; + ++c.count; + if (m.direction == Direction::Incoming && !m.read) ++c.unread; + const bool later = m.sortTime > c.lastTime || (m.sortTime == c.lastTime && m.id > c.lastId); + if (c.count == 1 || later) { + c.lastText = m.text; + c.lastTime = m.sortTime; + c.lastDirection = m.direction; + c.lastState = m.state; + c.lastId = m.id; + } + } + std::ranges::sort(out, [](const Conversation& a, const Conversation& b) { + return a.lastTime != b.lastTime ? a.lastTime > b.lastTime : a.lastId > b.lastId; + }); + return out; + } + + // What the app knows about imsd, for the banner and the send button. + struct AppStatus { + bool imsdPresent = false; // net.catcrafts.IMS1 has an owner + bool statusKnown = false; // GetStatus has answered since imsd appeared + bool enabled = false; // GetStatus: SMS over IMS is on + bool registered = false; // GetStatus / RegistrationChanged + bool subscribed = false; // Subscribe succeeded on this connection + bool subscribeDenied = false; // Subscribe was refused by polkit: no live updates + bool subscribeFailed = false; // Subscribe failed otherwise: no live updates until it is tried again + std::string smsc; // GetStatus: the service centre's number + std::string ownNumber; // GetStatus: the subscriber's own number (imsd's ppi), E.164; "" when the network gave none + std::string simOperator; // GetStatus: the SIM's operator (imsd's `operator`: MCC, then MNC); "" when imsd gave none + std::uint32_t undeletable = 0; // messages imsd still holds because Delete was refused + bool storeFailed = false; // the store refused a write (its disk full): texts wait and the banner says so; a send still goes, and a write that gets room clears this + friend bool operator==(const AppStatus&, const AppStatus&) = default; + }; + + // The one line under the header; "" when nothing needs saying. + std::string BannerText(const AppStatus& s) { + if (!s.imsdPresent) return "imsd is not running"; + if (!s.statusKnown) return "Connecting to imsd\u2026"; + if (!s.enabled) return "SMS over IMS is off in imsd (SMS_OVER_IMS=0)"; + if (s.subscribeDenied) return "No live updates: imsd refused this session (polkit)"; + // What blocks sending comes first: the line is a refused send's + // reason too (Sync's Submit). The store's refusal blocks no send; + // it costs texts, which wait for room, before live updates. + if (!s.registered) return "Not registered with the IMS network"; + if (s.storeFailed) return "Cannot save messages (storage full?): texts wait until there is room"; + if (s.subscribeFailed) return "No live updates: imsd did not answer the subscription"; + if (s.undeletable > 0) return std::format("imsd still holds {} message{} this session may not delete", s.undeletable, s.undeletable == 1 ? "" : "s"); + return ""; + } + + bool CanSend(const AppStatus& s) { + return s.imsdPresent && s.statusKnown && s.enabled && s.registered && !s.subscribeDenied; + } } diff --git a/interfaces/ImsdMessages-Number.cppm b/interfaces/ImsdMessages-Number.cppm index d8507d3..8ef91be 100644 --- a/interfaces/ImsdMessages-Number.cppm +++ b/interfaces/ImsdMessages-Number.cppm @@ -146,6 +146,18 @@ export namespace ImsdMessages { return cleaned; } + // A SIM's dialling plan as the app knows it: the country code of its + // own number ("" while that is not known: a service centre's code + // completes a key meanwhile and is never a plan's, since an MVNO's + // centre can be abroad) and its operator (imsd's `operator`: the SIM's + // MCC, then its MNC; "" when imsd gave none), whose short codes are its + // own. + struct SimPlan { + std::string code; + std::string operatorId; + friend bool operator==(const SimPlan&, const SimPlan&) = default; + }; + // The number as the UI shows it: "+31 612345678" for E.164, the key // itself for everything else. std::string DisplayNumber(std::string_view key) { diff --git a/project.cpp b/project.cpp index 2e29ea5..388bcaf 100644 --- a/project.cpp +++ b/project.cpp @@ -136,6 +136,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("Number").Dependencies({ Core.get() }); cfg.AddTest("Time").Dependencies({ Core.get() }); cfg.AddTest("Wrap").Dependencies({ Core.get() }); + cfg.AddTest("Model").Dependencies({ Core.get() }); LintRules::AddRules(cfg); return cfg; diff --git a/tests/Model/main.cpp b/tests/Model/main.cpp new file mode 100644 index 0000000..e3f179b --- /dev/null +++ b/tests/Model/main.cpp @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// The model: imsd's state words, a received text becoming a message, the +// grouping into conversations, and the banner matrix. +import std; +import ImsdMessages; +using namespace ImsdMessages; + +namespace { + +std::int32_t failures = 0; + +void Check(bool ok, std::string_view what) { + std::println("{} {}", ok ? "PASS" : "FAIL", what); + if (!ok) ++failures; +} + +void CheckEqual(std::string_view actual, std::string_view expected, std::string_view what) { + const bool ok = actual == expected; + if (ok) std::println("PASS {}", what); + else std::println("FAIL {} — expected \"{}\", got \"{}\"", what, expected, actual); + if (!ok) ++failures; +} + +} + +Message Make(std::uint64_t id, std::string_view conversation, Direction direction, std::int64_t sortTime, bool read, std::string_view text) { + Message m; + m.id = id; + m.conversation = std::string(conversation); + m.direction = direction; + m.sortTime = sortTime; + m.read = read; + m.text = std::string(text); + m.state = direction == Direction::Incoming ? MessageState::Received : MessageState::Sent; + return m; +} + +int main() { + Check(StateFromImsd("sent") == MessageState::Sent, "sent"); + Check(StateFromImsd("failed") == MessageState::Failed, "failed"); + Check(StateFromImsd("delivered") == MessageState::Delivered, "delivered"); + Check(StateFromImsd("delivery-pending") == MessageState::DeliveryPending, "delivery-pending"); + Check(StateFromImsd("delivery-failed") == MessageState::DeliveryFailed, "delivery-failed"); + Check(!StateFromImsd("lost"), "an unknown state is nullopt"); + CheckEqual(StateCaption(MessageState::Pending), "Sending…", "the pending caption"); + CheckEqual(StateCaption(MessageState::Received), "", "no caption under a received text"); + + constexpr std::int64_t e1 = 1792190500; // 2026-10-17T00:41:40+02:00 + ReceivedMessage r; + r.imsdId = "ims-sms-in-1792192661-1"; + r.from = "+31621308050"; + r.text = "Test"; + r.timestamp = "2026-10-17T00:41:40+02:00"; + r.received = e1 + 37; + r.sc = "+31624000000"; + r.to = "+31687654321"; + r.simOperator = "20408"; + const Message m = MessageFromReceived(r); + CheckEqual(m.conversation, "+31621308050", "the sender is the key"); + CheckEqual(m.peer, "+31621308050", "the peer is the address as sent"); + Check(m.plan == SimPlan{ "31", "20408" }, "the plan is the code of the number it arrived for and the operator of the SIM it arrived under"); + Check(m.direction == Direction::Incoming && m.state == MessageState::Received && !m.read, "a received text is incoming, Received, unread"); + Check(m.sortTime == e1, "the sort time is the service centre's stamp"); + Check(m.received == e1 + 37, "the arrival is kept"); + CheckEqual(m.imsdId, r.imsdId, "imsd's id is kept"); + r.timestamp = "garbage"; + Check(MessageFromReceived(r).sortTime == e1 + 37, "an unparseable stamp falls back to the arrival"); + r.from = "0612345678"; + CheckEqual(MessageFromReceived(r).conversation, "+31612345678", "a national sender is completed with the code of the number it arrived for"); + r.to = "+4915112345678"; + CheckEqual(MessageFromReceived(r).conversation, "+49612345678", "that number's code, whatever the centre's"); + CheckEqual(MessageFromReceived(r).plan.code, "49", "and it is the plan's"); + r.to = ""; + CheckEqual(MessageFromReceived(r).conversation, "+31612345678", "without one, the delivering centre's code stands in"); + Check(MessageFromReceived(r).plan == SimPlan{ "", "20408" }, "for the key alone: the plan has the own number's code or none"); + r.sc = ""; + CheckEqual(MessageFromReceived(r).conversation, "0612345678", "with neither, the digits: grouping only"); + CheckEqual(MessageFromReceived(r).plan.code, "", "and no code in the plan"); + r.simOperator = ""; + Check(MessageFromReceived(r).plan == SimPlan{}, "from an imsd that gave no operator either: no plan"); + r.sc = "+31624000000"; + r.from = "KPN"; + CheckEqual(MessageFromReceived(r).conversation, "KPN", "an alphanumeric sender is its own key"); + Check(!IsType0(r), "an ordinary text is no short message type 0"); + r.pid = 0x40; + Check(IsType0(r), "TP-PID 0x40 is the short message type 0"); + r.pid = 0x41; + Check(!IsType0(r), "a replace type is not"); + + const std::vector messages = { + Make(1, "+31611111111", Direction::Incoming, 100, false, "first"), + Make(2, "+31622222222", Direction::Outgoing, 200, false, "ours"), + Make(3, "+31611111111", Direction::Incoming, 300, true, "read"), + Make(4, "+31611111111", Direction::Incoming, 300, false, "latest"), + }; + const std::vector convs = GroupConversations(messages); + Check(convs.size() == 2, "two conversations"); + Check(convs.size() == 2 && convs[0].key == "+31611111111" && convs[1].key == "+31622222222", "newest conversation first"); + Check(convs.size() == 2 && convs[0].lastText == "latest" && convs[0].lastId == 4 && convs[0].lastTime == 300, "the last message is the latest by time, then id"); + Check(convs.size() == 2 && convs[0].unread == 2 && convs[0].count == 3, "unread counts incoming unread only"); + Check(convs.size() == 2 && convs[1].unread == 0 && convs[1].lastDirection == Direction::Outgoing, "our own message never counts as unread"); + Check(GroupConversations({}).empty(), "no messages, no conversations"); + + AppStatus s; + CheckEqual(BannerText(s), "imsd is not running", "banner: imsd absent"); + s.imsdPresent = true; + CheckEqual(BannerText(s), "Connecting to imsd\u2026", "banner: imsd present, GetStatus not answered yet"); + Check(!CanSend(s), "cannot send before GetStatus answered"); + s.statusKnown = true; + CheckEqual(BannerText(s), "SMS over IMS is off in imsd (SMS_OVER_IMS=0)", "banner: off"); + s.enabled = true; + s.subscribeDenied = true; + CheckEqual(BannerText(s), "No live updates: imsd refused this session (polkit)", "banner: subscribe denied"); + s.subscribeDenied = false; + s.subscribeFailed = true; + CheckEqual(BannerText(s), "Not registered with the IMS network", "banner: unregistered outranks a failed subscription, being what blocks sending"); + AppStatus registeredToo = s; + registeredToo.registered = true; + Check(CanSend(registeredToo), "a failed subscription leaves sending on: imsd answers a Send to its caller"); + CheckEqual(BannerText(registeredToo), "No live updates: imsd did not answer the subscription", "banner: subscribe failed, once registered"); + s.subscribeFailed = false; + CheckEqual(BannerText(s), "Not registered with the IMS network", "banner: unregistered"); + s.registered = true; + s.undeletable = 1; + CheckEqual(BannerText(s), "imsd still holds 1 message this session may not delete", "banner: one undeletable"); + s.undeletable = 3; + CheckEqual(BannerText(s), "imsd still holds 3 messages this session may not delete", "banner: undeletable plural"); + s.undeletable = 0; + CheckEqual(BannerText(s), "", "banner: nothing to say"); + s.storeFailed = true; + CheckEqual(BannerText(s), "Cannot save messages (storage full?): texts wait until there is room", "banner: the store refused a write"); + Check(CanSend(s), "and sending stays on: the send is tried"); + s.registered = false; + CheckEqual(BannerText(s), "Not registered with the IMS network", "banner: what blocks sending outranks the store's refusal, the line being a refused send's reason"); + s.registered = true; + s.subscribeFailed = true; + CheckEqual(BannerText(s), "Cannot save messages (storage full?): texts wait until there is room", "banner: the store's refusal outranks a failed subscription: texts wait"); + s.subscribeFailed = false; + s.storeFailed = false; + Check(CanSend(s), "can send when present, on, registered"); + s.registered = false; + Check(!CanSend(s), "cannot send unregistered"); + + return failures == 0 ? 0 : 1; +}