diff --git a/bitchat/Features/voice/PTTSettings.swift b/bitchat/Features/voice/PTTSettings.swift index c3b56510..dc84854a 100644 --- a/bitchat/Features/voice/PTTSettings.swift +++ b/bitchat/Features/voice/PTTSettings.swift @@ -16,12 +16,32 @@ import AppKit /// User preference for live push-to-talk voice. One switch controls both /// directions: streaming your holds live, and auto-playing inbound bursts. /// Off means voice messages behave exactly like classic voice notes. +/// +/// Off by default: live mode sends audio to other people before the hold is +/// released and plays strangers' voices out of the speaker unprompted. Both +/// are consequences someone must opt into, not discover. enum PTTSettings { - private static let liveVoiceEnabledKey = "ptt.liveVoiceEnabled" + static let liveVoiceEnabledKey = "ptt.liveVoiceEnabled" static var liveVoiceEnabled: Bool { - get { UserDefaults.standard.object(forKey: liveVoiceEnabledKey) as? Bool ?? true } - set { UserDefaults.standard.set(newValue, forKey: liveVoiceEnabledKey) } + get { liveVoiceEnabled(in: .standard) } + set { setLiveVoiceEnabled(newValue, in: .standard) } + } + + /// Store-injecting forms, so tests can assert the default and both settings + /// without touching the shared preferences other tests read. + static func liveVoiceEnabled(in defaults: UserDefaults) -> Bool { + defaults.object(forKey: liveVoiceEnabledKey) as? Bool ?? false + } + + static func setLiveVoiceEnabled(_ enabled: Bool, in defaults: UserDefaults) { + defaults.set(enabled, forKey: liveVoiceEnabledKey) + } + + /// Panic-wipe hook. Removing the key restores the off default, so a wiped + /// device cannot come back streaming live. + static func reset(in defaults: UserDefaults = .standard) { + defaults.removeObject(forKey: liveVoiceEnabledKey) } /// Autoplay is foreground-only: audio must never start from the diff --git a/bitchat/Localizable.xcstrings b/bitchat/Localizable.xcstrings index 601d5b6a..2eef51e5 100644 --- a/bitchat/Localizable.xcstrings +++ b/bitchat/Localizable.xcstrings @@ -32544,181 +32544,181 @@ "ar" : { "stringUnit" : { "state" : "translated", - "value" : "يُبث أثناء التحدث؛ الصوت المباشر الوارد يُشغَّل تلقائيًا" + "value" : "متوقف افتراضيًا. عند تفعيله، يُبث صوتك إلى الآخرين أثناء كلامك — قبل أن ترفع إصبعك — ويُشغَّل الصوت المباشر الوارد بصوت مسموع تلقائيًا." } }, "bn" : { "stringUnit" : { "state" : "translated", - "value" : "কথা বলার সাথে সাথে স্ট্রিম হয়; আগত লাইভ ভয়েস স্বয়ংক্রিয়ভাবে চলে" + "value" : "ডিফল্টভাবে বন্ধ। চালু থাকলে তোমার কণ্ঠ কথা বলার সঙ্গে সঙ্গেই অন্যদের কাছে স্ট্রিম হয় — বোতাম ছাড়ার আগেই — আর আসা লাইভ ভয়েস স্বয়ংক্রিয়ভাবে জোরে বাজে।" } }, "de" : { "stringUnit" : { "state" : "translated", - "value" : "überträgt live beim sprechen; eingehende live-stimme wird automatisch abgespielt" + "value" : "standardmäßig aus. wenn aktiviert, wird deine stimme schon beim sprechen an andere gestreamt — noch bevor du loslässt — und eingehende live-stimmen werden automatisch laut abgespielt." } }, "en" : { "stringUnit" : { "state" : "translated", - "value" : "streams as you speak; incoming live voice plays automatically" + "value" : "off by default. when on, your voice streams to people as you speak — before you release — and incoming live voice plays out loud automatically." } }, "es" : { "stringUnit" : { "state" : "translated", - "value" : "transmite mientras hablas; la voz en vivo entrante se reproduce automáticamente" + "value" : "desactivado por defecto. si lo activas, tu voz se transmite a la gente mientras hablas — antes de soltar — y la voz en directo entrante se reproduce en voz alta automáticamente." } }, "fa" : { "stringUnit" : { "state" : "translated", - "value" : "همان‌طور که حرف می‌زنی پخش می‌شود؛ صدای زندهٔ دریافتی خودکار پخش می‌شود" + "value" : "به‌طور پیش‌فرض خاموش است. وقتی روشن باشد، صدایت همان لحظه که حرف می‌زنی — پیش از رها کردن — برای دیگران پخش می‌شود و صدای زنده‌ی دریافتی هم به‌طور خودکار با صدای بلند پخش می‌شود." } }, "fil" : { "stringUnit" : { "state" : "translated", - "value" : "nag-i-stream habang nagsasalita ka; awtomatikong tumutugtog ang papasok na live na boses" + "value" : "naka-off bilang default. kapag naka-on, naist-stream ang boses mo sa iba habang nagsasalita ka — bago mo pa bitawan — at awtomatikong tumutugtog nang malakas ang papasok na live na boses." } }, "fr" : { "stringUnit" : { "state" : "translated", - "value" : "diffuse pendant que vous parlez ; la voix en direct entrante est lue automatiquement" + "value" : "désactivé par défaut. une fois activé, ta voix est diffusée aux autres pendant que tu parles — avant même de relâcher — et la voix en direct reçue est lue à voix haute automatiquement." } }, "he" : { "stringUnit" : { "state" : "translated", - "value" : "משדר בזמן שאתה מדבר; קול חי נכנס מושמע אוטומטית" + "value" : "כבוי כברירת מחדל. כשהוא פועל, הקול שלך משודר לאחרים תוך כדי דיבור — עוד לפני שחרור הכפתור — וקול חי נכנס מושמע בקול רם אוטומטית." } }, "hi" : { "stringUnit" : { "state" : "translated", - "value" : "बोलते समय स्ट्रीम होता है; आने वाली लाइव आवाज़ अपने आप चलती है" + "value" : "डिफ़ॉल्ट रूप से बंद। चालू होने पर तुम्हारी आवाज़ बोलते-बोलते ही लोगों तक स्ट्रीम होती है — बटन छोड़ने से पहले ही — और आने वाली लाइव आवाज़ अपने आप ज़ोर से बजती है।" } }, "id" : { "stringUnit" : { "state" : "translated", - "value" : "streaming saat Anda berbicara; suara langsung yang masuk diputar otomatis" + "value" : "nonaktif secara default. saat aktif, suaramu langsung dialirkan ke orang lain saat kamu bicara — sebelum tombol dilepas — dan suara langsung yang masuk otomatis diputar dengan keras." } }, "it" : { "stringUnit" : { "state" : "translated", - "value" : "trasmette mentre parli; la voce in diretta in arrivo viene riprodotta automaticamente" + "value" : "disattivato per impostazione predefinita. quando è attivo, la tua voce viene trasmessa agli altri mentre parli — prima ancora di rilasciare — e la voce dal vivo in arrivo viene riprodotta ad alta voce automaticamente." } }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "話しながらライブ配信。受信したライブ音声は自動再生されます" + "value" : "デフォルトはオフ。オンにすると、ボタンを離す前から話している声がそのまま相手に配信され、受信したライブ音声は自動的にスピーカーで再生されます。" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "말하는 동안 실시간 전송됩니다. 수신된 라이브 음성은 자동 재생됩니다" + "value" : "기본은 꺼짐. 켜면 버튼에서 손을 떼기 전부터 말하는 동안 목소리가 상대에게 실시간으로 전송되고, 수신된 라이브 음성은 자동으로 소리 내어 재생돼요." } }, "ms" : { "stringUnit" : { "state" : "translated", - "value" : "strim semasa anda bercakap; suara langsung masuk dimainkan secara automatik" + "value" : "dimatikan secara lalai. apabila dihidupkan, suara kamu distrim kepada orang lain semasa kamu bercakap — sebelum kamu lepaskan — dan suara langsung yang masuk dimainkan dengan kuat secara automatik." } }, "ne" : { "stringUnit" : { "state" : "translated", - "value" : "बोल्दै गर्दा स्ट्रिम हुन्छ; आगमन लाइभ आवाज स्वतः बज्छ" + "value" : "पूर्वनिर्धारित रूपमा बन्द। खुला हुँदा तिम्रो आवाज बोल्दै गर्दा नै — बटन छोड्नुअघि नै — अरूसम्म स्ट्रिम हुन्छ, र आएको लाइभ आवाज आफैँ ठूलो स्वरमा बज्छ।" } }, "nl" : { "stringUnit" : { "state" : "translated", - "value" : "streamt terwijl je praat; inkomende live spraak wordt automatisch afgespeeld" + "value" : "standaard uit. indien aan wordt je stem al tijdens het praten naar anderen gestreamd — nog vóór je loslaat — en binnenkomende live spraak wordt automatisch hardop afgespeeld." } }, "pl" : { "stringUnit" : { "state" : "translated", - "value" : "przesyła na żywo podczas mówienia; przychodzący głos na żywo odtwarza się automatycznie" + "value" : "domyślnie wyłączone. po włączeniu twój głos jest przesyłany innym już w trakcie mówienia — zanim puścisz przycisk — a przychodzący głos na żywo jest automatycznie odtwarzany na głos." } }, "pt" : { "stringUnit" : { "state" : "translated", - "value" : "transmite enquanto fala; a voz ao vivo recebida é reproduzida automaticamente" + "value" : "desligado por predefinição. quando ativado, a tua voz é transmitida às outras pessoas enquanto falas — antes de soltares — e a voz em direto recebida é reproduzida em voz alta automaticamente." } }, "pt-BR" : { "stringUnit" : { "state" : "translated", - "value" : "transmite enquanto você fala; a voz ao vivo recebida toca automaticamente" + "value" : "desativado por padrão. quando ativado, sua voz é transmitida às pessoas enquanto você fala — antes de soltar — e a voz ao vivo recebida toca em voz alta automaticamente." } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "передаёт, пока вы говорите; входящий живой голос воспроизводится автоматически" + "value" : "по умолчанию выключено. когда включено, твой голос передаётся другим прямо во время разговора — ещё до того, как ты отпустишь кнопку, — а входящий живой голос автоматически проигрывается вслух." } }, "sv" : { "stringUnit" : { "state" : "translated", - "value" : "strömmar medan du pratar; inkommande live-röst spelas upp automatiskt" + "value" : "av som standard. när det är på strömmas din röst till andra medan du pratar — innan du släpper — och inkommande live-röst spelas automatiskt upp högt." } }, "ta" : { "stringUnit" : { "state" : "translated", - "value" : "நீங்கள் பேசும்போதே நேரலையாக அனுப்பப்படும்; உள்வரும் நேரலை குரல் தானாக ஒலிக்கும்" + "value" : "இயல்பாக முடக்கப்பட்டுள்ளது. இயக்கினால், நீ பேசும்போதே — பொத்தானை விடுவதற்கு முன்பே — உன் குரல் மற்றவர்களுக்கு ஸ்ட்ரீம் ஆகும்; வரும் நேரடி குரல் தானாக சத்தமாக ஒலிக்கும்." } }, "th" : { "stringUnit" : { "state" : "translated", - "value" : "สตรีมขณะพูด เสียงสดขาเข้าจะเล่นอัตโนมัติ" + "value" : "ปิดไว้เป็นค่าเริ่มต้น เมื่อเปิด เสียงของคุณจะสตรีมถึงคนอื่นระหว่างที่พูด — ก่อนปล่อยปุ่ม — และเสียงสดที่เข้ามาจะเล่นออกลำโพงโดยอัตโนมัติ" } }, "tr" : { "stringUnit" : { "state" : "translated", - "value" : "siz konuşurken canlı iletilir; gelen canlı ses otomatik çalınır" + "value" : "varsayılan olarak kapalı. açıkken sesin, sen konuşurken — daha bırakmadan — başkalarına aktarılır ve gelen canlı ses otomatik olarak sesli çalınır." } }, "uk" : { "stringUnit" : { "state" : "translated", - "value" : "передає, поки ви говорите; вхідний живий голос відтворюється автоматично" + "value" : "типово вимкнено. коли ввімкнено, твій голос транслюється іншим просто під час розмови — ще до того, як ти відпустиш кнопку, — а вхідний живий голос автоматично відтворюється вголос." } }, "ur" : { "stringUnit" : { "state" : "translated", - "value" : "بولتے وقت لائیو نشر ہوتا ہے؛ موصول ہونے والی لائیو آواز خود بخود چلتی ہے" + "value" : "طے شدہ طور پر بند۔ آن ہونے پر تمہاری آواز بولتے ہی — بٹن چھوڑنے سے پہلے — لوگوں تک اسٹریم ہوتی ہے، اور آنے والی لائیو آواز خودبخود بلند آواز میں چلتی ہے۔" } }, "vi" : { "stringUnit" : { "state" : "translated", - "value" : "phát trực tiếp khi bạn nói; giọng nói trực tiếp đến sẽ tự phát" + "value" : "mặc định tắt. khi bật, giọng của bạn được truyền trực tiếp tới mọi người ngay lúc bạn nói — trước cả khi thả tay — và giọng nói trực tiếp nhận được sẽ tự động phát ra loa." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "边说边实时传输;收到的实时语音会自动播放" + "value" : "默认关闭。开启后,你说话的同时——还没松开按钮——声音就会实时传给对方,收到的实时语音也会自动外放播放。" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "邊說邊即時傳輸;收到的即時語音會自動播放" + "value" : "預設關閉。開啟後,你說話的同時——還沒放開按鈕——聲音就會即時傳給對方,收到的即時語音也會自動以擴音播放。" } } } diff --git a/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift b/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift index 78fa83e1..acc4a298 100644 --- a/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift +++ b/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift @@ -79,6 +79,11 @@ enum VoiceBurstScope: Hashable { /// bubble so nobody sees a duplicate. @MainActor final class ChatLiveVoiceCoordinator { + /// Injectable so tests exercise the live path without racing other + /// suites through the shared UserDefaults-backed preference (which now + /// defaults OFF). + var liveVoiceEnabled: () -> Bool = { PTTSettings.liveVoiceEnabled } + /// Burst IDs are sender-chosen, so they only identify a burst *within* /// an authenticated (peer, scope) pair: keying assemblies by the full /// triple stops an attacker who observed a public burst ID from racing @@ -187,7 +192,7 @@ final class ChatLiveVoiceCoordinator { // Live voice off means classic-notes-only in both directions: no live // bubble, no partial file, no early notification — the finalized // voice note still arrives through the normal pipeline. - guard PTTSettings.liveVoiceEnabled else { + guard liveVoiceEnabled() else { SecureLogger.debug("PTT: dropping inbound voice frame — live voice is toggled off", category: .session) return } @@ -403,7 +408,7 @@ final class ChatLiveVoiceCoordinator { case .directMessage: context.selectedPrivateChatPeer == peerID case .publicMesh: context.isViewingPublicMeshTimeline } - if PTTSettings.liveVoiceEnabled, PTTSettings.isAppActive, isViewing { + if liveVoiceEnabled(), PTTSettings.isAppActive, isViewing { assembly.player = PTTBurstPlayer() } diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index 36742d29..59d6480b 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -1652,6 +1652,9 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // A hand-added relay names an operator someone chose to route through, // which is the kind of trace a wipe should not leave behind. NostrRelaySettings.reset() + // Live voice streams before release and plays strangers out loud, so a + // wiped device comes back with it off, like a fresh install. + PTTSettings.reset() // Drop private group keys and rosters (keychain + disk) groupStore.wipe() diff --git a/bitchat/ViewModels/Extensions/ChatViewModel+PrivateChat.swift b/bitchat/ViewModels/Extensions/ChatViewModel+PrivateChat.swift index 9dad8030..49646d10 100644 --- a/bitchat/ViewModels/Extensions/ChatViewModel+PrivateChat.swift +++ b/bitchat/ViewModels/Extensions/ChatViewModel+PrivateChat.swift @@ -69,7 +69,7 @@ extension ChatViewModel { @MainActor private func liveVoiceTarget() -> LiveVoiceTarget? { - guard PTTSettings.liveVoiceEnabled else { return nil } + guard liveVoiceCoordinator.liveVoiceEnabled() else { return nil } if let selectedPeer = selectedPrivateChatPeer { guard !selectedPeer.isGeoDM, !selectedPeer.isGeoChat, !selectedPeer.isGroup else { return nil } @@ -110,7 +110,7 @@ extension ChatViewModel { voiceTransport?.sendVoiceFrameBroadcast(packet) }) case nil: - SecureLogger.info("PTT: hold uses classic voice note (liveVoiceEnabled=\(PTTSettings.liveVoiceEnabled), dmSelected=\(selectedPrivateChatPeer != nil))", category: .session) + SecureLogger.info("PTT: hold uses classic voice note (liveVoiceEnabled=\(liveVoiceCoordinator.liveVoiceEnabled()), dmSelected=\(selectedPrivateChatPeer != nil))", category: .session) return VoiceNoteCaptureSession() } } diff --git a/bitchatTests/ChatLiveVoiceCoordinatorTests.swift b/bitchatTests/ChatLiveVoiceCoordinatorTests.swift index 2e5ca317..b4fbe210 100644 --- a/bitchatTests/ChatLiveVoiceCoordinatorTests.swift +++ b/bitchatTests/ChatLiveVoiceCoordinatorTests.swift @@ -127,6 +127,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func burstCreatesBubbleAndPersistsFramesInOrder() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0xA1) defer { fallbackFileURL(burstID: burstID, peerID: peer).map { try? FileManager.default.removeItem(at: $0) } } @@ -168,6 +169,7 @@ struct ChatLiveVoiceCoordinatorTests { let context = MockChatLiveVoiceContext() context.selectedPrivateChatPeer = peer let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0xB2) let hex = burstID.hexEncodedString() let fileName = "voice_\(hex).m4a" @@ -223,6 +225,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func absorbIgnoresUnrelatedVoiceNotes() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } // A classic voice note (date-stamped name) and a live-capture name // must both pass through untouched. @@ -247,6 +250,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func canceledBurstRemovesBubbleAndFile() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0xC3) send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([Data(repeating: 9, count: 40)]))), to: coordinator, from: peer) @@ -262,6 +266,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func emptyBurstLeavesNoBubble() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0xD4) send(try #require(VoiceBurstPacket(burstID: burstID, seq: 0, kind: .start(codec: .aacLC16kMono))), to: coordinator, from: peer) @@ -275,6 +280,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func ignoresBlockedPeersAndUnknownControlPackets() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } context.blockedPeers = [peer] send(try #require(VoiceBurstPacket(burstID: makeBurstID(0xE5), seq: 0, kind: .start(codec: .aacLC16kMono))), to: coordinator, from: peer) @@ -290,6 +296,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func concurrentAssemblyCapDropsExtraBursts() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } var cleanup: [Data] = [] defer { @@ -309,12 +316,9 @@ struct ChatLiveVoiceCoordinatorTests { } @Test func liveVoiceToggleOffDropsInboundFrames() throws { - let previous = PTTSettings.liveVoiceEnabled - PTTSettings.liveVoiceEnabled = false - defer { PTTSettings.liveVoiceEnabled = previous } - let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { false } let burstID = makeBurstID(0xE8) // Off means classic-notes-only: no live bubble, no partial file. @@ -328,6 +332,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func publicBurstCreatesMeshBubbleAndTracksTalker() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0x71) defer { incomingFileURL(burstID: burstID, peerID: peer, scope: .publicMesh).map { try? FileManager.default.removeItem(at: $0) } @@ -369,6 +374,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func absorbEnforcesScopeBinding() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0x72) defer { fallbackFileURL(burstID: burstID, peerID: peer).map { try? FileManager.default.removeItem(at: $0) } } @@ -400,6 +406,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func collidingBurstIDFromAnotherPeerCannotHijackAssembly() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0x73) let attacker = PeerID(str: "ddddeeeeffff0002") defer { @@ -435,6 +442,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func sameBurstIDCoexistsAcrossScopes() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0x74) defer { fallbackFileURL(burstID: burstID, peerID: peer).map { try? FileManager.default.removeItem(at: $0) } @@ -492,6 +500,7 @@ struct ChatLiveVoiceCoordinatorTests { @Test func finalizedNoteBindsToItsAuthenticatedSender() throws { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0x75) let hex = burstID.hexEncodedString() let attacker = PeerID(str: "ddddeeeeffff0002") @@ -550,6 +559,7 @@ struct ChatLiveVoiceCoordinatorTests { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, fileStore: store) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0x76) send(try #require(VoiceBurstPacket(burstID: burstID, seq: 0, kind: .start(codec: .aacLC16kMono))), to: coordinator, from: peer) @@ -571,6 +581,7 @@ struct ChatLiveVoiceCoordinatorTests { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, fileStore: store) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0x77) send(try #require(VoiceBurstPacket(burstID: burstID, seq: 0, kind: .start(codec: .aacLC16kMono))), to: coordinator, from: peer) send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([Data(repeating: 8, count: 60)]))), to: coordinator, from: peer) @@ -618,6 +629,7 @@ struct ChatLiveVoiceCoordinatorTests { // sender out of range): the capture is the row's only audio. let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, fileStore: store) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0x79) let frame = Data(repeating: 0x0B, count: 60) send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([frame]))), to: coordinator, from: peer) @@ -642,6 +654,7 @@ struct ChatLiveVoiceCoordinatorTests { let context = MockChatLiveVoiceContext() let coordinator = ChatLiveVoiceCoordinator(context: context, fileStore: store) + coordinator.liveVoiceEnabled = { true } let burstID = makeBurstID(0x7A) send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([Data(repeating: 0x0C, count: 60)]))), to: coordinator, from: peer) send(try #require(VoiceBurstPacket(burstID: burstID, seq: 2, kind: .end(totalDataPackets: 1, durationMs: 64))), to: coordinator, from: peer) diff --git a/bitchatTests/ChatViewModelTests.swift b/bitchatTests/ChatViewModelTests.swift index 9306c606..9bdf87ce 100644 --- a/bitchatTests/ChatViewModelTests.swift +++ b/bitchatTests/ChatViewModelTests.swift @@ -1608,6 +1608,8 @@ struct ChatViewModelPrivateMediaDeletionTests { kind: .canceled )) let coordinator = viewModel.liveVoiceCoordinator + // Live voice defaults off; this fixture exercises the opted-in path. + coordinator.liveVoiceEnabled = { true } defer { coordinator.handleVoiceFramePayload( from: peerID, @@ -2150,6 +2152,27 @@ struct ChatViewModelPrivateMediaDeletionTests { struct ChatViewModelPanicTests { + @Test @MainActor + func panicClearAllData_turnsLiveVoiceBackOff() { + let defaults = UserDefaults.standard + let previous = defaults.object(forKey: PTTSettings.liveVoiceEnabledKey) + defer { + if let previous { + defaults.set(previous, forKey: PTTSettings.liveVoiceEnabledKey) + } else { + defaults.removeObject(forKey: PTTSettings.liveVoiceEnabledKey) + } + } + PTTSettings.liveVoiceEnabled = true + let (viewModel, _) = makeTestableViewModel() + + viewModel.panicClearAllData() + + // A wiped device comes back like a fresh install: not streaming holds + // and not auto-playing strangers. + #expect(!PTTSettings.liveVoiceEnabled) + } + @Test @MainActor func panicClearAllData_finishesMediaWipeBeforeReturning() { var wipeFinished = false @@ -2411,3 +2434,30 @@ struct ChatViewModelLifecycleTests { #expect(transport.startServicesCallCount == 1) } } + +// MARK: - Live Voice Gate Tests + +struct ChatViewModelLiveVoiceGateTests { + + @Test @MainActor + func holdOnPublicMesh_recordsAClassicNoteWhileLiveVoiceIsOff() { + let (viewModel, _) = makeTestableViewModel() + viewModel.activeChannel = .mesh + viewModel.liveVoiceCoordinator.liveVoiceEnabled = { false } + + // Off means nothing leaves the device before release: the hold records + // a classic voice note that sends only once it is finished. + #expect(!viewModel.makeVoiceCaptureSession().isLive) + } + + @Test @MainActor + func holdOnPublicMesh_streamsLiveOnlyAfterOptingIn() { + let (viewModel, _) = makeTestableViewModel() + viewModel.activeChannel = .mesh + viewModel.liveVoiceCoordinator.liveVoiceEnabled = { true } + + // The same hold goes live once the switch is on, so the test above + // fails if the gate is removed instead of passing vacuously. + #expect(viewModel.makeVoiceCaptureSession().isLive) + } +} diff --git a/bitchatTests/PTTSettingsTests.swift b/bitchatTests/PTTSettingsTests.swift new file mode 100644 index 00000000..32bd8321 --- /dev/null +++ b/bitchatTests/PTTSettingsTests.swift @@ -0,0 +1,46 @@ +// +// PTTSettingsTests.swift +// bitchatTests +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import Foundation +import Testing +@testable import bitchat + +/// Live push-to-talk streams a hold to other people before it is released and +/// plays strangers' voices out loud, so it must be something people opt into. +/// The preference is injected rather than read from shared preferences, so +/// these run in parallel with suites that use the default store. +struct PTTSettingsTests { + + private func isolatedDefaults() -> UserDefaults { + UserDefaults(suiteName: "bitchat.tests.ptt.\(UUID().uuidString)")! + } + + @Test func liveVoiceIsOffByDefault() { + // A fresh install must not stream holds or auto-play inbound bursts. + #expect(!PTTSettings.liveVoiceEnabled(in: isolatedDefaults())) + } + + @Test func theSettingRoundTrips() { + let defaults = isolatedDefaults() + + PTTSettings.setLiveVoiceEnabled(true, in: defaults) + #expect(PTTSettings.liveVoiceEnabled(in: defaults)) + + PTTSettings.setLiveVoiceEnabled(false, in: defaults) + #expect(!PTTSettings.liveVoiceEnabled(in: defaults)) + } + + @Test func panicResetRestoresTheOffDefault() { + let defaults = isolatedDefaults() + PTTSettings.setLiveVoiceEnabled(true, in: defaults) + + // Panic wipe restores the safe default rather than the last choice. + PTTSettings.reset(in: defaults) + #expect(!PTTSettings.liveVoiceEnabled(in: defaults)) + } +}