From 50df3fd2478129cbed2be316295106736c45aab0 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:49:04 -0800 Subject: [PATCH 01/10] feat: add text rules for incoming messages - Filter channel, DM, and room messages using local rules. - Keep matches in Recently Blocked for review. - Handle missed room posts and interrupted radio cleanup. --- MC1/Resources/Generated/L10n.swift | 164 ++++++++ .../Localization/de.lproj/Settings.strings | 69 +++ .../Localization/en.lproj/Settings.strings | 67 +++ .../Localization/es.lproj/Settings.strings | 69 +++ .../Localization/fr.lproj/Settings.strings | 69 +++ .../Localization/it.lproj/Settings.strings | 69 +++ .../Localization/ko.lproj/Settings.strings | 69 +++ .../Localization/nl.lproj/Settings.strings | 69 +++ .../Localization/pl.lproj/Settings.strings | 69 +++ .../Localization/pt.lproj/Settings.strings | 69 +++ .../Localization/ru.lproj/Settings.strings | 69 +++ .../Localization/uk.lproj/Settings.strings | 69 +++ .../zh-Hans.lproj/Settings.strings | 69 +++ MC1/State/AppState+TextRules.swift | 21 + MC1/State/AppState+Wiring.swift | 7 +- MC1/State/AppState.swift | 12 + MC1/State/MessageEvent.swift | 8 +- MC1/State/MessageEventDispatcher.swift | 28 +- MC1/Views/Chats/ChatConversationView.swift | 2 +- .../ConversationTextRulesSection.swift | 128 ++++++ MC1/Views/Chats/Room/RoomInfoSheet.swift | 7 + MC1/Views/Chats/Sheets/ChannelInfoSheet.swift | 7 + .../ViewModel/ChatTimelinePopulator.swift | 11 +- .../ViewModel/ChatViewModel+EventStream.swift | 12 +- MC1/Views/Contacts/ContactDetailContent.swift | 12 +- .../Rooms/RoomConversationView.swift | 35 +- .../Rooms/RoomConversationViewModel.swift | 22 +- MC1/Views/Settings/ChatSettingsView.swift | 1 + .../Settings/Sections/BlockingSection.swift | 34 +- .../Sections/DangerZoneViewModel.swift | 21 +- .../Settings/Sections/NewTextRuleSheet.swift | 105 +++++ .../Sections/RadioCleanupSection.swift | 43 ++ .../Sections/RecentlyBlockedView.swift | 90 ++++ .../Settings/Sections/TextRuleChatsView.swift | 107 +++++ .../Sections/TextRulesLoadNotice.swift | 20 + .../Sections/TextRulesSettingsView.swift | 140 ++++++ MC1/Views/Settings/SettingsSubpage.swift | 11 +- .../ConnectionManager+Lifecycle.swift | 12 +- .../ConnectionManager+Pairing.swift | 56 +-- .../ConnectionManager+RadioErase.swift | 153 +++++++ .../ConnectionManager+TextRules.swift | 47 +++ .../Connection/ConnectionManager.swift | 18 +- .../Sources/MC1Services/Models/Channel.swift | 42 +- .../Sources/MC1Services/Models/Contact.swift | 32 +- .../Sources/MC1Services/Models/Message.swift | 6 +- .../Models/PendingRadioErase.swift | 50 +++ .../MC1Services/Models/ReceiveScope.swift | 38 ++ .../Models/RecentlyBlockedMessage.swift | 52 +++ .../Models/RecentlyBlockedMessageDTO.swift | 72 ++++ .../Models/RemoteNodeSession.swift | 22 +- .../Models/TextRulesPreference.swift | 239 +++++++++++ .../MessagePollingServiceProtocol.swift | 6 +- .../Persistence/ContactPersisting.swift | 10 +- .../Persistence/MessagePersisting.swift | 11 + .../Persistence/RoomPersisting.swift | 8 + .../Protocols/PersistenceStoreProtocol.swift | 96 ++++- .../MC1Services/ServiceContainer.swift | 22 +- .../Services/AdvertisementEvent.swift | 2 +- .../AdvertisementService+DeltaSync.swift | 23 +- .../Services/AdvertisementService.swift | 40 +- .../Services/DirectMessageAdmission.swift | 8 + .../Services/MessagePollingService.swift | 120 ++++-- .../Services/NotificationService.swift | 24 +- .../PersistenceStore+BackupBatchInsert.swift | 6 +- .../PersistenceStore+BackupImport.swift | 1 + .../PersistenceStore+ChannelReceive.swift | 50 +++ .../Services/PersistenceStore+Channels.swift | 2 + .../Services/PersistenceStore+Contacts.swift | 22 +- .../Services/PersistenceStore+Devices.swift | 90 ++-- ...ersistenceStore+DirectMessageReceive.swift | 179 ++++++++ .../Services/PersistenceStore+Messages.swift | 10 + .../PersistenceStore+RadioErase.swift | 115 +++++ .../PersistenceStore+RecentlyBlocked.swift | 75 ++++ ...stenceStore+RecentlyBlockedOwnership.swift | 69 +++ .../PersistenceStore+RoomReceive.swift | 105 +++++ .../Services/PersistenceStore+Rooms.swift | 42 +- ...sistenceStore+TextRulesConversations.swift | 172 ++++++++ .../Services/PersistenceStore.swift | 21 +- .../Services/ReactionService.swift | 18 +- .../Services/RemoteNodeService+Login.swift | 39 +- .../RemoteNodeService+RoomKeepAlive.swift | 121 ++++++ .../Services/RemoteNodeService.swift | 28 +- .../Services/RoomServerService.swift | 108 +++-- .../MC1Services/Services/RxLogService.swift | 15 +- .../Sync/SyncCoordinator+HandlerHelpers.swift | 84 ++-- .../SyncCoordinator+MessageHandlers.swift | 366 ++++++++-------- .../SyncCoordinator+ReactionHandlers.swift | 44 +- .../MC1Services/Sync/SyncCoordinator.swift | 5 +- .../MC1Services/Sync/SyncDataEvent.swift | 12 +- .../Utilities/ChannelMessageFormat.swift | 9 + .../AdvertisementServiceTests.swift | 43 +- .../ConnectionManagerPairingTests.swift | 209 ++++++++- .../Mocks/MockAccessorySetupKitService.swift | 6 + .../Mocks/MockMeshCoreSession.swift | 24 +- .../Mocks/MockMessagePollingService.swift | 12 +- .../Services/ChannelServiceTests.swift | 24 +- .../MessagePollingServiceTextTypeTests.swift | 2 +- .../Services/RoomKeepAliveRecoveryTests.swift | 398 ++++++++++++++++++ .../Services/RoomPostTextRulesTests.swift | 142 +++++++ .../Services/StockChannelTextRulesTests.swift | 135 ++++++ ...SyncCoordinatorBackgroundUnreadTests.swift | 12 +- .../SyncCoordinatorMessageHandlerTests.swift | 245 ++++++++++- .../SyncCoordinatorTests.swift | 6 +- .../TextRulesOwnershipTests.swift | 140 ++++++ .../TextRulesPreferenceTests.swift | 152 +++++++ .../ConnectionStatusLifecycleTests.swift | 6 +- MC1Tests/AppState/RadioEraseDiskTests.swift | 82 ++++ .../RecentlyBlockedPersistenceTests.swift | 158 +++++++ .../ChatChannelInfoPresentationTests.swift | 45 +- .../Views/SettingsRouteAdmissionTests.swift | 5 + .../Protocols/MessageFetchSessionOps.swift | 6 + .../Protocols/RemoteAccessSessionOps.swift | 19 +- .../Protocols/SessionEventStreaming.swift | 6 + .../Session/MeshCoreSession+Messaging.swift | 53 +-- .../MeshCore/Session/MeshCoreSession.swift | 30 +- .../MeshCoreSessionGetChannelsTests.swift | 51 +++ 116 files changed, 6177 insertions(+), 725 deletions(-) create mode 100644 MC1/State/AppState+TextRules.swift create mode 100644 MC1/Views/Chats/Components/ConversationTextRulesSection.swift create mode 100644 MC1/Views/Settings/Sections/NewTextRuleSheet.swift create mode 100644 MC1/Views/Settings/Sections/RadioCleanupSection.swift create mode 100644 MC1/Views/Settings/Sections/RecentlyBlockedView.swift create mode 100644 MC1/Views/Settings/Sections/TextRuleChatsView.swift create mode 100644 MC1/Views/Settings/Sections/TextRulesLoadNotice.swift create mode 100644 MC1/Views/Settings/Sections/TextRulesSettingsView.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift create mode 100644 MC1Services/Sources/MC1Services/Models/PendingRadioErase.swift create mode 100644 MC1Services/Sources/MC1Services/Models/ReceiveScope.swift create mode 100644 MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessage.swift create mode 100644 MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessageDTO.swift create mode 100644 MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift create mode 100644 MC1Services/Sources/MC1Services/Services/DirectMessageAdmission.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+RadioErase.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlocked.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlockedOwnership.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+RoomReceive.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+TextRulesConversations.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RemoteNodeService+RoomKeepAlive.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/RoomKeepAliveRecoveryTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/StockChannelTextRulesTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift create mode 100644 MC1Tests/AppState/RadioEraseDiskTests.swift create mode 100644 MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 376ab482ca..25e6054ece 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -5539,6 +5539,20 @@ public enum L10n { } } } + public enum RadioCleanup { + /// Radio data removed + public static let completed = L10n.tr("Settings", "radioCleanup.completed", fallback: "Radio data removed") + /// Hidden messages from this radio may still be on this installation. + public static let failed = L10n.tr("Settings", "radioCleanup.failed", fallback: "Hidden messages from this radio may still be on this installation.") + /// Try Radio Cleanup Again for %@ + public static func retryAccessibility(_ p1: Any) -> String { + return L10n.tr("Settings", "radioCleanup.retryAccessibility", String(describing: p1), fallback: "Try Radio Cleanup Again for %@") + } + /// Removing radio data + public static let running = L10n.tr("Settings", "radioCleanup.running", fallback: "Removing radio data") + /// Cleanup + public static let title = L10n.tr("Settings", "radioCleanup.title", fallback: "Cleanup") + } public enum RadioWiFi { /// Button that clears the radio's saved WiFi settings public static let clear = L10n.tr("Settings", "radioWiFi.clear", fallback: "Clear WiFi Settings") @@ -6069,6 +6083,156 @@ public enum L10n { /// Description for trusted contacts toggle public static let trustedOnlyDescription = L10n.tr("Settings", "telemetry.trustedOnlyDescription", fallback: "Limit telemetry to selected contacts") } + public enum TextRules { + /// Deleting a rule leaves its hidden messages in Recently Blocked. + public static let deleteFooter = L10n.tr("Settings", "textRules.deleteFooter", fallback: "Deleting a rule leaves its hidden messages in Recently Blocked.") + /// No Text Rules + public static let empty = L10n.tr("Settings", "textRules.empty", fallback: "No Text Rules") + /// Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded. + public static let loadFailed = L10n.tr("Settings", "textRules.loadFailed", fallback: "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded.") + /// A sender-name match also hides incoming emoji reactions from that sender. + public static let reactionFooter = L10n.tr("Settings", "textRules.reactionFooter", fallback: "A sender-name match also hides incoming emoji reactions from that sender.") + /// Try Loading Text Rules Again + public static let retryAccessibility = L10n.tr("Settings", "textRules.retryAccessibility", fallback: "Try Loading Text Rules Again") + /// Rules + public static let rules = L10n.tr("Settings", "textRules.rules", fallback: "Rules") + /// %1$@ · %2$@ + public static func ruleSummary(_ p1: Any, _ p2: Any) -> String { + return L10n.tr("Settings", "textRules.ruleSummary", String(describing: p1), String(describing: p2), fallback: "%1$@ · %2$@") + } + /// Could not save Text Rules. Try again. + public static let saveFailed = L10n.tr("Settings", "textRules.saveFailed", fallback: "Could not save Text Rules. Try again.") + /// Text Rules + public static let title = L10n.tr("Settings", "textRules.title", fallback: "Text Rules") + public enum Archive { + /// No Hidden Messages + public static let empty = L10n.tr("Settings", "textRules.archive.empty", fallback: "No Hidden Messages") + /// Message and Sender + public static let fieldsBoth = L10n.tr("Settings", "textRules.archive.fieldsBoth", fallback: "Message and Sender") + /// The latest %d hidden messages are kept on this installation and are excluded from shareable backups. + public static func footer(_ p1: Int) -> String { + return L10n.tr("Settings", "textRules.archive.footer", p1, fallback: "The latest %d hidden messages are kept on this installation and are excluded from shareable backups.") + } + /// Matched “%1$@” in %2$@ (%3$@) + public static func reason(_ p1: Any, _ p2: Any, _ p3: Any) -> String { + return L10n.tr("Settings", "textRules.archive.reason", String(describing: p1), String(describing: p2), String(describing: p3), fallback: "Matched “%1$@” in %2$@ (%3$@)") + } + /// Recently Blocked + public static let title = L10n.tr("Settings", "textRules.archive.title", fallback: "Recently Blocked") + /// Unknown Conversation + public static let unknownConversation = L10n.tr("Settings", "textRules.archive.unknownConversation", fallback: "Unknown Conversation") + /// Unknown Radio + public static let unknownRadio = L10n.tr("Settings", "textRules.archive.unknownRadio", fallback: "Unknown Radio") + } + public enum Field { + /// Message + public static let message = L10n.tr("Settings", "textRules.field.message", fallback: "Message") + /// This rule checks the message body. + public static let messageFooter = L10n.tr("Settings", "textRules.field.messageFooter", fallback: "This rule checks the message body.") + /// Message or Sender + public static let messageOrSender = L10n.tr("Settings", "textRules.field.messageOrSender", fallback: "Message or Sender") + /// This rule checks the message and sender name separately. Either field can match. + public static let messageOrSenderFooter = L10n.tr("Settings", "textRules.field.messageOrSenderFooter", fallback: "This rule checks the message and sender name separately. Either field can match.") + /// Sender + public static let sender = L10n.tr("Settings", "textRules.field.sender", fallback: "Sender") + /// This rule checks the sender name. + public static let senderFooter = L10n.tr("Settings", "textRules.field.senderFooter", fallback: "This rule checks the sender name.") + } + public enum Info { + /// The saved conversation is unavailable. + public static let conversationUnavailable = L10n.tr("Settings", "textRules.info.conversationUnavailable", fallback: "The saved conversation is unavailable.") + /// Not included in %@ + public static func excluded(_ p1: Any) -> String { + return L10n.tr("Settings", "textRules.info.excluded", String(describing: p1), fallback: "Not included in %@") + } + /// Set for this conversation + public static let explicit = L10n.tr("Settings", "textRules.info.explicit", fallback: "Set for this conversation") + /// Follows %@ + public static func follows(_ p1: Any) -> String { + return L10n.tr("Settings", "textRules.info.follows", String(describing: p1), fallback: "Follows %@") + } + /// The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation. + public static let footer = L10n.tr("Settings", "textRules.info.footer", fallback: "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation.") + /// %1$@ (%2$@) + public static func inheritedChoice(_ p1: Any, _ p2: Any) -> String { + return L10n.tr("Settings", "textRules.info.inheritedChoice", String(describing: p1), String(describing: p2), fallback: "%1$@ (%2$@)") + } + /// Off for This Channel + public static let offChannel = L10n.tr("Settings", "textRules.info.offChannel", fallback: "Off for This Channel") + /// Off for This DM + public static let offDm = L10n.tr("Settings", "textRules.info.offDm", fallback: "Off for This DM") + /// Off for This Room + public static let offRoom = L10n.tr("Settings", "textRules.info.offRoom", fallback: "Off for This Room") + /// On for This Channel + public static let onChannel = L10n.tr("Settings", "textRules.info.onChannel", fallback: "On for This Channel") + /// On for This DM + public static let onDm = L10n.tr("Settings", "textRules.info.onDm", fallback: "On for This DM") + /// On for This Room + public static let onRoom = L10n.tr("Settings", "textRules.info.onRoom", fallback: "On for This Room") + /// Radio %@ + public static func radio(_ p1: Any) -> String { + return L10n.tr("Settings", "textRules.info.radio", String(describing: p1), fallback: "Radio %@") + } + /// Effective Setting + public static let status = L10n.tr("Settings", "textRules.info.status", fallback: "Effective Setting") + /// Unavailable + public static let unavailable = L10n.tr("Settings", "textRules.info.unavailable", fallback: "Unavailable") + } + public enum Match { + /// Contains + public static let contains = L10n.tr("Settings", "textRules.match.contains", fallback: "Contains") + /// Whole Field + public static let wholeField = L10n.tr("Settings", "textRules.match.wholeField", fallback: "Whole Field") + /// Whole Message + public static let wholeMessage = L10n.tr("Settings", "textRules.match.wholeMessage", fallback: "Whole Message") + /// Whole Name + public static let wholeName = L10n.tr("Settings", "textRules.match.wholeName", fallback: "Whole Name") + } + public enum New { + /// The phrase can match anywhere in the selected field, including inside a word. + public static let containsFooter = L10n.tr("Settings", "textRules.new.containsFooter", fallback: "The phrase can match anywhere in the selected field, including inside a word.") + /// Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations. + public static let deliveryFooter = L10n.tr("Settings", "textRules.new.deliveryFooter", fallback: "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations.") + /// Look In + public static let lookIn = L10n.tr("Settings", "textRules.new.lookIn", fallback: "Look In") + /// Match + public static let match = L10n.tr("Settings", "textRules.new.match", fallback: "Match") + /// Word or phrase + public static let phrase = L10n.tr("Settings", "textRules.new.phrase", fallback: "Word or phrase") + /// New Rule + public static let title = L10n.tr("Settings", "textRules.new.title", fallback: "New Rule") + /// The phrase must match the entire field. + public static let wholeFieldFooter = L10n.tr("Settings", "textRules.new.wholeFieldFooter", fallback: "The phrase must match the entire field.") + } + public enum Selection { + /// Chats for %@ + public static func accessibilityChats(_ p1: Any) -> String { + return L10n.tr("Settings", "textRules.selection.accessibilityChats", String(describing: p1), fallback: "Chats for %@") + } + /// All + public static let all = L10n.tr("Settings", "textRules.selection.all", fallback: "All") + /// %d Chats + public static func count(_ p1: Int) -> String { + return L10n.tr("Settings", "textRules.selection.count", p1, fallback: "%d Chats") + } + /// All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence. + public static let footer = L10n.tr("Settings", "textRules.selection.footer", fallback: "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence.") + /// None + public static let `none` = L10n.tr("Settings", "textRules.selection.none", fallback: "None") + } + public enum Types { + /// Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence. + public static let footer = L10n.tr("Settings", "textRules.types.footer", fallback: "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence.") + /// Hashtag Channels + public static let hashtagChannel = L10n.tr("Settings", "textRules.types.hashtagChannel", fallback: "Hashtag Channels") + /// Use rules for + public static let header = L10n.tr("Settings", "textRules.types.header", fallback: "Use rules for") + /// Private Channels + public static let privateChannel = L10n.tr("Settings", "textRules.types.privateChannel", fallback: "Private Channels") + /// Public + public static let publicChannel = L10n.tr("Settings", "textRules.types.publicChannel", fallback: "Public") + } + } public enum TrustedContacts { /// Apply button label public static let apply = L10n.tr("Settings", "trustedContacts.apply", fallback: "Apply") diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index 2a5d75eb2c..ad55be23a2 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -1449,6 +1449,75 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Das Anzeigen von Karten-Miniaturansichten lädt Kartenkacheln für die Koordinate von einem Drittanbieter-Server, was Ihre IP-Adresse offenlegen kann."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index bbeefe8db6..baf969589b 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -1437,6 +1437,73 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "No empty channel slot available for \"%@\""; +// MARK: - Text Rules + +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index 57647f90a6..7f21ef04eb 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -1449,6 +1449,75 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Mostrar miniaturas del mapa descarga las teselas para la coordenada desde un servidor de terceros, lo que puede revelar tu dirección IP."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index 6af9737e8f..2c29b2faa8 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -1449,6 +1449,75 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "L'affichage des vignettes de carte télécharge les tuiles pour la coordonnée depuis un serveur tiers, ce qui peut révéler votre adresse IP."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 6ca2381d60..25a21df045 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -1447,6 +1447,75 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "Nessuno slot canale libero disponibile per “%@”"; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index 4e97d7b498..fcacf97d29 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -1437,6 +1437,75 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "\"%@\"에 사용할 빈 채널 슬롯이 없습니다"; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index 7cc9c67fa1..f8353dca24 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -1449,6 +1449,75 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Het tonen van kaartminiaturen haalt kaarttegels voor de coördinaat op bij een externe server, waardoor uw IP-adres kan worden onthuld."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index 50e34031c9..cfeebfce02 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -1449,6 +1449,75 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Wyświetlanie miniatur mapy pobiera kafelki dla współrzędnych z serwera zewnętrznego, co może ujawnić Twój adres IP."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index b4709070f8..f1afbe40a3 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -1447,6 +1447,75 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "Nenhum slot de canal vazio disponível para \"%@\""; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index 8999e4f348..b935840f96 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -1449,6 +1449,75 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Отображение миниатюр карты загружает плитки для координаты со стороннего сервера, что может раскрыть ваш IP-адрес."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index fad917c184..eb51b9f423 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -1449,6 +1449,75 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Відображення мініатюр карти завантажує плитки для координати зі стороннього сервера, що може розкрити вашу IP-адресу."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index 06f5466913..6bb9fd41cc 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -1449,6 +1449,75 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "显示地图缩略图会从第三方服务器获取该坐标的地图图块,可能会暴露您的IP地址。"; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.title" = "Text Rules"; +"textRules.rules" = "Rules"; +"textRules.empty" = "No Text Rules"; +"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; +"textRules.retryAccessibility" = "Try Loading Text Rules Again"; +"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; +"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; +"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; +"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.field.messageFooter" = "This rule checks the message body."; +"textRules.field.senderFooter" = "This rule checks the sender name."; +"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.fieldsBoth" = "Message and Sender"; +"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate conversation Text Rules and radio Cleanup strings */ +"textRules.info.status" = "Effective Setting"; +"textRules.info.unavailable" = "Unavailable"; +"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; +"textRules.info.onChannel" = "On for This Channel"; +"textRules.info.offChannel" = "Off for This Channel"; +"textRules.info.onDm" = "On for This DM"; +"textRules.info.offDm" = "Off for This DM"; +"textRules.info.onRoom" = "On for This Room"; +"textRules.info.offRoom" = "Off for This Room"; +"textRules.info.follows" = "Follows %@"; +"textRules.info.excluded" = "Not included in %@"; +"textRules.info.explicit" = "Set for this conversation"; +"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; +"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; +"textRules.info.radio" = "Radio %@"; +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ diff --git a/MC1/State/AppState+TextRules.swift b/MC1/State/AppState+TextRules.swift new file mode 100644 index 0000000000..70dc9130f7 --- /dev/null +++ b/MC1/State/AppState+TextRules.swift @@ -0,0 +1,21 @@ +import MC1Services + +extension AppState { + func setTextRulesOverride( + _ choice: TextRulesPreference.Override, + kind: TextRulesPreference.Kind, + key: TextRulesPreference.Key + ) { + guard textRulesPreference != nil, textRulesOverrideWrites.insert(key).inserted else { return } + textRulesOverrideErrors[key] = nil + Task { + defer { textRulesOverrideWrites.remove(key) } + do { + try await connectionManager.persistenceStore.setTextRulesOverride(choice, kind: kind, key: key) + textRulesOverrideVersion += 1 + } catch { + textRulesOverrideErrors[key] = L10n.Settings.TextRules.saveFailed + } + } + } +} diff --git a/MC1/State/AppState+Wiring.swift b/MC1/State/AppState+Wiring.swift index 7a4ec8aece..48774cd63a 100644 --- a/MC1/State/AppState+Wiring.swift +++ b/MC1/State/AppState+Wiring.swift @@ -112,7 +112,12 @@ extension AppState { for await event in advertisementEvents { guard let self else { return } switch event { - case .contactUpdated: + case let .contactUpdated(contact, scope): + if let contact, let scope { + let store = connectionManager.persistenceStore + guard await (try? store.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { continue } + } contactsVersion += 1 PersistentLogger(subsystem: "com.mc1", category: "discover-trace") .debug("B4 contactUpdated bump contactsVersion=\(contactsVersion)") diff --git a/MC1/State/AppState.swift b/MC1/State/AppState.swift index b12ae588cf..8122beba52 100644 --- a/MC1/State/AppState.swift +++ b/MC1/State/AppState.swift @@ -219,6 +219,18 @@ final class AppState { return connectionManager.persistenceStore } + var textRulesOverrideWrites: Set = [] + var textRulesOverrideErrors: [TextRulesPreference.Key: String] = [:] + var textRulesOverrideVersion = 0 + + var textRulesPreference: TextRulesPreference? { + connectionManager.textRulesPreference + } + + var isTextRulesLoading: Bool { + connectionManager.isTextRulesLoading + } + /// Sole lazy factory for the process-lifetime registry. Bound to the /// process store; `wireServicesIfConnected` neither creates nor rebinds it. func ensureChatCoordinatorRegistry() -> ChatCoordinatorRegistry? { diff --git a/MC1/State/MessageEvent.swift b/MC1/State/MessageEvent.swift index fbb3790548..03696dd6ad 100644 --- a/MC1/State/MessageEvent.swift +++ b/MC1/State/MessageEvent.swift @@ -8,9 +8,11 @@ import MC1Services /// exhaustively (no `default`) so a new case becomes a compile error /// rather than a silent skip. enum MessageEvent: Equatable { - case directMessageReceived(message: MessageDTO, contact: ContactDTO) - case channelMessageReceived(message: MessageDTO, channelIndex: UInt8) - case roomMessageReceived(message: RoomMessageDTO, sessionID: UUID) + case directMessageReceived(message: MessageDTO, contact: ContactDTO, scope: ReceiveScope? = nil) + case channelMessageReceived( + message: MessageDTO, channelIndex: UInt8, legacyScope: ReceiveScope? = nil + ) + case roomMessageReceived(message: RoomMessageDTO, sessionID: UUID, roomID: UUID? = nil, scope: ReceiveScope? = nil) /// Fired when a message's status resolves to .sent or .delivered for an /// original (non-resend) send. `roundTripTime` is supplied only when firmware /// reports it (.delivered via end-to-end ACK); .sent transitions and diff --git a/MC1/State/MessageEventDispatcher.swift b/MC1/State/MessageEventDispatcher.swift index 2d16bbcf35..f5de74cb79 100644 --- a/MC1/State/MessageEventDispatcher.swift +++ b/MC1/State/MessageEventDispatcher.swift @@ -52,20 +52,34 @@ final class MessageEventDispatcher { let task = Task { [weak appState, stream] in for await event in events { switch event { - case let .directMessageReceived(message, contact): - stream.send(.directMessageReceived(message: message, contact: contact)) + case let .directMessageReceived(message, contact, scope): + if let scope { + guard let store = appState?.connectionManager.persistenceStore, + await (try? store.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { continue } + } + stream.send(.directMessageReceived(message: message, contact: contact, scope: scope)) // Keep a closed conversation's warm coordinator current so a reopen // renders the new tail on the first frame (no-op when open or cold). appState?.ensureChatPrewarmRefresher().noteDirectMessage(contact: contact) - case let .channelMessageReceived(message, channelIndex): - stream.send(.channelMessageReceived(message: message, channelIndex: channelIndex)) + case let .channelMessageReceived(message, channelIndex, legacyScope): + guard legacyScope?.isCurrent != false else { continue } + stream.send(.channelMessageReceived( + message: message, channelIndex: channelIndex, legacyScope: legacyScope + )) appState?.ensureChatPrewarmRefresher().noteChannelMessage( radioID: message.radioID, channelIndex: channelIndex ) - case let .roomMessageReceived(message): - stream.send(.roomMessageReceived(message: message, sessionID: message.sessionID)) - case let .reactionReceived(messageID, summary): + case let .roomMessageReceived(message, roomID, scope): + guard scope.isCurrent else { continue } + stream.send(.roomMessageReceived(message: message, sessionID: message.sessionID, roomID: roomID, scope: scope)) + case let .reactionReceived(messageID, summary, scope, contact): + if let scope, let contact { + guard let store = appState?.connectionManager.persistenceStore, + await (try? store.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { continue } + } stream.send(.reactionReceived(messageID: messageID, summary: summary)) await appState?.handleReactionNotification(messageID: messageID) case .contactsChanged, .conversationsChanged: diff --git a/MC1/Views/Chats/ChatConversationView.swift b/MC1/Views/Chats/ChatConversationView.swift index 86297b327c..46e80f8119 100644 --- a/MC1/Views/Chats/ChatConversationView.swift +++ b/MC1/Views/Chats/ChatConversationView.swift @@ -536,7 +536,7 @@ struct ChatConversationView: View { private func refreshChannel() async throws { guard case let .channel(channel) = conversationType else { return } guard let dataStore = appState.offlineDataStore else { throw ConnectionError.notConnected } - guard let updated = try await dataStore.fetchChannel(id: channel.id) else { + guard let updated = try await dataStore.fetchChannelForInfo(id: channel.id) else { throw PersistenceStoreError.channelNotFound } try Task.checkCancellation() diff --git a/MC1/Views/Chats/Components/ConversationTextRulesSection.swift b/MC1/Views/Chats/Components/ConversationTextRulesSection.swift new file mode 100644 index 0000000000..a94cb82e0b --- /dev/null +++ b/MC1/Views/Chats/Components/ConversationTextRulesSection.swift @@ -0,0 +1,128 @@ +import MC1Services +import SwiftUI + +struct ConversationTextRulesSection: View { + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + + private typealias Strings = L10n.Settings.TextRules.Info + + let kind: TextRulesPreference.Kind + let radioID: UUID + let conversationID: UUID? + let savedChoice: TextRulesPreference.Override + + @State private var committedChoice: TextRulesPreference.Override? + @State private var radioName: String? + + private var key: TextRulesPreference.Key? { + conversationID.map { .init(radioID: radioID, conversationID: $0) } + } + + private var selectedChoice: TextRulesPreference.Override { + committedChoice ?? savedChoice + } + + private var effective: TextRulesPreference.Effective? { + guard key != nil else { return nil } + return appState.textRulesPreference?.effective(for: kind, key: key, override: selectedChoice) + } + + private var isSaving: Bool { + key.map(appState.textRulesOverrideWrites.contains) ?? false + } + + private var errorMessage: Binding { + Binding( + get: { key.flatMap { appState.textRulesOverrideErrors[$0] } }, + set: { value in + if let key { appState.textRulesOverrideErrors[key] = value } + } + ) + } + + var body: some View { + Section { + LabeledContent(Strings.status, value: effective.map { status($0.isOn) } ?? Strings.unavailable) + if let effective { + Text(source(effective.source)) + .font(.subheadline) + .foregroundStyle(.secondary) + } + + Picker(L10n.Settings.TextRules.title, selection: Binding( + get: { selectedChoice }, + set: { choice in + guard let key, choice != selectedChoice else { return } + appState.setTextRulesOverride(choice, kind: kind, key: key) + } + )) { + Text(inheritedLabel).tag(TextRulesPreference.Override.inherit) + Text(explicitLabel(isOn: true)).tag(TextRulesPreference.Override.on) + Text(explicitLabel(isOn: false)).tag(TextRulesPreference.Override.off) + } + .pickerStyle(.inline) + .labelsHidden() + .disabled(effective == nil || isSaving) + + if isSaving { + ProgressView() + } + } header: { + Text(L10n.Settings.TextRules.title) + } footer: { + VStack(alignment: .leading) { + if appState.textRulesPreference == nil { + Text(L10n.Settings.TextRules.loadFailed) + } else if key == nil { + Text(Strings.conversationUnavailable) + } else { + Text(Strings.footer) + } + if let radioName { + Text(Strings.radio(radioName)) + } + } + } + .themedRowBackground(theme) + .task(id: appState.textRulesOverrideVersion) { + let store = appState.connectionManager.persistenceStore + if let key, let conversation = try? await store.textRulesConversation(kind: kind, key: key) { + committedChoice = conversation.override + let radios = try? await store.fetchDevices() + if let radios, Set(radios.map(\.radioID)).count > 1 { + radioName = conversation.radioName + } + } + } + .errorAlert(errorMessage) + } + + private var inheritedLabel: String { + guard let preference = appState.textRulesPreference else { return kind.title } + return Strings.inheritedChoice(kind.title, status(preference.selection(for: kind).isOn)) + } + + private func explicitLabel(isOn: Bool) -> String { + switch kind { + case .publicChannel, .hashtagChannel, .privateChannel: + isOn ? Strings.onChannel : Strings.offChannel + case .directMessage: + isOn ? Strings.onDm : Strings.offDm + case .room: + isOn ? Strings.onRoom : Strings.offRoom + } + } + + private func status(_ enabled: Bool) -> String { + enabled ? L10n.Localizable.Accessibility.on : L10n.Localizable.Accessibility.off + } + + private func source(_ source: TextRulesPreference.Effective.Source) -> String { + switch source { + case .type: Strings.follows(kind.title) + case .fixedExclusion: Strings.excluded(kind.title) + case .explicit: Strings.explicit + } + } +} diff --git a/MC1/Views/Chats/Room/RoomInfoSheet.swift b/MC1/Views/Chats/Room/RoomInfoSheet.swift index 2feac503ef..09a6f2909f 100644 --- a/MC1/Views/Chats/Room/RoomInfoSheet.swift +++ b/MC1/Views/Chats/Room/RoomInfoSheet.swift @@ -85,6 +85,13 @@ struct RoomInfoSheet: View { .themedRowBackground(theme) } + ConversationTextRulesSection( + kind: .room, + radioID: session.radioID, + conversationID: session.textRulesID, + savedChoice: session.textRulesOverride + ) + if session.isConnected { Section { Button { showTelemetry = true } label: { diff --git a/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift b/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift index d52bef832b..30dbe0bd8c 100644 --- a/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift +++ b/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift @@ -91,6 +91,13 @@ struct ChannelInfoSheet: View { .themedRowBackground(theme) } + ConversationTextRulesSection( + kind: TextRulesPreference.channelKind(isPublic: channel.isPublicChannel, name: channel.name), + radioID: channel.radioID, + conversationID: channel.textRulesID, + savedChoice: channel.textRulesOverride + ) + // Region Scope Section ChannelInfoRegionSection( knownRegions: knownRegions, diff --git a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift index caaa6d23d5..2035dbfd61 100644 --- a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift +++ b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift @@ -161,7 +161,7 @@ enum ChatTimelinePopulator { channelIndex: channel.index, senderName: senderName, text: message.text, - timestamp: message.timestamp + timestamp: message.reactionTimestamp ) for pending in pendingMatches { @@ -206,7 +206,8 @@ enum ChatTimelinePopulator { reactionDTO, reactionService: reactionService, dataStore: dataStore, - writer: writer + writer: writer, + directMessage: pending.directMessage ) } } @@ -217,7 +218,8 @@ enum ChatTimelinePopulator { _ reaction: ReactionDTO, reactionService: ReactionService, dataStore: DataStore, - writer: ChatTimelineWriter + writer: ChatTimelineWriter, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? = nil ) async { let exists = try? await dataStore.reactionExists( messageID: reaction.messageID, @@ -228,7 +230,8 @@ enum ChatTimelinePopulator { if let result = await reactionService.persistReactionAndUpdateSummary( reaction, - using: dataStore + using: dataStore, + directMessage: directMessage ) { writer.enqueueReload(messageID: result.messageID) } diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift index e57951e0e9..0d6edb22d0 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift @@ -11,15 +11,21 @@ extension ChatViewModel { /// Incoming messages are inserted in event order before their previews load. func handle(_ event: MessageEvent) async { switch event { - case let .directMessageReceived(message, contact): + case let .directMessageReceived(message, contact, scope): guard let current = currentContact, current.id == contact.id else { return } + if let scope { + guard let dataStore, + await (try? dataStore.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent, currentContact?.id == contact.id else { return } + } admitIncomingMessage(message, isChannelMessage: false) recordIncomingMentionIfNeeded(message) - case let .channelMessageReceived(message, channelIndex): + case let .channelMessageReceived(message, channelIndex, legacyScope): guard let channel = currentChannel, channel.index == channelIndex, - message.radioID == channel.radioID else { return } + message.radioID == channel.radioID, + legacyScope?.isCurrent != false else { return } admitIncomingMessage(message, isChannelMessage: true) recordIncomingMentionIfNeeded(message) diff --git a/MC1/Views/Contacts/ContactDetailContent.swift b/MC1/Views/Contacts/ContactDetailContent.swift index c794b517ee..f984e72539 100644 --- a/MC1/Views/Contacts/ContactDetailContent.swift +++ b/MC1/Views/Contacts/ContactDetailContent.swift @@ -55,6 +55,15 @@ struct ContactDetailContent: View { ) .themedRowBackground(theme) + if state.showFromDirectChat { + ConversationTextRulesSection( + kind: .directMessage, + radioID: state.currentContact.radioID, + conversationID: state.currentContact.textRulesID, + savedChoice: state.currentContact.textRulesOverride + ) + } + ContactDetailInfoSection( state: state, rendererID: rendererID, rendererRevision: rendererRevision, onRowPosition: recordRowPosition @@ -159,8 +168,7 @@ struct ContactDetailContent: View { } private func updateVisibleSection() { - guard isCurrentRenderer else { return } - guard let section = visibleSection else { return } + guard isCurrentRenderer, let section = visibleSection else { return } if !restoredScroll { guard section == restorationTarget else { return } restoredScroll = true diff --git a/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift b/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift index 11a519e3ab..49ea745d2e 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift @@ -63,6 +63,18 @@ struct RoomConversationView: View { onTitleTap: { showingRoomInfo = true } ) .toolbar { + ToolbarItem(placement: .primaryAction) { + if viewModel.isRefreshing { + ProgressView(L10n.RemoteNodes.RemoteNodes.Status.refresh) + .labelsHidden() + } else { + Button(L10n.RemoteNodes.RemoteNodes.Status.refresh, systemImage: "arrow.clockwise") { + let room = session + Task { await viewModel.refreshMessages(for: room) } + } + .disabled(appState.services == nil || !session.isConnected || appState.currentRadioID != session.radioID) + } + } if #unavailable(iOS 26) { ToolbarItem(placement: .primaryAction) { Button(L10n.RemoteNodes.RemoteNodes.Room.infoTitle, systemImage: "info.circle") { @@ -176,6 +188,7 @@ struct RoomConversationView: View { .task(id: appState.servicesVersion) { // Reassert the active room when servicesVersion changes because reconnect replaces NotificationService. appState.services?.notificationService.setActiveConversation(roomSessionID: session.id) + await startKeepAliveIfConnected() } .task { for await event in appState.messageEventStream.events() { @@ -190,17 +203,12 @@ struct RoomConversationView: View { } } } - .task(id: session.isConnected) { - guard session.isConnected else { return } - await appState.services?.remoteNodeService.startSessionKeepAlive( - sessionID: session.id, publicKey: session.publicKey - ) - } .onChange(of: session.isConnected) { _, isConnected in if isConnected { AccessibilityNotification.Announcement( L10n.RemoteNodes.RemoteNodes.Room.reconnected ).post() + Task { await startKeepAliveIfConnected() } } } .onChange(of: scenePhase) { _, newPhase in @@ -212,13 +220,7 @@ struct RoomConversationView: View { .removeDeliveredNotifications(forRoomSessionID: session.id) await appState.services?.notificationService.updateBadgeCount() } - if session.isConnected { - Task { - await appState.services?.remoteNodeService.startSessionKeepAlive( - sessionID: session.id, publicKey: session.publicKey - ) - } - } + Task { await startKeepAliveIfConnected() } } } .onDisappear { @@ -236,6 +238,13 @@ struct RoomConversationView: View { } } + private func startKeepAliveIfConnected() async { + guard session.isConnected, appState.currentRadioID == session.radioID else { return } + await appState.services?.remoteNodeService.startSessionKeepAlive( + sessionID: session.id, publicKey: session.publicKey + ) + } + private var connectionStatus: String { if session.isConnected { return session.permissionLevel.localizedName diff --git a/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift b/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift index ef974c471a..83b6f43262 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift @@ -55,6 +55,7 @@ final class RoomConversationViewModel { /// Whether a message is being sent var isSending = false + private(set) var isRefreshing = false // MARK: - Dependencies @@ -185,6 +186,21 @@ final class RoomConversationViewModel { isSending = false } + func refreshMessages(for room: RemoteNodeSessionDTO) async { + guard !isRefreshing, let roomServerService else { return } + isRefreshing = true + errorMessage = nil + defer { isRefreshing = false } + + do { + try await roomServerService.refreshMessages(for: room) + } catch is CancellationError { + return + } catch { + errorMessage = error.userFacingMessage + } + } + /// Refresh session state from database func refreshSession() async { guard let session, let dataStore else { return } @@ -202,11 +218,13 @@ final class RoomConversationViewModel { guard let session else { return } switch event { - case let .roomMessageReceived(message, sessionID): + case let .roomMessageReceived(message, sessionID, roomID, scope): // Optimistic append first so the message list sees the new count // immediately for unread tracking, then coalesce the reload so a // burst of incoming room messages triggers one DB sync, not N. - guard sessionID == session.id else { return } + guard sessionID == session.id, + roomID == nil || roomID == session.textRulesID, + scope?.isCurrent != false else { return } appendMessageIfNew(message) scheduleCoalescedReload() diff --git a/MC1/Views/Settings/ChatSettingsView.swift b/MC1/Views/Settings/ChatSettingsView.swift index 21f20f939a..5db0745822 100644 --- a/MC1/Views/Settings/ChatSettingsView.swift +++ b/MC1/Views/Settings/ChatSettingsView.swift @@ -20,6 +20,7 @@ struct ChatSettingsView: View { MapPreviewSettingsSection() MessagesSettingsSection() BlockingSection() + RadioCleanupSection() } .themedCanvas(theme) .settingsSubpageDestinations() diff --git a/MC1/Views/Settings/Sections/BlockingSection.swift b/MC1/Views/Settings/Sections/BlockingSection.swift index 6fa72ba518..cf0255d5aa 100644 --- a/MC1/Views/Settings/Sections/BlockingSection.swift +++ b/MC1/Views/Settings/Sections/BlockingSection.swift @@ -1,12 +1,38 @@ import MC1Services import SwiftUI -/// Settings section for managing blocked channel users and contacts. struct BlockingSection: View { @Environment(\.appTheme) private var theme + @Environment(\.appState) private var appState + @State private var recentlyBlockedCount: Int? var body: some View { Section { + TextRulesLoadNotice() + + NavigationLink(value: SettingsSubpage.textRules) { + TintedLabel(L10n.Settings.TextRules.title, systemImage: "line.3.horizontal.decrease") + } + + NavigationLink(value: SettingsSubpage.recentlyBlocked) { + HStack { + TintedLabel(L10n.Settings.TextRules.Archive.title, systemImage: "tray") + Spacer() + if let recentlyBlockedCount { + Text(recentlyBlockedCount, format: .number) + .foregroundStyle(.secondary) + } + } + } + .task { + let store = appState.connectionManager.persistenceStore + let changes = store.recentlyBlockedUpdates() + await refreshRecentlyBlockedCount(from: store) + for await _ in changes { + await refreshRecentlyBlockedCount(from: store) + } + } + NavigationLink(value: SettingsSubpage.blockedChannelSenders) { TintedLabel(L10n.Settings.Blocking.channelSenders, systemImage: "person.crop.circle.badge.xmark") } @@ -19,4 +45,10 @@ struct BlockingSection: View { } .themedRowBackground(theme) } + + private func refreshRecentlyBlockedCount(from store: PersistenceStore) async { + if let count = try? await store.recentlyBlockedCount() { + recentlyBlockedCount = count + } + } } diff --git a/MC1/Views/Settings/Sections/DangerZoneViewModel.swift b/MC1/Views/Settings/Sections/DangerZoneViewModel.swift index 5d0977d68b..d2be9a1ac4 100644 --- a/MC1/Views/Settings/Sections/DangerZoneViewModel.swift +++ b/MC1/Views/Settings/Sections/DangerZoneViewModel.swift @@ -31,8 +31,6 @@ final class DangerZoneViewModel { private var connectionManager: ConnectionManager? - /// Grace period for the radio to reboot after a factory reset before local cleanup. - private static let resetRebootGracePeriod: Duration = .seconds(1) /// How long the transient "Removed" confirmation stays on the button label. private static let removeSuccessDisplayDuration: Duration = .seconds(1.5) @@ -67,9 +65,7 @@ final class DangerZoneViewModel { /// Returns true when the reset flow finished and the hosting page should dismiss. /// A nil service or device ID mirrors a disconnected state. func factoryReset() async -> Bool { - guard let settingsService, - let deviceID = connectedDevice?.id, - let connectionManager else { + guard settingsService != nil, connectedDevice != nil, let connectionManager else { errorMessage = L10n.Settings.DangerZone.Error.servicesUnavailable return false } @@ -77,18 +73,15 @@ final class DangerZoneViewModel { isResetting = true defer { isResetting = false } - // Send reset command. The device typically reboots before responding, - // so a timeout/connection error here is expected, not a failure. do { - try await settingsService.factoryReset() - try await Task.sleep(for: Self.resetRebootGracePeriod) + try await connectionManager.factoryResetAndEraseRadio() + return true + } catch DevicePairingError.cancelled { + return false } catch { - // Expected: device reboots before sending OK response + errorMessage = error.userFacingMessage + return false } - - // Always clean up: remove from ASK, disconnect, delete from SwiftData - await connectionManager.forgetDevice(id: deviceID) - return true } func fetchUnfavoritedCount() async { diff --git a/MC1/Views/Settings/Sections/NewTextRuleSheet.swift b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift new file mode 100644 index 0000000000..2395093850 --- /dev/null +++ b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift @@ -0,0 +1,105 @@ +import MC1Services +import SwiftUI + +struct NewTextRuleSheet: View { + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + @Environment(\.dismiss) private var dismiss + @State private var phrase = "" + @State private var lookIn = TextRulesPreference.Rule.LookIn.message + @State private var match = TextRulesPreference.Rule.Match.contains + @State private var isSaving = false + @State private var errorMessage: String? + + var body: some View { + NavigationStack { + Form { + Section { + TextField(L10n.Settings.TextRules.New.phrase, text: $phrase, axis: .vertical) + Picker(L10n.Settings.TextRules.New.lookIn, selection: $lookIn) { + ForEach(TextRulesPreference.Rule.LookIn.allCases, id: \.self) { field in + Text(field.title).tag(field) + } + } + .pickerStyle(.menu) + Picker(L10n.Settings.TextRules.New.match, selection: $match) { + ForEach(TextRulesPreference.Rule.Match.allCases, id: \.self) { mode in + Text(mode.title(for: lookIn)).tag(mode) + } + } + .pickerStyle(.menu) + } footer: { + VStack(alignment: .leading) { + Text(match == .contains ? L10n.Settings.TextRules.New.containsFooter : L10n.Settings.TextRules.New.wholeFieldFooter) + Text(lookIn.footer) + if lookIn != .message { + Text(L10n.Settings.TextRules.reactionFooter) + } + Text(L10n.Settings.TextRules.New.deliveryFooter) + } + } + .disabled(isSaving) + .themedRowBackground(theme) + } + .themedCanvas(theme) + .navigationTitle(L10n.Settings.TextRules.New.title) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button(L10n.Localizable.Common.cancel) { dismiss() } + .disabled(isSaving) + } + ToolbarItem(placement: .confirmationAction) { + Button(L10n.Contacts.Contacts.Add.add, action: add) + .disabled(isSaving || phrase.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + .errorAlert($errorMessage) + } + .interactiveDismissDisabled(isSaving) + } + + private func add() { + let rule = TextRulesPreference.Rule(phrase: phrase, lookIn: lookIn, match: match) + guard !isSaving, rule.isValid else { return } + isSaving = true + Task { + defer { isSaving = false } + do { + try appState.connectionManager.updateTextRules { $0.append(rule) } + dismiss() + } catch { + errorMessage = L10n.Settings.TextRules.saveFailed + } + } + } +} + +extension TextRulesPreference.Rule.LookIn { + var title: String { + switch self { + case .message: L10n.Settings.TextRules.Field.message + case .sender: L10n.Settings.TextRules.Field.sender + case .messageOrSender: L10n.Settings.TextRules.Field.messageOrSender + } + } + + var footer: String { + switch self { + case .message: L10n.Settings.TextRules.Field.messageFooter + case .sender: L10n.Settings.TextRules.Field.senderFooter + case .messageOrSender: L10n.Settings.TextRules.Field.messageOrSenderFooter + } + } +} + +extension TextRulesPreference.Rule.Match { + func title(for field: TextRulesPreference.Rule.LookIn) -> String { + switch (self, field) { + case (.contains, _): L10n.Settings.TextRules.Match.contains + case (.wholeField, .message): L10n.Settings.TextRules.Match.wholeMessage + case (.wholeField, .sender): L10n.Settings.TextRules.Match.wholeName + case (.wholeField, .messageOrSender): L10n.Settings.TextRules.Match.wholeField + } + } +} diff --git a/MC1/Views/Settings/Sections/RadioCleanupSection.swift b/MC1/Views/Settings/Sections/RadioCleanupSection.swift new file mode 100644 index 0000000000..3c6d0797df --- /dev/null +++ b/MC1/Views/Settings/Sections/RadioCleanupSection.swift @@ -0,0 +1,43 @@ +import MC1Services +import SwiftUI + +struct RadioCleanupSection: View { + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + + private typealias Strings = L10n.Settings.RadioCleanup + + private var operations: [ConnectionManager.RadioCleanup] { + appState.connectionManager.radioCleanup.values.sorted { + $0.target.radioName.localizedStandardCompare($1.target.radioName) == .orderedAscending + } + } + + var body: some View { + if !operations.isEmpty { + Section(Strings.title) { + ForEach(operations) { operation in + VStack(alignment: .leading) { + Text(operation.target.radioName) + .font(.headline) + switch operation.state { + case .running: + ProgressView(Strings.running) + case .failed: + Text(Strings.failed) + .foregroundStyle(.secondary) + Button(L10n.Localizable.Common.tryAgain) { + appState.connectionManager.retryRadioErase(operation.target) + } + .accessibilityLabel(Strings.retryAccessibility(operation.target.radioName)) + case .completed: + Text(Strings.completed) + .foregroundStyle(.secondary) + } + } + } + } + .themedRowBackground(theme) + } + } +} diff --git a/MC1/Views/Settings/Sections/RecentlyBlockedView.swift b/MC1/Views/Settings/Sections/RecentlyBlockedView.swift new file mode 100644 index 0000000000..e34fc6d68e --- /dev/null +++ b/MC1/Views/Settings/Sections/RecentlyBlockedView.swift @@ -0,0 +1,90 @@ +import MC1Services +import SwiftUI + +struct RecentlyBlockedView: View { + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + @State private var entries: [RecentlyBlockedMessageDTO] = [] + @State private var errorMessage: String? + + var body: some View { + List { + Section { + if entries.isEmpty { + Text(L10n.Settings.TextRules.Archive.empty) + .foregroundStyle(.secondary) + } + ForEach(entries) { entry in + archiveRow(entry) + } + } footer: { + Text(L10n.Settings.TextRules.Archive.footer(PersistenceStore.recentlyBlockedRetentionLimit)) + } + .themedRowBackground(theme) + } + .themedCanvas(theme) + .navigationTitle(L10n.Settings.TextRules.Archive.title) + .navigationBarTitleDisplayMode(.inline) + .errorAlert($errorMessage) + .task { + let store = appState.connectionManager.persistenceStore + let changes = store.recentlyBlockedUpdates() + await refresh(from: store) + for await _ in changes { + await refresh(from: store) + } + } + } + + private func archiveRow(_ entry: RecentlyBlockedMessageDTO) -> some View { + VStack(alignment: .leading) { + Text(highlighted(entry.body, matches: entry.match.bodyHighlights)) + .fixedSize(horizontal: false, vertical: true) + Text(reason(for: entry.match)) + .font(.subheadline) + if let sender = entry.sender { + Text(highlighted(sender, matches: entry.match.senderHighlights)) + .font(.subheadline) + } + Text(entry.conversationName ?? L10n.Settings.TextRules.Archive.unknownConversation) + .foregroundStyle(.secondary) + Text(entry.radioName ?? L10n.Settings.TextRules.Archive.unknownRadio) + .foregroundStyle(.secondary) + Text(entry.arrivedAt, format: .dateTime.month().day().hour().minute()) + .foregroundStyle(.secondary) + } + .accessibilityElement(children: .combine) + } + + private func highlighted(_ text: String, matches: [TextRulesPreference.RuleMatch.Highlight]) -> AttributedString { + var attributed = AttributedString(text) + for match in matches { + guard let range = match.range(in: text), + let start = AttributedString.Index(range.lowerBound, within: attributed), + let end = AttributedString.Index(range.upperBound, within: attributed) else { continue } + attributed[start.. String { + let fields: String = if match.bodyHighlights.isEmpty { + L10n.Settings.TextRules.Field.sender + } else if match.senderHighlights.isEmpty { + L10n.Settings.TextRules.Field.message + } else { + L10n.Settings.TextRules.Archive.fieldsBoth + } + return L10n.Settings.TextRules.Archive.reason(match.rule.phrase, fields, match.rule.match.title(for: match.rule.lookIn)) + } + + private func refresh(from store: PersistenceStore) async { + do { + entries = try await store.recentlyBlockedMessages() + } catch { + errorMessage = L10n.Localizable.Common.Error.failedToLoad + } + } +} diff --git a/MC1/Views/Settings/Sections/TextRuleChatsView.swift b/MC1/Views/Settings/Sections/TextRuleChatsView.swift new file mode 100644 index 0000000000..7513871eb6 --- /dev/null +++ b/MC1/Views/Settings/Sections/TextRuleChatsView.swift @@ -0,0 +1,107 @@ +import MC1Services +import SwiftUI + +struct TextRuleChatsView: View { + let kind: TextRulesPreference.Kind + + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + @State private var inventory: [TextRulesPreference.Conversation] = [] + @State private var errorMessage: String? + + var body: some View { + List { + if let preference = appState.textRulesPreference { + selectionSection(preference.selection(for: kind)) + } else { + TextRulesLoadNotice() + .themedRowBackground(theme) + } + } + .themedCanvas(theme) + .navigationTitle(kind.title) + .navigationBarTitleDisplayMode(.inline) + .errorAlert($errorMessage) + .task { + do { + inventory = try await appState.connectionManager.persistenceStore.textRulesConversations(kind: kind) + } catch { + errorMessage = L10n.Localizable.Common.Error.failedToLoad + } + } + } + + private func selectionSection(_ selection: TextRulesPreference.Selection) -> some View { + Section { + Button { + updateSelection { _ in .all } + } label: { + selectionLabel(L10n.Settings.TextRules.Selection.all, radio: nil, isSelected: selection == .all) + } + .accessibilityAddTraits(selection == .all ? .isSelected : []) + ForEach(inventory) { conversation in + let isSelected = selection.includes(conversation.key) + Button { + toggle(conversation.key) + } label: { + selectionLabel(conversation.name, radio: conversation.radioName, isSelected: isSelected) + } + .accessibilityAddTraits(isSelected ? .isSelected : []) + } + } footer: { + Text(L10n.Settings.TextRules.Selection.footer) + } + .buttonStyle(.plain) + .disabled(!selection.isOn) + .themedRowBackground(theme) + } + + private func selectionLabel(_ title: String, radio: String?, isSelected: Bool) -> some View { + HStack { + VStack(alignment: .leading) { + Text(verbatim: title) + if let radio { + Text(verbatim: radio) + .font(.subheadline) + .foregroundStyle(.secondary) + } + } + Spacer() + if isSelected { + Image(systemName: "checkmark") + .foregroundStyle(.tint) + .accessibilityHidden(true) + } + } + .contentShape(.rect) + } + + private func toggle(_ key: TextRulesPreference.Key) { + updateSelection { selection in + var selected: Set + switch selection { + case .off: return .off + case .all: selected = Set(inventory.map(\.key)) + case let .fixed(keys): selected = keys + } + if selected.remove(key) == nil { + selected.insert(key) + } + return .fixed(selected) + } + } + + private func updateSelection( + _ update: (TextRulesPreference.Selection) -> TextRulesPreference.Selection + ) { + do { + try appState.connectionManager.updateTextRules { preference in + let selection = preference.selection(for: kind) + guard selection.isOn else { return } + preference.setSelection(update(selection), for: kind) + } + } catch { + errorMessage = L10n.Settings.TextRules.saveFailed + } + } +} diff --git a/MC1/Views/Settings/Sections/TextRulesLoadNotice.swift b/MC1/Views/Settings/Sections/TextRulesLoadNotice.swift new file mode 100644 index 0000000000..bfeb40da0b --- /dev/null +++ b/MC1/Views/Settings/Sections/TextRulesLoadNotice.swift @@ -0,0 +1,20 @@ +import SwiftUI + +struct TextRulesLoadNotice: View { + @Environment(\.appState) private var appState + + var body: some View { + if appState.isTextRulesLoading { + ProgressView(L10n.Settings.TextRules.title) + } else if appState.textRulesPreference == nil { + VStack(alignment: .leading) { + Text(L10n.Settings.TextRules.loadFailed) + .foregroundStyle(.secondary) + Button(L10n.Localizable.Common.tryAgain) { + Task { await appState.connectionManager.retryTextRulesLoad() } + } + .accessibilityLabel(L10n.Settings.TextRules.retryAccessibility) + } + } + } +} diff --git a/MC1/Views/Settings/Sections/TextRulesSettingsView.swift b/MC1/Views/Settings/Sections/TextRulesSettingsView.swift new file mode 100644 index 0000000000..164a6b4255 --- /dev/null +++ b/MC1/Views/Settings/Sections/TextRulesSettingsView.swift @@ -0,0 +1,140 @@ +import MC1Services +import SwiftUI + +struct TextRulesSettingsView: View { + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + @State private var isAddingRule = false + @State private var inventory: [TextRulesPreference.Conversation] = [] + @State private var errorMessage: String? + + var body: some View { + List { + if let preference = appState.textRulesPreference { + rulesSection(preference.rules) + typesSection(preference) + } else { + Section { + TextRulesLoadNotice() + } + .themedRowBackground(theme) + } + } + .themedCanvas(theme) + .navigationTitle(L10n.Settings.TextRules.title) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .primaryAction) { + Button(L10n.Settings.TextRules.New.title, systemImage: "plus") { + isAddingRule = true + } + .disabled(appState.textRulesPreference == nil) + } + } + .sheet(isPresented: $isAddingRule) { + NewTextRuleSheet() + } + .errorAlert($errorMessage) + .task { + do { + inventory = try await appState.connectionManager.persistenceStore.textRulesConversations() + } catch { + errorMessage = L10n.Localizable.Common.Error.failedToLoad + } + } + } + + private func rulesSection(_ rules: [TextRulesPreference.Rule]) -> some View { + Section { + if rules.isEmpty { + Text(L10n.Settings.TextRules.empty) + .foregroundStyle(.secondary) + } + ForEach(rules) { rule in + VStack(alignment: .leading) { + Text(verbatim: rule.phrase) + Text(L10n.Settings.TextRules.ruleSummary(rule.match.title(for: rule.lookIn), rule.lookIn.title)) + .font(.subheadline) + .foregroundStyle(.secondary) + if rule.lookIn != .message { + Text(L10n.Settings.TextRules.reactionFooter) + .font(.footnote) + .foregroundStyle(.secondary) + } + } + .accessibilityElement(children: .combine) + .swipeActions { + Button(L10n.Localizable.Common.delete, systemImage: "trash", role: .destructive) { + delete(rule) + } + } + .accessibilityAction(named: Text(L10n.Localizable.Common.delete)) { + delete(rule) + } + } + } header: { + Text(L10n.Settings.TextRules.rules) + } footer: { + Text(L10n.Settings.TextRules.deleteFooter) + } + .themedRowBackground(theme) + } + + private func typesSection(_ preference: TextRulesPreference) -> some View { + Section { + ForEach(TextRulesPreference.Kind.allCases, id: \.self) { kind in + let selection = preference.selection(for: kind) + Toggle(kind.title, isOn: Binding(get: { selection.isOn }, set: { isOn in + updatePreference { $0.setSelection(isOn ? .all : .off, for: kind) } + })) + if selection.isOn { + let value = summary(for: kind, selection: selection) + NavigationLink(value: SettingsSubpage.textRuleChats(kind)) { + LabeledContent(L10n.Settings.ChatSettings.title, value: value) + } + .accessibilityLabel(L10n.Settings.TextRules.Selection.accessibilityChats(kind.title)) + .accessibilityValue(Text(verbatim: value)) + } + } + } header: { + Text(L10n.Settings.TextRules.Types.header) + } footer: { + Text(L10n.Settings.TextRules.Types.footer) + } + .themedRowBackground(theme) + } + + private func summary(for kind: TextRulesPreference.Kind, selection: TextRulesPreference.Selection) -> String { + if selection == .all { return L10n.Settings.TextRules.Selection.all } + let names = inventory.filter { $0.kind == kind && selection.includes($0.key) }.map(\.name) + switch names.count { + case 0: return L10n.Settings.TextRules.Selection.none + case 1...2: return names.formatted(.list(type: .and)) + default: return L10n.Settings.TextRules.Selection.count(names.count) + } + } + + private func delete(_ rule: TextRulesPreference.Rule) { + updatePreference { $0.removeRule(id: rule.id) } + } + + private func updatePreference(_ update: (inout TextRulesPreference) -> Void) { + do { + try appState.connectionManager.updateTextRules(update) + } catch { + errorMessage = L10n.Settings.TextRules.saveFailed + } + } +} + +extension TextRulesPreference.Kind { + var title: String { + switch self { + case .publicChannel: L10n.Settings.TextRules.Types.publicChannel + case .hashtagChannel: L10n.Settings.TextRules.Types.hashtagChannel + case .privateChannel: L10n.Settings.TextRules.Types.privateChannel + case .directMessage: L10n.Settings.DirectMessages.header + case .room: L10n.Chats.Chats.Filter.rooms + } + } +} diff --git a/MC1/Views/Settings/SettingsSubpage.swift b/MC1/Views/Settings/SettingsSubpage.swift index 0ad1b6e9e1..091ff3e995 100644 --- a/MC1/Views/Settings/SettingsSubpage.swift +++ b/MC1/Views/Settings/SettingsSubpage.swift @@ -6,6 +6,9 @@ enum SettingsSubpage: Hashable { case publicKey(Data) case configExport case configImport + case textRules + case textRuleChats(TextRulesPreference.Kind) + case recentlyBlocked case blockedChannelSenders case blockedContacts case trustedContacts @@ -28,7 +31,7 @@ enum SettingsSubpage: Hashable { detail == .advanced case .remoteCLIContacts: detail == .advanced && device?.supportsRadioCLI == true - case .blockedChannelSenders, .blockedContacts: + case .textRules, .textRuleChats, .recentlyBlocked, .blockedChannelSenders, .blockedContacts: detail == .chats case .translateIntoLanguage: detail == .language @@ -104,6 +107,12 @@ private struct SettingsSubpageDestination: View { NodeConfigExportView() case .configImport: NodeConfigImportView() + case .textRules: + TextRulesSettingsView() + case let .textRuleChats(kind): + TextRuleChatsView(kind: kind) + case .recentlyBlocked: + RecentlyBlockedView() case .blockedChannelSenders: BlockedChannelSendersView() case .blockedContacts: diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift index 638926fd31..20694c26bb 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift @@ -63,8 +63,7 @@ public extension ConnectionManager { "blePhase: \(blePhase)" ) - guard currentTransportType == nil || currentTransportType == .bluetooth else { return } - guard connectionIntent.wantsConnection, connectionState == .disconnected else { return } + guard currentTransportType == nil || currentTransportType == .bluetooth, connectionIntent.wantsConnection, connectionState == .disconnected else { return } if shouldDeferOpportunisticReconnect { logger.info("[BLE] ConnectionManager: not re-arming watchdog on foreground (pairing in progress)") @@ -108,6 +107,8 @@ public extension ConnectionManager { /// Activates the connection manager on app launch. /// Call this once during app initialization. func activate() async { + loadTextRules() + // Ensure lifecycle handlers are installed before anything below can // construct the CBCentralManager; creating the central can fire // restoration callbacks synchronously, and a missed handler would @@ -176,6 +177,7 @@ public extension ConnectionManager { } #if targetEnvironment(simulator) + Task { await resumePendingRadioErases(pairingReady: true) } // Skip auto-reconnect if user explicitly disconnected if connectionIntent.isUserDisconnected { logger.info("Simulator: skipping auto-reconnect - user previously disconnected") @@ -200,9 +202,10 @@ public extension ConnectionManager { // ASK events and iOS 26 state restoration. On macOS this is a no-op. do { try await pairing.activate() + Task { await resumePendingRadioErases(pairingReady: true) } } catch { logger.error("Failed to activate pairing session: \(error.localizedDescription)") - // Don't return - WiFi doesn't need the pairing session + await resumePendingRadioErases(pairingReady: false) } // Skip auto-reconnect if user explicitly disconnected @@ -736,7 +739,8 @@ public extension ConnectionManager { radioID: MockDataProvider.simulatorDeviceID, appStateProvider: appStateProvider, connectionStateEvents: connectionStateEvents, - initialConnectionState: connectionState + initialConnectionState: connectionState, + textRulesPreference: { [weak self] in await self?.textRulesPreference } ) await wireCleanChannelSyncCallback(on: newServices) await newServices.chatSendQueueService.hydrate() diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift index 00255f6186..9781ca8db5 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift @@ -271,60 +271,14 @@ public extension ConnectionManager { /// - Parameter deleteData: If `true`, also deletes all associated data (contacts, messages, channels, trace paths). /// - Throws: `ConnectionError.notConnected` if no device is connected func forgetDevice(deleteData: Bool) async throws { - guard let deviceID = connectedDevice?.id else { + guard let device = connectedDevice else { throw ConnectionError.notConnected } - - guard pairing.isDeviceConnectable(deviceID) else { - throw ConnectionError.deviceNotFound - } - - logger.info("Forgetting device: \(deviceID), deleteData: \(deleteData)") - - try await pairing.removeDevice(deviceID) - await disconnect(reason: .forgetDevice) - - let dataStore = persistenceStore - do { - if deleteData { - try await dataStore.deleteDeviceAndData(id: deviceID) - } else { - try await dataStore.demoteDeviceToGhost(id: deviceID) - } - } catch { - logger.warning("Failed to demote device in SwiftData: \(error.localizedDescription)") + if deleteData { + try await startRadioErase(device) + } else { + try await deleteDevice(id: device.id) } - - await clearPersistedConnection(for: deviceID) - logger.info("Device forgotten") - } - - /// Forgets a device by ID, removing it from paired accessories and local storage. - /// Deletes both the device record and all associated data (factory reset path). - /// Best-effort cleanup — does not throw. - func forgetDevice(id: UUID) async { - logger.info("Forgetting device by ID: \(id)") - - await disconnect(reason: .factoryReset) - - do { - try await pairing.removeDevice(id) - } catch { - logger.warning("Failed to remove device from pairing registry: \(error.localizedDescription)") - } - - let dataStore = persistenceStore - do { - try await dataStore.deleteDeviceAndData(id: id) - } catch { - logger.warning("Failed to delete device data from SwiftData: \(error.localizedDescription)") - } - - // Always clear this device's bond verification; store keys are holder-matched - // so a non-last-connected forget still drops its in-memory/persistent shield. - await clearPersistedConnection(for: id) - - logger.info("Device forgotten by ID: \(id)") } // MARK: - Node Management diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift new file mode 100644 index 0000000000..bc3170b381 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift @@ -0,0 +1,153 @@ +import Foundation + +public extension ConnectionManager { + struct RadioCleanup: Identifiable, Sendable { + public enum State: Sendable { + case running + case failed + case completed + } + + public let target: PendingRadioEraseDTO + public var state: State + public var id: UUID { + target.radioID + } + } + + func factoryResetAndEraseRadio() async throws { + guard let device = connectedDevice, let settings = services?.settingsService else { + throw ConnectionError.notConnected + } + try await startRadioErase(device, resetWith: settings) + } + + func retryRadioErase(_ target: PendingRadioEraseDTO) { + guard radioEraseTasks[target.radioID] == nil else { return } + beginRadioEraseTask(radioID: target.radioID) { [self] in + guard try await persistenceStore.isRadioErasePending(target.radioID) else { return } + try await finishRadioErase(target) + } + } +} + +extension ConnectionManager { + func startRadioErase(_ device: DeviceDTO, resetWith settings: SettingsService? = nil) async throws { + if let running = radioEraseTasks[device.radioID] { + try await running.value + return + } + let task = beginRadioEraseTask(radioID: device.radioID) { [self] in + let ownsPairingFlow = connectedDevice?.radioID == device.radioID && !isPairingFlowActive + if ownsPairingFlow { isPairingFlowActive = true } + defer { + if ownsPairingFlow { isPairingFlowActive = false } + } + + let alreadyPending = try await persistenceStore.isRadioErasePending(device.radioID) + let poller = connectedDevice?.radioID == device.radioID ? services?.messagePollingService : nil + try await poller?.suspendForRadioErase() + + let target: PendingRadioEraseDTO + do { + guard connectedDevice?.radioID != device.radioID || services?.messagePollingService === poller else { + throw ConnectionError.notConnected + } + target = try await persistenceStore.beginRadioErase(device, isFactoryReset: settings != nil) + } catch { + if services?.messagePollingService === poller { + await poller?.resumeAfterRadioErase() + } + throw error + } + radioCleanup[target.radioID] = .init(target: target, state: .running) + if let settings, !alreadyPending { + // The radio usually reboots before it can acknowledge the command. + do { + try await settings.factoryReset() + try await Task.sleep(for: Self.factoryResetRebootGracePeriod) + } catch { + logger.info("Factory reset response interrupted: \(error.localizedDescription)") + } + } + try await finishRadioErase(target) + } + try await task.value + } + + func resumePendingRadioErases(pairingReady: Bool) async { + do { + for target in try await persistenceStore.fetchPendingRadioErases() { + if pairingReady { + retryRadioErase(target) + _ = await radioEraseTasks[target.radioID]?.result + } else { + radioCleanup[target.radioID] = .init(target: target, state: .failed) + } + } + } catch { + logger.error("Failed to read pending radio cleanup: \(error.localizedDescription)") + } + } + + @discardableResult + private func beginRadioEraseTask( + radioID: UUID, + operation: @escaping @MainActor () async throws -> Void + ) -> Task { + let task = Task { [self] in + defer { radioEraseTasks[radioID] = nil } + try await operation() + } + radioEraseTasks[radioID] = task + return task + } + + private func finishRadioErase(_ target: PendingRadioEraseDTO) async throws { + radioCleanup[target.radioID] = .init(target: target, state: .running) + let shouldTearDown = + connectedDevice?.radioID == target.radioID || + activeConnectionAttemptDeviceID == target.deviceID || + activeConnectionAttemptDeviceID == target.pairingID + let ownsPairingFlow = shouldTearDown && !isPairingFlowActive + if ownsPairingFlow { isPairingFlowActive = true } + defer { + if ownsPairingFlow { isPairingFlowActive = false } + } + + do { + #if canImport(UIKit) && !targetEnvironment(simulator) + if pairing.hasSystemPairingRegistry, !pairing.isSessionActive { + try await pairing.activate() + guard pairing.isSessionActive else { throw AccessorySetupKitError.sessionNotActive } + } + #endif + do { + try await pairing.removeDevice(target.pairingID) + } catch DevicePairingError.cancelled where target.isFactoryReset == false { + try await persistenceStore.cancelRadioErase(radioID: target.radioID) + radioCleanup[target.radioID] = nil + if connectedDevice?.radioID == target.radioID { + await services?.messagePollingService.resumeAfterRadioErase() + } + throw DevicePairingError.cancelled + } + if shouldTearDown, + connectedDevice == nil || connectedDevice?.radioID == target.radioID, + activeConnectionAttemptDeviceID == nil || + activeConnectionAttemptDeviceID == target.deviceID || + activeConnectionAttemptDeviceID == target.pairingID { + await disconnect(reason: target.isFactoryReset == true ? .factoryReset : .forgetDevice) + } + try await waitForConnectionTeardown() + await clearPersistedConnection(for: target.deviceID) + try await persistenceStore.completeRadioErase(radioID: target.radioID) + radioCleanup[target.radioID]?.state = .completed + } catch { + radioCleanup[target.radioID]?.state = .failed + throw error + } + } + + private static let factoryResetRebootGracePeriod: Duration = .seconds(1) +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift new file mode 100644 index 0000000000..4c3fe17247 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift @@ -0,0 +1,47 @@ +import Foundation + +extension ConnectionManager { + static var defaultTextRulesURL: URL { + FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appending(path: "TextRules.json") + } + + func loadTextRules() { + defer { isTextRulesLoading = false } + do { + let data = try Data(contentsOf: textRulesURL) + let preference = try JSONDecoder().decode(TextRulesPreference.self, from: data) + guard preference.isValid else { throw CocoaError(.fileReadCorruptFile) } + textRulesPreference = preference + } catch let error as CocoaError where error.code == .fileReadNoSuchFile { + textRulesPreference = TextRulesPreference() + } catch { + textRulesPreference = nil + logger.error("Could not load Text Rules: \(error.localizedDescription)") + } + } + + public func retryTextRulesLoad() async { + guard !isTextRulesLoading, textRulesPreference == nil else { return } + isTextRulesLoading = true + await Task.yield() + loadTextRules() + } + + public func updateTextRules(_ update: (inout TextRulesPreference) -> Void) throws { + guard !isTextRulesLoading, var preference = textRulesPreference else { + throw CocoaError(.fileReadCorruptFile) + } + update(&preference) + guard preference.isValid else { throw CocoaError(.fileWriteInapplicableStringEncoding) } + guard preference != textRulesPreference else { return } + preference.revision = UUID() + let data = try JSONEncoder().encode(preference) + try FileManager.default.createDirectory( + at: textRulesURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try data.write(to: textRulesURL, options: .atomic) + textRulesPreference = preference + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift index b72e355b93..83d4ae0815 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift @@ -299,6 +299,10 @@ public final class ConnectionManager { let modelContainer: ModelContainer private let defaults: UserDefaults private let lastConnectionStore: LastConnectionStore + + let textRulesURL: URL + public internal(set) var textRulesPreference: TextRulesPreference? + public internal(set) var isTextRulesLoading = true let transport: any iOSMeshTransport var wifiTransport: WiFiTransport? var session: MeshCoreSession? { @@ -370,6 +374,9 @@ public final class ConnectionManager { /// Task managing the resync retry loop var resyncTask: Task? + public internal(set) var radioCleanup: [UUID: RadioCleanup] = [:] + @ObservationIgnored var radioEraseTasks: [UUID: Task] = [:] + /// Task managing delayed channel-only retry after a partial channel phase. var channelRetryTask: Task? @@ -706,12 +713,14 @@ public final class ConnectionManager { defaults: UserDefaults = .standard, stateMachine: (any BLEStateMachineProtocol)? = nil, transport: (any iOSMeshTransport)? = nil, - pairing: (any DevicePairingService)? = nil + pairing: (any DevicePairingService)? = nil, + textRulesURL: URL? = nil ) { self.modelContainer = modelContainer persistenceStore = PersistenceStore(modelContainer: modelContainer) self.defaults = defaults lastConnectionStore = LastConnectionStore(defaults: defaults) + self.textRulesURL = textRulesURL ?? Self.defaultTextRulesURL connectionIntent = .restored(from: defaults) // Use provided state machine or create default @@ -970,6 +979,9 @@ public final class ConnectionManager { } let effectiveExisting = existingDevice ?? deviceByPublicKey let resolvedRadioID = effectiveExisting?.radioID ?? UUID() + guard try await !persistenceStore.isRadioErasePending(resolvedRadioID) else { + throw ConnectionError.deviceNotFound + } let newServices = ServiceContainer( session: session, @@ -977,7 +989,8 @@ public final class ConnectionManager { radioID: resolvedRadioID, appStateProvider: appStateProvider, connectionStateEvents: connectionStateEvents, - initialConnectionState: connectionState + initialConnectionState: connectionState, + textRulesPreference: { [weak self] in await self?.textRulesPreference } ) await wireCleanChannelSyncCallback(on: newServices) await newServices.nodeConfigService.setOnPostIdentityImport { [weak self, weak newServices] in @@ -1005,6 +1018,7 @@ public final class ConnectionManager { // Persist before warmUp so purgeOrphanPendingSends sees the in-progress // radio's Device row and does not classify its PendingSends as orphans. try await newServices.dataStore.saveDevice(deviceDTO) + try await persistenceStore.backfillTextRulesIdentities(radioID: resolvedRadioID) // Clean up orphaned Device row from backup import if let oldDevice = deviceByPublicKey, oldDevice.id != deviceID { diff --git a/MC1Services/Sources/MC1Services/Models/Channel.swift b/MC1Services/Sources/MC1Services/Models/Channel.swift index cddc739a0f..eeab3d0384 100644 --- a/MC1Services/Sources/MC1Services/Models/Channel.swift +++ b/MC1Services/Sources/MC1Services/Models/Channel.swift @@ -18,6 +18,13 @@ public final class Channel { @Attribute(originalName: "deviceID") public var radioID: UUID + var textRulesID: UUID? + var textRulesOverrideRawValue: String = TextRulesPreference.Override.inherit.rawValue + + var textRulesOverride: TextRulesPreference.Override { + TextRulesPreference.Override(rawValue: textRulesOverrideRawValue) ?? .inherit + } + /// Channel slot index public var index: UInt8 @@ -93,6 +100,7 @@ public final class Channel { ) { self.id = id self.radioID = radioID + textRulesID = UUID() self.index = index self.name = name self.secret = secret @@ -237,6 +245,8 @@ public extension Channel { public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { public let id: UUID public var radioID: UUID + public internal(set) var textRulesID: UUID? + public internal(set) var textRulesOverride: TextRulesPreference.Override = .inherit public let index: UInt8 public let name: String public let secret: Data @@ -316,6 +326,8 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { public init(from channel: Channel) { id = channel.id radioID = channel.radioID + textRulesID = channel.textRulesID + textRulesOverride = channel.textRulesOverride index = channel.index name = channel.name secret = channel.secret @@ -368,35 +380,44 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { /// Returns a copy with only `notificationLevel` changed. public func with(notificationLevel: NotificationLevel) -> ChannelDTO { - ChannelDTO( + var copy = ChannelDTO( id: id, radioID: radioID, index: index, name: name, secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, notificationLevel: notificationLevel, isPinned: isPinned, floodScope: floodScope ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> ChannelDTO { - ChannelDTO( + var copy = ChannelDTO( id: id, radioID: radioID, index: index, name: name, secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, notificationLevel: notificationLevel, isPinned: isPinned, floodScope: floodScope ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// Returns a copy with only the flood-scope preference changed. public func with(floodScope: ChannelFloodScope) -> ChannelDTO { - ChannelDTO( + var copy = ChannelDTO( id: id, radioID: radioID, index: index, name: name, secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, notificationLevel: notificationLevel, isPinned: isPinned, floodScope: floodScope ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// Returns a copy placed at a different slot `index`, forwarding every other raw @@ -404,7 +425,7 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { /// has no local match onto a free slot without routing through the normalizing /// ``ChannelFloodScope`` accessor (preserving pre-migration flood-scope rows). func with(index newIndex: UInt8) -> ChannelDTO { - ChannelDTO( + var copy = ChannelDTO( id: id, radioID: radioID, index: newIndex, name: name, secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, @@ -412,6 +433,9 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { floodScopeModeRawValue: floodScopeModeRawValue, regionScope: regionScope ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// Returns a copy with a fresh surrogate `id`, forwarding every other raw storage @@ -420,7 +444,7 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { /// id. Channel has no inbound foreign key, so re-issuing the id breaks no linkage; it /// uses the raw initializer to preserve pre-migration flood-scope rows (see ``init(dto:)``). func with(id newID: UUID) -> ChannelDTO { - ChannelDTO( + var copy = ChannelDTO( id: newID, radioID: radioID, index: index, name: name, secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, @@ -428,13 +452,16 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { floodScopeModeRawValue: floodScopeModeRawValue, regionScope: regionScope ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// Returns a copy with only the raw `regionScope` column changed. This is the /// low-level bypass used for tests that must simulate malformed on-disk state; /// production code should go through ``with(floodScope:)``. func with(regionScope: String?) -> ChannelDTO { - ChannelDTO( + var copy = ChannelDTO( id: id, radioID: radioID, index: index, name: name, secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, @@ -442,6 +469,9 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { floodScopeModeRawValue: floodScopeModeRawValue, regionScope: regionScope ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// Low-level init that sets both raw storage fields directly. Kept `internal` diff --git a/MC1Services/Sources/MC1Services/Models/Contact.swift b/MC1Services/Sources/MC1Services/Models/Contact.swift index 373dea2af8..042795d58e 100644 --- a/MC1Services/Sources/MC1Services/Models/Contact.swift +++ b/MC1Services/Sources/MC1Services/Models/Contact.swift @@ -20,6 +20,13 @@ public final class Contact { @Attribute(originalName: "deviceID") public var radioID: UUID + var textRulesID: UUID? + var textRulesOverrideRawValue: String = TextRulesPreference.Override.inherit.rawValue + + var textRulesOverride: TextRulesPreference.Override { + TextRulesPreference.Override(rawValue: textRulesOverrideRawValue) ?? .inherit + } + /// The 32-byte public key of the contact public var publicKey: Data @@ -117,6 +124,7 @@ public final class Contact { ) { self.id = id self.radioID = radioID + textRulesID = UUID() self.publicKey = publicKey self.name = name self.typeRawValue = typeRawValue @@ -301,6 +309,8 @@ public extension Contact { public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, RepeaterResolvable { public let id: UUID public var radioID: UUID + public internal(set) var textRulesID: UUID? + public internal(set) var textRulesOverride: TextRulesPreference.Override = .inherit public let publicKey: Data public let name: String public let typeRawValue: UInt8 @@ -396,6 +406,8 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, public init(from contact: Contact) { id = contact.id radioID = contact.radioID + textRulesID = contact.textRulesID + textRulesOverride = contact.textRulesOverride publicKey = contact.publicKey name = contact.name typeRawValue = contact.typeRawValue @@ -549,7 +561,7 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, /// Returns a copy with only `isMuted` changed. public func with(isMuted: Bool) -> ContactDTO { - ContactDTO( + var copy = ContactDTO( id: id, radioID: radioID, publicKey: publicKey, name: name, typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, @@ -561,11 +573,14 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, avatarImageData: avatarImageData ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// Returns a copy with only `isFavorite` changed. public func with(isFavorite: Bool) -> ContactDTO { - ContactDTO( + var copy = ContactDTO( id: id, radioID: radioID, publicKey: publicKey, name: name, typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, @@ -577,11 +592,14 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, avatarImageData: avatarImageData ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> ContactDTO { - ContactDTO( + var copy = ContactDTO( id: id, radioID: radioID, publicKey: publicKey, name: name, typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, @@ -593,11 +611,14 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, avatarImageData: avatarImageData ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// Returns a copy with only `avatarImageData` changed. public func with(avatarImageData: Data?) -> ContactDTO { - ContactDTO( + var copy = ContactDTO( id: id, radioID: radioID, publicKey: publicKey, name: name, typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, @@ -609,6 +630,9 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, avatarImageData: avatarImageData ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// The active OCV array for this contact (preset or custom) diff --git a/MC1Services/Sources/MC1Services/Models/Message.swift b/MC1Services/Sources/MC1Services/Models/Message.swift index 27caa780e5..e1df8f899e 100644 --- a/MC1Services/Sources/MC1Services/Models/Message.swift +++ b/MC1Services/Sources/MC1Services/Models/Message.swift @@ -26,10 +26,13 @@ public final class Message { [\.radioID, \.channelIndex, \.createdAt], [\.radioID, \.channelIndex, \.sortDate], [\.radioID, \.channelIndex, \.timestamp], + [\.radioID, \.channelIndex, \.senderTimestamp], [\.contactID, \.createdAt], [\.contactID, \.sortDate], [\.contactID, \.containsSelfMention, \.mentionSeen], [\.radioID, \.channelIndex, \.containsSelfMention, \.mentionSeen], + [\.radioID, \.senderKeyPrefix, \.senderTimestamp], + [\.radioID, \.senderKeyPrefix, \.timestamp], [\.deduplicationKey] ) @@ -723,8 +726,7 @@ public struct MessageDTO: Sendable, Equatable, Hashable, Identifiable, Codable { } private static func isSameSender(_ a: MessageDTO, _ b: MessageDTO) -> Bool { - guard a.direction == b.direction else { return false } - guard a.isChannelMessage == b.isChannelMessage else { return false } + guard a.direction == b.direction, a.isChannelMessage == b.isChannelMessage else { return false } // For channel messages, compare sender node name (nil = unknown, treat as different). // senderNodeName isn't unique — two users with the same name may be falsely clustered. diff --git a/MC1Services/Sources/MC1Services/Models/PendingRadioErase.swift b/MC1Services/Sources/MC1Services/Models/PendingRadioErase.swift new file mode 100644 index 0000000000..eac8dbe05a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/PendingRadioErase.swift @@ -0,0 +1,50 @@ +import Foundation +import SwiftData + +@Model +final class PendingRadioErase { + @Attribute(.unique) var radioID: UUID + var deviceID: UUID + var pairingID: UUID + var radioName: String + /// A legacy target has unknown purpose and must remain retryable. + var isFactoryReset: Bool? + + init(_ target: PendingRadioEraseDTO) { + radioID = target.radioID + deviceID = target.deviceID + pairingID = target.pairingID + radioName = target.radioName + isFactoryReset = target.isFactoryReset + } +} + +public struct PendingRadioEraseDTO: Sendable, Identifiable { + public let radioID: UUID + public let deviceID: UUID + public let pairingID: UUID + public let radioName: String + let isFactoryReset: Bool? + + public var id: UUID { + radioID + } + + init(radioID: UUID, deviceID: UUID, pairingID: UUID, radioName: String, isFactoryReset: Bool?) { + self.radioID = radioID + self.deviceID = deviceID + self.pairingID = pairingID + self.radioName = radioName + self.isFactoryReset = isFactoryReset + } + + init(_ target: PendingRadioErase) { + self.init( + radioID: target.radioID, + deviceID: target.deviceID, + pairingID: target.pairingID, + radioName: target.radioName, + isFactoryReset: target.isFactoryReset + ) + } +} diff --git a/MC1Services/Sources/MC1Services/Models/ReceiveScope.swift b/MC1Services/Sources/MC1Services/Models/ReceiveScope.swift new file mode 100644 index 0000000000..485efbaa58 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/ReceiveScope.swift @@ -0,0 +1,38 @@ +import Foundation +import Synchronization + +/// Authority captured before receive can suspend. Link teardown and partition retirement +/// invalidate the same authority at both the store and the buffered event consumer. +public struct ReceiveScope: Sendable, Equatable { + public final class Lifetime: Sendable { + private let active = Mutex(true) + + public init() {} + + public var isCurrent: Bool { + active.withLock { $0 } + } + + func retire() { + active.withLock { $0 = false } + } + } + + public let radioID: UUID + private let link: Lifetime + private let partition: Lifetime + + init(radioID: UUID, link: Lifetime, partition: Lifetime) { + self.radioID = radioID + self.link = link + self.partition = partition + } + + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.radioID == rhs.radioID && lhs.link === rhs.link && lhs.partition === rhs.partition + } + + public var isCurrent: Bool { + link.isCurrent && partition.isCurrent + } +} diff --git a/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessage.swift b/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessage.swift new file mode 100644 index 0000000000..e9b75f5864 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessage.swift @@ -0,0 +1,52 @@ +import Foundation +import SwiftData + +@Model +final class RecentlyBlockedMessage { + #Index([\.radioID, \.senderTimestamp]) + + @Attribute(.unique) + var id: UUID + var radioID: UUID + var conversationID: UUID? + var senderPrefix: Data? + var senderTimestamp: UInt32 + var textTypeRawValue: UInt8? + var wireText: Data + + var arrivedAt: Date + var body: String + var sender: String? + var conversationName: String? + var radioName: String? + var matchData: Data + var contactID: UUID? + + init(_ entry: RecentlyBlockedMessageDTO) throws { + id = entry.id + radioID = entry.identity.radioID + conversationID = entry.identity.conversationID + senderPrefix = entry.identity.senderPrefix + senderTimestamp = entry.identity.senderTimestamp + textTypeRawValue = entry.identity.textType + wireText = entry.identity.wireText + arrivedAt = entry.arrivedAt + body = entry.body + sender = entry.sender + conversationName = entry.conversationName + radioName = entry.radioName + matchData = try JSONEncoder().encode(entry.match) + contactID = entry.contactID + } + + var identity: RecentlyBlockedMessageDTO.Identity { + RecentlyBlockedMessageDTO.Identity( + radioID: radioID, + conversationID: conversationID, + senderPrefix: senderPrefix, + senderTimestamp: senderTimestamp, + textType: textTypeRawValue, + wireText: wireText + ) + } +} diff --git a/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessageDTO.swift b/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessageDTO.swift new file mode 100644 index 0000000000..600a5a996d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessageDTO.swift @@ -0,0 +1,72 @@ +import Foundation + +public struct RecentlyBlockedMessageDTO: Identifiable, Sendable, Equatable { + public struct Identity: Sendable, Equatable { + public let radioID: UUID + public let conversationID: UUID? + public let senderPrefix: Data? + public let senderTimestamp: UInt32 + public let textType: UInt8? + public let wireText: Data + + public init( + radioID: UUID, + conversationID: UUID?, + senderPrefix: Data?, + senderTimestamp: UInt32, + textType: UInt8?, + wireText: Data + ) { + self.radioID = radioID + self.conversationID = conversationID + self.senderPrefix = senderPrefix + self.senderTimestamp = senderTimestamp + self.textType = textType + self.wireText = wireText + } + } + + public let id: UUID + public let identity: Identity + public let arrivedAt: Date + public let body: String + public let sender: String? + public let conversationName: String? + public let radioName: String? + public let match: TextRulesPreference.RuleMatch + public let contactID: UUID? + + public init( + id: UUID = UUID(), + identity: Identity, + arrivedAt: Date, + body: String, + sender: String?, + conversationName: String?, + radioName: String?, + match: TextRulesPreference.RuleMatch, + contactID: UUID? = nil + ) { + self.id = id + self.identity = identity + self.arrivedAt = arrivedAt + self.body = body + self.sender = sender + self.conversationName = conversationName + self.radioName = radioName + self.match = match + self.contactID = contactID + } + + init(from entry: RecentlyBlockedMessage) throws { + id = entry.id + identity = entry.identity + arrivedAt = entry.arrivedAt + body = entry.body + sender = entry.sender + conversationName = entry.conversationName + radioName = entry.radioName + match = try JSONDecoder().decode(TextRulesPreference.RuleMatch.self, from: entry.matchData) + contactID = entry.contactID + } +} diff --git a/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift b/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift index 507f8ff8cf..04a4109951 100644 --- a/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift +++ b/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift @@ -16,6 +16,13 @@ public final class RemoteNodeSession { @Attribute(originalName: "deviceID") public var radioID: UUID + var textRulesID: UUID? + var textRulesOverrideRawValue: String = TextRulesPreference.Override.inherit.rawValue + + var textRulesOverride: TextRulesPreference.Override { + TextRulesPreference.Override(rawValue: textRulesOverrideRawValue) ?? .inherit + } + /// 32-byte remote node's public key public var publicKey: Data @@ -120,6 +127,7 @@ public final class RemoteNodeSession { ) { self.id = id self.radioID = radioID + textRulesID = UUID() self.publicKey = publicKey self.name = name roleRawValue = role.rawValue @@ -242,6 +250,8 @@ public extension RemoteNodeSession { public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, Codable { public let id: UUID public var radioID: UUID + public internal(set) var textRulesID: UUID? + public internal(set) var textRulesOverride: TextRulesPreference.Override = .inherit public let publicKey: Data public let name: String public let role: RemoteNodeRole @@ -331,6 +341,8 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, public init(from model: RemoteNodeSession) { id = model.id radioID = model.radioID + textRulesID = model.textRulesID + textRulesOverride = model.textRulesOverride publicKey = model.publicKey name = model.name role = model.role @@ -407,7 +419,7 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, /// Returns a copy with only `notificationLevel` changed. public func with(notificationLevel: NotificationLevel) -> RemoteNodeSessionDTO { - RemoteNodeSessionDTO( + var copy = RemoteNodeSessionDTO( id: id, radioID: radioID, publicKey: publicKey, name: name, role: role, latitude: latitude, longitude: longitude, isConnected: isConnected, permissionLevel: permissionLevel, @@ -419,11 +431,14 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, neighborCount: neighborCount, lastSyncTimestamp: lastSyncTimestamp, lastMessageDate: lastMessageDate ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> RemoteNodeSessionDTO { - RemoteNodeSessionDTO( + var copy = RemoteNodeSessionDTO( id: id, radioID: radioID, publicKey: publicKey, name: name, role: role, latitude: latitude, longitude: longitude, isConnected: isConnected, permissionLevel: permissionLevel, @@ -435,6 +450,9 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, neighborCount: neighborCount, lastSyncTimestamp: lastSyncTimestamp, lastMessageDate: lastMessageDate ) + copy.textRulesID = textRulesID + copy.textRulesOverride = textRulesOverride + return copy } public var publicKeyPrefix: Data { diff --git a/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift b/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift new file mode 100644 index 0000000000..7799d5ca2f --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift @@ -0,0 +1,239 @@ +import Foundation + +// swiftformat:disable redundantRawValues +// swiftlint:disable redundant_string_enum_value + +/// The installation-wide snapshot used by both receive and Settings. +public struct TextRulesPreference: Sendable, Codable, Equatable { + public enum Kind: String, CaseIterable, Sendable, Codable { + case publicChannel = "publicChannel" + case hashtagChannel = "hashtagChannel" + case privateChannel = "privateChannel" + case directMessage = "directMessage" + case room = "room" + } + + public struct Key: Hashable, Sendable, Codable { + public let radioID: UUID + public let conversationID: UUID + + public init(radioID: UUID, conversationID: UUID) { + self.radioID = radioID + self.conversationID = conversationID + } + } + + public struct Conversation: Identifiable, Sendable, Equatable { + public var id: Key { + key + } + + public let key: Key + public let kind: Kind + public let name: String + public let radioName: String + public let override: Override + + public init(key: Key, kind: Kind, name: String, radioName: String, override: Override) { + self.key = key + self.kind = kind + self.name = name + self.radioName = radioName + self.override = override + } + } + + public enum Selection: Sendable, Codable, Equatable { + case off + case all + case fixed(Set) + + private enum CodingKeys: String, CodingKey { + case off = "off" + case all = "all" + case fixed = "fixed" + } + + public var isOn: Bool { + self != .off + } + + public func includes(_ key: Key) -> Bool { + switch self { + case .off: false + case .all: true + case let .fixed(keys): keys.contains(key) + } + } + } + + public enum Override: String, CaseIterable, Sendable, Codable { + case inherit = "inherit" + case on = "on" + case off = "off" + } + + public struct Effective: Sendable, Equatable { + public enum Source: Sendable, Equatable { + case type + case fixedExclusion + case explicit + } + + public let isOn: Bool + public let source: Source + } + + public struct Rule: Identifiable, Sendable, Codable, Equatable { + public enum LookIn: String, CaseIterable, Sendable, Codable { + case message = "message" + case sender = "sender" + case messageOrSender = "messageOrSender" + } + + public enum Match: String, CaseIterable, Sendable, Codable { + case contains = "contains" + case wholeField = "wholeField" + } + + public let id: UUID + public let phrase: String + public let lookIn: LookIn + public let match: Match + + public var isValid: Bool { + !phrase.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + public init(id: UUID = UUID(), phrase: String, lookIn: LookIn, match: Match) { + self.id = id + self.phrase = phrase + self.lookIn = lookIn + self.match = match + } + } + + public struct RuleMatch: Sendable, Codable, Equatable { + public struct Highlight: Sendable, Codable, Equatable { + let location: Int + let length: Int + + init(_ range: NSRange) { + location = range.location + length = range.length + } + + public func range(in text: String) -> Range? { + Range(NSRange(location: location, length: length), in: text) + } + } + + public let rule: Rule + public let bodyHighlights: [Highlight] + public let senderHighlights: [Highlight] + } + + private static let comparisonLocale = Locale(identifier: "en_US_POSIX") + + public internal(set) var revision = UUID() + public private(set) var rules: [Rule] = [] + private var selections: [Kind: Selection] = [ + .publicChannel: .all, + .hashtagChannel: .all, + .privateChannel: .off, + .directMessage: .off, + .room: .off + ] + + public init() {} + + public mutating func append(_ rule: Rule) { + rules.append(rule) + } + + public mutating func removeRule(id: UUID) { + rules.removeAll { $0.id == id } + } + + public mutating func setSelection(_ selection: Selection, for kind: Kind) { + selections[kind] = selection + } + + public func selection(for kind: Kind) -> Selection { + selections[kind] ?? .off + } + + public func effective(for kind: Kind, key: Key?, override: Override) -> Effective { + switch override { + case .on: + Effective(isOn: true, source: .explicit) + case .off: + Effective(isOn: false, source: .explicit) + case .inherit: + switch selection(for: kind) { + case .off: + Effective(isOn: false, source: .type) + case .all: + Effective(isOn: true, source: .type) + case let .fixed(keys): + if let key, keys.contains(key) { + Effective(isOn: true, source: .type) + } else { + Effective(isOn: false, source: .fixedExclusion) + } + } + } + } + + public func firstMatch(body: String?, sender: String?) -> RuleMatch? { + for rule in rules { + let bodyHighlights = rule.lookIn == .sender ? [] : Self.highlights(in: body, for: rule) + let senderHighlights = rule.lookIn == .message ? [] : Self.highlights(in: sender, for: rule) + if !bodyHighlights.isEmpty || !senderHighlights.isEmpty { + return RuleMatch(rule: rule, bodyHighlights: bodyHighlights, senderHighlights: senderHighlights) + } + } + return nil + } + + var isValid: Bool { + selections.count == Kind.allCases.count && + rules.allSatisfy(\.isValid) && + Set(rules.map(\.id)).count == rules.count + } + + private static func highlights(in field: String?, for rule: Rule) -> [RuleMatch.Highlight] { + guard let field, !field.isEmpty, !rule.phrase.isEmpty else { return [] } + let text = field as NSString + let entireField = NSRange(location: 0, length: text.length) + let options: String.CompareOptions = [.literal, .caseInsensitive] + if rule.match == .wholeField { + let equal = text.compare(rule.phrase, options: options, range: entireField, locale: comparisonLocale) + return equal == .orderedSame ? [RuleMatch.Highlight(entireField)] : [] + } + + var highlights: [RuleMatch.Highlight] = [] + var start = 0 + while start < text.length { + let searchRange = NSRange(location: start, length: text.length - start) + let match = text.range(of: rule.phrase, options: options, range: searchRange, locale: comparisonLocale) + guard match.location != NSNotFound else { break } + let highlight = RuleMatch.Highlight(text.rangeOfComposedCharacterSequences(for: match)) + if highlights.last != highlight { + highlights.append(highlight) + } + start = NSMaxRange(match) + } + return highlights + } +} + +// swiftlint:enable redundant_string_enum_value +// swiftformat:enable redundantRawValues + +public extension TextRulesPreference { + static func channelKind(isPublic: Bool, name: String) -> Kind { + if isPublic { return .publicChannel } + return name.hasPrefix("#") ? .hashtagChannel : .privateChannel + } +} diff --git a/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift b/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift index 9e67ee4e51..1abde9cd14 100644 --- a/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift +++ b/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift @@ -43,13 +43,13 @@ protocol MessagePollingServiceProtocol: Actor { // MARK: - Ingestion Handlers /// Install the handler invoked for each incoming direct message. - func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void) + func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) /// Install the handler invoked for each incoming channel message. - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void) + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void) /// Install the handler invoked for each incoming signed room message. - func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) + func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) /// Install the handler invoked for each incoming CLI response. func setCLIMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift index c3ae8aa57e..6307daec4c 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift @@ -103,14 +103,8 @@ public protocol ContactPersisting: Actor { skippingPublicKeys: @Sendable () -> Set ) async throws -> [UUID] - /// Deletes the contact only when no messages reference it. Insert-only - /// rollback of a mid-sync radio delete: prefer an orphan contact over a - /// cascade that wipes a concurrent DM. Implementations that share a - /// ModelActor with message storage must keep probe and delete in one - /// isolation region with no suspension between them. - /// - /// PendingSend and Reaction cascade with their Message rows on - /// `deleteContact`, so a Message probe is sufficient. + /// Deletes a Contact only when no message or review entry references it. + /// Check references and delete without suspension so a concurrent DM cannot be cascaded. func deleteContactIfUnreferenced(id: UUID) async throws /// Links direct messages stored before their contact row existed. Channel diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift index d2dba541cc..a17547bf8f 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift @@ -19,6 +19,9 @@ public protocol MessagePersisting: Actor { /// Save a new message func saveMessage(_ dto: MessageDTO) async throws + /// Saves only while the captured receive scope and any resolved channel identity are current. + func saveLegacyChannelMessage(_ dto: MessageDTO, scope: ReceiveScope?, conversationID: UUID?) async throws -> Bool + /// Fetch a message by ID func fetchMessage(id: UUID) async throws -> MessageDTO? @@ -194,3 +197,11 @@ extension MessagePersisting { nil } } + +public extension MessagePersisting { + func saveLegacyChannelMessage(_ dto: MessageDTO, scope: ReceiveScope?, conversationID: UUID?) async throws -> Bool { + if let scope, !scope.isCurrent || scope.radioID != dto.radioID { return false } + try await saveMessage(dto) + return true + } +} diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/RoomPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/RoomPersisting.swift index 977cbf00a1..96d491cb0f 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/RoomPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/RoomPersisting.swift @@ -49,6 +49,8 @@ public protocol RoomPersisting: Actor { // MARK: - Room Message Operations + func hasRecentlyBlockedMessages(radioID: UUID, conversationID: UUID) async throws -> Bool + /// Save a new room message func saveRoomMessage(_ dto: RoomMessageDTO) async throws @@ -86,6 +88,12 @@ public protocol RoomPersisting: Actor { // MARK: - Default Parameter Values +public extension RoomPersisting { + func hasRecentlyBlockedMessages(radioID: UUID, conversationID: UUID) async throws -> Bool { + false + } +} + extension RoomPersisting { /// Update room activity with nil sync timestamp (sort date only) func updateRoomActivity(_ sessionID: UUID) async throws { diff --git a/MC1Services/Sources/MC1Services/Protocols/PersistenceStoreProtocol.swift b/MC1Services/Sources/MC1Services/Protocols/PersistenceStoreProtocol.swift index e95476ab88..3bebd6b25f 100644 --- a/MC1Services/Sources/MC1Services/Protocols/PersistenceStoreProtocol.swift +++ b/MC1Services/Sources/MC1Services/Protocols/PersistenceStoreProtocol.swift @@ -1,3 +1,5 @@ +import Foundation + /// Protocol for PersistenceStore to enable testability of dependent services. /// /// This protocol abstracts the SwiftData persistence operations used by services, @@ -33,4 +35,96 @@ public protocol PersistenceStoreProtocol: RoomPersisting, DiscoveredNodePersisting, ReactionPersisting, - NodeSnapshotPersisting {} + NodeSnapshotPersisting { + func captureReceiveScope(radioID: UUID, link: ReceiveScope.Lifetime) async throws -> ReceiveScope? + func admitDirectMessage( + _ message: MessageDTO, + wireTextType: UInt8, + contact: ContactDTO?, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> DirectMessageAdmission + func currentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) async throws -> ContactDTO? + func materializeContactForDirectMessage( + from frame: ContactFrame, + receivedAt: Date, + scope: ReceiveScope + ) async throws -> ContactDTO? + func touchDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope, at date: Date) async throws + func updateContactAfterDirectMessage( + _ message: MessageDTO, + contact: ContactDTO, + scope: ReceiveScope, + isViewingContact: Bool + ) async throws -> ContactDTO? + func admitDirectMessageReaction( + _ reaction: ReactionDTO, + contact: ContactDTO, + scope: ReceiveScope + ) async throws -> ReactionAdmission? + func shouldSuppressChannelMessage( + _ message: MessageDTO, + frame: ChannelMessage, + channel: ChannelDTO, + scope: ReceiveScope?, + preference: TextRulesPreference? + ) async throws -> Bool +} + +public extension PersistenceStoreProtocol { + func captureReceiveScope(radioID: UUID, link: ReceiveScope.Lifetime) async throws -> ReceiveScope? { + guard link.isCurrent else { return nil } + return ReceiveScope(radioID: radioID, link: link, partition: .init()) + } + + func admitDirectMessage( + _ message: MessageDTO, + wireTextType: UInt8, + contact: ContactDTO?, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> DirectMessageAdmission { + .discarded + } + + func currentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) async throws -> ContactDTO? { + nil + } + + func materializeContactForDirectMessage( + from frame: ContactFrame, + receivedAt: Date, + scope: ReceiveScope + ) async throws -> ContactDTO? { + nil + } + + func touchDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope, at date: Date) async throws {} + + func updateContactAfterDirectMessage( + _ message: MessageDTO, + contact: ContactDTO, + scope: ReceiveScope, + isViewingContact: Bool + ) async throws -> ContactDTO? { + nil + } + + func admitDirectMessageReaction( + _ reaction: ReactionDTO, + contact: ContactDTO, + scope: ReceiveScope + ) async throws -> ReactionAdmission? { + nil + } + + func shouldSuppressChannelMessage( + _ message: MessageDTO, + frame: ChannelMessage, + channel: ChannelDTO, + scope: ReceiveScope?, + preference: TextRulesPreference? + ) async throws -> Bool { + false + } +} diff --git a/MC1Services/Sources/MC1Services/ServiceContainer.swift b/MC1Services/Sources/MC1Services/ServiceContainer.swift index bc92654b99..9a5e01d81f 100644 --- a/MC1Services/Sources/MC1Services/ServiceContainer.swift +++ b/MC1Services/Sources/MC1Services/ServiceContainer.swift @@ -74,6 +74,7 @@ public final class ServiceContainer { /// The persistence store for SwiftData operations public let dataStore: PersistenceStore + let receiveLifetime = ReceiveScope.Lifetime() /// Persists inline-image aspect ratios for chat link previews. Built early /// because downstream caches and the prefetcher depend on it. @@ -225,7 +226,8 @@ public final class ServiceContainer { radioID: UUID, appStateProvider: AppStateProvider? = nil, connectionStateEvents: EventBroadcaster? = nil, - initialConnectionState: DeviceConnectionState = .disconnected + initialConnectionState: DeviceConnectionState = .disconnected, + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil } ) { self.session = session self.appStateProvider = appStateProvider @@ -249,7 +251,10 @@ public final class ServiceContainer { session: session, dataStore: dataStore, keychainService: keychainService, - contactRadioOwner: contactRadioOwner + contactRadioOwner: contactRadioOwner, + textRulesPreference: textRulesPreference, + receiveLifetime: receiveLifetime, + radioID: radioID ) let cleanupCoordinator = ContactCleanupCoordinator( dataStore: dataStore, @@ -283,7 +288,13 @@ public final class ServiceContainer { contactService: contactService, appStateProvider: appStateProvider ) - messagePollingService = MessagePollingService(session: session, dataStore: dataStore) + messagePollingService = MessagePollingService( + session: session, + dataStore: dataStore, + radioID: radioID, + textRulesPreference: textRulesPreference, + receiveLifetime: receiveLifetime + ) binaryProtocolService = BinaryProtocolService( session: session, radioID: radioID, @@ -316,7 +327,9 @@ public final class ServiceContainer { session: session, remoteNodeService: remoteNodeService, dataStore: dataStore, - radioID: radioID + radioID: radioID, + textRulesPreference: textRulesPreference, + receiveLifetime: receiveLifetime ) chatSendQueueService = ChatSendQueueService( @@ -430,6 +443,7 @@ public final class ServiceContainer { /// so the chat send queue drains. `stopEventMonitoring()` alone does not /// cover that. func tearDown() async { + receiveLifetime.retire() await stopEventMonitoring() // Break the retain cycles the wired handlers form. The message diff --git a/MC1Services/Sources/MC1Services/Services/AdvertisementEvent.swift b/MC1Services/Sources/MC1Services/Services/AdvertisementEvent.swift index 8399d8fe5a..d1d8a900e4 100644 --- a/MC1Services/Sources/MC1Services/Services/AdvertisementEvent.swift +++ b/MC1Services/Sources/MC1Services/Services/AdvertisementEvent.swift @@ -11,7 +11,7 @@ import MeshCore public enum AdvertisementEvent: Sendable { /// A contact or discovered node was created or updated; observers should /// reload contact lists. - case contactUpdated + case contactUpdated(contact: ContactDTO? = nil, scope: ReceiveScope? = nil) /// Adopted orphan DMs created or updated a conversation row; observers must /// refresh the conversation list (mirrors `SyncDataEvent.conversationsChanged`). case conversationsChanged diff --git a/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift b/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift index 2e69735b5d..3e470f7fde 100644 --- a/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift +++ b/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift @@ -32,15 +32,7 @@ extension AdvertisementService { return } - guard !Task.isCancelled else { - finishRound(generation: generation) - return - } - guard !isSyncingContacts else { - finishRound(generation: generation) - return - } - guard await isInForeground() else { + guard !Task.isCancelled, !isSyncingContacts, await isInForeground() else { finishRound(generation: generation) return } @@ -192,7 +184,7 @@ extension AdvertisementService { // Adopt against every drained key that now has a row — not only // insertedKeysForNotify — so a snapshot failure still links orphan DMs. let adoptedContactIDs = await adoptOrphanedMessages(for: drained, radioID: radioID) - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) // A non-nil lastMessageDate after adoption is a new/updated conversation // row; contactsVersion alone does not reload the mounted chat list. The // adopted DMs never notified at receipt (no contact then), so hand the @@ -222,8 +214,7 @@ extension AdvertisementService { /// Re-arms after a busy outcome with a short backoff so performResync-style /// claim holds do not spin at zero interval. private func scheduleBusyRetry() { - guard deltaSyncTask == nil else { return } - guard hasPendingDeltaSyncWork else { return } + guard deltaSyncTask == nil, hasPendingDeltaSyncWork else { return } deltaSyncGeneration &+= 1 let generation = deltaSyncGeneration let fireAt = ContinuousClock.now + advertSyncBusyBackoff @@ -280,7 +271,7 @@ extension AdvertisementService { ) else { continue } try await dataStore.deleteContactIfUnreferenced(id: contact.id) logger.info("Delta sync rollback: removed contact \(pubKeyHex) deleted by the radio mid-sync") - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) } catch { logger.error("Delta sync rollback failed for \(pubKeyHex): \(error.localizedDescription)") } @@ -396,8 +387,7 @@ extension AdvertisementService { var missing: Set = [] for publicKey in unknownAtStart { // A key the radio deleted is missing on purpose; refetching cannot bring it back. - guard !isRadioDeleted(publicKey) else { continue } - guard let exists = await contactExists(radioID: radioID, publicKey: publicKey) else { continue } + guard !isRadioDeleted(publicKey), let exists = await contactExists(radioID: radioID, publicKey: publicKey) else { continue } if !exists { missing.insert(publicKey) } @@ -484,8 +474,7 @@ extension AdvertisementService { guard let radioID = currentRadioID else { return } for publicKey in unknownAtStart { - guard !isRadioDeleted(publicKey) else { continue } - guard let exists = await contactExists(radioID: radioID, publicKey: publicKey) else { continue } + guard !isRadioDeleted(publicKey), let exists = await contactExists(radioID: radioID, publicKey: publicKey) else { continue } if !exists { let pubKeyHex = publicKey.uppercaseHexString() logger.info("Advert full refetch still missing key=\(pubKeyHex); dropping") diff --git a/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift b/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift index 6a7d34acd8..1cb9c83b7f 100644 --- a/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift +++ b/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift @@ -279,7 +279,7 @@ public actor AdvertisementService { logger.notice("Overwrite oldest: applying \(deletedIDs.count) deferred deletion(s)") eventBroadcaster.yield(.contactDeletedCleanup(contactIDs: deletedIDs)) eventBroadcaster.yield(.nodeStorageFullChanged(isFull: false)) - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) } catch { pendingDeletedKeys.formUnion(keys) pendingDeletedKeys.subtract(pendingAdvertKeys) @@ -361,9 +361,9 @@ public actor AdvertisementService { /// or the radio fetch / save fails. public func materializeContactForPendingAdvert( matchingPrefix prefix: Data, - radioID: UUID + scope: ReceiveScope ) async -> ContactDTO? { - guard !prefix.isEmpty else { return nil } + guard scope.isCurrent, !prefix.isEmpty else { return nil } let matches = pendingAdvertKeys.filter { $0.starts(with: prefix) } guard matches.count == 1, let publicKey = matches.first else { return nil } @@ -374,29 +374,15 @@ public actor AdvertisementService { logger.info("materialize pending advert: getContact nil key=\(pubKeyHex)") return nil } - let frame = meshContact.toContactFrame() - let saveResult = try await dataStore.insertContactIfAbsent(radioID: radioID, from: frame) - // Stamp phone recency before the returned DTO is read so a debounce-window - // insert is not prune-eligible under a stale radio lastModified. + guard scope.isCurrent, !isRadioDeleted(publicKey) else { return nil } let receivedAt = pendingAdvertReceiveTimes[publicKey] ?? Date() - do { - _ = try await dataStore.touchContactHeard( - radioID: radioID, publicKey: publicKey, at: receivedAt - ) - } catch { - logger.error( - "materialize pending advert lastHeard stamp failed key=\(pubKeyHex): \(error.localizedDescription)" - ) - } - do { - _ = try await dataStore.upsertDiscoveredNode(radioID: radioID, from: frame) - } catch { - logger.error( - "materialize pending advert Discover upsert failed key=\(pubKeyHex): \(error.localizedDescription)" - ) + guard let contact = try await dataStore.materializeContactForDirectMessage( + from: meshContact.toContactFrame(), receivedAt: receivedAt, scope: scope + ) else { return nil } + if scope.isCurrent { + eventBroadcaster.yield(.contactUpdated(contact: contact, scope: scope)) } - eventBroadcaster.yield(.contactUpdated) - return try await dataStore.fetchContact(id: saveResult.id) + return contact } catch { logger.error( "materialize pending advert failed key=\(pubKeyHex): \(error.localizedDescription)" @@ -547,7 +533,7 @@ public actor AdvertisementService { if let known { if known { - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) } else { discoverTrace.debug("B2 0x80 no local contact key=\(pubKeyHex) syncing=\(isSyncingContacts)") logger.debug("ADVERT received for unknown contact - scheduling delta sync") @@ -570,7 +556,7 @@ public actor AdvertisementService { let (node, isNew) = try await dataStore.upsertDiscoveredNode(radioID: radioID, from: contactFrame) discoverTrace.debug("B2 0x8A upsert key=\(pubKeyHex) isNew=\(isNew)") - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) // Notify only first-time discoveries, not repeat adverts for the same contact. if isNew { @@ -730,7 +716,7 @@ public actor AdvertisementService { eventBroadcaster.yield(.contactDeletedCleanup(contactIDs: [contactID])) eventBroadcaster.yield(.nodeStorageFullChanged(isFull: false)) logger.debug("Overwrite oldest: cleanup complete for '\(contactName)', storage full flag cleared") - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) } catch { pendingDeletedKeys.insert(publicKey) logger.error( diff --git a/MC1Services/Sources/MC1Services/Services/DirectMessageAdmission.swift b/MC1Services/Sources/MC1Services/Services/DirectMessageAdmission.swift new file mode 100644 index 0000000000..313b2f4e8f --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/DirectMessageAdmission.swift @@ -0,0 +1,8 @@ +import Foundation + +public enum DirectMessageAdmission: Sendable { + case discarded + case replay(MessageDTO) + case reaction(ContactDTO) + case saved(ContactDTO?) +} diff --git a/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift index fe08727b95..9895a9eebb 100644 --- a/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift @@ -29,19 +29,21 @@ actor MessagePollingService { private let session: any MeshCoreSessionProtocol private let dataStore: any PersistenceStoreProtocol + let receiveLifetime: ReceiveScope.Lifetime + let textRulesPreference: @Sendable () async -> TextRulesPreference? private let logger = PersistentLogger(subsystem: "com.mc1", category: "MessagePolling") /// Handler for incoming contact messages. /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. - private var contactMessageHandler: (@Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void)? + private var contactMessageHandler: (@Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void)? /// Handler for incoming channel messages. /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. - private var channelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void)? + private var channelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void)? /// Handler for signed messages (from room servers). /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. - private var signedMessageHandler: (@Sendable (ContactMessage, ContactDTO?) async -> Void)? + private var signedMessageHandler: (@Sendable (ContactMessage, ReceiveScope) async -> Void)? /// Handler for CLI responses (textType = 0x01). /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. @@ -49,6 +51,8 @@ actor MessagePollingService { /// Event monitoring task private var eventMonitorTask: Task? + private var eventSubscription: Task<(id: UUID, stream: AsyncStream), Never>? + private var isSuspendedForRadioErase = false /// Whether auto-fetch is currently enabled private var isAutoFetchEnabled = false @@ -68,10 +72,16 @@ actor MessagePollingService { init( session: any MeshCoreSessionProtocol, - dataStore: any PersistenceStoreProtocol + dataStore: any PersistenceStoreProtocol, + radioID: UUID? = nil, + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil }, + receiveLifetime: ReceiveScope.Lifetime = .init() ) { self.session = session self.dataStore = dataStore + currentRadioID = radioID + self.textRulesPreference = textRulesPreference + self.receiveLifetime = receiveLifetime } deinit { @@ -81,17 +91,17 @@ actor MessagePollingService { // MARK: - Event Handlers /// Set handler for incoming contact messages - func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void) { + func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) { contactMessageHandler = handler } /// Set handler for incoming channel messages - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void) { + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void) { channelMessageHandler = handler } /// Set handler for signed messages (from room servers) - func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) { + func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) { signedMessageHandler = handler } @@ -185,6 +195,35 @@ actor MessagePollingService { await session.startAutoMessageFetching() } + func suspendForRadioErase() async throws { + guard !isPolling else { throw MessagePollingError.pollingFailed } + guard !isSuspendedForRadioErase else { return } + isSuspendedForRadioErase = true + do { + try await session.suspendMessageFetching() + } catch { + isSuspendedForRadioErase = false + throw error + } + + // Finishing the stream lets the handler commit a reply already in its buffer. + if let eventSubscription, let eventMonitorTask { + await session.finishEvents(id: eventSubscription.value.id) + await eventMonitorTask.value + } + } + + func resumeAfterRadioErase() async { + guard isSuspendedForRadioErase, receiveLifetime.isCurrent else { return } + isSuspendedForRadioErase = false + if eventMonitorTask != nil || isAutoFetchEnabled { + startEventMonitoring() + _ = await eventSubscription?.value + } + guard receiveLifetime.isCurrent else { return } + await session.resumeMessageFetching() + } + /// Check if auto-fetch is currently enabled var isAutoFetching: Bool { isAutoFetchEnabled @@ -205,6 +244,7 @@ actor MessagePollingService { /// Poll all waiting messages from the device. /// - Returns: Count of messages retrieved func pollAllMessages() async throws -> Int { + guard !isSuspendedForRadioErase else { throw CancellationError() } isPolling = true defer { isPolling = false } var count = 0 @@ -254,16 +294,19 @@ actor MessagePollingService { /// Start monitoring MeshCore events for messages private func startEventMonitoring() { + guard !isSuspendedForRadioErase else { return } eventMonitorTask?.cancel() - - eventMonitorTask = Task { [weak self] in - guard let self else { return } - let events = await session.events(filter: EventFilter.anyContactMessage.or(.anyChannelMessage)) - + let subscription = Task { [session] in + await session.eventsTracked(filter: EventFilter.anyContactMessage.or(.anyChannelMessage)) + } + eventSubscription = subscription + eventMonitorTask = Task { [weak self, session] in + let (id, events) = await subscription.value for await event in events { - guard !Task.isCancelled else { break } + guard !Task.isCancelled, let self else { break } await handleEvent(event) } + await session.finishEvents(id: id) } } @@ -271,6 +314,7 @@ actor MessagePollingService { private func stopEventMonitoring() { eventMonitorTask?.cancel() eventMonitorTask = nil + eventSubscription = nil } /// Handle incoming MeshCore event @@ -299,45 +343,43 @@ actor MessagePollingService { private func handleContactMessage(_ message: ContactMessage, context: DeliveryContext) async { guard let radioID = currentRadioID else { logger.warning("Received message but no radio ID set") - await contactMessageHandler?(message, nil, context) return } - // Look up the sender contact - let contact = try? await dataStore.fetchContact( - radioID: radioID, - publicKeyPrefix: message.senderPublicKeyPrefix - ) - - // Route based on text type switch message.textType { case MeshTextType.cliData.rawValue: - // CLI responses from repeaters (textType = 0x01) + let contact = try? await dataStore.fetchContact( + radioID: radioID, + publicKeyPrefix: message.senderPublicKeyPrefix + ) await cliMessageHandler?(message, contact) case MeshTextType.signedPlain.rawValue: - // Signed messages from room servers (textType = 0x02) - await signedMessageHandler?(message, contact) - case MeshTextType.cliCommand.rawValue: - // Queued, not executed. Same path as plain so it is not treated as a CLI reply. - await contactMessageHandler?(message, contact, context) + guard let scope = try? await dataStore.captureReceiveScope(radioID: radioID, link: receiveLifetime) else { + return + } + await signedMessageHandler?(message, scope) default: - // Regular contact messages (textType = 0x00 or unknown) - await contactMessageHandler?(message, contact, context) + // Plain and queued CLI commands both follow ordinary DM delivery. + guard let scope = try? await dataStore.captureReceiveScope(radioID: radioID, link: receiveLifetime) else { + return + } + let preference = await textRulesPreference() + let contact = try? await dataStore.fetchContact( + radioID: radioID, + publicKeyPrefix: message.senderPublicKeyPrefix + ) + await contactMessageHandler?(message, contact, context, scope, preference) } } - /// Handle incoming channel message private func handleChannelMessage(_ message: ChannelMessage, context: DeliveryContext) async { - guard let radioID = currentRadioID else { - logger.warning("Received channel message but no radio ID set") - await channelMessageHandler?(message, nil, context) - return - } - - // Look up the channel + let arrivedAt = Date() + guard let radioID = currentRadioID, + let scope = try? await dataStore.captureReceiveScope(radioID: radioID, link: receiveLifetime) else { return } + let preference = await textRulesPreference() let channel = try? await dataStore.fetchChannel(radioID: radioID, index: message.channelIndex) - - await channelMessageHandler?(message, channel, context) + guard scope.isCurrent else { return } + await channelMessageHandler?(message, channel, context, preference, arrivedAt, scope) } } diff --git a/MC1Services/Sources/MC1Services/Services/NotificationService.swift b/MC1Services/Sources/MC1Services/Services/NotificationService.swift index 27b05f776c..ca9eb48da6 100644 --- a/MC1Services/Sources/MC1Services/Services/NotificationService.swift +++ b/MC1Services/Sources/MC1Services/Services/NotificationService.swift @@ -304,10 +304,10 @@ public final class NotificationService: NSObject { contactID: UUID, messageText: String, messageID: UUID, - isMuted: Bool = false + isMuted: Bool = false, + scope: ReceiveScope? = nil ) async { - guard !isMuted else { return } - guard isAuthorized else { return } + guard !isMuted, scope?.isCurrent != false, isAuthorized else { return } // Check granular preference (uses cached preferences) guard preferences.contactMessagesEnabled else { return } @@ -361,11 +361,10 @@ public final class NotificationService: NSObject { messageText: String, messageID: UUID, notificationLevel: NotificationLevel, - hasSelfMention: Bool + hasSelfMention: Bool, + legacyScope: ReceiveScope? = nil ) async { - guard notificationLevel != .muted else { return } - guard notificationLevel != .mentionsOnly || hasSelfMention else { return } - guard isAuthorized else { return } + guard legacyScope?.isCurrent != false, notificationLevel != .muted, notificationLevel != .mentionsOnly || hasSelfMention, isAuthorized else { return } // Check granular preference (uses cached preferences) guard preferences.channelMessagesEnabled else { return } @@ -421,10 +420,10 @@ public final class NotificationService: NSObject { senderName: String?, messageText: String, messageID: UUID, - notificationLevel: NotificationLevel + notificationLevel: NotificationLevel, + scope: ReceiveScope? = nil ) async { - guard notificationLevel != .muted else { return } - guard isAuthorized else { return } + guard notificationLevel != .muted, isAuthorized else { return } // Check granular preference guard preferences.roomMessagesEnabled else { return } @@ -459,6 +458,7 @@ public final class NotificationService: NSObject { trigger: nil ) + guard scope?.isCurrent != false else { return } do { try await UNUserNotificationCenter.current().add(request) } catch { @@ -596,9 +596,7 @@ public final class NotificationService: NSObject { deviceName: String, batteryPercentage: Int ) async { - guard isAuthorized else { return } - - guard preferences.lowBatteryEnabled else { return } + guard isAuthorized, preferences.lowBatteryEnabled else { return } let content = UNMutableNotificationContent() content.title = stringProvider?.lowBatteryTitle ?? "Low Battery" diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift index ad54daa20f..7d6bd45e34 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift @@ -130,6 +130,9 @@ extension PersistenceStore { inserted += 1 } + for radioID in Set(dtos.map(\.radioID)) { + try bindRecentlyBlockedContacts(radioID: radioID) + } return (inserted, skipped, merged, contactIDsByKey) } @@ -454,8 +457,7 @@ extension PersistenceStore { continue } - guard let foreignPath, foreignPath != parent.pathNodes else { continue } - guard extrasByMessage[localID, default: []].insert(foreignPath).inserted else { continue } + guard let foreignPath, foreignPath != parent.pathNodes, extrasByMessage[localID, default: []].insert(foreignPath).inserted else { continue } modelContext.insert(MessageRepeat( dto: MessageRepeatDTO( messageID: localID, diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift index 7be09ac9a2..303f20f00d 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift @@ -351,6 +351,7 @@ public extension PersistenceStore { #endif try modelContext.save() didCommit = true + publishRecentlyBlockedChange() #if DEBUG backupImportPostCommitHook?() diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift new file mode 100644 index 0000000000..3fadb67767 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift @@ -0,0 +1,50 @@ +import Foundation + +public extension PersistenceStore { + func shouldSuppressChannelMessage( + _ message: MessageDTO, + frame: ChannelMessage, + channel: ChannelDTO, + scope: ReceiveScope?, + preference: TextRulesPreference? + ) async throws -> Bool { + guard scope?.isCurrent != false, scope?.radioID == nil || scope?.radioID == message.radioID else { return true } + guard let conversationID = channel.textRulesID else { return false } + guard let current = try fetchChannel(radioID: message.radioID, index: frame.channelIndex), + current.textRulesID == conversationID else { return true } + + let identity = RecentlyBlockedMessageDTO.Identity( + radioID: message.radioID, + conversationID: conversationID, + senderPrefix: nil, + senderTimestamp: UInt32(frame.senderTimestamp.timeIntervalSince1970), + textType: frame.textType, + wireText: Data(frame.text.utf8) + ) + if try hasRecentlyBlockedMessage(identity) { return true } + + let kind = TextRulesPreference.channelKind(isPublic: current.isPublicChannel, name: current.name) + let key = TextRulesPreference.Key(radioID: message.radioID, conversationID: conversationID) + guard let preference, + !preference.rules.isEmpty, + preference.effective(for: kind, key: key, override: current.textRulesOverride).isOn else { return false } + + let fields = ChannelMessageFormat.originalFields(frame.text) + let isReaction = ReactionParser.isReactionText(message.text, isDM: false) + guard let match = preference.firstMatch(body: isReaction ? nil : fields.body, sender: fields.sender) else { + return false + } + if !isReaction { + try recordRecentlyBlockedMessage(RecentlyBlockedMessageDTO( + identity: identity, + arrivedAt: message.createdAt, + body: fields.body, + sender: fields.sender, + conversationName: current.name, + radioName: fetchDevice(radioID: message.radioID)?.nodeName, + match: match + )) + } + return true + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Channels.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Channels.swift index 65d5bd0793..083d8d06bf 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Channels.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Channels.swift @@ -334,6 +334,8 @@ public extension PersistenceStore { private func applyRadioChannelInfo(_ info: ChannelInfo, to row: Channel) throws { if row.secret != info.secret { try _deleteMessagesForChannelWithoutSaving(radioID: row.radioID, channelIndex: row.index) + row.textRulesID = UUID() + row.textRulesOverrideRawValue = TextRulesPreference.Override.inherit.rawValue row.lastMessageDate = nil row.unreadCount = 0 row.unreadMentionCount = 0 diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Contacts.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Contacts.swift index 057db5bc8a..e24288b42d 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Contacts.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Contacts.swift @@ -116,6 +116,7 @@ public extension PersistenceStore { /// Save or update a contact from a ContactFrame. /// Returns the contact id and whether the row was newly inserted (`isNew`). func saveContact(radioID: UUID, from frame: ContactFrame) throws -> (id: UUID, isNew: Bool) { + try commitPendingRxLogEntries() let targetRadioID = radioID let targetKey = frame.publicKey let predicate = #Predicate { contact in @@ -136,7 +137,7 @@ public extension PersistenceStore { isNew = true } - try modelContext.save() + try saveContactChangesBindingRecentlyBlocked(radioID: radioID) return (id: contact.id, isNew: isNew) } @@ -145,6 +146,7 @@ public extension PersistenceStore { @discardableResult func batchSaveContacts(radioID: UUID, from frames: [ContactFrame]) async throws -> Int { guard !frames.isEmpty else { return 0 } + try commitPendingRxLogEntries() let referenceDate = Date() let targetRadioID = radioID @@ -170,7 +172,7 @@ public extension PersistenceStore { } } - try modelContext.save() + try saveContactChangesBindingRecentlyBlocked(radioID: radioID) return frames.count } @@ -188,6 +190,7 @@ public extension PersistenceStore { /// Save or update a contact from DTO func saveContact(_ dto: ContactDTO) throws { + try commitPendingRxLogEntries() let targetID = dto.id let predicate = #Predicate { contact in contact.id == targetID @@ -201,11 +204,12 @@ public extension PersistenceStore { modelContext.insert(Contact(dto: dto)) } - try modelContext.save() + try saveContactChangesBindingRecentlyBlocked(radioID: dto.radioID) } @discardableResult func insertContactIfAbsent(radioID: UUID, from frame: ContactFrame) throws -> (id: UUID, isNew: Bool) { + try commitPendingRxLogEntries() let targetRadioID = radioID let targetKey = frame.publicKey let predicate = #Predicate { contact in @@ -220,7 +224,7 @@ public extension PersistenceStore { let contact = Contact(radioID: radioID, from: frame) modelContext.insert(contact) - try modelContext.save() + try saveContactChangesBindingRecentlyBlocked(radioID: radioID) return (id: contact.id, isNew: true) } @@ -378,17 +382,21 @@ public extension PersistenceStore { try commitPendingRxLogEntries() do { try _stageOverwriteOldestCascade(contactID: id) + try stageRecentlyBlockedContactDeletion(contactID: id) let targetID = id let predicate = #Predicate { contact in contact.id == targetID } if let contact = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first { + let radioID = contact.radioID modelContext.delete(contact) + try bindRecentlyBlockedContacts(radioID: radioID) } #if DEBUG try deleteContactsFaultInjection?() #endif try modelContext.save() + publishRecentlyBlockedChange() } catch { modelContext.rollback() throw error @@ -439,14 +447,17 @@ public extension PersistenceStore { if skippingPublicKeys().contains(publicKey) { continue } let contactID = contact.id try _stageOverwriteOldestCascade(contactID: contactID) + try stageRecentlyBlockedContactDeletion(contactID: contactID) modelContext.delete(contact) deletedIDs.append(contactID) } if !deletedIDs.isEmpty { + try bindRecentlyBlockedContacts(radioID: radioID) #if DEBUG try deleteContactsFaultInjection?() #endif try modelContext.save() + publishRecentlyBlockedChange() } } catch { modelContext.rollback() @@ -458,7 +469,7 @@ public extension PersistenceStore { /// Insert-only rollback: probe for messages and delete in one ModelActor /// region with no suspension between them. Prefer an orphan contact over a /// cascade that wipes a concurrent DM. - func deleteContactIfUnreferenced(id: UUID) throws { + func deleteContactIfUnreferenced(id: UUID) async throws { let targetID = id let messagePredicate = #Predicate { message in message.contactID == targetID @@ -468,6 +479,7 @@ public extension PersistenceStore { if try modelContext.fetch(messageDescriptor).first != nil { return } + guard try !hasRecentlyBlockedContactReference(contactID: id) else { return } try deleteContact(id: id) } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift index c922fd9355..601e4bfd9d 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift @@ -291,8 +291,17 @@ public extension PersistenceStore { /// RX log entries, discovered nodes, contacts, messages, channels, and saved trace paths. /// Does NOT delete the Device record itself. func deleteDeviceData(id: UUID) throws { - try _deleteAllDeviceData(id: id) - try modelContext.save() + guard let radioID = try fetchDevice(id: id)?.radioID else { return } + try commitPendingRxLogEntries() + do { + try stageDeleteAllDeviceData(radioID: radioID) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + retireReceiveScope(radioID: radioID) + publishRecentlyBlockedChange() } /// Delete a device record only. Does NOT delete associated data. @@ -361,16 +370,21 @@ public extension PersistenceStore { /// Delete a device and all its associated data atomically (single save). /// Use for factory reset and explicit "delete all data" user action. func deleteDeviceAndData(id: UUID) throws { - try _deleteAllDeviceData(id: id) - - let targetID = id - let devicePredicate = #Predicate { device in - device.id == targetID - } - if let device = try modelContext.fetch(FetchDescriptor(predicate: devicePredicate)).first { - modelContext.delete(device) + guard let radioID = try fetchDevice(id: id)?.radioID else { return } + try commitPendingRxLogEntries() + do { + try stageDeleteAllDeviceData(radioID: radioID) + let predicate = #Predicate { $0.id == id } + if let device = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first { + modelContext.delete(device) + } + try modelContext.save() + } catch { + modelContext.rollback() + throw error } - try modelContext.save() + retireReceiveScope(radioID: radioID) + publishRecentlyBlockedChange() } /// Looks for a ghost `Device` row whose `publicKey` matches `newPublicKey` @@ -420,34 +434,42 @@ public extension PersistenceStore { currentDescriptor.fetchLimit = 1 guard let current = try modelContext.fetch(currentDescriptor).first else { return nil } + let previousRadioID = current.radioID let newRadioID = ghost.radioID - current.radioID = newRadioID - current.publicKey = newPublicKey - current.connectionMethods = ConnectionMethod.canonicalized(current.connectionMethods) - if !current.connectionMethods.isEmpty, - !current.connectionMethods.contains(where: \.isWiFi), - let wifi = ConnectionMethod.canonicalized(ghost.connectionMethods).first(where: \.isWiFi) { - current.connectionMethods.insert(wifi, at: 0) + let oldOwner = #Predicate { $0.radioID == previousRadioID && $0.id != lookupID } + let abandoned = try previousRadioID != newRadioID && + modelContext.fetchCount(FetchDescriptor(predicate: oldOwner)) == 0 + + try commitPendingRxLogEntries() + do { + current.radioID = newRadioID + current.publicKey = newPublicKey + current.connectionMethods = ConnectionMethod.canonicalized(current.connectionMethods) + if !current.connectionMethods.isEmpty, + !current.connectionMethods.contains(where: \.isWiFi), + let wifi = ConnectionMethod.canonicalized(ghost.connectionMethods).first(where: \.isWiFi) { + current.connectionMethods.insert(wifi, at: 0) + } + if abandoned { + try retireTextRulesIdentities(radioID: previousRadioID) + try stageRecentlyBlockedDeletion(radioID: previousRadioID) + } + modelContext.delete(ghost) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + if abandoned { + retireReceiveScope(radioID: previousRadioID) + publishRecentlyBlockedChange() } - - modelContext.delete(ghost) - try modelContext.save() return newRadioID } - /// Stages deletion of all device-scoped data without calling save(). - /// Used by both `deleteDeviceData` and `deleteDeviceAndData` to compose - /// operations while maintaining single-save atomicity. - private func _deleteAllDeviceData(id: UUID) throws { - // Look up the Device's radioID since child records are keyed by radioID, not BLE UUID - let targetBLEID = id - let devicePredicate = #Predicate { device in - device.id == targetBLEID - } - guard let device = try modelContext.fetch(FetchDescriptor(predicate: devicePredicate)).first else { - return - } - let targetRadioID = device.radioID + /// Stages radio-scoped deletion independently of the lifetime of its Device row. + func stageDeleteAllDeviceData(radioID targetRadioID: UUID) throws { + try stageRecentlyBlockedDeletion(radioID: targetRadioID) // Delete reactions (references messages via messageID) let reactionPredicate = #Predicate { reaction in diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift new file mode 100644 index 0000000000..b008bc0289 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift @@ -0,0 +1,179 @@ +import Foundation +import SwiftData + +public extension PersistenceStore { + func admitDirectMessage( + _ message: MessageDTO, + wireTextType: UInt8, + contact capturedContact: ContactDTO?, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> DirectMessageAdmission { + guard scope.radioID == message.radioID, scope.isCurrent else { return .discarded } + let contact: ContactDTO? + if let capturedContact { + guard let current = try fetchCurrentDirectMessageContact(capturedContact, scope: scope) else { + return .discarded + } + contact = current + } else { + contact = nil + } + + let wireTimestamp = message.senderTimestamp ?? message.timestamp + let body = Data(message.text.utf8) + if let saved = try savedDirectMessage(message, timestamp: wireTimestamp, body: body) { + return .replay(saved) + } + + let identity = RecentlyBlockedMessageDTO.Identity( + radioID: message.radioID, + conversationID: nil, + senderPrefix: message.senderKeyPrefix, + senderTimestamp: wireTimestamp, + textType: wireTextType, + wireText: body + ) + if try hasRecentlyBlockedMessage(identity) { return .discarded } + + let isReaction = contact != nil && ReactionParser.isReactionText(message.text, isDM: true) + let key = contact?.textRulesID.map { + TextRulesPreference.Key(radioID: message.radioID, conversationID: $0) + } + if let preference, + !preference.rules.isEmpty, + contact?.isBlocked != true, + preference.effective(for: .directMessage, key: key, override: contact?.textRulesOverride ?? .inherit).isOn { + let sender = try uniqueDirectMessageSender(message) + if let match = preference.firstMatch(body: isReaction ? nil : message.text, sender: sender?.displayName) { + if !isReaction { + try recordRecentlyBlockedMessage(RecentlyBlockedMessageDTO( + identity: identity, + arrivedAt: message.createdAt, + body: message.text, + sender: sender?.displayName, + conversationName: contact?.displayName, + radioName: fetchDevice(radioID: message.radioID)?.nodeName, + match: match, + contactID: sender?.id + )) + } + return .discarded + } + } + + if isReaction, let contact { return .reaction(contact) } + try saveMessage(message) + return .saved(contact) + } + + func currentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) async throws -> ContactDTO? { + try fetchCurrentDirectMessageContact(contact, scope: scope) + } + + func materializeContactForDirectMessage( + from frame: ContactFrame, + receivedAt: Date, + scope: ReceiveScope + ) async throws -> ContactDTO? { + guard scope.isCurrent else { return nil } + + let result = try insertContactIfAbsent(radioID: scope.radioID, from: frame) + _ = try touchContactHeard(radioID: scope.radioID, publicKey: frame.publicKey, at: receivedAt) + _ = try upsertDiscoveredNode(radioID: scope.radioID, from: frame) + return try fetchContact(id: result.id) + } + + func touchDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope, at date: Date) async throws { + guard try fetchCurrentDirectMessageContact(contact, scope: scope) != nil else { return } + _ = try touchContactHeard(radioID: scope.radioID, publicKey: contact.publicKey, at: date) + } + + func updateContactAfterDirectMessage( + _ message: MessageDTO, + contact: ContactDTO, + scope: ReceiveScope, + isViewingContact: Bool + ) async throws -> ContactDTO? { + guard let current = try fetchCurrentDirectMessageContact(contact, scope: scope) else { return nil } + try updateContactLastMessage(contactID: current.id, date: message.createdAt) + if !isViewingContact, !current.isBlocked { + try incrementUnreadCount(contactID: current.id) + if message.containsSelfMention { + try incrementUnreadMentionCount(contactID: current.id) + } + } + return current + } + + func admitDirectMessageReaction( + _ reaction: ReactionDTO, + contact: ContactDTO, + scope: ReceiveScope + ) async throws -> ReactionAdmission? { + guard reaction.contactID == contact.id, reaction.radioID == scope.radioID, + try fetchCurrentDirectMessageContact(contact, scope: scope) != nil else { + return nil + } + return try admitReaction(reaction) + } +} + +private extension PersistenceStore { + static let directMessageSenderPrefixLength = 6 + + func fetchCurrentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) throws -> ContactDTO? { + guard scope.isCurrent, contact.radioID == scope.radioID, + let current = try fetchContact(id: contact.id), + current.radioID == scope.radioID, current.textRulesID == contact.textRulesID else { + return nil + } + return current + } + + func uniqueDirectMessageSender(_ message: MessageDTO) throws -> ContactDTO? { + guard let prefix = message.senderKeyPrefix, prefix.count == Self.directMessageSenderPrefixLength else { + return nil + } + let radioID = message.radioID + let descriptor = FetchDescriptor(predicate: #Predicate { $0.radioID == radioID }) + let matches = try modelContext.fetch(descriptor).lazy.filter { $0.publicKey.starts(with: prefix) }.prefix(2) + return matches.count == 1 ? matches.first.map { ContactDTO(from: $0) } : nil + } + + func savedDirectMessage(_ incoming: MessageDTO, timestamp: UInt32, body: Data) throws -> MessageDTO? { + guard let prefix = incoming.senderKeyPrefix, prefix.count == Self.directMessageSenderPrefixLength else { + return nil + } + let radioID = incoming.radioID + let incomingDirection = MessageDirection.incoming.rawValue + let type = incoming.textType.rawValue + let senderPrefix: Data? = prefix + let senderTimestamp: UInt32? = timestamp + + if let key = incoming.deduplicationKey, + let saved = try fetchMessage(deduplicationKey: key, radioID: radioID), + saved.direction == .incoming, saved.channelIndex == nil, + saved.senderKeyPrefix == prefix, saved.textType == incoming.textType, + (saved.senderTimestamp ?? (saved.timestampCorrected ? nil : saved.timestamp)) == timestamp, + saved.text.utf8.elementsEqual(body) { + return saved + } + + let corrected = #Predicate { + $0.radioID == radioID && $0.senderKeyPrefix == senderPrefix && $0.senderTimestamp == senderTimestamp && + $0.directionRawValue == incomingDirection && $0.channelIndex == nil && $0.textTypeRawValue == type + } + let original = #Predicate { + $0.radioID == radioID && $0.senderKeyPrefix == senderPrefix && $0.timestamp == timestamp && + $0.senderTimestamp == nil && !$0.timestampCorrected && + $0.directionRawValue == incomingDirection && $0.channelIndex == nil && $0.textTypeRawValue == type + } + for predicate in [corrected, original] { + if let row = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first(where: { $0.text.utf8.elementsEqual(body) }) { + return MessageDTO(from: row) + } + } + return nil + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift index f9ae6069e6..98c7427168 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -397,6 +397,16 @@ public extension PersistenceStore { try modelContext.save() } + func saveLegacyChannelMessage(_ dto: MessageDTO, scope: ReceiveScope?, conversationID: UUID?) async throws -> Bool { + if let scope, !scope.isCurrent || scope.radioID != dto.radioID { return false } + if let conversationID, let index = dto.channelIndex, + try fetchChannel(radioID: dto.radioID, index: index)?.textRulesID != conversationID { + return false + } + try saveMessage(dto) + return true + } + /// Update message status func updateMessageStatus(id: UUID, status: MessageStatus) throws { let targetID = id diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+RadioErase.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RadioErase.swift new file mode 100644 index 0000000000..26e881d6d3 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RadioErase.swift @@ -0,0 +1,115 @@ +import Foundation +import SwiftData + +extension PersistenceStore { + public func captureReceiveScope(radioID: UUID, link: ReceiveScope.Lifetime) async throws -> ReceiveScope? { + guard link.isCurrent, try !isRadioErasePending(radioID) else { return nil } + if let partition = receivePartitions[radioID] { + return ReceiveScope(radioID: radioID, link: link, partition: partition) + } + guard try fetchDevice(radioID: radioID) != nil else { return nil } + try backfillTextRulesIdentities(radioID: radioID) + let partition = ReceiveScope.Lifetime() + receivePartitions[radioID] = partition + return ReceiveScope(radioID: radioID, link: link, partition: partition) + } + + func retireReceiveScope(radioID: UUID) { + receivePartitions.removeValue(forKey: radioID)?.retire() + } + + func fetchPendingRadioErases() throws -> [PendingRadioEraseDTO] { + try modelContext.fetch(FetchDescriptor()).map(PendingRadioEraseDTO.init) + } + + func isRadioErasePending(_ radioID: UUID) throws -> Bool { + if let pendingEraseRadioIDs { + return pendingEraseRadioIDs.contains(radioID) + } + let pending = try Set(fetchPendingRadioErases().map(\.radioID)) + pendingEraseRadioIDs = pending + return pending.contains(radioID) + } + + func beginRadioErase(_ device: DeviceDTO, isFactoryReset: Bool = false) throws -> PendingRadioEraseDTO { + let radioID = device.radioID + if let existing = try pendingRadioErase(radioID) { + return PendingRadioEraseDTO(existing) + } + guard try fetchDevice(id: device.id)?.radioID == radioID else { + throw PersistenceStoreError.deviceNotFound + } + let target = PendingRadioEraseDTO( + radioID: radioID, + deviceID: device.id, + pairingID: device.bluetoothPeripheralID ?? device.id, + radioName: device.nodeName, + isFactoryReset: isFactoryReset + ) + try commitPendingRxLogEntries() + do { + modelContext.insert(PendingRadioErase(target)) + #if DEBUG + try beginRadioEraseFaultInjection?() + #endif + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + pendingEraseRadioIDs?.insert(radioID) + retireReceiveScope(radioID: radioID) + return target + } + + func cancelRadioErase(radioID: UUID) throws { + guard let target = try pendingRadioErase(radioID) else { return } + try commitPendingRxLogEntries() + do { + modelContext.delete(target) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + pendingEraseRadioIDs?.remove(radioID) + } + + func completeRadioErase(radioID: UUID) throws { + guard let target = try pendingRadioErase(radioID) else { return } + try commitPendingRxLogEntries() + do { + try stageDeleteAllDeviceData(radioID: radioID) + #if DEBUG + try completeRadioEraseFaultInjection?() + #endif + let devices = try modelContext.fetch(FetchDescriptor(predicate: #Predicate { $0.radioID == radioID })) + for device in devices { + modelContext.delete(device) + } + modelContext.delete(target) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + pendingEraseRadioIDs?.remove(radioID) + publishRecentlyBlockedChange() + } + + private func pendingRadioErase(_ radioID: UUID) throws -> PendingRadioErase? { + var descriptor = FetchDescriptor(predicate: #Predicate { $0.radioID == radioID }) + descriptor.fetchLimit = 1 + return try modelContext.fetch(descriptor).first + } + + #if DEBUG + func setRadioEraseFaults( + begin: (@Sendable () throws -> Void)?, + complete: (@Sendable () throws -> Void)? + ) { + beginRadioEraseFaultInjection = begin + completeRadioEraseFaultInjection = complete + } + #endif +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlocked.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlocked.swift new file mode 100644 index 0000000000..c1257ef3be --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlocked.swift @@ -0,0 +1,75 @@ +import Foundation +import SwiftData + +public extension PersistenceStore { + nonisolated func recentlyBlockedUpdates() -> AsyncStream { + recentlyBlockedChanges.subscribe(bufferingPolicy: .bufferingNewest(1)) + } + + internal func publishRecentlyBlockedChange() { + recentlyBlockedChanges.yield(()) + } + + func recentlyBlockedMessages() throws -> [RecentlyBlockedMessageDTO] { + try sortedRecentlyBlockedMessages().map(RecentlyBlockedMessageDTO.init(from:)) + } + + func recentlyBlockedCount() throws -> Int { + try modelContext.fetchCount(FetchDescriptor()) + } + + func hasRecentlyBlockedMessages(radioID: UUID, conversationID: UUID) async throws -> Bool { + let predicate = #Predicate { + $0.radioID == radioID && $0.conversationID == conversationID + } + var descriptor = FetchDescriptor(predicate: predicate) + descriptor.fetchLimit = 1 + return try !modelContext.fetch(descriptor).isEmpty + } + + internal func hasRecentlyBlockedMessage(_ identity: RecentlyBlockedMessageDTO.Identity) throws -> Bool { + let radioID = identity.radioID + let timestamp = identity.senderTimestamp + let predicate = #Predicate { + $0.radioID == radioID && $0.senderTimestamp == timestamp + } + return try modelContext.fetch(FetchDescriptor(predicate: predicate)).contains { + $0.identity == identity + } + } + + internal func recordRecentlyBlockedMessage(_ entry: RecentlyBlockedMessageDTO) throws { + guard try !hasRecentlyBlockedMessage(entry.identity) else { return } + try commitPendingRxLogEntries() + + do { + let rows = try modelContext.fetch(FetchDescriptor()) + let entry = try RecentlyBlockedMessage(entry) + let sorted = (rows + [entry]).sorted(by: Self.isMoreRecent) + modelContext.insert(entry) + for expired in sorted.dropFirst(Self.recentlyBlockedRetentionLimit) { + modelContext.delete(expired) + } + #if DEBUG + try recordRecentlyBlockedFaultInjection?() + #endif + try modelContext.save() + publishRecentlyBlockedChange() + } catch { + modelContext.rollback() + throw error + } + } + + private func sortedRecentlyBlockedMessages() throws -> [RecentlyBlockedMessage] { + try modelContext.fetch(FetchDescriptor()).sorted(by: Self.isMoreRecent) + } + + private static func isMoreRecent(_ left: RecentlyBlockedMessage, _ right: RecentlyBlockedMessage) -> Bool { + if left.arrivedAt == right.arrivedAt { + left.id.uuidString > right.id.uuidString + } else { + left.arrivedAt > right.arrivedAt + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlockedOwnership.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlockedOwnership.swift new file mode 100644 index 0000000000..b539936951 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlockedOwnership.swift @@ -0,0 +1,69 @@ +import Foundation +import SwiftData + +extension PersistenceStore { + func stageRecentlyBlockedDeletion(radioID: UUID) throws { + let rows = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID } + )) + for row in rows { + modelContext.delete(row) + } + } + + func stageRecentlyBlockedRoomDeletion(radioID: UUID, conversationID: UUID) throws { + let rows = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID && $0.conversationID == conversationID } + )) + for row in rows { + modelContext.delete(row) + } + } + + func stageRecentlyBlockedContactDeletion(contactID: UUID) throws { + let rows = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.contactID == contactID } + )) + for row in rows { + modelContext.delete(row) + } + } + + func hasRecentlyBlockedContactReference(contactID: UUID) throws -> Bool { + var descriptor = FetchDescriptor(predicate: #Predicate { $0.contactID == contactID }) + descriptor.fetchLimit = 1 + return try !modelContext.fetch(descriptor).isEmpty + } + + @discardableResult + func bindRecentlyBlockedContacts(radioID: UUID) throws -> Bool { + let unbound = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID && $0.conversationID == nil && $0.contactID == nil } + )) + guard !unbound.isEmpty else { return false } + + let contacts = try modelContext.fetch(FetchDescriptor(predicate: #Predicate { $0.radioID == radioID })) + let prefixLength = 6 + let contactsByPrefix = Dictionary(grouping: contacts) { Data($0.publicKey.prefix(prefixLength)) } + var changed = false + for row in unbound { + guard let prefix = row.senderPrefix, + let matches = contactsByPrefix[prefix], + matches.count == 1, let contact = matches.first else { continue } + row.contactID = contact.id + changed = true + } + return changed + } + + func saveContactChangesBindingRecentlyBlocked(radioID: UUID) throws { + do { + let changed = try bindRecentlyBlockedContacts(radioID: radioID) + try modelContext.save() + if changed { publishRecentlyBlockedChange() } + } catch { + modelContext.rollback() + throw error + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+RoomReceive.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RoomReceive.swift new file mode 100644 index 0000000000..5b9c07aa8a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RoomReceive.swift @@ -0,0 +1,105 @@ +import Foundation +import SwiftData + +extension PersistenceStore { + func receiveRoomPost( + _ post: RoomMessageDTO, + in room: RemoteNodeSessionDTO, + scope: ReceiveScope, + preference: TextRulesPreference? + ) throws -> (message: RoomMessageDTO?, recovered: Bool) { + guard scope.isCurrent, scope.radioID == room.radioID else { return (nil, false) } + + let sessionID = room.id + var roomDescriptor = FetchDescriptor(predicate: #Predicate { $0.id == sessionID }) + roomDescriptor.fetchLimit = 1 + guard let session = try modelContext.fetch(roomDescriptor).first, + session.radioID == room.radioID, + session.textRulesID == room.textRulesID else { return (nil, false) } + + let key = post.deduplicationKey + let candidates = try modelContext.fetch(FetchDescriptor(predicate: #Predicate { + $0.sessionID == sessionID && $0.deduplicationKey == key + })) + let alreadySaved = candidates.contains { + $0.timestamp == post.timestamp && + $0.authorKeyPrefix == post.authorKeyPrefix && + $0.text.utf8.elementsEqual(post.text.utf8) + } + let identity = RecentlyBlockedMessageDTO.Identity( + radioID: room.radioID, + conversationID: room.textRulesID, + senderPrefix: post.authorKeyPrefix, + senderTimestamp: post.timestamp, + textType: TextType.signedPlain.rawValue, + wireText: Data(post.text.utf8) + ) + if try alreadySaved || hasRecentlyBlockedMessage(identity) { + return try (nil, recoverRoom(session)) + } + + let displayName = try findContactNameByKeyPrefix(post.authorKeyPrefix) + if !post.isFromSelf, + let preference, + let conversationID = room.textRulesID, + preference.effective( + for: .room, + key: .init(radioID: room.radioID, conversationID: conversationID), + override: session.textRulesOverride + ).isOn { + let matchingName = try uniqueRoomAuthorName(post.authorKeyPrefix, radioID: room.radioID) + if let match = preference.firstMatch(body: post.text, sender: matchingName) { + let radioName = try fetchDevice(radioID: room.radioID)?.nodeName + try recordRecentlyBlockedMessage(RecentlyBlockedMessageDTO( + identity: identity, + arrivedAt: post.createdAt, + body: post.text, + sender: matchingName ?? displayName, + conversationName: session.name, + radioName: radioName, + match: match + )) + return try (nil, recoverRoom(session)) + } + } + + try commitPendingRxLogEntries() + let recovered = !session.isConnected + let message = RoomMessage(dto: post) + message.authorName = displayName + modelContext.insert(message) + session.isConnected = true + session.lastSyncTimestamp = max(session.lastSyncTimestamp, post.timestamp) + session.lastMessageDate = post.createdAt + if !post.isFromSelf { session.unreadCount += 1 } + do { + try modelContext.save() + return (RoomMessageDTO(from: message), recovered) + } catch { + modelContext.rollback() + throw error + } + } + + private func recoverRoom(_ room: RemoteNodeSession) throws -> Bool { + guard !room.isConnected else { return false } + try commitPendingRxLogEntries() + room.isConnected = true + do { + try modelContext.save() + return true + } catch { + modelContext.rollback() + throw error + } + } + + private func uniqueRoomAuthorName(_ prefix: Data, radioID: UUID) throws -> String? { + let descriptor = FetchDescriptor(predicate: #Predicate { $0.radioID == radioID }) + let matches = try modelContext.fetch(descriptor).lazy + .filter { $0.publicKey.prefix(prefix.count) == prefix } + .prefix(2) + guard matches.count == 1 else { return nil } + return matches.first?.displayName + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Rooms.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Rooms.swift index dbed549ba4..69d13d721c 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Rooms.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Rooms.swift @@ -199,26 +199,34 @@ public extension PersistenceStore { /// Delete remote node session and all associated room messages func deleteRemoteNodeSession(id: UUID) throws { - let targetID = id + try commitPendingRxLogEntries() + do { + let targetID = id - // Delete associated room messages - let messagePredicate = #Predicate { message in - message.sessionID == targetID - } - let messages = try modelContext.fetch(FetchDescriptor(predicate: messagePredicate)) - for message in messages { - modelContext.delete(message) - } + let messagePredicate = #Predicate { message in + message.sessionID == targetID + } + let messages = try modelContext.fetch(FetchDescriptor(predicate: messagePredicate)) + for message in messages { + modelContext.delete(message) + } - // Delete the session - let sessionPredicate = #Predicate { session in - session.id == targetID - } - if let session = try modelContext.fetch(FetchDescriptor(predicate: sessionPredicate)).first { - modelContext.delete(session) - } + let sessionPredicate = #Predicate { session in + session.id == targetID + } + if let session = try modelContext.fetch(FetchDescriptor(predicate: sessionPredicate)).first { + if let conversationID = session.textRulesID { + try stageRecentlyBlockedRoomDeletion(radioID: session.radioID, conversationID: conversationID) + } + modelContext.delete(session) + } - try modelContext.save() + try modelContext.save() + publishRecentlyBlockedChange() + } catch { + modelContext.rollback() + throw error + } } /// Mark a room session as connected. Called when an incoming message proves diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+TextRulesConversations.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+TextRulesConversations.swift new file mode 100644 index 0000000000..5e31aebe44 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+TextRulesConversations.swift @@ -0,0 +1,172 @@ +import Foundation +import SwiftData + +public extension PersistenceStore { + func fetchChannelForInfo(id: UUID) throws -> ChannelDTO? { + guard let channel = try fetchChannel(id: id) else { return nil } + guard channel.textRulesID == nil, + try !isRadioErasePending(channel.radioID), + try fetchDevice(radioID: channel.radioID) != nil else { return channel } + try backfillTextRulesIdentities(radioID: channel.radioID) + return try fetchChannel(id: id) + } + + func textRulesConversations(kind: TextRulesPreference.Kind? = nil) throws -> [TextRulesPreference.Conversation] { + var namesByRadio: [UUID: String] = [:] + for device in try fetchDevices() where namesByRadio[device.radioID] == nil { + guard try !isRadioErasePending(device.radioID) else { continue } + namesByRadio[device.radioID] = device.nodeName + try backfillTextRulesIdentities(radioID: device.radioID) + } + + var conversations: [TextRulesPreference.Conversation] = [] + for (radioID, radioName) in namesByRadio { + if kind != .directMessage && kind != .room { + for channel in try fetchChannels(radioID: radioID) { + let channelKind = TextRulesPreference.channelKind(isPublic: channel.isPublicChannel, name: channel.name) + guard kind == nil || channelKind == kind, let localID = channel.textRulesID else { continue } + conversations.append(.init( + key: .init(radioID: radioID, conversationID: localID), + kind: channelKind, name: channel.name, radioName: radioName, override: channel.textRulesOverride + )) + } + } + if kind == nil || kind == .directMessage { + for contact in try fetchContacts(radioID: radioID) where contact.type == .chat { + guard let localID = contact.textRulesID else { continue } + conversations.append(.init( + key: .init(radioID: radioID, conversationID: localID), + kind: .directMessage, name: contact.displayName, radioName: radioName, override: contact.textRulesOverride + )) + } + } + if kind == nil || kind == .room { + for room in try fetchRemoteNodeSessions(radioID: radioID) where room.isRoom { + guard let localID = room.textRulesID else { continue } + conversations.append(.init( + key: .init(radioID: radioID, conversationID: localID), + kind: .room, name: room.name, radioName: radioName, override: room.textRulesOverride + )) + } + } + } + return conversations.sorted { + if $0.name != $1.name { return $0.name.localizedStandardCompare($1.name) == .orderedAscending } + return $0.radioName.localizedStandardCompare($1.radioName) == .orderedAscending + } + } + + func textRulesConversation( + kind: TextRulesPreference.Kind, + key: TextRulesPreference.Key + ) throws -> TextRulesPreference.Conversation? { + let radioID = key.radioID + let conversationID = key.conversationID + guard try !isRadioErasePending(radioID), let device = try fetchDevice(radioID: radioID) else { return nil } + let name: String + let choice: TextRulesPreference.Override + switch kind { + case .directMessage: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let contact = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { return nil } + name = contact.displayName + choice = contact.textRulesOverride + case .room: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let room = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { return nil } + name = room.name + choice = room.textRulesOverride + case .publicChannel, .hashtagChannel, .privateChannel: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let channel = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { return nil } + name = channel.name + choice = channel.textRulesOverride + } + return .init(key: key, kind: kind, name: name, radioName: device.nodeName, override: choice) + } + + func setTextRulesOverride( + _ choice: TextRulesPreference.Override, + kind: TextRulesPreference.Kind, + key: TextRulesPreference.Key + ) throws { + let radioID = key.radioID + let conversationID = key.conversationID + guard try !isRadioErasePending(radioID), try fetchDevice(radioID: radioID) != nil else { + throw PersistenceStoreError.deviceNotFound + } + try commitPendingRxLogEntries() + do { + switch kind { + case .directMessage: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let contact = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { + throw PersistenceStoreError.contactNotFound + } + contact.textRulesOverrideRawValue = choice.rawValue + case .room: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let room = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { + throw PersistenceStoreError.remoteNodeSessionNotFound + } + room.textRulesOverrideRawValue = choice.rawValue + case .publicChannel, .hashtagChannel, .privateChannel: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let channel = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { + throw PersistenceStoreError.channelNotFound + } + channel.textRulesOverrideRawValue = choice.rawValue + } + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + } +} + +extension PersistenceStore { + func backfillTextRulesIdentities(radioID: UUID) throws { + let channels = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID && $0.textRulesID == nil } + )) + let contacts = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID && $0.textRulesID == nil } + )) + let sessions = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID && $0.textRulesID == nil } + )) + guard !channels.isEmpty || !contacts.isEmpty || !sessions.isEmpty else { return } + try commitPendingRxLogEntries() + do { + for channel in channels { + channel.textRulesID = UUID() + } + for contact in contacts { + contact.textRulesID = UUID() + } + for session in sessions { + session.textRulesID = UUID() + } + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + } + + func retireTextRulesIdentities(radioID: UUID) throws { + for channel in try modelContext.fetch(FetchDescriptor(predicate: #Predicate { $0.radioID == radioID })) { + channel.textRulesID = nil + channel.textRulesOverrideRawValue = TextRulesPreference.Override.inherit.rawValue + } + for contact in try modelContext.fetch(FetchDescriptor(predicate: #Predicate { $0.radioID == radioID })) { + contact.textRulesID = nil + contact.textRulesOverrideRawValue = TextRulesPreference.Override.inherit.rawValue + } + for room in try modelContext.fetch(FetchDescriptor(predicate: #Predicate { $0.radioID == radioID })) { + room.textRulesID = nil + room.textRulesOverrideRawValue = TextRulesPreference.Override.inherit.rawValue + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift index 4eca662121..bb95788e0c 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift @@ -65,6 +65,12 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { self.modelContainer = modelContainer } + var receivePartitions: [UUID: ReceiveScope.Lifetime] = [:] + var pendingEraseRadioIDs: Set? + + public static let recentlyBlockedRetentionLimit = 100 + nonisolated let recentlyBlockedChanges = EventBroadcaster() + var rxLogEntryCountsByDevice: [UUID: Int] = [:] var unsavedRxLogInsertCount = 0 var rxLogFlushTask: Task? @@ -119,9 +125,18 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { /// Test-only hook at the top of `fetchDevice(id:)`. The pairing query skips that id on throw. var fetchDeviceByIDFaultInjection: (@Sendable () throws -> Void)? + var beginRadioEraseFaultInjection: (@Sendable () throws -> Void)? + var completeRadioEraseFaultInjection: (@Sendable () throws -> Void)? + /// Test-only hook at the top of `fetchContactIDs`. A throw leaves that fetch unfinished. var fetchContactIDsFaultInjection: (@Sendable () throws -> Void)? + var recordRecentlyBlockedFaultInjection: (@Sendable () throws -> Void)? + + public func setRecordRecentlyBlockedFaultInjection(_ hook: (@Sendable () throws -> Void)?) { + recordRecentlyBlockedFaultInjection = hook + } + var updateContactLastMessageFaultInjection: (@Sendable () throws -> Void)? func setDeleteContactsFaultInjection(_ hook: (@Sendable () throws -> Void)?) { @@ -147,7 +162,9 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { DiscoveredNode.self, NodeStatusSnapshot.self, BlockedChannelSender.self, - PendingSend.self + PendingRadioErase.self, + PendingSend.self, + RecentlyBlockedMessage.self ]) /// Creates a ModelContainer for the app. @@ -174,6 +191,8 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { /// Int8 flood sentinel. DTO still exposes UInt8 via truncatingIfNeeded. /// - v8→v9: Added Contact.isPinned (Bool, default false). Channel.isFavorite and /// RemoteNodeSession.isFavorite renamed to isPinned via originalName (same column). + /// - v9→v10: Added local Text Rules identities, review entries, + /// and pending radio erase targets. public static func createContainer(inMemory: Bool = false) throws -> ModelContainer { if !inMemory { let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! diff --git a/MC1Services/Sources/MC1Services/Services/ReactionService.swift b/MC1Services/Sources/MC1Services/Services/ReactionService.swift index 8e65bc471d..4b51ddb790 100644 --- a/MC1Services/Sources/MC1Services/Services/ReactionService.swift +++ b/MC1Services/Sources/MC1Services/Services/ReactionService.swift @@ -20,6 +20,7 @@ public struct PendingDMReaction: Sendable { public let rawText: String public let radioID: UUID public let receivedAt: Date + public let directMessage: (scope: ReceiveScope, contact: ContactDTO)? } /// Result of persisting a reaction @@ -195,7 +196,8 @@ public actor ReactionService { /// Logs errors instead of silently discarding them. public func persistReactionAndUpdateSummary( _ reaction: ReactionDTO, - using dataStore: any PersistenceStoreProtocol + using dataStore: any PersistenceStoreProtocol, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? = nil ) async -> ReactionPersistResult? { #if DEBUG if let hold = reactionAdmitHoldForTesting { @@ -203,9 +205,12 @@ public actor ReactionService { } #endif do { - guard let admission = try await dataStore.admitReaction(reaction), admission.inserted else { - return nil + let admission: ReactionAdmission? = if let (scope, contact) = directMessage { + try await dataStore.admitDirectMessageReaction(reaction, contact: contact, scope: scope) + } else { + try await dataStore.admitReaction(reaction) } + guard let admission, admission.inserted else { return nil } return ReactionPersistResult(messageID: admission.messageID, summary: admission.summary) } catch { logger.error("Failed to save reaction for message \(reaction.messageID): \(error.localizedDescription)") @@ -256,8 +261,10 @@ public actor ReactionService { contactID: UUID, senderName: String, rawText: String, - radioID: UUID + radioID: UUID, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? = nil ) { + guard directMessage?.scope.isCurrent != false else { return } let key = PendingDMReactionKey(contactID: contactID, messageHash: parsed.messageHash) let pending = PendingDMReaction( parsed: parsed, @@ -265,7 +272,8 @@ public actor ReactionService { senderName: senderName, rawText: rawText, radioID: radioID, - receivedAt: Date() + receivedAt: Date(), + directMessage: directMessage ) if pendingDMReactions[key] != nil { diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift index 1fd312cb00..36c0be5970 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift @@ -295,7 +295,7 @@ public extension RemoteNodeService { ) async -> (shouldContinue: Bool, consecutiveFailures: Int) { var failures = consecutiveFailures do { - try await sendKeepAliveIfDirectRouted(sessionID: sessionID, publicKey: publicKey) + try await sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) KeepAliveRetryPolicy.recordSuccess(consecutiveFailures: &failures) return (shouldContinue: true, consecutiveFailures: failures) } catch { @@ -328,43 +328,6 @@ public extension RemoteNodeService { keepAliveTasks.removeValue(forKey: sessionID) } - /// Send keep-alive only if the session has a direct routing path. - private func sendKeepAliveIfDirectRouted(sessionID: UUID, publicKey: Data) async throws { - // Fetch session to get radioID - guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { - throw RemoteNodeError.sessionNotFound - } - - // Check contact's routing status - guard let contact = try await dataStore.fetchContact(radioID: remoteSession.radioID, publicKey: publicKey) else { - throw RemoteNodeError.contactNotFound - } - - // Keep-alive only works with direct routing - if contact.isFloodRouted { - throw RemoteNodeError.floodRouted - } - - // Log keep-alive - let targetType: CommandAuditLogger.Target = remoteSession.isRoom ? .room : .repeater - await auditLogger.logKeepAlive(target: targetType, publicKey: publicKey) - - // Send keep-alive with sync_since for force-resync hint - do { - _ = try await session.sendKeepAlive(to: publicKey, syncSince: remoteSession.lastSyncTimestamp) - } catch let error as MeshCoreError { - throw RemoteNodeError.sessionError(error) - } - } - - /// Public method to send keep-alive (for manual refresh). - func sendKeepAlive(sessionID: UUID) async throws { - guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { - throw RemoteNodeError.sessionNotFound - } - try await sendKeepAliveIfDirectRouted(sessionID: sessionID, publicKey: remoteSession.publicKey) - } - /// Start keep-alive for a room session (called when room view appears). func startSessionKeepAlive(sessionID: UUID, publicKey: Data) { startKeepAlive(sessionID: sessionID, publicKey: publicKey) diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+RoomKeepAlive.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+RoomKeepAlive.swift new file mode 100644 index 0000000000..ad1d0f2892 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+RoomKeepAlive.swift @@ -0,0 +1,121 @@ +import Foundation +import MeshCore + +extension RemoteNodeService { + func sendScheduledKeepAlive(sessionID: UUID, publicKey: Data) async throws { + try Task.checkCancellation() + guard let room = try await dataStore.fetchRemoteNodeSession(id: sessionID), + room.publicKey == publicKey, + room.isRoom, + radioID == nil || radioID == room.radioID else { + throw RemoteNodeError.sessionNotFound + } + guard let scope = try await dataStore.captureReceiveScope(radioID: room.radioID, link: receiveLifetime) else { + throw CancellationError() + } + + let key = room.textRulesID ?? room.id + let needsRecovery: Bool + if roomKeepAliveSchedules[key]?.recoverySubmitted.withLock({ $0 }) == true { + needsRecovery = false + } else { + let preference = await textRulesPreference() + let rulesAreOn = preference?.effective( + for: .room, + key: .init(radioID: room.radioID, conversationID: key), + override: room.textRulesOverride + ).isOn == true + if rulesAreOn { + needsRecovery = true + } else { + needsRecovery = await (try? dataStore.hasRecentlyBlockedMessages(radioID: room.radioID, conversationID: key)) == true + } + } + + try Task.checkCancellation() + let schedule = keepAliveSchedule(for: room) + if let recovery = schedule.recovery { + try await recovery.value + return + } + if schedule.refresh != nil { return } + let recoverySubmitted = schedule.recoverySubmitted.withLock { $0 } + if recoverySubmitted || !needsRecovery { + try await transmitRoomKeepAlive(room, scope: scope, schedule: schedule, useBookmark: !recoverySubmitted) + return + } + + let recovery = Task { + defer { roomKeepAliveSchedules[key]?.recovery = nil } + try await transmitRoomKeepAlive(room, scope: scope, schedule: schedule, useBookmark: true, markRecovery: true) + } + roomKeepAliveSchedules[key]?.recovery = recovery + try await recovery.value + } + + func refreshRoom(_ room: RemoteNodeSessionDTO) async throws { + guard room.isRoom else { throw RemoteNodeError.invalidResponse } + guard radioID == nil || radioID == room.radioID else { throw RemoteNodeError.notConnected } + guard let scope = try await dataStore.captureReceiveScope(radioID: room.radioID, link: receiveLifetime) else { + throw CancellationError() + } + + let key = room.textRulesID ?? room.id + let schedule = keepAliveSchedule(for: room) + if let refresh = schedule.refresh { + try await refresh.value + return + } + + let refresh = Task { + defer { roomKeepAliveSchedules[key]?.refresh = nil } + // A distinct refresh reads the bookmark after an in-flight automatic rewind. + _ = await schedule.recovery?.result + try await transmitRoomKeepAlive(room, scope: scope, schedule: schedule, useBookmark: true) + } + roomKeepAliveSchedules[key]?.refresh = refresh + try await refresh.value + } + + private func keepAliveSchedule(for room: RemoteNodeSessionDTO) -> RoomKeepAliveSchedule { + let key = room.textRulesID ?? room.id + let schedule = roomKeepAliveSchedules[key] ?? RoomKeepAliveSchedule(sessionID: room.id) + roomKeepAliveSchedules[key] = schedule + return schedule + } + + private func transmitRoomKeepAlive( + _ room: RemoteNodeSessionDTO, + scope: ReceiveScope, + schedule: RoomKeepAliveSchedule, + useBookmark: Bool, + markRecovery: Bool = false + ) async throws { + await auditLogger.logKeepAlive(target: .room, publicKey: room.publicKey) + do { + _ = try await session.sendKeepAlive(to: room.publicKey, syncSince: { [dataStore] in + guard scope.isCurrent, schedule.lifetime.isCurrent else { throw CancellationError() } + guard let contact = try await dataStore.fetchContact(radioID: room.radioID, publicKey: room.publicKey) else { + throw RemoteNodeError.contactNotFound + } + guard !contact.isFloodRouted else { throw RemoteNodeError.floodRouted } + guard let current = try await dataStore.fetchRemoteNodeSession(id: room.id), + current.radioID == room.radioID, + current.textRulesID == room.textRulesID else { + throw RemoteNodeError.sessionNotFound + } + return useBookmark ? current.lastSyncTimestamp : 0 + }, beforeSend: { + guard scope.isCurrent, schedule.lifetime.isCurrent else { throw CancellationError() } + if markRecovery { + schedule.recoverySubmitted.withLock { $0 = true } + } + }) + } catch let error as MeshCoreError { + if markRecovery, error.deviceErrorCode == .tableFull { + schedule.recoverySubmitted.withLock { $0 = false } + } + throw RemoteNodeError.sessionError(error) + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift index f81a1ece55..ba4525882f 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift @@ -20,6 +20,9 @@ public actor RemoteNodeService { let dataStore: any PersistenceStoreProtocol let keychainService: KeychainService let contactRadioOwner: ContactRadioOwner + let textRulesPreference: @Sendable () async -> TextRulesPreference? + let receiveLifetime: ReceiveScope.Lifetime + let radioID: UUID? let logger = PersistentLogger(subsystem: "com.mc1", category: "RemoteNode") let auditLogger = CommandAuditLogger() @@ -75,6 +78,17 @@ public actor RemoteNodeService { /// Keep-alive timer tasks var keepAliveTasks: [UUID: Task] = [:] + /// Recovery and refresh outlive timer restarts on this Link record. + struct RoomKeepAliveSchedule { + let sessionID: UUID + let lifetime = ReceiveScope.Lifetime() + let recoverySubmitted = OSAllocatedUnfairLock(initialState: false) + var recovery: Task? + var refresh: Task? + } + + var roomKeepAliveSchedules: [UUID: RoomKeepAliveSchedule] = [:] + /// Keep-alive intervals per session (from login response, in seconds) /// Default to 90 seconds if not specified var keepAliveIntervals: [UUID: Duration] = [:] @@ -128,12 +142,18 @@ public actor RemoteNodeService { session: any RemoteAccessSessionOps & SessionEventStreaming & ContactSessionOps, dataStore: any PersistenceStoreProtocol, keychainService: KeychainService, - contactRadioOwner: ContactRadioOwner = ContactRadioOwner() + contactRadioOwner: ContactRadioOwner = ContactRadioOwner(), + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil }, + receiveLifetime: ReceiveScope.Lifetime = .init(), + radioID: UUID? = nil ) { self.session = session self.dataStore = dataStore self.keychainService = keychainService self.contactRadioOwner = contactRadioOwner + self.textRulesPreference = textRulesPreference + self.receiveLifetime = receiveLifetime + self.radioID = radioID } deinit { @@ -314,6 +334,12 @@ public actor RemoteNodeService { stopKeepAlive(sessionID: id) try await keychainService.deletePassword(forNodeKey: publicKey) try await dataStore.deleteRemoteNodeSession(id: id) + for (key, schedule) in roomKeepAliveSchedules where schedule.sessionID == id { + schedule.lifetime.retire() + schedule.recovery?.cancel() + schedule.refresh?.cancel() + roomKeepAliveSchedules.removeValue(forKey: key) + } } /// Check if a password is stored for a contact's public key. diff --git a/MC1Services/Sources/MC1Services/Services/RoomServerService.swift b/MC1Services/Sources/MC1Services/Services/RoomServerService.swift index 2e4a9fbd1a..e17d965087 100644 --- a/MC1Services/Sources/MC1Services/Services/RoomServerService.swift +++ b/MC1Services/Sources/MC1Services/Services/RoomServerService.swift @@ -35,8 +35,10 @@ public actor RoomServerService { private let session: any RemoteAccessSessionOps private let remoteNodeService: RemoteNodeService - private let dataStore: any PersistenceStoreProtocol + private let dataStore: PersistenceStore + private let textRulesPreference: @Sendable () async -> TextRulesPreference? private let radioID: UUID + private let receiveLifetime: ReceiveScope.Lifetime private let logger = PersistentLogger(subsystem: "com.mc1", category: "RoomServer") private let auditLogger = CommandAuditLogger() @@ -58,15 +60,19 @@ public actor RoomServerService { init( session: any RemoteAccessSessionOps, remoteNodeService: RemoteNodeService, - dataStore: any PersistenceStoreProtocol, + dataStore: PersistenceStore, radioID: UUID, - config: MessageServiceConfig = MessageServiceConfig() + config: MessageServiceConfig = MessageServiceConfig(), + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil }, + receiveLifetime: ReceiveScope.Lifetime = .init() ) { self.session = session self.remoteNodeService = remoteNodeService self.dataStore = dataStore self.radioID = radioID self.config = config + self.textRulesPreference = textRulesPreference + self.receiveLifetime = receiveLifetime } /// Set self public key prefix from SelfInfo. @@ -182,6 +188,12 @@ public actor RoomServerService { try await remoteNodeService.removeSession(id: sessionID, publicKey: publicKey) } + /// Requests a fresh replay from this room's saved bookmark. + public func refreshMessages(for room: RemoteNodeSessionDTO) async throws { + guard room.radioID == radioID else { throw RoomServerError.notConnected } + try await remoteNodeService.refreshRoom(room) + } + // MARK: - Message Posting /// Post a message to a room server. @@ -414,69 +426,53 @@ public actor RoomServerService { authorPrefix: Data, text: String ) async throws -> RoomMessageDTO? { - guard let remoteSession = try await dataStore.fetchRemoteNodeSessions(radioID: radioID) - .first(where: { $0.publicKey.prefix(6) == senderPublicKeyPrefix && $0.isRoom }) else { + guard let scope = try await dataStore.captureReceiveScope(radioID: radioID, link: receiveLifetime) else { return nil } + return try await handleIncomingMessage( + senderPublicKeyPrefix: senderPublicKeyPrefix, + timestamp: timestamp, + authorPrefix: authorPrefix, + text: text, + scope: scope + )?.message + } - // Receiving any message (even duplicate) proves session is active - if !remoteSession.isConnected { - let recovered = await (try? dataStore.markRoomSessionConnected(remoteSession.id)) ?? false - if recovered { - eventBroadcaster.yield(.connectionRecovered(sessionID: remoteSession.id)) - } + func handleIncomingMessage( + senderPublicKeyPrefix: Data, + timestamp: UInt32, + authorPrefix: Data, + text: String, + scope: ReceiveScope + ) async throws -> (message: RoomMessageDTO, room: RemoteNodeSessionDTO)? { + let arrivedAt = Date() + let preference = await textRulesPreference() + guard scope.isCurrent, scope.radioID == radioID, + let room = try await dataStore.fetchRemoteNodeSessions(radioID: radioID) + .first(where: { $0.publicKey.prefix(6) == senderPublicKeyPrefix && $0.isRoom }) else { + return nil } - // Generate deduplication key - let dedupKey = RoomMessage.generateDeduplicationKey( - timestamp: timestamp, + let post = RoomMessageDTO( + sessionID: room.id, authorKeyPrefix: authorPrefix, - text: text + text: text, + timestamp: timestamp, + createdAt: arrivedAt, + isFromSelf: selfPublicKeyPrefix == authorPrefix ) - - // Check for duplicate using deduplication key - if try await dataStore.isDuplicateRoomMessage( - sessionID: remoteSession.id, - deduplicationKey: dedupKey - ) { - return nil + let result = try await dataStore.receiveRoomPost(post, in: room, scope: scope, preference: preference) + guard scope.isCurrent else { return nil } + if result.recovered { + eventBroadcaster.yield(.connectionRecovered(sessionID: room.id)) } - - // Log room message received (metadata only, no content) + guard let message = result.message else { return nil } await auditLogger.logRoomMessageReceived( roomPublicKey: senderPublicKeyPrefix, authorPrefix: authorPrefix, messageLength: text.count ) - - // Defensive check: room servers shouldn't push our own messages back - let isFromSelf = selfPublicKeyPrefix?.prefix(4) == authorPrefix.prefix(4) - if isFromSelf { - logger.info("Received self message from room server (unexpected)") - } - - let authorName = try await resolveAuthorName(keyPrefix: authorPrefix) - - let messageDTO = RoomMessageDTO( - sessionID: remoteSession.id, - authorKeyPrefix: authorPrefix, - authorName: authorName, - text: text, - timestamp: timestamp, - isFromSelf: isFromSelf - ) - - try await dataStore.saveRoomMessage(messageDTO) - - // Update sync bookmark and sort date - try await dataStore.updateRoomActivity(remoteSession.id, syncTimestamp: timestamp) - - // Increment unread count if not from self - if !isFromSelf { - try await dataStore.incrementRoomUnreadCount(remoteSession.id) - } - - return messageDTO + return (message, room) } // MARK: - Message Retrieval @@ -521,12 +517,6 @@ public actor RoomServerService { // MARK: - Private Helpers - private func resolveAuthorName(keyPrefix: Data) async throws -> String? { - // Try to find contact with matching public key prefix - // Returns nil if no matching contact found - try await dataStore.findContactNameByKeyPrefix(keyPrefix) - } - /// Attempt to sync history, using advert path first, then falling back to path discovery. private func syncHistoryIfPossible(sessionID: UUID) async { do { diff --git a/MC1Services/Sources/MC1Services/Services/RxLogService.swift b/MC1Services/Sources/MC1Services/Services/RxLogService.swift index ab0cb1f6e7..d02f66bd53 100644 --- a/MC1Services/Sources/MC1Services/Services/RxLogService.swift +++ b/MC1Services/Sources/MC1Services/Services/RxLogService.swift @@ -95,10 +95,12 @@ public actor RxLogService { // Build known-regions cache (and channel/contact secrets). await loadSecretsFromDatabase(radioID: radioID, generation: generation) + guard !Task.isCancelled else { return } // Subscribe before reprocess. EventDispatcher only buffers for existing // subscribers; awaiting full reprocess here would drop live RX. let events = await session.events(filter: .rxLogData) + guard !Task.isCancelled else { return } // Sibling reprocess so the for-await loop drains while store work runs. await self.launchRegionReprocessTask() @@ -153,11 +155,15 @@ public actor RxLogService { } /// Stop monitoring events. - public func stopEventMonitoring() { - eventMonitorTask?.cancel() + public func stopEventMonitoring() async { + let monitor = eventMonitorTask + let reprocess = regionReprocessTask eventMonitorTask = nil - regionReprocessTask?.cancel() regionReprocessTask = nil + monitor?.cancel() + reprocess?.cancel() + await monitor?.value + await reprocess?.value } /// Returns a fresh multicast stream of newly persisted entries. @@ -271,8 +277,7 @@ public actor RxLogService { isReprocessingDMs = true defer { isReprocessingDMs = false } - guard let radioID, let myPrivateKey else { return } - guard !contactPublicKeysByPrefix.isEmpty else { return } + guard let radioID, let myPrivateKey, !contactPublicKeysByPrefix.isEmpty else { return } let cutoff = Date().addingTimeInterval(-60) diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift index 6d6672a9a1..a938b40632 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift @@ -31,6 +31,7 @@ extension SyncCoordinator { do { if let channelIndex { + let rxEntry: RxLogEntryDTO? if let channelDeduplicationKey { let raw = try await dependencies.dataStore.fetchRxLogEntries( radioID: radioID, @@ -38,22 +39,22 @@ extension SyncCoordinator { senderTimestamp: senderTimestamp ) let decoded = await dependencies.rxLogService.decodedEntries(raw) - if let rxEntry = ChannelRXCorrelation.matching( - decoded, - deduplicationKey: channelDeduplicationKey - ).first { - let pathLength = rxEntry.pathLength - let pathNodes = rxEntry.pathNodes - logger.info("Correlated channel message to RxLogEntry: pathLength=\(pathLength), pathNodes=\(pathNodes.count) bytes") - return RxLogLookupResult( - pathNodes: pathNodes, - pathLength: pathLength, - packetHash: rxEntry.packetHash, - routeType: rxEntry.routeType, - regionScope: rxEntry.regionScope, - regionScopeMatches: rxEntry.regionScopeMatches - ) - } + rxEntry = ChannelRXCorrelation.matching(decoded, deduplicationKey: channelDeduplicationKey).first + } else { + rxEntry = nil + } + if let rxEntry { + let pathLength = rxEntry.pathLength + let pathNodes = rxEntry.pathNodes + logger.info("Correlated channel message to RxLogEntry: pathLength=\(pathLength), pathNodes=\(pathNodes.count) bytes") + return RxLogLookupResult( + pathNodes: pathNodes, + pathLength: pathLength, + packetHash: rxEntry.packetHash, + routeType: rxEntry.routeType, + regionScope: rxEntry.regionScope, + regionScopeMatches: rxEntry.regionScopeMatches + ) } logger.warning("No RxLogEntry found for channel \(channelIndex), senderTimestamp: \(senderTimestamp)") } else if let rxEntry = try await dependencies.dataStore.findRxLogEntry( @@ -114,34 +115,28 @@ extension SyncCoordinator { ) } - /// Increments unread counts and posts a notification for a direct message. + /// Updates the current Contact before publishing ordinary DM effects. func updateDMUnreadsAndNotify( messageDTO: MessageDTO, - contactID: UUID, - contact: ContactDTO?, - messageText: String, - hasSelfMention: Bool, - dependencies: SyncDependencies + contact: ContactDTO, + dependencies: SyncDependencies, + scope: ReceiveScope ) async throws { // A mounted conversation does not mean its messages are visible in the background. let isInForeground = await dependencies.appStateProvider?.isInForeground ?? true let activeContactID = await dependencies.notificationService.activeContactID - let isViewingContact = isInForeground && activeContactID == contactID - if !isViewingContact { - try await dependencies.dataStore.incrementUnreadCount(contactID: contactID) - - // Increment unread mention count if message contains self-mention - if hasSelfMention { - try await dependencies.dataStore.incrementUnreadMentionCount(contactID: contactID) - } - } + let isViewingContact = isInForeground && activeContactID == contact.id + guard let current = try await dependencies.dataStore.updateContactAfterDirectMessage( + messageDTO, contact: contact, scope: scope, isViewingContact: isViewingContact + ), !current.isBlocked, scope.isCurrent else { return } await dependencies.notificationService.postDirectMessageNotification( - from: contact?.displayName ?? "Unknown", - contactID: contactID, - messageText: messageText, + from: current.displayName, + contactID: current.id, + messageText: messageDTO.text, messageID: messageDTO.id, - isMuted: contact?.isMuted ?? false + isMuted: current.isMuted, + scope: scope ) await dependencies.notificationService.updateBadgeCount() } @@ -156,8 +151,10 @@ extension SyncCoordinator { timestamp: UInt32, hasSelfMention: Bool, radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + legacyScope: ReceiveScope? = nil ) async throws { + guard legacyScope?.isCurrent != false else { return } if let channelID = channel?.id { // A mounted conversation does not mean its messages are visible in the background. let isInForeground = await dependencies.appStateProvider?.isInForeground ?? true @@ -165,14 +162,16 @@ extension SyncCoordinator { let activeRadioID = await dependencies.notificationService.activeChannelRadioID let isViewingChannel = isInForeground && activeIndex == channel?.index && activeRadioID == channel?.radioID if !isViewingChannel { + guard legacyScope?.isCurrent != false else { return } try await dependencies.dataStore.incrementChannelUnreadCount(channelID: channelID) // Increment unread mention count if message contains self-mention - if hasSelfMention { + if hasSelfMention, legacyScope?.isCurrent != false { try await dependencies.dataStore.incrementChannelUnreadMentionCount(channelID: channelID) } } } + guard legacyScope?.isCurrent != false else { return } if Self.shouldPostChannelNotification(forResolvedChannel: channel) { await dependencies.notificationService.postChannelMessageNotification( channelName: channel?.name ?? "Channel \(channelIndex)", @@ -182,19 +181,24 @@ extension SyncCoordinator { messageText: messageText, messageID: messageDTO.id, notificationLevel: channel?.notificationLevel ?? .all, - hasSelfMention: hasSelfMention + hasSelfMention: hasSelfMention, + legacyScope: legacyScope ) - } else { + } else if channel == nil { recordUnresolvedChannel( channelIndex: channelIndex, radioID: radioID, senderTimestamp: timestamp ) } + guard legacyScope?.isCurrent != false else { return } await dependencies.notificationService.updateBadgeCount() // Broadcast for real-time chat updates - dataEventBroadcaster.yield(.channelMessageReceived(message: messageDTO, channelIndex: channelIndex)) + guard legacyScope?.isCurrent != false else { return } + dataEventBroadcaster.yield(.channelMessageReceived( + message: messageDTO, channelIndex: channelIndex, legacyScope: legacyScope + )) } private func recordUnresolvedChannel( diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index 6076b606f2..3ab2ef9041 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -28,10 +28,10 @@ extension SyncCoordinator { // MARK: - Contact Message Handler private func wireContactMessageHandler(dependencies: SyncDependencies, radioID: UUID, selfNodeName: String) async { - await dependencies.messagePollingService.setContactMessageHandler { [weak self] message, contact, context in - guard let self else { return } + await dependencies.messagePollingService.setContactMessageHandler { [weak self] message, contact, context, scope, preference in + guard let self, scope.radioID == radioID, scope.isCurrent else { return } await handleIncomingMessage( - kind: .direct(message, contact: contact), + kind: .direct(message, contact: contact, scope: scope, preference: preference), context: context, dependencies: dependencies, radioID: radioID, @@ -43,14 +43,16 @@ extension SyncCoordinator { // MARK: - Channel Message Handler private func wireChannelMessageHandler(dependencies: SyncDependencies, radioID: UUID, selfNodeName: String) async { - await dependencies.messagePollingService.setChannelMessageHandler { [weak self] message, channel, context in + await dependencies.messagePollingService.setChannelMessageHandler { [weak self] message, channel, context, preference, arrivedAt, legacyScope in guard let self else { return } await handleIncomingMessage( - kind: .channel(message, channel: channel), + kind: .channel(message, channel: channel, preference: preference), + receivedAt: arrivedAt, context: context, dependencies: dependencies, radioID: radioID, - selfNodeName: selfNodeName + selfNodeName: selfNodeName, + legacyScope: legacyScope ) } } @@ -60,8 +62,8 @@ extension SyncCoordinator { /// Discriminates the two text-message ingestion paths, carrying the wire /// message and the resolved conversation for each. private enum IncomingMessageKind { - case direct(ContactMessage, contact: ContactDTO?) - case channel(ChannelMessage, channel: ChannelDTO?) + case direct(ContactMessage, contact: ContactDTO?, scope: ReceiveScope, preference: TextRulesPreference?) + case channel(ChannelMessage, channel: ChannelDTO?, preference: TextRulesPreference?) /// Log noun distinguishing the two paths in shared diagnostics. var logLabel: String { @@ -77,21 +79,19 @@ extension SyncCoordinator { /// without posting a second alert. private func resolveDirectContactIfNeeded( _ kind: IncomingMessageKind, - dependencies: SyncDependencies, - radioID: UUID + dependencies: SyncDependencies ) async -> IncomingMessageKind { - guard case let .direct(message, contact) = kind, contact == nil else { + guard case let .direct(message, contact, scope, preference) = kind, contact == nil else { return kind } let prefix = message.senderPublicKeyPrefix - guard !prefix.isEmpty else { return kind } - - guard let materialized = await dependencies.advertisementService - .materializeContactForPendingAdvert(matchingPrefix: prefix, radioID: radioID) + guard !prefix.isEmpty, + let materialized = await dependencies.advertisementService + .materializeContactForPendingAdvert(matchingPrefix: prefix, scope: scope) else { return kind } - return .direct(message, contact: materialized) + return .direct(message, contact: materialized, scope: scope, preference: preference) } /// Re-decrypts stamp-matched 0x88 rows and harvests extras, then refetches @@ -99,7 +99,8 @@ extension SyncCoordinator { private func harvestAndRefreshChannelMessage( messageDTO: MessageDTO, radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + legacyScope: ReceiveScope? ) async throws -> MessageDTO { guard let channelIndex = messageDTO.channelIndex else { return messageDTO } let stamp = messageDTO.senderTimestamp ?? messageDTO.timestamp @@ -110,6 +111,7 @@ extension SyncCoordinator { senderTimestamp: stamp ) let decoded = await dependencies.rxLogService.decodedEntries(raw) + guard legacyScope?.isCurrent != false else { return messageDTO } await dependencies.heardRepeatsService.harvestIncomingPaths( for: messageDTO, decodedCandidates: decoded @@ -132,7 +134,8 @@ extension SyncCoordinator { rxResult: RxLogLookupResult, snr: Double?, receiveTime: Date, - dependencies: SyncDependencies + dependencies: SyncDependencies, + legacyScope: ReceiveScope? ) async -> Bool { do { guard let existing = try await dependencies.dataStore.fetchMessage( @@ -141,6 +144,7 @@ extension SyncCoordinator { ) else { return false } + guard legacyScope?.isCurrent != false else { return true } if case .channel = resolvedKind { guard let path = rxResult.pathNodes else { logger.info("Skipping duplicate \(resolvedKind.logLabel) message") @@ -169,16 +173,19 @@ extension SyncCoordinator { /// short-circuit, persistence, unread/notification updates, and UI refresh. private func handleIncomingMessage( kind: IncomingMessageKind, + receivedAt: Date = .now, context: DeliveryContext, dependencies: SyncDependencies, radioID: UUID, - selfNodeName: String + selfNodeName: String, + legacyScope: ReceiveScope? = nil ) async { + guard legacyScope?.isCurrent != false else { return } // A DM can land in the advert delta-sync debounce window before the local // Contact row exists. Materialize from a pending 0x80 key so unread, // notification, and Chats-list updates use the live path exactly once. let resolvedKind = await resolveDirectContactIfNeeded( - kind, dependencies: dependencies, radioID: radioID + kind, dependencies: dependencies ) // Per-kind wire fields. Channel messages embed the sender as a @@ -193,7 +200,7 @@ extension SyncCoordinator { let channelIndex: UInt8? let senderKeyPrefix: Data? switch resolvedKind { - case let .direct(message, contact): + case let .direct(message, contact, _, _): // The firmware cannot surface a self-DM here: decrypt runs against a // contact's ECDH shared secret and the local self_id is never in // contacts[], so an echo of the user's own DM never reaches this arm. @@ -206,7 +213,7 @@ extension SyncCoordinator { contactID = contact?.id channelIndex = nil senderKeyPrefix = message.senderPublicKeyPrefix - case let .channel(message, _): + case let .channel(message, _, _): // Parse "NodeName: text" format for sender name (senderNodeName, text) = Self.parseChannelMessage(message.text) senderTimestampDate = message.senderTimestamp @@ -221,7 +228,7 @@ extension SyncCoordinator { let timestamp = UInt32(senderTimestampDate.timeIntervalSince1970) // Correct invalid timestamps (sender clock wrong) - let receiveTime = Date() + let receiveTime = receivedAt let (finalTimestamp, timestampCorrected) = Self.correctTimestampIfNeeded(timestamp, receiveTime: receiveTime) if timestampCorrected { logger.debug("Corrected invalid \(resolvedKind.logLabel) message timestamp from \(Date(timeIntervalSince1970: TimeInterval(timestamp))) to \(receiveTime)") @@ -309,52 +316,39 @@ extension SyncCoordinator { regionScopeMatches: rxResult.regionScopeMatches ) - if await recordArrivalAndSkipDuplicate( - resolvedKind: resolvedKind, - deduplicationKey: deduplicationKey, - radioID: radioID, - rxResult: rxResult, - snr: snr, - receiveTime: receiveTime, - dependencies: dependencies - ) { - return - } - - // Stamp before the reaction early return so bodies and reactions both count. - if case let .direct(_, contact) = resolvedKind, let contact { - do { - _ = try await dependencies.dataStore.touchContactHeard( - radioID: radioID, - publicKey: contact.publicKey, - at: Date() - ) - } catch { - logger.error( - "lastHeard stamp failed for inbound DM: \(error.localizedDescription)" - ) - } - } - switch resolvedKind { - case let .direct(_, contact): - // Check if this is a DM reaction - if let contact, - await handleDMReaction( - text: text, - contact: contact, - radioID: radioID, - dependencies: dependencies - ) { + case let .direct(_, contact, scope, preference): + await receiveDirectMessage( + messageDTO, wireTextType: textTypeRaw, contact: contact, + scope: scope, preference: preference, dependencies: dependencies + ) + + case let .channel(message, channel, preference): + if await recordArrivalAndSkipDuplicate( + resolvedKind: resolvedKind, + deduplicationKey: deduplicationKey, + radioID: radioID, + rxResult: rxResult, + snr: snr, + receiveTime: receiveTime, + dependencies: dependencies, + legacyScope: legacyScope + ) { return } - case let .channel(message, _): - // Discard messages from blocked senders + guard legacyScope?.isCurrent != false else { return } if isBlockedSender(senderNodeName) { return } - - // Check if this is a reaction + do { + if let channel, try await dependencies.dataStore.shouldSuppressChannelMessage( + messageDTO, frame: message, channel: channel, scope: legacyScope, preference: preference + ) { return } + } catch { + logger.error("Failed to evaluate channel Text Rules: \(error)") + return + } + guard legacyScope?.isCurrent != false else { return } if await handleChannelReaction( text: text, channelIndex: message.channelIndex, @@ -366,31 +360,17 @@ extension SyncCoordinator { ) { return } - } - - do { - try await dependencies.dataStore.saveMessage(messageDTO) - var savedDTO = messageDTO - if case .channel = resolvedKind { - savedDTO = try await harvestAndRefreshChannelMessage( + do { + guard try await dependencies.dataStore.saveLegacyChannelMessage( + messageDTO, scope: legacyScope, conversationID: channel?.textRulesID + ), + legacyScope?.isCurrent != false else { return } + let savedDTO = try await harvestAndRefreshChannelMessage( messageDTO: messageDTO, radioID: radioID, - dependencies: dependencies - ) - } - - switch resolvedKind { - case let .direct(_, contact): - try await indexAndNotifyDirectMessage( - messageDTO: savedDTO, - contact: contact, - messageText: text, - timestamp: timestamp, - hasSelfMention: hasSelfMention, dependencies: dependencies, - radioID: radioID + legacyScope: legacyScope ) - case let .channel(message, channel): try await indexAndNotifyChannelMessage( messageDTO: savedDTO, channel: channel, @@ -400,24 +380,73 @@ extension SyncCoordinator { timestamp: timestamp, hasSelfMention: hasSelfMention, dependencies: dependencies, - radioID: radioID + radioID: radioID, + legacyScope: legacyScope ) + await notifyConversationsChanged(scope: legacyScope) + } catch { + logger.error("Failed to save channel message: \(error)") } + } + } - // Notify conversation list of changes - await notifyConversationsChanged() - - // Broadcast for real-time chat updates - if case let .direct(_, contact) = resolvedKind, let contact { - dataEventBroadcaster.yield(.directMessageReceived(message: savedDTO, contact: contact)) + private func receiveDirectMessage( + _ message: MessageDTO, + wireTextType: UInt8, + contact: ContactDTO?, + scope: ReceiveScope, + preference: TextRulesPreference?, + dependencies: SyncDependencies + ) async { + do { + let admission = try await dependencies.dataStore.admitDirectMessage( + message, wireTextType: wireTextType, contact: contact, scope: scope, preference: preference + ) + guard scope.isCurrent else { return } + switch admission { + case .discarded: + return + case let .replay(saved): + logger.debug("Skipping replay of direct message \(saved.id)") + case let .reaction(contact): + await stampDirectMessageContact(contact, message: message, scope: scope, dependencies: dependencies) + _ = await handleDMReaction( + text: message.text, + contact: contact, + radioID: message.radioID, + dependencies: dependencies, + scope: scope + ) + case let .saved(contact): + if let contact { + await stampDirectMessageContact(contact, message: message, scope: scope, dependencies: dependencies) + try await indexAndNotifyDirectMessage( + messageDTO: message, + contact: contact, + dependencies: dependencies, + scope: scope + ) + guard await (try? dependencies.dataStore.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { return } + dataEventBroadcaster.yield(.directMessageReceived(message: message, contact: contact, scope: scope)) + } + await notifyConversationsChanged(scope: scope) } } catch { - switch resolvedKind { - case .direct: - logger.error("Failed to save contact message: \(error)") - case .channel: - logger.error("Failed to save channel message: \(error)") - } + logger.error("Failed to process incoming direct message: \(error)") + } + } + + private func stampDirectMessageContact( + _ contact: ContactDTO, + message: MessageDTO, + scope: ReceiveScope, + dependencies: SyncDependencies + ) async { + do { + try await dependencies.dataStore.touchDirectMessageContact(contact, scope: scope, at: message.createdAt) + } catch { + logger.error("lastHeard stamp failed for inbound DM: \(error.localizedDescription)") } } @@ -425,55 +454,39 @@ extension SyncCoordinator { /// bookkeeping, and unread/notification updates. private func indexAndNotifyDirectMessage( messageDTO: MessageDTO, - contact: ContactDTO?, - messageText: String, - timestamp: UInt32, - hasSelfMention: Bool, + contact: ContactDTO, dependencies: SyncDependencies, - radioID: UUID + scope: ReceiveScope ) async throws { - // Index DM message for reaction targeting - if let contact { - let pendingMatches = await dependencies.reactionService.indexDMMessage( - id: messageDTO.id, + let pendingMatches = await dependencies.reactionService.indexDMMessage( + id: messageDTO.id, + contactID: contact.id, + text: messageDTO.text, + timestamp: messageDTO.reactionTimestamp + ) + for pending in pendingMatches { + let reactionDTO = ReactionDTO( + messageID: messageDTO.id, + emoji: pending.parsed.emoji, + senderName: pending.senderName, + messageHash: pending.parsed.messageHash, + rawText: pending.rawText, contactID: contact.id, - text: messageText, - timestamp: timestamp + radioID: scope.radioID ) - - // Process pending reactions that now have their target - for pending in pendingMatches { - let reactionDTO = ReactionDTO( - messageID: messageDTO.id, - emoji: pending.parsed.emoji, - senderName: pending.senderName, - messageHash: pending.parsed.messageHash, - rawText: pending.rawText, - contactID: contact.id, - radioID: radioID - ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { - logger.debug("Processed pending DM reaction \(pending.parsed.emoji)") - } - } - } - - // Update contact's last message date - if let contactID = contact?.id { - try await dependencies.dataStore.updateContactLastMessage(contactID: contactID, date: Date()) - } - - // Only increment unread count, post notification, and update badge for non-blocked contacts - if let contactID = contact?.id, contact?.isBlocked != true { - try await updateDMUnreadsAndNotify( - messageDTO: messageDTO, - contactID: contactID, - contact: contact, - messageText: messageText, - hasSelfMention: hasSelfMention, - dependencies: dependencies + await persistReactionIfNew( + reactionDTO, + dependencies: dependencies, + directMessage: pending.directMessage ?? (scope, contact) ) } + + try await updateDMUnreadsAndNotify( + messageDTO: messageDTO, + contact: contact, + dependencies: dependencies, + scope: scope + ) } /// Post-save side effects for a channel message: reaction indexing, channel @@ -487,8 +500,10 @@ extension SyncCoordinator { timestamp: UInt32, hasSelfMention: Bool, dependencies: SyncDependencies, - radioID: UUID + radioID: UUID, + legacyScope: ReceiveScope? = nil ) async throws { + guard legacyScope?.isCurrent != false else { return } // Index message for reaction matching and process any pending reactions // Use original timestamp for indexing so pending reactions can match if let senderName = senderNodeName { @@ -502,6 +517,7 @@ extension SyncCoordinator { // Process any pending reactions that now have their target for pending in pendingMatches { + guard legacyScope?.isCurrent != false else { return } let reactionDTO = ReactionDTO( messageID: messageDTO.id, emoji: pending.parsed.emoji, @@ -515,6 +531,7 @@ extension SyncCoordinator { } } + guard legacyScope?.isCurrent != false else { return } // Update channel's last message date if let channelID = channel?.id { try await dependencies.dataStore.updateChannelLastMessage(channelID: channelID, date: Date()) @@ -531,7 +548,8 @@ extension SyncCoordinator { timestamp: timestamp, hasSelfMention: hasSelfMention, radioID: radioID, - dependencies: dependencies + dependencies: dependencies, + legacyScope: legacyScope ) } } @@ -539,50 +557,50 @@ extension SyncCoordinator { // MARK: - Signed Message Handler private func wireSignedMessageHandler(dependencies: SyncDependencies) async { - await dependencies.messagePollingService.setSignedMessageHandler { [weak self] message, _ in + await dependencies.messagePollingService.setSignedMessageHandler { [weak self] message, scope in guard let self else { return } - await handleIncomingSignedMessage(message, dependencies: dependencies) + await handleIncomingSignedMessage(message, scope: scope, dependencies: dependencies) } } - /// Persists a signed room message via `RoomServerService`, then posts the - /// notification and refreshes the UI when the message was new. - private func handleIncomingSignedMessage(_ message: ContactMessage, dependencies: SyncDependencies) async { - // For signed room messages, the signature contains the 4-byte author key prefix + private func handleIncomingSignedMessage( + _ message: ContactMessage, + scope: ReceiveScope, + dependencies: SyncDependencies + ) async { + // For signed room messages, the signature contains the 4-byte author key prefix. guard let authorPrefix = message.signature?.prefix(4), authorPrefix.count == 4 else { logger.warning("Dropping signed message: missing or invalid author prefix") return } let timestamp = UInt32(message.senderTimestamp.timeIntervalSince1970) - do { - let savedMessage = try await dependencies.roomServerService.handleIncomingMessage( - senderPublicKeyPrefix: message.senderPublicKeyPrefix, - timestamp: timestamp, - authorPrefix: Data(authorPrefix), - text: message.text + guard let saved = try await dependencies.roomServerService.handleIncomingMessage( + senderPublicKeyPrefix: message.senderPublicKeyPrefix, + timestamp: timestamp, + authorPrefix: Data(authorPrefix), + text: message.text, + scope: scope + ), let room = try await dependencies.dataStore.fetchRemoteNodeSession(id: saved.room.id), + room.radioID == saved.room.radioID, + room.textRulesID == saved.room.textRulesID, + scope.isCurrent else { return } + + await dependencies.notificationService.postRoomMessageNotification( + roomName: room.name, + sessionID: saved.message.sessionID, + senderName: saved.message.authorName, + messageText: saved.message.text, + messageID: saved.message.id, + notificationLevel: room.notificationLevel, + scope: scope ) - - // If message was saved (not a duplicate), notify UI and post notification - if let savedMessage { - // Fetch session for room name and mute status - let session = try? await dependencies.dataStore.fetchRemoteNodeSession(id: savedMessage.sessionID) - - // Post notification for room message - await dependencies.notificationService.postRoomMessageNotification( - roomName: session?.name ?? "Room", - sessionID: savedMessage.sessionID, - senderName: savedMessage.authorName, - messageText: savedMessage.text, - messageID: savedMessage.id, - notificationLevel: session?.notificationLevel ?? .all - ) - await dependencies.notificationService.updateBadgeCount() - - await notifyConversationsChanged() - dataEventBroadcaster.yield(.roomMessageReceived(savedMessage)) - } + guard scope.isCurrent else { return } + await dependencies.notificationService.updateBadgeCount() + await notifyConversationsChanged(scope: scope) + guard scope.isCurrent else { return } + dataEventBroadcaster.yield(.roomMessageReceived(saved.message, roomID: room.textRulesID, scope: scope)) } catch { logger.error("Failed to handle room message: \(error)") } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift index 2682f749cb..5d4a292817 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift @@ -13,7 +13,8 @@ extension SyncCoordinator { @discardableResult func persistReactionIfNew( _ reactionDTO: ReactionDTO, - dependencies: SyncDependencies + dependencies: SyncDependencies, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? = nil ) async -> Bool { let exists = try? await dependencies.dataStore.reactionExists( messageID: reactionDTO.messageID, @@ -25,9 +26,17 @@ extension SyncCoordinator { if let result = await dependencies.reactionService.persistReactionAndUpdateSummary( reactionDTO, - using: dependencies.dataStore + using: dependencies.dataStore, + directMessage: directMessage ) { - dataEventBroadcaster.yield(.reactionReceived(messageID: result.messageID, summary: result.summary)) + if let (scope, contact) = directMessage { + guard await (try? dependencies.dataStore.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { return false } + } + dataEventBroadcaster.yield(.reactionReceived( + messageID: result.messageID, summary: result.summary, + scope: directMessage?.scope, contact: directMessage?.contact + )) } return true @@ -40,8 +49,12 @@ extension SyncCoordinator { text: String, contact: ContactDTO, radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + scope: ReceiveScope? = nil ) async -> Bool { + guard scope?.isCurrent != false else { return true } + let directMessage = scope.map { (scope: $0, contact: contact) } + // Try meshcore-open v3 format if let mcoReaction = MeshCoreOpenReactionParser.parse(text) { return await handleMCODMReaction( @@ -49,7 +62,8 @@ extension SyncCoordinator { rawText: text, contact: contact, radioID: radioID, - dependencies: dependencies + dependencies: dependencies, + directMessage: directMessage ) } @@ -60,7 +74,8 @@ extension SyncCoordinator { rawText: text, contact: contact, radioID: radioID, - dependencies: dependencies + dependencies: dependencies, + directMessage: directMessage ) } @@ -80,7 +95,7 @@ extension SyncCoordinator { contactID: contact.id, radioID: radioID ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { + if await persistReactionIfNew(reactionDTO, dependencies: dependencies, directMessage: directMessage) { logger.debug("Saved DM reaction \(parsed.emoji) to message \(targetMessageID)") } @@ -106,7 +121,7 @@ extension SyncCoordinator { contactID: contact.id, radioID: radioID ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { + if await persistReactionIfNew(reactionDTO, dependencies: dependencies, directMessage: directMessage) { logger.debug("Saved DM reaction \(parsed.emoji) to message \(targetMessage.id) (from DB)") } @@ -119,7 +134,8 @@ extension SyncCoordinator { contactID: contact.id, senderName: contact.displayName, rawText: text, - radioID: radioID + radioID: radioID, + directMessage: directMessage ) logger.debug("Queued pending DM reaction \(parsed.emoji)") @@ -269,7 +285,8 @@ extension SyncCoordinator { rawText: String, contact: ContactDTO, radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? ) async -> Bool { let timestampWindow = reactionTimestampWindow() @@ -304,7 +321,7 @@ extension SyncCoordinator { contactID: contact.id, radioID: radioID ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { + if await persistReactionIfNew(reactionDTO, dependencies: dependencies, directMessage: directMessage) { logger.debug("Saved MCO DM reaction \(mcoReaction.emoji) to message \(candidate.id)") } return true @@ -386,7 +403,8 @@ extension SyncCoordinator { rawText: String, contact: ContactDTO, radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? ) async -> Bool { let timestampWindow = reactionTimestampWindow( anchor: v1Reaction.timestampSeconds @@ -417,7 +435,7 @@ extension SyncCoordinator { contactID: contact.id, radioID: radioID ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { + if await persistReactionIfNew(reactionDTO, dependencies: dependencies, directMessage: directMessage) { logger.debug("Saved MCO v1 DM reaction \(v1Reaction.emoji) to message \(candidate.id)") } return true diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift index 43882abdee..2db69508f7 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift @@ -365,7 +365,10 @@ public actor SyncCoordinator { /// Notify that conversations data changed (triggers UI refresh) @MainActor - public func notifyConversationsChanged() { + public func notifyConversationsChanged( + scope: ReceiveScope? = nil + ) { + guard scope?.isCurrent != false else { return } conversationsVersion += 1 dataEventBroadcaster.yield(.conversationsChanged) } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift b/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift index b06850dba2..b5217f9fe1 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift @@ -12,11 +12,15 @@ public enum SyncDataEvent: Sendable { /// Conversations data changed; observers should reload chat lists. case conversationsChanged /// An incoming direct message was persisted for a known contact. - case directMessageReceived(message: MessageDTO, contact: ContactDTO) + case directMessageReceived(message: MessageDTO, contact: ContactDTO, scope: ReceiveScope? = nil) /// An incoming channel message was persisted. - case channelMessageReceived(message: MessageDTO, channelIndex: UInt8) + case channelMessageReceived( + message: MessageDTO, channelIndex: UInt8, legacyScope: ReceiveScope? = nil + ) /// An incoming signed room message was persisted. - case roomMessageReceived(RoomMessageDTO) + case roomMessageReceived(RoomMessageDTO, roomID: UUID?, scope: ReceiveScope) /// A reaction was persisted and its target message's summary updated. - case reactionReceived(messageID: UUID, summary: String) + case reactionReceived( + messageID: UUID, summary: String, scope: ReceiveScope? = nil, contact: ContactDTO? = nil + ) } diff --git a/MC1Services/Sources/MC1Services/Utilities/ChannelMessageFormat.swift b/MC1Services/Sources/MC1Services/Utilities/ChannelMessageFormat.swift index e0e4349601..2f1b8bf3d6 100644 --- a/MC1Services/Sources/MC1Services/Utilities/ChannelMessageFormat.swift +++ b/MC1Services/Sources/MC1Services/Utilities/ChannelMessageFormat.swift @@ -22,4 +22,13 @@ enum ChannelMessageFormat { let messageText = String(text[afterColon...]).trimmingCharacters(in: .whitespaces) return (senderName, messageText) } + + /// Removes the sender delimiter and its single framing space for rule matching. + static func originalFields(_ text: String) -> (sender: String?, body: String) { + guard let colon = text.firstIndex(of: ":"), colon != text.startIndex else { + return (nil, text) + } + let body = text[text.index(after: colon)...] + return (String(text[...makeStream() + defer { answerPrompt.finish() } + pairing.removeAccessoryGate = gate + pairing.removeAccessoryError = DevicePairingError.cancelled + + let transport = MockTransport() + let session = MeshCoreSession(transport: transport) + try await startEraseTestSession(session, transport: transport, radio: radio) + let services = ServiceContainer(session: session, dataStore: store, radioID: radio.radioID) + manager.setTestState( + connectionState: .connected, services: .some(services), session: .some(session), connectedDevice: .some(radio) + ) + let poller = services.messagePollingService + await services.syncCoordinator.wireMessageHandlers(dependencies: services.syncDependencies, radioID: radio.radioID) + await poller.startAutoFetch(radioID: radio.radioID) + try await waitUntil("poller and automatic fetch are subscribed") { await session.subscriberCountForTest >= 2 } + + let getMessage = PacketBuilder.getMessage() + let timestamp = UInt32(Date().timeIntervalSince1970) + await transport.simulateReceive(Data([ResponseCode.messagesWaiting.rawValue])) + try await waitUntil("first queue read reaches transport") { await transport.sentData.last == getMessage } + let erase = Task { try await manager.startRadioErase(radio) } + try await waitUntil("erase suspends new queue reads") { await session.isMessageFetchingSuspended } + #expect(pairing.removeAccessoryCallCount == 0) + #expect(try await !store.isRadioErasePending(radio.radioID)) + + await transport.simulateReceive(eraseTestChannelFrame("before prompt", timestamp: timestamp)) + try await waitUntil("pairing removal reaches confirmation") { + await MainActor.run { pairing.removeAccessoryCallCount == 1 } + } + #expect(try await store.fetchMessages(radioID: radio.radioID, channelIndex: 0).map(\.text) == ["before prompt"]) + #expect(try await store.isRadioErasePending(radio.radioID)) + await transport.simulateReceive(Data([ResponseCode.messagesWaiting.rawValue])) + try await waitUntil("message waiting was observed during pairing confirmation") { + await session.processedMessagesWaitingCountForTest == 2 + } + #expect(await transport.sentData.filter { $0 == getMessage }.count == 1) + + answerPrompt.yield() + await #expect(throws: DevicePairingError.cancelled) { try await erase.value } + #expect(try await !store.isRadioErasePending(radio.radioID)) + try await waitUntil("cancellation restarts the radio queue drain") { + await transport.sentData.filter { $0 == getMessage }.count == 2 + } + await transport.simulateReceive(eraseTestChannelFrame("during prompt", timestamp: timestamp + 1)) + try await waitUntil("radio queue is checked after the resumed delivery") { + await transport.sentData.filter { $0 == getMessage }.count == 3 + } + await transport.simulateReceive(Data([ResponseCode.noMoreMessages.rawValue])) + try await waitUntil("both channel arrivals are stored once") { + let messages = try? await store.fetchMessages(radioID: radio.radioID, channelIndex: 0) + return messages?.map(\.text).sorted() == ["before prompt", "during prompt"] + } + await poller.stopAutoFetch() + await session.stop() + } + + private func startEraseTestSession(_ session: MeshCoreSession, transport: MockTransport, radio: DeviceDTO) async throws { + let start = Task { try await session.start() } + try await waitUntil("app start reaches transport") { await !transport.sentData.isEmpty } + var selfInfo = Data([ResponseCode.selfInfo.rawValue, ContactType.chat.rawValue, 22, 22]) + selfInfo.append(radio.publicKey) + selfInfo.append(Data(repeating: 0, count: 12)) + for value in [radio.frequency, radio.bandwidth] { + selfInfo.append(withUnsafeBytes(of: value.littleEndian) { Data($0) }) + } + selfInfo.append(contentsOf: [radio.spreadingFactor, radio.codingRate]) + selfInfo.append(contentsOf: radio.nodeName.utf8) + await transport.simulateReceive(selfInfo) + try await start.value + } + + private func eraseTestChannelFrame(_ body: String, timestamp: UInt32) -> Data { + var frame = Data([ResponseCode.channelMessageReceivedV3.rawValue, 32, 0, 0, 0, 0, 0]) + frame.append(withUnsafeBytes(of: timestamp.littleEndian) { Data($0) }) + frame.append(contentsOf: "Peer: \(body)".utf8) + return frame + } + // MARK: - Forget/Resume Signal @Test @@ -399,11 +592,13 @@ struct ConnectionManagerPairingTests { defer { UserDefaults().removePersistentDomain(forName: suiteName) } let (manager, _) = try ConnectionManager.createForTesting(defaults: defaults) - let deviceID = UUID() - manager.persistConnection(deviceID: deviceID, radioID: UUID(), deviceName: "Radio") - #expect(manager.lastConnectedDeviceID == deviceID) + let device = DeviceDTO.testDevice() + try await manager.persistenceStore.saveDevice(device) + manager.setTestState(connectedDevice: .some(device)) + manager.persistConnection(deviceID: device.id, radioID: device.radioID, deviceName: device.nodeName) + #expect(manager.lastConnectedDeviceID == device.id) - await manager.forgetDevice(id: deviceID) + try await manager.forgetDevice(deleteData: true) // The auto-reconnect / onboarding-resume signal must not survive forgetting its own radio. #expect(manager.lastConnectedDeviceID == nil) @@ -419,7 +614,9 @@ struct ConnectionManagerPairingTests { let lastConnected = UUID() manager.persistConnection(deviceID: lastConnected, radioID: UUID(), deviceName: "Radio") - await manager.forgetDevice(id: UUID()) + let device = DeviceDTO.testDevice() + try await manager.persistenceStore.saveDevice(device) + try await manager.startRadioErase(device) #expect(manager.lastConnectedDeviceID == lastConnected) } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift index 8c96d591bd..e8bcfa2aca 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift @@ -44,6 +44,7 @@ public final class MockAccessorySetupKitService: AccessorySetupKitServicing { /// modelling the user declining the system removal confirmation so the /// accessory stays registered. public var removeAccessoryError: Error? + public var removeAccessoryGate: AsyncStream? public init() {} @@ -79,6 +80,11 @@ public final class MockAccessorySetupKitService: AccessorySetupKitServicing { public func removeAccessory(_ accessory: ASAccessory) async throws { removeAccessoryCallCount += 1 lastRemovedDeviceID = accessory.bluetoothIdentifier + if let gate = removeAccessoryGate { + for await _ in gate { + break + } + } if let removeAccessoryError { throw removeAccessoryError } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift index 2000d30e1d..5934d5fecb 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift @@ -32,14 +32,22 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps private var eventSubscriptions: [UUID: EventSubscription] = [:] public func events() async -> AsyncStream { - makeEventStream(filter: nil) + makeEventStream(filter: nil).stream } public func events(filter: EventFilter) async -> AsyncStream { + makeEventStream(filter: filter).stream + } + + public func eventsTracked(filter: EventFilter) async -> (id: UUID, stream: AsyncStream) { makeEventStream(filter: filter) } - private func makeEventStream(filter: EventFilter?) -> AsyncStream { + public func finishEvents(id: UUID) async { + eventSubscriptions.removeValue(forKey: id)?.continuation.finish() + } + + private func makeEventStream(filter: EventFilter?) -> (id: UUID, stream: AsyncStream) { let id = UUID() let (stream, continuation) = AsyncStream.makeStream() eventSubscriptions[id] = EventSubscription(filter: filter, continuation: continuation) @@ -47,7 +55,7 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps guard let self else { return } Task { await self.removeEventSubscription(id: id) } } - return stream + return (id, stream) } private func removeEventSubscription(id: UUID) { @@ -762,6 +770,10 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps startAutoMessageFetchingCallCount += 1 } + public func suspendMessageFetching() async throws {} + + public func resumeMessageFetching() {} + public func stopAutoMessageFetching() { stopAutoMessageFetchingCallCount += 1 } @@ -821,7 +833,11 @@ extension MockMeshCoreSession: RemoteAccessSessionOps { } } - public func sendKeepAlive(to publicKey: Data, syncSince: UInt32) async throws -> MessageSentInfo { + public func sendKeepAlive( + to publicKey: Data, + syncSince: @escaping @Sendable () async throws -> UInt32, + beforeSend: @escaping @Sendable () throws -> Void + ) async throws -> MessageSentInfo { throw NotStubbed.method("sendKeepAlive") } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift index c7de04e461..c6e9e7bf7d 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift @@ -56,28 +56,28 @@ public actor MockMessagePollingService: MessagePollingServiceProtocol { // MARK: - Captured Handlers /// Captured contact message handler (set via setContactMessageHandler) - public private(set) var capturedContactMessageHandler: (@Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void)? + public private(set) var capturedContactMessageHandler: (@Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void)? /// Captured channel message handler (set via setChannelMessageHandler) - public private(set) var capturedChannelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void)? + public private(set) var capturedChannelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void)? /// Captured signed message handler (set via setSignedMessageHandler) - public private(set) var capturedSignedMessageHandler: (@Sendable (ContactMessage, ContactDTO?) async -> Void)? + public private(set) var capturedSignedMessageHandler: (@Sendable (ContactMessage, ReceiveScope) async -> Void)? /// Captured CLI message handler (set via setCLIMessageHandler) public private(set) var capturedCLIMessageHandler: (@Sendable (ContactMessage, ContactDTO?) async -> Void)? // MARK: - Handler Setter Methods (matching MessagePollingService) - public func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void) { + public func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) { capturedContactMessageHandler = handler } - public func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void) { + public func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void) { capturedChannelMessageHandler = handler } - public func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) { + public func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) { capturedSignedMessageHandler = handler } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChannelServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChannelServiceTests.swift index 5db39fbf3d..8251bb3442 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChannelServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChannelServiceTests.swift @@ -284,14 +284,28 @@ struct ChannelServiceTests { @Test func `setChannel fires the slot handler on a new secret and not on a same-secret rename or first insert`() async throws { let radioID = UUID() - let (service, _, _, capture) = try await makeService(radioID: radioID) + let (service, _, store, capture) = try await makeService(radioID: radioID) + let index: UInt8 = 5 + + try await service.setChannel(radioID: radioID, index: index, name: "First", passphrase: "one") + let first = try #require(try await store.fetchChannel(radioID: radioID, index: index)) + let firstIdentity = try #require(first.textRulesID) + try await store.setTextRulesOverride( + .on, kind: .privateChannel, key: .init(radioID: radioID, conversationID: firstIdentity) + ) - try await service.setChannel(radioID: radioID, index: 5, name: "First", passphrase: "one") - try await service.setChannel(radioID: radioID, index: 5, name: "Renamed", passphrase: "one") + try await service.setChannel(radioID: radioID, index: index, name: "Renamed", passphrase: "one") + let renamed = try #require(try await store.fetchChannel(radioID: radioID, index: index)) + #expect(renamed.textRulesID == firstIdentity) + #expect(renamed.textRulesOverride == .on) #expect(await capture.received.isEmpty) - try await service.setChannel(radioID: radioID, index: 5, name: "Replaced", passphrase: "two") - #expect(await capture.received == [Set([5])]) + try await service.setChannel(radioID: radioID, index: index, name: "Replaced", passphrase: "two") + let replaced = try #require(try await store.fetchChannel(radioID: radioID, index: index)) + let replacementIdentity = try #require(replaced.textRulesID) + #expect(replacementIdentity != firstIdentity) + #expect(replaced.textRulesOverride == .inherit) + #expect(await capture.received == [Set([index])]) } @Test diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessagePollingServiceTextTypeTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessagePollingServiceTextTypeTests.swift index a9247e6eff..47a44cbe65 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessagePollingServiceTextTypeTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessagePollingServiceTextTypeTests.swift @@ -37,7 +37,7 @@ struct MessagePollingServiceTextTypeTests { let polling = MessagePollingService(session: session, dataStore: store) let hits = HandlerHits() - await polling.setContactMessageHandler { _, _, _ in + await polling.setContactMessageHandler { _, _, _, _, _ in await hits.recordContact() } await polling.setCLIMessageHandler { _, _ in diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RoomKeepAliveRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RoomKeepAliveRecoveryTests.swift new file mode 100644 index 0000000000..df4d3389b7 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RoomKeepAliveRecoveryTests.swift @@ -0,0 +1,398 @@ +import Foundation +@testable import MC1Services +import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Room keep-alive recovery", .timeLimit(.minutes(1))) +struct RoomKeepAliveRecoveryTests { + private static let savedBookmark: UInt32 = 40 + private static let missingPost: UInt32 = 41 + private static let newestPost: UInt32 = 42 + + private struct Harness { + let room: RemoteNodeSessionDTO + let store: PersistenceStore + let transport: RoomReplayTransport + let mesh: MeshCoreSession + let service: RemoteNodeService + let roomService: RoomServerService + let lifetime: ReceiveScope.Lifetime + let policy: Policy + } + + private actor Policy { + private var preference = TextRulesPreference() + + init() { + preference.setSelection(.all, for: .room) + } + + func snapshot() -> TextRulesPreference { + preference + } + + func turnOff() { + preference.setSelection(.off, for: .room) + } + + func block(_ text: String) { + preference.append(.init(phrase: text, lookIn: .message, match: .wholeField)) + } + } + + private func makeHarness( + bookmark: UInt32 = Self.savedBookmark, + clock: TestClock? = nil + ) async throws -> Harness { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let room = RemoteNodeSessionDTO.testSession( + radioID: radioID, + isConnected: true, + lastSyncTimestamp: bookmark + ) + try await store.saveRemoteNodeSessionDTO(room) + try await store.saveContact(ContactDTO.testContact( + radioID: radioID, + publicKey: room.publicKey, + outPathLength: 0 + )) + let saved = try #require(try await store.fetchRemoteNodeSession(id: room.id)) + let transport = RoomReplayTransport(serverCursor: Self.newestPost) + let mesh = MeshCoreSession(transport: transport, clock: clock) + try await mesh.start() + + let lifetime = ReceiveScope.Lifetime() + let policy = Policy() + let service = RemoteNodeService( + session: mesh, + dataStore: store, + keychainService: KeychainService(), + textRulesPreference: { await policy.snapshot() }, + receiveLifetime: lifetime + ) + let roomService = RoomServerService( + session: mesh, remoteNodeService: service, dataStore: store, radioID: radioID, + textRulesPreference: { await policy.snapshot() }, receiveLifetime: lifetime + ) + return Harness( + room: saved, store: store, transport: transport, mesh: mesh, service: service, + roomService: roomService, lifetime: lifetime, policy: policy + ) + } + + private func admitNextPost(_ harness: Harness) async throws -> RoomMessageDTO? { + guard let timestamp = await harness.transport.nextPost else { return nil } + let saved = try await harness.roomService.handleIncomingMessage( + senderPublicKeyPrefix: Data(harness.room.publicKey.prefix(6)), + timestamp: timestamp, + authorPrefix: Data([0xAB, 0xCD, 0xEF, 0x12]), + text: "Post \(timestamp)" + ) + await harness.transport.acknowledgeNextPost() + return saved + } + + private func holdRequestSlot(_ harness: Harness) async throws -> Task { + let held = Task { + try await harness.mesh.sendAndWait(Data([CommandCode.setTime.rawValue])) { event in + if case .ok = event { return true } + return nil + } + } + try await waitUntil("unrelated command never held the request slot") { + await harness.transport.isRequestHeld + } + return held + } + + private func reserveRecovery(_ harness: Harness) async throws -> Task { + let key = try #require(harness.room.textRulesID) + await harness.service.startSessionKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + try await waitUntil("no recovery reserved") { + await harness.service.roomKeepAliveSchedules[key]?.recovery != nil + } + return try #require(await harness.service.roomKeepAliveSchedules[key]?.recovery) + } + + @Test + func `restarting a room before submission still rewinds once to recover the missed post`() async throws { + let harness = try await makeHarness() + defer { + Task { + await harness.service.stopAllKeepAlives() + await harness.mesh.stop() + } + } + let hiddenText = "Filtered post" + await harness.policy.block(hiddenText) + #expect(try await harness.roomService.handleIncomingMessage( + senderPublicKeyPrefix: Data(harness.room.publicKey.prefix(6)), + timestamp: Self.newestPost, + authorPrefix: Data([0xAB, 0xCD, 0xEF, 0x12]), + text: hiddenText + ) == nil) + #expect(try await harness.store.recentlyBlockedMessages().map(\.body) == [hiddenText]) + #expect(try await harness.store.fetchRemoteNodeSession(id: harness.room.id)?.lastSyncTimestamp == Self.savedBookmark) + + let held = try await holdRequestSlot(harness) + let recovery = try await reserveRecovery(harness) + + #expect(await harness.transport.watermarks.isEmpty) + #expect(await harness.transport.nextPost == nil) + await harness.service.stopSessionKeepAlive(sessionID: harness.room.id) + await harness.service.startSessionKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + await harness.transport.releaseRequest() + #expect(try await held.value) + try await recovery.value + + await harness.service.stopSessionKeepAlive(sessionID: harness.room.id) + #expect(try await admitNextPost(harness)?.timestamp == Self.missingPost) + + for _ in 0..<2 { + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + } + let watermarks = await harness.transport.watermarks + #expect(watermarks.first == Self.savedBookmark) + #expect(watermarks.count >= 3) + #expect(watermarks.dropFirst().allSatisfy { $0 == 0 }) + } + + @Test + func `slow replay advances across routine keep-alives and a policy change`() async throws { + let harness = try await makeHarness() + defer { Task { await harness.mesh.stop() } } + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + #expect(try await admitNextPost(harness)?.timestamp == Self.missingPost) + + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + #expect(await harness.transport.nextPost == Self.newestPost) + await harness.policy.turnOff() + + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + #expect(try await admitNextPost(harness)?.timestamp == Self.newestPost) + #expect(await harness.transport.watermarks == [Self.savedBookmark, 0, 0]) + } + + @Test + func `a retired Link record cannot submit its reservation and replacement owns a new rewind`() async throws { + let harness = try await makeHarness() + defer { + Task { + await harness.service.stopAllKeepAlives() + await harness.mesh.stop() + } + } + let held = try await holdRequestSlot(harness) + let recovery = try await reserveRecovery(harness) + + harness.lifetime.retire() + await harness.service.stopSessionKeepAlive(sessionID: harness.room.id) + await harness.transport.releaseRequest() + #expect(try await held.value) + await #expect(throws: CancellationError.self) { try await recovery.value } + #expect(await harness.transport.watermarks.isEmpty) + + await harness.mesh.stop(disconnectTransport: false) + let replacementMesh = MeshCoreSession(transport: harness.transport) + try await replacementMesh.start() + defer { Task { await replacementMesh.stop() } } + + let replacement = RemoteNodeService( + session: replacementMesh, + dataStore: harness.store, + keychainService: KeychainService(), + textRulesPreference: { await harness.policy.snapshot() } + ) + try await replacement.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + try await replacement.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + #expect(await harness.transport.watermarks == [Self.savedBookmark, 0]) + } + + @Test + func `a rejected rewind retries the bookmark before routine keep-alives send zero`() async throws { + let harness = try await makeHarness() + defer { Task { await harness.mesh.stop() } } + let sessionID = harness.room.id + let publicKey = harness.room.publicKey + + await harness.transport.rejectNextRequest() + await #expect { + try await harness.service.sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + } throws: { error in + guard case let .sessionError(meshError) = error as? RemoteNodeError else { return false } + return meshError.deviceErrorCode == .tableFull + } + #expect(await harness.transport.nextPost == nil) + + try await harness.service.sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + #expect(try await admitNextPost(harness)?.timestamp == Self.missingPost) + try await harness.service.sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + #expect(await harness.transport.watermarks == [Self.savedBookmark, Self.savedBookmark, 0]) + #expect(await harness.transport.nextPost == Self.newestPost) + } + + @Test + func `a lost rewind response preserves the replay cursor`() async throws { + let clock = TestClock() + let harness = try await makeHarness(clock: clock) + defer { Task { await harness.mesh.stop() } } + let sessionID = harness.room.id + let publicKey = harness.room.publicKey + + await harness.transport.loseNextResponse() + let recovery = Task { + try await harness.service.sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + } + try await waitUntil("rewind was not sent or the timeout did not start") { + await harness.transport.watermarks == [Self.savedBookmark] && clock.sleeperCount == 1 + } + clock.advance(by: .seconds(SessionConfiguration.default.defaultTimeout)) + await #expect { + try await recovery.value + } throws: { error in + guard case .sessionError(.timeout) = error as? RemoteNodeError else { return false } + return true + } + + #expect(try await admitNextPost(harness)?.timestamp == Self.missingPost) + try await harness.service.sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + #expect(await harness.transport.watermarks == [Self.savedBookmark, 0]) + #expect(await harness.transport.nextPost == Self.newestPost) + } + + @Test + func `zero bookmark starts a zero-only schedule`() async throws { + let harness = try await makeHarness(bookmark: 0) + defer { Task { await harness.mesh.stop() } } + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + try await harness.store.updateRoomActivity(harness.room.id, syncTimestamp: Self.missingPost) + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + #expect(await harness.transport.watermarks == [0, 0]) + } + + @Test + func `distinct refreshes send the latest bookmark even after a lost request`() async throws { + let harness = try await makeHarness() + defer { Task { await harness.mesh.stop() } } + await harness.transport.dropNextRequest() + try await harness.service.refreshRoom(harness.room) + #expect(await harness.transport.nextPost == nil) + #expect(await harness.transport.watermarks == [Self.savedBookmark]) + + let held = try await holdRequestSlot(harness) + let key = try #require(harness.room.textRulesID) + async let first: Void = harness.service.refreshRoom(harness.room) + async let concurrent: Void = harness.service.refreshRoom(harness.room) + try await waitUntil("no refresh reserved") { await harness.service.roomKeepAliveSchedules[key]?.refresh != nil } + try await harness.store.updateRoomActivity(harness.room.id, syncTimestamp: Self.missingPost) + await harness.transport.releaseRequest() + #expect(try await held.value) + _ = try await (first, concurrent) + #expect(await harness.transport.watermarks == [Self.savedBookmark, Self.missingPost]) + #expect(await harness.transport.nextPost == Self.newestPost) + } + + /// Direct keep-alive semantics from the room server: a positive watermark rewinds, + /// zero preserves the cursor, and a post ACK advances it. + private actor RoomReplayTransport: MeshTransport { + private var stream = AsyncStream.makeStream(of: Data.self) + private var serverCursor: UInt32 + private var dropRequest = false + private var nextResponse: NextResponse? + + private enum NextResponse { + case tableFull + case lost + } + + private(set) var isConnected = false + private(set) var isRequestHeld = false + private(set) var watermarks: [UInt32] = [] + + var receivedData: AsyncStream { + stream.stream + } + + var nextPost: UInt32? { + [RoomKeepAliveRecoveryTests.missingPost, RoomKeepAliveRecoveryTests.newestPost].first { $0 > serverCursor } + } + + init(serverCursor: UInt32) { + self.serverCursor = serverCursor + } + + func connect() { + stream = AsyncStream.makeStream(of: Data.self) + isConnected = true + } + + func disconnect() { + isConnected = false + stream.continuation.finish() + } + + func acknowledgeNextPost() { + if let nextPost { serverCursor = nextPost } + } + + func dropNextRequest() { + dropRequest = true + } + + func rejectNextRequest() { + nextResponse = .tableFull + } + + func loseNextResponse() { + nextResponse = .lost + } + + func releaseRequest() { + stream.continuation.yield(Data([ResponseCode.ok.rawValue])) + isRequestHeld = false + } + + func send(_ data: Data) throws { + switch data.first { + case CommandCode.appStart.rawValue: + stream.continuation.yield(Self.selfInfoPacket()) + case CommandCode.setTime.rawValue: + isRequestHeld = true + case CommandCode.binaryRequest.rawValue: + guard data.count == 38, data[33] == BinaryRequestType.keepAlive.rawValue else { + throw MeshTransportError.sendFailed("Invalid keep-alive command") + } + let watermark = data.suffix(4).withUnsafeBytes { UInt32(littleEndian: $0.loadUnaligned(as: UInt32.self)) } + watermarks.append(watermark) + let response = nextResponse + nextResponse = nil + if response == .tableFull { + stream.continuation.yield(Data([ResponseCode.error.rawValue, ErrorCode.tableFull.rawValue])) + return + } + if dropRequest { + dropRequest = false + } else if watermark > 0 { + serverCursor = watermark + } + if response == .lost { return } + stream.continuation.yield(Data([ResponseCode.messageSent.rawValue, 0, 1, 2, 3, 4, 1, 0, 0, 0])) + default: + throw MeshTransportError.sendFailed("Unexpected test command") + } + } + + private static func selfInfoPacket() -> Data { + var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + packet.append(Data(repeating: 0x01, count: 32)) + packet.append(Data(repeating: 0, count: 12)) + for value: UInt32 in [915_000, 125_000] { + packet.append(withUnsafeBytes(of: value.littleEndian) { Data($0) }) + } + packet.append(contentsOf: [7, 5]) + return packet + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift new file mode 100644 index 0000000000..f10f88ea62 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift @@ -0,0 +1,142 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Signed room post text rules") +struct RoomPostTextRulesTests { + private static let bookmark: UInt32 = 40 + private static let author = Data([0xA1, 0xB2, 0xC3, 0xD4]) + + private struct Fixture { + let store: PersistenceStore + let room: RemoteNodeSessionDTO + let service: RoomServerService + let policy: Policy + let lifetime: ReceiveScope.Lifetime + + func receive(_ text: String, timestamp: UInt32 = 42) async throws -> RoomMessageDTO? { + try await service.handleIncomingMessage( + senderPublicKeyPrefix: Data(room.publicKey.prefix(6)), + timestamp: timestamp, + authorPrefix: RoomPostTextRulesTests.author, + text: text + ) + } + } + + private actor Policy { + private var preference = TextRulesPreference() + + init(_ rule: TextRulesPreference.Rule) { + preference.setSelection(.all, for: .room) + preference.append(rule) + } + + func snapshot() -> TextRulesPreference { + preference + } + + func turnOff() { + preference.setSelection(.off, for: .room) + } + } + + private func makeFixture( + phrase: String, + lookIn: TextRulesPreference.Rule.LookIn = .message, + bookmark: UInt32 = Self.bookmark + ) async throws -> Fixture { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let room = RemoteNodeSessionDTO.testSession( + radioID: radioID, lastSyncTimestamp: bookmark, lastMessageDate: Date(timeIntervalSince1970: 39) + ) + try await store.saveRemoteNodeSessionDTO(room) + let saved = try #require(try await store.fetchRemoteNodeSession(id: room.id)) + let policy = Policy(.init(phrase: phrase, lookIn: lookIn, match: .wholeField)) + let mesh = MockMeshCoreSession() + let remoteNode = RemoteNodeService(session: mesh, dataStore: store, keychainService: KeychainService()) + let lifetime = ReceiveScope.Lifetime() + let service = RoomServerService( + session: mesh, remoteNodeService: remoteNode, dataStore: store, radioID: radioID, + textRulesPreference: { await policy.snapshot() }, receiveLifetime: lifetime + ) + return Fixture(store: store, room: saved, service: service, policy: policy, lifetime: lifetime) + } + + @Test(arguments: [UInt32(0), UInt32(40)]) + func `drop can recover a room without advancing its bookmark or visible activity`(bookmark: UInt32) async throws { + let fixture = try await makeFixture(phrase: " ALERT ", bookmark: bookmark) + #expect(try await fixture.receive(" ALERT ") == nil) + + let recovered = try #require(try await fixture.store.fetchRemoteNodeSession(id: fixture.room.id)) + #expect(recovered.isConnected) + #expect(recovered.lastSyncTimestamp == bookmark) + #expect(recovered.lastMessageDate == fixture.room.lastMessageDate) + #expect(recovered.unreadCount == 0) + #expect(try await fixture.service.fetchMessages(sessionID: fixture.room.id).isEmpty) + + let entries = try await fixture.store.recentlyBlockedMessages() + #expect(entries.count == 1) + #expect(entries.first?.body == " ALERT ") + #expect(entries.first?.identity.conversationID == recovered.textRulesID) + + await fixture.policy.turnOff() + #expect(try await fixture.receive(" ALERT ") == nil) + #expect(try await fixture.store.recentlyBlockedCount() == 1) + #expect(try await fixture.receive(" ALERT", timestamp: 41)?.timestamp == 41) + let saved = try #require(try await fixture.store.fetchRemoteNodeSession(id: fixture.room.id)) + #expect(saved.lastSyncTimestamp == 41) + #expect(saved.lastMessageDate != fixture.room.lastMessageDate) + #expect(saved.unreadCount == 1) + } + + @Test + func `short key collision reaches policy and each exact replay keeps its disposition`() async throws { + let allowed = "collision fixture 58777" + let hidden = "collision fixture 123682" + let fixture = try await makeFixture(phrase: hidden) + #expect(try await fixture.receive(allowed)?.text == allowed) + #expect(try await fixture.receive(hidden) == nil) + await fixture.policy.turnOff() + #expect(try await fixture.receive(allowed) == nil) + #expect(try await fixture.receive(hidden) == nil) + #expect(try await fixture.service.fetchMessages(sessionID: fixture.room.id).map(\.text) == [allowed]) + #expect(try await fixture.store.recentlyBlockedMessages().map(\.body) == [hidden]) + } + + @Test + func `only a unique author on the current Radio ID is available to sender rules`() async throws { + let fixture = try await makeFixture(phrase: "Match me", lookIn: .sender) + let foreign = UUID() + func key(tail: UInt8) -> Data { + Self.author + Data(repeating: tail, count: 28) + } + + try await fixture.store.saveContact(.testContact( + radioID: foreign, publicKey: key(tail: 1), name: "Match me" + )) + let foreignOnly = try #require(try await fixture.receive("Foreign display", timestamp: 41)) + #expect(foreignOnly.authorName == "Match me") + + try await fixture.store.saveContact(.testContact( + radioID: fixture.room.radioID, publicKey: key(tail: 2), name: "Match me" + )) + #expect(try await fixture.receive("Unique", timestamp: 42) == nil) + + try await fixture.store.saveContact(.testContact( + radioID: fixture.room.radioID, publicKey: key(tail: 3), name: "Another author" + )) + #expect(try await fixture.receive("Ambiguous", timestamp: 43) != nil) + #expect(try await fixture.store.recentlyBlockedMessages().map(\.body) == ["Unique"]) + } + + @Test + func `a retired Link record cannot recover a room or archive its post`() async throws { + let fixture = try await makeFixture(phrase: "Hidden") + fixture.lifetime.retire() + #expect(try await fixture.receive("Hidden") == nil) + #expect(try await fixture.store.recentlyBlockedCount() == 0) + #expect(try await fixture.store.fetchRemoteNodeSession(id: fixture.room.id)?.isConnected == false) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/StockChannelTextRulesTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/StockChannelTextRulesTests.swift new file mode 100644 index 0000000000..6e8c77bb4f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/StockChannelTextRulesTests.swift @@ -0,0 +1,135 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Stock channel Text Rules", .timeLimit(.minutes(1))) +@MainActor +struct StockChannelTextRulesTests { + enum Delivery: CaseIterable { + case catchUp + case live + } + + @Test(arguments: Delivery.allCases) + func `stock arrivals use the rules of the ordinary delivery channel`(delivery: Delivery) async throws { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let filteredChannel = try await store.saveChannel( + radioID: radioID, + from: .init(index: 1, name: "Filtered", secret: Data(repeating: 0x11, count: ProtocolLimits.channelSecretSize)) + ) + let unfilteredChannel = try await store.saveChannel( + radioID: radioID, + from: .init(index: 2, name: "Unfiltered", secret: Data(repeating: 0x22, count: ProtocolLimits.channelSecretSize)) + ) + let filtered = try #require(try await store.fetchChannel(id: filteredChannel)) + let unfiltered = try #require(try await store.fetchChannel(id: unfilteredChannel)) + let filteredID = try #require(filtered.textRulesID) + let unfilteredID = try #require(unfiltered.textRulesID) + try await store.setTextRulesOverride( + .on, kind: .privateChannel, key: .init(radioID: radioID, conversationID: filteredID) + ) + try await store.setTextRulesOverride( + .off, kind: .privateChannel, key: .init(radioID: radioID, conversationID: unfilteredID) + ) + + let matchingText = "repeat promotion" + var preference = TextRulesPreference() + preference.append(.init(phrase: matchingText, lookIn: .message, match: .wholeField)) + let transport = MockTransport() + let session = MeshCoreSession(transport: transport) + let services = ServiceContainer( + session: session, dataStore: store, radioID: radioID, textRulesPreference: { [preference] in preference } + ) + defer { + Task { + await services.tearDown() + await session.stop() + } + } + services.notificationService.isSuppressingNotifications = true + let starting = Task { try await session.start() } + try await waitUntil("radio handshake command was not sent") { + await transport.sentData.last?.first == CommandCode.appStart.rawValue + } + await transport.simulateReceive(Self.selfInfoFrame()) + try await starting.value + + let coordinator = services.syncCoordinator + let poller = services.messagePollingService + await coordinator.wireMessageHandlers(dependencies: services.syncDependencies, radioID: radioID) + let subscriptions = await session.subscriberCountForTest + await poller.startMessageEventMonitoring(radioID: radioID) + try await waitUntil("message polling did not subscribe") { + await session.subscriberCountForTest > subscriptions + } + + let timestamp = UInt32(Date.now.timeIntervalSince1970) + let blocked = Self.channelFrame(slot: filtered.index, timestamp: timestamp, body: matchingText) + let allowed = Self.channelFrame(slot: unfiltered.index, timestamp: timestamp, body: matchingText) + + switch delivery { + case .catchUp: + let poll = Task { try await poller.pollAllMessages() } + for (offset, frame) in [blocked, allowed, Data([ResponseCode.noMoreMessages.rawValue])].enumerated() { + try await waitUntil("stock get-message command was not sent") { + await transport.sentData.count == offset + 2 + } + #expect(await transport.sentData.last == Data([CommandCode.getMessage.rawValue])) + await transport.simulateReceive(frame) + } + #expect(try await poll.value == 2) + case .live: + await transport.simulateReceive(blocked) + await transport.simulateReceive(allowed) + try await waitUntil("unfiltered channel arrival did not finish") { + coordinator.conversationsVersion >= 1 + } + #expect(await poller.waitForPendingHandlers(timeout: .seconds(2))) + } + + #expect(try await store.fetchMessages(radioID: radioID, channelIndex: filtered.index).isEmpty) + #expect(try await store.fetchMessages(radioID: radioID, channelIndex: unfiltered.index).map(\.text) == [matchingText]) + let drops = try await store.recentlyBlockedMessages() + #expect(drops.map(\.body) == [matchingText]) + #expect(drops.first?.identity.conversationID == filteredID) + #expect(drops.first?.conversationName == filtered.name) + + let unchanged = try #require(try await store.fetchChannel(radioID: radioID, index: filtered.index)) + #expect(unchanged.lastMessageDate == filtered.lastMessageDate) + #expect(unchanged.unreadCount == filtered.unreadCount) + #expect(unchanged.unreadMentionCount == filtered.unreadMentionCount) + #expect(coordinator.conversationsVersion == 1) + } + + private static func channelFrame(slot: UInt8, timestamp: UInt32, body: String) -> Data { + let snrQuarters: UInt8 = 32 + let reserved: UInt8 = 0 + let pathLength: UInt8 = 0 + let textType = MeshTextType.plain.rawValue + var frame = Data([ResponseCode.channelMessageReceivedV3.rawValue, snrQuarters, reserved, reserved, slot, pathLength, textType]) + frame.append(contentsOf: withUnsafeBytes(of: timestamp.littleEndian) { Array($0) }) + frame.append(contentsOf: "Sender: \(body)".utf8) + return frame + } + + private static func selfInfoFrame() -> Data { + let deviceType: UInt8 = 1 + let power: UInt8 = 22 + let publicKey = Data(repeating: 0xAB, count: 32) + let locationAndFlags = Data(repeating: 0, count: 12) + let frequency: UInt32 = 915_000 + let bandwidth: UInt32 = 125_000 + let spreadingFactor: UInt8 = 7 + let codingRate: UInt8 = 5 + var frame = Data([ResponseCode.selfInfo.rawValue, deviceType, power, power]) + frame.append(publicKey) + frame.append(locationAndFlags) + frame.append(contentsOf: withUnsafeBytes(of: frequency.littleEndian) { Array($0) }) + frame.append(contentsOf: withUnsafeBytes(of: bandwidth.littleEndian) { Array($0) }) + frame.append(contentsOf: [spreadingFactor, codingRate]) + frame.append(contentsOf: "Test".utf8) + return frame + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift index 7cf5cdb4c3..4c8b7dc5e2 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift @@ -11,8 +11,8 @@ struct SyncCoordinatorBackgroundUnreadTests { isChannel: Bool, isInForeground: Bool ) async throws { - let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) let services = ServiceContainer( session: MeshCoreSession(transport: SimulatorMockTransport()), dataStore: store, @@ -50,13 +50,13 @@ struct SyncCoordinatorBackgroundUnreadTests { try await store.saveContact(contact) services.notificationService.setActiveConversation(contactID: contact.id) let message = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let persisted = try #require(await store.fetchContact(id: contact.id)) try await services.syncCoordinator.updateDMUnreadsAndNotify( messageDTO: message, - contactID: contact.id, - contact: contact, - messageText: message.text, - hasSelfMention: false, - dependencies: services.syncDependencies + contact: persisted, + dependencies: services.syncDependencies, + scope: scope ) let saved = try #require(await store.fetchContact(id: contact.id)) #expect(saved.unreadCount == expectedUnread) diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift index cc813c20e2..56610d1f30 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift @@ -11,7 +11,7 @@ struct SyncCoordinatorMessageHandlerTests { private func createTestDataStore(radioID: UUID) async throws -> PersistenceStore { let container = try PersistenceStore.createContainer(inMemory: true) let store = PersistenceStore(modelContainer: container) - let device = DeviceDTO.testDevice(id: radioID, nodeName: "TestNode") + let device = DeviceDTO.testDevice(id: radioID, radioID: radioID, nodeName: "TestNode") try await store.saveDevice(device) return store } @@ -267,7 +267,9 @@ struct SyncCoordinatorMessageHandlerTests { text: "hello mesh", snr: nil ) - await mockPolling.capturedContactMessageHandler?(message, contact, .live) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) + let persisted = try #require(await dataStore.fetchContact(id: contact.id)) + await mockPolling.capturedContactMessageHandler?(message, persisted, .live, scope, nil) let updated = try #require( await dataStore.fetchContact(radioID: radioID, publicKey: publicKey) @@ -304,13 +306,182 @@ struct SyncCoordinatorMessageHandlerTests { text: "get cad", snr: nil ) - await mockPolling.capturedContactMessageHandler?(message, contact, .live) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) + let persisted = try #require(await dataStore.fetchContact(id: contact.id)) + await mockPolling.capturedContactMessageHandler?(message, persisted, .live, scope, nil) let saved = try await dataStore.fetchMessages(contactID: contact.id) #expect(saved.count == 1) #expect(saved[0].textType == .cliCommand) } + @Test(arguments: [false, true]) + func `DM rule drop and replay leave conversation effects untouched`(catchUp: Bool) async throws { + let context: DeliveryContext = catchUp ? .initialSync(anchor: Date()) : .live + let radioID = UUID() + let store = try await createTestDataStore(radioID: radioID) + let key = Data(repeating: 0xB6, count: 32) + let inputContact = ContactDTO.testContact(radioID: radioID, publicKey: key, name: "Peer", lastHeardTimestamp: 0) + try await store.saveContact(inputContact) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let contact = try #require(await store.fetchContact(id: inputContact.id)) + let polling = MockMessagePollingService() + let (_, services) = try await createTestServices() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: polling), + radioID: radioID + ) + let deliver = try #require(await polling.capturedContactMessageHandler) + var preference = TextRulesPreference() + preference.setSelection(.all, for: .directMessage) + preference.append(.init(phrase: "ALERT", lookIn: .message, match: .contains)) + + let arrival = makeDirectArrival(" alert! ", key: key, timestamp: 50) + await deliver(arrival, contact, context, scope, preference) + await deliver(arrival, contact, context, scope, nil) + + let entries = try await store.recentlyBlockedMessages() + #expect(entries.count == 1) + #expect(entries.first?.body == arrival.text) + #expect(entries.first?.identity.senderTimestamp == 50) + #expect(entries.first?.contactID == contact.id) + #expect(try await store.fetchMessages(contactID: contact.id).isEmpty) + let current = try #require(await store.fetchContact(id: contact.id)) + #expect(current.unreadCount == 0) + #expect(current.lastMessageDate == nil) + #expect(current.lastHeardTimestamp == contact.lastHeardTimestamp) + #expect(await coordinator.conversationsVersion == 0) + + await deliver(makeDirectArrival("safe", key: key, timestamp: 51), contact, context, scope, preference) + #expect(try await store.fetchMessages(contactID: contact.id).map(\.text) == ["safe"]) + #expect(try await store.fetchContact(id: contact.id)?.unreadCount == 1) + #expect(await coordinator.conversationsVersion == 1) + } + + @Test + func `DM short key collision uses current policy and exact saved replay`() async throws { + let radioID = UUID() + let store = try await createTestDataStore(radioID: radioID) + let key = Data(repeating: 0xB7, count: 32) + let inputContact = ContactDTO.testContact(radioID: radioID, publicKey: key) + try await store.saveContact(inputContact) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let contact = try #require(await store.fetchContact(id: inputContact.id)) + let polling = MockMessagePollingService() + let (_, services) = try await createTestServices() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: polling), + radioID: radioID + ) + let deliver = try #require(await polling.capturedContactMessageHandler) + let first = makeDirectArrival("collision fixture 58777", key: key, timestamp: 50) + let second = makeDirectArrival("collision fixture 123682", key: key, timestamp: 50) + let firstKey = DeduplicationKey.contentBased( + contactID: contact.id, channelIndex: nil, senderNodeName: nil, timestamp: 50, content: first.text + ) + let secondKey = DeduplicationKey.contentBased( + contactID: contact.id, channelIndex: nil, senderNodeName: nil, timestamp: 50, content: second.text + ) + try #require(firstKey == secondKey) + + await deliver(first, contact, .live, scope, nil) + var preference = TextRulesPreference() + preference.setSelection(.all, for: .directMessage) + preference.append(.init(phrase: "collision", lookIn: .message, match: .contains)) + await deliver(second, contact, .live, scope, preference) + await deliver(first, contact, .live, scope, preference) + #expect(try await store.fetchMessages(contactID: contact.id).map(\.text) == [first.text]) + #expect(try await store.recentlyBlockedMessages().map(\.body) == [second.text]) + } + + @Test + func `removed Contact authority cannot write after same ID is restored`() async throws { + let radioID = UUID() + let store = try await createTestDataStore(radioID: radioID) + let key = Data(repeating: 0xB8, count: 32) + let inputContact = ContactDTO.testContact(radioID: radioID, publicKey: key) + try await store.saveContact(inputContact) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let captured = try #require(await store.fetchContact(id: inputContact.id)) + let polling = MockMessagePollingService() + let (_, services) = try await createTestServices() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: polling), + radioID: radioID + ) + let deliver = try #require(await polling.capturedContactMessageHandler) + try await store.deleteContact(id: captured.id) + try await store.saveContact(inputContact) + let restored = try #require(await store.fetchContact(id: captured.id)) + try #require(restored.textRulesID != captured.textRulesID) + var preference = TextRulesPreference() + preference.setSelection(.all, for: .directMessage) + preference.append(.init(phrase: "alert", lookIn: .message, match: .contains)) + + await deliver(makeDirectArrival("alert", key: key, timestamp: 50), captured, .live, scope, preference) + await deliver(makeDirectArrival("safe", key: key, timestamp: 51), captured, .live, scope, preference) + #expect(try await store.fetchMessages(contactID: captured.id).isEmpty) + #expect(try await store.recentlyBlockedMessages().isEmpty) + #expect(await coordinator.conversationsVersion == 0) + } + + @Test + func `DM sender rule suppresses reactions while existing Contact block keeps ordinary history`() async throws { + let radioID = UUID() + let store = try await createTestDataStore(radioID: radioID) + let key = Data(repeating: 0xB9, count: 32) + let inputContact = ContactDTO.testContact(radioID: radioID, publicKey: key, name: "Peer") + try await store.saveContact(inputContact) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let contact = try #require(await store.fetchContact(id: inputContact.id)) + let polling = MockMessagePollingService() + let (_, services) = try await createTestServices() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: polling), + radioID: radioID + ) + let deliver = try #require(await polling.capturedContactMessageHandler) + let target = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id, text: "Ready") + try await store.saveMessage(target) + let reaction = services.reactionService.buildDMReactionText( + emoji: "👍", targetText: target.text, targetTimestamp: target.timestamp + ) + let arrival = makeDirectArrival(reaction, key: key, timestamp: target.timestamp) + var preference = TextRulesPreference() + preference.setSelection(.all, for: .directMessage) + preference.append(.init(phrase: "Peer", lookIn: .sender, match: .wholeField)) + await deliver(arrival, contact, .live, scope, preference) + #expect(try await store.fetchReactions(for: target.id).isEmpty) + #expect(try await store.recentlyBlockedMessages().isEmpty) + + await deliver(arrival, contact, .live, scope, nil) + #expect(try await store.fetchReactions(for: target.id).map(\.emoji) == ["👍"]) + + _ = try await store.updateContactLocalPreferences( + contactID: contact.id, nickname: .unchanged, isBlocked: true, isFavorite: nil, clearRemoteCLI: false + ) + await deliver(makeDirectArrival("ordinary body", key: key, timestamp: 60), contact, .live, scope, preference) + #expect(try await store.recentlyBlockedMessages().isEmpty) + #expect(try await store.fetchMessages(contactID: contact.id).contains { $0.text == "ordinary body" }) + #expect(try await store.fetchContact(id: contact.id)?.unreadCount == 0) + } + + private func makeDirectArrival(_ text: String, key: Data, timestamp: UInt32) -> ContactMessage { + ContactMessage( + senderPublicKeyPrefix: Data(key.prefix(6)), + pathLength: 0, + textType: 0, + senderTimestamp: Date(timeIntervalSince1970: TimeInterval(timestamp)), + signature: nil, + text: text, + snr: nil + ) + } + @Test func `cli data from a chat contact does not reach admin handlers`() async throws { let radioID = UUID() @@ -383,7 +554,7 @@ struct SyncCoordinatorMessageHandlerTests { text: "ChannelPeer: hello channel", snr: nil ) - await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live) + await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live, nil, .now, nil) let updated = try #require( await dataStore.fetchContact(radioID: radioID, publicKey: publicKey) @@ -393,6 +564,62 @@ struct SyncCoordinatorMessageHandlerTests { // MARK: - Live receive region propagation + @Test(.timeLimit(.minutes(1))) + func `legacy channel arrival cannot cross a retired receive scope`() async throws { + let radioID = UUID() + let store = try await createTestDataStore(radioID: radioID) + let radio = try #require(await store.fetchDevice(radioID: radioID)) + let lifetime = ReceiveScope.Lifetime() + let mesh = MockMeshCoreSession() + let poller = MessagePollingService( + session: mesh, dataStore: store, receiveLifetime: lifetime + ) + let mockPolling = MockMessagePollingService() + let (_, services) = try await createTestServices() + let dependencies = services.syncDependencies.with(dataStore: store, messagePollingService: mockPolling) + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers(dependencies: dependencies, radioID: radioID) + let handler = try #require(await mockPolling.capturedChannelMessageHandler) + + let (captured, capture) = AsyncStream.makeStream() + let (released, release) = AsyncStream.makeStream() + await poller.setChannelMessageHandler { message, channel, context, preference, arrivedAt, scope in + if message.text == "Peer: before erase" { + capture.yield(scope) + var iterator = released.makeAsyncIterator() + _ = await iterator.next() + } + await handler(message, channel, context, preference, arrivedAt, scope) + } + await poller.startMessageEventMonitoring(radioID: radioID) + try await waitUntil("poller did not subscribe") { await mesh.eventSubscriptionCount == 1 } + let stamp = Date() + await mesh.yieldEvent(.channelMessageReceived(ChannelMessage( + channelIndex: 0, pathLength: 0, textType: 0, senderTimestamp: stamp, text: "Peer: before erase", snr: nil + ))) + var captureIterator = captured.makeAsyncIterator() + let deliveredScope = await captureIterator.next() ?? nil + let oldScope = try #require(deliveredScope) + + _ = try await store.beginRadioErase(radio) + try await store.cancelRadioErase(radioID: radioID) + #expect(!oldScope.isCurrent) + let lateWrite = MessageDTO.testChannelMessage(radioID: radioID, channelIndex: 0, text: "Before erase") + #expect(try await store.saveLegacyChannelMessage(lateWrite, scope: oldScope, conversationID: nil) == false) + + release.finish() + await mesh.yieldEvent(.channelMessageReceived(ChannelMessage( + channelIndex: 0, pathLength: 0, textType: 0, senderTimestamp: stamp, text: "Peer: after cancellation", snr: nil + ))) + try await waitUntil("fresh channel arrival was not published") { + await coordinator.conversationsVersion == 1 + } + #expect(try await store.fetchMessages(radioID: radioID, channelIndex: 0).map(\.text) == ["after cancellation"]) + + await poller.stopMessageEventMonitoring() + await mesh.finishEventStreams() + } + @Test func `live channel receive with undecryptable RX does not copy regionScope onto Message`() async throws { let radioID = UUID() @@ -442,7 +669,7 @@ struct SyncCoordinatorMessageHandlerTests { text: "NodeAlpha: region scope test", snr: nil ) - await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live) + await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live, nil, .now, nil) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) let message = try #require(saved.first) @@ -499,7 +726,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), nil, - .live + .live, nil, .now, nil ) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) @@ -512,7 +739,7 @@ struct SyncCoordinatorMessageHandlerTests { var broadcast: MessageDTO? for _ in 0..<8 { guard let event = await iterator.next() else { break } - if case let .channelMessageReceived(message, _) = event { + if case let .channelMessageReceived(message, _, _) = event { broadcast = message break } @@ -578,7 +805,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), channel, - .live + .live, nil, .now, nil ) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) @@ -646,7 +873,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), nil, - .live + .live, nil, .now, nil ) #expect(try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex).count == 1) diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift index e49de2b638..3471395c46 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift @@ -2326,11 +2326,11 @@ actor OrderTrackingMessagePollingService: MessagePollingServiceProtocol { func resumeAutoFetch() async {} - func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void) {} + func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) {} - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void) {} + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void) {} - func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} + func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) {} func setCLIMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} } diff --git a/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift b/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift new file mode 100644 index 0000000000..7c9a445b98 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift @@ -0,0 +1,140 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Text Rules conversation ownership") +struct TextRulesOwnershipTests { + @Test + func `contact binding survives insert only rollback and later collision`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radio = DeviceDTO.testDevice() + try await store.saveDevice(radio) + let prefix = Data([1, 2, 3, 4, 5, 6]) + let contact = ContactDTO.testContact(radioID: radio.radioID, publicKey: prefix + Data(repeating: 1, count: 26)) + let collision = ContactDTO.testContact(radioID: radio.radioID, publicKey: prefix + Data(repeating: 2, count: 26)) + let drop = try makeDrop(radioID: radio.radioID, prefix: prefix) + try await store.recordRecentlyBlockedMessage(drop) + + try await store.saveContact(contact) + let bound = try await store.recentlyBlockedMessages().first + #expect(bound?.contactID == contact.id) + try await store.deleteContactIfUnreferenced(id: contact.id) + #expect(try await store.fetchContact(id: contact.id) != nil) + #expect(try await store.recentlyBlockedMessages().first?.contactID == contact.id) + #expect(try await store.hasRecentlyBlockedMessage(drop.identity)) + + try await store.saveContact(collision) + try await store.deleteContactIfUnreferenced(id: collision.id) + #expect(try await store.fetchContact(id: collision.id) == nil) + #expect(try await store.recentlyBlockedMessages().first?.contactID == contact.id) + + try await store.deleteContact(id: contact.id) + #expect(try await store.recentlyBlockedCount() == 0) + #expect(try await store.fetchContact(id: contact.id) == nil) + } + + @Test + func `removing one of two prefix matches binds only the unbound dm`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radio = DeviceDTO.testDevice() + try await store.saveDevice(radio) + let prefix = Data([1, 2, 3, 4, 5, 6]) + let first = ContactDTO.testContact(radioID: radio.radioID, publicKey: prefix + Data(repeating: 1, count: 26)) + let second = ContactDTO.testContact(radioID: radio.radioID, publicKey: prefix + Data(repeating: 2, count: 26)) + let room = RemoteNodeSessionDTO.testSession(radioID: radio.radioID) + try await store.saveContact(first) + try await store.saveContact(second) + try await store.saveRemoteNodeSessionDTO(room) + let roomID = try #require(await store.fetchRemoteNodeSession(id: room.id)?.textRulesID) + let dmDrop = try makeDrop(radioID: radio.radioID, prefix: prefix) + let roomDrop = try makeDrop(radioID: radio.radioID, prefix: Data(prefix.prefix(4)), conversationID: roomID) + try await store.recordRecentlyBlockedMessage(dmDrop) + try await store.recordRecentlyBlockedMessage(roomDrop) + + try await store.deleteContact(id: first.id) + let retained = try await store.recentlyBlockedMessages() + #expect(retained.first(where: { $0.id == dmDrop.id })?.contactID == second.id) + #expect(retained.first(where: { $0.id == roomDrop.id })?.contactID == nil) + + try await store.deleteContact(id: second.id) + #expect(try await store.recentlyBlockedMessages().map(\.id) == [roomDrop.id]) + try await store.deleteRemoteNodeSession(id: room.id) + #expect(try await store.recentlyBlockedCount() == 0) + } + + @Test + func `restoring the same contact UUID does not restore its selection identity or override`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radio = DeviceDTO.testDevice() + let contact = ContactDTO.testContact(radioID: radio.radioID) + try await store.saveDevice(radio) + try await store.saveContact(contact) + let selected = try #require(await store.textRulesConversations(kind: .directMessage).first) + try await store.setTextRulesOverride(.on, kind: selected.kind, key: selected.key) + let backupService = AppBackupService() + let backup = try await backupService.export(persistenceStore: store) + let envelope = try parseBackup(data: backup.data) + let exportedContact = try #require(envelope.contacts.first) + #expect(exportedContact.id == contact.id) + #expect(exportedContact.textRulesID == nil) + #expect(exportedContact.textRulesOverride == .inherit) + + _ = try await backupService.importBackup(envelope: envelope, into: store) + #expect(try await store.textRulesConversation(kind: selected.kind, key: selected.key)?.override == .on) + try await store.deleteContact(id: contact.id) + _ = try await backupService.importBackup(envelope: envelope, into: store) + + let restored = try #require(await store.fetchContact(id: contact.id)) + #expect(restored.textRulesID != selected.key.conversationID) + #expect(restored.textRulesOverride == .inherit) + #expect(try await store.textRulesConversation(kind: selected.kind, key: selected.key) == nil) + await #expect(throws: PersistenceStoreError.self) { + try await store.setTextRulesOverride(.on, kind: selected.kind, key: selected.key) + } + } + + @Test(arguments: [false, true]) + func `ghost reconciliation retires only an abandoned partition`(stillOwned: Bool) async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let current = DeviceDTO.testDevice(publicKey: Data(repeating: 1, count: 32)) + let ghost = DeviceDTO.testDevice(publicKey: Data(repeating: 2, count: 32)) + try await store.saveDevice(current) + try await store.saveDevice(ghost) + try await store.demoteDeviceToGhost(id: ghost.id) + if stillOwned { + try await store.saveDevice(.testDevice(radioID: current.radioID, publicKey: Data(repeating: 3, count: 32))) + } + let contact = ContactDTO.testContact(radioID: current.radioID) + try await store.saveContact(contact) + let before = try #require(await store.fetchContact(id: contact.id)?.textRulesID) + let scope = try #require(await store.captureReceiveScope(radioID: current.radioID, link: .init())) + let currentDrop = try makeDrop(radioID: current.radioID, prefix: nil) + let retainedDrop = try makeDrop(radioID: ghost.radioID, prefix: nil) + try await store.recordRecentlyBlockedMessage(currentDrop) + try await store.recordRecentlyBlockedMessage(retainedDrop) + + #expect(try await store.reconcileGhostIdentity(currentDeviceID: current.id, newPublicKey: ghost.publicKey) == ghost.radioID) + #expect(scope.isCurrent == stillOwned) + #expect(try await store.fetchContact(id: contact.id)?.textRulesID == (stillOwned ? before : nil)) + #expect(try await store.hasRecentlyBlockedMessage(currentDrop.identity) == stillOwned) + #expect(try await store.hasRecentlyBlockedMessage(retainedDrop.identity)) + } + + private func makeDrop( + radioID: UUID, + prefix: Data?, + conversationID: UUID? = nil + ) throws -> RecentlyBlockedMessageDTO { + let body = "Keep this original" + var preference = TextRulesPreference() + preference.append(.init(phrase: "original", lookIn: .message, match: .contains)) + return try RecentlyBlockedMessageDTO( + identity: .init( + radioID: radioID, conversationID: conversationID, senderPrefix: prefix, + senderTimestamp: 1, textType: 0, wireText: Data(body.utf8) + ), + arrivedAt: Date(), body: body, sender: nil, conversationName: nil, radioName: nil, + match: #require(preference.firstMatch(body: body, sender: nil)) + ) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift b/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift new file mode 100644 index 0000000000..0bc7d94662 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift @@ -0,0 +1,152 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Text Rules preference") +struct TextRulesPreferenceTests { + @Test + func `type defaults and explicit choices are independent`() { + var preference = TextRulesPreference() + let member = TextRulesPreference.Key(radioID: UUID(), conversationID: UUID()) + let otherRadio = TextRulesPreference.Key(radioID: UUID(), conversationID: member.conversationID) + + for kind in TextRulesPreference.Kind.allCases { + let onByDefault = kind == .publicChannel || kind == .hashtagChannel + #expect(preference.selection(for: kind) == (onByDefault ? .all : .off)) + #expect(preference.effective(for: kind, key: nil, override: .inherit).isOn == onByDefault) + #expect(preference.effective(for: kind, key: member, override: .on) == .init(isOn: true, source: .explicit)) + #expect(preference.effective(for: kind, key: member, override: .off) == .init(isOn: false, source: .explicit)) + + preference.setSelection(.fixed([member]), for: kind) + #expect(preference.effective(for: kind, key: member, override: .inherit) == .init(isOn: true, source: .type)) + #expect(preference.effective(for: kind, key: otherRadio, override: .inherit).source == .fixedExclusion) + #expect(preference.effective(for: kind, key: nil, override: .inherit).source == .fixedExclusion) + + preference.setSelection(.fixed([]), for: kind) + #expect(preference.selection(for: kind).isOn) + #expect(!preference.effective(for: kind, key: member, override: .inherit).isOn) + } + } + + @Test + func `comparison is literal and case insensitive across independent fields`() throws { + let first = TextRulesPreference.Rule(phrase: "CAFÉ*", lookIn: .messageOrSender, match: .contains) + let second = TextRulesPreference.Rule(phrase: "alert", lookIn: .message, match: .contains) + var preference = TextRulesPreference() + preference.append(first) + preference.append(second) + + let body = "Alert café* café*" + let sender = "café* store" + let matched = try #require(preference.firstMatch(body: body, sender: sender)) + #expect(matched.rule == first) + #expect(matched.bodyHighlights.compactMap { $0.range(in: body).map { String(body[$0]) } } == ["café*", "café*"]) + #expect(matched.senderHighlights.compactMap { $0.range(in: sender).map { String(sender[$0]) } } == ["café*"]) + #expect(preference.firstMatch(body: "cafe*", sender: nil) == nil) + #expect(preference.firstMatch(body: "cafe\u{301}*", sender: nil) == nil) + #expect(preference.firstMatch(body: "caféx", sender: nil) == nil) + #expect(preference.firstMatch(body: "", sender: nil) == nil) + #expect(preference.firstMatch(body: nil, sender: "alert") == nil) + #expect(preference.firstMatch(body: nil, sender: sender)?.rule == first) + } + + @Test + func `whole field keeps significant spaces and substring highlights expand to characters`() throws { + var preference = TextRulesPreference() + let whole = TextRulesPreference.Rule(phrase: " ALERT", lookIn: .messageOrSender, match: .wholeField) + preference.append(whole) + #expect(preference.firstMatch(body: " alert", sender: "ALERT")?.rule == whole) + #expect(preference.firstMatch(body: " alert", sender: "ALERT") == nil) + #expect(preference.firstMatch(body: " alert ", sender: nil) == nil) + + preference.append(.init(phrase: "👩", lookIn: .sender, match: .contains)) + let sender = "Radio 👩‍🚒" + let match = try #require(preference.firstMatch(body: nil, sender: sender)) + let range = try #require(match.senderHighlights.first?.range(in: sender)) + #expect(sender[range] == "👩‍🚒") + } + + @Test @MainActor + func `failed settings saves leave committed values and concurrent edits rebase`() async throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appending(path: "rules.json") + let manager = try makeManager(url: url) + manager.loadTextRules() + let defaults = try #require(manager.textRulesPreference) + #expect(defaults.rules.isEmpty) + #expect(defaults.selection(for: .publicChannel) == .all) + + let rule = TextRulesPreference.Rule(phrase: " alert ", lookIn: .message, match: .contains) + let first = Task { @MainActor in + try manager.updateTextRules { $0.append(rule) } + } + let second = Task { @MainActor in + try manager.updateTextRules { $0.setSelection(.fixed([]), for: .publicChannel) } + } + try await first.value + try await second.value + let committed = try #require(manager.textRulesPreference) + #expect(committed.revision != defaults.revision) + #expect(committed.rules == [rule]) + #expect(committed.selection(for: .publicChannel) == .fixed([])) + + let reopened = try makeManager(url: url) + reopened.loadTextRules() + #expect(reopened.textRulesPreference == committed) + let committedBytes = try Data(contentsOf: url) + #expect(throws: CocoaError.self) { + try manager.updateTextRules { $0.append(.init(phrase: " \n", lookIn: .sender, match: .contains)) } + } + #expect(try Data(contentsOf: url) == committedBytes) + + try FileManager.default.removeItem(at: url) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false) + #expect(throws: CocoaError.self) { + try manager.updateTextRules { $0.removeRule(id: rule.id) } + } + #expect(manager.textRulesPreference == committed) + } + + @Test @MainActor + func `unreadable preference bytes survive until successful retry`() async throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appending(path: "rules.json") + let malformed = Data("invalid settings".utf8) + try malformed.write(to: url) + + let manager = try makeManager(url: url) + manager.loadTextRules() + #expect(manager.textRulesPreference == nil) + #expect(!manager.isTextRulesLoading) + #expect(throws: CocoaError.self) { + try manager.updateTextRules { $0.setSelection(.all, for: .room) } + } + await manager.retryTextRulesLoad() + #expect(try Data(contentsOf: url) == malformed) + #expect(manager.textRulesPreference == nil) + + let recovered = TextRulesPreference() + try JSONEncoder().encode(recovered).write(to: url) + await manager.retryTextRulesLoad() + #expect(manager.textRulesPreference == recovered) + #expect(!manager.isTextRulesLoading) + } + + private func makeDirectory() throws -> URL { + let directory = URL.temporaryDirectory.appending(path: UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + return directory + } + + @MainActor + private func makeManager(url: URL) throws -> ConnectionManager { + try ConnectionManager( + modelContainer: PersistenceStore.createContainer(inMemory: true), + stateMachine: MockBLEStateMachine(), + transport: MockMeshTransport(), + textRulesURL: url + ) + } +} diff --git a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift index eef0e17410..080d9d6816 100644 --- a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift +++ b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift @@ -263,9 +263,9 @@ struct ConnectionStatusLifecycleTests { func startAutoFetch(radioID: UUID) async {} func pauseAutoFetch() async {} func resumeAutoFetch() async {} - func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void) {} - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void) {} - func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} + func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) {} + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void) {} + func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) {} func setCLIMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} } } diff --git a/MC1Tests/AppState/RadioEraseDiskTests.swift b/MC1Tests/AppState/RadioEraseDiskTests.swift new file mode 100644 index 0000000000..0bf4c8d860 --- /dev/null +++ b/MC1Tests/AppState/RadioEraseDiskTests.swift @@ -0,0 +1,82 @@ +import Foundation +@testable import MC1Services +import SwiftData +import Testing + +@MainActor +struct RadioEraseDiskTests { + private enum InjectedFailure: Error { + case save + } + + @Test + func `pending target survives partial cleanup and reopens without A device row`() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("cleanup.store") + let radio = DeviceDTO(from: Device(publicKey: Data(repeating: 1, count: 32), nodeName: "Target")) + let other = DeviceDTO(from: Device(publicKey: Data(repeating: 2, count: 32), nodeName: "Other")) + let lifetime = ReceiveScope.Lifetime() + let scope: ReceiveScope + + do { + let store = try openStore(url) + try await store.saveDevice(radio) + try await store.saveDevice(other) + try await store.recordRecentlyBlockedMessage(makeDrop(radio)) + try await store.recordRecentlyBlockedMessage(makeDrop(other)) + scope = try #require(await store.captureReceiveScope(radioID: radio.radioID, link: lifetime)) + + await store.setRadioEraseFaults(begin: { throw InjectedFailure.save }, complete: nil) + await #expect(throws: InjectedFailure.save) { + _ = try await store.beginRadioErase(radio) + } + #expect(scope.isCurrent) + #expect(try await store.fetchPendingRadioErases().isEmpty) + #expect(try await store.fetchDevice(id: radio.id) != nil) + #expect(try await store.recentlyBlockedCount() == 2) + + await store.setRadioEraseFaults(begin: nil, complete: { throw InjectedFailure.save }) + _ = try await store.beginRadioErase(radio, isFactoryReset: true) + #expect(!scope.isCurrent) + #expect(try await store.captureReceiveScope(radioID: radio.radioID, link: lifetime) == nil) + await #expect(throws: InjectedFailure.save) { + try await store.completeRadioErase(radioID: radio.radioID) + } + try await store.deleteDevice(id: radio.id) + } + + let reopened = try openStore(url) + let target = try #require(await reopened.fetchPendingRadioErases().first) + #expect(target.radioID == radio.radioID) + #expect(target.radioName == radio.nodeName) + #expect(target.isFactoryReset == true) + #expect(try await reopened.captureReceiveScope(radioID: radio.radioID, link: .init()) == nil) + try await reopened.completeRadioErase(radioID: target.radioID) + #expect(try await reopened.fetchPendingRadioErases().isEmpty) + #expect(try await reopened.recentlyBlockedMessages().map(\.identity.radioID) == [other.radioID]) + #expect(try await reopened.fetchDevice(id: other.id) != nil) + #expect(!scope.isCurrent) + } + + private func openStore(_ url: URL) throws -> PersistenceStore { + let schema = PersistenceStore.schema + let configuration = ModelConfiguration(schema: schema, url: url) + return try PersistenceStore(modelContainer: ModelContainer(for: schema, configurations: configuration)) + } + + private func makeDrop(_ radio: DeviceDTO) throws -> RecentlyBlockedMessageDTO { + let body = "Hidden body" + var preference = TextRulesPreference() + preference.append(.init(phrase: "hidden", lookIn: .message, match: .contains)) + return try RecentlyBlockedMessageDTO( + identity: .init( + radioID: radio.radioID, conversationID: nil, senderPrefix: nil, + senderTimestamp: 1, textType: 0, wireText: Data(body.utf8) + ), + arrivedAt: Date(), body: body, sender: nil, conversationName: nil, radioName: radio.nodeName, + match: #require(preference.firstMatch(body: body, sender: nil)) + ) + } +} diff --git a/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift b/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift new file mode 100644 index 0000000000..f866b9a903 --- /dev/null +++ b/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift @@ -0,0 +1,158 @@ +import Foundation +@testable import MC1Services +import SwiftData +import Testing + +@Suite("Recently Blocked persistence") +struct RecentlyBlockedPersistenceTests { + private struct InjectedSaveFailure: Error {} + + @Test + func `retained drops are capped across radios and rollback preserves the committed archive`() async throws { + let directory = URL.temporaryDirectory.appending(path: UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let configuration = ModelConfiguration( + schema: PersistenceStore.schema, + url: directory.appending(path: "recently-blocked.store") + ) + let radios = [UUID(), UUID()] + let limit = PersistenceStore.recentlyBlockedRetentionLimit + let drops = try (0...limit + 1).map { index in + try makeDrop(index: index, radioID: radios[index % radios.count]) + } + + do { + let container = try ModelContainer(for: PersistenceStore.schema, configurations: [configuration]) + let store = PersistenceStore(modelContainer: container) + for drop in drops.dropLast() { + try await store.recordRecentlyBlockedMessage(drop) + } + let lastDrop = drops[limit] + try await store.recordRecentlyBlockedMessage(lastDrop) + let committed = try await store.recentlyBlockedMessages() + #expect(committed == Array(drops[1...limit].reversed())) + #expect(try await store.recentlyBlockedCount() == limit) + + await store.setRecordRecentlyBlockedFaultInjection { throw InjectedSaveFailure() } + await #expect(throws: InjectedSaveFailure.self) { + try await store.recordRecentlyBlockedMessage(drops[limit + 1]) + } + #expect(try await store.recentlyBlockedMessages() == committed) + #expect(try await store.recentlyBlockedCount() == limit) + } + + let reopened = try ModelContainer(for: PersistenceStore.schema, configurations: [configuration]) + let store = PersistenceStore(modelContainer: reopened) + #expect(try await store.recentlyBlockedMessages() == Array(drops[1...limit].reversed())) + let exported = try await AppBackupService().export(persistenceStore: store) + let envelope = try parseBackup(data: exported.data) + #expect(envelope.messages.isEmpty) + #expect(envelope.roomMessages.isEmpty) + let encoded = try JSONEncoder().encode(envelope) + #expect(!String(decoding: encoded, as: UTF8.self).contains("Archive-only body")) + } + + @Test(arguments: [false, true]) + func `restored DM wins over retained drop after reopening the store`(corrected: Bool) async throws { + let directory = URL.temporaryDirectory.appending(path: UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let configuration = ModelConfiguration( + schema: PersistenceStore.schema, + url: directory.appending(path: "dm-replay.store") + ) + let radioID = UUID() + let radioKey = Data(repeating: 0x17, count: 32) + let contactKey = Data(repeating: 0x48, count: 32) + let contact = ContactDTO(from: Contact( + radioID: radioID, publicKey: contactKey, name: "Peer", lastHeardTimestamp: 0 + )) + let arrival = MessageDTO(from: Message( + radioID: radioID, contactID: contact.id, text: "Field alert ", timestamp: 1_700_000_100, + directionRawValue: MessageDirection.incoming.rawValue, statusRawValue: MessageStatus.delivered.rawValue, + senderKeyPrefix: Data(contactKey.prefix(6)), deduplicationKey: "live-contact-key", + timestampCorrected: corrected, senderTimestamp: corrected ? 50 : nil + )) + var preference = TextRulesPreference() + preference.setSelection(.all, for: .directMessage) + preference.append(.init(phrase: "alert", lookIn: .message, match: .contains)) + + do { + let store = try PersistenceStore(modelContainer: ModelContainer( + for: PersistenceStore.schema, configurations: [configuration] + )) + try await store.saveDevice(DeviceDTO(from: Device(radioID: radioID, publicKey: radioKey, nodeName: "Local"))) + try await store.saveContact(contact) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let captured = try #require(await store.fetchContact(id: contact.id)) + let admission = try await store.admitDirectMessage( + arrival, wireTextType: arrival.textType.rawValue, contact: captured, scope: scope, preference: preference + ) + guard case .discarded = admission else { + Issue.record("Expected rule to drop the initial arrival") + return + } + #expect(try await store.recentlyBlockedCount() == 1) + } + + let store = try PersistenceStore(modelContainer: ModelContainer( + for: PersistenceStore.schema, configurations: [configuration] + )) + let foreignRadioID = UUID() + let foreignContact = ContactDTO(from: Contact( + radioID: foreignRadioID, publicKey: contactKey, name: "Peer", lastHeardTimestamp: 0 + )) + let foreignMessage = arrival.copy { + $0.id = UUID() + $0.radioID = foreignRadioID + $0.contactID = foreignContact.id + $0.deduplicationKey = "foreign-contact-key" + } + let backup = AppBackupEnvelope( + appVersion: "1", appBuild: "1", + devices: [DeviceDTO(from: Device(radioID: foreignRadioID, publicKey: radioKey, nodeName: "Foreign"))], + contacts: [foreignContact], + messages: [foreignMessage] + ) + _ = try await AppBackupService().importBackup(envelope: backup, into: store) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let captured = try #require(await store.fetchContact(id: contact.id)) + let admission = try await store.admitDirectMessage( + arrival, wireTextType: arrival.textType.rawValue, contact: captured, scope: scope, preference: preference + ) + guard case let .replay(saved) = admission else { + Issue.record("Expected exact saved DM to win over the retained drop") + return + } + #expect(saved.id == foreignMessage.id) + #expect(saved.radioID == radioID) + #expect(saved.contactID == contact.id) + #expect(try await store.recentlyBlockedCount() == 1) + #expect(try await store.fetchMessages(contactID: contact.id).count == 1) + } + + private func makeDrop(index: Int, radioID: UUID) throws -> RecentlyBlockedMessageDTO { + var preference = TextRulesPreference() + preference.append(.init(phrase: "archive", lookIn: .messageOrSender, match: .contains)) + let body = "Archive-only body \(index) " + let sender = "Archive Sender" + let match = try #require(preference.firstMatch(body: body, sender: sender)) + return RecentlyBlockedMessageDTO( + identity: .init( + radioID: radioID, + conversationID: UUID(), + senderPrefix: nil, + senderTimestamp: UInt32(index), + textType: 0, + wireText: Data(body.utf8) + ), + arrivedAt: Date(timeIntervalSince1970: Double(index)), + body: body, + sender: sender, + conversationName: "#test", + radioName: "Radio \(radioID)", + match: match + ) + } +} diff --git a/MC1Tests/Views/Chats/ChatChannelInfoPresentationTests.swift b/MC1Tests/Views/Chats/ChatChannelInfoPresentationTests.swift index 9c3e17a5a3..b0f562eb12 100644 --- a/MC1Tests/Views/Chats/ChatChannelInfoPresentationTests.swift +++ b/MC1Tests/Views/Chats/ChatChannelInfoPresentationTests.swift @@ -36,6 +36,28 @@ struct ChatChannelInfoPresentationTests { try await host.expectPin(initialPin) } + @Test + func `opening Channel Info offline initializes a legacy Text Rules identity`() async throws { + let host = try Host(initialPin: false, legacyChannel: true) + defer { host.tearDown() } + let store = host.appState.connectionManager.persistenceStore + host.appState.connectionManager.setTestState(connectionState: .disconnected, connectedDevice: .some(nil)) + #expect(try await store.fetchChannel(id: host.channel.id)?.textRulesID == nil) + + host.mount() + try await host.openInfo() + + let conversationID = try #require(try await store.fetchChannel(id: host.channel.id)?.textRulesID) + try await store.setTextRulesOverride( + .on, kind: .privateChannel, key: .init(radioID: host.channel.radioID, conversationID: conversationID) + ) + try await host.closeInfo() + try await host.openInfo() + let reopened = try #require(try await store.fetchChannel(id: host.channel.id)) + #expect(reopened.textRulesID == conversationID) + #expect(reopened.textRulesOverride == .on) + } + @MainActor private final class Host { let preferences = IsolatedUserDefaults() @@ -44,16 +66,25 @@ struct ChatChannelInfoPresentationTests { let window: UIWindow private(set) var controller: UIViewController = .init() - init(initialPin: Bool) throws { + init(initialPin: Bool, legacyChannel: Bool = false) throws { let container = try PersistenceStore.createContainer(inMemory: true) - appState = AppState(modelContainer: container, isPlaceholder: true, defaults: preferences.defaults) - let device = DeviceDTO(from: Device(publicKey: Data(repeating: 1, count: ProtocolLimits.publicKeySize), nodeName: "Radio")) - appState.connectionManager.setTestState(connectionState: .ready, connectedDevice: .some(device)) - appState.connectionManager.persistConnection(deviceID: device.id, radioID: device.radioID, deviceName: device.nodeName) - channel = ChannelDTO(from: Channel( + let device = Device(publicKey: Data(repeating: 1, count: ProtocolLimits.publicKeySize), nodeName: "Radio") + let model = Channel( radioID: device.radioID, index: 1, name: "General", secret: Data(repeating: 1, count: ProtocolLimits.channelSecretSize), isPinned: initialPin - )) + ) + if legacyChannel { + model.textRulesID = nil + let context = ModelContext(container) + context.insert(device) + context.insert(model) + try context.save() + } + let deviceDTO = DeviceDTO(from: device) + channel = ChannelDTO(from: model) + appState = AppState(modelContainer: container, isPlaceholder: true, defaults: preferences.defaults) + appState.connectionManager.setTestState(connectionState: .ready, connectedDevice: .some(deviceDTO)) + appState.connectionManager.persistConnection(deviceID: deviceDTO.id, radioID: deviceDTO.radioID, deviceName: deviceDTO.nodeName) let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) window = UIWindow(windowScene: scene) window.frame = ChatChannelInfoPresentationTests.viewport diff --git a/MC1Tests/Views/SettingsRouteAdmissionTests.swift b/MC1Tests/Views/SettingsRouteAdmissionTests.swift index 6cee2f2ea0..f17df58cf0 100644 --- a/MC1Tests/Views/SettingsRouteAdmissionTests.swift +++ b/MC1Tests/Views/SettingsRouteAdmissionTests.swift @@ -13,6 +13,11 @@ struct SettingsRouteAdmissionTests { #expect(SettingsSubpage.publicKey(key).isAdmitted(for: .deviceInfo, device: device)) #expect(SettingsSubpage.configExport.isAdmitted(for: .advanced, device: device)) #expect(SettingsSubpage.configImport.isAdmitted(for: .advanced, device: device)) + #expect(SettingsSubpage.textRules.isAdmitted(for: .chats, device: nil)) + #expect(SettingsSubpage.textRuleChats(.room).isAdmitted(for: .chats, device: nil)) + #expect(SettingsSubpage.recentlyBlocked.isAdmitted(for: .chats, device: nil)) + #expect(!SettingsSubpage.textRules.isAdmitted(for: .advanced, device: device)) + #expect(!SettingsSubpage.recentlyBlocked.isAdmitted(for: .advanced, device: device)) #expect(SettingsSubpage.blockedChannelSenders.isAdmitted(for: .chats, device: device)) #expect(SettingsSubpage.blockedContacts.isAdmitted(for: .chats, device: device)) #expect(SettingsSubpage.trustedContacts.isAdmitted(for: .advanced, device: device)) diff --git a/MeshCore/Sources/MeshCore/Protocols/MessageFetchSessionOps.swift b/MeshCore/Sources/MeshCore/Protocols/MessageFetchSessionOps.swift index b8446c671b..de168c7695 100644 --- a/MeshCore/Sources/MeshCore/Protocols/MessageFetchSessionOps.swift +++ b/MeshCore/Sources/MeshCore/Protocols/MessageFetchSessionOps.swift @@ -15,6 +15,12 @@ public protocol MessageFetchSessionOps: Actor { /// Stops the automatic fetching started by ``startAutoMessageFetching()``. func stopAutoMessageFetching() + + /// Blocks new queue reads and lets an already-issued read finish. + func suspendMessageFetching() async throws + + /// Allows queue reads and drains any backlog when auto-fetch is enabled. + func resumeMessageFetching() } // MARK: - Default Implementations diff --git a/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift b/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift index 54b2bb094e..9c7a0ffb0b 100644 --- a/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift +++ b/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift @@ -34,14 +34,12 @@ public protocol RemoteAccessSessionOps: Actor { timestamp: Date ) async throws -> MessageSentInfo - /// Sends a keep-alive request to a room server with the client's sync watermark. - /// - /// - Parameters: - /// - publicKey: The full 32-byte public key of the room server. - /// - syncSince: The client's last-received message timestamp. - /// - Returns: Information about the sent message. - /// - Throws: `MeshCoreError` if the device doesn't respond. - func sendKeepAlive(to publicKey: Data, syncSince: UInt32) async throws -> MessageSentInfo + /// Resolves the room bookmark after serializing the request and checks ownership just before sending. + func sendKeepAlive( + to publicKey: Data, + syncSince: @escaping @Sendable () async throws -> UInt32, + beforeSend: @escaping @Sendable () throws -> Void + ) async throws -> MessageSentInfo /// Requests owner information from a repeater using the binary protocol. /// @@ -127,6 +125,11 @@ public protocol RemoteAccessSessionOps: Actor { // MARK: - Default Implementations public extension RemoteAccessSessionOps { + /// Sends a keep-alive with a fixed watermark. + func sendKeepAlive(to publicKey: Data, syncSince: UInt32) async throws -> MessageSentInfo { + try await sendKeepAlive(to: publicKey, syncSince: { syncSince }, beforeSend: {}) + } + /// Sends a command message stamped with the current time. func sendCommand( to destination: Data, diff --git a/MeshCore/Sources/MeshCore/Protocols/SessionEventStreaming.swift b/MeshCore/Sources/MeshCore/Protocols/SessionEventStreaming.swift index 5766385b4b..9e7f6d246a 100644 --- a/MeshCore/Sources/MeshCore/Protocols/SessionEventStreaming.swift +++ b/MeshCore/Sources/MeshCore/Protocols/SessionEventStreaming.swift @@ -25,6 +25,12 @@ public protocol SessionEventStreaming: Actor { /// - Returns: An async stream yielding only events that pass `filter`. func events(filter: EventFilter) async -> AsyncStream + /// Subscribes to filtered events with a handle for finishing the stream. + func eventsTracked(filter: EventFilter) async -> (id: UUID, stream: AsyncStream) + + /// Finishes a tracked stream, letting its consumer drain buffered events. + func finishEvents(id: UUID) async + /// Waits for an event matching an ``EventFilter`` with timeout. /// /// - Parameters: diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift index 4bcd07ab86..fa1279b0b2 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift @@ -182,6 +182,7 @@ public extension MeshCoreSession { /// channel datagram (firmware v11+), or ``MessageResult/noMoreMessages``. /// - Throws: ``MeshCoreError`` if the fetch fails. func getMessage(timeout: TimeInterval? = nil) async throws -> MessageResult { + guard !isMessageFetchingSuspended else { throw CancellationError() } getMessageCallerCountForTest += 1 defer { getMessageCallerCountForTest -= 1 } @@ -583,32 +584,32 @@ public extension MeshCoreSession { // MARK: - Keep-Alive - /// Sends a keep-alive request to a room server with the client's sync watermark. - /// - /// The companion radio passes the payload through to the mesh layer, producing: - /// `[tag(4)][REQ_TYPE_KEEP_ALIVE(1)][sync_since(4)]` — 9 bytes total. - /// - /// The room server uses `sync_since` as a force-resync hint to update the client's - /// message watermark. The normal push-and-ACK cycle also advances `sync_since` - /// independently, so this serves as a correction mechanism. - /// - /// - Parameters: - /// - publicKey: The full 32-byte public key of the room server. - /// - syncSince: The client's last-received message timestamp (little-endian on wire). - /// - Returns: Information about the sent message. - /// - Throws: ``MeshCoreError/timeout`` if the device doesn't respond. - func sendKeepAlive(to publicKey: Data, syncSince: UInt32) async throws -> MessageSentInfo { + /// Sends the room bookmark as a four-byte little-endian value. + /// A zero bookmark preserves the server’s replay cursor. + func sendKeepAlive( + to publicKey: Data, + syncSince: @escaping @Sendable () async throws -> UInt32, + beforeSend: @escaping @Sendable () throws -> Void + ) async throws -> MessageSentInfo { try requireFullPublicKey(publicKey, operation: "sendKeepAlive") - var syncSinceLE = syncSince.littleEndian - let payload = withUnsafeBytes(of: &syncSinceLE) { Data($0) } - let data = PacketBuilder.binaryRequest(to: publicKey, type: .keepAlive, payload: payload) - return try await sendAndWaitWithError( - data, - matching: { event in - if case let .messageSent(info) = event { return info } - return nil - }, - errorMatcher: Self.deviceErrorMatcher - ) + let cancelled = OSAllocatedUnfairLock(initialState: false) + + return try await withTaskCancellationHandler { + try await requestResponseSerializer.withSerialization { [self] in + var watermark = try await syncSince().littleEndian + let payload = withUnsafeBytes(of: &watermark) { Data($0) } + let data = PacketBuilder.binaryRequest(to: publicKey, type: .keepAlive, payload: payload) + return try await sendAndMatchHoldingSerialization(data, beforeSend: { + if cancelled.withLock({ $0 }) { throw CancellationError() } + try beforeSend() + }) { event in + if let error = Self.deviceErrorMatcher(event) { return .failure(error) } + if case let .messageSent(info) = event { return .success(info) } + return .ignore + } + } + } onCancel: { + cancelled.withLock { $0 = true } + } } } diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift index 9f54bed757..76132cdc50 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift @@ -121,6 +121,7 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { private var autoMessageDrainTask: Task? private var autoContactRefreshTask: Task? private var isAutoFetchingMessages = false + private(set) var isMessageFetchingSuspended = false private var autoMessageDrainRequested = false private var autoContactRefreshRequested = false var inFlightGetMessage: Task? @@ -210,6 +211,7 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { return } + isMessageFetchingSuspended = false logger.info("Starting MeshCore session...") if let reconnectingAttempt { updateConnectionState(.reconnecting(attempt: max(1, reconnectingAttempt))) @@ -318,7 +320,11 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { await dispatcher.subscribeTracked() } - /// Finishes a subscription created via ``eventsTracked()``. + public func eventsTracked(filter: EventFilter) async -> (id: UUID, stream: AsyncStream) { + await dispatcher.subscribeTracked(filter: filter.matches) + } + + /// Finishes a tracked event subscription. /// /// Causes the corresponding `for await` loop to exit. Safe to call with an unknown id. public func finishEvents(id: UUID) async { @@ -361,6 +367,25 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { autoMessageDrainTask = nil } + public func suspendMessageFetching() async throws { + isMessageFetchingSuspended = true + autoMessageDrainRequested = false + do { + _ = try await inFlightGetMessage?.value + } catch { + resumeMessageFetching() + throw error + } + await autoMessageDrainTask?.value + } + + public func resumeMessageFetching() { + isMessageFetchingSuspended = false + if isAutoFetchingMessages { + requestAutoMessageDrain() + } + } + private func autoMessageFetchLoop(events: AsyncStream) async { for await event in events { guard isAutoFetchingMessages else { break } @@ -373,6 +398,7 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { } private func requestAutoMessageDrain() { + guard !isMessageFetchingSuspended else { return } autoMessageDrainRequested = true guard autoMessageDrainTask == nil else { return } @@ -389,7 +415,7 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { autoMessageDrainRequested = false do { - while isAutoFetchingMessages, !Task.isCancelled { + while isAutoFetchingMessages, !isMessageFetchingSuspended, !Task.isCancelled { let result = try await getMessage() if case .noMoreMessages = result { break } try await Task.sleep(for: .milliseconds(100)) diff --git a/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionGetChannelsTests.swift b/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionGetChannelsTests.swift index ed15e7acf0..894a709707 100644 --- a/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionGetChannelsTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionGetChannelsTests.swift @@ -7,6 +7,57 @@ import Testing /// window/refill bound and the capability fallback to serial reads. @Suite("MeshCoreSession getChannels pipeline") struct MeshCoreSessionGetChannelsTests { + @Test + func `channel reads and queued text use stock framing`() async throws { + let transport = MockTransport() + await transport.setSupportsWriteWithoutResponse(true) + let session = MeshCoreSession(transport: transport, configuration: pipelineConfig()) + try await startSession(session, transport: transport) + + let query = Task { try await session.queryDevice() } + try await waitUntil("expected stock device query") { + await transport.sentData.last == Data([0x16, 0x03]) + } + var info = Data([0x0D, 0x0E]) + info.append(Data(repeating: 0, count: 80)) + await transport.simulateReceive(info) + #expect(try await query.value.firmwareVersion == 14) + + let secret = Data(repeating: 0xAA, count: 16) + let channel = makeChannelInfoPacket(index: 2, name: "two", secret: secret) + let serial = Task { try await session.getChannel(index: 2) } + try await waitUntil("expected stock serial channel read") { + await transport.sentData.last == Data([0x1F, 0x02]) + } + await transport.simulateReceive(channel) + #expect(try await serial.value.secret == secret) + + let pipeline = Task { try await session.getChannels(indices: [2]) } + try await waitUntil("expected stock pipelined channel read") { + let sent = await transport.sentData + return sent.count == 4 && sent.last == Data([0x1F, 0x02]) + } + await transport.simulateReceive(channel) + #expect(try await pipeline.value.received.first?.secret == secret) + + let message = Task { try await session.getMessage() } + try await waitUntil("expected stock queued message fetch") { + await transport.sentData.last == Data([0x0A]) + } + var frame = Data([0x11, 0xFC, 0x00, 0x00, 0x02, 0x01, 0x00, 0x20, 0x10, 0x00, 0x00]) + let text = String(repeating: "🙂", count: 40) + frame.append(contentsOf: text.utf8) + await transport.simulateReceive(frame) + guard case let .channelMessage(result) = try await message.value else { + Issue.record("Expected queued channel text") + return + } + #expect(result.channelIndex == 2) + #expect(result.text == text) + #expect(result.snr == -1) + await session.stop() + } + // MARK: - Gate #1: correctness with gaps @Test From 983c585681b0bb54393474067508983fb6eb3956 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:57:36 -0800 Subject: [PATCH 02/10] style: match the CI swiftformat version --- .../Services/RoomServerService.swift | 2 +- .../SyncCoordinator+MessageHandlers.swift | 26 +++++++++---------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/MC1Services/Sources/MC1Services/Services/RoomServerService.swift b/MC1Services/Sources/MC1Services/Services/RoomServerService.swift index e17d965087..65d1bf350f 100644 --- a/MC1Services/Sources/MC1Services/Services/RoomServerService.swift +++ b/MC1Services/Sources/MC1Services/Services/RoomServerService.swift @@ -449,7 +449,7 @@ public actor RoomServerService { let preference = await textRulesPreference() guard scope.isCurrent, scope.radioID == radioID, let room = try await dataStore.fetchRemoteNodeSessions(radioID: radioID) - .first(where: { $0.publicKey.prefix(6) == senderPublicKeyPrefix && $0.isRoom }) else { + .first(where: { $0.publicKey.prefix(6) == senderPublicKeyPrefix && $0.isRoom }) else { return nil } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index 3ab2ef9041..7c2a804119 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -87,7 +87,7 @@ extension SyncCoordinator { let prefix = message.senderPublicKeyPrefix guard !prefix.isEmpty, let materialized = await dependencies.advertisementService - .materializeContactForPendingAdvert(matchingPrefix: prefix, scope: scope) + .materializeContactForPendingAdvert(matchingPrefix: prefix, scope: scope) else { return kind } @@ -362,9 +362,9 @@ extension SyncCoordinator { } do { guard try await dependencies.dataStore.saveLegacyChannelMessage( - messageDTO, scope: legacyScope, conversationID: channel?.textRulesID - ), - legacyScope?.isCurrent != false else { return } + messageDTO, scope: legacyScope, conversationID: channel?.textRulesID + ), + legacyScope?.isCurrent != false else { return } let savedDTO = try await harvestAndRefreshChannelMessage( messageDTO: messageDTO, radioID: radioID, @@ -577,15 +577,15 @@ extension SyncCoordinator { let timestamp = UInt32(message.senderTimestamp.timeIntervalSince1970) do { guard let saved = try await dependencies.roomServerService.handleIncomingMessage( - senderPublicKeyPrefix: message.senderPublicKeyPrefix, - timestamp: timestamp, - authorPrefix: Data(authorPrefix), - text: message.text, - scope: scope - ), let room = try await dependencies.dataStore.fetchRemoteNodeSession(id: saved.room.id), - room.radioID == saved.room.radioID, - room.textRulesID == saved.room.textRulesID, - scope.isCurrent else { return } + senderPublicKeyPrefix: message.senderPublicKeyPrefix, + timestamp: timestamp, + authorPrefix: Data(authorPrefix), + text: message.text, + scope: scope + ), let room = try await dependencies.dataStore.fetchRemoteNodeSession(id: saved.room.id), + room.radioID == saved.room.radioID, + room.textRulesID == saved.room.textRulesID, + scope.isCurrent else { return } await dependencies.notificationService.postRoomMessageNotification( roomName: room.name, From e6f48a30d1a0bc27d3c11b80ba1435703d1ed4f1 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:55:40 -0800 Subject: [PATCH 03/10] refactor: unify text rules message handling - Require a receive scope through delivery so each layer can reject stale work. - Save rules directly and update DTO copies to avoid rebuilding records. - Verify that Text Rules settings stay out of backups and remove duplicate test cases. --- MC1/State/MessageEvent.swift | 6 +- MC1/State/MessageEventDispatcher.swift | 16 +-- .../ViewModel/ChatViewModel+EventStream.swift | 12 +- .../Rooms/RoomConversationViewModel.swift | 2 +- .../Settings/Sections/NewTextRuleSheet.swift | 22 +-- .../ConnectionManager+TextRules.swift | 1 - .../Sources/MC1Services/Models/Channel.swift | 102 ++++---------- .../Sources/MC1Services/Models/Contact.swift | 72 ++-------- .../Models/RemoteNodeSession.swift | 36 +---- .../Models/TextRulesPreference.swift | 1 - .../MessagePollingServiceProtocol.swift | 2 +- .../Persistence/ContactPersisting.swift | 42 ++++++ .../Persistence/MessagePersisting.swift | 51 ++++++- .../Persistence/ReactionPersisting.swift | 15 ++ .../Protocols/PersistenceStoreProtocol.swift | 96 +------------ .../Services/MessagePollingService.swift | 6 +- .../Services/NotificationService.swift | 4 +- .../PersistenceStore+ChannelReceive.swift | 4 +- .../Services/PersistenceStore+Messages.swift | 4 +- .../Sync/SyncCoordinator+HandlerHelpers.swift | 37 ++--- .../SyncCoordinator+MessageHandlers.swift | 129 +++++++----------- .../MC1Services/Sync/SyncDataEvent.swift | 4 +- .../BackupIntegrationTests.swift | 43 ++++++ .../Mocks/MockMessagePollingService.swift | 4 +- .../Services/RoomPostTextRulesTests.swift | 16 +-- ...SyncCoordinatorBackgroundUnreadTests.swift | 10 +- .../SyncCoordinatorMessageHandlerTests.swift | 39 +++--- .../SyncCoordinatorTests.swift | 2 +- .../TextRulesOwnershipTests.swift | 2 - .../TextRulesPreferenceTests.swift | 16 +-- .../ConnectionStatusLifecycleTests.swift | 2 +- .../RecentlyBlockedPersistenceTests.swift | 2 - .../ChatViewModelPaginationTests.swift | 3 +- .../Chats/ChatReconnectPopulateTests.swift | 11 +- .../Chats/ChatViewModelFailedSendTests.swift | 10 +- .../Protocols/RemoteAccessSessionOps.swift | 1 - .../MeshCore/Session/MeshCoreSession.swift | 5 +- .../MeshCoreSessionGetChannelsTests.swift | 51 ------- 38 files changed, 351 insertions(+), 530 deletions(-) diff --git a/MC1/State/MessageEvent.swift b/MC1/State/MessageEvent.swift index 03696dd6ad..b927812884 100644 --- a/MC1/State/MessageEvent.swift +++ b/MC1/State/MessageEvent.swift @@ -8,11 +8,11 @@ import MC1Services /// exhaustively (no `default`) so a new case becomes a compile error /// rather than a silent skip. enum MessageEvent: Equatable { - case directMessageReceived(message: MessageDTO, contact: ContactDTO, scope: ReceiveScope? = nil) + case directMessageReceived(message: MessageDTO, contact: ContactDTO, scope: ReceiveScope) case channelMessageReceived( - message: MessageDTO, channelIndex: UInt8, legacyScope: ReceiveScope? = nil + message: MessageDTO, channelIndex: UInt8, scope: ReceiveScope ) - case roomMessageReceived(message: RoomMessageDTO, sessionID: UUID, roomID: UUID? = nil, scope: ReceiveScope? = nil) + case roomMessageReceived(message: RoomMessageDTO, sessionID: UUID, roomID: UUID? = nil, scope: ReceiveScope) /// Fired when a message's status resolves to .sent or .delivered for an /// original (non-resend) send. `roundTripTime` is supplied only when firmware /// reports it (.delivered via end-to-end ACK); .sent transitions and diff --git a/MC1/State/MessageEventDispatcher.swift b/MC1/State/MessageEventDispatcher.swift index cda36ca558..2981f17ea4 100644 --- a/MC1/State/MessageEventDispatcher.swift +++ b/MC1/State/MessageEventDispatcher.swift @@ -60,20 +60,18 @@ final class MessageEventDispatcher { guard let appState, !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } switch event { case let .directMessageReceived(message, contact, scope): - if let scope { - let store = appState.connectionManager.persistenceStore - guard await (try? store.currentDirectMessageContact(contact, scope: scope)) != nil, - scope.isCurrent else { continue } - guard !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } - } + let store = appState.connectionManager.persistenceStore + guard await (try? store.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { continue } + guard !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } stream.send(.directMessageReceived(message: message, contact: contact, scope: scope)) // Keep a closed conversation's warm coordinator current so a reopen // renders the new tail on the first frame (no-op when open or cold). appState.ensureChatPrewarmRefresher().noteDirectMessage(contact: contact) - case let .channelMessageReceived(message, channelIndex, legacyScope): - guard legacyScope?.isCurrent != false else { continue } + case let .channelMessageReceived(message, channelIndex, scope): + guard scope.isCurrent else { continue } stream.send(.channelMessageReceived( - message: message, channelIndex: channelIndex, legacyScope: legacyScope + message: message, channelIndex: channelIndex, scope: scope )) appState.ensureChatPrewarmRefresher().noteChannelMessage( radioID: message.radioID, diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift index 0d6edb22d0..390df9b75c 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift @@ -13,19 +13,17 @@ extension ChatViewModel { switch event { case let .directMessageReceived(message, contact, scope): guard let current = currentContact, current.id == contact.id else { return } - if let scope { - guard let dataStore, - await (try? dataStore.currentDirectMessageContact(contact, scope: scope)) != nil, - scope.isCurrent, currentContact?.id == contact.id else { return } - } + guard let dataStore, + await (try? dataStore.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent, currentContact?.id == contact.id else { return } admitIncomingMessage(message, isChannelMessage: false) recordIncomingMentionIfNeeded(message) - case let .channelMessageReceived(message, channelIndex, legacyScope): + case let .channelMessageReceived(message, channelIndex, scope): guard let channel = currentChannel, channel.index == channelIndex, message.radioID == channel.radioID, - legacyScope?.isCurrent != false else { return } + scope.isCurrent else { return } admitIncomingMessage(message, isChannelMessage: true) recordIncomingMentionIfNeeded(message) diff --git a/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift b/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift index 83b6f43262..7bc352729d 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift @@ -224,7 +224,7 @@ final class RoomConversationViewModel { // burst of incoming room messages triggers one DB sync, not N. guard sessionID == session.id, roomID == nil || roomID == session.textRulesID, - scope?.isCurrent != false else { return } + scope.isCurrent else { return } appendMessageIfNew(message) scheduleCoalescedReload() diff --git a/MC1/Views/Settings/Sections/NewTextRuleSheet.swift b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift index 2395093850..b64c595c4f 100644 --- a/MC1/Views/Settings/Sections/NewTextRuleSheet.swift +++ b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift @@ -8,7 +8,6 @@ struct NewTextRuleSheet: View { @State private var phrase = "" @State private var lookIn = TextRulesPreference.Rule.LookIn.message @State private var match = TextRulesPreference.Rule.Match.contains - @State private var isSaving = false @State private var errorMessage: String? var body: some View { @@ -38,7 +37,6 @@ struct NewTextRuleSheet: View { Text(L10n.Settings.TextRules.New.deliveryFooter) } } - .disabled(isSaving) .themedRowBackground(theme) } .themedCanvas(theme) @@ -47,30 +45,24 @@ struct NewTextRuleSheet: View { .toolbar { ToolbarItem(placement: .cancellationAction) { Button(L10n.Localizable.Common.cancel) { dismiss() } - .disabled(isSaving) } ToolbarItem(placement: .confirmationAction) { Button(L10n.Contacts.Contacts.Add.add, action: add) - .disabled(isSaving || phrase.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + .disabled(phrase.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } } .errorAlert($errorMessage) } - .interactiveDismissDisabled(isSaving) } private func add() { let rule = TextRulesPreference.Rule(phrase: phrase, lookIn: lookIn, match: match) - guard !isSaving, rule.isValid else { return } - isSaving = true - Task { - defer { isSaving = false } - do { - try appState.connectionManager.updateTextRules { $0.append(rule) } - dismiss() - } catch { - errorMessage = L10n.Settings.TextRules.saveFailed - } + guard rule.isValid else { return } + do { + try appState.connectionManager.updateTextRules { $0.append(rule) } + dismiss() + } catch { + errorMessage = L10n.Settings.TextRules.saveFailed } } } diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift index 4c3fe17247..2d7cdf3e49 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift @@ -35,7 +35,6 @@ extension ConnectionManager { update(&preference) guard preference.isValid else { throw CocoaError(.fileWriteInapplicableStringEncoding) } guard preference != textRulesPreference else { return } - preference.revision = UUID() let data = try JSONEncoder().encode(preference) try FileManager.default.createDirectory( at: textRulesURL.deletingLastPathComponent(), diff --git a/MC1Services/Sources/MC1Services/Models/Channel.swift b/MC1Services/Sources/MC1Services/Models/Channel.swift index eeab3d0384..fc8c691268 100644 --- a/MC1Services/Sources/MC1Services/Models/Channel.swift +++ b/MC1Services/Sources/MC1Services/Models/Channel.swift @@ -243,21 +243,21 @@ public extension Channel { /// A sendable snapshot of Channel for cross-actor transfers public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { - public let id: UUID + public private(set) var id: UUID public var radioID: UUID public internal(set) var textRulesID: UUID? public internal(set) var textRulesOverride: TextRulesPreference.Override = .inherit - public let index: UInt8 + public private(set) var index: UInt8 public let name: String public let secret: Data public let isEnabled: Bool public let lastMessageDate: Date? public let unreadCount: Int public let unreadMentionCount: Int - public let notificationLevel: NotificationLevel - public let isPinned: Bool - public let floodScopeModeRawValue: String - public let regionScope: String? + public private(set) var notificationLevel: NotificationLevel + public private(set) var isPinned: Bool + public private(set) var floodScopeModeRawValue: String + public private(set) var regionScope: String? /// Convenience property for checking if muted public var isMuted: Bool { @@ -380,103 +380,49 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { /// Returns a copy with only `notificationLevel` changed. public func with(notificationLevel: NotificationLevel) -> ChannelDTO { - var copy = ChannelDTO( - id: id, radioID: radioID, index: index, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScope: floodScope - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.notificationLevel = notificationLevel return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> ChannelDTO { - var copy = ChannelDTO( - id: id, radioID: radioID, index: index, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScope: floodScope - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.isPinned = isPinned return copy } /// Returns a copy with only the flood-scope preference changed. public func with(floodScope: ChannelFloodScope) -> ChannelDTO { - var copy = ChannelDTO( - id: id, radioID: radioID, index: index, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScope: floodScope - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + let storage = ChannelFloodScopeStorage.decompose(floodScope) + copy.floodScopeModeRawValue = storage.mode.rawValue + copy.regionScope = storage.regionName return copy } - /// Returns a copy placed at a different slot `index`, forwarding every other raw - /// storage field verbatim. Used by backup import to relocate a channel whose secret - /// has no local match onto a free slot without routing through the normalizing - /// ``ChannelFloodScope`` accessor (preserving pre-migration flood-scope rows). + /// Relocates the channel to a different slot while preserving raw flood-scope values for migration. func with(index newIndex: UInt8) -> ChannelDTO { - var copy = ChannelDTO( - id: id, radioID: radioID, index: newIndex, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScopeModeRawValue: floodScopeModeRawValue, - regionScope: regionScope - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.index = newIndex return copy } - /// Returns a copy with a fresh surrogate `id`, forwarding every other raw storage - /// field verbatim. Used by backup import so a relocated/non-matching channel can never - /// upsert a live local channel that happens to share the backup's `@Attribute(.unique)` - /// id. Channel has no inbound foreign key, so re-issuing the id breaks no linkage; it - /// uses the raw initializer to preserve pre-migration flood-scope rows (see ``init(dto:)``). + /// Replaces the row ID so backup import cannot overwrite a different channel with the same ID. func with(id newID: UUID) -> ChannelDTO { - var copy = ChannelDTO( - id: newID, radioID: radioID, index: index, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScopeModeRawValue: floodScopeModeRawValue, - regionScope: regionScope - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.id = newID return copy } - /// Returns a copy with only the raw `regionScope` column changed. This is the - /// low-level bypass used for tests that must simulate malformed on-disk state; - /// production code should go through ``with(floodScope:)``. + /// Changes the raw region name without normalizing the stored flood scope. func with(regionScope: String?) -> ChannelDTO { - var copy = ChannelDTO( - id: id, radioID: radioID, index: index, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScopeModeRawValue: floodScopeModeRawValue, - regionScope: regionScope - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.regionScope = regionScope return copy } - /// Low-level init that sets both raw storage fields directly. Kept `internal` - /// to prevent callers from constructing invalid combinations; used by - /// ``with(regionScope:)`` and migration tests. + /// Accepts raw flood-scope values, including combinations that require migration. init( id: UUID, radioID: UUID, diff --git a/MC1Services/Sources/MC1Services/Models/Contact.swift b/MC1Services/Sources/MC1Services/Models/Contact.swift index 042795d58e..34a155fe36 100644 --- a/MC1Services/Sources/MC1Services/Models/Contact.swift +++ b/MC1Services/Sources/MC1Services/Models/Contact.swift @@ -325,15 +325,15 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, public let lastHeardTimestamp: UInt32? public let nickname: String? public let isBlocked: Bool - public let isMuted: Bool - public let isFavorite: Bool - public let isPinned: Bool + public private(set) var isMuted: Bool + public private(set) var isFavorite: Bool + public private(set) var isPinned: Bool public let lastMessageDate: Date? public let unreadCount: Int public let unreadMentionCount: Int public let ocvPreset: String? public let customOCVArrayString: String? - public let avatarImageData: Data? + public private(set) var avatarImageData: Data? /// A missing `isPinned` key decodes as `isFavorite`. An explicit false stays unpinned. private enum CodingKeys: String, CodingKey { @@ -561,77 +561,29 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, /// Returns a copy with only `isMuted` changed. public func with(isMuted: Bool) -> ContactDTO { - var copy = ContactDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, - outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, - latitude: latitude, longitude: longitude, lastModified: lastModified, - lastHeardTimestamp: lastHeardTimestamp, - nickname: nickname, isBlocked: isBlocked, isMuted: isMuted, - isFavorite: isFavorite, isPinned: isPinned, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, - avatarImageData: avatarImageData - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.isMuted = isMuted return copy } /// Returns a copy with only `isFavorite` changed. public func with(isFavorite: Bool) -> ContactDTO { - var copy = ContactDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, - outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, - latitude: latitude, longitude: longitude, lastModified: lastModified, - lastHeardTimestamp: lastHeardTimestamp, - nickname: nickname, isBlocked: isBlocked, isMuted: isMuted, - isFavorite: isFavorite, isPinned: isPinned, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, - avatarImageData: avatarImageData - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.isFavorite = isFavorite return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> ContactDTO { - var copy = ContactDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, - outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, - latitude: latitude, longitude: longitude, lastModified: lastModified, - lastHeardTimestamp: lastHeardTimestamp, - nickname: nickname, isBlocked: isBlocked, isMuted: isMuted, - isFavorite: isFavorite, isPinned: isPinned, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, - avatarImageData: avatarImageData - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.isPinned = isPinned return copy } /// Returns a copy with only `avatarImageData` changed. public func with(avatarImageData: Data?) -> ContactDTO { - var copy = ContactDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, - outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, - latitude: latitude, longitude: longitude, lastModified: lastModified, - lastHeardTimestamp: lastHeardTimestamp, - nickname: nickname, isBlocked: isBlocked, isMuted: isMuted, - isFavorite: isFavorite, isPinned: isPinned, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, - avatarImageData: avatarImageData - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.avatarImageData = avatarImageData return copy } diff --git a/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift b/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift index 07a8094d38..c39b77235e 100644 --- a/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift +++ b/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift @@ -268,8 +268,8 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, public let lastUptimeSeconds: UInt32? public let lastNoiseFloor: Int16? public let unreadCount: Int - public let notificationLevel: NotificationLevel - public let isPinned: Bool + public private(set) var notificationLevel: NotificationLevel + public private(set) var isPinned: Bool /// Convenience property for checking if muted public var isMuted: Bool { @@ -423,39 +423,15 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, /// Returns a copy with only `notificationLevel` changed. public func with(notificationLevel: NotificationLevel) -> RemoteNodeSessionDTO { - var copy = RemoteNodeSessionDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - role: role, latitude: latitude, longitude: longitude, - isConnected: isConnected, permissionLevel: permissionLevel, - lastConnectedDate: lastConnectedDate, - lastBatteryMillivolts: lastBatteryMillivolts, - lastUptimeSeconds: lastUptimeSeconds, lastNoiseFloor: lastNoiseFloor, - unreadCount: unreadCount, notificationLevel: notificationLevel, - isPinned: isPinned, lastRxAirtimeSeconds: lastRxAirtimeSeconds, - neighborCount: neighborCount, lastSyncTimestamp: lastSyncTimestamp, - lastMessageDate: lastMessageDate - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.notificationLevel = notificationLevel return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> RemoteNodeSessionDTO { - var copy = RemoteNodeSessionDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - role: role, latitude: latitude, longitude: longitude, - isConnected: isConnected, permissionLevel: permissionLevel, - lastConnectedDate: lastConnectedDate, - lastBatteryMillivolts: lastBatteryMillivolts, - lastUptimeSeconds: lastUptimeSeconds, lastNoiseFloor: lastNoiseFloor, - unreadCount: unreadCount, notificationLevel: notificationLevel, - isPinned: isPinned, lastRxAirtimeSeconds: lastRxAirtimeSeconds, - neighborCount: neighborCount, lastSyncTimestamp: lastSyncTimestamp, - lastMessageDate: lastMessageDate - ) - copy.textRulesID = textRulesID - copy.textRulesOverride = textRulesOverride + var copy = self + copy.isPinned = isPinned return copy } diff --git a/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift b/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift index 7799d5ca2f..92790d5879 100644 --- a/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift +++ b/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift @@ -135,7 +135,6 @@ public struct TextRulesPreference: Sendable, Codable, Equatable { private static let comparisonLocale = Locale(identifier: "en_US_POSIX") - public internal(set) var revision = UUID() public private(set) var rules: [Rule] = [] private var selections: [Kind: Selection] = [ .publicChannel: .all, diff --git a/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift b/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift index 1abde9cd14..bbe2c70750 100644 --- a/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift +++ b/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift @@ -46,7 +46,7 @@ protocol MessagePollingServiceProtocol: Actor { func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) /// Install the handler invoked for each incoming channel message. - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void) + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) /// Install the handler invoked for each incoming signed room message. func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift index 6307daec4c..220b02cdf4 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift @@ -2,6 +2,23 @@ import Foundation /// Store operations for contact rows, contact mention tracking, and blocked senders. public protocol ContactPersisting: Actor { + func currentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) async throws -> ContactDTO? + + func materializeContactForDirectMessage( + from frame: ContactFrame, + receivedAt: Date, + scope: ReceiveScope + ) async throws -> ContactDTO? + + func touchDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope, at date: Date) async throws + + func updateContactAfterDirectMessage( + _ message: MessageDTO, + contact: ContactDTO, + scope: ReceiveScope, + isViewingContact: Bool + ) async throws -> ContactDTO? + // MARK: - Contact Operations /// Fetch all confirmed contacts for a device @@ -238,3 +255,28 @@ public extension ContactPersisting where Self: MessagePersisting { [:] } } + +public extension ContactPersisting { + func currentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) async throws -> ContactDTO? { + nil + } + + func materializeContactForDirectMessage( + from frame: ContactFrame, + receivedAt: Date, + scope: ReceiveScope + ) async throws -> ContactDTO? { + nil + } + + func touchDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope, at date: Date) async throws {} + + func updateContactAfterDirectMessage( + _ message: MessageDTO, + contact: ContactDTO, + scope: ReceiveScope, + isViewingContact: Bool + ) async throws -> ContactDTO? { + nil + } +} diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift index 95e745174a..2957e47766 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift @@ -2,6 +2,26 @@ import Foundation /// Store operations for message rows and their pending-send queue entries. public protocol MessagePersisting: Actor { + // MARK: - Incoming Messages + + func captureReceiveScope(radioID: UUID, link: ReceiveScope.Lifetime) async throws -> ReceiveScope? + + func admitDirectMessage( + _ message: MessageDTO, + wireTextType: UInt8, + contact: ContactDTO?, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> DirectMessageAdmission + + func shouldSuppressChannelMessage( + _ message: MessageDTO, + frame: ChannelMessage, + channel: ChannelDTO, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> Bool + // MARK: - Message Operations /// Check if a message with this deduplication key already exists for the given radio. @@ -20,7 +40,7 @@ public protocol MessagePersisting: Actor { func saveMessage(_ dto: MessageDTO) async throws /// Saves only while the captured receive scope and any resolved channel identity are current. - func saveLegacyChannelMessage(_ dto: MessageDTO, scope: ReceiveScope?, conversationID: UUID?) async throws -> Bool + func saveReceivedChannelMessage(_ dto: MessageDTO, scope: ReceiveScope, conversationID: UUID?) async throws -> Bool /// Fetch a message by ID func fetchMessage(id: UUID) async throws -> MessageDTO? @@ -205,9 +225,34 @@ extension MessagePersisting { } public extension MessagePersisting { - func saveLegacyChannelMessage(_ dto: MessageDTO, scope: ReceiveScope?, conversationID: UUID?) async throws -> Bool { - if let scope, !scope.isCurrent || scope.radioID != dto.radioID { return false } + func saveReceivedChannelMessage(_ dto: MessageDTO, scope: ReceiveScope, conversationID: UUID?) async throws -> Bool { + guard scope.isCurrent, scope.radioID == dto.radioID else { return false } try await saveMessage(dto) return true } + + func captureReceiveScope(radioID: UUID, link: ReceiveScope.Lifetime) async throws -> ReceiveScope? { + guard link.isCurrent else { return nil } + return ReceiveScope(radioID: radioID, link: link, partition: .init()) + } + + func admitDirectMessage( + _ message: MessageDTO, + wireTextType: UInt8, + contact: ContactDTO?, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> DirectMessageAdmission { + .discarded + } + + func shouldSuppressChannelMessage( + _ message: MessageDTO, + frame: ChannelMessage, + channel: ChannelDTO, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> Bool { + false + } } diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/ReactionPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/ReactionPersisting.swift index 43857736ca..7de05aa8a4 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/ReactionPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/ReactionPersisting.swift @@ -2,6 +2,11 @@ import Foundation /// Store operations for message reactions and their summary cache. public protocol ReactionPersisting: Actor { + func admitDirectMessageReaction( + _ reaction: ReactionDTO, + contact: ContactDTO, + scope: ReceiveScope + ) async throws -> ReactionAdmission? /// Fetch reactions for a message, ordered by most recent first func fetchReactions(for messageID: UUID, limit: Int) async throws -> [ReactionDTO] @@ -30,3 +35,13 @@ extension ReactionPersisting { try await fetchReactions(for: messageID, limit: ReactionParser.summaryRowLimit) } } + +public extension ReactionPersisting { + func admitDirectMessageReaction( + _ reaction: ReactionDTO, + contact: ContactDTO, + scope: ReceiveScope + ) async throws -> ReactionAdmission? { + nil + } +} diff --git a/MC1Services/Sources/MC1Services/Protocols/PersistenceStoreProtocol.swift b/MC1Services/Sources/MC1Services/Protocols/PersistenceStoreProtocol.swift index 3bebd6b25f..e95476ab88 100644 --- a/MC1Services/Sources/MC1Services/Protocols/PersistenceStoreProtocol.swift +++ b/MC1Services/Sources/MC1Services/Protocols/PersistenceStoreProtocol.swift @@ -1,5 +1,3 @@ -import Foundation - /// Protocol for PersistenceStore to enable testability of dependent services. /// /// This protocol abstracts the SwiftData persistence operations used by services, @@ -35,96 +33,4 @@ public protocol PersistenceStoreProtocol: RoomPersisting, DiscoveredNodePersisting, ReactionPersisting, - NodeSnapshotPersisting { - func captureReceiveScope(radioID: UUID, link: ReceiveScope.Lifetime) async throws -> ReceiveScope? - func admitDirectMessage( - _ message: MessageDTO, - wireTextType: UInt8, - contact: ContactDTO?, - scope: ReceiveScope, - preference: TextRulesPreference? - ) async throws -> DirectMessageAdmission - func currentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) async throws -> ContactDTO? - func materializeContactForDirectMessage( - from frame: ContactFrame, - receivedAt: Date, - scope: ReceiveScope - ) async throws -> ContactDTO? - func touchDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope, at date: Date) async throws - func updateContactAfterDirectMessage( - _ message: MessageDTO, - contact: ContactDTO, - scope: ReceiveScope, - isViewingContact: Bool - ) async throws -> ContactDTO? - func admitDirectMessageReaction( - _ reaction: ReactionDTO, - contact: ContactDTO, - scope: ReceiveScope - ) async throws -> ReactionAdmission? - func shouldSuppressChannelMessage( - _ message: MessageDTO, - frame: ChannelMessage, - channel: ChannelDTO, - scope: ReceiveScope?, - preference: TextRulesPreference? - ) async throws -> Bool -} - -public extension PersistenceStoreProtocol { - func captureReceiveScope(radioID: UUID, link: ReceiveScope.Lifetime) async throws -> ReceiveScope? { - guard link.isCurrent else { return nil } - return ReceiveScope(radioID: radioID, link: link, partition: .init()) - } - - func admitDirectMessage( - _ message: MessageDTO, - wireTextType: UInt8, - contact: ContactDTO?, - scope: ReceiveScope, - preference: TextRulesPreference? - ) async throws -> DirectMessageAdmission { - .discarded - } - - func currentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) async throws -> ContactDTO? { - nil - } - - func materializeContactForDirectMessage( - from frame: ContactFrame, - receivedAt: Date, - scope: ReceiveScope - ) async throws -> ContactDTO? { - nil - } - - func touchDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope, at date: Date) async throws {} - - func updateContactAfterDirectMessage( - _ message: MessageDTO, - contact: ContactDTO, - scope: ReceiveScope, - isViewingContact: Bool - ) async throws -> ContactDTO? { - nil - } - - func admitDirectMessageReaction( - _ reaction: ReactionDTO, - contact: ContactDTO, - scope: ReceiveScope - ) async throws -> ReactionAdmission? { - nil - } - - func shouldSuppressChannelMessage( - _ message: MessageDTO, - frame: ChannelMessage, - channel: ChannelDTO, - scope: ReceiveScope?, - preference: TextRulesPreference? - ) async throws -> Bool { - false - } -} + NodeSnapshotPersisting {} diff --git a/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift index a8c4d9c24f..8b88fe21b7 100644 --- a/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift @@ -39,7 +39,7 @@ actor MessagePollingService { /// Handler for incoming channel messages. /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. - private var channelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void)? + private var channelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void)? /// Handler for signed messages (from room servers). /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. @@ -96,7 +96,7 @@ actor MessagePollingService { } /// Set handler for incoming channel messages - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void) { + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) { channelMessageHandler = handler } @@ -381,7 +381,7 @@ actor MessagePollingService { let preference = await textRulesPreference() let channel = try? await dataStore.fetchChannel(radioID: radioID, index: message.channelIndex) guard scope.isCurrent else { return } - await channelMessageHandler?(message, channel, context, preference, arrivedAt, scope) + await channelMessageHandler?(message, channel, context, scope, preference, arrivedAt) } } diff --git a/MC1Services/Sources/MC1Services/Services/NotificationService.swift b/MC1Services/Sources/MC1Services/Services/NotificationService.swift index f426c80709..e1e8345990 100644 --- a/MC1Services/Sources/MC1Services/Services/NotificationService.swift +++ b/MC1Services/Sources/MC1Services/Services/NotificationService.swift @@ -362,9 +362,9 @@ public final class NotificationService: NSObject { messageID: UUID, notificationLevel: NotificationLevel, hasSelfMention: Bool, - legacyScope: ReceiveScope? = nil + scope: ReceiveScope ) async { - guard legacyScope?.isCurrent != false, notificationLevel != .muted, notificationLevel != .mentionsOnly || hasSelfMention, isAuthorized else { return } + guard scope.isCurrent, notificationLevel != .muted, notificationLevel != .mentionsOnly || hasSelfMention, isAuthorized else { return } // Check granular preference (uses cached preferences) guard preferences.channelMessagesEnabled else { return } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift index 3fadb67767..9f4e92386d 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift @@ -5,10 +5,10 @@ public extension PersistenceStore { _ message: MessageDTO, frame: ChannelMessage, channel: ChannelDTO, - scope: ReceiveScope?, + scope: ReceiveScope, preference: TextRulesPreference? ) async throws -> Bool { - guard scope?.isCurrent != false, scope?.radioID == nil || scope?.radioID == message.radioID else { return true } + guard scope.isCurrent, scope.radioID == message.radioID else { return true } guard let conversationID = channel.textRulesID else { return false } guard let current = try fetchChannel(radioID: message.radioID, index: frame.channelIndex), current.textRulesID == conversationID else { return true } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift index 3b81f7945a..c4357799e9 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -397,8 +397,8 @@ public extension PersistenceStore { try modelContext.save() } - func saveLegacyChannelMessage(_ dto: MessageDTO, scope: ReceiveScope?, conversationID: UUID?) async throws -> Bool { - if let scope, !scope.isCurrent || scope.radioID != dto.radioID { return false } + func saveReceivedChannelMessage(_ dto: MessageDTO, scope: ReceiveScope, conversationID: UUID?) async throws -> Bool { + guard scope.isCurrent, scope.radioID == dto.radioID else { return false } if let conversationID, let index = dto.channelIndex, try fetchChannel(radioID: dto.radioID, index: index)?.textRulesID != conversationID { return false diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift index a938b40632..4ec3a51d48 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift @@ -115,7 +115,6 @@ extension SyncCoordinator { ) } - /// Updates the current Contact before publishing ordinary DM effects. func updateDMUnreadsAndNotify( messageDTO: MessageDTO, contact: ContactDTO, @@ -145,16 +144,10 @@ extension SyncCoordinator { func updateChannelUnreadsAndNotify( messageDTO: MessageDTO, channel: ChannelDTO?, - channelIndex: UInt8, - senderNodeName: String?, - messageText: String, - timestamp: UInt32, - hasSelfMention: Bool, - radioID: UUID, dependencies: SyncDependencies, - legacyScope: ReceiveScope? = nil + scope: ReceiveScope ) async throws { - guard legacyScope?.isCurrent != false else { return } + guard scope.isCurrent, let channelIndex = messageDTO.channelIndex else { return } if let channelID = channel?.id { // A mounted conversation does not mean its messages are visible in the background. let isInForeground = await dependencies.appStateProvider?.isInForeground ?? true @@ -162,42 +155,42 @@ extension SyncCoordinator { let activeRadioID = await dependencies.notificationService.activeChannelRadioID let isViewingChannel = isInForeground && activeIndex == channel?.index && activeRadioID == channel?.radioID if !isViewingChannel { - guard legacyScope?.isCurrent != false else { return } + guard scope.isCurrent else { return } try await dependencies.dataStore.incrementChannelUnreadCount(channelID: channelID) // Increment unread mention count if message contains self-mention - if hasSelfMention, legacyScope?.isCurrent != false { + if messageDTO.containsSelfMention, scope.isCurrent { try await dependencies.dataStore.incrementChannelUnreadMentionCount(channelID: channelID) } } } - guard legacyScope?.isCurrent != false else { return } + guard scope.isCurrent else { return } if Self.shouldPostChannelNotification(forResolvedChannel: channel) { await dependencies.notificationService.postChannelMessageNotification( channelName: channel?.name ?? "Channel \(channelIndex)", channelIndex: channelIndex, - radioID: radioID, - senderName: senderNodeName, - messageText: messageText, + radioID: messageDTO.radioID, + senderName: messageDTO.senderNodeName, + messageText: messageDTO.text, messageID: messageDTO.id, notificationLevel: channel?.notificationLevel ?? .all, - hasSelfMention: hasSelfMention, - legacyScope: legacyScope + hasSelfMention: messageDTO.containsSelfMention, + scope: scope ) } else if channel == nil { recordUnresolvedChannel( channelIndex: channelIndex, - radioID: radioID, - senderTimestamp: timestamp + radioID: messageDTO.radioID, + senderTimestamp: messageDTO.reactionTimestamp ) } - guard legacyScope?.isCurrent != false else { return } + guard scope.isCurrent else { return } await dependencies.notificationService.updateBadgeCount() // Broadcast for real-time chat updates - guard legacyScope?.isCurrent != false else { return } + guard scope.isCurrent else { return } dataEventBroadcaster.yield(.channelMessageReceived( - message: messageDTO, channelIndex: channelIndex, legacyScope: legacyScope + message: messageDTO, channelIndex: channelIndex, scope: scope )) } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index ea97d658a4..87d4d1d770 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -31,11 +31,12 @@ extension SyncCoordinator { await dependencies.messagePollingService.setContactMessageHandler { [weak self] message, contact, context, scope, preference in guard let self, scope.radioID == radioID, scope.isCurrent else { return } await handleIncomingMessage( - kind: .direct(message, contact: contact, scope: scope, preference: preference), + kind: .direct(message, contact: contact), context: context, dependencies: dependencies, - radioID: radioID, - selfNodeName: selfNodeName + selfNodeName: selfNodeName, + scope: scope, + preference: preference ) } } @@ -43,16 +44,16 @@ extension SyncCoordinator { // MARK: - Channel Message Handler private func wireChannelMessageHandler(dependencies: SyncDependencies, radioID: UUID, selfNodeName: String) async { - await dependencies.messagePollingService.setChannelMessageHandler { [weak self] message, channel, context, preference, arrivedAt, legacyScope in - guard let self else { return } + await dependencies.messagePollingService.setChannelMessageHandler { [weak self] message, channel, context, scope, preference, arrivedAt in + guard let self, scope.radioID == radioID, scope.isCurrent else { return } await handleIncomingMessage( - kind: .channel(message, channel: channel, preference: preference), + kind: .channel(message, channel: channel), receivedAt: arrivedAt, context: context, dependencies: dependencies, - radioID: radioID, selfNodeName: selfNodeName, - legacyScope: legacyScope + scope: scope, + preference: preference ) } } @@ -62,8 +63,8 @@ extension SyncCoordinator { /// Discriminates the two text-message ingestion paths, carrying the wire /// message and the resolved conversation for each. private enum IncomingMessageKind { - case direct(ContactMessage, contact: ContactDTO?, scope: ReceiveScope, preference: TextRulesPreference?) - case channel(ChannelMessage, channel: ChannelDTO?, preference: TextRulesPreference?) + case direct(ContactMessage, contact: ContactDTO?) + case channel(ChannelMessage, channel: ChannelDTO?) /// Log noun distinguishing the two paths in shared diagnostics. var logLabel: String { @@ -79,9 +80,10 @@ extension SyncCoordinator { /// without posting a second alert. private func resolveDirectContactIfNeeded( _ kind: IncomingMessageKind, - dependencies: SyncDependencies + dependencies: SyncDependencies, + scope: ReceiveScope ) async -> IncomingMessageKind { - guard case let .direct(message, contact, scope, preference) = kind, contact == nil else { + guard case let .direct(message, contact) = kind, contact == nil else { return kind } let prefix = message.senderPublicKeyPrefix @@ -91,7 +93,7 @@ extension SyncCoordinator { else { return kind } - return .direct(message, contact: materialized, scope: scope, preference: preference) + return .direct(message, contact: materialized) } /// Re-decrypts stamp-matched 0x88 rows and harvests extras, then refetches @@ -100,7 +102,7 @@ extension SyncCoordinator { messageDTO: MessageDTO, radioID: UUID, dependencies: SyncDependencies, - legacyScope: ReceiveScope? + scope: ReceiveScope ) async throws -> MessageDTO { guard let channelIndex = messageDTO.channelIndex else { return messageDTO } let stamp = messageDTO.senderTimestamp ?? messageDTO.timestamp @@ -111,7 +113,7 @@ extension SyncCoordinator { senderTimestamp: stamp ) let decoded = await dependencies.rxLogService.decodedEntries(raw) - guard legacyScope?.isCurrent != false else { return messageDTO } + guard scope.isCurrent else { return messageDTO } await dependencies.heardRepeatsService.harvestIncomingPaths( for: messageDTO, decodedCandidates: decoded @@ -127,15 +129,14 @@ extension SyncCoordinator { /// True when a row already owns this content key. A known distinct channel path /// is recorded as an extra; a nil path is unknown and is not written as one. - private func recordArrivalAndSkipDuplicate( - resolvedKind: IncomingMessageKind, + private func recordChannelArrivalAndSkipDuplicate( deduplicationKey: String, radioID: UUID, rxResult: RxLogLookupResult, snr: Double?, receiveTime: Date, dependencies: SyncDependencies, - legacyScope: ReceiveScope? + scope: ReceiveScope ) async -> Bool { do { guard let existing = try await dependencies.dataStore.fetchMessage( @@ -144,12 +145,8 @@ extension SyncCoordinator { ) else { return false } - guard legacyScope?.isCurrent != false else { return true } - if case .channel = resolvedKind { - guard let path = rxResult.pathNodes else { - logger.info("Skipping duplicate \(resolvedKind.logLabel) message") - return true - } + guard scope.isCurrent else { return true } + if let path = rxResult.pathNodes { await dependencies.heardRepeatsService.recordDistinctPathIfNeeded( message: existing, pathNodes: path, @@ -160,7 +157,7 @@ extension SyncCoordinator { rxLogEntryID: nil ) } - logger.info("Skipping duplicate \(resolvedKind.logLabel) message") + logger.info("Skipping duplicate channel message") return true } catch { logger.warning("Dedup check failed, proceeding with save: \(error)") @@ -176,16 +173,17 @@ extension SyncCoordinator { receivedAt: Date = .now, context: DeliveryContext, dependencies: SyncDependencies, - radioID: UUID, selfNodeName: String, - legacyScope: ReceiveScope? = nil + scope: ReceiveScope, + preference: TextRulesPreference? ) async { - guard legacyScope?.isCurrent != false else { return } + guard scope.isCurrent else { return } + let radioID = scope.radioID // A DM can land in the advert delta-sync debounce window before the local // Contact row exists. Materialize from a pending 0x80 key so unread, // notification, and Chats-list updates use the live path exactly once. let resolvedKind = await resolveDirectContactIfNeeded( - kind, dependencies: dependencies + kind, dependencies: dependencies, scope: scope ) // Per-kind wire fields. Channel messages embed the sender as a @@ -200,7 +198,7 @@ extension SyncCoordinator { let channelIndex: UInt8? let senderKeyPrefix: Data? switch resolvedKind { - case let .direct(message, contact, _, _): + case let .direct(message, contact): // The firmware cannot surface a self-DM here: decrypt runs against a // contact's ECDH shared secret and the local self_id is never in // contacts[], so an echo of the user's own DM never reaches this arm. @@ -213,7 +211,7 @@ extension SyncCoordinator { contactID = contact?.id channelIndex = nil senderKeyPrefix = message.senderPublicKeyPrefix - case let .channel(message, _, _): + case let .channel(message, _): // Parse "NodeName: text" format for sender name (senderNodeName, text) = Self.parseChannelMessage(message.text) senderTimestampDate = message.senderTimestamp @@ -317,38 +315,37 @@ extension SyncCoordinator { ) switch resolvedKind { - case let .direct(_, contact, scope, preference): + case let .direct(_, contact): await receiveDirectMessage( messageDTO, wireTextType: textTypeRaw, contact: contact, scope: scope, preference: preference, dependencies: dependencies ) - case let .channel(message, channel, preference): - if await recordArrivalAndSkipDuplicate( - resolvedKind: resolvedKind, + case let .channel(message, channel): + if await recordChannelArrivalAndSkipDuplicate( deduplicationKey: deduplicationKey, radioID: radioID, rxResult: rxResult, snr: snr, receiveTime: receiveTime, dependencies: dependencies, - legacyScope: legacyScope + scope: scope ) { return } - guard legacyScope?.isCurrent != false else { return } + guard scope.isCurrent else { return } if isBlockedSender(senderNodeName) { return } do { if let channel, try await dependencies.dataStore.shouldSuppressChannelMessage( - messageDTO, frame: message, channel: channel, scope: legacyScope, preference: preference + messageDTO, frame: message, channel: channel, scope: scope, preference: preference ) { return } } catch { logger.error("Failed to evaluate channel Text Rules: \(error)") return } - guard legacyScope?.isCurrent != false else { return } + guard scope.isCurrent else { return } if await handleChannelReaction( text: text, channelIndex: message.channelIndex, @@ -362,29 +359,23 @@ extension SyncCoordinator { } do { await runTestBeforeMessageSave(messageDTO) - guard try await dependencies.dataStore.saveLegacyChannelMessage( - messageDTO, scope: legacyScope, conversationID: channel?.textRulesID + guard try await dependencies.dataStore.saveReceivedChannelMessage( + messageDTO, scope: scope, conversationID: channel?.textRulesID ), - legacyScope?.isCurrent != false else { return } + scope.isCurrent else { return } let savedDTO = try await harvestAndRefreshChannelMessage( messageDTO: messageDTO, radioID: radioID, dependencies: dependencies, - legacyScope: legacyScope + scope: scope ) try await indexAndNotifyChannelMessage( messageDTO: savedDTO, channel: channel, - channelIndex: message.channelIndex, - senderNodeName: senderNodeName, - messageText: text, - timestamp: timestamp, - hasSelfMention: hasSelfMention, dependencies: dependencies, - radioID: radioID, - legacyScope: legacyScope + scope: scope ) - await notifyConversationsChanged(scope: legacyScope) + await notifyConversationsChanged(scope: scope) } catch { logger.error("Failed to save channel message: \(error)") } @@ -496,30 +487,22 @@ extension SyncCoordinator { private func indexAndNotifyChannelMessage( messageDTO: MessageDTO, channel: ChannelDTO?, - channelIndex: UInt8, - senderNodeName: String?, - messageText: String, - timestamp: UInt32, - hasSelfMention: Bool, dependencies: SyncDependencies, - radioID: UUID, - legacyScope: ReceiveScope? = nil + scope: ReceiveScope ) async throws { - guard legacyScope?.isCurrent != false else { return } - // Index message for reaction matching and process any pending reactions - // Use original timestamp for indexing so pending reactions can match - if let senderName = senderNodeName { + guard scope.isCurrent, let channelIndex = messageDTO.channelIndex else { return } + // Use the sender timestamp so pending reactions match corrected-clock messages. + if let senderName = messageDTO.senderNodeName { let pendingMatches = await dependencies.reactionService.indexMessage( id: messageDTO.id, channelIndex: channelIndex, senderName: senderName, - text: messageText, - timestamp: timestamp + text: messageDTO.text, + timestamp: messageDTO.reactionTimestamp ) - // Process any pending reactions that now have their target for pending in pendingMatches { - guard legacyScope?.isCurrent != false else { return } + guard scope.isCurrent else { return } let reactionDTO = ReactionDTO( messageID: messageDTO.id, emoji: pending.parsed.emoji, @@ -533,25 +516,17 @@ extension SyncCoordinator { } } - guard legacyScope?.isCurrent != false else { return } - // Update channel's last message date + guard scope.isCurrent else { return } if let channelID = channel?.id { try await dependencies.dataStore.updateChannelLastMessage(channelID: channelID, date: Date()) } - // Only update unread count, badges, and notify UI for non-blocked senders - if !isBlockedSender(senderNodeName) { + if !isBlockedSender(messageDTO.senderNodeName) { try await updateChannelUnreadsAndNotify( messageDTO: messageDTO, channel: channel, - channelIndex: channelIndex, - senderNodeName: senderNodeName, - messageText: messageText, - timestamp: timestamp, - hasSelfMention: hasSelfMention, - radioID: radioID, dependencies: dependencies, - legacyScope: legacyScope + scope: scope ) } } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift b/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift index b5217f9fe1..d46fad8ad8 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift @@ -12,10 +12,10 @@ public enum SyncDataEvent: Sendable { /// Conversations data changed; observers should reload chat lists. case conversationsChanged /// An incoming direct message was persisted for a known contact. - case directMessageReceived(message: MessageDTO, contact: ContactDTO, scope: ReceiveScope? = nil) + case directMessageReceived(message: MessageDTO, contact: ContactDTO, scope: ReceiveScope) /// An incoming channel message was persisted. case channelMessageReceived( - message: MessageDTO, channelIndex: UInt8, legacyScope: ReceiveScope? = nil + message: MessageDTO, channelIndex: UInt8, scope: ReceiveScope ) /// An incoming signed room message was persisted. case roomMessageReceived(RoomMessageDTO, roomID: UUID?, scope: ReceiveScope) diff --git a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift index c407d73de9..47a5c92fff 100644 --- a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift @@ -8,6 +8,49 @@ import Testing /// exercising the complete data flow rather than manually constructed envelopes. @Suite("BackupIntegration") struct BackupIntegrationTests { + @Test + func `backup restores conversations without local text rule selections`() async throws { + let radioID = UUID() + let source = try await PersistenceStore.createTestDataStore(radioID: radioID) + try await source.saveContact(.testContact(radioID: radioID)) + try await source.saveChannel(.testChannel(radioID: radioID)) + try await source.saveRemoteNodeSessionDTO(.testSession(radioID: radioID)) + let originals = try await source.textRulesConversations() + #expect(originals.count == 3) + for conversation in originals { + try await source.setTextRulesOverride(.on, kind: conversation.kind, key: conversation.key) + } + + let service = AppBackupService() + let exported = try await service.export(persistenceStore: source) + let encoded = try exported.data.zlibDecompressed(maxUncompressedBytes: maxBackupUncompressedBytes) + let json = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + for collection in ["contacts", "channels", "remoteNodeSessions"] { + let row = try #require((json[collection] as? [[String: Any]])?.first) + #expect(row["textRulesID"] == nil) + #expect(row["textRulesOverride"] == nil) + } + let envelope = try parseBackup(data: exported.data) + let contact = try #require(envelope.contacts.first) + let channel = try #require(envelope.channels.first) + let room = try #require(envelope.remoteNodeSessions.first) + #expect(contact.textRulesID == nil) + #expect(channel.textRulesID == nil) + #expect(room.textRulesID == nil) + #expect(contact.textRulesOverride == .inherit) + #expect(channel.textRulesOverride == .inherit) + #expect(room.textRulesOverride == .inherit) + + let destination = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + _ = try await service.importBackup(envelope: envelope, into: destination) + let restored = try await destination.textRulesConversations() + #expect(restored.count == originals.count) + for conversation in restored { + #expect(conversation.override == .inherit) + #expect(!originals.contains { $0.key == conversation.key }) + } + } + @Test(arguments: [RemoteNodeRole.sensor, .repeater, .roomServer]) func `remote roles and legacy pins survive envelope import`(role: RemoteNodeRole) async throws { let radioID = UUID() diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift index c6e9e7bf7d..4534afbf67 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift @@ -59,7 +59,7 @@ public actor MockMessagePollingService: MessagePollingServiceProtocol { public private(set) var capturedContactMessageHandler: (@Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void)? /// Captured channel message handler (set via setChannelMessageHandler) - public private(set) var capturedChannelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void)? + public private(set) var capturedChannelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void)? /// Captured signed message handler (set via setSignedMessageHandler) public private(set) var capturedSignedMessageHandler: (@Sendable (ContactMessage, ReceiveScope) async -> Void)? @@ -73,7 +73,7 @@ public actor MockMessagePollingService: MessagePollingServiceProtocol { capturedContactMessageHandler = handler } - public func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void) { + public func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) { capturedChannelMessageHandler = handler } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift index f10f88ea62..68e9bfc514 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift @@ -43,13 +43,12 @@ struct RoomPostTextRulesTests { private func makeFixture( phrase: String, - lookIn: TextRulesPreference.Rule.LookIn = .message, - bookmark: UInt32 = Self.bookmark + lookIn: TextRulesPreference.Rule.LookIn = .message ) async throws -> Fixture { let radioID = UUID() let store = try await PersistenceStore.createTestDataStore(radioID: radioID) let room = RemoteNodeSessionDTO.testSession( - radioID: radioID, lastSyncTimestamp: bookmark, lastMessageDate: Date(timeIntervalSince1970: 39) + radioID: radioID, lastSyncTimestamp: Self.bookmark, lastMessageDate: Date(timeIntervalSince1970: 39) ) try await store.saveRemoteNodeSessionDTO(room) let saved = try #require(try await store.fetchRemoteNodeSession(id: room.id)) @@ -64,14 +63,14 @@ struct RoomPostTextRulesTests { return Fixture(store: store, room: saved, service: service, policy: policy, lifetime: lifetime) } - @Test(arguments: [UInt32(0), UInt32(40)]) - func `drop can recover a room without advancing its bookmark or visible activity`(bookmark: UInt32) async throws { - let fixture = try await makeFixture(phrase: " ALERT ", bookmark: bookmark) + @Test + func `drop can recover a room without advancing its bookmark or visible activity`() async throws { + let fixture = try await makeFixture(phrase: " ALERT ") #expect(try await fixture.receive(" ALERT ") == nil) let recovered = try #require(try await fixture.store.fetchRemoteNodeSession(id: fixture.room.id)) #expect(recovered.isConnected) - #expect(recovered.lastSyncTimestamp == bookmark) + #expect(recovered.lastSyncTimestamp == fixture.room.lastSyncTimestamp) #expect(recovered.lastMessageDate == fixture.room.lastMessageDate) #expect(recovered.unreadCount == 0) #expect(try await fixture.service.fetchMessages(sessionID: fixture.room.id).isEmpty) @@ -116,8 +115,7 @@ struct RoomPostTextRulesTests { try await fixture.store.saveContact(.testContact( radioID: foreign, publicKey: key(tail: 1), name: "Match me" )) - let foreignOnly = try #require(try await fixture.receive("Foreign display", timestamp: 41)) - #expect(foreignOnly.authorName == "Match me") + #expect(try await fixture.receive("Foreign display", timestamp: 41) != nil) try await fixture.store.saveContact(.testContact( radioID: fixture.room.radioID, publicKey: key(tail: 2), name: "Match me" diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift index 4c8b7dc5e2..04260d7ffd 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift @@ -32,16 +32,12 @@ struct SyncCoordinatorBackgroundUnreadTests { channelRadioID: radioID ) let message = MessageDTO.testChannelMessage(radioID: radioID, channelIndex: channel.index) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) try await services.syncCoordinator.updateChannelUnreadsAndNotify( messageDTO: message, channel: channel, - channelIndex: channel.index, - senderNodeName: nil, - messageText: message.text, - timestamp: message.timestamp, - hasSelfMention: false, - radioID: radioID, - dependencies: services.syncDependencies + dependencies: services.syncDependencies, + scope: scope ) let saved = try #require(await store.fetchChannel(id: channel.id)) #expect(saved.unreadCount == expectedUnread) diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift index 56610d1f30..e65bfcafe1 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift @@ -315,9 +315,8 @@ struct SyncCoordinatorMessageHandlerTests { #expect(saved[0].textType == .cliCommand) } - @Test(arguments: [false, true]) - func `DM rule drop and replay leave conversation effects untouched`(catchUp: Bool) async throws { - let context: DeliveryContext = catchUp ? .initialSync(anchor: Date()) : .live + @Test + func `DM rule drop and replay leave conversation effects untouched`() async throws { let radioID = UUID() let store = try await createTestDataStore(radioID: radioID) let key = Data(repeating: 0xB6, count: 32) @@ -338,8 +337,8 @@ struct SyncCoordinatorMessageHandlerTests { preference.append(.init(phrase: "ALERT", lookIn: .message, match: .contains)) let arrival = makeDirectArrival(" alert! ", key: key, timestamp: 50) - await deliver(arrival, contact, context, scope, preference) - await deliver(arrival, contact, context, scope, nil) + await deliver(arrival, contact, .live, scope, preference) + await deliver(arrival, contact, .live, scope, nil) let entries = try await store.recentlyBlockedMessages() #expect(entries.count == 1) @@ -353,7 +352,7 @@ struct SyncCoordinatorMessageHandlerTests { #expect(current.lastHeardTimestamp == contact.lastHeardTimestamp) #expect(await coordinator.conversationsVersion == 0) - await deliver(makeDirectArrival("safe", key: key, timestamp: 51), contact, context, scope, preference) + await deliver(makeDirectArrival("safe", key: key, timestamp: 51), contact, .live, scope, preference) #expect(try await store.fetchMessages(contactID: contact.id).map(\.text) == ["safe"]) #expect(try await store.fetchContact(id: contact.id)?.unreadCount == 1) #expect(await coordinator.conversationsVersion == 1) @@ -554,7 +553,8 @@ struct SyncCoordinatorMessageHandlerTests { text: "ChannelPeer: hello channel", snr: nil ) - await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live, nil, .now, nil) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) + await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live, scope, nil, .now) let updated = try #require( await dataStore.fetchContact(radioID: radioID, publicKey: publicKey) @@ -565,7 +565,7 @@ struct SyncCoordinatorMessageHandlerTests { // MARK: - Live receive region propagation @Test(.timeLimit(.minutes(1))) - func `legacy channel arrival cannot cross a retired receive scope`() async throws { + func `channel arrival cannot cross a retired receive scope`() async throws { let radioID = UUID() let store = try await createTestDataStore(radioID: radioID) let radio = try #require(await store.fetchDevice(radioID: radioID)) @@ -581,15 +581,15 @@ struct SyncCoordinatorMessageHandlerTests { await coordinator.wireMessageHandlers(dependencies: dependencies, radioID: radioID) let handler = try #require(await mockPolling.capturedChannelMessageHandler) - let (captured, capture) = AsyncStream.makeStream() + let (captured, capture) = AsyncStream.makeStream() let (released, release) = AsyncStream.makeStream() - await poller.setChannelMessageHandler { message, channel, context, preference, arrivedAt, scope in + await poller.setChannelMessageHandler { message, channel, context, scope, preference, arrivedAt in if message.text == "Peer: before erase" { capture.yield(scope) var iterator = released.makeAsyncIterator() _ = await iterator.next() } - await handler(message, channel, context, preference, arrivedAt, scope) + await handler(message, channel, context, scope, preference, arrivedAt) } await poller.startMessageEventMonitoring(radioID: radioID) try await waitUntil("poller did not subscribe") { await mesh.eventSubscriptionCount == 1 } @@ -598,14 +598,13 @@ struct SyncCoordinatorMessageHandlerTests { channelIndex: 0, pathLength: 0, textType: 0, senderTimestamp: stamp, text: "Peer: before erase", snr: nil ))) var captureIterator = captured.makeAsyncIterator() - let deliveredScope = await captureIterator.next() ?? nil - let oldScope = try #require(deliveredScope) + let oldScope = try #require(await captureIterator.next()) _ = try await store.beginRadioErase(radio) try await store.cancelRadioErase(radioID: radioID) #expect(!oldScope.isCurrent) let lateWrite = MessageDTO.testChannelMessage(radioID: radioID, channelIndex: 0, text: "Before erase") - #expect(try await store.saveLegacyChannelMessage(lateWrite, scope: oldScope, conversationID: nil) == false) + #expect(try await store.saveReceivedChannelMessage(lateWrite, scope: oldScope, conversationID: nil) == false) release.finish() await mesh.yieldEvent(.channelMessageReceived(ChannelMessage( @@ -669,7 +668,8 @@ struct SyncCoordinatorMessageHandlerTests { text: "NodeAlpha: region scope test", snr: nil ) - await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live, nil, .now, nil) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) + await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live, scope, nil, .now) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) let message = try #require(saved.first) @@ -716,6 +716,7 @@ struct SyncCoordinatorMessageHandlerTests { let events = coordinator.dataEventBroadcaster.subscribe() await coordinator.wireMessageHandlers(dependencies: dependencies, radioID: radioID) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) await mockPolling.capturedChannelMessageHandler?( ChannelMessage( channelIndex: channelIndex, @@ -726,7 +727,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), nil, - .live, nil, .now, nil + .live, scope, nil, .now ) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) @@ -795,6 +796,7 @@ struct SyncCoordinatorMessageHandlerTests { let coordinator = SyncCoordinator() await coordinator.wireMessageHandlers(dependencies: dependencies, radioID: radioID) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) await mockPolling.capturedChannelMessageHandler?( ChannelMessage( channelIndex: channelIndex, @@ -805,7 +807,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), channel, - .live, nil, .now, nil + .live, scope, nil, .now ) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) @@ -863,6 +865,7 @@ struct SyncCoordinatorMessageHandlerTests { let coordinator = SyncCoordinator() await coordinator.wireMessageHandlers(dependencies: dependencies, radioID: radioID) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) await mockPolling.capturedChannelMessageHandler?( ChannelMessage( channelIndex: channelIndex, @@ -873,7 +876,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), nil, - .live, nil, .now, nil + .live, scope, nil, .now ) #expect(try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex).count == 1) diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift index 3471395c46..0df020b756 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift @@ -2328,7 +2328,7 @@ actor OrderTrackingMessagePollingService: MessagePollingServiceProtocol { func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) {} - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void) {} + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) {} func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) {} diff --git a/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift b/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift index a01f4557d5..f312598366 100644 --- a/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift @@ -76,8 +76,6 @@ struct TextRulesOwnershipTests { let envelope = try parseBackup(data: backup.data) let exportedContact = try #require(envelope.contacts.first) #expect(exportedContact.id == contact.id) - #expect(exportedContact.textRulesID == nil) - #expect(exportedContact.textRulesOverride == .inherit) _ = try await backupService.importBackup(envelope: envelope, into: store) #expect(try await store.textRulesConversation(kind: selected.kind, key: selected.key)?.override == .on) diff --git a/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift b/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift index 0bc7d94662..fc7a61e21a 100644 --- a/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift @@ -67,27 +67,17 @@ struct TextRulesPreferenceTests { } @Test @MainActor - func `failed settings saves leave committed values and concurrent edits rebase`() async throws { + func `settings edits persist and failed saves leave committed values intact`() throws { let directory = try makeDirectory() defer { try? FileManager.default.removeItem(at: directory) } let url = directory.appending(path: "rules.json") let manager = try makeManager(url: url) manager.loadTextRules() - let defaults = try #require(manager.textRulesPreference) - #expect(defaults.rules.isEmpty) - #expect(defaults.selection(for: .publicChannel) == .all) let rule = TextRulesPreference.Rule(phrase: " alert ", lookIn: .message, match: .contains) - let first = Task { @MainActor in - try manager.updateTextRules { $0.append(rule) } - } - let second = Task { @MainActor in - try manager.updateTextRules { $0.setSelection(.fixed([]), for: .publicChannel) } - } - try await first.value - try await second.value + try manager.updateTextRules { $0.append(rule) } + try manager.updateTextRules { $0.setSelection(.fixed([]), for: .publicChannel) } let committed = try #require(manager.textRulesPreference) - #expect(committed.revision != defaults.revision) #expect(committed.rules == [rule]) #expect(committed.selection(for: .publicChannel) == .fixed([])) diff --git a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift index abafd00cdf..08a24f9ba9 100644 --- a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift +++ b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift @@ -271,7 +271,7 @@ struct ConnectionStatusLifecycleTests { func pauseAutoFetch() async {} func resumeAutoFetch() async {} func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) {} - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, TextRulesPreference?, Date, ReceiveScope?) async -> Void) {} + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) {} func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) {} func setCLIMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} } diff --git a/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift b/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift index f866b9a903..81e9a4f1e5 100644 --- a/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift +++ b/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift @@ -32,14 +32,12 @@ struct RecentlyBlockedPersistenceTests { try await store.recordRecentlyBlockedMessage(lastDrop) let committed = try await store.recentlyBlockedMessages() #expect(committed == Array(drops[1...limit].reversed())) - #expect(try await store.recentlyBlockedCount() == limit) await store.setRecordRecentlyBlockedFaultInjection { throw InjectedSaveFailure() } await #expect(throws: InjectedSaveFailure.self) { try await store.recordRecentlyBlockedMessage(drops[limit + 1]) } #expect(try await store.recentlyBlockedMessages() == committed) - #expect(try await store.recentlyBlockedCount() == limit) } let reopened = try ModelContainer(for: PersistenceStore.schema, configurations: [configuration]) diff --git a/MC1Tests/ViewModels/ChatViewModelPaginationTests.swift b/MC1Tests/ViewModels/ChatViewModelPaginationTests.swift index 9f68f71bd3..22f5a7d871 100644 --- a/MC1Tests/ViewModels/ChatViewModelPaginationTests.swift +++ b/MC1Tests/ViewModels/ChatViewModelPaginationTests.swift @@ -438,7 +438,8 @@ struct ChatViewModelChannelPaginationTests { channelIndex: channelIndex, timestamp: 2000 ) - await viewModel.handle(.channelMessageReceived(message: channelMessage, channelIndex: channelIndex)) + let scope = ReceiveScope(radioID: radioID, link: .init(), partition: .init()) + await viewModel.handle(.channelMessageReceived(message: channelMessage, channelIndex: channelIndex, scope: scope)) #expect(viewModel.messages.count == baselineCount, "An incoming channel message must not be admitted into the open DM after the axis switch") diff --git a/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift b/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift index 2676dd593d..8e9d4e7210 100644 --- a/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift +++ b/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift @@ -169,12 +169,19 @@ struct ChatReconnectPopulateTests { timestamp: 9000 ) try await env.dataStore.saveMessage(incoming) + try await env.dataStore.saveDevice(DeviceDTO(from: Device( + radioID: env.contact.radioID, + publicKey: Data(repeating: 0x17, count: 32), + nodeName: "TestRadio" + ))) + let scope = try #require(await env.dataStore.captureReceiveScope(radioID: env.contact.radioID, link: .init())) + let contact = try #require(await env.dataStore.fetchContact(id: env.contact.id)) - await env.viewModel.handle(.directMessageReceived(message: incoming, contact: env.contact)) + await env.viewModel.handle(.directMessageReceived(message: incoming, contact: contact, scope: scope)) #expect(env.viewModel.messages.contains { $0.id == incoming.id }) let countAfterAdmit = env.viewModel.messages.count - await env.viewModel.handle(.directMessageReceived(message: incoming, contact: env.contact)) + await env.viewModel.handle(.directMessageReceived(message: incoming, contact: contact, scope: scope)) #expect(env.viewModel.messages.count == countAfterAdmit) } diff --git a/MC1Tests/Views/Chats/ChatViewModelFailedSendTests.swift b/MC1Tests/Views/Chats/ChatViewModelFailedSendTests.swift index 97849a0e84..3a14b49861 100644 --- a/MC1Tests/Views/Chats/ChatViewModelFailedSendTests.swift +++ b/MC1Tests/Views/Chats/ChatViewModelFailedSendTests.swift @@ -309,12 +309,15 @@ struct ChatViewModelFailedSendTests { let messageID = UUID() let contact = makeContact() let message = makeMessage(radioID: contact.radioID, contactID: contact.id) + let scope = ReceiveScope(radioID: contact.radioID, link: .init(), partition: .init()) #expect(!viewModel.shouldRefreshFailedSendIndicators( - for: .directMessageReceived(message: message, contact: contact) + for: .directMessageReceived(message: message, contact: contact, scope: scope) )) #expect(!viewModel.shouldRefreshFailedSendIndicators( - for: .channelMessageReceived(message: message, channelIndex: 0) + for: .channelMessageReceived( + message: message, channelIndex: 0, scope: scope + ) )) #expect(!viewModel.shouldRefreshFailedSendIndicators( for: .roomMessageReceived( @@ -324,7 +327,8 @@ struct ChatViewModelFailedSendTests { text: "hi", timestamp: 1 ), - sessionID: UUID() + sessionID: UUID(), + scope: scope ) )) #expect(!viewModel.shouldRefreshFailedSendIndicators( diff --git a/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift b/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift index 9c7a0ffb0b..92b7efbac9 100644 --- a/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift +++ b/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift @@ -125,7 +125,6 @@ public protocol RemoteAccessSessionOps: Actor { // MARK: - Default Implementations public extension RemoteAccessSessionOps { - /// Sends a keep-alive with a fixed watermark. func sendKeepAlive(to publicKey: Data, syncSince: UInt32) async throws -> MessageSentInfo { try await sendKeepAlive(to: publicKey, syncSince: { syncSince }, beforeSend: {}) } diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift index ccdc036a1a..be9fb83761 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift @@ -376,9 +376,8 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { await dispatcher.subscribeTracked(filter: filter.matches) } - /// Finishes a tracked event subscription. - /// - /// Causes the corresponding `for await` loop to exit. Safe to call with an unknown id. + /// Finishes a tracked subscription so its consumer exits after draining buffered events. + /// Unknown subscription IDs are ignored. public func finishEvents(id: UUID) async { await dispatcher.finishSubscription(id: id) } diff --git a/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionGetChannelsTests.swift b/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionGetChannelsTests.swift index 894a709707..ed15e7acf0 100644 --- a/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionGetChannelsTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionGetChannelsTests.swift @@ -7,57 +7,6 @@ import Testing /// window/refill bound and the capability fallback to serial reads. @Suite("MeshCoreSession getChannels pipeline") struct MeshCoreSessionGetChannelsTests { - @Test - func `channel reads and queued text use stock framing`() async throws { - let transport = MockTransport() - await transport.setSupportsWriteWithoutResponse(true) - let session = MeshCoreSession(transport: transport, configuration: pipelineConfig()) - try await startSession(session, transport: transport) - - let query = Task { try await session.queryDevice() } - try await waitUntil("expected stock device query") { - await transport.sentData.last == Data([0x16, 0x03]) - } - var info = Data([0x0D, 0x0E]) - info.append(Data(repeating: 0, count: 80)) - await transport.simulateReceive(info) - #expect(try await query.value.firmwareVersion == 14) - - let secret = Data(repeating: 0xAA, count: 16) - let channel = makeChannelInfoPacket(index: 2, name: "two", secret: secret) - let serial = Task { try await session.getChannel(index: 2) } - try await waitUntil("expected stock serial channel read") { - await transport.sentData.last == Data([0x1F, 0x02]) - } - await transport.simulateReceive(channel) - #expect(try await serial.value.secret == secret) - - let pipeline = Task { try await session.getChannels(indices: [2]) } - try await waitUntil("expected stock pipelined channel read") { - let sent = await transport.sentData - return sent.count == 4 && sent.last == Data([0x1F, 0x02]) - } - await transport.simulateReceive(channel) - #expect(try await pipeline.value.received.first?.secret == secret) - - let message = Task { try await session.getMessage() } - try await waitUntil("expected stock queued message fetch") { - await transport.sentData.last == Data([0x0A]) - } - var frame = Data([0x11, 0xFC, 0x00, 0x00, 0x02, 0x01, 0x00, 0x20, 0x10, 0x00, 0x00]) - let text = String(repeating: "🙂", count: 40) - frame.append(contentsOf: text.utf8) - await transport.simulateReceive(frame) - guard case let .channelMessage(result) = try await message.value else { - Issue.record("Expected queued channel text") - return - } - #expect(result.channelIndex == 2) - #expect(result.text == text) - #expect(result.snr == -1) - await session.stop() - } - // MARK: - Gate #1: correctness with gaps @Test From ad48b3ff1d90e2acdf03bf492179b6b2adeb2867 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:46:28 -0800 Subject: [PATCH 04/10] fix: drop surrounding whitespace when saving a text rule A space after the last word was stored with the phrase and then failed to match. --- MC1/Views/Settings/Sections/NewTextRuleSheet.swift | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/MC1/Views/Settings/Sections/NewTextRuleSheet.swift b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift index b64c595c4f..c906a59f0a 100644 --- a/MC1/Views/Settings/Sections/NewTextRuleSheet.swift +++ b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift @@ -10,6 +10,10 @@ struct NewTextRuleSheet: View { @State private var match = TextRulesPreference.Rule.Match.contains @State private var errorMessage: String? + private var trimmedPhrase: String { + phrase.trimmingCharacters(in: .whitespacesAndNewlines) + } + var body: some View { NavigationStack { Form { @@ -48,7 +52,7 @@ struct NewTextRuleSheet: View { } ToolbarItem(placement: .confirmationAction) { Button(L10n.Contacts.Contacts.Add.add, action: add) - .disabled(phrase.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + .disabled(trimmedPhrase.isEmpty) } } .errorAlert($errorMessage) @@ -56,7 +60,7 @@ struct NewTextRuleSheet: View { } private func add() { - let rule = TextRulesPreference.Rule(phrase: phrase, lookIn: lookIn, match: match) + let rule = TextRulesPreference.Rule(phrase: trimmedPhrase, lookIn: lookIn, match: match) guard rule.isValid else { return } do { try appState.connectionManager.updateTextRules { $0.append(rule) } From 25f27402292b74c7ff28ea4a7c793d4da2ba39e9 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:04:22 -0800 Subject: [PATCH 05/10] ui: label each line in recently blocked - Name the message, rule, sender, chat, node, and time on each hidden message. - Describe the matched rule with the summary the rules list already uses. - Translate the new labels for the other locales. --- MC1/Resources/Generated/L10n.swift | 16 +++-- .../Localization/de.lproj/Settings.strings | 7 ++- .../Localization/en.lproj/Settings.strings | 7 ++- .../Localization/es.lproj/Settings.strings | 7 ++- .../Localization/fr.lproj/Settings.strings | 7 ++- .../Localization/it.lproj/Settings.strings | 7 ++- .../Localization/ko.lproj/Settings.strings | 7 ++- .../Localization/nl.lproj/Settings.strings | 7 ++- .../Localization/pl.lproj/Settings.strings | 7 ++- .../Localization/pt.lproj/Settings.strings | 7 ++- .../Localization/ru.lproj/Settings.strings | 7 ++- .../Localization/uk.lproj/Settings.strings | 7 ++- .../zh-Hans.lproj/Settings.strings | 7 ++- .../Settings/Sections/NewTextRuleSheet.swift | 6 ++ .../Sections/RecentlyBlockedView.swift | 60 ++++++++++++------- .../Sections/TextRulesSettingsView.swift | 2 +- 16 files changed, 116 insertions(+), 52 deletions(-) diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 97ea60fa61..d96bc6715c 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -6199,18 +6199,24 @@ public enum L10n { /// Text Rules public static let title = L10n.tr("Settings", "textRules.title", fallback: "Text Rules") public enum Archive { + /// Chat + public static let chat = L10n.tr("Settings", "textRules.archive.chat", fallback: "Chat") /// No Hidden Messages public static let empty = L10n.tr("Settings", "textRules.archive.empty", fallback: "No Hidden Messages") - /// Message and Sender - public static let fieldsBoth = L10n.tr("Settings", "textRules.archive.fieldsBoth", fallback: "Message and Sender") /// The latest %d hidden messages are kept on this installation and are excluded from shareable backups. public static func footer(_ p1: Int) -> String { return L10n.tr("Settings", "textRules.archive.footer", p1, fallback: "The latest %d hidden messages are kept on this installation and are excluded from shareable backups.") } - /// Matched “%1$@” in %2$@ (%3$@) - public static func reason(_ p1: Any, _ p2: Any, _ p3: Any) -> String { - return L10n.tr("Settings", "textRules.archive.reason", String(describing: p1), String(describing: p2), String(describing: p3), fallback: "Matched “%1$@” in %2$@ (%3$@)") + /// %@: + public static func labelPrefix(_ p1: Any) -> String { + return L10n.tr("Settings", "textRules.archive.labelPrefix", String(describing: p1), fallback: "%@: ") } + /// My Node + public static let myNode = L10n.tr("Settings", "textRules.archive.myNode", fallback: "My Node") + /// Rule + public static let rule = L10n.tr("Settings", "textRules.archive.rule", fallback: "Rule") + /// Time + public static let time = L10n.tr("Settings", "textRules.archive.time", fallback: "Time") /// Recently Blocked public static let title = L10n.tr("Settings", "textRules.archive.title", fallback: "Recently Blocked") /// Unknown Conversation diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index e98b15dcf3..6be046b4d2 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -1539,8 +1539,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "Regel"; +"textRules.archive.chat" = "Chat"; +"textRules.archive.myNode" = "Mein Knoten"; +"textRules.archive.time" = "Zeit"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index e3a6cbd4a4..e45ae1ee95 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -1525,8 +1525,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "Rule"; +"textRules.archive.chat" = "Chat"; +"textRules.archive.myNode" = "My Node"; +"textRules.archive.time" = "Time"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index 037143dab4..1c671daf7b 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -1539,8 +1539,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "Regla"; +"textRules.archive.chat" = "Chat"; +"textRules.archive.myNode" = "Mi nodo"; +"textRules.archive.time" = "Hora"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index e2bb7d3892..0727a6fb2d 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -1539,8 +1539,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@ : "; +"textRules.archive.rule" = "Règle"; +"textRules.archive.chat" = "Discussion"; +"textRules.archive.myNode" = "Mon nœud"; +"textRules.archive.time" = "Heure"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 4250909981..1080052475 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -1537,8 +1537,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "Regola"; +"textRules.archive.chat" = "Chat"; +"textRules.archive.myNode" = "Il mio nodo"; +"textRules.archive.time" = "Ora"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index 8636acfbad..856140c6d6 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -1527,8 +1527,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "규칙"; +"textRules.archive.chat" = "채팅"; +"textRules.archive.myNode" = "내 노드"; +"textRules.archive.time" = "시간"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index 70a9656ea5..199b4141c2 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -1539,8 +1539,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "Regel"; +"textRules.archive.chat" = "Gesprek"; +"textRules.archive.myNode" = "Mijn knooppunt"; +"textRules.archive.time" = "Tijd"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index d411ddfdec..e5b9ad13a7 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -1539,8 +1539,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "Reguła"; +"textRules.archive.chat" = "Czat"; +"textRules.archive.myNode" = "Mój węzeł"; +"textRules.archive.time" = "Czas"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index 4e28815f32..411dc5f424 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -1537,8 +1537,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "Regra"; +"textRules.archive.chat" = "Conversa"; +"textRules.archive.myNode" = "O meu nó"; +"textRules.archive.time" = "Hora"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index c748ebd34b..02a1f9b857 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -1539,8 +1539,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "Правило"; +"textRules.archive.chat" = "Чат"; +"textRules.archive.myNode" = "Мой узел"; +"textRules.archive.time" = "Время"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 59197a7f30..24e28ed251 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -1539,8 +1539,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "Правило"; +"textRules.archive.chat" = "Чат"; +"textRules.archive.myNode" = "Мій вузол"; +"textRules.archive.time" = "Час"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index 067fee15ff..35c07e9ff8 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -1539,8 +1539,11 @@ "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; -"textRules.archive.fieldsBoth" = "Message and Sender"; -"textRules.archive.reason" = "Matched “%1$@” in %2$@ (%3$@)"; +"textRules.archive.labelPrefix" = "%@: "; +"textRules.archive.rule" = "规则"; +"textRules.archive.chat" = "聊天"; +"textRules.archive.myNode" = "我的节点"; +"textRules.archive.time" = "时间"; "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; diff --git a/MC1/Views/Settings/Sections/NewTextRuleSheet.swift b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift index c906a59f0a..0323e28d9f 100644 --- a/MC1/Views/Settings/Sections/NewTextRuleSheet.swift +++ b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift @@ -99,3 +99,9 @@ extension TextRulesPreference.Rule.Match { } } } + +extension TextRulesPreference.Rule { + var summary: String { + L10n.Settings.TextRules.ruleSummary(match.title(for: lookIn), lookIn.title) + } +} diff --git a/MC1/Views/Settings/Sections/RecentlyBlockedView.swift b/MC1/Views/Settings/Sections/RecentlyBlockedView.swift index e34fc6d68e..4f9abdc95b 100644 --- a/MC1/Views/Settings/Sections/RecentlyBlockedView.swift +++ b/MC1/Views/Settings/Sections/RecentlyBlockedView.swift @@ -38,21 +38,44 @@ struct RecentlyBlockedView: View { private func archiveRow(_ entry: RecentlyBlockedMessageDTO) -> some View { VStack(alignment: .leading) { - Text(highlighted(entry.body, matches: entry.match.bodyHighlights)) - .fixedSize(horizontal: false, vertical: true) - Text(reason(for: entry.match)) - .font(.subheadline) - if let sender = entry.sender { - Text(highlighted(sender, matches: entry.match.senderHighlights)) - .font(.subheadline) + labeled( + L10n.Settings.TextRules.Field.message, + Text(highlighted(entry.body, matches: entry.match.bodyHighlights)) + ) + VStack(alignment: .leading) { + labeled( + L10n.Settings.TextRules.Archive.rule, + Text(verbatim: L10n.Settings.TextRules.ruleSummary( + entry.match.rule.phrase, + entry.match.rule.summary + )) + ) + if let sender = entry.sender { + labeled( + L10n.Settings.TextRules.Field.sender, + Text(highlighted(sender, matches: entry.match.senderHighlights)) + ) + } + } + .font(.subheadline) + VStack(alignment: .leading) { + labeled( + L10n.Settings.TextRules.Archive.chat, + Text(verbatim: entry.conversationName ?? L10n.Settings.TextRules.Archive.unknownConversation) + ) + labeled( + L10n.Settings.TextRules.Archive.myNode, + Text(verbatim: entry.radioName ?? L10n.Settings.TextRules.Archive.unknownRadio) + ) + labeled( + L10n.Settings.TextRules.Archive.time, + Text(entry.arrivedAt, format: .dateTime.month().day().hour().minute()) + ) } - Text(entry.conversationName ?? L10n.Settings.TextRules.Archive.unknownConversation) - .foregroundStyle(.secondary) - Text(entry.radioName ?? L10n.Settings.TextRules.Archive.unknownRadio) - .foregroundStyle(.secondary) - Text(entry.arrivedAt, format: .dateTime.month().day().hour().minute()) - .foregroundStyle(.secondary) + .font(.footnote) + .foregroundStyle(.secondary) } + .fixedSize(horizontal: false, vertical: true) .accessibilityElement(children: .combine) } @@ -69,15 +92,8 @@ struct RecentlyBlockedView: View { return attributed } - private func reason(for match: TextRulesPreference.RuleMatch) -> String { - let fields: String = if match.bodyHighlights.isEmpty { - L10n.Settings.TextRules.Field.sender - } else if match.senderHighlights.isEmpty { - L10n.Settings.TextRules.Field.message - } else { - L10n.Settings.TextRules.Archive.fieldsBoth - } - return L10n.Settings.TextRules.Archive.reason(match.rule.phrase, fields, match.rule.match.title(for: match.rule.lookIn)) + private func labeled(_ label: String, _ value: Text) -> Text { + Text(verbatim: L10n.Settings.TextRules.Archive.labelPrefix(label)) + value } private func refresh(from store: PersistenceStore) async { diff --git a/MC1/Views/Settings/Sections/TextRulesSettingsView.swift b/MC1/Views/Settings/Sections/TextRulesSettingsView.swift index 164a6b4255..e3cf04aac5 100644 --- a/MC1/Views/Settings/Sections/TextRulesSettingsView.swift +++ b/MC1/Views/Settings/Sections/TextRulesSettingsView.swift @@ -53,7 +53,7 @@ struct TextRulesSettingsView: View { ForEach(rules) { rule in VStack(alignment: .leading) { Text(verbatim: rule.phrase) - Text(L10n.Settings.TextRules.ruleSummary(rule.match.title(for: rule.lookIn), rule.lookIn.title)) + Text(verbatim: rule.summary) .font(.subheadline) .foregroundStyle(.secondary) if rule.lookIn != .message { From 81c14ae344cfdb55c5e04d689573aefc3bd1fa19 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 19:31:01 -0800 Subject: [PATCH 06/10] ui: clarify text rules footers --- MC1/Resources/Generated/L10n.swift | 44 +++++++++---------- .../Localization/de.lproj/Settings.strings | 22 +++++----- .../Localization/en.lproj/Settings.strings | 22 +++++----- .../Localization/es.lproj/Settings.strings | 22 +++++----- .../Localization/fr.lproj/Settings.strings | 22 +++++----- .../Localization/it.lproj/Settings.strings | 22 +++++----- .../Localization/ko.lproj/Settings.strings | 22 +++++----- .../Localization/nl.lproj/Settings.strings | 22 +++++----- .../Localization/pl.lproj/Settings.strings | 22 +++++----- .../Localization/pt.lproj/Settings.strings | 22 +++++----- .../Localization/ru.lproj/Settings.strings | 22 +++++----- .../Localization/uk.lproj/Settings.strings | 22 +++++----- .../zh-Hans.lproj/Settings.strings | 22 +++++----- .../ConversationTextRulesSection.swift | 20 ++++----- .../Settings/Sections/NewTextRuleSheet.swift | 34 +++++++------- .../Sections/TextRulesSettingsView.swift | 5 --- 16 files changed, 168 insertions(+), 199 deletions(-) diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index d96bc6715c..cb16de3a30 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -6178,14 +6178,12 @@ public enum L10n { public static let trustedOnlyDescription = L10n.tr("Settings", "telemetry.trustedOnlyDescription", fallback: "Limit telemetry to selected contacts") } public enum TextRules { - /// Deleting a rule leaves its hidden messages in Recently Blocked. - public static let deleteFooter = L10n.tr("Settings", "textRules.deleteFooter", fallback: "Deleting a rule leaves its hidden messages in Recently Blocked.") + /// Hidden messages stay in Recently Blocked. + public static let deleteFooter = L10n.tr("Settings", "textRules.deleteFooter", fallback: "Hidden messages stay in Recently Blocked.") /// No Text Rules public static let empty = L10n.tr("Settings", "textRules.empty", fallback: "No Text Rules") /// Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded. public static let loadFailed = L10n.tr("Settings", "textRules.loadFailed", fallback: "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded.") - /// A sender-name match also hides incoming emoji reactions from that sender. - public static let reactionFooter = L10n.tr("Settings", "textRules.reactionFooter", fallback: "A sender-name match also hides incoming emoji reactions from that sender.") /// Try Loading Text Rules Again public static let retryAccessibility = L10n.tr("Settings", "textRules.retryAccessibility", fallback: "Try Loading Text Rules Again") /// Rules @@ -6203,9 +6201,9 @@ public enum L10n { public static let chat = L10n.tr("Settings", "textRules.archive.chat", fallback: "Chat") /// No Hidden Messages public static let empty = L10n.tr("Settings", "textRules.archive.empty", fallback: "No Hidden Messages") - /// The latest %d hidden messages are kept on this installation and are excluded from shareable backups. + /// The latest %d hidden messages are kept on this device. They aren’t included in app backups. public static func footer(_ p1: Int) -> String { - return L10n.tr("Settings", "textRules.archive.footer", p1, fallback: "The latest %d hidden messages are kept on this installation and are excluded from shareable backups.") + return L10n.tr("Settings", "textRules.archive.footer", p1, fallback: "The latest %d hidden messages are kept on this device. They aren’t included in app backups.") } /// %@: public static func labelPrefix(_ p1: Any) -> String { @@ -6227,16 +6225,10 @@ public enum L10n { public enum Field { /// Message public static let message = L10n.tr("Settings", "textRules.field.message", fallback: "Message") - /// This rule checks the message body. - public static let messageFooter = L10n.tr("Settings", "textRules.field.messageFooter", fallback: "This rule checks the message body.") /// Message or Sender public static let messageOrSender = L10n.tr("Settings", "textRules.field.messageOrSender", fallback: "Message or Sender") - /// This rule checks the message and sender name separately. Either field can match. - public static let messageOrSenderFooter = L10n.tr("Settings", "textRules.field.messageOrSenderFooter", fallback: "This rule checks the message and sender name separately. Either field can match.") /// Sender public static let sender = L10n.tr("Settings", "textRules.field.sender", fallback: "Sender") - /// This rule checks the sender name. - public static let senderFooter = L10n.tr("Settings", "textRules.field.senderFooter", fallback: "This rule checks the sender name.") } public enum Info { /// The saved conversation is unavailable. @@ -6251,8 +6243,6 @@ public enum L10n { public static func follows(_ p1: Any) -> String { return L10n.tr("Settings", "textRules.info.follows", String(describing: p1), fallback: "Follows %@") } - /// The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation. - public static let footer = L10n.tr("Settings", "textRules.info.footer", fallback: "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation.") /// %1$@ (%2$@) public static func inheritedChoice(_ p1: Any, _ p2: Any) -> String { return L10n.tr("Settings", "textRules.info.inheritedChoice", String(describing: p1), String(describing: p2), fallback: "%1$@ (%2$@)") @@ -6289,10 +6279,12 @@ public enum L10n { public static let wholeName = L10n.tr("Settings", "textRules.match.wholeName", fallback: "Whole Name") } public enum New { - /// The phrase can match anywhere in the selected field, including inside a word. - public static let containsFooter = L10n.tr("Settings", "textRules.new.containsFooter", fallback: "The phrase can match anywhere in the selected field, including inside a word.") - /// Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations. - public static let deliveryFooter = L10n.tr("Settings", "textRules.new.deliveryFooter", fallback: "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations.") + /// Matches anywhere in the message, including inside a word. + public static let containsMessageFooter = L10n.tr("Settings", "textRules.new.containsMessageFooter", fallback: "Matches anywhere in the message, including inside a word.") + /// Matches the message or the sender’s name, including inside a word. Reactions from a matching sender are hidden too. + public static let containsMessageOrSenderFooter = L10n.tr("Settings", "textRules.new.containsMessageOrSenderFooter", fallback: "Matches the message or the sender’s name, including inside a word. Reactions from a matching sender are hidden too.") + /// Matches anywhere in the sender’s name, including inside a word. Reactions from that sender are hidden too. + public static let containsSenderFooter = L10n.tr("Settings", "textRules.new.containsSenderFooter", fallback: "Matches anywhere in the sender’s name, including inside a word. Reactions from that sender are hidden too.") /// Look In public static let lookIn = L10n.tr("Settings", "textRules.new.lookIn", fallback: "Look In") /// Match @@ -6301,8 +6293,12 @@ public enum L10n { public static let phrase = L10n.tr("Settings", "textRules.new.phrase", fallback: "Word or phrase") /// New Rule public static let title = L10n.tr("Settings", "textRules.new.title", fallback: "New Rule") - /// The phrase must match the entire field. - public static let wholeFieldFooter = L10n.tr("Settings", "textRules.new.wholeFieldFooter", fallback: "The phrase must match the entire field.") + /// Matches only when the whole message is this phrase. + public static let wholeMessageFooter = L10n.tr("Settings", "textRules.new.wholeMessageFooter", fallback: "Matches only when the whole message is this phrase.") + /// Matches only when the whole message or the whole sender name is this phrase. Reactions from a matching sender are hidden too. + public static let wholeMessageOrSenderFooter = L10n.tr("Settings", "textRules.new.wholeMessageOrSenderFooter", fallback: "Matches only when the whole message or the whole sender name is this phrase. Reactions from a matching sender are hidden too.") + /// Matches only when the sender’s name is exactly this. Reactions from that sender are hidden too. + public static let wholeNameFooter = L10n.tr("Settings", "textRules.new.wholeNameFooter", fallback: "Matches only when the sender’s name is exactly this. Reactions from that sender are hidden too.") } public enum Selection { /// Chats for %@ @@ -6315,14 +6311,14 @@ public enum L10n { public static func count(_ p1: Int) -> String { return L10n.tr("Settings", "textRules.selection.count", p1, fallback: "%d Chats") } - /// All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence. - public static let footer = L10n.tr("Settings", "textRules.selection.footer", fallback: "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence.") + /// All includes chats you join later. + public static let footer = L10n.tr("Settings", "textRules.selection.footer", fallback: "All includes chats you join later.") /// None public static let `none` = L10n.tr("Settings", "textRules.selection.none", fallback: "None") } public enum Types { - /// Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence. - public static let footer = L10n.tr("Settings", "textRules.types.footer", fallback: "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence.") + /// On includes every chat of that type, including chats you join later. + public static let footer = L10n.tr("Settings", "textRules.types.footer", fallback: "On includes every chat of that type, including chats you join later.") /// Hashtag Channels public static let hashtagChannel = L10n.tr("Settings", "textRules.types.hashtagChannel", fallback: "Hashtag Channels") /// Use rules for diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index 6be046b4d2..192ea00dff 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -1503,7 +1503,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "Ausgeblendete Nachrichten bleiben in „Recently Blocked“."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1511,23 +1511,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "Trifft überall in der Nachricht zu, auch innerhalb eines Wortes."; +"textRules.new.wholeMessageFooter" = "Trifft nur zu, wenn die ganze Nachricht dieser Text ist."; +"textRules.new.containsSenderFooter" = "Trifft überall im Namen des Absenders zu, auch innerhalb eines Wortes. Reaktionen von diesem Absender werden ebenfalls ausgeblendet."; +"textRules.new.wholeNameFooter" = "Trifft nur zu, wenn der Name des Absenders genau dieser Text ist. Reaktionen von diesem Absender werden ebenfalls ausgeblendet."; +"textRules.new.containsMessageOrSenderFooter" = "Trifft in der Nachricht oder im Namen des Absenders zu, auch innerhalb eines Wortes. Reaktionen eines zutreffenden Absenders werden ebenfalls ausgeblendet."; +"textRules.new.wholeMessageOrSenderFooter" = "Trifft nur zu, wenn die ganze Nachricht oder der ganze Name des Absenders dieser Text ist. Reaktionen eines zutreffenden Absenders werden ebenfalls ausgeblendet."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "Ist er eingeschaltet, gilt er für jeden Chat dieses Typs, auch für Chats, denen du später beitrittst."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1535,10 +1534,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "„All“ gilt auch für Chats, denen du später beitrittst."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "Die letzten %d ausgeblendeten Nachrichten bleiben auf diesem Gerät. Sie sind nicht in Sicherungen der App-Daten enthalten."; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "Regel"; "textRules.archive.chat" = "Chat"; @@ -1560,7 +1559,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index e45ae1ee95..5e9640199a 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -1489,7 +1489,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "Hidden messages stay in Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1497,23 +1497,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "Matches anywhere in the message, including inside a word."; +"textRules.new.wholeMessageFooter" = "Matches only when the whole message is this phrase."; +"textRules.new.containsSenderFooter" = "Matches anywhere in the sender’s name, including inside a word. Reactions from that sender are hidden too."; +"textRules.new.wholeNameFooter" = "Matches only when the sender’s name is exactly this. Reactions from that sender are hidden too."; +"textRules.new.containsMessageOrSenderFooter" = "Matches the message or the sender’s name, including inside a word. Reactions from a matching sender are hidden too."; +"textRules.new.wholeMessageOrSenderFooter" = "Matches only when the whole message or the whole sender name is this phrase. Reactions from a matching sender are hidden too."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "On includes every chat of that type, including chats you join later."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1521,10 +1520,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "All includes chats you join later."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this device. They aren’t included in app backups."; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "Rule"; "textRules.archive.chat" = "Chat"; @@ -1545,7 +1544,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index 1c671daf7b..b4fd003236 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -1503,7 +1503,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "Los mensajes ocultos siguen en Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1511,23 +1511,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "Coincide en cualquier parte del mensaje, incluso dentro de una palabra."; +"textRules.new.wholeMessageFooter" = "Coincide solo cuando todo el mensaje es esta frase."; +"textRules.new.containsSenderFooter" = "Coincide en cualquier parte del nombre del remitente, incluso dentro de una palabra. Las reacciones de ese remitente también se ocultan."; +"textRules.new.wholeNameFooter" = "Coincide solo cuando el nombre del remitente es exactamente este. Las reacciones de ese remitente también se ocultan."; +"textRules.new.containsMessageOrSenderFooter" = "Coincide con el mensaje o con el nombre del remitente, incluso dentro de una palabra. Las reacciones de un remitente que coincida también se ocultan."; +"textRules.new.wholeMessageOrSenderFooter" = "Coincide solo cuando todo el mensaje o todo el nombre del remitente es esta frase. Las reacciones de un remitente que coincida también se ocultan."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "Cuando está activado, se incluyen todos los chats de ese tipo, incluso los chats a los que te unas más tarde."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1535,10 +1534,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "All incluye los chats a los que te unas más tarde."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "Los %d mensajes ocultos más recientes se guardan en este dispositivo. No se incluyen en las copias de seguridad de la app."; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "Regla"; "textRules.archive.chat" = "Chat"; @@ -1560,7 +1559,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index 0727a6fb2d..52d890882c 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -1503,7 +1503,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "Les messages masqués restent dans Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1511,23 +1511,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "Ce texte correspond s’il figure n’importe où dans le message, y compris à l’intérieur d’un mot."; +"textRules.new.wholeMessageFooter" = "Ce texte ne correspond que si le message entier est ce texte."; +"textRules.new.containsSenderFooter" = "Ce texte correspond s’il figure n’importe où dans le nom de l’expéditeur, y compris à l’intérieur d’un mot. Les réactions de cet expéditeur sont aussi masquées."; +"textRules.new.wholeNameFooter" = "Ce texte ne correspond que si le nom de l’expéditeur est exactement ce texte. Les réactions de cet expéditeur sont aussi masquées."; +"textRules.new.containsMessageOrSenderFooter" = "Ce texte correspond s’il figure n’importe où dans le message ou n’importe où dans le nom de l’expéditeur, y compris à l’intérieur d’un mot. Les réactions d’un expéditeur dont le nom correspond sont aussi masquées."; +"textRules.new.wholeMessageOrSenderFooter" = "Ce texte ne correspond que si le message entier ou le nom entier de l’expéditeur est ce texte. Les réactions d’un expéditeur dont le nom correspond sont aussi masquées."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "Si cette option est activée, toutes les discussions de ce type sont incluses, y compris celles que vous rejoignez plus tard."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1535,10 +1534,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "All inclut les discussions que vous rejoignez plus tard."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "Les %d derniers messages masqués sont conservés sur cet appareil. Ils ne sont pas inclus dans les sauvegardes des données de l’app."; "textRules.archive.labelPrefix" = "%@ : "; "textRules.archive.rule" = "Règle"; "textRules.archive.chat" = "Discussion"; @@ -1560,7 +1559,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 1080052475..e9ab97c7ca 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -1501,7 +1501,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "I messaggi nascosti restano in “Recently Blocked”."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1509,23 +1509,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "Corrisponde in qualsiasi punto del messaggio, anche all’interno di una parola."; +"textRules.new.wholeMessageFooter" = "Corrisponde solo quando l’intero messaggio è questa frase."; +"textRules.new.containsSenderFooter" = "Corrisponde in qualsiasi punto del nome del mittente, anche all’interno di una parola. Anche le reazioni di quel mittente vengono nascoste."; +"textRules.new.wholeNameFooter" = "Corrisponde solo quando il nome del mittente è esattamente questo. Anche le reazioni di quel mittente vengono nascoste."; +"textRules.new.containsMessageOrSenderFooter" = "Corrisponde in qualsiasi punto del messaggio o del nome del mittente, anche all’interno di una parola. Anche le reazioni di un mittente che corrisponde vengono nascoste."; +"textRules.new.wholeMessageOrSenderFooter" = "Corrisponde solo quando l’intero messaggio o l’intero nome del mittente è questa frase. Anche le reazioni di un mittente che corrisponde vengono nascoste."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "Se attivo, include tutte le chat di quel tipo, anche quelle a cui ti unisci in seguito."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1533,10 +1532,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "“All” include le chat a cui ti unisci in seguito."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "Gli ultimi %d messaggi nascosti sono conservati su questo dispositivo. Non sono inclusi nei backup dell’app."; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "Regola"; "textRules.archive.chat" = "Chat"; @@ -1558,7 +1557,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index 856140c6d6..d69464ee02 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -1491,7 +1491,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "숨겨진 메시지는 Recently Blocked에 남습니다."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1499,23 +1499,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "메시지 어디에서든, 단어 안에서도 일치합니다."; +"textRules.new.wholeMessageFooter" = "메시지 전체가 이 문구일 때만 일치합니다."; +"textRules.new.containsSenderFooter" = "발신자 이름 어디에서든, 단어 안에서도 일치합니다. 그 발신자의 반응도 숨겨집니다."; +"textRules.new.wholeNameFooter" = "발신자 이름이 정확히 이 문구일 때만 일치합니다. 그 발신자의 반응도 숨겨집니다."; +"textRules.new.containsMessageOrSenderFooter" = "메시지 또는 발신자 이름 어디에서든, 단어 안에서도 일치합니다. 일치하는 발신자의 반응도 숨겨집니다."; +"textRules.new.wholeMessageOrSenderFooter" = "메시지 전체 또는 발신자 이름 전체가 이 문구일 때만 일치합니다. 일치하는 발신자의 반응도 숨겨집니다."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "켜면 해당 유형의 모든 채팅이 포함됩니다. 나중에 참여하는 채팅도 포함됩니다."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1523,10 +1522,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "All은 나중에 참여하는 채팅도 포함합니다."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "최근 숨겨진 메시지 %d개가 이 기기에 보관됩니다. 앱 백업에는 포함되지 않습니다."; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "규칙"; "textRules.archive.chat" = "채팅"; @@ -1548,7 +1547,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index 199b4141c2..c5d55106b7 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -1503,7 +1503,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "Verborgen berichten blijven in Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1511,23 +1511,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "Komt ergens in het bericht overeen, ook binnen een woord."; +"textRules.new.wholeMessageFooter" = "Komt alleen overeen als het hele bericht deze tekst is."; +"textRules.new.containsSenderFooter" = "Komt ergens in de naam van de afzender overeen, ook binnen een woord. Reacties van die afzender worden ook verborgen."; +"textRules.new.wholeNameFooter" = "Komt alleen overeen als de naam van de afzender precies deze tekst is. Reacties van die afzender worden ook verborgen."; +"textRules.new.containsMessageOrSenderFooter" = "Komt in het bericht of in de naam van de afzender overeen, ook binnen een woord. Reacties van een overeenkomende afzender worden ook verborgen."; +"textRules.new.wholeMessageOrSenderFooter" = "Komt alleen overeen als het hele bericht of de hele naam van de afzender deze tekst is. Reacties van een overeenkomende afzender worden ook verborgen."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "Staat de schakelaar aan, dan geldt die voor elk gesprek van dat type, ook voor gesprekken waaraan je later deelneemt."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1535,10 +1534,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "All geldt ook voor gesprekken waaraan je later deelneemt."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "De laatste %d verborgen berichten worden op dit apparaat bewaard. Ze zijn niet in de app-data back-up opgenomen."; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "Regel"; "textRules.archive.chat" = "Gesprek"; @@ -1560,7 +1559,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index e5b9ad13a7..fedc331640 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -1503,7 +1503,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "Ukryte wiadomości pozostają w Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1511,23 +1511,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "Pasuje w dowolnym miejscu wiadomości, także wewnątrz słowa."; +"textRules.new.wholeMessageFooter" = "Pasuje tylko wtedy, gdy cała wiadomość jest tym tekstem."; +"textRules.new.containsSenderFooter" = "Pasuje w dowolnym miejscu nazwy nadawcy, także wewnątrz słowa. Reakcje od tego nadawcy są też ukryte."; +"textRules.new.wholeNameFooter" = "Pasuje tylko wtedy, gdy nazwa nadawcy jest dokładnie tym tekstem. Reakcje od tego nadawcy są też ukryte."; +"textRules.new.containsMessageOrSenderFooter" = "Pasuje w dowolnym miejscu wiadomości lub nazwy nadawcy, także wewnątrz słowa. Reakcje od pasującego nadawcy są też ukryte."; +"textRules.new.wholeMessageOrSenderFooter" = "Pasuje tylko wtedy, gdy cała wiadomość lub cała nazwa nadawcy jest tym tekstem. Reakcje od pasującego nadawcy są też ukryte."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "Włączenie obejmuje wszystkie czaty tego typu, w tym te, do których dołączysz później."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1535,10 +1534,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "All obejmuje czaty, do których dołączysz później."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "To urządzenie przechowuje %d najnowszych ukrytych wiadomości. Kopia zapasowa danych aplikacji ich nie obejmuje."; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "Reguła"; "textRules.archive.chat" = "Czat"; @@ -1560,7 +1559,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index 411dc5f424..388a0cee83 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -1501,7 +1501,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "As mensagens ocultas ficam em Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1509,23 +1509,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "Corresponde em qualquer parte da mensagem, incluindo dentro de uma palavra."; +"textRules.new.wholeMessageFooter" = "Só corresponde se a mensagem inteira for esta frase."; +"textRules.new.containsSenderFooter" = "Corresponde em qualquer parte do nome do remetente, incluindo dentro de uma palavra. As reações desse remetente também ficam ocultas."; +"textRules.new.wholeNameFooter" = "Só corresponde se o nome do remetente for exatamente este. As reações desse remetente também ficam ocultas."; +"textRules.new.containsMessageOrSenderFooter" = "Corresponde em qualquer parte da mensagem ou do nome do remetente, incluindo dentro de uma palavra. As reações de um remetente que corresponda também ficam ocultas."; +"textRules.new.wholeMessageOrSenderFooter" = "Só corresponde se a mensagem inteira ou o nome inteiro do remetente for esta frase. As reações de um remetente que corresponda também ficam ocultas."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "Quando ativado, inclui todas as conversas desse tipo, incluindo as conversas a que aderir mais tarde."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1533,10 +1532,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "All inclui as conversas a que aderir mais tarde."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "As %d mensagens ocultas mais recentes são guardadas neste dispositivo. Não são incluídas no backup da app."; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "Regra"; "textRules.archive.chat" = "Conversa"; @@ -1558,7 +1557,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index 02a1f9b857..985c1295b9 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -1503,7 +1503,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "Скрытые сообщения остаются в «Recently Blocked»."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1511,23 +1511,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "Совпадает в любом месте сообщения, в том числе внутри слова."; +"textRules.new.wholeMessageFooter" = "Совпадает, только если всё сообщение равно этой фразе."; +"textRules.new.containsSenderFooter" = "Совпадает в любом месте имени отправителя, в том числе внутри слова. Реакции от этого отправителя тоже скрыты."; +"textRules.new.wholeNameFooter" = "Совпадает, только если имя отправителя в точности такое. Реакции от этого отправителя тоже скрыты."; +"textRules.new.containsMessageOrSenderFooter" = "Совпадает в любом месте сообщения или имени отправителя, в том числе внутри слова. Если совпало имя, реакции этого отправителя тоже скрыты."; +"textRules.new.wholeMessageOrSenderFooter" = "Совпадает, только если всё сообщение или всё имя отправителя равно этой фразе. Если совпало имя, реакции этого отправителя тоже скрыты."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "Включённый переключатель охватывает все чаты этого типа, включая те, к которым ты присоединишься позже."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1535,10 +1534,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "«All» включает чаты, к которым ты присоединишься позже."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "Последние %d скрытых сообщений хранятся на этом устройстве. В резервную копию приложения они не входят."; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "Правило"; "textRules.archive.chat" = "Чат"; @@ -1560,7 +1559,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 24e28ed251..243210dcf4 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -1503,7 +1503,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "Приховані повідомлення залишаються у «Recently Blocked»."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1511,23 +1511,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "Збігається будь-де в повідомленні, зокрема всередині слова."; +"textRules.new.wholeMessageFooter" = "Збігається лише тоді, коли все повідомлення — ця фраза."; +"textRules.new.containsSenderFooter" = "Збігається будь-де в імені відправника, зокрема всередині слова. Реакції від цього відправника також приховано."; +"textRules.new.wholeNameFooter" = "Збігається лише тоді, коли ім'я відправника — точно ця фраза. Реакції від цього відправника також приховано."; +"textRules.new.containsMessageOrSenderFooter" = "Збігається будь-де в повідомленні або в імені відправника, зокрема всередині слова. Якщо збігається ім'я, реакції від цього відправника також приховано."; +"textRules.new.wholeMessageOrSenderFooter" = "Збігається лише тоді, коли все повідомлення або все ім'я відправника — ця фраза. Якщо збігається ім'я, реакції від цього відправника також приховано."; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "Коли увімкнено, це охоплює всі чати цього типу, зокрема ті, до яких ти приєднаєшся пізніше."; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1535,10 +1534,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "«All» охоплює чати, до яких ти приєднаєшся пізніше."; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "На цьому пристрої зберігаються останні %d прихованих повідомлень. Вони не входять до резервної копії застосунку."; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "Правило"; "textRules.archive.chat" = "Чат"; @@ -1560,7 +1559,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index 35c07e9ff8..e465b49a4b 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -1503,7 +1503,7 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Deleting a rule leaves its hidden messages in Recently Blocked."; +"textRules.deleteFooter" = "隐藏消息仍会保留在“Recently Blocked”中。"; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; @@ -1511,23 +1511,22 @@ "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; "textRules.new.match" = "Match"; -"textRules.new.containsFooter" = "The phrase can match anywhere in the selected field, including inside a word."; -"textRules.new.wholeFieldFooter" = "The phrase must match the entire field."; -"textRules.new.deliveryFooter" = "Rules apply to incoming messages in conversations that use Text Rules. Saved messages stay in their conversations."; -"textRules.reactionFooter" = "A sender-name match also hides incoming emoji reactions from that sender."; +"textRules.new.containsMessageFooter" = "只要在消息中出现就会匹配,包括某个词的一部分。"; +"textRules.new.wholeMessageFooter" = "仅当整条消息就是这段文字时才会匹配。"; +"textRules.new.containsSenderFooter" = "只要在发送者名称中出现就会匹配,包括某个词的一部分。该发送者的表情反应也会被隐藏。"; +"textRules.new.wholeNameFooter" = "仅当发送者名称正好是这段文字时才会匹配。该发送者的表情反应也会被隐藏。"; +"textRules.new.containsMessageOrSenderFooter" = "只要在消息或发送者名称中出现就会匹配,包括某个词的一部分。发送者名称匹配时,其表情反应也会被隐藏。"; +"textRules.new.wholeMessageOrSenderFooter" = "仅当整条消息或发送者的整个名称就是这段文字时才会匹配。发送者名称匹配时,其表情反应也会被隐藏。"; "textRules.field.message" = "Message"; "textRules.field.sender" = "Sender"; "textRules.field.messageOrSender" = "Message or Sender"; -"textRules.field.messageFooter" = "This rule checks the message body."; -"textRules.field.senderFooter" = "This rule checks the sender name."; -"textRules.field.messageOrSenderFooter" = "This rule checks the message and sender name separately. Either field can match."; "textRules.match.contains" = "Contains"; "textRules.match.wholeMessage" = "Whole Message"; "textRules.match.wholeName" = "Whole Name"; "textRules.match.wholeField" = "Whole Field"; "textRules.ruleSummary" = "%1$@ · %2$@"; "textRules.types.header" = "Use rules for"; -"textRules.types.footer" = "Turn on a type to include all its chats. Open Chats below a switch to choose specific chats. Explicit conversation choices take precedence."; +"textRules.types.footer" = "开启后,该类型的所有聊天都会包括在内,包括您之后加入的聊天。"; "textRules.types.publicChannel" = "Public"; "textRules.types.hashtagChannel" = "Hashtag Channels"; "textRules.types.privateChannel" = "Private Channels"; @@ -1535,10 +1534,10 @@ "textRules.selection.none" = "None"; "textRules.selection.count" = "%d Chats"; "textRules.selection.accessibilityChats" = "Chats for %@"; -"textRules.selection.footer" = "All includes future chats of this type. An individual selection follows only the selected chats. Explicit conversation choices take precedence."; +"textRules.selection.footer" = "“All”会包括您之后加入的聊天。"; "textRules.archive.title" = "Recently Blocked"; "textRules.archive.empty" = "No Hidden Messages"; -"textRules.archive.footer" = "The latest %d hidden messages are kept on this installation and are excluded from shareable backups."; +"textRules.archive.footer" = "最近的 %d 条隐藏消息会保留在此设备上。这些消息不会包含在应用备份中。"; "textRules.archive.labelPrefix" = "%@: "; "textRules.archive.rule" = "规则"; "textRules.archive.chat" = "聊天"; @@ -1560,7 +1559,6 @@ "textRules.info.follows" = "Follows %@"; "textRules.info.excluded" = "Not included in %@"; "textRules.info.explicit" = "Set for this conversation"; -"textRules.info.footer" = "The type choice follows your Text Rules selection. On or Off here takes precedence for this conversation."; "textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; "textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; diff --git a/MC1/Views/Chats/Components/ConversationTextRulesSection.swift b/MC1/Views/Chats/Components/ConversationTextRulesSection.swift index a94cb82e0b..e8e6202217 100644 --- a/MC1/Views/Chats/Components/ConversationTextRulesSection.swift +++ b/MC1/Views/Chats/Components/ConversationTextRulesSection.swift @@ -71,16 +71,16 @@ struct ConversationTextRulesSection: View { } header: { Text(L10n.Settings.TextRules.title) } footer: { - VStack(alignment: .leading) { - if appState.textRulesPreference == nil { - Text(L10n.Settings.TextRules.loadFailed) - } else if key == nil { - Text(Strings.conversationUnavailable) - } else { - Text(Strings.footer) - } - if let radioName { - Text(Strings.radio(radioName)) + if appState.textRulesPreference == nil || key == nil || radioName != nil { + VStack(alignment: .leading) { + if appState.textRulesPreference == nil { + Text(L10n.Settings.TextRules.loadFailed) + } else if key == nil { + Text(Strings.conversationUnavailable) + } + if let radioName { + Text(Strings.radio(radioName)) + } } } } diff --git a/MC1/Views/Settings/Sections/NewTextRuleSheet.swift b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift index 0323e28d9f..2335e8b9ab 100644 --- a/MC1/Views/Settings/Sections/NewTextRuleSheet.swift +++ b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift @@ -14,6 +14,23 @@ struct NewTextRuleSheet: View { phrase.trimmingCharacters(in: .whitespacesAndNewlines) } + private var ruleFooter: String { + switch (lookIn, match) { + case (.message, .contains): + L10n.Settings.TextRules.New.containsMessageFooter + case (.message, .wholeField): + L10n.Settings.TextRules.New.wholeMessageFooter + case (.sender, .contains): + L10n.Settings.TextRules.New.containsSenderFooter + case (.sender, .wholeField): + L10n.Settings.TextRules.New.wholeNameFooter + case (.messageOrSender, .contains): + L10n.Settings.TextRules.New.containsMessageOrSenderFooter + case (.messageOrSender, .wholeField): + L10n.Settings.TextRules.New.wholeMessageOrSenderFooter + } + } + var body: some View { NavigationStack { Form { @@ -32,14 +49,7 @@ struct NewTextRuleSheet: View { } .pickerStyle(.menu) } footer: { - VStack(alignment: .leading) { - Text(match == .contains ? L10n.Settings.TextRules.New.containsFooter : L10n.Settings.TextRules.New.wholeFieldFooter) - Text(lookIn.footer) - if lookIn != .message { - Text(L10n.Settings.TextRules.reactionFooter) - } - Text(L10n.Settings.TextRules.New.deliveryFooter) - } + Text(ruleFooter) } .themedRowBackground(theme) } @@ -79,14 +89,6 @@ extension TextRulesPreference.Rule.LookIn { case .messageOrSender: L10n.Settings.TextRules.Field.messageOrSender } } - - var footer: String { - switch self { - case .message: L10n.Settings.TextRules.Field.messageFooter - case .sender: L10n.Settings.TextRules.Field.senderFooter - case .messageOrSender: L10n.Settings.TextRules.Field.messageOrSenderFooter - } - } } extension TextRulesPreference.Rule.Match { diff --git a/MC1/Views/Settings/Sections/TextRulesSettingsView.swift b/MC1/Views/Settings/Sections/TextRulesSettingsView.swift index e3cf04aac5..ab6911fe6e 100644 --- a/MC1/Views/Settings/Sections/TextRulesSettingsView.swift +++ b/MC1/Views/Settings/Sections/TextRulesSettingsView.swift @@ -56,11 +56,6 @@ struct TextRulesSettingsView: View { Text(verbatim: rule.summary) .font(.subheadline) .foregroundStyle(.secondary) - if rule.lookIn != .message { - Text(L10n.Settings.TextRules.reactionFooter) - .font(.footnote) - .foregroundStyle(.secondary) - } } .accessibilityElement(children: .combine) .swipeActions { From 3b9f595b2719debdcd778e20c2e91b91c22ff695 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:04:35 -0800 Subject: [PATCH 07/10] ui: show recently blocked messages as a log --- MC1/Resources/Generated/L10n.swift | 8 ++ .../Localization/de.lproj/Settings.strings | 4 + .../Localization/en.lproj/Settings.strings | 4 + .../Localization/es.lproj/Settings.strings | 4 + .../Localization/fr.lproj/Settings.strings | 4 + .../Localization/it.lproj/Settings.strings | 4 + .../Localization/ko.lproj/Settings.strings | 4 + .../Localization/nl.lproj/Settings.strings | 4 + .../Localization/pl.lproj/Settings.strings | 4 + .../Localization/pt.lproj/Settings.strings | 4 + .../Localization/ru.lproj/Settings.strings | 4 + .../Localization/uk.lproj/Settings.strings | 4 + .../zh-Hans.lproj/Settings.strings | 4 + .../Sections/RecentlyBlockedRow.swift | 85 +++++++++++ .../Sections/RecentlyBlockedView.swift | 135 ++++++++++-------- .../Settings/RecentlyBlockedRowTests.swift | 94 ++++++++++++ 16 files changed, 310 insertions(+), 60 deletions(-) create mode 100644 MC1/Views/Settings/Sections/RecentlyBlockedRow.swift create mode 100644 MC1Tests/Views/Settings/RecentlyBlockedRowTests.swift diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index cb16de3a30..27ed4b7bc4 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -6197,6 +6197,14 @@ public enum L10n { /// Text Rules public static let title = L10n.tr("Settings", "textRules.title", fallback: "Text Rules") public enum Archive { + /// Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. + public static func caption(_ p1: Any, _ p2: Any, _ p3: Any) -> String { + return L10n.tr("Settings", "textRules.archive.caption", String(describing: p1), String(describing: p2), String(describing: p3), fallback: "%1$@ · “%2$@” · %3$@") + } + /// Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. + public static func captionWithoutChat(_ p1: Any, _ p2: Any) -> String { + return L10n.tr("Settings", "textRules.archive.captionWithoutChat", String(describing: p1), String(describing: p2), fallback: "“%1$@” · %2$@") + } /// Chat public static let chat = L10n.tr("Settings", "textRules.archive.chat", fallback: "Chat") /// No Hidden Messages diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index 192ea00dff..ad3424db17 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -1539,6 +1539,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "Die letzten %d ausgeblendeten Nachrichten bleiben auf diesem Gerät. Sie sind nicht in Sicherungen der App-Daten enthalten."; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "Regel"; "textRules.archive.chat" = "Chat"; "textRules.archive.myNode" = "Mein Knoten"; diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index 5e9640199a..19b3af075d 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -1525,6 +1525,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "The latest %d hidden messages are kept on this device. They aren’t included in app backups."; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "Rule"; "textRules.archive.chat" = "Chat"; "textRules.archive.myNode" = "My Node"; diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index b4fd003236..cad945796a 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -1539,6 +1539,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "Los %d mensajes ocultos más recientes se guardan en este dispositivo. No se incluyen en las copias de seguridad de la app."; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "Regla"; "textRules.archive.chat" = "Chat"; "textRules.archive.myNode" = "Mi nodo"; diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index 52d890882c..f32a97199d 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -1539,6 +1539,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "Les %d derniers messages masqués sont conservés sur cet appareil. Ils ne sont pas inclus dans les sauvegardes des données de l’app."; "textRules.archive.labelPrefix" = "%@ : "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "Règle"; "textRules.archive.chat" = "Discussion"; "textRules.archive.myNode" = "Mon nœud"; diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index e9ab97c7ca..46ff8fdbde 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -1537,6 +1537,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "Gli ultimi %d messaggi nascosti sono conservati su questo dispositivo. Non sono inclusi nei backup dell’app."; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "Regola"; "textRules.archive.chat" = "Chat"; "textRules.archive.myNode" = "Il mio nodo"; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index d69464ee02..3850af49b4 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -1527,6 +1527,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "최근 숨겨진 메시지 %d개가 이 기기에 보관됩니다. 앱 백업에는 포함되지 않습니다."; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "규칙"; "textRules.archive.chat" = "채팅"; "textRules.archive.myNode" = "내 노드"; diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index c5d55106b7..62522cd48d 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -1539,6 +1539,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "De laatste %d verborgen berichten worden op dit apparaat bewaard. Ze zijn niet in de app-data back-up opgenomen."; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "Regel"; "textRules.archive.chat" = "Gesprek"; "textRules.archive.myNode" = "Mijn knooppunt"; diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index fedc331640..c737778574 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -1539,6 +1539,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "To urządzenie przechowuje %d najnowszych ukrytych wiadomości. Kopia zapasowa danych aplikacji ich nie obejmuje."; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "Reguła"; "textRules.archive.chat" = "Czat"; "textRules.archive.myNode" = "Mój węzeł"; diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index 388a0cee83..a202b3c267 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -1537,6 +1537,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "As %d mensagens ocultas mais recentes são guardadas neste dispositivo. Não são incluídas no backup da app."; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "Regra"; "textRules.archive.chat" = "Conversa"; "textRules.archive.myNode" = "O meu nó"; diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index 985c1295b9..23930d1f95 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -1539,6 +1539,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "Последние %d скрытых сообщений хранятся на этом устройстве. В резервную копию приложения они не входят."; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "Правило"; "textRules.archive.chat" = "Чат"; "textRules.archive.myNode" = "Мой узел"; diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 243210dcf4..0fd341b1af 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -1539,6 +1539,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "На цьому пристрої зберігаються останні %d прихованих повідомлень. Вони не входять до резервної копії застосунку."; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "Правило"; "textRules.archive.chat" = "Чат"; "textRules.archive.myNode" = "Мій вузол"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index e465b49a4b..4611900aa5 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -1539,6 +1539,10 @@ "textRules.archive.empty" = "No Hidden Messages"; "textRules.archive.footer" = "最近的 %d 条隐藏消息会保留在此设备上。这些消息不会包含在应用备份中。"; "textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; "textRules.archive.rule" = "规则"; "textRules.archive.chat" = "聊天"; "textRules.archive.myNode" = "我的节点"; diff --git a/MC1/Views/Settings/Sections/RecentlyBlockedRow.swift b/MC1/Views/Settings/Sections/RecentlyBlockedRow.swift new file mode 100644 index 0000000000..74e2418b5b --- /dev/null +++ b/MC1/Views/Settings/Sections/RecentlyBlockedRow.swift @@ -0,0 +1,85 @@ +import MC1Services +import SwiftUI + +struct RecentlyBlockedRow: View { + let entry: RecentlyBlockedMessageDTO + + var body: some View { + VStack(alignment: .leading, spacing: Metrics.lineSpacing) { + HStack(alignment: .firstTextBaseline, spacing: Metrics.titleSpacing) { + if let sender = entry.sender { + Text(Self.highlighted(sender, matches: entry.match.senderHighlights, base: .primary)) + .font(.headline) + .lineLimit(1) + } + Spacer(minLength: Metrics.titleSpacing) + ConversationTimestamp(date: entry.arrivedAt) + } + Text(Self.highlighted(entry.body, matches: entry.match.bodyHighlights, base: .secondary)) + .font(.subheadline) + Text(Self.caption( + conversationName: entry.conversationName, + phrase: entry.match.rule.phrase, + summary: entry.match.rule.summary + )) + .font(.footnote) + .foregroundStyle(.secondary) + } + .fixedSize(horizontal: false, vertical: true) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Self.accessibilityLabel(for: entry)) + } + + static func caption(conversationName: String?, phrase: String, summary: String) -> String { + if let conversationName { + return L10n.Settings.TextRules.Archive.caption(conversationName, phrase, summary) + } + return L10n.Settings.TextRules.Archive.captionWithoutChat(phrase, summary) + } + + static func accessibilityLabel(for entry: RecentlyBlockedMessageDTO) -> String { + var parts: [String] = [] + if let sender = entry.sender { + parts.append(labeled(L10n.Settings.TextRules.Field.sender, sender)) + } + parts.append(labeled(L10n.Settings.TextRules.Field.message, entry.body)) + let rule = L10n.Settings.TextRules.ruleSummary(entry.match.rule.phrase, entry.match.rule.summary) + parts.append(labeled(L10n.Settings.TextRules.Archive.rule, rule)) + if let conversationName = entry.conversationName { + parts.append(labeled(L10n.Settings.TextRules.Archive.chat, conversationName)) + } + let time = entry.arrivedAt.formatted(.dateTime.month(.abbreviated).day().hour().minute()) + parts.append(labeled(L10n.Settings.TextRules.Archive.time, time)) + return parts.formatted(.list(type: .and)) + } + + static func highlighted( + _ text: String, + matches: [TextRulesPreference.RuleMatch.Highlight], + base: Color + ) -> AttributedString { + var attributed = AttributedString(text) + attributed.foregroundColor = base + for match in matches { + guard let range = match.range(in: text), + let start = AttributedString.Index(range.lowerBound, within: attributed), + let end = AttributedString.Index(range.upperBound, within: attributed) else { continue } + attributed[start.. String { + L10n.Settings.TextRules.Archive.labelPrefix(label) + value + } + + private enum Metrics { + static let lineSpacing: CGFloat = 4 + static let titleSpacing: CGFloat = 8 + static let matchHighlightOpacity = 0.4 + static var matchHighlight: Color { + Color.yellow.opacity(matchHighlightOpacity) + } + } +} diff --git a/MC1/Views/Settings/Sections/RecentlyBlockedView.swift b/MC1/Views/Settings/Sections/RecentlyBlockedView.swift index 4f9abdc95b..d75eda7884 100644 --- a/MC1/Views/Settings/Sections/RecentlyBlockedView.swift +++ b/MC1/Views/Settings/Sections/RecentlyBlockedView.swift @@ -2,25 +2,31 @@ import MC1Services import SwiftUI struct RecentlyBlockedView: View { + struct RadioGroup: Identifiable { + let radioID: UUID + let radioName: String? + let entries: [RecentlyBlockedMessageDTO] + + var id: UUID { + radioID + } + } + @Environment(\.appState) private var appState @Environment(\.appTheme) private var theme @State private var entries: [RecentlyBlockedMessageDTO] = [] @State private var errorMessage: String? var body: some View { + let groups = Self.radioGroups(in: entries) List { - Section { - if entries.isEmpty { - Text(L10n.Settings.TextRules.Archive.empty) - .foregroundStyle(.secondary) - } - ForEach(entries) { entry in - archiveRow(entry) + if groups.count > 1 { + ForEach(groups) { group in + radioSection(group, isLast: group.id == groups.last?.id) } - } footer: { - Text(L10n.Settings.TextRules.Archive.footer(PersistenceStore.recentlyBlockedRetentionLimit)) + } else { + messageSection(entries) } - .themedRowBackground(theme) } .themedCanvas(theme) .navigationTitle(L10n.Settings.TextRules.Archive.title) @@ -36,64 +42,73 @@ struct RecentlyBlockedView: View { } } - private func archiveRow(_ entry: RecentlyBlockedMessageDTO) -> some View { - VStack(alignment: .leading) { - labeled( - L10n.Settings.TextRules.Field.message, - Text(highlighted(entry.body, matches: entry.match.bodyHighlights)) - ) - VStack(alignment: .leading) { - labeled( - L10n.Settings.TextRules.Archive.rule, - Text(verbatim: L10n.Settings.TextRules.ruleSummary( - entry.match.rule.phrase, - entry.match.rule.summary - )) - ) - if let sender = entry.sender { - labeled( - L10n.Settings.TextRules.Field.sender, - Text(highlighted(sender, matches: entry.match.senderHighlights)) - ) - } + static func radioGroups(in entries: [RecentlyBlockedMessageDTO]) -> [RadioGroup] { + var order: [UUID] = [] + var grouped: [UUID: [RecentlyBlockedMessageDTO]] = [:] + var names: [UUID: String] = [:] + for entry in entries { + let radioID = entry.identity.radioID + if grouped[radioID] == nil { + order.append(radioID) } - .font(.subheadline) - VStack(alignment: .leading) { - labeled( - L10n.Settings.TextRules.Archive.chat, - Text(verbatim: entry.conversationName ?? L10n.Settings.TextRules.Archive.unknownConversation) - ) - labeled( - L10n.Settings.TextRules.Archive.myNode, - Text(verbatim: entry.radioName ?? L10n.Settings.TextRules.Archive.unknownRadio) - ) - labeled( - L10n.Settings.TextRules.Archive.time, - Text(entry.arrivedAt, format: .dateTime.month().day().hour().minute()) - ) + grouped[radioID, default: []].append(entry) + if names[radioID] == nil, let radioName = entry.radioName { + names[radioID] = radioName } - .font(.footnote) - .foregroundStyle(.secondary) } - .fixedSize(horizontal: false, vertical: true) - .accessibilityElement(children: .combine) + return order.map { radioID in + RadioGroup(radioID: radioID, radioName: names[radioID], entries: grouped[radioID] ?? []) + } } - private func highlighted(_ text: String, matches: [TextRulesPreference.RuleMatch.Highlight]) -> AttributedString { - var attributed = AttributedString(text) - for match in matches { - guard let range = match.range(in: text), - let start = AttributedString.Index(range.lowerBound, within: attributed), - let end = AttributedString.Index(range.upperBound, within: attributed) else { continue } - attributed[start.. some View { + Section { + if rows.isEmpty { + Text(L10n.Settings.TextRules.Archive.empty) + .foregroundStyle(.secondary) + } + ForEach(rows) { entry in + RecentlyBlockedRow(entry: entry) + } + } footer: { + retentionFooter } - return attributed + .themedRowBackground(theme) + } + + @ViewBuilder + private func radioSection(_ group: RadioGroup, isLast: Bool) -> some View { + if isLast { + Section { + messageRows(group.entries) + } header: { + Text(radioHeader(group)) + } footer: { + retentionFooter + } + .themedRowBackground(theme) + } else { + Section { + messageRows(group.entries) + } header: { + Text(radioHeader(group)) + } + .themedRowBackground(theme) + } + } + + private func messageRows(_ rows: [RecentlyBlockedMessageDTO]) -> some View { + ForEach(rows) { entry in + RecentlyBlockedRow(entry: entry) + } + } + + private func radioHeader(_ group: RadioGroup) -> String { + group.radioName ?? L10n.Settings.TextRules.Archive.unknownRadio } - private func labeled(_ label: String, _ value: Text) -> Text { - Text(verbatim: L10n.Settings.TextRules.Archive.labelPrefix(label)) + value + private var retentionFooter: Text { + Text(L10n.Settings.TextRules.Archive.footer(PersistenceStore.recentlyBlockedRetentionLimit)) } private func refresh(from store: PersistenceStore) async { diff --git a/MC1Tests/Views/Settings/RecentlyBlockedRowTests.swift b/MC1Tests/Views/Settings/RecentlyBlockedRowTests.swift new file mode 100644 index 0000000000..8b2a0ba3d6 --- /dev/null +++ b/MC1Tests/Views/Settings/RecentlyBlockedRowTests.swift @@ -0,0 +1,94 @@ +import Foundation +@testable import MC1 +import MC1Services +import Testing + +@Suite("Recently Blocked rows") +@MainActor +struct RecentlyBlockedRowTests { + @Test + func `caption names the chat, the phrase, and the rule`() { + let caption = RecentlyBlockedRow.caption( + conversationName: "Dock", + phrase: "spare", + summary: "Contains · Message" + ) + #expect(caption == "Dock · “spare” · Contains · Message") + } + + @Test + func `caption omits a missing chat`() { + let caption = RecentlyBlockedRow.caption( + conversationName: nil, + phrase: "spare", + summary: "Contains · Message" + ) + #expect(caption == "“spare” · Contains · Message") + } + + @Test + func `several radios keep the newest radio first`() throws { + let home = UUID() + let field = UUID() + let rows = try [ + makeEntry(body: "home-new", radioName: nil, radioID: home, phrase: "home-new", arrivedAt: date(3)), + makeEntry(body: "field", radioName: nil, radioID: field, phrase: "field", arrivedAt: date(2)), + makeEntry(body: "home-old", radioName: "Home", radioID: home, phrase: "home-old", arrivedAt: date(1)), + ] + let groups = RecentlyBlockedView.radioGroups(in: rows) + #expect(groups.map(\.radioID) == [home, field]) + #expect(groups.map(\.radioName) == ["Home", nil] as [String?]) + #expect(groups[0].entries.map(\.body) == ["home-new", "home-old"]) + #expect(groups[1].entries.map(\.body) == ["field"]) + } + + @Test + func `voiceover skips a missing sender and chat`() throws { + let missing = try makeEntry(body: "bring the spare", sender: nil, conversationName: nil, phrase: "spare") + let label = RecentlyBlockedRow.accessibilityLabel(for: missing) + let rule = L10n.Settings.TextRules.ruleSummary(missing.match.rule.phrase, missing.match.rule.summary) + #expect(!label.contains(L10n.Settings.TextRules.Archive.labelPrefix(L10n.Settings.TextRules.Field.sender))) + #expect(!label.contains(L10n.Settings.TextRules.Archive.labelPrefix(L10n.Settings.TextRules.Archive.chat))) + #expect(label.contains(labeled(L10n.Settings.TextRules.Field.message, "bring the spare"))) + #expect(label.contains(labeled(L10n.Settings.TextRules.Archive.rule, rule))) + #expect(label.contains(L10n.Settings.TextRules.Archive.labelPrefix(L10n.Settings.TextRules.Archive.time))) + } + + private func labeled(_ label: String, _ value: String) -> String { + L10n.Settings.TextRules.Archive.labelPrefix(label) + value + } + + private func date(_ index: Int) -> Date { + Date(timeIntervalSince1970: Double(index)) + } + + private func makeEntry( + body: String, + sender: String? = "Ada", + conversationName: String? = "Dock", + radioName: String? = "Home", + radioID: UUID = UUID(), + phrase: String = "spare", + arrivedAt: Date = Date(timeIntervalSince1970: 1_700_000_000) + ) throws -> RecentlyBlockedMessageDTO { + var preference = TextRulesPreference() + preference.append(.init(phrase: phrase, lookIn: .message, match: .contains)) + let match = try #require(preference.firstMatch(body: body, sender: sender)) + return RecentlyBlockedMessageDTO( + identity: .init( + radioID: radioID, + conversationID: UUID(), + senderPrefix: nil, + senderTimestamp: 1, + textType: 0, + wireText: Data(body.utf8) + ), + arrivedAt: arrivedAt, + body: body, + sender: sender, + conversationName: conversationName, + radioName: radioName, + match: match + ) + } +} From 60f9fc8f065364a1b631e0b56ac9f45ebeca1295 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 6 Nov 2026 07:13:48 -0800 Subject: [PATCH 08/10] ui: drop the rules list footer --- MC1/Resources/Generated/L10n.swift | 2 -- MC1/Resources/Localization/de.lproj/Settings.strings | 1 - MC1/Resources/Localization/en.lproj/Settings.strings | 1 - MC1/Resources/Localization/es.lproj/Settings.strings | 1 - MC1/Resources/Localization/fr.lproj/Settings.strings | 1 - MC1/Resources/Localization/it.lproj/Settings.strings | 1 - MC1/Resources/Localization/ko.lproj/Settings.strings | 1 - MC1/Resources/Localization/nl.lproj/Settings.strings | 1 - MC1/Resources/Localization/pl.lproj/Settings.strings | 1 - MC1/Resources/Localization/pt.lproj/Settings.strings | 1 - MC1/Resources/Localization/ru.lproj/Settings.strings | 1 - MC1/Resources/Localization/uk.lproj/Settings.strings | 1 - MC1/Resources/Localization/zh-Hans.lproj/Settings.strings | 1 - MC1/Views/Settings/Sections/TextRulesSettingsView.swift | 2 -- 14 files changed, 16 deletions(-) diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 27ed4b7bc4..992b8f674a 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -6178,8 +6178,6 @@ public enum L10n { public static let trustedOnlyDescription = L10n.tr("Settings", "telemetry.trustedOnlyDescription", fallback: "Limit telemetry to selected contacts") } public enum TextRules { - /// Hidden messages stay in Recently Blocked. - public static let deleteFooter = L10n.tr("Settings", "textRules.deleteFooter", fallback: "Hidden messages stay in Recently Blocked.") /// No Text Rules public static let empty = L10n.tr("Settings", "textRules.empty", fallback: "No Text Rules") /// Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded. diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index ad3424db17..b81ab056c6 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -1503,7 +1503,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Ausgeblendete Nachrichten bleiben in „Recently Blocked“."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index 19b3af075d..146717b735 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -1489,7 +1489,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Hidden messages stay in Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index cad945796a..b36d8a6e75 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -1503,7 +1503,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Los mensajes ocultos siguen en Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index f32a97199d..47d35887c4 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -1503,7 +1503,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Les messages masqués restent dans Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 46ff8fdbde..251876e97d 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -1501,7 +1501,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "I messaggi nascosti restano in “Recently Blocked”."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index 3850af49b4..32a2a6f5e5 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -1491,7 +1491,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "숨겨진 메시지는 Recently Blocked에 남습니다."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index 62522cd48d..2a8609ccdf 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -1503,7 +1503,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Verborgen berichten blijven in Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index c737778574..ec9ced65c9 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -1503,7 +1503,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Ukryte wiadomości pozostają w Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index a202b3c267..27c813dd78 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -1501,7 +1501,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "As mensagens ocultas ficam em Recently Blocked."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index 23930d1f95..b65d1986e8 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -1503,7 +1503,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Скрытые сообщения остаются в «Recently Blocked»."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 0fd341b1af..7022ac8486 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -1503,7 +1503,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "Приховані повідомлення залишаються у «Recently Blocked»."; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index 4611900aa5..677111bb3e 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -1503,7 +1503,6 @@ "textRules.title" = "Text Rules"; "textRules.rules" = "Rules"; "textRules.empty" = "No Text Rules"; -"textRules.deleteFooter" = "隐藏消息仍会保留在“Recently Blocked”中。"; "textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; "textRules.retryAccessibility" = "Try Loading Text Rules Again"; "textRules.saveFailed" = "Could not save Text Rules. Try again."; diff --git a/MC1/Views/Settings/Sections/TextRulesSettingsView.swift b/MC1/Views/Settings/Sections/TextRulesSettingsView.swift index ab6911fe6e..f82f004d80 100644 --- a/MC1/Views/Settings/Sections/TextRulesSettingsView.swift +++ b/MC1/Views/Settings/Sections/TextRulesSettingsView.swift @@ -69,8 +69,6 @@ struct TextRulesSettingsView: View { } } header: { Text(L10n.Settings.TextRules.rules) - } footer: { - Text(L10n.Settings.TextRules.deleteFooter) } .themedRowBackground(theme) } From 0d794744ac9fa922eb761918a07324802c9fb283 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:09:20 -0800 Subject: [PATCH 09/10] ui: drop text rules from chat info --- MC1/Resources/Generated/L10n.swift | 38 ------ .../Localization/de.lproj/Settings.strings | 16 +-- .../Localization/en.lproj/Settings.strings | 14 -- .../Localization/es.lproj/Settings.strings | 16 +-- .../Localization/fr.lproj/Settings.strings | 16 +-- .../Localization/it.lproj/Settings.strings | 16 +-- .../Localization/ko.lproj/Settings.strings | 16 +-- .../Localization/nl.lproj/Settings.strings | 16 +-- .../Localization/pl.lproj/Settings.strings | 16 +-- .../Localization/pt.lproj/Settings.strings | 16 +-- .../Localization/ru.lproj/Settings.strings | 16 +-- .../Localization/uk.lproj/Settings.strings | 16 +-- .../zh-Hans.lproj/Settings.strings | 16 +-- MC1/State/AppState+TextRules.swift | 21 --- MC1/State/AppState.swift | 4 - .../ConversationTextRulesSection.swift | 128 ------------------ MC1/Views/Chats/Room/RoomInfoSheet.swift | 7 - MC1/Views/Chats/Sheets/ChannelInfoSheet.swift | 7 - MC1/Views/Contacts/ContactDetailContent.swift | 9 -- 19 files changed, 11 insertions(+), 393 deletions(-) delete mode 100644 MC1/State/AppState+TextRules.swift delete mode 100644 MC1/Views/Chats/Components/ConversationTextRulesSection.swift diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 992b8f674a..acdea68dbc 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -6236,44 +6236,6 @@ public enum L10n { /// Sender public static let sender = L10n.tr("Settings", "textRules.field.sender", fallback: "Sender") } - public enum Info { - /// The saved conversation is unavailable. - public static let conversationUnavailable = L10n.tr("Settings", "textRules.info.conversationUnavailable", fallback: "The saved conversation is unavailable.") - /// Not included in %@ - public static func excluded(_ p1: Any) -> String { - return L10n.tr("Settings", "textRules.info.excluded", String(describing: p1), fallback: "Not included in %@") - } - /// Set for this conversation - public static let explicit = L10n.tr("Settings", "textRules.info.explicit", fallback: "Set for this conversation") - /// Follows %@ - public static func follows(_ p1: Any) -> String { - return L10n.tr("Settings", "textRules.info.follows", String(describing: p1), fallback: "Follows %@") - } - /// %1$@ (%2$@) - public static func inheritedChoice(_ p1: Any, _ p2: Any) -> String { - return L10n.tr("Settings", "textRules.info.inheritedChoice", String(describing: p1), String(describing: p2), fallback: "%1$@ (%2$@)") - } - /// Off for This Channel - public static let offChannel = L10n.tr("Settings", "textRules.info.offChannel", fallback: "Off for This Channel") - /// Off for This DM - public static let offDm = L10n.tr("Settings", "textRules.info.offDm", fallback: "Off for This DM") - /// Off for This Room - public static let offRoom = L10n.tr("Settings", "textRules.info.offRoom", fallback: "Off for This Room") - /// On for This Channel - public static let onChannel = L10n.tr("Settings", "textRules.info.onChannel", fallback: "On for This Channel") - /// On for This DM - public static let onDm = L10n.tr("Settings", "textRules.info.onDm", fallback: "On for This DM") - /// On for This Room - public static let onRoom = L10n.tr("Settings", "textRules.info.onRoom", fallback: "On for This Room") - /// Radio %@ - public static func radio(_ p1: Any) -> String { - return L10n.tr("Settings", "textRules.info.radio", String(describing: p1), fallback: "Radio %@") - } - /// Effective Setting - public static let status = L10n.tr("Settings", "textRules.info.status", fallback: "Effective Setting") - /// Unavailable - public static let unavailable = L10n.tr("Settings", "textRules.info.unavailable", fallback: "Unavailable") - } public enum Match { /// Contains public static let contains = L10n.tr("Settings", "textRules.match.contains", fallback: "Contains") diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index b81ab056c6..a82ec58bbc 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -1549,21 +1549,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index 146717b735..b363fab839 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -1535,20 +1535,6 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index b36d8a6e75..d4036261a3 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -1549,21 +1549,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index 47d35887c4..badb5e29e4 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -1549,21 +1549,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 251876e97d..0529e2ffa7 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -1547,21 +1547,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index 32a2a6f5e5..405b566ad0 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -1537,21 +1537,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index 2a8609ccdf..3700483ade 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -1549,21 +1549,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index ec9ced65c9..0cb6f5895c 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -1549,21 +1549,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index 27c813dd78..cb36317b9c 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -1547,21 +1547,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index b65d1986e8..a4c5538f10 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -1549,21 +1549,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 7022ac8486..169723a602 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -1549,21 +1549,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index 677111bb3e..8793f91e7b 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -1549,21 +1549,7 @@ "textRules.archive.unknownConversation" = "Unknown Conversation"; "textRules.archive.unknownRadio" = "Unknown Radio"; -/* TODO: translate conversation Text Rules and radio Cleanup strings */ -"textRules.info.status" = "Effective Setting"; -"textRules.info.unavailable" = "Unavailable"; -"textRules.info.inheritedChoice" = "%1$@ (%2$@)"; -"textRules.info.onChannel" = "On for This Channel"; -"textRules.info.offChannel" = "Off for This Channel"; -"textRules.info.onDm" = "On for This DM"; -"textRules.info.offDm" = "Off for This DM"; -"textRules.info.onRoom" = "On for This Room"; -"textRules.info.offRoom" = "Off for This Room"; -"textRules.info.follows" = "Follows %@"; -"textRules.info.excluded" = "Not included in %@"; -"textRules.info.explicit" = "Set for this conversation"; -"textRules.info.conversationUnavailable" = "The saved conversation is unavailable."; -"textRules.info.radio" = "Radio %@"; +/* TODO: translate radio Cleanup strings */ "radioCleanup.title" = "Cleanup"; "radioCleanup.running" = "Removing radio data"; "radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; diff --git a/MC1/State/AppState+TextRules.swift b/MC1/State/AppState+TextRules.swift deleted file mode 100644 index 70dc9130f7..0000000000 --- a/MC1/State/AppState+TextRules.swift +++ /dev/null @@ -1,21 +0,0 @@ -import MC1Services - -extension AppState { - func setTextRulesOverride( - _ choice: TextRulesPreference.Override, - kind: TextRulesPreference.Kind, - key: TextRulesPreference.Key - ) { - guard textRulesPreference != nil, textRulesOverrideWrites.insert(key).inserted else { return } - textRulesOverrideErrors[key] = nil - Task { - defer { textRulesOverrideWrites.remove(key) } - do { - try await connectionManager.persistenceStore.setTextRulesOverride(choice, kind: kind, key: key) - textRulesOverrideVersion += 1 - } catch { - textRulesOverrideErrors[key] = L10n.Settings.TextRules.saveFailed - } - } - } -} diff --git a/MC1/State/AppState.swift b/MC1/State/AppState.swift index a3cc239933..f99cda33ff 100644 --- a/MC1/State/AppState.swift +++ b/MC1/State/AppState.swift @@ -219,10 +219,6 @@ final class AppState { return connectionManager.persistenceStore } - var textRulesOverrideWrites: Set = [] - var textRulesOverrideErrors: [TextRulesPreference.Key: String] = [:] - var textRulesOverrideVersion = 0 - var textRulesPreference: TextRulesPreference? { connectionManager.textRulesPreference } diff --git a/MC1/Views/Chats/Components/ConversationTextRulesSection.swift b/MC1/Views/Chats/Components/ConversationTextRulesSection.swift deleted file mode 100644 index e8e6202217..0000000000 --- a/MC1/Views/Chats/Components/ConversationTextRulesSection.swift +++ /dev/null @@ -1,128 +0,0 @@ -import MC1Services -import SwiftUI - -struct ConversationTextRulesSection: View { - @Environment(\.appState) private var appState - @Environment(\.appTheme) private var theme - - private typealias Strings = L10n.Settings.TextRules.Info - - let kind: TextRulesPreference.Kind - let radioID: UUID - let conversationID: UUID? - let savedChoice: TextRulesPreference.Override - - @State private var committedChoice: TextRulesPreference.Override? - @State private var radioName: String? - - private var key: TextRulesPreference.Key? { - conversationID.map { .init(radioID: radioID, conversationID: $0) } - } - - private var selectedChoice: TextRulesPreference.Override { - committedChoice ?? savedChoice - } - - private var effective: TextRulesPreference.Effective? { - guard key != nil else { return nil } - return appState.textRulesPreference?.effective(for: kind, key: key, override: selectedChoice) - } - - private var isSaving: Bool { - key.map(appState.textRulesOverrideWrites.contains) ?? false - } - - private var errorMessage: Binding { - Binding( - get: { key.flatMap { appState.textRulesOverrideErrors[$0] } }, - set: { value in - if let key { appState.textRulesOverrideErrors[key] = value } - } - ) - } - - var body: some View { - Section { - LabeledContent(Strings.status, value: effective.map { status($0.isOn) } ?? Strings.unavailable) - if let effective { - Text(source(effective.source)) - .font(.subheadline) - .foregroundStyle(.secondary) - } - - Picker(L10n.Settings.TextRules.title, selection: Binding( - get: { selectedChoice }, - set: { choice in - guard let key, choice != selectedChoice else { return } - appState.setTextRulesOverride(choice, kind: kind, key: key) - } - )) { - Text(inheritedLabel).tag(TextRulesPreference.Override.inherit) - Text(explicitLabel(isOn: true)).tag(TextRulesPreference.Override.on) - Text(explicitLabel(isOn: false)).tag(TextRulesPreference.Override.off) - } - .pickerStyle(.inline) - .labelsHidden() - .disabled(effective == nil || isSaving) - - if isSaving { - ProgressView() - } - } header: { - Text(L10n.Settings.TextRules.title) - } footer: { - if appState.textRulesPreference == nil || key == nil || radioName != nil { - VStack(alignment: .leading) { - if appState.textRulesPreference == nil { - Text(L10n.Settings.TextRules.loadFailed) - } else if key == nil { - Text(Strings.conversationUnavailable) - } - if let radioName { - Text(Strings.radio(radioName)) - } - } - } - } - .themedRowBackground(theme) - .task(id: appState.textRulesOverrideVersion) { - let store = appState.connectionManager.persistenceStore - if let key, let conversation = try? await store.textRulesConversation(kind: kind, key: key) { - committedChoice = conversation.override - let radios = try? await store.fetchDevices() - if let radios, Set(radios.map(\.radioID)).count > 1 { - radioName = conversation.radioName - } - } - } - .errorAlert(errorMessage) - } - - private var inheritedLabel: String { - guard let preference = appState.textRulesPreference else { return kind.title } - return Strings.inheritedChoice(kind.title, status(preference.selection(for: kind).isOn)) - } - - private func explicitLabel(isOn: Bool) -> String { - switch kind { - case .publicChannel, .hashtagChannel, .privateChannel: - isOn ? Strings.onChannel : Strings.offChannel - case .directMessage: - isOn ? Strings.onDm : Strings.offDm - case .room: - isOn ? Strings.onRoom : Strings.offRoom - } - } - - private func status(_ enabled: Bool) -> String { - enabled ? L10n.Localizable.Accessibility.on : L10n.Localizable.Accessibility.off - } - - private func source(_ source: TextRulesPreference.Effective.Source) -> String { - switch source { - case .type: Strings.follows(kind.title) - case .fixedExclusion: Strings.excluded(kind.title) - case .explicit: Strings.explicit - } - } -} diff --git a/MC1/Views/Chats/Room/RoomInfoSheet.swift b/MC1/Views/Chats/Room/RoomInfoSheet.swift index 09a6f2909f..2feac503ef 100644 --- a/MC1/Views/Chats/Room/RoomInfoSheet.swift +++ b/MC1/Views/Chats/Room/RoomInfoSheet.swift @@ -85,13 +85,6 @@ struct RoomInfoSheet: View { .themedRowBackground(theme) } - ConversationTextRulesSection( - kind: .room, - radioID: session.radioID, - conversationID: session.textRulesID, - savedChoice: session.textRulesOverride - ) - if session.isConnected { Section { Button { showTelemetry = true } label: { diff --git a/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift b/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift index a93d2266b5..1e66eae31c 100644 --- a/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift +++ b/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift @@ -91,13 +91,6 @@ struct ChannelInfoSheet: View { .themedRowBackground(theme) } - ConversationTextRulesSection( - kind: TextRulesPreference.channelKind(isPublic: channel.isPublicChannel, name: channel.name), - radioID: channel.radioID, - conversationID: channel.textRulesID, - savedChoice: channel.textRulesOverride - ) - // Region Scope Section ChannelInfoRegionSection( knownRegions: knownRegions, diff --git a/MC1/Views/Contacts/ContactDetailContent.swift b/MC1/Views/Contacts/ContactDetailContent.swift index f984e72539..05bcb14bbe 100644 --- a/MC1/Views/Contacts/ContactDetailContent.swift +++ b/MC1/Views/Contacts/ContactDetailContent.swift @@ -55,15 +55,6 @@ struct ContactDetailContent: View { ) .themedRowBackground(theme) - if state.showFromDirectChat { - ConversationTextRulesSection( - kind: .directMessage, - radioID: state.currentContact.radioID, - conversationID: state.currentContact.textRulesID, - savedChoice: state.currentContact.textRulesOverride - ) - } - ContactDetailInfoSection( state: state, rendererID: rendererID, rendererRevision: rendererRevision, onRowPosition: recordRowPosition From da64878e76d7717951f370efabf9ebac66fe7fa2 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:50:02 -0800 Subject: [PATCH 10/10] ui: add blocks & filters to settings --- MC1/Resources/Generated/L10n.swift | 28 ++++++---- .../Localization/de.lproj/Settings.strings | 14 +++-- .../Localization/en.lproj/Settings.strings | 14 +++-- .../Localization/es.lproj/Settings.strings | 14 +++-- .../Localization/fr.lproj/Settings.strings | 14 +++-- .../Localization/it.lproj/Settings.strings | 14 +++-- .../Localization/ko.lproj/Settings.strings | 14 +++-- .../Localization/nl.lproj/Settings.strings | 14 +++-- .../Localization/pl.lproj/Settings.strings | 14 +++-- .../Localization/pt.lproj/Settings.strings | 14 +++-- .../Localization/ru.lproj/Settings.strings | 14 +++-- .../Localization/uk.lproj/Settings.strings | 14 +++-- .../zh-Hans.lproj/Settings.strings | 14 +++-- ...ift => BlocksAndFiltersSettingsView.swift} | 55 ++++++++++--------- MC1/Views/Settings/ChatSettingsView.swift | 2 - .../Settings/Sections/BlockingSection.swift | 6 -- .../Sections/TextRulesLoadNotice.swift | 2 +- MC1/Views/Settings/SettingsDetail.swift | 3 +- MC1/Views/Settings/SettingsDetailView.swift | 2 + MC1/Views/Settings/SettingsListContent.swift | 4 ++ MC1/Views/Settings/SettingsSubpage.swift | 7 +-- .../Views/OfflineMapSettingsErrorTests.swift | 2 +- MC1Tests/Views/SettingsDestination.swift | 16 ++++++ MC1Tests/Views/SettingsRoot.swift | 6 ++ .../Views/SettingsRouteAdmissionTests.swift | 15 ++--- .../Views/SettingsTabHarness+Actions.swift | 4 +- .../SettingsTabNavigationTests+Helpers.swift | 2 +- .../Views/SettingsTabNavigationTests.swift | 25 +++++++-- 28 files changed, 207 insertions(+), 140 deletions(-) rename MC1/Views/Settings/{Sections/TextRulesSettingsView.swift => BlocksAndFiltersSettingsView.swift} (76%) diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index acdea68dbc..fecaae3042 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -4549,6 +4549,10 @@ public enum L10n { } } } + public enum BlocksAndFilters { + /// Blocks & Filters + public static let title = L10n.tr("Settings", "blocksAndFilters.title", fallback: "Blocks & Filters") + } public enum Bluetooth { /// Button to change the device display name public static let changeDisplayName = L10n.tr("Settings", "bluetooth.changeDisplayName", fallback: "Change Display Name") @@ -6178,22 +6182,22 @@ public enum L10n { public static let trustedOnlyDescription = L10n.tr("Settings", "telemetry.trustedOnlyDescription", fallback: "Limit telemetry to selected contacts") } public enum TextRules { - /// No Text Rules - public static let empty = L10n.tr("Settings", "textRules.empty", fallback: "No Text Rules") - /// Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded. - public static let loadFailed = L10n.tr("Settings", "textRules.loadFailed", fallback: "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded.") - /// Try Loading Text Rules Again - public static let retryAccessibility = L10n.tr("Settings", "textRules.retryAccessibility", fallback: "Try Loading Text Rules Again") - /// Rules - public static let rules = L10n.tr("Settings", "textRules.rules", fallback: "Rules") + /// No Filter Rules + public static let empty = L10n.tr("Settings", "textRules.empty", fallback: "No Filter Rules") + /// Could not load filter rules. New messages won’t use filter rules until they can be loaded. + public static let loadFailed = L10n.tr("Settings", "textRules.loadFailed", fallback: "Could not load filter rules. New messages won’t use filter rules until they can be loaded.") + /// Loading Filter Rules… + public static let loading = L10n.tr("Settings", "textRules.loading", fallback: "Loading Filter Rules…") + /// Try Loading Filter Rules Again + public static let retryAccessibility = L10n.tr("Settings", "textRules.retryAccessibility", fallback: "Try Loading Filter Rules Again") + /// Filter Rules + public static let rules = L10n.tr("Settings", "textRules.rules", fallback: "Filter Rules") /// %1$@ · %2$@ public static func ruleSummary(_ p1: Any, _ p2: Any) -> String { return L10n.tr("Settings", "textRules.ruleSummary", String(describing: p1), String(describing: p2), fallback: "%1$@ · %2$@") } - /// Could not save Text Rules. Try again. - public static let saveFailed = L10n.tr("Settings", "textRules.saveFailed", fallback: "Could not save Text Rules. Try again.") - /// Text Rules - public static let title = L10n.tr("Settings", "textRules.title", fallback: "Text Rules") + /// Could not save filter rules. Try again. + public static let saveFailed = L10n.tr("Settings", "textRules.saveFailed", fallback: "Could not save filter rules. Try again.") public enum Archive { /// Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. public static func caption(_ p1: Any, _ p2: Any, _ p3: Any) -> String { diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index a82ec58bbc..07ebff0f92 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chats"; +"blocksAndFilters.title" = "Blockierung & Filter"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1500,12 +1502,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "Filterregeln"; +"textRules.empty" = "Keine Filterregeln"; +"textRules.loading" = "Filterregeln werden geladen…"; +"textRules.loadFailed" = "Filterregeln konnten nicht geladen werden. Neue Nachrichten verwenden keine Filterregeln, bis die Regeln geladen werden können."; +"textRules.retryAccessibility" = "Filterregeln erneut laden"; +"textRules.saveFailed" = "Filterregeln konnten nicht gespeichert werden. Versuche es erneut."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index b363fab839..3bfeb10306 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -758,6 +758,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chats"; +"blocksAndFilters.title" = "Blocks & Filters"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1486,12 +1488,12 @@ // MARK: - Text Rules -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "Filter Rules"; +"textRules.empty" = "No Filter Rules"; +"textRules.loading" = "Loading Filter Rules…"; +"textRules.loadFailed" = "Could not load filter rules. New messages won’t use filter rules until they can be loaded."; +"textRules.retryAccessibility" = "Try Loading Filter Rules Again"; +"textRules.saveFailed" = "Could not save filter rules. Try again."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index d4036261a3..d4595ad3b1 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chats"; +"blocksAndFilters.title" = "Bloqueo y filtros"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1500,12 +1502,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "Reglas de filtro"; +"textRules.empty" = "Sin reglas de filtro"; +"textRules.loading" = "Cargando reglas de filtro…"; +"textRules.loadFailed" = "No se pudieron cargar las reglas de filtro. Hasta que se puedan cargar, los mensajes nuevos no se filtrarán."; +"textRules.retryAccessibility" = "Reintentar la carga de las reglas de filtro"; +"textRules.saveFailed" = "No se pudieron guardar las reglas de filtro. Inténtalo de nuevo."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index badb5e29e4..b30d9e7c26 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Discussions"; +"blocksAndFilters.title" = "Blocage et filtres"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1500,12 +1502,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "Règles de filtrage"; +"textRules.empty" = "Aucune règle de filtrage"; +"textRules.loading" = "Chargement des règles de filtrage…"; +"textRules.loadFailed" = "Impossible de charger les règles de filtrage. Les nouveaux messages ne les utiliseront pas jusqu’à ce qu’elles puissent être chargées."; +"textRules.retryAccessibility" = "Réessayer de charger les règles de filtrage"; +"textRules.saveFailed" = "Impossible d’enregistrer les règles de filtrage. Réessayez."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 0529e2ffa7..30aa4feb8d 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -768,6 +768,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chat"; +"blocksAndFilters.title" = "Blocco e filtri"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1498,12 +1500,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "Regole di filtro"; +"textRules.empty" = "Nessuna regola di filtro"; +"textRules.loading" = "Caricamento delle regole di filtro…"; +"textRules.loadFailed" = "Impossibile caricare le regole di filtro. I nuovi messaggi non useranno le regole di filtro finché non sarà possibile caricarle."; +"textRules.retryAccessibility" = "Riprova a caricare le regole di filtro"; +"textRules.saveFailed" = "Impossibile salvare le regole di filtro. Riprova."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index 405b566ad0..ca44a91b41 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -758,6 +758,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "채팅"; +"blocksAndFilters.title" = "차단 및 필터"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1488,12 +1490,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "필터 규칙"; +"textRules.empty" = "필터 규칙 없음"; +"textRules.loading" = "필터 규칙을 불러오는 중…"; +"textRules.loadFailed" = "필터 규칙을 불러올 수 없습니다. 불러올 수 있을 때까지 새 메시지는 필터 규칙을 사용하지 않습니다."; +"textRules.retryAccessibility" = "필터 규칙 다시 불러오기"; +"textRules.saveFailed" = "필터 규칙을 저장할 수 없습니다. 다시 시도하십시오."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index 3700483ade..8eb6ea82f2 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chats"; +"blocksAndFilters.title" = "Blokkering en filters"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1500,12 +1502,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "Filterregels"; +"textRules.empty" = "Geen filterregels"; +"textRules.loading" = "Filterregels laden…"; +"textRules.loadFailed" = "Filterregels konden niet worden geladen. Nieuwe berichten gebruiken geen filterregels totdat het laden lukt."; +"textRules.retryAccessibility" = "Filterregels opnieuw laden"; +"textRules.saveFailed" = "Kan filterregels niet opslaan. Probeer het opnieuw."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index 0cb6f5895c..b76e7265f4 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Czaty"; +"blocksAndFilters.title" = "Blokowanie i filtry"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1500,12 +1502,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "Reguły filtrowania"; +"textRules.empty" = "Brak reguł filtrowania"; +"textRules.loading" = "Ładowanie reguł filtrowania…"; +"textRules.loadFailed" = "Nie udało się załadować reguł filtrowania. Nowe wiadomości nie będą ich używać, dopóki reguły nie zostaną załadowane."; +"textRules.retryAccessibility" = "Spróbuj ponownie załadować reguły filtrowania"; +"textRules.saveFailed" = "Nie udało się zapisać reguł filtrowania. Spróbuj ponownie."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index cb36317b9c..828247d7c7 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -768,6 +768,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chats"; +"blocksAndFilters.title" = "Bloqueio e filtros"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1498,12 +1500,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "Regras de filtro"; +"textRules.empty" = "Nenhuma regra de filtro"; +"textRules.loading" = "A carregar regras de filtro…"; +"textRules.loadFailed" = "Não foi possível carregar as regras de filtro. As mensagens novas não vão usar regras de filtro até ser possível carregá-las."; +"textRules.retryAccessibility" = "Tentar carregar regras de filtro novamente"; +"textRules.saveFailed" = "Não foi possível guardar as regras de filtro. Tente novamente."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index a4c5538f10..5d211fda42 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Чаты"; +"blocksAndFilters.title" = "Блокировка и фильтры"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1500,12 +1502,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "Правила фильтрации"; +"textRules.empty" = "Нет правил фильтрации"; +"textRules.loading" = "Загрузка правил фильтрации…"; +"textRules.loadFailed" = "Не удалось загрузить правила фильтрации. Новые сообщения не будут использовать эти правила, пока их не удастся загрузить."; +"textRules.retryAccessibility" = "Попробовать загрузить правила фильтрации ещё раз"; +"textRules.saveFailed" = "Не удалось сохранить правила фильтрации. Попробуй ещё раз."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 169723a602..a811fb7785 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Чати"; +"blocksAndFilters.title" = "Блокування та фільтри"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1500,12 +1502,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "Правила фільтрації"; +"textRules.empty" = "Немає правил фільтрації"; +"textRules.loading" = "Завантаження правил фільтрації…"; +"textRules.loadFailed" = "Не вдалося завантажити правила фільтрації. Нові повідомлення не використовуватимуть правила фільтрації, доки їх не вдасться завантажити."; +"textRules.retryAccessibility" = "Спробувати завантажити правила фільтрації ще раз"; +"textRules.saveFailed" = "Не вдалося зберегти правила фільтрації. Спробуй ще раз."; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index 8793f91e7b..f619039877 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "聊天"; +"blocksAndFilters.title" = "屏蔽与过滤"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1500,12 +1502,12 @@ // MARK: - Text Rules /* TODO: translate Text Rules strings */ -"textRules.title" = "Text Rules"; -"textRules.rules" = "Rules"; -"textRules.empty" = "No Text Rules"; -"textRules.loadFailed" = "Could not load Text Rules. New messages use ordinary delivery until Text Rules can be loaded."; -"textRules.retryAccessibility" = "Try Loading Text Rules Again"; -"textRules.saveFailed" = "Could not save Text Rules. Try again."; +"textRules.rules" = "过滤规则"; +"textRules.empty" = "没有过滤规则"; +"textRules.loading" = "正在加载过滤规则…"; +"textRules.loadFailed" = "无法加载过滤规则。在过滤规则加载成功之前,新消息不会使用过滤规则。"; +"textRules.retryAccessibility" = "重新加载过滤规则"; +"textRules.saveFailed" = "无法保存过滤规则。请重试。"; "textRules.new.title" = "New Rule"; "textRules.new.phrase" = "Word or phrase"; "textRules.new.lookIn" = "Look In"; diff --git a/MC1/Views/Settings/Sections/TextRulesSettingsView.swift b/MC1/Views/Settings/BlocksAndFiltersSettingsView.swift similarity index 76% rename from MC1/Views/Settings/Sections/TextRulesSettingsView.swift rename to MC1/Views/Settings/BlocksAndFiltersSettingsView.swift index f82f004d80..86a0bc65ec 100644 --- a/MC1/Views/Settings/Sections/TextRulesSettingsView.swift +++ b/MC1/Views/Settings/BlocksAndFiltersSettingsView.swift @@ -1,7 +1,7 @@ import MC1Services import SwiftUI -struct TextRulesSettingsView: View { +struct BlocksAndFiltersSettingsView: View { @Environment(\.appState) private var appState @Environment(\.appTheme) private var theme @State private var isAddingRule = false @@ -9,26 +9,25 @@ struct TextRulesSettingsView: View { @State private var errorMessage: String? var body: some View { + let preference = appState.textRulesPreference List { - if let preference = appState.textRulesPreference { - rulesSection(preference.rules) + BlockingSection() + rulesSection(preference?.rules) + + if let preference { typesSection(preference) - } else { - Section { - TextRulesLoadNotice() - } - .themedRowBackground(theme) } } .themedCanvas(theme) - .navigationTitle(L10n.Settings.TextRules.title) + .settingsSubpageDestinations() + .navigationTitle(L10n.Settings.BlocksAndFilters.title) .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .primaryAction) { Button(L10n.Settings.TextRules.New.title, systemImage: "plus") { isAddingRule = true } - .disabled(appState.textRulesPreference == nil) + .disabled(preference == nil) } } .sheet(isPresented: $isAddingRule) { @@ -44,28 +43,32 @@ struct TextRulesSettingsView: View { } } - private func rulesSection(_ rules: [TextRulesPreference.Rule]) -> some View { + private func rulesSection(_ rules: [TextRulesPreference.Rule]?) -> some View { Section { - if rules.isEmpty { - Text(L10n.Settings.TextRules.empty) - .foregroundStyle(.secondary) - } - ForEach(rules) { rule in - VStack(alignment: .leading) { - Text(verbatim: rule.phrase) - Text(verbatim: rule.summary) - .font(.subheadline) + if let rules { + if rules.isEmpty { + Text(L10n.Settings.TextRules.empty) .foregroundStyle(.secondary) } - .accessibilityElement(children: .combine) - .swipeActions { - Button(L10n.Localizable.Common.delete, systemImage: "trash", role: .destructive) { + ForEach(rules) { rule in + VStack(alignment: .leading) { + Text(verbatim: rule.phrase) + Text(verbatim: rule.summary) + .font(.subheadline) + .foregroundStyle(.secondary) + } + .accessibilityElement(children: .combine) + .swipeActions { + Button(L10n.Localizable.Common.delete, systemImage: "trash", role: .destructive) { + delete(rule) + } + } + .accessibilityAction(named: Text(L10n.Localizable.Common.delete)) { delete(rule) } } - .accessibilityAction(named: Text(L10n.Localizable.Common.delete)) { - delete(rule) - } + } else { + TextRulesLoadNotice() } } header: { Text(L10n.Settings.TextRules.rules) diff --git a/MC1/Views/Settings/ChatSettingsView.swift b/MC1/Views/Settings/ChatSettingsView.swift index 5db0745822..07741593ed 100644 --- a/MC1/Views/Settings/ChatSettingsView.swift +++ b/MC1/Views/Settings/ChatSettingsView.swift @@ -19,11 +19,9 @@ struct ChatSettingsView: View { LinkPreviewSettingsSection() MapPreviewSettingsSection() MessagesSettingsSection() - BlockingSection() RadioCleanupSection() } .themedCanvas(theme) - .settingsSubpageDestinations() .navigationTitle(L10n.Settings.ChatSettings.title) .navigationBarTitleDisplayMode(.inline) } diff --git a/MC1/Views/Settings/Sections/BlockingSection.swift b/MC1/Views/Settings/Sections/BlockingSection.swift index cf0255d5aa..57af729850 100644 --- a/MC1/Views/Settings/Sections/BlockingSection.swift +++ b/MC1/Views/Settings/Sections/BlockingSection.swift @@ -8,12 +8,6 @@ struct BlockingSection: View { var body: some View { Section { - TextRulesLoadNotice() - - NavigationLink(value: SettingsSubpage.textRules) { - TintedLabel(L10n.Settings.TextRules.title, systemImage: "line.3.horizontal.decrease") - } - NavigationLink(value: SettingsSubpage.recentlyBlocked) { HStack { TintedLabel(L10n.Settings.TextRules.Archive.title, systemImage: "tray") diff --git a/MC1/Views/Settings/Sections/TextRulesLoadNotice.swift b/MC1/Views/Settings/Sections/TextRulesLoadNotice.swift index bfeb40da0b..63909d3eb0 100644 --- a/MC1/Views/Settings/Sections/TextRulesLoadNotice.swift +++ b/MC1/Views/Settings/Sections/TextRulesLoadNotice.swift @@ -5,7 +5,7 @@ struct TextRulesLoadNotice: View { var body: some View { if appState.isTextRulesLoading { - ProgressView(L10n.Settings.TextRules.title) + ProgressView(L10n.Settings.TextRules.loading) } else if appState.textRulesPreference == nil { VStack(alignment: .leading) { Text(L10n.Settings.TextRules.loadFailed) diff --git a/MC1/Views/Settings/SettingsDetail.swift b/MC1/Views/Settings/SettingsDetail.swift index 5b87bf1f52..1477f62efa 100644 --- a/MC1/Views/Settings/SettingsDetail.swift +++ b/MC1/Views/Settings/SettingsDetail.swift @@ -10,6 +10,7 @@ enum SettingsDetail: Hashable { case advanced case notifications case chats + case blocksAndFilters case appearance case maps case language @@ -23,7 +24,7 @@ enum SettingsDetail: Hashable { switch self { case .deviceInfo, .radio, .location, .connection, .advanced: true - case .notifications, .chats, .appearance, .maps, .language, .backup, .support, .feedback: + case .notifications, .chats, .blocksAndFilters, .appearance, .maps, .language, .backup, .support, .feedback: false } } diff --git a/MC1/Views/Settings/SettingsDetailView.swift b/MC1/Views/Settings/SettingsDetailView.swift index 96aeb9b062..c4ad520f9c 100644 --- a/MC1/Views/Settings/SettingsDetailView.swift +++ b/MC1/Views/Settings/SettingsDetailView.swift @@ -28,6 +28,8 @@ struct SettingsDetailView: View { NotificationSettingsView() case .chats: ChatSettingsView() + case .blocksAndFilters: + BlocksAndFiltersSettingsView() case .appearance: AppearanceView() case .maps: diff --git a/MC1/Views/Settings/SettingsListContent.swift b/MC1/Views/Settings/SettingsListContent.swift index b61e5adc10..ccdff2019e 100644 --- a/MC1/Views/Settings/SettingsListContent.swift +++ b/MC1/Views/Settings/SettingsListContent.swift @@ -88,6 +88,10 @@ struct SettingsListContent: View { TintedLabel(L10n.Settings.ChatSettings.title, systemImage: "bubble.left.and.bubble.right") } + SettingsDetailRow(detail: .blocksAndFilters) { + TintedLabel(L10n.Settings.BlocksAndFilters.title, systemImage: "line.3.horizontal.decrease") + } + AppearanceSection() TipView(liveActivityTip, arrowEdge: .bottom) diff --git a/MC1/Views/Settings/SettingsSubpage.swift b/MC1/Views/Settings/SettingsSubpage.swift index 494e95c811..67955a9d75 100644 --- a/MC1/Views/Settings/SettingsSubpage.swift +++ b/MC1/Views/Settings/SettingsSubpage.swift @@ -6,7 +6,6 @@ enum SettingsSubpage: Hashable { case publicKey(Data) case configExport case configImport - case textRules case textRuleChats(TextRulesPreference.Kind) case recentlyBlocked case blockedChannelSenders @@ -37,8 +36,8 @@ enum SettingsSubpage: Hashable { detail == .advanced case .remoteCLIContacts: detail == .advanced && device?.supportsRadioCLI == true - case .textRules, .textRuleChats, .recentlyBlocked, .blockedChannelSenders, .blockedContacts: - detail == .chats + case .textRuleChats, .recentlyBlocked, .blockedChannelSenders, .blockedContacts: + detail == .blocksAndFilters case .translateIntoLanguage: detail == .language case .presetLocation: @@ -122,8 +121,6 @@ private struct SettingsSubpageDestination: View { NodeConfigImportView(viewModel: configImport) .onAppear { configImport.beginImport() } } - case .textRules: - TextRulesSettingsView() case let .textRuleChats(kind): TextRuleChatsView(kind: kind) case .recentlyBlocked: diff --git a/MC1Tests/Views/OfflineMapSettingsErrorTests.swift b/MC1Tests/Views/OfflineMapSettingsErrorTests.swift index abaf1ed5bb..c9a28d2c47 100644 --- a/MC1Tests/Views/OfflineMapSettingsErrorTests.swift +++ b/MC1Tests/Views/OfflineMapSettingsErrorTests.swift @@ -26,7 +26,7 @@ struct OfflineMapSettingsErrorTests { try #require(try await harness.waitUntil { harness.appState.offlineMapService.errorMessage == message }) let destination = SettingsDestination.offlineMaps - try #require(try await harness.openChild( + try #require(try await harness.openRow( row: destination.row, title: destination.title, markers: [message], detail: maps.detail )) try #require(try await harness.waitUntil { harness.controller.presentedViewController is UIAlertController }) diff --git a/MC1Tests/Views/SettingsDestination.swift b/MC1Tests/Views/SettingsDestination.swift index 46db0e8c68..ef7b8253cf 100644 --- a/MC1Tests/Views/SettingsDestination.swift +++ b/MC1Tests/Views/SettingsDestination.swift @@ -2,12 +2,16 @@ import Testing enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { + case recentlyBlocked + case blockedChannelSenders + case blockedContacts case translateInto case offlineMaps case manageRegions var root: SettingsRoot { switch self { + case .recentlyBlocked, .blockedChannelSenders, .blockedContacts: .blocksAndFilters case .translateInto: .language case .offlineMaps: .maps case .manageRegions: .advanced @@ -20,6 +24,9 @@ enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { var row: String { switch self { + case .recentlyBlocked: L10n.Settings.TextRules.Archive.title + case .blockedChannelSenders: L10n.Settings.Blocking.channelSenders + case .blockedContacts: L10n.Settings.Blocking.contacts case .translateInto: L10n.Settings.Language.TranslateInto.header case .offlineMaps: L10n.Settings.OfflineMaps.title case .manageRegions: L10n.Chats.Chats.ChannelInfo.Region.manageRegions @@ -28,6 +35,9 @@ enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { var title: String { switch self { + case .recentlyBlocked: L10n.Settings.TextRules.Archive.title + case .blockedChannelSenders: L10n.Settings.Blocking.ChannelSenders.title + case .blockedContacts: L10n.Contacts.Contacts.Blocked.title case .translateInto: L10n.Settings.Language.TranslateInto.header case .offlineMaps: L10n.Settings.OfflineMaps.title case .manageRegions: L10n.Chats.Chats.ChannelInfo.Region.manage @@ -36,6 +46,9 @@ enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { var markers: [String] { switch self { + case .recentlyBlocked: [L10n.Settings.TextRules.Archive.empty] + case .blockedChannelSenders: [L10n.Settings.Blocking.ChannelSenders.Empty.title] + case .blockedContacts: [L10n.Contacts.Contacts.Blocked.Empty.title] case .translateInto: [L10n.Settings.Language.matchAppLanguage] case .offlineMaps: [L10n.Settings.OfflineMaps.emptyTitle, L10n.Settings.OfflineMaps.storageUsed] case .manageRegions: [L10n.Chats.Chats.ChannelInfo.Region.addManually] @@ -44,6 +57,9 @@ enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { var testDescription: String { switch self { + case .recentlyBlocked: "recentlyBlocked" + case .blockedChannelSenders: "blockedChannelSenders" + case .blockedContacts: "blockedContacts" case .translateInto: "translateInto" case .offlineMaps: "offlineMaps" case .manageRegions: "manageRegions" diff --git a/MC1Tests/Views/SettingsRoot.swift b/MC1Tests/Views/SettingsRoot.swift index aeecf965e3..fd58fe8f62 100644 --- a/MC1Tests/Views/SettingsRoot.swift +++ b/MC1Tests/Views/SettingsRoot.swift @@ -9,6 +9,7 @@ enum SettingsRoot: CaseIterable, Sendable, CustomTestStringConvertible { case advanced case notifications case chats + case blocksAndFilters case appearance case maps case language @@ -25,6 +26,7 @@ enum SettingsRoot: CaseIterable, Sendable, CustomTestStringConvertible { case .advanced: .advanced case .notifications: .notifications case .chats: .chats + case .blocksAndFilters: .blocksAndFilters case .appearance: .appearance case .maps: .maps case .language: .language @@ -47,6 +49,7 @@ enum SettingsRoot: CaseIterable, Sendable, CustomTestStringConvertible { case .advanced: L10n.Settings.AdvancedSettings.title case .notifications: L10n.Settings.Notifications.header case .chats: L10n.Settings.ChatSettings.title + case .blocksAndFilters: L10n.Settings.BlocksAndFilters.title case .appearance: L10n.Settings.Appearance.title case .maps: L10n.Settings.Maps.title case .language: L10n.Settings.Language.title @@ -72,6 +75,8 @@ enum SettingsRoot: CaseIterable, Sendable, CustomTestStringConvertible { [L10n.Settings.Notifications.enable, L10n.Settings.Notifications.disabled, L10n.Settings.Notifications.contactMessages] case .chats: [L10n.Settings.ReplyWithQuote.toggle] + case .blocksAndFilters: + [L10n.Settings.Blocking.channelSenders] case .appearance: [L10n.Settings.Appearance.Scheme.header] case .maps: @@ -96,6 +101,7 @@ enum SettingsRoot: CaseIterable, Sendable, CustomTestStringConvertible { case .advanced: "advanced" case .notifications: "notifications" case .chats: "chats" + case .blocksAndFilters: "blocksAndFilters" case .appearance: "appearance" case .maps: "maps" case .language: "language" diff --git a/MC1Tests/Views/SettingsRouteAdmissionTests.swift b/MC1Tests/Views/SettingsRouteAdmissionTests.swift index 224a8d7b65..7a960c67c3 100644 --- a/MC1Tests/Views/SettingsRouteAdmissionTests.swift +++ b/MC1Tests/Views/SettingsRouteAdmissionTests.swift @@ -13,13 +13,6 @@ struct SettingsRouteAdmissionTests { #expect(SettingsSubpage.publicKey(key).isAdmitted(for: .deviceInfo, device: device)) #expect(SettingsSubpage.configExport.isAdmitted(for: .advanced, device: device)) #expect(SettingsSubpage.configImport.isAdmitted(for: .advanced, device: device)) - #expect(SettingsSubpage.textRules.isAdmitted(for: .chats, device: nil)) - #expect(SettingsSubpage.textRuleChats(.room).isAdmitted(for: .chats, device: nil)) - #expect(SettingsSubpage.recentlyBlocked.isAdmitted(for: .chats, device: nil)) - #expect(!SettingsSubpage.textRules.isAdmitted(for: .advanced, device: device)) - #expect(!SettingsSubpage.recentlyBlocked.isAdmitted(for: .advanced, device: device)) - #expect(SettingsSubpage.blockedChannelSenders.isAdmitted(for: .chats, device: device)) - #expect(SettingsSubpage.blockedContacts.isAdmitted(for: .chats, device: device)) #expect(SettingsSubpage.trustedContacts.isAdmitted(for: .advanced, device: device)) #expect(!SettingsSubpage.remoteCLIContacts.isAdmitted(for: .advanced, device: device)) #expect(SettingsSubpage.translateIntoLanguage.isAdmitted(for: .language, device: device)) @@ -40,6 +33,14 @@ struct SettingsRouteAdmissionTests { #expect(!SettingsSubpage.manageRegions.isAdmitted(for: .maps, device: device)) } + @Test + func `blocks and filters routes belong to their own settings page while disconnected`() { + let path: [SettingsSubpage] = [.recentlyBlocked, .blockedChannelSenders, .blockedContacts, .textRuleChats(.room)] + + #expect(SettingsSubpage.admitted(path, for: .blocksAndFilters, device: nil) == path) + #expect(SettingsSubpage.admitted(path, for: .chats, device: nil).isEmpty) + } + @Test func `capability rules drop preset location and regions`() { let repeating = makeDevice(firmware: 11, clientRepeat: true) diff --git a/MC1Tests/Views/SettingsTabHarness+Actions.swift b/MC1Tests/Views/SettingsTabHarness+Actions.swift index cc0abca280..6b769cb69d 100644 --- a/MC1Tests/Views/SettingsTabHarness+Actions.swift +++ b/MC1Tests/Views/SettingsTabHarness+Actions.swift @@ -21,8 +21,8 @@ extension SettingsTabHarness { } @discardableResult - func openChild(row: String, title: String, markers: [String], detail: SettingsDetail) async throws -> Bool { - note = "open child \(row)" + func openRow(row: String, title: String, markers: [String], detail: SettingsDetail) async throws -> Bool { + note = "open row \(row)" guard try await activateRow(row) else { return false } return try await waitUntil { navigation.selectedSetting == detail && showsPage(title: title, markers: markers) diff --git a/MC1Tests/Views/SettingsTabNavigationTests+Helpers.swift b/MC1Tests/Views/SettingsTabNavigationTests+Helpers.swift index 3a9b855ddd..70e08344ed 100644 --- a/MC1Tests/Views/SettingsTabNavigationTests+Helpers.swift +++ b/MC1Tests/Views/SettingsTabNavigationTests+Helpers.swift @@ -15,7 +15,7 @@ extension SettingsTabNavigationTests { func requireChild(_ destination: SettingsDestination, on harness: SettingsTabHarness) async throws { try await requireRoot(destination.root, on: harness) try #require( - try await harness.openChild(row: destination.row, title: destination.title, markers: destination.markers, detail: destination.root.detail), + try await harness.openRow(row: destination.row, title: destination.title, markers: destination.markers, detail: destination.root.detail), "\(harness.describe())" ) } diff --git a/MC1Tests/Views/SettingsTabNavigationTests.swift b/MC1Tests/Views/SettingsTabNavigationTests.swift index c9a8e90780..f4b25eddea 100644 --- a/MC1Tests/Views/SettingsTabNavigationTests.swift +++ b/MC1Tests/Views/SettingsTabNavigationTests.swift @@ -18,9 +18,8 @@ struct SettingsTabNavigationTests { #expect(try await harness.waitUntil { harness.tabControlsAreOnScreen() }, "\(harness.describe())") } - @Test - func `Regular back keeps the selected detail`() async throws { - let destination = SettingsDestination.manageRegions + @Test(arguments: [SettingsDestination.manageRegions, .recentlyBlocked, .blockedChannelSenders, .blockedContacts]) + func `Regular back keeps the selected detail`(_ destination: SettingsDestination) async throws { let harness = try mounted(destination.root) defer { harness.tearDown() } try await requireChild(destination, on: harness) @@ -66,7 +65,7 @@ struct SettingsTabNavigationTests { "\(harness.describe())" ) - try #require(try await harness.openChild(row: destination.row, title: destination.title, markers: destination.markers, detail: destination.root.detail), "\(harness.describe())") + try #require(try await harness.openRow(row: destination.row, title: destination.title, markers: destination.markers, detail: destination.root.detail), "\(harness.describe())") harness.selectTab(.chats) try #require(try await harness.waitUntil { harness.showsSelectedTab(.chats) }, "\(harness.describe())") harness.navigation.navigateToSetting(.backup) @@ -162,6 +161,24 @@ struct SettingsTabNavigationTests { #expect(try await harness.waitUntil { harness.tabControlsAreOnScreen() }, "\(harness.describe())") } + @Test + func `Blocks and Filters has its own row immediately after Chats`() async throws { + let harness = try SettingsTabHarness.make(connected: false) + defer { harness.tearDown() } + let chats = SettingsRoot.chats + let blocksAndFilters = SettingsRoot.blocksAndFilters + + try #require(try await harness.showSettingsList(), "\(harness.describe())") + let chatsRow = try #require(harness.cell(matching: chats.title, in: harness.visibleCollectionViews())) + let filtersRow = try #require(harness.cell(matching: blocksAndFilters.title, in: [chatsRow.list])) + #expect(filtersRow.indexPath.section == chatsRow.indexPath.section) + #expect(filtersRow.indexPath.item == chatsRow.indexPath.item + 1) + + try #require(try await harness.openRow( + row: blocksAndFilters.title, title: blocksAndFilters.title, markers: blocksAndFilters.markers, detail: blocksAndFilters.detail + ), "\(harness.describe())") + } + @Test(arguments: SettingsRoot.allCases) func `Compact root keeps tab controls on screen`(_ root: SettingsRoot) async throws { let harness = try mounted(root)