Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / apple / FindFamily / FindFamilyiOS / Location / Location.swift
Location.swift417 lines · 18.8 KiBRaw
| 1 | import Foundation |
| 2 | import Combine |
| 3 | import CoreLocation |
| 4 | import UIKit |
| 5 | import UserNotifications |
| 6 | import OSLog |
| 7 | |
| 8 | let logger = Logger(subsystem: "cc.findfamily.ios.swift", category: "Location") |
| 9 | |
| 10 | // MARK: - LocationsHandler (CoreLocation pipeline) |
| 11 | |
| 12 | /// Mirrors the `LocationsHandler` in the standalone Find-Family iOS app: uses iOS 17+ |
| 13 | /// `CLLocationUpdate.liveUpdates()` driven by a `CLBackgroundActivitySession` plus a |
| 14 | /// `CLServiceSession(.always)` so updates keep flowing in the background. |
| 15 | @MainActor |
| 16 | final class LocationsHandler: ObservableObject { |
| 17 | static let shared = LocationsHandler() |
| 18 | |
| 19 | private let manager = CLLocationManager() |
| 20 | private var background: CLBackgroundActivitySession? |
| 21 | private var session: CLServiceSession? |
| 22 | private var task: Task<Void, Never>? |
| 23 | private var sharingWatchers = Set<AnyCancellable>() |
| 24 | |
| 25 | private init() { |
| 26 | manager.allowsBackgroundLocationUpdates = true |
| 27 | } |
| 28 | |
| 29 | func authorize() { |
| 30 | switch manager.authorizationStatus { |
| 31 | case .notDetermined: |
| 32 | manager.requestWhenInUseAuthorization() |
| 33 | case .authorizedWhenInUse: |
| 34 | manager.requestAlwaysAuthorization() |
| 35 | default: |
| 36 | break |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | func startLocationUpdates() { |
| 41 | authorize() |
| 42 | manager.allowsBackgroundLocationUpdates = true |
| 43 | guard task == nil else { return } |
| 44 | logger.info("Starting location updates") |
| 45 | task = Task { [weak self] in |
| 46 | do { |
| 47 | self?.background = CLBackgroundActivitySession() |
| 48 | self?.session = CLServiceSession(authorization: .always) |
| 49 | let updates = CLLocationUpdate.liveUpdates() |
| 50 | for try await update in updates { |
| 51 | if let loc = update.location { |
| 52 | BackgroundTask.shared.onLocationUpdate(loc, sleep: false) |
| 53 | } |
| 54 | // Diagnostic flags are logged on the device only (the old /api/problem |
| 55 | // report endpoint is gone). |
| 56 | if update.authorizationDenied { logger.notice("Location update: Auth denied") } |
| 57 | if update.authorizationDeniedGlobally { logger.notice("Location update: Auth denied globally") } |
| 58 | if update.authorizationRequestInProgress { logger.notice("Location update: Auth in progress") } |
| 59 | if update.authorizationRestricted { logger.notice("Location update: Auth restricted") } |
| 60 | if update.insufficientlyInUse { logger.notice("Location update: Insufficient Use") } |
| 61 | if update.locationUnavailable { logger.notice("Location update: Location Unavailable") } |
| 62 | if update.serviceSessionRequired { logger.notice("Location update: Service Session required") } |
| 63 | if update.stationary { logger.notice("Location update: Stationary") } |
| 64 | } |
| 65 | } catch { |
| 66 | logger.error("Could not start location updates: \(error.localizedDescription)") |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | func stopLocationUpdates() { |
| 72 | task?.cancel() |
| 73 | task = nil |
| 74 | background?.invalidate() |
| 75 | background = nil |
| 76 | session?.invalidate() |
| 77 | session = nil |
| 78 | manager.stopUpdatingLocation() |
| 79 | manager.stopMonitoringSignificantLocationChanges() |
| 80 | for region in manager.monitoredRegions { |
| 81 | manager.stopMonitoring(for: region) |
| 82 | } |
| 83 | manager.stopMonitoringVisits() |
| 84 | manager.allowsBackgroundLocationUpdates = false |
| 85 | BackgroundTask.shared.stopHeartbeat() |
| 86 | RelaySocket.shared.trackingStopped() |
| 87 | logger.info("Stopped location updates (not sharing with anyone)") |
| 88 | } |
| 89 | |
| 90 | /// Whether we currently publish our location to anyone: any peer with |
| 91 | /// `sendingEnabled`, any pending share auto-toggle timer (which may flip |
| 92 | /// sharing back on by itself), or any live temporary link. Expired links |
| 93 | /// are pruned here so they can't keep location alive forever. |
| 94 | func isSharingWithAnyone() -> Bool { |
| 95 | pruneExpiredTemporaryLinks() |
| 96 | let now = Date() |
| 97 | let users = Database.shared.usersSubject.value |
| 98 | let me = Networking.shared.userid |
| 99 | if users.contains(where: { $0.id != me && ($0.sendingEnabled || $0.sharingAutoToggleAt != nil) }) { |
| 100 | return true |
| 101 | } |
| 102 | return Database.shared.temporaryLinksSubject.value.contains(where: { $0.deleteAt > now }) |
| 103 | } |
| 104 | |
| 105 | /// Start location work only when we're actually sharing with someone. |
| 106 | /// Safe to call on every launch (including background relaunch): re-entrant, |
| 107 | /// no-ops when updates are already running. |
| 108 | func startLocationUpdatesIfSharing() { |
| 109 | if isSharingWithAnyone() { |
| 110 | BackgroundTask.shared.startHeartbeat() |
| 111 | RelaySocket.shared.wake() |
| 112 | startLocationUpdates() |
| 113 | } else { |
| 114 | stopLocationUpdates() |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Re-evaluate the sharing gate whenever the sharing state changes: the |
| 119 | /// per-user toggle, auto-toggle timers, and temporary links. Every write |
| 120 | /// path funnels through these subjects, so this covers manual toggles, |
| 121 | /// timer flips, link add/delete, and user add/delete. |
| 122 | func beginMonitoringSharing() { |
| 123 | guard sharingWatchers.isEmpty else { return } |
| 124 | // Hop to the main thread like MainViewModel does: Database sends from |
| 125 | // its serial queue, and a synchronous MainActor hop from there risks |
| 126 | // deadlock against its queue.sync writes. |
| 127 | Database.shared.usersSubject |
| 128 | .dropFirst() |
| 129 | .receive(on: DispatchQueue.main) |
| 130 | .sink { [weak self] _ in Task { @MainActor in self?.startLocationUpdatesIfSharing() } } |
| 131 | .store(in: &sharingWatchers) |
| 132 | Database.shared.temporaryLinksSubject |
| 133 | .dropFirst() |
| 134 | .receive(on: DispatchQueue.main) |
| 135 | .sink { [weak self] _ in Task { @MainActor in self?.startLocationUpdatesIfSharing() } } |
| 136 | .store(in: &sharingWatchers) |
| 137 | } |
| 138 | |
| 139 | /// Delete temporary links past their expiry so an unopened/undeleted link |
| 140 | /// can't pin background location on indefinitely. (The per-tick cleanup in |
| 141 | /// `runTick` only runs while sharing is active.) |
| 142 | private func pruneExpiredTemporaryLinks() { |
| 143 | let now = Date() |
| 144 | for link in Database.shared.temporaryLinksSubject.value where link.deleteAt <= now { |
| 145 | Database.shared.deleteTemporaryLink(link) |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | // MARK: - BackgroundTask (per-tick work) |
| 151 | |
| 152 | /// Implements the per-tick logic from Modern-Apps `BackgroundTask.kt`: |
| 153 | /// throttled to 3s, reverse-geocodes, computes waypoint enter/exit, publishes to each |
| 154 | /// `sendingEnabled` user, receives + persists incoming locations, and emits |
| 155 | /// notifications for sharing requests + low-battery + waypoint transitions. |
| 156 | @MainActor |
| 157 | final class BackgroundTask { |
| 158 | static let shared = BackgroundTask() |
| 159 | |
| 160 | static let shareIntervalSeconds: TimeInterval = 3.0 |
| 161 | |
| 162 | private var lastUpdateAt: Date = .distantPast |
| 163 | private var tickCount = 0 |
| 164 | private var lastBatteryLevels: [Int64: Float] = [:] |
| 165 | private var isProcessing = false |
| 166 | |
| 167 | /// Last location delivered by CoreLocation. Cached so the timer-driven |
| 168 | /// heartbeat below can keep publishing even when CLLocationUpdate goes quiet |
| 169 | /// (e.g. the phone is sitting on a desk). |
| 170 | private var lastKnownLocation: CLLocation? |
| 171 | |
| 172 | /// Background timer that keeps `runTick` firing every `shareIntervalSeconds` |
| 173 | /// regardless of whether CoreLocation has delivered a new fix. This mirrors |
| 174 | /// Modern-Apps Android `syncHeartbeat` which runs on a 30 s loop independent |
| 175 | /// of location callbacks — without it, a stationary iPhone never calls |
| 176 | /// `/api/location/receive` and so never sees peer locations. |
| 177 | private var heartbeatTask: Task<Void, Never>? |
| 178 | |
| 179 | private let geocoder = CLGeocoder() |
| 180 | |
| 181 | private init() {} |
| 182 | |
| 183 | /// Idempotent: safe to call on every launch and every sharing-state change. |
| 184 | func startHeartbeat() { |
| 185 | guard heartbeatTask == nil else { return } |
| 186 | heartbeatTask = Task { [weak self] in |
| 187 | while !Task.isCancelled { |
| 188 | if let loc = self?.lastKnownLocation { |
| 189 | self?.onLocationUpdate(loc, sleep: false) |
| 190 | } |
| 191 | try? await Task.sleep(nanoseconds: UInt64(Self.shareIntervalSeconds * 1_000_000_000)) |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | func stopHeartbeat() { |
| 197 | heartbeatTask?.cancel() |
| 198 | heartbeatTask = nil |
| 199 | lastKnownLocation = nil |
| 200 | } |
| 201 | |
| 202 | /// Whether location tracking (the heartbeat) is running. |
| 203 | var isHeartbeatRunning: Bool { heartbeatTask != nil } |
| 204 | |
| 205 | func onLocationUpdate(_ loc: CLLocation, sleep: Bool) { |
| 206 | // Every location update / heartbeat tick may be the app waking from suspension: |
| 207 | // make sure the relay socket is up (no-op when it already is). |
| 208 | RelaySocket.shared.wake() |
| 209 | lastKnownLocation = loc |
| 210 | let now = Date() |
| 211 | if !sleep && now.timeIntervalSince(lastUpdateAt) < Self.shareIntervalSeconds { return } |
| 212 | lastUpdateAt = now |
| 213 | if isProcessing { return } |
| 214 | isProcessing = true |
| 215 | Task { [weak self] in |
| 216 | await self?.runTick(loc: loc, sleep: sleep) |
| 217 | self?.isProcessing = false |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | private func runTick(loc: CLLocation, sleep: Bool) async { |
| 222 | guard Networking.shared.isReady else { return } |
| 223 | let battery = max(0, UIDevice.current.batteryLevel) * 100 |
| 224 | let coord = Coord(lat: loc.coordinate.latitude, lon: loc.coordinate.longitude) |
| 225 | let me = LocationValue( |
| 226 | id: Int64.random(in: Int64.min...Int64.max), |
| 227 | userid: Networking.shared.userid, |
| 228 | coord: coord, |
| 229 | speed: Float(max(0, loc.speed)), |
| 230 | acc: Float(max(0, loc.horizontalAccuracy)), |
| 231 | timestamp: Date(), |
| 232 | battery: battery |
| 233 | ) |
| 234 | |
| 235 | // Periodically (re)register so the server has our current key. |
| 236 | tickCount += 1 |
| 237 | if tickCount % 100 == 1 { _ = await Networking.shared.ensureUserExists() } |
| 238 | |
| 239 | // 1 + 2. Persist our own fix, then compute our current waypoint (with 1.2× exit |
| 240 | // hysteresis) and a display name. Uses the atomic partial update so timers/flags |
| 241 | // set elsewhere (sharingAutoToggleAt / sendingEnabled) aren't clobbered. |
| 242 | Database.shared.insertLocationValue(me) |
| 243 | if let meUser = Database.shared.user(id: Networking.shared.userid) { |
| 244 | let (currentId, resolvedName) = await resolveWaypoint(coord: coord, prevId: meUser.lastWaypointId) |
| 245 | let displayName = resolvedName ?? (meUser.locationName.isEmpty ? "Unnamed Location" : meUser.locationName) |
| 246 | if currentId != meUser.lastWaypointId || displayName != meUser.locationName { |
| 247 | Database.shared.updateLocationMeta( |
| 248 | id: meUser.id, |
| 249 | locationName: displayName, |
| 250 | lastWaypointId: currentId, |
| 251 | lastLocationChangeTime: Date() |
| 252 | ) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | // 3. Delete expired temporary links. |
| 257 | let now = Date() |
| 258 | for link in Database.shared.temporaryLinksSubject.value where link.deleteAt < now { |
| 259 | Database.shared.deleteTemporaryLink(link) |
| 260 | } |
| 261 | |
| 262 | // 4. Apply any due auto-toggle timers, then publish. Mirrors Android: flip |
| 263 | // `sendingEnabled` atomically for due timers, then publish only to peers with |
| 264 | // sharing enabled (`id != me && sendingEnabled`) so the "Share your location" |
| 265 | // toggle — and the auto-toggle countdown — are actually honored. |
| 266 | Database.shared.applyDueAutoToggles(now: now) |
| 267 | let users = Database.shared.usersSubject.value |
| 268 | for u in users where u.id != Networking.shared.userid && u.sendingEnabled { |
| 269 | _ = await Networking.shared.publishLocation(me, toUser: u) |
| 270 | } |
| 271 | for link in Database.shared.temporaryLinksSubject.value { |
| 272 | _ = await Networking.shared.publishLocation(me, toLink: link) |
| 273 | } |
| 274 | |
| 275 | // 5. Receive incoming peer locations. The relay socket pushes them as they arrive |
| 276 | // (RelaySocket -> handleIncomingLocations); poll HTTP only while it is not |
| 277 | // subscribed, so a socket outage degrades to the old per-tick polling. |
| 278 | let socketLive = RelaySocket.shared.isSubscribed |
| 279 | if !socketLive, let incoming = await Networking.shared.receiveLocations() { |
| 280 | await handleIncomingLocations(incoming) |
| 281 | } |
| 282 | |
| 283 | // 6. Trim old locations (>7 days). |
| 284 | let cutoff = Date().addingTimeInterval(-7 * 24 * 60 * 60) |
| 285 | Database.shared.deleteLocationValuesOlderThan(cutoff) |
| 286 | |
| 287 | // 7. Drain the UWB session-setup channel (same rule: socket pushes, HTTP fallback). |
| 288 | if !socketLive, let envelopes = await Networking.shared.receiveUwbMessages() { |
| 289 | handleIncomingUwb(envelopes) |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | /// Stores incoming peer fixes — from the relay socket or an HTTP drain. Any sender we |
| 294 | /// don't already know about is added as AWAITING_REQUEST (Modern-Apps uses received |
| 295 | /// locations — not a separate `/api/request_sharing` endpoint — to discover incoming |
| 296 | /// requests). |
| 297 | func handleIncomingLocations(_ incoming: [LocationValue]) async { |
| 298 | guard !incoming.isEmpty else { return } |
| 299 | let users = Database.shared.usersSubject.value |
| 300 | let knownIds = Set(users.map { $0.id } + [Networking.shared.userid]) |
| 301 | let newSenderIds = Set(incoming.map { $0.userid }).subtracting(knownIds) |
| 302 | for id in newSenderIds { |
| 303 | let user = User( |
| 304 | id: id, name: "ID \(Base26.encode(id))", photo: nil, |
| 305 | locationName: "Unknown Location", sendingEnabled: true, |
| 306 | requestStatus: .awaitingRequest, lastLocationChangeTime: Date(), |
| 307 | encryptionKey: nil |
| 308 | ) |
| 309 | Database.shared.upsertUser(user) |
| 310 | NotificationsUtil.send( |
| 311 | title: Strings.notifSharingRequestTitle, |
| 312 | body: Strings.notifSharingRequestBody(Base26.encode(id)), |
| 313 | category: "SHARING_REQUEST" |
| 314 | ) |
| 315 | } |
| 316 | for loc in incoming { |
| 317 | Database.shared.insertLocationValue(loc) |
| 318 | await updateUserLocationName(loc) |
| 319 | await maybeNotifyBatteryDrop(loc) |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | /// Hands incoming UWB envelopes (relay socket or HTTP drain) to UwbInbox so an open |
| 324 | /// Precision Finding view can react; a REQUEST with no view open posts a notification. |
| 325 | func handleIncomingUwb(_ envelopes: [UwbEnvelope]) { |
| 326 | for env in envelopes { |
| 327 | UwbInbox.shared.emit(env) |
| 328 | if env.kind == UwbEnvelopeKind.request { |
| 329 | let senderId = Int64(bitPattern: env.sender) |
| 330 | let senderName = Database.shared.user(id: senderId)?.name ?? "Someone" |
| 331 | NotificationsUtil.send( |
| 332 | title: "Precision Finding request", |
| 333 | body: "\(senderName) wants to find you with Precision Finding. Tap to begin.", |
| 334 | category: "UWB_REQUEST" |
| 335 | ) |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | /// Computes the current waypoint id for a coordinate with 1.2× exit hysteresis and a |
| 341 | /// display name, mirroring Android `syncHeartbeat`. To *enter* a waypoint you must be |
| 342 | /// within its radius; to *remain* in the previously-entered waypoint you only need to be |
| 343 | /// within 1.2× the radius (prevents flapping at the boundary). The returned name prefers |
| 344 | /// the entered/sticky waypoint name, then a reverse-geocoded address, else nil (unresolved). |
| 345 | private func resolveWaypoint(coord: Coord, prevId: Int64?) async -> (currentId: Int64?, name: String?) { |
| 346 | let waypoints = Database.shared.waypointsSubject.value |
| 347 | let inWaypoint = waypoints.first { haversine(coord, $0.coord) < $0.range } |
| 348 | let stillInsidePrev: Bool = { |
| 349 | guard let pid = prevId, let wp = waypoints.first(where: { $0.id == pid }) else { return false } |
| 350 | return haversine(coord, wp.coord) < wp.range * 1.2 |
| 351 | }() |
| 352 | let currentId: Int64? = inWaypoint?.id ?? (stillInsidePrev ? prevId : nil) |
| 353 | if let name = inWaypoint?.name { return (currentId, name) } |
| 354 | if let cid = currentId, let wp = waypoints.first(where: { $0.id == cid }) { |
| 355 | return (currentId, wp.name) |
| 356 | } |
| 357 | if let placemarks = try? await geocoder.reverseGeocodeLocation( |
| 358 | CLLocation(latitude: coord.lat, longitude: coord.lon) |
| 359 | ), let p = placemarks.first { |
| 360 | return (currentId, [p.name, p.locality].compactMap { $0 }.first) |
| 361 | } |
| 362 | return (currentId, nil) |
| 363 | } |
| 364 | |
| 365 | private func updateUserLocationName(_ loc: LocationValue) async { |
| 366 | guard let user = Database.shared.user(id: loc.userid) else { return } |
| 367 | // Recompute waypoint (with hysteresis) + display name on every incoming fix. Prefer a |
| 368 | // matching waypoint, otherwise reverse-geocode. Keep the existing name if we can't |
| 369 | // resolve a fresh one rather than clobbering it. |
| 370 | let prevId = user.lastWaypointId |
| 371 | let (currentId, resolvedName) = await resolveWaypoint(coord: loc.coord, prevId: prevId) |
| 372 | let resolved = resolvedName ?? user.locationName |
| 373 | if currentId != prevId || resolved != user.locationName { |
| 374 | // Atomic partial update — avoids a stale snapshot clobbering |
| 375 | // sharingAutoToggleAt / sendingEnabled. |
| 376 | Database.shared.updateLocationMeta( |
| 377 | id: user.id, |
| 378 | locationName: resolved, |
| 379 | lastWaypointId: currentId, |
| 380 | lastLocationChangeTime: Date() |
| 381 | ) |
| 382 | } |
| 383 | // Enter/exit notifications fire only on an actual waypoint transition. |
| 384 | guard currentId != prevId else { return } |
| 385 | if currentId != nil { |
| 386 | let enteredName = Database.shared.waypointsSubject.value.first { $0.id == currentId }?.name ?? resolved |
| 387 | NotificationsUtil.send( |
| 388 | title: Strings.notifWaypointEnterTitle, |
| 389 | body: Strings.notifWaypointEnterBody(user.name, enteredName), |
| 390 | category: "WAYPOINT_ENTER_EXIT" |
| 391 | ) |
| 392 | } else if let pid = prevId { |
| 393 | let exitedName = Database.shared.waypointsSubject.value.first { $0.id == pid }?.name ?? user.locationName |
| 394 | NotificationsUtil.send( |
| 395 | title: Strings.notifWaypointExitTitle, |
| 396 | body: Strings.notifWaypointExitBody(user.name, exitedName), |
| 397 | category: "WAYPOINT_ENTER_EXIT" |
| 398 | ) |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | private func maybeNotifyBatteryDrop(_ loc: LocationValue) async { |
| 403 | let prev = lastBatteryLevels[loc.userid] |
| 404 | lastBatteryLevels[loc.userid] = loc.battery |
| 405 | guard let prev = prev else { return } |
| 406 | // Edge-triggered at 15% (matches Android): one alert as a peer crosses the threshold. |
| 407 | if prev > 15 && loc.battery <= 15 { |
| 408 | if let user = Database.shared.user(id: loc.userid) { |
| 409 | NotificationsUtil.send( |
| 410 | title: Strings.notifBatteryLowTitle, |
| 411 | body: Strings.notifBatteryLowBody(user.name, Int(loc.battery)), |
| 412 | category: "BATTERY_LOW" |
| 413 | ) |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | } |