diff --git a/bitchat/App/PeerListModel.swift b/bitchat/App/PeerListModel.swift index 7e6375e6..56253d9d 100644 --- a/bitchat/App/PeerListModel.swift +++ b/bitchat/App/PeerListModel.swift @@ -395,13 +395,28 @@ final class PeerListModel: ObservableObject { } guard matchesConversation else { continue } - if let hit = conversation.messages.last(where: { $0.content.localizedCaseInsensitiveContains(query) }) { + if let hit = conversation.messages.last(where: { message in + guard message.sender != "system", + MessageInteractionCodec.parseReaction(from: message.content) == nil else { + return false + } + let preview = MessageInteractionCodec.formattedPreview( + for: message.content, + sender: row.isGroup ? message.sender : nil + ) + return preview.localizedCaseInsensitiveContains(query) + }) { if bestMessage == nil || hit.timestamp > bestMessage!.timestamp { bestMessage = hit } } } - return bestMessage?.content + return bestMessage.map { + MessageInteractionCodec.formattedPreview( + for: $0.content, + sender: row.isGroup ? $0.sender : nil + ) + } } private func bind() { @@ -602,10 +617,19 @@ final class PeerListModel: ObservableObject { let pinnedKeys = InboxPinnedChats.pinnedKeys() let mutedKeys = InboxMutedChats.mutedKeys() + let myPeerID = chatViewModel.meshService.myPeerID + let isCurrentUser: (BitchatMessage) -> Bool = { message in + message.isOwn(myPeerID: myPeerID, myGeoChatPeerID: nil) + } + // 1. Groups for group in groupRows { - let lastMsg = conversations.conversationsByID[.directPeer(group.peerID)]?.messages.last - let preview = lastMsg.map { "\($0.sender): \($0.content)" } + let lastMsg = conversations.conversationsByID[.directPeer(group.peerID)].flatMap { + MessageInteractionCodec.latestPreviewMessage(in: $0.messages, isCurrentUser: isCurrentUser) + } + let preview = lastMsg.map { + MessageInteractionCodec.formattedPreview(for: $0.content, sender: $0.sender) + } ?? String( format: String(localized: "inbox.group.members", defaultValue: "%lld members · hybrid E2E", comment: "Subtitle for a group with no messages yet"), locale: .current, @@ -641,11 +665,16 @@ final class PeerListModel: ObservableObject { // Helper to resolve latest DM message across ephemeral + stable peer IDs func latestDirectMessage(for peerID: PeerID, fingerprint: String?) -> BitchatMessage? { - var latest = conversations.conversationsByID[.directPeer(peerID)]?.messages.last + var latest = conversations.conversationsByID[.directPeer(peerID)].flatMap { + MessageInteractionCodec.latestPreviewMessage(in: $0.messages, isCurrentUser: isCurrentUser) + } if let fingerprint { for (id, conv) in conversations.conversationsByID { guard case .direct(let handle) = id, - let msg = conv.messages.last, + let msg = MessageInteractionCodec.latestPreviewMessage( + in: conv.messages, + isCurrentUser: isCurrentUser + ), chatViewModel.getFingerprint(for: handle.routingPeerID) == fingerprint else { continue } if latest == nil || msg.timestamp > latest!.timestamp { latest = msg @@ -685,7 +714,7 @@ final class PeerListModel: ObservableObject { peerID: targetPeerID, pinKey: fingerprint, displayName: meshRow?.displayName ?? rel.peerNickname, - subtitle: lastMsg?.content ?? fallbackSubtitle, + subtitle: lastMsg.map { MessageInteractionCodec.formattedPreview(for: $0.content) } ?? fallbackSubtitle, lastActivity: lastMsg?.timestamp ?? rel.lastUpdated, hasUnread: chatViewModel.hasUnreadMessages(for: targetPeerID), isPinned: pinnedKeys.contains(fingerprint), @@ -704,7 +733,10 @@ final class PeerListModel: ObservableObject { guard case .direct(let handle) = id else { continue } let peerID = handle.routingPeerID guard !peerID.isGroup, - let lastMsg = conversation.messages.last, + let lastMsg = MessageInteractionCodec.latestPreviewMessage( + in: conversation.messages, + isCurrentUser: isCurrentUser + ), !chatViewModel.isPeerBlocked(peerID) else { continue } let fingerprint = chatViewModel.getFingerprint(for: peerID) let key = fingerprint ?? peerID.id @@ -724,7 +756,7 @@ final class PeerListModel: ObservableObject { peerID: meshRow?.peerID ?? peerID, pinKey: key, displayName: meshRow?.displayName ?? displayName(for: peerID), - subtitle: lastMsg.content, + subtitle: MessageInteractionCodec.formattedPreview(for: lastMsg.content), lastActivity: lastMsg.timestamp, hasUnread: chatViewModel.hasUnreadMessages(for: peerID), isPinned: pinnedKeys.contains(key), diff --git a/bitchat/App/PublicChatModel.swift b/bitchat/App/PublicChatModel.swift index e683c590..f4b63830 100644 --- a/bitchat/App/PublicChatModel.swift +++ b/bitchat/App/PublicChatModel.swift @@ -106,7 +106,7 @@ final class PublicChatModel: ObservableObject { return } - let preview = Self.formattedPreview(for: message.content) + let preview = MessageInteractionCodec.formattedPreview(for: message.content) // When `activeConversation` is already `.mesh`, `ConversationStore` // emits a single `activeConversation.objectWillChange` per append/batch; // only emit explicitly here when observing a non-mesh channel. @@ -117,19 +117,6 @@ final class PublicChatModel: ObservableObject { latestUnreadMeshPreview = UnreadMeshPreview(sender: message.sender, text: preview) } - private static func formattedPreview(for rawContent: String) -> String { - let body = MessageInteractionCodec.parseReply(from: rawContent)?.body ?? rawContent - if body.hasPrefix(MimeType.Category.audio.messagePrefix) { - return String(localized: "chats.nearby_banner.voice_preview", defaultValue: "Voice message", comment: "Preview text for an unread Nearby voice message") - } - if body.hasPrefix(MimeType.Category.image.messagePrefix) { - return String(localized: "chats.nearby_banner.photo_preview", defaultValue: "Photo", comment: "Preview text for an unread Nearby photo message") - } - return body - .replacingOccurrences(of: "\n", with: " ") - .trimmingCharacters(in: .whitespacesAndNewlines) - } - private func retargetActiveConversation(to channel: ChannelID) { let conversation = conversations.conversation(for: ConversationID(channelID: channel)) guard conversation !== activeConversation else { diff --git a/bitchat/Localizable.xcstrings b/bitchat/Localizable.xcstrings index 1321b0e3..01eec935 100644 --- a/bitchat/Localizable.xcstrings +++ b/bitchat/Localizable.xcstrings @@ -148299,6 +148299,561 @@ } } } + }, + "message.preview.file" : { + "comment" : "Preview text for a file attachment message", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "translated", + "value" : "ملف" + } + }, + "bn" : { + "stringUnit" : { + "state" : "translated", + "value" : "ফাইল" + } + }, + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Datei" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "File" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Archivo" + } + }, + "fa" : { + "stringUnit" : { + "state" : "translated", + "value" : "فایل" + } + }, + "fil" : { + "stringUnit" : { + "state" : "translated", + "value" : "File" + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Fichier" + } + }, + "he" : { + "stringUnit" : { + "state" : "translated", + "value" : "קובץ" + } + }, + "hi" : { + "stringUnit" : { + "state" : "translated", + "value" : "फ़ाइल" + } + }, + "id" : { + "stringUnit" : { + "state" : "translated", + "value" : "File" + } + }, + "it" : { + "stringUnit" : { + "state" : "translated", + "value" : "File" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ファイル" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "파일" + } + }, + "ms" : { + "stringUnit" : { + "state" : "translated", + "value" : "Fail" + } + }, + "ne" : { + "stringUnit" : { + "state" : "translated", + "value" : "फाइल" + } + }, + "nl" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bestand" + } + }, + "pl" : { + "stringUnit" : { + "state" : "translated", + "value" : "Plik" + } + }, + "pt" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ficheiro" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "Arquivo" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Файл" + } + }, + "sv" : { + "stringUnit" : { + "state" : "translated", + "value" : "Fil" + } + }, + "ta" : { + "stringUnit" : { + "state" : "translated", + "value" : "கோப்பு" + } + }, + "th" : { + "stringUnit" : { + "state" : "translated", + "value" : "ไฟล์" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Dosya" + } + }, + "uk" : { + "stringUnit" : { + "state" : "translated", + "value" : "Файл" + } + }, + "ur" : { + "stringUnit" : { + "state" : "translated", + "value" : "فائل" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tệp" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "文件" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "檔案" + } + } + } + }, + "message.preview.reacted" : { + "comment" : "Chat preview when someone reacted to a message", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "translated", + "value" : "تفاعل بـ %@" + } + }, + "bn" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ দিয়ে প্রতিক্রিয়া জানিয়েছেন" + } + }, + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hat mit %@ reagiert" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Reacted %@" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Reaccionó con %@" + } + }, + "fa" : { + "stringUnit" : { + "state" : "translated", + "value" : "با %@ واکنش نشان داد" + } + }, + "fil" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nag-react ng %@" + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "A réagi %@" + } + }, + "he" : { + "stringUnit" : { + "state" : "translated", + "value" : "הגיב עם %@" + } + }, + "hi" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ के साथ प्रतिक्रिया दी" + } + }, + "id" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bereaksi %@" + } + }, + "it" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ha reagito con %@" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@でリアクションしました" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ 반응을 남겼습니다" + } + }, + "ms" : { + "stringUnit" : { + "state" : "translated", + "value" : "Memberi reaksi %@" + } + }, + "ne" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ प्रतिक्रिया दियो" + } + }, + "nl" : { + "stringUnit" : { + "state" : "translated", + "value" : "Reageerde met %@" + } + }, + "pl" : { + "stringUnit" : { + "state" : "translated", + "value" : "Zareagował(a) %@" + } + }, + "pt" : { + "stringUnit" : { + "state" : "translated", + "value" : "Reagiu com %@" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "Reagiu com %@" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отреагировал(а) %@" + } + }, + "sv" : { + "stringUnit" : { + "state" : "translated", + "value" : "Reagerade med %@" + } + }, + "ta" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ என எதிர்வினையாற்றினார்" + } + }, + "th" : { + "stringUnit" : { + "state" : "translated", + "value" : "ตอบกลับด้วย %@" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ tepkisi verdi" + } + }, + "uk" : { + "stringUnit" : { + "state" : "translated", + "value" : "Відреагував(ла) %@" + } + }, + "ur" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ کے ساتھ ردعمل دیا" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đã bày tỏ cảm xúc %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "回应了 %@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "回應了 %@" + } + } + } + }, + "message.preview.reacted_with_sender" : { + "comment" : "Chat preview when a group member reacted to a message", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "translated", + "value" : "تفاعل %@ بـ %@" + } + }, + "bn" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ %@ দিয়ে প্রতিক্রিয়া জানিয়েছেন" + } + }, + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ hat mit %@ reagiert" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ reacted %@" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ reaccionó con %@" + } + }, + "fa" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ با %@ واکنش نشان داد" + } + }, + "fil" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nag-react si %@ ng %@" + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ a réagi %@" + } + }, + "he" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ הגיב עם %@" + } + }, + "hi" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ ने %@ के साथ प्रतिक्रिया दी" + } + }, + "id" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ bereaksi %@" + } + }, + "it" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ ha reagito con %@" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@が%@でリアクションしました" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@님이 %@ 반응을 남겼습니다" + } + }, + "ms" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ memberi reaksi %@" + } + }, + "ne" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ ले %@ प्रतिक्रिया दियो" + } + }, + "nl" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ reageerde met %@" + } + }, + "pl" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ zareagował(a) %@" + } + }, + "pt" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ reagiu com %@" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ reagiu com %@" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ отреагировал(а) %@" + } + }, + "sv" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ reagerade med %@" + } + }, + "ta" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ %@ என எதிர்வினையாற்றினார்" + } + }, + "th" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ ตอบกลับด้วย %@" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ %@ tepkisi verdi" + } + }, + "uk" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ відреагував(ла) %@" + } + }, + "ur" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ نے %@ کے ساتھ ردعمل دیا" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ đã bày tỏ cảm xúc %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ 回应了 %@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ 回應了 %@" + } + } + } } } } diff --git a/bitchat/Protocols/MessageInteractionCodec.swift b/bitchat/Protocols/MessageInteractionCodec.swift index bb53996e..7001e8ff 100644 --- a/bitchat/Protocols/MessageInteractionCodec.swift +++ b/bitchat/Protocols/MessageInteractionCodec.swift @@ -46,21 +46,144 @@ enum MessageInteractionCodec { static let maxSnippetLength = 80 static let reactionTargetPrefixLength = 8 + // MARK: - Message Previews + + /// Formats a raw wire/storage message into clean, single-line human-readable + /// preview text suitable for inbox rows, banners, notifications, and snippets. + /// + /// - Media markers (`[voice] `, `[image] `, `[file] `) become + /// localized labels (`"Voice message"`, `"Photo"`, `"File"`). + /// - Quoted replies (`> @sender: snippet\nbody`) are unwrapped to their body. + /// - Reaction control payloads (`[react::]`) become `" reacted "` + /// when a non-system `sender` is supplied, or `"Reacted "` otherwise. + static func formattedPreview(for content: String, sender: String? = nil) -> String { + let cleanSender: String? = { + guard let raw = sender?.trimmingCharacters(in: .whitespacesAndNewlines), + !raw.isEmpty, + raw != "system" else { + return nil + } + return raw + }() + + if let reaction = parseReaction(from: content) { + if let cleanSender { + return String( + format: String( + localized: "message.preview.reacted_with_sender", + defaultValue: "%@ reacted %@", + comment: "Chat preview when a group member reacted to a message" + ), + locale: .current, + cleanSender, + reaction.emoji + ) + } + return String( + format: String( + localized: "message.preview.reacted", + defaultValue: "Reacted %@", + comment: "Chat preview when someone reacted to a message" + ), + locale: .current, + reaction.emoji + ) + } + + let body = parseReply(from: content)?.body ?? content + let formattedBody: String + if body.hasPrefix(MimeType.Category.audio.messagePrefix) { + formattedBody = String( + localized: "chats.nearby_banner.voice_preview", + defaultValue: "Voice message", + comment: "Preview text for a voice message" + ) + } else if body.hasPrefix(MimeType.Category.image.messagePrefix) { + formattedBody = String( + localized: "chats.nearby_banner.photo_preview", + defaultValue: "Photo", + comment: "Preview text for a photo message" + ) + } else if body.hasPrefix(MimeType.Category.file.messagePrefix) { + formattedBody = String( + localized: "message.preview.file", + defaultValue: "File", + comment: "Preview text for a file attachment message" + ) + } else { + formattedBody = body + .replacingOccurrences(of: "\r\n", with: " ") + .replacingOccurrences(of: "\n", with: " ") + .replacingOccurrences(of: "\r", with: " ") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + if let cleanSender { + return "\(cleanSender): \(formattedBody)" + } + return formattedBody + } + + /// Returns the latest message suitable for a conversation list preview. + /// Reaction control messages that toggled off (an even number of occurrences + /// for the same actor, target, and emoji) are skipped so removing a reaction + /// falls back to the previous message rather than advertising the removed one. + static func latestPreviewMessage( + in messages: [BitchatMessage], + isCurrentUser: ((BitchatMessage) -> Bool)? = nil + ) -> BitchatMessage? { + guard let last = messages.last else { return nil } + if parseReaction(from: last.content) == nil { + return last + } + + struct ReactionKey: Hashable { + let actor: String + let targetShortID: String + let emoji: String + } + + func actorKey(for message: BitchatMessage) -> String { + if let isCurrentUser, isCurrentUser(message) { + return "__me__" + } + return message.senderPeerID?.id ?? "name:\(message.sender)" + } + + var counts: [ReactionKey: Int] = [:] + for message in messages where message.sender != "system" { + guard let parsed = parseReaction(from: message.content) else { continue } + let key = ReactionKey( + actor: actorKey(for: message), + targetShortID: parsed.targetShortID, + emoji: parsed.emoji + ) + counts[key, default: 0] += 1 + } + + for message in messages.reversed() { + if let parsed = parseReaction(from: message.content) { + guard message.sender != "system" else { continue } + let key = ReactionKey( + actor: actorKey(for: message), + targetShortID: parsed.targetShortID, + emoji: parsed.emoji + ) + if (counts[key] ?? 0) % 2 == 1 { + return message + } + continue + } + return message + } + return nil + } + // MARK: - Quoted Replies /// Condenses a message into a single-line bounded preview suitable for reply quotes. static func makeSnippet(from content: String) -> String { - let stripped: String - if let parsed = parseReply(from: content) { - stripped = parsed.body - } else { - stripped = content - } - let collapsed = stripped - .replacingOccurrences(of: "\r\n", with: " ") - .replacingOccurrences(of: "\n", with: " ") - .replacingOccurrences(of: "\r", with: " ") - .trimmingCharacters(in: .whitespacesAndNewlines) + let collapsed = formattedPreview(for: content) if collapsed.count <= maxSnippetLength { return collapsed } @@ -243,7 +366,7 @@ enum MessageInteractionCodec { parseReaction(from: message.content) == nil else { return nil } - let searchableBody = parseReply(from: message.content)?.body ?? message.content + let searchableBody = formattedPreview(for: message.content) if searchableBody.localizedCaseInsensitiveContains(trimmed) || message.sender.localizedCaseInsensitiveContains(trimmed) { return message.id diff --git a/bitchat/Services/NotificationService.swift b/bitchat/Services/NotificationService.swift index 8c7d82f8..83e53bd8 100644 --- a/bitchat/Services/NotificationService.swift +++ b/bitchat/Services/NotificationService.swift @@ -179,7 +179,7 @@ final class NotificationService { func sendMentionNotification(from sender: String, message: String) { let title = hidePreviews ? Redacted.mentionTitle : "🫵 You were mentioned by \(sender)" - let body = hidePreviews ? Redacted.body : message + let body = hidePreviews ? Redacted.body : MessageInteractionCodec.formattedPreview(for: message) let identifier = "mention-\(UUID().uuidString)" sendLocalNotification(title: title, body: body, identifier: identifier) @@ -187,7 +187,7 @@ final class NotificationService { func sendPrivateMessageNotification(from sender: String, message: String, peerID: PeerID) { let title = hidePreviews ? Redacted.directMessageTitle : "🔒 DM from \(sender)" - let body = hidePreviews ? Redacted.body : message + let body = hidePreviews ? Redacted.body : MessageInteractionCodec.formattedPreview(for: message) let identifier = "private-\(UUID().uuidString)" // Routing payload, not display copy: `userInfo` never reaches the lock // screen, and the conversation to open still has to be identifiable. diff --git a/bitchatTests/PeerListModelTests.swift b/bitchatTests/PeerListModelTests.swift index d7b32017..5306c265 100644 --- a/bitchatTests/PeerListModelTests.swift +++ b/bitchatTests/PeerListModelTests.swift @@ -81,6 +81,130 @@ struct PeerListModelTests { #expect(renamed) } + @Test func inboxPreviewsFormatMediaAndReactionsCleanly() async throws { + let viewModel = makeViewModel() + let model = PeerListModel( + chatViewModel: viewModel, + conversations: viewModel.conversations, + locationChannelsModel: LocationChannelsModel(manager: makeLocationManager()) + ) + + let peerID = PeerID(str: "00000000000000a1") + let baseDate = Date(timeIntervalSince1970: 1_700_000_000) + + // DM with a voice note should display "Voice message", never the raw filename. + viewModel.conversations.append( + BitchatMessage( + id: "dm-voice-1", + sender: "Lulose", + content: "[voice] 0D84B302-F93A-45D5-986A-CE9196C.m4a", + timestamp: baseDate, + isRelay: false, + isPrivate: true, + senderPeerID: peerID + ), + to: .directPeer(peerID) + ) + let hasVoiceRow = await TestHelpers.waitUntil({ + model.inboxRows.first(where: { $0.peerID == peerID })?.subtitle == "Voice message" + }, timeout: TestConstants.settleTimeout) + #expect(hasVoiceRow) + + // Searching by raw UUID must not match; searching by "voice" must match cleanly. + #expect(model.filteredInboxRows(matching: "0D84B302").isEmpty) + let voiceSearch = model.filteredInboxRows(matching: "voice") + #expect(voiceSearch.first(where: { $0.peerID == peerID })?.subtitle == "Voice message") + + // DM ending with a reaction shows "Reacted ❤️"; toggling it off falls back to "Voice message". + viewModel.conversations.append( + BitchatMessage( + id: "dm-react-1", + sender: "Lulose", + content: "[react:dm-voice:❤️]", + timestamp: baseDate.addingTimeInterval(5), + isRelay: false, + isPrivate: true, + senderPeerID: peerID + ), + to: .directPeer(peerID) + ) + let hasReactRow = await TestHelpers.waitUntil({ + model.inboxRows.first(where: { $0.peerID == peerID })?.subtitle == "Reacted ❤️" + }, timeout: TestConstants.settleTimeout) + #expect(hasReactRow) + #expect(model.filteredInboxRows(matching: "react:").isEmpty) + + viewModel.conversations.append( + BitchatMessage( + id: "dm-react-2", + sender: "Lulose", + content: "[react:dm-voice:❤️]", + timestamp: baseDate.addingTimeInterval(6), + isRelay: false, + isPrivate: true, + senderPeerID: peerID + ), + to: .directPeer(peerID) + ) + let fellBackToVoice = await TestHelpers.waitUntil({ + model.inboxRows.first(where: { $0.peerID == peerID })?.subtitle == "Voice message" + }, timeout: TestConstants.settleTimeout) + #expect(fellBackToVoice) + } + + @Test func groupInboxPreviewFormatsSenderReactionAndMedia() async throws { + let viewModel = makeViewModel() + let model = PeerListModel( + chatViewModel: viewModel, + conversations: viewModel.conversations, + locationChannelsModel: LocationChannelsModel(manager: makeLocationManager()) + ) + + let creator = GroupMember( + fingerprint: String(repeating: "a", count: 64), + signingKey: Data(repeating: 0x22, count: 32), + nickname: "jack" + ) + let group = try #require(viewModel.groupStore.createGroup(named: "kooks", creator: creator)) + let groupPeerID = group.peerID + let senderPeerID = PeerID(str: "00000000000000b2") + let baseDate = Date(timeIntervalSince1970: 1_700_000_100) + + viewModel.conversations.append( + BitchatMessage( + id: "7831339C-group-msg", + sender: "jack", + content: "[image] ABCDEF12-3456.jpg", + timestamp: baseDate, + isRelay: false, + isPrivate: true, + senderPeerID: senderPeerID + ), + to: .directPeer(groupPeerID) + ) + let hasPhotoPreview = await TestHelpers.waitUntil({ + model.inboxRows.first(where: { $0.peerID == groupPeerID })?.subtitle == "jack: Photo" + }, timeout: TestConstants.settleTimeout) + #expect(hasPhotoPreview) + + viewModel.conversations.append( + BitchatMessage( + id: "group-react-1", + sender: "jack", + content: "[react:7831339C:❤️]", + timestamp: baseDate.addingTimeInterval(5), + isRelay: false, + isPrivate: true, + senderPeerID: senderPeerID + ), + to: .directPeer(groupPeerID) + ) + let hasReactionPreview = await TestHelpers.waitUntil({ + model.inboxRows.first(where: { $0.peerID == groupPeerID })?.subtitle == "jack reacted ❤️" + }, timeout: TestConstants.settleTimeout) + #expect(hasReactionPreview) + } + // MARK: - Helpers private func makeViewModel(transport: MockTransport = MockTransport()) -> ChatViewModel { diff --git a/bitchatTests/Services/NotificationServiceTests.swift b/bitchatTests/Services/NotificationServiceTests.swift index 748962e2..8caedc46 100644 --- a/bitchatTests/Services/NotificationServiceTests.swift +++ b/bitchatTests/Services/NotificationServiceTests.swift @@ -89,6 +89,33 @@ final class NotificationServiceTests: XCTestCase { XCTAssertEqual(request?.content.userInfo["senderName"] as? String, "Alice") } + func test_sendPrivateMessageNotification_formatsMediaAndReactions() { + var requests: [UNNotificationRequest] = [] + var deps = NotificationService.Dependencies.noop + deps.deliver = { requests.append($0) } + let service = NotificationService( + isRunningTestsProvider: { false }, + dependencies: deps, + hidePreviewsProvider: { false } + ) + let peerID = PeerID(str: "deadbeefdeadbeef") + + service.sendPrivateMessageNotification( + from: "Lulose", + message: "[voice] 0D84B302-F93A-45D5-986A-CE9196C.m4a", + peerID: peerID + ) + service.sendPrivateMessageNotification( + from: "Lulose", + message: "[react:7831339C:❤️]", + peerID: peerID + ) + + XCTAssertEqual(requests.count, 2) + XCTAssertEqual(requests[0].content.body, "Voice message") + XCTAssertEqual(requests[1].content.body, "Reacted ❤️") + } + /// Previews hidden: the default. The routing payload has to survive /// redaction, or tapping the alert would not open the conversation. func test_sendPrivateMessageNotification_withPreviewsHidden_keepsRoutingButDropsContent() { diff --git a/bitchatTests/Services/Phase1FeaturesTests.swift b/bitchatTests/Services/Phase1FeaturesTests.swift index af82f160..05686386 100644 --- a/bitchatTests/Services/Phase1FeaturesTests.swift +++ b/bitchatTests/Services/Phase1FeaturesTests.swift @@ -925,4 +925,109 @@ final class InboxPinnedChatsTests: XCTestCase { XCTAssertEqual(parsed?.quotedSnippet, "Original body: with colon") XCTAssertEqual(parsed?.body, "Got it!") } + + func test_formattedPreviewCleansMediaRepliesAndReactions() { + XCTAssertEqual( + MessageInteractionCodec.formattedPreview(for: "[voice] 0D84B302-F93A-45D5-986A-CE9196C.m4a"), + "Voice message" + ) + XCTAssertEqual( + MessageInteractionCodec.formattedPreview(for: "[voice] 0D84B302-F93A-45D5-986A-CE9196C.m4a", sender: "jack"), + "jack: Voice message" + ) + XCTAssertEqual( + MessageInteractionCodec.formattedPreview(for: "[image] 12345678-ABCD.jpg"), + "Photo" + ) + XCTAssertEqual( + MessageInteractionCodec.formattedPreview(for: "[image] 12345678-ABCD.jpg", sender: "jack"), + "jack: Photo" + ) + XCTAssertEqual( + MessageInteractionCodec.formattedPreview(for: "[file] document.pdf"), + "File" + ) + XCTAssertEqual( + MessageInteractionCodec.formattedPreview(for: "[react:7831339C:❤️]"), + "Reacted ❤️" + ) + XCTAssertEqual( + MessageInteractionCodec.formattedPreview(for: "[react:7831339C:❤️]", sender: "jack"), + "jack reacted ❤️" + ) + XCTAssertEqual( + MessageInteractionCodec.formattedPreview(for: "> @alice: hi\nOn my way", sender: "jack"), + "jack: On my way" + ) + XCTAssertEqual( + MessageInteractionCodec.formattedPreview(for: "Alice joined", sender: "system"), + "Alice joined" + ) + + // Reply targets for media messages quote clean labels rather than raw filenames. + let voiceTarget = MessageReplyTarget( + messageID: "v1", + sender: "Lulose", + content: "[voice] 0D84B302-F93A-45D5-986A-CE9196C.m4a" + ) + XCTAssertEqual(voiceTarget.snippet, "Voice message") + } + + func test_latestPreviewMessageSkipsToggledOffReactions() { + let alice = PeerID(str: "1111111111111111") + let bob = PeerID(str: "2222222222222222") + let msg = BitchatMessage( + id: "7831339C-1111-2222", + sender: "alice", + content: "See you soon", + timestamp: Date(timeIntervalSince1970: 100), + isRelay: false, + isPrivate: true, + senderPeerID: alice + ) + let reactAdd = BitchatMessage( + id: "r1", + sender: "bob", + content: "[react:7831339C:❤️]", + timestamp: Date(timeIntervalSince1970: 101), + isRelay: false, + isPrivate: true, + senderPeerID: bob + ) + let reactRemove = BitchatMessage( + id: "r2", + sender: "bob", + content: "[react:7831339C:❤️]", + timestamp: Date(timeIntervalSince1970: 102), + isRelay: false, + isPrivate: true, + senderPeerID: bob + ) + let reactReadd = BitchatMessage( + id: "r3", + sender: "bob", + content: "[react:7831339C:❤️]", + timestamp: Date(timeIntervalSince1970: 103), + isRelay: false, + isPrivate: true, + senderPeerID: bob + ) + + XCTAssertEqual(MessageInteractionCodec.latestPreviewMessage(in: [msg, reactAdd])?.id, "r1") + XCTAssertEqual(MessageInteractionCodec.latestPreviewMessage(in: [msg, reactAdd, reactRemove])?.id, msg.id) + XCTAssertEqual(MessageInteractionCodec.latestPreviewMessage(in: [msg, reactAdd, reactRemove, reactReadd])?.id, "r3") + } + + func test_inChatSearchMatchesFriendlyMediaLabelsInsteadOfUUIDs() { + let voice = BitchatMessage( + id: "v1", + sender: "Lulose", + content: "[voice] 0D84B302-F93A-45D5-986A-CE9196C.m4a", + timestamp: Date(), + isRelay: false, + isPrivate: true + ) + XCTAssertEqual(MessageInteractionCodec.matchingMessageIDs(in: [voice], query: "0D84B302"), []) + XCTAssertEqual(MessageInteractionCodec.matchingMessageIDs(in: [voice], query: "voice"), ["v1"]) + } }