2022-08-18 16:41:59 +02:00
|
|
|
import 'dart:async';
|
|
|
|
import 'dart:developer';
|
|
|
|
import 'dart:io';
|
|
|
|
import 'dart:isolate';
|
|
|
|
import 'dart:ui' show IsolateNameServer, PluginUtilities;
|
|
|
|
import 'package:cancellation_token_http/http.dart';
|
|
|
|
import 'package:easy_localization/easy_localization.dart';
|
|
|
|
import 'package:flutter/services.dart';
|
|
|
|
import 'package:flutter/widgets.dart';
|
|
|
|
import 'package:hive_flutter/hive_flutter.dart';
|
|
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
|
|
import 'package:immich_mobile/constants/hive_box.dart';
|
|
|
|
import 'package:immich_mobile/modules/backup/background_service/localization.dart';
|
|
|
|
import 'package:immich_mobile/modules/backup/models/current_upload_asset.model.dart';
|
|
|
|
import 'package:immich_mobile/modules/backup/models/error_upload_asset.model.dart';
|
|
|
|
import 'package:immich_mobile/modules/backup/models/hive_backup_albums.model.dart';
|
2022-10-25 16:51:03 +02:00
|
|
|
import 'package:immich_mobile/modules/backup/models/hive_duplicated_assets.model.dart';
|
2022-08-18 16:41:59 +02:00
|
|
|
import 'package:immich_mobile/modules/backup/services/backup.service.dart';
|
|
|
|
import 'package:immich_mobile/modules/login/models/hive_saved_login_info.model.dart';
|
2022-08-21 18:29:24 +02:00
|
|
|
import 'package:immich_mobile/modules/settings/services/app_settings.service.dart';
|
2022-08-18 16:41:59 +02:00
|
|
|
import 'package:immich_mobile/shared/services/api.service.dart';
|
|
|
|
import 'package:photo_manager/photo_manager.dart';
|
|
|
|
|
|
|
|
final backgroundServiceProvider = Provider(
|
|
|
|
(ref) => BackgroundService(),
|
|
|
|
);
|
|
|
|
|
|
|
|
/// Background backup service
|
|
|
|
class BackgroundService {
|
|
|
|
static const String _portNameLock = "immichLock";
|
|
|
|
static const MethodChannel _foregroundChannel =
|
|
|
|
MethodChannel('immich/foregroundChannel');
|
|
|
|
static const MethodChannel _backgroundChannel =
|
|
|
|
MethodChannel('immich/backgroundChannel');
|
2022-10-05 16:59:35 +02:00
|
|
|
static final NumberFormat numberFormat = NumberFormat("###0.##");
|
2022-11-01 10:16:46 +02:00
|
|
|
static const notifyInterval = Duration(milliseconds: 400);
|
2022-08-18 16:41:59 +02:00
|
|
|
bool _isBackgroundInitialized = false;
|
|
|
|
CancellationToken? _cancellationToken;
|
|
|
|
bool _canceledBySystem = false;
|
|
|
|
int _wantsLockTime = 0;
|
|
|
|
bool _hasLock = false;
|
|
|
|
SendPort? _waitingIsolate;
|
|
|
|
ReceivePort? _rp;
|
2022-08-21 18:29:24 +02:00
|
|
|
bool _errorGracePeriodExceeded = true;
|
2022-10-05 16:59:35 +02:00
|
|
|
int _uploadedAssetsCount = 0;
|
|
|
|
int _assetsToUploadCount = 0;
|
2022-11-01 10:16:46 +02:00
|
|
|
String _lastPrintedDetailContent = "";
|
|
|
|
String? _lastPrintedDetailTitle;
|
|
|
|
late final _Throttle _throttledNotifiy =
|
|
|
|
_Throttle(_updateProgress, notifyInterval);
|
|
|
|
late final _Throttle _throttledDetailNotify =
|
|
|
|
_Throttle(_updateDetailProgress, notifyInterval);
|
2022-11-08 19:00:24 +02:00
|
|
|
Completer<bool> _hasAccessCompleter = Completer();
|
|
|
|
late Future<bool> _hasAccess =
|
|
|
|
Platform.isAndroid ? _hasAccessCompleter.future : Future.value(true);
|
|
|
|
|
|
|
|
Future<bool> get hasAccess => _hasAccess;
|
2022-08-18 16:41:59 +02:00
|
|
|
|
|
|
|
bool get isBackgroundInitialized {
|
|
|
|
return _isBackgroundInitialized;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Ensures that the background service is enqueued if enabled in settings
|
|
|
|
Future<bool> resumeServiceIfEnabled() async {
|
2022-09-08 15:36:08 +02:00
|
|
|
return await isBackgroundBackupEnabled() && await enableService();
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Enqueues the background service
|
2022-09-08 15:36:08 +02:00
|
|
|
Future<bool> enableService({bool immediate = false}) async {
|
|
|
|
if (!Platform.isAndroid) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
final callback = PluginUtilities.getCallbackHandle(_nativeEntry)!;
|
|
|
|
final String title =
|
|
|
|
"backup_background_service_default_notification".tr();
|
|
|
|
final bool ok = await _foregroundChannel
|
|
|
|
.invokeMethod('enable', [callback.toRawHandle(), title, immediate]);
|
|
|
|
return ok;
|
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Configures the background service
|
|
|
|
Future<bool> configureService({
|
2022-08-18 16:41:59 +02:00
|
|
|
bool requireUnmetered = true,
|
|
|
|
bool requireCharging = false,
|
2022-12-08 17:51:36 +02:00
|
|
|
int triggerUpdateDelay = 5000,
|
|
|
|
int triggerMaxDelay = 50000,
|
2022-08-18 16:41:59 +02:00
|
|
|
}) async {
|
|
|
|
if (!Platform.isAndroid) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
final bool ok = await _foregroundChannel.invokeMethod(
|
2022-09-08 15:36:08 +02:00
|
|
|
'configure',
|
2022-12-08 17:51:36 +02:00
|
|
|
[
|
|
|
|
requireUnmetered,
|
|
|
|
requireCharging,
|
|
|
|
triggerUpdateDelay,
|
|
|
|
triggerMaxDelay
|
|
|
|
],
|
2022-08-18 16:41:59 +02:00
|
|
|
);
|
|
|
|
return ok;
|
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Cancels the background service (if currently running) and removes it from work queue
|
2022-09-08 15:36:08 +02:00
|
|
|
Future<bool> disableService() async {
|
2022-08-18 16:41:59 +02:00
|
|
|
if (!Platform.isAndroid) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
try {
|
2022-09-08 15:36:08 +02:00
|
|
|
final ok = await _foregroundChannel.invokeMethod('disable');
|
2022-08-18 16:41:59 +02:00
|
|
|
return ok;
|
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns `true` if the background service is enabled
|
|
|
|
Future<bool> isBackgroundBackupEnabled() async {
|
|
|
|
if (!Platform.isAndroid) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
return await _foregroundChannel.invokeMethod("isEnabled");
|
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-31 15:08:40 +02:00
|
|
|
/// Returns `true` if battery optimizations are disabled
|
|
|
|
Future<bool> isIgnoringBatteryOptimizations() async {
|
2022-08-18 16:41:59 +02:00
|
|
|
if (!Platform.isAndroid) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
try {
|
2022-08-31 15:08:40 +02:00
|
|
|
return await _foregroundChannel
|
|
|
|
.invokeMethod('isIgnoringBatteryOptimizations');
|
2022-08-18 16:41:59 +02:00
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Updates the notification shown by the background service
|
2022-10-05 16:59:35 +02:00
|
|
|
Future<bool?> _updateNotification({
|
|
|
|
String? title,
|
2022-08-18 16:41:59 +02:00
|
|
|
String? content,
|
2022-10-05 16:59:35 +02:00
|
|
|
int progress = 0,
|
|
|
|
int max = 0,
|
|
|
|
bool indeterminate = false,
|
|
|
|
bool isDetail = false,
|
|
|
|
bool onlyIfFG = false,
|
2022-08-18 16:41:59 +02:00
|
|
|
}) async {
|
|
|
|
if (!Platform.isAndroid) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
if (_isBackgroundInitialized) {
|
2022-10-05 16:59:35 +02:00
|
|
|
return _backgroundChannel.invokeMethod<bool>(
|
|
|
|
'updateNotification',
|
|
|
|
[title, content, progress, max, indeterminate, isDetail, onlyIfFG],
|
|
|
|
);
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
|
|
|
} catch (error) {
|
2022-08-21 18:29:24 +02:00
|
|
|
debugPrint("[_updateNotification] failed to communicate with plugin");
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
2022-10-05 16:59:35 +02:00
|
|
|
return false;
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Shows a new priority notification
|
2022-08-21 18:29:24 +02:00
|
|
|
Future<bool> _showErrorNotification({
|
|
|
|
required String title,
|
|
|
|
String? content,
|
|
|
|
String? individualTag,
|
|
|
|
}) async {
|
2022-08-18 16:41:59 +02:00
|
|
|
if (!Platform.isAndroid) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
try {
|
2022-08-21 18:29:24 +02:00
|
|
|
if (_isBackgroundInitialized && _errorGracePeriodExceeded) {
|
2022-08-18 16:41:59 +02:00
|
|
|
return await _backgroundChannel
|
2022-08-21 18:29:24 +02:00
|
|
|
.invokeMethod('showError', [title, content, individualTag]);
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
|
|
|
} catch (error) {
|
2022-08-21 18:29:24 +02:00
|
|
|
debugPrint("[_showErrorNotification] failed to communicate with plugin");
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
2022-08-21 18:29:24 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<bool> _clearErrorNotifications() async {
|
|
|
|
if (!Platform.isAndroid) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
if (_isBackgroundInitialized) {
|
|
|
|
return await _backgroundChannel.invokeMethod('clearErrorNotifications');
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
debugPrint(
|
2022-09-10 18:46:51 +02:00
|
|
|
"[_clearErrorNotifications] failed to communicate with plugin",
|
|
|
|
);
|
2022-08-21 18:29:24 +02:00
|
|
|
}
|
|
|
|
return false;
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// await to ensure this thread (foreground or background) has exclusive access
|
|
|
|
Future<bool> acquireLock() async {
|
|
|
|
if (!Platform.isAndroid) {
|
|
|
|
return true;
|
|
|
|
}
|
2022-11-08 19:00:24 +02:00
|
|
|
if (_hasLock) {
|
|
|
|
debugPrint("WARNING: [acquireLock] called more than once");
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
if (_hasAccessCompleter.isCompleted) {
|
|
|
|
debugPrint("WARNING: [acquireLock] _hasAccessCompleter is completed");
|
|
|
|
_hasAccessCompleter = Completer();
|
|
|
|
_hasAccess = _hasAccessCompleter.future;
|
|
|
|
}
|
2022-08-18 16:41:59 +02:00
|
|
|
final int lockTime = Timeline.now;
|
|
|
|
_wantsLockTime = lockTime;
|
|
|
|
final ReceivePort rp = ReceivePort(_portNameLock);
|
|
|
|
_rp = rp;
|
|
|
|
final SendPort sp = rp.sendPort;
|
|
|
|
|
|
|
|
while (!IsolateNameServer.registerPortWithName(sp, _portNameLock)) {
|
|
|
|
try {
|
|
|
|
await _checkLockReleasedWithHeartbeat(lockTime);
|
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if (_wantsLockTime != lockTime) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_hasLock = true;
|
|
|
|
rp.listen(_heartbeatListener);
|
2022-11-08 19:00:24 +02:00
|
|
|
_hasAccessCompleter.complete(true);
|
2022-08-18 16:41:59 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> _checkLockReleasedWithHeartbeat(final int lockTime) async {
|
|
|
|
SendPort? other = IsolateNameServer.lookupPortByName(_portNameLock);
|
|
|
|
if (other != null) {
|
|
|
|
final ReceivePort tempRp = ReceivePort();
|
|
|
|
final SendPort tempSp = tempRp.sendPort;
|
|
|
|
final bs = tempRp.asBroadcastStream();
|
|
|
|
while (_wantsLockTime == lockTime) {
|
|
|
|
other.send(tempSp);
|
|
|
|
final dynamic answer = await bs.first
|
|
|
|
.timeout(const Duration(seconds: 5), onTimeout: () => null);
|
|
|
|
if (_wantsLockTime != lockTime) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
if (answer == null) {
|
|
|
|
// other isolate failed to answer, assuming it exited without releasing the lock
|
|
|
|
if (other == IsolateNameServer.lookupPortByName(_portNameLock)) {
|
|
|
|
IsolateNameServer.removePortNameMapping(_portNameLock);
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
} else if (answer == true) {
|
|
|
|
// other isolate released the lock
|
|
|
|
break;
|
|
|
|
} else if (answer == false) {
|
|
|
|
// other isolate is still active
|
|
|
|
}
|
|
|
|
final dynamic isFinished = await bs.first
|
|
|
|
.timeout(const Duration(seconds: 5), onTimeout: () => false);
|
|
|
|
if (isFinished == true) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
tempRp.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void _heartbeatListener(dynamic msg) {
|
|
|
|
if (msg is SendPort) {
|
|
|
|
_waitingIsolate = msg;
|
|
|
|
msg.send(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// releases the exclusive access lock
|
|
|
|
void releaseLock() {
|
|
|
|
if (!Platform.isAndroid) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
_wantsLockTime = 0;
|
|
|
|
if (_hasLock) {
|
2022-11-08 19:00:24 +02:00
|
|
|
_hasAccessCompleter = Completer();
|
|
|
|
_hasAccess = _hasAccessCompleter.future;
|
2022-08-18 16:41:59 +02:00
|
|
|
IsolateNameServer.removePortNameMapping(_portNameLock);
|
|
|
|
_waitingIsolate?.send(true);
|
|
|
|
_waitingIsolate = null;
|
|
|
|
_hasLock = false;
|
|
|
|
}
|
|
|
|
_rp?.close();
|
|
|
|
_rp = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
void _setupBackgroundCallHandler() {
|
|
|
|
_backgroundChannel.setMethodCallHandler(_callHandler);
|
|
|
|
_isBackgroundInitialized = true;
|
|
|
|
_backgroundChannel.invokeMethod('initialized');
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<bool> _callHandler(MethodCall call) async {
|
|
|
|
switch (call.method) {
|
|
|
|
case "onAssetsChanged":
|
|
|
|
final Future<bool> translationsLoaded = loadTranslations();
|
|
|
|
try {
|
2022-10-05 16:59:35 +02:00
|
|
|
_clearErrorNotifications();
|
2022-08-18 16:41:59 +02:00
|
|
|
final bool hasAccess = await acquireLock();
|
|
|
|
if (!hasAccess) {
|
2022-09-08 15:36:08 +02:00
|
|
|
debugPrint("[_callHandler] could not acquire lock, exiting");
|
2022-08-18 16:41:59 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
await translationsLoaded;
|
2022-08-21 18:29:24 +02:00
|
|
|
final bool ok = await _onAssetsChanged();
|
|
|
|
return ok;
|
2022-08-18 16:41:59 +02:00
|
|
|
} catch (error) {
|
|
|
|
debugPrint(error.toString());
|
|
|
|
return false;
|
|
|
|
} finally {
|
|
|
|
await Hive.close();
|
|
|
|
releaseLock();
|
|
|
|
}
|
|
|
|
case "systemStop":
|
|
|
|
_canceledBySystem = true;
|
|
|
|
_cancellationToken?.cancel();
|
|
|
|
return true;
|
|
|
|
default:
|
|
|
|
debugPrint("Unknown method ${call.method}");
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<bool> _onAssetsChanged() async {
|
|
|
|
await Hive.initFlutter();
|
|
|
|
|
|
|
|
Hive.registerAdapter(HiveSavedLoginInfoAdapter());
|
|
|
|
Hive.registerAdapter(HiveBackupAlbumsAdapter());
|
2022-10-25 16:51:03 +02:00
|
|
|
Hive.registerAdapter(HiveDuplicatedAssetsAdapter());
|
|
|
|
|
2022-10-31 16:38:24 +02:00
|
|
|
await Future.wait([
|
|
|
|
Hive.openBox(userInfoBox),
|
|
|
|
Hive.openBox<HiveSavedLoginInfo>(hiveLoginInfoBox),
|
|
|
|
Hive.openBox(userSettingInfoBox),
|
|
|
|
Hive.openBox(backgroundBackupInfoBox),
|
|
|
|
Hive.openBox<HiveDuplicatedAssets>(duplicatedAssetsBox),
|
|
|
|
Hive.openBox<HiveBackupAlbums>(hiveBackupInfoBox),
|
|
|
|
]);
|
2022-08-18 16:41:59 +02:00
|
|
|
ApiService apiService = ApiService();
|
|
|
|
apiService.setEndpoint(Hive.box(userInfoBox).get(serverEndpointKey));
|
|
|
|
apiService.setAccessToken(Hive.box(userInfoBox).get(accessTokenKey));
|
|
|
|
BackupService backupService = BackupService(apiService);
|
2022-10-05 16:59:35 +02:00
|
|
|
AppSettingsService settingsService = AppSettingsService();
|
2022-08-18 16:41:59 +02:00
|
|
|
|
|
|
|
final Box<HiveBackupAlbums> box =
|
2022-10-31 16:38:24 +02:00
|
|
|
Hive.box<HiveBackupAlbums>(hiveBackupInfoBox);
|
2022-08-18 16:41:59 +02:00
|
|
|
final HiveBackupAlbums? backupAlbumInfo = box.get(backupInfoKey);
|
|
|
|
if (backupAlbumInfo == null) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
await PhotoManager.setIgnorePermissionCheck(true);
|
2022-09-08 15:36:08 +02:00
|
|
|
|
|
|
|
do {
|
2022-10-05 16:59:35 +02:00
|
|
|
final bool backupOk = await _runBackup(
|
|
|
|
backupService,
|
|
|
|
settingsService,
|
|
|
|
backupAlbumInfo,
|
|
|
|
);
|
2022-09-08 15:36:08 +02:00
|
|
|
if (backupOk) {
|
|
|
|
await Hive.box(backgroundBackupInfoBox).delete(backupFailedSince);
|
|
|
|
await box.put(
|
|
|
|
backupInfoKey,
|
|
|
|
backupAlbumInfo,
|
|
|
|
);
|
|
|
|
} else if (Hive.box(backgroundBackupInfoBox).get(backupFailedSince) ==
|
|
|
|
null) {
|
|
|
|
Hive.box(backgroundBackupInfoBox)
|
|
|
|
.put(backupFailedSince, DateTime.now());
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
// check for new assets added while performing backup
|
|
|
|
} while (true ==
|
|
|
|
await _backgroundChannel.invokeMethod<bool>("hasContentChanged"));
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<bool> _runBackup(
|
2022-09-10 18:46:51 +02:00
|
|
|
BackupService backupService,
|
2022-10-05 16:59:35 +02:00
|
|
|
AppSettingsService settingsService,
|
2022-09-10 18:46:51 +02:00
|
|
|
HiveBackupAlbums backupAlbumInfo,
|
|
|
|
) async {
|
2022-10-05 16:59:35 +02:00
|
|
|
_errorGracePeriodExceeded = _isErrorGracePeriodExceeded(settingsService);
|
|
|
|
final bool notifyTotalProgress = settingsService
|
|
|
|
.getSetting<bool>(AppSettingsEnum.backgroundBackupTotalProgress);
|
|
|
|
final bool notifySingleProgress = settingsService
|
|
|
|
.getSetting<bool>(AppSettingsEnum.backgroundBackupSingleProgress);
|
2022-08-18 16:41:59 +02:00
|
|
|
|
|
|
|
if (_canceledBySystem) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2022-08-21 18:29:24 +02:00
|
|
|
List<AssetEntity> toUpload =
|
|
|
|
await backupService.buildUploadCandidates(backupAlbumInfo);
|
|
|
|
|
|
|
|
try {
|
|
|
|
toUpload = await backupService.removeAlreadyUploadedAssets(toUpload);
|
|
|
|
} catch (e) {
|
|
|
|
_showErrorNotification(
|
|
|
|
title: "backup_background_service_error_title".tr(),
|
|
|
|
content: "backup_background_service_connection_failed_message".tr(),
|
|
|
|
);
|
|
|
|
return false;
|
|
|
|
}
|
2022-08-18 16:41:59 +02:00
|
|
|
|
|
|
|
if (_canceledBySystem) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (toUpload.isEmpty) {
|
|
|
|
return true;
|
|
|
|
}
|
2022-10-05 16:59:35 +02:00
|
|
|
_assetsToUploadCount = toUpload.length;
|
|
|
|
_uploadedAssetsCount = 0;
|
|
|
|
_updateNotification(
|
|
|
|
title: "backup_background_service_in_progress_notification".tr(),
|
|
|
|
content: notifyTotalProgress ? _formatAssetBackupProgress() : null,
|
|
|
|
progress: 0,
|
|
|
|
max: notifyTotalProgress ? _assetsToUploadCount : 0,
|
|
|
|
indeterminate: !notifyTotalProgress,
|
|
|
|
onlyIfFG: !notifyTotalProgress,
|
|
|
|
);
|
2022-08-18 16:41:59 +02:00
|
|
|
|
|
|
|
_cancellationToken = CancellationToken();
|
|
|
|
final bool ok = await backupService.backupAsset(
|
|
|
|
toUpload,
|
|
|
|
_cancellationToken!,
|
2022-10-25 16:51:03 +02:00
|
|
|
notifyTotalProgress ? _onAssetUploaded : (assetId, deviceId, isDup) {},
|
2022-10-05 16:59:35 +02:00
|
|
|
notifySingleProgress ? _onProgress : (sent, total) {},
|
|
|
|
notifySingleProgress ? _onSetCurrentBackupAsset : (asset) {},
|
2022-08-18 16:41:59 +02:00
|
|
|
_onBackupError,
|
|
|
|
);
|
2022-10-05 16:59:35 +02:00
|
|
|
if (!ok && !_cancellationToken!.isCancelled) {
|
2022-08-21 18:29:24 +02:00
|
|
|
_showErrorNotification(
|
|
|
|
title: "backup_background_service_error_title".tr(),
|
|
|
|
content: "backup_background_service_backup_failed_message".tr(),
|
|
|
|
);
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
|
|
|
return ok;
|
|
|
|
}
|
|
|
|
|
2022-10-05 16:59:35 +02:00
|
|
|
String _formatAssetBackupProgress() {
|
|
|
|
final int percent = (_uploadedAssetsCount * 100) ~/ _assetsToUploadCount;
|
|
|
|
return "$percent% ($_uploadedAssetsCount/$_assetsToUploadCount)";
|
|
|
|
}
|
|
|
|
|
2022-10-25 16:51:03 +02:00
|
|
|
void _onAssetUploaded(String deviceAssetId, String deviceId, bool isDup) {
|
2022-10-05 16:59:35 +02:00
|
|
|
_uploadedAssetsCount++;
|
2022-11-01 10:16:46 +02:00
|
|
|
_throttledNotifiy();
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
|
|
|
|
2022-10-05 16:59:35 +02:00
|
|
|
void _onProgress(int sent, int total) {
|
2022-11-01 10:16:46 +02:00
|
|
|
_throttledDetailNotify(progress: sent, total: total);
|
2022-11-01 04:02:06 +02:00
|
|
|
}
|
|
|
|
|
2022-11-01 10:16:46 +02:00
|
|
|
void _updateDetailProgress(String? title, int progress, int total) {
|
|
|
|
final String msg =
|
|
|
|
total > 0 ? _humanReadableBytesProgress(progress, total) : "";
|
2022-11-01 04:02:06 +02:00
|
|
|
// only update if message actually differs (to stop many useless notification updates on large assets or slow connections)
|
2022-11-01 10:16:46 +02:00
|
|
|
if (msg != _lastPrintedDetailContent || _lastPrintedDetailTitle != title) {
|
|
|
|
_lastPrintedDetailContent = msg;
|
|
|
|
_lastPrintedDetailTitle = title;
|
2022-11-01 04:02:06 +02:00
|
|
|
_updateNotification(
|
2022-11-01 10:16:46 +02:00
|
|
|
progress: total > 0 ? (progress * 1000) ~/ total : 0,
|
|
|
|
max: 1000,
|
2022-11-01 04:02:06 +02:00
|
|
|
isDetail: true,
|
2022-11-01 10:16:46 +02:00
|
|
|
title: title,
|
2022-11-01 04:02:06 +02:00
|
|
|
content: msg,
|
|
|
|
);
|
2022-10-05 16:59:35 +02:00
|
|
|
}
|
|
|
|
}
|
2022-08-18 16:41:59 +02:00
|
|
|
|
2022-11-01 10:16:46 +02:00
|
|
|
void _updateProgress(String? title, int progress, int total) {
|
|
|
|
_updateNotification(
|
|
|
|
progress: _uploadedAssetsCount,
|
|
|
|
max: _assetsToUploadCount,
|
|
|
|
title: title,
|
|
|
|
content: _formatAssetBackupProgress(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-08-18 16:41:59 +02:00
|
|
|
void _onBackupError(ErrorUploadAsset errorAssetInfo) {
|
2022-08-21 18:29:24 +02:00
|
|
|
_showErrorNotification(
|
2022-10-05 16:59:35 +02:00
|
|
|
title: "backup_background_service_upload_failure_notification"
|
2022-08-18 16:41:59 +02:00
|
|
|
.tr(args: [errorAssetInfo.fileName]),
|
2022-08-21 18:29:24 +02:00
|
|
|
individualTag: errorAssetInfo.id,
|
2022-08-18 16:41:59 +02:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
void _onSetCurrentBackupAsset(CurrentUploadAsset currentUploadAsset) {
|
2022-11-01 10:16:46 +02:00
|
|
|
_throttledDetailNotify.title =
|
|
|
|
"backup_background_service_current_upload_notification"
|
|
|
|
.tr(args: [currentUploadAsset.fileName]);
|
|
|
|
_throttledDetailNotify.progress = 0;
|
|
|
|
_throttledDetailNotify.total = 0;
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
2022-08-21 18:29:24 +02:00
|
|
|
|
2022-10-05 16:59:35 +02:00
|
|
|
bool _isErrorGracePeriodExceeded(AppSettingsService appSettingsService) {
|
|
|
|
final int value = appSettingsService
|
2022-08-21 18:29:24 +02:00
|
|
|
.getSetting(AppSettingsEnum.uploadErrorNotificationGracePeriod);
|
|
|
|
if (value == 0) {
|
|
|
|
return true;
|
|
|
|
} else if (value == 5) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
final DateTime? failedSince =
|
|
|
|
Hive.box(backgroundBackupInfoBox).get(backupFailedSince);
|
|
|
|
if (failedSince == null) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
final Duration duration = DateTime.now().difference(failedSince);
|
|
|
|
if (value == 1) {
|
|
|
|
return duration > const Duration(minutes: 30);
|
|
|
|
} else if (value == 2) {
|
|
|
|
return duration > const Duration(hours: 2);
|
|
|
|
} else if (value == 3) {
|
|
|
|
return duration > const Duration(hours: 8);
|
|
|
|
} else if (value == 4) {
|
|
|
|
return duration > const Duration(hours: 24);
|
|
|
|
}
|
|
|
|
assert(false, "Invalid value");
|
|
|
|
return true;
|
|
|
|
}
|
2022-10-05 16:59:35 +02:00
|
|
|
|
|
|
|
/// prints percentage and absolute progress in useful (kilo/mega/giga)bytes
|
|
|
|
static String _humanReadableBytesProgress(int bytes, int bytesTotal) {
|
|
|
|
String unit = "KB"; // Kilobyte
|
|
|
|
if (bytesTotal >= 0x40000000) {
|
|
|
|
unit = "GB"; // Gigabyte
|
|
|
|
bytes >>= 20;
|
|
|
|
bytesTotal >>= 20;
|
|
|
|
} else if (bytesTotal >= 0x100000) {
|
|
|
|
unit = "MB"; // Megabyte
|
|
|
|
bytes >>= 10;
|
|
|
|
bytesTotal >>= 10;
|
|
|
|
} else if (bytesTotal < 0x400) {
|
|
|
|
return "$bytes / $bytesTotal B";
|
|
|
|
}
|
|
|
|
final int percent = (bytes * 100) ~/ bytesTotal;
|
|
|
|
final String done = numberFormat.format(bytes / 1024.0);
|
|
|
|
final String total = numberFormat.format(bytesTotal / 1024.0);
|
|
|
|
return "$percent% ($done/$total$unit)";
|
|
|
|
}
|
2022-08-18 16:41:59 +02:00
|
|
|
}
|
|
|
|
|
2022-11-01 04:02:06 +02:00
|
|
|
class _Throttle {
|
|
|
|
_Throttle(this._fun, Duration interval) : _interval = interval.inMicroseconds;
|
2022-11-01 10:16:46 +02:00
|
|
|
final void Function(String?, int, int) _fun;
|
2022-11-01 04:02:06 +02:00
|
|
|
final int _interval;
|
|
|
|
int _invokedAt = 0;
|
|
|
|
Timer? _timer;
|
|
|
|
|
2022-11-01 10:16:46 +02:00
|
|
|
String? title;
|
|
|
|
int progress = 0;
|
|
|
|
int total = 0;
|
|
|
|
|
|
|
|
void call({
|
|
|
|
final String? title,
|
|
|
|
final int progress = 0,
|
|
|
|
final int total = 0,
|
|
|
|
}) {
|
2022-11-01 04:02:06 +02:00
|
|
|
final time = Timeline.now;
|
2022-11-01 10:16:46 +02:00
|
|
|
this.title = title ?? this.title;
|
|
|
|
this.progress = progress;
|
|
|
|
this.total = total;
|
2022-11-01 04:02:06 +02:00
|
|
|
if (time > _invokedAt + _interval) {
|
|
|
|
_timer?.cancel();
|
|
|
|
_onTimeElapsed();
|
|
|
|
} else {
|
|
|
|
_timer ??= Timer(Duration(microseconds: _interval), _onTimeElapsed);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void _onTimeElapsed() {
|
|
|
|
_invokedAt = Timeline.now;
|
2022-11-01 10:16:46 +02:00
|
|
|
_fun(title, progress, total);
|
2022-11-01 04:02:06 +02:00
|
|
|
_timer = null;
|
2022-11-01 10:16:46 +02:00
|
|
|
// clear title to not send/overwrite it next time if unchanged
|
|
|
|
title = null;
|
2022-11-01 04:02:06 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-18 16:41:59 +02:00
|
|
|
/// entry point called by Kotlin/Java code; needs to be a top-level function
|
2022-09-10 18:46:51 +02:00
|
|
|
@pragma('vm:entry-point')
|
2022-08-18 16:41:59 +02:00
|
|
|
void _nativeEntry() {
|
|
|
|
WidgetsFlutterBinding.ensureInitialized();
|
|
|
|
BackgroundService backgroundService = BackgroundService();
|
|
|
|
backgroundService._setupBackgroundCallHandler();
|
|
|
|
}
|