Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / apple / FindFamily / FindFamilyiOS / Location / Location.swift

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