apple_health_upload_tool.dart
11 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
import 'package:doublefeel_flutter/core/result/app_result.dart';
import 'package:doublefeel_flutter/core/logging/app_logger.dart';
import 'package:doublefeel_flutter/data/local/user_preferences_storage.dart';
import 'package:doublefeel_flutter/pigeon/health_kit_api.g.dart';
import 'apple_health_upload_api.dart';
import 'apple_health_upload_local_recorder.dart';
import 'health_kit_upload_mapper.dart';
import 'models/apple_health_upload_record.dart';
import 'models/apple_health_upload_request.dart';
import 'models/apple_health_upload_sample.dart';
import 'models/health_upload_data_type.dart';
import 'models/upload_activity_target.dart';
import 'models/upload_sleep.dart';
class AppleHealthUploadTool {
AppleHealthUploadTool(
this._api,
this._localRecorder,
this._userPreferences, {
HealthKitHostApi? hostApi,
}) : _hostApi = hostApi ?? HealthKitHostApi();
final AppleHealthUploadApi _api;
final AppleHealthUploadLocalRecorder _localRecorder;
final UserPreferencesStorage _userPreferences;
final HealthKitHostApi _hostApi;
static const _historyWindow = Duration(days: 365 * 2);
static const _commonTypes = [
HealthUploadDataType.hrv,
HealthUploadDataType.heartRate,
HealthUploadDataType.walkingHeartRate,
HealthUploadDataType.restingHeartRate,
HealthUploadDataType.sleepingHeartRate,
HealthUploadDataType.oxygenSaturation,
HealthUploadDataType.activeEnergy,
HealthUploadDataType.exercise,
HealthUploadDataType.stand,
HealthUploadDataType.steps,
HealthUploadDataType.sleepingWristTemperature,
HealthUploadDataType.respiratoryRate,
HealthUploadDataType.irregularHeartRhythm,
];
Future<AppleHealthUploadResult> upload({
List<AppleHealthUploadSample> commonData = const [],
List<HealthSleepUploadData> sleepData = const [],
HealthActivityTargetUploadData? activityTarget,
}) async {
AppResult<void>? commonResult;
AppResult<void>? sleepResult;
AppResult<void>? activityTargetResult;
if (commonData.isNotEmpty) {
commonResult = await _api.uploadCommonData(
AppleHealthCommonUploadRequest(dataList: commonData),
);
}
if (sleepData.isNotEmpty) {
sleepResult = await _api.uploadSleepData(
AppleHealthSleepUploadRequest(dataList: sleepData),
);
}
if (activityTarget != null) {
activityTargetResult = await _api.uploadActivityTarget(activityTarget);
}
return AppleHealthUploadResult(
commonUploadSuccess:
commonResult == null || commonResult is AppSuccess<void>,
sleepUploadSuccess:
sleepResult == null || sleepResult is AppSuccess<void>,
activityTargetUploadSuccess: activityTargetResult == null ||
activityTargetResult is AppSuccess<void>,
);
}
Future<AppResult<AppleHealthLatestUploadRecordList>>
getLatestCommonUploadRecordList() {
return _api.getLatestCommonUploadRecordList();
}
Future<AppResult<AppleHealthLatestSleepUploadRecord>>
getLatestSleepUploadRecord() {
return _api.getLatestSleepUploadRecord();
}
Future<AppleHealthUploadResult> uploadAllNewDataFromHealthKit() async {
final userId = _userPreferences.preferences.value.meUserInfo?.id ?? 0;
if (userId <= 0) {
return const AppleHealthUploadResult(
commonUploadSuccess: false,
sleepUploadSuccess: false,
activityTargetUploadSuccess: false,
);
}
final endTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
final startTimes = await _resolveStartTimes(userId);
final commonDataByType =
<HealthUploadDataType, List<AppleHealthUploadSample>>{};
for (final type in _commonTypes) {
final points = await _safeFetchCommonDataPointList(
type: type,
startTime: startTimes[type] ?? _fallbackStartTime(),
endTime: endTime,
);
final models = points
.map((point) => point.toAppleHealthUploadSample())
.whereType<AppleHealthUploadSample>()
.toList();
commonDataByType[type] = models;
}
final sleepPoints = await _safeFetchSleepDataPointList(
startTimes[HealthUploadDataType.sleep] ?? _fallbackStartTime(),
endTime,
);
final sleepData =
sleepPoints.map((item) => item.toHealthSleepUploadData()).toList();
final activityTarget = await _fetchActivityTarget(startTimes, endTime);
final commonData = commonDataByType.values
.expand((items) => items)
.toList(growable: false);
final result = await upload(
commonData: commonData,
sleepData: sleepData,
activityTarget: activityTarget,
);
if (result.commonUploadSuccess) {
final uploadedCommonTypes = <HealthUploadDataType, int>{};
for (final entry in commonDataByType.entries) {
if (entry.value.isNotEmpty) {
uploadedCommonTypes[entry.key] = endTime;
}
}
await _localRecorder.saveLatestDataTimes(
userId: userId,
latestDataTimes: uploadedCommonTypes,
);
}
if (result.sleepUploadSuccess && sleepData.isNotEmpty) {
await _localRecorder.saveLatestDataTime(
userId: userId,
dataType: HealthUploadDataType.sleep,
latestDataTime: endTime,
);
}
return AppleHealthUploadResult(
commonUploadSuccess: result.commonUploadSuccess,
sleepUploadSuccess: result.sleepUploadSuccess,
activityTargetUploadSuccess: result.activityTargetUploadSuccess,
commonCount: commonData.length,
sleepCount: sleepData.length,
activityTargetCount: activityTarget == null ? 0 : 1,
);
}
Future<Map<HealthUploadDataType, int>> _resolveStartTimes(int userId) async {
final localRecords = _localRecorder.load(userId);
final serverCommonRecords = await _serverCommonRecordMap();
final serverSleepRecord = await _serverSleepLatestTime();
final result = <HealthUploadDataType, int>{};
for (final type in [..._commonTypes, HealthUploadDataType.sleep]) {
final serverTime = type == HealthUploadDataType.sleep
? serverSleepRecord
: serverCommonRecords[type];
result[type] = _resolveStartTime(
localTime: localRecords.latestDataTime(type),
serverTime: serverTime,
);
}
return result;
}
Future<Map<HealthUploadDataType, int>> _serverCommonRecordMap() async {
final result = await _api.getLatestCommonUploadRecordList(
errorHandlingPolicy: null,
);
if (result
case AppSuccess<AppleHealthLatestUploadRecordList>(data: final data)) {
final records = data.latestDataTimeList ?? const [];
return {
for (final record in records)
if (record.dataType != null && record.latestDataTime != null)
record.dataType!: record.latestDataTime!,
};
}
return {};
}
Future<int?> _serverSleepLatestTime() async {
final result = await _api.getLatestSleepUploadRecord(
errorHandlingPolicy: null,
);
if (result
case AppSuccess<AppleHealthLatestSleepUploadRecord>(data: final data)) {
return data.latestDataTime;
}
return null;
}
int _resolveStartTime({int? localTime, int? serverTime}) {
final fallback = _fallbackStartTime();
if (localTime != null && localTime > fallback) return localTime;
if (serverTime != null && serverTime > fallback) return serverTime;
return fallback;
}
int _fallbackStartTime() {
final start = DateTime.now().subtract(_historyWindow);
return DateTime(start.year, start.month, start.day)
.millisecondsSinceEpoch ~/
1000;
}
Future<List<HealthUploadDataPoint>> _safeFetchCommonDataPointList({
required HealthUploadDataType type,
required int startTime,
required int endTime,
}) async {
try {
return await _fetchCommonDataPointList(type, startTime, endTime);
} catch (error, stackTrace) {
AppLogger.w(
'Fetch Apple Health data failed: $type',
error,
stackTrace,
);
return const [];
}
}
Future<List<HealthSleepUploadDataPoint>> _safeFetchSleepDataPointList(
int startTime,
int endTime,
) async {
try {
return await _hostApi.fetchSleepData(startTime, endTime);
} catch (error, stackTrace) {
AppLogger.w('Fetch Apple Health sleep data failed', error, stackTrace);
return const [];
}
}
Future<List<HealthUploadDataPoint>> _fetchCommonDataPointList(
HealthUploadDataType type,
int startTime,
int endTime,
) {
return switch (type) {
HealthUploadDataType.hrv => _hostApi.fetchHrvData(startTime, endTime),
HealthUploadDataType.heartRate =>
_hostApi.fetchHeartRateData(startTime, endTime),
HealthUploadDataType.walkingHeartRate =>
_hostApi.fetchWalkingHeartRateData(startTime, endTime),
HealthUploadDataType.restingHeartRate =>
_hostApi.fetchRestingHeartRateData(startTime, endTime),
HealthUploadDataType.sleepingHeartRate =>
_hostApi.fetchSleepingHeartRateData(startTime, endTime),
HealthUploadDataType.oxygenSaturation =>
_hostApi.fetchOxygenSaturationData(startTime, endTime),
HealthUploadDataType.activeEnergy =>
_hostApi.fetchActiveEnergyData(startTime, endTime),
HealthUploadDataType.exercise =>
_hostApi.fetchExerciseData(startTime, endTime),
HealthUploadDataType.stand => _hostApi.fetchStandData(startTime, endTime),
HealthUploadDataType.steps =>
_hostApi.fetchStepCountData(startTime, endTime),
HealthUploadDataType.sleepingWristTemperature =>
_hostApi.fetchSleepingWristTemperatureData(startTime, endTime),
HealthUploadDataType.respiratoryRate =>
_hostApi.fetchRespiratoryRateData(startTime, endTime),
HealthUploadDataType.irregularHeartRhythm =>
_hostApi.fetchIrregularHeartRhythmData(startTime, endTime),
HealthUploadDataType.unknown ||
HealthUploadDataType.sleep =>
Future.value(const []),
};
}
Future<HealthActivityTargetUploadData?> _fetchActivityTarget(
Map<HealthUploadDataType, int> startTimes,
int endTime,
) async {
final startTime =
startTimes[HealthUploadDataType.activeEnergy] ?? _fallbackStartTime();
final HealthActivityTargetData? target;
try {
target = await _hostApi.fetchActivityTargetData(startTime, endTime);
} catch (error, stackTrace) {
AppLogger.w(
'Fetch Apple Health activity target failed', error, stackTrace);
return null;
}
if (target == null) return null;
return HealthActivityTargetUploadData(
move: target.move,
stand: target.stand,
);
}
}
class AppleHealthUploadResult {
const AppleHealthUploadResult({
required this.commonUploadSuccess,
required this.sleepUploadSuccess,
required this.activityTargetUploadSuccess,
this.commonCount = 0,
this.sleepCount = 0,
this.activityTargetCount = 0,
});
final bool commonUploadSuccess;
final bool sleepUploadSuccess;
final bool activityTargetUploadSuccess;
final int commonCount;
final int sleepCount;
final int activityTargetCount;
bool get isSuccess =>
commonUploadSuccess && sleepUploadSuccess && activityTargetUploadSuccess;
}