diff --git a/bitchat/App/AppRuntime.swift b/bitchat/App/AppRuntime.swift index 3d5bc5bc..95136fc8 100644 --- a/bitchat/App/AppRuntime.swift +++ b/bitchat/App/AppRuntime.swift @@ -102,8 +102,10 @@ final class AppRuntime: ObservableObject { onPanicWipe: { sharedContentImportModel.discardAll() } ) let chatViewModel = self.chatViewModel + let identityManager = chatViewModel.identityManager self.boardAlertsModel = BoardAlertsModel( arrivals: BoardStore.shared.postArrivals.eraseToAnyPublisher(), + endorsements: BoardStore.shared.endorsementArrivals.eraseToAnyPublisher(), wipes: BoardStore.shared.didWipe.eraseToAnyPublisher(), dependencies: BoardAlertsModel.Dependencies( isOwnPost: { post in @@ -116,6 +118,15 @@ final class AppRuntime: ObservableObject { } else { chatViewModel.addGeohashSystemMessage(content, geohash: geohash) } + }, + confirmation: { endorsement in + guard let post = BoardStore.shared.post(withID: endorsement.postID) else { return nil } + let count = BoardManager.trustedConfirmationCount( + endorsers: BoardStore.shared.endorserKeys(forPostID: endorsement.postID), + trusted: identityManager.trustedSigningKeys(), + author: post.authorSigningKey + ) + return (post, count) } ) ) diff --git a/bitchat/Localizable.xcstrings b/bitchat/Localizable.xcstrings index e498a20e..ebee7dc4 100644 --- a/bitchat/Localizable.xcstrings +++ b/bitchat/Localizable.xcstrings @@ -81307,6 +81307,192 @@ } } }, + "notices.alert.urgent_confirmed" : { + "comment" : "Local chat line when people the user verified or vouched for endorse an urgent notice. Placeholders: author, number of trusted confirmations, notice text", + "extractionState" : "manual", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 إعلان عاجل من @%1$@ أكّده أشخاص تثق بهم (%2$lld): %3$@" + } + }, + "bn" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@-এর জরুরি নোটিশ, আপনার বিশ্বস্ত লোকেরা নিশ্চিত করেছে (%2$lld): %3$@" + } + }, + "de" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 dringender hinweis von @%1$@, bestätigt von leuten, denen du vertraust (%2$lld): %3$@" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "📌 urgent notice from @%1$@ confirmed by people you trust (%2$lld): %3$@" + } + }, + "es" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 aviso urgente de @%1$@ confirmado por personas de confianza (%2$lld): %3$@" + } + }, + "fa" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 اعلان فوری از @%1$@ که افراد مورد اعتمادت تأیید کرده‌اند (%2$lld): %3$@" + } + }, + "fil" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 urgent na paunawa mula kay @%1$@, kinumpirma ng mga taong pinagkakatiwalaan mo (%2$lld): %3$@" + } + }, + "fr" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 avis urgent de @%1$@ confirmé par des personnes de confiance (%2$lld) : %3$@" + } + }, + "he" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 הודעה דחופה מ-@%1$@ אושרה על ידי אנשים שאתה סומך עליהם (%2$lld): %3$@" + } + }, + "hi" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ की तत्काल सूचना, आपके भरोसेमंद लोगों ने पुष्टि की (%2$lld): %3$@" + } + }, + "id" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 pemberitahuan mendesak dari @%1$@ dikonfirmasi oleh orang yang kamu percaya (%2$lld): %3$@" + } + }, + "it" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 avviso urgente da @%1$@ confermato da persone di cui ti fidi (%2$lld): %3$@" + } + }, + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ からの緊急のお知らせを信頼できる人が確認しました (%2$lld): %3$@" + } + }, + "ko" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ 님의 긴급 공지를 신뢰하는 사람들이 확인했습니다 (%2$lld): %3$@" + } + }, + "ms" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 notis segera daripada @%1$@ disahkan oleh orang yang anda percayai (%2$lld): %3$@" + } + }, + "ne" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ को जरुरी सूचना, तिमीले विश्वास गर्ने मानिसहरूले पुष्टि गरे (%2$lld): %3$@" + } + }, + "nl" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 dringende melding van @%1$@ bevestigd door mensen die je vertrouwt (%2$lld): %3$@" + } + }, + "pl" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 pilne ogłoszenie od @%1$@ potwierdzone przez zaufane osoby (%2$lld): %3$@" + } + }, + "pt" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 aviso urgente de @%1$@ confirmado por pessoas em quem confias (%2$lld): %3$@" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 aviso urgente de @%1$@ confirmado por pessoas em quem você confia (%2$lld): %3$@" + } + }, + "ru" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 срочное объявление от @%1$@ подтвердили люди, которым ты доверяешь (%2$lld): %3$@" + } + }, + "sv" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 brådskande meddelande från @%1$@ bekräftat av personer du litar på (%2$lld): %3$@" + } + }, + "ta" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ இன் அவசர அறிவிப்பை நீங்கள் நம்பும் நபர்கள் உறுதிப்படுத்தினர் (%2$lld): %3$@" + } + }, + "th" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 ประกาศด่วนจาก @%1$@ ได้รับการยืนยันจากคนที่คุณไว้ใจ (%2$lld): %3$@" + } + }, + "tr" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ kişisinden acil duyuru, güvendiğin kişilerce doğrulandı (%2$lld): %3$@" + } + }, + "uk" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 термінове оголошення від @%1$@ підтвердили люди, яким ти довіряєш (%2$lld): %3$@" + } + }, + "ur" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 @%1$@ کا فوری نوٹس، جن لوگوں پر آپ بھروسہ کرتے ہیں انہوں نے تصدیق کی (%2$lld): %3$@" + } + }, + "vi" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 thông báo khẩn từ @%1$@ đã được những người bạn tin tưởng xác nhận (%2$lld): %3$@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 来自 @%1$@ 的紧急通知已获你信任的人确认 (%2$lld):%3$@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "📌 來自 @%1$@ 的緊急通知已獲你信任的人確認 (%2$lld):%3$@" + } + } + } + }, "notices.alert.urgent_single" : { "comment" : "Local chat line when one urgent notice is pinned nearby", "extractionState" : "manual", diff --git a/bitchat/Services/Board/BoardAlertsModel.swift b/bitchat/Services/Board/BoardAlertsModel.swift index 35daedfe..7534988a 100644 --- a/bitchat/Services/Board/BoardAlertsModel.swift +++ b/bitchat/Services/Board/BoardAlertsModel.swift @@ -18,6 +18,8 @@ import Foundation /// arrive together. /// - Every other new pin just marks the header's pin icon until the notices /// sheet is opened. +/// - A recent urgent pin that someone we trust endorses gets one more line +/// saying so, the first time it happens. @MainActor final class BoardAlertsModel: ObservableObject { struct Dependencies { @@ -26,6 +28,9 @@ final class BoardAlertsModel: ObservableObject { /// Appends a local system line to a scope's chat timeline /// (geohash, or "" for mesh chat). var emitSystemLine: @MainActor (_ content: String, _ geohash: String) -> Void + /// The endorsed post and how many trusted people now confirm it, or + /// nil when the post is not known here. + var confirmation: @MainActor (BoardEndorsementPacket) -> (post: BoardPostPacket, trustedCount: Int)? = { _ in nil } var now: () -> Date = Date.init /// Schedules the collapsed flush of pending urgent alerts; tests /// inject a synchronous hook. @@ -51,10 +56,13 @@ final class BoardAlertsModel: ObservableObject { /// PostIDs already handled this session, so store eviction/re-sync churn /// can't re-alert. Bounded by session wire volume (32-byte strings). private var handledPostIDs = Set() + /// Urgent posts already announced as confirmed this session. + private var confirmedPostIDs = Set() private var pendingUrgent: [String: [BoardPostPacket]] = [:] private var flushScheduled = false private let dependencies: Dependencies private var cancellable: AnyCancellable? + private var endorsementCancellable: AnyCancellable? private var wipeCancellable: AnyCancellable? private enum Strings { @@ -73,10 +81,19 @@ final class BoardAlertsModel: ObservableObject { count ) } + + static func urgentConfirmed(author: String, count: Int, content: String) -> String { + String( + format: String(localized: "notices.alert.urgent_confirmed", defaultValue: "📌 urgent notice from @%1$@ confirmed by people you trust (%2$lld): %3$@", comment: "Local chat line when people the user verified or vouched for endorse an urgent notice. Placeholders: author, number of trusted confirmations, notice text"), + locale: .current, + author, count, content + ) + } } init( arrivals: AnyPublisher, + endorsements: AnyPublisher = Empty(completeImmediately: false).eraseToAnyPublisher(), wipes: AnyPublisher = Empty(completeImmediately: false).eraseToAnyPublisher(), dependencies: Dependencies ) { @@ -86,6 +103,11 @@ final class BoardAlertsModel: ObservableObject { .sink { [weak self] post in self?.handleArrival(post) } + endorsementCancellable = endorsements + .receive(on: DispatchQueue.main) + .sink { [weak self] endorsement in + self?.handleEndorsement(endorsement) + } wipeCancellable = wipes .receive(on: DispatchQueue.main) .sink { [weak self] in @@ -110,6 +132,7 @@ final class BoardAlertsModel: ObservableObject { func reset() { pendingUrgent.removeAll() handledPostIDs.removeAll() + confirmedPostIDs.removeAll() guard !unseenPostScopes.isEmpty else { return } unseenPostScopes.removeAll() } @@ -136,6 +159,28 @@ final class BoardAlertsModel: ObservableObject { } } + /// One line per urgent post, the first time a trusted endorsement lands + /// while the post is still recent. Later endorsements only move the + /// count shown in the notices sheet. + func handleEndorsement(_ endorsement: BoardEndorsementPacket) { + let postID = endorsement.postID.hexEncodedString() + guard !confirmedPostIDs.contains(postID), + let (post, trustedCount) = dependencies.confirmation(endorsement), + trustedCount > 0, + post.isUrgent, + !dependencies.isOwnPost(post) else { + return + } + let createdAt = Date(timeIntervalSince1970: TimeInterval(post.createdAt) / 1000) + guard dependencies.now().timeIntervalSince(createdAt) <= Self.inlineRecencyWindow else { return } + confirmedPostIDs.insert(postID) + let author = post.authorNickname.trimmedOrNilIfEmpty ?? "anon" + dependencies.emitSystemLine( + Strings.urgentConfirmed(author: author, count: trustedCount, content: Self.truncated(post.content)), + post.geohash + ) + } + private func flushPendingUrgent() { flushScheduled = false let pending = pendingUrgent diff --git a/bitchat/Services/Board/BoardManager.swift b/bitchat/Services/Board/BoardManager.swift index 5874b31e..f0e2efc9 100644 --- a/bitchat/Services/Board/BoardManager.swift +++ b/bitchat/Services/Board/BoardManager.swift @@ -82,8 +82,12 @@ final class BoardManager: ObservableObject { /// strangers are stored and relayed but never counted here. func confirmationCount(for post: BoardPostPacket) -> Int { guard let endorsers = endorsements[post.postID], !endorsers.isEmpty else { return 0 } - let trusted = trustedSigningKeys() - return Set(endorsers).filter { trusted.contains($0) && $0 != post.authorSigningKey }.count + return Self.trustedConfirmationCount(endorsers: endorsers, trusted: trustedSigningKeys(), author: post.authorSigningKey) + } + + /// Distinct trusted endorsers, never counting the author. + nonisolated static func trustedConfirmationCount(endorsers: [Data], trusted: Set, author: Data) -> Int { + Set(endorsers).filter { trusted.contains($0) && $0 != author }.count } func hasEndorsed(_ post: BoardPostPacket) -> Bool { diff --git a/bitchat/Services/Board/BoardStore.swift b/bitchat/Services/Board/BoardStore.swift index 37bbe5d7..7f03f27a 100644 --- a/bitchat/Services/Board/BoardStore.swift +++ b/bitchat/Services/Board/BoardStore.swift @@ -172,6 +172,15 @@ final class BoardStore { } } + /// The live post with this ID, if any. + func post(withID postID: Data) -> BoardPostPacket? { + let nowMs = currentMs() + return queue.sync { + pruneExpiredLocked(nowMs: nowMs) + return posts.first { $0.post.postID == postID }?.post + } + } + /// Endorser signing keys stored for one post, oldest endorsement first. func endorserKeys(forPostID postID: Data) -> [Data] { let nowMs = currentMs() diff --git a/bitchatTests/Services/BoardAlertsModelTests.swift b/bitchatTests/Services/BoardAlertsModelTests.swift index df891cea..865b02f6 100644 --- a/bitchatTests/Services/BoardAlertsModelTests.swift +++ b/bitchatTests/Services/BoardAlertsModelTests.swift @@ -30,7 +30,11 @@ struct BoardAlertsModelTests { } } - private func makeModel(harness: Harness, now: Date? = nil) -> BoardAlertsModel { + private func makeModel( + harness: Harness, + now: Date? = nil, + confirmation: @escaping @MainActor (BoardEndorsementPacket) -> (post: BoardPostPacket, trustedCount: Int)? = { _ in nil } + ) -> BoardAlertsModel { let fixedNow = now ?? baseDate return BoardAlertsModel( arrivals: Empty(completeImmediately: false).eraseToAnyPublisher(), @@ -39,6 +43,7 @@ struct BoardAlertsModelTests { emitSystemLine: { content, geohash in harness.lines.append((content, geohash)) }, + confirmation: confirmation, now: { fixedNow }, scheduleFlush: { flush in harness.pendingFlushes.append(flush) @@ -212,4 +217,96 @@ struct BoardAlertsModelTests { #expect(harness.lines[0].content.count < 200) #expect(harness.lines[0].content.contains("…")) } + + // MARK: - Trusted confirmations + + private func endorsement(of post: BoardPostPacket) -> BoardEndorsementPacket { + BoardEndorsementPacket( + postID: post.postID, + postAuthorSigningKey: post.authorSigningKey, + endorserSigningKey: Data(repeating: 9, count: 32), + endorsedAt: baseMs + 1, + signature: Data(repeating: 2, count: 64) + ) + } + + @Test + func trustedEndorsementOfRecentUrgentPost_emitsOneConfirmedLine() { + let harness = Harness() + let post = makePost(content: "road closed", geohash: "9q8yy", urgent: true) + var count = 1 + let model = makeModel(harness: harness) { _ in (post, count) } + + model.handleEndorsement(endorsement(of: post)) + count = 2 + model.handleEndorsement(endorsement(of: post)) + + #expect(harness.lines.count == 1) + #expect(harness.lines[0].geohash == "9q8yy") + #expect(harness.lines[0].content.contains("road closed")) + #expect(harness.lines[0].content.contains("@alice")) + #expect(harness.lines[0].content.contains("1")) + } + + @Test + func untrustedEndorsement_staysSilent() { + let harness = Harness() + let post = makePost(urgent: true) + let model = makeModel(harness: harness) { _ in (post, 0) } + + model.handleEndorsement(endorsement(of: post)) + #expect(harness.lines.isEmpty) + } + + @Test + func endorsementOfCalmPost_staysSilent() { + let harness = Harness() + let post = makePost(urgent: false) + let model = makeModel(harness: harness) { _ in (post, 3) } + + model.handleEndorsement(endorsement(of: post)) + #expect(harness.lines.isEmpty) + } + + @Test + func endorsementOfOwnPost_staysSilent() { + let harness = Harness() + let post = makePost(urgent: true, authorKey: ownKey) + let model = makeModel(harness: harness) { _ in (post, 2) } + + model.handleEndorsement(endorsement(of: post)) + #expect(harness.lines.isEmpty) + } + + @Test + func endorsementOfStaleUrgentPost_staysSilent() { + let harness = Harness() + let post = makePost(createdAt: baseMs, urgent: true) + let later = baseDate.addingTimeInterval(BoardAlertsModel.inlineRecencyWindow + 60) + let model = makeModel(harness: harness, now: later) { _ in (post, 2) } + + model.handleEndorsement(endorsement(of: post)) + #expect(harness.lines.isEmpty) + } + + @Test + func endorsementOfUnknownPost_staysSilent() { + let harness = Harness() + let model = makeModel(harness: harness) + + model.handleEndorsement(endorsement(of: makePost(urgent: true))) + #expect(harness.lines.isEmpty) + } + + @Test + func reset_allowsConfirmationAgainAfterWipe() { + let harness = Harness() + let post = makePost(urgent: true) + let model = makeModel(harness: harness) { _ in (post, 1) } + + model.handleEndorsement(endorsement(of: post)) + model.reset() + model.handleEndorsement(endorsement(of: post)) + #expect(harness.lines.count == 2) + } }