← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


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/// Captures the live context of a report: location and its address, the
12/// weather there, and device state.
13///
14/// Every provider runs at once and on its own, within the time budget. One
15/// that fails, is denied or runs out of time leaves its section `nil`; none
16/// of them can stop the report being saved.
17struct ContextCapture: Sendable {
18    private static let log = EventLog.shared.category("Capture")
19    /// Details kept out of the event log, which is shared as it is.
20    private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Capture")
21
22    /// A capture for a notification action, which runs in the background.
23    /// iOS gives an action about 30 seconds, and a fix there may start
24    /// cold, so it gets longer than the foreground's 10.
25    static let background = ContextCapture(budget: .seconds(25))
26
27    /// The whole capture's budget.
28    var budget: Duration = .seconds(10)
29    /// A recent fix at least this accurate, in metres, ends the search
30    /// early.
31    var goodAccuracy: CLLocationAccuracy = 50
32    /// Time kept back from the location search for looking up the address
33    /// and the weather, which both start once there's a fix.
34    var geocodingAllowance: Duration = .seconds(3)
35    /// The current weather at a fix. Replaced in tests.
36    var weather: @Sendable (CLLocation) async -> WeatherContext? = { await AppleWeather.current(at: $0) }
37
38    /// Captures the context. `onLocation` is called as soon as there's a
39    /// fix, before its address has been looked up, so places near it can be
40    /// suggested while the capture finishes.
41    func capture(
42        onLocation: @escaping @Sendable (LocationContext) -> Void = { _ in }
43    ) async -> Context {
44        // The weather needs the fix, so the location capture hands it over
45        // as soon as it has one, and the two lookups run side by side.
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    /// Whether a section was captured, for the event log, which never says
66    /// what it holds.
67    private static func found(_ section: (some Any)?) -> String {
68        section == nil ? "missing" : "captured"
69    }
70
71    // MARK: Weather
72
73    /// The weather at the first fix handed over, within the same allowance
74    /// as the address. `nil` if there's no fix, or no answer in time.
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    // MARK: Location
83
84    private func captureLocation(
85        onFix: @Sendable (CLLocation) -> Void,
86        onLocation: @Sendable (LocationContext) -> Void
87    ) async -> LocationContext? {
88        // Holding a session is what asks for authorisation. While the prompt
89        // is on screen the budget hasn't started: the user is reading it.
90        // With 'Always' granted, the session asks for it too, though in the
91        // background that only works while the app already holds one
92        // started earlier: Core Location won't let a new one take effect
93        // there. `BackgroundLocation` holds that one in the app.
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    /// Waits until the user has answered the authorisation prompt, if one is
116    /// showing, and reports whether location may be used. Gives up after a
117    /// minute so a prompt left on screen can't hold up saving forever.
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    /// The first recent fix within `goodAccuracy`, or the best one received
145    /// within `limit` (see `FixChoice`).
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            // When time runs out, cancel the search and take its best fix.
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    /// Picks a location search's fix as updates arrive.
199    ///
200    /// Core Location's first update is often a cached fix, which can be
201    /// minutes old and somewhere else, but accurate enough to end the search
202    /// on accuracy alone. So only a recent fix ends it early; an older one is
203    /// kept in case nothing recent arrives in time. A recent fix beats an
204    /// older one whatever their accuracy, and between two of the same kind
205    /// the more accurate wins. An update marked stationary counts as recent:
206    /// the device hasn't moved since its fix, and Core Location pauses
207    /// updates until it does.
208    struct FixChoice {
209        /// A recent fix at least this accurate, in metres, ends the search.
210        var goodAccuracy: CLLocationAccuracy
211        /// How old a fix can be, in seconds, and still count as recent.
212        var recentAge: TimeInterval = 30
213        private(set) var best: CLLocation?
214        private(set) var isRecent = false
215
216        /// Takes in a fix, and says whether the search can stop.
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    /// Records why a search ended without a fix: the last update's
235    /// diagnostics say whether Core Location held updates back.
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    /// The fix's address in the user's first language and, where the
259    /// place's own language differs, in that language too, which the detail
260    /// view shows as the endonymic address. A
261    /// location MapKit has no address for has none; other errors, such as
262    /// MapKit's throttling, are thrown.
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    /// The main language of a region, such as `ja` for `JP`. Chinese keeps
286    /// its script, which tells Traditional (`zh-Hant` in Taiwan and Hong
287    /// Kong) from Simplified.
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    /// Distinct language codes from the user's preferred languages, in order.
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    // MARK: Device
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                // The level is -1 when it's unknown, as in the Simulator.
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/// Runs `operation`, giving up with `nil` after `timeout`.
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        // Negative accuracies mean the reading is invalid, as in Core
369        // Location, and an invalid vertical accuracy invalidates the altitude.
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}