imsd-messages/interfaces/ImsdMessages-Number.cppm

271 lines
14 KiB
Text
Raw Normal View History

// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
Number: the conversation key of an address An address becomes one conversation key. A number in international form becomes E.164, and one in national form gets the given country code in front — nine digits or more with a leading 0, or eight or more without one, as a plan without a trunk prefix writes its numbers, the latter only while the result is no longer than a number can be; the country code of an E.164 number is found by the ITU length rule; short codes and alphanumeric senders are their own keys. The display form puts a space after the country code. The key groups; a text goes to the address as dialled (DialledNumber: the separators gone, a parenthesised trunk zero after a country code dropped — not after Italy's code or San Marino's, where no zero is a trunk prefix (a landline's is part of its number, a mobile has none): such an address names two numbers and is none — nothing added), since imsd sends a national number or a short code with the type unknown and the network reads it by its own dialling plan — a country code completed for the key would be dialled for real. A national number's leading 0 is taken for the trunk prefix and goes when the country code is added — not under Italy's code or San Marino's, where it is the number's and stays. The key's known limits are of grouping: a number written with its country code and no '+' is completed as a national one, one of a plan whose trunk prefix is not a lone 0 (Hungary's 06, Russia's 8) is completed wrongly, and a national number shorter than those lengths (Iceland's seven digits) stays its digits. Tested: tests/Number, thirty-two normalisation cases (the parenthesised trunk zero of an international number, one after San Marino's code left as no number, a national number's zero kept under Italy's code and San Marino's, the numbers without a trunk prefix and both rules' shortest numbers among them), twelve dialled forms (two with a zero in parentheses after Italy's code, left as typed, among them), the country codes of one-, two- and three-digit countries, the display forms.
2026-10-17 23:25:34 +02:00
/*
ImsdMessages:Number — the conversation key of an address.
imsd hands the app whatever the network sent as the originating address: an
international number ("+31612345678"), occasionally a national one, a short
code ("1234") or an alphanumeric sender ("KPN"); the user types numbers in
every local spelling. One conversation per correspondent needs one key per
correspondent, so a number in international form is normalised to E.164
and one in national form gets the given country code in front — nine
digits or more with a leading 0, or eight or more without one, as a plan
without a trunk prefix writes its numbers, the latter only while the
result is no longer than a number can be; short codes and alphanumeric
senders are their own keys. The key groups; a text goes to the address as dialled
(DialledNumber), nothing added — imsd sends a national number or a short
code with the type unknown and the network reads it by its own dialling
plan. A national number's leading 0 is taken for the trunk prefix and goes
when the country code is added — but under Italy's code and San Marino's, whose
numbers have none: there the 0 is the number's and stays. Known limits, of
the grouping: a number written with its country code and no '+'
("31612345678", the "1" before a North American number) is completed as a
national one; one of a plan whose trunk prefix is not a lone 0 (Hungary's
06, Russia's 8) is completed wrongly; and a national number shorter than
those lengths (Iceland's seven digits) stays its digits.
*/
export module ImsdMessages:Number;
import std;
Number: the conversation key of an address An address becomes one conversation key. A number in international form becomes E.164, and one in national form gets the given country code in front — nine digits or more with a leading 0, or eight or more without one, as a plan without a trunk prefix writes its numbers, the latter only while the result is no longer than a number can be; the country code of an E.164 number is found by the ITU length rule; short codes and alphanumeric senders are their own keys. The display form puts a space after the country code. The key groups; a text goes to the address as dialled (DialledNumber: the separators gone, a parenthesised trunk zero after a country code dropped — not after Italy's code or San Marino's, where no zero is a trunk prefix (a landline's is part of its number, a mobile has none): such an address names two numbers and is none — nothing added), since imsd sends a national number or a short code with the type unknown and the network reads it by its own dialling plan — a country code completed for the key would be dialled for real. A national number's leading 0 is taken for the trunk prefix and goes when the country code is added — not under Italy's code or San Marino's, where it is the number's and stays. The key's known limits are of grouping: a number written with its country code and no '+' is completed as a national one, one of a plan whose trunk prefix is not a lone 0 (Hungary's 06, Russia's 8) is completed wrongly, and a national number shorter than those lengths (Iceland's seven digits) stays its digits. Tested: tests/Number, thirty-two normalisation cases (the parenthesised trunk zero of an international number, one after San Marino's code left as no number, a national number's zero kept under Italy's code and San Marino's, the numbers without a trunk prefix and both rules' shortest numbers among them), twelve dialled forms (two with a zero in parentheses after Italy's code, left as typed, among them), the country codes of one-, two- and three-digit countries, the display forms.
2026-10-17 23:25:34 +02:00
namespace ImsdMessages {
// ITU-T E.164: the one- and two-digit country codes; every other code is
// three digits long.
constexpr std::array<std::string_view, 2> oneDigitCodes = { "1", "7" };
constexpr std::array<std::string_view, 44> twoDigitCodes = {
"20", "27", "30", "31", "32", "33", "34", "36", "39", "40", "41", "43", "44", "45", "46", "47", "48", "49",
"51", "52", "53", "54", "55", "56", "57", "58", "60", "61", "62", "63", "64", "65", "66", "81", "82", "84",
"86", "90", "91", "92", "93", "94", "95", "98",
};
bool AllDigits(std::string_view s) {
return !s.empty() && std::ranges::all_of(s, [](char c) { return c >= '0' && c <= '9'; });
}
// Italy's plan and San Marino's have no trunk zero: a landline's zero is
// part of its number, abroad too, and a mobile number has none.
bool NoTrunkZero(std::string_view countryCode) { return countryCode == "39" || countryCode == "378"; }
std::string_view Trimmed(std::string_view raw) {
while (!raw.empty() && std::isspace(static_cast<std::uint8_t>(raw.front()))) raw.remove_prefix(1);
while (!raw.empty() && std::isspace(static_cast<std::uint8_t>(raw.back()))) raw.remove_suffix(1);
return raw;
}
// The digits of an address, a leading '+' kept: the separators dropped,
// and the trunk zero written in parentheses after a country code —
// "+31 (0)6 12345678", "+44 (0)20 …", "(+44) (0)20 …" — which is not
// dialled. "" for what is not a number: a letter, a '#', a second '+',
// a '+' alone — and that zero after a code without a trunk zero
// (NoTrunkZero): with the zero and without it the address is two
// different numbers, and neither is guessed.
std::string Digits(std::string_view trimmed) {
std::string body(trimmed);
// The international form is read past the separators: a country
// code in parentheses is one too.
const std::size_t lead = body.find_first_not_of(" -./()");
const std::string_view head = lead == std::string::npos ? std::string_view{} : std::string_view(body).substr(lead);
if (head.starts_with('+') || head.starts_with("00")) {
if (const std::size_t at = body.find("(0)"); at != std::string::npos) {
std::string code;
for (const char c : std::string_view(body).substr(0, at)) {
if (c >= '0' && c <= '9') code.push_back(c);
}
if (head.starts_with("00")) code.erase(0, 2);
if (NoTrunkZero(code)) return "";
body.erase(at, 3);
}
}
std::string digits;
for (char c : body) {
if (c == ' ' || c == '-' || c == '.' || c == '(' || c == ')' || c == '/') continue;
if (c == '+' && digits.empty()) {
digits.push_back(c);
continue;
}
if (c < '0' || c > '9') return "";
digits.push_back(c);
}
return digits == "+" ? "" : digits;
}
}
export namespace ImsdMessages {
Number: the conversation key of an address An address becomes one conversation key. A number in international form becomes E.164, and one in national form gets the given country code in front — nine digits or more with a leading 0, or eight or more without one, as a plan without a trunk prefix writes its numbers, the latter only while the result is no longer than a number can be; the country code of an E.164 number is found by the ITU length rule; short codes and alphanumeric senders are their own keys. The display form puts a space after the country code. The key groups; a text goes to the address as dialled (DialledNumber: the separators gone, a parenthesised trunk zero after a country code dropped — not after Italy's code or San Marino's, where no zero is a trunk prefix (a landline's is part of its number, a mobile has none): such an address names two numbers and is none — nothing added), since imsd sends a national number or a short code with the type unknown and the network reads it by its own dialling plan — a country code completed for the key would be dialled for real. A national number's leading 0 is taken for the trunk prefix and goes when the country code is added — not under Italy's code or San Marino's, where it is the number's and stays. The key's known limits are of grouping: a number written with its country code and no '+' is completed as a national one, one of a plan whose trunk prefix is not a lone 0 (Hungary's 06, Russia's 8) is completed wrongly, and a national number shorter than those lengths (Iceland's seven digits) stays its digits. Tested: tests/Number, thirty-two normalisation cases (the parenthesised trunk zero of an international number, one after San Marino's code left as no number, a national number's zero kept under Italy's code and San Marino's, the numbers without a trunk prefix and both rules' shortest numbers among them), twelve dialled forms (two with a zero in parentheses after Italy's code, left as typed, among them), the country codes of one-, two- and three-digit countries, the display forms.
2026-10-17 23:25:34 +02:00
// "+" and 7 to 15 digits.
bool IsE164(std::string_view s) {
return s.size() >= 8 && s.size() <= 16 && s[0] == '+' && AllDigits(s.substr(1));
}
// The country code of an E.164 number by the ITU length rule; "" when
// the string is not one.
std::string CountryCodeOf(std::string_view e164) {
if (!IsE164(e164)) return "";
const std::string_view digits = e164.substr(1);
for (std::string_view code : oneDigitCodes) {
if (digits.starts_with(code)) return std::string(code);
}
for (std::string_view code : twoDigitCodes) {
if (digits.starts_with(code)) return std::string(code);
}
return std::string(digits.substr(0, 3));
}
// The address a text is sent to: as the user typed or a link gave it,
// its separators gone and nothing added. imsd sends a national number
// or a short code as dialled with the type unknown, and the network
// reads it by its own dialling plan; a country code the app completed
// for the key would be dialled for real. What is not a number stays as
// typed, for imsd to judge (it takes digits, '*' and '#').
std::string DialledNumber(std::string_view raw) {
const std::string_view trimmed = Trimmed(raw);
const std::string digits = Digits(trimmed);
return digits.empty() ? std::string(trimmed) : digits;
}
// The conversation key of an address the user typed or the network
// sent — for grouping, never for sending. `defaultCountryCode` ("31")
// completes a national number: nine digits or more whose first is
// the trunk zero, which goes — it stays under a code without one
// (NoTrunkZero), where it is the number's — or eight digits or more
// with no leading zero, as a plan without a trunk prefix writes its
// numbers (a short code is shorter). Empty when none is known, and the
// national number is then its own key.
std::string NormalizeNumber(std::string_view raw, std::string_view defaultCountryCode) {
const std::string_view trimmed = Trimmed(raw);
if (trimmed.empty()) return "";
const std::string cleaned = Digits(trimmed);
// A letter, a '#', a second '+': not a number. The address is the key.
if (cleaned.empty()) return std::string(trimmed);
if (cleaned[0] == '+') return IsE164(cleaned) ? cleaned : std::string(trimmed);
if (cleaned.starts_with("00") && cleaned.size() >= 9 && cleaned.size() <= 17) return std::format("+{}", cleaned.substr(2));
if (cleaned[0] == '0' && cleaned.size() >= 9 && !defaultCountryCode.empty()) return std::format("+{}{}", defaultCountryCode, NoTrunkZero(defaultCountryCode) ? cleaned : cleaned.substr(1));
if (cleaned[0] != '0' && cleaned.size() >= 8 && !defaultCountryCode.empty()) {
// What the code would make longer than a number can be stays as it is.
if (const std::string completed = std::format("+{}{}", defaultCountryCode, cleaned); IsE164(completed)) return completed;
}
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;
};
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
// Whether an address is dialled under another SIM's plan than the one
// it was written under (`then`; `now` is the SIM's as imsd's status
// gives it), where it would reach another subscriber or another
// service. An international address (a leading '+') names its own
// plan. Under the same operator the plan is the same, a side's code
// known or not. Under another operator a number its country's plan
// reads as a subscriber's (NormalizeNumber completes it) means the same
// while both SIMs' own numbers have one country code; anything else —
// a short code, which is the operator's own, or a number where a
// side's code is not known — does not. Without both operators the
// codes decide alone, and nothing is known without both of those.
bool AnotherPlan(std::string_view address, const SimPlan& then, const SimPlan& now) {
if (address.empty() || address[0] == '+') return false;
const bool operators = !then.operatorId.empty() && !now.operatorId.empty();
if (operators && then.operatorId == now.operatorId) return false;
const bool codes = !then.code.empty() && !now.code.empty();
if (codes && then.code != now.code) return true;
if (!operators) return false;
return !codes || !IsE164(NormalizeNumber(address, now.code));
}
main: show the window; --screenshot and --quit-after The executable shows the window at start unless --daemon (which --headless and --send imply), on Activate and Open from a second launch or a notification (of the URIs an Open carries, its first sms: link), and on an sms: link, which opens the conversation of its first recipient at once (Number's SmsUriRecipient: the scheme in any case, the fields after '?' dropped, percent-escapes decoded; then ConversationKey with the country code known at that moment — --country's, else the one imsd's status gave once it is in, else what the number itself carries — which takes NormalizeNumber's result as a phone number — E.164, or digits: a short code, a national number no country code completed — and nothing else), or just the window when it names no phone number; the conversation remembers the address as dialled and the plan of the SIM it was typed under, and that SIM's statuses move its key (Number's AfterStatus, one step, applied in App::Status: another SIM's status — another operator's, or without operators another own number's code, Number's SameSim — changes nothing, so a SIM change leaves the key and the plan the address was typed under; the same SIM's fills in what the plan lacks, and the key follows from its digits to the centre's stand-in and from any key to the own number's code once the plan has it, never from one stand-in's key to another's and not while the code is lost, the conversation it moves to shown at its latest message — and only while nothing is stored under the key: a text stored before the code arrived keeps the conversation on the key its rows carry). The shell forwards Sync's events to the window and the notifier closes a conversation's notification when it is opened (one closed while its Notify is on its way goes when the answer comes). --screenshot renders one frame outside the compositor's pacing 2.5 s after start — 600 ms later where it has to make the window first — and saves it as a PNG before quitting, or ends with exit 1 when no frame was captured — with a line when no window could render it or another instance is running (a flag that acts on the window finds none there: the run forwards nothing), and without one when the run ended before the capture (the display gone, a close that quits); a PNG the library cannot write is not noticed at this commit, and a capture that throws ends the process — the verification path for a machine without eyes, which must not depend on a desktop that repaints — and --quit-after ends a bench on its own clock (a number of seconds its timer can take: anything else is refused); a --send errand ended by anything but its final state — that clock — exits 2, as it does on a signal, its end latched before the loop stops; --screenshot beside --send or --quit is refused, neither having a window. The window is torn down in order before the bus client stops, and when the compositor's connection breaks the process ends, so the next launch starts afresh. A window the library cannot make (no display, no Vulkan driver) is logged by Ui's Show and the start ends with exit 1, as a start without its database does; a resident instance logs it and runs on without one, and a later Activate or Open logs the same at once, the device's set-up running only once. Tested: tests/Number, the sms: links (a query, an escape, a list, the scheme in capitals, no number), the keys of typed addresses, SameSim (the same operator, another operator of one country, a status without its operator, nothing known, own numbers' codes without operators) and AfterStatus through the statuses a typed address meets: the stand-in completing its digits while the plan learns the operator; another stand-in, a lost code and another operator's status — its own number's code the stand-in's or not — changing nothing; rows keeping the key while the plan learns the code; the own number's code moving the stand-in's key, at once or once nothing is stored; a key the own number's code made, and its plan, staying under another SIM and under its own SIM's stand-in; an own code that makes the stand-in's key; a short code; --country before the operator; no operators; no address; an international address, under another SIM and under its own; and the address as dialled making the key the address as typed made.
2026-10-18 00:26:09 +02:00
// An sms: link (RFC 5724), its scheme in any case.
bool IsSmsUri(std::string_view s) {
constexpr std::string_view scheme = "sms:";
return s.size() >= scheme.size() && std::ranges::equal(s.substr(0, scheme.size()), scheme, [](char a, char b) { return std::tolower(static_cast<std::uint8_t>(a)) == b; });
}
// The conversation key of a typed or linked address: NormalizeNumber's
// result when it is a phone number — E.164, or digits: a short code, a
// national number no country code completed — and empty for anything
// else.
std::string ConversationKey(std::string_view address, std::string_view defaultCountryCode) {
const std::string key = NormalizeNumber(address, defaultCountryCode);
return IsE164(key) || AllDigits(key) ? key : "";
}
// The key of a conversation opened with a typed or linked address, and
// the plan of the SIM the address was typed under.
struct TypedKey {
std::string key;
SimPlan plan;
friend bool operator==(const TypedKey&, const TypedKey&) = default;
};
// Whether a status's plan (`now`) can be that of the SIM `typed` is
// from. With its operator the plan tells: the same operator. Without
// one, two own numbers' codes that differ are two SIMs, and nothing
// else is known.
bool SameSim(const SimPlan& typed, const SimPlan& now) {
if (!typed.operatorId.empty()) return typed.operatorId == now.operatorId;
return typed.code.empty() || now.code.empty() || typed.code == now.code;
}
// What imsd's status makes of a typed address's key and plan: `now` is
// the SIM's plan as the status gives it, `code` the code a key is
// completed with meanwhile (the own number's, else the centre's
// stand-in, else none). Another SIM's status changes nothing: the key
// and the plan stay, and the plan is what an address typed under it is
// judged by under another SIM (AnotherPlan). The same SIM's fills in
// what the plan lacks, and while nothing is stored under the key
// (`nothingStored`: rows keep a conversation on the key they carry)
// the key follows: to the own number's code once the plan has it,
// whatever made the key before, and until then from its digits to the
// stand-in's — never from one stand-in's key to another's, and a lost
// code leaves it.
TypedKey AfterStatus(std::string_view dialled, TypedKey typed, const SimPlan& now, std::string_view code, bool nothingStored) {
if (!SameSim(typed.plan, now)) return typed;
if (typed.plan.operatorId.empty()) typed.plan.operatorId = now.operatorId;
if (typed.plan.code.empty()) typed.plan.code = now.code;
if (!nothingStored) return typed;
const std::string_view completing = !typed.plan.code.empty() ? std::string_view(typed.plan.code) : IsE164(typed.key) ? std::string_view() : code;
if (completing.empty()) return typed;
if (std::string key = ConversationKey(dialled, completing); !key.empty()) typed.key = std::move(key);
return typed;
}
// The first recipient of an sms: link, percent-decoded, without the
// fields after '?'; "" when the string is not an sms: link. Its key is
// ConversationKey's, its dialled form DialledNumber's.
std::string SmsUriRecipient(std::string_view uri) {
if (!IsSmsUri(uri)) return "";
std::string_view recipients = uri.substr(4);
if (recipients.starts_with("//")) recipients.remove_prefix(2);
recipients = recipients.substr(0, recipients.find('?'));
recipients = recipients.substr(0, recipients.find(','));
const auto hex = [](char c) -> std::int32_t {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
std::string decoded;
for (std::size_t i = 0; i < recipients.size(); ++i) {
if (recipients[i] == '%' && i + 2 < recipients.size() && hex(recipients[i + 1]) >= 0 && hex(recipients[i + 2]) >= 0) {
decoded.push_back(static_cast<char>(hex(recipients[i + 1]) * 16 + hex(recipients[i + 2])));
i += 2;
} else {
decoded.push_back(recipients[i]);
}
}
return decoded;
}
Number: the conversation key of an address An address becomes one conversation key. A number in international form becomes E.164, and one in national form gets the given country code in front — nine digits or more with a leading 0, or eight or more without one, as a plan without a trunk prefix writes its numbers, the latter only while the result is no longer than a number can be; the country code of an E.164 number is found by the ITU length rule; short codes and alphanumeric senders are their own keys. The display form puts a space after the country code. The key groups; a text goes to the address as dialled (DialledNumber: the separators gone, a parenthesised trunk zero after a country code dropped — not after Italy's code or San Marino's, where no zero is a trunk prefix (a landline's is part of its number, a mobile has none): such an address names two numbers and is none — nothing added), since imsd sends a national number or a short code with the type unknown and the network reads it by its own dialling plan — a country code completed for the key would be dialled for real. A national number's leading 0 is taken for the trunk prefix and goes when the country code is added — not under Italy's code or San Marino's, where it is the number's and stays. The key's known limits are of grouping: a number written with its country code and no '+' is completed as a national one, one of a plan whose trunk prefix is not a lone 0 (Hungary's 06, Russia's 8) is completed wrongly, and a national number shorter than those lengths (Iceland's seven digits) stays its digits. Tested: tests/Number, thirty-two normalisation cases (the parenthesised trunk zero of an international number, one after San Marino's code left as no number, a national number's zero kept under Italy's code and San Marino's, the numbers without a trunk prefix and both rules' shortest numbers among them), twelve dialled forms (two with a zero in parentheses after Italy's code, left as typed, among them), the country codes of one-, two- and three-digit countries, the display forms.
2026-10-17 23:25:34 +02:00
// 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) {
const std::string code = CountryCodeOf(key);
if (code.empty()) return std::string(key);
return std::format("+{} {}", code, key.substr(1 + code.size()));
}
}