local_sync_service.dart 12 KB

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