diff --git a/README.md b/README.md index 22b5b20..d7df1e3 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ ![macOS 14+](https://img.shields.io/badge/macOS-14%2B-lightgrey) ![Universal: Apple Silicon and Intel](https://img.shields.io/badge/arch-universal-lightgrey) ![PJSIP 2.17](https://img.shields.io/badge/PJSIP-2.17-green) -![Release 26.2.0](https://img.shields.io/badge/release-26.2.0-brightgreen) +![Release 26.3.0](https://img.shields.io/badge/release-26.3.0-brightgreen) A MicroSIP-style SIP softphone for macOS on Apple Silicon and Intel. Native Swift and SwiftUI interface, [PJSIP](https://github.com/pjsip/pjproject) 2.17 engine, @@ -19,7 +19,7 @@ presence, quick keys, global hotkeys, English and Russian interface. Guide: https://hsmm.github.io/MacroSIP/wiki/ -Status: `26.2.0` released 2026-11-04. What comes next: [docs/ROADMAP.md](docs/ROADMAP.md). +Status: `26.3.0` released 2026-11-05. What comes next: [docs/ROADMAP.md](docs/ROADMAP.md). ## Screenshots @@ -27,41 +27,48 @@ The app follows the macOS appearance; every picture below switches with it (ligh frames are in [docs/screenshots](docs/screenshots), English and Russian).

- Two calls, one on hold - Contacts with presence - Active call with recording + Two calls, one on hold + Contacts with presence + Active call with recording

- Conference of two participants - Suggestions from Contacts and the directory + Conference of two participants + Suggestions from Contacts and the directory

Account pop-up: pick the outgoing account, switch accounts on and off. Light theme on the left, dark theme on the right:

- Account pop-up, light theme - Account pop-up, dark theme + Account pop-up, light theme + Account pop-up, dark theme

Settings: global hotkeys (Calls) and the Troubleshooting group with Debug mode (General › Advanced):

- Settings, Calls: global hotkeys - Settings, General: Troubleshooting with Debug mode + Settings, Calls: global hotkeys + Settings, General: Troubleshooting with Debug mode

- Settings, Recording + Settings, Recording

Import from MicroSIP with a preview, and the incoming call window with auto-answer: - - + +
Import from MicroSIP, previewIncoming call with the auto-answer countdownImport from MicroSIP, previewIncoming call with the auto-answer countdown
+Messages: the conversation list, and a conversation open: + +

+ Messages tab + Conversation +

+ ## Features **Calls** @@ -73,6 +80,14 @@ Import from MicroSIP with a preview, and the incoming call window with auto-answ - Reject incoming calls from nobody, everyone, numbers not in Contacts, or anonymous callers; Do Not Disturb, also for 30 minutes, 1 hour or until 9:00 tomorrow. - Call log with playback of recordings; `sip:`, `sips:` and `tel:` links open in the app. +**Messages** + +- Send and receive text messages over SIP `MESSAGE` (`text/plain`, UTF-8, Cyrillic included); SMS forwarded by Asterisk `chan_dongle` arrive as ordinary messages. +- A Messages tab with conversations kept between launches; unread counts on the tab and the Dock icon, macOS notifications, and an optional sound (Settings › Audio › Sound events: New message). +- Each outgoing message shows its status: "Sent" means the SIP server or the peer accepted the message, not that a phone received it; "Not sent" shows the SIP reason, with Retry. +- "Send Message" in the Contacts and Call Log menus; up to 2800 bytes per message. +- Not included: group chat, attachments, typing indicators, end-to-end encryption. + **Accounts and network** - Several SIP accounts registered at once; UDP, TCP and TLS with certificate verification; SRTP; STUN and ICE; outgoing-only accounts; each account switched on or off in the account pop-up; search and a status summary when there are many. Passwords are kept in the Keychain. @@ -166,6 +181,7 @@ update; allow it once more. /Applications/MacroSIP.app/Contents/MacOS/MacroSIP --log-level 5 log show --last 10m --predicate 'subsystem == "com.hsmm.macrosip"' --info ``` +- A message shows Sent but the phone did not get it: "Sent" only means the server accepted the message. Delivery to a mobile depends on the server (chan_dongle, the modem, the carrier); check the Asterisk log. Bugs and feature requests: https://github.com/HSMM/MacroSIP/issues diff --git a/README.ru.md b/README.ru.md index fda8997..1c45248 100644 --- a/README.ru.md +++ b/README.ru.md @@ -9,7 +9,7 @@ ![macOS 14+](https://img.shields.io/badge/macOS-14%2B-lightgrey) ![Universal: Apple Silicon and Intel](https://img.shields.io/badge/arch-universal-lightgrey) ![PJSIP 2.17](https://img.shields.io/badge/PJSIP-2.17-green) -![Release 26.2.0](https://img.shields.io/badge/release-26.2.0-brightgreen) +![Release 26.3.0](https://img.shields.io/badge/release-26.3.0-brightgreen) SIP-софтфон для macOS на Apple Silicon и Intel в духе MicroSIP. Нативный интерфейс на Swift и SwiftUI, движок [PJSIP](https://github.com/pjsip/pjproject) 2.17, без @@ -19,7 +19,7 @@ Electron и Qt. Одно небольшое окно, значок в строк Руководство: https://hsmm.github.io/MacroSIP/wiki/ru/index.html -Статус: выпущена версия `26.2.0` (4 ноября 2026). Что дальше: [docs/ROADMAP.md](docs/ROADMAP.md). +Статус: выпущена версия `26.3.0` (5 ноября 2026). Что дальше: [docs/ROADMAP.md](docs/ROADMAP.md). ## Скриншоты @@ -27,41 +27,48 @@ Electron и Qt. Одно небольшое окно, значок в строк тёмные кадры на двух языках лежат в [docs/screenshots](docs/screenshots)).

- Два звонка, один на удержании - Контакты со статусами - Активный звонок с записью + Два звонка, один на удержании + Контакты со статусами + Активный звонок с записью

- Конференция из двух участников - Подсказки из контактов и справочника + Конференция из двух участников + Подсказки из контактов и справочника

Меню аккаунтов: выбор исходящего аккаунта, включение и выключение аккаунтов. Слева светлая тема, справа тёмная:

- Меню аккаунтов, светлая тема - Меню аккаунтов, тёмная тема + Меню аккаунтов, светлая тема + Меню аккаунтов, тёмная тема

Настройки: глобальные горячие клавиши (Звонки) и группа «Устранение неполадок» с режимом отладки (Основные › Дополнительно):

- Настройки, Звонки: глобальные горячие клавиши - Настройки, Основные: устранение неполадок и режим отладки + Настройки, Звонки: глобальные горячие клавиши + Настройки, Основные: устранение неполадок и режим отладки

- Настройки, Запись + Настройки, Запись

Импорт из MicroSIP с предварительным просмотром и окно входящего звонка с автоответом: - - + +
Импорт из MicroSIP, предпросмотрВходящий звонок с обратным отсчётом автоответаИмпорт из MicroSIP, предпросмотрВходящий звонок с обратным отсчётом автоответа
+Сообщения: список переписок и открытая переписка: + +

+ Вкладка «Сообщения» + Переписка +

+ ## Возможности **Звонки** @@ -73,6 +80,14 @@ Electron и Qt. Одно небольшое окно, значок в строк - Отклонение входящих от никого, от всех, от номеров не из контактов или от анонимных абонентов; «Не беспокоить», в том числе на 30 минут, на час или до 9:00 завтра. - Журнал звонков с воспроизведением записей; ссылки `sip:`, `sips:` и `tel:` открываются в приложении. +**Сообщения** + +- Отправка и приём текстовых сообщений по SIP `MESSAGE` (`text/plain`, UTF-8, кириллица включена); SMS, которые пересылает Asterisk через `chan_dongle`, приходят как обычные сообщения. +- Вкладка «Сообщения» с переписками, которые сохраняются между запусками; счётчик непрочитанных на вкладке и на значке в Dock, уведомления macOS и необязательный звук (Настройки › Звук › События звука: «Новое сообщение»). +- У каждого исходящего сообщения виден статус: «Отправлено» означает, что SIP-сервер или собеседник принял сообщение, но не то, что телефон его получил; «Не отправлено» показывает причину SIP и кнопку «Повторить». +- «Написать сообщение» в меню контактов и журнала звонков; до 2800 байт на сообщение. +- Не входит: групповой чат, вложения, индикаторы набора, сквозное шифрование. + **Аккаунты и сеть** - Несколько SIP-аккаунтов с одновременной регистрацией; UDP, TCP и TLS с проверкой сертификата; SRTP; STUN и ICE; аккаунты «только исходящие»; каждый аккаунт включается и выключается в меню аккаунтов; поиск и сводка состояния, когда аккаунтов много. Пароли хранятся в связке ключей. @@ -167,6 +182,7 @@ brew install --cask hsmm/tap/macrosip /Applications/MacroSIP.app/Contents/MacOS/MacroSIP --log-level 5 log show --last 10m --predicate 'subsystem == "com.hsmm.macrosip"' --info ``` +- Сообщение отмечено «Отправлено», но телефон его не получил: «Отправлено» означает только то, что сервер принял сообщение. Доставка на мобильный зависит от сервера (chan_dongle, модема, оператора связи); проверьте журнал Asterisk. Ошибки и пожелания: https://github.com/HSMM/MacroSIP/issues diff --git a/Sources/CPJSUA/include/CPJSUA.h b/Sources/CPJSUA/include/CPJSUA.h index fc48506..15cb4ee 100644 --- a/Sources/CPJSUA/include/CPJSUA.h +++ b/Sources/CPJSUA/include/CPJSUA.h @@ -268,6 +268,30 @@ pj_status_t cpjsua_acc_set_presence(pjsua_acc_id acc_id, int online, * NOTIFY belongs to our own subscription (evsub set), 0 for an unsolicited one. */ int cpjsua_mwi_body(const pjsua_mwi_info *info, char *buf, unsigned size, int *solicited); +/* ------------------------------------------------- text messages (MESSAGE) --- */ + +/** Content-Type of every MESSAGE MacroSIP sends. */ +#define CPJSUA_IM_CONTENT_TYPE "text/plain;charset=utf-8" + +/** Out-of-dialog MESSAGE (pjsua_im_send) from account `acc_id` to the SIP URI `to` with + * `len` bytes of `content` (may contain any bytes) and Content-Type CPJSUA_IM_CONTENT_TYPE + * (pjsua_parse_media_type splits only at '/', so the parameter stays in the subtype and is + * printed as it is). `token` goes into user_data and comes back in on_pager_status2. + * pjsua reports the final answer there (never a provisional one), also for a timeout (408) + * and for a transport or DNS error (503/502 without a response). An error returned here + * either comes before the transaction exists (no callback follows) or after pjsua already + * ran on_pager_status2 for it (pjsip_endpt_send_request terminates the transaction). */ +pj_status_t cpjsua_im_send(pjsua_acc_id acc_id, const char *to, const char *content, + unsigned len, unsigned long long token); + +/** Registers, once per pjsua instance (call after pjsua_init), a module in front of the + * dialog layer that answers an incoming MESSAGE whose body is neither text/plain (any + * parameters) nor application/im-iscomposing+xml with 415 Unsupported Media Type and + * pjsua's Accept (text/plain, application/im-iscomposing+xml), in and outside dialogs. pjsua 2.17 would answer 200 to any body and + * hand it to on_pager2 (pjsua_im_accept_pager accepts everything). A MESSAGE without a body + * passes. */ +pj_status_t cpjsua_im_filter_register(void); + /* ------------------------------------------------- Call-Info answer-after --- */ /** Seconds from an `answer-after=N` parameter in a Call-Info header value: the parameter diff --git a/Sources/CPJSUA/shim.c b/Sources/CPJSUA/shim.c index 4340d09..2ea082d 100644 --- a/Sources/CPJSUA/shim.c +++ b/Sources/CPJSUA/shim.c @@ -894,6 +894,76 @@ int cpjsua_mwi_body(const pjsua_mwi_info *info, char *buf, unsigned size, int *s return (int)len; } +/* ====================================================== text messages === */ + +pj_status_t cpjsua_im_send(pjsua_acc_id acc_id, const char *to, const char *content, + unsigned len, unsigned long long token) +{ + pj_str_t dst, mime, body; + + if (!to || !content || len == 0) + return PJ_EINVAL; + dst = cpjsua_str(to); + mime = cpjsua_str(CPJSUA_IM_CONTENT_TYPE); + body.ptr = (char *)content; + body.slen = (pj_ssize_t)len; + return pjsua_im_send(acc_id, &dst, &mime, &body, NULL, (void *)(pj_size_t)token); +} + +static pj_bool_t im_filter_on_rx_request(pjsip_rx_data *rdata); + +/* Runs before the dialog layer (UA_PROXY_LAYER), so MESSAGEs inside a call are seen too; + * retransmissions of requests that already have a transaction never get here. */ +static pjsip_module im_filter_mod = +{ + NULL, NULL, /* prev, next */ + { "mod-macrosip-im-filter", 22 }, /* name */ + -1, /* id */ + PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1, /* priority */ + NULL, NULL, NULL, NULL, /* load, start, stop, unload */ + &im_filter_on_rx_request, /* on_rx_request */ + NULL, NULL, NULL, NULL, /* on_rx_response, on_tx_request, on_tx_response, on_tsx_state */ +}; + +static pj_bool_t im_filter_on_rx_request(pjsip_rx_data *rdata) +{ + const pjsip_msg *msg = rdata ? rdata->msg_info.msg : NULL; + const pjsip_media_type *ct; + pjsip_hdr hdrs; + pj_status_t status; + + if (!msg || msg->type != PJSIP_REQUEST_MSG || + pj_strcmp2(&msg->line.req.method.name, "MESSAGE") != 0 || !msg->body) + return PJ_FALSE; + ct = &msg->body->content_type; + if ((pj_stricmp2(&ct->type, "text") == 0 && pj_stricmp2(&ct->subtype, "plain") == 0) || + (pj_stricmp2(&ct->type, "application") == 0 && + pj_stricmp2(&ct->subtype, "im-iscomposing+xml") == 0)) + return PJ_FALSE; + + PJ_LOG(4, ("macrosip-im", "MESSAGE with Content-Type %.*s/%.*s answered 415", + (int)ct->type.slen, ct->type.ptr, (int)ct->subtype.slen, ct->subtype.ptr)); + pj_list_init(&hdrs); + pj_list_push_back(&hdrs, pjsua_im_create_accept(rdata->tp_info.pool)); + status = pjsip_endpt_respond_stateless(pjsua_get_pjsip_endpt(), rdata, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE, + NULL, &hdrs, NULL); + if (status != PJ_SUCCESS) + PJ_PERROR(2, ("macrosip-im", status, "Cannot answer MESSAGE with 415")); + /* Handled either way: pjsua must not accept it with 200 (the sender retransmits). */ + return PJ_TRUE; +} + +pj_status_t cpjsua_im_filter_register(void) +{ + pjsip_endpoint *endpt = pjsua_get_pjsip_endpt(); + + if (!endpt) + return PJ_EINVALIDOP; + if (im_filter_mod.id != -1) /* reset by pjsip_endpt_destroy */ + return PJ_SUCCESS; + return pjsip_endpt_register_module(endpt, &im_filter_mod); +} + /* ============================================ Call-Info answer-after === */ static const char *skip_ws(const char *p) diff --git a/Sources/MacroSIPApp/Engine/MockEngine.swift b/Sources/MacroSIPApp/Engine/MockEngine.swift index 7f9e6c7..38c0a6d 100644 --- a/Sources/MacroSIPApp/Engine/MockEngine.swift +++ b/Sources/MacroSIPApp/Engine/MockEngine.swift @@ -4,6 +4,8 @@ import MacroSIPCore /// Simulated engine for UI development and `--mock-engine`. /// Registration: registering, then registered after 1 s. Outgoing call: calling, early, connected after 2 s. /// A password of "wrong" (or a domain containing "fail") makes registration fail with 403. +/// Text messages: accepted after 0.6 s; a To user "404" fails with 404 Not Found, "timeout" with 408 Request Timeout, +/// "offline" with a local failure (code 0). actor MockEngine: SIPEngine { nonisolated let events: AsyncStream private nonisolated let continuation: AsyncStream.Continuation @@ -51,6 +53,9 @@ actor MockEngine: SIPEngine { /// Every `playTestTone` call: the device asked for and the length. private(set) var testTones: [(device: String?, seconds: Double)] = [] private(set) var testTonePlaying = false + /// Every `sendMessage` call, in order (the self-test reads them). + private(set) var sentMessages: [(id: MessageID, text: String, user: String, account: AccountID)] = [] + private var pendingMessages: Set = [] private var testToneTask: Task? init() { @@ -81,6 +86,8 @@ actor MockEngine: SIPEngine { for task in presenceTasks.values { task.cancel() } presenceTasks = [:] for id in accounts.keys { set(id, .unregistered) } + for id in pendingMessages { emit(.messageStatus(id, .failed(code: 0, reason: Engine.messageInterruptedReason))) } + pendingMessages = [] accounts = [:] voicemail = [:] stopTestTone() @@ -283,6 +290,40 @@ actor MockEngine: SIPEngine { func calls() -> [CallInfo] { order.compactMap { callTable[$0] } } + // MARK: text messages + + func sendMessage(_ text: String, to dial: DialString, from account: AccountID, id: MessageID) throws -> MessageID { + guard started else { throw EngineError.notStarted } + guard accounts[account] != nil else { throw EngineError.unknownAccount(account) } + let size = text.utf8.count + guard size > 0 else { throw EngineError.invalidArgument("empty message") } + guard size <= Engine.maxMessageBytes else { + throw EngineError.invalidArgument("message of \(size) bytes (at most \(Engine.maxMessageBytes))") + } + sentMessages.append((id, text, dial.display, account)) + pendingMessages.insert(id) + Task { + try? await Task.sleep(for: .milliseconds(600)) + guard self.pendingMessages.remove(id) != nil else { return } + let result: MessageSendResult + switch dial.display { + case "404": result = .failed(code: 404, reason: "Not Found") + case "timeout": result = .failed(code: 408, reason: "Request Timeout") + case "offline": result = .failed(code: 0, reason: "Network is unreachable") + default: result = .accepted(code: 200) + } + self.emit(.messageStatus(id, result)) + } + return id + } + + /// A text message arrives on `account` (first account when nil) from `from` (a number or user) at `host` (the account's domain when nil). + func simulateIncomingMessage(account: AccountID? = nil, from: String, text: String, name: String? = nil, host: String? = nil) { + guard let acct = account ?? accounts.keys.first else { return } + let remote = RemoteParty(displayName: name, uri: "sip:\(from)@\(host ?? accounts[acct]?.domain ?? "mock.example.org")", number: from) + emit(.messageReceived(IncomingMessage(accountID: acct, remote: remote, text: text, receivedAt: Date()))) + } + // MARK: network func networkState() -> NetworkState { networkStatus } diff --git a/Sources/MacroSIPApp/Engine/SIPEngine.swift b/Sources/MacroSIPApp/Engine/SIPEngine.swift index 6e8b03b..5299139 100644 --- a/Sources/MacroSIPApp/Engine/SIPEngine.swift +++ b/Sources/MacroSIPApp/Engine/SIPEngine.swift @@ -40,6 +40,10 @@ protocol SIPEngine: Actor { /// The gain new calls start with. func setDefaultCallVolume(speaker: Float, microphone: Float) + // text messages (SIP MESSAGE, 26.3). The outcome arrives once as `.messageStatus(id, result)`; the app passes its own + // id so the status matches the stored message however early it comes. Throws when no request could be made. + func sendMessage(_ text: String, to dial: DialString, from account: AccountID, id: MessageID) throws -> MessageID + // conference, recording, presence (milestone 5) func merge(_ ids: [CallID]) throws func split(_ id: CallID) throws diff --git a/Sources/MacroSIPApp/Model/AppModel+Directory.swift b/Sources/MacroSIPApp/Model/AppModel+Directory.swift index 0f2de51..43fc076 100644 --- a/Sources/MacroSIPApp/Model/AppModel+Directory.swift +++ b/Sources/MacroSIPApp/Model/AppModel+Directory.swift @@ -27,6 +27,9 @@ final class DirectoryRuntime { var pending: [DirectorySource] = [] /// Sources asked by the last search, and how many of them answered. var asked = 0 + /// Who the results belong to: the number field, or the To field of a new message (screen 14.3). The other one shows none. + var owner: Owner = .numberField + enum Owner { case numberField, messageTo } /// The user closed the list with Escape; it stays closed until the text changes. var dismissed = false /// The number a click put into the field: it is not searched again. @@ -141,8 +144,9 @@ extension AppModel { /// Called whenever the number field changes. Starts a search after the minimum length and a pause; a /// running search is cancelled. - func textChangedForDirectory(_ text: String) { + func textChangedForDirectory(_ text: String, owner: DirectoryRuntime.Owner = .numberField) { let d = directory + d.owner = owner d.searchTask?.cancel() d.dismissed = false let q = text.trimmingCharacters(in: .whitespacesAndNewlines) @@ -240,7 +244,7 @@ extension AppModel { } /// A SIP display name that says nothing: empty, or just the number. - private func isWeak(_ name: String?, number: String) -> Bool { + func isWeak(_ name: String?, number: String) -> Bool { guard let name = name?.trimmingCharacters(in: .whitespaces), !name.isEmpty else { return true } return Contact.normalize(name) == Contact.normalize(number) && !name.contains(where: \.isLetter) } diff --git a/Sources/MacroSIPApp/Model/AppModel+Engine.swift b/Sources/MacroSIPApp/Model/AppModel+Engine.swift index 26e11a2..21dc4af 100644 --- a/Sources/MacroSIPApp/Model/AppModel+Engine.swift +++ b/Sources/MacroSIPApp/Model/AppModel+Engine.swift @@ -144,6 +144,10 @@ extension AppModel { Task { await devicesChanged() } case let .voicemail(id, waiting, new, old): handleVoicemail(id, waiting: waiting, new: new, old: old) + case let .messageReceived(message): + handleMessageReceived(message) + case let .messageStatus(id, result): + handleMessageStatus(id, result) } } diff --git a/Sources/MacroSIPApp/Model/AppModel+Messages.swift b/Sources/MacroSIPApp/Model/AppModel+Messages.swift new file mode 100644 index 0000000..cdb0f2d --- /dev/null +++ b/Sources/MacroSIPApp/Model/AppModel+Messages.swift @@ -0,0 +1,352 @@ +import SwiftUI +import AppKit +import MacroSIPCore + +/// Text messages (SIP MESSAGE, SCREENS.md section 14): the conversations of the Messages tab, sending and retrying, +/// the engine's `.messageReceived` / `.messageStatus` events, the read state behind the tab and Dock badges, and the +/// notification and sound for a new message. The store is `MessageStore` (messages.json); the engine only carries text. +extension AppModel { + // MARK: - Loading + + /// Reads the conversations (and the open one's messages) back from the store after any change. The store keeps the + /// file in memory, so this does not touch the disk. + func reloadMessages() { + let last = messageStore.lastMessages() + // Newest activity first: by the time of the last message (a retried message moves to the end, and so does the row). + conversations = messageStore.conversations().sorted { + (last[$0.id]?.at ?? $0.lastActivityAt) > (last[$1.id]?.at ?? $1.lastActivityAt) + } + conversationLast = last + if case let .conversation(id) = messagesPage { + if conversations.contains(where: { $0.id == id }) { setThread(messageStore.messages(in: id)) } + else { messagesPage = .list; setThread([]) } + } else if !messageThread.isEmpty { + setThread([]) + } + } + + /// The open conversation's messages and the rows built from them (once per change, not once per redraw). + private func setThread(_ messages: [Message]) { + guard messages != messageThread else { return } + messageThread = messages + threadRows = MessageFormat.thread(messages) + } + + /// Messages of one conversation, oldest first. + func messages(in conversation: UUID) -> [Message] { messageStore.messages(in: conversation) } + + /// Unread incoming messages over all conversations: the tab badge and, with the unseen missed calls, the Dock badge. + var messagesUnread: Int { conversations.reduce(0) { $0 + $1.unread } } + + func conversation(_ id: UUID) -> Conversation? { conversations.first { $0.id == id } } + + /// The conversation with `address` (a number in any format, a URI or `user@host`) on this account: numbers meet by + /// their digits, a host counts where it tells peers apart (`ConversationAddress`). + func conversation(account: AccountID, address: String) -> Conversation? { + let key = ConversationAddress(address, accountDomain: self.account(account)?.domain ?? "") + guard !key.user.isEmpty else { return nil } + return conversations.first { $0.matches(account: account, address: key) } + } + + // MARK: - Names and accounts + + func contact(for conversation: Conversation) -> Contact? { + if let id = conversation.contactID, let c = contacts.first(where: { $0.id == id }) { return c } + return contact(forNumber: conversation.remoteNumber) + } + + /// The contact's name; else the display name of the last incoming message (unless it only repeats the number); + /// else the number. + func name(for conversation: Conversation) -> String { + if let c = contact(for: conversation) { return c.displayName } + if !isWeak(conversation.remoteDisplayName, number: conversation.remoteNumber), let n = conversation.remoteDisplayName { + return n + } + return directoryName(forNumber: conversation.remoteNumber) ?? conversation.shownNumber + } + + /// The account of a conversation is gone, or switched off: nothing can be sent or called through it. + func accountState(of conversation: Conversation) -> MessageAccountState { + guard let a = account(conversation.accountID) else { return .removed } + return a.enabled ? .ready : .off + } + + /// Composer placeholder when the account cannot send (`nil` = the normal one). + func composerPlaceholder(for conversation: Conversation) -> String { + switch accountState(of: conversation) { + case .ready: return L.messagesComposerPlaceholder + case .off: return L.messagesComposerAccountOff(accountName(conversation.accountID)) + case .removed: return L.messagesComposerAccountRemoved + } + } + + // MARK: - Navigation + + /// A conversation or the new-message form is shown: the composer or the To field has the focus, not the number field. + var messageFieldHasFocus: Bool { tab == .messages && messagesPage != .list } + + func showMessagesList() { + messagesPage = .list + setThread([]) + directory.owner = .numberField + clearDirectoryResults() + } + + func openConversation(_ id: UUID, focus: Bool = false) { + guard conversation(id) != nil else { return } + tab = .messages + messagesPage = .conversation(id) + setThread(messageStore.messages(in: id)) + directory.owner = .numberField + updateMessageReadState() + if focus { focusComposer &+= 1 } + } + + /// The form of 14.3. `prefill` is the recipient (the number field's text, or a contact). + func newMessage(to prefill: NewMessagePrefill? = nil) { + tab = .messages + newMessagePrefill = prefill + messagesPage = .new + setThread([]) + } + + /// New Message button: the number field's text goes into To. + func newMessageFromList() { + let typed = dialText.trimmingCharacters(in: .whitespacesAndNewlines) + newMessage(to: typed.isEmpty ? nil : NewMessagePrefill(number: typed, name: nil)) + } + + /// "Send Message" in the Contacts and Call Log menus: the conversation with this number on the outgoing account when + /// it exists, otherwise the new-message form with the recipient filled in. `account` (a call-log entry's account) + /// is used for this message only; the account row's choice for calls stays. + func composeMessage(to number: String, name: String?, account explicit: AccountID? = nil) { + let target = number.trimmingCharacters(in: .whitespacesAndNewlines) + guard !target.isEmpty else { return } + let chosen = explicit.flatMap { self.account($0) }.flatMap { $0.enabled ? $0 : nil } ?? effectiveAccount + guard let acct = chosen else { showBanner(L.bannerNoAccount); return } + let address = DialString.parse(target, account: acct)?.uri ?? target + if let existing = conversation(account: acct.id, address: address) { openConversation(existing.id, focus: true) } + else { newMessage(to: NewMessagePrefill(number: target, name: name, account: explicit.flatMap { $0 == acct.id ? $0 : nil })) } + } + + func sendMessage(to contact: Contact) { + guard let number = contact.defaultNumber?.value else { return } + composeMessage(to: number, name: contact.displayName) + } + + func sendMessage(to entry: CallLogEntry) { + composeMessage(to: entry.remoteNumber, name: contact(for: entry)?.displayName ?? entry.remoteDisplayName, + account: self.account(entry.accountID) != nil ? entry.accountID : nil) + } + + /// A click on a message notification: the window comes forward on the conversation, the cursor in the composer. + func openConversationFromNotification(_ id: UUID) { + showMainWindow() + openConversation(id, focus: true) + } + + // MARK: - Read state + + /// Whether the user can be reading the main window: it is key in the active app, not covered, and the screen is not locked + /// (a demo check can pretend). + var mainWindowIsKey: Bool { + if let o = messagesWindowKeyOverride { return o } + guard NSApp.isActive, !screenLocked, let w = mainWindow else { return false } + return w.isKeyWindow && w.occlusionState.contains(.visible) + } + + /// The conversation shown on the Messages tab in the key main window is read: its count and the badges drop and its + /// notifications go. + func updateMessageReadState() { + guard tab == .messages, case let .conversation(id) = messagesPage, mainWindowIsKey, + (conversation(id)?.unread ?? 0) > 0 else { return } + markMessagesRead(id) + } + + func markMessagesRead(_ id: UUID) { + do { try messageStore.markRead(id) } catch { report(error) } + reloadMessages() + MessageNotifications.shared.remove(conversation: id) + } + + /// The open conversation, when the user could be reading it right now. + func isReading(_ id: UUID) -> Bool { + tab == .messages && messagesPage == .conversation(id) && mainWindowIsKey + } + + // MARK: - Sending + + /// Longest text that can be sent, in UTF-8 bytes (`Engine.maxMessageBytes`). + var messageByteLimit: Int { Engine.maxMessageBytes } + + func canSend(_ text: String) -> Bool { + let t = text.trimmingCharacters(in: .whitespacesAndNewlines) + return !t.isEmpty && t.utf8.count <= messageByteLimit + } + + func isTooLong(_ text: String) -> Bool { + text.trimmingCharacters(in: .whitespacesAndNewlines).utf8.count > messageByteLimit + } + + /// Stores the text as a message in `conversation` and sends it through the conversation's account. + @discardableResult + func send(text: String, in conversationID: UUID) -> Bool { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard canSend(trimmed), let conv = conversation(conversationID), + let acct = account(conv.accountID), acct.enabled else { return false } + let message = Message(conversationID: conv.id, direction: .outgoing, text: trimmed, at: Date(), state: .sending) + do { try messageStore.append(message) } catch { report(error); return false } + messageDrafts[conv.id] = nil + reloadMessages() + transmit(message, in: conv, through: acct) + return true + } + + /// 14.3: the first message of a conversation with `rawAddress` through `account` (the account row's choice when nil). + /// The conversation and the message are stored in one write; an address that already has a conversation sends into it. + @discardableResult + func sendNew(text: String, to rawAddress: String, name: String?, account: AccountID? = nil) -> UUID? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard canSend(trimmed), let acct = account.flatMap({ self.account($0) }) ?? effectiveAccount, acct.enabled, + let dial = DialString.parse(rawAddress, account: acct) else { return nil } + let stored: (Conversation, Message) + do { + stored = try messageStore.conversation(account: acct.id, remoteNumber: dial.display, remoteURI: dial.uri, displayName: name, + accountDomain: acct.domain) { + Message(conversationID: $0, direction: .outgoing, text: trimmed, at: Date(), state: .sending) + } + } catch { report(error); return nil } + reloadMessages() + transmit(stored.1, in: stored.0, through: acct) + return stored.0.id + } + + /// Hands the message to the engine. The status comes back as `.messageStatus` under a fresh id; a request that could + /// not even be made fails here. + private func transmit(_ message: Message, in conv: Conversation, through acct: AccountConfig) { + let target = conv.remoteURI.isEmpty ? conv.remoteNumber : conv.remoteURI + guard let dial = DialString.parse(target, account: acct) else { + finish(message.id, .failed(code: 0, reason: "invalid address")) + return + } + let id = MessageID() + pendingSends[id] = message.id + let text = message.text + Task { @MainActor [weak self] in + guard let self else { return } + do { _ = try await self.engine.sendMessage(text, to: dial, from: acct.id, id: id) } + catch { + if self.pendingSends.removeValue(forKey: id) != nil { self.finish(message.id, .failed(code: 0, reason: describe(error))) } + } + } + } + + /// Retry: the same text through the same account, as a new message at the end of the conversation. + func retry(_ message: Message) { + guard message.state == .failed, let conv = conversation(message.conversationID), + let acct = account(conv.accountID), acct.enabled else { return } + let again = Message(conversationID: conv.id, direction: .outgoing, text: message.text, at: Date(), state: .sending) + do { try messageStore.replace(message: message.id, with: again) } catch { report(error); return } + reloadMessages() + transmit(again, in: conv, through: acct) + } + + /// The final outcome of a send: stored and shown. + func finish(_ message: UUID, _ result: MessageSendResult) { + do { + try messageStore.update(message) { m in + switch result { + case .accepted: + m.state = .sent; m.failureCode = nil; m.failureReason = nil + case let .failed(code, reason): + m.state = .failed; m.failureCode = code; m.failureReason = reason + } + } + } catch { report(error) } + reloadMessages() + } + + func handleMessageStatus(_ id: MessageID, _ result: MessageSendResult) { + guard let message = pendingSends.removeValue(forKey: id) else { return } + finish(message, result) + if case let .failed(code, reason) = result { AppLog.app.info("message not sent: \(code) \(reason)") } + } + + // MARK: - Receiving + + func handleMessageReceived(_ incoming: IncomingMessage) { + guard account(incoming.accountID) != nil else { + AppLog.app.info("message for an unknown account ignored") + return + } + let remote = incoming.remote + let number = remote.number.isEmpty ? remote.uri : remote.number + let displayName = isWeak(remote.displayName, number: number) ? nil : remote.displayName + let conv: Conversation + do { + conv = try messageStore.conversation(account: incoming.accountID, remoteNumber: number, remoteURI: remote.uri, + displayName: displayName, accountDomain: account(incoming.accountID)?.domain ?? "") + try messageStore.append(Message(conversationID: conv.id, direction: .incoming, text: incoming.text, + at: incoming.receivedAt, state: .sent)) + } catch { report(error); return } + reloadMessages() + let reading = isReading(conv.id) + updateMessageReadState() + guard !doNotDisturb else { return } // stored and counted, but silent + playMessageSound() + if !reading, let stored = conversation(conv.id) { + MessageNotifications.shared.post(text: incoming.text, from: name(for: stored), account: accountName(stored.accountID), + conversation: stored.id) + } + } + + /// "New message" sound event: also for the open conversation, at most once every 2 seconds. + func playMessageSound() { + let now = Date() + if let last = lastMessageSoundAt, now.timeIntervalSince(last) < 2 { return } + lastMessageSoundAt = now + playSound(.message) + } + + // MARK: - Deleting + + /// Removes one message; the last one takes the conversation with it (the page goes back to the list). + func deleteMessage(_ id: UUID) { + guard let m = messageThread.first(where: { $0.id == id }) ?? messageStore.allMessages().first(where: { $0.id == id }) else { return } + let conv = m.conversationID + do { + try messageStore.remove(message: id) + if messageStore.messages(in: conv).isEmpty { try messageStore.remove(conversation: conv); forget(conversation: conv) } + } catch { report(error) } + reloadMessages() + } + + func deleteConversation(_ id: UUID) { + do { try messageStore.remove(conversation: id) } catch { report(error) } + forget(conversation: id) + reloadMessages() + } + + private func forget(conversation id: UUID) { + messageDrafts[id] = nil + MessageNotifications.shared.remove(conversation: id) + if messagesPage == .conversation(id) { messagesPage = .list } + } + + // MARK: - Calling from a conversation + + /// Call through the conversation's own account. + func call(_ conversation: Conversation) { + guard accountState(of: conversation) == .ready else { return } + // The URI the peer was last seen at: right for `sip:` users and for hosts other than the account's own. + placeCall(to: conversation.remoteURI.isEmpty ? conversation.remoteNumber : conversation.remoteURI, account: conversation.accountID) + } + + func addToContacts(_ conversation: Conversation) { + ContactCardController.shared.show( + ContactEditorRequest(contact: nil, prefillName: conversation.remoteDisplayName ?? "", prefillNumber: conversation.shownNumber), + model: self) + } +} + +enum MessageAccountState { case ready, off, removed } diff --git a/Sources/MacroSIPApp/Model/AppModel+Sounds.swift b/Sources/MacroSIPApp/Model/AppModel+Sounds.swift index 40f9b7f..1149ae0 100644 --- a/Sources/MacroSIPApp/Model/AppModel+Sounds.swift +++ b/Sources/MacroSIPApp/Model/AppModel+Sounds.swift @@ -51,6 +51,7 @@ extension AppModel { case .keyPress: wanted = s.keyPress case .voicemail: wanted = s.voicemail case .error: wanted = s.error + case .message: wanted = s.message } guard wanted, engineReady else { return } Task { [engine] in diff --git a/Sources/MacroSIPApp/Model/AppModel.swift b/Sources/MacroSIPApp/Model/AppModel.swift index 92253b6..4cfa49c 100644 --- a/Sources/MacroSIPApp/Model/AppModel.swift +++ b/Sources/MacroSIPApp/Model/AppModel.swift @@ -17,6 +17,7 @@ final class AppModel { @ObservationIgnored let contactStore: ContactStore @ObservationIgnored let callLogStore: CallLogStore @ObservationIgnored let settingsStore: SettingsStore + @ObservationIgnored let messageStore: MessageStore @ObservationIgnored let vault: PasswordVault @ObservationIgnored let prefs: UserDefaults @ObservationIgnored var eventTask: Task? @@ -59,6 +60,11 @@ final class AppModel { @ObservationIgnored var microSIPLoad: Task? // reads the files of the Import from MicroSIP sheet @ObservationIgnored var hotkeysInDemo = false // a demo check may register real hotkeys; no other demo does @ObservationIgnored var lastErrorSoundAt: Date? // the `.error` sound plays at most once per 10 s + @ObservationIgnored var lastMessageSoundAt: Date? // the `.message` sound plays at most once per 2 s + @ObservationIgnored var pendingSends: [MessageID: UUID] = [:] // outgoing MESSAGEs waiting for their status -> stored message + @ObservationIgnored var messageDrafts: [UUID: String] = [:] // unsent composer text per conversation (until sent or quit) + @ObservationIgnored var screenLocked = false // the screen is locked: nobody is reading (AppDelegate observes it) + @ObservationIgnored var messagesWindowKeyOverride: Bool? // demo checks: stands in for "the main window is key" // Data var accounts: [AccountConfig] = [] @@ -89,10 +95,17 @@ final class AppModel { var playerEntry: UUID? // the call-log entry whose inline player is open var recordingLinks: [UUID: URL] = [:] // call-log entries whose recording file exists var voicemail: [AccountID: VoicemailState] = [:] // message-summary indicator per account (`.voicemail` events) + var conversations: [Conversation] = [] // newest activity first; change through AppModel+Messages + var conversationLast: [UUID: Message] = [:] // the newest message of every conversation (the list previews) + var threadRows: [MessageFormat.Row] = [] // `MessageFormat.thread(messageThread)`, rebuilt when the thread changes + var messageThread: [Message] = [] // messages of the conversation shown on the Messages tab, oldest first // UI state var banner: Banner? var tab: MainTab = .dialpad + var messagesPage: MessagesPage = .list + var newMessagePrefill: NewMessagePrefill? // read once by the new-message form + var focusComposer = 0 // bumped to put the cursor into the composer (notification click) var dialText = "" var selectedAccountID: AccountID? var showKeypad = false @@ -145,6 +158,7 @@ final class AppModel { accountStore = AccountStore(directory: dir) contactStore = ContactStore(directory: dir) callLogStore = CallLogStore(directory: dir, contacts: contactStore) + messageStore = MessageStore(directory: dir, contacts: contactStore) settingsStore = SettingsStore(directory: dir) isMockEngine = launch.mockEngine let startLevel = LogLevelPolicy.effectiveLevel(launchLevel: launch.logLevel, explicit: launch.logLevelIsExplicit, @@ -152,8 +166,12 @@ final class AppModel { FileLog.shared?.setLevel(startLevel) engine = EngineFactory.make(useMock: launch.mockEngine, logLevel: startLevel) #if DEBUG - if launch.isDemo { DemoState.seed(stores: (accountStore, contactStore, callLogStore, settingsStore), vault: vault) } + if launch.isDemo { + DemoState.seed(stores: (accountStore, contactStore, callLogStore, settingsStore), vault: vault) + DemoState.seedMessages(messageStore, state: launch.demoState ?? "") + } #endif + try? messageStore.failInterruptedSends() // a send whose answer the last run never saw can be retried var loaded = settingsStore.load() // A language this build no longer ships (saved by an earlier build) falls back to the system language. if let language = loaded.general.language, !GeneralSettings.languages.contains(language) { @@ -267,6 +285,7 @@ final class AppModel { .map { AccountID(raw: $0) }.filter { id in list.contains { $0.id == id && MicroSIPImport.needsPassword($0) } }) setContacts(contactStore.all()) callLog = callLogStore.all() + reloadMessages() if let sel = selectedAccountID, account(sel)?.enabled != true { selectedAccountID = nil } } diff --git a/Sources/MacroSIPApp/Model/AppTypes.swift b/Sources/MacroSIPApp/Model/AppTypes.swift index 87e8fd2..6ffb82f 100644 --- a/Sources/MacroSIPApp/Model/AppTypes.swift +++ b/Sources/MacroSIPApp/Model/AppTypes.swift @@ -1,7 +1,24 @@ import Foundation import MacroSIPCore -enum MainTab: Hashable { case dialpad, contacts, callLog } +enum MainTab: Hashable { case dialpad, contacts, callLog, messages } + +/// What the Messages tab shows (SCREENS.md 14): the list, one conversation, or the new-message form. +/// The tab remembers it while another tab is shown. +enum MessagesPage: Equatable { + case list + case conversation(UUID) + case new +} + +/// What "New Message" starts with: an address typed in the number field, or a recipient picked from Contacts. +struct NewMessagePrefill: Equatable { + var number = "" + var name: String? + /// The account the message goes through instead of the account row's choice (from a call-log entry); the account + /// row, once the user changes it, wins again. + var account: AccountID? +} enum SettingsTab: String, Hashable, CaseIterable { case general, accounts, audio, network, codecs, recording, calls, quickKeys, directory } diff --git a/Sources/MacroSIPApp/Model/DemoState+Messages.swift b/Sources/MacroSIPApp/Model/DemoState+Messages.swift new file mode 100644 index 0000000..3dee6c4 --- /dev/null +++ b/Sources/MacroSIPApp/Model/DemoState+Messages.swift @@ -0,0 +1,436 @@ +import Foundation +import MacroSIPCore +#if DEBUG +import AppKit + +/// Demo states of screen 14 (Messages): +/// messages the conversation list: two unread, one not sent (README `messages-list`) +/// messages-conversation Andrei Kavaliou, the last message "Sent", a reply typed (README `messages-conversation`) +/// messages-failed Volha Marozava: the last message failed with 404 Not Found, Retry +/// messages-new the new-message form with "Ka" in To: and the suggestion list (contacts, then the directory) +/// messages-empty no conversations +/// messages-many 120 unread messages and 120 missed calls: both tab badges at their widest (Russian labels still fit) +/// messages-selftest only the message checks of `selftest` (send, receive, retry, unread, notifications, sound) +extension DemoState { + static func isMessagesState(_ state: String) -> Bool { state.hasPrefix("messages") } + + /// The six conversations of the mockup (14.1), oldest activity first because a new conversation starts "now". + static func seedMessages(_ store: MessageStore, state: String) { + guard state == "selftest" || (isMessagesState(state) && state != "messages-empty" && state != "messages-many") else { return } + let cal = Calendar.current + let now = Date() + let startOfToday = cal.startOfDay(for: now) + /// A time today, `minutes` ago (not before 00:01). + func ago(_ minutes: Double) -> Date { max(now.addingTimeInterval(-minutes * 60), startOfToday.addingTimeInterval(60)) } + func day(_ offset: Int, _ hour: Int, _ minute: Int) -> Date { + let d = cal.date(byAdding: .day, value: offset, to: startOfToday) ?? startOfToday + return cal.date(bySettingHour: hour, minute: minute, second: 0, of: d) ?? d + } + func conversation(_ account: AccountID, _ number: String, uri: String, name: String? = nil) -> Conversation? { + try? store.conversation(account: account, remoteNumber: number, remoteURI: uri, displayName: name) + } + func add(_ c: Conversation?, _ direction: MessageDirection, _ text: String, _ at: Date, + failed: (Int, String)? = nil, read: Bool = true) { + guard let c else { return } + var m = Message(conversationID: c.id, direction: direction, text: text, at: at, state: .sent) + if let failed { m.state = .failed; m.failureCode = failed.0; m.failureReason = failed.1 } + _ = try? store.append(m) + if read, direction == .incoming { try? store.markRead(c.id) } + } + let ru = Locale.preferredLanguages.first?.hasPrefix("ru") == true + func pick(_ latin: String, _ cyrillic: String) -> String { ru ? cyrillic : latin } + + let katsiaryna = conversation(officeID, "elena", uri: "sip:elena@pbx.example.com") + add(katsiaryna, .incoming, pick("Room 4 is free on Thursday.", "Переговорная 4 свободна в четверг."), day(-30, 10, 12)) + let dzmitry = conversation(homeID, "+79125550123", uri: "sip:+79125550123@sip.provider.net") + add(dzmitry, .outgoing, pick("Sent you the invoice.", "Отправил вам счёт."), day(-3, 16, 5)) + add(dzmitry, .incoming, pick("Thanks, the invoice is paid.", "Спасибо, счёт оплачен."), day(-3, 16, 20)) + let volha = conversation(officeID, "+375 44 555-77-10", uri: "sip:+375445557710@pbx.example.com", name: DemoPeople.volha) + add(volha, .incoming, pick("Are we still meeting tomorrow?", "Мы завтра встречаемся?"), day(-1, 18, 2)) + add(volha, .outgoing, pick("Yes.", "Да."), day(-1, 18, 4)) + add(volha, .outgoing, pick("See you at 10 at the entrance.", "Встречаемся в 10 у входа."), day(-1, 18, 8), failed: (404, "Not Found")) + let andrei = conversation(officeID, "101", uri: "sip:101@pbx.example.com") + add(andrei, .incoming, pick("Did you get the contract?", "Ты получил договор?"), day(-1, 17, 30)) + add(andrei, .outgoing, pick("Not yet. I'll check in the morning.", "Пока нет. Утром проверю."), day(-1, 17, 32)) + add(andrei, .incoming, pick("It's in the shared folder now.", "Он уже в общей папке."), ago(190)) + add(andrei, .outgoing, pick("Got it, thanks!", "Получил, спасибо!"), ago(180)) + let parcel = conversation(homeID, "+375 29 123-45-67", uri: "sip:+375291234567@sip.provider.net") + add(parcel, .incoming, pick("Parcel 2214 is ready for pickup until 12 Nov.", "Посылка 2214 ждёт вас в пункте выдачи до 12 ноября."), + ago(100), read: false) + let alesia = conversation(officeID, "+375295550142", uri: "sip:+375295550142@pbx.example.com") + add(alesia, .incoming, pick("Can you call me after the meeting?", "Перезвони, пожалуйста, после совещания."), ago(12), read: false) + } + + @MainActor + static func runMessages(_ model: AppModel, state: String) async { + try? await Task.sleep(for: .seconds(1.2)) + if state != "messages-selftest", state != "messages-many" { model.markLogSeen() } // the Call Log badge is not part of these frames + func open(_ name: String) { + guard let c = model.conversations.first(where: { model.name(for: $0) == name }) else { return } + model.openConversation(c.id) + } + switch state { + case "messages", "messages-empty": + model.tab = .messages + case "messages-conversation": + model.tab = .messages + if let c = model.conversations.first(where: { model.name(for: $0) == DemoPeople.andrei }) { + model.messageDrafts[c.id] = Locale.preferredLanguages.first?.hasPrefix("ru") == true + ? "Отправлю замечания к трём" : "I'll send my comments by 3" + model.openConversation(c.id) + } + case "messages-failed": + model.tab = .messages + open(DemoPeople.volha) + case "messages-new": + let ru = Locale.preferredLanguages.first?.hasPrefix("ru") == true + model.newMessage(to: NewMessagePrefill(number: ru ? "Ка" : "Ka", name: nil)) + try? await Task.sleep(for: .seconds(Double(MockDirectory.googleDelayMilliseconds) / 1000 + 1)) + case "messages-many": + for i in 0..<120 { + let incoming = IncomingMessage(accountID: officeID, remote: RemoteParty(displayName: nil, uri: "sip:777@pbx", number: "777"), + text: "#\(i)", receivedAt: Date()) + model.handleMessageReceived(incoming) + } + for i in 0..<120 { + _ = try? model.callLogStore.append(CallLogEntry(direction: .missed, remoteNumber: "100", remoteDisplayName: nil, accountID: officeID, + startedAt: Date().addingTimeInterval(-Double(i) - 1), duration: 0)) + } + model.reloadCallLog() + model.tab = .messages + case "messages-selftest": + await runMessagesSelftest(model) + default: break + } + } + + @MainActor + static func runMessagesSelftest(_ model: AppModel) async { + var out: [String] = [] + var failures = 0 + await messagesChecks(model) { name, ok, detail in + if !ok { failures += 1 } + out.append("\(ok ? "PASS" : "FAIL") \(name) \(ok ? "" : detail)") + } + let text = out.joined(separator: "\n") + "\nfailures=\(failures)\n" + if let prefix = model.launch.snapshotPrefix { try? text.write(toFile: "\(prefix)-selftest.txt", atomically: true, encoding: .utf8) } + print(text) + quitLater() + } + + /// Sending, receiving, retrying, the read state behind the badges, notifications and the sound, through the mock engine. + @MainActor + static func messagesChecks(_ model: AppModel, report: (String, Bool, String) -> Void) async { + func check(_ name: String, _ ok: Bool, _ detail: @autoclosure () -> String = "") { report("messages: " + name, ok, ok ? "" : detail()) } + func wait(_ s: Double) async { try? await Task.sleep(for: .seconds(s)) } + func until(_ seconds: Double, _ condition: () -> Bool) async { + let end = Date().addingTimeInterval(seconds) + while !condition(), Date() < end { try? await Task.sleep(for: .milliseconds(50)) } + } + guard let mock = model.engine as? MockEngine else { check("mock engine", false); return } + let notifications = MessageNotifications.shared + let savedSound = model.settings.audio.soundEvents + let savedDND = model.settings.general.doNotDisturb + + // The seeded list + await until(3) { model.engineReady && model.registration[officeID] != nil } + model.messagesWindowKeyOverride = false + model.selectedAccountID = nil + model.tab = .messages + model.showMessagesList() + model.updateSettings { $0.general.doNotDisturb = false; $0.audio.soundEvents.message = false } + check("message sound is off by default", !AppSettings().audio.soundEvents.message) + check("six conversations, newest activity first", + model.conversations.count == 6 && model.name(for: model.conversations[0]) == DemoPeople.alesia, + model.conversations.map { model.name(for: $0) }.joined(separator: ", ")) + check("two unread messages in the badge", model.messagesUnread == 2, "\(model.messagesUnread)") + let number = model.conversations.first { $0.remoteNumber == "+375 29 123-45-67" } + check("a number without a contact is named by its number", number.map { model.name(for: $0) } == "+375 29 123-45-67") + let andrei = model.conversations.first { model.name(for: $0) == DemoPeople.andrei } + check("a conversation with a contact number shows the contact", andrei.map { model.contact(for: $0) != nil } == true) + let volha = model.conversations.first { model.name(for: $0) == DemoPeople.volha } + check("a stranger with a display name shows it, and the last message is not sent", + volha != nil && volha.flatMap { model.conversationLast[$0.id] }?.state == .failed) + check("the previews are the last message of each conversation", + andrei.flatMap { model.conversationLast[$0.id] }.map(MessageFormat.preview) == L.messagesRowYou(model.conversationLast[andrei!.id]!.text)) + + // Receiving: unread, notification, sound, Do Not Disturb + notifications.clearPosted() + await mock.clearPlayedSounds() + await mock.simulateIncomingMessage(account: officeID, from: "101", text: "Call me") + await until(2) { (andrei.flatMap { model.conversation($0.id) }?.unread ?? 0) == 1 } + check("an incoming message counts as unread", andrei.flatMap { model.conversation($0.id) }?.unread == 1 && model.messagesUnread == 3, + "\(model.messagesUnread)") + check("the conversation moves to the top", model.conversations.first?.id == andrei?.id) + check("one notification: sender, account, text, conversation", + notifications.posted.count == 1 && notifications.posted[0] == .init( + conversation: andrei?.id ?? UUID(), title: DemoPeople.andrei, subtitle: "Office", body: "Call me"), + "\(notifications.posted)") + check("no sound while the setting is off", await mock.playedSounds.isEmpty) + model.updateSettings { $0.audio.soundEvents.message = true } + model.lastMessageSoundAt = nil + await mock.simulateIncomingMessage(account: officeID, from: "101", text: "Hello?") + await until(2) { model.messagesUnread == 4 } + await wait(0.3) + var sounds = await mock.playedSounds + check("the message sound plays once the setting is on", sounds == [.message], "\(sounds)") + await mock.simulateIncomingMessage(account: officeID, from: "101", text: "Hello??") + await until(2) { model.messagesUnread == 5 } + await wait(0.3) + sounds = await mock.playedSounds + check("the sound plays at most once every 2 seconds", sounds.count == 1, "\(sounds)") + model.updateSettings { $0.general.doNotDisturb = true } + notifications.clearPosted() + model.lastMessageSoundAt = nil + await mock.clearPlayedSounds() + await mock.simulateIncomingMessage(account: officeID, from: "101", text: "Quiet one") + await until(2) { model.messagesUnread == 6 } + await wait(0.3) + sounds = await mock.playedSounds + check("Do Not Disturb: stored and counted, no notification, no sound", + model.messagesUnread == 6 && notifications.posted.isEmpty && sounds.isEmpty, "\(model.messagesUnread) \(notifications.posted.count) \(sounds)") + model.updateSettings { $0.general.doNotDisturb = false } + + // The read state + if let andrei { + model.openConversation(andrei.id) + check("a conversation shown while the window is not key stays unread", model.conversation(andrei.id)?.unread == 4) + model.messagesWindowKeyOverride = true + model.updateMessageReadState() + check("it is read when the window becomes key", model.conversation(andrei.id)?.unread == 0 && model.messagesUnread == 2, "\(model.messagesUnread)") + notifications.clearPosted() + model.lastMessageSoundAt = nil + await mock.clearPlayedSounds() + await mock.simulateIncomingMessage(account: officeID, from: "101", text: "Are you there?") + await until(2) { model.messageThread.last?.text == "Are you there?" } + await wait(0.3) + sounds = await mock.playedSounds + check("a message for the open conversation is read at once: no notification, the sound still plays", + model.conversation(andrei.id)?.unread == 0 && notifications.posted.isEmpty && sounds == [.message], + "\(String(describing: model.conversation(andrei.id)?.unread)) \(notifications.posted.count) \(sounds)") + check("the open thread shows it last", model.messageThread.last?.text == "Are you there?" && model.messageThread.last?.direction == .incoming) + model.messagesWindowKeyOverride = false + await mock.simulateIncomingMessage(account: officeID, from: "101", text: "Hello again") + await until(2) { model.conversation(andrei.id)?.unread == 1 } + check("a message for the open conversation in a window that is not key stays unread and is notified", + model.conversation(andrei.id)?.unread == 1 && notifications.posted.count == 1) + model.tab = .callLog + model.messagesWindowKeyOverride = true + model.updateMessageReadState() + check("another tab does not read the conversation", model.conversation(andrei.id)?.unread == 1) + model.tab = .messages + model.updateMessageReadState() + check("back on the Messages tab it is read", model.conversation(andrei.id)?.unread == 0) + check("the page is remembered across tabs", model.messagesPage == .conversation(andrei.id)) + } + model.messagesWindowKeyOverride = false + model.showMessagesList() + model.markMessagesRead(model.conversations.first { $0.unread > 0 }?.id ?? UUID()) + + // Sending + if let andrei { + model.openConversation(andrei.id) + let before = model.messageThread.count + check("an empty text is not sent", !model.send(text: " \n ", in: andrei.id) && model.messageThread.count == before) + let tooLong = String(repeating: "é", count: model.messageByteLimit / 2 + 1) + check("over the byte limit is refused", model.isTooLong(tooLong) && !model.canSend(tooLong) && !model.send(text: tooLong, in: andrei.id)) + check("the limit is the engine's", model.messageByteLimit == Engine.maxMessageBytes && model.canSend(String(repeating: "é", count: model.messageByteLimit / 2))) + check("a text is sent trimmed", model.send(text: " On my way \n", in: andrei.id)) + check("the message shows Sending… at once", model.messageThread.last?.text == "On my way" && model.messageThread.last?.state == .sending) + await until(2) { model.messageThread.last?.state == .sent } + check("accepted by the engine: Sent", model.messageThread.last?.state == .sent) + let sent = await mock.sentMessages.last + check("the engine got the text for the conversation's account", sent?.text == "On my way" && sent?.user == "101" && sent?.account == officeID, "\(String(describing: sent))") + let rows = MessageFormat.thread(model.messageThread) + check("Sent only under the last outgoing message", rows.filter(\.showsSent).count == 1 && rows.last?.showsSent == true) + } + + // Failures and Retry + model.selectedAccountID = officeID + func failure(_ to: String) async -> Message? { + guard let id = model.sendNew(text: "to \(to)", to: to, name: nil) else { return nil } + await until(3) { model.messages(in: id).last?.state == .failed } + return model.messages(in: id).last + } + let notFound = await failure("404") + check("404: Not sent · 404 Not Found", notFound.map { MessageFormat.failure($0).reason } == "404 Not Found", "\(String(describing: notFound))") + let timedOut = await failure("timeout@pbx.example.com") + check("no answer: 408 Request Timeout", timedOut.map { MessageFormat.failure($0).reason } == "408 Request Timeout") + let local = await failure("offline@pbx.example.com") + check("a local failure: No connection, the engine's text is the tooltip", + local.map { MessageFormat.failure($0) }.map { $0.reason == L.messagesErrorLocal && $0.tooltip == "Network is unreachable" } == true) + if let notFound { + let conv = notFound.conversationID + model.openConversation(conv) + model.retry(notFound) + check("Retry: the same text, sending again, at the end, one message", model.messageThread.count == 1 && model.messageThread[0].state == .sending + && model.messageThread[0].text == notFound.text && model.messageThread[0].id != notFound.id) + await until(3) { model.messageThread.last?.state == .failed } + check("Retry fails again the same way", model.messageThread.last.map { MessageFormat.failure($0).reason } == "404 Not Found") + model.deleteMessage(model.messageThread[0].id) + check("deleting the last message removes the conversation and returns to the list", + model.conversation(conv) == nil && model.messagesPage == .list) + } + if let timedOut { + model.deleteConversation(timedOut.conversationID) + check("Delete Conversation removes it and its messages", model.conversation(timedOut.conversationID) == nil + && model.messages(in: timedOut.conversationID).isEmpty) + } + if let local { model.deleteConversation(local.conversationID) } + + // Interrupted sends, status of unknown messages, accounts + if let andrei { + let stuck = Message(conversationID: andrei.id, direction: .outgoing, text: "stuck", at: Date(), state: .sending) + _ = try? model.messageStore.append(stuck) + try? model.messageStore.failInterruptedSends() + model.reloadMessages() + let after = model.messages(in: andrei.id).first { $0.id == stuck.id } + check("a send still waiting at launch becomes Not sent · Interrupted", + after.map { MessageFormat.failure($0).reason } == L.messagesErrorInterrupted && after?.state == .failed) + let count = model.messages(in: andrei.id).count + model.handleMessageStatus(MessageID(), .accepted(code: 200)) + check("a status nobody waits for changes nothing", model.messages(in: andrei.id).count == count) + try? model.messageStore.remove(message: stuck.id) + model.reloadMessages() + } + let ghost = try? model.messageStore.conversation(account: AccountID(), remoteNumber: "777", remoteURI: "sip:777@gone.example.org", displayName: nil) + model.reloadMessages() + check("a conversation whose account was removed cannot send or call", ghost.map { model.accountState(of: $0) == .removed } == true + && ghost.map { !model.send(text: "x", in: $0.id) } == true + && ghost.map { model.composerPlaceholder(for: $0) == L.messagesComposerAccountRemoved } == true) + if let ghost { model.deleteConversation(ghost.id) } + if let andrei { + model.setAccountEnabled(officeID, false) + await model.waitForAccountSync() + check("a switched-off account disables the composer and Call", model.accountState(of: andrei) == .off + && model.composerPlaceholder(for: andrei) == L.messagesComposerAccountOff("Office") && !model.send(text: "x", in: andrei.id)) + model.setAccountEnabled(officeID, true) + await model.waitForAccountSync() + } + + // Entry points + if let andrei { + model.showMessagesList() + model.selectedAccountID = officeID + model.composeMessage(to: "101", name: DemoPeople.andrei) + check("Send Message opens the existing conversation", model.messagesPage == .conversation(andrei.id) && model.tab == .messages) + model.composeMessage(to: "888", name: "Nobody") + check("Send Message without a conversation opens the form with the recipient", + model.messagesPage == .new && model.newMessagePrefill == NewMessagePrefill(number: "888", name: "Nobody")) + model.newMessagePrefill = nil + model.dialText = "555" + model.newMessageFromList() + check("New Message copies the number field", model.newMessagePrefill == NewMessagePrefill(number: "555", name: nil)) + model.newMessagePrefill = nil + model.dialText = "" + } + model.showMessagesList() + check("an address matches a conversation of the same number and account", + model.conversation(account: officeID, address: "+375 (29) 555-01-42") != nil && model.conversation(account: homeID, address: "101") == nil) + + // Peers: formats, hosts, the unread count, the account of a message, the call target + model.messagesWindowKeyOverride = false + notifications.clearPosted() + let alesiaConv = model.conversation(account: officeID, address: "+375295550142") + let before = model.conversations.count + let unreadBefore = alesiaConv?.unread ?? 0 + await mock.simulateIncomingMessage(account: officeID, from: "375295550142", text: "no plus", host: "pbx.example.com") + await until(2) { (alesiaConv.flatMap { model.conversation($0.id) }?.unread ?? 0) == unreadBefore + 1 } + check("the same number without its plus joins the existing conversation", + model.conversations.count == before && alesiaConv.flatMap { model.conversation($0.id) }?.unread == unreadBefore + 1, + "\(before) -> \(model.conversations.count)") + await mock.simulateIncomingMessage(account: officeID, from: "alice", text: "from a", host: "a.example.com") + await mock.simulateIncomingMessage(account: officeID, from: "alice", text: "from b", host: "b.example.com") + await mock.simulateIncomingMessage(account: officeID, from: "alice", text: "from a again", host: "A.example.com") + await until(2) { model.conversations.count == before + 2 } + await wait(0.5) + let aliceA = model.conversation(account: officeID, address: "sip:alice@a.example.com") + let aliceB = model.conversation(account: officeID, address: "sip:alice@b.example.com") + check("one user at two hosts is two conversations, a host in another case is the first", + aliceA != nil && aliceB != nil && aliceA?.id != aliceB?.id && aliceA.map { model.messages(in: $0.id).count } == 2 + && aliceB.map { model.messages(in: $0.id).count } == 1, "\(model.conversations.count)") + check("the host is shown with the user", aliceA?.shownNumber == "alice@a.example.com") + if let alice = aliceA { + model.call(alice) + await until(2) { !model.liveCalls.isEmpty } + check("Call dials the conversation's URI, not the user on the account's domain", + model.liveCalls.last?.remote.uri.lowercased().hasPrefix("sip:alice@a.example.com") == true, model.liveCalls.last?.remote.uri ?? "no call") + model.endCurrentCall() + await until(2) { model.calls.isEmpty } + let incomingTwice = model.messages(in: alice.id).filter { $0.direction == .incoming } + if let one = incomingTwice.first { model.deleteMessage(one.id) } + check("deleting an incoming message lowers the unread count", model.conversation(alice.id)?.unread == 1, "\(String(describing: model.conversation(alice.id)?.unread))") + } + let beforeSends = model.conversations.count + let bob1 = model.sendNew(text: "one", to: "bob@pbx.example.com", name: nil, account: officeID) + let bob2 = model.sendNew(text: "two", to: "bob@partner.org", name: nil, account: officeID) + let bob3 = model.sendNew(text: "three", to: "sip:bob@pbx.example.com", name: nil, account: officeID) + check("a new message to another host is another conversation, to the same peer the same one", + bob1 != nil && bob2 != nil && bob1 != bob2 && bob1 == bob3 && model.conversations.count == beforeSends + 2) + await until(3) { model.conversationLast.values.filter { $0.state == .sending }.isEmpty } + let bobs = await mock.sentMessages.suffix(3) + check("each is sent to its own address", bobs.map(\.user) == ["bob", "bob", "bob"]) + for id in [bob1, bob2].compactMap({ $0 }) { model.deleteConversation(id) } + for id in [aliceA?.id, aliceB?.id].compactMap({ $0 }) { model.deleteConversation(id) } + model.selectedAccountID = officeID + model.composeMessage(to: "5550101", name: nil, account: homeID) + check("Send Message from a call-log entry keeps the account row alone", + model.selectedAccountID == officeID && model.messagesPage == .new && model.newMessagePrefill?.account == homeID) + model.newMessagePrefill = nil + model.showMessagesList() + model.selectedAccountID = nil + var tooLong = Message(conversationID: UUID(), direction: .outgoing, text: "x", at: Date(), state: .failed) + tooLong.failureCode = 0; tooLong.failureReason = "Message too long (PJSIP_EMSGTOOLONG)" + check("a local failure that is not about the connection shows the engine's text", + MessageFormat.failure(tooLong).reason == "Message too long (PJSIP_EMSGTOOLONG)" && MessageFormat.failure(tooLong).tooltip == nil) + model.messagesWindowKeyOverride = nil + model.screenLocked = true + check("a locked screen is nobody reading", !model.mainWindowIsKey) + model.screenLocked = false + + // Formatting + let cal = Calendar(identifier: .gregorian) + let noon = cal.date(from: DateComponents(year: 2026, month: 11, day: 5, hour: 12))! + func at(_ d: Int, _ h: Int, _ m: Int, _ s: Int = 0) -> Date { + cal.date(from: DateComponents(year: 2026, month: 11, day: d, hour: h, minute: m, second: s))! + } + let conv = UUID() + func msg(_ dir: MessageDirection, _ date: Date, _ state: MessageState = .sent) -> Message { + Message(conversationID: conv, direction: dir, text: "x", at: date, state: state) + } + let a = msg(.incoming, at(4, 23, 59)), b = msg(.incoming, at(5, 0, 1)), c = msg(.incoming, at(5, 0, 2)) + let d = msg(.outgoing, at(5, 9, 0)), e = msg(.outgoing, at(5, 9, 1)), f = msg(.outgoing, at(5, 9, 5), .sending) + let g = msg(.outgoing, at(5, 9, 6), .failed) + let rows = MessageFormat.thread([a, b, c, d, e, f, g], now: noon, calendar: cal) + func row(_ m: Message) -> MessageFormat.Row? { rows.first { $0.id == m.id.uuidString } } + check("day separators before the first message of each day", rows.filter { if case .day = $0.kind { return true } else { return false } }.count == 2) + check("consecutive messages less than 2 minutes apart form a group: time under the last only", + row(b)?.showsMeta == false && row(c)?.showsMeta == true && row(d)?.showsMeta == false && row(e)?.showsMeta == true) + check("Sending… and Not sent are shown under every such message", row(f)?.showsMeta == true && row(g)?.showsMeta == true) + check("2 pt inside a group, 8 pt between groups, none under a day separator", + row(a)?.gap == 0 && row(c)?.gap == 2 && row(d)?.gap == 8 && row(e)?.gap == 2 && row(f)?.gap == 8 && row(b)?.gap == 0) + check("a day boundary breaks a group", row(b)?.gap == 0 && row(a)?.showsMeta == true) + check("Sent is never shown when the last outgoing message is not accepted", rows.allSatisfy { !$0.showsSent }) + check("row time: today is a time", MessageFormat.rowTime(at(5, 9, 0), now: noon, calendar: cal) == at(5, 9, 0).formatted(date: .omitted, time: .shortened)) + check("row time: yesterday", MessageFormat.rowTime(at(4, 9, 0), now: noon, calendar: cal) == L.messagesDayYesterday) + check("row time: within 6 days is the weekday", MessageFormat.rowTime(at(2, 9, 0), now: noon, calendar: cal) == at(2, 9, 0).formatted(.dateTime.weekday(.abbreviated))) + let oct = cal.date(from: DateComponents(year: 2026, month: 10, day: 6, hour: 10))! + let old = cal.date(from: DateComponents(year: 2025, month: 10, day: 6, hour: 10))! + check("row time: older is the date, with the year when not this year", + MessageFormat.rowTime(oct, now: noon, calendar: cal) == oct.formatted(.dateTime.day().month(.abbreviated)) + && MessageFormat.rowTime(old, now: noon, calendar: cal) == old.formatted(.dateTime.day().month(.abbreviated).year())) + check("day separator: Today, Yesterday, then the date", MessageFormat.daySeparator(at(5, 1, 0), now: noon, calendar: cal) == L.messagesDayToday + && MessageFormat.daySeparator(at(4, 1, 0), now: noon, calendar: cal) == L.messagesDayYesterday + && MessageFormat.daySeparator(at(1, 1, 0), now: noon, calendar: cal) == at(1, 1, 0).formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))) + var multi = msg(.outgoing, noon) + multi.text = "line one\nline two" + check("a preview is one line", MessageFormat.preview(multi) == L.messagesRowYou("line one line two")) + + // Put things back + model.messagesWindowKeyOverride = nil + model.updateSettings { $0.audio.soundEvents = savedSound; $0.general.doNotDisturb = savedDND } + model.tab = .dialpad + notifications.clearPosted() + } +} +#endif diff --git a/Sources/MacroSIPApp/Model/DemoState.swift b/Sources/MacroSIPApp/Model/DemoState.swift index f67b9e2..4a4df96 100644 --- a/Sources/MacroSIPApp/Model/DemoState.swift +++ b/Sources/MacroSIPApp/Model/DemoState.swift @@ -12,6 +12,7 @@ import SwiftUI /// | settings-audio | settings-codecs | timed-dnd | call-log-playback | busy-mode | quick-keys | quick-keys-bottom | contact-card | contact-card-new /// | settings-diagnostics | settings-diagnostics-on | diagnostics-selftest | settings-hotkeys | settings-hotkeys-on | import-microsip | import-microsip-done | hotkeys-selftest | import-selftest /// | directory | directory-done | directory-incoming | directory-sheet | directory-import | settings-directory +/// | messages | messages-conversation | messages-failed | messages-new | messages-empty | messages-selftest /// Data goes to a throw-away directory (see LaunchOptions); the Keychain is never touched. enum DemoState { static let officeID = AccountID(raw: UUID(uuidString: "00000000-0000-0000-0000-000000000001")!) @@ -23,7 +24,7 @@ enum DemoState { let state = LaunchOptions.current.demoState ?? "" if state == "first-launch" || state == "editor-first-launch" { return } let (accounts, contacts, log, settingsStore) = stores - if isDirectoryState(state) { seedDirectory(settingsStore) } + if isDirectoryState(state) || state == "messages-new" { seedDirectory(settingsStore) } var list = [ AccountConfig(id: officeID, displayName: "Office", username: "1001", domain: "pbx.example.com", transport: .tls, srtp: .mandatory, isDefaultOutgoing: true, voicemailNumber: "*97"), @@ -231,6 +232,8 @@ enum DemoState { model.openSettings(tab: .calls) case "quick-keys", "quick-keys-bottom": // the panel (right / bottom) with eight keys, one ringing; Settings › Quick keys opens too await quickKeysDemo(model, bottom: state == "quick-keys-bottom") + case let s where isMessagesState(s): + await runMessages(model, state: s) case let s where isDirectoryState(s) && s != "settings-directory": await runDirectory(model, state: s) case "settings-diagnostics-on": // Troubleshooting with Debug mode switched on (README screenshots) @@ -357,7 +360,7 @@ enum DemoState { if state == "timed-dnd" || state == "voicemail", let menu = StatusItemController.current?.debugMenuTitles() { try? menu.joined(separator: "\n").write(toFile: "\(prefix)-menu.txt", atomically: true, encoding: .utf8) } - if state != "selftest", state != "directory-selftest", state != "hotkeys-selftest", state != "import-selftest", state != "diagnostics-selftest" { quitLater() } // the snapshot was the point; those two quit themselves + if state != "selftest", state != "directory-selftest", state != "hotkeys-selftest", state != "import-selftest", state != "diagnostics-selftest", state != "messages-selftest" { quitLater() } // the snapshot was the point; those two quit themselves } } @@ -1313,6 +1316,7 @@ enum DemoState { await networkChecks(model) { check($0, $1, $2) } await hotkeyChecks(model) { check($0, $1, $2) } await importChecks(model) { check($0, $1, $2) } + await messagesChecks(model) { check($0, $1, $2) } let text = out.joined(separator: "\n") + "\nfailures=\(failures)\n" if let prefix = model.launch.snapshotPrefix { try? text.write(toFile: "\(prefix)-selftest.txt", atomically: true, encoding: .utf8) } diff --git a/Sources/MacroSIPApp/Model/Strings.swift b/Sources/MacroSIPApp/Model/Strings.swift index 4bd9a3a..c1133ea 100644 --- a/Sources/MacroSIPApp/Model/Strings.swift +++ b/Sources/MacroSIPApp/Model/Strings.swift @@ -37,6 +37,7 @@ enum L { static var tabsDialpad: String { loc("tabs.dialpad", "Dialpad") } static var tabsContacts: String { loc("tabs.contacts", "Contacts") } static var tabsCallLog: String { loc("tabs.callLog", "Call Log") } + static var tabsMessages: String { loc("tabs.messages", "Messages") } static var numberPlaceholder: String { loc("main.numberField.placeholder", "Name or number") } static var accountPickerHelp: String { loc("main.accountPicker.help", "Outgoing account") } static var accountPopupHeader: String { loc("account.popup.header", "Accounts") } @@ -96,6 +97,7 @@ enum L { static var contactsMenuCopy: String { loc("contacts.menu.copyNumber", "Copy Number") } static var contactsMenuEdit: String { loc("contacts.menu.edit", "Edit…") } static var contactsMenuDelete: String { loc("contacts.menu.delete", "Delete") } + static var contactsMenuMessage: String { loc("contacts.menu.message", "Send Message") } static func contactsDeleteConfirm(_ name: String) -> String { loc("contacts.delete.confirm", "Delete \(name)?") } @@ -120,6 +122,7 @@ enum L { static var logMenuAddContact: String { loc("calllog.menu.addContact", "Add to Contacts") } static var logMenuCopy: String { loc("calllog.menu.copyNumber", "Copy Number") } static var logMenuDelete: String { loc("calllog.menu.delete", "Delete Entry") } + static var logMenuMessage: String { loc("calllog.menu.message", "Send Message") } static var logClearTitle: String { loc("calllog.clear.title", "Clear the call log?") } static func logClearBody(_ n: Int) -> String { loc("calllog.clear.body", "All \(n) entries are removed.") } static var logClearConfirm: String { loc("calllog.clear.confirm", "Clear") } @@ -478,6 +481,42 @@ enum L { loc("account.field.verifyCertificate.help", "Turn off only for a server with a self-signed certificate.") } + // MARK: messages (SIP MESSAGE, screen 14) + static var messagesNew: String { loc("messages.new", "New Message") } + static var messagesEmptyTitle: String { loc("messages.empty.title", "No messages") } + static var messagesEmptyBody: String { loc("messages.empty.body", "Messages you receive appear here. Click New Message to write one.") } + static func messagesRowYou(_ text: String) -> String { loc("messages.row.you", "You: \(text)") } + static func messagesRowUnread(_ n: Int) -> String { loc("messages.row.unread", "\(n) unread") } + static var messagesDayToday: String { loc("messages.day.today", "Today") } + static var messagesDayYesterday: String { loc("messages.day.yesterday", "Yesterday") } + static var messagesBackHelp: String { loc("messages.back.help", "All conversations") } + static var messagesCallHelp: String { loc("messages.call.help", "Call") } + static var messagesComposerPlaceholder: String { loc("messages.composer.placeholder", "Message") } + static var messagesSendHelp: String { loc("messages.send.help", "Send") } + static func messagesComposerAccountOff(_ account: String) -> String { loc("messages.composer.accountOff", "\(account) is switched off") } + static var messagesComposerAccountRemoved: String { loc("messages.composer.accountRemoved", "The account of this conversation was removed") } + static var messagesComposerTooLong: String { loc("messages.composer.tooLong", "Too long to send") } + static var messagesStatusSending: String { loc("messages.status.sending", "Sending…") } + static var messagesStatusSent: String { loc("messages.status.sent", "Sent") } + static var messagesStatusSentHelp: String { + loc("messages.status.sent.help", "Accepted by the server. This does not confirm that the message reached the recipient's phone.") + } + static var messagesStatusFailed: String { loc("messages.status.failed", "Not sent") } + static func messagesStatusFailedReason(_ reason: String) -> String { loc("messages.status.failedReason", "Not sent · \(reason)") } + static var messagesErrorInterrupted: String { loc("messages.error.interrupted", "Interrupted") } + static var messagesErrorLocal: String { loc("messages.error.local", "No connection") } + static var messagesRetry: String { loc("messages.retry", "Retry") } + static var messagesMenuCall: String { loc("messages.menu.call", "Call") } + static var messagesMenuAddContact: String { loc("messages.menu.addContact", "Add to Contacts") } + static var messagesMenuCopyNumber: String { loc("messages.menu.copyNumber", "Copy Number") } + static var messagesMenuDeleteConversation: String { loc("messages.menu.deleteConversation", "Delete Conversation…") } + static var messagesMenuCopyText: String { loc("messages.menu.copyText", "Copy Text") } + static var messagesMenuDeleteMessage: String { loc("messages.menu.deleteMessage", "Delete Message") } + static func messagesDeleteTitle(_ name: String) -> String { loc("messages.delete.title", "Delete the conversation with \(name)?") } + static func messagesDeleteBody(_ n: Int) -> String { loc("messages.delete.body", "\(n) messages are removed from this Mac.") } + static var messagesNewTo: String { loc("messages.new.to", "To:") } + static func messagesNewFrom(_ account: String) -> String { loc("messages.new.from", "From \(account), the account chosen above") } + /// A number for display: at most one decimal, in the app's language ("0,5" in Russian). static func number(_ value: Double) -> String { let language = stringsBundle.preferredLocalizations.first ?? "en" @@ -817,6 +856,7 @@ enum L { static var audioSoundKeyPress: String { loc("settings.audio.soundEvents.keyPress", "Dial pad key presses") } static var audioSoundVoicemail: String { loc("settings.audio.soundEvents.voicemail", "New voicemail") } static var audioSoundError: String { loc("settings.audio.soundEvents.error", "Registration error and lost network") } + static var audioSoundMessage: String { loc("settings.audio.soundEvents.message", "New message") } static var audioSoundEventsFooter: String { loc("settings.audio.soundEvents.footer", "Short beeps on the speaker; the other side never hears them.") } static var audioTestHeader: String { loc("settings.audio.audioTest.header", "Audio test") } static var audioTestRow: String { loc("settings.audio.audioTest.row", "Speaker and microphone") } diff --git a/Sources/MacroSIPApp/Platform/AppDelegate.swift b/Sources/MacroSIPApp/Platform/AppDelegate.swift index a12f2b8..37171df 100644 --- a/Sources/MacroSIPApp/Platform/AppDelegate.swift +++ b/Sources/MacroSIPApp/Platform/AppDelegate.swift @@ -33,7 +33,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { model.startQuickKeys() observeContinuously { [model] in - let n = model.missedUnseen + let n = model.missedUnseen + model.messagesUnread // unseen missed calls plus unread messages NSApp.dockTile.badgeLabel = n > 0 ? "\(n)" : nil } observeContinuously { [weak self] in self?.statusItem?.refresh() } @@ -53,6 +53,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate { MainActor.assumeIsolated { if !isPanel { model.refreshIncomingPresentation() } } } } + // A conversation counts as read only while somebody can see it: not behind other windows, not on a locked screen. + nc.addObserver(forName: NSWindow.didChangeOcclusionStateNotification, object: nil, queue: .main) { [model] note in + let window = (note.object as? NSWindow).map(ObjectIdentifier.init) + MainActor.assumeIsolated { if window != nil, window == model.mainWindow.map(ObjectIdentifier.init) { model.updateMessageReadState() } } + } + let distributed = DistributedNotificationCenter.default() + distributed.addObserver(forName: Notification.Name("com.apple.screenIsLocked"), object: nil, queue: .main) { [model] _ in + MainActor.assumeIsolated { model.screenLocked = true } + } + distributed.addObserver(forName: Notification.Name("com.apple.screenIsUnlocked"), object: nil, queue: .main) { [model] _ in + MainActor.assumeIsolated { model.screenLocked = false; model.updateMessageReadState() } + } // A recorder that lost the keyboard stops listening, so the hotkeys do not stay off behind another app. for name in [NSApplication.didResignActiveNotification, NSWindow.didResignKeyNotification] { nc.addObserver(forName: name, object: nil, queue: .main) { [model] _ in diff --git a/Sources/MacroSIPApp/Platform/CallNotifications.swift b/Sources/MacroSIPApp/Platform/CallNotifications.swift index ce25b7b..627b867 100644 --- a/Sources/MacroSIPApp/Platform/CallNotifications.swift +++ b/Sources/MacroSIPApp/Platform/CallNotifications.swift @@ -2,7 +2,8 @@ import Foundation import UserNotifications import MacroSIPCore -/// Incoming-call notification with Answer / Decline actions (SCREENS.md 6.3). +/// Incoming-call notification with Answer / Decline actions (SCREENS.md 6.3). It is also the notification center's +/// delegate, so message notifications (`MessageNotifications`) pass through here. @MainActor final class CallNotifications: NSObject, UNUserNotificationCenterDelegate { static let shared = CallNotifications() @@ -24,7 +25,8 @@ final class CallNotifications: NSObject, UNUserNotificationCenterDelegate { let answer = UNNotificationAction(identifier: answerID, title: L.incomingAnswer, options: []) let decline = UNNotificationAction(identifier: declineID, title: L.incomingDecline, options: [.destructive]) center.setNotificationCategories([ - UNNotificationCategory(identifier: categoryID, actions: [answer, decline], intentIdentifiers: [], options: []) + UNNotificationCategory(identifier: categoryID, actions: [answer, decline], intentIdentifiers: [], options: []), + MessageNotifications.category, ]) // The completion handler runs on a UserNotifications queue, not on the main actor. center.requestAuthorization(options: [.alert, .sound]) { @Sendable _, _ in } @@ -65,6 +67,11 @@ final class CallNotifications: NSObject, UNUserNotificationCenterDelegate { ) async { let action = response.actionIdentifier let info = response.notification.request.content.userInfo + if response.notification.request.content.categoryIdentifier == MessageNotifications.categoryID { + guard let conversation = MessageNotifications.conversation(in: info) else { return } + await MainActor.run { AppModel.shared.openConversationFromNotification(conversation) } + return + } guard let raw = info["raw"] as? Int, let serial = info["serial"] as? Int else { return } await MainActor.run { let model = AppModel.shared diff --git a/Sources/MacroSIPApp/Platform/MessageNotifications.swift b/Sources/MacroSIPApp/Platform/MessageNotifications.swift new file mode 100644 index 0000000..4e252ee --- /dev/null +++ b/Sources/MacroSIPApp/Platform/MessageNotifications.swift @@ -0,0 +1,73 @@ +import Foundation +import UserNotifications + +/// One notification per incoming text message (SCREENS.md 14.4). Title: the sender, subtitle: the account, body: the text, +/// no action buttons and no sound (the "New message" sound event is the only sound). `threadIdentifier` is the +/// conversation, so Notification Center groups by conversation. A click opens the conversation. The notification +/// center's delegate is `CallNotifications`; it hands message responses to `handle(_:)`. +@MainActor +final class MessageNotifications { + static let shared = MessageNotifications() + + nonisolated static let categoryID = "MESSAGE" + private nonisolated static let conversationKey = "conversation" + + /// What `post` was asked for (the newest 64), also when the notification center is not available (demo launches): + /// the self-test reads it. + struct Posted: Equatable { + var conversation: UUID + var title: String + var subtitle: String + var body: String + } + private(set) var posted: [Posted] = [] + + /// Needs a real .app bundle; demo launches skip it so no permission dialog covers screenshots. + private var available: Bool { + Bundle.main.bundleURL.pathExtension == "app" && !LaunchOptions.current.isDemo + } + + private var center: UNUserNotificationCenter { UNUserNotificationCenter.current() } + + static var category: UNNotificationCategory { + UNNotificationCategory(identifier: categoryID, actions: [], intentIdentifiers: [], options: []) + } + + func post(text: String, from sender: String, account: String, conversation: UUID) { + posted.append(Posted(conversation: conversation, title: sender, subtitle: account, body: text)) + if posted.count > 64 { posted.removeFirst(posted.count - 64) } + guard available else { return } + let content = UNMutableNotificationContent() + content.title = sender + content.subtitle = account + content.body = text + content.categoryIdentifier = Self.categoryID + content.threadIdentifier = conversation.uuidString + content.userInfo = [Self.conversationKey: conversation.uuidString] + center.add(UNNotificationRequest(identifier: "message-\(UUID().uuidString)", content: content, trigger: nil)) + } + + func clearPosted() { posted = [] } + + /// The conversation was read in the app or deleted: its notifications leave Notification Center. + func remove(conversation: UUID) { + guard available else { return } + let thread = conversation.uuidString + Task.detached { + let ids = await Self.deliveredIdentifiers(thread: thread) + guard !ids.isEmpty else { return } + UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ids) + } + } + + private nonisolated static func deliveredIdentifiers(thread: String) async -> [String] { + await UNUserNotificationCenter.current().deliveredNotifications() + .filter { $0.request.content.threadIdentifier == thread } + .map(\.request.identifier) + } + + /// The conversation a message notification belongs to (`userInfo` of its request). + nonisolated static func conversation(in userInfo: [AnyHashable: Any]) -> UUID? { + (userInfo[conversationKey] as? String).flatMap(UUID.init(uuidString:)) + } +} diff --git a/Sources/MacroSIPApp/Resources/en.lproj/Localizable.strings b/Sources/MacroSIPApp/Resources/en.lproj/Localizable.strings index 0e93404..db25135 100644 --- a/Sources/MacroSIPApp/Resources/en.lproj/Localizable.strings +++ b/Sources/MacroSIPApp/Resources/en.lproj/Localizable.strings @@ -716,3 +716,39 @@ "import.microsip.andMore" = "and %lld more"; "import.microsip.warn.tooManyAccounts" = "Too many accounts in the file: only the first %lld are read."; "import.microsip.warn.tooManyContacts" = "Too many contacts in the file: only the first %lld are read."; + +/* 26.3: messages (screen 14) */ +"tabs.messages" = "Messages"; +"messages.new" = "New Message"; +"messages.empty.title" = "No messages"; +"messages.empty.body" = "Messages you receive appear here. Click New Message to write one."; +"messages.row.you" = "You: %@"; +"messages.day.today" = "Today"; +"messages.day.yesterday" = "Yesterday"; +"messages.back.help" = "All conversations"; +"messages.call.help" = "Call"; +"messages.composer.placeholder" = "Message"; +"messages.send.help" = "Send"; +"messages.composer.accountOff" = "%@ is switched off"; +"messages.composer.accountRemoved" = "The account of this conversation was removed"; +"messages.composer.tooLong" = "Too long to send"; +"messages.status.sending" = "Sending…"; +"messages.status.sent" = "Sent"; +"messages.status.sent.help" = "Accepted by the server. This does not confirm that the message reached the recipient's phone."; +"messages.status.failed" = "Not sent"; +"messages.status.failedReason" = "Not sent · %@"; +"messages.error.interrupted" = "Interrupted"; +"messages.error.local" = "No connection"; +"messages.retry" = "Retry"; +"messages.menu.call" = "Call"; +"messages.menu.addContact" = "Add to Contacts"; +"messages.menu.copyNumber" = "Copy Number"; +"messages.menu.deleteConversation" = "Delete Conversation…"; +"messages.menu.copyText" = "Copy Text"; +"messages.menu.deleteMessage" = "Delete Message"; +"messages.delete.title" = "Delete the conversation with %@?"; +"messages.new.to" = "To:"; +"messages.new.from" = "From %@, the account chosen above"; +"contacts.menu.message" = "Send Message"; +"calllog.menu.message" = "Send Message"; +"settings.audio.soundEvents.message" = "New message"; diff --git a/Sources/MacroSIPApp/Resources/en.lproj/Localizable.stringsdict b/Sources/MacroSIPApp/Resources/en.lproj/Localizable.stringsdict index 29132d3..6eee0ac 100644 --- a/Sources/MacroSIPApp/Resources/en.lproj/Localizable.stringsdict +++ b/Sources/MacroSIPApp/Resources/en.lproj/Localizable.stringsdict @@ -210,5 +210,37 @@ %lld contacts + messages.row.unread + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld unread + other + %lld unread + + + messages.delete.body + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld message is removed from this Mac. + other + %lld messages are removed from this Mac. + + diff --git a/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.strings b/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.strings index fdff3ee..87f50bb 100644 --- a/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.strings +++ b/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.strings @@ -716,3 +716,39 @@ "import.microsip.andMore" = "и ещё %lld"; "import.microsip.warn.tooManyAccounts" = "В файле слишком много аккаунтов: прочитаны только первые %lld."; "import.microsip.warn.tooManyContacts" = "В файле слишком много контактов: прочитаны только первые %lld."; + +/* 26.3: messages (screen 14) */ +"tabs.messages" = "Сообщения"; +"messages.new" = "Новое сообщение"; +"messages.empty.title" = "Нет сообщений"; +"messages.empty.body" = "Здесь появятся полученные сообщения. Нажмите «Новое сообщение», чтобы написать."; +"messages.row.you" = "Вы: %@"; +"messages.day.today" = "Сегодня"; +"messages.day.yesterday" = "Вчера"; +"messages.back.help" = "Все переписки"; +"messages.call.help" = "Позвонить"; +"messages.composer.placeholder" = "Сообщение"; +"messages.send.help" = "Отправить"; +"messages.composer.accountOff" = "Аккаунт %@ выключен"; +"messages.composer.accountRemoved" = "Аккаунт этой переписки удалён"; +"messages.composer.tooLong" = "Слишком длинное сообщение"; +"messages.status.sending" = "Отправляется…"; +"messages.status.sent" = "Отправлено"; +"messages.status.sent.help" = "Принято сервером. Это не значит, что сообщение дошло до телефона получателя."; +"messages.status.failed" = "Не отправлено"; +"messages.status.failedReason" = "Не отправлено · %@"; +"messages.error.interrupted" = "Прервано"; +"messages.error.local" = "Нет связи"; +"messages.retry" = "Повторить"; +"messages.menu.call" = "Позвонить"; +"messages.menu.addContact" = "Добавить в контакты"; +"messages.menu.copyNumber" = "Скопировать номер"; +"messages.menu.deleteConversation" = "Удалить переписку…"; +"messages.menu.copyText" = "Скопировать текст"; +"messages.menu.deleteMessage" = "Удалить сообщение"; +"messages.delete.title" = "Удалить переписку с «%@»?"; +"messages.new.to" = "Кому:"; +"messages.new.from" = "С аккаунта %@, выбранного выше"; +"contacts.menu.message" = "Написать сообщение"; +"calllog.menu.message" = "Написать сообщение"; +"settings.audio.soundEvents.message" = "Новое сообщение"; diff --git a/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.stringsdict b/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.stringsdict index 2c8d44f..edce8ae 100644 --- a/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.stringsdict +++ b/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.stringsdict @@ -262,5 +262,45 @@ %lld контакта + messages.row.unread + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld непрочитанное + few + %lld непрочитанных + many + %lld непрочитанных + other + %lld непрочитанного + + + messages.delete.body + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + С этого Mac будет удалено %lld сообщение. + few + С этого Mac будет удалено %lld сообщения. + many + С этого Mac будет удалено %lld сообщений. + other + С этого Mac будет удалено %lld сообщения. + + diff --git a/Sources/MacroSIPApp/Views/CallLog/CallLogView.swift b/Sources/MacroSIPApp/Views/CallLog/CallLogView.swift index a4aac59..4c4cca1 100644 --- a/Sources/MacroSIPApp/Views/CallLog/CallLogView.swift +++ b/Sources/MacroSIPApp/Views/CallLog/CallLogView.swift @@ -155,6 +155,8 @@ struct CallLogView: View { Menu(L.logMenuCallFrom) { ForEach(model.enabledAccounts) { a in Button(a.displayName) { model.callBack(e, account: a.id) } } } + Button(L.logMenuMessage) { model.sendMessage(to: e) } + .disabled(model.enabledAccounts.isEmpty) Button(L.logMenuAddContact) { ContactCardController.shared.show(ContactEditorRequest(contact: nil, prefillName: e.remoteDisplayName ?? "", prefillNumber: e.remoteNumber), model: model) } diff --git a/Sources/MacroSIPApp/Views/Components/Theme.swift b/Sources/MacroSIPApp/Views/Components/Theme.swift index 6625cd2..f2abaf5 100644 --- a/Sources/MacroSIPApp/Views/Components/Theme.swift +++ b/Sources/MacroSIPApp/Views/Components/Theme.swift @@ -147,43 +147,87 @@ struct StatusDot: View { } /// Segmented control look from the mockups, with an optional badge on a segment. +/// `.equal` gives every segment the same width. `.byLabel` (the main window's four tabs, SCREENS.md 14 "Tab control") +/// makes each segment as wide as its label and badge plus an equal share of the remaining width, so a long label +/// ("Сообщения") and its badge fit where equal widths would not. struct SegmentedTabs: View { - struct Item { let value: Value; let title: String; var badge: Int = 0 } + struct Item { + let value: Value + let title: String + var badge: Int = 0 + /// Counts above this show as "+". + var badgeLimit: Int? + } + enum Widths { case equal, byLabel } let items: [Item] @Binding var selection: Value var height: CGFloat = 24 + var fontSize: CGFloat = 12.5 + var widths: Widths = .equal var body: some View { - HStack(spacing: 0) { - ForEach(items, id: \.value) { item in - let selected = item.value == selection - Button { selection = item.value } label: { - HStack(spacing: 5) { - Text(item.title).font(.system(size: 12.5)).lineLimit(1).minimumScaleFactor(0.85) - if item.badge > 0 { CountPill(count: item.badge) } - } - .frame(maxWidth: .infinity, minHeight: height - 4) - .background { - if selected { - RoundedRectangle(cornerRadius: 5).fill(Theme.segSelected) - .shadow(color: .black.opacity(0.18), radius: 1, y: 1) - } - } - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .accessibilityAddTraits(selected ? .isSelected : []) + Group { + switch widths { + case .equal: HStack(spacing: 0) { segments } + case .byLabel: LabelWidthsLayout { segments } } } .padding(2) .background(RoundedRectangle(cornerRadius: 7).fill(Color.primary.opacity(0.07))) } + + private var segments: some View { + ForEach(items, id: \.value) { item in + let selected = item.value == selection + Button { selection = item.value } label: { + HStack(spacing: 5) { + Text(item.title).font(.system(size: fontSize)).lineLimit(1).minimumScaleFactor(0.85) + if item.badge > 0 { CountPill(count: item.badge, limit: item.badgeLimit) } + } + .frame(maxWidth: .infinity, minHeight: height - 4) + .background { + if selected { + RoundedRectangle(cornerRadius: 5).fill(Theme.segSelected) + .shadow(color: .black.opacity(0.18), radius: 1, y: 1) + } + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityAddTraits(selected ? .isSelected : []) + } + } +} + +/// Each child is as wide as its natural width plus an equal share of what is left of the proposed width. When the natural +/// widths do not fit, they shrink in proportion (the labels then fall back on their minimum scale). +private struct LabelWidthsLayout: Layout { + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let natural = subviews.map { $0.sizeThatFits(.unspecified) } + return CGSize(width: proposal.width ?? natural.reduce(0) { $0 + $1.width }, height: natural.map(\.height).max() ?? 0) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + let natural = subviews.map { $0.sizeThatFits(.unspecified).width } + let total = natural.reduce(0, +) + guard !subviews.isEmpty, total > 0 else { return } + let share = (bounds.width - total) / CGFloat(subviews.count) + var x = bounds.minX + for (i, subview) in subviews.enumerated() { + let width = total <= bounds.width ? natural[i] + share : natural[i] * bounds.width / total + subview.place(at: CGPoint(x: x, y: bounds.minY), anchor: .topLeading, + proposal: ProposedViewSize(width: width, height: bounds.height)) + x += width + } + } } struct CountPill: View { let count: Int + /// Counts above this show as "+". + var limit: Int? var body: some View { - Text("\(count)") + Text(limit.map { count > $0 ? "\($0)+" : "\(count)" } ?? "\(count)") .font(.system(size: 10, weight: .bold)) .foregroundStyle(.white) .padding(.horizontal, 5) diff --git a/Sources/MacroSIPApp/Views/Contacts/ContactRow.swift b/Sources/MacroSIPApp/Views/Contacts/ContactRow.swift index b4f8698..c1fb862 100644 --- a/Sources/MacroSIPApp/Views/Contacts/ContactRow.swift +++ b/Sources/MacroSIPApp/Views/Contacts/ContactRow.swift @@ -83,6 +83,8 @@ struct ContactRow: View { Button(a.displayName) { model.placeCall(to: c, account: a.id) } } } + Button(L.contactsMenuMessage) { model.sendMessage(to: c) } + .disabled(c.defaultNumber == nil || model.enabledAccounts.isEmpty) Button(L.contactsMenuCopy, action: onCopy).keyboardShortcut("c", modifiers: .command) Divider() Button(L.contactsMenuEdit, action: onEdit).keyboardShortcut("e", modifiers: .command) diff --git a/Sources/MacroSIPApp/Views/Directory/SuggestionList.swift b/Sources/MacroSIPApp/Views/Directory/SuggestionList.swift index 9a0aea0..1980205 100644 --- a/Sources/MacroSIPApp/Views/Directory/SuggestionList.swift +++ b/Sources/MacroSIPApp/Views/Directory/SuggestionList.swift @@ -15,7 +15,8 @@ struct SuggestionList: View { let call: (SuggestionRow) -> Void private static let rowHeight: CGFloat = 27 - private static let maxHeight: CGFloat = 340 + /// The list scrolls beyond this height (the new-message form is shorter than the number field's room). + var maxHeight: CGFloat = 340 private var entryCount: Int { sections.reduce(0) { $0 + $1.entries.count } } private var hasDirectory: Bool { !sections.isEmpty || !pending.isEmpty } @@ -30,10 +31,10 @@ struct SuggestionList: View { var body: some View { let content = rowsView Group { - if estimatedHeight > Self.maxHeight { + if estimatedHeight > maxHeight { ScrollViewReader { proxy in ScrollView { content } - .frame(height: Self.maxHeight) + .frame(height: maxHeight) .onChange(of: highlighted) { _, id in if let id { proxy.scrollTo(id) } } } } else { diff --git a/Sources/MacroSIPApp/Views/Main/MainWindowView.swift b/Sources/MacroSIPApp/Views/Main/MainWindowView.swift index 50bcb14..5555ed0 100644 --- a/Sources/MacroSIPApp/Views/Main/MainWindowView.swift +++ b/Sources/MacroSIPApp/Views/Main/MainWindowView.swift @@ -21,6 +21,10 @@ struct MainWindowView: View { } .onChange(of: model.tab) { _, tab in if tab == .callLog { model.markLogSeen() } + model.updateMessageReadState() + } + .onReceive(NotificationCenter.default.publisher(for: NSWindow.didBecomeKeyNotification)) { note in + if (note.object as? NSWindow) === model.mainWindow { model.updateMessageReadState() } } .onAppear { model.openSettingsAction = { openSettings() } } } @@ -39,8 +43,9 @@ struct MainWindowView: View { .init(value: MainTab.dialpad, title: L.tabsDialpad), .init(value: MainTab.contacts, title: L.tabsContacts), .init(value: MainTab.callLog, title: L.tabsCallLog, badge: model.missedUnseen), + .init(value: MainTab.messages, title: L.tabsMessages, badge: model.messagesUnread, badgeLimit: 99), ], - selection: $model.tab) + selection: $model.tab, fontSize: 12, widths: .byLabel) .padding(.horizontal, 10) .padding(.bottom, 8) Divider() @@ -76,6 +81,11 @@ struct MainWindowView: View { CallSummaryBar() CallLogView() } + case .messages: + VStack(spacing: 0) { + CallSummaryBar() + MessagesTab() + } } } } diff --git a/Sources/MacroSIPApp/Views/Main/NumberRow.swift b/Sources/MacroSIPApp/Views/Main/NumberRow.swift index b3f6ce1..ef85eb6 100644 --- a/Sources/MacroSIPApp/Views/Main/NumberRow.swift +++ b/Sources/MacroSIPApp/Views/Main/NumberRow.swift @@ -18,10 +18,11 @@ struct NumberRow: View { var body: some View { @Bindable var model = model // Computed once per body, from the contacts held in memory. + let mine = model.directory.owner == .numberField // the To field of a new message uses the same search let local = model.directory.dismissed ? [] : self.suggestions - let sections = model.directorySections(excluding: local) + let sections = mine ? model.directorySections(excluding: local) : [] let rows = SuggestionRow.rows(local: local, sections: sections) - let pending = model.directory.dismissed ? [] : model.directory.pending + let pending = model.directory.dismissed || !mine ? [] : model.directory.pending let visible = !rows.isEmpty HStack(spacing: 6) { TextField(L.numberPlaceholder, text: $model.dialText) @@ -74,7 +75,7 @@ struct NumberRow: View { model.textChangedForDirectory(text) } .onReceive(NotificationCenter.default.publisher(for: NSWindow.didBecomeKeyNotification)) { note in - if (note.object as? NSWindow) === model.mainWindow, !model.showKeypad { focused = true } + if (note.object as? NSWindow) === model.mainWindow, !model.showKeypad, !model.messageFieldHasFocus { focused = true } } .onChange(of: model.showKeypad) { _, on in if !on { focused = true } } .onChange(of: model.tab) { _, tab in if tab == .dialpad, !model.showKeypad { focused = true } } diff --git a/Sources/MacroSIPApp/Views/Messages/ConversationView.swift b/Sources/MacroSIPApp/Views/Messages/ConversationView.swift new file mode 100644 index 0000000..5e0c570 --- /dev/null +++ b/Sources/MacroSIPApp/Views/Messages/ConversationView.swift @@ -0,0 +1,234 @@ +import SwiftUI +import MacroSIPCore + +/// 14.2: header (back, contact, Call), the bubbles, the composer. +struct ConversationView: View { + @Environment(AppModel.self) private var model + let id: UUID + @Local private var text = "" + @Local private var loaded = false + + var body: some View { + if let conv = model.conversation(id) { content(conv) } else { Color.clear } + } + + private func content(_ conv: Conversation) -> some View { + let state = model.accountState(of: conv) + let ready = state == .ready + return VStack(spacing: 0) { + ConversationHeader(conversation: conv) + Divider() + MessageThreadView(conversation: conv) + MessageComposerBar( + text: $text, placeholder: model.composerPlaceholder(for: conv), enabled: ready, + canSend: ready && model.canSend(text), tooLong: model.isTooLong(text), + focusTrigger: model.focusComposer, autoFocus: true, + onSend: { if model.send(text: text, in: conv.id) { text = "" } }, + onEscape: { model.showMessagesList() }) + } + .onAppear { + guard !loaded else { return } + loaded = true + text = model.messageDrafts[id] ?? "" + model.updateMessageReadState() + } + .onChange(of: text) { _, new in model.messageDrafts[id] = new.isEmpty ? nil : new } + } +} + +struct ConversationHeader: View { + @Environment(AppModel.self) private var model + let conversation: Conversation + + var body: some View { + let c = conversation + let name = model.name(for: c) + let hasChip = model.account(c.accountID) != nil + HStack(spacing: 8) { + BackButton { model.showMessagesList() } + AvatarView(name: name, size: 28, contact: model.contact(for: c)) + VStack(alignment: .leading, spacing: 0) { + Text(name).font(.system(size: 13, weight: .semibold)).lineLimit(1) + HStack(spacing: 5) { + if name != c.shownNumber { Text(c.shownNumber).monospacedDigit().lineLimit(1) } + if name != c.shownNumber, hasChip { Text("·") } + if hasChip { AccountChip(name: model.accountName(c.accountID)) } + } + .font(.system(size: 11)).foregroundStyle(Theme.label2) + } + Spacer(minLength: 4) + let ready = model.accountState(of: c) == .ready + Button { model.call(c) } label: { + Image(systemName: "phone.fill").font(.system(size: 11)).foregroundStyle(Theme.green) + .frame(width: 24, height: 24).background(Circle().fill(Theme.fill)) + } + .buttonStyle(.plain) + .disabled(!ready) + .opacity(ready ? 1 : 0.4) + .help(L.messagesCallHelp) + .accessibilityLabel(L.messagesCallHelp) + } + .padding(.leading, 6).padding(.trailing, 10).padding(.vertical, 5) + .frame(height: 44) + .background(Theme.content) + } +} + +/// Chevron at the left of the 14.2 and 14.3 headers. +struct BackButton: View { + let action: () -> Void + + var body: some View { + Button(action: action) { + Image(systemName: "chevron.left").font(.system(size: 13, weight: .semibold)).foregroundStyle(Theme.blue) + .frame(width: 22, height: 26).contentShape(Rectangle()) + } + .buttonStyle(.plain) + .help(L.messagesBackHelp) + .accessibilityLabel(L.messagesBackHelp) + } +} + +/// The bubbles of one conversation, oldest at the top; opens at the newest message. +struct MessageThreadView: View { + @Environment(AppModel.self) private var model + let conversation: Conversation + + var body: some View { + let rows = model.threadRows + GeometryReader { geo in + ScrollViewReader { proxy in + ScrollView { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(rows) { row in + switch row.kind { + case let .day(title): + Text(title) + .font(.system(size: 11, weight: .semibold)).foregroundStyle(Theme.label2) + .frame(maxWidth: .infinity) + .padding(.top, 8).padding(.bottom, 5) + case let .bubble(message): + MessageBubbleRow(message: message, showsMeta: row.showsMeta, showsSent: row.showsSent, + width: geo.size.width - 20) + .padding(.top, row.gap) + } + } + Color.clear.frame(height: 1).id("end") + } + .padding(.horizontal, 10).padding(.top, 4).padding(.bottom, 6) + .frame(minHeight: geo.size.height, alignment: .bottom) + } + .defaultScrollAnchor(.bottom) + .onChange(of: model.messageThread.map(\.id)) { _, _ in proxy.scrollTo("end", anchor: .bottom) } + .onAppear { proxy.scrollTo("end", anchor: .bottom) } + } + } + .background(Theme.content) + } +} + +/// A bubble with its time line. +struct MessageBubbleRow: View { + @Environment(AppModel.self) private var model + let message: Message + let showsMeta: Bool + let showsSent: Bool + let width: CGFloat + + private var outgoing: Bool { message.direction == .outgoing } + private var failed: Bool { message.state == .failed } + + var body: some View { + VStack(alignment: outgoing ? .trailing : .leading, spacing: 0) { + HStack(spacing: 6) { + if outgoing { Spacer(minLength: 0) } + if failed { failedGlyph } + bubble + if !outgoing { Spacer(minLength: 0) } + } + .frame(maxWidth: .infinity, alignment: outgoing ? .trailing : .leading) + if showsMeta { meta.padding(.top, 2) } + } + } + + private var bubble: some View { + let shape = UnevenRoundedRectangle(topLeadingRadius: 15, bottomLeadingRadius: outgoing ? 15 : 5, + bottomTrailingRadius: outgoing ? 5 : 15, topTrailingRadius: 15) + // At most 76 % of the list width (84 % with the failed glyph), as wide as its text below that. + let limit = failed ? width * 0.84 - 22 : width * 0.76 + return CappedWidth(maxWidth: limit) { + Text(message.text) + .font(.system(size: 13)) + .foregroundStyle(outgoing ? Color.white : Color.primary) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 10).padding(.vertical, 6) + .background(shape.fill(outgoing ? Theme.blue : Theme.fill2)) + } + .contextMenu { bubbleMenu } + } + + @ViewBuilder + private var bubbleMenu: some View { + Button(L.messagesMenuCopyText) { model.copyToPasteboard(message.text) } + if failed { Button(L.messagesRetry) { model.retry(message) } } + Divider() + Button(L.messagesMenuDeleteMessage, role: .destructive) { model.deleteMessage(message.id) } + } + + /// Red exclamation in a circle at the left of a failed bubble; a click opens the bubble menu. + private var failedGlyph: some View { + Menu { bubbleMenu } label: { + Image(systemName: "exclamationmark.circle").font(.system(size: 16, weight: .regular)).foregroundStyle(Theme.red) + .frame(width: 16, height: 16) + } + .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize() + .accessibilityLabel(L.messagesStatusFailed) + } + + /// Time of the message, then the status of an outgoing one. + private var meta: some View { + HStack(spacing: 4) { + Text(MessageFormat.timeOfDay(message.at)).monospacedDigit() + if outgoing { + switch message.state { + case .sending: + Text("·") + ProgressView().controlSize(.mini).scaleEffect(0.55).frame(width: 9, height: 9) + Text(L.messagesStatusSending) + case .failed: + let f = MessageFormat.failure(message) + Text("·") + Text(L.messagesStatusFailedReason(f.reason)).fontWeight(.medium).foregroundStyle(Theme.red) + .help(f.tooltip ?? "") + Text("·") + Button(L.messagesRetry) { model.retry(message) } + .buttonStyle(.plain).fontWeight(.medium).foregroundStyle(Theme.blue) + case .sent: + if showsSent { + Text("·") + Text(L.messagesStatusSent).help(L.messagesStatusSentHelp) + } + } + } + } + .font(.system(size: 10.5)).foregroundStyle(Theme.label2).lineLimit(1) + .padding(.horizontal, 6) + .accessibilityElement(children: .combine) + } +} + +/// Offers its one child at most `maxWidth` and takes the size the child chooses (unlike `frame(maxWidth:)`, which grows). +private struct CappedWidth: Layout { + var maxWidth: CGFloat + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + guard let child = subviews.first else { return .zero } + let width = proposal.width.map { min($0, maxWidth) } ?? maxWidth + return child.sizeThatFits(ProposedViewSize(width: width, height: proposal.height)) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + subviews.first?.place(at: bounds.origin, anchor: .topLeading, proposal: ProposedViewSize(width: bounds.width, height: bounds.height)) + } +} diff --git a/Sources/MacroSIPApp/Views/Messages/MessageComposer.swift b/Sources/MacroSIPApp/Views/Messages/MessageComposer.swift new file mode 100644 index 0000000..d32dc12 --- /dev/null +++ b/Sources/MacroSIPApp/Views/Messages/MessageComposer.swift @@ -0,0 +1,257 @@ +import SwiftUI +import AppKit + +/// The text of the message composer (SCREENS.md 14.2): a multi-line text view that grows to five lines, then scrolls. +/// Return sends, Shift-Return and Option-Return start a new line, Escape goes back. While an input method has marked +/// text, Return belongs to it and does not send. +struct ComposerTextView: NSViewRepresentable { + @Binding var text: String + @Binding var height: CGFloat + @Binding var isFocused: Bool + var placeholder: String + var enabled: Bool + /// Changes whenever the cursor should go into the field. + var focusTrigger: Int + var autoFocus: Bool + var onSend: () -> Void + var onEscape: () -> Void + + static let font = NSFont.systemFont(ofSize: 13) + /// One line of the field's text. + static var lineHeight: CGFloat { ceil(NSLayoutManager().defaultLineHeight(for: font)) } + + func makeCoordinator() -> Coordinator { Coordinator(self) } + + func makeNSView(context: Context) -> ComposerScrollView { + let storage = NSTextStorage() + let layout = NSLayoutManager() + storage.addLayoutManager(layout) + let container = NSTextContainer(size: NSSize(width: 270, height: CGFloat.greatestFiniteMagnitude)) + container.widthTracksTextView = true + container.lineFragmentPadding = 0 + layout.addTextContainer(container) + + let view = ComposerNSTextView(frame: NSRect(x: 0, y: 0, width: 270, height: Self.lineHeight), textContainer: container) + view.delegate = context.coordinator + view.focusRingType = .none + view.isRichText = false + view.importsGraphics = false + view.allowsUndo = true + view.font = Self.font + view.textColor = .labelColor + view.drawsBackground = false + view.textContainerInset = .zero + view.isVerticallyResizable = true + view.isHorizontallyResizable = false + view.autoresizingMask = [.width] + view.isAutomaticQuoteSubstitutionEnabled = false + view.isAutomaticDashSubstitutionEnabled = false + view.typingAttributes = [.font: Self.font, .foregroundColor: NSColor.labelColor] + view.string = text + view.onReturn = { [weak coordinator = context.coordinator] in coordinator?.parent.onSend() } + view.onEscape = { [weak coordinator = context.coordinator] in coordinator?.parent.onEscape() } + view.onFocusChange = { [weak coordinator = context.coordinator] focused in coordinator?.setFocused(focused) } + view.focusWhenShown = autoFocus && enabled + + let scroll = ComposerScrollView(frame: NSRect(x: 0, y: 0, width: 270, height: Self.lineHeight)) + scroll.focusRingType = .none + scroll.drawsBackground = false + scroll.borderType = .noBorder + scroll.hasVerticalScroller = true + scroll.hasHorizontalScroller = false + scroll.autohidesScrollers = true + scroll.scrollerStyle = .overlay + scroll.documentView = view + context.coordinator.textView = view + context.coordinator.measure() + return scroll + } + + func updateNSView(_ scroll: ComposerScrollView, context: Context) { + let c = context.coordinator + c.parent = self + guard let view = c.textView else { return } + if view.string != text { + view.string = text + c.measure() + } + view.placeholder = placeholder + view.isEditable = enabled + view.isSelectable = enabled + view.alphaValue = enabled ? 1 : 0.55 + if focusTrigger != c.lastFocusTrigger { + c.lastFocusTrigger = focusTrigger + if enabled { DispatchQueue.main.async { view.window?.makeFirstResponder(view) } } + } + } + + @MainActor + final class Coordinator: NSObject, NSTextViewDelegate { + var parent: ComposerTextView + weak var textView: ComposerNSTextView? + var lastFocusTrigger: Int + + init(_ parent: ComposerTextView) { + self.parent = parent + lastFocusTrigger = parent.focusTrigger + } + + func textDidChange(_ notification: Notification) { + guard let view = textView else { return } + if parent.text != view.string { parent.text = view.string } + measure() + } + + func setFocused(_ focused: Bool) { + DispatchQueue.main.async { [self] in if parent.isFocused != focused { parent.isFocused = focused } } + } + + /// The height of the text, reported to SwiftUI after the current layout pass. + func measure() { + guard let view = textView, let layout = view.layoutManager, let container = view.textContainer else { return } + layout.ensureLayout(for: container) + let h = max(ceil(layout.usedRect(for: container).height), ComposerTextView.lineHeight) + DispatchQueue.main.async { [self] in if abs(parent.height - h) > 0.5 { parent.height = h } } + } + } +} + +/// The text never scrolls sideways (it wraps), whatever the first layout passes did to the clip view. +final class ComposerScrollView: NSScrollView { + override var focusRingType: NSFocusRingType { get { .none } set {} } + override var focusRingMaskBounds: NSRect { .zero } + override func drawFocusRingMask() {} + + override func layout() { + super.layout() + if contentView.bounds.origin.x != 0 { + contentView.scroll(to: NSPoint(x: 0, y: contentView.bounds.origin.y)) + reflectScrolledClipView(contentView) + } + } +} + +final class ComposerNSTextView: NSTextView { + var onReturn: (() -> Void)? + var onEscape: (() -> Void)? + var onFocusChange: ((Bool) -> Void)? + var focusWhenShown = false + var placeholder = "" { didSet { if oldValue != placeholder { needsDisplay = true } } } + + // The field draws its own focus ring (the pill); the system one would be cut at the scroll view's edges. + override var focusRingType: NSFocusRingType { get { .none } set {} } + override var focusRingMaskBounds: NSRect { .zero } + override func drawFocusRingMask() {} + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + guard focusWhenShown, let window else { return } + focusWhenShown = false + DispatchQueue.main.async { [weak self, weak window] in + guard let self, let window, self.isEditable else { return } + window.makeFirstResponder(self) + } + } + + override func becomeFirstResponder() -> Bool { + let ok = super.becomeFirstResponder() + if ok { onFocusChange?(true) } + return ok + } + + override func resignFirstResponder() -> Bool { + let ok = super.resignFirstResponder() + if ok { onFocusChange?(false) } + return ok + } + + override func keyDown(with event: NSEvent) { + let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + let isReturn = event.keyCode == 36 || event.keyCode == 76 + if isReturn, !hasMarkedText() { + if flags.contains(.shift) || flags.contains(.option) { insertNewlineIgnoringFieldEditor(nil); return } + if flags.isDisjoint(with: [.command, .control]) { onReturn?(); return } + } + if event.keyCode == 53, !hasMarkedText() { onEscape?(); return } // Escape + super.keyDown(with: event) + } + + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + guard string.isEmpty, !placeholder.isEmpty, !hasMarkedText() else { return } + let attrs: [NSAttributedString.Key: Any] = [.font: ComposerTextView.font, .foregroundColor: NSColor.tertiaryLabelColor] + NSAttributedString(string: placeholder, attributes: attrs) + .draw(at: NSPoint(x: textContainerInset.width + (textContainer?.lineFragmentPadding ?? 0), y: textContainerInset.height)) + } +} + +/// The bottom of 14.2 and 14.3: top hairline, the red "Too long to send" line, the field and the Send button. +struct MessageComposerBar: View { + @Binding var text: String + var placeholder: String + var enabled: Bool + var canSend: Bool + var tooLong: Bool + var focusTrigger: Int + var autoFocus: Bool + var onSend: () -> Void + var onEscape: () -> Void + @Local private var contentHeight: CGFloat = ComposerTextView.lineHeight + @Local private var focused = false + + /// The text view in its frame: a pill for one line, a 15 pt rounded rectangle once the field has grown (one shape type, + /// so growing never rebuilds the text view), with the accent border and tint ring while it has the focus. + @ViewBuilder + private var field: some View { + let text = ComposerTextView(text: $text, height: $contentHeight, isFocused: $focused, placeholder: placeholder, enabled: enabled, + focusTrigger: focusTrigger, autoFocus: autoFocus, onSend: send, onEscape: onEscape) + .focusEffectDisabled() + .frame(height: fieldHeight) + .padding(.horizontal, 11).padding(.vertical, 7) + framed(text, RoundedRectangle(cornerRadius: min(15, (fieldHeight + 14) / 2))) + } + + private func framed(_ content: some View, _ shape: S) -> some View { + let on = focused && enabled + return content + .background(shape.fill(Theme.control)) + .overlay(shape.strokeBorder(on ? Theme.blue : Theme.controlBorder, lineWidth: on ? 1 : 0.5)) + .overlay(shape.strokeBorder(Theme.blue.opacity(on ? 0.28 : 0), lineWidth: 3).padding(-1.5)) + .opacity(enabled ? 1 : 0.6) + } + + private var fieldHeight: CGFloat { + let line = ComposerTextView.lineHeight + return min(max(contentHeight, line), line * 5) + } + + var body: some View { + VStack(spacing: 0) { + Divider() + if tooLong { + Text(L.messagesComposerTooLong) + .font(.system(size: 11)).foregroundStyle(Theme.red) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 14).padding(.top, 6) + } + HStack(alignment: .bottom, spacing: 7) { + field + Button(action: send) { + Image(systemName: "arrow.up").font(.system(size: 12, weight: .bold)) + .foregroundStyle(canSend ? Color.white : Theme.content) + .frame(width: 26, height: 26) + .background(Circle().fill(canSend ? Theme.blue : Theme.fill3)) + } + .buttonStyle(.plain) + .disabled(!canSend) + .padding(.bottom, 2) + .help(L.messagesSendHelp) + .accessibilityLabel(L.messagesSendHelp) + } + .padding(.horizontal, 10).padding(.top, 7).padding(.bottom, 8) + } + .background(Theme.content) + } + + private func send() { if canSend && enabled { onSend() } } +} diff --git a/Sources/MacroSIPApp/Views/Messages/MessageFormat.swift b/Sources/MacroSIPApp/Views/Messages/MessageFormat.swift new file mode 100644 index 0000000..8bd476f --- /dev/null +++ b/Sources/MacroSIPApp/Views/Messages/MessageFormat.swift @@ -0,0 +1,104 @@ +import Foundation +import MacroSIPCore + +/// What the Messages tab shows for stored data (SCREENS.md 14): row times, day separators, grouped bubbles, status lines and +/// failure reasons. Pure functions of the data, a date and a calendar, so the demo self-test can check them. +enum MessageFormat { + /// Time column of a conversation row: today the time, yesterday the word, the last 6 days the weekday, older the date + /// without the year (with it when not this year). + static func rowTime(_ date: Date, now: Date = Date(), calendar: Calendar = .current) -> String { + let days = daysBetween(date, now, calendar) + if days <= 0 { return date.formatted(date: .omitted, time: .shortened) } + if days == 1 { return L.messagesDayYesterday } + if days <= 6 { return date.formatted(.dateTime.weekday(.abbreviated)) } + if calendar.component(.year, from: date) == calendar.component(.year, from: now) { + return date.formatted(.dateTime.day().month(.abbreviated)) + } + return date.formatted(.dateTime.day().month(.abbreviated).year()) + } + + /// Day separator of a conversation: Today, Yesterday, then "Mon, 6 Oct" (as the call log sections). + static func daySeparator(_ date: Date, now: Date = Date(), calendar: Calendar = .current) -> String { + let days = daysBetween(date, now, calendar) + if days == 0 { return L.messagesDayToday } + if days == 1 { return L.messagesDayYesterday } + return date.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated)) + } + + private static func daysBetween(_ date: Date, _ now: Date, _ calendar: Calendar) -> Int { + calendar.dateComponents([.day], from: calendar.startOfDay(for: date), to: calendar.startOfDay(for: now)).day ?? 0 + } + + static func timeOfDay(_ date: Date) -> String { date.formatted(date: .omitted, time: .shortened) } + + /// The last message on one line: line breaks become spaces; an outgoing one starts with "You: ". + static func preview(_ message: Message) -> String { + let flat = message.text.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty }.joined(separator: " ") + return message.direction == .outgoing ? L.messagesRowYou(flat) : flat + } + + /// Text after "Not sent · ": the answer as received ("404 Not Found"), "Interrupted", "No connection" for a transport or + /// name-resolution failure (the engine's own text is the tooltip), and otherwise the engine's text itself ("Message too + /// long (PJSIP_EMSGTOOLONG)"). + static func failure(_ message: Message) -> (reason: String, tooltip: String?) { + let code = message.failureCode ?? 0 + let phrase = (message.failureReason ?? "").trimmingCharacters(in: .whitespaces) + if (300...699).contains(code) { return (phrase.isEmpty ? "\(code)" : "\(code) \(phrase)", nil) } + if phrase == Engine.messageInterruptedReason { return (L.messagesErrorInterrupted, nil) } + if phrase.isEmpty { return (L.messagesErrorLocal, nil) } + return isConnectionProblem(phrase) ? (L.messagesErrorLocal, phrase) : (phrase, nil) + } + + /// The texts pjsua gives when the request could not be sent or the host not found (strerror of the socket, DNS and + /// transport errors; a 502/503 the engine turned into code 0). + private static let connectionTexts = [ + "unreachable", "refused", "host is down", "no route", "timed out", "timeout", "connection", "network", "resolve", + "dns", "name or service", "no such host", "broken pipe", "reset", "socket", "transport", "permission denied", + "bad gateway", "service unavailable", "offline", + ] + + static func isConnectionProblem(_ text: String) -> Bool { + let lower = text.lowercased() + return connectionTexts.contains { lower.contains($0) } + } + + /// One line of the thread: a day separator, or a bubble with what goes under it. + struct Row: Identifiable, Equatable { + enum Kind: Equatable { case day(String), bubble(Message) } + var id: String + var kind: Kind + /// The time line under the bubble (the last of its group, and every message still sending or not sent). + var showsMeta = false + /// "Sent": the last outgoing message, accepted. + var showsSent = false + /// Space above: 2 pt inside a group, 8 pt between groups, 0 under a day separator or at the top. + var gap: CGFloat = 0 + } + + /// Messages that follow each other in one direction less than 2 minutes apart, on one day, form a group. + static let groupInterval: TimeInterval = 120 + + static func thread(_ messages: [Message], now: Date = Date(), calendar: Calendar = .current) -> [Row] { + var rows: [Row] = [] + let lastOutgoing = messages.last { $0.direction == .outgoing }?.id + for (i, m) in messages.enumerated() { + let previous = i > 0 ? messages[i - 1] : nil + let next = i + 1 < messages.count ? messages[i + 1] : nil + let newDay = previous.map { !calendar.isDate($0.at, inSameDayAs: m.at) } ?? true + if newDay { rows.append(Row(id: "day-\(m.id)", kind: .day(daySeparator(m.at, now: now, calendar: calendar)))) } + let withPrevious = !newDay && previous.map { grouped($0, m) } == true + let withNext = next.map { calendar.isDate($0.at, inSameDayAs: m.at) && grouped(m, $0) } == true + rows.append(Row( + id: m.id.uuidString, kind: .bubble(m), + showsMeta: !withNext || m.state != .sent, + showsSent: m.id == lastOutgoing && m.state == .sent, + gap: newDay ? 0 : (withPrevious ? 2 : 8))) + } + return rows + } + + private static func grouped(_ a: Message, _ b: Message) -> Bool { + a.direction == b.direction && b.at.timeIntervalSince(a.at) < groupInterval && b.at >= a.at + } +} diff --git a/Sources/MacroSIPApp/Views/Messages/MessagesView.swift b/Sources/MacroSIPApp/Views/Messages/MessagesView.swift new file mode 100644 index 0000000..9ebb71e --- /dev/null +++ b/Sources/MacroSIPApp/Views/Messages/MessagesView.swift @@ -0,0 +1,210 @@ +import SwiftUI +import MacroSIPCore + +/// The Messages tab (SCREENS.md 14): the conversation list, one conversation, or the new-message form. Which one is +/// shown lives in the model, so it is still there after another tab was used. +struct MessagesTab: View { + @Environment(AppModel.self) private var model + + var body: some View { + switch model.messagesPage { + case .list: MessagesView() + case let .conversation(id): ConversationView(id: id).id(id) + case .new: NewMessageView() + } + } +} + +/// 14.1: tool row with New Message, then the conversations, newest activity first. +struct MessagesView: View { + @Environment(AppModel.self) private var model + @Local private var selection: UUID? + @Local private var pendingDelete: UUID? + @FocusState private var listFocused: Bool + + private var selected: Conversation? { selection.flatMap(model.conversation) } + + var body: some View { + VStack(spacing: 0) { + HStack { + Spacer() + Button { model.newMessageFromList() } label: { + Label(L.messagesNew, systemImage: "plus") + } + .controlSize(.small) + .disabled(model.enabledAccounts.isEmpty) + } + .padding(.horizontal, 10).padding(.vertical, 8) + .frame(height: 40) + Divider() + if model.conversations.isEmpty { + VStack(spacing: 4) { + Spacer() + Image(systemName: "bubble.left").font(.system(size: 30, weight: .light)) + .foregroundStyle(Theme.label3).padding(.bottom, 6) + Text(L.messagesEmptyTitle).font(.system(size: 13, weight: .semibold)) + Text(L.messagesEmptyBody) + .font(.system(size: 12)).foregroundStyle(Theme.label2) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + Spacer() + Spacer().frame(height: 20) + } + .padding(.horizontal, 34) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + ScrollViewReader { proxy in + ScrollView { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(model.conversations) { conv in + ConversationRow(conversation: conv, selected: selection == conv.id, + select: { selection = conv.id; listFocused = true }, + open: { model.openConversation(conv.id, focus: true) }, + delete: { pendingDelete = conv.id }) + .id(conv.id) + } + } + .padding(.vertical, 3) + } + .onChange(of: selection) { _, id in if let id { proxy.scrollTo(id) } } + } + .focusable() + .focused($listFocused) + .focusEffectDisabled() + .onKeyPress(.return) { + guard !model.incomingKeyGuard, let c = selected else { return .ignored } + model.openConversation(c.id, focus: true); return .handled + } + .onKeyPress(.upArrow) { move(-1); return .handled } + .onKeyPress(.downArrow) { move(1); return .handled } + .onKeyPress(.delete, phases: .down) { press in + guard press.modifiers.contains(.command), let c = selected else { return .ignored } + pendingDelete = c.id; return .handled + } + } + } + .alert(pendingDeleteTitle, isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } })) { + Button(L.commonCancel, role: .cancel) { pendingDelete = nil } + Button(L.commonDelete, role: .destructive) { + if let id = pendingDelete { model.deleteConversation(id); if selection == id { selection = nil } } + pendingDelete = nil + } + } message: { + Text(L.messagesDeleteBody(pendingDelete.map { model.messages(in: $0).count } ?? 0)) + } + } + + private var pendingDeleteTitle: String { + L.messagesDeleteTitle(pendingDelete.flatMap(model.conversation).map(model.name(for:)) ?? "") + } + + private func move(_ delta: Int) { + let list = model.conversations + guard !list.isEmpty else { return } + guard let current = selection, let i = list.firstIndex(where: { $0.id == current }) else { + selection = list.first?.id; return + } + selection = list[max(0, min(list.count - 1, i + delta))].id + } +} + +/// One conversation (44 pt): avatar, name with the account chip, the last message, the time and the unread count. +struct ConversationRow: View { + @Environment(AppModel.self) private var model + let conversation: Conversation + let selected: Bool + let select: () -> Void + let open: () -> Void + let delete: () -> Void + + var body: some View { + let c = conversation + let name = model.name(for: c) + let last = model.conversationLast[c.id] + let unread = c.unread > 0 + let secondary: Color = selected ? .white.opacity(0.8) : Theme.label2 + HStack(spacing: 9) { + AvatarView(name: name, size: 32, contact: model.contact(for: c)) + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 5) { + Text(name).font(.system(size: 13, weight: unread ? .bold : .medium)).lineLimit(1) + if model.account(c.accountID) != nil { AccountChip(name: model.accountName(c.accountID), selected: selected) } + } + previewLine(last, secondary: secondary) + } + Spacer(minLength: 4) + VStack(alignment: .trailing, spacing: 3) { + Text(last.map { MessageFormat.rowTime($0.at) } ?? "") + .font(.system(size: 11.5, weight: unread ? .medium : .regular)).monospacedDigit().lineLimit(1) + .foregroundStyle(selected ? Color.white.opacity(0.85) : (unread ? Theme.blue : Theme.label2)) + if unread { + Text("\(c.unread)") + .font(.system(size: 10.5, weight: .bold)).foregroundStyle(selected ? Theme.blue : .white) + .padding(.horizontal, 5).frame(minWidth: 18, minHeight: 16) + .background(Capsule().fill(selected ? Color.white : Theme.blue)) + .accessibilityLabel(L.messagesRowUnread(c.unread)) + } else { + Color.clear.frame(width: 1, height: 16) + } + } + } + .padding(.horizontal, 10).padding(.vertical, 6) + .frame(minHeight: 44) + .foregroundStyle(selected ? Color.white : Color.primary) + .background(RoundedRectangle(cornerRadius: 6).fill(selected ? Theme.blue : .clear)) + .padding(.horizontal, 5) + .contentShape(Rectangle()) + .onTapGesture(count: 2) { open() } + .onTapGesture { select() } + .contextMenu { + Button(L.messagesMenuCall) { model.call(c) }.disabled(model.accountState(of: c) != .ready) + if model.contact(for: c) == nil { Button(L.messagesMenuAddContact) { model.addToContacts(c) } } + Button(L.messagesMenuCopyNumber) { model.copyToPasteboard(c.shownNumber) } + Divider() + Button(L.messagesMenuDeleteConversation, role: .destructive, action: delete) + .keyboardShortcut(.delete, modifiers: .command) + } + .accessibilityElement(children: .combine) + .accessibilityLabel(accessibility(name: name, last: last)) + } + + /// Line 2: the last message on one line. A last outgoing message that failed starts with the red "Not sent" marker. + @ViewBuilder + private func previewLine(_ last: Message?, secondary: Color) -> some View { + if let last { + let failed = last.direction == .outgoing && last.state == .failed + HStack(spacing: 0) { + if failed { + Image(systemName: "exclamationmark.circle").font(.system(size: 10.5, weight: .medium)) + .foregroundStyle(selected ? Color.white : Theme.red).padding(.trailing, 2) + Text(L.messagesStatusFailed).fontWeight(.medium).foregroundStyle(selected ? Color.white : Theme.red).lineLimit(1) + .fixedSize() + Text(" · ").foregroundStyle(secondary) + } + Text(MessageFormat.preview(last)).foregroundStyle(secondary).lineLimit(1).truncationMode(.tail) + } + .font(.system(size: 11.5)) + } + } + + private func accessibility(name: String, last: Message?) -> String { + var parts = [name] + if conversation.unread > 0 { parts.append(L.messagesRowUnread(conversation.unread)) } + if let last { parts.append(MessageFormat.preview(last)) } + return parts.joined(separator: ", ") + } +} + +/// The account name as a small grey chip (as in the call log rows). +struct AccountChip: View { + let name: String + var selected = false + + var body: some View { + Text(name) + .font(.system(size: 10)).lineLimit(1) + .padding(.horizontal, 5) + .background(RoundedRectangle(cornerRadius: 4).fill(selected ? Color.white.opacity(0.2) : Theme.fill)) + .fixedSize() + } +} diff --git a/Sources/MacroSIPApp/Views/Messages/NewMessageView.swift b/Sources/MacroSIPApp/Views/Messages/NewMessageView.swift new file mode 100644 index 0000000..227ff82 --- /dev/null +++ b/Sources/MacroSIPApp/Views/Messages/NewMessageView.swift @@ -0,0 +1,220 @@ +import SwiftUI +import MacroSIPCore + +/// 14.3: back and title, the To field with the number field's suggestions, the From line, the composer. +struct NewMessageView: View { + @Environment(AppModel.self) private var model + @Local private var toText = "" + @Local private var picked: NewMessagePrefill? // a suggestion shown as a token followed by its number + @Local private var text = "" + @Local private var highlighted: SuggestionRow.ID? + @Local private var composerFocus = 0 + @Local private var started = false + @Local private var caretToEnd = false + @Local private var accountOverride: AccountID? // an account chosen outside the account row (a call-log entry's) + @Local private var rowChoiceAtStart: AccountID? + @FocusState private var toFocused: Bool + @FocusState private var tokenFocused: Bool + + /// What the To field holds: the picked number, or the typed text. + private var address: String { (picked?.number ?? toText).trimmingCharacters(in: .whitespacesAndNewlines) } + + private var local: [Contact] { + guard picked == nil, toText.contains(where: \.isLetter), !toText.lowercased().hasPrefix("sip:"), + !model.directory.dismissed else { return [] } + return model.suggestions(for: toText) + } + + /// The account the message goes through: the account row's choice, unless the form was opened for another account and + /// the row has not been changed since. + private var composeAccount: AccountConfig? { + if let id = accountOverride, model.selectedAccountID == rowChoiceAtStart, let a = model.account(id), a.enabled { return a } + return model.effectiveAccount + } + + var body: some View { + let account = composeAccount + let local = self.local + let mine = model.directory.owner == .messageTo && picked == nil + let sections = mine ? model.directorySections(excluding: local) : [] + let rows = SuggestionRow.rows(local: local, sections: sections) + let pending = (mine && !model.directory.dismissed) ? model.directory.pending : [] + VStack(spacing: 0) { + header + Divider() + toRow(rows: rows) + fromLine(account) + Spacer(minLength: 0).background(Theme.content) + MessageComposerBar( + text: $text, placeholder: L.messagesComposerPlaceholder, enabled: account != nil, + canSend: account != nil && !address.isEmpty && model.canSend(text), tooLong: model.isTooLong(text), + focusTrigger: composerFocus, autoFocus: false, + onSend: send, onEscape: escape) + } + .overlay(alignment: .topLeading) { + if !rows.isEmpty || !pending.isEmpty { + SuggestionList(local: local, sections: sections, pending: pending, highlighted: highlighted, query: toText, + fill: { pick($0) }, call: { pick($0) }, maxHeight: 270) + .padding(.leading, 44).padding(.trailing, 10) + .offset(y: 74) + } + } + .onAppear { + guard !started else { return } + started = true + rowChoiceAtStart = model.selectedAccountID + if let prefill = model.newMessagePrefill { + model.newMessagePrefill = nil + accountOverride = prefill.account + if let name = prefill.name, !name.isEmpty { picked = prefill } else { toText = prefill.number } + } + if picked != nil { composerFocus &+= 1 } + else { + caretToEnd = !toText.isEmpty + toFocused = true + } + if picked == nil, !toText.isEmpty { model.textChangedForDirectory(toText, owner: .messageTo) } + } + .onChange(of: toFocused) { _, focused in + // A prefilled address is not selected when the field gets the focus: the cursor goes to its end. + guard focused, caretToEnd else { return } + caretToEnd = false + Task { @MainActor in + try? await Task.sleep(for: .milliseconds(60)) + _ = NSApp.sendAction(#selector(NSResponder.moveToEndOfLine(_:)), to: nil, from: nil) + } + } + .onChange(of: toText) { _, t in + highlighted = nil + model.textChangedForDirectory(t, owner: .messageTo) + } + .onDisappear { model.directory.owner = .numberField; model.clearDirectoryResults() } + .background(Theme.content) + } + + private var header: some View { + ZStack { + Text(L.messagesNew).font(.system(size: 13, weight: .semibold)) + HStack { BackButton { model.showMessagesList() }; Spacer() } + } + .padding(.leading, 6).padding(.trailing, 10) + .frame(height: 44) + } + + private func toRow(rows: [SuggestionRow]) -> some View { + HStack(spacing: 6) { + Text(L.messagesNewTo).font(.system(size: 12.5)).foregroundStyle(Theme.label2) + Group { + if let picked { + HStack(spacing: 6) { + Text(picked.name ?? picked.number) + .font(.system(size: 12.5)).foregroundStyle(Theme.blue).lineLimit(1) + .padding(.horizontal, 7).frame(height: 19) + .background(Capsule().fill(Theme.blueTint)) + Text(picked.number).font(.system(size: 12)).monospacedDigit().foregroundStyle(Theme.label2).lineLimit(1) + Spacer(minLength: 0) + } + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + .focusable() + .focused($tokenFocused) + .focusEffectDisabled() + .onTapGesture { tokenFocused = true } + .onKeyPress(.delete) { clearToken(); return .handled } + .onKeyPress(.deleteForward) { clearToken(); return .handled } + } else { + TextField(L.numberPlaceholder, text: $toText) + .textFieldStyle(.plain) + .focused($toFocused) + .onSubmit { + if let id = highlighted, let row = rows.first(where: { $0.id == id }) { pick(row) } + else { commitAddress() } + } + .onKeyPress(.downArrow) { move(1, in: rows) } + .onKeyPress(.upArrow) { move(-1, in: rows) } + .onKeyPress(.escape) { + if !rows.isEmpty || !model.directory.pending.isEmpty { + model.directory.dismissed = true; highlighted = nil; return .handled + } + escape(); return .handled + } + .accessibilityLabel(L.messagesNewTo) + } + } + .font(.system(size: 13)) + .padding(.horizontal, 8).frame(minHeight: 26) + .fieldBackground(focused: toFocused || tokenFocused) + } + .padding(.horizontal, 10).padding(.top, 7).padding(.bottom, 4) + .zIndex(1) + } + + private func fromLine(_ account: AccountConfig?) -> some View { + VStack(spacing: 0) { + HStack(spacing: 5) { + StatusDot(kind: account.map { model.dot(for: $0) } ?? .off, size: 7) + Text(L.messagesNewFrom(account?.displayName ?? L.accountPopupNone)).lineLimit(1) + Spacer(minLength: 0) + } + .font(.system(size: 11)).foregroundStyle(Theme.label2) + .padding(.leading, 37).padding(.trailing, 10).padding(.bottom, 7) + Divider() + } + } + + private func move(_ delta: Int, in rows: [SuggestionRow]) -> KeyPress.Result { + guard !rows.isEmpty else { return .ignored } + let current = highlighted.flatMap { id in rows.firstIndex { $0.id == id } } + let next: Int + if let current { next = (current + delta + rows.count) % rows.count } + else { next = delta > 0 ? 0 : rows.count - 1 } + highlighted = rows[next].id + return .handled + } + + /// A suggestion becomes the token; the cursor goes to the composer. + private func pick(_ row: SuggestionRow) { + let name: String + switch row { + case let .contact(c): name = c.displayName + case let .entry(e): name = e.displayName + } + guard let number = row.number else { return } + picked = NewMessagePrefill(number: number, name: name) + toText = "" + highlighted = nil + model.clearDirectoryResults() + if !switchToExisting() { composerFocus &+= 1 } + } + + private func clearToken() { + picked = nil + toText = "" + toFocused = true + } + + /// Return in the To field with nothing highlighted: the typed address is final, the cursor goes to the composer. + private func commitAddress() { + guard !address.isEmpty else { return } + model.clearDirectoryResults() + if !switchToExisting() { composerFocus &+= 1 } + } + + /// The address already has a conversation on the outgoing account: show it, with the typed text in its composer. + @discardableResult + private func switchToExisting() -> Bool { + guard let account = composeAccount, let dial = DialString.parse(address, account: account), + let existing = model.conversation(account: account.id, address: dial.uri) else { return false } + if !text.isEmpty { model.messageDrafts[existing.id] = text } + model.openConversation(existing.id, focus: true) + return true + } + + private func send() { + guard !address.isEmpty else { return } + // An address that already has a conversation on this account sends into it (`sendNew` reuses it). + if let id = model.sendNew(text: text, to: address, name: picked?.name, account: composeAccount?.id) { model.openConversation(id, focus: true) } + } + + private func escape() { model.showMessagesList() } +} diff --git a/Sources/MacroSIPApp/Views/Settings/AudioPane.swift b/Sources/MacroSIPApp/Views/Settings/AudioPane.swift index 68d5f95..9526c90 100644 --- a/Sources/MacroSIPApp/Views/Settings/AudioPane.swift +++ b/Sources/MacroSIPApp/Views/Settings/AudioPane.swift @@ -114,6 +114,8 @@ struct AudioPane: View { soundToggle(L.audioSoundVoicemail, \.voicemail) FormDivider() soundToggle(L.audioSoundError, \.error) + FormDivider() + soundToggle(L.audioSoundMessage, \.message) } FormGroup(header: L.audioTestHeader) { FormRow(label: L.audioTestRow, help: L.audioTestHelp) { diff --git a/Sources/MacroSIPCore/Engine/Engine+Messages.swift b/Sources/MacroSIPCore/Engine/Engine+Messages.swift new file mode 100644 index 0000000..189b347 --- /dev/null +++ b/Sources/MacroSIPCore/Engine/Engine+Messages.swift @@ -0,0 +1,161 @@ +internal import CPJSUA +import Foundation + +// Text messages: SIP MESSAGE (RFC 3428) outside dialogs, text/plain;charset=utf-8 +// (docs/ENGINE.md "Text messages (SIP MESSAGE)"). Sending: `sendMessage` and +// `pjOnPagerStatus2`; receiving: `pjOnPager2` and the shim's 415 filter (EngineBridge.swift, +// cpjsua_im_send / cpjsua_im_filter_register). + +extension Engine { + /// Longest text `sendMessage` accepts, in UTF-8 bytes: 2800. PJSIP encodes the whole request + /// into PJSIP_MAX_PKT_LEN (4000) bytes and fails a longer one locally ("Message too long"); + /// the headers take about 460 bytes on a LAN and up to about 1050 with a long domain, a + /// display name, a Route and the Authorization header after a 401. Follows + /// PJSIP_MAX_PKT_LEN if config_site.h raises it. + public static let maxMessageBytes = Int(PJSIP_MAX_PKT_LEN) - messageHeaderReserve + /// Room kept for the request line and headers of a MESSAGE. + static let messageHeaderReserve = 1200 + + /// Reason of `.messageStatus(id, .failed(code: 0, reason:))` for a MESSAGE still waiting for + /// its answer when the engine stopped. + public static let messageInterruptedReason = "interrupted" + + /// Sends `text` as `MESSAGE` (Content-Type text/plain;charset=utf-8) from `account` to + /// `dial.uri`. Returns at once; the outcome arrives as `.messageStatus(id, result)` exactly + /// once per id. Throws `.notStarted`, `.unknownAccount`, `.invalidArgument` (empty text, + /// text over `maxMessageBytes` UTF-8 bytes, a target that is not a SIP URI) and `.pjsip` + /// when pjsua cannot create the request (no event follows then). + /// + /// A failure while sending (transport or DNS error) may be reported before this returns. + /// Callers that must match the status to a message they stored use + /// `sendMessage(_:to:from:id:)` with that message's id. + public func sendMessage(_ text: String, to dial: DialString, from account: AccountID) throws -> MessageID { + try sendMessage(text, to: dial, from: account, id: MessageID()) + } + + /// `sendMessage(_:to:from:)` with an id the caller chose (a fresh one per message), so the + /// status event can be matched however early it comes. + public func sendMessage(_ text: String, to dial: DialString, from account: AccountID, + id: MessageID) throws -> MessageID { + try requireStarted() + guard let entry = accounts[account] else { throw EngineError.unknownAccount(account) } + let bytes = Array(text.utf8) + guard !bytes.isEmpty else { throw EngineError.invalidArgument("empty message") } + guard bytes.count <= Engine.maxMessageBytes else { + throw EngineError.invalidArgument("message of \(bytes.count) bytes (at most \(Engine.maxMessageBytes))") + } + guard pjsua_verify_sip_url(dial.uri) == PJ.success else { + throw EngineError.invalidArgument("message target \(dial.uri)") + } + // Registered before the request exists: pjsua may report it before cpjsua_im_send returns. + let token = bridge.allocateSerial() + bridge.addPendingMessage(token, PendingMessage(id: id, accountID: account, target: dial.uri)) + let status = bytes.withUnsafeBytes { raw in + cpjsua_im_send(entry.index, dial.uri, raw.baseAddress?.assumingMemoryBound(to: CChar.self), + UInt32(raw.count), token) + } + if status != PJ.success { + // Still pending: pjsua failed before the transaction existed and will not report it. + // Otherwise on_pager_status2 has already emitted the failure for `id`. + if bridge.takePendingMessage(token) != nil { throw PJ.error(status, "MESSAGE to \(dial.uri)") } + return id + } + emit(.log(level: 4, "engine: \(id) sent to \(dial.uri) (\(bytes.count) bytes)")) + return id + } + + /// `stop`: MESSAGEs whose answer can no longer arrive fail with `messageInterruptedReason`. + /// pjsua_destroy normally reports them itself (503 without a response, mapped to the same + /// result while the bridge is stopping); this catches any it left. Call after pjsua_destroy + /// and before the bridge is detached; emit the returned events after. + func interruptedMessageEvents() -> [EngineEvent] { + bridge.takeAllPendingMessages().map { + .messageStatus($0.id, .failed(code: 0, reason: Engine.messageInterruptedReason)) + } + } +} + +/// An outgoing MESSAGE waiting for its final answer (`EngineBridge.State.pendingMessages`). +struct PendingMessage: Sendable { + var id: MessageID + var accountID: AccountID + /// The Request-URI (for log lines). + var target: String +} + +/// Keeps the text of MESSAGEs out of the log (`pjLogWriter`: os_log, `.log` events, the file +/// log and the diagnostics archive). PJSIP writes it in pjsua_im.c's "Message '' delivered +/// successfully" (level 4) and "Failed to deliver message '': /" (level 3), +/// and in the packet dumps of a MESSAGE request: pjsua's "RX/TX ... bytes ...:\n\n--end +/// msg--" (level 4) and pjsip's "Dropped packet:\n-- end of packet." (level 4). The text +/// or the body becomes "…"; status, reason, request line and headers stay. Where the end of the +/// text is ambiguous, more is replaced, never less. +enum MessageLogRedaction { + static let placeholder = "…" + + static func redact(_ line: String) -> String { + // Every log line passes here: only lines that can carry a MESSAGE are looked at. + guard line.contains("essage '") || line.contains("MESSAGE ") else { return line } + var out = line + if !redactDelivery(&out) { redactPacketBody(&out) } + return out + } + + /// pjsua_im.c's delivery lines. Returns true when the line was one. + private static func redactDelivery(_ s: inout String) -> Bool { + if let start = s.range(of: "Message '"), + let end = s.range(of: "' delivered successfully", options: .backwards), start.upperBound <= end.lowerBound { + s.replaceSubrange(start.upperBound../" (pjsua appends "/"). + var searchEnd = s.endIndex + while let quote = s.range(of: "': ", options: .backwards, range: start.upperBound.. result. 2xx: accepted. A response: its code and reason phrase. No + /// response (`answered == false`): 408 for the transaction timeout, else a local failure + /// (pjsua reports transport errors as 503 and DNS errors as 502 with the pj_strerror text + /// as reason), which becomes code 0 with that text. + static func result(code: Int, reason: String, answered: Bool) -> MessageSendResult { + if (200...299).contains(code) { return .accepted(code: code) } + let text = reason.isEmpty ? PJ.string(pjsip_get_status_text(Int32(code)).pointee) : reason + if !answered && code != 408 { return .failed(code: 0, reason: text) } + return .failed(code: code, reason: text) + } + + /// `on_pager2` -> event, nil for a MESSAGE that is not text/plain or has no body. + /// `mimeType` is pjsua's "type/subtype" (parameters dropped); `from` the From name-addr. + static func incoming(account: AccountID, from: String, mimeType: String, body: String, at: Date) -> IncomingMessage? { + guard mimeType.trimmingCharacters(in: .whitespaces).lowercased() == "text/plain", !body.isEmpty else { return nil } + return IncomingMessage(accountID: account, remote: RemoteParty.parse(from), text: body, receivedAt: at) + } +} diff --git a/Sources/MacroSIPCore/Engine/Engine+Sounds.swift b/Sources/MacroSIPCore/Engine/Engine+Sounds.swift index ab9a71c..5a231ad 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Sounds.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Sounds.swift @@ -20,6 +20,7 @@ enum EventSounds { case .callEnded: return [tone(660, on: 80, off: 40), tone(440, on: 160, off: 0)] case .voicemail: return [tone(880, on: 70, off: 30), tone(880, on: 70, off: 30), tone(1175, on: 120, off: 0)] case .error: return [tone(330, on: 120, off: 60), tone(330, on: 120, off: 0)] + case .message: return [tone(1175, on: 70, off: 60), tone(1175, on: 70, off: 0)] case .keyPress: return nil } } diff --git a/Sources/MacroSIPCore/Engine/Engine.swift b/Sources/MacroSIPCore/Engine/Engine.swift index 426ac9f..71cd00d 100644 --- a/Sources/MacroSIPCore/Engine/Engine.swift +++ b/Sources/MacroSIPCore/Engine/Engine.swift @@ -336,6 +336,8 @@ public actor Engine { bridge.unwatchAll() buddies = [:] pendingHolds = [:] + // pjsua_destroy terminates MESSAGEs still waiting for an answer (reported as interrupted). + bridge.beginStopping() pjsua_call_hangup_all() PJ.warn(pjsua_destroy(), "pjsua_destroy") if transactionTimeoutOverrideMs != nil { cpjsua_set_tsx_timeout(Engine.defaultTransactionTimeoutMs) } @@ -353,8 +355,10 @@ public actor Engine { appliedSoftwareEC = nil let ids = Array(accounts.keys) accounts = [:] + let interrupted = interruptedMessageEvents() bridge.detach(self) for id in ids { emit(.registration(id, .unregistered)) } + for event in interrupted { emit(event) } } private func initPJSUA(_ network: NetworkSettings) throws { @@ -413,6 +417,8 @@ public actor Engine { try withExtendedLifetime(arena) { try PJ.check(pjsua_init(ua, log, media), "pjsua_init") } + // 415 for MESSAGE bodies other than text/plain (pjsua would accept them with 200). + PJ.warn(cpjsua_im_filter_register(), "MESSAGE content-type filter") if dnsServers.contains(where: { $0.port != 53 }) { applyNameservers(dnsServers) } if !dnsServers.isEmpty { emit(.log(level: 3, "engine: DNS SRV via \(dnsServers.map(\.description).joined(separator: ", "))")) diff --git a/Sources/MacroSIPCore/Engine/EngineBridge.swift b/Sources/MacroSIPCore/Engine/EngineBridge.swift index d4b3a2b..c87f88e 100644 --- a/Sources/MacroSIPCore/Engine/EngineBridge.swift +++ b/Sources/MacroSIPCore/Engine/EngineBridge.swift @@ -133,6 +133,13 @@ final class EngineBridge: Sendable { var watched: [UInt64: WatchedBuddy] = [:] /// Latest voicemail indicator per account (RFC 3842 message-summary NOTIFY). var voicemail: [AccountID: VoicemailState] = [:] + /// MESSAGEs sent and not answered yet, by the token in their pjsua user data. Whoever + /// removes an entry reports it: `on_pager_status2`, `sendMessage` after a failure + /// pjsua did not report, or `Engine.stop`. + var pendingMessages: [UInt64: PendingMessage] = [:] + /// `Engine.stop` is destroying pjsua: it terminates pending MESSAGEs itself (503, no + /// response), which are reported as interrupted. + var stopping = false /// Never reset, so CallIDs stay unique across engine restarts in one process. var nextSerial: UInt64 = 1 /// `Engine.setCallOptions` / `start`: read by `on_incoming_call` (single-call mode). @@ -603,6 +610,60 @@ final class EngineBridge: Sendable { } } + // MARK: text messages + + func addPendingMessage(_ token: UInt64, _ message: PendingMessage) { + state.withLock { $0.pendingMessages[token] = message } + } + + /// Removes the entry; nil when its outcome was reported already. + func takePendingMessage(_ token: UInt64) -> PendingMessage? { + state.withLock { $0.pendingMessages.removeValue(forKey: token) } + } + + /// Removes every entry, oldest first (`Engine.stop`: no answer can come any more). + func takeAllPendingMessages() -> [PendingMessage] { + state.withLock { st in + defer { st.pendingMessages = [:] } + return st.pendingMessages.sorted { $0.key < $1.key }.map(\.value) + } + } + + /// `Engine.stop`: from now on a MESSAGE that fails without an answer was interrupted. + func beginStopping() { + state.withLock { $0.stopping = true } + } + + /// The final answer to a MESSAGE we sent: emits `.messageStatus` once, the first time the + /// token is reported. + func reportMessageStatus(token: UInt64, _ reported: MessageSendResult) { + state.withLock { st in + guard let m = st.pendingMessages.removeValue(forKey: token) else { return } + var result = reported + if st.stopping, case .failed(0, _) = reported { + result = .failed(code: 0, reason: Engine.messageInterruptedReason) + } + switch result { + case let .accepted(code): + st.sink?.yield(.log(level: 4, "engine: \(m.id) to \(m.target) accepted (\(code))")) + case let .failed(code, reason): + st.sink?.yield(.log(level: 3, "engine: \(m.id) to \(m.target) failed: \(code > 0 ? "\(code) " : "")\(reason)")) + } + st.sink?.yield(.messageStatus(m.id, result)) + } + } + + /// Emits `.messageReceived` for an account the engine knows (none during shutdown). + func reportIncomingMessage(_ message: IncomingMessage, inCall slot: Int32) { + state.withLock { st in + guard st.accounts.values.contains(where: { $0.id == message.accountID }) else { return } + let sender = message.remote.number.isEmpty ? message.remote.uri : message.remote.number + st.sink?.yield(.log(level: 4, "engine: account \(message.accountID.raw): MESSAGE from \(sender), " + + "\(message.text.utf8.count) bytes\(slot >= 0 ? " (in call \(slot))" : "")")) + st.sink?.yield(.messageReceived(message)) + } + } + /// Logs a warning (os_log + `.log` event) from a callback. func warn(_ text: String) { engineLogger.notice("\(text, privacy: .public)") @@ -737,7 +798,8 @@ func installPJCallbacks(_ cb: inout pjsua_callback) { cb.on_transport_state = pjOnTransportState cb.on_ip_change_progress = pjOnIPChangeProgress cb.on_mwi_info = pjOnMwiInfo - // on_pager (instant messages) stays unset: pjsua answers MESSAGE with 200 and drops it. + cb.on_pager2 = pjOnPager2 // text messages (Engine+Messages.swift) + cb.on_pager_status2 = pjOnPagerStatus2 } /// PJSIP log writer: os_log (subsystem com.hsmm.macrosip, category pjsip) + `.log` event. @@ -745,6 +807,7 @@ func pjLogWriter(_ level: Int32, _ data: UnsafePointer?, _ len: Int32) { guard let data, len > 0 else { return } var text = String(decoding: UnsafeRawBufferPointer(start: data, count: Int(len)), as: UTF8.self) while let last = text.last, last.isNewline { text.removeLast() } // "\r\n" is one Character + text = MessageLogRedaction.redact(text) // no message text in any log let bridge = EngineBridge.shared let type: OSLogType switch level { @@ -1140,6 +1203,45 @@ private func pjOnMwiInfo(_ accID: pjsua_acc_id, _ info: UnsafeMutablePointer`, no tag). +private func pjOnPager2(_ callID: pjsua_call_id, _ from: UnsafePointer?, _ to: UnsafePointer?, + _ contact: UnsafePointer?, _ mimeType: UnsafePointer?, + _ body: UnsafePointer?, _ rdata: UnsafeMutablePointer?, + _ accID: pjsua_acc_id) { + let bridge = EngineBridge.shared + let sender = from.map { PJ.string($0.pointee) } ?? "" + guard let account = bridge.account(for: accID) else { + bridge.emit(.log(level: 4, "engine: MESSAGE from \(sender) for pjsua account \(accID) ignored (not ours)")) + return + } + let mime = mimeType.map { PJ.string($0.pointee) } ?? "" + guard let message = MessageMapping.incoming(account: account.id, from: sender, mimeType: mime, + body: body.map { PJ.string($0.pointee) } ?? "", at: Date()) + else { + bridge.emit(.log(level: 4, "engine: MESSAGE from \(sender) ignored (\(mime.isEmpty ? "no body" : mime))")) + return + } + bridge.reportIncomingMessage(message, inCall: callID) +} + +/// The final answer to a MESSAGE of `Engine.sendMessage` (user data = its token). pjsua calls it +/// once per request: for a response, a timeout (408) and a local failure alike, never for 1xx; +/// after a 401/407 it sends the request again with credentials and reports that one. +private func pjOnPagerStatus2(_ callID: pjsua_call_id, _ to: UnsafePointer?, _ body: UnsafePointer?, + _ userData: UnsafeMutableRawPointer?, _ status: pjsip_status_code, + _ reason: UnsafePointer?, _ tdata: UnsafeMutablePointer?, + _ rdata: UnsafeMutablePointer?, _ accID: pjsua_acc_id) { + let code = Int(status.rawValue) + guard code >= 200 else { return } // not a final answer: the request is still pending + let token = UInt64(UInt(bitPattern: userData)) + guard token != 0 else { return } + let text = reason.map { PJ.string($0.pointee) } ?? "" + EngineBridge.shared.reportMessageStatus(token: token, MessageMapping.result(code: code, reason: text, + answered: rdata != nil)) +} + private func pjOnBuddyState(_ buddyID: pjsua_buddy_id) { PJ.registerThread() guard let buddy = BuddySnapshot.read(buddyID) else { return } diff --git a/Sources/MacroSIPCore/Engine/EngineTypes.swift b/Sources/MacroSIPCore/Engine/EngineTypes.swift index cc2bdc4..0c10496 100644 --- a/Sources/MacroSIPCore/Engine/EngineTypes.swift +++ b/Sources/MacroSIPCore/Engine/EngineTypes.swift @@ -173,9 +173,55 @@ public enum EngineEvent: Sendable { /// whether messages wait and the new/old voice message counts. Emitted when the /// indicator changed (and on the first NOTIFY); `Engine.voicemailState(for:)` has the latest. case voicemail(AccountID, waiting: Bool, new: Int, old: Int) + /// A text/plain MESSAGE arrived on one of our accounts (docs/ENGINE.md "Text messages"). + case messageReceived(IncomingMessage) + /// The final outcome of `Engine.sendMessage`, exactly once per id. + case messageStatus(MessageID, MessageSendResult) case log(level: Int, String) } +// MARK: - Text messages (SIP MESSAGE, release 26.3) + +/// Token of one outgoing MESSAGE (`Engine.sendMessage`); `.messageStatus` names it. +public struct MessageID: Hashable, Sendable, CustomStringConvertible { + public let raw: UUID + + public init(raw: UUID = UUID()) { + self.raw = raw + } + + public var description: String { "message#\(raw.uuidString.prefix(8))" } +} + +/// A MESSAGE that arrived on one of our accounts (text/plain only). +public struct IncomingMessage: Equatable, Sendable { + public var accountID: AccountID + /// From the From header: `number` is the user part ("+375291234567", "102"), `uri` the + /// sender's URI (the reply target), `displayName` the From display name, if any. + public var remote: RemoteParty + /// The body decoded as UTF-8 (with `charset=utf-8` or without a charset); invalid bytes + /// become U+FFFD. + public var text: String + public var receivedAt: Date + + public init(accountID: AccountID, remote: RemoteParty, text: String, receivedAt: Date) { + self.accountID = accountID + self.remote = remote + self.text = text + self.receivedAt = receivedAt + } +} + +/// How a MESSAGE we sent ended (`.messageStatus`). +public enum MessageSendResult: Equatable, Sendable { + /// 2xx from the server or the peer: accepted, which does not mean delivered to a phone. + case accepted(code: Int) + /// Final failure: the SIP code and reason phrase of the answer (404 "Not Found", 480, + /// 403...), 408 "Request Timeout" when nothing answered, or code 0 with the PJSIP error + /// text when the request could not be sent at all (transport or DNS error, engine stopped). + case failed(code: Int, reason: String) +} + /// The latest voicemail indicator of an account (`Engine.voicemailState(for:)`). public struct VoicemailState: Equatable, Sendable { /// `Messages-Waiting: yes`. @@ -209,6 +255,8 @@ public enum SoundEvent: Equatable, Sendable { case voicemail /// Two low beeps. case error + /// Two short high beeps (a text message arrived). + case message } public enum EngineError: Error, Equatable, Sendable, CustomStringConvertible { diff --git a/Sources/MacroSIPCore/Engine/PJSupport.swift b/Sources/MacroSIPCore/Engine/PJSupport.swift index a20ee45..03488ad 100644 --- a/Sources/MacroSIPCore/Engine/PJSupport.swift +++ b/Sources/MacroSIPCore/Engine/PJSupport.swift @@ -179,23 +179,58 @@ extension AccountID { } extension RemoteParty { - /// Parses a printed name-addr such as `"Alice" `. + /// Parses a printed name-addr such as `"Alice" ` (also the + /// sender of a MESSAGE, whose `uri` is the reply target). The URI is the last `<...>` outside + /// the quoted display name (`"x " ` -> `sip:a@b`); a quoted name is unescaped + /// (`"A \"B\""` -> `A "B"`), an unquoted one trimmed. Without brackets the whole value is the URI. static func parse(_ raw: String) -> RemoteParty { let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) var name: String? var uri = trimmed - if let lt = trimmed.firstIndex(of: "<"), - let gt = trimmed[lt...].firstIndex(of: ">") { - uri = String(trimmed[trimmed.index(after: lt)..` pair outside double quotes (backslash escapes inside quotes). + private static func lastAngleBrackets(_ s: String) -> (String.Index, String.Index)? { + var inQuotes = false + var escaped = false + var open: String.Index? + var pair: (String.Index, String.Index)? + for i in s.indices { + let ch = s[i] + if inQuotes { + if escaped { escaped = false } else if ch == "\\" { escaped = true } else if ch == "\"" { inQuotes = false } + continue + } + switch ch { + case "\"": inQuotes = true + case "<": open = i + case ">": + if let o = open { pair = (o, i); open = nil } + default: break + } + } + return pair + } + + /// A display name as printed: a quoted string loses its quotes and backslash escapes + /// (RFC 3261 quoted-pair); anything after the closing quote is ignored. A token is kept. + private static func displayName(_ s: String) -> String { + guard s.first == "\"" else { return s } + var out = "" + var escaped = false + for ch in s.dropFirst() { + if escaped { out.append(ch); escaped = false } else if ch == "\\" { escaped = true } else if ch == "\"" { break } else { out.append(ch) } + } + return out.trimmingCharacters(in: .whitespaces) + } } /// `Call-Info` header parsing (the C parser in shim.c, also used on incoming INVITEs). diff --git a/Sources/MacroSIPCore/Model/AppSettings.swift b/Sources/MacroSIPCore/Model/AppSettings.swift index 7b7d3ed..c563c98 100644 --- a/Sources/MacroSIPCore/Model/AppSettings.swift +++ b/Sources/MacroSIPCore/Model/AppSettings.swift @@ -27,12 +27,16 @@ public struct SoundEventSettings: Codable, Equatable, Sendable { public var voicemail: Bool /// `.error` when a call or registration fails. public var error: Bool + /// `.message` when a text message arrives. + public var message: Bool - public init(callEvents: Bool = false, keyPress: Bool = false, voicemail: Bool = false, error: Bool = false) { + public init(callEvents: Bool = false, keyPress: Bool = false, voicemail: Bool = false, error: Bool = false, + message: Bool = false) { self.callEvents = callEvents self.keyPress = keyPress self.voicemail = voicemail self.error = error + self.message = message } /// Missing keys decode as off. @@ -42,6 +46,7 @@ public struct SoundEventSettings: Codable, Equatable, Sendable { keyPress = (try? c.decodeIfPresent(Bool.self, forKey: .keyPress)) ?? false voicemail = (try? c.decodeIfPresent(Bool.self, forKey: .voicemail)) ?? false error = (try? c.decodeIfPresent(Bool.self, forKey: .error)) ?? false + message = (try? c.decodeIfPresent(Bool.self, forKey: .message)) ?? false } } diff --git a/Sources/MacroSIPCore/Model/Message.swift b/Sources/MacroSIPCore/Model/Message.swift new file mode 100644 index 0000000..e8312d4 --- /dev/null +++ b/Sources/MacroSIPCore/Model/Message.swift @@ -0,0 +1,194 @@ +import Foundation + +public enum MessageDirection: String, Codable, Sendable { case incoming, outgoing } + +/// `sent` means the SIP server or peer accepted the message (2xx), not that a phone received it. +public enum MessageState: String, Codable, Sendable { case sending, sent, failed } + +public struct Conversation: Codable, Identifiable, Equatable, Sendable { + public var id: UUID + public var accountID: AccountID + /// What the UI shows and what a reply dials (user part, e.g. "+375291234567" or "102"). + public var remoteNumber: String + /// Full URI of the peer as last seen. + public var remoteURI: String + /// The peer's host when it is part of who the peer is: an explicit host that is not the account's own domain, and the + /// host of every non-numeric user. nil for numbers dialled through the account. Absent in older files. + public var remoteHost: String? + /// From display name of the last incoming message, if any. Absent in older files. + public var remoteDisplayName: String? + /// Resolved when the conversation is created, if a contact matches. + public var contactID: UUID? + public var lastActivityAt: Date + /// Incoming messages not yet read. Absent in older files. + public var unread: Int + + public init( + id: UUID = UUID(), + accountID: AccountID, + remoteNumber: String, + remoteURI: String = "", + remoteHost: String? = nil, + remoteDisplayName: String? = nil, + contactID: UUID? = nil, + lastActivityAt: Date = Date(), + unread: Int = 0 + ) { + self.id = id + self.accountID = accountID + self.remoteNumber = remoteNumber + self.remoteURI = remoteURI + self.remoteHost = remoteHost + self.remoteDisplayName = remoteDisplayName + self.contactID = contactID + self.lastActivityAt = lastActivityAt + self.unread = unread + } + + private enum CodingKeys: String, CodingKey { + case id, accountID, remoteNumber, remoteURI, remoteHost, remoteDisplayName, contactID, lastActivityAt, unread + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(UUID.self, forKey: .id) + accountID = try c.decode(AccountID.self, forKey: .accountID) + remoteNumber = try c.decode(String.self, forKey: .remoteNumber) + remoteURI = try c.decodeIfPresent(String.self, forKey: .remoteURI) ?? "" + remoteHost = try c.decodeIfPresent(String.self, forKey: .remoteHost) + remoteDisplayName = try c.decodeIfPresent(String.self, forKey: .remoteDisplayName) + contactID = try c.decodeIfPresent(UUID.self, forKey: .contactID) + lastActivityAt = try c.decode(Date.self, forKey: .lastActivityAt) + unread = try c.decodeIfPresent(Int.self, forKey: .unread) ?? 0 + } +} + +extension Conversation { + /// What the UI shows when the peer has no name: the number, or `user@host` where the host tells peers apart. + public var shownNumber: String { remoteHost.map { "\(remoteNumber)@\($0)" } ?? remoteNumber } + + /// Whether this conversation is with the peer `address` on `account`. + public func matches(account: AccountID, address: ConversationAddress) -> Bool { + accountID == account && address.matches(user: remoteNumber, host: remoteHost) + } +} + +/// Who a message is to or from, as a conversation tells peers apart: the user and, where it matters, the host. +/// - A number (digits, `+`, `*`, `#` and the usual separators) is compared by its digits: `+375 29 123-45-67` and +/// `375291234567` are one number, and a number with a country prefix meets the same number without it (one ends with +/// the other and the shorter has at least 7 digits); shorter numbers (extensions) must be equal. The host counts only when it is explicit and not +/// the account's own domain (an unknown domain: never). +/// - Any other user (`alice`, `bob.smith`) is compared as written, case-insensitively, together with its host, which +/// always counts. +public struct ConversationAddress: Equatable, Sendable { + public var user: String + public var host: String? + + /// Fewest digits for which one number may match another as its suffix. + public static let minSuffixDigits = 7 + + /// `raw` is a number, a `sip:`/`sips:`/`tel:` URI or `user@host`; `accountDomain` the account's domain. + public init(_ raw: String, accountDomain: String = "") { + let s = raw.trimmingCharacters(in: .whitespacesAndNewlines) + let lower = s.lowercased() + var user = s + var host: String? + if lower.hasPrefix("tel:") { + user = String(s.dropFirst(4)) + } else if lower.hasPrefix("sip:") || lower.hasPrefix("sips:") || s.contains("@") { + user = DialString.userPart(of: s) + if let at = s.lastIndex(of: "@") { + let h = Self.bareHost(String(s[s.index(after: at)...])) + host = h.isEmpty ? nil : h + } + } + self.init(user: user, host: host, accountDomain: accountDomain) + } + + /// The user as written and the host found next to it (nil when none). + init(user: String, host: String?, accountDomain: String) { + var host = host + if Self.isNumber(user) { + self.user = DialString.normalizeNumber(user) + // The host of a number counts only when it is explicit and differs from the account's domain (unknown: never). + if let h = host, accountDomain.isEmpty || h == Self.bareHost(accountDomain) { host = nil } + } else { + self.user = user.lowercased() + } + self.host = host + } + + /// The peer of a conversation: `number` is the user part, `uri` (may be empty) says where it lives. + public init(number: String, uri: String, accountDomain: String) { + let fromURI = ConversationAddress(uri, accountDomain: accountDomain) + if number.isEmpty { self = fromURI; return } + let plain = ConversationAddress(number, accountDomain: accountDomain) + if plain.host != nil || uri.isEmpty { self = plain; return } + // `number` is a bare user: the host is the URI's (and numbers drop it when it is the account's own). + let host = uri.lastIndex(of: "@").map { Self.bareHost(String(uri[uri.index(after: $0)...])) }.flatMap { $0.isEmpty ? nil : $0 } + self.init(user: number, host: host, accountDomain: accountDomain) + } + + static func isNumber(_ user: String) -> Bool { + !user.isEmpty && user.allSatisfy { "0123456789+*#-.() ".contains($0) } && user.contains(where: \.isNumber) + } + + /// Host without port, parameters and header part, lower case. + static func bareHost(_ s: String) -> String { + String(s.prefix { !";?>:".contains($0) }).trimmingCharacters(in: .whitespaces).lowercased() + } + + func matches(user other: String, host otherHost: String?) -> Bool { + guard host == otherHost.map({ $0.lowercased() }) else { return false } + if Self.isNumber(user) || Self.isNumber(other) { + guard Self.isNumber(user), Self.isNumber(other) else { return false } + return Self.sameNumber(user, DialString.normalizeNumber(other)) + } + return user == other.lowercased() + } + + /// Equal digits, or one number is the tail of the other and at least `minSuffixDigits` long (country prefix, trunk + /// prefix). `*` and `#` codes are compared as written. + static func sameNumber(_ a: String, _ b: String) -> Bool { + if a == b { return true } + let da = a.filter(\.isNumber), db = b.filter(\.isNumber) + guard !da.isEmpty, !db.isEmpty, a.allSatisfy({ $0.isNumber || $0 == "+" }), b.allSatisfy({ $0.isNumber || $0 == "+" }) else { return false } + if da == db { return true } + let (short, long) = da.count <= db.count ? (da, db) : (db, da) + return short.count >= minSuffixDigits && long.hasSuffix(short) + } +} + +public struct Message: Codable, Identifiable, Equatable, Sendable { + public var id: UUID + public var conversationID: UUID + public var direction: MessageDirection + public var text: String + /// Received, or when sending started. + public var at: Date + /// Incoming messages are always `.sent`. + public var state: MessageState + /// For `.failed`: the SIP code, or 0 for a local failure. + public var failureCode: Int? + public var failureReason: String? + + public init( + id: UUID = UUID(), + conversationID: UUID, + direction: MessageDirection, + text: String, + at: Date = Date(), + state: MessageState = .sent, + failureCode: Int? = nil, + failureReason: String? = nil + ) { + self.id = id + self.conversationID = conversationID + self.direction = direction + self.text = text + self.at = at + self.state = state + self.failureCode = failureCode + self.failureReason = failureReason + } +} diff --git a/Sources/MacroSIPCore/Product.swift b/Sources/MacroSIPCore/Product.swift index 2d60087..365faa0 100644 --- a/Sources/MacroSIPCore/Product.swift +++ b/Sources/MacroSIPCore/Product.swift @@ -14,5 +14,5 @@ public enum Product { return fallbackVersion }() - public static let fallbackVersion = "26.2.0" + public static let fallbackVersion = "26.3.0" } diff --git a/Sources/MacroSIPCore/Storage/MessageStore.swift b/Sources/MacroSIPCore/Storage/MessageStore.swift new file mode 100644 index 0000000..5ff6d41 --- /dev/null +++ b/Sources/MacroSIPCore/Storage/MessageStore.swift @@ -0,0 +1,272 @@ +import Foundation +import os + +/// messages.json as stored: conversations and their messages in one file. Each array is read element by element: a +/// record that cannot be decoded is skipped and counted, the rest stays (as `ContactList` does for contacts). +struct MessageFile: Codable, Sendable { + var conversations: [Conversation] = [] + var messages: [Message] = [] + /// Records the decoder could not read (only set by decoding). + var skipped = 0 + + init(conversations: [Conversation] = [], messages: [Message] = []) { + self.conversations = conversations + self.messages = messages + } + + private enum CodingKeys: String, CodingKey { case conversations, messages } + private struct Skip: Decodable {} + + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + func elements(_ key: CodingKeys, _ type: T.Type) throws -> ([T], Int) { + guard c.contains(key) else { return ([], 0) } + var list = try c.nestedUnkeyedContainer(forKey: key) + var out: [T] = [], bad = 0 + while !list.isAtEnd { + if let item = try? list.decode(T.self) { out.append(item) } + else { _ = try? list.decode(Skip.self); bad += 1 } + } + return (out, bad) + } + let (conversations, badConversations) = try elements(.conversations, Conversation.self) + let (messages, badMessages) = try elements(.messages, Message.self) + self.conversations = conversations + self.messages = messages + skipped = badConversations + badMessages + } + + func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(conversations, forKey: .conversations) + try c.encode(messages, forKey: .messages) + } +} + +/// Conversations and messages (messages.json). The whole file is held in memory after the first access and written +/// through on every change: one write per operation, no reads. Safe from any thread. +public final class MessageStore: @unchecked Sendable { + private let store: JSONStore + private let directory: URL + private let contacts: ContactStore? + private let limit: @Sendable () -> Int + private let lock = NSLock() + private var cache: MessageFile? + private static let log = Logger(subsystem: "com.hsmm.macrosip", category: "messages") + + /// `contacts`: used to resolve `contactID` when a conversation is created. `limit`: max messages kept overall + /// (default 5000); the oldest are dropped and conversations left without messages are pruned. + public init(directory: URL, contacts: ContactStore? = nil, limit: @escaping @Sendable () -> Int = { 5000 }) { + self.directory = directory + store = JSONStore(directory: directory, name: "messages", default: MessageFile()) + self.contacts = contacts + self.limit = limit + } + + // MARK: - Access + + /// The file, read on first use. A file with unreadable records keeps a copy of the original and is rewritten + /// without them; a file that is not JSON at all is moved aside by `JSONStore.load`. + private func loaded() -> MessageFile { + if let cache { return cache } + var file = store.load() + if file.skipped > 0 { + if let data = try? Data(contentsOf: store.fileURL) { + let stamp = ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: "-") + let copy = directory.appendingPathComponent("messages.damaged-\(stamp).json") + try? data.write(to: copy) + Self.log.error("messages.json: \(file.skipped) unreadable records skipped, original kept as \(copy.lastPathComponent, privacy: .public)") + } + file.skipped = 0 + try? store.save(file) + } + cache = file + return file + } + + private func read(_ body: (MessageFile) -> T) -> T { + lock.lock(); defer { lock.unlock() } + return body(loaded()) + } + + /// Applies `body` to a copy, writes it, and only then keeps it: a failed write leaves memory and file as they were. + @discardableResult + private func change(_ body: (inout MessageFile) throws -> T) throws -> T { + lock.lock(); defer { lock.unlock() } + var file = loaded() + let result = try body(&file) + try store.save(file) + cache = file + return result + } + + /// Newest activity first. + public func conversations() -> [Conversation] { + read { $0.conversations.sorted { $0.lastActivityAt > $1.lastActivityAt } } + } + + /// Oldest first; messages with equal dates keep their insertion order. + public func messages(in conversation: UUID) -> [Message] { + read { Self.ordered($0.messages.filter { $0.conversationID == conversation }) } + } + + public func allMessages() -> [Message] { read { Self.ordered($0.messages) } } + + /// The newest message of every conversation (what the list previews), in one pass. + public func lastMessages() -> [UUID: Message] { + read { file in + var best: [UUID: (Message, Int)] = [:] + for (i, m) in file.messages.enumerated() { + if let b = best[m.conversationID], (b.0.at, b.1) > (m.at, i) { continue } + best[m.conversationID] = (m, i) + } + return best.mapValues(\.0) + } + } + + public var unreadTotal: Int { read { $0.conversations.reduce(0) { $0 + $1.unread } } } + + private static func ordered(_ list: [Message]) -> [Message] { + list.enumerated().sorted { ($0.element.at, $0.offset) < ($1.element.at, $1.offset) }.map(\.element) + } + + // MARK: - Conversations + + /// Finds the conversation of (account, peer) or creates it. The peer is told apart by `ConversationAddress`: the user + /// (numbers by their digits, so `+375291234567` and `375 29 123-45-67` meet) and the host where it matters (an explicit + /// host other than `accountDomain`, or any host of a non-numeric user). A non-empty `remoteURI` or `displayName` + /// replaces the stored one. `remoteNumber` is the user part; `remoteURI` may carry the host. + @discardableResult + public func conversation(account: AccountID, remoteNumber: String, remoteURI: String, displayName: String?, + accountDomain: String = "") throws -> Conversation { + try change { file in + Self.findOrCreate(&file, account: account, remoteNumber: remoteNumber, remoteURI: remoteURI, displayName: displayName, + accountDomain: accountDomain, contactID: contacts?.findUnique(byNumber: remoteNumber)?.id) + } + } + + /// `conversation(...)` and the first message in one write; `message` gets the conversation's id. Nothing is + /// stored when the write fails. + @discardableResult + public func conversation(account: AccountID, remoteNumber: String, remoteURI: String, displayName: String?, + accountDomain: String = "", appending message: (UUID) -> Message) throws -> (Conversation, Message) { + let max = Swift.max(1, limit()) + let contactID = contacts?.findUnique(byNumber: remoteNumber)?.id + return try change { file in + let conv = Self.findOrCreate(&file, account: account, remoteNumber: remoteNumber, remoteURI: remoteURI, displayName: displayName, + accountDomain: accountDomain, contactID: contactID) + let m = message(conv.id) + Self.appendLocked(&file, m, max: max) + return (file.conversations.first { $0.id == conv.id } ?? conv, m) + } + } + + private static func findOrCreate(_ file: inout MessageFile, account: AccountID, remoteNumber: String, remoteURI: String, + displayName: String?, accountDomain: String, contactID: UUID?) -> Conversation { + let key = ConversationAddress(number: remoteNumber, uri: remoteURI, accountDomain: accountDomain) + if let i = file.conversations.firstIndex(where: { $0.matches(account: account, address: key) }) { + if !remoteURI.isEmpty { file.conversations[i].remoteURI = remoteURI } + if let name = displayName, !name.isEmpty { file.conversations[i].remoteDisplayName = name } + if file.conversations[i].contactID == nil { file.conversations[i].contactID = contactID } + return file.conversations[i] + } + let c = Conversation( + accountID: account, remoteNumber: remoteNumber, remoteURI: remoteURI, remoteHost: key.host, + remoteDisplayName: (displayName?.isEmpty ?? true) ? nil : displayName, + contactID: contactID, lastActivityAt: Date(), unread: 0) + file.conversations.append(c) + return c + } + + // MARK: - Messages + + /// Adds the message, bumps the conversation's activity and, for an incoming one, its unread count. + @discardableResult + public func append(_ message: Message) throws -> Message { + let max = Swift.max(1, limit()) + try change { Self.appendLocked(&$0, message, max: max) } + return message + } + + private static func appendLocked(_ file: inout MessageFile, _ message: Message, max: Int) { + file.messages.append(message) + if let i = file.conversations.firstIndex(where: { $0.id == message.conversationID }) { + if message.at > file.conversations[i].lastActivityAt { file.conversations[i].lastActivityAt = message.at } + if message.direction == .incoming { file.conversations[i].unread += 1 } + } + prune(&file, max: max) + } + + private static func prune(_ file: inout MessageFile, max: Int) { + if file.messages.count > max { + let drop = file.messages.enumerated() + .sorted { ($0.element.at, $0.offset) < ($1.element.at, $1.offset) } + .prefix(file.messages.count - max).map(\.offset) + let dropSet = Set(drop) + file.messages = file.messages.enumerated().filter { !dropSet.contains($0.offset) }.map(\.element) + let alive = Set(file.messages.map(\.conversationID)) + file.conversations.removeAll { !alive.contains($0.id) } + clampUnread(&file) + } + } + + /// A conversation never has more unread messages than incoming messages left in it. + private static func clampUnread(_ file: inout MessageFile) { + var incoming: [UUID: Int] = [:] + for m in file.messages where m.direction == .incoming { incoming[m.conversationID, default: 0] += 1 } + for i in file.conversations.indices where file.conversations[i].unread > (incoming[file.conversations[i].id] ?? 0) { + file.conversations[i].unread = incoming[file.conversations[i].id] ?? 0 + } + } + + /// Changes one message (state transitions). A message that is gone is ignored. + public func update(_ id: UUID, _ change: (inout Message) -> Void) throws { + try self.change { file in + if let i = file.messages.firstIndex(where: { $0.id == id }) { change(&file.messages[i]) } + } + } + + /// Retry: `old` is removed and `new` added in one write, so the message moves to the end with its new time. + /// Nothing changes when the write fails. + public func replace(message old: UUID, with new: Message) throws { + let max = Swift.max(1, limit()) + try change { file in + file.messages.removeAll { $0.id == old } + Self.appendLocked(&file, new, max: max) + Self.clampUnread(&file) + } + } + + public func markRead(_ conversation: UUID) throws { + try change { file in + if let i = file.conversations.firstIndex(where: { $0.id == conversation }) { file.conversations[i].unread = 0 } + } + } + + public func remove(message id: UUID) throws { + try change { file in + file.messages.removeAll { $0.id == id } + Self.clampUnread(&file) + } + } + + public func remove(conversation id: UUID) throws { + try change { file in + file.conversations.removeAll { $0.id == id } + file.messages.removeAll { $0.conversationID == id } + } + } + + public func clear() throws { try change { $0 = MessageFile() } } + + /// At launch: every message still `.sending` becomes `.failed(0, "interrupted")` so the UI can offer Retry. + public func failInterruptedSends() throws { + try change { file in + for i in file.messages.indices where file.messages[i].state == .sending { + file.messages[i].state = .failed + file.messages[i].failureCode = 0 + file.messages[i].failureReason = "interrupted" + } + } + } +} diff --git a/Sources/macrosip-cli/main.swift b/Sources/macrosip-cli/main.swift index 8e0ed12..7650c1d 100644 --- a/Sources/macrosip-cli/main.swift +++ b/Sources/macrosip-cli/main.swift @@ -128,6 +128,14 @@ func describe(_ e: EngineEvent) -> String { case let .network(state): return "[network] \(state == .online ? "online" : "offline")" case let .voicemail(id, waiting, new, old): return "[voicemail] \(id.raw.uuidString.prefix(8)) \(waiting ? "waiting" : "none") new=\(new) old=\(old)" + case let .messageReceived(m): + let from = m.remote.displayName.map { "\"\($0)\" <\(m.remote.uri)>" } ?? m.remote.uri + return "[messageReceived] \(m.accountID.raw.uuidString.prefix(8)) from \(from): \(m.text)" + case let .messageStatus(id, result): + switch result { + case let .accepted(code): return "[messageStatus] \(id) accepted \(code)" + case let .failed(code, reason): return "[messageStatus] \(id) failed \(code) \(reason)" + } case let .log(level, text): return text.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) .map { " pj\(level)| \($0)" }.joined(separator: "\n") diff --git a/Tests/MacroSIPCoreTests/EngineMessageTests.swift b/Tests/MacroSIPCoreTests/EngineMessageTests.swift new file mode 100644 index 0000000..76569e7 --- /dev/null +++ b/Tests/MacroSIPCoreTests/EngineMessageTests.swift @@ -0,0 +1,652 @@ +import Foundation +import os +import Testing +@testable import MacroSIPCore + +// Text messages (docs/ENGINE.md "Text messages (SIP MESSAGE)"): sending with each outcome, +// receiving (Cyrillic from chan_dongle, the 415 filter, account mapping, inside a call), +// validation, and the pure mappings. + +// MARK: - MESSAGE stub + +/// A SIP peer on 127.0.0.1 (one UDP socket, random port) for the MESSAGE tests. Every MESSAGE +/// it receives is recorded byte for byte and answered with `answer` (a status line such as +/// "404 Not Found"; nil = no answer at all, so the sender times out). It answers an INVITE with +/// 200 and a PCMU SDP (it never sends RTP) and remembers that dialog for `sendInDialogMessage`; +/// any other request gets 200. It sends MESSAGEs of its own as Asterisk/chan_dongle does +/// (`sendMessage`) and records the status lines of the answers by Call-ID. +final class MessageStub: Sendable { + struct Request: Sendable { + var requestLine: String + /// Header lines as received ("Content-Type: text/plain;charset=utf-8"). + var headers: [String] + var body: [UInt8] + /// Size of the whole datagram. + var size: Int + + /// Value of the first header called `name` (case-insensitive), trimmed. + func header(_ name: String) -> String? { + for line in headers { + guard let colon = line.firstIndex(of: ":"), + line[..(initialState: "200 OK") + private let received = OSAllocatedUnfairLock(initialState: [Request]()) + private let answers = OSAllocatedUnfairLock(initialState: [Response]()) + private let dialog = OSAllocatedUnfairLock(initialState: nil) + + /// Status line for MESSAGEs ("200 OK"); nil = never answer. + var answer: String? { + get { answerLock.withLock { $0 } } + set { answerLock.withLock { $0 = newValue } } + } + + /// MESSAGE requests received, retransmissions included, in order. + var messages: [Request] { received.withLock { $0 } } + var responses: [Response] { answers.withLock { $0 } } + var hasDialog: Bool { dialog.withLock { $0 != nil } } + + /// Status lines of the answers to the request with this Call-ID. + func responses(to callID: String) -> [String] { + responses.filter { $0.callID == callID }.map(\.statusLine) + } + + init() throws { + let sock = socket(AF_INET, SOCK_DGRAM, 0) + guard sock >= 0 else { throw EngineError.unsupported("socket") } + var addr = sockaddr_in() + addr.sin_len = UInt8(MemoryLayout.size) + addr.sin_family = sa_family_t(AF_INET) + addr.sin_addr.s_addr = inet_addr("127.0.0.1") + var len = socklen_t(MemoryLayout.size) + let ok = withUnsafeMutablePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + bind(sock, $0, len) == 0 && getsockname(sock, $0, &len) == 0 + } + } + guard ok else { close(sock); throw EngineError.unsupported("bind") } + var tv = timeval(tv_sec: 0, tv_usec: 100_000) + setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, socklen_t(MemoryLayout.size)) + fd = sock + port = UInt16(bigEndian: addr.sin_port) + Thread.detachNewThread { [self] in self.serve() } + } + + func stop() { stopped.withLock { $0 = true } } + + private func serve() { + var buf = [UInt8](repeating: 0, count: 65_536) + while !stopped.withLock({ $0 }) { + var from = sockaddr_in() + var fromLen = socklen_t(MemoryLayout.size) + let n = withUnsafeMutablePointer(to: &from) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { recvfrom(fd, &buf, buf.count, 0, $0, &fromLen) } + } + guard n > 0 else { continue } + handle(Array(buf[0..") { + target = String(contact[contact.index(after: lt).."], contentType: "application/sdp", body: sdp) + default: + reply("200 OK") + } + } + + /// Sends a MESSAGE to the engine on 127.0.0.1:`port` the way Asterisk relays an SMS from + /// chan_dongle: `From: "" @127.0.0.1:>`, To and + /// Request-URI `sip:@127.0.0.1:`, the given Content-Type (nil: none) and body. + /// Returns the Call-ID (answers: `responses(to:)`). + @discardableResult + func sendMessage(toPort port: Int, user: String, fromNumber: String, displayName: String?, + contentType: String?, body: [UInt8]) -> String { + let callID = "msg-\(UInt32.random(in: 1...UInt32.max))@127.0.0.1" + let name = displayName.map { "\"\($0)\" " } ?? "" + var head = "MESSAGE sip:\(user)@127.0.0.1:\(port) SIP/2.0\r\n" + head += "Via: SIP/2.0/UDP 127.0.0.1:\(self.port);branch=z9hG4bK-msg-\(UInt32.random(in: 1...UInt32.max));rport\r\n" + head += "Max-Forwards: 70\r\n" + head += "From: \(name);tag=msg-from-\(UInt32.random(in: 1...UInt32.max))\r\n" + head += "To: \r\n" + head += "Call-ID: \(callID)\r\nCSeq: 1 MESSAGE\r\n" + if let contentType { head += "Content-Type: \(contentType)\r\n" } + head += "Content-Length: \(body.count)\r\n\r\n" + send(Array(head.utf8) + body, toPort: port) + return callID + } + + /// Sends a MESSAGE inside the call the engine set up with the stub (after its INVITE). + /// Returns the Call-ID, nil when there is no call. + @discardableResult + func sendInDialogMessage(toPort port: Int, contentType: String, body: [UInt8]) -> String? { + guard let d = dialog.withLock({ d -> Dialog? in + d?.cseq += 1 + return d + }) else { return nil } + var head = "MESSAGE \(d.target) SIP/2.0\r\n" + head += "Via: SIP/2.0/UDP 127.0.0.1:\(self.port);branch=z9hG4bK-msg-\(UInt32.random(in: 1...UInt32.max));rport\r\n" + head += "Max-Forwards: 70\r\nFrom: \(d.local)\r\nTo: \(d.remote)\r\n" + head += "Call-ID: \(d.callID)\r\nCSeq: \(d.cseq) MESSAGE\r\n" + head += "Content-Type: \(contentType)\r\nContent-Length: \(body.count)\r\n\r\n" + send(Array(head.utf8) + body, toPort: port) + return d.callID + } + + private func send(_ bytes: [UInt8], toPort port: Int) { + var dest = sockaddr_in() + dest.sin_len = UInt8(MemoryLayout.size) + dest.sin_family = sa_family_t(AF_INET) + dest.sin_addr.s_addr = inet_addr("127.0.0.1") + dest.sin_port = in_port_t(UInt16(port).bigEndian) + send(bytes, to: dest) + } + + private func send(_ bytes: [UInt8], to dest: sockaddr_in) { + var dest = dest + _ = withUnsafePointer(to: &dest) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + sendto(fd, bytes, bytes.count, 0, $0, socklen_t(MemoryLayout.size)) + } + } + } +} + +extension EventLog { + func messageStatuses(_ id: MessageID) -> [MessageSendResult] { + all.compactMap { if case let .messageStatus(i, r) = $0, i == id { return r }; return nil } + } + + var receivedMessages: [IncomingMessage] { + all.compactMap { if case let .messageReceived(m) = $0 { return m }; return nil } + } +} + +/// The SMS text of the chan_dongle fixture. +private let cyrillicText = "Привет, это тест из chan_dongle" + +/// An enabled account on 127.0.0.1 that does not register (messages and calls only). +private func localAccount(_ user: String) -> AccountConfig { + AccountConfig(displayName: "Acc \(user)", username: user, domain: "127.0.0.1", registerWithServer: false, mwi: false) +} + +// MARK: - tests that run pjsua (part of the serialized "Engine (pjsua)" suite) + +extension EngineTests { + /// A MESSAGE goes out as text/plain;charset=utf-8 with the exact UTF-8 bytes to the dialled + /// URI, and the stub's 200 becomes `.accepted(200)` once. The `id:` form reports the + /// caller's id. A text of `Engine.maxMessageBytes` fits into one request. + @Test func messageSentAndAccepted() async throws { + let stub = try MessageStub() + defer { stub.stop() } + let engine = await makeEngine() + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let account = localAccount("101") + try await engine.addAccount(account, password: "") + let target = "sip:102@127.0.0.1:\(stub.port)" + let dial = try #require(DialString.parse(target, account: account)) + + let id = try await engine.sendMessage(cyrillicText, to: dial, from: account.id) + #expect(await waitUntil(timeout: 5) { !log.messageStatuses(id).isEmpty }) + #expect(log.messageStatuses(id) == [.accepted(code: 200)]) + let request = try #require(stub.messages.first) + #expect(request.size - request.body.count < 600, "headers: \(request.size - request.body.count) bytes") + #expect(request.requestLine == "MESSAGE \(target) SIP/2.0") + // PJSIP prints To/From URIs without the port (RFC 3261 Table 1). + #expect(request.header("To") == "", "To: \(request.header("To") ?? "-")") + #expect(request.header("Content-Type")?.lowercased().replacingOccurrences(of: " ", with: "") + == "text/plain;charset=utf-8", "Content-Type: \(request.header("Content-Type") ?? "-")") + #expect(request.body == Array(cyrillicText.utf8)) + #expect(request.header("From")?.contains("sip:101@127.0.0.1") == true) + + let chosen = MessageID() + #expect(try await engine.sendMessage("second", to: dial, from: account.id, id: chosen) == chosen) + #expect(await waitUntil(timeout: 5) { log.messageStatuses(chosen) == [.accepted(code: 200)] }) + + // The longest text allowed still fits into one request with all its headers. + let longest = String(repeating: "Ж", count: Engine.maxMessageBytes / 2) + let big = try await engine.sendMessage(longest, to: dial, from: account.id) + #expect(await waitUntil(timeout: 5) { !log.messageStatuses(big).isEmpty }) + #expect(log.messageStatuses(big) == [.accepted(code: 200)]) + #expect(stub.messages.last?.body == Array(longest.utf8)) + let size = stub.messages.last?.size ?? 0 + #expect(size <= 4000, "request of \(size) bytes") + + try await Task.sleep(for: .milliseconds(300)) + #expect(log.messageStatuses(id).count == 1) + await engine.stop() + } + + /// A final non-2xx answer is `.failed` with its code and reason phrase; no answer at all is + /// 408 after the transaction timeout (shortened to 2 s); a request that cannot be sent is + /// `.failed(code: 0, ...)` with the transport error. Each id gets exactly one status. + @Test func messageFailuresCarryCodeAndReason() async throws { + let stub = try MessageStub() + defer { stub.stop() } + let engine = await makeEngine() + await engine.setTestTimings(transactionTimeoutMs: 2000) + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let account = localAccount("101") + try await engine.addAccount(account, password: "") + let dial = DialString(uri: "sip:102@127.0.0.1:\(stub.port)", display: "102") + + var ids: [MessageID] = [] + for (answer, expected) in [("404 Not Found", MessageSendResult.failed(code: 404, reason: "Not Found")), + ("480 Temporarily Unavailable", .failed(code: 480, reason: "Temporarily Unavailable"))] { + stub.answer = answer + let id = try await engine.sendMessage("hello", to: dial, from: account.id) + ids.append(id) + #expect(await waitUntil(timeout: 5) { !log.messageStatuses(id).isEmpty }) + #expect(log.messageStatuses(id) == [expected]) + } + + stub.answer = nil + let silent = try await engine.sendMessage("anyone there?", to: dial, from: account.id) + ids.append(silent) + #expect(await waitUntil(timeout: 8) { !log.messageStatuses(silent).isEmpty }) + #expect(log.messageStatuses(silent) == [.failed(code: 408, reason: "Request Timeout")]) + #expect(stub.messages.filter { $0.body == Array("anyone there?".utf8) }.count >= 2) // retransmitted + + // sendto to the broadcast address fails at once (as without a network). pjsua reports + // it through on_pager_status2 inside pjsua_im_send, then returns the error: one status, + // no throw. + let local = MessageID() + let returned = try await engine.sendMessage("x", to: DialString(uri: "sip:102@255.255.255.255:5060", display: "102"), + from: account.id, id: local) + #expect(returned == local) + ids.append(local) + #expect(await waitUntil(timeout: 5) { !log.messageStatuses(local).isEmpty }) + let result = try #require(log.messageStatuses(local).first) + if case let .failed(code, reason) = result { + #expect(code == 0) + #expect(!reason.isEmpty) + } else { + Issue.record("local failure reported as \(result)") + } + + try await Task.sleep(for: .milliseconds(500)) + for id in ids { #expect(log.messageStatuses(id).count == 1, "\(id): \(log.messageStatuses(id))") } + await engine.stop() + } + + /// A MESSAGE whose answer has not come when the engine stops fails with + /// `Engine.messageInterruptedReason`, once. + @Test func messagePendingAtStopIsInterrupted() async throws { + let stub = try MessageStub() + defer { stub.stop() } + stub.answer = nil + let engine = await makeEngine() + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let account = localAccount("101") + try await engine.addAccount(account, password: "") + let id = try await engine.sendMessage("late", to: DialString(uri: "sip:102@127.0.0.1:\(stub.port)", display: "102"), + from: account.id) + #expect(await waitUntil { !stub.messages.isEmpty }) + await engine.stop() + #expect(await waitUntil { !log.messageStatuses(id).isEmpty }) + try await Task.sleep(for: .milliseconds(200)) + #expect(log.messageStatuses(id) == [.failed(code: 0, reason: Engine.messageInterruptedReason)]) + } + + /// What `sendMessage` refuses before anything is sent. + @Test func sendMessageValidation() async throws { + let engine = await makeEngine() + let account = localAccount("101") + let dial = DialString(uri: "sip:102@127.0.0.1:5999", display: "102") + await #expect(throws: EngineError.notStarted) { + try await engine.sendMessage("hi", to: dial, from: account.id) + } + try await engine.start(network: Self.network) + await #expect(throws: EngineError.unknownAccount(account.id)) { + try await engine.sendMessage("hi", to: dial, from: account.id) + } + try await engine.addAccount(account, password: "") + for (text, uri) in [("", dial.uri), + (String(repeating: "a", count: Engine.maxMessageBytes + 1), dial.uri), + (String(repeating: "Ж", count: Engine.maxMessageBytes / 2 + 1), dial.uri), + ("hi", "tel:+375291234567"), + ("hi", "sip:")] { + do { + _ = try await engine.sendMessage(text, to: DialString(uri: uri, display: ""), from: account.id) + Issue.record("sent \(text.utf8.count) bytes to \(uri)") + } catch let error as EngineError { + guard case .invalidArgument = error else { Issue.record("\(error)"); continue } + } + } + await engine.stop() + } + + /// An SMS relayed by Asterisk from chan_dongle: Cyrillic text/plain;charset=utf-8 from + /// "+375291234567" arrives byte-exact as `.messageReceived` on the addressed account, and + /// the engine answers 200. Without a charset and with invalid UTF-8 (lossy) too. + @Test func incomingCyrillicMessageFromChanDongle() async throws { + let stub = try MessageStub() + defer { stub.stop() } + let engine = await makeEngine() + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let account = localAccount("102") + try await engine.addAccount(account, password: "") + let port = await engine.localPort(of: .udp) + + let before = Date() + let callID = stub.sendMessage(toPort: port, user: "102", fromNumber: "+375291234567", displayName: "+375291234567", + contentType: "text/plain;charset=utf-8", body: Array(cyrillicText.utf8)) + #expect(await waitUntil(timeout: 5) { !log.receivedMessages.isEmpty }) + #expect(await waitUntil(timeout: 5) { stub.responses(to: callID).contains("SIP/2.0 200 OK") }) + let message = try #require(log.receivedMessages.first) + #expect(message.accountID == account.id) + #expect(Array(message.text.utf8) == Array(cyrillicText.utf8)) + #expect(message.remote.number == "+375291234567") + #expect(message.remote.displayName == "+375291234567") + #expect(message.remote.uri == "sip:+375291234567@127.0.0.1") // no port in From (RFC 3261 Table 1) + #expect(message.receivedAt >= before.addingTimeInterval(-1) && message.receivedAt <= Date()) + + stub.sendMessage(toPort: port, user: "102", fromNumber: "1001", displayName: nil, + contentType: "text/plain", body: Array("no charset".utf8)) + #expect(await waitUntil(timeout: 5) { log.receivedMessages.count == 2 }) + #expect(log.receivedMessages.last?.text == "no charset") + #expect(log.receivedMessages.last?.remote.number == "1001") + #expect(log.receivedMessages.last?.remote.displayName == nil) + + stub.sendMessage(toPort: port, user: "102", fromNumber: "1001", displayName: nil, + contentType: "text/plain; charset=UTF-8", body: [0x48, 0x69, 0xFF, 0x21]) + #expect(await waitUntil(timeout: 5) { log.receivedMessages.count == 3 }) + #expect(log.receivedMessages.last?.text == "Hi\u{FFFD}!") + + try await Task.sleep(for: .milliseconds(300)) + #expect(log.receivedMessages.count == 3) // retransmissions absorbed + await engine.stop() + } + + /// Bodies other than text/plain are answered 415 (with Accept) and produce no event; a + /// MESSAGE without a body gets 200 and no event either. + @Test func incomingNonTextMessageIsRejectedWith415() async throws { + let stub = try MessageStub() + defer { stub.stop() } + let engine = await makeEngine() + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let account = localAccount("102") + try await engine.addAccount(account, password: "") + let port = await engine.localPort(of: .udp) + + for type in ["application/octet-stream", "text/html"] { + let callID = stub.sendMessage(toPort: port, user: "102", fromNumber: "+375291234567", displayName: nil, + contentType: type, body: [0x00, 0x01, 0xD0, 0x9F]) + #expect(await waitUntil(timeout: 5) { !stub.responses(to: callID).isEmpty }, "\(type)") + #expect(stub.responses(to: callID).first == "SIP/2.0 415 Unsupported Media Type", "\(type)") + } + let empty = stub.sendMessage(toPort: port, user: "102", fromNumber: "+375291234567", displayName: nil, + contentType: nil, body: []) + #expect(await waitUntil(timeout: 5) { stub.responses(to: empty).contains("SIP/2.0 200 OK") }) + try await Task.sleep(for: .milliseconds(500)) + #expect(log.receivedMessages.isEmpty) + await engine.stop() + } + + /// Two accounts: each MESSAGE is reported for the account its Request-URI and To name. + @Test func secondAccountReceivesItsOwnMessage() async throws { + let stub = try MessageStub() + defer { stub.stop() } + let engine = await makeEngine() + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let first = localAccount("102") + let second = localAccount("103") + try await engine.addAccount(first, password: "") + try await engine.addAccount(second, password: "") + let port = await engine.localPort(of: .udp) + + stub.sendMessage(toPort: port, user: "103", fromNumber: "200", displayName: "Two Hundred", + contentType: "text/plain;charset=utf-8", body: Array("for 103".utf8)) + #expect(await waitUntil(timeout: 5) { log.receivedMessages.count == 1 }) + stub.sendMessage(toPort: port, user: "102", fromNumber: "200", displayName: "Two Hundred", + contentType: "text/plain;charset=utf-8", body: Array("for 102".utf8)) + #expect(await waitUntil(timeout: 5) { log.receivedMessages.count == 2 }) + let byText = Dictionary(log.receivedMessages.map { ($0.text, $0.accountID) }, uniquingKeysWith: { a, _ in a }) + #expect(byText["for 103"] == second.id) + #expect(byText["for 102"] == first.id) + #expect(log.receivedMessages.first?.remote.displayName == "Two Hundred") + await engine.stop() + } + + /// At log level 4 (Debug mode) PJSIP writes delivery lines and packet dumps that carry the + /// text; none of it reaches a `.log` event (nor os_log, which gets the same string), while + /// the redacted lines with code and reason are still there. + @Test func messageTextStaysOutOfTheLog() async throws { + let stub = try MessageStub() + defer { stub.stop() } + let engine = await makeEngine() + await engine.setLogLevel(4) + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let account = localAccount("102") + try await engine.addAccount(account, password: "") + let dial = DialString(uri: "sip:103@127.0.0.1:\(stub.port)", display: "103") + let accepted = "секрет 200\nвторая строка" + let refused = "секрет 404: it's 5/5" + let incoming = "секрет входящее" + + let ok = try await engine.sendMessage(accepted, to: dial, from: account.id) + #expect(await waitUntil(timeout: 5) { !log.messageStatuses(ok).isEmpty }) + stub.answer = "404 Not Found" + let failed = try await engine.sendMessage(refused, to: dial, from: account.id) + #expect(await waitUntil(timeout: 5) { !log.messageStatuses(failed).isEmpty }) + let port = await engine.localPort(of: .udp) + stub.sendMessage(toPort: port, user: "102", fromNumber: "+375291234567", displayName: nil, + contentType: "text/plain;charset=utf-8", body: Array(incoming.utf8)) + #expect(await waitUntil(timeout: 5) { log.receivedMessages.count == 1 }) + try await Task.sleep(for: .milliseconds(300)) + await engine.stop() + + let lines = log.all.compactMap { if case let .log(_, text) = $0 { return text }; return nil } + for secret in ["секрет", "вторая строка"] { + #expect(!lines.contains { $0.contains(secret) }, "\(secret): \(lines.filter { $0.contains(secret) })") + } + #expect(lines.contains { $0.contains("Message '…' delivered successfully") }) + #expect(lines.contains { $0.contains("Failed to deliver message '…': 404/Not Found") }) + let dumps = lines.filter { $0.contains("MESSAGE sip:") && $0.hasSuffix("--end msg--") } + #expect(dumps.count >= 3, "\(dumps.count) MESSAGE dumps") + #expect(dumps.allSatisfy { $0.contains("\r\n\r\n…\n--end msg--") }) + } + + /// A MESSAGE inside a call is reported like one outside (the call's account, the peer from + /// the dialog); a non-text one inside the call gets 415 too. + @Test func messageInsideACall() async throws { + let stub = try MessageStub() + defer { stub.stop() } + let engine = await makeEngine() + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let account = localAccount("101") + try await engine.addAccount(account, password: "") + let port = await engine.localPort(of: .udp) + let call = try await engine.makeCall(to: DialString(uri: "sip:200@127.0.0.1:\(stub.port)", display: "200"), + from: account.id) + #expect(await waitUntil(timeout: 5) { await engine.calls().first { $0.id == call }?.state == .connected }) + #expect(stub.hasDialog) + + let callID = try #require(stub.sendInDialogMessage(toPort: port, contentType: "text/plain;charset=utf-8", + body: Array(cyrillicText.utf8))) + #expect(await waitUntil(timeout: 5) { !log.receivedMessages.isEmpty }) + #expect(stub.responses(to: callID).contains("SIP/2.0 200 OK")) + let message = try #require(log.receivedMessages.first) + #expect(message.accountID == account.id) + #expect(message.text == cyrillicText) + #expect(message.remote.number == "200") + + let mark = stub.responses(to: callID).count + stub.sendInDialogMessage(toPort: port, contentType: "application/octet-stream", body: [1, 2, 3]) + #expect(await waitUntil(timeout: 5) { stub.responses(to: callID).count > mark }) + #expect(stub.responses(to: callID).dropFirst(mark).first == "SIP/2.0 415 Unsupported Media Type") + try await Task.sleep(for: .milliseconds(300)) + #expect(log.receivedMessages.count == 1) + try await engine.hangup(call) + #expect(await waitUntil { await engine.calls().isEmpty }) + await engine.stop() + } +} + +// MARK: - pure mappings + +@Suite("Text message mappings") +struct MessageMappingTests { + @Test func statusMapping() { + #expect(MessageMapping.result(code: 200, reason: "OK", answered: true) == .accepted(code: 200)) + #expect(MessageMapping.result(code: 202, reason: "Accepted", answered: true) == .accepted(code: 202)) + #expect(MessageMapping.result(code: 404, reason: "Not Found", answered: true) == .failed(code: 404, reason: "Not Found")) + #expect(MessageMapping.result(code: 486, reason: "", answered: true) == .failed(code: 486, reason: "Busy Here")) + #expect(MessageMapping.result(code: 302, reason: "Moved Temporarily", answered: true) + == .failed(code: 302, reason: "Moved Temporarily")) + // a server's 503 is a SIP answer; pjsua's own 503/502 without a response is a local failure + #expect(MessageMapping.result(code: 503, reason: "Service Unavailable", answered: true) + == .failed(code: 503, reason: "Service Unavailable")) + #expect(MessageMapping.result(code: 503, reason: "Connection refused", answered: false) + == .failed(code: 0, reason: "Connection refused")) + #expect(MessageMapping.result(code: 502, reason: "", answered: false) == .failed(code: 0, reason: "Bad Gateway")) + #expect(MessageMapping.result(code: 408, reason: "Request Timeout", answered: false) + == .failed(code: 408, reason: "Request Timeout")) + } + + @Test func logRedaction() { + let prefix = "15:04:05.123 pjsua_im.h ." + #expect(MessageLogRedaction.redact(prefix + "Message 'Привет\n'двойные' кавычки' delivered successfully") + == prefix + "Message '…' delivered successfully") + #expect(MessageLogRedaction.redact(prefix + "Failed to deliver message 'it's: 5/5 ok': 404/Not Found") + == prefix + "Failed to deliver message '…': 404/Not Found") + #expect(MessageLogRedaction.redact(prefix + "Failed to deliver message 'a': 408/Request Timeout") + == prefix + "Failed to deliver message '…': 408/Request Timeout") + #expect(MessageLogRedaction.redact(prefix + "Failed to deliver message 'no code at all") + == prefix + "Failed to deliver message '…'") + + let head = "15:04:05.124 pjsua_core.c .TX 520 bytes Request msg MESSAGE/cseq=7 (tdta0x1) to UDP 127.0.0.1:5070:\n" + let headers = "MESSAGE sip:102@127.0.0.1:5070 SIP/2.0\r\nVia: SIP/2.0/UDP 127.0.0.1:5060\r\n" + + "Content-Type: text/plain;charset=utf-8\r\nContent-Length: 12\r\n\r\n" + #expect(MessageLogRedaction.redact(head + headers + "секрет\r\n\r\nещё\n--end msg--") + == head + headers + "…\n--end msg--") + let lfOnly = "MESSAGE sip:a@b SIP/2.0\nContent-Length: 4\n\n" + #expect(MessageLogRedaction.redact(head + lfOnly + "text\n--end msg--") == head + lfOnly + "…\n--end msg--") + let dropped = "15:04:05.125 sip_transport.c Dropped packet:MESSAGE sip:a@b SIP/2.0\r\nContent-Length: 4\r\n\r\n" + #expect(MessageLogRedaction.redact(dropped + "text\n-- end of packet.") == dropped + "…\n-- end of packet.") + + // Untouched: a MESSAGE without a body, its 200, other requests, other lines. + let empty = head + "MESSAGE sip:a@b SIP/2.0\r\nContent-Length: 0\r\n\r\n\n--end msg--" + #expect(MessageLogRedaction.redact(empty) == empty) + let response = "15:04:05.126 pjsua_core.c .RX 300 bytes Response msg 200/MESSAGE/cseq=7 (rdata0x2) from UDP 127.0.0.1:5070:\n" + + "SIP/2.0 200 OK\r\nCSeq: 7 MESSAGE\r\nContent-Length: 0\r\n\r\n\n--end msg--" + #expect(MessageLogRedaction.redact(response) == response) + let invite = head + "INVITE sip:a@b SIP/2.0\r\nContent-Type: application/sdp\r\n\r\nv=0\r\no=MESSAGE x\n--end msg--" + #expect(MessageLogRedaction.redact(invite) == invite) + for line in ["15:04:05.127 pjsua_acc.c Registration sent", "Processing incoming message: Request msg MESSAGE/cseq=1", + "engine: account x: MESSAGE from +375291234567, 12 bytes"] { + #expect(MessageLogRedaction.redact(line) == line) + } + } + + @Test func incomingMapping() { + let account = AccountID() + let at = Date() + let m = MessageMapping.incoming(account: account, from: "\"Иван\" ", + mimeType: "TEXT/Plain", body: "Привет", at: at) + #expect(m == IncomingMessage(accountID: account, + remote: RemoteParty(displayName: "Иван", uri: "sip:+375291234567@pbx.example.com", + number: "+375291234567"), + text: "Привет", receivedAt: at)) + #expect(MessageMapping.incoming(account: account, from: "", mimeType: "text/plain", body: "", + at: at) == nil) + #expect(MessageMapping.incoming(account: account, from: "", mimeType: "", body: "", at: at) == nil) + #expect(MessageMapping.incoming(account: account, from: "", mimeType: "application/octet-stream", + body: "x", at: at) == nil) + #expect(MessageMapping.incoming(account: account, from: "", mimeType: "text/plain", + body: "x", at: at)?.remote.number == "102") + } +} diff --git a/Tests/MacroSIPCoreTests/EngineSoundsTests.swift b/Tests/MacroSIPCoreTests/EngineSoundsTests.swift index 1a53969..5ae8830 100644 --- a/Tests/MacroSIPCoreTests/EngineSoundsTests.swift +++ b/Tests/MacroSIPCoreTests/EngineSoundsTests.swift @@ -235,7 +235,7 @@ extension EngineTests { let (lb, consumer) = try await startLoopback(CallOptions()) defer { consumer.cancel() } let engine = lb.engine - for e in [SoundEvent.callConnected, .callEnded, .voicemail, .error, .keyPress("5")] { + for e in [SoundEvent.callConnected, .callEnded, .voicemail, .error, .message, .keyPress("5")] { #expect(EventSounds.duration(of: e) <= 400, "\(e)") } @@ -306,6 +306,9 @@ struct EngineSoundValueTests { @Test func settingsDecodeDefaultsAndRoundTrip() throws { let old = try JSONDecoder().decode(AppSettings.self, from: Data(#"{"callLogLimit":50}"#.utf8)) #expect(old.audio.holdMusic == .builtIn && old.audio.soundEvents == SoundEventSettings()) + #expect(!old.audio.soundEvents.message) + let before26_3 = try JSONDecoder().decode(SoundEventSettings.self, from: Data(#"{"callEvents":true,"voicemail":true}"#.utf8)) + #expect(before26_3.callEvents && before26_3.voicemail && !before26_3.message) #expect(!old.recording.noticeTone && old.recording.noticeToneIntervalSeconds == 15) let odd = try JSONDecoder().decode(RecordingSettings.self, from: Data(#"{"noticeTone":true,"noticeToneIntervalSeconds":3}"#.utf8)) @@ -319,7 +322,7 @@ struct EngineSoundValueTests { var s = AppSettings() s.audio.holdMusic = .file(URL(fileURLWithPath: "/tmp/music.mp3")) - s.audio.soundEvents = SoundEventSettings(callEvents: true, keyPress: false, voicemail: true, error: true) + s.audio.soundEvents = SoundEventSettings(callEvents: true, keyPress: false, voicemail: true, error: true, message: true) s.recording.noticeTone = true s.recording.noticeToneIntervalSeconds = 30 var back = try JSONDecoder().decode(AppSettings.self, from: JSONEncoder().encode(s)) diff --git a/Tests/MacroSIPCoreTests/EngineTests.swift b/Tests/MacroSIPCoreTests/EngineTests.swift index bfb59fe..c8a7610 100644 --- a/Tests/MacroSIPCoreTests/EngineTests.swift +++ b/Tests/MacroSIPCoreTests/EngineTests.swift @@ -759,6 +759,17 @@ struct EngineHelperTests { #expect(b == RemoteParty(displayName: nil, uri: "sip:+74951234567@example.com", number: "+74951234567")) let c = RemoteParty.parse("sip:test@127.0.0.1:5080") #expect(c == RemoteParty(displayName: nil, uri: "sip:test@127.0.0.1:5080", number: "test")) + // Escaped quotes in the display name are unescaped. + let d = RemoteParty.parse(#""A \"B\" C:\\x" "#) + #expect(d == RemoteParty(displayName: #"A "B" C:\x"#, uri: "sip:200@pbx", number: "200")) + // '<' inside the quoted name is not the URI: the last <...> outside quotes is. + let e = RemoteParty.parse(#""x " "#) + #expect(e == RemoteParty(displayName: "x ", uri: "sip:a@b;transport=tcp", number: "a")) + let f = RemoteParty.parse(#""Иван " "#) + #expect(f == RemoteParty(displayName: "Иван ", uri: "sip:+375291234567@pbx", number: "+375291234567")) + // An unquoted (token) display name stays as it is. + let g = RemoteParty.parse("Alice ") + #expect(g == RemoteParty(displayName: "Alice", uri: "sip:100@example.com", number: "100")) } func snapshot(outgoing: Bool, state: InviteState, media: MediaStatus = .none, diff --git a/Tests/MacroSIPCoreTests/MessageStoreTests.swift b/Tests/MacroSIPCoreTests/MessageStoreTests.swift new file mode 100644 index 0000000..eb2f513 --- /dev/null +++ b/Tests/MacroSIPCoreTests/MessageStoreTests.swift @@ -0,0 +1,320 @@ +import Foundation +import Testing +@testable import MacroSIPCore + +@Suite struct MessageStoreTests { + let acct = AccountID() + let t0 = Date(timeIntervalSince1970: (Date().timeIntervalSince1970 + 86400).rounded()) // after any conversation created during the test + + func note(_ conv: UUID, _ dir: MessageDirection = .incoming, text: String = "hi", at: Date, state: MessageState = .sent) -> Message { + Message(conversationID: conv, direction: dir, text: text, at: at, state: state) + } + + @Test func conversationKeyedByNormalizedNumberAndAccount() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let a = try s.conversation(account: acct, remoteNumber: "+375 29 123-45-67", remoteURI: "sip:a@h", displayName: nil) + let b = try s.conversation(account: acct, remoteNumber: "+375291234567", remoteURI: "", displayName: nil) + #expect(a.id == b.id && s.conversations().count == 1) + _ = try s.conversation(account: AccountID(), remoteNumber: "+375291234567", remoteURI: "", displayName: nil) + #expect(s.conversations().count == 2) + } + } + + @Test func uriAndNameUpdateOnlyWhenNonEmpty() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + _ = try s.conversation(account: acct, remoteNumber: "102", remoteURI: "sip:102@h", displayName: "Bob") + let c = try s.conversation(account: acct, remoteNumber: "102", remoteURI: "", displayName: nil) + #expect(c.remoteURI == "sip:102@h" && c.remoteDisplayName == "Bob") + let d = try s.conversation(account: acct, remoteNumber: "102", remoteURI: "sip:102@h2", displayName: "Robert") + #expect(d.remoteURI == "sip:102@h2" && d.remoteDisplayName == "Robert") + #expect(s.conversations()[0] == d) + } + } + + @Test func contactResolvedThroughContactStore() throws { + try withTempDir { dir in + let contacts = ContactStore(directory: dir) + let alice = Contact(name: "Alice", number: "+7 495 123-45-67") + try contacts.upsert(alice) + let s = MessageStore(directory: dir, contacts: contacts) + let c = try s.conversation(account: acct, remoteNumber: "+74951234567", remoteURI: "", displayName: nil) + #expect(c.contactID == alice.id) + let other = try s.conversation(account: acct, remoteNumber: "999", remoteURI: "", displayName: nil) + #expect(other.contactID == nil) + } + } + + @Test func appendBumpsActivityAndUnread() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let c = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + let later = t0.addingTimeInterval(1000) + try s.append(note(c.id, at: later)) + try s.append(note(c.id, at: later.addingTimeInterval(5))) + try s.append(note(c.id, .outgoing, at: later.addingTimeInterval(-100))) // earlier: activity unchanged + let stored = s.conversations()[0] + #expect(stored.unread == 2 && s.unreadTotal == 2) + #expect(stored.lastActivityAt == later.addingTimeInterval(5)) + } + } + + @Test func markReadZeroesUnread() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let a = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + let b = try s.conversation(account: acct, remoteNumber: "2", remoteURI: "", displayName: nil) + try s.append(note(a.id, at: t0)); try s.append(note(b.id, at: t0)) + #expect(s.unreadTotal == 2) + try s.markRead(a.id) + #expect(s.unreadTotal == 1) + #expect(s.conversations().first { $0.id == a.id }?.unread == 0) + } + } + + @Test func orderingOfConversationsAndMessages() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let a = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + let b = try s.conversation(account: acct, remoteNumber: "2", remoteURI: "", displayName: nil) + let m3 = note(a.id, text: "3", at: t0.addingTimeInterval(30)) + let m1 = note(a.id, text: "1", at: t0.addingTimeInterval(10)) + let m2a = note(a.id, text: "2a", at: t0.addingTimeInterval(20)) + let m2b = note(a.id, text: "2b", at: t0.addingTimeInterval(20)) + for m in [m3, m1, m2a, m2b] { try s.append(m) } + try s.append(note(b.id, at: t0.addingTimeInterval(40))) + #expect(s.messages(in: a.id).map(\.text) == ["1", "2a", "2b", "3"]) + #expect(s.conversations().map(\.id) == [b.id, a.id]) + #expect(s.allMessages().count == 5) + #expect(s.messages(in: b.id).count == 1) + } + } + + @Test func limitDropsOldestAndPrunesEmptyConversations() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir, limit: { 3 }) + let a = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + let b = try s.conversation(account: acct, remoteNumber: "2", remoteURI: "", displayName: nil) + try s.append(note(a.id, text: "a1", at: t0)) + try s.append(note(b.id, text: "b1", at: t0.addingTimeInterval(1))) + try s.append(note(b.id, text: "b2", at: t0.addingTimeInterval(2))) + try s.append(note(b.id, text: "b3", at: t0.addingTimeInterval(3))) + #expect(s.allMessages().map(\.text) == ["b1", "b2", "b3"]) + #expect(s.conversations().map(\.id) == [b.id]) + } + } + + @Test func updateChangesState() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let c = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + let m = try s.append(note(c.id, .outgoing, at: t0, state: .sending)) + try s.update(m.id) { $0.state = .failed; $0.failureCode = 404; $0.failureReason = "Not Found" } + var got = s.messages(in: c.id)[0] + #expect(got.state == .failed && got.failureCode == 404 && got.failureReason == "Not Found") + try s.update(m.id) { $0.state = .sent; $0.failureCode = nil; $0.failureReason = nil } + got = s.messages(in: c.id)[0] + #expect(got.state == .sent && got.failureCode == nil) + try s.update(UUID()) { $0.text = "x" } // unknown id is ignored + } + } + + @Test func failInterruptedSends() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let c = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + let pending = try s.append(note(c.id, .outgoing, at: t0, state: .sending)) + let done = try s.append(note(c.id, .outgoing, at: t0.addingTimeInterval(1), state: .sent)) + try s.failInterruptedSends() + let all = s.messages(in: c.id) + #expect(all.first { $0.id == pending.id }.map { ($0.state, $0.failureCode, $0.failureReason) }! == (.failed, 0, "interrupted")) + #expect(all.first { $0.id == done.id }?.state == .sent) + } + } + + @Test func removeMessageConversationAndClear() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let a = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + let b = try s.conversation(account: acct, remoteNumber: "2", remoteURI: "", displayName: nil) + let m = try s.append(note(a.id, at: t0)) + try s.append(note(a.id, at: t0.addingTimeInterval(1))) + try s.append(note(b.id, at: t0)) + try s.remove(message: m.id) + #expect(s.messages(in: a.id).count == 1) + try s.remove(conversation: a.id) + #expect(s.conversations().map(\.id) == [b.id] && s.allMessages().count == 1) + try s.clear() + #expect(s.conversations().isEmpty && s.allMessages().isEmpty && s.unreadTotal == 0) + } + } + + @Test func persistsAcrossInstancesAndCyrillicRoundTrips() throws { + try withTempDir { dir in + let first = MessageStore(directory: dir) + let c = try first.conversation(account: acct, remoteNumber: "102", remoteURI: "sip:102@h", displayName: "Иван") + let m = try first.append(note(c.id, text: "Привет, мир", at: t0)) + let second = MessageStore(directory: dir) + #expect(second.conversations() == [first.conversations()[0]]) + #expect(second.messages(in: c.id) == [m]) + #expect(second.unreadTotal == 1) + } + } + + @Test func decodesOlderFileWithoutOptionalFields() throws { + try withTempDir { dir in + let acctID = UUID(), conv = UUID(), mid = UUID() + let json = """ + {"conversations":[{"id":"\(conv)","accountID":{"raw":"\(acctID)"},"remoteNumber":"102", + "remoteURI":"sip:102@h","lastActivityAt":"2023-11-14T22:13:20Z","futureField":42}], + "messages":[{"id":"\(mid)","conversationID":"\(conv)","direction":"incoming","text":"hey", + "at":"2023-11-14T22:13:20Z","state":"sent","extra":true}]} + """ + try Data(json.utf8).write(to: dir.appendingPathComponent("messages.json")) + let s = MessageStore(directory: dir) + let c = try #require(s.conversations().first) + #expect(c.unread == 0 && c.remoteDisplayName == nil && c.contactID == nil && c.accountID.raw == acctID) + let m = try #require(s.messages(in: conv).first) + #expect(m.text == "hey" && m.failureCode == nil && m.failureReason == nil) + } + } + + @Test func damagedFileLeavesDefaultAndIsMovedAside() throws { + try withTempDir { dir in + try Data("{ not json".utf8).write(to: dir.appendingPathComponent("messages.json")) + let s = MessageStore(directory: dir) + #expect(s.conversations().isEmpty && s.allMessages().isEmpty) + let files = try FileManager.default.contentsOfDirectory(atPath: dir.path) + #expect(files.contains { $0.hasPrefix("messages.broken-") }) + let c = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + #expect(s.conversations().map(\.id) == [c.id]) + } + } + + // MARK: peers, formats, hosts + + @Test func sameNumberInDifferentFormatsIsOneConversation() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let a = try s.conversation(account: acct, remoteNumber: "375291234567", remoteURI: "sip:375291234567@pbx.example.com", displayName: nil, accountDomain: "pbx.example.com") + let b = try s.conversation(account: acct, remoteNumber: "+375 29 123-45-67", remoteURI: "", displayName: nil, accountDomain: "pbx.example.com") + let c = try s.conversation(account: acct, remoteNumber: "291234567", remoteURI: "", displayName: nil, accountDomain: "pbx.example.com") + let d = try s.conversation(account: acct, remoteNumber: "4567", remoteURI: "", displayName: nil, accountDomain: "pbx.example.com") + #expect(a.id == b.id && b.id == c.id) // a country prefix may be missing from the shorter side (9 digits) + #expect(d.id != a.id && s.conversations().count == 2) // an extension is not a suffix match + } + } + + @Test func hostSeparatesPeers() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let domain = "pbx.example.com" + let bob = try s.conversation(account: acct, remoteNumber: "bob", remoteURI: "sip:bob@pbx.example.com", displayName: nil, accountDomain: domain) + let partner = try s.conversation(account: acct, remoteNumber: "bob", remoteURI: "sip:bob@partner.org", displayName: nil, accountDomain: domain) + let again = try s.conversation(account: acct, remoteNumber: "Bob", remoteURI: "sip:Bob@PBX.example.com:5061;transport=tls", displayName: nil, accountDomain: domain) + #expect(bob.id != partner.id && again.id == bob.id) + #expect(partner.remoteHost == "partner.org" && partner.shownNumber == "bob@partner.org") + // a number through the account has no host; the same number at a foreign host is another peer + let own = try s.conversation(account: acct, remoteNumber: "102", remoteURI: "sip:102@pbx.example.com", displayName: nil, accountDomain: domain) + let ownBare = try s.conversation(account: acct, remoteNumber: "102", remoteURI: "", displayName: nil, accountDomain: domain) + let foreign = try s.conversation(account: acct, remoteNumber: "102", remoteURI: "sip:102@other.net", displayName: nil, accountDomain: domain) + #expect(own.id == ownBare.id && own.remoteHost == nil && foreign.id != own.id && foreign.remoteHost == "other.net") + #expect(s.conversations().count == 4) + } + } + + @Test func addressMatching() { + let a = ConversationAddress("sip:+375291234567@pbx.example.com;transport=tls", accountDomain: "PBX.example.com") + #expect(a.host == nil && a.user == "+375291234567") + #expect(ConversationAddress("tel:+375 29 123-45-67", accountDomain: "x").user == "+375291234567") + #expect(ConversationAddress("alice@A.com", accountDomain: "a.com").host == "a.com") + #expect(ConversationAddress("102", accountDomain: "x").host == nil) + let c = Conversation(accountID: acct, remoteNumber: "alice", remoteHost: "a.com") + #expect(c.matches(account: acct, address: ConversationAddress("sip:ALICE@a.com"))) + #expect(!c.matches(account: acct, address: ConversationAddress("sip:alice@b.com"))) + #expect(!c.matches(account: AccountID(), address: ConversationAddress("sip:alice@a.com"))) + } + + // MARK: unread, replace, tolerance, cache + + @Test func removingAndPruningNeverLeaveMoreUnreadThanIncoming() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir, limit: { 3 }) + let c = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + let m1 = try s.append(note(c.id, at: t0)) + try s.append(note(c.id, at: t0.addingTimeInterval(1))) + try s.append(note(c.id, .outgoing, at: t0.addingTimeInterval(2))) + #expect(s.unreadTotal == 2) + try s.remove(message: m1.id) + #expect(s.unreadTotal == 1) + let o = try s.conversation(account: acct, remoteNumber: "2", remoteURI: "", displayName: nil) + try s.append(note(o.id, at: t0.addingTimeInterval(10))) // fourth message: the oldest of `c` is dropped + try s.append(note(o.id, at: t0.addingTimeInterval(11))) + try s.append(note(o.id, at: t0.addingTimeInterval(12))) // `c` loses everything + #expect(s.conversations().map(\.id) == [o.id] && s.unreadTotal == 3) + try s.append(note(o.id, .outgoing, at: t0.addingTimeInterval(13))) + #expect(s.unreadTotal <= s.allMessages().filter { $0.direction == .incoming }.count) + } + } + + @Test func replaceMovesAMessageToTheEndInOneWrite() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let c = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + let failed = try s.append(note(c.id, .outgoing, text: "again", at: t0, state: .failed)) + try s.append(note(c.id, at: t0.addingTimeInterval(5))) + let retry = note(c.id, .outgoing, text: "again", at: t0.addingTimeInterval(60), state: .sending) + try s.replace(message: failed.id, with: retry) + #expect(s.messages(in: c.id).map(\.id).last == retry.id && s.messages(in: c.id).count == 2) + #expect(s.conversations()[0].lastActivityAt == retry.at) + } + } + + @Test func firstMessageAndConversationInOneWrite() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let (conv, message) = try s.conversation(account: acct, remoteNumber: "7", remoteURI: "", displayName: nil) { + Message(conversationID: $0, direction: .outgoing, text: "hello", at: t0, state: .sending) + } + #expect(s.conversations().map(\.id) == [conv.id] && s.messages(in: conv.id) == [message]) + let (again, _) = try s.conversation(account: acct, remoteNumber: "7", remoteURI: "", displayName: nil) { + Message(conversationID: $0, direction: .outgoing, text: "second", at: t0.addingTimeInterval(1)) + } + #expect(again.id == conv.id && s.messages(in: conv.id).count == 2) + #expect(s.lastMessages()[conv.id]?.text == "second") + } + } + + @Test func unreadableRecordsAreSkippedAndTheRestIsKept() throws { + try withTempDir { dir in + let acctID = UUID(), conv = UUID(), good = UUID() + let json = """ + {"conversations":[{"id":"\(conv)","accountID":{"raw":"\(acctID)"},"remoteNumber":"102","lastActivityAt":"2023-11-14T22:13:20Z"}, + {"id":"not-a-uuid","remoteNumber":5}], + "messages":[{"id":"\(good)","conversationID":"\(conv)","direction":"incoming","text":"ok","at":"2023-11-14T22:13:20Z","state":"sent"}, + {"id":"\(UUID())","conversationID":"\(conv)","direction":"sideways","text":"bad","at":"2023-11-14T22:13:20Z","state":"sent"}, + 42]} + """ + try Data(json.utf8).write(to: dir.appendingPathComponent("messages.json")) + let s = MessageStore(directory: dir) + #expect(s.conversations().map(\.id) == [conv] && s.allMessages().map(\.id) == [good]) + let files = try FileManager.default.contentsOfDirectory(atPath: dir.path) + #expect(files.contains { $0.hasPrefix("messages.damaged-") } && !files.contains { $0.hasPrefix("messages.broken-") }) + #expect(MessageStore(directory: dir).allMessages().map(\.id) == [good]) // rewritten without them + } + } + + @Test func aFailedWriteLeavesTheStoreAsItWas() throws { + try withTempDir { dir in + let s = MessageStore(directory: dir) + let c = try s.conversation(account: acct, remoteNumber: "1", remoteURI: "", displayName: nil) + try s.append(note(c.id, at: t0)) + // The directory becomes a file: saving fails. + try FileManager.default.removeItem(at: dir) + try Data("x".utf8).write(to: dir) + #expect(throws: (any Error).self) { try s.append(note(c.id, at: t0.addingTimeInterval(1))) } + #expect(s.allMessages().count == 1) + } + } +} diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 129a8f8..d56949e 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -30,7 +30,7 @@ Built on an Apple Silicon Mac; the x86_64 half is cross-compiled (ADR 0012). - **Codecs built**: Opus, G.722, G.711 and, from pjproject's own `third_party` sources, G.722.1 (Siren7/14), GSM, iLBC and Speex (`config_site.h` `PJMEDIA_HAS_*_CODEC`; `build-pjsip.sh` no longer passes `--disable-{g7221,gsm,ilbc,speex}-codec` and stops if configure disables one or a library is missing). Their archives (`libg7221codec.a`, `libgsmcodec.a`, `libilbccodec.a`, `libspeex.a`) are in `pjsipLibraries` in `Package.swift`; keep that list in sync with `third_party/pjsip/LINKFLAGS` after changing codecs. No G.729. Changing `config_site.h` rebuilds PJSIP for both architectures (about 2-5 min; OpenSSL and Opus stay cached). Codec ids and defaults: docs/ENGINE.md "Codecs". - **Universal build**: `build-pjsip.sh` builds every library for arm64 and x86_64 (deployment target 14.0) and merges them with `lipo`; `make-app.sh release` (and so `make-dmg.sh`) runs `swift build --arch arm64 --arch x86_64` and checks both slices; `make-app.sh debug` and plain `swift build` stay native. `ARCHS=arm64 scripts/make-app.sh` builds a single-arch release. Test the Intel slice on Apple Silicon with `SELFTEST_ARCH=x86_64 scripts/selftest-call.sh` (needs Rosetta 2: `softwareupdate --install-rosetta --agree-to-license`). - Debug builds (`scripts/make-app.sh debug`; a release app ignores the demo options and starts the real app on the real data, Keychain prompt included) accept `--mock-engine`, `--demo-state `, `--data-dir `, `--snapshot ` (the app quits once the PNGs are written; a state with a ringing call or an open sheet needs `timeout`; the app comes to the front and the front window becomes key just before the capture, so the frames show active windows, and the app's window flashes on screen), `--appearance light|dark` (forces the theme, for screenshots); all builds accept `--log-level 0-6` (or `MACROSIP_LOG_LEVEL`) for PJSIP verbosity; see `Sources/MacroSIPApp/Model/LaunchOptions.swift`. Demo launches use a temp data dir and never touch the real Keychain. -- README screenshots (`docs/screenshots/{light,dark,ru/light,ru/dark}`, `?v=N` on every image in both READMEs, bumped when frames change), one demo launch each with `--appearance light|dark -AppleLanguages '(en)'|'(ru)' --snapshot ` and a short `--data-dir` (the import sheet shows it); the file taken from the output: `dialpad-calls` (`calls`, `-main`), `contacts-presence` (`contacts`, `-main`), `call-recording` (`recording`, `-main`), `conference` (`conference`, `-main`), `directory-search` (`directory-done`, `-main`), `account-popup` (`account-popup`, `-popup`), `incoming-auto-answer` (`autoAnswer`, `--snapshot-after 2`, `-panel`), `settings-recording` (`settings-recording`, `-settings`), `settings-hotkeys` (`settings-hotkeys-on`, `-settings`), `import-microsip` (`import-microsip`, `-settings-sheet`), `settings-diagnostics` (`settings-diagnostics-on`, `-settings`). +- README screenshots (`docs/screenshots/{light,dark,ru/light,ru/dark}`, `?v=N` on every image in both READMEs, bumped when frames change), one demo launch each with `--appearance light|dark -AppleLanguages '(en)'|'(ru)' --snapshot ` and a short `--data-dir` (the import sheet shows it); the file taken from the output: `dialpad-calls` (`calls`, `-main`), `contacts-presence` (`contacts`, `-main`), `call-recording` (`recording`, `-main`), `conference` (`conference`, `-main`), `directory-search` (`directory-done`, `-main`), `account-popup` (`account-popup`, `-popup`), `incoming-auto-answer` (`autoAnswer`, `--snapshot-after 2`, `-panel`), `settings-recording` (`settings-recording`, `-settings`), `settings-hotkeys` (`settings-hotkeys-on`, `-settings`), `import-microsip` (`import-microsip`, `-settings-sheet`), `settings-diagnostics` (`settings-diagnostics-on`, `-settings`), `messages-list` (`messages`, `-main`), `messages-conversation` (`messages-conversation`, `-main`). - Do not add dependencies without an ADR. - **Documentation site**: https://hsmm.github.io/MacroSIP/wiki/ is built from a clone of the GitHub wiki with `scripts/build-wiki-site.py ` and copied to `wiki/` on the `gh-pages` branch. Wiki edits do not reach it by themselves. - Versions are `YY.MINOR.PATCH` (ADR 0010): the first release is `26.0.0`; tags carry the bare number. `make-app.sh` takes the version from `git describe`. @@ -46,12 +46,13 @@ Built on an Apple Silicon Mac; the x86_64 half is cross-compiled (ADR 0012). - Quick keys (screen 11): `--demo-state quick-keys|quick-keys-bottom` fills eight keys (Andrei rings, Siarhei is on the phone, Sales queue has no presence information), shows the panel at the right or the bottom and opens Settings › Quick keys with key 2 selected; a snapshot writes `-main.png` and `-settings.png`. Keys live in `AppSettings.quickKeys` (settings.json); BLF subscriptions are kept by `AppModel+QuickKeys.swift` (observes the keys, the accounts and the presence map). The engine reports `PresenceStatus.ringing` (Asterisk "Ringing" note) with the note in `.buddyPresence(contactURI:, status, note:)`: `AppModel.handleQuickKeyPresence` lights every key whose URI matches (orange, blinking, click dials the pickup code) and clears it on any other status; the tooltip shows "Ringing · N min" once the line has rung a minute. dnd is shown as "on the phone" (red), away as available; `AppModel.setQuickKeyRinging(_:for:)` stays as the seam for demo states. Presence watches of contacts and quick keys go through one reference-counted registry (`PresenceRegistry` in Core, `AppModel.setPresenceWatches(owner:uris:)`): one engine subscription per target (`presenceKey`), however many owners or spellings; unsubscribed when the last owner is gone; a failed subscribe is logged once. BLF targets and key calls use the default outgoing account, not the one picked in the main window; a pickup is the URI `sip:@` (`#` escaped), built directly. The Call › Quick keys items and View › Show Quick Keys are AppKit items (`Platform/QuickKeysMenu.swift`) validated each time the menu opens or ⌘1–⌘9 is looked up, because SwiftUI `Commands` do not refresh when the keys change; a second conference-key press before the first leg is answered is ignored. `MockEngine.pinPresence(user:_:)` keeps a watched user at one status. - Contact card (screen 12): `--demo-state contacts|contact-card|contact-card-new`. The demo address book (`DemoState.demoContacts()`) has several numbers per person, two generated photos, two favourites and an organization-only contact; `contact-card` opens the card for the first favourite and the snapshot writes `-card.png` next to `-main.png`. Contacts live in `contacts.json` as `firstName`/`lastName`/`numbers` (plus `name`/`number` for downgrades; photos are `photos/.jpg`, `ContactStore` hands them back in `Contact.photo`); older files with only `name`/`number` are read as well (name split at the last space, number as Other, default). - Network, codecs and the incoming-call rule: `--demo-state settings-network|settings-codecs|deny-incoming` (also `settings-general`, `settings-general-advanced` with the Advanced group open, `settings-calls`). `settings-network` moves the RTP range and turns DNS SRV on, so the engine answers `.needsRestart` and the pane shows the "Restart now" banner (`AppModel.networkRestartNeeded`; `scheduleNetworkApply` asks the engine 0.8 s after the last change, `restartEngineForNetwork` stops and starts it). `settings-codecs` shows the seven new codecs (all off unless turned on; `CodecCatalog` in `CodecsPane.swift` appends the ones a stored order lacks). `deny-incoming` sets "Numbers not in Contacts", lets a stranger call and shows the call log (note `denied`, "Rejected: rule") beside Settings › Calls. The rule goes through `CallOptions.denyIncoming`; `AppModel.syncKnownNumbers` keeps `CallOptions.knownNumbers` equal to every number of every contact (`Contact.normalize`) whenever `setContacts` runs; the numbers are derived, never written to settings.json. The engine turns the call away with 603 (433 for anonymous) and the app only sees `.callEnded`; `handleEnded` writes the missed entry. `MockEngine` applies the same rule and the same restart answer, and the self-test covers both. +- Messages (screen 14, 26.3): text messages as SIP MESSAGE in the fourth tab. Demo states: `--demo-state messages|messages-conversation|messages-failed|messages-new|messages-empty|messages-many|messages-selftest` (`DemoState+Messages.swift`; the mockup's six conversations are seeded for every `messages*` state except `messages-empty` and `messages-many`, and for `selftest`). `messages` is the list (two unread, one not sent; README `messages-list`), `messages-conversation` opens Andrei Kavaliou with the last message "Sent" and a draft in the composer (README `messages-conversation`), `messages-failed` opens Volha Marozava with the 404 and Retry, `messages-new` opens 14.3 with "Ka" in To: and the contacts-then-directory suggestion list (the mock Google source answers after 4 s, so the frame needs the default snapshot delay or more), `messages-many` shows both tab badges beyond 99 (the Russian tab row must still fit), `messages-selftest` runs only the message checks that `selftest` also includes (PASS/FAIL lines, `failures=N`). Snapshots write `-main.png`. Code map: engine side `Engine+Messages.swift` (`sendMessage(_:to:from:id:)`, `Engine.maxMessageBytes`, `.messageReceived` / `.messageStatus`) and `MockEngine.sendMessage` (accepted after 0.6 s; a To user `404` fails with 404 Not Found, `timeout` with 408, `offline` with a local failure; `simulateIncomingMessage(account:from:text:name:)`); data `MessageStore` (messages.json beside the call log); `Model/AppModel+Messages.swift` is the whole model side: `conversations` (newest last message first), `conversationLast`, `messageThread` (the open conversation), `messagesPage` (`MessagesPage`: list, conversation, new; the tab remembers it), `send(text:in:)`, `sendNew(text:to:name:)`, `retry` (removes the failed message and appends the same text as a new `.sending` one, so it takes the current time and moves to the end), `deleteMessage` / `deleteConversation`, `composeMessage(to:name:account:)` (the Contacts and Call Log "Send Message" items), `handleMessageReceived` / `handleMessageStatus` (a status is matched through `pendingSends`, one fresh `MessageID` per attempt; an unknown id is ignored). Read state: a conversation is read while it is shown in the key main window (`mainWindowIsKey`, `updateMessageReadState`, called on tab change, window key and page change); the tab badge and the Dock badge read `messagesUnread` (the Dock adds the unseen missed calls in `AppDelegate`; the menu bar icon still counts missed calls only). At launch `MessageStore.failInterruptedSends` turns messages still `.sending` into Not sent · Interrupted. Do Not Disturb stores and counts a message but posts no notification and plays no sound. Notifications: `Platform/MessageNotifications.swift` (category `MESSAGE`, no actions, no sound, `threadIdentifier` = conversation id, removed when the conversation is read or deleted); `CallNotifications` stays the notification center's delegate and passes message clicks to `AppModel.openConversationFromNotification`. The sound event plays at most once every 2 s (`playMessageSound`). Views: `Views/Messages/` (`MessagesView.swift` list and row, `ConversationView.swift` header, bubbles and meta lines, `NewMessageView.swift`, `MessageComposer.swift` an `NSTextView` that grows to five lines: Return sends, Shift/Option-Return newline, Escape back, marked text is left to the input method, `MessageFormat.swift` the pure rules: row times, day separators, 2-minute groups, status lines, failure reasons). The To field of 14.3 shares the number field's directory search (`DirectoryRuntime.owner` says which of the two shows the results). `SegmentedTabs` has `widths: .byLabel` for the main tabs (each segment as wide as its label and badge plus an equal share of the rest, 12 pt). Strings: `messages.*`, `tabs.messages`, `contacts.menu.message`, `calllog.menu.message`, `settings.audio.soundEvents.message`. Peers: `ConversationAddress` (Core) decides who a conversation is with (see ENGINE.md "Storage"); `AppModel.conversation(account:address:)` looks one up, `Call` dials the stored `remoteURI`, `Conversation.shownNumber` is `user@host` where the host matters. `NewMessagePrefill.account` carries a call-log entry's account into 14.3 without touching the account row's choice for calls. "Read" needs `mainWindowIsKey`: key window of the active app, not occluded (`occlusionState`), screen not locked (`com.apple.screenIsLocked` / `screenIsUnlocked`, observed in `AppDelegate`); `updateMessageReadState` runs on unlock and on occlusion changes. The open thread's rows are built once per change (`AppModel.threadRows`). A code-0 failure shows "No connection" only for transport-like texts (`MessageFormat.isConnectionProblem`), otherwise the engine's own text. Deviations from the mockup that the spec leaves open: a typed address that already has a conversation switches to it when the address is committed (a suggestion picked, Return in To:), and Send with such an address sends into that conversation; messages that arrive for an account that is not in the app are dropped with a log line. - Directory (screen 13): `--demo-state directory|directory-done|directory-incoming|directory-sheet[-url|-google|-macos]|directory-import|directory-selftest` and `settings-directory`. Demo launches use `MockDirectory` (`Engine/MockDirectory.swift`): Company LDAP (answers in 0.45 s), Google Contacts (4 s, so use `--snapshot-after 3` for the "Searching Google Contacts…" row; `settings-directory` shows its sign-in as expired), macOS Contacts and a URL feed, from a fake address book in `DemoPeople`; nothing is sent anywhere. `directory` types "ka" in the number field; `directory-incoming` rings from 2214 (the lookup names the call); `directory-import` presses Import now on macOS Contacts; `directory-selftest` runs only the directory part of `selftest` (suggestions, lookup, import merge). UI code: `Views/Directory/` (suggestion list, source sheet), `Views/Settings/DirectoryPane.swift`, `Model/AppModel+Directory.swift` (search, lookup, import, schedule), `Model/DirectoryMerge.swift` (match by number, never duplicate; a card the source created follows the directory, a user's card only receives what it lacks; `Contact.importedFrom`); the real service is wrapped by `Engine/LiveDirectory.swift`. Error reasons are structured `DirectoryError` cases mapped to strings in `DirectoryStyle.text(for:)`; the Test button never writes to the Keychain (`DirectoryCredentials.overriding`). - Global hotkeys and MicroSIP import (26.1): `--demo-state settings-hotkeys|settings-hotkeys-on|import-microsip|import-microsip-done|hotkeys-selftest|import-selftest` (also part of `selftest`). `settings-hotkeys` opens Settings › Calls with the hotkeys on and the "could not be registered" message on Mute (`settings-hotkeys-on` is the same without the message); `import-microsip` writes a sample `MicroSIP.ini` and `Contacts.xml` to a temporary folder and opens the preview sheet (`-done` presses Import; the snapshot writes `-settings.png` and `-settings-sheet.png`). Example: `dist/MacroSIP.app/Contents/MacOS/MacroSIP --demo-state import-selftest --data-dir "$(mktemp -d)/x"` prints PASS/FAIL lines and `failures=N` (use a fresh `--data-dir` inside the system temp folder; demo launches clear it). Code: hotkeys `Core/Model/Hotkeys.swift` (combination, settings, validation, `HotkeyEffect.resolve`: what a press applies to, `HotkeyPressFilter`: a repeat of an action within 0.5 s counts once and a press older than 1 s is dropped, which is what an `NSMenu` open at the moment of the press leads to: Carbon holds the event until the menu closes; `HotkeyRecorderKeys`: the recorder takes the first press and swallows its repeats), `Platform/GlobalHotkeys.swift` (Carbon `RegisterEventHotKey`; the C callback hands the id and the event's age to the main actor; `stop()` before quit; a second process's registration of a held combination returns noErr, so macOS does not report another app's use of the same keys), `Model/AppModel+Hotkeys.swift` (applies `AppSettings.hotkeys` on every change, suspends while a recorder listens: `hotkeyListening` names the one row that does, and it ends on Esc, on another row's click and when the app or the window loses the keyboard, registers nothing in demo or mock launches unless `hotkeysInDemo` is set by a check; `hotkeys-selftest` registers real hotkeys on ⌃⌥⇧⌘F13 to F16 for a moment and simulates presses after Carbon's callback, never real keys); import `Core/Import/MicroSIPImport.swift` (read, merge, `save` reporting what was written, `recordSaved` for caller names, order and `accountsNeedingPassword`, limits: INI 1 MB, 1000 accounts, 20000 contacts), `Model/AppModel+Import.swift` (file panels, sheet state, the read and merge off the main actor; write: accounts through the store disabled and without Keychain access, contacts through the contact store and `loadStores`; `accountsNeedingPassword`, kept in the app's defaults, marks imported accounts that register until a password is saved, and `setAccountEnabled` opens the editor for them instead of enabling; an account with `registerWithServer` off needs no password) and `Views/Settings/MicroSIPImportSheet.swift` (at most 50 rows per list, then "and N more"). - Command-line import, for scripts and MDM, in every build: `/Applications/MacroSIP.app/Contents/MacOS/MacroSIP --import-microsip [--contacts ] [--data-dir ] [--dry-run]`. `AppEntry` in `MacroSIPApp.swift` handles it before any UI, Keychain or engine start, prints the report and exits: 0 done, 1 refused or failed, 2 wrong arguments. The code is `Core/Import/MicroSIPImportCommand.swift`; `macrosip-cli --import-microsip` is the same command, and only the running-app check (AppKit, leaves out the current process) is injected. Into the app's own directory it is refused while MacroSIP runs, and it writes caller names, order and password marks to the `com.hsmm.macrosip` defaults (`appDefaults()`: `.standard` inside the app, a suite elsewhere) and synchronizes before exit; with another `--data-dir` the preferences stay untouched. `--dry-run` writes nothing, and an existing store that cannot be read is an error message and is left as it is, in a real run too. - Hold music, sound events, audio test, notice tone, voicemail and Google sign-in: `--demo-state settings-audio|settings-recording|voicemail` (`settings-audio` and `settings-recording` are generic `settings-` states; `voicemail` lets the mock report two new messages on Office with `MockEngine.simulateVoicemail(account:new:old:)`, so the status bar shows the envelope badge and `-menu.txt` the "Voicemail: 2 new" item). `--demo-state selftest` checks all of them (`DemoState.soundChecks`) through the mock's records (`holdMusic`, `recordingNotice`, `playedSounds`, `testTones`, `voicemailState(for:)`). - **Hold music** (`AppSettings.audio.holdMusic`, Settings › Audio › Hold music: Built-in / Custom file… / Off): `AppModel.applyHoldMusic` hands it to `engine.setHoldMusic` at start and on every change (`updateSettings`); a file the engine cannot read leaves the engine's source alone and shows the reason in the group footer (`AppModel.holdMusicError`) and a banner. - - **Sound events** (`AppSettings.audio.soundEvents`, all off): `AppModel+Sounds.swift` decides, `engine.playEventSound` plays. `.callConnected` when a call becomes `.connected` without having been established before (a resume from hold is not a new connection), `.callEnded` for a call that was established (connected or held at some point; not a missed or declined ringing call, not a failed outgoing attempt), `.keyPress(digit)` from `dialPadPressed` while no call is active ("+" has no tone; the key pad during a call sends DTMF), `.voicemail` when an account reports more new messages than before, `.error` on a registration `.failed` or `.network(.offline)`, at most once per 10 s (`playErrorSound`). + - **Sound events** (`AppSettings.audio.soundEvents`, all off; `.message` is the 26.3 "New message" toggle: two short high beeps when a text message arrives, see Messages below): `AppModel+Sounds.swift` decides, `engine.playEventSound` plays. `.callConnected` when a call becomes `.connected` without having been established before (a resume from hold is not a new connection), `.callEnded` for a call that was established (connected or held at some point; not a missed or declined ringing call, not a failed outgoing attempt), `.keyPress(digit)` from `dialPadPressed` while no call is active ("+" has no tone; the key pad during a call sends DTMF), `.voicemail` when an account reports more new messages than before, `.error` on a registration `.failed` or `.network(.offline)`, at most once per 10 s (`playErrorSound`). - **Audio test**: Settings › Audio › Audio test, `AppModel.playTestTone` plays two notes for 2 s on the chosen speaker (`engine.playTestTone(outputDevice:seconds:)`, nil = system default); the microphone meter sits beside the button. **Headset buttons** is now a stored setting (`AppSettings.audio.headsetButtons`, default on, tolerant decoding) applied through `setHeadsetButtonsEnabled`; the row names the connected device (`headsetButtonsDevice`). - **Notice tone** (`AppSettings.recording.noticeTone`, `noticeToneIntervalSeconds` 5...60): Settings › Recording › Notice tone; `AppModel.applyRecordingNotice` calls `engine.setRecordingNotice` at start and on change. - **Voicemail (MWI)**: `AppModel.voicemail: [AccountID: VoicemailState]` follows `.voicemail` events (`handleVoicemail`) and is read from `engine.voicemailState(for:)` after the engine starts (`refreshVoicemail`); cleared on account removal and an engine restart. The account editor's Advanced section has the Voicemail group (`AccountConfig.voicemailNumber`, `AccountConfig.mwi`). The main window's status bar shows an envelope badge with the sum of new messages while any account has `waiting` (click dials the voicemail number: `callVoicemailFromBadge`); the menu bar menu has "Voicemail: N new" per enabled account with a number (`voicemailAccounts`), disabled while nothing waits, which calls `callVoicemail(for:)` through that account. The menu bar icon and the Dock badge are unchanged. `StatusItemController.debugMenuEntries()` returns the titles with their enabled state for the self-test. diff --git a/docs/ENGINE.md b/docs/ENGINE.md index 8aa87e7..630dc05 100644 --- a/docs/ENGINE.md +++ b/docs/ENGINE.md @@ -5,7 +5,7 @@ The engine is the only code that talks to PJSIP. The UI never imports `CPJSUA`. ## Threading model - PJSIP demands that every `pjsua_*` call comes from a thread registered with `pj_thread_register`, and that its callbacks are not blocked. - `Engine` is a Swift `actor` whose executor is a dedicated serial `DispatchQueue("macrosip.engine")`. The queue's thread registers itself with PJSIP on first use (`pj_thread_register` guarded by a thread-local flag). All `pjsua_*` calls run inside the actor. -- PJSIP callbacks (`on_reg_state2`, `on_incoming_call`, `on_call_state`, `on_call_media_state`, `on_call_transfer_status`, `on_buddy_state`, `on_dtmf_digit2`...) run on PJSIP worker threads. They copy the minimal data into an `EngineEvent` value and hand it to `Engine.events` (an `AsyncStream`), returning immediately. They never call back into the actor synchronously and never touch UI. +- PJSIP callbacks (`on_reg_state2`, `on_incoming_call`, `on_call_state`, `on_call_media_state`, `on_call_transfer_status`, `on_buddy_state`, `on_dtmf_digit2`, `on_pager2`, `on_pager_status2`...) run on PJSIP worker threads. They copy the minimal data into an `EngineEvent` value and hand it to `Engine.events` (an `AsyncStream`), returning immediately. They never call back into the actor synchronously and never touch UI. - `pjsua_config.thread_cnt = 1` and `cb` struct set once in `start()`. No `pjsua_handle_events` polling; the worker thread does it. - Audio device changes (`pjsua_set_snd_dev2`) also happen inside the actor. @@ -105,9 +105,16 @@ public enum EngineEvent: Sendable { case audioDevicesChanged case network(NetworkState) // on change, and once after start case voicemail(AccountID, waiting: Bool, new: Int, old: Int) // message-summary NOTIFY, when it changed + case messageReceived(IncomingMessage) // text/plain MESSAGE (see "Text messages") + case messageStatus(MessageID, MessageSendResult) // final outcome of sendMessage, once per id case log(level: Int, String) } +// text messages (see "Text messages (SIP MESSAGE)") +public struct MessageID: Hashable { public let raw: UUID } +public struct IncomingMessage: Equatable { public var accountID: AccountID; public var remote: RemoteParty; public var text: String; public var receivedAt: Date } +public enum MessageSendResult: Equatable { case accepted(code: Int), failed(code: Int, reason: String) } // 2xx = accepted, not delivered + // hold music, UI sounds, voicemail (see the sections of the same names) public enum HoldMusic: Codable { case builtIn, file(URL), off } // AppSettings.audio.holdMusic, default .builtIn public struct SoundEventSettings: Codable { public var callEvents, keyPress, voicemail, error: Bool } // all false @@ -185,6 +192,12 @@ public actor Engine { public func playTestTone(outputDevice: String?, seconds: Double) throws // device name from audioDevices(); nil = call output public func stopTestTone() public func playEventSound(_ event: SoundEvent) throws // on the call output only + + // text messages (SIP MESSAGE) + public func sendMessage(_ text: String, to dial: DialString, from account: AccountID) throws -> MessageID + public func sendMessage(_ text: String, to dial: DialString, from account: AccountID, id: MessageID) throws -> MessageID + public static let maxMessageBytes // 2800 UTF-8 bytes (PJSIP_MAX_PKT_LEN - 1200) + public static let messageInterruptedReason // "interrupted" } ``` @@ -204,6 +217,7 @@ Pure Swift, tested. ## Storage (MacroSIPCore, no PJSIP) - `JSONStore`: atomic write to `~/Library/Application Support/MacroSIP/.json` (`FileManager.replaceItemAt`), load with default on missing/corrupt (corrupt file renamed `.broken-`). - `AccountStore`, `ContactStore`, `CallLogStore`, `SettingsStore` wrap it. +- `MessageStore` keeps `messages.json` (`{ conversations, messages }`): conversations keyed by account and peer (`ConversationAddress`: a number by its digits, so `+375291234567`, `375 29 123-45-67` and the same number without its country prefix are one peer, extensions must be equal; the host counts when it is explicit and not the account's own domain, and always for a non-numeric user, so `bob@pbx` and `bob@partner.org` are two conversations; `Conversation.remoteHost`), unread counts (never more than the incoming messages left after a removal or a prune), state of each outgoing message; the oldest messages are dropped past the limit (5000). The file is read once and held in memory; every change is one write-through (a failed write leaves memory as it was); `replace(message:with:)` (Retry) and `conversation(...appending:)` (first message of a new conversation) are single writes. Records that cannot be decoded are skipped one by one (the original is kept as `messages.damaged-