diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 80f579dc40..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") @@ -5631,6 +5635,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") @@ -6163,6 +6181,126 @@ 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 { + /// 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 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 { + 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 + public static let empty = L10n.tr("Settings", "textRules.archive.empty", fallback: "No Hidden Messages") + /// 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 device. They aren’t included in app backups.") + } + /// %@: + 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 + 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") + /// Message or Sender + public static let messageOrSender = L10n.tr("Settings", "textRules.field.messageOrSender", fallback: "Message or Sender") + /// Sender + public static let sender = L10n.tr("Settings", "textRules.field.sender", fallback: "Sender") + } + 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 { + /// 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 + 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") + /// 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 %@ + 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 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 { + /// 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 + 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 caefa22a3f..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 */ @@ -1497,6 +1499,65 @@ /* 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.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"; +"textRules.new.match" = "Match"; +"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.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" = "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"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"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" = "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"; +"textRules.archive.time" = "Zeit"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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 9280dd2ef3..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 */ @@ -1484,6 +1486,63 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "No empty channel slot available for \"%@\""; +// MARK: - Text Rules + +"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"; +"textRules.new.match" = "Match"; +"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.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" = "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"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"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 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"; +"textRules.archive.time" = "Time"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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 42675c572c..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 */ @@ -1497,6 +1499,65 @@ /* 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.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"; +"textRules.new.match" = "Match"; +"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.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" = "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"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"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" = "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"; +"textRules.archive.time" = "Hora"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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 1a4c6bdfa6..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 */ @@ -1497,6 +1499,65 @@ /* 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.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"; +"textRules.new.match" = "Match"; +"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.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" = "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"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"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" = "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"; +"textRules.archive.time" = "Heure"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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 aae42f46b2..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 */ @@ -1495,6 +1497,65 @@ /* 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.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"; +"textRules.new.match" = "Match"; +"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.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" = "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"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"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" = "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"; +"textRules.archive.time" = "Ora"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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 cae2d8a78f..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 */ @@ -1485,6 +1487,65 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "\"%@\"에 사용할 빈 채널 슬롯이 없습니다"; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"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"; +"textRules.new.match" = "Match"; +"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.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" = "켜면 해당 유형의 모든 채팅이 포함됩니다. 나중에 참여하는 채팅도 포함됩니다."; +"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은 나중에 참여하는 채팅도 포함합니다."; +"textRules.archive.title" = "Recently Blocked"; +"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" = "내 노드"; +"textRules.archive.time" = "시간"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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 10c56ed886..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 */ @@ -1497,6 +1499,65 @@ /* 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.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"; +"textRules.new.match" = "Match"; +"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.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" = "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"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"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" = "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"; +"textRules.archive.time" = "Tijd"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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 975e1f1173..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 */ @@ -1497,6 +1499,65 @@ /* 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.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"; +"textRules.new.match" = "Match"; +"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.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" = "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"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"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" = "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ł"; +"textRules.archive.time" = "Czas"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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 4fb1171078..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 */ @@ -1495,6 +1497,65 @@ /* 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.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"; +"textRules.new.match" = "Match"; +"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.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" = "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"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"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" = "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ó"; +"textRules.archive.time" = "Hora"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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 fe3aa8caac..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 */ @@ -1497,6 +1499,65 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Отображение миниатюр карты загружает плитки для координаты со стороннего сервера, что может раскрыть ваш IP-адрес."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"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"; +"textRules.new.match" = "Match"; +"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.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" = "Включённый переключатель охватывает все чаты этого типа, включая те, к которым ты присоединишься позже."; +"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» включает чаты, к которым ты присоединишься позже."; +"textRules.archive.title" = "Recently Blocked"; +"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" = "Мой узел"; +"textRules.archive.time" = "Время"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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 b26d02b0db..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 */ @@ -1497,6 +1499,65 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Відображення мініатюр карти завантажує плитки для координати зі стороннього сервера, що може розкрити вашу IP-адресу."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"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"; +"textRules.new.match" = "Match"; +"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.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" = "Коли увімкнено, це охоплює всі чати цього типу, зокрема ті, до яких ти приєднаєшся пізніше."; +"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» охоплює чати, до яких ти приєднаєшся пізніше."; +"textRules.archive.title" = "Recently Blocked"; +"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" = "Мій вузол"; +"textRules.archive.time" = "Час"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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 44432be9a0..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 */ @@ -1497,6 +1499,65 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "显示地图缩略图会从第三方服务器获取该坐标的地图图块,可能会暴露您的IP地址。"; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"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"; +"textRules.new.match" = "Match"; +"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.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" = "开启后,该类型的所有聊天都会包括在内,包括您之后加入的聊天。"; +"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”会包括您之后加入的聊天。"; +"textRules.archive.title" = "Recently Blocked"; +"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" = "我的节点"; +"textRules.archive.time" = "时间"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown 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."; +"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+Wiring.swift b/MC1/State/AppState+Wiring.swift index feea27925d..517183b509 100644 --- a/MC1/State/AppState+Wiring.swift +++ b/MC1/State/AppState+Wiring.swift @@ -112,7 +112,13 @@ extension AppState { for await event in advertisementEvents { guard let self, !Task.isCancelled, context.isCurrent(connectionManager) 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 } + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } + } 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 5a53f7a91c..f99cda33ff 100644 --- a/MC1/State/AppState.swift +++ b/MC1/State/AppState.swift @@ -219,6 +219,14 @@ final class AppState { return connectionManager.persistenceStore } + 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..b927812884 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) + case channelMessageReceived( + message: MessageDTO, channelIndex: UInt8, scope: ReceiveScope + ) + 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 e4050bea29..2981f17ea4 100644 --- a/MC1/State/MessageEventDispatcher.swift +++ b/MC1/State/MessageEventDispatcher.swift @@ -59,20 +59,34 @@ final class MessageEventDispatcher { for await event in events { guard let appState, !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } switch event { - case let .directMessageReceived(message, contact): - stream.send(.directMessageReceived(message: message, contact: contact)) + case let .directMessageReceived(message, contact, 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 } + 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, scope): + guard scope.isCurrent else { continue } + stream.send(.channelMessageReceived( + message: message, channelIndex: channelIndex, scope: scope + )) 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 { + 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(.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 b0eacb8858..d8809cbb76 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/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..390df9b75c 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift @@ -11,15 +11,19 @@ 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 } + 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, scope): guard let channel = currentChannel, channel.index == channelIndex, - message.radioID == channel.radioID else { return } + message.radioID == channel.radioID, + scope.isCurrent else { return } admitIncomingMessage(message, isChannelMessage: true) recordIncomingMentionIfNeeded(message) diff --git a/MC1/Views/Contacts/ContactDetailContent.swift b/MC1/Views/Contacts/ContactDetailContent.swift index c794b517ee..05bcb14bbe 100644 --- a/MC1/Views/Contacts/ContactDetailContent.swift +++ b/MC1/Views/Contacts/ContactDetailContent.swift @@ -159,8 +159,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 1a878760fe..65259e722e 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(!session.isConnected || appState.connectionSnapshot(for: session.radioID) == nil) + } + } if #unavailable(iOS 26) { ToolbarItem(placement: .primaryAction) { Button(L10n.RemoteNodes.RemoteNodes.Room.infoTitle, systemImage: "info.circle") { @@ -161,6 +173,7 @@ struct RoomConversationView: View { .task(id: appState.servicesVersion) { // Reassert the active room when servicesVersion changes because reconnect replaces NotificationService. appState.connectionSnapshot(for: session.radioID)?.services.notificationService.setActiveConversation(roomSessionID: session.id) + await startSessionKeepAlive() } .task { for await event in appState.messageEventStream.events() { diff --git a/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift b/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift index ef974c471a..7bc352729d 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 else { return } appendMessageIfNew(message) scheduleCoalescedReload() diff --git a/MC1/Views/Settings/BlocksAndFiltersSettingsView.swift b/MC1/Views/Settings/BlocksAndFiltersSettingsView.swift new file mode 100644 index 0000000000..86a0bc65ec --- /dev/null +++ b/MC1/Views/Settings/BlocksAndFiltersSettingsView.swift @@ -0,0 +1,136 @@ +import MC1Services +import SwiftUI + +struct BlocksAndFiltersSettingsView: 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 { + let preference = appState.textRulesPreference + List { + BlockingSection() + rulesSection(preference?.rules) + + if let preference { + typesSection(preference) + } + } + .themedCanvas(theme) + .settingsSubpageDestinations() + .navigationTitle(L10n.Settings.BlocksAndFilters.title) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .primaryAction) { + Button(L10n.Settings.TextRules.New.title, systemImage: "plus") { + isAddingRule = true + } + .disabled(preference == 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 let rules { + 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) + .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) + } + } + } else { + TextRulesLoadNotice() + } + } header: { + Text(L10n.Settings.TextRules.rules) + } + .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/ChatSettingsView.swift b/MC1/Views/Settings/ChatSettingsView.swift index 21f20f939a..07741593ed 100644 --- a/MC1/Views/Settings/ChatSettingsView.swift +++ b/MC1/Views/Settings/ChatSettingsView.swift @@ -19,10 +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 6fa72ba518..57af729850 100644 --- a/MC1/Views/Settings/Sections/BlockingSection.swift +++ b/MC1/Views/Settings/Sections/BlockingSection.swift @@ -1,12 +1,32 @@ 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 { + 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 +39,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 421cbd7d70..9a44a4f190 100644 --- a/MC1/Views/Settings/Sections/DangerZoneViewModel.swift +++ b/MC1/Views/Settings/Sections/DangerZoneViewModel.swift @@ -32,8 +32,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) @@ -72,7 +70,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, + guard settingsService != nil, connectedDevice != nil, let connectionManager, let context = connectionManager.captureCurrentRemoval() else { @@ -84,21 +82,22 @@ final class DangerZoneViewModel { removalOperationID = operationID isResetting = true defer { - if removalOperationID == operationID { isResetting = false; removalOperationID = nil } + if removalOperationID == operationID { + isResetting = false + removalOperationID = nil + } } - // 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) + let result = try await connectionManager.factoryResetAndEraseRadio(context) + guard removalOperationID == operationID, case let .removed(receipt) = result else { return false } + return connectionManager.isCurrent(receipt) + } catch is CancellationError { + return false } catch { - // Expected: device reboots before sending OK response + if removalOperationID == operationID { errorMessage = error.userFacingMessage } + return false } - - let result = await connectionManager.forgetDeviceAfterReset(context) - guard removalOperationID == operationID, case let .removed(receipt) = result else { return false } - return connectionManager.isCurrent(receipt) } 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..2335e8b9ab --- /dev/null +++ b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift @@ -0,0 +1,109 @@ +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 errorMessage: String? + + private var trimmedPhrase: String { + 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 { + 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: { + Text(ruleFooter) + } + .themedRowBackground(theme) + } + .themedCanvas(theme) + .navigationTitle(L10n.Settings.TextRules.New.title) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button(L10n.Localizable.Common.cancel) { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button(L10n.Contacts.Contacts.Add.add, action: add) + .disabled(trimmedPhrase.isEmpty) + } + } + .errorAlert($errorMessage) + } + } + + private func add() { + let rule = TextRulesPreference.Rule(phrase: trimmedPhrase, lookIn: lookIn, match: match) + guard rule.isValid else { return } + 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 + } + } +} + +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 + } + } +} + +extension TextRulesPreference.Rule { + var summary: String { + L10n.Settings.TextRules.ruleSummary(match.title(for: lookIn), lookIn.title) + } +} 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/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 new file mode 100644 index 0000000000..d75eda7884 --- /dev/null +++ b/MC1/Views/Settings/Sections/RecentlyBlockedView.swift @@ -0,0 +1,121 @@ +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 { + if groups.count > 1 { + ForEach(groups) { group in + radioSection(group, isLast: group.id == groups.last?.id) + } + } else { + messageSection(entries) + } + } + .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) + } + } + } + + 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) + } + grouped[radioID, default: []].append(entry) + if names[radioID] == nil, let radioName = entry.radioName { + names[radioID] = radioName + } + } + return order.map { radioID in + RadioGroup(radioID: radioID, radioName: names[radioID], entries: grouped[radioID] ?? []) + } + } + + private func messageSection(_ rows: [RecentlyBlockedMessageDTO]) -> some View { + Section { + if rows.isEmpty { + Text(L10n.Settings.TextRules.Archive.empty) + .foregroundStyle(.secondary) + } + ForEach(rows) { entry in + RecentlyBlockedRow(entry: entry) + } + } footer: { + retentionFooter + } + .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 var retentionFooter: Text { + Text(L10n.Settings.TextRules.Archive.footer(PersistenceStore.recentlyBlockedRetentionLimit)) + } + + 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..63909d3eb0 --- /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.loading) + } 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/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 d9da533e66..67955a9d75 100644 --- a/MC1/Views/Settings/SettingsSubpage.swift +++ b/MC1/Views/Settings/SettingsSubpage.swift @@ -6,6 +6,8 @@ enum SettingsSubpage: Hashable { case publicKey(Data) case configExport case configImport + case textRuleChats(TextRulesPreference.Kind) + case recentlyBlocked case blockedChannelSenders case blockedContacts case trustedContacts @@ -34,8 +36,8 @@ enum SettingsSubpage: Hashable { detail == .advanced case .remoteCLIContacts: detail == .advanced && device?.supportsRadioCLI == true - case .blockedChannelSenders, .blockedContacts: - detail == .chats + case .textRuleChats, .recentlyBlocked, .blockedChannelSenders, .blockedContacts: + detail == .blocksAndFilters case .translateIntoLanguage: detail == .language case .presetLocation: @@ -119,6 +121,10 @@ private struct SettingsSubpageDestination: View { NodeConfigImportView(viewModel: configImport) .onAppear { configImport.beginImport() } } + case let .textRuleChats(kind): + TextRuleChatsView(kind: kind) + case .recentlyBlocked: + RecentlyBlockedView() case .blockedChannelSenders: BlockedChannelSendersView() case .blockedContacts: diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift index 58dabdc8cd..6bc2314842 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift @@ -113,7 +113,8 @@ public extension ConnectionManager { session: session, dataStore: persistenceStore, radioID: MockDataProvider.simulatorDeviceID, appStateProvider: appStateProvider, connectionStateEvents: connectionStateEvents, initialConnectionState: .connected, radioWiFiState: radioWiFiState(for: MockDataProvider.simulatorDeviceID), - notificationService: notificationServiceForTesting() + notificationService: notificationServiceForTesting(), + textRulesPreference: { [weak self] in await self?.textRulesPreference } ) attempt.preparedServices = container try await simulatorMode.seedDataStore(persistenceStore) diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift index 409cfbec54..b548feb505 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift @@ -103,6 +103,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 @@ -177,8 +179,10 @@ public extension ConnectionManager { guard connectionIntent.wantsConnection else { return } do { try await pairing.activate() + Task { await resumePendingRadioErases(pairingReady: true) } } catch { logger.error("Failed to activate pairing session: \(error.localizedDescription)") + await resumePendingRadioErases(pairingReady: false) } guard desiredRequest?.id == activationRequestID else { return } await checkWiFiConnectionHealth() @@ -187,6 +191,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") @@ -211,9 +216,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 diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift index 39fc7c7948..764a2ff489 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift @@ -205,20 +205,22 @@ public extension ConnectionManager { @discardableResult func forgetDevice(_ context: ConnectionRemovalContext, deleteData: Bool) async throws -> ConnectionRemovalResult { - try await removeDevice( - context, policy: .wholeDevice(deleteData: deleteData), reason: .forgetDevice, systemPolicy: .required - ) - } - - @discardableResult - func forgetDeviceAfterReset(_ context: ConnectionRemovalContext) async -> ConnectionRemovalResult { - do { + if !deleteData { return try await removeDevice( - context, policy: .wholeDevice(deleteData: true), reason: .factoryReset, systemPolicy: .bestEffort + context, policy: .wholeDevice(deleteData: false), reason: .forgetDevice, systemPolicy: .required ) - } catch { - logger.warning("Reset cleanup failed: \(error.localizedDescription)") - return .superseded + } + guard ownsRemovalSource(context) else { return .superseded } + let device = if let connectedDevice, context.identity.matches(ConnectionDeviceIdentity(connectedDevice)) { + connectedDevice + } else { + try await resolveRemovalDevice(context.identity, store: persistenceStore) + } + guard let device, ownsRemovalSource(context) else { return .superseded } + do { + return try await startRadioErase(device, context: context) + } catch DevicePairingError.cancelled { + return .cancelled } } @@ -413,15 +415,21 @@ public extension ConnectionManager { extension ConnectionManager: DevicePairingDelegate { public func devicePairing(_ service: any DevicePairingService, didRemoveDeviceWithID bluetoothID: UUID) { - guard removalDeviceID != bluetoothID else { return } + guard !isRemovingPairing(bluetoothID) else { return } handleRegistryRemoval(bluetoothID, pairingFailed: false) } public func devicePairing(_ service: any DevicePairingService, didFailPairingForDeviceWithID bluetoothID: UUID) { - guard removalDeviceID != bluetoothID else { return } + guard !isRemovingPairing(bluetoothID) else { return } handleRegistryRemoval(bluetoothID, pairingFailed: true) } + private func isRemovingPairing(_ bluetoothID: UUID) -> Bool { + removalDeviceID == bluetoothID || radioCleanup.values.contains { + $0.target.pairingID == bluetoothID && radioEraseTasks[$0.target.radioID] != nil + } + } + private func handleRegistryRemoval(_ id: UUID, pairingFailed: Bool) { let identity: ConnectionDeviceIdentity = if let device = connectedDevice, device.id == id { ConnectionDeviceIdentity(device) diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift index e617fea9d1..e48bf94cc7 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift @@ -62,7 +62,9 @@ extension ConnectionManager { )) let bluetoothPeripheralID = attempt.target.deviceID let registration = enqueueMetadata { store in - try await store.registerConnectionDevice(observation, bluetoothPeripheralID: bluetoothPeripheralID) + let device = try await store.registerConnectionDevice(observation, bluetoothPeripheralID: bluetoothPeripheralID) + try await store.backfillTextRulesIdentities(radioID: device.radioID) + return device } let device = try await registration.value attempt.identity = ConnectionDeviceIdentity(device) @@ -88,7 +90,8 @@ extension ConnectionManager { session: resource.session, dataStore: persistenceStore, radioID: device.radioID, appStateProvider: appStateProvider, connectionStateEvents: connectionStateEvents, initialConnectionState: .connected, radioWiFiState: wifiState, - notificationService: notificationServiceForTesting(), ackEvents: attempt.ackEvents + notificationService: notificationServiceForTesting(), ackEvents: attempt.ackEvents, + textRulesPreference: { [weak self] in await self?.textRulesPreference } ) attempt.preparedServices = container await wireCleanChannelSyncCallback(on: container) diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift new file mode 100644 index 0000000000..fbdd9f7c4b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift @@ -0,0 +1,221 @@ +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(_ context: ConnectionRemovalContext) async throws -> ConnectionRemovalResult { + guard ownsRemovalSource(context), let device = connectedDevice, let settings = services?.settingsService, + context.identity.matches(ConnectionDeviceIdentity(device)) else { return .superseded } + return try await startRadioErase(device, context: context, 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 .superseded } + let context = ConnectionRemovalContext( + deviceID: target.deviceID, identity: .init(deviceID: target.deviceID, radioID: target.radioID), + requestID: desiredRequest?.id, generation: installedLink?.generation + ) + return try await finishRadioErase(target, context: context) + } + } +} + +extension ConnectionManager { + @discardableResult + func startRadioErase( + _ device: DeviceDTO, context: ConnectionRemovalContext? = nil, resetWith settings: SettingsService? = nil + ) async throws -> ConnectionRemovalResult { + let context = context ?? ConnectionRemovalContext( + deviceID: device.id, device: device, requestID: desiredRequest?.id, generation: installedLink?.generation + ) + guard ownsRemovalSource(context) else { return .superseded } + if let running = radioEraseTasks[device.radioID] { + return try await running.value + } + let task = beginRadioEraseTask(radioID: device.radioID) { [self] in + guard ownsRemovalSource(context) else { return .superseded } + let alreadyPending = try await persistenceStore.isRadioErasePending(device.radioID) + guard ownsRemovalSource(context) else { return .superseded } + let poller = connectedDevice?.radioID == device.radioID ? services?.messagePollingService : nil + do { + try await poller?.suspendForRadioErase() + } catch { + guard ownsRemovalSource(context) else { return .superseded } + throw error + } + + let record: Task = enqueueMetadata { store in + guard self.ownsRemovalSource(context), + self.connectedDevice?.radioID != device.radioID || self.services?.messagePollingService === poller else { return nil } + return try await store.beginRadioErase(device, isFactoryReset: settings != nil) + } + let target: PendingRadioEraseDTO? + do { + target = try await record.value + } catch { + if services?.messagePollingService === poller { await poller?.resumeAfterRadioErase() } + guard ownsRemovalSource(context) else { return .superseded } + throw error + } + guard let target else { + if services?.messagePollingService === poller { await poller?.resumeAfterRadioErase() } + return .superseded + } + radioCleanup[target.radioID] = .init(target: target, state: .running) + if let settings, !alreadyPending { + let canSubmitReset = ownsRemovalSource(context) && services?.settingsService === settings + if canSubmitReset { + // 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)") + } + } + // An admitted recovery owns the next Link record while the old reset settles. + let recoveryOwnsRequest = installedLink == nil && reconnectionCoordinator.currentCycle.map { + $0.requestID == context.requestID + } == true + if !canSubmitReset || !ownsRemovalSource(context) || recoveryOwnsRequest { + do { + try await persistenceStore.cancelRadioErase(radioID: target.radioID) + radioCleanup[target.radioID] = nil + if services?.messagePollingService === poller { await poller?.resumeAfterRadioErase() } + } catch { + radioCleanup[target.radioID]?.state = .failed + logger.warning("Failed to roll back superseded reset cleanup: \(error.localizedDescription)") + } + return .superseded + } + } + return try await finishRadioErase(target, context: context) + } + return 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 -> ConnectionRemovalResult + ) -> Task { + let task = Task { [self] in + defer { radioEraseTasks[radioID] = nil } + return try await operation() + } + radioEraseTasks[radioID] = task + return task + } + + private func finishRadioErase( + _ target: PendingRadioEraseDTO, context: ConnectionRemovalContext + ) async throws -> ConnectionRemovalResult { + radioCleanup[target.radioID] = .init(target: target, state: .running) + let operationID = UUID() + if ownsRemovalSource(context), removalMatchesCurrent(context, policy: .wholeDevice(deleteData: true)) { + removalOperationID = operationID + removalDeviceID = target.pairingID + } + defer { + if removalOperationID == operationID { removalOperationID = nil; removalDeviceID = nil } + } + + 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 + } + } catch { + if radioCleanup[target.radioID] != nil { radioCleanup[target.radioID]?.state = .failed } + guard ownsRemovalSource(context) else { return .superseded } + throw error + } + + let sourceIsCurrent = ownsRemovalSource(context) + if sourceIsCurrent, let request = desiredRequest, !request.removedIdentities.contains(context.identity) { + request.removedIdentities.append(context.identity) + } + let terminal = if sourceIsCurrent, + removalMatchesCurrent(context, policy: .wholeDevice(deleteData: true)) || + desiredRequest?.target.deviceID == target.pairingID { + beginDisconnect(reason: target.isFactoryReset == true ? .factoryReset : .forgetDevice) + } else { + nil as (barrier: ConnectionRetirement, receipt: ConnectionLossReceipt)? + } + let writerDrain = retirementTask + let notifyingRequestID = terminal?.receipt.requestID ?? context.requestID + let cleanup = enqueueMetadata { store -> Bool in + await writerDrain?.value + let sourceStillCurrent = terminal.map { self.isCurrent($0.receipt) } ?? self.ownsRemovalSource(context) + let sourceWasSuperseded = !sourceIsCurrent || !sourceStillCurrent + if sourceWasSuperseded, self.pairing.hasSystemPairingRegistry, self.pairing.isDeviceConnectable(target.pairingID) { + try await store.cancelRadioErase(radioID: target.radioID) + return false + } + await self.clearPersistedConnection(for: target.deviceID, notifyingRequestID: notifyingRequestID) + try await store.completeRadioErase(radioID: target.radioID) + return true + } + do { + guard try await cleanup.value else { + radioCleanup[target.radioID] = nil + return .superseded + } + radioCleanup[target.radioID]?.state = .completed + guard let terminal, isCurrent(terminal.receipt) else { return .superseded } + await onConnectionLost?(terminal.receipt) + return .removed(terminal.receipt) + } catch { + radioCleanup[target.radioID]?.state = .failed + if let terminal { + guard isCurrent(terminal.receipt) else { return .superseded } + } else { + guard ownsRemovalSource(context) else { return .superseded } + } + throw error + } + } + + private static let factoryResetRebootGracePeriod: Duration = .seconds(1) +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift index e55bf2eb44..946cb1f804 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift @@ -62,7 +62,7 @@ extension ConnectionManager { removalOperationID == operationID && ownsRemovalSource(context) } - private func ownsRemovalSource(_ context: ConnectionRemovalContext) -> Bool { + func ownsRemovalSource(_ context: ConnectionRemovalContext) -> Bool { desiredRequest?.id == context.requestID && (context.generation == nil || desiredRequest?.committedGeneration == context.generation) } @@ -143,7 +143,7 @@ extension ConnectionManager { } } - private func removalMatchesCurrent(_ context: ConnectionRemovalContext, policy: RemovalPolicy) -> Bool { + func removalMatchesCurrent(_ context: ConnectionRemovalContext, policy: RemovalPolicy) -> Bool { switch policy { case .wholeDevice: if let device = connectedDevice, context.identity.matches(ConnectionDeviceIdentity(device)) { return true } @@ -155,7 +155,7 @@ extension ConnectionManager { } } - private func resolveRemovalDevice( + func resolveRemovalDevice( _ identity: ConnectionDeviceIdentity, store: PersistenceStore ) async throws -> DeviceDTO? { if let id = identity.deviceID, let device = try await store.fetchDevice(id: id) { return device } diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift new file mode 100644 index 0000000000..2d7cdf3e49 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift @@ -0,0 +1,46 @@ +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 } + 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 fd04e4f4ed..de6e6e499e 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift @@ -162,6 +162,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 private(set) var wifiTransport: (any WiFiMeshTransport)? private(set) var session: MeshCoreSession? { @@ -281,6 +285,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? @@ -617,7 +624,8 @@ public final class ConnectionManager { transport: (any iOSMeshTransport)? = nil, pairing: (any DevicePairingService)? = nil, reconnectionClock: (any Clock)? = nil, - makeWiFiTransport: @escaping @Sendable () -> any WiFiMeshTransport = { WiFiTransport() } + makeWiFiTransport: @escaping @Sendable () -> any WiFiMeshTransport = { WiFiTransport() }, + textRulesURL: URL? = nil ) { self.modelContainer = modelContainer self.makeWiFiTransport = makeWiFiTransport @@ -627,6 +635,7 @@ public final class ConnectionManager { 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 diff --git a/MC1Services/Sources/MC1Services/Models/Channel.swift b/MC1Services/Sources/MC1Services/Models/Channel.swift index cddc739a0f..fc8c691268 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 @@ -235,19 +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 let index: UInt8 + public internal(set) var textRulesID: UUID? + public internal(set) var textRulesOverride: TextRulesPreference.Override = .inherit + 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 { @@ -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,85 +380,49 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { /// Returns a copy with only `notificationLevel` changed. public func with(notificationLevel: NotificationLevel) -> ChannelDTO { - 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 - ) + var copy = self + copy.notificationLevel = notificationLevel + return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> ChannelDTO { - 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 - ) + var copy = self + copy.isPinned = isPinned + return copy } /// Returns a copy with only the flood-scope preference changed. public func with(floodScope: ChannelFloodScope) -> ChannelDTO { - 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 - ) + 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 { - 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 - ) + 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 { - 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 - ) + 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 { - 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 - ) + 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 373dea2af8..34a155fe36 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 @@ -315,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 { @@ -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,66 +561,30 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, /// Returns a copy with only `isMuted` changed. public func with(isMuted: Bool) -> ContactDTO { - 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 - ) + var copy = self + copy.isMuted = isMuted + return copy } /// Returns a copy with only `isFavorite` changed. public func with(isFavorite: Bool) -> ContactDTO { - 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 - ) + var copy = self + copy.isFavorite = isFavorite + return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> ContactDTO { - 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 - ) + var copy = self + copy.isPinned = isPinned + return copy } /// Returns a copy with only `avatarImageData` changed. public func with(avatarImageData: Data?) -> ContactDTO { - 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 - ) + var copy = self + copy.avatarImageData = avatarImageData + 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 ec92b861b2..c39b77235e 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 @@ -246,6 +254,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 @@ -258,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 { @@ -335,6 +345,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 @@ -411,34 +423,16 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, /// Returns a copy with only `notificationLevel` changed. public func with(notificationLevel: NotificationLevel) -> RemoteNodeSessionDTO { - 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 - ) + var copy = self + copy.notificationLevel = notificationLevel + return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> RemoteNodeSessionDTO { - 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 - ) + var copy = self + copy.isPinned = isPinned + 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..92790d5879 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift @@ -0,0 +1,238 @@ +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 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..bbe2c70750 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, ReceiveScope, TextRulesPreference?, Date) 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..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 @@ -103,14 +120,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 @@ -244,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 f7f4a4f2ae..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. @@ -19,6 +39,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 saveReceivedChannelMessage(_ dto: MessageDTO, scope: ReceiveScope, conversationID: UUID?) async throws -> Bool + /// Fetch a message by ID func fetchMessage(id: UUID) async throws -> MessageDTO? @@ -200,3 +223,36 @@ extension MessagePersisting { nil } } + +public extension MessagePersisting { + 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/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/ServiceContainer.swift b/MC1Services/Sources/MC1Services/ServiceContainer.swift index 61b39ec967..fd55a18070 100644 --- a/MC1Services/Sources/MC1Services/ServiceContainer.swift +++ b/MC1Services/Sources/MC1Services/ServiceContainer.swift @@ -14,6 +14,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. @@ -160,7 +161,8 @@ public final class ServiceContainer { radioWiFiState: RadioWiFiState? = nil, notificationService suppliedNotificationService: NotificationService? = nil, ackEvents: AsyncStream? = nil, - messageConfig: MessageServiceConfig = .default + messageConfig: MessageServiceConfig = .default, + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil } ) { self.session = session self.appStateProvider = appStateProvider @@ -184,7 +186,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, @@ -225,7 +230,13 @@ public final class ServiceContainer { appStateProvider: appStateProvider, notificationService: self.notificationService ) - messagePollingService = MessagePollingService(session: session, dataStore: dataStore) + messagePollingService = MessagePollingService( + session: session, + dataStore: dataStore, + radioID: radioID, + textRulesPreference: textRulesPreference, + receiveLifetime: receiveLifetime + ) binaryProtocolService = BinaryProtocolService( session: session, radioID: radioID, @@ -259,7 +270,9 @@ public final class ServiceContainer { remoteNodeService: remoteNodeService, dataStore: dataStore, radioID: radioID, - plainTextSendGate: plainTextSendGate + plainTextSendGate: plainTextSendGate, + textRulesPreference: textRulesPreference, + receiveLifetime: receiveLifetime ) chatSendQueueService = ChatSendQueueService( @@ -416,6 +429,7 @@ public final class ServiceContainer { /// so the chat send queue drains. `stopEventMonitoring()` alone does not /// cover that. func tearDown() async { + receiveLifetime.retire() isTornDown = true if let tearDownTask { await tearDownTask.value 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 44696693ca..2ae11b2cff 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)") } @@ -397,8 +388,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) } @@ -485,8 +475,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 a2ef456fbf..f68aefa8ea 100644 --- a/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift +++ b/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift @@ -300,7 +300,7 @@ public actor AdvertisementService { await notificationService?.removeDeliveredNotifications(forContactIDs: Set(deletedIDs)) eventBroadcaster.yield(.contactDeletedCleanup(contactIDs: deletedIDs)) eventBroadcaster.yield(.nodeStorageFullChanged(isFull: false)) - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) } catch { pendingDeletedKeys.formUnion(keys) pendingDeletedKeys.subtract(pendingAdvertKeys) @@ -380,9 +380,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 } @@ -393,29 +393,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)" @@ -566,7 +552,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") @@ -589,7 +575,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 { 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 4edd4ba406..8b88fe21b7 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, ReceiveScope, TextRulesPreference?, Date) 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, ReceiveScope, TextRulesPreference?, Date) 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() async { let eventMonitorTaskToStop = eventMonitorTask eventMonitorTask = nil + eventSubscription = nil eventMonitorTaskToStop?.cancel() await eventMonitorTaskToStop?.value } @@ -301,45 +345,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, scope, preference, arrivedAt) } } diff --git a/MC1Services/Sources/MC1Services/Services/NotificationService.swift b/MC1Services/Sources/MC1Services/Services/NotificationService.swift index cb42c02905..e1e8345990 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, + scope: ReceiveScope ) async { - guard notificationLevel != .muted else { return } - guard notificationLevel != .mentionsOnly || hasSelfMention else { return } - guard 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 } @@ -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 { @@ -597,9 +597,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 d0b53b3cd7..41452567c8 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift @@ -125,6 +125,9 @@ extension PersistenceStore { inserted += 1 } + for radioID in Set(dtos.map(\.radioID)) { + try bindRecentlyBlockedContacts(radioID: radioID) + } return (inserted, skipped, merged, contactIDsByKey) } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift index 6176a92f0f..7fbd4a33b9 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift @@ -142,9 +142,7 @@ public extension PersistenceStore { modelContext.autosaveEnabled = false defer { - if !didCommit { - modelContext.rollback() - } + if !didCommit { modelContext.rollback() } modelContext.autosaveEnabled = originalAutosaveEnabled } @@ -365,6 +363,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..9f4e92386d --- /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, 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+Connection.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift index 3464226908..ff824960bb 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift @@ -13,6 +13,9 @@ extension PersistenceStore { /// Registers authenticated radio observations while preserving the store's current local state. func registerConnectionDevice(_ observation: DeviceDTO, bluetoothPeripheralID: UUID?) throws -> DeviceDTO { let current = try fetchDevice(id: observation.id) ?? fetchDevice(publicKey: observation.publicKey) + guard try !isRadioErasePending(current?.radioID ?? observation.radioID) else { + throw ConnectionError.deviceNotFound + } let merged: DeviceDTO = if let current { current.copy { $0.id = observation.id @@ -71,6 +74,7 @@ extension PersistenceStore { /// Selects from a fresh row so a delayed connection cannot restore old preferences or endpoints. func selectConnectionDevice(id: UUID, method: ConnectionMethod?) throws -> DeviceDTO { guard let current = try fetchDevice(id: id) else { throw PersistenceStoreError.deviceNotFound } + guard try !isRadioErasePending(current.radioID) else { throw ConnectionError.deviceNotFound } let selected = current.copy { if let method { $0.connectionMethods.removeAll { $0.isBluetooth == method.isBluetooth } 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 009c989bb7..55e90adae1 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift @@ -193,8 +193,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. @@ -263,16 +272,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` @@ -299,11 +313,17 @@ public extension PersistenceStore { /// - newPublicKey: The radio's `selfInfo.publicKey` after `importPrivateKey`. /// - Returns: The new `radioID` if reconciliation occurred, otherwise `nil`. func reconcileGhostIdentity(currentDeviceID: UUID, newPublicKey: Data) throws -> UUID? { - guard let current = try identityDevice(id: currentDeviceID) else { return nil } + guard let current = try identityDevice(id: currentDeviceID), + try !isRadioErasePending(current.radioID) else { return nil } try commitPendingRxLogEntries() - guard let radioID = try stageGhostIdentity(current: current, newPublicKey: newPublicKey) else { return nil } - try saveIdentityChanges() - return radioID + do { + guard let adoption = try stageGhostIdentity(current: current, newPublicKey: newPublicKey) else { return nil } + try saveIdentityChanges(retiring: adoption.abandonedRadioID) + return adoption.radioID + } catch { + modelContext.rollback() + throw error + } } /// Saves an authenticated identity observation and its canonical partition in one actor turn. @@ -312,13 +332,14 @@ public extension PersistenceStore { ) throws -> DeviceDTO? { guard let current = try identityDevice(id: deviceID), current.radioID == expectedRadioID, current.publicKey == expectedPublicKey, - !current.connectionMethods.isEmpty else { return nil } + !current.connectionMethods.isEmpty, + try !isRadioErasePending(current.radioID) else { return nil } guard let selfInfo else { return DeviceDTO(from: current) } try commitPendingRxLogEntries() do { current.apply(DeviceDTO(from: current).updating(from: selfInfo)) - _ = try stageGhostIdentity(current: current, newPublicKey: selfInfo.publicKey) - try saveIdentityChanges() + let adoption = try stageGhostIdentity(current: current, newPublicKey: selfInfo.publicKey) + try saveIdentityChanges(retiring: adoption?.abandonedRadioID) return DeviceDTO(from: current) } catch { modelContext.rollback() @@ -334,7 +355,9 @@ public extension PersistenceStore { return try modelContext.fetch(descriptor).first } - private func stageGhostIdentity(current: Device, newPublicKey: Data) throws -> UUID? { + private func stageGhostIdentity( + current: Device, newPublicKey: Data + ) throws -> (radioID: UUID, abandonedRadioID: UUID?)? { let lookupKey = newPublicKey let lookupID = current.id let ghostPredicate = #Predicate { device in @@ -346,9 +369,17 @@ public extension PersistenceStore { !ghost.connectionMethods.contains(where: \.isBluetooth) else { return nil } let departingRadioID = current.radioID let newRadioID = ghost.radioID + guard try !isRadioErasePending(newRadioID) else { throw PersistenceStoreError.deviceNotFound } if departingRadioID != newRadioID { try reassignSelfTelemetrySnapshots(from: departingRadioID, to: newRadioID) } + let oldOwner = #Predicate { $0.radioID == departingRadioID && $0.id != lookupID } + let abandoned = try departingRadioID != newRadioID && + modelContext.fetchCount(FetchDescriptor(predicate: oldOwner)) == 0 + if abandoned { + try retireTextRulesIdentities(radioID: departingRadioID) + try stageRecentlyBlockedDeletion(radioID: departingRadioID) + } current.radioID = newRadioID current.publicKey = newPublicKey current.connectionMethods = ConnectionMethod.canonicalized(current.connectionMethods) @@ -358,34 +389,23 @@ public extension PersistenceStore { current.connectionMethods.insert(wifi, at: 0) } modelContext.delete(ghost) - return newRadioID + return (newRadioID, abandoned ? departingRadioID : nil) } - private func saveIdentityChanges() throws { - do { - #if DEBUG - try identityReconciliationFaultInjection?() - #endif - try modelContext.save() - } catch { - modelContext.rollback() - throw error + private func saveIdentityChanges(retiring abandonedRadioID: UUID?) throws { + #if DEBUG + try identityReconciliationFaultInjection?() + #endif + try modelContext.save() + if let abandonedRadioID { + retireReceiveScope(radioID: abandonedRadioID) + publishRecentlyBlockedChange() } } - /// 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) try deleteSelfTelemetrySnapshots(radioID: targetRadioID) 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 d65ec3add3..c4357799e9 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 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 + } + 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 dd6a6cb5e2..55e0f18cfe 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? @@ -122,9 +128,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)? var savePendingAcknowledgementFaultInjection: (@Sendable () throws -> Void)? @@ -151,7 +166,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. @@ -178,7 +195,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 NodeStatusSnapshot.selfRadioID (UUID?, default nil). Existing rows + /// - v9→v10: Added local Text Rules identities, review entries, and pending radio erase targets. + /// Added NodeStatusSnapshot.selfRadioID (UUID?, default nil). Existing rows /// stay remote history. Self telemetry rows store the Device's radioID. public static func createContainer(inMemory: Bool = false) throws -> ModelContainer { if !inMemory { 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 b399fc3733..e1bb25514d 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift @@ -282,7 +282,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 { @@ -316,30 +316,27 @@ public extension RemoteNodeService { retiredKeepAliveTasks.append(worker) } - /// 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 + /// Send a manual keep-alive for a directly routed session. + func sendKeepAlive(sessionID: UUID) async throws { guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { throw RemoteNodeError.sessionNotFound } guard !remoteSession.isSensor else { throw RemoteNodeError.invalidResponse } + if remoteSession.isRoom { + try await refreshRoom(remoteSession) + return + } - // Check contact's routing status + let publicKey = remoteSession.publicKey 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 - } + guard !contact.isFloodRouted else { throw RemoteNodeError.floodRouted } - // Log keep-alive - let targetType: CommandAuditLogger.Target = CommandAuditLogger.target(for: remoteSession.role) - await auditLogger.logKeepAlive(target: targetType, publicKey: publicKey) + await auditLogger.logKeepAlive(target: .repeater, 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 { @@ -347,14 +344,6 @@ public extension RemoteNodeService { } } - /// 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 9efdc17bf0..0a93fa850a 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() @@ -82,6 +85,17 @@ public actor RemoteNodeService { var retiredKeepAliveTasks: [Task] = [] private var retirementTask: 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] = [:] @@ -135,12 +149,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 { @@ -343,6 +363,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 b7eb0b8010..b67569365f 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() @@ -63,15 +65,19 @@ public actor RoomServerService { init( session: any RemoteAccessSessionOps, remoteNodeService: RemoteNodeService, - dataStore: any PersistenceStoreProtocol, + dataStore: PersistenceStore, radioID: UUID, - plainTextSendGate: PlainTextSendGate? = nil + plainTextSendGate: PlainTextSendGate? = nil, + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil }, + receiveLifetime: ReceiveScope.Lifetime = .init() ) { self.session = session self.remoteNodeService = remoteNodeService self.dataStore = dataStore self.radioID = radioID self.plainTextSendGate = plainTextSendGate + self.textRulesPreference = textRulesPreference + self.receiveLifetime = receiveLifetime } /// Set self public key prefix from SelfInfo. @@ -187,6 +193,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. @@ -379,69 +391,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 @@ -486,12 +482,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 d81448e000..060fdcd7cb 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() @@ -275,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..4ec3a51d48 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,27 @@ extension SyncCoordinator { ) } - /// Increments unread counts and posts a notification for a direct message. 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() } @@ -150,14 +144,10 @@ extension SyncCoordinator { func updateChannelUnreadsAndNotify( messageDTO: MessageDTO, channel: ChannelDTO?, - channelIndex: UInt8, - senderNodeName: String?, - messageText: String, - timestamp: UInt32, - hasSelfMention: Bool, - radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + scope: ReceiveScope ) async throws { + 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 @@ -165,36 +155,43 @@ extension SyncCoordinator { let activeRadioID = await dependencies.notificationService.activeChannelRadioID let isViewingChannel = isInForeground && activeIndex == channel?.index && activeRadioID == channel?.radioID if !isViewingChannel { + guard scope.isCurrent else { return } try await dependencies.dataStore.incrementChannelUnreadCount(channelID: channelID) // Increment unread mention count if message contains self-mention - if hasSelfMention { + if messageDTO.containsSelfMention, scope.isCurrent { try await dependencies.dataStore.incrementChannelUnreadMentionCount(channelID: channelID) } } } + 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 + hasSelfMention: messageDTO.containsSelfMention, + scope: scope ) - } else { + } else if channel == nil { recordUnresolvedChannel( channelIndex: channelIndex, - radioID: radioID, - senderTimestamp: timestamp + radioID: messageDTO.radioID, + senderTimestamp: messageDTO.reactionTimestamp ) } + guard scope.isCurrent else { return } await dependencies.notificationService.updateBadgeCount() // Broadcast for real-time chat updates - dataEventBroadcaster.yield(.channelMessageReceived(message: messageDTO, channelIndex: channelIndex)) + guard scope.isCurrent else { return } + dataEventBroadcaster.yield(.channelMessageReceived( + message: messageDTO, channelIndex: channelIndex, scope: scope + )) } private func recordUnresolvedChannel( diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index ebf44facbf..87d4d1d770 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -28,14 +28,15 @@ 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), context: context, dependencies: dependencies, - radioID: radioID, - selfNodeName: selfNodeName + selfNodeName: selfNodeName, + scope: scope, + preference: preference ) } } @@ -43,14 +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 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), + receivedAt: arrivedAt, context: context, dependencies: dependencies, - radioID: radioID, - selfNodeName: selfNodeName + selfNodeName: selfNodeName, + scope: scope, + preference: preference ) } } @@ -78,16 +81,15 @@ extension SyncCoordinator { private func resolveDirectContactIfNeeded( _ kind: IncomingMessageKind, dependencies: SyncDependencies, - radioID: UUID + scope: ReceiveScope ) async -> IncomingMessageKind { guard case let .direct(message, contact) = 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 } @@ -99,7 +101,8 @@ extension SyncCoordinator { private func harvestAndRefreshChannelMessage( messageDTO: MessageDTO, radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + scope: ReceiveScope ) async throws -> MessageDTO { guard let channelIndex = messageDTO.channelIndex else { return messageDTO } let stamp = messageDTO.senderTimestamp ?? messageDTO.timestamp @@ -110,6 +113,7 @@ extension SyncCoordinator { senderTimestamp: stamp ) let decoded = await dependencies.rxLogService.decodedEntries(raw) + guard scope.isCurrent else { return messageDTO } await dependencies.heardRepeatsService.harvestIncomingPaths( for: messageDTO, decodedCandidates: decoded @@ -125,14 +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 + dependencies: SyncDependencies, + scope: ReceiveScope ) async -> Bool { do { guard let existing = try await dependencies.dataStore.fetchMessage( @@ -141,11 +145,8 @@ extension SyncCoordinator { ) else { return false } - 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, @@ -156,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)") @@ -169,16 +170,20 @@ 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, + scope: ReceiveScope, + preference: TextRulesPreference? ) async { + 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, radioID: radioID + kind, dependencies: dependencies, scope: scope ) // Per-kind wire fields. Channel messages embed the sender as a @@ -221,7 +226,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 +314,38 @@ 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 - ) { + await receiveDirectMessage( + messageDTO, wireTextType: textTypeRaw, contact: contact, + scope: scope, preference: preference, dependencies: dependencies + ) + + case let .channel(message, channel): + if await recordChannelArrivalAndSkipDuplicate( + deduplicationKey: deduplicationKey, + radioID: radioID, + rxResult: rxResult, + snr: snr, + receiveTime: receiveTime, + dependencies: dependencies, + scope: scope + ) { return } - case let .channel(message, _): - // Discard messages from blocked senders + guard scope.isCurrent 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: scope, preference: preference + ) { return } + } catch { + logger.error("Failed to evaluate channel Text Rules: \(error)") + return + } + guard scope.isCurrent else { return } if await handleChannelReaction( text: text, channelIndex: message.channelIndex, @@ -366,59 +357,89 @@ extension SyncCoordinator { ) { return } - } - - do { - await runTestBeforeMessageSave(messageDTO) - try await dependencies.dataStore.saveMessage(messageDTO) - var savedDTO = messageDTO - if case .channel = resolvedKind { - savedDTO = try await harvestAndRefreshChannelMessage( + do { + await runTestBeforeMessageSave(messageDTO) + guard try await dependencies.dataStore.saveReceivedChannelMessage( + messageDTO, scope: scope, conversationID: channel?.textRulesID + ), + scope.isCurrent 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 + scope: scope ) - case let .channel(message, channel): try await indexAndNotifyChannelMessage( messageDTO: savedDTO, channel: channel, - channelIndex: message.channelIndex, - senderNodeName: senderNodeName, - messageText: text, - timestamp: timestamp, - hasSelfMention: hasSelfMention, dependencies: dependencies, - radioID: radioID + scope: scope ) + await notifyConversationsChanged(scope: scope) + } 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 { + await runTestBeforeMessageSave(message) + 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)") } } @@ -426,55 +447,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 @@ -482,27 +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 + scope: ReceiveScope ) async throws { - // 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 scope.isCurrent else { return } let reactionDTO = ReactionDTO( messageID: messageDTO.id, emoji: pending.parsed.emoji, @@ -516,23 +516,17 @@ extension SyncCoordinator { } } - // 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 + dependencies: dependencies, + scope: scope ) } } @@ -540,50 +534,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 6b8fd4a9bc..a48c5e9f76 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift @@ -379,7 +379,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..d46fad8ad8 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) /// An incoming channel message was persisted. - case channelMessageReceived(message: MessageDTO, channelIndex: UInt8) + case channelMessageReceived( + message: MessageDTO, channelIndex: UInt8, scope: ReceiveScope + ) /// 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,12 +593,14 @@ 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) - let context = try await manager.captureRemoval(id: deviceID) - await manager.forgetDeviceAfterReset(context) + let context = try #require(manager.captureCurrentRemoval()) + _ = try await manager.forgetDevice(context, deleteData: true) // The auto-reconnect / onboarding-resume signal must not survive forgetting its own radio. #expect(manager.lastConnectedDeviceID == nil) @@ -420,8 +616,9 @@ struct ConnectionManagerPairingTests { let lastConnected = UUID() manager.persistConnection(deviceID: lastConnected, radioID: UUID(), deviceName: "Radio") - let context = try await manager.captureRemoval(id: UUID()) - await manager.forgetDeviceAfterReset(context) + 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/ConnectionRemovalConfirmationTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift index 77cbd17946..0b1a1501c3 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift @@ -10,7 +10,7 @@ import Testing @MainActor struct ConnectionRemovalConfirmationTests { @Test - func `reset cleanup retains its best effort system removal policy`() async throws { + func `reset cleanup persists across declined system removal`() async throws { let env = try ConnectionManagerRadioTestHarness() do { _ = try await env.connect(.bluetooth) @@ -19,12 +19,14 @@ struct ConnectionRemovalConfirmationTests { env.pairing.isSessionActive = true env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: device.id, displayName: "Reset radio")]) env.pairing.removeAccessoryError = DevicePairingError.cancelled - let result = await env.manager.forgetDeviceAfterReset(context) - if case let .removed(receipt) = result { - #expect(env.manager.isCurrent(receipt)) - } else { - Issue.record("After a submitted factory reset, local cleanup remains best effort across system removal failure") - } + await #expect(throws: DevicePairingError.cancelled) { try await env.manager.factoryResetAndEraseRadio(context) } + let target = try #require(try await env.manager.persistenceStore.fetchPendingRadioErases().first) + #expect(target.radioID == device.radioID) + #expect(try await env.manager.persistenceStore.fetchDevice(id: device.id) != nil) + env.pairing.removeAccessoryError = nil + env.manager.retryRadioErase(target) + _ = try await env.manager.radioEraseTasks[device.radioID]?.value + #expect(try await env.manager.persistenceStore.fetchPendingRadioErases().isEmpty) #expect(try await env.manager.persistenceStore.fetchDevice(id: device.id) == nil) let disconnected = env.manager.currentConnection == nil #expect(disconnected) diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift index c2943b98b0..8479158952 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift @@ -1,6 +1,6 @@ import Foundation @testable import MC1Services -import MeshCore +@testable import MeshCore import Testing @Suite("Destructive removal drains admitted writers") @@ -23,10 +23,11 @@ struct ConnectionRemovalDrainTests { finished = true return result } - try await waitUntil("forget must park in retirement while the admitted save is held") { - fixture.env.manager.connectionTeardownCount > 0 + try await waitUntil("forget must suspend new reads while the admitted save is held") { + await fixture.env.manager.session?.isMessageFetchingSuspended == true } - try await fixture.observeDeletionStillPending() + #expect(try await !fixture.env.manager.persistenceStore.isRadioErasePending(fixture.radioID)) + #expect(try await fixture.env.manager.persistenceStore.fetchDevice(radioID: fixture.radioID) != nil) #expect(!finished) let messageID = try #require(fixture.gate.messageID) fixture.gate.release() @@ -44,16 +45,20 @@ struct ConnectionRemovalDrainTests { @Test func `admitted successor cannot pass the reserved destructive removal`() async throws { let fixture = try await Fixture.make(sameRadio: false) + let retirement = Gate() + fixture.armRetirement(retirement) var removal: Task? var successor: Task? do { try await fixture.admitSentinel() + fixture.gate.release() let context = try #require(fixture.env.manager.captureCurrentRemoval()) let removedRadioID = fixture.radioID removal = Task { try await fixture.env.manager.forgetDevice(context, deleteData: true) } try await waitUntil("forget must capture retirement before the successor is admitted") { - fixture.env.manager.connectionTeardownCount > 0 + retirement.entered } + #expect(try await fixture.env.manager.persistenceStore.isRadioErasePending(removedRadioID)) let dialsBefore = await fixture.env.wifi.connectCount successor = Task { try await fixture.env.connect(.wifi) } try await waitUntil("successor must be admitted behind the reserved removal") { @@ -63,7 +68,7 @@ struct ConnectionRemovalDrainTests { #expect(await fixture.env.wifi.connectCount == dialsBefore) #expect(fixture.env.manager.currentConnection == nil) let messageID = try #require(fixture.gate.messageID) - fixture.gate.release() + retirement.release() _ = try await removal?.value let connected = try await #require(successor).value #expect(fixture.env.manager.isCurrent(connected)) @@ -75,6 +80,7 @@ struct ConnectionRemovalDrainTests { try await fixture.expectUnrelatedDataRemains() await fixture.finish() } catch { + retirement.release() await fixture.stop(removal, successor) throw error } @@ -83,11 +89,14 @@ struct ConnectionRemovalDrainTests { @Test func `accepted confirmation after supersession still drains the captured retirement`() async throws { let fixture = try await Fixture.make(sameRadio: false) - let confirmation = ConfirmationGate() + let confirmation = Gate() + let retirement = Gate() + fixture.armRetirement(retirement) var removal: Task? var successor: Task? do { try await fixture.admitSentinel() + fixture.gate.release() let device = try #require(fixture.env.manager.connectedDevice) fixture.armConfirmation(confirmation, accessoryID: device.id) let context = try #require(fixture.env.manager.captureCurrentRemoval()) @@ -95,9 +104,9 @@ struct ConnectionRemovalDrainTests { try await waitUntil("system confirmation must be waiting") { confirmation.entered } let previousRequest = fixture.env.manager.connectionRequestID successor = Task { try await fixture.env.connect(.wifi) } - try await waitUntil("successor retirement must park on the admitted writer") { + try await waitUntil("successor must park on retirement") { let dials = await fixture.env.wifi.connectCount - return fixture.env.manager.connectionRequestID != previousRequest && fixture.env.manager.connectionTeardownCount > 0 + return fixture.env.manager.connectionRequestID != previousRequest && retirement.entered && dials == 0 } let successorRequest = fixture.env.manager.connectionRequestID @@ -112,7 +121,7 @@ struct ConnectionRemovalDrainTests { #expect(fixture.losses.count == lossesBefore) #expect(await fixture.env.wifi.connectCount == 0) let messageID = try #require(fixture.gate.messageID) - fixture.gate.release() + retirement.release() let outcome = try await #require(removal).value if case .superseded = outcome {} else { Issue.record("A detached confirmation must not publish removal into the successor") } let connected = try await #require(successor).value @@ -123,6 +132,7 @@ struct ConnectionRemovalDrainTests { await fixture.finish() } catch { confirmation.release() + retirement.release() await fixture.stop(removal, successor) throw error } @@ -131,11 +141,14 @@ struct ConnectionRemovalDrainTests { @Test func `new pairing during a held destructive removal keeps the fresh association`() async throws { let fixture = try await Fixture.make(sameRadio: false) - let confirmation = ConfirmationGate() + let confirmation = Gate() + let retirement = Gate() + fixture.armRetirement(retirement) var removal: Task? var successor: Task? do { try await fixture.admitSentinel() + fixture.gate.release() let device = try #require(fixture.env.manager.connectedDevice) fixture.armConfirmation(confirmation, accessoryID: device.id) let context = try #require(fixture.env.manager.captureCurrentRemoval()) @@ -143,10 +156,10 @@ struct ConnectionRemovalDrainTests { try await waitUntil("system confirmation must be waiting") { confirmation.entered } successor = Task { try await fixture.env.connect(.wifi) } try await waitUntil("successor must supersede the removal source") { - fixture.env.manager.connectionRequestID != context.requestID && fixture.env.manager.connectionTeardownCount > 0 + fixture.env.manager.connectionRequestID != context.requestID && retirement.entered } confirmation.release() - try await waitUntil("accepted confirmation must queue removal while the admitted save is held") { + try await waitUntil("accepted confirmation must queue removal while retirement is held") { fixture.env.pairing.accessory(for: device.id) == nil && fixture.gate.messageID != nil } try await fixture.observeDeletionStillPending() @@ -154,15 +167,17 @@ struct ConnectionRemovalDrainTests { ASAccessory(bluetoothIdentifier: device.id, displayName: "Renewed association") ]) #expect(fixture.env.manager.pairing.isDeviceConnectable(device.id)) - fixture.gate.release() + retirement.release() _ = try await removal?.value _ = try await successor?.value let preserved = try #require(try await fixture.env.manager.persistenceStore.fetchDevice(id: device.id)) #expect(preserved.radioID == device.radioID) + #expect(try await !fixture.env.manager.persistenceStore.isRadioErasePending(device.radioID)) #expect(try await fixture.env.manager.session?.getTime() != nil) await fixture.finish() } catch { confirmation.release() + retirement.release() await fixture.stop(removal, successor) throw error } @@ -315,12 +330,16 @@ struct ConnectionRemovalDrainTests { #expect(try await env.manager.persistenceStore.fetchDevice(radioID: radioID) != nil) } - func armConfirmation(_ confirmation: ConfirmationGate, accessoryID: UUID) { + func armConfirmation(_ confirmation: Gate, accessoryID: UUID) { env.pairing.isSessionActive = true env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: accessoryID, displayName: "Radio")]) env.pairing.beforeRemovalResult = { await confirmation.wait() } } + func armRetirement(_ retirement: Gate) { + env.manager.testConnectionTeardownHandler = { await retirement.wait() } + } + func expectPartitionAbsent(messageID: UUID) async throws { #expect(try await env.manager.persistenceStore.fetchMessage(id: messageID) == nil) #expect(try await env.manager.persistenceStore.fetchDevice(radioID: radioID) == nil) @@ -343,6 +362,7 @@ struct ConnectionRemovalDrainTests { func finish() async { gate.release() + env.manager.testConnectionTeardownHandler = nil if let coordinator { await coordinator.setTestBeforeMessageSave(nil) } @@ -413,7 +433,7 @@ struct ConnectionRemovalDrainTests { } @MainActor - private final class ConfirmationGate { + private final class Gate { private(set) var entered = false private var released = false private var continuation: CheckedContinuation? diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift index 34ee9b613f..114df0d956 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 var beforeRemovalResult: (@MainActor () async -> Void)? public init() {} @@ -85,6 +86,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 + } + } await beforeRemovalResult?() if let removeAccessoryError { throw removeAccessoryError diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift index 4d9ebfea36..ff0218dc93 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) { @@ -785,6 +793,10 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps startAutoMessageFetchingCallCount += 1 } + public func suspendMessageFetching() async throws {} + + public func resumeMessageFetching() {} + public func stopAutoMessageFetching() { stopAutoMessageFetchingCallCount += 1 } @@ -844,7 +856,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..4534afbf67 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, ReceiveScope, TextRulesPreference?, Date) 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, ReceiveScope, TextRulesPreference?, Date) 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..68e9bfc514 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift @@ -0,0 +1,140 @@ +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 + ) async throws -> Fixture { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let room = RemoteNodeSessionDTO.testSession( + 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)) + 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 + 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 == fixture.room.lastSyncTimestamp) + #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" + )) + #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" + )) + #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..04260d7ffd 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, @@ -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) @@ -50,13 +46,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..e65bfcafe1 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,181 @@ 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 + 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) + 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, .live, scope, preference) + await deliver(arrival, contact, .live, 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, .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) + } + + @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 +553,8 @@ struct SyncCoordinatorMessageHandlerTests { text: "ChannelPeer: hello channel", snr: nil ) - await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live) + 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) @@ -393,6 +564,61 @@ struct SyncCoordinatorMessageHandlerTests { // MARK: - Live receive region propagation + @Test(.timeLimit(.minutes(1))) + 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)) + 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, 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, scope, preference, arrivedAt) + } + 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 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.saveReceivedChannelMessage(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 +668,8 @@ struct SyncCoordinatorMessageHandlerTests { text: "NodeAlpha: region scope test", snr: nil ) - await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live) + 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) @@ -489,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, @@ -499,7 +727,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), nil, - .live + .live, scope, nil, .now ) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) @@ -512,7 +740,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 } @@ -568,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, @@ -578,7 +807,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), channel, - .live + .live, scope, nil, .now ) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) @@ -636,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, @@ -646,7 +876,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), nil, - .live + .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 e49de2b638..0df020b756 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, ReceiveScope, TextRulesPreference?, Date) 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..f312598366 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift @@ -0,0 +1,160 @@ +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) + + _ = 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)) + } + + @Test + func `completing a pending erase preserves a radio that tried to adopt its identity`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let current = DeviceDTO.testDevice(publicKey: Data(repeating: 1, count: 32)) + let target = DeviceDTO.testDevice(publicKey: Data(repeating: 2, count: 32), isActive: false).copy { + $0.connectionMethods = [] + } + try await store.saveDevice(current) + try await store.saveDevice(target) + _ = try await store.beginRadioErase(target) + + await #expect(throws: PersistenceStoreError.self) { + _ = try await store.reconcileGhostIdentity(currentDeviceID: current.id, newPublicKey: target.publicKey) + } + try await store.completeRadioErase(radioID: target.radioID) + + let surviving = try #require(await store.fetchDevice(id: current.id)) + #expect(surviving.radioID == current.radioID) + #expect(surviving.publicKey == current.publicKey) + #expect(try await store.fetchDevice(id: target.id) == nil) + } + + 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..fc7a61e21a --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift @@ -0,0 +1,142 @@ +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 `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 rule = TextRulesPreference.Rule(phrase: " alert ", lookIn: .message, match: .contains) + try manager.updateTextRules { $0.append(rule) } + try manager.updateTextRules { $0.setSelection(.fixed([]), for: .publicChannel) } + let committed = try #require(manager.textRulesPreference) + #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 8f81916030..08a24f9ba9 100644 --- a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift +++ b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift @@ -270,9 +270,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, 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/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..81e9a4f1e5 --- /dev/null +++ b/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift @@ -0,0 +1,156 @@ +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())) + + await store.setRecordRecentlyBlockedFaultInjection { throw InjectedSaveFailure() } + await #expect(throws: InjectedSaveFailure.self) { + try await store.recordRecentlyBlockedMessage(drops[limit + 1]) + } + #expect(try await store.recentlyBlockedMessages() == committed) + } + + 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/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/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/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/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/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 + ) + } +} 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 29708c8121..7a960c67c3 100644 --- a/MC1Tests/Views/SettingsRouteAdmissionTests.swift +++ b/MC1Tests/Views/SettingsRouteAdmissionTests.swift @@ -13,8 +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.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)) @@ -35,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) 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..92b7efbac9 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,10 @@ public protocol RemoteAccessSessionOps: Actor { // MARK: - Default Implementations public extension RemoteAccessSessionOps { + 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 784eeffc37..8b22e25494 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 } @@ -566,32 +567,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 e4b973fd03..75c01def4e 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift @@ -151,6 +151,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? @@ -247,6 +248,7 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { isStarting = true defer { isStarting = false } + isMessageFetchingSuspended = false logger.info("Starting MeshCore session...") if let reconnectingAttempt { updateConnectionState(.reconnecting(attempt: max(1, reconnectingAttempt))) @@ -392,9 +394,12 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { await dispatcher.subscribeTracked() } - /// Finishes a subscription created via ``eventsTracked()``. - /// - /// Causes the corresponding `for await` loop to exit. Safe to call with an unknown id. + public func eventsTracked(filter: EventFilter) async -> (id: UUID, stream: AsyncStream) { + await dispatcher.subscribeTracked(filter: filter.matches) + } + + /// 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) } @@ -437,6 +442,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 } @@ -449,6 +473,7 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { } private func requestAutoMessageDrain() { + guard !isMessageFetchingSuspended else { return } autoMessageDrainRequested = true guard autoMessageDrainTask == nil else { return } @@ -465,7 +490,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))