local_sync_service.dart 14 KB

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