local_sync_service.dart 12 KB

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