// ONE PAGE OF A TYPE'S SAMPLES as `health.land` reads it // (`cotton_core::health::land`): the touched days' statistics, the touched // days' intervals sent whole, each workout and each measurement, and the // deleted objects. Every number is in the unit `health.types` named. import CottonKit import Foundation import HealthKit struct HealthBatch { var days: [JSONValue] = [] var intervals: [JSONValue] = [] var workouts: [JSONValue] = [] var measurements: [JSONValue] = [] var deleted: [String] = [] func request(anchors: [String: String]) -> JSONValue { .object([ "source": "healthkit", "days": .array(days), "intervals": .array(intervals), "workouts": .array(workouts), "measurements": .array(measurements), "deleted": .array(deleted.map(JSONValue.string)), "anchors": .object(anchors.mapValues(JSONValue.string)), ]) } /// What `added` sends for `type`, as the core named it. mutating func take(_ added: [HKSample], of type: HealthReadType, from reader: HealthReader) async throws { guard !added.isEmpty else { return } let unit = type.unit.flatMap { $0.isEmpty ? nil : HKUnit(from: $0) } if type.sends.contains("days"), let quantity = type.sampleType as? HKQuantityType, let unit { let touched = Set(added.flatMap { HealthDays.touched($0.startDate, $0.endDate) }).sorted() days += try await reader.dayStatistics(quantity, option: type.statistics, unit: unit, days: touched) } if type.sends.contains("intervals"), let category = type.sampleType as? HKCategoryType { let touched = Set(added.flatMap { HealthDays.touched($0.startDate, $0.endDate) }).sorted() if let from = touched.first, let to = touched.last { try await takeWhole(category, of: type, from: from, to: to, reader: reader) } } if type.sends.contains("workouts") { workouts += added.compactMap { $0 as? HKWorkout }.map(Self.workout) } if type.sends.contains("measurements") { measurements += added.compactMap { Self.measurement($0, type: type, unit: unit) } } } /// Every sample of a category touching the days `from`…`to`, sent whole: /// those days are folded again, and a day now holding none goes. mutating func takeWhole(_ category: HKCategoryType, of type: HealthReadType, from: String, to: String, reader: HealthReader) async throws { let whole = try await reader.samples(category, from: from, to: to) intervals.append(.object([ "type": .string(type.healthkit), "from": .string(from), "to": .string(to), "samples": .array(whole.map { sample in .object([ "start": .string(HealthDays.instant(sample.startDate)), "end": .string(HealthDays.instant(sample.endDate)), "value": .number(Double(sample.value)), "device": Self.device(sample), ]) }), ])) } static func device(_ sample: HKSample) -> JSONValue { let name = sample.device?.name ?? sample.sourceRevision.source.name return name.isEmpty ? .null : .string(name) } static func workout(_ workout: HKWorkout) -> JSONValue { var entry: [String: JSONValue] = [ "uuid": .string(workout.uuid.uuidString), "activity": .number(Double(workout.workoutActivityType.rawValue)), "start": .string(HealthDays.instant(workout.startDate)), "end": .string(HealthDays.instant(workout.endDate)), "device": device(workout), ] // Its distance, whichever kind it covered, and its active energy. let distances: [HKQuantityTypeIdentifier] = [.distanceWalkingRunning, .distanceCycling, .distanceSwimming, .distanceWheelchair, .distanceDownhillSnowSports, .distanceRowing, .distancePaddleSports, .distanceSkatingSports, .distanceCrossCountrySkiing] let metres = distances.compactMap { workout.statistics(for: HKQuantityType($0))?.sumQuantity()?.doubleValue(for: .meter()) }.reduce(0, +) if metres > 0 { entry["distance_m"] = .number(metres) } if let energy = workout.statistics(for: HKQuantityType(.activeEnergyBurned))?.sumQuantity()?.doubleValue(for: .kilocalorie()) { entry["energy_kcal"] = .number(energy) } let beats = HKUnit.count().unitDivided(by: .minute()) if let heart = workout.statistics(for: HKQuantityType(.heartRate)) { if let average = heart.averageQuantity() { entry["heart_rate_avg"] = .number(average.doubleValue(for: beats)) } if let most = heart.maximumQuantity() { entry["heart_rate_max"] = .number(most.doubleValue(for: beats)) } } return .object(entry) } static func measurement(_ sample: HKSample, type: HealthReadType, unit: HKUnit?) -> JSONValue? { var entry: [String: JSONValue] = [ "type": .string(type.healthkit), "uuid": .string(sample.uuid.uuidString), "at": .string(HealthDays.instant(sample.startDate)), "device": device(sample), ] if let correlation = sample as? HKCorrelation { let mmHg = HKUnit.millimeterOfMercury() let part = { (id: HKQuantityTypeIdentifier) in (correlation.objects(for: HKQuantityType(id)).first as? HKQuantitySample)?.quantity.doubleValue(for: mmHg) } guard let systolic = part(.bloodPressureSystolic), let diastolic = part(.bloodPressureDiastolic) else { return nil } entry["systolic"] = .number(systolic) entry["diastolic"] = .number(diastolic) return .object(entry) } guard let quantity = sample as? HKQuantitySample, let unit else { return nil } entry["value"] = .number(quantity.quantity.doubleValue(for: unit)) if let meal = sample.metadata?[HKMetadataKeyBloodGlucoseMealTime] as? NSNumber { entry["meal"] = .number(meal.doubleValue) } return .object(entry) } }