π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Simplify contact and person linking code
Neeraj Guptafeb6a98a798d
diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dartindex 46decbd2a0..96fcf738f2 100644--- a/mobile/apps/photos/lib/services/photos_contacts_service.dart+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart@@ -92,16 +92,13 @@ class PhotosContactsService {int? contactUserId,String? email,}) async {- final cached = _getCachedContact(- contactUserId: contactUserId,- email: email,- );+ final cached = getCachedContact(contactUserId: contactUserId, email: email);if (cached != null) {return cached;}return _runReadSafely(() async {await ensureReady();- final hydratedCached = _getCachedContact(+ final hydratedCached = getCachedContact(contactUserId: contactUserId,email: email,);@@ -119,7 +116,7 @@ class PhotosContactsService {if (contact != null) {_cacheContact(contact);}- return _getCachedContact(contactUserId: contactUserId, email: email);+ return getCachedContact(contactUserId: contactUserId, email: email);}, description: "load contact for user $contactUserId");}@@ -127,7 +124,16 @@ class PhotosContactsService {int? contactUserId,String? email,}) {- return _getCachedContact(contactUserId: contactUserId, email: email);+ if (_sessionKey == null) {+ return null;+ }+ if (contactUserId != null) {+ return _contactsByUserId[contactUserId];+ }+ final normalizedEmail = normalizeContactLinkEmail(email);+ return normalizedEmail == null+ ? null+ : _contactsByNormalizedEmail[normalizedEmail];}String? getCachedSavedName({int? contactUserId, String? email}) {@@ -483,42 +489,6 @@ class PhotosContactsService {_profilePictureLoadsByUserId.remove(contactUserId);}- contacts.ContactRecord? _getCachedContact({- int? contactUserId,- String? email,- }) {- if (_sessionKey == null) {- return null;- }- if (contactUserId != null) {- return _contactByUserIdOrNull(contactUserId);- }- return _contactByEmailOrNull(email);- }-- contacts.ContactRecord? _contactByUserIdOrNull(int? contactUserId) {- if (contactUserId == null) {- return null;- }- final contact = _contactsByUserId[contactUserId];- if (contact == null || contact.isDeleted) {- return null;- }- return contact;- }-- contacts.ContactRecord? _contactByEmailOrNull(String? email) {- final normalizedEmail = normalizeContactLinkEmail(email);- if (normalizedEmail == null) {- return null;- }- final contact = _contactsByNormalizedEmail[normalizedEmail];- if (contact == null || contact.isDeleted) {- return null;- }- return contact;- }-void _attachSessionResetListeners() {Bus.instance.on<UserLoggedOutEvent>().listen((_) {_sessionGeneration += 1;diff --git a/mobile/apps/photos/lib/ui/viewer/people/people_app_bar.dart b/mobile/apps/photos/lib/ui/viewer/people/people_app_bar.dartindex 28aa08178f..3fad547834 100644--- a/mobile/apps/photos/lib/ui/viewer/people/people_app_bar.dart+++ b/mobile/apps/photos/lib/ui/viewer/people/people_app_bar.dart@@ -168,8 +168,7 @@ class _AppBarWidgetState extends State<PeopleAppBar> {if (event.person != null &&event.type == PeopleEventType.saveOrEditPerson &&widget.person.remoteID == event.person!.remoteID &&- (event.source == "linkEmailToPerson" ||- event.source == "reassignMe")) {+ event.source == "reassignMe") {person = event.person!;_appBarTitle = _resolveAppBarTitle(diff --git a/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart b/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dartindex 31767b33eb..3e697553b1 100644--- a/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart+++ b/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart@@ -226,8 +226,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>generation: generation,useFullFile: widget.useFullFile,);- if (_isCurrentLoad(generation, personOrClusterId) &&- thumbnailCrop != null) {+ if (_isCurrentLoad(generation) && thumbnailCrop != null) {_fallbackEverUsed = true;_showingFallback = false;}@@ -239,7 +238,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>useFullFile: widget.useFullFile,);if (fullCrop != null) {- if (_isCurrentLoad(generation, personOrClusterId)) {+ if (_isCurrentLoad(generation)) {_showingFallback = false;}return fullCrop;@@ -254,7 +253,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>useFullFile: false,);if (fallbackCrop != null) {- if (_isCurrentLoad(generation, personOrClusterId)) {+ if (_isCurrentLoad(generation)) {_showingFallback = true;_fallbackEverUsed = true;}@@ -288,7 +287,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>);return null;}- if (!_isCurrentLoad(generation, personOrClusterId)) {+ if (!_isCurrentLoad(generation)) {return null;}_personName = personEntity.data.name;@@ -296,7 +295,6 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>final contactPhotoBytes = await _getLinkedContactPhotoBytes(personEntity,generation: generation,- personOrClusterId: personOrClusterId,);if (contactPhotoBytes != null) {return contactPhotoBytes;@@ -472,7 +470,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>personOrClusterID: personOrClusterId,useTempCache: false,);- if (_isCurrentLoad(generation, personOrClusterId)) {+ if (_isCurrentLoad(generation)) {_faceCropFileId = recentFileID;}final result = cropMap?[face.faceID];@@ -493,10 +491,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>}}- bool _isCurrentLoad(int generation, String personOrClusterId) {- return _loadGeneration == generation &&- (widget.personId ?? widget.clusterID) == personOrClusterId;- }+ bool _isCurrentLoad(int generation) => _loadGeneration == generation;bool _hasContactLink(PersonEntity personEntity) {final userId = personEntity.data.userID;@@ -508,7 +503,6 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>Future<Uint8List?> _getLinkedContactPhotoBytes(PersonEntity personEntity, {required int generation,- required String personOrClusterId,}) async {if (!_personHasContactLink) {_linkedContactUserId = null;@@ -518,7 +512,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>contactUserId: personEntity.data.userID,email: personEntity.data.email,);- if (!_isCurrentLoad(generation, personOrClusterId)) {+ if (!_isCurrentLoad(generation)) {return null;}_linkedContactUserId = contact?.contactUserId ?? personEntity.data.userID;diff --git a/mobile/apps/photos/lib/ui/viewer/people/save_or_edit_person.dart b/mobile/apps/photos/lib/ui/viewer/people/save_or_edit_person.dartindex 247166c6aa..82cc624fe2 100644--- a/mobile/apps/photos/lib/ui/viewer/people/save_or_edit_person.dart+++ b/mobile/apps/photos/lib/ui/viewer/people/save_or_edit_person.dart@@ -65,7 +65,6 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {late final Logger _logger = Logger("_SavePersonState");PersonEntity? person;final _nameFocsNode = FocusNode();- late final TextEditingController _nameController;List<PersonEntity> _allPersons = [];String? get _emailToSave => trimToNull(_email);@@ -100,14 +99,10 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {void initState() {super.initState();_inputName = widget.person?.data.name ?? "";- _nameController = TextEditingController(text: _inputName);_selectedDate = widget.person?.data.birthDate;_email = widget.person?.data.email;person = widget.person;- _isMe = isCurrentUserContactLink(- email: widget.person?.data.email,- userID: widget.person?.data.userID,- );+ _isMe = _initiallyIsMe;_isPinned = widget.person?.data.isPinned ?? false;_hideFromMemories = widget.person?.data.hideFromMemories ?? false;_nameFocsNode.addListener(_handleNameFocusChange);@@ -118,7 +113,6 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {void dispose() {_nameFocsNode.removeListener(_handleNameFocusChange);_nameFocsNode.dispose();- _nameController.dispose();super.dispose();}@@ -158,7 +152,6 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {}},child: Scaffold(- resizeToAvoidBottomInset: true,backgroundColor: colors.backgroundBase,body: GestureDetector(onTap: () => FocusScope.of(context).unfocus(),@@ -169,7 +162,6 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {title: widget.isEditing? context.l10n.editPerson: context.l10n.savePerson,- onBack: () => Navigator.of(context).maybePop(),physics: const BouncingScrollPhysics(),slivers: [SliverPadding(@@ -183,7 +175,7 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {TextInputComponent(label: context.l10n.name,hintText: context.l10n.enterName,- controller: _nameController,+ initialValue: widget.person?.data.name,focusNode: _nameFocsNode,keyboardType: TextInputType.name,textCapitalization: TextCapitalization.words,@@ -344,10 +336,7 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {_isMe = selected;_email = selected? Configuration.instance.getEmail()- : isCurrentUserContactLink(- email: widget.person?.data.email,- userID: widget.person?.data.userID,- )+ : _initiallyIsMe? null: widget.person?.data.email;});diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/contact_photo_picker_sheet.dart b/mobile/apps/photos/lib/ui/viewer/search/result/contact_photo_picker_sheet.dartindex 9ac4e90d7e..0015b71086 100644--- a/mobile/apps/photos/lib/ui/viewer/search/result/contact_photo_picker_sheet.dart+++ b/mobile/apps/photos/lib/ui/viewer/search/result/contact_photo_picker_sheet.dart@@ -49,13 +49,7 @@ class _ContactPhotoPickerSheet extends StatefulWidget {}class _ContactPhotoPickerSheetState extends State<_ContactPhotoPickerSheet> {- late final SelectedFiles _selectedFiles;-- @override- void initState() {- super.initState();- _selectedFiles = SelectedFiles();- }+ final _selectedFiles = SelectedFiles();@overridevoid dispose() {@@ -96,42 +90,30 @@ class _ContactPhotoPickerSheetState extends State<_ContactPhotoPickerSheet> {listenable: _selectedFiles,builder: (context, _) {final isFileSelected = _selectedFiles.files.isNotEmpty;- return Column(- mainAxisSize: MainAxisSize.min,- children: [- ButtonComponent(- label: l10n.setSelectedPhoto,- isDisabled: !isFileSelected,- shouldSurfaceExecutionStates: false,- onTap: isFileSelected- ? () {- Navigator.pop(- context,- ContactPhotoPickerFile(- _selectedFiles.files.first,- ),- );- }- : null,- ),- if (widget.canRemovePhoto) ...[- const SizedBox(height: Spacing.md),- ButtonComponent(- label: l10n.removeContactPhoto,- variant: ButtonComponentVariant.secondary,- shouldSurfaceExecutionStates: false,- onTap: () {+ return ButtonComponent(+ label: l10n.setSelectedPhoto,+ isDisabled: !isFileSelected,+ shouldSurfaceExecutionStates: false,+ onTap: isFileSelected+ ? () {Navigator.pop(context,- const ContactPhotoPickerRemove(),+ ContactPhotoPickerFile(_selectedFiles.files.first),);- },- ),- ],- ],+ }+ : null,);},),+ if (widget.canRemovePhoto)+ ButtonComponent(+ label: l10n.removeContactPhoto,+ variant: ButtonComponentVariant.secondary,+ shouldSurfaceExecutionStates: false,+ onTap: () {+ Navigator.pop(context, const ContactPhotoPickerRemove());+ },+ ),],),);diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/edit_contact_page.dart b/mobile/apps/photos/lib/ui/viewer/search/result/edit_contact_page.dartindex 774a31a966..aaba6982fb 100644--- a/mobile/apps/photos/lib/ui/viewer/search/result/edit_contact_page.dart+++ b/mobile/apps/photos/lib/ui/viewer/search/result/edit_contact_page.dart@@ -61,7 +61,6 @@ class _EditContactPageState extends State<EditContactPage> {PersonEntity? _initialLinkedPerson;PersonEntity? _draftLinkedPerson;bool _linkDirty = false;- bool _unlinkDraft = false;@overridevoid initState() {@@ -73,12 +72,7 @@ class _EditContactPageState extends State<EditContactPage> {setState(() {});}});- _nameFocusNode = FocusNode()- ..addListener(() {- if (mounted) {- setState(() {});- }- });+ _nameFocusNode = FocusNode();_loadExistingPhoto();_loadLinkedPersonDraft();}@@ -94,7 +88,7 @@ class _EditContactPageState extends State<EditContactPage> {String get _initialName => (widget.existingContact?.data?.name ?? "").trim();bool get _hasUnsavedChanges =>_nameController.text.trim() != _initialName || _photoDirty || _linkDirty;- bool get _hasLinkedPersonDraft => !_unlinkDraft && _draftLinkedPerson != null;+ bool get _hasLinkedPersonDraft => _draftLinkedPerson != null;bool get _hasContactPhoto =>_draftPhotoBytes != null ||(!_photoDirty &&@@ -308,7 +302,6 @@ class _EditContactPageState extends State<EditContactPage> {setState(() {_initialLinkedPerson = linkedPerson;_draftLinkedPerson = linkedPerson;- _unlinkDraft = false;});if (shouldPrefillFromPerson && !_photoDirty && _draftPhotoBytes == null) {@@ -376,7 +369,6 @@ class _EditContactPageState extends State<EditContactPage> {void _draftUnlinkPerson() {setState(() {_draftLinkedPerson = null;- _unlinkDraft = true;_linkDirty = _initialLinkedPerson != null;});}@@ -394,7 +386,6 @@ class _EditContactPageState extends State<EditContactPage> {_nameController.text = person.data.name;setState(() {_draftLinkedPerson = person;- _unlinkDraft = false;_linkDirty =_initialLinkedPerson?.remoteID != person.remoteID ||_personNeedsContactLinkUpdate(person);@@ -546,7 +537,7 @@ class _EditContactPageState extends State<EditContactPage> {required bool contactNameChanged,}) async {final previousPerson = _initialLinkedPerson;- final selectedPerson = _unlinkDraft ? null : _draftLinkedPerson;+ final selectedPerson = _draftLinkedPerson;final updatedPersons = <PersonEntity>[];if (previousPerson != null &&@@ -567,9 +558,7 @@ class _EditContactPageState extends State<EditContactPage> {previousPerson?.remoteID != selectedPerson.remoteID ||_personNeedsContactLinkUpdate(selectedPerson);final shouldUpdateSelectedName =- contactNameChanged &&- contactName.isNotEmpty &&- selectedPerson.data.name.trim() != contactName;+ contactNameChanged && selectedPerson.data.name.trim() != contactName;if (shouldUpdateSelectedLink || shouldUpdateSelectedName) {updatedPersons.add(await PersonService.instance.updateAttributes(diff --git a/mobile/apps/photos/lib/ui/viewer/search_tab/contacts_section.dart b/mobile/apps/photos/lib/ui/viewer/search_tab/contacts_section.dartindex 96b044e0fe..f62027772d 100644--- a/mobile/apps/photos/lib/ui/viewer/search_tab/contacts_section.dart+++ b/mobile/apps/photos/lib/ui/viewer/search_tab/contacts_section.dart@@ -6,13 +6,11 @@ import "package:flutter/material.dart";import "package:flutter_svg/flutter_svg.dart";import "package:photos/events/event.dart";import "package:photos/generated/l10n.dart";-import "package:photos/models/api/collection/user.dart";import "package:photos/models/search/generic_search_result.dart";import "package:photos/models/search/recent_searches.dart";import "package:photos/models/search/search_constants.dart";import "package:photos/models/search/search_types.dart";import "package:photos/service_locator.dart" show isLocalGalleryMode;-import "package:photos/services/contacts/contact_identity_resolver.dart";import "package:photos/services/search_service.dart";import "package:photos/theme/ente_theme.dart";import "package:photos/ui/common/loading_widget.dart";@@ -214,7 +212,7 @@ class ContactRecommendation extends StatelessWidget {final personId = contactSearchResult.params[kPersonParamID] as String?;final contactUserId = contactSearchResult.params[kContactUserId] as int?;final contactEmail = contactSearchResult.params[kContactEmail] as String;- final displayName = _displayName(contactUserId, contactEmail);+ final displayName = contactSearchResult.hierarchicalSearchFilter.name();return GestureDetector(onTap: () {RecentSearches().add(displayName);@@ -249,16 +247,6 @@ class ContactRecommendation extends StatelessWidget {),);}-- String _displayName(int? contactUserId, String contactEmail) {- final contactUser = User(id: contactUserId, email: contactEmail);- final resolvedName = resolveDisplayName(contactUser);- final resolvedEmail = resolveKnownEmail(contactUser) ?? contactEmail;- if (resolvedName == resolvedEmail || resolvedName == "Someone") {- return contactSearchResult.name();- }- return resolvedName;- }}class ContactCTA extends StatelessWidget {diff --git a/mobile/apps/photos/lib/utils/person_contact_linking_util.dart b/mobile/apps/photos/lib/utils/person_contact_linking_util.dartindex 11d1cf6fa2..b8468a3cb0 100644--- a/mobile/apps/photos/lib/utils/person_contact_linking_util.dart+++ b/mobile/apps/photos/lib/utils/person_contact_linking_util.dart@@ -9,9 +9,6 @@ import "package:photos/ui/viewer/people/people_page.dart";import "package:photos/utils/contact_string_util.dart";import "package:photos/utils/dialog_util.dart";-export "package:photos/utils/contact_string_util.dart"- show normalizeContactLinkEmail;-bool contactLinkEmailMatches(String? first, String? second) {final normalizedFirst = normalizeContactLinkEmail(first);final normalizedSecond = normalizeContactLinkEmail(second);@@ -100,10 +97,7 @@ bool isLinkedToDifferentContact(}final linkedEmail = normalizeContactLinkEmail(person.data.email);- if (linkedEmail == null) {- return false;- }- return !contactLinkEmailMatches(linkedEmail, email);+ return linkedEmail != null && linkedEmail != normalizeContactLinkEmail(email);}Future<void> showAlreadyLinkedEmailDialog(diff --git a/mobile/apps/photos/test/models/ml/face/person_contact_link_test.dart b/mobile/apps/photos/test/models/ml/face/person_contact_link_test.dartindex 5abee80519..36a5617cf4 100644--- a/mobile/apps/photos/test/models/ml/face/person_contact_link_test.dart+++ b/mobile/apps/photos/test/models/ml/face/person_contact_link_test.dart@@ -1,14 +1,11 @@import "dart:convert";-import "package:dio/dio.dart";import "package:ente_contacts/contacts.dart" as contacts;import "package:flutter_test/flutter_test.dart";-import "package:package_info_plus/package_info_plus.dart";import "package:photos/db/ml/db.dart";import "package:photos/gateways/entity/models/type.dart";import "package:photos/models/local_entity_data.dart";import "package:photos/models/ml/face/person.dart";-import "package:photos/service_locator.dart";import "package:photos/services/entity_service.dart";import "package:photos/services/machine_learning/face_ml/person/person_service.dart";import "package:photos/services/photos_contacts_service.dart";@@ -16,23 +13,6 @@ import "package:photos/utils/person_contact_linking_util.dart";import "package:shared_preferences/shared_preferences.dart";void main() {- setUpAll(() async {- SharedPreferences.setMockInitialValues({});- final prefs = await SharedPreferences.getInstance();- ServiceLocator.instance.init(- prefs,- Dio(),- Dio(),- Dio(),- PackageInfo(- appName: "Photos",- packageName: "photos",- version: "1.0.0",- buildNumber: "1",- ),- );- });-group("PersonData contact link", () {test("copyWith preserves link fields when omitted", () {final data = PersonData(diff --git a/mobile/apps/photos/test/services/photos_contacts_service_test.dart b/mobile/apps/photos/test/services/photos_contacts_service_test.dartindex bdafca23c2..35fa31c9ef 100644--- a/mobile/apps/photos/test/services/photos_contacts_service_test.dart+++ b/mobile/apps/photos/test/services/photos_contacts_service_test.dart@@ -240,47 +240,14 @@ void main() {await service.getProfilePictureBytesByUserId(7),Uint8List.fromList([1, 2, 3]),);+ expect(+ service.getCachedProfilePictureBytesByUserId(7),+ Uint8List.fromList([1, 2, 3]),+ );expect(contactsService.getProfilePictureCalls, 1);},);- test('loads profile picture through linked email lookup', () async {- contactsService = FakeContactsService(- localContacts: const [- contacts.ContactRecord(- id: 'ct_1',- contactUserId: 7,- email: '[email protected]',- data: contacts.ContactData(contactUserId: 7, name: 'Alice'),- profilePictureAttachmentId: 'att_1',- isDeleted: false,- createdAt: 1,- updatedAt: 2,- ),- ],- );- contactsService.profilePictureBytesByContactId['ct_1'] = Uint8List.fromList(- [4, 5, 6],- );- service = PhotosContactsService.forTesting(- contactsService: contactsService,- );-- await service.debugOpenAndSync(session);-- final contact = await service.getContact(email: '[email protected]');- expect(contact?.id, 'ct_1');- expect(- await service.getProfilePictureBytesByUserId(contact!.contactUserId),- Uint8List.fromList([4, 5, 6]),- );- expect(- service.getCachedProfilePictureBytesByUserId(7),- Uint8List.fromList([4, 5, 6]),- );- expect(contactsService.getProfilePictureCalls, 1);- });-test('logout event clears hydrated contact cache immediately', () async {await service.debugOpenAndSync(session);