HealthKitRawDataHostApiImpl.swift
14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import Foundation
import UIKit
final class HealthKitRawDataHostApiImpl: HealthKitRawDataHostApi {
private var localNotificationDebugFileURL: URL {
FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
.appendingPathComponent("local_notification_debug_events.json")
}
func saveLocalNotificationRecord(notificationType: String, timestamp: Int64, completion: @escaping (Result<Bool, any Error>) -> Void) {
saveLocalNotificationDebugEvent(
event: [
"event": "nativeLocalNotificationRecord",
"notification_type": notificationType,
"timestamp": timestamp,
],
completion: completion
)
}
func saveLocalNotificationDebugEvent(event: [String: Any?], completion: @escaping (Result<Bool, any Error>) -> Void) {
do {
var payload = sanitizeJSONObject(event) as? [String: Any] ?? [:]
let now = Date()
payload["saved_at_unix"] = now.timeIntervalSince1970
payload["saved_at"] = ISO8601DateFormatter().string(from: now)
payload["process_name"] = ProcessInfo.processInfo.processName
var events = try readLocalNotificationDebugEvents()
events.append(payload)
let data = try JSONSerialization.data(
withJSONObject: events,
options: [.prettyPrinted, .sortedKeys]
)
try data.write(to: localNotificationDebugFileURL, options: .atomic)
completion(.success(true))
} catch {
completion(.failure(error))
}
}
func shareLocalNotificationDebugRecord(completion: @escaping (Result<Bool, any Error>) -> Void) {
do {
if !FileManager.default.fileExists(atPath: localNotificationDebugFileURL.path) {
try Data("[]".utf8).write(to: localNotificationDebugFileURL, options: .atomic)
}
shareItems([localNotificationDebugFileURL], completion: completion)
} catch {
completion(.failure(error))
}
}
func shareUploadTaskRecord(completion: @escaping (Result<Bool, any Error>) -> Void) {
}
func saveNativeCallFlutterChange(relativeDataTypes: [Int64], completion: @escaping (Result<Bool, any Error>) -> Void) {
}
func saveFlutterCaculateFinished(relativeDataTypes: [Int64], completion: @escaping (Result<Bool, any Error>) -> Void) {
}
func shareNativeAppleHealthObserverRecord(completion: @escaping (Result<Bool, any Error>) -> Void) {
}
func shareFlutterObserverRecord(completion: @escaping (Result<Bool, any Error>) -> Void) {
let timestamp = Int64(Date().timeIntervalSince1970.rounded())
let dataTypes = NativeHealthDataType.allCases
.map(\.rawValue)
.sorted()
DispatchQueue.main.async {
NotificationCenter.default.post(
name: .nativeHealthDataDidUpdate,
object: nil,
userInfo: [
"dataTypes": dataTypes,
"timestamp": timestamp,
]
)
completion(.success(true))
}
}
private let service: HealthKitService
init(service: HealthKitService = .shared) {
self.service = service
}
private func readLocalNotificationDebugEvents() throws -> [[String: Any]] {
guard FileManager.default.fileExists(atPath: localNotificationDebugFileURL.path) else {
return []
}
let data = try Data(contentsOf: localNotificationDebugFileURL)
guard !data.isEmpty else { return [] }
let decoded = try JSONSerialization.jsonObject(with: data)
return decoded as? [[String: Any]] ?? []
}
private func sanitizeJSONObject(_ value: Any?) -> Any {
guard let value else { return NSNull() }
if let dictionary = value as? [String: Any?] {
return dictionary.mapValues { sanitizeJSONObject($0) }
}
if let dictionary = value as? [String: Any] {
return dictionary.mapValues { sanitizeJSONObject($0) }
}
if let array = value as? [Any?] {
return array.map { sanitizeJSONObject($0) }
}
if JSONSerialization.isValidJSONObject([value]) {
return value
}
return String(describing: value)
}
private func shareItems(_ items: [Any], completion: @escaping (Result<Bool, any Error>) -> Void) {
DispatchQueue.main.async {
guard let viewController = Self.topViewController() else {
completion(.failure(NSError(
domain: "HealthKitRawDataHostApiImpl.Share",
code: 1,
userInfo: [NSLocalizedDescriptionKey: "Unable to find a view controller for sharing."]
)))
return
}
let activityController = UIActivityViewController(
activityItems: items,
applicationActivities: nil
)
activityController.popoverPresentationController?.sourceView = viewController.view
activityController.popoverPresentationController?.sourceRect = CGRect(
x: viewController.view.bounds.midX,
y: viewController.view.bounds.midY,
width: 1,
height: 1
)
activityController.completionWithItemsHandler = { _, completed, _, error in
if let error {
completion(.failure(error))
} else {
completion(.success(completed))
}
}
viewController.present(activityController, animated: true)
}
}
private static func topViewController(
base: UIViewController? = UIApplication.shared
.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap { $0.windows }
.first { $0.isKeyWindow }?
.rootViewController
) -> UIViewController? {
if let navigationController = base as? UINavigationController {
return topViewController(base: navigationController.visibleViewController)
}
if let tabBarController = base as? UITabBarController {
return topViewController(base: tabBarController.selectedViewController)
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
func hasHealthData(completion: @escaping (Result<Bool, Error>) -> Void) {
Task {
let hasData = await service.hasAnyReadableData()
completion(.success(hasData))
}
}
func performHealthDataUpload(completion: @escaping (Result<Bool, any Error>) -> Void) {
print("trigger HealthDataUpload")
Task {
let summary = await AnchoredHealthDataUploader.shared.uploadAll()
completion(.success(true))
}
}
func syncDatabase(hrDataPath: String, hrvDataPath: String, sleepDataPath: String, avgRealtimeStressDataPath: String, completion: @escaping (Result<Bool, any Error>) -> Void) {
HealthRawStressSQLiteUploader.shared.syncDatabase(
hrDataPath: hrDataPath,
hrvDataPath: hrvDataPath,
sleepDataPath: sleepDataPath,
avgRealtimeStressDataPath: avgRealtimeStressDataPath
)
completion(.success(true))
}
func performHRDataUpload(sqliteFilePath: String, completion: @escaping (Result<Int64, any Error>) -> Void) {
print("trigger HRDataUpload")
Task {
do {
let uploadedUntil = try await HealthRawStressSQLiteUploader.shared.uploadRealtimeStress(sqliteFilePath: sqliteFilePath)
completion(.success(uploadedUntil))
} catch {
completion(.failure(error))
}
}
}
func performHRVDataUpload(sqliteFilePath: String, completion: @escaping (Result<Int64, any Error>) -> Void) {
print("trigger HRVDataUpload")
Task {
do {
let uploadedUntil = try await HealthRawStressSQLiteUploader.shared.uploadHrv(sqliteFilePath: sqliteFilePath)
completion(.success(uploadedUntil))
} catch {
completion(.failure(error))
}
}
}
func performAvgRealtimeStressDataUpload(sqliteFilePath: String, completion: @escaping (Result<Int64, any Error>) -> Void) {
print("trigger AvgRealtimeStressDataUpload")
Task {
do {
let uploadedUntil = try await HealthRawStressSQLiteUploader.shared.uploadDailyStress(sqliteFilePath: sqliteFilePath)
completion(.success(uploadedUntil))
} catch {
completion(.failure(error))
}
}
}
func performSleepAnalysisDataUpload(sqliteFilePath: String, completion: @escaping (Result<Int64, any Error>) -> Void) {
print("trigger SleepAnalysisDataUpload")
Task {
do {
let uploadedUntil = try await HealthRawStressSQLiteUploader.shared.uploadSleepScore(sqliteFilePath: sqliteFilePath)
completion(.success(uploadedUntil))
} catch {
completion(.failure(error))
}
}
}
func getHealthKitRawData(
dataType: Int64,
startTime: Int64,
endTime: Int64,
completion: @escaping (Result<[HealthKitRawDataPoint], Error>) -> Void
) {
guard let nativeDataType = NativeHealthDataType(rawValue: Int(dataType)) else {
completion(.failure(PigeonError(
code: "invalid_data_type",
message: "无效的健康数据类型:\(dataType)",
details: nil
)))
return
}
guard nativeDataType != .sleep else {
completion(.failure(PigeonError(
code: "unsupported_data_type",
message: "睡眠数据请使用 getHealthKitRawSleepData 读取",
details: nil
)))
return
}
let startDate = Date(timeIntervalSince1970: TimeInterval(startTime))
let endDate = Date(timeIntervalSince1970: TimeInterval(endTime))
Task {
do {
let points = try await service.fetchRawData(
for: nativeDataType,
startDate: startDate,
endDate: endDate
)
completion(.success(points.map { Self.rawDataPoint(from: $0, dataType: nativeDataType) }))
} catch {
completion(.failure(error))
}
}
}
func getHealthKitRawSleepData(
startTime: Int64,
endTime: Int64,
completion: @escaping (Result<[HealthKitRawSleepDataPoint], Error>) -> Void
) {
let startDate = Date(timeIntervalSince1970: TimeInterval(startTime))
let endDate = Date(timeIntervalSince1970: TimeInterval(endTime))
print("trigger getHealthKitRawSleepData from: \(startDate) to \(endDate)")
Task {
do {
let intervals = try await service.fetchSleepData(
startDate: startDate,
endDate: endDate
)
let points = intervals.map(Self.sleepDataPoint)
guard !points.isEmpty else {
completion(.success([]))
return
}
completion(.success([
HealthKitRawSleepDataPoint(
dataType: Int64(NativeHealthDataType.sleep.rawValue),
sleepDataPoints: points
)
]))
} catch {
completion(.failure(error))
}
}
}
func getHealthKitRawActivityData(
startTime: Int64,
endTime: Int64,
completion: @escaping (Result<[HealthKitRawActivityDataPoint], Error>) -> Void
) {
let startDate = Date(timeIntervalSince1970: TimeInterval(startTime))
let endDate = Date(timeIntervalSince1970: TimeInterval(endTime))
Task {
do {
let targets = try await service.fetchActivityTargetDataList(
startDate: startDate,
endDate: endDate
)
completion(.success(targets.compactMap(Self.activityDataPoint)))
} catch {
completion(.failure(error))
}
}
}
func getHealthKitRawWorkoutData(
startTime: Int64,
endTime: Int64,
completion: @escaping (Result<[HealthKitRawWorkoutDataPoint], Error>) -> Void
) {
let startDate = Date(timeIntervalSince1970: TimeInterval(startTime))
let endDate = Date(timeIntervalSince1970: TimeInterval(endTime))
Task {
do {
let workouts = try await service.fetchWorkoutDataList(
startDate: startDate,
endDate: endDate
)
completion(.success(workouts.map(Self.workoutDataPoint)))
} catch {
completion(.failure(error))
}
}
}
func performSleepDataUpload(completion: @escaping (Result<Bool, Error>) -> Void) {
Task {
let summary = await AnchoredHealthDataUploader.shared.uploadAll()
completion(.success(summary.sleepUploadSuccess))
}
}
private static func rawDataPoint(
from point: NativeHealthRawDataPoint,
dataType: NativeHealthDataType
) -> HealthKitRawDataPoint {
HealthKitRawDataPoint(
dataType: Int64(dataType.rawValue),
startTime: Int64(point.startTime.rounded()),
endTime: Int64(point.endTime.rounded()),
value: point.value
)
}
private static func sleepDataPoint(from interval: NativeSleepInterval) -> HealthKitRawDataPoint {
HealthKitRawDataPoint(
dataType: Int64(interval.dataType),
startTime: Int64(interval.fromTime.rounded()),
endTime: Int64(interval.toTime.rounded()),
value: nil
)
}
private static func activityDataPoint(from target: NativeActivityTarget) -> HealthKitRawActivityDataPoint? {
guard let endTime = target.healthValueTimestamp else {
return nil
}
return HealthKitRawActivityDataPoint(
endTime: Int64(endTime.rounded()),
activityMoveMode: target.activityMoveMode == nil ? nil : Int64(target.activityMoveMode!),
activeEnergyBurned: target.activeEnergyBurned,
activeEnergyBurnedGoal: target.activeEnergyBurnedGoal,
appleMoveTime: target.appleMoveTime,
appleMoveTimeGoal: target.appleMoveTimeGoal,
appleExerciseTime: target.appleExerciseTime,
exerciseTimeGoal: target.exerciseTimeGoal,
appleStandHours: target.appleStandHours,
standHoursGoal: target.standHoursGoal
)
}
private static func workoutDataPoint(from workout: NativeWorkoutInterval) -> HealthKitRawWorkoutDataPoint {
HealthKitRawWorkoutDataPoint(
workoutType: Int64(workout.workoutType),
startTime: Int64(workout.startTime.rounded()),
endTime: Int64(workout.endTime.rounded())
)
}
}