local_sync_service.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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:logging/logging.dart';
  7. import 'package:photo_manager/photo_manager.dart';
  8. import 'package:photos/core/configuration.dart';
  9. import 'package:photos/core/event_bus.dart';
  10. import 'package:photos/db/device_files_db.dart';
  11. import 'package:photos/db/file_updation_db.dart';
  12. import 'package:photos/db/files_db.dart';
  13. import 'package:photos/events/backup_folders_updated_event.dart';
  14. import 'package:photos/events/local_photos_updated_event.dart';
  15. import 'package:photos/events/sync_status_update_event.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. 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() async {
  42. _prefs = await SharedPreferences.getInstance();
  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();
  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() async {
  131. final List<Tuple2<AssetPathEntity, String>> result =
  132. await getDeviceFolderWithCountAndCoverID();
  133. final bool hasUpdated = await _db.updateDeviceCoverWithCount(
  134. result,
  135. shouldBackup: Configuration.instance.hasSelectedAllFoldersForBackup(),
  136. );
  137. if (hasUpdated) {
  138. Bus.instance.fire(BackupFoldersUpdatedEvent());
  139. }
  140. return hasUpdated;
  141. }
  142. Future<bool> syncAll() async {
  143. final stopwatch = Stopwatch()..start();
  144. final localAssets = await getAllLocalAssets();
  145. _logger.info(
  146. "Loading allLocalAssets ${localAssets.length} took ${stopwatch.elapsedMilliseconds}ms ",
  147. );
  148. await _refreshDeviceFolderCountAndCover();
  149. _logger.info(
  150. "refreshDeviceFolderCountAndCover + allLocalAssets took ${stopwatch.elapsedMilliseconds}ms ",
  151. );
  152. final existingLocalFileIDs = await _db.getExistingLocalFileIDs();
  153. final Map<String, Set<String>> pathToLocalIDs =
  154. await _db.getDevicePathIDToLocalIDMap();
  155. final invalidIDs = _getInvalidFileIDs().toSet();
  156. final localDiffResult = await getDiffWithLocal(
  157. localAssets,
  158. existingLocalFileIDs,
  159. pathToLocalIDs,
  160. invalidIDs,
  161. _computer,
  162. );
  163. bool hasAnyMappingChanged = false;
  164. if (localDiffResult.newPathToLocalIDs?.isNotEmpty ?? false) {
  165. await _db.insertPathIDToLocalIDMapping(localDiffResult.newPathToLocalIDs);
  166. hasAnyMappingChanged = true;
  167. }
  168. if (localDiffResult.deletePathToLocalIDs?.isNotEmpty ?? false) {
  169. await _db
  170. .deletePathIDToLocalIDMapping(localDiffResult.deletePathToLocalIDs);
  171. hasAnyMappingChanged = true;
  172. }
  173. final bool hasUnsyncedFiles =
  174. localDiffResult.uniqueLocalFiles?.isNotEmpty ?? false;
  175. if (hasUnsyncedFiles) {
  176. await _db.insertMultiple(
  177. localDiffResult.uniqueLocalFiles,
  178. conflictAlgorithm: ConflictAlgorithm.ignore,
  179. );
  180. _logger.info(
  181. "Inserted ${localDiffResult.uniqueLocalFiles.length} "
  182. "un-synced files",
  183. );
  184. }
  185. debugPrint(
  186. "syncAll: mappingChange : $hasAnyMappingChanged, "
  187. "unSyncedFiles: $hasUnsyncedFiles",
  188. );
  189. if (hasAnyMappingChanged || hasUnsyncedFiles) {
  190. Bus.instance.fire(
  191. LocalPhotosUpdatedEvent(localDiffResult.uniqueLocalFiles),
  192. );
  193. }
  194. _logger.info("syncAll took ${stopwatch.elapsed.inMilliseconds}ms ");
  195. return hasUnsyncedFiles;
  196. }
  197. Future<void> trackEditedFile(File file) async {
  198. final editedIDs = _getEditedFileIDs();
  199. editedIDs.add(file.localID);
  200. await _prefs.setStringList(kEditedFileIDsKey, editedIDs);
  201. }
  202. List<String> _getEditedFileIDs() {
  203. if (_prefs.containsKey(kEditedFileIDsKey)) {
  204. return _prefs.getStringList(kEditedFileIDsKey);
  205. } else {
  206. final List<String> editedIDs = [];
  207. return editedIDs;
  208. }
  209. }
  210. Future<void> trackDownloadedFile(String localID) async {
  211. final downloadedIDs = _getDownloadedFileIDs();
  212. downloadedIDs.add(localID);
  213. await _prefs.setStringList(kDownloadedFileIDsKey, downloadedIDs);
  214. }
  215. List<String> _getDownloadedFileIDs() {
  216. if (_prefs.containsKey(kDownloadedFileIDsKey)) {
  217. return _prefs.getStringList(kDownloadedFileIDsKey);
  218. } else {
  219. return <String>[];
  220. }
  221. }
  222. Future<void> trackInvalidFile(File file) async {
  223. final invalidIDs = _getInvalidFileIDs();
  224. invalidIDs.add(file.localID);
  225. await _prefs.setStringList(kInvalidFileIDsKey, invalidIDs);
  226. }
  227. List<String> _getInvalidFileIDs() {
  228. if (_prefs.containsKey(kInvalidFileIDsKey)) {
  229. return _prefs.getStringList(kInvalidFileIDsKey);
  230. } else {
  231. return <String>[];
  232. }
  233. }
  234. bool hasGrantedPermissions() {
  235. return _prefs.getBool(kHasGrantedPermissionsKey) ?? false;
  236. }
  237. bool hasGrantedLimitedPermissions() {
  238. return _prefs.getString(kPermissionStateKey) ==
  239. PermissionState.limited.toString();
  240. }
  241. Future<void> onPermissionGranted(PermissionState state) async {
  242. await _prefs.setBool(kHasGrantedPermissionsKey, true);
  243. await _prefs.setString(kPermissionStateKey, state.toString());
  244. _registerChangeCallback();
  245. }
  246. bool hasCompletedFirstImport() {
  247. return _prefs.getBool(kHasCompletedFirstImportKey) ?? false;
  248. }
  249. // Warning: resetLocalSync should only be used for testing imported related
  250. // changes
  251. Future<void> resetLocalSync() async {
  252. assert(kDebugMode, "only available in debug mode");
  253. await FilesDB.instance.deleteDB();
  254. for (var element in [
  255. kHasCompletedFirstImportKey,
  256. hasImportedDeviceCollections,
  257. kDbUpdationTimeKey,
  258. kDownloadedFileIDsKey,
  259. kEditedFileIDsKey
  260. ]) {
  261. await _prefs.remove(element);
  262. }
  263. }
  264. Future<void> _loadAndStorePhotos(
  265. int fromTime,
  266. int toTime,
  267. Set<String> existingLocalFileIDs,
  268. Set<String> editedFileIDs,
  269. Set<String> downloadedFileIDs,
  270. ) async {
  271. _logger.info(
  272. "Loading photos from " +
  273. DateTime.fromMicrosecondsSinceEpoch(fromTime).toString() +
  274. " to " +
  275. DateTime.fromMicrosecondsSinceEpoch(toTime).toString(),
  276. );
  277. final Tuple2<List<LocalPathAsset>, List<File>> result =
  278. await getLocalPathAssetsAndFiles(fromTime, toTime, _computer);
  279. await FilesDB.instance.insertLocalAssets(
  280. result.item1,
  281. shouldAutoBackup: Configuration.instance.hasSelectedAllFoldersForBackup(),
  282. );
  283. final List<File> files = result.item2;
  284. if (files.isNotEmpty) {
  285. _logger.info("Fetched " + files.length.toString() + " files.");
  286. await _trackUpdatedFiles(
  287. files,
  288. existingLocalFileIDs,
  289. editedFileIDs,
  290. downloadedFileIDs,
  291. );
  292. final List<File> allFiles = [];
  293. allFiles.addAll(files);
  294. files.removeWhere((file) => existingLocalFileIDs.contains(file.localID));
  295. await _db.insertMultiple(
  296. files,
  297. conflictAlgorithm: ConflictAlgorithm.ignore,
  298. );
  299. _logger.info("Inserted " + files.length.toString() + " files.");
  300. // _updatePathsToBackup(files);
  301. Bus.instance.fire(LocalPhotosUpdatedEvent(allFiles));
  302. }
  303. await _prefs.setInt(kDbUpdationTimeKey, toTime);
  304. }
  305. Future<void> _trackUpdatedFiles(
  306. List<File> files,
  307. Set<String> existingLocalFileIDs,
  308. Set<String> editedFileIDs,
  309. Set<String> downloadedFileIDs,
  310. ) async {
  311. final updatedFiles = files
  312. .where((file) => existingLocalFileIDs.contains(file.localID))
  313. .toList();
  314. updatedFiles.removeWhere((file) => editedFileIDs.contains(file.localID));
  315. updatedFiles
  316. .removeWhere((file) => downloadedFileIDs.contains(file.localID));
  317. if (updatedFiles.isNotEmpty) {
  318. _logger.info(
  319. updatedFiles.length.toString() + " local files were updated.",
  320. );
  321. final List<String> updatedLocalIDs = [];
  322. for (final file in updatedFiles) {
  323. updatedLocalIDs.add(file.localID);
  324. }
  325. await FileUpdationDB.instance.insertMultiple(
  326. updatedLocalIDs,
  327. FileUpdationDB.modificationTimeUpdated,
  328. );
  329. }
  330. }
  331. void _registerChangeCallback() {
  332. // In case of iOS limit permission, this call back is fired immediately
  333. // after file selection dialog is dismissed.
  334. PhotoManager.addChangeCallback((value) async {
  335. _logger.info("Something changed on disk");
  336. if (_existingSync != null) {
  337. await _existingSync.future;
  338. }
  339. if (hasGrantedLimitedPermissions()) {
  340. syncAll();
  341. } else {
  342. sync();
  343. }
  344. });
  345. PhotoManager.startChangeNotify();
  346. }
  347. }