local_sync_service.dart 13 KB

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