← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Services/Health/HealthFill.swift (8232B)

1import CoreData
2import Foundation
3import HealthKit
4
5/// Fills in the Health cache: reads Health for reports whose entry is
6/// missing or not yet settled, newest first.
7struct HealthFill: Sendable {
8    let store: ReportStore
9    let reader: any HealthReading
10    /// How long after a report its Health is taken to have stopped changing.
11    var settleAfter: TimeInterval = 24 * 60 * 60
12    /// How far before a wake report to look for the night's sleep.
13    var sleepWindow: TimeInterval = 18 * 60 * 60
14    var batchSize = 50
15
16    /// Fills the reports dated before `before`, and on or after `since` if
17    /// given, and returns how many it read. `progress` is told the running
18    /// count after each batch. Health being locked, or any other error from
19    /// it, ends the pass; what was read before it is kept.
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            // Entries that aren't settled yet would be found again, so the
38            // next batch starts after this one.
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/// Asking for Health access, and when it was first asked for. Reports from
64/// then on are filled in automatically; earlier ones only when the user asks.
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    /// Whether asking would show Health's access sheet.
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    /// When Health access was first asked for, or `nil` if it hasn't been.
94    /// Access asked for some other way, as it may be after a restore, counts
95    /// from the first time this finds it.
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/// Runs Health passes for the app: reports filed since Health was asked for,
109/// each time the app comes to the foreground and whenever a report is filed,
110/// and earlier reports when the user asks. Health can only be read while the
111/// iPhone is unlocked, so a report filed while it's locked waits for the app
112/// to come to the foreground.
113@MainActor
114@Observable
115final class HealthFiller {
116    /// How many earlier reports have been filled in, while that pass runs.
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    /// Whether a report was filed while a recent pass was running.
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            // Reports filed before Health was asked for. Nothing is read
181            // until it has been.
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}