local_file_update_service.dart 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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:photos/core/configuration.dart';
  8. import 'package:photos/core/constants.dart';
  9. import 'package:photos/db/file_updation_db.dart';
  10. import 'package:photos/db/files_db.dart';
  11. import 'package:photos/extensions/stop_watch.dart';
  12. import 'package:photos/models/file.dart' as ente;
  13. import 'package:photos/services/files_service.dart';
  14. import 'package:photos/utils/file_uploader_util.dart';
  15. import 'package:photos/utils/file_util.dart';
  16. import 'package:shared_preferences/shared_preferences.dart';
  17. // LocalFileUpdateService tracks all the potential local file IDs which have
  18. // changed/modified on the device and needed to be uploaded again.
  19. class LocalFileUpdateService {
  20. FileUpdationDB _fileUpdationDB;
  21. SharedPreferences _prefs;
  22. Logger _logger;
  23. static const isLocationMigrationComplete = "fm_isLocationMigrationComplete";
  24. static const isLocalImportDone = "fm_IsLocalImportDone";
  25. static const isBadCreationTimeImportDone = 'fm_badCreationTime';
  26. static const isBadCreationTimeMigrationComplete =
  27. 'fm_badCreationTimeCompleted';
  28. Completer<void> _existingMigration;
  29. LocalFileUpdateService._privateConstructor() {
  30. _logger = Logger((LocalFileUpdateService).toString());
  31. _fileUpdationDB = FileUpdationDB.instance;
  32. }
  33. void init(SharedPreferences preferences) {
  34. _prefs = preferences;
  35. }
  36. static LocalFileUpdateService instance =
  37. LocalFileUpdateService._privateConstructor();
  38. bool isBadCreationMigrationCompleted() {
  39. return _prefs.get(isBadCreationTimeMigrationComplete) ?? false;
  40. }
  41. Future<void> markUpdatedFilesForReUpload() async {
  42. if (_existingMigration != null) {
  43. _logger.info("migration is already in progress, skipping");
  44. return _existingMigration.future;
  45. }
  46. _existingMigration = Completer<void>();
  47. try {
  48. await _markFilesWhichAreActuallyUpdated();
  49. if (Platform.isAndroid) {
  50. await _migrationForFixingBadCreationTime();
  51. }
  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. // singleRunLimit indicates number of files to check during single
  66. // invocation of this method. The limit act as a crude way to limit the
  67. // resource consumed by the method
  68. const int singleRunLimit = 10;
  69. final localIDsToProcess =
  70. await _fileUpdationDB.getLocalIDsForPotentialReUpload(
  71. singleRunLimit,
  72. FileUpdationDB.modificationTimeUpdated,
  73. );
  74. if (localIDsToProcess.isNotEmpty) {
  75. await _checkAndMarkFilesWithDifferentHashForFileUpdate(
  76. localIDsToProcess,
  77. );
  78. final eTime = DateTime.now().microsecondsSinceEpoch;
  79. final d = Duration(microseconds: eTime - sTime);
  80. _logger.info(
  81. 'Performed hashCheck for ${localIDsToProcess.length} updated files '
  82. 'completed in ${d.inSeconds.toString()} secs',
  83. );
  84. }
  85. }
  86. Future<void> _checkAndMarkFilesWithDifferentHashForFileUpdate(
  87. List<String> localIDsToProcess,
  88. ) async {
  89. _logger.info("files to process ${localIDsToProcess.length} for reupload");
  90. final List<ente.File> localFiles =
  91. await FilesDB.instance.getLocalFiles(localIDsToProcess);
  92. final Set<String> processedIDs = {};
  93. for (ente.File file in localFiles) {
  94. if (processedIDs.contains(file.localID)) {
  95. continue;
  96. }
  97. MediaUploadData uploadData;
  98. try {
  99. uploadData = await getUploadData(file);
  100. if (uploadData != null &&
  101. uploadData.hashData != null &&
  102. file.hash != null &&
  103. (file.hash == uploadData.hashData.fileHash ||
  104. file.hash == uploadData.hashData.zipHash)) {
  105. _logger.info("Skip file update as hash matched ${file.tag}");
  106. } else {
  107. _logger.info(
  108. "Marking for file update as hash did not match ${file.tag}",
  109. );
  110. await clearCache(file);
  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> _migrationForFixingBadCreationTime() async {
  144. if (_prefs.containsKey(isBadCreationTimeMigrationComplete)) {
  145. return;
  146. }
  147. await _importFilesWithBadCreationTime();
  148. const int singleRunLimit = 100;
  149. try {
  150. final generatedIDs =
  151. await _fileUpdationDB.getLocalIDsForPotentialReUpload(
  152. singleRunLimit,
  153. FileUpdationDB.badCreationTime,
  154. );
  155. if (generatedIDs.isNotEmpty) {
  156. final List<int> genIdIntList =
  157. generatedIDs.map((e) => int.tryParse(e)).toList();
  158. final filesWithBadTime =
  159. await FilesDB.instance.getFilesFromGeneratedIDs(genIdIntList);
  160. await FilesService.instance.bulkEditTime(
  161. filesWithBadTime.values.toList(), EditTimeSource.fileName);
  162. } else {
  163. // everything is done
  164. await _prefs.setBool(isBadCreationTimeMigrationComplete, true);
  165. }
  166. await _fileUpdationDB.deleteByLocalIDs(
  167. generatedIDs,
  168. FileUpdationDB.badCreationTime,
  169. );
  170. } catch (e) {
  171. _logger.severe("Failed to fix bad creationTime", e);
  172. }
  173. }
  174. Future<void> _importFilesWithBadCreationTime() async {
  175. if (_prefs.containsKey(isBadCreationTimeImportDone) ||
  176. !Platform.isAndroid) {
  177. return;
  178. }
  179. _logger.info('_importFilesWithBadCreationTime');
  180. final EnteWatch watch = EnteWatch("_importFilesWithBadCreationTime");
  181. final int ownerID = Configuration.instance.getUserID();
  182. final filesGeneratedID = await FilesDB.instance
  183. .getGeneratedIDForFilesOlderThan(jan011981Time, ownerID);
  184. await _fileUpdationDB.insertMultiple(
  185. filesGeneratedID,
  186. FileUpdationDB.badCreationTime,
  187. );
  188. watch.log("imported ${filesGeneratedID.length} files");
  189. _prefs.setBool(isBadCreationTimeImportDone, true);
  190. }
  191. }