mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 06:25:20 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41c297b889 | ||
|
|
45fec95af2 | ||
|
|
1a569cfb80 | ||
|
|
3ad9cbe48f | ||
|
|
4f62364bf4 | ||
|
|
fb003ba25e | ||
|
|
52c51c9be6 | ||
|
|
96a580491a | ||
|
|
fec5769fd2 | ||
|
|
12d3e91182 | ||
|
|
cf6d169337 |
+1
-1
@@ -6,7 +6,7 @@ let package = Package(
|
||||
name: "bitchat",
|
||||
defaultLocalization: "en",
|
||||
platforms: [
|
||||
.iOS(.v16),
|
||||
.iOS(.v17),
|
||||
.macOS(.v13)
|
||||
],
|
||||
products: [
|
||||
|
||||
@@ -335,6 +335,20 @@ extension BitchatMessage {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - System Message Factory
|
||||
|
||||
extension BitchatMessage {
|
||||
/// Creates a system message with default values
|
||||
static func system(_ content: String, timestamp: Date = Date()) -> BitchatMessage {
|
||||
return BitchatMessage(
|
||||
sender: "system",
|
||||
content: content,
|
||||
timestamp: timestamp,
|
||||
isRelay: false
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension Array where Element == BitchatMessage {
|
||||
/// Filters out empty ones and deduplicate by ID while preserving order (from oldest to newest)
|
||||
func cleanedAndDeduped() -> [Element] {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//
|
||||
// GeoPerson.swift
|
||||
// bitchat
|
||||
//
|
||||
// Model representing a participant in a geohash channel
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Represents a person participating in a geohash-based location channel
|
||||
struct GeoPerson: Identifiable, Equatable {
|
||||
let id: String // pubkey hex (lowercased)
|
||||
let displayName: String
|
||||
let lastSeen: Date
|
||||
}
|
||||
@@ -109,7 +109,20 @@ final class NostrRelayManager: ObservableObject {
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
}
|
||||
|
||||
|
||||
deinit {
|
||||
// Clean up timers and active connections
|
||||
reconnectionTimer?.invalidate()
|
||||
for (_, tracker) in eoseTrackers {
|
||||
tracker.timer?.invalidate()
|
||||
}
|
||||
for (_, task) in connections {
|
||||
task.cancel(with: .goingAway, reason: nil)
|
||||
}
|
||||
cancellables.removeAll()
|
||||
SecureLogger.debug("NostrRelayManager deinitialized", category: .session)
|
||||
}
|
||||
|
||||
/// Connect to all configured relays
|
||||
func connect() {
|
||||
// Global network policy gate
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
//
|
||||
// ColorPaletteService.swift
|
||||
// bitchat
|
||||
//
|
||||
// Manages consistent color assignment for peers using minimal-distance algorithm
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
/// Service that assigns consistent, visually distinct colors to peers
|
||||
/// Uses a minimal-distance hue assignment algorithm to maximize color separation
|
||||
final class ColorPaletteService {
|
||||
|
||||
// MARK: - Palette State
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
private let slotCount: Int
|
||||
private let avoidCenter: Double // Hue to avoid (typically orange for self)
|
||||
private let avoidDelta: Double
|
||||
private let saturationDark: Double
|
||||
private let saturationLight: Double
|
||||
private let baseBrightnessDark: Double
|
||||
private let baseBrightnessLight: Double
|
||||
private let ringDeltaDark: Double
|
||||
private let ringDeltaLight: Double
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
init(
|
||||
slotCount: Int = max(8, TransportConfig.uiPeerPaletteSlots),
|
||||
avoidCenter: Double = 30.0 / 360.0, // Orange hue
|
||||
avoidDelta: Double = TransportConfig.uiColorHueAvoidanceDelta,
|
||||
saturationDark: Double = 0.80,
|
||||
saturationLight: Double = 0.70,
|
||||
baseBrightnessDark: Double = 0.75,
|
||||
baseBrightnessLight: Double = 0.45,
|
||||
ringDeltaDark: Double = TransportConfig.uiPeerPaletteRingBrightnessDeltaDark,
|
||||
ringDeltaLight: Double = TransportConfig.uiPeerPaletteRingBrightnessDeltaLight
|
||||
) {
|
||||
self.slotCount = slotCount
|
||||
self.avoidCenter = avoidCenter
|
||||
self.avoidDelta = avoidDelta
|
||||
self.saturationDark = saturationDark
|
||||
self.saturationLight = saturationLight
|
||||
self.baseBrightnessDark = baseBrightnessDark
|
||||
self.baseBrightnessLight = baseBrightnessLight
|
||||
self.ringDeltaDark = ringDeltaDark
|
||||
self.ringDeltaLight = ringDeltaLight
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Get color for a mesh peer
|
||||
func colorForMeshPeer(
|
||||
peerID: String,
|
||||
isDark: Bool,
|
||||
myPeerID: String,
|
||||
allPeers: [BitchatPeer],
|
||||
getNoiseKeyForShortID: (String) -> String?
|
||||
) -> Color {
|
||||
// Ensure palette is up to date
|
||||
rebuildPeerPaletteIfNeeded(
|
||||
myPeerID: myPeerID,
|
||||
allPeers: allPeers,
|
||||
getNoiseKeyForShortID: getNoiseKeyForShortID
|
||||
)
|
||||
|
||||
let entry = (isDark ? peerPaletteDark[peerID] : peerPaletteLight[peerID])
|
||||
let orange = Color.orange
|
||||
if peerID == myPeerID { return orange }
|
||||
|
||||
let saturation: Double = isDark ? saturationDark : saturationLight
|
||||
let baseBrightness: Double = isDark ? baseBrightnessDark : baseBrightnessLight
|
||||
let ringDelta = isDark ? ringDeltaDark : ringDeltaLight
|
||||
|
||||
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
|
||||
let seed = meshSeed(for: peerID, getNoiseKeyForShortID: getNoiseKeyForShortID)
|
||||
return Color(peerSeed: seed, isDark: isDark)
|
||||
}
|
||||
|
||||
/// Get color for a Nostr participant
|
||||
func colorForNostrPubkey(
|
||||
pubkeyHexLowercased: String,
|
||||
isDark: Bool,
|
||||
myNostrPubkey: String?,
|
||||
geohashPeople: [(id: String, seed: String)]
|
||||
) -> Color {
|
||||
rebuildNostrPaletteIfNeeded(
|
||||
myNostrPubkey: myNostrPubkey,
|
||||
geohashPeople: geohashPeople
|
||||
)
|
||||
|
||||
let entry = (isDark ? nostrPaletteDark[pubkeyHexLowercased] : nostrPaletteLight[pubkeyHexLowercased])
|
||||
if let me = myNostrPubkey, pubkeyHexLowercased == me { return .orange }
|
||||
|
||||
let saturation: Double = isDark ? saturationDark : saturationLight
|
||||
let baseBrightness: Double = isDark ? baseBrightnessDark : baseBrightnessLight
|
||||
let ringDelta = isDark ? ringDeltaDark : ringDeltaLight
|
||||
|
||||
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
|
||||
return Color(peerSeed: "nostr:" + pubkeyHexLowercased, isDark: isDark)
|
||||
}
|
||||
|
||||
/// Get color for a message sender (auto-detects type)
|
||||
func peerColor(
|
||||
for message: BitchatMessage,
|
||||
isDark: Bool,
|
||||
myPeerID: String,
|
||||
myNostrPubkey: String?,
|
||||
nostrKeyMapping: [String: String],
|
||||
allPeers: [BitchatPeer],
|
||||
geohashPeople: [(id: String, seed: String)],
|
||||
getNoiseKeyForShortID: (String) -> String?
|
||||
) -> Color {
|
||||
if let spid = message.senderPeerID?.id {
|
||||
if spid.hasPrefix("nostr:") || spid.hasPrefix("nostr_") {
|
||||
let bare: String = {
|
||||
if spid.hasPrefix("nostr:") { return String(spid.dropFirst(6)) }
|
||||
if spid.hasPrefix("nostr_") { return String(spid.dropFirst(6)) }
|
||||
return spid
|
||||
}()
|
||||
let full = nostrKeyMapping[spid]?.lowercased() ?? bare.lowercased()
|
||||
return colorForNostrPubkey(
|
||||
pubkeyHexLowercased: full,
|
||||
isDark: isDark,
|
||||
myNostrPubkey: myNostrPubkey,
|
||||
geohashPeople: geohashPeople
|
||||
)
|
||||
} else if spid.count == 16 {
|
||||
return colorForMeshPeer(
|
||||
peerID: spid,
|
||||
isDark: isDark,
|
||||
myPeerID: myPeerID,
|
||||
allPeers: allPeers,
|
||||
getNoiseKeyForShortID: getNoiseKeyForShortID
|
||||
)
|
||||
} else {
|
||||
return colorForMeshPeer(
|
||||
peerID: spid.lowercased(),
|
||||
isDark: isDark,
|
||||
myPeerID: myPeerID,
|
||||
allPeers: allPeers,
|
||||
getNoiseKeyForShortID: getNoiseKeyForShortID
|
||||
)
|
||||
}
|
||||
}
|
||||
// Fallback when we only have a display name
|
||||
return Color(peerSeed: message.sender.lowercased(), isDark: isDark)
|
||||
}
|
||||
|
||||
/// Reset all palette state (useful for testing)
|
||||
func reset() {
|
||||
peerPaletteLight.removeAll()
|
||||
peerPaletteDark.removeAll()
|
||||
peerPaletteSeeds.removeAll()
|
||||
nostrPaletteLight.removeAll()
|
||||
nostrPaletteDark.removeAll()
|
||||
nostrPaletteSeeds.removeAll()
|
||||
}
|
||||
|
||||
// MARK: - Private Helpers
|
||||
|
||||
private func meshSeed(for peerID: String, getNoiseKeyForShortID: (String) -> String?) -> String {
|
||||
if let full = getNoiseKeyForShortID(peerID)?.lowercased() {
|
||||
return "noise:" + full
|
||||
}
|
||||
return peerID.lowercased()
|
||||
}
|
||||
|
||||
private func rebuildPeerPaletteIfNeeded(
|
||||
myPeerID: String,
|
||||
allPeers: [BitchatPeer],
|
||||
getNoiseKeyForShortID: (String) -> String?
|
||||
) {
|
||||
// Build current peer->seed map (excluding self)
|
||||
var currentSeeds: [String: String] = [:]
|
||||
for p in allPeers where p.peerID.id != myPeerID {
|
||||
currentSeeds[p.peerID.id] = meshSeed(for: p.peerID.id, getNoiseKeyForShortID: getNoiseKeyForShortID)
|
||||
}
|
||||
|
||||
// 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 palette
|
||||
let mapping = assignColorsMinimalDistance(seeds: currentSeeds, previousMapping: peerPaletteLight)
|
||||
peerPaletteLight = mapping
|
||||
peerPaletteDark = mapping
|
||||
}
|
||||
|
||||
private func rebuildNostrPaletteIfNeeded(
|
||||
myNostrPubkey: String?,
|
||||
geohashPeople: [(id: String, seed: String)]
|
||||
) {
|
||||
// Build seeds map from currently visible geohash people (excluding self)
|
||||
var currentSeeds: [String: String] = [:]
|
||||
for p in geohashPeople where p.id != myNostrPubkey {
|
||||
currentSeeds[p.id] = p.seed
|
||||
}
|
||||
|
||||
if currentSeeds == nostrPaletteSeeds,
|
||||
nostrPaletteLight.keys.count == currentSeeds.count,
|
||||
nostrPaletteDark.keys.count == currentSeeds.count {
|
||||
return
|
||||
}
|
||||
nostrPaletteSeeds = currentSeeds
|
||||
|
||||
let mapping = assignColorsMinimalDistance(seeds: currentSeeds, previousMapping: nostrPaletteLight)
|
||||
nostrPaletteLight = mapping
|
||||
nostrPaletteDark = mapping
|
||||
}
|
||||
|
||||
// MARK: - Minimal-Distance Color Assignment Algorithm
|
||||
|
||||
private func assignColorsMinimalDistance(
|
||||
seeds: [String: String],
|
||||
previousMapping: [String: (slot: Int, ring: Int, hue: Double)]
|
||||
) -> [String: (slot: Int, ring: Int, hue: Double)] {
|
||||
// Generate evenly spaced hue slots avoiding self-orange range
|
||||
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 = seeds.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 = (seeds[id] ?? id).djb2()
|
||||
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] = []
|
||||
|
||||
// Keep previous assignments if still valid to minimize churn
|
||||
for (id, entry) in previousMapping {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//
|
||||
// DeliveryTrackingService.swift
|
||||
// bitchat
|
||||
//
|
||||
// Service for tracking message delivery and read status
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
//
|
||||
|
||||
import BitLogger
|
||||
import Foundation
|
||||
|
||||
/// Service that manages delivery status updates for messages
|
||||
/// Prevents status downgrades (e.g., read → delivered) and maintains consistency
|
||||
final class DeliveryTrackingService {
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Update delivery status for a message, preventing downgrades
|
||||
/// - Parameters:
|
||||
/// - messageID: The message ID to update
|
||||
/// - status: The new delivery status
|
||||
/// - messages: Array of public messages (inout for mutation)
|
||||
/// - privateChats: Dictionary of private chats (inout for mutation)
|
||||
/// - notifyChange: Closure to trigger UI update
|
||||
func updateStatus(
|
||||
messageID: String,
|
||||
status: DeliveryStatus,
|
||||
messages: inout [BitchatMessage],
|
||||
privateChats: inout [String: [BitchatMessage]],
|
||||
notifyChange: @escaping () -> Void
|
||||
) {
|
||||
// Update in main messages
|
||||
if let index = messages.firstIndex(where: { $0.id == messageID }) {
|
||||
let currentStatus = messages[index].deliveryStatus
|
||||
if !shouldSkipUpdate(currentStatus: currentStatus, newStatus: status) {
|
||||
messages[index].deliveryStatus = status
|
||||
}
|
||||
}
|
||||
|
||||
// Update in private chats
|
||||
for (peerID, chatMessages) in privateChats {
|
||||
guard let index = chatMessages.firstIndex(where: { $0.id == messageID }) else { continue }
|
||||
|
||||
let currentStatus = chatMessages[index].deliveryStatus
|
||||
guard !shouldSkipUpdate(currentStatus: currentStatus, newStatus: status) else { continue }
|
||||
|
||||
// Update delivery status
|
||||
privateChats[peerID]?[index].deliveryStatus = status
|
||||
}
|
||||
|
||||
// Trigger UI update
|
||||
DispatchQueue.main.async {
|
||||
notifyChange()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private Helpers
|
||||
|
||||
/// Check if we should skip a status update to prevent downgrades
|
||||
private func shouldSkipUpdate(currentStatus: DeliveryStatus?, newStatus: DeliveryStatus) -> Bool {
|
||||
guard let current = currentStatus else { return false }
|
||||
|
||||
// Don't downgrade from read to delivered or sent
|
||||
switch (current, newStatus) {
|
||||
case (.read, .delivered):
|
||||
return true
|
||||
case (.read, .sent):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,13 @@ final class FavoritesPersistenceService: ObservableObject {
|
||||
}
|
||||
.assign(to: &$mutualFavorites)
|
||||
}
|
||||
|
||||
|
||||
deinit {
|
||||
// Clean up Combine subscriptions
|
||||
cancellables.removeAll()
|
||||
SecureLogger.debug("FavoritesPersistenceService deinitialized", category: .session)
|
||||
}
|
||||
|
||||
/// Add or update a favorite
|
||||
func addFavorite(
|
||||
peerNoisePublicKey: Data,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import BitLogger
|
||||
import Foundation
|
||||
import Combine
|
||||
#if os(iOS) || os(macOS)
|
||||
import CoreLocation
|
||||
#endif
|
||||
|
||||
/// Stores a user-maintained list of bookmarked geohash channels.
|
||||
/// - Persistence: UserDefaults (JSON string array)
|
||||
@@ -16,10 +15,8 @@ final class GeohashBookmarksStore: ObservableObject {
|
||||
private let storeKey = "locationChannel.bookmarks"
|
||||
private let namesStoreKey = "locationChannel.bookmarkNames"
|
||||
private var membership: Set<String> = []
|
||||
#if os(iOS) || os(macOS)
|
||||
private let geocoder = CLGeocoder()
|
||||
private var resolving: Set<String> = []
|
||||
#endif
|
||||
|
||||
private let storage: UserDefaults
|
||||
|
||||
@@ -28,6 +25,12 @@ final class GeohashBookmarksStore: ObservableObject {
|
||||
load()
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Cancel any pending geocoding operations
|
||||
geocoder.cancelGeocode()
|
||||
SecureLogger.debug("GeohashBookmarksStore deinitialized", category: .session)
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
func isBookmarked(_ geohash: String) -> Bool {
|
||||
return membership.contains(Self.normalize(geohash))
|
||||
@@ -118,7 +121,6 @@ final class GeohashBookmarksStore: ObservableObject {
|
||||
let gh = Self.normalize(geohash)
|
||||
guard !gh.isEmpty else { return }
|
||||
if bookmarkNames[gh] != nil { return }
|
||||
#if os(iOS) || os(macOS)
|
||||
if resolving.contains(gh) { return }
|
||||
resolving.insert(gh)
|
||||
// For very coarse geohashes, sample multiple points to capture multiple admin areas
|
||||
@@ -149,10 +151,8 @@ final class GeohashBookmarksStore: ObservableObject {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(iOS) || os(macOS)
|
||||
private func resolveCompositeAdminName(geohash gh: String, points: [CLLocation]) {
|
||||
var uniqueAdmins = OrderedSet<String>()
|
||||
var idx = 0
|
||||
@@ -215,7 +215,6 @@ final class GeohashBookmarksStore: ObservableObject {
|
||||
return pm.subLocality ?? pm.locality ?? pm.administrativeArea ?? pm.country
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if DEBUG
|
||||
/// Testing-only reset helper
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
//
|
||||
// GeohashParticipantsService.swift
|
||||
// bitchat
|
||||
//
|
||||
// Manages tracking of participants in geohash-based location channels
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
//
|
||||
|
||||
import BitLogger
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
/// Service for tracking and managing participants in geohash channels
|
||||
/// Handles automatic expiration, refresh timers, and participant list management
|
||||
final class GeohashParticipantsService: ObservableObject {
|
||||
|
||||
// MARK: - Published Properties
|
||||
|
||||
@Published private(set) var geohashPeople: [GeoPerson] = []
|
||||
|
||||
// MARK: - Private State
|
||||
|
||||
private var geoParticipants: [String: [String: Date]] = [:] // geohash -> [pubkeyHex -> lastSeen]
|
||||
private var geoParticipantsTimer: Timer? = nil
|
||||
private var currentGeohash: String? = nil
|
||||
|
||||
// MARK: - Dependencies
|
||||
|
||||
private let identityManager: SecureIdentityStateManagerProtocol
|
||||
private let displayNameProvider: (String) -> String
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
private let activityWindowSeconds: TimeInterval
|
||||
private let refreshIntervalSeconds: TimeInterval
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
init(
|
||||
identityManager: SecureIdentityStateManagerProtocol,
|
||||
displayNameProvider: @escaping (String) -> String,
|
||||
activityWindowSeconds: TimeInterval = TransportConfig.uiRecentCutoffFiveMinutesSeconds,
|
||||
refreshIntervalSeconds: TimeInterval = 30.0
|
||||
) {
|
||||
self.identityManager = identityManager
|
||||
self.displayNameProvider = displayNameProvider
|
||||
self.activityWindowSeconds = activityWindowSeconds
|
||||
self.refreshIntervalSeconds = refreshIntervalSeconds
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Note: deinit cannot call @MainActor methods
|
||||
// Timer cleanup will happen automatically when service is deallocated
|
||||
SecureLogger.debug("GeohashParticipantsService deinitialized", category: .session)
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Set the current geohash being tracked (starts/stops timer accordingly)
|
||||
func setCurrentGeohash(_ geohash: String?) {
|
||||
if currentGeohash != geohash {
|
||||
currentGeohash = geohash
|
||||
refreshPeopleList()
|
||||
|
||||
if geohash != nil {
|
||||
startTimer()
|
||||
} else {
|
||||
stopTimer()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a participant activity in the current geohash
|
||||
func recordParticipant(pubkeyHex: String) {
|
||||
guard let gh = currentGeohash else { return }
|
||||
recordParticipant(pubkeyHex: pubkeyHex, geohash: gh)
|
||||
}
|
||||
|
||||
/// Record a participant activity in a specific geohash
|
||||
func recordParticipant(pubkeyHex: String, geohash: String) {
|
||||
let key = pubkeyHex.lowercased()
|
||||
var map = geoParticipants[geohash] ?? [:]
|
||||
map[key] = Date()
|
||||
geoParticipants[geohash] = map
|
||||
|
||||
// Only refresh list if this geohash is currently selected
|
||||
if currentGeohash == geohash {
|
||||
refreshPeopleList()
|
||||
}
|
||||
}
|
||||
|
||||
/// Get visible people for the current geohash (without mutating state)
|
||||
func visiblePeople() -> [GeoPerson] {
|
||||
guard let gh = currentGeohash else { return [] }
|
||||
return visiblePeople(for: gh)
|
||||
}
|
||||
|
||||
/// Get visible people for a specific geohash
|
||||
func visiblePeople(for geohash: String) -> [GeoPerson] {
|
||||
let cutoff = Date().addingTimeInterval(-activityWindowSeconds)
|
||||
let map = (geoParticipants[geohash] ?? [:])
|
||||
.filter { $0.value >= cutoff }
|
||||
.filter { !identityManager.isNostrBlocked(pubkeyHexLowercased: $0.key) }
|
||||
let people = map
|
||||
.map { (pub, seen) in
|
||||
GeoPerson(id: pub, displayName: displayNameProvider(pub), lastSeen: seen)
|
||||
}
|
||||
.sorted { $0.lastSeen > $1.lastSeen }
|
||||
return people
|
||||
}
|
||||
|
||||
/// Get participant count for a specific geohash (using activity window)
|
||||
func participantCount(for geohash: String) -> Int {
|
||||
let cutoff = Date().addingTimeInterval(-activityWindowSeconds)
|
||||
let map = geoParticipants[geohash] ?? [:]
|
||||
return map.values.filter { $0 >= cutoff }.count
|
||||
}
|
||||
|
||||
/// Remove a participant from all geohashes (e.g., when blocked)
|
||||
func removeParticipant(pubkeyHexLowercased: String) {
|
||||
let hex = pubkeyHexLowercased.lowercased()
|
||||
for (gh, var map) in geoParticipants {
|
||||
map.removeValue(forKey: hex)
|
||||
geoParticipants[gh] = map
|
||||
}
|
||||
refreshPeopleList()
|
||||
}
|
||||
|
||||
/// Clear all participant data (for testing or reset)
|
||||
func reset() {
|
||||
stopTimer()
|
||||
geoParticipants.removeAll()
|
||||
geohashPeople.removeAll()
|
||||
currentGeohash = nil
|
||||
}
|
||||
|
||||
// MARK: - Private Helpers
|
||||
|
||||
private func refreshPeopleList() {
|
||||
guard let gh = currentGeohash else {
|
||||
geohashPeople = []
|
||||
return
|
||||
}
|
||||
|
||||
let cutoff = Date().addingTimeInterval(-activityWindowSeconds)
|
||||
var map = geoParticipants[gh] ?? [:]
|
||||
|
||||
// Prune expired entries
|
||||
map = map.filter { $0.value >= cutoff }
|
||||
|
||||
// Remove blocked Nostr pubkeys
|
||||
map = map.filter { !identityManager.isNostrBlocked(pubkeyHexLowercased: $0.key) }
|
||||
|
||||
// Update cleaned map
|
||||
geoParticipants[gh] = map
|
||||
|
||||
// Build display list
|
||||
let people = map
|
||||
.map { (pub, seen) in
|
||||
GeoPerson(id: pub, displayName: displayNameProvider(pub), lastSeen: seen)
|
||||
}
|
||||
.sorted { $0.lastSeen > $1.lastSeen }
|
||||
|
||||
geohashPeople = people
|
||||
}
|
||||
|
||||
private func startTimer() {
|
||||
stopTimer()
|
||||
geoParticipantsTimer = Timer.scheduledTimer(withTimeInterval: refreshIntervalSeconds, repeats: true) { [weak self] _ in
|
||||
Task { @MainActor in
|
||||
self?.refreshPeopleList()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func stopTimer() {
|
||||
geoParticipantsTimer?.invalidate()
|
||||
geoParticipantsTimer = nil
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,12 @@ final class LocationNotesCounter: ObservableObject {
|
||||
self.dependencies = testDependencies
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Note: deinit cannot call @MainActor functions
|
||||
// Subscription cleanup will happen automatically when counter is deallocated
|
||||
SecureLogger.debug("LocationNotesCounter deinitialized", category: .session)
|
||||
}
|
||||
|
||||
func subscribe(geohash gh: String) {
|
||||
let norm = gh.lowercased()
|
||||
if geohash == norm, subscriptionID != nil { return }
|
||||
|
||||
@@ -101,6 +101,12 @@ final class LocationNotesManager: ObservableObject {
|
||||
subscribe()
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Note: deinit cannot call @MainActor functions
|
||||
// Subscription cleanup will happen automatically when manager is deallocated
|
||||
SecureLogger.debug("LocationNotesManager deinitialized", category: .session)
|
||||
}
|
||||
|
||||
func setGeohash(_ newGeohash: String) {
|
||||
let norm = newGeohash.lowercased()
|
||||
guard norm != geohash else { return }
|
||||
|
||||
@@ -0,0 +1,618 @@
|
||||
//
|
||||
// MessageFormattingService.swift
|
||||
// bitchat
|
||||
//
|
||||
// Service for formatting chat messages with syntax highlighting
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
/// Service that formats BitchatMessages into styled AttributedStrings
|
||||
/// Handles hashtags, mentions, links, payment tokens, and more
|
||||
final class MessageFormattingService {
|
||||
|
||||
// MARK: - Precompiled Regexes
|
||||
|
||||
private enum Regexes {
|
||||
static let hashtag: NSRegularExpression = {
|
||||
try! NSRegularExpression(pattern: "#([a-zA-Z0-9_]+)", options: [])
|
||||
}()
|
||||
static let mention: NSRegularExpression = {
|
||||
try! NSRegularExpression(pattern: "@([\\p{L}0-9_]+(?:#[a-fA-F0-9]{4})?)", options: [])
|
||||
}()
|
||||
static let cashu: NSRegularExpression = {
|
||||
try! NSRegularExpression(pattern: "\\bcashu[AB][A-Za-z0-9._-]{40,}\\b", options: [])
|
||||
}()
|
||||
static let bolt11: NSRegularExpression = {
|
||||
try! NSRegularExpression(pattern: "(?i)\\bln(bc|tb|bcrt)[0-9][a-z0-9]{50,}\\b", options: [])
|
||||
}()
|
||||
static let lnurl: NSRegularExpression = {
|
||||
try! NSRegularExpression(pattern: "(?i)\\blnurl1[a-z0-9]{20,}\\b", options: [])
|
||||
}()
|
||||
static let lightningScheme: NSRegularExpression = {
|
||||
try! NSRegularExpression(pattern: "(?i)\\blightning:[^\\s]+", options: [])
|
||||
}()
|
||||
static let linkDetector: NSDataDetector? = {
|
||||
try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
|
||||
}()
|
||||
static let quickCashuPresence: NSRegularExpression = {
|
||||
try! NSRegularExpression(pattern: "\\bcashu[AB][A-Za-z0-9._-]{40,}\\b", options: [])
|
||||
}()
|
||||
}
|
||||
|
||||
// MARK: - Dependencies
|
||||
|
||||
private let colorPalette: ColorPaletteService
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
init(colorPalette: ColorPaletteService) {
|
||||
self.colorPalette = colorPalette
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Format a message with full syntax highlighting (hashtags, mentions, links, payments)
|
||||
/// This is the primary formatter used in the main chat view
|
||||
func formatMessageAsText(
|
||||
_ message: BitchatMessage,
|
||||
colorScheme: ColorScheme,
|
||||
nickname: String,
|
||||
myPeerID: String,
|
||||
myNostrPubkey: String?,
|
||||
activeChannel: ChannelID,
|
||||
nostrKeyMapping: [String: String],
|
||||
allPeers: [BitchatPeer],
|
||||
geohashPeople: [GeoPerson],
|
||||
getNoiseKeyForShortID: @escaping (String) -> String?
|
||||
) -> AttributedString {
|
||||
// Determine if this message was sent by self
|
||||
let isSelf = isSelfMessage(
|
||||
message,
|
||||
nickname: nickname,
|
||||
myPeerID: myPeerID,
|
||||
myNostrPubkey: myNostrPubkey,
|
||||
activeChannel: activeChannel
|
||||
)
|
||||
|
||||
// Check cache first
|
||||
let isDark = colorScheme == .dark
|
||||
if let cachedText = message.getCachedFormattedText(isDark: isDark, isSelf: isSelf) {
|
||||
return cachedText
|
||||
}
|
||||
|
||||
// Not cached, format the message
|
||||
var result = AttributedString()
|
||||
|
||||
let baseColor: Color = isSelf ? .orange : colorPalette.peerColor(
|
||||
for: message,
|
||||
isDark: isDark,
|
||||
myPeerID: myPeerID,
|
||||
myNostrPubkey: myNostrPubkey,
|
||||
nostrKeyMapping: nostrKeyMapping,
|
||||
allPeers: allPeers,
|
||||
geohashPeople: geohashPeople.map { (id: $0.id, seed: "nostr:" + $0.id) },
|
||||
getNoiseKeyForShortID: getNoiseKeyForShortID
|
||||
)
|
||||
|
||||
if message.sender != "system" {
|
||||
// Sender (at the beginning) with light-gray suffix styling if present
|
||||
let (baseName, suffix) = message.sender.splitSuffix()
|
||||
var senderStyle = AttributeContainer()
|
||||
senderStyle.foregroundColor = baseColor
|
||||
let fontWeight: Font.Weight = isSelf ? .bold : .medium
|
||||
senderStyle.font = .bitchatSystem(size: 14, weight: fontWeight, design: .monospaced)
|
||||
|
||||
// Make sender clickable: encode senderPeerID into a custom URL
|
||||
if let spid = message.senderPeerID?.id,
|
||||
let url = URL(string: "bitchat://user/\(spid.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? spid)") {
|
||||
senderStyle.link = url
|
||||
}
|
||||
|
||||
// Format: <@name#suffix>
|
||||
result.append(AttributedString("<@").mergingAttributes(senderStyle))
|
||||
result.append(AttributedString(baseName).mergingAttributes(senderStyle))
|
||||
if !suffix.isEmpty {
|
||||
var suffixStyle = senderStyle
|
||||
suffixStyle.foregroundColor = baseColor.opacity(0.6)
|
||||
result.append(AttributedString(suffix).mergingAttributes(suffixStyle))
|
||||
}
|
||||
result.append(AttributedString("> ").mergingAttributes(senderStyle))
|
||||
|
||||
// Process content with syntax highlighting
|
||||
let content = message.content
|
||||
let nsContent = content as NSString
|
||||
let nsLen = nsContent.length
|
||||
|
||||
// Check for Cashu presence early to decide rendering strategy
|
||||
let containsCashuEarly = Regexes.quickCashuPresence.numberOfMatches(
|
||||
in: content,
|
||||
options: [],
|
||||
range: NSRange(location: 0, length: nsLen)
|
||||
) > 0
|
||||
|
||||
// For extremely long content, render as plain text (unless has Cashu)
|
||||
if (content.count > 4000 || content.hasVeryLongToken(threshold: 1024)) && !containsCashuEarly {
|
||||
var plainStyle = AttributeContainer()
|
||||
plainStyle.foregroundColor = baseColor
|
||||
plainStyle.font = isSelf
|
||||
? .bitchatSystem(size: 14, weight: .bold, design: .monospaced)
|
||||
: .bitchatSystem(size: 14, design: .monospaced)
|
||||
result.append(AttributedString(content).mergingAttributes(plainStyle))
|
||||
} else {
|
||||
// Full syntax highlighting
|
||||
result.append(formatContent(
|
||||
content,
|
||||
nsContent: nsContent,
|
||||
nsLen: nsLen,
|
||||
message: message,
|
||||
baseColor: baseColor,
|
||||
isSelf: isSelf,
|
||||
isDark: isDark,
|
||||
nickname: nickname,
|
||||
myPeerID: myPeerID,
|
||||
myNostrPubkey: myNostrPubkey,
|
||||
activeChannel: activeChannel
|
||||
))
|
||||
}
|
||||
|
||||
// Add timestamp
|
||||
let timestamp = AttributedString(" [\(message.formattedTimestamp)]")
|
||||
var timestampStyle = AttributeContainer()
|
||||
timestampStyle.foregroundColor = Color.gray.opacity(0.7)
|
||||
timestampStyle.font = .bitchatSystem(size: 10, design: .monospaced)
|
||||
result.append(timestamp.mergingAttributes(timestampStyle))
|
||||
} else {
|
||||
// System message
|
||||
var contentStyle = AttributeContainer()
|
||||
contentStyle.foregroundColor = Color.gray
|
||||
let content = AttributedString("* \(message.content) *")
|
||||
contentStyle.font = .bitchatSystem(size: 12, design: .monospaced).italic()
|
||||
result.append(content.mergingAttributes(contentStyle))
|
||||
|
||||
// Add timestamp
|
||||
let timestamp = AttributedString(" [\(message.formattedTimestamp)]")
|
||||
var timestampStyle = AttributeContainer()
|
||||
timestampStyle.foregroundColor = Color.gray.opacity(0.5)
|
||||
timestampStyle.font = .bitchatSystem(size: 10, design: .monospaced)
|
||||
result.append(timestamp.mergingAttributes(timestampStyle))
|
||||
}
|
||||
|
||||
// Cache the formatted text
|
||||
message.setCachedFormattedText(result, isDark: isDark, isSelf: isSelf)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// Simpler message formatter (used in legacy contexts)
|
||||
func formatMessage(
|
||||
_ message: BitchatMessage,
|
||||
colorScheme: ColorScheme,
|
||||
nickname: String
|
||||
) -> AttributedString {
|
||||
var result = AttributedString()
|
||||
|
||||
let isDark = colorScheme == .dark
|
||||
let primaryColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)
|
||||
|
||||
if message.sender == "system" {
|
||||
let content = AttributedString("* \(message.content) *")
|
||||
var contentStyle = AttributeContainer()
|
||||
contentStyle.foregroundColor = Color.gray
|
||||
contentStyle.font = .bitchatSystem(size: 12, design: .monospaced).italic()
|
||||
result.append(content.mergingAttributes(contentStyle))
|
||||
|
||||
// Add timestamp
|
||||
let timestamp = AttributedString(" [\(message.formattedTimestamp)]")
|
||||
var timestampStyle = AttributeContainer()
|
||||
timestampStyle.foregroundColor = Color.gray.opacity(0.5)
|
||||
timestampStyle.font = .bitchatSystem(size: 10, design: .monospaced)
|
||||
result.append(timestamp.mergingAttributes(timestampStyle))
|
||||
} else {
|
||||
let sender = AttributedString("<@\(message.sender)> ")
|
||||
var senderStyle = AttributeContainer()
|
||||
senderStyle.foregroundColor = primaryColor
|
||||
let fontWeight: Font.Weight = message.sender == nickname ? .bold : .medium
|
||||
senderStyle.font = .bitchatSystem(size: 12, weight: fontWeight, design: .monospaced)
|
||||
result.append(sender.mergingAttributes(senderStyle))
|
||||
|
||||
// Process content to highlight mentions
|
||||
let contentText = message.content
|
||||
let pattern = "@([\\p{L}0-9_]+)"
|
||||
let regex = try? NSRegularExpression(pattern: pattern, options: [])
|
||||
let nsContent = contentText as NSString
|
||||
let nsLen = nsContent.length
|
||||
let matches = regex?.matches(in: contentText, options: [], range: NSRange(location: 0, length: nsLen)) ?? []
|
||||
|
||||
var processedContent = AttributedString()
|
||||
var lastEndIndex = contentText.startIndex
|
||||
|
||||
for match in matches {
|
||||
if let range = Range(match.range(at: 0), in: contentText) {
|
||||
// Add text before mention
|
||||
if lastEndIndex < range.lowerBound {
|
||||
let beforeText = String(contentText[lastEndIndex..<range.lowerBound])
|
||||
if !beforeText.isEmpty {
|
||||
var normalStyle = AttributeContainer()
|
||||
normalStyle.font = .bitchatSystem(size: 14, design: .monospaced)
|
||||
normalStyle.foregroundColor = isDark ? Color.white : Color.black
|
||||
processedContent.append(AttributedString(beforeText).mergingAttributes(normalStyle))
|
||||
}
|
||||
}
|
||||
|
||||
// Add the mention with highlight
|
||||
let mentionText = String(contentText[range])
|
||||
var mentionStyle = AttributeContainer()
|
||||
mentionStyle.font = .bitchatSystem(size: 14, weight: .semibold, design: .monospaced)
|
||||
mentionStyle.foregroundColor = Color.orange
|
||||
processedContent.append(AttributedString(mentionText).mergingAttributes(mentionStyle))
|
||||
|
||||
if lastEndIndex < range.upperBound { lastEndIndex = range.upperBound }
|
||||
}
|
||||
}
|
||||
|
||||
// Add remaining text
|
||||
if lastEndIndex < contentText.endIndex {
|
||||
let remainingText = String(contentText[lastEndIndex...])
|
||||
var normalStyle = AttributeContainer()
|
||||
normalStyle.font = .bitchatSystem(size: 14, design: .monospaced)
|
||||
normalStyle.foregroundColor = isDark ? Color.white : Color.black
|
||||
processedContent.append(AttributedString(remainingText).mergingAttributes(normalStyle))
|
||||
}
|
||||
|
||||
result.append(processedContent)
|
||||
|
||||
if message.isRelay, let originalSender = message.originalSender {
|
||||
let relay = AttributedString(" (via \(originalSender))")
|
||||
var relayStyle = AttributeContainer()
|
||||
relayStyle.foregroundColor = primaryColor.opacity(0.7)
|
||||
relayStyle.font = .bitchatSystem(size: 11, design: .monospaced)
|
||||
result.append(relay.mergingAttributes(relayStyle))
|
||||
}
|
||||
|
||||
// Add timestamp
|
||||
let timestamp = AttributedString(" [\(message.formattedTimestamp)]")
|
||||
var timestampStyle = AttributeContainer()
|
||||
timestampStyle.foregroundColor = Color.gray.opacity(0.7)
|
||||
timestampStyle.font = .bitchatSystem(size: 10, design: .monospaced)
|
||||
result.append(timestamp.mergingAttributes(timestampStyle))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// MARK: - Private Helpers
|
||||
|
||||
private func isSelfMessage(
|
||||
_ message: BitchatMessage,
|
||||
nickname: String,
|
||||
myPeerID: String,
|
||||
myNostrPubkey: String?,
|
||||
activeChannel: ChannelID
|
||||
) -> Bool {
|
||||
if let spid = message.senderPeerID?.id {
|
||||
// In geohash channels, compare against our per-geohash nostr short ID
|
||||
if case .location = activeChannel, spid.hasPrefix("nostr:"),
|
||||
let myGeo = myNostrPubkey {
|
||||
return spid == "nostr:\(myGeo.prefix(TransportConfig.nostrShortKeyDisplayLength))"
|
||||
}
|
||||
return spid == myPeerID
|
||||
}
|
||||
// Fallback by nickname
|
||||
if message.sender == nickname { return true }
|
||||
if message.sender.hasPrefix(nickname + "#") { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
private func formatContent(
|
||||
_ content: String,
|
||||
nsContent: NSString,
|
||||
nsLen: Int,
|
||||
message: BitchatMessage,
|
||||
baseColor: Color,
|
||||
isSelf: Bool,
|
||||
isDark: Bool,
|
||||
nickname: String,
|
||||
myPeerID: String,
|
||||
myNostrPubkey: String?,
|
||||
activeChannel: ChannelID
|
||||
) -> AttributedString {
|
||||
// Extract all matches
|
||||
let hasMentionsHint = content.contains("@")
|
||||
let hasHashtagsHint = content.contains("#")
|
||||
let hasURLHint = content.contains("://") || content.contains("www.") || content.contains("http")
|
||||
let hasLightningHint = content.lowercased().contains("ln") || content.lowercased().contains("lightning:")
|
||||
let hasCashuHint = content.lowercased().contains("cashu")
|
||||
|
||||
let hashtagMatches = hasHashtagsHint ? Regexes.hashtag.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) : []
|
||||
let mentionMatches = hasMentionsHint ? Regexes.mention.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) : []
|
||||
let urlMatches = hasURLHint ? (Regexes.linkDetector?.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) ?? []) : []
|
||||
let cashuMatches = hasCashuHint ? Regexes.cashu.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) : []
|
||||
let lightningMatches = hasLightningHint ? Regexes.lightningScheme.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) : []
|
||||
let bolt11Matches = hasLightningHint ? Regexes.bolt11.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) : []
|
||||
let lnurlMatches = hasLightningHint ? Regexes.lnurl.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) : []
|
||||
|
||||
// Combine and sort matches, excluding hashtags/URLs overlapping mentions
|
||||
let mentionRanges = mentionMatches.map { $0.range(at: 0) }
|
||||
|
||||
func overlapsMention(_ r: NSRange) -> Bool {
|
||||
for mr in mentionRanges {
|
||||
if NSIntersectionRange(r, mr).length > 0 { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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)] = []
|
||||
for match in hashtagMatches where !overlapsMention(match.range(at: 0)) && !attachedToMention(match.range(at: 0)) && isStandaloneHashtag(match.range(at: 0)) {
|
||||
allMatches.append((match.range(at: 0), "hashtag"))
|
||||
}
|
||||
for match in mentionMatches {
|
||||
allMatches.append((match.range(at: 0), "mention"))
|
||||
}
|
||||
for match in urlMatches where !overlapsMention(match.range) {
|
||||
allMatches.append((match.range, "url"))
|
||||
}
|
||||
for match in cashuMatches where !overlapsMention(match.range(at: 0)) {
|
||||
allMatches.append((match.range(at: 0), "cashu"))
|
||||
}
|
||||
for match in lightningMatches where !overlapsMention(match.range(at: 0)) {
|
||||
allMatches.append((match.range(at: 0), "lightning"))
|
||||
}
|
||||
|
||||
// Exclude overlaps with lightning/url for bolt11/lnurl
|
||||
let occupied: [NSRange] = urlMatches.map { $0.range } + lightningMatches.map { $0.range(at: 0) }
|
||||
func overlapsOccupied(_ r: NSRange) -> Bool {
|
||||
for or in occupied {
|
||||
if NSIntersectionRange(r, or).length > 0 { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
for match in bolt11Matches where !overlapsMention(match.range(at: 0)) && !overlapsOccupied(match.range(at: 0)) {
|
||||
allMatches.append((match.range(at: 0), "bolt11"))
|
||||
}
|
||||
for match in lnurlMatches where !overlapsMention(match.range(at: 0)) && !overlapsOccupied(match.range(at: 0)) {
|
||||
allMatches.append((match.range(at: 0), "lnurl"))
|
||||
}
|
||||
allMatches.sort { $0.range.location < $1.range.location }
|
||||
|
||||
// Build content with styling
|
||||
var processedContent = AttributedString()
|
||||
var lastEnd = content.startIndex
|
||||
let isMentioned = message.mentions?.contains(nickname) ?? false
|
||||
|
||||
for (range, type) in allMatches {
|
||||
if let nsRange = Range(range, in: content) {
|
||||
// Add text before match
|
||||
if lastEnd < nsRange.lowerBound {
|
||||
let beforeText = String(content[lastEnd..<nsRange.lowerBound])
|
||||
if !beforeText.isEmpty {
|
||||
var beforeStyle = AttributeContainer()
|
||||
beforeStyle.foregroundColor = baseColor
|
||||
beforeStyle.font = isSelf
|
||||
? .bitchatSystem(size: 14, weight: .bold, design: .monospaced)
|
||||
: .bitchatSystem(size: 14, design: .monospaced)
|
||||
if isMentioned {
|
||||
beforeStyle.font = beforeStyle.font?.bold()
|
||||
}
|
||||
processedContent.append(AttributedString(beforeText).mergingAttributes(beforeStyle))
|
||||
}
|
||||
}
|
||||
|
||||
// Add styled match
|
||||
let matchText = String(content[nsRange])
|
||||
processedContent.append(formatMatch(
|
||||
matchText,
|
||||
type: type,
|
||||
baseColor: baseColor,
|
||||
isSelf: isSelf,
|
||||
isDark: isDark,
|
||||
nickname: nickname,
|
||||
myPeerID: myPeerID,
|
||||
myNostrPubkey: myNostrPubkey,
|
||||
activeChannel: activeChannel
|
||||
))
|
||||
|
||||
lastEnd = nsRange.upperBound
|
||||
}
|
||||
}
|
||||
|
||||
// Add remaining text after last match
|
||||
if lastEnd < content.endIndex {
|
||||
let remainingText = String(content[lastEnd...])
|
||||
var remainingStyle = AttributeContainer()
|
||||
remainingStyle.foregroundColor = baseColor
|
||||
remainingStyle.font = isSelf
|
||||
? .bitchatSystem(size: 14, weight: .bold, design: .monospaced)
|
||||
: .bitchatSystem(size: 14, design: .monospaced)
|
||||
if isMentioned {
|
||||
remainingStyle.font = remainingStyle.font?.bold()
|
||||
}
|
||||
processedContent.append(AttributedString(remainingText).mergingAttributes(remainingStyle))
|
||||
}
|
||||
|
||||
return processedContent
|
||||
}
|
||||
|
||||
private func formatMatch(
|
||||
_ matchText: String,
|
||||
type: String,
|
||||
baseColor: Color,
|
||||
isSelf: Bool,
|
||||
isDark: Bool,
|
||||
nickname: String,
|
||||
myPeerID: String,
|
||||
myNostrPubkey: String?,
|
||||
activeChannel: ChannelID
|
||||
) -> AttributedString {
|
||||
switch type {
|
||||
case "mention":
|
||||
return formatMention(
|
||||
matchText,
|
||||
baseColor: baseColor,
|
||||
isSelf: isSelf,
|
||||
nickname: nickname,
|
||||
myPeerID: myPeerID,
|
||||
myNostrPubkey: myNostrPubkey,
|
||||
activeChannel: activeChannel
|
||||
)
|
||||
case "hashtag":
|
||||
return formatHashtag(matchText, isDark: isDark, baseColor: baseColor, activeChannel: activeChannel)
|
||||
case "url":
|
||||
return formatURL(matchText, baseColor: baseColor, isSelf: isSelf)
|
||||
case "cashu", "bolt11", "lnurl", "lightning":
|
||||
return formatPayment(matchText, type: type, baseColor: baseColor, isSelf: isSelf)
|
||||
default:
|
||||
return AttributedString(matchText)
|
||||
}
|
||||
}
|
||||
|
||||
private func formatMention(
|
||||
_ matchText: String,
|
||||
baseColor: Color,
|
||||
isSelf: Bool,
|
||||
nickname: String,
|
||||
myPeerID: String,
|
||||
myNostrPubkey: String?,
|
||||
activeChannel: ChannelID
|
||||
) -> AttributedString {
|
||||
// Split optional '#abcd' suffix and color suffix light grey
|
||||
let (mBase, mSuffix) = matchText.splitSuffix()
|
||||
|
||||
// Determine if this mention targets me
|
||||
let mySuffix: String? = {
|
||||
if case .location = activeChannel, let myGeo = myNostrPubkey {
|
||||
return String(myGeo.suffix(4))
|
||||
}
|
||||
return String(myPeerID.prefix(4))
|
||||
}()
|
||||
|
||||
let isMentionToMe: Bool = {
|
||||
if mBase == nickname {
|
||||
if let suf = mySuffix, !mSuffix.isEmpty {
|
||||
return mSuffix == "#\(suf)"
|
||||
}
|
||||
return mSuffix.isEmpty
|
||||
}
|
||||
return false
|
||||
}()
|
||||
|
||||
var mentionStyle = AttributeContainer()
|
||||
mentionStyle.font = .bitchatSystem(size: 14, weight: .semibold, design: .monospaced)
|
||||
mentionStyle.foregroundColor = isMentionToMe ? .orange : baseColor
|
||||
|
||||
var result = AttributedString()
|
||||
result.append(AttributedString(mBase).mergingAttributes(mentionStyle))
|
||||
|
||||
if !mSuffix.isEmpty {
|
||||
var suffixStyle = mentionStyle
|
||||
suffixStyle.foregroundColor = (isMentionToMe ? Color.orange : baseColor).opacity(0.5)
|
||||
result.append(AttributedString(mSuffix).mergingAttributes(suffixStyle))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
private func formatHashtag(
|
||||
_ matchText: String,
|
||||
isDark: Bool,
|
||||
baseColor: Color,
|
||||
activeChannel: ChannelID
|
||||
) -> AttributedString {
|
||||
var hashtagStyle = AttributeContainer()
|
||||
hashtagStyle.font = .bitchatSystem(size: 14, weight: .medium, design: .monospaced)
|
||||
|
||||
// Determine if this hashtag represents the active channel
|
||||
let isActiveChannel: Bool = {
|
||||
if matchText.count > 1 {
|
||||
let tag = String(matchText.dropFirst()) // Remove '#'
|
||||
switch activeChannel {
|
||||
case .mesh:
|
||||
return tag.lowercased() == "mesh"
|
||||
case .location(let ch):
|
||||
return tag.lowercased() == ch.geohash.lowercased()
|
||||
}
|
||||
}
|
||||
return false
|
||||
}()
|
||||
|
||||
if isActiveChannel {
|
||||
// Highlight active channel hashtag in green
|
||||
hashtagStyle.foregroundColor = isDark ? Color.green : Color(red: 0, green: 0.5, blue: 0)
|
||||
hashtagStyle.font = .bitchatSystem(size: 14, weight: .bold, design: .monospaced)
|
||||
} else {
|
||||
// Link to geohash if valid
|
||||
if matchText.count > 1 {
|
||||
let tag = String(matchText.dropFirst())
|
||||
if tag.count >= 2, tag.count <= 12,
|
||||
tag.allSatisfy({ "0123456789bcdefghjkmnpqrstuvwxyz".contains($0) }) {
|
||||
if let url = URL(string: "bitchat://geohash/\(tag)") {
|
||||
hashtagStyle.link = url
|
||||
}
|
||||
}
|
||||
}
|
||||
hashtagStyle.foregroundColor = baseColor.opacity(0.8)
|
||||
}
|
||||
|
||||
return AttributedString(matchText).mergingAttributes(hashtagStyle)
|
||||
}
|
||||
|
||||
private func formatURL(_ matchText: String, baseColor: Color, isSelf: Bool) -> AttributedString {
|
||||
var urlStyle = AttributeContainer()
|
||||
if let url = URL(string: matchText) {
|
||||
urlStyle.link = url
|
||||
}
|
||||
urlStyle.foregroundColor = baseColor
|
||||
urlStyle.font = isSelf
|
||||
? .bitchatSystem(size: 14, weight: .bold, design: .monospaced)
|
||||
: .bitchatSystem(size: 14, design: .monospaced)
|
||||
urlStyle.underlineStyle = .single
|
||||
return AttributedString(matchText).mergingAttributes(urlStyle)
|
||||
}
|
||||
|
||||
private func formatPayment(
|
||||
_ matchText: String,
|
||||
type: String,
|
||||
baseColor: Color,
|
||||
isSelf: Bool
|
||||
) -> AttributedString {
|
||||
var paymentStyle = AttributeContainer()
|
||||
paymentStyle.foregroundColor = baseColor
|
||||
paymentStyle.font = isSelf
|
||||
? .bitchatSystem(size: 14, weight: .bold, design: .monospaced)
|
||||
: .bitchatSystem(size: 14, design: .monospaced)
|
||||
|
||||
// Make payment tokens tappable
|
||||
if type == "cashu", let url = URL(string: "cashu:\(matchText)") {
|
||||
paymentStyle.link = url
|
||||
} else if type == "lightning" || type == "bolt11" || type == "lnurl" {
|
||||
if let url = URL(string: matchText.lowercased().hasPrefix("lightning:") ? matchText : "lightning:\(matchText)") {
|
||||
paymentStyle.link = url
|
||||
}
|
||||
}
|
||||
|
||||
return AttributedString(matchText).mergingAttributes(paymentStyle)
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,12 @@ final class NetworkActivationService: ObservableObject {
|
||||
|
||||
private init() {}
|
||||
|
||||
deinit {
|
||||
// Clean up Combine subscriptions
|
||||
cancellables.removeAll()
|
||||
SecureLogger.debug("NetworkActivationService deinitialized", category: .session)
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard !started else { return }
|
||||
started = true
|
||||
|
||||
@@ -27,6 +27,10 @@ final class PrivateChatManager: ObservableObject {
|
||||
self.meshService = meshService
|
||||
}
|
||||
|
||||
deinit {
|
||||
SecureLogger.debug("PrivateChatManager deinitialized", category: .session)
|
||||
}
|
||||
|
||||
// Cap for messages stored per private chat
|
||||
private let privateChatCap = TransportConfig.privateChatCap
|
||||
|
||||
|
||||
@@ -41,12 +41,6 @@ enum TransportConfig {
|
||||
static let uiLateInsertThresholdGeo: TimeInterval = 0.0
|
||||
static let uiProcessedNostrEventsCap: Int = 2000
|
||||
static let uiChannelInactivityThresholdSeconds: TimeInterval = 9 * 60
|
||||
|
||||
// UI rate limiters (token buckets)
|
||||
static let uiSenderRateBucketCapacity: Double = 5
|
||||
static let uiSenderRateBucketRefillPerSec: Double = 1.0
|
||||
static let uiContentRateBucketCapacity: Double = 3
|
||||
static let uiContentRateBucketRefillPerSec: Double = 0.5
|
||||
|
||||
// UI sleeps/delays
|
||||
static let uiStartupInitialDelaySeconds: TimeInterval = 1.0
|
||||
|
||||
@@ -46,7 +46,17 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate {
|
||||
updatePeers()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
deinit {
|
||||
// Clean up NotificationCenter observers
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
|
||||
// Clean up Combine subscriptions
|
||||
cancellables.removeAll()
|
||||
|
||||
SecureLogger.debug("UnifiedPeerService deinitialized", category: .session)
|
||||
}
|
||||
|
||||
// MARK: - Setup
|
||||
|
||||
private func setupSubscriptions() {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user