Reportage/Services/Health/HealthFill.swift (8232B)
1import CoreData
2import Foundation
3import HealthKit
4
5
6
7struct HealthFill: Sendable {
8 let store: ReportStore
9 let reader: any HealthReading
10
11 var settleAfter: TimeInterval = 24 * 60 * 60
12
13 var sleepWindow: TimeInterval = 18 * 60 * 60
14 var batchSize = 50
15
16
17
18
19
20 @discardableResult
21 func fill(
22 since: Date? = nil, before: Date, now: Date = Date(),
23 progress: (@Sendable (Int) async -> Void)? = nil
24 ) async throws -> Int {
25 var cursor = before
26 var count = 0
27 while true {
28 try Task.checkCancellation()
29 let targets = try await store.healthTargets(since: since, before: cursor, limit: batchSize)
30 guard let last = targets.last else { break }
31 for target in targets {
32 try Task.checkCancellation()
33 try await store.setHealth(read(target, now: now), for: target.id)
34 count += 1
35 }
36 await progress?(count)
37
38
39 cursor = last.date
40 }
41 return count
42 }
43
44 func read(_ target: HealthTarget, now: Date) async throws -> HealthRecord {
45 var calendar = Calendar(identifier: .gregorian)
46 calendar.timeZone = TimeZone(identifier: target.timeZone) ?? .current
47 var health = HealthContext()
48 let activity = try await reader.activity(from: calendar.startOfDay(for: target.date), to: target.date)
49 if activity != ActivityHealth() {
50 health.activity = activity
51 }
52 if target.kind == .wake {
53 let samples = try await reader.sleepSamples(
54 from: target.date.addingTimeInterval(-sleepWindow), to: target.date)
55 health.sleep = SleepHealth(samples: samples)
56 }
57 return HealthRecord(
58 health: health, derivedAt: now,
59 isSettled: now >= target.date.addingTimeInterval(settleAfter))
60 }
61}
62
63
64
65@MainActor
66enum HealthAccess {
67 private static let key = "healthAskedAt"
68 private static let log = EventLog.shared.category("Health")
69
70 static var isAvailable: Bool { HKHealthStore.isHealthDataAvailable() }
71
72
73 static func needsAsking(store: HKHealthStore = HKHealthStore()) async -> Bool {
74 guard isAvailable else { return false }
75 let status = try? await store.statusForAuthorizationRequest(toShare: [], read: HealthKitReader.readTypes)
76 return status == .shouldRequest
77 }
78
79 static func ask(store: HKHealthStore = HKHealthStore(), defaults: UserDefaults = .standard) async {
80 guard await needsAsking(store: store) else { return }
81 do {
82 try await store.requestAuthorization(toShare: [], read: HealthKitReader.readTypes)
83 log.info("Asked for Health access")
84 } catch {
85 log.error("Couldn't ask for Health access: \(error)")
86 return
87 }
88 if defaults.object(forKey: key) == nil {
89 defaults.set(Date(), forKey: key)
90 }
91 }
92
93
94
95
96 static func askedAt(store: HKHealthStore = HKHealthStore(), defaults: UserDefaults = .standard) async -> Date? {
97 if let date = defaults.object(forKey: key) as? Date { return date }
98 guard isAvailable,
99 (try? await store.statusForAuthorizationRequest(toShare: [], read: HealthKitReader.readTypes))
100 == .unnecessary
101 else { return nil }
102 let now = Date()
103 defaults.set(now, forKey: key)
104 return now
105 }
106}
107
108
109
110
111
112
113@MainActor
114@Observable
115final class HealthFiller {
116
117 private(set) var pastCount: Int?
118
119 @ObservationIgnored private let store: ReportStore
120 @ObservationIgnored private let healthStore = HKHealthStore()
121 @ObservationIgnored private var recentTask: Task<Void, Never>?
122 @ObservationIgnored private var pastTask: Task<Void, Never>?
123
124 @ObservationIgnored private var isRecentStale = false
125 @ObservationIgnored private var observer: (any NSObjectProtocol)?
126 private static let log = EventLog.shared.category("Health")
127
128 init(store: ReportStore) {
129 self.store = store
130 let coordinator = store.persistence.container.persistentStoreCoordinator
131 observer = NotificationCenter.default.addObserver(
132 forName: NSManagedObjectContext.didSaveObjectIDsNotification, object: nil, queue: nil
133 ) { [weak self] notification in
134 guard (notification.object as? NSManagedObjectContext)?.persistentStoreCoordinator === coordinator,
135 let inserted = notification.userInfo?[NSInsertedObjectIDsKey] as? Set<NSManagedObjectID>,
136 inserted.contains(where: { $0.entity.name == "ReportEntity" })
137 else { return }
138 Task { @MainActor in self?.fillRecent() }
139 }
140 }
141
142 private var fill: HealthFill {
143 HealthFill(store: store, reader: HealthKitReader(store: healthStore))
144 }
145
146 func fillRecent() {
147 guard recentTask == nil else {
148 isRecentStale = true
149 return
150 }
151 recentTask = Task {
152 guard let since = await HealthAccess.askedAt(store: healthStore) else {
153 recentTask = nil
154 return
155 }
156 repeat {
157 isRecentStale = false
158 do {
159 let count = try await fill.fill(since: since, before: .distantFuture)
160 if count > 0 { Self.log.info("Read Health for \(count) recent reports") }
161 } catch {
162 Self.log.error("Couldn't read Health for recent reports: \(error)")
163 isRecentStale = false
164 }
165 } while isRecentStale
166 recentTask = nil
167 }
168 }
169
170 var isFillingPast: Bool { pastCount != nil }
171
172 func fillPast() {
173 guard pastTask == nil else { return }
174 pastCount = 0
175 pastTask = Task {
176 defer {
177 pastTask = nil
178 pastCount = nil
179 }
180
181
182 guard let since = await HealthAccess.askedAt(store: healthStore) else { return }
183 do {
184 let count = try await fill.fill(before: since) { count in
185 await MainActor.run { self.pastCount = count }
186 }
187 Self.log.info("Read Health for \(count) earlier reports")
188 } catch is CancellationError {
189 Self.log.info("Stopped reading Health for earlier reports")
190 } catch {
191 Self.log.error("Couldn't read Health for earlier reports: \(error)")
192 }
193 }
194 }
195
196 func stopPast() {
197 pastTask?.cancel()
198 }
199}