local_sync_service.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:computer/computer.dart';
  4. import 'package:flutter/foundation.dart';
  5. import 'package:logging/logging.dart';
  6. import 'package:photo_manager/photo_manager.dart';
  7. import 'package:photos/core/configuration.dart';
  8. import 'package:photos/core/event_bus.dart';
  9. import 'package:photos/db/device_files_db.dart';
  10. import 'package:photos/db/file_updation_db.dart';
  11. import 'package:photos/db/files_db.dart';
  12. import 'package:photos/events/backup_folders_updated_event.dart';
  13. import 'package:photos/events/local_photos_updated_event.dart';
  14. import 'package:photos/events/sync_status_update_event.dart';
  15. import 'package:photos/extensions/stop_watch.dart';
  16. import 'package:photos/models/file.dart';
  17. import 'package:photos/services/app_lifecycle_service.dart';
  18. import 'package:photos/services/local/local_sync_util.dart';
  19. import 'package:shared_preferences/shared_preferences.dart';
  20. import 'package:sqflite/sqflite.dart';
  21. import 'package:tuple/tuple.dart';
  22. class LocalSyncService {
  23. final _logger = Logger("LocalSyncService");
  24. final _db = FilesDB.instance;
  25. final Computer _computer = Computer();
  26. late SharedPreferences _prefs;
  27. Completer<void>? _existingSync;
  28. static const kDbUpdationTimeKey = "db_updation_time";
  29. static const kHasCompletedFirstImportKey = "has_completed_firstImport";
  30. static const hasImportedDeviceCollections = "has_imported_device_collections";
  31. static const kHasGrantedPermissionsKey = "has_granted_permissions";
  32. static const kPermissionStateKey = "permission_state";
  33. static const kEditedFileIDsKey = "edited_file_ids";
  34. static const kDownloadedFileIDsKey = "downloaded_file_ids";
  35. // Adding `_2` as a suffic to pull files that were earlier ignored due to permission errors
  36. // See https://github.com/CaiJingLong/flutter_photo_manager/issues/589
  37. static const kInvalidFileIDsKey = "invalid_file_ids_2";
  38. LocalSyncService._privateConstructor();
  39. static final LocalSyncService instance =
  40. LocalSyncService._privateConstructor();
  41. Future<void> init(SharedPreferences preferences) async {
  42. _prefs = preferences;
  43. if (!AppLifecycleService.instance.isForeground) {
  44. await PhotoManager.setIgnorePermissionCheck(true);
  45. }
  46. await _computer.turnOn(workersCount: 1);
  47. if (hasGrantedPermissions()) {
  48. _registerChangeCallback();
  49. }
  50. }
  51. Future<void> sync() async {
  52. if (!_prefs.containsKey(kHasGrantedPermissionsKey)) {
  53. _logger.info("Skipping local sync since permission has not been granted");
  54. return;
  55. }
  56. if (Platform.isAndroid && AppLifecycleService.instance.isForeground) {
  57. final permissionState = await PhotoManager.requestPermissionExtend();
  58. if (permissionState != PermissionState.authorized) {
  59. _logger.severe(
  60. "sync requested with invalid permission",
  61. permissionState.toString(),
  62. );
  63. return;
  64. }
  65. }
  66. if (_existingSync != null) {
  67. _logger.warning("Sync already in progress, skipping.");
  68. return _existingSync!.future;
  69. }
  70. _existingSync = Completer<void>();
  71. final existingLocalFileIDs = await _db.getExistingLocalFileIDs();
  72. _logger.info(
  73. existingLocalFileIDs.length.toString() + " localIDs were discovered",
  74. );
  75. final editedFileIDs = _getEditedFileIDs().toSet();
  76. final downloadedFileIDs = _getDownloadedFileIDs().toSet();
  77. final syncStartTime = DateTime.now().microsecondsSinceEpoch;
  78. final lastDBUpdationTime = _prefs.getInt(kDbUpdationTimeKey) ?? 0;
  79. final startTime = DateTime.now().microsecondsSinceEpoch;
  80. if (lastDBUpdationTime != 0) {
  81. await _loadAndStorePhotos(
  82. lastDBUpdationTime,
  83. syncStartTime,
  84. existingLocalFileIDs,
  85. editedFileIDs,
  86. downloadedFileIDs,
  87. );
  88. } else {
  89. // Load from 0 - 01.01.2010
  90. Bus.instance.fire(SyncStatusUpdate(SyncStatus.startedFirstGalleryImport));
  91. var startTime = 0;
  92. var toYear = 2010;
  93. var toTime = DateTime(toYear).microsecondsSinceEpoch;
  94. while (toTime < syncStartTime) {
  95. await _loadAndStorePhotos(
  96. startTime,
  97. toTime,
  98. existingLocalFileIDs,
  99. editedFileIDs,
  100. downloadedFileIDs,
  101. );
  102. startTime = toTime;
  103. toYear++;
  104. toTime = DateTime(toYear).microsecondsSinceEpoch;
  105. }
  106. await _loadAndStorePhotos(
  107. startTime,
  108. syncStartTime,
  109. existingLocalFileIDs,
  110. editedFileIDs,
  111. downloadedFileIDs,
  112. );
  113. }
  114. if (!_prefs.containsKey(kHasCompletedFirstImportKey) ||
  115. !(_prefs.getBool(kHasCompletedFirstImportKey)!)) {
  116. await _prefs.setBool(kHasCompletedFirstImportKey, true);
  117. // mark device collection has imported on first import
  118. await _refreshDeviceFolderCountAndCover(isFirstSync: true);
  119. await _prefs.setBool(hasImportedDeviceCollections, true);
  120. _logger.fine("first gallery import finished");
  121. Bus.instance
  122. .fire(SyncStatusUpdate(SyncStatus.completedFirstGalleryImport));
  123. }
  124. final endTime = DateTime.now().microsecondsSinceEpoch;
  125. final duration = Duration(microseconds: endTime - startTime);
  126. _logger.info("Load took " + duration.inMilliseconds.toString() + "ms");
  127. _existingSync?.complete();
  128. _existingSync = null;
  129. }
  130. Future<bool> _refreshDeviceFolderCountAndCover({
  131. bool isFirstSync = false,
  132. }) async {
  133. final List<Tuple2<AssetPathEntity, String>> result =
  134. await getDeviceFolderWithCountAndCoverID();
  135. final bool hasUpdated = await _db.updateDeviceCoverWithCount(
  136. result,
  137. shouldBackup: Configuration.instance.hasSelectedAllFoldersForBackup(),
  138. );
  139. // do not fire UI update event during first sync. Otherwise the next screen
  140. // to shop the backup folder is skipped
  141. if (hasUpdated && !isFirstSync) {
  142. Bus.instance.fire(BackupFoldersUpdatedEvent());
  143. }
  144. // migrate the backed up folder settings after first import is done remove
  145. // after 6 months?
  146. if (!_prefs.containsKey(hasImportedDeviceCollections) &&
  147. _prefs.containsKey(kHasCompletedFirstImportKey)) {
  148. await _migrateOldSettings(result);
  149. }
  150. return hasUpdated;
  151. }
  152. Future<void> _migrateOldSettings(
  153. List<Tuple2<AssetPathEntity, String>> result,
  154. ) async {
  155. final pathsToBackUp = Configuration.instance.getPathsToBackUp();
  156. final entriesToBackUp = Map.fromEntries(
  157. result
  158. .where((element) => pathsToBackUp.contains(element.item1.name))
  159. .map((e) => MapEntry(e.item1.id, true)),
  160. );
  161. if (entriesToBackUp.isNotEmpty) {
  162. await _db.updateDevicePathSyncStatus(entriesToBackUp);
  163. Bus.instance.fire(BackupFoldersUpdatedEvent());
  164. }
  165. await Configuration.instance
  166. .setHasSelectedAnyBackupFolder(pathsToBackUp.isNotEmpty);
  167. await _prefs.setBool(hasImportedDeviceCollections, true);
  168. }
  169. bool isDeviceFileMigrationDone() {
  170. return _prefs.containsKey(hasImportedDeviceCollections);
  171. }
  172. Future<bool> syncAll() async {
  173. final stopwatch = EnteWatch("localSyncAll")..start();
  174. final localAssets = await getAllLocalAssets();
  175. _logger.info(
  176. "Loading allLocalAssets ${localAssets.length} took ${stopwatch.elapsedMilliseconds}ms ",
  177. );
  178. await _refreshDeviceFolderCountAndCover();
  179. _logger.info(
  180. "refreshDeviceFolderCountAndCover + allLocalAssets took ${stopwatch.elapsedMilliseconds}ms ",
  181. );
  182. final existingLocalFileIDs = await _db.getExistingLocalFileIDs();
  183. final Map<String, Set<String>> pathToLocalIDs =
  184. await _db.getDevicePathIDToLocalIDMap();
  185. final invalidIDs = _getInvalidFileIDs().toSet();
  186. final localDiffResult = await getDiffWithLocal(
  187. localAssets,
  188. existingLocalFileIDs,
  189. pathToLocalIDs,
  190. invalidIDs,
  191. _computer,
  192. );
  193. bool hasAnyMappingChanged = false;
  194. if (localDiffResult.newPathToLocalIDs?.isNotEmpty ?? false) {
  195. await _db
  196. .insertPathIDToLocalIDMapping(localDiffResult.newPathToLocalIDs!);
  197. hasAnyMappingChanged = true;
  198. }
  199. if (localDiffResult.deletePathToLocalIDs?.isNotEmpty ?? false) {
  200. await _db
  201. .deletePathIDToLocalIDMapping(localDiffResult.deletePathToLocalIDs!);
  202. hasAnyMappingChanged = true;
  203. }
  204. final bool hasUnsyncedFiles =
  205. localDiffResult.uniqueLocalFiles?.isNotEmpty ?? false;
  206. if (hasUnsyncedFiles) {
  207. await _db.insertMultiple(
  208. localDiffResult.uniqueLocalFiles!,
  209. conflictAlgorithm: ConflictAlgorithm.ignore,
  210. );
  211. _logger.info(
  212. "Inserted ${localDiffResult.uniqueLocalFiles?.length} "
  213. "un-synced files",
  214. );
  215. }
  216. debugPrint(
  217. "syncAll: mappingChange : $hasAnyMappingChanged, "
  218. "unSyncedFiles: $hasUnsyncedFiles",
  219. );
  220. if (hasAnyMappingChanged || hasUnsyncedFiles) {
  221. Bus.instance.fire(
  222. LocalPhotosUpdatedEvent(
  223. localDiffResult.uniqueLocalFiles,
  224. source: "syncAllChange",
  225. ),
  226. );
  227. }
  228. _logger.info("syncAll took ${stopwatch.elapsed.inMilliseconds}ms ");
  229. return hasUnsyncedFiles;
  230. }
  231. Future<void> trackEditedFile(File file) async {
  232. if (file.localID == null) {
  233. debugPrint("Warning: Edit file has no localID");
  234. return;
  235. }
  236. final editedIDs = _getEditedFileIDs();
  237. editedIDs.add(file.localID!);
  238. await _prefs.setStringList(kEditedFileIDsKey, editedIDs);
  239. }
  240. List<String> _getEditedFileIDs() {
  241. if (_prefs.containsKey(kEditedFileIDsKey)) {
  242. return _prefs.getStringList(kEditedFileIDsKey)!;
  243. } else {
  244. final List<String> editedIDs = [];
  245. return editedIDs;
  246. }
  247. }
  248. Future<void> trackDownloadedFile(String localID) async {
  249. final downloadedIDs = _getDownloadedFileIDs();
  250. downloadedIDs.add(localID);
  251. await _prefs.setStringList(kDownloadedFileIDsKey, downloadedIDs);
  252. }
  253. List<String> _getDownloadedFileIDs() {
  254. if (_prefs.containsKey(kDownloadedFileIDsKey)) {
  255. return _prefs.getStringList(kDownloadedFileIDsKey)!;
  256. } else {
  257. return <String>[];
  258. }
  259. }
  260. Future<void> trackInvalidFile(File file) async {
  261. if (file.localID == null) {
  262. debugPrint("Warning: Invalid file has no localID");
  263. return;
  264. }
  265. final invalidIDs = _getInvalidFileIDs();
  266. invalidIDs.add(file.localID!);
  267. await _prefs.setStringList(kInvalidFileIDsKey, invalidIDs);
  268. }
  269. List<String> _getInvalidFileIDs() {
  270. if (_prefs.containsKey(kInvalidFileIDsKey)) {
  271. return _prefs.getStringList(kInvalidFileIDsKey)!;
  272. } else {
  273. return <String>[];
  274. }
  275. }
  276. bool hasGrantedPermissions() {
  277. return _prefs.getBool(kHasGrantedPermissionsKey) ?? false;
  278. }
  279. bool hasGrantedLimitedPermissions() {
  280. return _prefs.getString(kPermissionStateKey) ==
  281. PermissionState.limited.toString();
  282. }
  283. Future<void> onPermissionGranted(PermissionState state) async {
  284. await _prefs.setBool(kHasGrantedPermissionsKey, true);
  285. await _prefs.setString(kPermissionStateKey, state.toString());
  286. if (state == PermissionState.limited) {
  287. // when limited permission is granted, by default mark all folders for
  288. // backup
  289. await Configuration.instance.setSelectAllFoldersForBackup(true);
  290. }
  291. _registerChangeCallback();
  292. }
  293. bool hasCompletedFirstImport() {
  294. return _prefs.getBool(kHasCompletedFirstImportKey) ?? false;
  295. }
  296. // Warning: resetLocalSync should only be used for testing imported related
  297. // changes
  298. Future<void> resetLocalSync() async {
  299. assert(kDebugMode, "only available in debug mode");
  300. await FilesDB.instance.deleteDB();
  301. for (var element in [
  302. kHasCompletedFirstImportKey,
  303. hasImportedDeviceCollections,
  304. kDbUpdationTimeKey,
  305. kDownloadedFileIDsKey,
  306. kEditedFileIDsKey,
  307. "has_synced_edit_time",
  308. "has_selected_all_folders_for_backup",
  309. ]) {
  310. await _prefs.remove(element);
  311. }
  312. }
  313. Future<void> _loadAndStorePhotos(
  314. int fromTime,
  315. int toTime,
  316. Set<String> existingLocalFileIDs,
  317. Set<String> editedFileIDs,
  318. Set<String> downloadedFileIDs,
  319. ) async {
  320. final Tuple2<List<LocalPathAsset>, List<File>> result =
  321. await getLocalPathAssetsAndFiles(fromTime, toTime, _computer);
  322. await FilesDB.instance.insertLocalAssets(
  323. result.item1,
  324. shouldAutoBackup: Configuration.instance.hasSelectedAllFoldersForBackup(),
  325. );
  326. final List<File> files = result.item2;
  327. _logger.info(
  328. "Loaded ${files.length} photos from " +
  329. DateTime.fromMicrosecondsSinceEpoch(fromTime).toString() +
  330. " to " +
  331. DateTime.fromMicrosecondsSinceEpoch(toTime).toString(),
  332. );
  333. if (files.isNotEmpty) {
  334. await _trackUpdatedFiles(
  335. files,
  336. existingLocalFileIDs,
  337. editedFileIDs,
  338. downloadedFileIDs,
  339. );
  340. final List<File> allFiles = [];
  341. allFiles.addAll(files);
  342. files.removeWhere((file) => existingLocalFileIDs.contains(file.localID));
  343. await _db.insertMultiple(
  344. files,
  345. conflictAlgorithm: ConflictAlgorithm.ignore,
  346. );
  347. _logger.info("Inserted " + files.length.toString() + " files.");
  348. Bus.instance.fire(
  349. LocalPhotosUpdatedEvent(allFiles, source: "loadedPhoto"),
  350. );
  351. }
  352. await _prefs.setInt(kDbUpdationTimeKey, toTime);
  353. }
  354. Future<void> _trackUpdatedFiles(
  355. List<File> files,
  356. Set<String> existingLocalFileIDs,
  357. Set<String> editedFileIDs,
  358. Set<String> downloadedFileIDs,
  359. ) async {
  360. final updatedFiles = files
  361. .where((file) => existingLocalFileIDs.contains(file.localID))
  362. .toList();
  363. updatedFiles.removeWhere((file) => editedFileIDs.contains(file.localID));
  364. updatedFiles
  365. .removeWhere((file) => downloadedFileIDs.contains(file.localID));
  366. if (updatedFiles.isNotEmpty) {
  367. _logger.info(
  368. updatedFiles.length.toString() + " local files were updated.",
  369. );
  370. final List<String> updatedLocalIDs = [];
  371. for (final file in updatedFiles) {
  372. if (file.localID != null) {
  373. updatedLocalIDs.add(file.localID!);
  374. }
  375. }
  376. await FileUpdationDB.instance.insertMultiple(
  377. updatedLocalIDs,
  378. FileUpdationDB.modificationTimeUpdated,
  379. );
  380. }
  381. }
  382. void _registerChangeCallback() {
  383. // In case of iOS limit permission, this call back is fired immediately
  384. // after file selection dialog is dismissed.
  385. PhotoManager.addChangeCallback((value) async {
  386. _logger.info("Something changed on disk");
  387. if (_existingSync != null) {
  388. await _existingSync!.future;
  389. }
  390. if (hasGrantedLimitedPermissions()) {
  391. syncAll();
  392. } else {
  393. sync().then((value) => _refreshDeviceFolderCountAndCover());
  394. }
  395. });
  396. PhotoManager.startChangeNotify();
  397. }
  398. }