mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 12:05:19 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d4c596a17 |
@@ -2,108 +2,59 @@
|
|||||||
|
|
||||||
## 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)
|
||||||
|
|
||||||
📲 [App Store](https://apps.apple.com/us/app/bitchat-mesh/id6748219622)
|
📲 [App Store](https://apps.apple.com/us/app/bitchat-mesh/id6748219622)
|
||||||
|
|
||||||
> [!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
|
||||||
@@ -134,5 +84,5 @@ For detailed protocol documentation, see the [Technical Whitepaper](WHITEPAPER.m
|
|||||||
|
|
||||||
### Option 4: just
|
### Option 4: just
|
||||||
|
|
||||||
Want to try this on macos: `just run` will set it up and run from source.
|
Want to try this on macos: `just run` will set it up and run from source.
|
||||||
Run `just clean` afterwards to restore things to original state for mobile app building and development.
|
Run `just clean` afterwards to restore things to original state for mobile app building and development.
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -136,21 +129,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 +202,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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -634,26 +634,6 @@ class ChatViewModel: ObservableObject, BitchatDelegate {
|
|||||||
if state == .authorized { LocationChannelManager.shared.refreshChannels() }
|
if state == .authorized { LocationChannelManager.shared.refreshChannels() }
|
||||||
}
|
}
|
||||||
.store(in: &cancellables)
|
.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 +772,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 +1217,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 +1237,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 +1252,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 +1297,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 +1317,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 +1354,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 +1375,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 +1411,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,26 +1766,15 @@ 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
|
// Notify on new message activity in this geohash (sampling across channels)
|
||||||
let content = event.content.trimmingCharacters(in: .whitespacesAndNewlines)
|
let content = event.content.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
guard !content.isEmpty else { return }
|
guard !content.isEmpty else { return }
|
||||||
// Respect geohash blocks
|
// Respect geohash blocks
|
||||||
if SecureIdentityStateManager.shared.isNostrBlocked(pubkeyHexLowercased: event.pubkey.lowercased()) { return }
|
if SecureIdentityStateManager.shared.isNostrBlocked(pubkeyHexLowercased: event.pubkey.lowercased()) { return }
|
||||||
// Skip self identity for this geohash
|
// Skip self identity for this geohash
|
||||||
if let my = try? NostrIdentityBridge.deriveIdentity(forGeohash: gh), my.publicKeyHex.lowercased() == event.pubkey.lowercased() { return }
|
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
|
// 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
|
// Suppress only when app is active AND we're already in this same geohash channel
|
||||||
#if os(iOS)
|
#if os(iOS)
|
||||||
@@ -4350,12 +4288,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,
|
||||||
@@ -5740,7 +5677,34 @@ 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!"
|
||||||
|
if case .location(let ch) = activeChannel {
|
||||||
|
// Attach deep link to open this geohash directly
|
||||||
|
NotificationService.shared.sendGeohashActivityNotification(geohash: ch.geohash, titlePrefix: title + " ", bodyPreview: body)
|
||||||
|
} else {
|
||||||
|
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 {
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
|||||||
Reference in New Issue
Block a user