Compare commits

..
Author SHA1 Message Date
jack 06791ce218 Peer icons: faster, accurate reachability\n\n- Run connectivity checks every maintenance tick (5s)\n- Publish peer snapshots on central unsubscribe for instant UI refresh\n- Lower inactivity timeout to 8s and disconnect debounce to 0.9s\n- Gate reachability on mesh-attached (>=1 direct link); no links => no reachable peers\n- Keep 21s retention for verified/unverified, but only when attached to mesh\n\nImproves list responsiveness when walking out of range and prevents stale 'reachable' states when isolated. 2025-08-26 17:27:19 +02:00
jack 95af23a8f6 Logs/robustness: debounce disconnect notifications (1.5s), debounce 'reconnected' logs (2s), add weak-link cooldown after timeouts on very weak RSSI (<= -90) 2025-08-26 13:38:15 +02:00
jack b919b3ff0a UI: unread envelope uses orange; hasUnreadMessages checks Nostr conv key for peers with known Nostr pubkeys (geohash DM consistency) 2025-08-26 13:21:13 +02:00
jack ae2b247834 Peer list: real-time icon updates by publishing snapshots on connectivity checks; add unread message indicator (envelope) next to peers with unread DMs 2025-08-26 13:15:22 +02:00
jack c6ed3cd665 Announces: TTL 7 (sparse only) via RelayController; no fanout subset for announces; neighbor-change rebroadcast of last 2–3 announces. Fragments: faster pacing (5ms global, 4ms directed). 2025-08-26 13:03:47 +02:00
jack 08eceab7cd Fix warnings: remove unused msgID and unused mutable var in directed spool flush 2025-08-26 12:46:07 +02:00
jack 11950a7fe4 Range/robustness: store-and-forward for directed packets (15s) with flush on new links + periodic; announces: no subset + afterglow re-announce on first-seen; adaptive scanning: force ON when <=2 neighbors or recent traffic 2025-08-26 12:43:04 +02:00
jack 86bdb1af27 Relay: increase broadcast TTL cap in sparse graphs to 6; tighten jitter for handshake (10–35ms) and directed (20–60ms) relays 2025-08-26 12:17:23 +02:00
jack 744e87f924 Announce cadence: faster discovery (4s), sparse 15±4s, dense 30±8s; initial 0.6s; post-subscribe 50ms; min-force 150ms; maintenance 5s; proactive announces on handshake + recent-traffic nudge 2025-08-26 12:09:54 +02:00
jack 0d1450df4d Verification sheet: compute encryption status and fingerprint using short mesh ID mapping (fix 'not encrypted/handshake' for DMs with stable key) 2025-08-26 12:01:01 +02:00
jack 89175e2065 mesh DMs/acks: route to reachable peers; queue READ/DELIVERED until handshake; add Transport.isPeerReachable; UI: hide offline non-mutuals; DM header: better name fallback + show transport + encryption icons; fix NostrTransport conformance 2025-08-26 11:58:41 +02:00
jack bc383cb02f Reachability: reduce retention to 21s for all peers (verified and unverified) to minimize stale presence 2025-08-26 10:53:27 +02:00
jack 1913719662 UI: switch to 'point.3.filled.connected.trianglepath.dotted' for mesh-reachable icons in list and header 2025-08-26 02:40:40 +02:00
jack fc690fc0ac UI: use 'point.3.connected.trianglepath.dotted' for mesh-reachable; change people count to include connected+reachable (exclude Nostr-only) 2025-08-26 02:39:16 +02:00
jack 35e4ad8914 Fix syntax error: remove stray else/log inserted into writeOrEnqueue; keep logs clean 2025-08-26 02:28:21 +02:00
jack f251c5333c Logs: tag relayed announces as 'Reachable via mesh' and annotate public message logs with (direct|mesh) path for easier field analysis 2025-08-26 02:26:15 +02:00
jack 92a0204368 ContentView: handle new .meshReachable connection state in header icon switch (exhaustive switch fix) 2025-08-26 02:13:33 +02:00
jack acfce858ec Add connected vs reachable model: retain peers after link drop, expire after reachability window; expose all peers in snapshots; compute isReachable in UI; add meshReachable state and sorting; avoid removing peers on link events; notify UI on stale removals 2025-08-26 02:11:30 +02:00
jack dc9b9e996d Sign public broadcasts; verify relayed messages via persisted signing keys; keep scheduled relays in sparse graphs and speed their jitter; persist announce signing key for offline auth; add short backoff after disconnect errors to reduce reconnect thrash 2025-08-26 01:52:34 +02:00
8 changed files with 109 additions and 630 deletions
+16 -66
View File
@@ -2,7 +2,7 @@
## bitchat ## bitchat
A decentralized peer-to-peer messaging app with dual transport architecture: local Bluetooth mesh networks for offline communication and internet-based Nostr protocol for global reach. No accounts, no phone numbers, no central servers. It's the side-groupchat. A decentralized peer-to-peer messaging app that works over Bluetooth mesh networks. No internet required, no servers, no phone numbers. It's the side-groupchat.
[bitchat.free](http://bitchat.free) [bitchat.free](http://bitchat.free)
@@ -11,99 +11,50 @@ A decentralized peer-to-peer messaging app with dual transport architecture: loc
> [!WARNING] > [!WARNING]
> Private messages have not received external security review and may contain vulnerabilities. Do not use for sensitive use cases, and do not rely on its security until it has been reviewed. Now uses the [Noise Protocol](http://www.noiseprotocol.org) for identity and encryption. Public local chat (the main feature) has no security concerns. > Private messages have not received external security review and may contain vulnerabilities. Do not use for sensitive use cases, and do not rely on its security until it has been reviewed. Now uses the [Noise Protocol](http://www.noiseprotocol.org) for identity and encryption. Public local chat (the main feature) has no security concerns.
## License ## License
This project is released into the public domain. See the [LICENSE](LICENSE) file for details. This project is released into the public domain. See the [LICENSE](LICENSE) file for details.
## Features ## Features
- **Dual Transport Architecture**: Bluetooth mesh for offline + Nostr protocol for internet-based messaging
- **Location-Based Channels**: Geographic chat rooms using geohash coordinates over global Nostr relays
- **Intelligent Message Routing**: Automatically chooses best transport (Bluetooth → Nostr fallback)
- **Decentralized Mesh Network**: Automatic peer discovery and multi-hop message relay over Bluetooth LE - **Decentralized Mesh Network**: Automatic peer discovery and multi-hop message relay over Bluetooth LE
- **Privacy First**: No accounts, no phone numbers, no persistent identifiers - **Privacy First**: No accounts, no phone numbers, no persistent identifiers
- **Private Message End-to-End Encryption**: [Noise Protocol](http://noiseprotocol.org) for mesh, NIP-17 for Nostr - **Private Message End-to-End Encryption**: [Noise Protocol](http://noiseprotocol.org)
- **IRC-Style Commands**: Familiar `/slap`, `/msg`, `/who` style interface - **IRC-Style Commands**: Familiar `/slap`, `/msg`, `/who` style interface
- **Universal App**: Native support for iOS and macOS - **Universal App**: Native support for iOS and macOS
- **Emergency Wipe**: Triple-tap to instantly clear all data - **Emergency Wipe**: Triple-tap to instantly clear all data
- **Performance Optimizations**: LZ4 message compression, adaptive battery modes, and optimized networking - **Performance Optimizations**: LZ4 message compression, adaptive battery modes, and optimized networking
## [Technical Architecture](https://deepwiki.com/permissionlesstech/bitchat) ## [Technical Architecture](https://deepwiki.com/permissionlesstech/bitchat)
BitChat uses a **hybrid messaging architecture** with two complementary transport layers: ### Binary Protocol
bitchat uses an efficient binary protocol optimized for Bluetooth LE:
- Compact packet format with 1-byte type field
- TTL-based message routing (max 7 hops)
- Automatic fragmentation for large messages
- Message deduplication via unique IDs
### Bluetooth Mesh Network (Offline) ### Mesh Networking
- Each device acts as both client and peripheral
- **Local Communication**: Direct peer-to-peer within Bluetooth range - Automatic peer discovery and connection management
- **Multi-hop Relay**: Messages route through nearby devices (max 7 hops) - Adaptive duty cycling for battery optimization
- **No Internet Required**: Works completely offline in disaster scenarios
- **Noise Protocol Encryption**: End-to-end encryption with forward secrecy
- **Binary Protocol**: Compact packet format optimized for Bluetooth LE constraints
- **Automatic Discovery**: Peer discovery and connection management
- **Adaptive Power**: Battery-optimized duty cycling
### Nostr Protocol (Internet)
- **Global Reach**: Connect with users worldwide via internet relays
- **Location Channels**: Geographic chat rooms using geohash coordinates
- **290+ Relay Network**: Distributed across the globe for reliability
- **NIP-17 Encryption**: Gift-wrapped private messages for internet privacy
- **Ephemeral Keys**: Fresh cryptographic identity per geohash area
### Channel Types
#### `mesh #bluetooth`
- **Transport**: Bluetooth Low Energy mesh network
- **Scope**: Local devices within multi-hop range
- **Internet**: Not required
- **Use Case**: Offline communication, protests, disasters, remote areas
#### Location Channels (`block #dr5rsj7`, `neighborhood #dr5rs`, `country #dr`)
- **Transport**: Nostr protocol over internet
- **Scope**: Geographic areas defined by geohash precision
- `block` (7 chars): City block level
- `neighborhood` (6 chars): District/neighborhood
- `city` (5 chars): City level
- `province` (4 chars): State/province
- `region` (2 chars): Country/large region
- **Internet**: Required (connects to Nostr relays)
- **Use Case**: Location-based community chat, local events, regional discussions
### Direct Message Routing
Private messages use **intelligent transport selection**:
1. **Bluetooth First** (preferred when available)
- Direct connection with established Noise session
- Fastest and most private option
2. **Nostr Fallback** (when Bluetooth unavailable)
- Uses recipient's Nostr public key
- NIP-17 gift-wrapping for privacy
- Routes through global relay network
3. **Smart Queuing** (when neither available)
- Messages queued until transport becomes available
- Automatic delivery when connection established
For detailed protocol documentation, see the [Technical Whitepaper](WHITEPAPER.md). For detailed protocol documentation, see the [Technical Whitepaper](WHITEPAPER.md).
## Setup ## Setup
### Option 1: Using XcodeGen (Recommended) ### Option 1: Using XcodeGen (Recommended)
1. Install XcodeGen if you haven't already: 1. Install XcodeGen if you haven't already:
```bash ```bash
brew install xcodegen brew install xcodegen
``` ```
2. Generate the Xcode project: 2. Generate the Xcode project:
```bash ```bash
cd bitchat cd bitchat
xcodegen generate xcodegen generate
@@ -117,7 +68,6 @@ For detailed protocol documentation, see the [Technical Whitepaper](WHITEPAPER.m
### Option 2: Using Swift Package Manager ### Option 2: Using Swift Package Manager
1. Open the project in Xcode: 1. Open the project in Xcode:
```bash ```bash
cd bitchat cd bitchat
open Package.swift open Package.swift
-17
View File
@@ -173,14 +173,6 @@ class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
} }
} }
} }
// Handle deeplink (e.g., geohash activity)
if let deep = userInfo["deeplink"] as? String, let url = URL(string: deep) {
#if os(iOS)
DispatchQueue.main.async { UIApplication.shared.open(url) }
#else
DispatchQueue.main.async { NSWorkspace.shared.open(url) }
#endif
}
completionHandler() completionHandler()
} }
@@ -200,15 +192,6 @@ class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
} }
} }
} }
// Suppress geohash activity notification if we're already in that geohash channel
if identifier.hasPrefix("geo-activity-"),
let deep = userInfo["deeplink"] as? String,
let gh = deep.components(separatedBy: "/").last {
if case .location(let ch) = LocationChannelManager.shared.selectedChannel, ch.geohash == gh {
completionHandler([])
return
}
}
// Show notification in all other cases // Show notification in all other cases
completionHandler([.banner, .sound]) completionHandler([.banner, .sound])
+16 -55
View File
@@ -50,8 +50,10 @@ final class LocationChannelManager: NSObject, CLLocationManagerDelegate, Observa
let arr = try? JSONDecoder().decode([String].self, from: data) { let arr = try? JSONDecoder().decode([String].self, from: data) {
teleportedSet = Set(arr) teleportedSet = Set(arr)
} }
// Do not eagerly mark teleported on startup; wait for location to compute regional set. // Initialize teleported flag from persisted state if a location channel is selected
// This avoids showing teleported for in-region channels during cold start. if case .location(let ch) = selectedChannel {
teleported = teleportedSet.contains(ch.geohash)
}
let status: CLAuthorizationStatus let status: CLAuthorizationStatus
if #available(iOS 14.0, macOS 11.0, *) { if #available(iOS 14.0, macOS 11.0, *) {
status = cl.authorizationStatus status = cl.authorizationStatus
@@ -59,15 +61,6 @@ final class LocationChannelManager: NSObject, CLLocationManagerDelegate, Observa
status = CLLocationManager.authorizationStatus() status = CLLocationManager.authorizationStatus()
} }
updatePermissionState(from: status) updatePermissionState(from: status)
// If we don't have location authorization at startup, fall back to persisted teleport state
switch status {
case .authorizedAlways, .authorizedWhenInUse, .authorized:
break // will compute from location
default:
if case .location(let ch) = selectedChannel {
teleported = teleportedSet.contains(ch.geohash)
}
}
} }
// MARK: - Public API // MARK: - Public API
@@ -99,30 +92,23 @@ final class LocationChannelManager: NSObject, CLLocationManagerDelegate, Observa
} }
} }
/// Begin continuous, distance-filtered updates while the channel sheet is visible. /// Begin periodic one-shot location refreshes while a selector UI is visible.
/// Uses a 21m filter (configurable) to only refresh on meaningful movement.
func beginLiveRefresh(interval: TimeInterval = TransportConfig.locationLiveRefreshInterval) { func beginLiveRefresh(interval: TimeInterval = TransportConfig.locationLiveRefreshInterval) {
guard permissionState == .authorized else { return } guard permissionState == .authorized else { return }
// Stop any previous polling timer // Switch to a lightweight periodic one-shot request (polling) while the sheet is open
refreshTimer?.invalidate() refreshTimer?.invalidate()
refreshTimer = nil refreshTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
// Tighten accuracy and distance filter for live view self?.requestOneShotLocation()
cl.desiredAccuracy = kCLLocationAccuracyNearestTenMeters }
cl.distanceFilter = TransportConfig.locationDistanceFilterLiveMeters // Kick off immediately
// Start continuous updates
cl.startUpdatingLocation()
// Request an immediate fix to populate UI without waiting for movement
requestOneShotLocation() requestOneShotLocation()
} }
/// Stop continuous refreshes when selector UI is dismissed. /// Stop periodic refreshes when selector UI is dismissed.
func endLiveRefresh() { func endLiveRefresh() {
refreshTimer?.invalidate() refreshTimer?.invalidate()
refreshTimer = nil refreshTimer = nil
cl.stopUpdatingLocation() cl.stopUpdatingLocation()
// Restore more relaxed defaults for background/idle state
cl.desiredAccuracy = kCLLocationAccuracyHundredMeters
cl.distanceFilter = TransportConfig.locationDistanceFilterMeters
} }
func select(_ channel: ChannelID) { func select(_ channel: ChannelID) {
@@ -136,21 +122,7 @@ final class LocationChannelManager: NSObject, CLLocationManagerDelegate, Observa
case .mesh: case .mesh:
self.teleported = false self.teleported = false
case .location(let ch): case .location(let ch):
// If this geohash is in our current regional set, do NOT mark teleported. self.teleported = self.teleportedSet.contains(ch.geohash)
let inRegional = self.availableChannels.contains { $0.geohash == ch.geohash }
if inRegional {
self.teleported = false
// Clear persisted teleport for this geohash to keep future selections clean
if self.teleportedSet.contains(ch.geohash) {
self.teleportedSet.remove(ch.geohash)
if let data = try? JSONEncoder().encode(Array(self.teleportedSet)) {
UserDefaults.standard.set(data, forKey: self.teleportedStoreKey)
}
}
} else {
// Fall back to persisted mark (set by deep link or manual teleport)
self.teleported = self.teleportedSet.contains(ch.geohash)
}
} }
} }
} }
@@ -223,25 +195,14 @@ final class LocationChannelManager: NSObject, CLLocationManagerDelegate, Observa
} }
Task { @MainActor in Task { @MainActor in
self.availableChannels = result self.availableChannels = result
// Recompute teleported status based on whether the selected geohash is in our regional set // Recompute teleported status based on persisted state OR current location vs selected channel
switch self.selectedChannel { switch self.selectedChannel {
case .mesh: case .mesh:
self.teleported = false self.teleported = false
case .location(let ch): case .location(let ch):
// Membership check using freshly computed regional channels; avoids precision/rename drift let persisted = self.teleportedSet.contains(ch.geohash)
let inRegional = result.contains { $0.geohash == ch.geohash } let currentGH = Geohash.encode(latitude: coord.latitude, longitude: coord.longitude, precision: ch.level.precision)
if inRegional { self.teleported = persisted || (currentGH != ch.geohash)
self.teleported = false
// Clear persisted teleport flag if present
if self.teleportedSet.contains(ch.geohash) {
self.teleportedSet.remove(ch.geohash)
if let data = try? JSONEncoder().encode(Array(self.teleportedSet)) {
UserDefaults.standard.set(data, forKey: self.teleportedStoreKey)
}
}
} else {
self.teleported = true
}
} }
} }
} }
@@ -90,15 +90,6 @@ class NotificationService {
} }
} }
// Geohash public chat notification with deep link to a specific geohash
func sendGeohashActivityNotification(geohash: String, titlePrefix: String = "#", bodyPreview: String) {
let title = "\(titlePrefix)\(geohash)"
let identifier = "geo-activity-\(geohash)-\(Date().timeIntervalSince1970)"
let deeplink = "bitchat://geohash/\(geohash)"
let userInfo: [String: Any] = ["deeplink": deeplink]
sendLocalNotification(title: title, body: bodyPreview, identifier: identifier, userInfo: userInfo)
}
func sendNetworkAvailableNotification(peerCount: Int) { func sendNetworkAvailableNotification(peerCount: Int) {
let title = "👥 bitchatters nearby!" let title = "👥 bitchatters nearby!"
let body = peerCount == 1 ? "1 person around" : "\(peerCount) people around" let body = peerCount == 1 ? "1 person around" : "\(peerCount) people around"
-10
View File
@@ -100,14 +100,8 @@ enum TransportConfig {
// Location // Location
static let locationDistanceFilterMeters: Double = 1000 static let locationDistanceFilterMeters: Double = 1000
// Live (channel sheet open) distance threshold for meaningful updates
static let locationDistanceFilterLiveMeters: Double = 21.0
static let locationLiveRefreshInterval: TimeInterval = 5.0 static let locationLiveRefreshInterval: TimeInterval = 5.0
// Notifications (geohash)
static let uiGeoNotifyCooldownSeconds: TimeInterval = 60.0
static let uiGeoNotifySnippetMaxLen: Int = 80
// Nostr geohash // Nostr geohash
static let nostrGeohashInitialLookbackSeconds: TimeInterval = 3600 static let nostrGeohashInitialLookbackSeconds: TimeInterval = 3600
static let nostrGeohashInitialLimit: Int = 200 static let nostrGeohashInitialLimit: Int = 200
@@ -175,10 +169,6 @@ enum TransportConfig {
// UI color tuning // UI color tuning
static let uiColorHueAvoidanceDelta: Double = 0.05 static let uiColorHueAvoidanceDelta: Double = 0.05
static let uiColorHueOffset: Double = 0.12 static let uiColorHueOffset: Double = 0.12
// Peer list palette
static let uiPeerPaletteSlots: Int = 36
static let uiPeerPaletteRingBrightnessDeltaLight: Double = 0.07
static let uiPeerPaletteRingBrightnessDeltaDark: Double = -0.07
// UI windowing (infinite scroll) // UI windowing (infinite scroll)
static let uiWindowInitialCountPublic: Int = 300 static let uiWindowInitialCountPublic: Int = 300
+64 -460
View File
@@ -402,7 +402,6 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
@Published private(set) var teleportedGeo: Set<String> = [] // lowercased pubkey hex @Published private(set) var teleportedGeo: Set<String> = [] // lowercased pubkey hex
// Sampling subscriptions for multiple geohashes (when channel sheet is open) // Sampling subscriptions for multiple geohashes (when channel sheet is open)
private var geoSamplingSubs: [String: String] = [:] // subID -> geohash private var geoSamplingSubs: [String: String] = [:] // subID -> geohash
private var lastGeoNotificationAt: [String: Date] = [:] // geohash -> last notify time
// MARK: - Message Delivery Tracking // MARK: - Message Delivery Tracking
@@ -611,50 +610,6 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
self.switchLocationChannel(to: LocationChannelManager.shared.selectedChannel) self.switchLocationChannel(to: LocationChannelManager.shared.selectedChannel)
} }
// Background: keep sampling nearby geohashes for notifications even when sheet is closed
LocationChannelManager.shared.$availableChannels
.receive(on: DispatchQueue.main)
.sink { [weak self] channels in
guard let self = self else { return }
let ghs = channels.map { $0.geohash }
Task { @MainActor in
self.beginGeohashSampling(for: ghs)
}
}
.store(in: &cancellables)
// Kick off initial sampling if we already have channels
if !LocationChannelManager.shared.availableChannels.isEmpty {
let ghs = LocationChannelManager.shared.availableChannels.map { $0.geohash }
Task { @MainActor in self.beginGeohashSampling(for: ghs) }
}
// Refresh channels once when authorized to seed sampling
LocationChannelManager.shared.$permissionState
.receive(on: DispatchQueue.main)
.sink { state in
if state == .authorized { LocationChannelManager.shared.refreshChannels() }
}
.store(in: &cancellables)
// Track teleport flag changes to keep our own teleported marker in sync with regional status
LocationChannelManager.shared.$teleported
.receive(on: DispatchQueue.main)
.sink { [weak self] isTeleported in
guard let self = self else { return }
Task { @MainActor in
guard case .location(let ch) = self.activeChannel,
let id = try? NostrIdentityBridge.deriveIdentity(forGeohash: ch.geohash) else { return }
let key = id.publicKeyHex.lowercased()
let hasRegional = !LocationChannelManager.shared.availableChannels.isEmpty
let inRegional = LocationChannelManager.shared.availableChannels.contains { $0.geohash == ch.geohash }
if isTeleported && hasRegional && !inRegional {
self.teleportedGeo = self.teleportedGeo.union([key])
} else {
self.teleportedGeo.remove(key)
}
}
}
.store(in: &cancellables)
// Request notification permission // Request notification permission
NotificationService.shared.requestAuthorization() NotificationService.shared.requestAuthorization()
@@ -792,19 +747,10 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
}) })
if hasTeleportTag { if hasTeleportTag {
let key = event.pubkey.lowercased() let key = event.pubkey.lowercased()
// Do not mark our own key from historical events; rely on manager.teleported for self Task { @MainActor in self.teleportedGeo = self.teleportedGeo.union([key]) }
let isSelf: Bool = {
if let gh = self.currentGeohash, let my = try? NostrIdentityBridge.deriveIdentity(forGeohash: gh) {
return my.publicKeyHex.lowercased() == key
}
return false
}()
if !isSelf {
Task { @MainActor in self.teleportedGeo = self.teleportedGeo.union([key]) }
}
} }
let senderName = self.displayNameForNostrPubkey(event.pubkey) let senderName = self.displayNameForNostrPubkey(event.pubkey)
let content = event.content.trimmingCharacters(in: .whitespacesAndNewlines) let content = event.content
let timestamp = Date(timeIntervalSince1970: TimeInterval(event.created_at)) let timestamp = Date(timeIntervalSince1970: TimeInterval(event.created_at))
let mentions = self.parseMentions(from: content) let mentions = self.parseMentions(from: content)
let msg = BitchatMessage( let msg = BitchatMessage(
@@ -1246,9 +1192,7 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
/// Routes to private chat if one is selected, otherwise broadcasts /// Routes to private chat if one is selected, otherwise broadcasts
@MainActor @MainActor
func sendMessage(_ content: String) { func sendMessage(_ content: String) {
// Ignore messages that are empty or whitespace-only to prevent blank lines guard !content.isEmpty else { return }
let trimmed = content.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
// Check for commands // Check for commands
if content.hasPrefix("/") { if content.hasPrefix("/") {
@@ -1268,7 +1212,7 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
} else { } else {
} }
} else { } else {
// Parse mentions from the content (use original content for user intent) // Parse mentions from the content
let mentions = parseMentions(from: content) let mentions = parseMentions(from: content)
// Add message to local display // Add message to local display
@@ -1283,7 +1227,7 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
let message = BitchatMessage( let message = BitchatMessage(
sender: displaySender, sender: displaySender,
content: trimmed, content: content,
timestamp: Date(), timestamp: Date(),
isRelay: false, isRelay: false,
originalSender: nil, originalSender: nil,
@@ -1328,7 +1272,7 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
do { do {
let identity = try NostrIdentityBridge.deriveIdentity(forGeohash: ch.geohash) let identity = try NostrIdentityBridge.deriveIdentity(forGeohash: ch.geohash)
let event = try NostrProtocol.createEphemeralGeohashEvent( let event = try NostrProtocol.createEphemeralGeohashEvent(
content: trimmed, content: content,
geohash: ch.geohash, geohash: ch.geohash,
senderIdentity: identity, senderIdentity: identity,
nickname: self.nickname, nickname: self.nickname,
@@ -1348,10 +1292,7 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
SecureLogger.log("GeoTeleport: sent geo message pub=\(identity.publicKeyHex.prefix(8))… teleported=\(LocationChannelManager.shared.teleported)", SecureLogger.log("GeoTeleport: sent geo message pub=\(identity.publicKeyHex.prefix(8))… teleported=\(LocationChannelManager.shared.teleported)",
category: SecureLogger.session, level: .debug) category: SecureLogger.session, level: .debug)
// If we tagged this as teleported, also mark our pubkey in teleportedGeo for UI // If we tagged this as teleported, also mark our pubkey in teleportedGeo for UI
// Only when not in our regional set (and regional list is known) if LocationChannelManager.shared.teleported {
let hasRegional = !LocationChannelManager.shared.availableChannels.isEmpty
let inRegional = LocationChannelManager.shared.availableChannels.contains { $0.geohash == ch.geohash }
if LocationChannelManager.shared.teleported && hasRegional && !inRegional {
let key = identity.publicKeyHex.lowercased() let key = identity.publicKeyHex.lowercased()
self.teleportedGeo = self.teleportedGeo.union([key]) self.teleportedGeo = self.teleportedGeo.union([key])
SecureLogger.log("GeoTeleport: mark self teleported key=\(key.prefix(8))… total=\(self.teleportedGeo.count)", SecureLogger.log("GeoTeleport: mark self teleported key=\(key.prefix(8))… total=\(self.teleportedGeo.count)",
@@ -1388,13 +1329,9 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
case .location(let ch): case .location(let ch):
// Sanitize existing timeline (filter any prior empty-content entries) // Sanitize existing timeline (filter any prior empty-content entries)
var arr = geoTimelines[ch.geohash] ?? [] var arr = geoTimelines[ch.geohash] ?? []
let before = arr.count
arr.removeAll { $0.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } arr.removeAll { $0.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
// Ensure chronological order when returning to a geohash if arr.count != before { geoTimelines[ch.geohash] = arr }
if arr.count > 1 {
arr.sort { $0.timestamp < $1.timestamp }
}
// Persist the cleaned/sorted timeline for this geohash
geoTimelines[ch.geohash] = arr
messages = arr messages = arr
} }
// Unsubscribe previous // Unsubscribe previous
@@ -1413,18 +1350,14 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
guard case .location(let ch) = channel else { return } guard case .location(let ch) = channel else { return }
currentGeohash = ch.geohash currentGeohash = ch.geohash
// Ensure self appears immediately in the people list; mark teleported state only when truly teleported // Ensure self appears immediately in the people list; mark teleported state if applicable
if let id = try? NostrIdentityBridge.deriveIdentity(forGeohash: ch.geohash) { if let id = try? NostrIdentityBridge.deriveIdentity(forGeohash: ch.geohash) {
self.recordGeoParticipant(pubkeyHex: id.publicKeyHex) self.recordGeoParticipant(pubkeyHex: id.publicKeyHex)
let hasRegional = !LocationChannelManager.shared.availableChannels.isEmpty if LocationChannelManager.shared.teleported {
let inRegional = LocationChannelManager.shared.availableChannels.contains { $0.geohash == ch.geohash } let key = id.publicKeyHex.lowercased()
let key = id.publicKeyHex.lowercased()
if LocationChannelManager.shared.teleported && hasRegional && !inRegional {
teleportedGeo = teleportedGeo.union([key]) teleportedGeo = teleportedGeo.union([key])
SecureLogger.log("GeoTeleport: channel switch mark self teleported key=\(key.prefix(8))… total=\(teleportedGeo.count)", SecureLogger.log("GeoTeleport: channel switch mark self teleported key=\(key.prefix(8))… total=\(teleportedGeo.count)",
category: SecureLogger.session, level: .info) category: SecureLogger.session, level: .info)
} else {
teleportedGeo.remove(key)
} }
} }
let subID = "geo-\(ch.geohash)" let subID = "geo-\(ch.geohash)"
@@ -1453,19 +1386,10 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
}) })
if hasTeleportTag { if hasTeleportTag {
let key = event.pubkey.lowercased() let key = event.pubkey.lowercased()
// Avoid marking our own key from historical events; rely on manager.teleported for self Task { @MainActor in
let isSelf: Bool = { self.teleportedGeo = self.teleportedGeo.union([key])
if let gh = self.currentGeohash, let my = try? NostrIdentityBridge.deriveIdentity(forGeohash: gh) { SecureLogger.log("GeoTeleport: mark peer teleported key=\(key.prefix(8))… total=\(self.teleportedGeo.count)",
return my.publicKeyHex.lowercased() == key category: SecureLogger.session, level: .info)
}
return false
}()
if !isSelf {
Task { @MainActor in
self.teleportedGeo = self.teleportedGeo.union([key])
SecureLogger.log("GeoTeleport: mark peer teleported key=\(key.prefix(8))… total=\(self.teleportedGeo.count)",
category: SecureLogger.session, level: .info)
}
} }
} }
// Skip only very recent self-echo from relay; include older self events for hydration // Skip only very recent self-echo from relay; include older self events for hydration
@@ -1817,52 +1741,8 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays) { [weak self] event in NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays) { [weak self] event in
guard let self = self else { return } guard let self = self else { return }
guard event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue else { return } guard event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue else { return }
// Compute current participant count (5-minute window) BEFORE updating with this event
let cutoff = Date().addingTimeInterval(-TransportConfig.uiRecentCutoffFiveMinutesSeconds)
let existingCount: Int = {
let map = self.geoParticipants[gh] ?? [:]
return map.values.filter { $0 >= cutoff }.count
}()
// Update participants for this specific geohash // Update participants for this specific geohash
self.recordGeoParticipant(pubkeyHex: event.pubkey, geohash: gh) self.recordGeoParticipant(pubkeyHex: event.pubkey, geohash: gh)
// Notify only on rising-edge: previously zero people, now someone sends a chat
let content = event.content.trimmingCharacters(in: .whitespacesAndNewlines)
guard !content.isEmpty else { return }
// Respect geohash blocks
if SecureIdentityStateManager.shared.isNostrBlocked(pubkeyHexLowercased: event.pubkey.lowercased()) { return }
// Skip self identity for this geohash
if let my = try? NostrIdentityBridge.deriveIdentity(forGeohash: gh), my.publicKeyHex.lowercased() == event.pubkey.lowercased() { return }
// Only trigger when there were zero participants in this geohash recently
guard existingCount == 0 else { return }
// Avoid notifications for old sampled events when launching or (re)subscribing
let eventTime = Date(timeIntervalSince1970: TimeInterval(event.created_at))
if Date().timeIntervalSince(eventTime) > 30 { return }
// Foreground policy: allow if it's a different geohash than the one currently open
// Suppress only when app is active AND we're already in this same geohash channel
#if os(iOS)
if UIApplication.shared.applicationState == .active {
if case .location(let ch) = self.activeChannel, ch.geohash == gh { return }
}
#elseif os(macOS)
if NSApplication.shared.isActive {
if case .location(let ch) = self.activeChannel, ch.geohash == gh { return }
}
#endif
// Cooldown per geohash
let now = Date()
let last = self.lastGeoNotificationAt[gh] ?? .distantPast
if now.timeIntervalSince(last) < TransportConfig.uiGeoNotifyCooldownSeconds { return }
// Compose a short preview
let preview: String = {
let maxLen = TransportConfig.uiGeoNotifySnippetMaxLen
if content.count <= maxLen { return content }
let idx = content.index(content.startIndex, offsetBy: maxLen)
return String(content[..<idx]) + ""
}()
Task { @MainActor in
self.lastGeoNotificationAt[gh] = now
NotificationService.shared.sendGeohashActivityNotification(geohash: gh, bodyPreview: preview)
}
} }
} }
} }
@@ -3155,29 +3035,8 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
for mr in mentionRanges { if NSIntersectionRange(r, mr).length > 0 { return true } } for mr in mentionRanges { if NSIntersectionRange(r, mr).length > 0 { return true } }
return false return false
} }
// Helper: check if a hashtag is immediately attached to a preceding @mention (e.g., @name#abcd)
func attachedToMention(_ r: NSRange) -> Bool {
if let nsRange = Range(r, in: content), nsRange.lowerBound > content.startIndex {
var i = content.index(before: nsRange.lowerBound)
while true {
let ch = content[i]
if ch.isWhitespace || ch.isNewline { break }
if ch == "@" { return true }
if i == content.startIndex { break }
i = content.index(before: i)
}
}
return false
}
// Helper: ensure '#' starts a new token (start-of-line or whitespace before '#')
func isStandaloneHashtag(_ r: NSRange) -> Bool {
guard let nsRange = Range(r, in: content) else { return false }
if nsRange.lowerBound == content.startIndex { return true }
let prev = content.index(before: nsRange.lowerBound)
return content[prev].isWhitespace || content[prev].isNewline
}
var allMatches: [(range: NSRange, type: String)] = [] var allMatches: [(range: NSRange, type: String)] = []
for match in hashtagMatches where !overlapsMention(match.range(at: 0)) && !attachedToMention(match.range(at: 0)) && isStandaloneHashtag(match.range(at: 0)) { for match in hashtagMatches where !overlapsMention(match.range(at: 0)) {
allMatches.append((match.range(at: 0), "hashtag")) allMatches.append((match.range(at: 0), "hashtag"))
} }
for match in mentionMatches { for match in mentionMatches {
@@ -3285,18 +3144,12 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
} }
return false return false
}() }()
// Also require the '#' to start a new token (whitespace or start-of-line before '#')
let standalone: Bool = {
if nsRange.lowerBound == content.startIndex { return true }
let prev = content.index(before: nsRange.lowerBound)
return content[prev].isWhitespace || content[prev].isNewline
}()
var tagStyle = AttributeContainer() var tagStyle = AttributeContainer()
tagStyle.font = isSelf tagStyle.font = isSelf
? .system(size: 14, weight: .bold, design: .monospaced) ? .system(size: 14, weight: .bold, design: .monospaced)
: .system(size: 14, design: .monospaced) : .system(size: 14, design: .monospaced)
tagStyle.foregroundColor = baseColor tagStyle.foregroundColor = baseColor
if isGeohash && !attachedToMention && standalone, let url = URL(string: "bitchat://geohash/\(token)") { if isGeohash && !attachedToMention, let url = URL(string: "bitchat://geohash/\(token)") {
tagStyle.link = url tagStyle.link = url
tagStyle.underlineStyle = .single tagStyle.underlineStyle = .single
} }
@@ -3635,20 +3488,14 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
func colorForPeerSeed(_ seed: String, isDark: Bool) -> Color { func colorForPeerSeed(_ seed: String, isDark: Bool) -> Color {
let cacheKey = seed + (isDark ? "|dark" : "|light") let cacheKey = seed + (isDark ? "|dark" : "|light")
if let cached = peerColorCache[cacheKey] { return cached } if let cached = peerColorCache[cacheKey] { return cached }
let h = djb2(seed) var hue = Double(djb2(seed) % 360) / 360.0
var hue = Double(h % 1000) / 1000.0 // Avoid orange (~30°) reserved for self
let orange = 30.0 / 360.0 let orange = 30.0 / 360.0
if abs(hue - orange) < TransportConfig.uiColorHueAvoidanceDelta { if abs(hue - orange) < TransportConfig.uiColorHueAvoidanceDelta {
hue = fmod(hue + TransportConfig.uiColorHueOffset, 1.0) hue = fmod(hue + TransportConfig.uiColorHueOffset, 1.0)
} }
let sRand = Double((h >> 17) & 0x3FF) / 1023.0 let saturation: Double = isDark ? 0.80 : 0.70
let bRand = Double((h >> 27) & 0x3FF) / 1023.0 let brightness: Double = isDark ? 0.75 : 0.45
let sBase: Double = isDark ? 0.80 : 0.70
let sRange: Double = 0.20
let bBase: Double = isDark ? 0.75 : 0.45
let bRange: Double = isDark ? 0.16 : 0.14
let saturation = min(1.0, max(0.50, sBase + (sRand - 0.5) * sRange))
let brightness = min(1.0, max(0.35, bBase + (bRand - 0.5) * bRange))
let c = Color(hue: hue, saturation: saturation, brightness: brightness) let c = Color(hue: hue, saturation: saturation, brightness: brightness)
peerColorCache[cacheKey] = c peerColorCache[cacheKey] = c
return c return c
@@ -3656,35 +3503,41 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
@MainActor @MainActor
private func peerColor(for message: BitchatMessage, isDark: Bool) -> Color { private func peerColor(for message: BitchatMessage, isDark: Bool) -> Color {
var seed: String
if let spid = message.senderPeerID { if let spid = message.senderPeerID {
if spid.hasPrefix("nostr:") || spid.hasPrefix("nostr_") { if spid.hasPrefix("nostr:") || spid.hasPrefix("nostr_") {
// Normalize to the bare short id, then prefer full mapping when available
let bare: String = { let bare: String = {
if spid.hasPrefix("nostr:") { return String(spid.dropFirst(6)) } if spid.hasPrefix("nostr:") { return String(spid.dropFirst(6)) }
if spid.hasPrefix("nostr_") { return String(spid.dropFirst(6)) } if spid.hasPrefix("nostr_") { return String(spid.dropFirst(6)) }
return spid return spid
}() }()
let full = nostrKeyMapping[spid]?.lowercased() ?? bare.lowercased() let full = nostrKeyMapping[spid]?.lowercased() ?? bare.lowercased()
return getNostrPaletteColor(for: full, isDark: isDark) seed = "nostr:" + full
} else if spid.count == 16 { } else if spid.count == 16, let full = getNoiseKeyForShortID(spid)?.lowercased() {
// Mesh short ID seed = "noise:" + full
return getPeerPaletteColor(for: spid, isDark: isDark)
} else { } else {
return getPeerPaletteColor(for: spid.lowercased(), isDark: isDark) seed = spid.lowercased()
} }
} else {
seed = message.sender.lowercased()
} }
// Fallback when we only have a display name return colorForPeerSeed(seed, isDark: isDark)
return colorForPeerSeed(message.sender.lowercased(), isDark: isDark)
} }
// Public helpers for views to color peers consistently in lists // Public helpers for views to color peers consistently in lists
@MainActor @MainActor
func colorForNostrPubkey(_ pubkeyHexLowercased: String, isDark: Bool) -> Color { func colorForNostrPubkey(_ pubkeyHexLowercased: String, isDark: Bool) -> Color {
return getNostrPaletteColor(for: pubkeyHexLowercased.lowercased(), isDark: isDark) return colorForPeerSeed("nostr:" + pubkeyHexLowercased.lowercased(), isDark: isDark)
} }
@MainActor @MainActor
func colorForMeshPeer(id peerID: String, isDark: Bool) -> Color { func colorForMeshPeer(id peerID: String, isDark: Bool) -> Color {
return getPeerPaletteColor(for: peerID, isDark: isDark) // Mirror message coloring: prefer stable full noise key mapping when available, else short ID
if let full = getNoiseKeyForShortID(peerID)?.lowercased() {
return colorForPeerSeed("noise:" + full, isDark: isDark)
}
return colorForPeerSeed(peerID.lowercased(), isDark: isDark)
} }
private func trimMeshTimelineIfNeeded() { private func trimMeshTimelineIfNeeded() {
@@ -3693,276 +3546,6 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
} }
} }
// MARK: - Peer List Minimal-Distance Palette
private var peerPaletteLight: [String: (slot: Int, ring: Int, hue: Double)] = [:]
private var peerPaletteDark: [String: (slot: Int, ring: Int, hue: Double)] = [:]
private var peerPaletteSeeds: [String: String] = [:] // peerID -> seed used
@MainActor
private func meshSeed(for peerID: String) -> String {
if let full = getNoiseKeyForShortID(peerID)?.lowercased() {
return "noise:" + full
}
return peerID.lowercased()
}
@MainActor
private func getPeerPaletteColor(for peerID: String, isDark: Bool) -> Color {
// Ensure palette up to date for current peer set and seeds
rebuildPeerPaletteIfNeeded()
let entry = (isDark ? peerPaletteDark[peerID] : peerPaletteLight[peerID])
let orange = Color.orange
if peerID == meshService.myPeerID { return orange }
let saturation: Double = isDark ? 0.80 : 0.70
let baseBrightness: Double = isDark ? 0.75 : 0.45
let ringDelta = isDark ? TransportConfig.uiPeerPaletteRingBrightnessDeltaDark : TransportConfig.uiPeerPaletteRingBrightnessDeltaLight
if let e = entry {
let brightness = min(1.0, max(0.0, baseBrightness + ringDelta * Double(e.ring)))
return Color(hue: e.hue, saturation: saturation, brightness: brightness)
}
// Fallback to seed color if not in palette (e.g., transient)
let seed = meshSeed(for: peerID)
return colorForPeerSeed(seed, isDark: isDark)
}
@MainActor
private func rebuildPeerPaletteIfNeeded() {
// Build current peer->seed map (excluding self)
let myID = meshService.myPeerID
var currentSeeds: [String: String] = [:]
for p in allPeers where p.id != myID {
currentSeeds[p.id] = meshSeed(for: p.id)
}
// If seeds unchanged and palette exists for both themes, skip
if currentSeeds == peerPaletteSeeds,
peerPaletteLight.keys.count == currentSeeds.count,
peerPaletteDark.keys.count == currentSeeds.count {
return
}
peerPaletteSeeds = currentSeeds
// Generate evenly spaced hue slots avoiding self-orange range
let slotCount = max(8, TransportConfig.uiPeerPaletteSlots)
let avoidCenter = 30.0 / 360.0
let avoidDelta = TransportConfig.uiColorHueAvoidanceDelta
var slots: [Double] = []
for i in 0..<slotCount {
let hue = Double(i) / Double(slotCount)
if abs(hue - avoidCenter) < avoidDelta { continue }
slots.append(hue)
}
if slots.isEmpty {
// Safety: if avoidance consumed all (shouldn't happen), fall back to full slots
for i in 0..<slotCount { slots.append(Double(i) / Double(slotCount)) }
}
// Helper to compute circular distance
func circDist(_ a: Double, _ b: Double) -> Double {
let d = abs(a - b)
return d > 0.5 ? 1.0 - d : d
}
// Assign slots to peers to maximize minimal distance, deterministically
let peers = currentSeeds.keys.sorted() // stable order
// Preferred slot index by seed (wrapping to available slots)
let prefIndex: [String: Int] = Dictionary(uniqueKeysWithValues: peers.map { id in
let h = djb2(currentSeeds[id] ?? id)
// Map to available slot range deterministically
let idx = Int(h % UInt64(slots.count))
return (id, idx)
})
func assign(for seeds: [String: String]) -> [String: (slot: Int, ring: Int, hue: Double)] {
var mapping: [String: (slot: Int, ring: Int, hue: Double)] = [:]
var usedSlots = Set<Int>()
var usedHues: [Double] = []
// Keep previous assignments if still valid to minimize churn
let prev = peerPaletteLight.isEmpty ? peerPaletteDark : peerPaletteLight
for (id, entry) in prev {
if seeds.keys.contains(id), entry.slot < slots.count { // slot index still valid
mapping[id] = (entry.slot, entry.ring, slots[entry.slot])
usedSlots.insert(entry.slot)
usedHues.append(slots[entry.slot])
}
}
// First ring assignment using free slots
let unassigned = peers.filter { mapping[$0] == nil }
for id in unassigned {
// If a preferred slot free, take it
let preferred = prefIndex[id] ?? 0
if !usedSlots.contains(preferred) && preferred < slots.count {
mapping[id] = (preferred, 0, slots[preferred])
usedSlots.insert(preferred)
usedHues.append(slots[preferred])
continue
}
// Choose free slot maximizing minimal distance to used hues
var bestSlot: Int? = nil
var bestScore: Double = -1
for sIdx in 0..<slots.count where !usedSlots.contains(sIdx) {
let hue = slots[sIdx]
let minDist = usedHues.isEmpty ? 1.0 : usedHues.map { circDist(hue, $0) }.min() ?? 1.0
// Bias toward preferred index for stability
let bias = 1.0 - (Double((abs(sIdx - (prefIndex[id] ?? 0)) % slots.count)) / Double(slots.count))
let score = minDist + 0.05 * bias
if score > bestScore { bestScore = score; bestSlot = sIdx }
}
if let s = bestSlot {
mapping[id] = (s, 0, slots[s])
usedSlots.insert(s)
usedHues.append(slots[s])
}
}
// Overflow peers: assign additional rings by reusing slots with stable preference
let stillUnassigned = peers.filter { mapping[$0] == nil }
if !stillUnassigned.isEmpty {
for (idx, id) in stillUnassigned.enumerated() {
let preferred = prefIndex[id] ?? 0
// Spread over slots by rotating from preferred with a golden-step
let goldenStep = 7 // small prime step for dispersion
let s = (preferred + idx * goldenStep) % slots.count
mapping[id] = (s, 1, slots[s])
}
}
return mapping
}
let mapping = assign(for: currentSeeds)
peerPaletteLight = mapping
peerPaletteDark = mapping
}
// MARK: - Nostr People Minimal-Distance Palette (same algo)
private var nostrPaletteLight: [String: (slot: Int, ring: Int, hue: Double)] = [:]
private var nostrPaletteDark: [String: (slot: Int, ring: Int, hue: Double)] = [:]
private var nostrPaletteSeeds: [String: String] = [:] // pubkey -> seed used
@MainActor
private func getNostrPaletteColor(for pubkeyHexLowercased: String, isDark: Bool) -> Color {
rebuildNostrPaletteIfNeeded()
let entry = (isDark ? nostrPaletteDark[pubkeyHexLowercased] : nostrPaletteLight[pubkeyHexLowercased])
let myHex: String? = {
if case .location(let ch) = LocationChannelManager.shared.selectedChannel,
let id = try? NostrIdentityBridge.deriveIdentity(forGeohash: ch.geohash) {
return id.publicKeyHex.lowercased()
}
return nil
}()
if let me = myHex, pubkeyHexLowercased == me { return .orange }
let saturation: Double = isDark ? 0.80 : 0.70
let baseBrightness: Double = isDark ? 0.75 : 0.45
let ringDelta = isDark ? TransportConfig.uiPeerPaletteRingBrightnessDeltaDark : TransportConfig.uiPeerPaletteRingBrightnessDeltaLight
if let e = entry {
let brightness = min(1.0, max(0.0, baseBrightness + ringDelta * Double(e.ring)))
return Color(hue: e.hue, saturation: saturation, brightness: brightness)
}
// Fallback to seed color if not in palette (e.g., transient)
return colorForPeerSeed("nostr:" + pubkeyHexLowercased, isDark: isDark)
}
@MainActor
private func rebuildNostrPaletteIfNeeded() {
// Build seeds map from currently visible geohash people (excluding self)
let myHex: String? = {
if case .location(let ch) = LocationChannelManager.shared.selectedChannel,
let id = try? NostrIdentityBridge.deriveIdentity(forGeohash: ch.geohash) {
return id.publicKeyHex.lowercased()
}
return nil
}()
let people = visibleGeohashPeople()
var currentSeeds: [String: String] = [:]
for p in people where p.id != myHex { currentSeeds[p.id] = "nostr:" + p.id }
if currentSeeds == nostrPaletteSeeds,
nostrPaletteLight.keys.count == currentSeeds.count,
nostrPaletteDark.keys.count == currentSeeds.count {
return
}
nostrPaletteSeeds = currentSeeds
let slotCount = max(8, TransportConfig.uiPeerPaletteSlots)
let avoidCenter = 30.0 / 360.0
let avoidDelta = TransportConfig.uiColorHueAvoidanceDelta
var slots: [Double] = []
for i in 0..<slotCount {
let hue = Double(i) / Double(slotCount)
if abs(hue - avoidCenter) < avoidDelta { continue }
slots.append(hue)
}
if slots.isEmpty {
for i in 0..<slotCount { slots.append(Double(i) / Double(slotCount)) }
}
func circDist(_ a: Double, _ b: Double) -> Double {
let d = abs(a - b)
return d > 0.5 ? 1.0 - d : d
}
let peers = currentSeeds.keys.sorted()
let prefIndex: [String: Int] = Dictionary(uniqueKeysWithValues: peers.map { id in
let h = djb2(currentSeeds[id] ?? id)
let idx = Int(h % UInt64(slots.count))
return (id, idx)
})
var mapping: [String: (slot: Int, ring: Int, hue: Double)] = [:]
var usedSlots = Set<Int>()
var usedHues: [Double] = []
let prev = nostrPaletteLight.isEmpty ? nostrPaletteDark : nostrPaletteLight
for (id, entry) in prev {
if peers.contains(id), entry.slot < slots.count {
mapping[id] = (entry.slot, entry.ring, slots[entry.slot])
usedSlots.insert(entry.slot)
usedHues.append(slots[entry.slot])
}
}
let unassigned = peers.filter { mapping[$0] == nil }
for id in unassigned {
let preferred = prefIndex[id] ?? 0
if !usedSlots.contains(preferred) && preferred < slots.count {
mapping[id] = (preferred, 0, slots[preferred])
usedSlots.insert(preferred)
usedHues.append(slots[preferred])
continue
}
var bestSlot: Int? = nil
var bestScore: Double = -1
for sIdx in 0..<slots.count where !usedSlots.contains(sIdx) {
let hue = slots[sIdx]
let minDist = usedHues.isEmpty ? 1.0 : usedHues.map { circDist(hue, $0) }.min() ?? 1.0
let bias = 1.0 - (Double((abs(sIdx - (prefIndex[id] ?? 0)) % slots.count)) / Double(slots.count))
let score = minDist + 0.05 * bias
if score > bestScore { bestScore = score; bestSlot = sIdx }
}
if let s = bestSlot {
mapping[id] = (s, 0, slots[s])
usedSlots.insert(s)
usedHues.append(slots[s])
}
}
let stillUnassigned = peers.filter { mapping[$0] == nil }
if !stillUnassigned.isEmpty {
for (idx, id) in stillUnassigned.enumerated() {
let preferred = prefIndex[id] ?? 0
let goldenStep = 7
let s = (preferred + idx * goldenStep) % slots.count
mapping[id] = (s, 1, slots[s])
}
}
nostrPaletteLight = mapping
nostrPaletteDark = mapping
}
// Clear the current public channel's timeline (visible + persistent buffer) // Clear the current public channel's timeline (visible + persistent buffer)
@MainActor @MainActor
func clearCurrentPublicTimeline() { func clearCurrentPublicTimeline() {
@@ -4350,12 +3933,11 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
func didReceivePublicMessage(from peerID: String, nickname: String, content: String, timestamp: Date) { func didReceivePublicMessage(from peerID: String, nickname: String, content: String, timestamp: Date) {
Task { @MainActor in Task { @MainActor in
let normalized = content.trimmingCharacters(in: .whitespacesAndNewlines) let publicMentions = parseMentions(from: content)
let publicMentions = parseMentions(from: normalized)
let msg = BitchatMessage( let msg = BitchatMessage(
id: UUID().uuidString, id: UUID().uuidString,
sender: nickname, sender: nickname,
content: normalized, content: content,
timestamp: timestamp, timestamp: timestamp,
isRelay: false, isRelay: false,
originalSender: nil, originalSender: nil,
@@ -4524,9 +4106,9 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
// Cancel any pending reset if peers are back // Cancel any pending reset if peers are back
self.networkResetTimer?.invalidate() self.networkResetTimer?.invalidate()
self.networkResetTimer = nil self.networkResetTimer = nil
// Count mesh peers that are connected OR recently reachable via mesh relays // Only count mesh peers (actually connected via Bluetooth)
let meshPeers = peers.filter { peerID in let meshPeers = peers.filter { peerID in
self.meshService.isPeerConnected(peerID) || self.meshService.isPeerReachable(peerID) self.meshService.isPeerConnected(peerID)
} }
// Check if we have new mesh peers we haven't seen recently // Check if we have new mesh peers we haven't seen recently
@@ -5740,7 +5322,29 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
guard channelMatches else { return } guard channelMatches else { return }
// Background nudge: notify on new activity after inactivity threshold in current channel
#if os(iOS)
if UIApplication.shared.applicationState != .active {
let channelKey: String = {
switch activeChannel {
case .mesh: return "mesh"
case .location(let ch): return "geo:\(ch.geohash)"
}
}()
let now = Date()
if let last = lastPublicActivityAt[channelKey], now.timeIntervalSince(last) >= channelInactivityThreshold {
// Optional: simple cooldown to avoid duplicate bursts
let lastNotified = lastPublicActivityNotifyAt[channelKey] ?? .distantPast
if now.timeIntervalSince(lastNotified) >= 60 {
let title = activeChannelDisplayName()
let body = "new chats!"
NotificationService.shared.sendLocalNotification(title: title, body: body, identifier: "channel-activity-\(channelKey)-\(now.timeIntervalSince1970)")
lastPublicActivityNotifyAt[channelKey] = now
}
}
lastPublicActivityAt[channelKey] = now
}
#endif
// Append via batching buffer (skip empty content) // Append via batching buffer (skip empty content)
if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { if !finalMessage.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+1 -7
View File
@@ -459,13 +459,7 @@ struct ContentView: View {
} }
let level = levelForLength(gh.count) let level = levelForLength(gh.count)
let ch = GeohashChannel(level: level, geohash: gh) let ch = GeohashChannel(level: level, geohash: gh)
// Do not mark teleported when opening a geohash that is in our regional set. LocationChannelManager.shared.markTeleported(for: gh, true)
// If availableChannels is empty (e.g., cold start), defer marking and let
// LocationChannelManager compute teleported based on actual location.
let inRegional = LocationChannelManager.shared.availableChannels.contains { $0.geohash == gh }
if !inRegional && !LocationChannelManager.shared.availableChannels.isEmpty {
LocationChannelManager.shared.markTeleported(for: gh, true)
}
LocationChannelManager.shared.select(ChannelID.location(ch)) LocationChannelManager.shared.select(ChannelID.location(ch))
} }
.onTapGesture(count: 3) { .onTapGesture(count: 3) {
+10 -4
View File
@@ -83,17 +83,24 @@ struct LocationChannelsSheet: View {
} }
// Begin periodic refresh while sheet is open // Begin periodic refresh while sheet is open
manager.beginLiveRefresh() manager.beginLiveRefresh()
// Geohash sampling is now managed by ChatViewModel globally // Begin multi-channel sampling for counts
let ghs = manager.availableChannels.map { $0.geohash }
viewModel.beginGeohashSampling(for: ghs)
} }
.onDisappear { .onDisappear {
manager.endLiveRefresh() manager.endLiveRefresh()
viewModel.endGeohashSampling()
} }
.onChange(of: manager.permissionState) { newValue in .onChange(of: manager.permissionState) { newValue in
if newValue == LocationChannelManager.PermissionState.authorized { if newValue == LocationChannelManager.PermissionState.authorized {
manager.refreshChannels() manager.refreshChannels()
} }
} }
.onChange(of: manager.availableChannels) { _ in } .onChange(of: manager.availableChannels) { newValue in
// Keep sampling list in sync with available channels as they refresh live
let ghs = newValue.map { $0.geohash }
viewModel.beginGeohashSampling(for: ghs)
}
} }
private var channelList: some View { private var channelList: some View {
@@ -282,10 +289,9 @@ struct LocationChannelsSheet: View {
} }
private func meshCount() -> Int { private func meshCount() -> Int {
// Count mesh-connected OR mesh-reachable peers (exclude self)
let myID = viewModel.meshService.myPeerID let myID = viewModel.meshService.myPeerID
return viewModel.allPeers.reduce(0) { acc, peer in return viewModel.allPeers.reduce(0) { acc, peer in
if peer.id != myID && (peer.isConnected || peer.isReachable) { return acc + 1 } if peer.id != myID && peer.isConnected { return acc + 1 }
return acc return acc
} }
} }