Reportage/Services/Places/AddressFill.swift (10829B)
1import CoreData
2import CoreLocation
3import Foundation
4import MapKit
5import UIKit
6
7
8
9
10struct AddressTarget: Equatable, Sendable {
11 var id: UUID
12 var coordinate: Coordinate
13}
14
15
16struct AddressSpot: Equatable, Sendable {
17
18 var coordinate: Coordinate
19 var reportIDs: [UUID]
20}
21
22enum AddressSpots {
23
24
25
26
27 static func group(_ targets: [AddressTarget], within radius: Double = 25) -> [AddressSpot] {
28 let cell = radius / metresPerDegree
29 var spots: [AddressSpot] = []
30
31
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
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
57
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
66
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
89protocol AddressLooking: Sendable {
90
91
92
93 func placemarks(at coordinate: Coordinate) async throws -> [Placemark]
94}
95
96enum AddressLookupError: Error {
97 case throttled
98}
99
100
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
113struct AddressFillProgress: Equatable, Sendable {
114
115 var total = 0
116 var updated = 0
117
118 var unfound = 0
119
120 var isWaiting = false
121}
122
123
124
125
126struct AddressFill: Sendable {
127 let store: ReportStore
128 let lookup: any AddressLooking
129 var radius = 25.0
130
131 var throttlePause: Duration = .seconds(60)
132
133
134
135
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
170
171
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
187 context.refresh(entity, mergeChanges: false)
188 }
189 return targets
190 }
191 }
192
193
194
195
196
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
218
219
220@MainActor
221@Observable
222final class AddressUpdater {
223
224 private(set) var progress: AddressFillProgress?
225
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}