syncAppUsage static method

Future<void> syncAppUsage({
  1. required AppUsageAuditDao appUsageAuditDao,
  2. DateTime? lastSync,
  3. required String deviceId,
  4. required HttpService httpService,
})

Implementation

static Future<void> syncAppUsage({
  required AppUsageAuditDao appUsageAuditDao,
  DateTime? lastSync,
  required String deviceId,
  required HttpService httpService,
}) async {
  final yesterday = DateTime.now().subtract(const Duration(days: 1));
  final endOfYesterday =
      DateTime(yesterday.year, yesterday.month, yesterday.day, 23, 59, 59);
  final appUsages = await appUsageAuditDao.findManyBetween(
      lastSync ?? endOfYesterday.subtract(const Duration(days: 60)),
      endOfYesterday);
  if (appUsages.isEmpty) {
    return;
  }

  Map<String, List<AppUsageAuditData>> appUsagesByDate = {};
  for (final appUsage in appUsages) {
    if (appUsagesByDate[appUsage.date] == null) {
      appUsagesByDate[appUsage.date] = [];
    }

    appUsagesByDate[appUsage.date]!.add(appUsage);
  }

  List<Map<String, dynamic>> uploadData = [];
  for (final key in appUsagesByDate.keys) {
    if (appUsagesByDate[key] == null ||
        appUsagesByDate[key]!.isEmpty == true) {
      continue;
    }

    uploadData.add({
      'date': key,
      'deviceId': deviceId,
      'data': appUsagesByDate[key]!
          .map<Map<String, dynamic>>((item) => {
                'id': item.id,
                'date': item.date.toString(),
                'usageTime': item.totalTimeVisible == 0
                    ? item.totalTimeInForeground
                    : item.totalTimeVisible,
                'foregroundServiceTime': item.totalTimeForegroundServiceUsed,
                'packageName': item.packageName
              })
          .toList(),
    });
    if (uploadData.length == 3) {
      await httpService.post(AppUsageAuditRoute.uploadPath, uploadData);
      uploadData = [];
    }
  }

  if (uploadData.isEmpty == false) {
    await httpService.post(AppUsageAuditRoute.uploadPath, uploadData);
  }
}