local_file_update_service.dart 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // @dart=2.9
  2. import 'dart:async';
  3. import 'dart:core';
  4. import 'dart:io';
  5. import 'package:flutter/foundation.dart';
  6. import 'package:logging/logging.dart';
  7. import 'package:photo_manager/photo_manager.dart';
  8. import 'package:photos/db/file_updation_db.dart';
  9. import 'package:photos/db/files_db.dart';
  10. import 'package:photos/models/file.dart' as ente;
  11. import 'package:photos/utils/file_uploader_util.dart';
  12. import 'package:shared_preferences/shared_preferences.dart';
  13. // LocalFileUpdateService tracks all the potential local file IDs which have
  14. // changed/modified on the device and needed to be uploaded again.
  15. class LocalFileUpdateService {
  16. FilesDB _filesDB;
  17. FileUpdationDB _fileUpdationDB;
  18. SharedPreferences _prefs;
  19. Logger _logger;
  20. static const isLocationMigrationComplete = "fm_isLocationMigrationComplete";
  21. static const isLocalImportDone = "fm_IsLocalImportDone";
  22. Completer<void> _existingMigration;
  23. LocalFileUpdateService._privateConstructor() {
  24. _logger = Logger((LocalFileUpdateService).toString());
  25. _filesDB = FilesDB.instance;
  26. _fileUpdationDB = FileUpdationDB.instance;
  27. }
  28. Future<void> init() async {
  29. _prefs = await SharedPreferences.getInstance();
  30. }
  31. static LocalFileUpdateService instance =
  32. LocalFileUpdateService._privateConstructor();
  33. Future<bool> _markLocationMigrationAsCompleted() async {
  34. _logger.info('marking migration as completed');
  35. return _prefs.setBool(isLocationMigrationComplete, true);
  36. }
  37. bool isLocationMigrationCompleted() {
  38. return _prefs.get(isLocationMigrationComplete) ?? false;
  39. }
  40. Future<void> markUpdatedFilesForReUpload() async {
  41. if (_existingMigration != null) {
  42. _logger.info("migration is already in progress, skipping");
  43. return _existingMigration.future;
  44. }
  45. _existingMigration = Completer<void>();
  46. try {
  47. if (!isLocationMigrationCompleted() && Platform.isAndroid) {
  48. _logger.info("start migration for missing location");
  49. await _runMigrationForFilesWithMissingLocation();
  50. }
  51. await _markFilesWhichAreActuallyUpdated();
  52. } catch (e, s) {
  53. _logger.severe('failed to perform migration', e, s);
  54. } finally {
  55. _existingMigration?.complete();
  56. _existingMigration = null;
  57. }
  58. }
  59. // This method analyses all of local files for which the file
  60. // modification/update time was changed. It checks if the existing fileHash
  61. // is different from the hash of uploaded file. If fileHash are different,
  62. // then it marks the file for file update.
  63. Future<void> _markFilesWhichAreActuallyUpdated() async {
  64. final sTime = DateTime.now().microsecondsSinceEpoch;
  65. bool hasData = true;
  66. const int limitInBatch = 100;
  67. while (hasData) {
  68. final localIDsToProcess =
  69. await _fileUpdationDB.getLocalIDsForPotentialReUpload(
  70. limitInBatch,
  71. FileUpdationDB.modificationTimeUpdated,
  72. );
  73. if (localIDsToProcess.isEmpty) {
  74. hasData = false;
  75. } else {
  76. await _checkAndMarkFilesWithDifferentHashForFileUpdate(
  77. localIDsToProcess,
  78. );
  79. }
  80. }
  81. final eTime = DateTime.now().microsecondsSinceEpoch;
  82. final d = Duration(microseconds: eTime - sTime);
  83. _logger.info(
  84. '_markFilesWhichAreActuallyUpdated migration completed in ${d.inSeconds.toString()} seconds',
  85. );
  86. }
  87. Future<void> _checkAndMarkFilesWithDifferentHashForFileUpdate(
  88. List<String> localIDsToProcess,
  89. ) async {
  90. _logger.info("files to process ${localIDsToProcess.length} for reupload");
  91. List<ente.File> localFiles =
  92. (await FilesDB.instance.getLocalFiles(localIDsToProcess));
  93. Set<String> processedIDs = {};
  94. for (ente.File file in localFiles) {
  95. if (processedIDs.contains(file.localID)) {
  96. continue;
  97. }
  98. MediaUploadData uploadData;
  99. try {
  100. uploadData = await getUploadData(file);
  101. if (uploadData != null &&
  102. uploadData.hashData != null &&
  103. file.hash != null &&
  104. (file.hash == uploadData.hashData.fileHash ||
  105. file.hash == uploadData.hashData.zipHash)) {
  106. _logger.info("Skip file update as hash matched ${file.tag()}");
  107. } else {
  108. _logger.info(
  109. "Marking for file update as hash did not match ${file.tag()}",
  110. );
  111. await FilesDB.instance.updateUploadedFile(
  112. file.localID,
  113. file.title,
  114. file.location,
  115. file.creationTime,
  116. file.modificationTime,
  117. null,
  118. );
  119. }
  120. processedIDs.add(file.localID);
  121. } catch (e) {
  122. _logger.severe("Failed to get file uploadData", e);
  123. } finally {}
  124. }
  125. debugPrint("Deleting files ${processedIDs.length}");
  126. await _fileUpdationDB.deleteByLocalIDs(
  127. processedIDs.toList(),
  128. FileUpdationDB.modificationTimeUpdated,
  129. );
  130. }
  131. Future<MediaUploadData> getUploadData(ente.File file) async {
  132. final mediaUploadData = await getUploadDataFromEnteFile(file);
  133. // delete the file from app's internal cache if it was copied to app
  134. // for upload. Shared Media should only be cleared when the upload
  135. // succeeds.
  136. if (Platform.isIOS &&
  137. mediaUploadData != null &&
  138. mediaUploadData.sourceFile != null) {
  139. await mediaUploadData.sourceFile.delete();
  140. }
  141. return mediaUploadData;
  142. }
  143. Future<void> _runMigrationForFilesWithMissingLocation() async {
  144. if (!Platform.isAndroid) {
  145. return;
  146. }
  147. // migration only needs to run if Android API Level is 29 or higher
  148. final int version = int.parse(await PhotoManager.systemVersion());
  149. bool isMigrationRequired = version >= 29;
  150. if (isMigrationRequired) {
  151. await _importLocalFilesForMigration();
  152. final sTime = DateTime.now().microsecondsSinceEpoch;
  153. bool hasData = true;
  154. const int limitInBatch = 100;
  155. while (hasData) {
  156. var localIDsToProcess =
  157. await _fileUpdationDB.getLocalIDsForPotentialReUpload(
  158. limitInBatch,
  159. FileUpdationDB.missingLocation,
  160. );
  161. if (localIDsToProcess.isEmpty) {
  162. hasData = false;
  163. } else {
  164. await _checkAndMarkFilesWithLocationForReUpload(localIDsToProcess);
  165. }
  166. }
  167. final eTime = DateTime.now().microsecondsSinceEpoch;
  168. final d = Duration(microseconds: eTime - sTime);
  169. _logger.info(
  170. 'filesWithMissingLocation migration completed in ${d.inSeconds.toString()} seconds',
  171. );
  172. }
  173. await _markLocationMigrationAsCompleted();
  174. }
  175. Future<void> _checkAndMarkFilesWithLocationForReUpload(
  176. List<String> localIDsToProcess,
  177. ) async {
  178. _logger.info("files to process ${localIDsToProcess.length}");
  179. var localIDsWithLocation = <String>[];
  180. for (var localID in localIDsToProcess) {
  181. bool hasLocation = false;
  182. try {
  183. var assetEntity = await AssetEntity.fromId(localID);
  184. if (assetEntity == null) {
  185. continue;
  186. }
  187. var latLng = await assetEntity.latlngAsync();
  188. if ((latLng.longitude ?? 0.0) != 0.0 ||
  189. (latLng.longitude ?? 0.0) != 0.0) {
  190. _logger.finest(
  191. 'found lat/long ${latLng.longitude}/${latLng.longitude} for ${assetEntity.title} ${assetEntity.relativePath} with id : $localID',
  192. );
  193. hasLocation = true;
  194. }
  195. } catch (e, s) {
  196. _logger.severe('failed to get asset entity with id $localID', e, s);
  197. }
  198. if (hasLocation) {
  199. localIDsWithLocation.add(localID);
  200. }
  201. }
  202. _logger.info('marking ${localIDsWithLocation.length} files for re-upload');
  203. await _filesDB.markForReUploadIfLocationMissing(localIDsWithLocation);
  204. await _fileUpdationDB.deleteByLocalIDs(
  205. localIDsToProcess,
  206. FileUpdationDB.missingLocation,
  207. );
  208. }
  209. Future<void> _importLocalFilesForMigration() async {
  210. if (_prefs.containsKey(isLocalImportDone)) {
  211. return;
  212. }
  213. final sTime = DateTime.now().microsecondsSinceEpoch;
  214. _logger.info('importing files without location info');
  215. var fileLocalIDs = await _filesDB.getLocalFilesBackedUpWithoutLocation();
  216. await _fileUpdationDB.insertMultiple(
  217. fileLocalIDs,
  218. FileUpdationDB.missingLocation,
  219. );
  220. final eTime = DateTime.now().microsecondsSinceEpoch;
  221. final d = Duration(microseconds: eTime - sTime);
  222. _logger.info(
  223. 'importing completed, total files count ${fileLocalIDs.length} and took ${d.inSeconds.toString()} seconds',
  224. );
  225. await _prefs.setBool(isLocalImportDone, true);
  226. }
  227. }