Shared/Capture/ContextCapture.swift (17831B)
1import CoreLocation
2import Foundation
3import MapKit
4import Network
5import OSLog
6
7#if os(iOS)
8 import UIKit
9#endif
10
11
12
13
14
15
16
17struct ContextCapture: Sendable {
18 private static let log = EventLog.shared.category("Capture")
19
20 private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Capture")
21
22
23
24
25 static let background = ContextCapture(budget: .seconds(25))
26
27
28 var budget: Duration = .seconds(10)
29
30
31 var goodAccuracy: CLLocationAccuracy = 50
32
33
34 var geocodingAllowance: Duration = .seconds(3)
35
36 var weather: @Sendable (CLLocation) async -> WeatherContext? = { await AppleWeather.current(at: $0) }
37
38
39
40
41 func capture(
42 onLocation: @escaping @Sendable (LocationContext) -> Void = { _ in }
43 ) async -> Context {
44
45
46 Self.log.info("Started capturing, within \(budget.formatted(.units(allowed: [.seconds], width: .narrow)))")
47 let start = ContinuousClock.now
48 let (fixes, handOver) = AsyncStream.makeStream(of: CLLocation.self)
49 async let location = captureLocation(onFix: { handOver.yield($0) }, onLocation: onLocation)
50 async let weather = captureWeather(from: fixes)
51 async let device = captureDevice()
52 let captured = await location
53 handOver.finish()
54 let context = Context(location: captured, weather: await weather, device: await device)
55 let elapsed = start.duration(to: .now).formatted(.units(allowed: [.seconds], width: .narrow, fractionalPart: .show(length: 1)))
56 Self.log.info(
57 """
58 Finished capturing after \(elapsed): location \(Self.found(context.location)), \
59 address \(Self.found(context.location?.placemark)), weather \(Self.found(context.weather)), \
60 device \(Self.found(context.device))
61 """)
62 return context
63 }
64
65
66
67 private static func found(_ section: (some Any)?) -> String {
68 section == nil ? "missing" : "captured"
69 }
70
71
72
73
74
75 private func captureWeather(from fixes: AsyncStream<CLLocation>) async -> WeatherContext? {
76 for await fix in fixes {
77 return await withTimeout(geocodingAllowance) { await weather(fix) }
78 }
79 return nil
80 }
81
82
83
84 private func captureLocation(
85 onFix: @Sendable (CLLocation) -> Void,
86 onLocation: @Sendable (LocationContext) -> Void
87 ) async -> LocationContext? {
88
89
90
91
92
93
94 let isAlways = CLLocationManager().authorizationStatus == .authorizedAlways
95 let session = CLServiceSession(authorization: isAlways ? .always : .whenInUse)
96 Self.log.info("Holding a location session for \(isAlways ? "'Always'" : "'While Using'")")
97 defer { session.invalidate() }
98 guard await Self.isAuthorised(session) else { return nil }
99 guard let fix = await bestFix(within: budget - geocodingAllowance) else { return nil }
100 Self.logger.debug("Got a fix within \(fix.horizontalAccuracy)m")
101 Self.log.info("Got a fix")
102 var context = LocationContext(fix)
103 onFix(fix)
104 onLocation(context)
105 let placemarks = await withTimeout(geocodingAllowance) {
106 try? await Self.placemarks(for: fix)
107 }
108 context.placemark = placemarks?.first
109 if let others = placemarks?.dropFirst(), !others.isEmpty {
110 context.localisedPlacemarks = Array(others)
111 }
112 return context
113 }
114
115
116
117
118 private static func isAuthorised(_ session: CLServiceSession) async -> Bool {
119 let status = CLLocationManager().authorizationStatus
120 switch status {
121 case .authorizedWhenInUse, .authorizedAlways: return true
122 case .denied, .restricted:
123 log.notice("Location isn't authorised (status \(status.rawValue))")
124 return false
125 case .notDetermined: break
126 @unknown default: break
127 }
128 let answer = await withTimeout(.seconds(60)) { () async -> Bool? in
129 do {
130 for try await diagnostic in session.diagnostics {
131 if diagnostic.authorizationRequestInProgress { continue }
132 return !(diagnostic.authorizationDenied || diagnostic.authorizationDeniedGlobally
133 || diagnostic.authorizationRestricted)
134 }
135 } catch {}
136 return nil
137 }
138 if answer != true {
139 log.notice("Location wasn't authorised when asked")
140 }
141 return answer ?? false
142 }
143
144
145
146 private func bestFix(within limit: Duration) async -> CLLocation? {
147 await withTaskGroup(of: CLLocation??.self) { group in
148 group.addTask {
149 var choice = FixChoice(goodAccuracy: goodAccuracy)
150 var updates = 0
151 var last: CLLocationUpdate?
152 do {
153 for try await update in CLLocationUpdate.liveUpdates() {
154 updates += 1
155 last = update
156 if update.authorizationDenied || update.authorizationDeniedGlobally
157 || update.authorizationRestricted
158 {
159 break
160 }
161 if let location = update.location,
162 choice.consider(location, stationary: update.stationary)
163 {
164 break
165 }
166 if Task.isCancelled { break }
167 }
168 } catch {
169 Self.log.error("Location updates failed: \(error)")
170 }
171 if let best = choice.best {
172 let age = Date.now.timeIntervalSince(best.timestamp)
173 Self.log.info("Best fix was \(Int(age.rounded()))s old\(choice.isRecent ? "" : ", none recent")")
174 } else {
175 Self.logUnfixed(updates: updates, last: last)
176 }
177 return .some(choice.best)
178 }
179 group.addTask {
180 try? await Task.sleep(for: limit)
181 return .none
182 }
183
184
185 var result: CLLocation?
186 while let next = await group.next() {
187 if case .some(let fix) = next {
188 result = fix
189 break
190 }
191 group.cancelAll()
192 }
193 group.cancelAll()
194 return result
195 }
196 }
197
198
199
200
201
202
203
204
205
206
207
208 struct FixChoice {
209
210 var goodAccuracy: CLLocationAccuracy
211
212 var recentAge: TimeInterval = 30
213 private(set) var best: CLLocation?
214 private(set) var isRecent = false
215
216
217 mutating func consider(_ location: CLLocation, stationary: Bool = false, now: Date = .now) -> Bool {
218 guard location.horizontalAccuracy >= 0 else { return false }
219 let recent = stationary || now.timeIntervalSince(location.timestamp) <= recentAge
220 let isBetter =
221 if let best {
222 recent != isRecent ? recent : location.horizontalAccuracy < best.horizontalAccuracy
223 } else {
224 true
225 }
226 if isBetter {
227 best = location
228 isRecent = recent
229 }
230 return isRecent && best.map { $0.horizontalAccuracy <= goodAccuracy } == true
231 }
232 }
233
234
235
236 private static func logUnfixed(updates: Int, last: CLLocationUpdate?) {
237 guard let last else {
238 log.notice("No fix: no location updates arrived")
239 return
240 }
241 let flags = [
242 ("authorizationDenied", last.authorizationDenied),
243 ("authorizationDeniedGlobally", last.authorizationDeniedGlobally),
244 ("authorizationRestricted", last.authorizationRestricted),
245 ("authorizationRequestInProgress", last.authorizationRequestInProgress),
246 ("insufficientlyInUse", last.insufficientlyInUse),
247 ("serviceSessionRequired", last.serviceSessionRequired),
248 ("locationUnavailable", last.locationUnavailable),
249 ("accuracyLimited", last.accuracyLimited),
250 ("stationary", last.stationary),
251 ]
252 let set = flags.filter(\.1).map(\.0).joined(separator: ", ")
253 log.notice(
254 "No fix after \(updates) updates; last had location: \(last.location != nil), flags: \(set.isEmpty ? "none" : set)"
255 )
256 }
257
258
259
260
261
262
263 static func placemarks(for location: CLLocation) async throws -> [Placemark] {
264 guard let first = preferredLanguages(limit: 1).first,
265 let placemark = try await placemark(for: location, language: first)
266 else { return [] }
267 guard let local = placemark.countryCode.flatMap(localLanguage(ofRegion:)),
268 Locale.Language(identifier: local).languageCode != Locale.Language(identifier: first).languageCode,
269 let localPlacemark = try await self.placemark(for: location, language: local)
270 else { return [placemark] }
271 return [placemark, localPlacemark]
272 }
273
274 private static func placemark(for location: CLLocation, language: String) async throws -> Placemark? {
275 guard let request = MKReverseGeocodingRequest(location: location) else { return nil }
276 request.preferredLocale = Locale(identifier: language)
277 do {
278 guard let item = try await request.mapItems.first else { return nil }
279 return Placemark(item, language: language)
280 } catch let error as MKError where error.code == .placemarkNotFound {
281 return nil
282 }
283 }
284
285
286
287
288 static func localLanguage(ofRegion code: String) -> String? {
289 let likely = Locale.Language(identifier: Locale.Language(identifier: "und-\(code)").maximalIdentifier)
290 guard let language = likely.languageCode?.identifier, language != "und" else { return nil }
291 if language == "zh", let script = likely.script?.identifier {
292 return "zh-\(script)"
293 }
294 return language
295 }
296
297
298 static func preferredLanguages(limit: Int) -> [String] {
299 var languages: [String] = []
300 for identifier in Locale.preferredLanguages {
301 guard let code = Locale(identifier: identifier).language.languageCode?.identifier,
302 !languages.contains(code)
303 else { continue }
304 languages.append(code)
305 if languages.count == limit { break }
306 }
307 return languages
308 }
309
310
311
312 private func captureDevice() async -> DeviceContext? {
313 var device = DeviceContext()
314 #if os(iOS)
315 (device.batteryLevel, device.batteryState) = await MainActor.run {
316 let current = UIDevice.current
317 current.isBatteryMonitoringEnabled = true
318 defer { current.isBatteryMonitoringEnabled = false }
319 let level = current.batteryLevel
320 let state: DeviceContext.BatteryState? =
321 switch current.batteryState {
322 case .unplugged: .unplugged
323 case .charging: .charging
324 case .full: .full
325 case .unknown: nil
326 @unknown default: nil
327 }
328
329 return (level >= 0 ? Double(level) : nil, state)
330 }
331 #endif
332 device.connectivity = await withTimeout(.seconds(2)) { await Self.connectivity() }
333 return device == DeviceContext() ? nil : device
334 }
335
336 private static func connectivity() async -> DeviceContext.Connectivity {
337 let monitor = NWPathMonitor()
338 defer { monitor.cancel() }
339 for await path in monitor {
340 guard path.status == .satisfied else { return .none }
341 if path.usesInterfaceType(.wifi) || path.usesInterfaceType(.wiredEthernet) { return .wifi }
342 if path.usesInterfaceType(.cellular) { return .cellular }
343 return .wifi
344 }
345 return .none
346 }
347}
348
349
350func withTimeout<T: Sendable>(
351 _ timeout: Duration,
352 operation: @escaping @Sendable () async -> T?
353) async -> T? {
354 await withTaskGroup(of: T?.self) { group in
355 group.addTask { await operation() }
356 group.addTask {
357 try? await Task.sleep(for: timeout)
358 return nil
359 }
360 let first = await group.next() ?? nil
361 group.cancelAll()
362 return first
363 }
364}
365
366extension LocationContext {
367 init(_ location: CLLocation) {
368
369
370 let verticalValid = location.verticalAccuracy >= 0
371 self.init(
372 coordinate: Coordinate(
373 latitude: location.coordinate.latitude, longitude: location.coordinate.longitude),
374 altitude: verticalValid ? location.altitude : nil,
375 horizontalAccuracy: location.horizontalAccuracy >= 0 ? location.horizontalAccuracy : nil,
376 verticalAccuracy: verticalValid ? location.verticalAccuracy : nil,
377 speed: location.speed >= 0 ? location.speed : nil,
378 course: location.course >= 0 ? location.course : nil,
379 timestamp: location.timestamp
380 )
381 }
382}
383
384extension Placemark {
385 init(_ item: MKMapItem, language: String) {
386 let representations = item.addressRepresentations
387 self.init(
388 name: item.name,
389 locality: representations?.cityName,
390 country: representations?.regionName,
391 language: language,
392 countryCode: representations?.region?.identifier,
393 cityWithContext: representations?.cityWithContext,
394 fullAddress: item.address?.fullAddress,
395 shortAddress: item.address?.shortAddress
396 )
397 }
398}