2025-04-17 20:55:27 +05:30
|
|
|
import 'dart:async';
|
|
|
|
|
2025-05-29 21:12:00 +05:30
|
|
|
import 'package:immich_mobile/providers/infrastructure/sync.provider.dart';
|
2025-04-17 20:55:27 +05:30
|
|
|
import 'package:immich_mobile/utils/isolate.dart';
|
|
|
|
import 'package:worker_manager/worker_manager.dart';
|
|
|
|
|
|
|
|
class BackgroundSyncManager {
|
2025-04-18 14:01:16 -05:00
|
|
|
Cancelable<void>? _syncTask;
|
2025-05-29 21:12:00 +05:30
|
|
|
Cancelable<void>? _deviceAlbumSyncTask;
|
2025-06-06 11:23:05 +05:30
|
|
|
Cancelable<void>? _hashTask;
|
2025-04-17 20:55:27 +05:30
|
|
|
|
|
|
|
BackgroundSyncManager();
|
|
|
|
|
|
|
|
Future<void> cancel() {
|
|
|
|
final futures = <Future>[];
|
2025-04-18 14:01:16 -05:00
|
|
|
|
|
|
|
if (_syncTask != null) {
|
|
|
|
futures.add(_syncTask!.future);
|
2025-04-17 20:55:27 +05:30
|
|
|
}
|
2025-04-18 14:01:16 -05:00
|
|
|
_syncTask?.cancel();
|
|
|
|
_syncTask = null;
|
|
|
|
|
2025-04-17 20:55:27 +05:30
|
|
|
return Future.wait(futures);
|
|
|
|
}
|
|
|
|
|
2025-05-29 21:12:00 +05:30
|
|
|
// No need to cancel the task, as it can also be run when the user logs out
|
|
|
|
Future<void> syncLocal({bool full = false}) {
|
|
|
|
if (_deviceAlbumSyncTask != null) {
|
|
|
|
return _deviceAlbumSyncTask!.future;
|
|
|
|
}
|
|
|
|
|
|
|
|
// We use a ternary operator to avoid [_deviceAlbumSyncTask] from being
|
|
|
|
// captured by the closure passed to [runInIsolateGentle].
|
|
|
|
_deviceAlbumSyncTask = full
|
|
|
|
? runInIsolateGentle(
|
|
|
|
computation: (ref) =>
|
|
|
|
ref.read(localSyncServiceProvider).sync(full: true),
|
|
|
|
)
|
|
|
|
: runInIsolateGentle(
|
|
|
|
computation: (ref) =>
|
|
|
|
ref.read(localSyncServiceProvider).sync(full: false),
|
|
|
|
);
|
|
|
|
|
|
|
|
return _deviceAlbumSyncTask!.whenComplete(() {
|
|
|
|
_deviceAlbumSyncTask = null;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2025-06-06 11:23:05 +05:30
|
|
|
// No need to cancel the task, as it can also be run when the user logs out
|
|
|
|
Future<void> hashAssets() {
|
|
|
|
if (_hashTask != null) {
|
|
|
|
return _hashTask!.future;
|
|
|
|
}
|
|
|
|
|
|
|
|
_hashTask = runInIsolateGentle(
|
|
|
|
computation: (ref) => ref.read(hashServiceProvider).hashAssets(),
|
|
|
|
);
|
|
|
|
return _hashTask!.whenComplete(() {
|
|
|
|
_hashTask = null;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2025-05-29 21:12:00 +05:30
|
|
|
Future<void> syncRemote() {
|
2025-04-18 14:01:16 -05:00
|
|
|
if (_syncTask != null) {
|
|
|
|
return _syncTask!.future;
|
2025-04-17 20:55:27 +05:30
|
|
|
}
|
|
|
|
|
2025-04-18 14:01:16 -05:00
|
|
|
_syncTask = runInIsolateGentle(
|
|
|
|
computation: (ref) => ref.read(syncStreamServiceProvider).sync(),
|
2025-04-17 20:55:27 +05:30
|
|
|
);
|
2025-05-29 21:12:00 +05:30
|
|
|
return _syncTask!.whenComplete(() {
|
2025-04-18 14:01:16 -05:00
|
|
|
_syncTask = null;
|
2025-04-17 20:55:27 +05:30
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|