backup.provider.dart 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. import 'package:cancellation_token_http/http.dart';
  2. import 'package:collection/collection.dart';
  3. import 'package:flutter/widgets.dart';
  4. import 'package:hooks_riverpod/hooks_riverpod.dart';
  5. import 'package:immich_mobile/modules/backup/models/available_album.model.dart';
  6. import 'package:immich_mobile/modules/backup/models/backup_album.model.dart';
  7. import 'package:immich_mobile/modules/backup/models/backup_state.model.dart';
  8. import 'package:immich_mobile/modules/backup/models/current_upload_asset.model.dart';
  9. import 'package:immich_mobile/modules/backup/models/error_upload_asset.model.dart';
  10. import 'package:immich_mobile/modules/backup/providers/error_backup_list.provider.dart';
  11. import 'package:immich_mobile/modules/backup/background_service/background.service.dart';
  12. import 'package:immich_mobile/modules/backup/services/backup.service.dart';
  13. import 'package:immich_mobile/modules/login/models/authentication_state.model.dart';
  14. import 'package:immich_mobile/modules/login/providers/authentication.provider.dart';
  15. import 'package:immich_mobile/modules/onboarding/providers/gallery_permission.provider.dart';
  16. import 'package:immich_mobile/shared/models/store.dart';
  17. import 'package:immich_mobile/shared/providers/app_state.provider.dart';
  18. import 'package:immich_mobile/shared/providers/db.provider.dart';
  19. import 'package:immich_mobile/shared/services/server_info.service.dart';
  20. import 'package:immich_mobile/utils/diff.dart';
  21. import 'package:isar/isar.dart';
  22. import 'package:logging/logging.dart';
  23. import 'package:openapi/api.dart';
  24. import 'package:permission_handler/permission_handler.dart';
  25. import 'package:photo_manager/photo_manager.dart';
  26. class BackupNotifier extends StateNotifier<BackUpState> {
  27. BackupNotifier(
  28. this._backupService,
  29. this._serverInfoService,
  30. this._authState,
  31. this._backgroundService,
  32. this._galleryPermissionNotifier,
  33. this._db,
  34. this.ref,
  35. ) : super(
  36. BackUpState(
  37. backupProgress: BackUpProgressEnum.idle,
  38. allAssetsInDatabase: const [],
  39. progressInPercentage: 0,
  40. cancelToken: CancellationToken(),
  41. autoBackup: Store.get(StoreKey.autoBackup, false),
  42. backgroundBackup: false,
  43. backupRequireWifi: Store.get(StoreKey.backupRequireWifi, true),
  44. backupRequireCharging:
  45. Store.get(StoreKey.backupRequireCharging, false),
  46. backupTriggerDelay: Store.get(StoreKey.backupTriggerDelay, 5000),
  47. serverInfo: ServerInfoResponseDto(
  48. diskAvailable: "0",
  49. diskAvailableRaw: 0,
  50. diskSize: "0",
  51. diskSizeRaw: 0,
  52. diskUsagePercentage: 0,
  53. diskUse: "0",
  54. diskUseRaw: 0,
  55. ),
  56. availableAlbums: const [],
  57. selectedBackupAlbums: const {},
  58. excludedBackupAlbums: const {},
  59. allUniqueAssets: const {},
  60. selectedAlbumsBackupAssetsIds: const {},
  61. currentUploadAsset: CurrentUploadAsset(
  62. id: '...',
  63. fileCreatedAt: DateTime.parse('2020-10-04'),
  64. fileName: '...',
  65. fileType: '...',
  66. ),
  67. ),
  68. );
  69. final log = Logger('BackupNotifier');
  70. final BackupService _backupService;
  71. final ServerInfoService _serverInfoService;
  72. final AuthenticationState _authState;
  73. final BackgroundService _backgroundService;
  74. final GalleryPermissionNotifier _galleryPermissionNotifier;
  75. final Isar _db;
  76. final Ref ref;
  77. ///
  78. /// UI INTERACTION
  79. ///
  80. /// Album selection
  81. /// Due to the overlapping assets across multiple albums on the device
  82. /// We have method to include and exclude albums
  83. /// The total unique assets will be used for backing mechanism
  84. ///
  85. void addAlbumForBackup(AvailableAlbum album) {
  86. if (state.excludedBackupAlbums.contains(album)) {
  87. removeExcludedAlbumForBackup(album);
  88. }
  89. state = state
  90. .copyWith(selectedBackupAlbums: {...state.selectedBackupAlbums, album});
  91. _updateBackupAssetCount();
  92. }
  93. void addExcludedAlbumForBackup(AvailableAlbum album) {
  94. if (state.selectedBackupAlbums.contains(album)) {
  95. removeAlbumForBackup(album);
  96. }
  97. state = state
  98. .copyWith(excludedBackupAlbums: {...state.excludedBackupAlbums, album});
  99. _updateBackupAssetCount();
  100. }
  101. void removeAlbumForBackup(AvailableAlbum album) {
  102. Set<AvailableAlbum> currentSelectedAlbums = state.selectedBackupAlbums;
  103. currentSelectedAlbums.removeWhere((a) => a == album);
  104. state = state.copyWith(selectedBackupAlbums: currentSelectedAlbums);
  105. _updateBackupAssetCount();
  106. }
  107. void removeExcludedAlbumForBackup(AvailableAlbum album) {
  108. Set<AvailableAlbum> currentExcludedAlbums = state.excludedBackupAlbums;
  109. currentExcludedAlbums.removeWhere((a) => a == album);
  110. state = state.copyWith(excludedBackupAlbums: currentExcludedAlbums);
  111. _updateBackupAssetCount();
  112. }
  113. void setAutoBackup(bool enabled) {
  114. Store.put(StoreKey.autoBackup, enabled);
  115. state = state.copyWith(autoBackup: enabled);
  116. }
  117. void configureBackgroundBackup({
  118. bool? enabled,
  119. bool? requireWifi,
  120. bool? requireCharging,
  121. int? triggerDelay,
  122. required void Function(String msg) onError,
  123. required void Function() onBatteryInfo,
  124. }) async {
  125. assert(
  126. enabled != null ||
  127. requireWifi != null ||
  128. requireCharging != null ||
  129. triggerDelay != null,
  130. );
  131. final bool wasEnabled = state.backgroundBackup;
  132. final bool wasWifi = state.backupRequireWifi;
  133. final bool wasCharging = state.backupRequireCharging;
  134. final int oldTriggerDelay = state.backupTriggerDelay;
  135. state = state.copyWith(
  136. backgroundBackup: enabled,
  137. backupRequireWifi: requireWifi,
  138. backupRequireCharging: requireCharging,
  139. backupTriggerDelay: triggerDelay,
  140. );
  141. if (state.backgroundBackup) {
  142. bool success = true;
  143. if (!wasEnabled) {
  144. if (!await _backgroundService.isIgnoringBatteryOptimizations()) {
  145. onBatteryInfo();
  146. }
  147. success &= await _backgroundService.enableService(immediate: true);
  148. }
  149. success &= success &&
  150. await _backgroundService.configureService(
  151. requireUnmetered: state.backupRequireWifi,
  152. requireCharging: state.backupRequireCharging,
  153. triggerUpdateDelay: state.backupTriggerDelay,
  154. triggerMaxDelay: state.backupTriggerDelay * 10,
  155. );
  156. if (success) {
  157. await Store.put(StoreKey.backupRequireWifi, state.backupRequireWifi);
  158. await Store.put(
  159. StoreKey.backupRequireCharging,
  160. state.backupRequireCharging,
  161. );
  162. await Store.put(StoreKey.backupTriggerDelay, state.backupTriggerDelay);
  163. } else {
  164. state = state.copyWith(
  165. backgroundBackup: wasEnabled,
  166. backupRequireWifi: wasWifi,
  167. backupRequireCharging: wasCharging,
  168. backupTriggerDelay: oldTriggerDelay,
  169. );
  170. onError("backup_controller_page_background_configure_error");
  171. }
  172. } else {
  173. final bool success = await _backgroundService.disableService();
  174. if (!success) {
  175. state = state.copyWith(backgroundBackup: wasEnabled);
  176. onError("backup_controller_page_background_configure_error");
  177. }
  178. }
  179. }
  180. ///
  181. /// Get all album on the device
  182. /// Get all selected and excluded album from the user's persistent storage
  183. /// If this is the first time performing backup - set the default selected album to be
  184. /// the one that has all assets (`Recent` on Android, `Recents` on iOS)
  185. ///
  186. Future<void> _getBackupAlbumsInfo() async {
  187. Stopwatch stopwatch = Stopwatch()..start();
  188. // Get all albums on the device
  189. List<AvailableAlbum> availableAlbums = [];
  190. List<AssetPathEntity> albums = await PhotoManager.getAssetPathList(
  191. hasAll: true,
  192. type: RequestType.common,
  193. );
  194. // Map of id -> album for quick album lookup later on.
  195. Map<String, AssetPathEntity> albumMap = {};
  196. log.info('Found ${albums.length} local albums');
  197. for (AssetPathEntity album in albums) {
  198. AvailableAlbum availableAlbum = AvailableAlbum(albumEntity: album);
  199. final assetCountInAlbum = await album.assetCountAsync;
  200. if (assetCountInAlbum > 0) {
  201. final assetList =
  202. await album.getAssetListRange(start: 0, end: assetCountInAlbum);
  203. if (assetList.isNotEmpty) {
  204. final thumbnailAsset = assetList.first;
  205. try {
  206. final thumbnailData = await thumbnailAsset
  207. .thumbnailDataWithSize(const ThumbnailSize(512, 512));
  208. availableAlbum =
  209. availableAlbum.copyWith(thumbnailData: thumbnailData);
  210. } catch (e, stack) {
  211. log.severe(
  212. "Failed to get thumbnail for album ${album.name}",
  213. e.toString(),
  214. stack,
  215. );
  216. }
  217. }
  218. availableAlbums.add(availableAlbum);
  219. albumMap[album.id] = album;
  220. }
  221. }
  222. state = state.copyWith(availableAlbums: availableAlbums);
  223. final List<BackupAlbum> excludedBackupAlbums =
  224. await _backupService.excludedAlbumsQuery().findAll();
  225. final List<BackupAlbum> selectedBackupAlbums =
  226. await _backupService.selectedAlbumsQuery().findAll();
  227. // First time backup - set isAll album is the default one for backup.
  228. if (selectedBackupAlbums.isEmpty) {
  229. log.info("First time backup; setup 'Recent(s)' album as default");
  230. // Get album that contains all assets
  231. final list = await PhotoManager.getAssetPathList(
  232. hasAll: true,
  233. onlyAll: true,
  234. type: RequestType.common,
  235. );
  236. if (list.isEmpty) {
  237. return;
  238. }
  239. AssetPathEntity albumHasAllAssets = list.first;
  240. final ba = BackupAlbum(
  241. albumHasAllAssets.id,
  242. DateTime.fromMillisecondsSinceEpoch(0),
  243. BackupSelection.select,
  244. );
  245. await _db.writeTxn(() => _db.backupAlbums.put(ba));
  246. }
  247. // Generate AssetPathEntity from id to add to local state
  248. final Set<AvailableAlbum> selectedAlbums = {};
  249. for (final BackupAlbum ba in selectedBackupAlbums) {
  250. final albumAsset = albumMap[ba.id];
  251. if (albumAsset != null) {
  252. selectedAlbums.add(
  253. AvailableAlbum(albumEntity: albumAsset, lastBackup: ba.lastBackup),
  254. );
  255. } else {
  256. log.severe('Selected album not found');
  257. }
  258. }
  259. final Set<AvailableAlbum> excludedAlbums = {};
  260. for (final BackupAlbum ba in excludedBackupAlbums) {
  261. final albumAsset = albumMap[ba.id];
  262. if (albumAsset != null) {
  263. excludedAlbums.add(
  264. AvailableAlbum(albumEntity: albumAsset, lastBackup: ba.lastBackup),
  265. );
  266. } else {
  267. log.severe('Excluded album not found');
  268. }
  269. }
  270. state = state.copyWith(
  271. selectedBackupAlbums: selectedAlbums,
  272. excludedBackupAlbums: excludedAlbums,
  273. );
  274. debugPrint("_getBackupAlbumsInfo takes ${stopwatch.elapsedMilliseconds}ms");
  275. }
  276. ///
  277. /// From all the selected and albums assets
  278. /// Find the assets that are not overlapping between the two sets
  279. /// Those assets are unique and are used as the total assets
  280. ///
  281. Future<void> _updateBackupAssetCount() async {
  282. final duplicatedAssetIds = await _backupService.getDuplicatedAssetIds();
  283. final Set<AssetEntity> assetsFromSelectedAlbums = {};
  284. final Set<AssetEntity> assetsFromExcludedAlbums = {};
  285. for (final album in state.selectedBackupAlbums) {
  286. final assets = await album.albumEntity.getAssetListRange(
  287. start: 0,
  288. end: await album.albumEntity.assetCountAsync,
  289. );
  290. assetsFromSelectedAlbums.addAll(assets);
  291. }
  292. for (final album in state.excludedBackupAlbums) {
  293. final assets = await album.albumEntity.getAssetListRange(
  294. start: 0,
  295. end: await album.albumEntity.assetCountAsync,
  296. );
  297. assetsFromExcludedAlbums.addAll(assets);
  298. }
  299. final Set<AssetEntity> allUniqueAssets =
  300. assetsFromSelectedAlbums.difference(assetsFromExcludedAlbums);
  301. final allAssetsInDatabase = await _backupService.getDeviceBackupAsset();
  302. if (allAssetsInDatabase == null) {
  303. return;
  304. }
  305. // Find asset that were backup from selected albums
  306. final Set<String> selectedAlbumsBackupAssets =
  307. Set.from(allUniqueAssets.map((e) => e.id));
  308. selectedAlbumsBackupAssets
  309. .removeWhere((assetId) => !allAssetsInDatabase.contains(assetId));
  310. // Remove duplicated asset from all unique assets
  311. allUniqueAssets.removeWhere(
  312. (asset) => duplicatedAssetIds.contains(asset.id),
  313. );
  314. if (allUniqueAssets.isEmpty) {
  315. log.info("Not found albums or assets on the device to backup");
  316. state = state.copyWith(
  317. backupProgress: BackUpProgressEnum.idle,
  318. allAssetsInDatabase: allAssetsInDatabase,
  319. allUniqueAssets: {},
  320. selectedAlbumsBackupAssetsIds: selectedAlbumsBackupAssets,
  321. );
  322. return;
  323. } else {
  324. state = state.copyWith(
  325. allAssetsInDatabase: allAssetsInDatabase,
  326. allUniqueAssets: allUniqueAssets,
  327. selectedAlbumsBackupAssetsIds: selectedAlbumsBackupAssets,
  328. );
  329. }
  330. // Save to persistent storage
  331. await _updatePersistentAlbumsSelection();
  332. return;
  333. }
  334. /// Get all necessary information for calculating the available albums,
  335. /// which albums are selected or excluded
  336. /// and then update the UI according to those information
  337. Future<void> getBackupInfo() async {
  338. final isEnabled = await _backgroundService.isBackgroundBackupEnabled();
  339. state = state.copyWith(backgroundBackup: isEnabled);
  340. if (state.backupProgress != BackUpProgressEnum.inBackground) {
  341. await _getBackupAlbumsInfo();
  342. await updateServerInfo();
  343. await _updateBackupAssetCount();
  344. }
  345. }
  346. /// Save user selection of selected albums and excluded albums to database
  347. Future<void> _updatePersistentAlbumsSelection() {
  348. final epoch = DateTime.fromMillisecondsSinceEpoch(0, isUtc: true);
  349. final selected = state.selectedBackupAlbums.map(
  350. (e) => BackupAlbum(e.id, e.lastBackup ?? epoch, BackupSelection.select),
  351. );
  352. final excluded = state.excludedBackupAlbums.map(
  353. (e) => BackupAlbum(e.id, e.lastBackup ?? epoch, BackupSelection.exclude),
  354. );
  355. final backupAlbums = selected.followedBy(excluded).toList();
  356. backupAlbums.sortBy((e) => e.id);
  357. return _db.writeTxn(() async {
  358. final dbAlbums = await _db.backupAlbums.where().sortById().findAll();
  359. final List<int> toDelete = [];
  360. final List<BackupAlbum> toUpsert = [];
  361. // stores the most recent `lastBackup` per album but always keeps the `selection` the user just made
  362. diffSortedListsSync(
  363. dbAlbums,
  364. backupAlbums,
  365. compare: (BackupAlbum a, BackupAlbum b) => a.id.compareTo(b.id),
  366. both: (BackupAlbum a, BackupAlbum b) {
  367. b.lastBackup =
  368. a.lastBackup.isAfter(b.lastBackup) ? a.lastBackup : b.lastBackup;
  369. toUpsert.add(b);
  370. return true;
  371. },
  372. onlyFirst: (BackupAlbum a) => toDelete.add(a.isarId),
  373. onlySecond: (BackupAlbum b) => toUpsert.add(b),
  374. );
  375. await _db.backupAlbums.deleteAll(toDelete);
  376. await _db.backupAlbums.putAll(toUpsert);
  377. });
  378. }
  379. /// Invoke backup process
  380. Future<void> startBackupProcess() async {
  381. debugPrint("Start backup process");
  382. assert(state.backupProgress == BackUpProgressEnum.idle);
  383. state = state.copyWith(backupProgress: BackUpProgressEnum.inProgress);
  384. await getBackupInfo();
  385. final hasPermission = _galleryPermissionNotifier.hasPermission;
  386. if (hasPermission) {
  387. await PhotoManager.clearFileCache();
  388. if (state.allUniqueAssets.isEmpty) {
  389. log.info("No Asset On Device - Abort Backup Process");
  390. state = state.copyWith(backupProgress: BackUpProgressEnum.idle);
  391. return;
  392. }
  393. Set<AssetEntity> assetsWillBeBackup = Set.from(state.allUniqueAssets);
  394. // Remove item that has already been backed up
  395. for (final assetId in state.allAssetsInDatabase) {
  396. assetsWillBeBackup.removeWhere((e) => e.id == assetId);
  397. }
  398. if (assetsWillBeBackup.isEmpty) {
  399. state = state.copyWith(backupProgress: BackUpProgressEnum.idle);
  400. }
  401. // Perform Backup
  402. state = state.copyWith(cancelToken: CancellationToken());
  403. await _backupService.backupAsset(
  404. assetsWillBeBackup,
  405. state.cancelToken,
  406. _onAssetUploaded,
  407. _onUploadProgress,
  408. _onSetCurrentBackupAsset,
  409. _onBackupError,
  410. );
  411. await notifyBackgroundServiceCanRun();
  412. } else {
  413. openAppSettings();
  414. }
  415. }
  416. void setAvailableAlbums(availableAlbums) {
  417. state = state.copyWith(
  418. availableAlbums: availableAlbums,
  419. );
  420. }
  421. void _onBackupError(ErrorUploadAsset errorAssetInfo) {
  422. ref.watch(errorBackupListProvider.notifier).add(errorAssetInfo);
  423. }
  424. void _onSetCurrentBackupAsset(CurrentUploadAsset currentUploadAsset) {
  425. state = state.copyWith(currentUploadAsset: currentUploadAsset);
  426. }
  427. void cancelBackup() {
  428. if (state.backupProgress != BackUpProgressEnum.inProgress) {
  429. notifyBackgroundServiceCanRun();
  430. }
  431. state.cancelToken.cancel();
  432. state = state.copyWith(
  433. backupProgress: BackUpProgressEnum.idle,
  434. progressInPercentage: 0.0,
  435. );
  436. }
  437. void _onAssetUploaded(
  438. String deviceAssetId,
  439. String deviceId,
  440. bool isDuplicated,
  441. ) {
  442. if (isDuplicated) {
  443. state = state.copyWith(
  444. allUniqueAssets: state.allUniqueAssets
  445. .where((asset) => asset.id != deviceAssetId)
  446. .toSet(),
  447. );
  448. } else {
  449. state = state.copyWith(
  450. selectedAlbumsBackupAssetsIds: {
  451. ...state.selectedAlbumsBackupAssetsIds,
  452. deviceAssetId,
  453. },
  454. allAssetsInDatabase: [...state.allAssetsInDatabase, deviceAssetId],
  455. );
  456. }
  457. if (state.allUniqueAssets.length -
  458. state.selectedAlbumsBackupAssetsIds.length ==
  459. 0) {
  460. final latestAssetBackup =
  461. state.allUniqueAssets.map((e) => e.modifiedDateTime).reduce(
  462. (v, e) => e.isAfter(v) ? e : v,
  463. );
  464. state = state.copyWith(
  465. selectedBackupAlbums: state.selectedBackupAlbums
  466. .map((e) => e.copyWith(lastBackup: latestAssetBackup))
  467. .toSet(),
  468. excludedBackupAlbums: state.excludedBackupAlbums
  469. .map((e) => e.copyWith(lastBackup: latestAssetBackup))
  470. .toSet(),
  471. backupProgress: BackUpProgressEnum.done,
  472. progressInPercentage: 0.0,
  473. );
  474. _updatePersistentAlbumsSelection();
  475. }
  476. updateServerInfo();
  477. }
  478. void _onUploadProgress(int sent, int total) {
  479. state = state.copyWith(
  480. progressInPercentage: (sent.toDouble() / total.toDouble() * 100),
  481. );
  482. }
  483. Future<void> updateServerInfo() async {
  484. final serverInfo = await _serverInfoService.getServerInfo();
  485. // Update server info
  486. if (serverInfo != null) {
  487. state = state.copyWith(
  488. serverInfo: serverInfo,
  489. );
  490. }
  491. }
  492. Future<void> _resumeBackup() async {
  493. // Check if user is login
  494. final accessKey = Store.tryGet(StoreKey.accessToken);
  495. // User has been logged out return
  496. if (accessKey == null || !_authState.isAuthenticated) {
  497. log.info("[_resumeBackup] not authenticated - abort");
  498. return;
  499. }
  500. // Check if this device is enable backup by the user
  501. if (state.autoBackup) {
  502. // check if backup is already in process - then return
  503. if (state.backupProgress == BackUpProgressEnum.inProgress) {
  504. log.info("[_resumeBackup] Auto Backup is already in progress - abort");
  505. return;
  506. }
  507. if (state.backupProgress == BackUpProgressEnum.inBackground) {
  508. log.info("[_resumeBackup] Background backup is running - abort");
  509. return;
  510. }
  511. if (state.backupProgress == BackUpProgressEnum.manualInProgress) {
  512. log.info("[_resumeBackup] Manual upload is running - abort");
  513. return;
  514. }
  515. // Run backup
  516. log.info("[_resumeBackup] Start back up");
  517. await startBackupProcess();
  518. }
  519. return;
  520. }
  521. Future<void> resumeBackup() async {
  522. final List<BackupAlbum> selectedBackupAlbums = await _db.backupAlbums
  523. .filter()
  524. .selectionEqualTo(BackupSelection.select)
  525. .findAll();
  526. final List<BackupAlbum> excludedBackupAlbums = await _db.backupAlbums
  527. .filter()
  528. .selectionEqualTo(BackupSelection.exclude)
  529. .findAll();
  530. Set<AvailableAlbum> selectedAlbums = state.selectedBackupAlbums;
  531. Set<AvailableAlbum> excludedAlbums = state.excludedBackupAlbums;
  532. if (selectedAlbums.isNotEmpty) {
  533. selectedAlbums = _updateAlbumsBackupTime(
  534. selectedAlbums,
  535. selectedBackupAlbums,
  536. );
  537. }
  538. if (excludedAlbums.isNotEmpty) {
  539. excludedAlbums = _updateAlbumsBackupTime(
  540. excludedAlbums,
  541. excludedBackupAlbums,
  542. );
  543. }
  544. final BackUpProgressEnum previous = state.backupProgress;
  545. state = state.copyWith(
  546. backupProgress: BackUpProgressEnum.inBackground,
  547. selectedBackupAlbums: selectedAlbums,
  548. excludedBackupAlbums: excludedAlbums,
  549. );
  550. // assumes the background service is currently running
  551. // if true, waits until it has stopped to start the backup
  552. final bool hasLock = await _backgroundService.acquireLock();
  553. if (hasLock) {
  554. state = state.copyWith(backupProgress: previous);
  555. }
  556. return _resumeBackup();
  557. }
  558. Set<AvailableAlbum> _updateAlbumsBackupTime(
  559. Set<AvailableAlbum> albums,
  560. List<BackupAlbum> backupAlbums,
  561. ) {
  562. Set<AvailableAlbum> result = {};
  563. for (BackupAlbum ba in backupAlbums) {
  564. try {
  565. AvailableAlbum a = albums.firstWhere((e) => e.id == ba.id);
  566. result.add(a.copyWith(lastBackup: ba.lastBackup));
  567. } on StateError {
  568. log.severe(
  569. "[_updateAlbumBackupTime] failed to find album in state",
  570. "State Error",
  571. StackTrace.current,
  572. );
  573. }
  574. }
  575. return result;
  576. }
  577. Future<void> notifyBackgroundServiceCanRun() async {
  578. const allowedStates = [
  579. AppStateEnum.inactive,
  580. AppStateEnum.paused,
  581. AppStateEnum.detached,
  582. ];
  583. if (allowedStates.contains(ref.read(appStateProvider.notifier).state)) {
  584. _backgroundService.releaseLock();
  585. }
  586. }
  587. BackUpProgressEnum get backupProgress => state.backupProgress;
  588. void updateBackupProgress(BackUpProgressEnum backupProgress) {
  589. state = state.copyWith(backupProgress: backupProgress);
  590. }
  591. }
  592. final backupProvider =
  593. StateNotifierProvider<BackupNotifier, BackUpState>((ref) {
  594. return BackupNotifier(
  595. ref.watch(backupServiceProvider),
  596. ref.watch(serverInfoServiceProvider),
  597. ref.watch(authenticationProvider),
  598. ref.watch(backgroundServiceProvider),
  599. ref.watch(galleryPermissionNotifier.notifier),
  600. ref.watch(dbProvider),
  601. ref,
  602. );
  603. });