2022-08-18 14:41:59 +00:00
|
|
|
import 'dart:async';
|
|
|
|
import 'dart:developer';
|
|
|
|
import 'dart:io';
|
|
|
|
import 'dart:isolate';
|
2023-02-20 05:59:50 +00:00
|
|
|
import 'dart:ui' show DartPluginRegistrant, IsolateNameServer, PluginUtilities;
|
2022-08-18 14:41:59 +00:00
|
|
|
import 'package:cancellation_token_http/http.dart';
|
2023-03-18 14:55:11 +00:00
|
|
|
import 'package:collection/collection.dart';
|
2022-08-18 14:41:59 +00:00
|
|
|
import 'package:easy_localization/easy_localization.dart';
|
2024-12-05 15:11:48 +00:00
|
|
|
import 'package:flutter/foundation.dart';
|
2022-08-18 14:41:59 +00:00
|
|
|
import 'package:flutter/services.dart';
|
|
|
|
import 'package:flutter/widgets.dart';
|
|
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
2024-09-30 14:37:30 +00:00
|
|
|
import 'package:immich_mobile/interfaces/backup.interface.dart';
|
2023-03-18 14:55:11 +00:00
|
|
|
import 'package:immich_mobile/main.dart';
|
2024-08-26 18:21:19 +00:00
|
|
|
import 'package:immich_mobile/models/backup/backup_candidate.model.dart';
|
|
|
|
import 'package:immich_mobile/models/backup/success_upload_asset.model.dart';
|
2024-09-16 20:26:14 +00:00
|
|
|
import 'package:immich_mobile/repositories/album.repository.dart';
|
2024-09-20 13:32:37 +00:00
|
|
|
import 'package:immich_mobile/repositories/album_api.repository.dart';
|
2024-09-16 20:26:14 +00:00
|
|
|
import 'package:immich_mobile/repositories/asset.repository.dart';
|
2024-09-27 15:28:31 +00:00
|
|
|
import 'package:immich_mobile/repositories/asset_media.repository.dart';
|
2024-12-05 15:11:48 +00:00
|
|
|
import 'package:immich_mobile/repositories/auth.repository.dart';
|
|
|
|
import 'package:immich_mobile/repositories/auth_api.repository.dart';
|
2024-09-16 20:26:14 +00:00
|
|
|
import 'package:immich_mobile/repositories/backup.repository.dart';
|
2024-09-18 15:15:52 +00:00
|
|
|
import 'package:immich_mobile/repositories/album_media.repository.dart';
|
2024-09-30 14:37:30 +00:00
|
|
|
import 'package:immich_mobile/repositories/etag.repository.dart';
|
|
|
|
import 'package:immich_mobile/repositories/exif_info.repository.dart';
|
2024-09-18 15:15:52 +00:00
|
|
|
import 'package:immich_mobile/repositories/file_media.repository.dart';
|
2024-12-05 15:11:48 +00:00
|
|
|
import 'package:immich_mobile/repositories/network.repository.dart';
|
2024-09-24 12:50:21 +00:00
|
|
|
import 'package:immich_mobile/repositories/partner_api.repository.dart';
|
2024-12-05 15:11:48 +00:00
|
|
|
import 'package:immich_mobile/repositories/permission.repository.dart';
|
2024-09-16 20:26:14 +00:00
|
|
|
import 'package:immich_mobile/repositories/user.repository.dart';
|
2024-09-24 12:50:21 +00:00
|
|
|
import 'package:immich_mobile/repositories/user_api.repository.dart';
|
2024-08-26 18:21:19 +00:00
|
|
|
import 'package:immich_mobile/services/album.service.dart';
|
2024-12-05 15:11:48 +00:00
|
|
|
import 'package:immich_mobile/services/auth.service.dart';
|
2024-09-20 13:32:37 +00:00
|
|
|
import 'package:immich_mobile/services/entity.service.dart';
|
2024-08-26 18:21:19 +00:00
|
|
|
import 'package:immich_mobile/services/hash.service.dart';
|
2024-05-02 20:59:14 +00:00
|
|
|
import 'package:immich_mobile/services/localization.service.dart';
|
2024-05-01 02:36:40 +00:00
|
|
|
import 'package:immich_mobile/entities/backup_album.entity.dart';
|
|
|
|
import 'package:immich_mobile/models/backup/current_upload_asset.model.dart';
|
|
|
|
import 'package:immich_mobile/models/backup/error_upload_asset.model.dart';
|
2024-05-02 20:59:14 +00:00
|
|
|
import 'package:immich_mobile/services/backup.service.dart';
|
|
|
|
import 'package:immich_mobile/services/app_settings.service.dart';
|
2024-05-01 02:36:40 +00:00
|
|
|
import 'package:immich_mobile/entities/store.entity.dart';
|
2024-05-02 20:59:14 +00:00
|
|
|
import 'package:immich_mobile/services/api.service.dart';
|
2024-12-05 15:11:48 +00:00
|
|
|
import 'package:immich_mobile/services/network.service.dart';
|
2024-08-26 18:21:19 +00:00
|
|
|
import 'package:immich_mobile/services/sync.service.dart';
|
|
|
|
import 'package:immich_mobile/services/user.service.dart';
|
2023-08-06 02:40:50 +00:00
|
|
|
import 'package:immich_mobile/utils/backup_progress.dart';
|
2023-03-18 14:55:11 +00:00
|
|
|
import 'package:immich_mobile/utils/diff.dart';
|
2024-05-24 09:16:14 +00:00
|
|
|
import 'package:immich_mobile/utils/http_ssl_cert_override.dart';
|
2024-12-05 15:11:48 +00:00
|
|
|
import 'package:network_info_plus/network_info_plus.dart';
|
2023-02-20 05:59:50 +00:00
|
|
|
import 'package:path_provider_ios/path_provider_ios.dart';
|
2024-09-18 15:15:52 +00:00
|
|
|
import 'package:photo_manager/photo_manager.dart' show PMProgressHandler;
|
2022-08-18 14:41:59 +00:00
|
|
|
|
|
|
|
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-11-01 08:16:46 +00:00
|
|
|
static const notifyInterval = Duration(milliseconds: 400);
|
2022-08-18 14:41:59 +00:00
|
|
|
bool _isBackgroundInitialized = false;
|
|
|
|
CancellationToken? _cancellationToken;
|
|
|
|
bool _canceledBySystem = false;
|
|
|
|
int _wantsLockTime = 0;
|
|
|
|
bool _hasLock = false;
|
|
|
|
SendPort? _waitingIsolate;
|
|
|
|
ReceivePort? _rp;
|
2022-08-21 16:29:24 +00:00
|
|
|
bool _errorGracePeriodExceeded = true;
|
2022-10-05 14:59:35 +00:00
|
|
|
int _uploadedAssetsCount = 0;
|
|
|
|
int _assetsToUploadCount = 0;
|
2022-11-01 08:16:46 +00:00
|
|
|
String _lastPrintedDetailContent = "";
|
|
|
|
String? _lastPrintedDetailTitle;
|
2023-08-06 02:40:50 +00:00
|
|
|
late final ThrottleProgressUpdate _throttledNotifiy =
|
|
|
|
ThrottleProgressUpdate(_updateProgress, notifyInterval);
|
|
|
|
late final ThrottleProgressUpdate _throttledDetailNotify =
|
|
|
|
ThrottleProgressUpdate(_updateDetailProgress, notifyInterval);
|
2022-08-18 14:41:59 +00:00
|
|
|
|
|
|
|
bool get isBackgroundInitialized {
|
|
|
|
return _isBackgroundInitialized;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Ensures that the background service is enqueued if enabled in settings
|
|
|
|
Future<bool> resumeServiceIfEnabled() async {
|
2022-09-08 13:36:08 +00:00
|
|
|
return await isBackgroundBackupEnabled() && await enableService();
|
2022-08-18 14:41:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Enqueues the background service
|
2022-09-08 13:36:08 +00:00
|
|
|
Future<bool> enableService({bool immediate = false}) async {
|
|
|
|
try {
|
|
|
|
final callback = PluginUtilities.getCallbackHandle(_nativeEntry)!;
|
|
|
|
final String title =
|
|
|
|
"backup_background_service_default_notification".tr();
|
2024-05-09 17:16:53 +00:00
|
|
|
final bool ok = await _foregroundChannel
|
|
|
|
.invokeMethod('enable', [callback.toRawHandle(), title, immediate]);
|
2022-09-08 13:36:08 +00:00
|
|
|
return ok;
|
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Configures the background service
|
|
|
|
Future<bool> configureService({
|
2022-08-18 14:41:59 +00:00
|
|
|
bool requireUnmetered = true,
|
|
|
|
bool requireCharging = false,
|
2022-12-08 15:51:36 +00:00
|
|
|
int triggerUpdateDelay = 5000,
|
|
|
|
int triggerMaxDelay = 50000,
|
2022-08-18 14:41:59 +00:00
|
|
|
}) async {
|
|
|
|
try {
|
|
|
|
final bool ok = await _foregroundChannel.invokeMethod(
|
2022-09-08 13:36:08 +00:00
|
|
|
'configure',
|
2022-12-08 15:51:36 +00:00
|
|
|
[
|
|
|
|
requireUnmetered,
|
|
|
|
requireCharging,
|
|
|
|
triggerUpdateDelay,
|
2023-08-18 22:52:40 +00:00
|
|
|
triggerMaxDelay,
|
2022-12-08 15:51:36 +00:00
|
|
|
],
|
2022-08-18 14:41:59 +00:00
|
|
|
);
|
|
|
|
return ok;
|
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Cancels the background service (if currently running) and removes it from work queue
|
2022-09-08 13:36:08 +00:00
|
|
|
Future<bool> disableService() async {
|
2022-08-18 14:41:59 +00:00
|
|
|
try {
|
2022-09-08 13:36:08 +00:00
|
|
|
final ok = await _foregroundChannel.invokeMethod('disable');
|
2022-08-18 14:41:59 +00:00
|
|
|
return ok;
|
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns `true` if the background service is enabled
|
|
|
|
Future<bool> isBackgroundBackupEnabled() async {
|
|
|
|
try {
|
|
|
|
return await _foregroundChannel.invokeMethod("isEnabled");
|
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-31 13:08:40 +00:00
|
|
|
/// Returns `true` if battery optimizations are disabled
|
|
|
|
Future<bool> isIgnoringBatteryOptimizations() async {
|
2023-02-20 05:59:50 +00:00
|
|
|
// iOS does not need battery optimizations enabled
|
|
|
|
if (Platform.isIOS) {
|
2022-08-18 14:41:59 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
try {
|
2022-08-31 13:08:40 +00:00
|
|
|
return await _foregroundChannel
|
|
|
|
.invokeMethod('isIgnoringBatteryOptimizations');
|
2022-08-18 14:41:59 +00:00
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-05 16:49:43 +00:00
|
|
|
// Yet to be implemented
|
2023-06-10 18:13:59 +00:00
|
|
|
Future<Uint8List?> digestFile(String path) {
|
|
|
|
return _foregroundChannel.invokeMethod<Uint8List>("digestFile", [path]);
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<List<Uint8List?>?> digestFiles(List<String> paths) {
|
|
|
|
return _foregroundChannel.invokeListMethod<Uint8List?>(
|
|
|
|
"digestFiles",
|
|
|
|
paths,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-08-18 14:41:59 +00:00
|
|
|
/// Updates the notification shown by the background service
|
2022-10-05 14:59:35 +00:00
|
|
|
Future<bool?> _updateNotification({
|
|
|
|
String? title,
|
2022-08-18 14:41:59 +00:00
|
|
|
String? content,
|
2022-10-05 14:59:35 +00:00
|
|
|
int progress = 0,
|
|
|
|
int max = 0,
|
|
|
|
bool indeterminate = false,
|
|
|
|
bool isDetail = false,
|
|
|
|
bool onlyIfFG = false,
|
2022-08-18 14:41:59 +00:00
|
|
|
}) async {
|
|
|
|
try {
|
|
|
|
if (_isBackgroundInitialized) {
|
2022-10-05 14:59:35 +00:00
|
|
|
return _backgroundChannel.invokeMethod<bool>(
|
|
|
|
'updateNotification',
|
|
|
|
[title, content, progress, max, indeterminate, isDetail, onlyIfFG],
|
|
|
|
);
|
2022-08-18 14:41:59 +00:00
|
|
|
}
|
|
|
|
} catch (error) {
|
2022-08-21 16:29:24 +00:00
|
|
|
debugPrint("[_updateNotification] failed to communicate with plugin");
|
2022-08-18 14:41:59 +00:00
|
|
|
}
|
2022-10-05 14:59:35 +00:00
|
|
|
return false;
|
2022-08-18 14:41:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Shows a new priority notification
|
2022-08-21 16:29:24 +00:00
|
|
|
Future<bool> _showErrorNotification({
|
|
|
|
required String title,
|
|
|
|
String? content,
|
|
|
|
String? individualTag,
|
|
|
|
}) async {
|
2022-08-18 14:41:59 +00:00
|
|
|
try {
|
2022-08-21 16:29:24 +00:00
|
|
|
if (_isBackgroundInitialized && _errorGracePeriodExceeded) {
|
2022-08-18 14:41:59 +00:00
|
|
|
return await _backgroundChannel
|
2022-08-21 16:29:24 +00:00
|
|
|
.invokeMethod('showError', [title, content, individualTag]);
|
2022-08-18 14:41:59 +00:00
|
|
|
}
|
|
|
|
} catch (error) {
|
2022-08-21 16:29:24 +00:00
|
|
|
debugPrint("[_showErrorNotification] failed to communicate with plugin");
|
2022-08-18 14:41:59 +00:00
|
|
|
}
|
2022-08-21 16:29:24 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<bool> _clearErrorNotifications() async {
|
|
|
|
try {
|
|
|
|
if (_isBackgroundInitialized) {
|
|
|
|
return await _backgroundChannel.invokeMethod('clearErrorNotifications');
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
debugPrint(
|
2022-09-10 16:46:51 +00:00
|
|
|
"[_clearErrorNotifications] failed to communicate with plugin",
|
|
|
|
);
|
2022-08-21 16:29:24 +00:00
|
|
|
}
|
|
|
|
return false;
|
2022-08-18 14:41:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// await to ensure this thread (foreground or background) has exclusive access
|
|
|
|
Future<bool> acquireLock() async {
|
2022-11-08 17:00:24 +00:00
|
|
|
if (_hasLock) {
|
|
|
|
debugPrint("WARNING: [acquireLock] called more than once");
|
|
|
|
return true;
|
|
|
|
}
|
2022-08-18 14:41:59 +00: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);
|
|
|
|
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
|
2023-02-20 05:59:50 +00:00
|
|
|
.timeout(const Duration(seconds: 3), onTimeout: () => null);
|
2022-08-18 14:41:59 +00:00
|
|
|
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
|
2023-02-20 05:59:50 +00:00
|
|
|
.timeout(const Duration(seconds: 3), onTimeout: () => false);
|
2022-08-18 14:41:59 +00:00
|
|
|
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() {
|
|
|
|
_wantsLockTime = 0;
|
|
|
|
if (_hasLock) {
|
|
|
|
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 {
|
2023-02-20 05:59:50 +00:00
|
|
|
DartPluginRegistrant.ensureInitialized();
|
|
|
|
if (Platform.isIOS) {
|
|
|
|
// NOTE: I'm not sure this is strictly necessary anymore, but
|
|
|
|
// out of an abundance of caution, we will keep it in until someone
|
|
|
|
// can say for sure
|
|
|
|
PathProviderIOS.registerWith();
|
|
|
|
}
|
2022-08-18 14:41:59 +00:00
|
|
|
switch (call.method) {
|
2023-02-20 05:59:50 +00:00
|
|
|
case "backgroundProcessing":
|
2022-08-18 14:41:59 +00:00
|
|
|
case "onAssetsChanged":
|
|
|
|
try {
|
2022-10-05 14:59:35 +00:00
|
|
|
_clearErrorNotifications();
|
2023-02-20 05:59:50 +00:00
|
|
|
|
|
|
|
// iOS should time out after some threshhold so it doesn't wait
|
|
|
|
// indefinitely and can run later
|
|
|
|
// Android is fine to wait here until the lock releases
|
|
|
|
final waitForLock = Platform.isIOS
|
2023-02-21 03:40:19 +00:00
|
|
|
? acquireLock().timeout(
|
|
|
|
const Duration(seconds: 5),
|
|
|
|
onTimeout: () => false,
|
|
|
|
)
|
|
|
|
: acquireLock();
|
2023-02-20 05:59:50 +00:00
|
|
|
|
|
|
|
final bool hasAccess = await waitForLock;
|
2022-08-18 14:41:59 +00:00
|
|
|
if (!hasAccess) {
|
2022-09-08 13:36:08 +00:00
|
|
|
debugPrint("[_callHandler] could not acquire lock, exiting");
|
2022-08-18 14:41:59 +00:00
|
|
|
return false;
|
|
|
|
}
|
2023-02-21 03:44:14 +00:00
|
|
|
|
2023-02-21 12:28:52 +00:00
|
|
|
final translationsOk = await loadTranslations();
|
|
|
|
if (!translationsOk) {
|
|
|
|
debugPrint("[_callHandler] could not load translations");
|
2023-02-21 03:44:14 +00:00
|
|
|
}
|
|
|
|
|
2022-08-21 16:29:24 +00:00
|
|
|
final bool ok = await _onAssetsChanged();
|
|
|
|
return ok;
|
2022-08-18 14:41:59 +00:00
|
|
|
} catch (error) {
|
|
|
|
debugPrint(error.toString());
|
|
|
|
return false;
|
|
|
|
} finally {
|
|
|
|
releaseLock();
|
|
|
|
}
|
|
|
|
case "systemStop":
|
|
|
|
_canceledBySystem = true;
|
|
|
|
_cancellationToken?.cancel();
|
|
|
|
return true;
|
|
|
|
default:
|
|
|
|
debugPrint("Unknown method ${call.method}");
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<bool> _onAssetsChanged() async {
|
2024-09-30 14:37:30 +00:00
|
|
|
final db = await loadDb();
|
2022-08-18 14:41:59 +00:00
|
|
|
|
2024-09-02 19:42:51 +00:00
|
|
|
HttpOverrides.global = HttpSSLCertOverride();
|
2022-08-18 14:41:59 +00:00
|
|
|
ApiService apiService = ApiService();
|
2023-03-23 01:36:44 +00:00
|
|
|
apiService.setAccessToken(Store.get(StoreKey.accessToken));
|
2022-10-05 14:59:35 +00:00
|
|
|
AppSettingsService settingsService = AppSettingsService();
|
2024-09-16 20:26:14 +00:00
|
|
|
AlbumRepository albumRepository = AlbumRepository(db);
|
|
|
|
AssetRepository assetRepository = AssetRepository(db);
|
2024-09-30 14:37:30 +00:00
|
|
|
BackupRepository backupRepository = BackupRepository(db);
|
|
|
|
ExifInfoRepository exifInfoRepository = ExifInfoRepository(db);
|
|
|
|
ETagRepository eTagRepository = ETagRepository(db);
|
2024-09-18 15:15:52 +00:00
|
|
|
AlbumMediaRepository albumMediaRepository = AlbumMediaRepository();
|
|
|
|
FileMediaRepository fileMediaRepository = FileMediaRepository();
|
2024-09-27 15:28:31 +00:00
|
|
|
AssetMediaRepository assetMediaRepository = AssetMediaRepository();
|
2024-09-20 13:32:37 +00:00
|
|
|
UserRepository userRepository = UserRepository(db);
|
2024-09-24 12:50:21 +00:00
|
|
|
UserApiRepository userApiRepository =
|
|
|
|
UserApiRepository(apiService.usersApi);
|
2024-09-20 13:32:37 +00:00
|
|
|
AlbumApiRepository albumApiRepository =
|
|
|
|
AlbumApiRepository(apiService.albumsApi);
|
2024-09-24 12:50:21 +00:00
|
|
|
PartnerApiRepository partnerApiRepository =
|
|
|
|
PartnerApiRepository(apiService.partnersApi);
|
|
|
|
HashService hashService =
|
|
|
|
HashService(assetRepository, this, albumMediaRepository);
|
2024-09-20 13:32:37 +00:00
|
|
|
EntityService entityService =
|
|
|
|
EntityService(assetRepository, userRepository);
|
|
|
|
SyncService syncSerive = SyncService(
|
|
|
|
hashService,
|
|
|
|
entityService,
|
|
|
|
albumMediaRepository,
|
|
|
|
albumApiRepository,
|
2024-09-30 14:37:30 +00:00
|
|
|
albumRepository,
|
|
|
|
assetRepository,
|
|
|
|
exifInfoRepository,
|
|
|
|
userRepository,
|
|
|
|
eTagRepository,
|
2024-09-20 13:32:37 +00:00
|
|
|
);
|
2024-09-24 12:50:21 +00:00
|
|
|
UserService userService = UserService(
|
|
|
|
partnerApiRepository,
|
|
|
|
userApiRepository,
|
|
|
|
userRepository,
|
|
|
|
syncSerive,
|
|
|
|
);
|
2024-09-16 20:26:14 +00:00
|
|
|
AlbumService albumService = AlbumService(
|
|
|
|
userService,
|
|
|
|
syncSerive,
|
2024-09-20 13:32:37 +00:00
|
|
|
entityService,
|
2024-09-16 20:26:14 +00:00
|
|
|
albumRepository,
|
|
|
|
assetRepository,
|
2024-09-30 14:37:30 +00:00
|
|
|
backupRepository,
|
2024-09-18 15:15:52 +00:00
|
|
|
albumMediaRepository,
|
2024-09-20 13:32:37 +00:00
|
|
|
albumApiRepository,
|
2024-09-18 15:15:52 +00:00
|
|
|
);
|
|
|
|
BackupService backupService = BackupService(
|
|
|
|
apiService,
|
2024-12-27 15:45:23 +00:00
|
|
|
settingsService,
|
2024-09-18 15:15:52 +00:00
|
|
|
albumService,
|
|
|
|
albumMediaRepository,
|
|
|
|
fileMediaRepository,
|
2024-09-30 14:37:30 +00:00
|
|
|
assetRepository,
|
2024-09-27 15:28:31 +00:00
|
|
|
assetMediaRepository,
|
2024-09-16 20:26:14 +00:00
|
|
|
);
|
2022-08-18 14:41:59 +00:00
|
|
|
|
2024-12-05 15:11:48 +00:00
|
|
|
AuthApiRepository authApiRepository = AuthApiRepository(apiService);
|
|
|
|
AuthRepository authRepository = AuthRepository(db);
|
|
|
|
NetworkRepository networkRepository = NetworkRepository(NetworkInfo());
|
|
|
|
PermissionRepository permissionRepository = PermissionRepository();
|
|
|
|
NetworkService networkService =
|
|
|
|
NetworkService(networkRepository, permissionRepository);
|
|
|
|
AuthService authService = AuthService(
|
|
|
|
authApiRepository,
|
|
|
|
authRepository,
|
|
|
|
apiService,
|
|
|
|
networkService,
|
|
|
|
);
|
|
|
|
|
|
|
|
final endpoint = await authService.setOpenApiServiceEndpoint();
|
|
|
|
if (kDebugMode) {
|
|
|
|
debugPrint("[BG UPLOAD] Using endpoint: $endpoint");
|
|
|
|
}
|
|
|
|
|
2024-09-30 14:37:30 +00:00
|
|
|
final selectedAlbums =
|
|
|
|
await backupRepository.getAllBySelection(BackupSelection.select);
|
|
|
|
final excludedAlbums =
|
|
|
|
await backupRepository.getAllBySelection(BackupSelection.exclude);
|
2023-03-18 14:55:11 +00:00
|
|
|
if (selectedAlbums.isEmpty) {
|
2022-08-18 14:41:59 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2024-09-18 15:15:52 +00:00
|
|
|
await fileMediaRepository.enableBackgroundAccess();
|
2022-09-08 13:36:08 +00:00
|
|
|
|
|
|
|
do {
|
2022-10-05 14:59:35 +00:00
|
|
|
final bool backupOk = await _runBackup(
|
|
|
|
backupService,
|
|
|
|
settingsService,
|
2023-03-18 14:55:11 +00:00
|
|
|
selectedAlbums,
|
2024-06-29 16:30:18 +00:00
|
|
|
excludedAlbums,
|
2022-10-05 14:59:35 +00:00
|
|
|
);
|
2022-09-08 13:36:08 +00:00
|
|
|
if (backupOk) {
|
2023-03-18 14:55:11 +00:00
|
|
|
await Store.delete(StoreKey.backupFailedSince);
|
2024-06-29 16:30:18 +00:00
|
|
|
final backupAlbums = [...selectedAlbums, ...excludedAlbums];
|
2023-03-18 14:55:11 +00:00
|
|
|
backupAlbums.sortBy((e) => e.id);
|
2024-09-30 14:37:30 +00:00
|
|
|
|
|
|
|
final dbAlbums =
|
|
|
|
await backupRepository.getAll(sort: BackupAlbumSort.id);
|
|
|
|
final List<int> toDelete = [];
|
|
|
|
final List<BackupAlbum> toUpsert = [];
|
|
|
|
// stores the most recent `lastBackup` per album but always keeps the `selection` from the most recent DB state
|
|
|
|
diffSortedListsSync(
|
|
|
|
dbAlbums,
|
|
|
|
backupAlbums,
|
|
|
|
compare: (BackupAlbum a, BackupAlbum b) => a.id.compareTo(b.id),
|
|
|
|
both: (BackupAlbum a, BackupAlbum b) {
|
|
|
|
a.lastBackup = a.lastBackup.isAfter(b.lastBackup)
|
|
|
|
? a.lastBackup
|
|
|
|
: b.lastBackup;
|
|
|
|
toUpsert.add(a);
|
|
|
|
return true;
|
|
|
|
},
|
|
|
|
onlyFirst: (BackupAlbum a) => toUpsert.add(a),
|
|
|
|
onlySecond: (BackupAlbum b) => toDelete.add(b.isarId),
|
|
|
|
);
|
|
|
|
await backupRepository.deleteAll(toDelete);
|
|
|
|
await backupRepository.updateAll(toUpsert);
|
2023-03-23 01:36:44 +00:00
|
|
|
} else if (Store.tryGet(StoreKey.backupFailedSince) == null) {
|
2023-03-18 14:55:11 +00:00
|
|
|
Store.put(StoreKey.backupFailedSince, DateTime.now());
|
2022-09-08 13:36:08 +00:00
|
|
|
return false;
|
|
|
|
}
|
2023-02-20 05:59:50 +00:00
|
|
|
// Android should check for new assets added while performing backup
|
|
|
|
} while (Platform.isAndroid &&
|
2023-02-21 03:40:19 +00:00
|
|
|
true ==
|
|
|
|
await _backgroundChannel.invokeMethod<bool>("hasContentChanged"));
|
2022-09-08 13:36:08 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<bool> _runBackup(
|
2022-09-10 16:46:51 +00:00
|
|
|
BackupService backupService,
|
2022-10-05 14:59:35 +00:00
|
|
|
AppSettingsService settingsService,
|
2023-03-18 14:55:11 +00:00
|
|
|
List<BackupAlbum> selectedAlbums,
|
2024-06-29 16:30:18 +00:00
|
|
|
List<BackupAlbum> excludedAlbums,
|
2022-09-10 16:46:51 +00:00
|
|
|
) async {
|
2022-10-05 14:59:35 +00:00
|
|
|
_errorGracePeriodExceeded = _isErrorGracePeriodExceeded(settingsService);
|
|
|
|
final bool notifyTotalProgress = settingsService
|
|
|
|
.getSetting<bool>(AppSettingsEnum.backgroundBackupTotalProgress);
|
|
|
|
final bool notifySingleProgress = settingsService
|
|
|
|
.getSetting<bool>(AppSettingsEnum.backgroundBackupSingleProgress);
|
2022-08-18 14:41:59 +00:00
|
|
|
|
|
|
|
if (_canceledBySystem) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2024-08-26 18:21:19 +00:00
|
|
|
Set<BackupCandidate> toUpload = await backupService.buildUploadCandidates(
|
2023-03-18 14:55:11 +00:00
|
|
|
selectedAlbums,
|
2024-06-29 16:30:18 +00:00
|
|
|
excludedAlbums,
|
2023-03-18 14:55:11 +00:00
|
|
|
);
|
2022-08-21 16:29:24 +00:00
|
|
|
|
|
|
|
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 14:41:59 +00:00
|
|
|
|
|
|
|
if (_canceledBySystem) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (toUpload.isEmpty) {
|
|
|
|
return true;
|
|
|
|
}
|
2022-10-05 14:59:35 +00:00
|
|
|
_assetsToUploadCount = toUpload.length;
|
|
|
|
_uploadedAssetsCount = 0;
|
|
|
|
_updateNotification(
|
|
|
|
title: "backup_background_service_in_progress_notification".tr(),
|
2023-08-06 02:40:50 +00:00
|
|
|
content: notifyTotalProgress
|
|
|
|
? formatAssetBackupProgress(
|
|
|
|
_uploadedAssetsCount,
|
|
|
|
_assetsToUploadCount,
|
|
|
|
)
|
|
|
|
: null,
|
2022-10-05 14:59:35 +00:00
|
|
|
progress: 0,
|
|
|
|
max: notifyTotalProgress ? _assetsToUploadCount : 0,
|
|
|
|
indeterminate: !notifyTotalProgress,
|
|
|
|
onlyIfFG: !notifyTotalProgress,
|
|
|
|
);
|
2022-08-18 14:41:59 +00:00
|
|
|
|
|
|
|
_cancellationToken = CancellationToken();
|
2023-12-10 15:56:39 +00:00
|
|
|
final pmProgressHandler = Platform.isIOS ? PMProgressHandler() : null;
|
2023-12-07 15:53:15 +00:00
|
|
|
|
2022-08-18 14:41:59 +00:00
|
|
|
final bool ok = await backupService.backupAsset(
|
|
|
|
toUpload,
|
|
|
|
_cancellationToken!,
|
2024-08-26 18:21:19 +00:00
|
|
|
pmProgressHandler: pmProgressHandler,
|
|
|
|
onSuccess: (result) => _onAssetUploaded(
|
|
|
|
result: result,
|
|
|
|
shouldNotify: notifyTotalProgress,
|
|
|
|
),
|
|
|
|
onProgress: (bytes, totalBytes) =>
|
|
|
|
_onProgress(bytes, totalBytes, shouldNotify: notifySingleProgress),
|
|
|
|
onCurrentAsset: (asset) =>
|
|
|
|
_onSetCurrentBackupAsset(asset, shouldNotify: notifySingleProgress),
|
|
|
|
onError: _onBackupError,
|
|
|
|
isBackground: true,
|
2022-08-18 14:41:59 +00:00
|
|
|
);
|
2024-08-26 18:21:19 +00:00
|
|
|
|
2022-10-05 14:59:35 +00:00
|
|
|
if (!ok && !_cancellationToken!.isCancelled) {
|
2022-08-21 16:29:24 +00:00
|
|
|
_showErrorNotification(
|
|
|
|
title: "backup_background_service_error_title".tr(),
|
|
|
|
content: "backup_background_service_backup_failed_message".tr(),
|
|
|
|
);
|
2022-08-18 14:41:59 +00:00
|
|
|
}
|
2024-08-26 18:21:19 +00:00
|
|
|
|
2022-08-18 14:41:59 +00:00
|
|
|
return ok;
|
|
|
|
}
|
|
|
|
|
2024-08-26 18:21:19 +00:00
|
|
|
void _onAssetUploaded({
|
|
|
|
required SuccessUploadAsset result,
|
|
|
|
bool shouldNotify = false,
|
|
|
|
}) async {
|
|
|
|
if (!shouldNotify) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-10-05 14:59:35 +00:00
|
|
|
_uploadedAssetsCount++;
|
2022-11-01 08:16:46 +00:00
|
|
|
_throttledNotifiy();
|
2022-08-18 14:41:59 +00:00
|
|
|
}
|
|
|
|
|
2024-08-26 18:21:19 +00:00
|
|
|
void _onProgress(int bytes, int totalBytes, {bool shouldNotify = false}) {
|
|
|
|
if (!shouldNotify) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
_throttledDetailNotify(progress: bytes, total: totalBytes);
|
2022-11-01 02:02:06 +00:00
|
|
|
}
|
|
|
|
|
2022-11-01 08:16:46 +00:00
|
|
|
void _updateDetailProgress(String? title, int progress, int total) {
|
|
|
|
final String msg =
|
2023-08-06 02:40:50 +00:00
|
|
|
total > 0 ? humanReadableBytesProgress(progress, total) : "";
|
2022-11-01 02:02:06 +00:00
|
|
|
// only update if message actually differs (to stop many useless notification updates on large assets or slow connections)
|
2022-11-01 08:16:46 +00:00
|
|
|
if (msg != _lastPrintedDetailContent || _lastPrintedDetailTitle != title) {
|
|
|
|
_lastPrintedDetailContent = msg;
|
|
|
|
_lastPrintedDetailTitle = title;
|
2022-11-01 02:02:06 +00:00
|
|
|
_updateNotification(
|
2022-11-01 08:16:46 +00:00
|
|
|
progress: total > 0 ? (progress * 1000) ~/ total : 0,
|
|
|
|
max: 1000,
|
2022-11-01 02:02:06 +00:00
|
|
|
isDetail: true,
|
2022-11-01 08:16:46 +00:00
|
|
|
title: title,
|
2022-11-01 02:02:06 +00:00
|
|
|
content: msg,
|
|
|
|
);
|
2022-10-05 14:59:35 +00:00
|
|
|
}
|
|
|
|
}
|
2022-08-18 14:41:59 +00:00
|
|
|
|
2022-11-01 08:16:46 +00:00
|
|
|
void _updateProgress(String? title, int progress, int total) {
|
|
|
|
_updateNotification(
|
|
|
|
progress: _uploadedAssetsCount,
|
|
|
|
max: _assetsToUploadCount,
|
|
|
|
title: title,
|
2023-08-06 02:40:50 +00:00
|
|
|
content: formatAssetBackupProgress(
|
|
|
|
_uploadedAssetsCount,
|
|
|
|
_assetsToUploadCount,
|
|
|
|
),
|
2022-11-01 08:16:46 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-08-18 14:41:59 +00:00
|
|
|
void _onBackupError(ErrorUploadAsset errorAssetInfo) {
|
2022-08-21 16:29:24 +00:00
|
|
|
_showErrorNotification(
|
2022-10-05 14:59:35 +00:00
|
|
|
title: "backup_background_service_upload_failure_notification"
|
2022-08-18 14:41:59 +00:00
|
|
|
.tr(args: [errorAssetInfo.fileName]),
|
2022-08-21 16:29:24 +00:00
|
|
|
individualTag: errorAssetInfo.id,
|
2022-08-18 14:41:59 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-08-26 18:21:19 +00:00
|
|
|
void _onSetCurrentBackupAsset(
|
|
|
|
CurrentUploadAsset currentUploadAsset, {
|
|
|
|
bool shouldNotify = false,
|
|
|
|
}) {
|
|
|
|
if (!shouldNotify) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-11-01 08:16:46 +00:00
|
|
|
_throttledDetailNotify.title =
|
|
|
|
"backup_background_service_current_upload_notification"
|
|
|
|
.tr(args: [currentUploadAsset.fileName]);
|
|
|
|
_throttledDetailNotify.progress = 0;
|
|
|
|
_throttledDetailNotify.total = 0;
|
2022-08-18 14:41:59 +00:00
|
|
|
}
|
2022-08-21 16:29:24 +00:00
|
|
|
|
2022-10-05 14:59:35 +00:00
|
|
|
bool _isErrorGracePeriodExceeded(AppSettingsService appSettingsService) {
|
|
|
|
final int value = appSettingsService
|
2022-08-21 16:29:24 +00:00
|
|
|
.getSetting(AppSettingsEnum.uploadErrorNotificationGracePeriod);
|
|
|
|
if (value == 0) {
|
|
|
|
return true;
|
|
|
|
} else if (value == 5) {
|
|
|
|
return false;
|
|
|
|
}
|
2023-03-23 01:36:44 +00:00
|
|
|
final DateTime? failedSince = Store.tryGet(StoreKey.backupFailedSince);
|
2022-08-21 16:29:24 +00:00
|
|
|
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 14:59:35 +00:00
|
|
|
|
2023-02-20 05:59:50 +00:00
|
|
|
Future<DateTime?> getIOSBackupLastRun(IosBackgroundTask task) async {
|
2023-02-28 16:22:18 +00:00
|
|
|
if (!Platform.isIOS) {
|
|
|
|
return null;
|
|
|
|
}
|
2023-02-20 05:59:50 +00:00
|
|
|
// Seconds since last run
|
|
|
|
final double? lastRun = task == IosBackgroundTask.fetch
|
2023-02-21 03:40:19 +00:00
|
|
|
? await _foregroundChannel.invokeMethod('lastBackgroundFetchTime')
|
|
|
|
: await _foregroundChannel.invokeMethod('lastBackgroundProcessingTime');
|
2023-02-20 05:59:50 +00:00
|
|
|
if (lastRun == null) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
final time = DateTime.fromMillisecondsSinceEpoch(lastRun.toInt() * 1000);
|
|
|
|
return time;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<int> getIOSBackupNumberOfProcesses() async {
|
2023-02-28 16:22:18 +00:00
|
|
|
if (!Platform.isIOS) {
|
|
|
|
return 0;
|
|
|
|
}
|
2023-02-21 03:40:19 +00:00
|
|
|
return await _foregroundChannel.invokeMethod('numberOfBackgroundProcesses');
|
2023-02-20 05:59:50 +00:00
|
|
|
}
|
2023-02-23 18:33:53 +00:00
|
|
|
|
|
|
|
Future<bool> getIOSBackgroundAppRefreshEnabled() async {
|
2023-02-28 16:22:18 +00:00
|
|
|
if (!Platform.isIOS) {
|
|
|
|
return false;
|
|
|
|
}
|
2023-02-23 18:33:53 +00:00
|
|
|
return await _foregroundChannel.invokeMethod('backgroundAppRefreshEnabled');
|
|
|
|
}
|
2023-02-20 05:59:50 +00:00
|
|
|
}
|
|
|
|
|
2023-02-21 03:40:19 +00:00
|
|
|
enum IosBackgroundTask { fetch, processing }
|
2022-08-18 14:41:59 +00:00
|
|
|
|
|
|
|
/// entry point called by Kotlin/Java code; needs to be a top-level function
|
2022-09-10 16:46:51 +00:00
|
|
|
@pragma('vm:entry-point')
|
2022-08-18 14:41:59 +00:00
|
|
|
void _nativeEntry() {
|
2024-05-24 09:16:14 +00:00
|
|
|
HttpOverrides.global = HttpSSLCertOverride();
|
2022-08-18 14:41:59 +00:00
|
|
|
WidgetsFlutterBinding.ensureInitialized();
|
2023-02-20 05:59:50 +00:00
|
|
|
DartPluginRegistrant.ensureInitialized();
|
2022-08-18 14:41:59 +00:00
|
|
|
BackgroundService backgroundService = BackgroundService();
|
|
|
|
backgroundService._setupBackgroundCallHandler();
|
|
|
|
}
|