local_sync_service.dart 13 KB

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