π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mobile] Add existing upload resolver
Neeraj Gupta16115174140b
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.dartnew file mode 100644index 0000000000..a28b8670cf--- /dev/null+++ b/mobile/apps/photos/lib/module/upload/service/existing_upload_resolver.dart@@ -0,0 +1,176 @@+import "package:collection/collection.dart";+import "package:logging/logging.dart";+import "package:photos/core/event_bus.dart";+import "package:photos/db/files_db.dart";+import "package:photos/events/files_updated_event.dart";+import "package:photos/events/local_photos_updated_event.dart";+import "package:photos/models/file/file.dart";+import "package:photos/models/file/file_type.dart";+import "package:photos/services/collections_service.dart";++typedef FindUploadedFiles =+ Future<List<EnteFile>> Function(+ String hash,+ FileType fileType,+ int ownerID,+ );+typedef DeleteGeneratedFile = Future<void> Function(int generatedID);+typedef UpdateUploadedFileLocalID =+ Future<void> Function(int uploadedFileID, String localID);+typedef LinkExistingUpload =+ Future<EnteFile> Function(+ int collectionID, {+ required EnteFile localFileToUpload,+ required EnteFile existingUploadedFile,+ });+typedef EmitLocalPhotosUpdated = void Function(LocalPhotosUpdatedEvent event);++/// Resolves a pending upload to an already-uploaded file with the same hash.+///+/// Resolution priority and side effects intentionally match the legacy upload+/// flow: same local file in the target collection, missing local ID, same local+/// file in another collection, then no mapping.+class ExistingUploadResolver {+ ExistingUploadResolver({+ required FindUploadedFiles findUploadedFiles,+ required DeleteGeneratedFile deleteGeneratedFile,+ required UpdateUploadedFileLocalID updateUploadedFileLocalID,+ required LinkExistingUpload linkExistingUpload,+ required EmitLocalPhotosUpdated emitLocalPhotosUpdated,+ }) : _findUploadedFiles = findUploadedFiles,+ _deleteGeneratedFile = deleteGeneratedFile,+ _updateUploadedFileLocalID = updateUploadedFileLocalID,+ _linkExistingUpload = linkExistingUpload,+ _emitLocalPhotosUpdated = emitLocalPhotosUpdated;++ factory ExistingUploadResolver.forApp() => ExistingUploadResolver(+ findUploadedFiles: (hash, fileType, ownerID) =>+ FilesDB.instance.getUploadedFilesWithHash(hash, fileType, ownerID),+ deleteGeneratedFile: (generatedID) =>+ FilesDB.instance.deleteByGeneratedID(generatedID),+ updateUploadedFileLocalID: (uploadedFileID, localID) =>+ FilesDB.instance.updateLocalIDForUploaded(uploadedFileID, localID),+ linkExistingUpload:+ (+ collectionID, {+ required localFileToUpload,+ required existingUploadedFile,+ }) => CollectionsService.instance+ .linkLocalFileToExistingUploadedFileInAnotherCollection(+ collectionID,+ localFileToUpload: localFileToUpload,+ existingUploadedFile: existingUploadedFile,+ ),+ emitLocalPhotosUpdated: (event) => Bus.instance.fire(event),+ );++ final _logger = Logger("ExistingUploadResolver");+ final FindUploadedFiles _findUploadedFiles;+ final DeleteGeneratedFile _deleteGeneratedFile;+ final UpdateUploadedFileLocalID _updateUploadedFileLocalID;+ final LinkExistingUpload _linkExistingUpload;+ final EmitLocalPhotosUpdated _emitLocalPhotosUpdated;++ /// Returns the mapped file, or `null` when the caller should upload it.+ Future<EnteFile?> resolve({+ 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+ // the branches below can delete or relink the pending local entry.+ _logger.severe("Critical: file is already uploaded, skipped mapping");+ return null;+ }++ final existingUploadedFiles = await _findUploadedFiles(+ fileHash,+ fileToUpload.fileType,+ ownerID,+ );+ 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) =>+ file.collectionID == targetCollectionID &&+ (file.localID == fileToUpload.localID || isSandboxFile),+ );+ if (sameLocalSameCollection != null) {+ _logger.info(+ "sameLocalSameCollection: toUpload ${fileToUpload.tag} "+ "existing: ${sameLocalSameCollection.tag} $isSandboxFile",+ );+ if (fileToUpload.generatedID != null) {+ await _deleteGeneratedFile(fileToUpload.generatedID!);+ }+ _emitDeletedEvent(fileToUpload, "sameLocalSameCollection");+ return sameLocalSameCollection;+ }++ // Case b: reuse an uploaded file whose local ID is not known yet.+ final fileMissingLocal = existingUploadedFiles.firstWhereOrNull(+ (file) => file.localID == null,+ );+ if (fileMissingLocal != null) {+ _logger.info(+ "fileMissingLocal: \n toUpload ${fileToUpload.tag} "+ "\n existing: ${fileMissingLocal.tag}",+ );+ fileMissingLocal.localID = fileToUpload.localID;+ await _updateUploadedFileLocalID(+ fileMissingLocal.uploadedFileID!,+ fileToUpload.localID!,+ );+ if (fileToUpload.generatedID != null) {+ await _deleteGeneratedFile(fileToUpload.generatedID!);+ }+ _emitDeletedEvent(fileToUpload, "fileMissingLocal");+ return fileMissingLocal;+ }++ // Case c: link the same local file from another collection.+ final fileInDifferentCollection = existingUploadedFiles.firstWhereOrNull(+ (file) =>+ file.collectionID != targetCollectionID &&+ (file.localID == fileToUpload.localID || isSandboxFile),+ );+ if (fileInDifferentCollection != null) {+ _logger.info(+ "fileExistsButDifferentCollection: toUpload ${fileToUpload.tag} "+ "existing: ${fileInDifferentCollection.tag} $isSandboxFile",+ );+ return _linkExistingUpload(+ targetCollectionID,+ localFileToUpload: fileToUpload,+ existingUploadedFile: fileInDifferentCollection,+ );+ }++ // Case d: the hash belongs to a different local file, so upload this one.+ final matchLocalIDs = existingUploadedFiles+ .where((file) => file.localID != null)+ .map((file) => file.localID!)+ .toSet();+ _logger.info(+ "Found hashMatch but probably with diff localIDs $matchLocalIDs",+ );+ return null;+ }++ void _emitDeletedEvent(EnteFile file, String source) {+ _emitLocalPhotosUpdated(+ LocalPhotosUpdatedEvent(+ [file],+ type: EventType.deletedFromEverywhere,+ source: source,+ ),+ );+ }+}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.dartnew file mode 100644index 0000000000..8e2b273cd6--- /dev/null+++ b/mobile/apps/photos/test/module/upload/service/existing_upload_resolver_test.dart@@ -0,0 +1,310 @@+import "package:flutter_test/flutter_test.dart";+import "package:photos/core/constants.dart";+import "package:photos/events/files_updated_event.dart";+import "package:photos/events/local_photos_updated_event.dart";+import "package:photos/models/file/file.dart";+import "package:photos/models/file/file_type.dart";+import "package:photos/module/upload/service/existing_upload_resolver.dart";++void main() {+ test("already-uploaded input skips lookup and mapping", () async {+ final fixture = _Fixture();+ final pending = _file(localID: "local", uploadedFileID: 1);++ expect(await fixture.resolve(pending), isNull);+ expect(fixture.calls, isEmpty);+ });++ test("no hash matches continues uploading", () async {+ final fixture = _Fixture();++ expect(await fixture.resolve(_file(localID: "local")), isNull);+ expect(fixture.calls, ["find:hash:${FileType.image.index}:10"]);+ });++ test("case a deletes pending row before emitting deletion", () async {+ final existing = _file(+ localID: "local",+ uploadedFileID: 11,+ collectionID: 20,+ );+ final fixture = _Fixture(existingFiles: [existing]);+ final pending = _file(localID: "local", generatedID: 7);++ expect(await fixture.resolve(pending), same(existing));+ expect(fixture.calls, [+ "find:hash:${FileType.image.index}:10",+ "delete:7",+ "event:deletedFromEverywhere:sameLocalSameCollection",+ ]);+ _expectDeletionEvent(+ fixture.events.single,+ pending,+ "sameLocalSameCollection",+ );+ });++ test(+ "case a emits deletion without deleting an absent pending row",+ () async {+ final existing = _file(+ localID: "local",+ uploadedFileID: 11,+ collectionID: 20,+ );+ final fixture = _Fixture(existingFiles: [existing]);+ final pending = _file(localID: "local");++ expect(await fixture.resolve(pending), same(existing));+ expect(fixture.calls, [+ "find:hash:${FileType.image.index}:10",+ "event:deletedFromEverywhere:sameLocalSameCollection",+ ]);+ },+ );++ test("case b updates local ID, deletes pending row, then emits", () async {+ final existing = _file(uploadedFileID: 12, collectionID: 30);+ final fixture = _Fixture(existingFiles: [existing]);+ final pending = _file(localID: "local", generatedID: 8);++ expect(await fixture.resolve(pending), same(existing));+ expect(existing.localID, "local");+ expect(fixture.calls, [+ "find:hash:${FileType.image.index}:10",+ "update:12:local",+ "delete:8",+ "event:deletedFromEverywhere:fileMissingLocal",+ ]);+ _expectDeletionEvent(fixture.events.single, pending, "fileMissingLocal");+ });++ test("case c links matching local file from another collection", () async {+ final existing = _file(+ localID: "local",+ uploadedFileID: 13,+ collectionID: 30,+ );+ final linked = _file(+ localID: "local",+ uploadedFileID: 13,+ collectionID: 20,+ );+ final fixture = _Fixture(existingFiles: [existing], linkedFile: linked);+ final pending = _file(localID: "local", generatedID: 9);++ expect(await fixture.resolve(pending), same(linked));+ expect(fixture.calls, [+ "find:hash:${FileType.image.index}:10",+ "link:20:local:13",+ ]);+ expect(fixture.linkedLocalFile, same(pending));+ expect(fixture.linkedExistingFile, same(existing));+ expect(fixture.events, isEmpty);+ });++ test("case d leaves a different local file untouched", () async {+ final existing = _file(+ localID: "other",+ uploadedFileID: 14,+ collectionID: 30,+ );+ final fixture = _Fixture(existingFiles: [existing]);++ expect(await fixture.resolve(_file(localID: "local")), isNull);+ expect(fixture.calls, ["find:hash:${FileType.image.index}:10"]);+ expect(fixture.events, isEmpty);+ });++ test("case priority remains a then b then c", () async {+ final caseC = _file(localID: "local", uploadedFileID: 13, collectionID: 30);+ final caseB = _file(uploadedFileID: 12, collectionID: 30);+ final caseA = _file(localID: "local", uploadedFileID: 11, collectionID: 20);+ final fixture = _Fixture(existingFiles: [caseC, caseB, caseA]);++ expect(await fixture.resolve(_file(localID: "local")), same(caseA));+ expect(fixture.calls, [+ "find:hash:${FileType.image.index}:10",+ "event:deletedFromEverywhere:sameLocalSameCollection",+ ]);+ });++ test("case b remains preferred over case c", () async {+ final caseC = _file(localID: "local", uploadedFileID: 13, collectionID: 30);+ final caseB = _file(uploadedFileID: 12, collectionID: 30);+ final fixture = _Fixture(existingFiles: [caseC, caseB]);++ expect(await fixture.resolve(_file(localID: "local")), same(caseB));+ expect(fixture.calls, [+ "find:hash:${FileType.image.index}:10",+ "update:12:local",+ "event:deletedFromEverywhere:fileMissingLocal",+ ]);+ });++ test("sandbox file ignores local ID for same-collection mapping", () async {+ final existing = _file(+ localID: "different",+ uploadedFileID: 11,+ collectionID: 20,+ );+ final fixture = _Fixture(existingFiles: [existing]);++ expect(+ await fixture.resolve(_file(localID: "${sharedMediaIdentifier}pending")),+ same(existing),+ );+ });++ test("sandbox file ignores local ID for cross-collection mapping", () async {+ final existing = _file(+ localID: "different",+ uploadedFileID: 13,+ collectionID: 30,+ );+ final linked = _file(uploadedFileID: 13, collectionID: 20);+ final fixture = _Fixture(existingFiles: [existing], linkedFile: linked);++ expect(+ await fixture.resolve(_file(localID: "${sharedMediaIdentifier}pending")),+ same(linked),+ );+ });++ test("delete failure prevents case a event", () async {+ final existing = _file(+ localID: "local",+ uploadedFileID: 11,+ collectionID: 20,+ );+ final fixture = _Fixture(existingFiles: [existing])..deleteError = _Error();++ await expectLater(+ fixture.resolve(_file(localID: "local", generatedID: 7)),+ throwsA(isA<_Error>()),+ );+ expect(fixture.calls, ["find:hash:${FileType.image.index}:10", "delete:7"]);+ expect(fixture.events, isEmpty);+ });++ test("update failure prevents case b deletion and event", () async {+ final existing = _file(uploadedFileID: 12, collectionID: 30);+ final fixture = _Fixture(existingFiles: [existing])..updateError = _Error();++ await expectLater(+ fixture.resolve(_file(localID: "local", generatedID: 8)),+ throwsA(isA<_Error>()),+ );+ expect(fixture.calls, [+ "find:hash:${FileType.image.index}:10",+ "update:12:local",+ ]);+ expect(fixture.events, isEmpty);+ });++ test("link failure propagates without resolver event", () async {+ final existing = _file(+ localID: "local",+ uploadedFileID: 13,+ collectionID: 30,+ );+ final fixture = _Fixture(existingFiles: [existing])..linkError = _Error();++ await expectLater(+ fixture.resolve(_file(localID: "local")),+ throwsA(isA<_Error>()),+ );+ expect(fixture.calls, [+ "find:hash:${FileType.image.index}:10",+ "link:20:local:13",+ ]);+ expect(fixture.events, isEmpty);+ });+}++void _expectDeletionEvent(+ LocalPhotosUpdatedEvent event,+ EnteFile pending,+ String source,+) {+ expect(event.updatedFiles, [same(pending)]);+ expect(event.type, EventType.deletedFromEverywhere);+ expect(event.source, source);+}++EnteFile _file({+ String? localID,+ int? generatedID,+ int? uploadedFileID,+ int? collectionID,+ FileType fileType = FileType.image,+}) => EnteFile()+ ..localID = localID+ ..generatedID = generatedID+ ..uploadedFileID = uploadedFileID+ ..collectionID = collectionID+ ..fileType = fileType;++class _Fixture {+ _Fixture({List<EnteFile>? existingFiles, EnteFile? linkedFile})+ : existingFiles = existingFiles ?? [],+ linkedFile = linkedFile ?? _file(uploadedFileID: 99, collectionID: 20) {+ resolver = ExistingUploadResolver(+ findUploadedFiles: (hash, fileType, ownerID) async {+ calls.add("find:$hash:${fileType.index}:$ownerID");+ return this.existingFiles;+ },+ deleteGeneratedFile: (generatedID) async {+ calls.add("delete:$generatedID");+ if (deleteError != null) throw deleteError!;+ },+ updateUploadedFileLocalID: (uploadedFileID, localID) async {+ calls.add("update:$uploadedFileID:$localID");+ if (updateError != null) throw updateError!;+ },+ linkExistingUpload:+ (+ collectionID, {+ required localFileToUpload,+ required existingUploadedFile,+ }) async {+ calls.add(+ "link:$collectionID:${localFileToUpload.localID}:"+ "${existingUploadedFile.uploadedFileID}",+ );+ linkedLocalFile = localFileToUpload;+ linkedExistingFile = existingUploadedFile;+ if (linkError != null) throw linkError!;+ return this.linkedFile;+ },+ emitLocalPhotosUpdated: (event) {+ calls.add("event:${event.type.name}:${event.source}");+ events.add(event);+ },+ );+ }++ static const fileHash = "hash";+ static const ownerID = 10;+ static const targetCollectionID = 20;++ final List<EnteFile> existingFiles;+ final EnteFile linkedFile;+ final calls = <String>[];+ final events = <LocalPhotosUpdatedEvent>[];+ late final ExistingUploadResolver resolver;+ EnteFile? linkedLocalFile;+ EnteFile? linkedExistingFile;+ Object? deleteError;+ Object? updateError;+ Object? linkError;++ Future<EnteFile?> resolve(EnteFile pending) => resolver.resolve(+ fileHash: fileHash,+ fileToUpload: pending,+ targetCollectionID: targetCollectionID,+ ownerID: ownerID,+ );+}++class _Error extends Error {}