ente/lib/services/local_file_update_service.dart

243 lines
8.4 KiB
Dart
Raw Normal View History

// @dart=2.9
2022-06-08 08:49:23 +00:00
import 'dart:async';
import 'dart:core';
import 'dart:io';
import 'package:flutter/foundation.dart';
2022-06-08 08:49:23 +00:00
import 'package:logging/logging.dart';
import 'package:photo_manager/photo_manager.dart';
2022-08-29 04:30:28 +00:00
import 'package:photos/db/file_updation_db.dart';
2022-06-08 08:49:23 +00:00
import 'package:photos/db/files_db.dart';
2022-08-29 17:43:17 +00:00
import 'package:photos/models/file.dart' as ente;
import 'package:photos/utils/file_uploader_util.dart';
2022-06-08 08:49:23 +00:00
import 'package:shared_preferences/shared_preferences.dart';
2022-07-29 06:06:03 +00:00
// LocalFileUpdateService tracks all the potential local file IDs which have
// changed/modified on the device and needed to be uploaded again.
2022-08-01 11:05:16 +00:00
class LocalFileUpdateService {
2022-06-08 08:49:23 +00:00
FilesDB _filesDB;
2022-08-29 04:30:28 +00:00
FileUpdationDB _fileUpdationDB;
2022-06-08 09:30:21 +00:00
SharedPreferences _prefs;
2022-06-08 08:49:23 +00:00
Logger _logger;
static const isLocationMigrationComplete = "fm_isLocationMigrationComplete";
static const isLocalImportDone = "fm_IsLocalImportDone";
Completer<void> _existingMigration;
2022-08-01 11:05:16 +00:00
LocalFileUpdateService._privateConstructor() {
_logger = Logger((LocalFileUpdateService).toString());
2022-06-08 08:49:23 +00:00
_filesDB = FilesDB.instance;
2022-08-29 04:30:28 +00:00
_fileUpdationDB = FileUpdationDB.instance;
2022-06-08 09:30:21 +00:00
}
Future<void> init() async {
_prefs = await SharedPreferences.getInstance();
2022-06-08 08:49:23 +00:00
}
2022-08-01 11:05:16 +00:00
static LocalFileUpdateService instance =
LocalFileUpdateService._privateConstructor();
2022-06-08 08:49:23 +00:00
Future<bool> _markLocationMigrationAsCompleted() async {
_logger.info('marking migration as completed');
2022-06-08 09:30:21 +00:00
return _prefs.setBool(isLocationMigrationComplete, true);
2022-06-08 08:49:23 +00:00
}
2022-06-08 09:30:21 +00:00
bool isLocationMigrationCompleted() {
return _prefs.get(isLocationMigrationComplete) ?? false;
2022-06-08 08:49:23 +00:00
}
2022-08-01 11:05:16 +00:00
Future<void> markUpdatedFilesForReUpload() async {
2022-06-08 08:49:23 +00:00
if (_existingMigration != null) {
_logger.info("migration is already in progress, skipping");
2022-06-08 08:49:23 +00:00
return _existingMigration.future;
}
_existingMigration = Completer<void>();
try {
2022-07-29 06:06:03 +00:00
if (!isLocationMigrationCompleted() && Platform.isAndroid) {
_logger.info("start migration for missing location");
await _runMigrationForFilesWithMissingLocation();
}
await _markFilesWhichAreActuallyUpdated();
2022-06-08 08:49:23 +00:00
} catch (e, s) {
_logger.severe('failed to perform migration', e, s);
2022-08-29 17:43:17 +00:00
} finally {
_existingMigration?.complete();
2022-06-08 08:49:23 +00:00
_existingMigration = null;
}
}
// This method analyses all of local files for which the file
// modification/update time was changed. It checks if the existing fileHash
// is different from the hash of uploaded file. If fileHash are different,
// then it marks the file for file update.
Future<void> _markFilesWhichAreActuallyUpdated() async {
final sTime = DateTime.now().microsecondsSinceEpoch;
bool hasData = true;
const int limitInBatch = 100;
while (hasData) {
final localIDsToProcess =
2022-08-29 04:30:28 +00:00
await _fileUpdationDB.getLocalIDsForPotentialReUpload(
limitInBatch,
2022-08-29 04:30:28 +00:00
FileUpdationDB.modificationTimeUpdated,
);
if (localIDsToProcess.isEmpty) {
hasData = false;
} else {
await _checkAndMarkFilesWithDifferentHashForFileUpdate(
localIDsToProcess,
);
}
}
final eTime = DateTime.now().microsecondsSinceEpoch;
final d = Duration(microseconds: eTime - sTime);
_logger.info(
'_markFilesWhichAreActuallyUpdated migration completed in ${d.inSeconds.toString()} seconds',
);
}
Future<void> _checkAndMarkFilesWithDifferentHashForFileUpdate(
List<String> localIDsToProcess,
) async {
_logger.info("files to process ${localIDsToProcess.length} for reupload");
2022-08-29 18:05:13 +00:00
final List<ente.File> localFiles =
await FilesDB.instance.getLocalFiles(localIDsToProcess);
final Set<String> processedIDs = {};
2022-08-29 17:43:17 +00:00
for (ente.File file in localFiles) {
if (processedIDs.contains(file.localID)) {
continue;
}
MediaUploadData uploadData;
try {
2022-08-29 17:43:17 +00:00
uploadData = await getUploadData(file);
if (uploadData != null &&
uploadData.hashData != null &&
2022-08-29 07:58:49 +00:00
file.hash != null &&
(file.hash == uploadData.hashData.fileHash ||
file.hash == uploadData.hashData.zipHash)) {
_logger.info("Skip file update as hash matched ${file.tag()}");
} else {
_logger.info(
"Marking for file update as hash did not match ${file.tag()}",
);
await FilesDB.instance.updateUploadedFile(
file.localID,
file.title,
file.location,
file.creationTime,
file.modificationTime,
null,
);
}
processedIDs.add(file.localID);
} catch (e) {
_logger.severe("Failed to get file uploadData", e);
2022-08-29 17:43:17 +00:00
} finally {}
}
debugPrint("Deleting files ${processedIDs.length}");
2022-08-29 04:30:28 +00:00
await _fileUpdationDB.deleteByLocalIDs(
processedIDs.toList(),
2022-08-29 04:30:28 +00:00
FileUpdationDB.modificationTimeUpdated,
);
}
2022-08-29 17:43:17 +00:00
Future<MediaUploadData> getUploadData(ente.File file) async {
final mediaUploadData = await getUploadDataFromEnteFile(file);
// delete the file from app's internal cache if it was copied to app
// for upload. Shared Media should only be cleared when the upload
// succeeds.
if (Platform.isIOS &&
mediaUploadData != null &&
mediaUploadData.sourceFile != null) {
await mediaUploadData.sourceFile.delete();
}
return mediaUploadData;
}
2022-06-08 09:20:03 +00:00
Future<void> _runMigrationForFilesWithMissingLocation() async {
if (!Platform.isAndroid) {
return;
}
// migration only needs to run if Android API Level is 29 or higher
final int version = int.parse(await PhotoManager.systemVersion());
final bool isMigrationRequired = version >= 29;
if (isMigrationRequired) {
await _importLocalFilesForMigration();
final sTime = DateTime.now().microsecondsSinceEpoch;
2022-06-08 14:17:19 +00:00
bool hasData = true;
2022-07-04 06:02:17 +00:00
const int limitInBatch = 100;
while (hasData) {
final localIDsToProcess =
2022-08-29 04:30:28 +00:00
await _fileUpdationDB.getLocalIDsForPotentialReUpload(
2022-08-01 11:05:16 +00:00
limitInBatch,
2022-08-29 04:30:28 +00:00
FileUpdationDB.missingLocation,
2022-08-01 11:05:16 +00:00
);
if (localIDsToProcess.isEmpty) {
hasData = false;
} else {
await _checkAndMarkFilesWithLocationForReUpload(localIDsToProcess);
}
2022-06-08 09:20:03 +00:00
}
final eTime = DateTime.now().microsecondsSinceEpoch;
final d = Duration(microseconds: eTime - sTime);
_logger.info(
2022-06-11 08:23:52 +00:00
'filesWithMissingLocation migration completed in ${d.inSeconds.toString()} seconds',
);
2022-06-08 09:20:03 +00:00
}
await _markLocationMigrationAsCompleted();
}
Future<void> _checkAndMarkFilesWithLocationForReUpload(
2022-06-11 08:23:52 +00:00
List<String> localIDsToProcess,
) async {
_logger.info("files to process ${localIDsToProcess.length}");
final localIDsWithLocation = <String>[];
2022-06-08 08:49:23 +00:00
for (var localID in localIDsToProcess) {
bool hasLocation = false;
try {
final assetEntity = await AssetEntity.fromId(localID);
2022-06-08 08:49:23 +00:00
if (assetEntity == null) {
continue;
}
final latLng = await assetEntity.latlngAsync();
2022-06-08 09:20:03 +00:00
if ((latLng.longitude ?? 0.0) != 0.0 ||
(latLng.longitude ?? 0.0) != 0.0) {
2022-06-08 08:49:23 +00:00
_logger.finest(
2022-06-11 08:23:52 +00:00
'found lat/long ${latLng.longitude}/${latLng.longitude} for ${assetEntity.title} ${assetEntity.relativePath} with id : $localID',
);
2022-06-08 08:49:23 +00:00
hasLocation = true;
}
} catch (e, s) {
_logger.severe('failed to get asset entity with id $localID', e, s);
}
if (hasLocation) {
localIDsWithLocation.add(localID);
}
}
_logger.info('marking ${localIDsWithLocation.length} files for re-upload');
2022-06-08 10:29:29 +00:00
await _filesDB.markForReUploadIfLocationMissing(localIDsWithLocation);
2022-08-29 04:30:28 +00:00
await _fileUpdationDB.deleteByLocalIDs(
localIDsToProcess,
2022-08-29 04:30:28 +00:00
FileUpdationDB.missingLocation,
);
2022-06-08 08:49:23 +00:00
}
Future<void> _importLocalFilesForMigration() async {
2022-06-08 09:30:21 +00:00
if (_prefs.containsKey(isLocalImportDone)) {
2022-06-08 08:49:23 +00:00
return;
}
2022-06-08 09:20:03 +00:00
final sTime = DateTime.now().microsecondsSinceEpoch;
2022-06-08 08:49:23 +00:00
_logger.info('importing files without location info');
final fileLocalIDs = await _filesDB.getLocalFilesBackedUpWithoutLocation();
2022-08-29 04:30:28 +00:00
await _fileUpdationDB.insertMultiple(
2022-08-01 11:05:16 +00:00
fileLocalIDs,
2022-08-29 04:30:28 +00:00
FileUpdationDB.missingLocation,
2022-08-01 11:05:16 +00:00
);
2022-06-08 09:20:03 +00:00
final eTime = DateTime.now().microsecondsSinceEpoch;
final d = Duration(microseconds: eTime - sTime);
_logger.info(
2022-06-11 08:23:52 +00:00
'importing completed, total files count ${fileLocalIDs.length} and took ${d.inSeconds.toString()} seconds',
);
2022-08-01 11:05:16 +00:00
await _prefs.setBool(isLocalImportDone, true);
2022-06-08 08:49:23 +00:00
}
}