Compare commits

...
Author SHA1 Message Date
jack ef010dff37 Update Localizable.xcstrings with latest build changes 2025-10-18 21:10:44 +02:00
jack 8fbfa359ff Add Localizable strings for camera and voice features
Xcode auto-generated localization strings for new UI elements:
- Camera/photo picker labels
- Voice recording UI strings
- Media attachment descriptions

These are legitimate new strings needed for the audio+image feature,
not just formatting changes.
2025-10-18 20:29:33 +02:00
jack eeb4d55476 Add macOS photo picker support
- Added MacImagePickerView with NSOpenPanel for macOS
- macOS shows photo.circle.fill icon (no camera hardware)
- Opens native file picker for images (.png, .jpeg, .heic)
- Images processed through ImageUtils with EXIF stripping
- Simple sheet with Select/Cancel buttons

Cross-platform photo sharing now works:
- iOS: Tap for library, long-press for camera
- macOS: Tap for file picker
2025-10-18 15:04:13 +02:00
jack 4882b99752 Remove Localizable.xcstrings formatting noise
The Localizable.xcstrings file had massive formatting-only changes
(spacing: 'key' vs 'key :') that added 50K+ lines to the PR diff.

This was just Xcode reformatting with no actual string changes.

Reverted to main's version to keep PR focused on actual code changes.
2025-10-18 14:54:22 +02:00
jack 9b8498c78e Fix critical thread-safety crash in PeerID fragment handler
CRITICAL: The PeerID version of _handleFragment was accessing
incomingFragments dictionary without collectionsQueue synchronization,
causing crashes when multiple BLE threads processed fragments concurrently.

Crash stack trace pointed to line 3431 (dictionary subscript) with:
'doesNotRecognizeSelector' - classic concurrent mutation crash.

Fix:
- Wrapped ALL incomingFragments/fragmentMetadata access in
  collectionsQueue.sync(flags: .barrier)
- Matches the thread-safe pattern used in String version
- Separate cleanup into its own barrier block after reassembly
- Prevents concurrent dictionary mutations from multiple BLE threads

This is the same pattern as the String version (line 1128) which didn't crash.
2025-10-18 14:50:25 +02:00
jack 1cf8449e22 Fix decompression size limit to support max-sized file transfers
Root cause: BinaryProtocol.decode() was rejecting decompressed payloads
larger than maxPayloadBytes (1 MB), but TLV-encoded file transfers are
slightly larger due to metadata overhead.

Fixes:
- Changed decompression limit from maxPayloadBytes to maxFramedFileBytes
- This accounts for TLV overhead (~50 bytes) + binary protocol headers
- Now allows ~1.12 MB decompressed payloads (1 MB + overhead budget)

The failing test was:
- Creating 1 MB file content
- TLV encoding adds ~50 bytes (1,048,627 total)
- Compression reduces to ~1,084 bytes (highly repetitive data)
- During decode, decompression was rejecting the 1,048,627 byte output
- Now correctly allows it since 1,048,627 < 1,179,760 (maxFramedFileBytes)

All 154 tests now pass including 'Max-sized file transfer survives reassembly'
2025-10-18 14:47:43 +02:00
jack 7ca1ff0a7e Fix P1: Add DoS protections to PeerID fragment handler
Critical security fix addressing Codex review feedback:

The PeerID overload of handleFragment (which is actually called by
CoreBluetooth) was missing key safety checks that existed in the
String overload:

1. Added total <= 10000 check to prevent unbounded fragment counts
2. Added cumulative size check against FileTransferLimits before
   storing each fragment
3. Prevents memory exhaustion DoS attacks via malicious fragment streams

This ensures the actually-used code path has proper bounds checking.
2025-10-18 14:24:56 +02:00
jack 7316a4a46d Optimize sheet presentation for camera UI
- Force .large detent for maximum height
- Hide drag indicator for cleaner look
- Use ignoresSafeArea to give camera full space
- Should show complete flash button and controls
2025-10-18 14:23:04 +02:00
jack e992d96939 Force dark mode on camera/picker for black safe area bars
- Set overrideUserInterfaceStyle = .dark on UIImagePickerController
- Changes white bars to black (much better looking)
- Camera controls and photo library also appear in dark mode
- Consistent dark appearance regardless of system settings
2025-10-18 14:12:51 +02:00
jack e427e1c62f Simplify camera presentation to reduce frame errors
- Changed back to standard .fullScreen presentation
- Removed overFullScreen which was causing frame dimension errors
- Let iOS handle safe areas automatically (white bars are intentional)
- Reduces gesture gate timeout warnings

Note: White bars on notched devices are iOS default behavior for
UIImagePickerController. This respects safe areas for status bar
and home indicator. True edge-to-edge would require custom AVFoundation
camera implementation.
2025-10-18 14:11:02 +02:00
jack fae76dc515 Gesture-based photo access: Tap for library, long-press for camera
UX improvements:
- Tap camera icon → Photo library (common use case)
- Long press camera icon (0.3s) → Direct camera (quick photos)
- Removed action sheet entirely for cleaner flow
- Power users can long-press for instant camera access

This is more discoverable and eliminates an extra step in the UI.
2025-10-18 13:57:38 +02:00
jack 76f976438f Fix camera white bars with overFullScreen presentation
- Changed modalPresentationStyle from .fullScreen to .overFullScreen
- This should eliminate white bars at top/bottom on notched devices
- Explicitly set showsCameraControls and cameraOverlayView for camera mode
2025-10-18 13:55:44 +02:00
jack 369c335088 Full-screen camera with photo library option
- Change to fullScreenCover for immersive camera experience
- Add action sheet with 'Take Photo' and 'Choose from Library' options
- Renamed ImagePickerView to support both camera and library sources
- Both options open full-screen for better UX
- Updated accessibility label to 'Add photo' (more accurate)
2025-10-18 13:52:02 +02:00
jack a84b8c05f1 Improve camera UX: Direct camera access with camera icon
- Change paperclip icon to camera icon for clearer affordance
- Open camera directly on tap (no confirmation dialog)
- Add CameraPickerView wrapper for UIImagePickerController
- Remove PhotosPicker in favor of direct camera access
- Images still processed through ImageUtils with EXIF stripping
- Accessibility: Added 'Take photo' label
2025-10-18 13:45:04 +02:00
jack 9d738cff45 Simplify PR: Focus on audio+image, fix EXIF stripping, remove file transfers
- Fix critical EXIF privacy issue in iOS image processing
  - Both iOS and macOS now use CGImageDestination for metadata stripping
  - Shared encodeJPEG function ensures no GPS, camera, or metadata leaks

- Remove file transfer functionality to simplify PR scope
  - Deleted FileAttachmentView
  - Removed sendFileAttachment from ChatViewModel
  - Removed file picker UI from ContentView
  - Simplified attachment dialog to image only (iOS) or voice only

- Keep focused media features:
  - Voice recording and playback
  - Image sending with progressive reveal
  - Binary protocol for media transfer
2025-10-18 13:35:14 +02:00
jack 9879cb2580 Merge branch 'main' into feature/ble-binary-transfers
# Conflicts:
#	bitchat/Views/ContentView.swift
2025-10-18 13:24:05 +02:00
7040d9ecb0 Add plus-minus feature to location notes (± 1 grid) (#821)
Expands location notes coverage to include 8 neighboring geohash cells,
creating a 3×3 grid around the user's current building-level location.

Changes:
- Add Geohash.neighbors() method to calculate 8 surrounding cells
- Update LocationNotesManager to subscribe to center + neighbors (9 cells total)
- Add NostrFilter.geohashNotes([String]) overload for multi-cell subscriptions
- Display '± 1' indicator in LocationNotesView header

Coverage:
- Single cell: ~38m × 19m
- 3×3 grid: ~114m × 57m total area
- Better discovery of nearby activity

Behavior:
- Subscribe: Fetches notes from all 9 cells (single efficient subscription)
- Post: Still uses center geohash only (correct privacy-preserving behavior)
- UI: Shows 'geohash ± 1' to indicate expanded coverage

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
2025-10-18 12:44:06 +02:00
88bafb41cc Remove LocationNotesCounter for privacy-first approach (#820)
Simplifies geonotes architecture by eliminating all background subscriptions:

- Delete LocationNotesCounter.swift (104 lines) and related tests (58 lines)
- Remove background subscription system entirely
- Icon is now constant darker orange (indicates availability, not state)
- Subscription ONLY happens when user explicitly opens the sheet
- Total: ~220 lines of code removed

Privacy Benefits:
- Zero network traffic until user action
- No location leaking to relays via background polling
- User must explicitly opt-in to discover notes

The icon (note.text in orange) simply indicates the feature is available
when location permission is granted. Notes are only fetched when the
sheet is opened, prioritizing privacy over convenience.

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
2025-10-18 12:06:31 +02:00
13 changed files with 24119 additions and 24539 deletions
+43 -7
View File
@@ -1,10 +1,10 @@
import Foundation import Foundation
import ImageIO
import UniformTypeIdentifiers
#if os(iOS) #if os(iOS)
import UIKit import UIKit
#else #else
import AppKit import AppKit
import ImageIO
import UniformTypeIdentifiers
#endif #endif
enum ImageUtilsError: Error { enum ImageUtilsError: Error {
@@ -40,19 +40,30 @@ enum ImageUtils {
#if os(iOS) #if os(iOS)
static func processImage(_ image: UIImage, maxDimension: CGFloat = 512) throws -> URL { static func processImage(_ image: UIImage, maxDimension: CGFloat = 512) throws -> URL {
return try autoreleasepool { return try autoreleasepool {
// Scale the image first
let scaled = scaledImage(image, maxDimension: maxDimension) let scaled = scaledImage(image, maxDimension: maxDimension)
var quality = compressionQuality
guard var jpegData = scaled.jpegData(compressionQuality: quality) else { // Get CGImage from UIImage - this is the key to stripping metadata
guard let cgImage = scaled.cgImage else {
throw ImageUtilsError.encodingFailed throw ImageUtilsError.encodingFailed
} }
// Use CGImageDestination to encode without metadata (same as macOS)
var quality = compressionQuality
guard var jpegData = encodeJPEG(from: cgImage, quality: quality) else {
throw ImageUtilsError.encodingFailed
}
// Compress to target size
while jpegData.count > targetImageBytes && quality > 0.3 { while jpegData.count > targetImageBytes && quality > 0.3 {
quality -= 0.1 quality -= 0.1
autoreleasepool { autoreleasepool {
if let next = scaled.jpegData(compressionQuality: quality) { if let next = encodeJPEG(from: cgImage, quality: quality) {
jpegData = next jpegData = next
} }
} }
} }
let outputURL = try makeOutputURL() let outputURL = try makeOutputURL()
try jpegData.write(to: outputURL, options: .atomic) try jpegData.write(to: outputURL, options: .atomic)
return outputURL return outputURL
@@ -65,12 +76,35 @@ enum ImageUtils {
guard maxSide > maxDimension else { return image } guard maxSide > maxDimension else { return image }
let scale = maxDimension / maxSide let scale = maxDimension / maxSide
let newSize = CGSize(width: size.width * scale, height: size.height * scale) let newSize = CGSize(width: size.width * scale, height: size.height * scale)
// Draw into a new context to get a clean CGImage without metadata
UIGraphicsBeginImageContextWithOptions(newSize, true, 1.0) UIGraphicsBeginImageContextWithOptions(newSize, true, 1.0)
image.draw(in: CGRect(origin: .zero, size: newSize)) image.draw(in: CGRect(origin: .zero, size: newSize))
let rendered = UIGraphicsGetImageFromCurrentImageContext() let rendered = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext() UIGraphicsEndImageContext()
return rendered ?? image return rendered ?? image
} }
// Shared EXIF-stripping JPEG encoder for both iOS and macOS
private static func encodeJPEG(from cgImage: CGImage, quality: CGFloat) -> Data? {
guard let data = CFDataCreateMutable(nil, 0) else {
return nil
}
guard let destination = CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil) else {
return nil
}
// Security: Strip ALL metadata (EXIF, GPS, TIFF, IPTC, XMP)
// By only specifying compression quality and no metadata keys,
// we ensure a clean JPEG with no privacy-leaking information
let options: [CFString: Any] = [
kCGImageDestinationLossyCompressionQuality: quality
]
CGImageDestinationAddImage(destination, cgImage, options as CFDictionary)
guard CGImageDestinationFinalize(destination) else {
return nil
}
return data as Data
}
#else #else
static func processImage(_ image: NSImage, maxDimension: CGFloat = 512) throws -> URL { static func processImage(_ image: NSImage, maxDimension: CGFloat = 512) throws -> URL {
return try autoreleasepool { return try autoreleasepool {
@@ -130,6 +164,7 @@ enum ImageUtils {
return scaledImage return scaledImage
} }
// Shared EXIF-stripping JPEG encoder for both iOS and macOS
private static func encodeJPEG(from cgImage: CGImage, quality: CGFloat) -> Data? { private static func encodeJPEG(from cgImage: CGImage, quality: CGFloat) -> Data? {
guard let data = CFDataCreateMutable(nil, 0) else { guard let data = CFDataCreateMutable(nil, 0) else {
return nil return nil
@@ -137,8 +172,9 @@ enum ImageUtils {
guard let destination = CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil) else { guard let destination = CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil) else {
return nil return nil
} }
// Security H2: Strip ALL metadata (EXIF, GPS, TIFF, IPTC, XMP) // Security: Strip ALL metadata (EXIF, GPS, TIFF, IPTC, XMP)
// Don't add any metadata dictionary keys - fresh CGContext ensures clean image // By only specifying compression quality and no metadata keys,
// we ensure a clean JPEG with no privacy-leaking information
let options: [CFString: Any] = [ let options: [CFString: Any] = [
kCGImageDestinationLossyCompressionQuality: quality kCGImageDestinationLossyCompressionQuality: quality
] ]
+23775 -23987
View File
File diff suppressed because it is too large Load Diff
+10
View File
@@ -906,6 +906,16 @@ struct NostrFilter: Encodable {
filter.limit = limit filter.limit = limit
return filter return filter
} }
// For location notes with neighbors: subscribe to multiple geohashes (center + neighbors)
static func geohashNotes(_ geohashes: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter {
var filter = NostrFilter()
filter.kinds = [1]
filter.since = since?.timeIntervalSince1970.toInt()
filter.tagFilters = ["g": geohashes]
filter.limit = limit
return filter
}
} }
// Dynamic coding key for tag filters // Dynamic coding key for tag filters
+2 -1
View File
@@ -333,7 +333,8 @@ struct BinaryProtocol {
originalSize = Int(rawSize) originalSize = Int(rawSize)
} }
// Guard to keep decompression bounded to sane BLE payload limits // Guard to keep decompression bounded to sane BLE payload limits
guard originalSize >= 0 && originalSize <= FileTransferLimits.maxPayloadBytes else { return nil } // Use maxFramedFileBytes to account for TLV overhead in file transfer payloads
guard originalSize >= 0 && originalSize <= FileTransferLimits.maxFramedFileBytes else { return nil }
let compressedSize = payloadLength - lengthFieldBytes let compressedSize = payloadLength - lengthFieldBytes
guard compressedSize >= 0, let compressed = readData(compressedSize) else { return nil } guard compressedSize >= 0, let compressed = readData(compressedSize) else { return nil }
+53
View File
@@ -119,4 +119,57 @@ enum Geohash {
} }
return (latInterval.0, latInterval.1, lonInterval.0, lonInterval.1) return (latInterval.0, latInterval.1, lonInterval.0, lonInterval.1)
} }
/// Returns all 8 neighboring geohash cells at the same precision.
/// - Parameter geohash: Base32 geohash string.
/// - Returns: Array of 8 neighboring geohashes (N, NE, E, SE, S, SW, W, NW order).
static func neighbors(of geohash: String) -> [String] {
guard !geohash.isEmpty else { return [] }
let precision = geohash.count
let bounds = decodeBounds(geohash)
let center = decodeCenter(geohash)
// Calculate cell dimensions
let latHeight = bounds.latMax - bounds.latMin
let lonWidth = bounds.lonMax - bounds.lonMin
// Helper to wrap longitude around ±180
func wrapLongitude(_ lon: Double) -> Double {
var wrapped = lon
while wrapped > 180.0 { wrapped -= 360.0 }
while wrapped < -180.0 { wrapped += 360.0 }
return wrapped
}
// Helper to clamp latitude to ±90
func clampLatitude(_ lat: Double) -> Double {
return max(-90.0, min(90.0, lat))
}
// Calculate 8 neighbor centers
let neighbors: [(lat: Double, lon: Double)] = [
(center.lat + latHeight, center.lon), // N
(center.lat + latHeight, center.lon + lonWidth), // NE
(center.lat, center.lon + lonWidth), // E
(center.lat - latHeight, center.lon + lonWidth), // SE
(center.lat - latHeight, center.lon), // S
(center.lat - latHeight, center.lon - lonWidth), // SW
(center.lat, center.lon - lonWidth), // W
(center.lat + latHeight, center.lon - lonWidth) // NW
]
// Encode each neighbor, handling boundary conditions
return neighbors.compactMap { neighbor in
let lat = clampLatitude(neighbor.lat)
let lon = wrapLongitude(neighbor.lon)
// Skip if we've crossed a pole (latitude clamped to boundary)
if (neighbor.lat > 90.0 || neighbor.lat < -90.0) {
return nil
}
return encode(latitude: lat, longitude: lon, precision: precision)
}
}
} }
+72 -32
View File
@@ -3395,7 +3395,7 @@ extension BLEService {
if peerID == myPeerID { if peerID == myPeerID {
return return
} }
// Minimum header: 8 bytes ID + 2 index + 2 total + 1 type // Minimum header: 8 bytes ID + 2 index + 2 total + 1 type
guard packet.payload.count >= 13 else { return } guard packet.payload.count >= 13 else { return }
@@ -3414,44 +3414,84 @@ extension BLEService {
let originalType = packet.payload[12] let originalType = packet.payload[12]
let fragmentData = packet.payload.suffix(from: 13) let fragmentData = packet.payload.suffix(from: 13)
// Sanity checks // Sanity checks - add reasonable upper bound on total to prevent DoS
guard total > 0 && index >= 0 && index < total else { return } guard total > 0 && total <= 10000 && index >= 0 && index < total else { return }
// Store fragment // Compute fragment key for this assembly
let key = FragmentKey(sender: senderU64, id: fragU64) let key = FragmentKey(sender: senderU64, id: fragU64)
if incomingFragments[key] == nil {
// Cap in-flight assemblies to prevent memory/battery blowups
if incomingFragments.count >= maxInFlightAssemblies {
// Evict the oldest assembly by timestamp
if let oldest = fragmentMetadata.min(by: { $0.value.timestamp < $1.value.timestamp })?.key {
incomingFragments.removeValue(forKey: oldest)
fragmentMetadata.removeValue(forKey: oldest)
}
}
incomingFragments[key] = [:]
fragmentMetadata[key] = (originalType, total, Date())
}
incomingFragments[key]?[index] = Data(fragmentData)
// Check if complete // Critical section: Store fragment and check completion status
if let fragments = incomingFragments[key], var shouldReassemble: Bool = false
fragments.count == total { var fragmentsToReassemble: [Int: Data]? = nil
// Reassemble
var reassembled = Data() collectionsQueue.sync(flags: .barrier) {
for i in 0..<total { if incomingFragments[key] == nil {
if let fragment = fragments[i] { // Cap in-flight assemblies to prevent memory/battery blowups
reassembled.append(fragment) if incomingFragments.count >= maxInFlightAssemblies {
// Evict the oldest assembly by timestamp
if let oldest = fragmentMetadata.min(by: { $0.value.timestamp < $1.value.timestamp })?.key {
incomingFragments.removeValue(forKey: oldest)
fragmentMetadata.removeValue(forKey: oldest)
}
} }
incomingFragments[key] = [:]
fragmentMetadata[key] = (originalType, total, Date())
} }
// Decode the original packet bytes we reassembled, so flags/compression are preserved // Check cumulative size before storing this fragment
if let originalPacket = BinaryProtocol.decode(reassembled) { let currentSize = incomingFragments[key]?.values.reduce(0) { $0 + $1.count } ?? 0
handleReceivedPacket(originalPacket, from: peerID) let assemblyLimit: Int = {
if originalType == MessageType.fileTransfer.rawValue {
// Allow headroom for TLV metadata and binary framing overhead.
return FileTransferLimits.maxFramedFileBytes
}
return FileTransferLimits.maxPayloadBytes
}()
let projectedSize = currentSize + fragmentData.count
guard projectedSize <= assemblyLimit else {
// Exceeds size limit - evict this assembly
SecureLogger.warning(
"🚫 Fragment assembly exceeds size limit (\(projectedSize) bytes > \(assemblyLimit)), evicting. Type=\(originalType) Index=\(index)/\(total)",
category: .security
)
incomingFragments.removeValue(forKey: key)
fragmentMetadata.removeValue(forKey: key)
shouldReassemble = false
fragmentsToReassemble = nil
return
}
incomingFragments[key]?[index] = Data(fragmentData)
// Check if complete
if let fragments = incomingFragments[key], fragments.count == total {
shouldReassemble = true
fragmentsToReassemble = fragments
} else { } else {
SecureLogger.error("❌ Failed to decode reassembled packet (type=\(originalType), total=\(total))", category: .session) shouldReassemble = false
fragmentsToReassemble = nil
} }
}
// Cleanup
// Heavy work outside lock: reassemble and decode
guard shouldReassemble, let fragments = fragmentsToReassemble else { return }
var reassembled = Data()
for i in 0..<total {
if let fragment = fragments[i] {
reassembled.append(fragment)
}
}
// Decode the original packet bytes we reassembled, so flags/compression are preserved
if let originalPacket = BinaryProtocol.decode(reassembled) {
handleReceivedPacket(originalPacket, from: peerID)
} else {
SecureLogger.error("❌ Failed to decode reassembled packet (type=\(originalType), total=\(total))", category: .session)
}
// Critical section: Cleanup completed assembly
collectionsQueue.sync(flags: .barrier) {
incomingFragments.removeValue(forKey: key) incomingFragments.removeValue(forKey: key)
fragmentMetadata.removeValue(forKey: key) fragmentMetadata.removeValue(forKey: key)
} }
-104
View File
@@ -1,104 +0,0 @@
import BitLogger
import Foundation
struct LocationNotesCounterDependencies {
typealias RelayLookup = @MainActor (_ geohash: String, _ count: Int) -> [String]
typealias Subscribe = @MainActor (_ filter: NostrFilter, _ id: String, _ relays: [String], _ handler: @escaping (NostrEvent) -> Void, _ onEOSE: (() -> Void)?) -> Void
typealias Unsubscribe = @MainActor (_ id: String) -> Void
var relayLookup: RelayLookup
var subscribe: Subscribe
var unsubscribe: Unsubscribe
static let live = LocationNotesCounterDependencies(
relayLookup: { geohash, count in
GeoRelayDirectory.shared.closestRelays(toGeohash: geohash, count: count)
},
subscribe: { filter, id, relays, handler, onEOSE in
NostrRelayManager.shared.subscribe(
filter: filter,
id: id,
relayUrls: relays,
handler: handler,
onEOSE: onEOSE
)
},
unsubscribe: { id in
NostrRelayManager.shared.unsubscribe(id: id)
}
)
}
/// Lightweight background counter for location notes (kind 1) at building-level geohash (8 chars).
@MainActor
final class LocationNotesCounter: ObservableObject {
static let shared = LocationNotesCounter()
@Published private(set) var geohash: String? = nil
@Published private(set) var count: Int? = 0
@Published private(set) var initialLoadComplete: Bool = false
@Published private(set) var relayAvailable: Bool = true
private var subscriptionID: String? = nil
private var noteIDs = Set<String>()
private let dependencies: LocationNotesCounterDependencies
private init(dependencies: LocationNotesCounterDependencies = .live) {
self.dependencies = dependencies
}
init(testDependencies: LocationNotesCounterDependencies) {
self.dependencies = testDependencies
}
func subscribe(geohash gh: String) {
let norm = gh.lowercased()
if geohash == norm, subscriptionID != nil { return }
// Validate geohash (building-level precision: 8 chars)
guard Geohash.isValidBuildingGeohash(norm) else {
SecureLogger.warning("LocationNotesCounter: rejecting invalid geohash '\(norm)' (expected 8 valid base32 chars)", category: .session)
return
}
// Unsubscribe previous without clearing count to avoid flicker
if let sub = subscriptionID { dependencies.unsubscribe(sub) }
subscriptionID = nil
geohash = norm
noteIDs.removeAll()
initialLoadComplete = false
relayAvailable = true
// Subscribe only to the building geohash (precision 8)
let subID = "locnotes-count-\(norm)-\(UUID().uuidString.prefix(6))"
let relays = dependencies.relayLookup(norm, TransportConfig.nostrGeoRelayCount)
guard !relays.isEmpty else {
relayAvailable = false
initialLoadComplete = true
count = 0
SecureLogger.warning("LocationNotesCounter: no geo relays for geohash=\(norm)", category: .session)
return
}
subscriptionID = subID
let filter = NostrFilter.geohashNotes(norm, since: nil, limit: 200)
dependencies.subscribe(filter, subID, relays, { [weak self] event in
guard let self = self else { return }
guard event.kind == NostrProtocol.EventKind.textNote.rawValue else { return }
guard event.tags.contains(where: { $0.count >= 2 && $0[0].lowercased() == "g" && $0[1].lowercased() == norm }) else { return }
if !self.noteIDs.contains(event.id) {
self.noteIDs.insert(event.id)
self.count = self.noteIDs.count
}
}, { [weak self] in
self?.initialLoadComplete = true
})
}
func cancel() {
if let sub = subscriptionID { dependencies.unsubscribe(sub) }
subscriptionID = nil
geohash = nil
count = 0
noteIDs.removeAll()
relayAvailable = true
}
}
+12 -4
View File
@@ -163,14 +163,22 @@ final class LocationNotesManager: ObservableObject {
subscriptionID = subID subscriptionID = subID
initialLoadComplete = false initialLoadComplete = false
// For persistent notes, allow relays to return recent history without an aggressive time cutoff
let filter = NostrFilter.geohashNotes(geohash, since: nil, limit: 200) // Subscribe to center + 8 neighbors (± 1 grid)
let neighbors = Geohash.neighbors(of: geohash)
let allGeohashes = [geohash] + neighbors
let filter = NostrFilter.geohashNotes(allGeohashes, since: nil, limit: 200)
// Build a set of valid geohashes for tag matching (includes all 9 cells)
let validGeohashes = Set(allGeohashes.map { $0.lowercased() })
dependencies.subscribe(filter, subID, relays, { [weak self] event in dependencies.subscribe(filter, subID, relays, { [weak self] event in
guard let self = self else { return } guard let self = self else { return }
guard event.kind == NostrProtocol.EventKind.textNote.rawValue else { return } guard event.kind == NostrProtocol.EventKind.textNote.rawValue else { return }
// Ensure matching tag // Ensure matching tag - accept any of our 9 geohashes
guard event.tags.contains(where: { $0.count >= 2 && $0[0].lowercased() == "g" && $0[1].lowercased() == self.geohash }) else { return } guard event.tags.contains(where: { tag in
tag.count >= 2 && tag[0].lowercased() == "g" && validGeohashes.contains(tag[1].lowercased())
}) else { return }
guard !self.noteIDs.contains(event.id) else { return } guard !self.noteIDs.contains(event.id) else { return }
self.noteIDs.insert(event.id) self.noteIDs.insert(event.id)
let nick = event.tags.first(where: { $0.first?.lowercased() == "n" && $0.count >= 2 })?.dropFirst().first let nick = event.tags.first(where: { $0.first?.lowercased() == "n" && $0.count >= 2 })?.dropFirst().first
-108
View File
@@ -2503,65 +2503,6 @@ final class ChatViewModel: ObservableObject, BitchatDelegate {
} }
} }
@MainActor
func sendFileAttachment(from sourceURL: URL) {
let targetPeer = selectedPrivateChatPeer
Task.detached(priority: .userInitiated) { [weak self] in
guard let self = self else { return }
defer { try? FileManager.default.removeItem(at: sourceURL) }
var destinationURL: URL?
do {
// Security H1: Check file size BEFORE reading into memory
let attrs = try FileManager.default.attributesOfItem(atPath: sourceURL.path)
guard let fileSize = attrs[.size] as? Int else {
throw MediaSendError.encodingFailed
}
guard FileTransferLimits.isValidPayload(fileSize) else {
throw MediaSendError.tooLarge
}
let data = try Data(contentsOf: sourceURL)
let destination = try self.prepareOutgoingFileCopy(from: sourceURL, data: data)
destinationURL = destination
let packet = BitchatFilePacket(
fileName: destination.lastPathComponent,
fileSize: UInt64(data.count),
mimeType: self.mimeType(for: destination),
content: data
)
guard packet.encode() != nil else {
try? FileManager.default.removeItem(at: destination)
throw MediaSendError.encodingFailed
}
await MainActor.run {
let message = self.enqueueMediaMessage(content: "[file] \(destination.lastPathComponent)", targetPeer: targetPeer?.id)
let messageID = message.id
let transferId = self.makeTransferID(messageID: messageID)
self.registerTransfer(transferId: transferId, messageID: messageID)
if let peerID = targetPeer {
self.meshService.sendFilePrivate(packet, to: peerID, transferId: transferId)
} else {
self.meshService.sendFileBroadcast(packet, transferId: transferId)
}
}
} catch MediaSendError.tooLarge {
await MainActor.run {
self.addSystemMessage("File is too large to send.")
}
} catch {
if let destination = destinationURL {
try? FileManager.default.removeItem(at: destination)
}
SecureLogger.error("File attachment send failed: \(error)", category: .session)
await MainActor.run {
self.addSystemMessage("Failed to send file.")
}
}
}
}
@MainActor @MainActor
func cancelMediaSend(messageID: String) { func cancelMediaSend(messageID: String) {
@@ -2748,55 +2689,6 @@ final class ChatViewModel: ObservableObject, BitchatDelegate {
} }
} }
private func prepareOutgoingFileCopy(from sourceURL: URL, data: Data) throws -> URL {
let base = try applicationFilesDirectory().appendingPathComponent("files/outgoing", isDirectory: true)
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true, attributes: nil)
let rawName = sourceURL.lastPathComponent
let sanitized = sanitizeOutgoingFileName(rawName.isEmpty ? "file" : rawName)
var destination = base.appendingPathComponent(sanitized)
var counter = 1
while FileManager.default.fileExists(atPath: destination.path) {
let baseName = (sanitized as NSString).deletingPathExtension
let ext = (sanitized as NSString).pathExtension
let newName: String
if ext.isEmpty {
newName = "\(baseName) (\(counter))"
} else {
newName = "\(baseName) (\(counter)).\(ext)"
}
destination = base.appendingPathComponent(newName)
counter += 1
}
try data.write(to: destination, options: .atomic)
return destination
}
private func sanitizeOutgoingFileName(_ name: String) -> String {
var candidate = name
candidate = candidate.replacingOccurrences(of: "\\", with: "/")
candidate = candidate.components(separatedBy: "/").last ?? name
candidate = candidate.trimmingCharacters(in: .whitespacesAndNewlines)
if candidate.isEmpty { candidate = "file" }
let invalid = CharacterSet(charactersIn: "<>:\"|?*")
candidate = candidate.components(separatedBy: invalid).joined(separator: "_")
if candidate.isEmpty { candidate = "file" }
if (candidate as NSString).pathExtension.isEmpty {
candidate += ".bin"
}
return candidate
}
private func mimeType(for url: URL) -> String {
let ext = url.pathExtension.lowercased()
if !ext.isEmpty,
let type = UTType(filenameExtension: ext),
let mime = type.preferredMIMEType {
return mime
}
return "application/octet-stream"
}
private func applicationFilesDirectory() throws -> URL { private func applicationFilesDirectory() throws -> URL {
let base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
+151 -119
View File
@@ -15,9 +15,6 @@ import AppKit
#endif #endif
import UniformTypeIdentifiers import UniformTypeIdentifiers
import BitLogger import BitLogger
#if canImport(PhotosUI)
import PhotosUI
#endif
// MARK: - Supporting Types // MARK: - Supporting Types
@@ -38,7 +35,6 @@ struct ContentView: View {
@EnvironmentObject var viewModel: ChatViewModel @EnvironmentObject var viewModel: ChatViewModel
@ObservedObject private var locationManager = LocationChannelManager.shared @ObservedObject private var locationManager = LocationChannelManager.shared
@ObservedObject private var bookmarks = GeohashBookmarksStore.shared @ObservedObject private var bookmarks = GeohashBookmarksStore.shared
@ObservedObject private var notesCounter = LocationNotesCounter.shared
@State private var messageText = "" @State private var messageText = ""
@FocusState private var isTextFieldFocused: Bool @FocusState private var isTextFieldFocused: Bool
@Environment(\.colorScheme) var colorScheme @Environment(\.colorScheme) var colorScheme
@@ -72,12 +68,12 @@ struct ContentView: View {
@State private var recordingDuration: TimeInterval = 0 @State private var recordingDuration: TimeInterval = 0
@State private var recordingTimer: Timer? @State private var recordingTimer: Timer?
@State private var recordingStartDate: Date? @State private var recordingStartDate: Date?
@State private var showFileImporter = false
#if os(iOS) #if os(iOS)
@State private var showPhotoPicker = false @State private var showImagePicker = false
@State private var selectedPhotoPickerItem: PhotosPickerItem? @State private var imagePickerSourceType: UIImagePickerController.SourceType = .camera
#else
@State private var showMacImagePicker = false
#endif #endif
@State private var showAttachmentActions = false
@ScaledMetric(relativeTo: .body) private var headerHeight: CGFloat = 44 @ScaledMetric(relativeTo: .body) private var headerHeight: CGFloat = 44
@ScaledMetric(relativeTo: .subheadline) private var headerPeerIconSize: CGFloat = 11 @ScaledMetric(relativeTo: .subheadline) private var headerPeerIconSize: CGFloat = 11
@ScaledMetric(relativeTo: .subheadline) private var headerPeerCountFontSize: CGFloat = 12 @ScaledMetric(relativeTo: .subheadline) private var headerPeerCountFontSize: CGFloat = 12
@@ -211,15 +207,46 @@ struct ContentView: View {
} }
} }
#if os(iOS) #if os(iOS)
.photosPicker(isPresented: $showPhotoPicker, selection: $selectedPhotoPickerItem, matching: .images) .sheet(isPresented: $showImagePicker) {
.onChange(of: selectedPhotoPickerItem) { newItem in ImagePickerView(sourceType: imagePickerSourceType) { image in
guard let item = newItem else { return } showImagePicker = false
Task { await handlePhotoSelection(item) } if let image = image {
Task {
do {
let processedURL = try ImageUtils.processImage(image)
await MainActor.run {
viewModel.sendImage(from: processedURL)
}
} catch {
SecureLogger.error("Image processing failed: \(error)", category: .session)
}
}
}
}
.presentationDetents([.large])
.presentationDragIndicator(.hidden)
.ignoresSafeArea()
} }
#endif #endif
.fileImporter(isPresented: $showFileImporter, allowedContentTypes: [.data], allowsMultipleSelection: false) { result in #if os(macOS)
handleImportResult(result, handler: handleImportedFile) .sheet(isPresented: $showMacImagePicker) {
MacImagePickerView { url in
showMacImagePicker = false
if let url = url {
Task {
do {
let processedURL = try ImageUtils.processImage(at: url)
await MainActor.run {
viewModel.sendImage(from: processedURL)
}
} catch {
SecureLogger.error("Image processing failed: \(error)", category: .session)
}
}
}
}
} }
#endif
.sheet(isPresented: Binding( .sheet(isPresented: Binding(
get: { imagePreviewURL != nil }, get: { imagePreviewURL != nil },
set: { presenting in if !presenting { imagePreviewURL = nil } } set: { presenting in if !presenting { imagePreviewURL = nil } }
@@ -228,19 +255,6 @@ struct ContentView: View {
ImagePreviewView(url: url) ImagePreviewView(url: url)
} }
} }
.confirmationDialog("Attach", isPresented: $showAttachmentActions, titleVisibility: .visible) {
#if os(iOS)
Button("Image") {
showAttachmentActions = false
DispatchQueue.main.async { showPhotoPicker = true }
}
#endif
Button("File") {
showAttachmentActions = false
DispatchQueue.main.async { showFileImporter = true }
}
Button("Cancel", role: .cancel) {}
}
.alert("Recording Error", isPresented: $showRecordingAlert, actions: { .alert("Recording Error", isPresented: $showRecordingAlert, actions: {
Button("OK", role: .cancel) {} Button("OK", role: .cancel) {}
}, message: { }, message: {
@@ -1349,10 +1363,9 @@ struct ContentView: View {
showLocationNotes = true showLocationNotes = true
}) { }) {
HStack(alignment: .center, spacing: 4) { HStack(alignment: .center, spacing: 4) {
let hasNotes = (notesCounter.count ?? 0) > 0 Image(systemName: "note.text")
Image(systemName: "long.text.page.and.pencil")
.font(.bitchatSystem(size: 12)) .font(.bitchatSystem(size: 12))
.foregroundColor(hasNotes ? textColor : Color.gray) .foregroundColor(Color.orange.opacity(0.8))
.padding(.top, 1) .padding(.top, 1)
} }
.fixedSize(horizontal: true, vertical: false) .fixedSize(horizontal: true, vertical: false)
@@ -1454,7 +1467,7 @@ struct ContentView: View {
}) { }) {
Group { Group {
if let gh = notesGeohash ?? LocationChannelManager.shared.availableChannels.first(where: { $0.level == .building })?.geohash { if let gh = notesGeohash ?? LocationChannelManager.shared.availableChannels.first(where: { $0.level == .building })?.geohash {
LocationNotesView(geohash: gh, onNotesCountChanged: { cnt in sheetNotesCount = cnt }) LocationNotesView(geohash: gh)
.environmentObject(viewModel) .environmentObject(viewModel)
} else { } else {
VStack(spacing: 12) { VStack(spacing: 12) {
@@ -1511,7 +1524,6 @@ struct ContentView: View {
} }
} }
.onAppear { .onAppear {
updateNotesCounterSubscription()
if case .mesh = locationManager.selectedChannel, if case .mesh = locationManager.selectedChannel,
locationManager.permissionState == .authorized, locationManager.permissionState == .authorized,
LocationChannelManager.shared.availableChannels.isEmpty { LocationChannelManager.shared.availableChannels.isEmpty {
@@ -1519,16 +1531,13 @@ struct ContentView: View {
} }
} }
.onChange(of: locationManager.selectedChannel) { _ in .onChange(of: locationManager.selectedChannel) { _ in
updateNotesCounterSubscription()
if case .mesh = locationManager.selectedChannel, if case .mesh = locationManager.selectedChannel,
locationManager.permissionState == .authorized, locationManager.permissionState == .authorized,
LocationChannelManager.shared.availableChannels.isEmpty { LocationChannelManager.shared.availableChannels.isEmpty {
LocationChannelManager.shared.refreshChannels() LocationChannelManager.shared.refreshChannels()
} }
} }
.onChange(of: locationManager.availableChannels) { _ in updateNotesCounterSubscription() }
.onChange(of: locationManager.permissionState) { _ in .onChange(of: locationManager.permissionState) { _ in
updateNotesCounterSubscription()
if case .mesh = locationManager.selectedChannel, if case .mesh = locationManager.selectedChannel,
locationManager.permissionState == .authorized, locationManager.permissionState == .authorized,
LocationChannelManager.shared.availableChannels.isEmpty { LocationChannelManager.shared.availableChannels.isEmpty {
@@ -1545,34 +1554,6 @@ struct ContentView: View {
} }
// MARK: - Notes Counter Subscription Helper
extension ContentView {
private func updateNotesCounterSubscription() {
switch locationManager.selectedChannel {
case .mesh:
// Ensure we have a fresh one-shot location fix so building geohash is current
if locationManager.permissionState == .authorized {
LocationChannelManager.shared.refreshChannels()
}
if locationManager.permissionState == .authorized {
if let building = LocationChannelManager.shared.availableChannels.first(where: { $0.level == .building })?.geohash {
LocationNotesCounter.shared.subscribe(geohash: building)
} else {
// Keep existing subscription if we had one to avoid flicker
// Only cancel if we have no known geohash
if LocationNotesCounter.shared.geohash == nil {
LocationNotesCounter.shared.cancel()
}
}
} else {
LocationNotesCounter.shared.cancel()
}
case .location:
LocationNotesCounter.shared.cancel()
}
}
}
// MARK: - Helper Views // MARK: - Helper Views
// Rounded payment chip button // Rounded payment chip button
@@ -1581,11 +1562,10 @@ extension ContentView {
private enum MessageMedia { private enum MessageMedia {
case voice(URL) case voice(URL)
case image(URL) case image(URL)
case file(URL)
var url: URL { var url: URL {
switch self { switch self {
case .voice(let url), .image(let url), .file(let url): case .voice(let url), .image(let url):
return url return url
} }
} }
@@ -1623,13 +1603,6 @@ private extension ContentView {
let url = baseDirectory.appendingPathComponent(subdir, isDirectory: true).appendingPathComponent(filename) let url = baseDirectory.appendingPathComponent(subdir, isDirectory: true).appendingPathComponent(filename)
return .image(url) return .image(url)
} }
if message.content.hasPrefix("[file] ") {
let filename = String(message.content.dropFirst("[file] ".count)).trimmingCharacters(in: .whitespacesAndNewlines)
guard !filename.isEmpty else { return nil }
let subdir = message.sender == viewModel.nickname ? "files/outgoing" : "files/incoming"
let url = baseDirectory.appendingPathComponent(subdir, isDirectory: true).appendingPathComponent(filename)
return .file(url)
}
return nil return nil
} }
@@ -1721,13 +1694,6 @@ private extension ContentView {
} : nil } : nil
) )
.frame(maxWidth: 280) .frame(maxWidth: 280)
case .file(let url):
FileAttachmentView(
url: url,
isSending: state.isSending,
progress: state.progress,
onCancel: cancelAction
)
} }
} }
} }
@@ -1862,13 +1828,33 @@ private extension ContentView {
} }
var attachmentButton: some View { var attachmentButton: some View {
Button(action: { showAttachmentActions = true }) { #if os(iOS)
Image(systemName: "paperclip.circle.fill") Image(systemName: "camera.circle.fill")
.font(.bitchatSystem(size: 24))
.foregroundColor(composerAccentColor)
.frame(width: 36, height: 36)
.contentShape(Circle())
.onTapGesture {
// Tap = Photo Library
imagePickerSourceType = .photoLibrary
showImagePicker = true
}
.onLongPressGesture(minimumDuration: 0.3) {
// Long press = Camera
imagePickerSourceType = .camera
showImagePicker = true
}
.accessibilityLabel("Tap for library, long press for camera")
#else
Button(action: { showMacImagePicker = true }) {
Image(systemName: "photo.circle.fill")
.font(.bitchatSystem(size: 24)) .font(.bitchatSystem(size: 24))
.foregroundColor(composerAccentColor) .foregroundColor(composerAccentColor)
.frame(width: 36, height: 36) .frame(width: 36, height: 36)
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.accessibilityLabel("Choose photo")
#endif
} }
var sendOrMicButton: some View { var sendOrMicButton: some View {
@@ -2037,44 +2023,6 @@ private extension ContentView {
} }
} }
#if os(iOS)
func handlePhotoSelection(_ item: PhotosPickerItem) async {
defer { Task { @MainActor in selectedPhotoPickerItem = nil } }
do {
if let data = try await item.loadTransferable(type: Data.self) {
let tempURL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension("jpg")
try data.write(to: tempURL, options: Data.WritingOptions.atomic)
await MainActor.run {
viewModel.sendImage(from: tempURL) {
try? FileManager.default.removeItem(at: tempURL)
}
}
}
} catch {
SecureLogger.error("Photo picker load failed: \(error)", category: .session)
}
}
#endif
func handleImportedFile(url: URL) async {
do {
let fileManager = FileManager.default
let tempDir = fileManager.temporaryDirectory
let fileName = url.lastPathComponent.isEmpty ? "attachment" : url.lastPathComponent
let destination = tempDir.appendingPathComponent(UUID().uuidString + "_" + fileName)
if fileManager.fileExists(atPath: destination.path) {
try fileManager.removeItem(at: destination)
}
try fileManager.copyItem(at: url, to: destination)
await MainActor.run {
viewModel.sendFileAttachment(from: destination)
}
} catch {
SecureLogger.error("File copy failed before send: \(error)", category: .session)
}
}
func applicationFilesDirectory() -> URL? { func applicationFilesDirectory() -> URL? {
// Cache the directory lookup to avoid repeated FileManager calls during view rendering // Cache the directory lookup to avoid repeated FileManager calls during view rendering
@@ -2218,3 +2166,87 @@ struct ImagePreviewView: View {
} }
#endif #endif
} }
#if os(iOS)
// MARK: - Image Picker (Camera or Photo Library)
struct ImagePickerView: UIViewControllerRepresentable {
let sourceType: UIImagePickerController.SourceType
let completion: (UIImage?) -> Void
func makeUIViewController(context: Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.sourceType = sourceType
picker.delegate = context.coordinator
picker.allowsEditing = false
// Use standard full screen - iOS handles safe areas automatically
picker.modalPresentationStyle = .fullScreen
// Force dark mode to make safe area bars black instead of white
picker.overrideUserInterfaceStyle = .dark
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(completion: completion)
}
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let completion: (UIImage?) -> Void
init(completion: @escaping (UIImage?) -> Void) {
self.completion = completion
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
let image = info[.originalImage] as? UIImage
completion(image)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
completion(nil)
}
}
}
#endif
#if os(macOS)
// MARK: - macOS Image Picker
struct MacImagePickerView: View {
let completion: (URL?) -> Void
@Environment(\.dismiss) private var dismiss
var body: some View {
VStack(spacing: 16) {
Text("Choose an image")
.font(.headline)
Button("Select Image") {
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
panel.canChooseFiles = true
panel.allowedContentTypes = [.image, .png, .jpeg, .heic]
panel.message = "Choose an image to send"
if panel.runModal() == .OK {
completion(panel.url)
} else {
dismiss()
}
}
.buttonStyle(.borderedProminent)
Button("Cancel") {
completion(nil)
}
.buttonStyle(.bordered)
}
.padding(40)
.frame(minWidth: 300, minHeight: 150)
}
}
#endif
+1 -1
View File
@@ -141,7 +141,7 @@ struct LocationNotesView: View {
String( String(
format: String(localized: "location_notes.header", comment: "Header displaying the geohash and localized note count"), format: String(localized: "location_notes.header", comment: "Header displaying the geohash and localized note count"),
locale: .current, locale: .current,
geohash, count "\(geohash) ± 1", count
) )
} }
@@ -1,118 +0,0 @@
import SwiftUI
struct FileAttachmentView: View {
private let url: URL
private let isSending: Bool
private let progress: Double?
private let onCancel: (() -> Void)?
@Environment(\.colorScheme) private var colorScheme
#if os(iOS)
@State private var showExporter = false
#endif
init(url: URL, isSending: Bool, progress: Double?, onCancel: (() -> Void)?) {
self.url = url
self.isSending = isSending
self.progress = progress
self.onCancel = onCancel
}
private var fileName: String {
url.lastPathComponent
}
private var normalizedProgress: Double? {
guard let progress = progress else { return nil }
return max(0, min(1, progress))
}
var body: some View {
HStack(alignment: .center, spacing: 12) {
Image(systemName: "doc.fill")
.foregroundColor(Color.blue)
.font(.bitchatSystem(size: 24))
VStack(alignment: .leading, spacing: 4) {
Text(fileName)
.font(.bitchatSystem(size: 14, weight: .medium))
.foregroundColor(.primary)
.lineLimit(2)
Text(url.lastPathComponent)
.font(.bitchatSystem(size: 11, design: .monospaced))
.foregroundColor(.secondary)
.lineLimit(1)
if let progress = normalizedProgress {
ProgressView(value: progress)
.progressViewStyle(.linear)
.tint(Color.blue)
}
}
Spacer()
Button(action: openFile) {
Text("open", comment: "Button to open attached file")
.font(.bitchatSystem(size: 13, weight: .semibold))
.padding(.horizontal, 12)
.padding(.vertical, 6)
.background(
Capsule().fill(Color.blue.opacity(0.15))
)
}
.buttonStyle(.plain)
if let onCancel = onCancel, isSending {
Button(action: onCancel) {
Image(systemName: "xmark")
.font(.bitchatSystem(size: 11, weight: .bold))
.frame(width: 26, height: 26)
.background(Circle().fill(Color.red.opacity(0.9)))
.foregroundColor(.white)
}
.buttonStyle(.plain)
}
}
.padding(12)
.background(
RoundedRectangle(cornerRadius: 14)
.fill(colorScheme == .dark ? Color.black.opacity(0.6) : Color.white)
)
.overlay(
RoundedRectangle(cornerRadius: 14)
.stroke(Color.gray.opacity(0.2), lineWidth: 1)
)
#if os(iOS)
.sheet(isPresented: $showExporter) {
FileExportController(url: url)
}
#endif
}
private func openFile() {
#if os(iOS)
showExporter = true
#else
NSWorkspace.shared.open(url)
#endif
}
}
#if os(iOS)
import UniformTypeIdentifiers
import UIKit
private struct FileExportController: UIViewControllerRepresentable {
let url: URL
func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
let controller = UIDocumentPickerViewController(forExporting: [url])
controller.shouldShowFileExtensions = true
return controller
}
func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {}
}
#else
import AppKit
#endif
@@ -91,61 +91,3 @@ struct LocationNotesManagerTests {
case shouldNotDerive case shouldNotDerive
} }
} }
@MainActor
struct LocationNotesCounterTests {
@Test func subscribeWithoutRelaysMarksUnavailable() {
var subscribeCalled = false
let deps = LocationNotesCounterDependencies(
relayLookup: { _, _ in [] },
subscribe: { _, _, _, _, _ in subscribeCalled = true },
unsubscribe: { _ in }
)
let counter = LocationNotesCounter(testDependencies: deps)
counter.subscribe(geohash: "u4pruydq")
#expect(!subscribeCalled)
#expect(!counter.relayAvailable)
#expect(counter.initialLoadComplete)
#expect(counter.count == 0)
}
@Test func subscribeCountsUniqueNotes() {
var storedHandler: ((NostrEvent) -> Void)?
var storedEOSE: (() -> Void)?
let deps = LocationNotesCounterDependencies(
relayLookup: { _, _ in ["wss://relay.geo"] },
subscribe: { filter, id, relays, handler, eose in
#expect(relays == ["wss://relay.geo"])
#expect(filter.kinds == [1])
#expect(!id.isEmpty)
storedHandler = handler
storedEOSE = eose
},
unsubscribe: { _ in }
)
let counter = LocationNotesCounter(testDependencies: deps)
counter.subscribe(geohash: "u4pruydq")
var first = NostrEvent(
pubkey: "pub",
createdAt: Date(),
kind: .textNote,
tags: [["g", "u4pruydq"]],
content: "a"
)
first.id = "eventA"
storedHandler?(first)
let duplicate = first
storedHandler?(duplicate)
storedEOSE?()
#expect(counter.relayAvailable)
#expect(counter.count == 1)
#expect(counter.initialLoadComplete)
}
}