← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Services/Places/AddressFill.swift (10829B)

1import CoreData
2import CoreLocation
3import Foundation
4import MapKit
5import UIKit
6
7/// A report whose address isn't in the form MapKit gives new reports, such
8/// as one imported from Reporter, whose address came from the geocoder of
9/// its day.
10struct AddressTarget: Equatable, Sendable {
11    var id: UUID
12    var coordinate: Coordinate
13}
14
15/// Reports close enough together to share one address lookup.
16struct AddressSpot: Equatable, Sendable {
17    /// Where the address is looked up: the first report's location.
18    var coordinate: Coordinate
19    var reportIDs: [UUID]
20}
21
22enum AddressSpots {
23    /// Groups `targets` so each is within `radius` metres of its spot's
24    /// coordinate, the spots with the most reports first. A fix is rarely
25    /// better than a few tens of metres, so reports this close are as likely
26    /// to have been at one address as at two.
27    static func group(_ targets: [AddressTarget], within radius: Double = 25) -> [AddressSpot] {
28        let cell = radius / metresPerDegree
29        var spots: [AddressSpot] = []
30        /// Spot indices by grid cell, so a target is compared only with the
31        /// spots in the cells around it.
32        var grid: [Cell: [Int]] = [:]
33        for target in targets {
34            let home = Cell(target.coordinate, size: cell)
35            let near = home.neighbours.lazy.flatMap { grid[$0] ?? [] }.first { index in
36                distance(spots[index].coordinate, target.coordinate) <= radius
37            }
38            if let near {
39                spots[near].reportIDs.append(target.id)
40            } else {
41                grid[home, default: []].append(spots.count)
42                spots.append(AddressSpot(coordinate: target.coordinate, reportIDs: [target.id]))
43            }
44        }
45        // Stable, so spots with as many reports keep the targets' order.
46        return spots.enumerated()
47            .sorted { lhs, rhs in
48                lhs.element.reportIDs.count != rhs.element.reportIDs.count
49                    ? lhs.element.reportIDs.count > rhs.element.reportIDs.count : lhs.offset < rhs.offset
50            }
51            .map(\.element)
52    }
53
54    private static let metresPerDegree = 111_320.0
55
56    /// Metres between two nearby coordinates, treating the earth as flat
57    /// over the distance.
58    static func distance(_ a: Coordinate, _ b: Coordinate) -> Double {
59        let latitude = (a.latitude - b.latitude) * metresPerDegree
60        let longitude =
61            (a.longitude - b.longitude) * metresPerDegree * cos((a.latitude + b.latitude) / 2 * .pi / 180)
62        return (latitude * latitude + longitude * longitude).squareRoot()
63    }
64
65    /// A square of the grid, `size` degrees of latitude high and as many
66    /// metres wide at its latitude.
67    private struct Cell: Hashable {
68        var row: Int
69        var column: Int
70
71        init(row: Int, column: Int) {
72            self.row = row
73            self.column = column
74        }
75
76        init(_ coordinate: Coordinate, size: Double) {
77            row = Int((coordinate.latitude / size).rounded(.down))
78            let width = size / max(cos(coordinate.latitude * .pi / 180), 0.01)
79            column = Int((coordinate.longitude / width).rounded(.down))
80        }
81
82        var neighbours: [Cell] {
83            (-1...1).flatMap { dr in (-1...1).map { dc in Cell(row: row + dr, column: column + dc) } }
84        }
85    }
86}
87
88/// Looks up the address at a coordinate.
89protocol AddressLooking: Sendable {
90    /// The address in the user's first language, then in the place's own
91    /// language if it differs, or none if there's no address there. Throws
92    /// `AddressLookupError.throttled` when asked too often.
93    func placemarks(at coordinate: Coordinate) async throws -> [Placemark]
94}
95
96enum AddressLookupError: Error {
97    case throttled
98}
99
100/// Addresses from MapKit, as new reports are given them.
101struct MapKitAddressLookup: AddressLooking {
102    func placemarks(at coordinate: Coordinate) async throws -> [Placemark] {
103        do {
104            return try await ContextCapture.placemarks(
105                for: CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude))
106        } catch let error as MKError where error.code == .loadingThrottled {
107            throw AddressLookupError.throttled
108        }
109    }
110}
111
112/// How far an address update has got.
113struct AddressFillProgress: Equatable, Sendable {
114    /// How many reports needed an address when the update started.
115    var total = 0
116    var updated = 0
117    /// Reports at spots MapKit has no address for. They keep the one they had.
118    var unfound = 0
119    /// Whether the update is waiting out MapKit's throttling.
120    var isWaiting = false
121}
122
123/// Gives reports the address MapKit would give them today, replacing one
124/// in an older form. Reports already in MapKit's form are left alone, so an
125/// update that stops can be run again to carry on.
126struct AddressFill: Sendable {
127    let store: ReportStore
128    let lookup: any AddressLooking
129    var radius = 25.0
130    /// How long to wait after MapKit throttles a lookup before trying again.
131    var throttlePause: Duration = .seconds(60)
132
133    /// Returns how far it got. `progress` is told after each spot. An error
134    /// other than throttling ends the update; addresses saved before it are
135    /// kept.
136    @discardableResult
137    func fill(progress: (@Sendable (AddressFillProgress) async -> Void)? = nil) async throws
138        -> AddressFillProgress
139    {
140        let targets = try await store.addressTargets()
141        var state = AddressFillProgress(total: targets.count)
142        await progress?(state)
143        for spot in AddressSpots.group(targets, within: radius) {
144            try Task.checkCancellation()
145            var placemarks: [Placemark]?
146            while placemarks == nil {
147                do {
148                    placemarks = try await lookup.placemarks(at: spot.coordinate)
149                } catch AddressLookupError.throttled {
150                    state.isWaiting = true
151                    await progress?(state)
152                    try await Task.sleep(for: throttlePause)
153                    state.isWaiting = false
154                }
155            }
156            if let placemarks, !placemarks.isEmpty {
157                try await store.setPlacemarks(placemarks, for: spot.reportIDs)
158                state.updated += spot.reportIDs.count
159            } else {
160                state.unfound += spot.reportIDs.count
161            }
162            await progress?(state)
163        }
164        return state
165    }
166}
167
168extension ReportStore {
169    /// Reports with an address that isn't in MapKit's form, newest first.
170    /// MapKit's addresses record their language; older ones don't. A report
171    /// without an address has nothing to upgrade, and is left without one.
172    func addressTargets() async throws -> [AddressTarget] {
173        let context = persistence.newBackgroundContext()
174        return try await context.perform {
175            let request = ReportEntity.fetchRequest()
176            request.predicate = NSPredicate(format: "context != nil")
177            request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
178            request.fetchBatchSize = 500
179            var targets: [AddressTarget] = []
180            for entity in try context.fetch(request) {
181                guard let id = entity.id, let data = entity.context,
182                    let location = try ModelCoding.decode(Context.self, from: data).location,
183                    let placemark = location.placemark, placemark.language == nil
184                else { continue }
185                targets.append(AddressTarget(id: id, coordinate: location.coordinate))
186                // Decoded contexts aren't needed once read.
187                context.refresh(entity, mergeChanges: false)
188            }
189            return targets
190        }
191    }
192
193    /// Gives the reports `placemarks` as their address: the first in the
194    /// user's first language, and the rest in other languages. The address
195    /// they had is replaced; for an imported report, Reporter's is still in
196    /// the Reporter export.
197    func setPlacemarks(_ placemarks: [Placemark], for ids: [UUID], now: Date = Date()) async throws {
198        guard let first = placemarks.first else { return }
199        let context = persistence.newBackgroundContext()
200        try await context.perform {
201            let request = ReportEntity.fetchRequest()
202            request.predicate = NSPredicate(format: "id IN %@", ids)
203            for entity in try context.fetch(request) {
204                guard let data = entity.context else { continue }
205                var captured = try ModelCoding.decode(Context.self, from: data)
206                guard captured.location != nil else { continue }
207                captured.location?.placemark = first
208                captured.location?.localisedPlacemarks = placemarks.count > 1 ? Array(placemarks.dropFirst()) : nil
209                entity.context = try ModelCoding.encode(captured)
210                entity.modifiedAt = now
211            }
212            try context.save()
213        }
214    }
215}
216
217/// Runs an address update for the app when the user asks, keeping the
218/// screen on meanwhile: a locked iPhone would suspend the app, and the
219/// update with it.
220@MainActor
221@Observable
222final class AddressUpdater {
223    /// How far the update has got, while it runs.
224    private(set) var progress: AddressFillProgress?
225    /// How the last update ended, until another starts.
226    private(set) var outcome: AddressFillProgress?
227
228    @ObservationIgnored private let store: ReportStore
229    @ObservationIgnored private var task: Task<Void, Never>?
230    private static let log = EventLog.shared.category("Addresses")
231
232    init(store: ReportStore) {
233        self.store = store
234    }
235
236    var isUpdating: Bool { progress != nil }
237
238    func start() {
239        guard task == nil else { return }
240        progress = AddressFillProgress()
241        outcome = nil
242        UIApplication.shared.isIdleTimerDisabled = true
243        task = Task {
244            defer {
245                outcome = progress
246                outcome?.isWaiting = false
247                task = nil
248                progress = nil
249                UIApplication.shared.isIdleTimerDisabled = false
250            }
251            do {
252                let last = try await AddressFill(store: store, lookup: MapKitAddressLookup()).fill { state in
253                    await MainActor.run { self.progress = state }
254                }
255                Self.log.info("Updated \(last.updated) addresses; \(last.unfound) had none")
256            } catch is CancellationError {
257                Self.log.info("Stopped updating addresses after \(self.progress?.updated ?? 0)")
258            } catch {
259                Self.log.error("Couldn't update addresses: \(error)")
260            }
261        }
262    }
263
264    func stop() {
265        task?.cancel()
266    }
267}