local_sync_service.dart 13 KB

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