π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mobile] Delegate existing upload resolution
Neeraj Gupta686eff8ac7c7
diff --git a/mobile/apps/photos/lib/module/upload/service/existing_upload_resolver.dart b/mobile/apps/photos/lib/module/upload/service/existing_upload_resolver.dartindex a28b8670cf..103749933b 100644--- a/mobile/apps/photos/lib/module/upload/service/existing_upload_resolver.dart+++ b/mobile/apps/photos/lib/module/upload/service/existing_upload_resolver.dart@@ -1,5 +1,6 @@import "package:collection/collection.dart";import "package:logging/logging.dart";+import "package:photos/core/configuration.dart";import "package:photos/core/event_bus.dart";import "package:photos/db/files_db.dart";import "package:photos/events/files_updated_event.dart";@@ -14,6 +15,7 @@ typedef FindUploadedFiles =FileType fileType,int ownerID,);+typedef GetOwnerID = int Function();typedef DeleteGeneratedFile = Future<void> Function(int generatedID);typedef UpdateUploadedFileLocalID =Future<void> Function(int uploadedFileID, String localID);@@ -33,11 +35,13 @@ typedef EmitLocalPhotosUpdated = void Function(LocalPhotosUpdatedEvent event);class ExistingUploadResolver {ExistingUploadResolver({required FindUploadedFiles findUploadedFiles,+ required GetOwnerID getOwnerID,required DeleteGeneratedFile deleteGeneratedFile,required UpdateUploadedFileLocalID updateUploadedFileLocalID,required LinkExistingUpload linkExistingUpload,required EmitLocalPhotosUpdated emitLocalPhotosUpdated,}) : _findUploadedFiles = findUploadedFiles,+ _getOwnerID = getOwnerID,_deleteGeneratedFile = deleteGeneratedFile,_updateUploadedFileLocalID = updateUploadedFileLocalID,_linkExistingUpload = linkExistingUpload,@@ -46,6 +50,7 @@ class ExistingUploadResolver {factory ExistingUploadResolver.forApp() => ExistingUploadResolver(findUploadedFiles: (hash, fileType, ownerID) =>FilesDB.instance.getUploadedFilesWithHash(hash, fileType, ownerID),+ getOwnerID: () => Configuration.instance.getUserID()!,deleteGeneratedFile: (generatedID) =>FilesDB.instance.deleteByGeneratedID(generatedID),updateUploadedFileLocalID: (uploadedFileID, localID) =>@@ -66,6 +71,7 @@ class ExistingUploadResolver {final _logger = Logger("ExistingUploadResolver");final FindUploadedFiles _findUploadedFiles;+ final GetOwnerID _getOwnerID;final DeleteGeneratedFile _deleteGeneratedFile;final UpdateUploadedFileLocalID _updateUploadedFileLocalID;final LinkExistingUpload _linkExistingUpload;@@ -76,7 +82,6 @@ class ExistingUploadResolver {required String fileHash,required EnteFile fileToUpload,required int targetCollectionID,- required int ownerID,}) async {if (fileToUpload.uploadedFileID != null) {// This should never happen. Avoid mapping an already-uploaded row because@@ -85,17 +90,16 @@ class ExistingUploadResolver {return null;}+ final isSandboxFile = fileToUpload.isSharedMediaToAppSandbox;final existingUploadedFiles = await _findUploadedFiles(fileHash,fileToUpload.fileType,- ownerID,+ _getOwnerID(),);if (existingUploadedFiles.isEmpty) {return null;}- final isSandboxFile = fileToUpload.isSharedMediaToAppSandbox;-// Case a: the same local file is already in the target collection.final sameLocalSameCollection = existingUploadedFiles.firstWhereOrNull((file) =>diff --git a/mobile/apps/photos/lib/module/upload/service/file_uploader.dart b/mobile/apps/photos/lib/module/upload/service/file_uploader.dartindex 92df3978ef..f8ebab8d22 100644--- a/mobile/apps/photos/lib/module/upload/service/file_uploader.dart+++ b/mobile/apps/photos/lib/module/upload/service/file_uploader.dart@@ -2,7 +2,6 @@ import 'dart:async';import 'dart:convert';import 'dart:io';-import 'package:collection/collection.dart';import "package:dio/dio.dart";import 'package:ente_crypto/ente_crypto.dart';import 'package:ente_pure_utils/ente_pure_utils.dart';@@ -28,6 +27,7 @@ import 'package:photos/models/file/file_type.dart';import "package:photos/models/user_details.dart";import "package:photos/module/metadata/exif.dart";import 'package:photos/module/upload/model/media_upload_data.dart';+import "package:photos/module/upload/service/existing_upload_resolver.dart";import "package:photos/module/upload/service/multipart.dart";import 'package:photos/module/upload/service/upload_artifact_lifecycle.dart';import 'package:photos/module/upload/service/upload_queue.dart';@@ -43,7 +43,6 @@ import 'package:photos/services/sync/sync_service.dart';import "package:photos/utils/file_key.dart";import "package:photos/utils/network_util.dart";import 'package:shared_preferences/shared_preferences.dart';-import 'package:tuple/tuple.dart';import "package:uuid/uuid.dart";/// Coordinates encryption, transfer, persistence, and retries for file uploads.@@ -67,6 +66,7 @@ class FileUploader {UploadLocksDB.instance,FilesDB.instance,);+ final _existingUploadResolver = ExistingUploadResolver.forApp();final kSafeBufferForLockExpiry = const Duration(hours: 4).inMicroseconds;final kBGTaskDeathTimeout = const Duration(seconds: 5).inMicroseconds;Map<String, BackupItem> get allBackups => _queue.backupItems;@@ -454,23 +454,18 @@ class FileUploader {key = getFileKey(file);} else {key = multiPartFileEncResult?.key;- // check if the file is already uploaded and can be mapped to existing- // uploaded file. If map is found, it also returns the corresponding- // mapped or update file entry.- final result = await _mapToExistingUploadWithSameHash(- mediaUploadData,- file,- collectionID,+ final mappedFile = await _existingUploadResolver.resolve(+ fileHash: mediaUploadData.fileHash,+ fileToUpload: file,+ targetCollectionID: collectionID,);- final isMappedToExistingUpload = result.item1;- if (isMappedToExistingUpload) {+ if (mappedFile != null) {debugPrint("File success mapped to existing uploaded ${file.toString()}",);// treat as completed so _onUploadDone clears the source exportuploadCompleted = true;- // return the mapped file- return result.item2;+ return mappedFile;}}@@ -822,140 +817,6 @@ class FileUploader {return false;}- /*- _mapToExistingUpload links the fileToUpload with the existing uploaded- files. if the link is successful, it returns true otherwise false.- When false, we should go ahead and re-upload or update the file.- It performs following checks:- a) Target file with same localID and destination collection exists. Delete the- fileToUpload entry. If target file is sandbox file, then we skip localID match- check.- b) Uploaded file in any collection but with missing localID.- Update the localID for uploadedFile and delete the fileToUpload entry- c) A uploaded file exist with same localID but in a different collection.- Add a symlink in the destination collection and update the fileToUpload.- If target file is sandbox file, then we skip localID match- check.- d) File already exists but different localID. Re-upload- In case the existing files already have local identifier, which is- different from the {fileToUpload}, then most probably device has- duplicate files.- */- Future<Tuple2<bool, EnteFile>> _mapToExistingUploadWithSameHash(- MediaUploadData mediaUploadData,- EnteFile fileToUpload,- int toCollectionID,- ) async {- if (fileToUpload.uploadedFileID != null) {- // ideally this should never happen, but because the code below this case- // can do unexpected mapping, we are adding this additional check- _logger.severe('Critical: file is already uploaded, skipped mapping');- return Tuple2(false, fileToUpload);- }- final bool isSandBoxFile = fileToUpload.isSharedMediaToAppSandbox;-- final List<EnteFile> existingUploadedFiles = await FilesDB.instance- .getUploadedFilesWithHash(- mediaUploadData.fileHash,- fileToUpload.fileType,- Configuration.instance.getUserID()!,- );- if (existingUploadedFiles.isEmpty) {- // continueUploading this file- return Tuple2(false, fileToUpload);- }-- // case a- final EnteFile? sameLocalSameCollection = existingUploadedFiles- .firstWhereOrNull(- (e) =>- e.collectionID == toCollectionID &&- (e.localID == fileToUpload.localID || isSandBoxFile),- );- if (sameLocalSameCollection != null) {- _logger.info(- "sameLocalSameCollection: toUpload ${fileToUpload.tag} "- "existing: ${sameLocalSameCollection.tag} $isSandBoxFile",- );- // should delete the fileToUploadEntry- if (fileToUpload.generatedID != null) {- await FilesDB.instance.deleteByGeneratedID(fileToUpload.generatedID!);- }-- Bus.instance.fire(- LocalPhotosUpdatedEvent(- [fileToUpload],- type: EventType.deletedFromEverywhere,- source: "sameLocalSameCollection", //- ),- );- return Tuple2(true, sameLocalSameCollection);- }-- // case b- final EnteFile? fileMissingLocal = existingUploadedFiles.firstWhereOrNull(- (e) => e.localID == null,- );- if (fileMissingLocal != null) {- // update the local id of the existing file and delete the fileToUpload- // entry- _logger.info(- "fileMissingLocal: \n toUpload ${fileToUpload.tag} "- "\n existing: ${fileMissingLocal.tag}",- );- fileMissingLocal.localID = fileToUpload.localID;- // set localID for the given uploadedID across collections- await FilesDB.instance.updateLocalIDForUploaded(- fileMissingLocal.uploadedFileID!,- fileToUpload.localID!,- );- // For files selected from device, during collaborative upload, we don't- // insert entries in the FilesDB. So, we don't need to delete the entry- if (fileToUpload.generatedID != null) {- await FilesDB.instance.deleteByGeneratedID(fileToUpload.generatedID!);- }- Bus.instance.fire(- LocalPhotosUpdatedEvent(- [fileToUpload],- source: "fileMissingLocal",- type: EventType.deletedFromEverywhere, //- ),- );- return Tuple2(true, fileMissingLocal);- }-- // case c- final EnteFile? fileExistsButDifferentCollection = existingUploadedFiles- .firstWhereOrNull(- (e) =>- e.collectionID != toCollectionID &&- (e.localID == fileToUpload.localID || isSandBoxFile),- );- if (fileExistsButDifferentCollection != null) {- _logger.info(- "fileExistsButDifferentCollection: toUpload ${fileToUpload.tag} "- "existing: ${fileExistsButDifferentCollection.tag} $isSandBoxFile",- );- final linkedFile = await CollectionsService.instance- .linkLocalFileToExistingUploadedFileInAnotherCollection(- toCollectionID,- localFileToUpload: fileToUpload,- existingUploadedFile: fileExistsButDifferentCollection,- );- return Tuple2(true, linkedFile);- }- final Set<String> matchLocalIDs = existingUploadedFiles- .where((e) => e.localID != null)- .map((e) => e.localID!)- .toSet();- _logger.info(- "Found hashMatch but probably with diff localIDs "- "$matchLocalIDs",- );- // case d- return Tuple2(false, fileToUpload);- }-Future<void> _onUploadDone(MediaUploadData? mediaUploadData,bool uploadCompleted,diff --git a/mobile/apps/photos/test/module/upload/service/existing_upload_resolver_test.dart b/mobile/apps/photos/test/module/upload/service/existing_upload_resolver_test.dartindex 8e2b273cd6..5acc4713fd 100644--- a/mobile/apps/photos/test/module/upload/service/existing_upload_resolver_test.dart+++ b/mobile/apps/photos/test/module/upload/service/existing_upload_resolver_test.dart@@ -13,6 +13,7 @@ void main() {expect(await fixture.resolve(pending), isNull);expect(fixture.calls, isEmpty);+ expect(fixture.ownerIDCalls, 0);});test("no hash matches continues uploading", () async {@@ -20,6 +21,18 @@ void main() {expect(await fixture.resolve(_file(localID: "local")), isNull);expect(fixture.calls, ["find:hash:${FileType.image.index}:10"]);+ expect(fixture.ownerIDCalls, 1);+ });++ test("hash lookup failure propagates without side effects", () async {+ final fixture = _Fixture()..findError = _Error();++ await expectLater(+ fixture.resolve(_file(localID: "local")),+ throwsA(isA<_Error>()),+ );+ expect(fixture.calls, ["find:hash:${FileType.image.index}:10"]);+ expect(fixture.events, isEmpty);});test("case a deletes pending row before emitting deletion", () async {@@ -187,6 +200,26 @@ void main() {expect(fixture.events, isEmpty);});+ test("event failure propagates after case a deletion", () async {+ final existing = _file(+ localID: "local",+ uploadedFileID: 11,+ collectionID: 20,+ );+ final fixture = _Fixture(existingFiles: [existing])..emitError = _Error();++ await expectLater(+ fixture.resolve(_file(localID: "local", generatedID: 7)),+ throwsA(isA<_Error>()),+ );+ expect(fixture.calls, [+ "find:hash:${FileType.image.index}:10",+ "delete:7",+ "event:deletedFromEverywhere:sameLocalSameCollection",+ ]);+ expect(fixture.events, hasLength(1));+ });+test("update failure prevents case b deletion and event", () async {final existing = _file(uploadedFileID: 12, collectionID: 30);final fixture = _Fixture(existingFiles: [existing])..updateError = _Error();@@ -252,8 +285,13 @@ class _Fixture {resolver = ExistingUploadResolver(findUploadedFiles: (hash, fileType, ownerID) async {calls.add("find:$hash:${fileType.index}:$ownerID");+ if (findError != null) throw findError!;return this.existingFiles;},+ getOwnerID: () {+ ownerIDCalls++;+ return ownerID;+ },deleteGeneratedFile: (generatedID) async {calls.add("delete:$generatedID");if (deleteError != null) throw deleteError!;@@ -280,6 +318,7 @@ class _Fixture {emitLocalPhotosUpdated: (event) {calls.add("event:${event.type.name}:${event.source}");events.add(event);+ if (emitError != null) throw emitError!;},);}@@ -296,14 +335,16 @@ class _Fixture {EnteFile? linkedLocalFile;EnteFile? linkedExistingFile;Object? deleteError;+ Object? findError;+ Object? emitError;Object? updateError;Object? linkError;+ var ownerIDCalls = 0;Future<EnteFile?> resolve(EnteFile pending) => resolver.resolve(fileHash: fileHash,fileToUpload: pending,targetCollectionID: targetCollectionID,- ownerID: ownerID,);}