Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Simplify contact person linking

Neeraj Gupta504e6ca891bb
diff --git a/mobile/apps/photos/lib/models/ml/face/person.dart b/mobile/apps/photos/lib/models/ml/face/person.dart
index 6baeddc464..6ec819eefa 100644
--- a/mobile/apps/photos/lib/models/ml/face/person.dart
+++ b/mobile/apps/photos/lib/models/ml/face/person.dart
@@ -83,7 +83,6 @@ class PersonData {
bool? isHidden,
bool? isPinned,
bool? hideFromMemories,
- int? version,
Object? birthDate = _personDataUnchanged,
Object? email = _personDataUnchanged,
Object? userID = _personDataUnchanged,
diff --git a/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart b/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart
index 90f9f19d7e..9814f0c9d2 100644
--- a/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart
+++ b/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart
@@ -51,16 +51,10 @@ String? _savedContactName(User user) {
}
final contactUserId = _validContactUserId(user);
- final savedName = PhotosContactsService.instance
- .getCachedSavedName(
- contactUserId: contactUserId,
- email: contactUserId == null ? user.email : null,
- )
- ?.trim();
- if (savedName == null || savedName.isEmpty) {
- return null;
- }
- return savedName;
+ return PhotosContactsService.instance.getCachedSavedName(
+ contactUserId: contactUserId,
+ email: contactUserId == null ? user.email : null,
+ );
}
int? _validContactUserId(User user) {
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart
index e737b88361..997b30cab4 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart
@@ -3,6 +3,7 @@ import "dart:convert";
import "dart:developer";
import "package:computer/computer.dart";
+import "package:ente_contacts/contacts.dart" as contacts;
import "package:ente_pure_utils/ente_pure_utils.dart";
import "package:flutter/foundation.dart";
import "package:logging/logging.dart";
@@ -605,14 +606,8 @@ class PersonService {
EnteFile file,
Face face,
) async {
- if (!flagService.enableContact) {
- return;
- }
- final contact = await _contactsService.getContact(
- contactUserId: person.data.userID,
- email: person.data.email,
- );
- if (contact == null || !flagService.enableContact) {
+ final contact = await _getLinkedContactIfEnabled(person);
+ if (contact == null) {
return;
}
final Uint8List? bytes = await buildContactPhotoAttachmentBytesFromFace(
@@ -624,17 +619,12 @@ class PersonService {
"Failed to prepare contact avatar for linked person ${person.remoteID}",
);
}
- try {
- await _contactsService.setProfilePicture(
+ await _runLinkedContactWriteIfEnabled(
+ () => _contactsService.setProfilePicture(
contactId: contact.id,
bytes: bytes,
- );
- } on StateError {
- if (!flagService.enableContact) {
- return;
- }
- rethrow;
- }
+ ),
+ );
}
Future<PersonEntity> updateAttributes(
@@ -644,7 +634,6 @@ class PersonService {
bool? isHidden,
bool? isPinned,
bool? hideFromMemories,
- int? version,
Object? birthDate = _attributeNotProvided,
Object? email = _attributeNotProvided,
Object? userID = _attributeNotProvided,
@@ -664,7 +653,6 @@ class PersonService {
isHidden: isHidden,
isPinned: isPinned,
hideFromMemories: hideFromMemories,
- version: version,
);
if (!identical(birthDate, _attributeNotProvided)) {
updatedData = updatedData.copyWith(birthDate: birthDate as String?);
@@ -692,22 +680,43 @@ class PersonService {
PersonEntity person,
String name,
) async {
- if (!flagService.enableContact) {
+ final contact = await _getLinkedContactIfEnabled(person);
+ if (contact == null) {
return;
}
+ await _runLinkedContactWriteIfEnabled(
+ () => _contactsService.createOrUpdateContact(
+ contactUserId: contact.contactUserId,
+ name: name,
+ birthDate: contact.data?.birthDate,
+ ),
+ );
+ }
+
+ Future<contacts.ContactRecord?> _getLinkedContactIfEnabled(
+ PersonEntity person,
+ ) async {
+ if (!flagService.enableContact) {
+ return null;
+ }
final contact = await _contactsService.getContact(
contactUserId: person.data.userID,
email: person.data.email,
);
if (contact == null || !flagService.enableContact) {
+ return null;
+ }
+ return contact;
+ }
+
+ Future<void> _runLinkedContactWriteIfEnabled(
+ Future<void> Function() write,
+ ) async {
+ if (!flagService.enableContact) {
return;
}
try {
- await _contactsService.createOrUpdateContact(
- contactUserId: contact.contactUserId,
- name: name,
- birthDate: contact.data?.birthDate,
- );
+ await write();
} on StateError {
if (!flagService.enableContact) {
return;
@@ -716,19 +725,6 @@ class PersonService {
}
}
- Future<PersonEntity> updateContactLink(
- String id, {
- required int? userID,
- required String? email,
- }) async {
- return updateAttributes(
- id,
- userID: userID,
- email: email,
- syncLinkedContactName: false,
- );
- }
-
Future<ManualPersonAssignmentResult> addManualFileAssignments({
required String personID,
required Set<int> fileIDs,
diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dart
index 78590387c9..e5b5c3305a 100644
--- a/mobile/apps/photos/lib/services/photos_contacts_service.dart
+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart
@@ -33,7 +33,6 @@ class PhotosContactsService {
final _logger = Logger("PhotosContactsService");
final Map<int, contacts.ContactRecord> _contactsByUserId = {};
final Map<String, contacts.ContactRecord> _contactsByNormalizedEmail = {};
- final Map<int, String?> _normalizedEmailByUserId = {};
final Map<int, Uint8List?> _profilePictureBytesByUserId = {};
final Set<int> _resolvedProfilePictureUserIds = {};
final Map<int, Future<Uint8List?>> _profilePictureLoadsByUserId = {};
@@ -132,10 +131,6 @@ class PhotosContactsService {
}, description: "load contact for user $contactUserId");
}
- contacts.ContactRecord? getCachedContactByUserId(int? contactUserId) {
- return _getCachedContact(contactUserId: contactUserId);
- }
-
contacts.ContactRecord? getCachedContact({
int? contactUserId,
String? email,
@@ -143,10 +138,6 @@ class PhotosContactsService {
return _getCachedContact(contactUserId: contactUserId, email: email);
}
- String? getCachedSavedNameByUserId(int? contactUserId) {
- return getCachedSavedName(contactUserId: contactUserId);
- }
-
String? getCachedSavedName({int? contactUserId, String? email}) {
final savedName = getCachedContact(
contactUserId: contactUserId,
@@ -159,10 +150,6 @@ class PhotosContactsService {
return trimmed.isEmpty ? null : trimmed;
}
- String? getCachedResolvedEmailByUserId(int? contactUserId) {
- return getCachedResolvedEmail(contactUserId: contactUserId);
- }
-
String? getCachedResolvedEmail({int? contactUserId, String? email}) {
final resolved = getCachedContact(
contactUserId: contactUserId,
@@ -176,14 +163,10 @@ class PhotosContactsService {
}
Uint8List? getCachedProfilePictureBytesByUserId(int? contactUserId) {
- if (_sessionKey == null) {
+ if (!hasResolvedProfilePictureByUserId(contactUserId)) {
return null;
}
- if (contactUserId == null ||
- !_resolvedProfilePictureUserIds.contains(contactUserId)) {
- return null;
- }
- return _profilePictureBytesByUserId[contactUserId];
+ return _profilePictureBytesByUserId[contactUserId!];
}
bool hasResolvedProfilePictureByUserId(int? contactUserId) {
@@ -483,24 +466,20 @@ class PhotosContactsService {
void _cacheContact(contacts.ContactRecord contact) {
final userId = contact.contactUserId;
final existing = _contactsByUserId[userId];
- final previousEmail = _normalizedEmailByUserId[userId];
+ final previousEmail = _normalizeEmail(existing?.email);
if (previousEmail != null &&
_contactsByNormalizedEmail[previousEmail]?.contactUserId == userId) {
_contactsByNormalizedEmail.remove(previousEmail);
}
if (contact.isDeleted) {
_contactsByUserId.remove(userId);
- _normalizedEmailByUserId.remove(userId);
_invalidateProfilePictureCache(userId);
return;
}
_contactsByUserId[userId] = contact;
final normalizedEmail = _normalizeEmail(contact.email);
- if (normalizedEmail == null) {
- _normalizedEmailByUserId.remove(userId);
- } else {
+ if (normalizedEmail != null) {
_contactsByNormalizedEmail[normalizedEmail] = contact;
- _normalizedEmailByUserId[userId] = normalizedEmail;
}
if (existing?.profilePictureAttachmentId !=
contact.profilePictureAttachmentId) {
@@ -512,7 +491,6 @@ class PhotosContactsService {
final hadCachedContacts = _contactsByUserId.isNotEmpty;
_contactsByUserId.clear();
_contactsByNormalizedEmail.clear();
- _normalizedEmailByUserId.clear();
_profilePictureBytesByUserId.clear();
_resolvedProfilePictureUserIds.clear();
_profilePictureLoadsByUserId.clear();
diff --git a/mobile/apps/photos/lib/ui/social/social_actor_contact_navigation.dart b/mobile/apps/photos/lib/ui/social/social_actor_contact_navigation.dart
index 16722d8ae1..bd959bc802 100644
--- a/mobile/apps/photos/lib/ui/social/social_actor_contact_navigation.dart
+++ b/mobile/apps/photos/lib/ui/social/social_actor_contact_navigation.dart
@@ -71,7 +71,7 @@ Future<Widget?> _buildDestination(
required String email,
}) async {
final contactsService = PhotosContactsService.instance;
- final cachedContact = contactsService.getCachedContactByUserId(userId);
+ final cachedContact = contactsService.getCachedContact(contactUserId: userId);
if (cachedContact != null) {
return _contactResultPageForUser(user);
}
@@ -88,7 +88,7 @@ Future<Widget?> _buildDestination(
}
}
- final savedContact = contactsService.getCachedContactByUserId(userId);
+ final savedContact = contactsService.getCachedContact(contactUserId: userId);
if (savedContact != null) {
return _contactResultPageForUser(user);
}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/link_email_screen.dart b/mobile/apps/photos/lib/ui/viewer/people/link_email_screen.dart
index 875af6c9be..03f0d27ac4 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/link_email_screen.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/link_email_screen.dart
@@ -315,8 +315,13 @@ class _LinkEmailScreen extends State<LinkEmailScreen> {
String personID,
BuildContext context,
) async {
- if (await checkIfEmailAlreadyAssignedToAPerson(email)) {
- await showAlreadyLinkedEmailDialog(context, email);
+ final linkedPerson = await findPersonLinkedToEmail(email);
+ if (linkedPerson != null) {
+ await showAlreadyLinkedEmailDialog(
+ context,
+ email,
+ linkedPerson: linkedPerson,
+ );
return false;
}
@@ -359,7 +364,7 @@ class _LinkEmailScreen extends State<LinkEmailScreen> {
try {
final personEntity = await PersonService.instance.getPerson(personID);
late final PersonEntity updatedPerson;
- final currentUserID = _currentUserIDForEmail(email);
+ final currentUserID = currentUserIDForContactLinkEmail(email);
if (personEntity == null) {
throw AssertionError(
@@ -394,14 +399,3 @@ class _LinkEmailScreen extends State<LinkEmailScreen> {
}
}
}
-
-bool _matchesCurrentUserEmail(String email) {
- final currentEmail = Configuration.instance.getEmail()?.trim().toLowerCase();
- return currentEmail != null && email.trim().toLowerCase() == currentEmail;
-}
-
-int? _currentUserIDForEmail(String email) {
- return _matchesCurrentUserEmail(email)
- ? Configuration.instance.getUserID()
- : null;
-}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/people_util.dart b/mobile/apps/photos/lib/ui/viewer/people/people_util.dart
index e018a8209d..5446737997 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/people_util.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/people_util.dart
@@ -1,22 +1,12 @@
-import "package:photos/core/configuration.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
+import "package:photos/utils/person_contact_linking_util.dart";
Future<bool> isMeAssigned() async {
final personEntities = await PersonService.instance.getPersons();
- final currentUserEmail = Configuration.instance
- .getEmail()
- ?.trim()
- .toLowerCase();
- final currentUserID = Configuration.instance.getUserID();
-
- bool isAssigned = false;
- for (final personEntity in personEntities) {
- final personEmail = personEntity.data.email?.trim().toLowerCase();
- if ((currentUserEmail != null && personEmail == currentUserEmail) ||
- (currentUserID != null && personEntity.data.userID == currentUserID)) {
- isAssigned = true;
- break;
- }
- }
- return isAssigned;
+ return personEntities.any(
+ (person) => isCurrentUserContactLink(
+ email: person.data.email,
+ userID: person.data.userID,
+ ),
+ );
}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/person_selection_action_widgets.dart b/mobile/apps/photos/lib/ui/viewer/people/person_selection_action_widgets.dart
index e75bd5666d..42c2c7d7d7 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/person_selection_action_widgets.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/person_selection_action_widgets.dart
@@ -33,14 +33,10 @@ import "package:photos/utils/dialog_util.dart";
import "package:photos/utils/people_sort_util.dart";
import "package:photos/utils/person_contact_linking_util.dart";
-enum PersonSelectionMode { linkContact, autofillContact }
-
class LinkContactToPersonSelectionPage extends StatefulWidget {
- final String? emailToLink;
- final PersonSelectionMode mode;
+ final String emailToLink;
const LinkContactToPersonSelectionPage({
- this.emailToLink,
- this.mode = PersonSelectionMode.linkContact,
+ required this.emailToLink,
super.key,
});
@@ -96,7 +92,7 @@ class _LinkContactToPersonSelectionPageState
if (person.data.isIgnored) {
continue;
}
- if (widget.mode == PersonSelectionMode.linkContact && isAlreadyLinked) {
+ if (isAlreadyLinked) {
continue;
}
final searchResult = resultsById[person.remoteID];
@@ -329,17 +325,10 @@ class _LinkContactToPersonSelectionPageState
return _RoundedPersonFaceWidget(
key: ValueKey(results[index].personEntity.remoteID),
onTap: () async {
- if (widget.mode ==
- PersonSelectionMode.autofillContact) {
- Navigator.of(
- context,
- ).pop(results[index].personEntity);
- return;
- }
try {
final updatedPerson = await linkPersonToContact(
context,
- emailToLink: widget.emailToLink!,
+ emailToLink: widget.emailToLink,
personEntity: results[index].personEntity,
);
@@ -522,8 +511,13 @@ class _LinkContactToPersonSelectionPageState
required String emailToLink,
required PersonEntity personEntity,
}) async {
- if (await checkIfEmailAlreadyAssignedToAPerson(emailToLink)) {
- await showAlreadyLinkedEmailDialog(context, emailToLink);
+ final linkedPerson = await findPersonLinkedToEmail(emailToLink);
+ if (linkedPerson != null) {
+ await showAlreadyLinkedEmailDialog(
+ context,
+ emailToLink,
+ linkedPerson: linkedPerson,
+ );
return null;
}
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.dart
index b3e88f23d7..1a8a1ffa89 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
@@ -66,20 +66,6 @@ String? _trimEmptyToNull(String? value) {
return trimmedValue;
}
-bool _matchesCurrentUserEmail(String? email) {
- final currentEmail = _trimEmptyToNull(Configuration.instance.getEmail());
- final candidateEmail = _trimEmptyToNull(email);
- return currentEmail != null &&
- candidateEmail != null &&
- candidateEmail.toLowerCase() == currentEmail.toLowerCase();
-}
-
-int? _currentUserIDForEmail(String? email) {
- return _matchesCurrentUserEmail(email)
- ? Configuration.instance.getUserID()
- : null;
-}
-
class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
static const int _maxSuggestedPersons = 3;
bool isKeypadOpen = false;
@@ -98,7 +84,8 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
String? get _emailToSave => _trimEmptyToNull(_email);
- int? get _currentUserIDToSave => _currentUserIDForEmail(_emailToSave);
+ int? get _currentUserIDToSave =>
+ currentUserIDForContactLinkEmail(_emailToSave);
bool get _shouldClearContactUserID =>
widget.isEditing &&
@@ -631,14 +618,19 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
String? birthdate,
String? email,
}) async {
- if (email != null &&
- email.isNotEmpty &&
- await checkIfEmailAlreadyAssignedToAPerson(email)) {
- _logger.severe(
- "Failed to addNewPerson, email is already assigned to a person",
- );
- await showAlreadyLinkedEmailDialog(context, email);
- return null;
+ if (email != null && email.isNotEmpty) {
+ final linkedPerson = await findPersonLinkedToEmail(email);
+ if (linkedPerson != null) {
+ _logger.severe(
+ "Failed to addNewPerson, email is already assigned to a person",
+ );
+ await showAlreadyLinkedEmailDialog(
+ context,
+ email,
+ linkedPerson: linkedPerson,
+ );
+ return null;
+ }
}
try {
@@ -656,7 +648,7 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
hideFromMemories: _hideFromMemories,
birthdate: birthdate,
email: email,
- userID: _currentUserIDForEmail(email),
+ userID: currentUserIDForContactLinkEmail(email),
);
final bool extraPhotosFound = await ClusterFeedbackService.instance
.checkAndDoAutomaticMerges(personEntity, personClusterID: clusterID);
@@ -692,10 +684,16 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
try {
final emailToSave = _emailToSave;
if (emailToSave != null &&
- emailToSave != _trimEmptyToNull(person!.data.email) &&
- await checkIfEmailAlreadyAssignedToAPerson(emailToSave)) {
- await showAlreadyLinkedEmailDialog(context, emailToSave);
- return null;
+ emailToSave != _trimEmptyToNull(person!.data.email)) {
+ final linkedPerson = await findPersonLinkedToEmail(emailToSave);
+ if (linkedPerson != null) {
+ await showAlreadyLinkedEmailDialog(
+ context,
+ emailToSave,
+ linkedPerson: linkedPerson,
+ );
+ return null;
+ }
}
final String name = _inputName.trim();
final String? birthDate = _selectedDate;
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/contact_person_picker_page.dart b/mobile/apps/photos/lib/ui/viewer/search/result/contact_person_picker_page.dart
index 22e2047714..fa87f777f1 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/result/contact_person_picker_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/contact_person_picker_page.dart
@@ -1,11 +1,8 @@
-import "package:collection/collection.dart";
import "package:ente_components/ente_components.dart";
import "package:flutter/material.dart";
import "package:hugeicons/hugeicons.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/ml/face/person.dart";
-import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
-import "package:photos/ui/common/loading_widget.dart";
import "package:photos/ui/notification/toast.dart";
import "package:photos/ui/viewer/people/face_thumbnail_squircle.dart";
import "package:photos/ui/viewer/people/person_face_widget.dart";
@@ -25,51 +22,20 @@ class ContactPersonPickerPickPhoto extends ContactPersonPickerResult {
const ContactPersonPickerPickPhoto();
}
-class ContactPersonPickerPage extends StatefulWidget {
+class ContactPersonPickerPage extends StatelessWidget {
const ContactPersonPickerPage({
required this.contactUserId,
required this.contactEmail,
+ required this.persons,
super.key,
});
final int contactUserId;
final String contactEmail;
-
- @override
- State<ContactPersonPickerPage> createState() =>
- _ContactPersonPickerPageState();
-}
-
-class _ContactPersonPickerPageState extends State<ContactPersonPickerPage> {
+ final List<PersonEntity> persons;
static const _horizontalPadding = 16.0;
static const _gridGap = 10.0;
- late final Future<List<PersonEntity>> _personsFuture;
-
- @override
- void initState() {
- super.initState();
- _personsFuture = _loadPersons();
- }
-
- Future<List<PersonEntity>> _loadPersons() async {
- final persons = await PersonService.instance.getPersons();
- final visiblePersons = persons
- .where((person) => !person.data.isIgnored)
- .toList();
- visiblePersons.sort((first, second) {
- final nameComparison = compareAsciiLowerCaseNatural(
- first.data.name,
- second.data.name,
- );
- if (nameComparison != 0) {
- return nameComparison;
- }
- return first.remoteID.compareTo(second.remoteID);
- });
- return visiblePersons;
- }
-
@override
Widget build(BuildContext context) {
final colors = context.componentColors;
@@ -80,28 +46,18 @@ class _ContactPersonPickerPageState extends State<ContactPersonPickerPage> {
body: CustomScrollView(
slivers: [
SliverToBoxAdapter(child: _buildHeader(context, l10n)),
- FutureBuilder<List<PersonEntity>>(
- future: _personsFuture,
- builder: (context, snapshot) {
- if (snapshot.connectionState == ConnectionState.waiting) {
- return const SliverFillRemaining(
- child: Center(child: EnteLoadingWidget()),
- );
- }
- if (!snapshot.hasData || snapshot.data!.isEmpty) {
- return SliverFillRemaining(
- hasScrollBody: false,
- child: Center(
- child: Text(
- "${l10n.noResultsFound}.",
- style: TextStyles.body.copyWith(color: colors.textLight),
- ),
- ),
- );
- }
- return _buildGrid(snapshot.data!);
- },
- ),
+ if (persons.isEmpty)
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(
+ child: Text(
+ "${l10n.noResultsFound}.",
+ style: TextStyles.body.copyWith(color: colors.textLight),
+ ),
+ ),
+ )
+ else
+ _buildGrid(persons),
],
),
);
@@ -182,8 +138,8 @@ class _ContactPersonPickerPageState extends State<ContactPersonPickerPage> {
(context, index) => _PersonTile(
person: persons[index],
size: tileSize,
- contactUserId: widget.contactUserId,
- contactEmail: widget.contactEmail,
+ contactUserId: contactUserId,
+ contactEmail: contactEmail,
),
),
);
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.dart
index ad9947674b..e4ef315446 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,29 +49,20 @@ class _ContactPhotoPickerSheet extends StatefulWidget {
}
class _ContactPhotoPickerSheetState extends State<_ContactPhotoPickerSheet> {
- late final ValueNotifier<bool> _isFileSelected;
late final SelectedFiles _selectedFiles;
@override
void initState() {
super.initState();
- _isFileSelected = ValueNotifier(false);
- _selectedFiles = SelectedFiles()..addListener(_handleSelectionChanged);
+ _selectedFiles = SelectedFiles();
}
@override
void dispose() {
- _selectedFiles
- ..removeListener(_handleSelectionChanged)
- ..dispose();
- _isFileSelected.dispose();
+ _selectedFiles.dispose();
super.dispose();
}
- void _handleSelectionChanged() {
- _isFileSelected.value = _selectedFiles.files.isNotEmpty;
- }
-
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
@@ -119,17 +110,18 @@ class _ContactPhotoPickerSheetState extends State<_ContactPhotoPickerSheet> {
Spacing.xl,
Spacing.xl,
),
- child: ValueListenableBuilder<bool>(
- valueListenable: _isFileSelected,
- builder: (context, value, _) {
+ child: ListenableBuilder(
+ listenable: _selectedFiles,
+ builder: (context, _) {
+ final isFileSelected = _selectedFiles.files.isNotEmpty;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
ButtonComponent(
label: l10n.setSelectedPhoto,
- isDisabled: !value,
+ isDisabled: !isFileSelected,
shouldSurfaceExecutionStates: false,
- onTap: value
+ onTap: isFileSelected
? () {
Navigator.pop(
context,
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.dart
index bf00f3fac1..48cde091b0 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
@@ -1,5 +1,6 @@
import "dart:typed_data";
+import "package:collection/collection.dart";
import "package:ente_components/ente_components.dart";
import "package:ente_contacts/contacts.dart" as contacts;
import "package:ente_pure_utils/ente_pure_utils.dart";
@@ -9,7 +10,6 @@ import "package:logging/logging.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/events/people_changed_event.dart";
import "package:photos/generated/l10n.dart";
-import "package:photos/models/file/file.dart";
import "package:photos/models/ml/face/person.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
import "package:photos/services/photos_contacts_service.dart";
@@ -286,9 +286,9 @@ class _EditContactPageState extends State<EditContactPage> {
return;
}
- final needsContactLinkUpdate =
- linkedPerson.data.userID != widget.contactUserId ||
- !contactLinkEmailMatches(linkedPerson.data.email, widget.email);
+ final needsContactLinkUpdate = _personNeedsContactLinkUpdate(
+ linkedPerson,
+ );
final shouldPrefillFromPerson = widget.existingContact == null;
if (shouldPrefillFromPerson && _nameController.text.trim().isEmpty) {
_nameController.text = linkedPerson.data.name;
@@ -327,7 +327,19 @@ class _EditContactPageState extends State<EditContactPage> {
if (!mounted) {
return;
}
- if (persons.where((person) => !person.data.isIgnored).isEmpty) {
+ final visiblePersons =
+ persons.where((person) => !person.data.isIgnored).toList()
+ ..sort((first, second) {
+ final nameComparison = compareAsciiLowerCaseNatural(
+ first.data.name,
+ second.data.name,
+ );
+ if (nameComparison != 0) {
+ return nameComparison;
+ }
+ return first.remoteID.compareTo(second.remoteID);
+ });
+ if (visiblePersons.isEmpty) {
await _pickContactPhoto();
return;
}
@@ -337,6 +349,7 @@ class _EditContactPageState extends State<EditContactPage> {
ContactPersonPickerPage(
contactUserId: widget.contactUserId,
contactEmail: widget.email,
+ persons: visiblePersons,
),
);
if (!mounted || result == null) {
@@ -359,6 +372,11 @@ class _EditContactPageState extends State<EditContactPage> {
});
}
+ bool _personNeedsContactLinkUpdate(PersonEntity person) {
+ return person.data.userID != widget.contactUserId ||
+ !contactLinkEmailMatches(person.data.email, widget.email);
+ }
+
Future<void> _draftSelectedPerson(PersonEntity person) async {
final success = await _loadPersonPhotoDraft(person, showError: true);
if (!success || !mounted) {
@@ -370,8 +388,7 @@ class _EditContactPageState extends State<EditContactPage> {
_unlinkDraft = false;
_linkDirty =
_initialLinkedPerson?.remoteID != person.remoteID ||
- person.data.userID != widget.contactUserId ||
- !contactLinkEmailMatches(person.data.email, widget.email);
+ _personNeedsContactLinkUpdate(person);
});
}
@@ -433,7 +450,7 @@ class _EditContactPageState extends State<EditContactPage> {
setState(() {
_isLoadingPhoto = true;
});
- final sourceBytes = await _loadEditablePhotoBytesFromFile(selectedFile);
+ final sourceBytes = await getThumbnail(selectedFile);
if (!mounted) {
return;
}
@@ -529,10 +546,11 @@ class _EditContactPageState extends State<EditContactPage> {
(selectedPerson == null ||
selectedPerson.remoteID != previousPerson.remoteID)) {
updatedPersons.add(
- await PersonService.instance.updateContactLink(
+ await PersonService.instance.updateAttributes(
previousPerson.remoteID,
userID: null,
email: null,
+ syncLinkedContactName: false,
),
);
}
@@ -540,8 +558,7 @@ class _EditContactPageState extends State<EditContactPage> {
if (selectedPerson != null) {
final shouldUpdateSelectedLink =
previousPerson?.remoteID != selectedPerson.remoteID ||
- selectedPerson.data.userID != widget.contactUserId ||
- !contactLinkEmailMatches(selectedPerson.data.email, widget.email);
+ _personNeedsContactLinkUpdate(selectedPerson);
final shouldUpdateSelectedName =
contactNameChanged &&
contactName.isNotEmpty &&
@@ -635,10 +652,6 @@ class _EditContactPageState extends State<EditContactPage> {
);
return actionResult?.action;
}
-
- Future<Uint8List?> _loadEditablePhotoBytesFromFile(EnteFile file) async {
- return getThumbnail(file);
- }
}
class _EditContactHeader extends StatelessWidget {
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.dart
index 84e5440636..c2f9028c19 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
@@ -199,34 +199,26 @@ class _ContactsSectionState extends State<ContactsSection> {
}
}
-class ContactRecommendation extends StatefulWidget {
+class ContactRecommendation extends StatelessWidget {
static const _avatarSize = 62.0;
final GenericSearchResult contactSearchResult;
const ContactRecommendation(this.contactSearchResult, {super.key});
- @override
- State<ContactRecommendation> createState() => _ContactRecommendationState();
-}
-
-class _ContactRecommendationState extends State<ContactRecommendation> {
@override
Widget build(BuildContext context) {
final colors = context.componentColors;
- final personId =
- widget.contactSearchResult.params[kPersonParamID] as String?;
- final contactUserId =
- widget.contactSearchResult.params[kContactUserId] as int?;
- final contactEmail =
- widget.contactSearchResult.params[kContactEmail] as String;
+ 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);
return GestureDetector(
onTap: () {
RecentSearches().add(displayName);
- if (widget.contactSearchResult.onResultTap != null) {
- widget.contactSearchResult.onResultTap!(context);
+ if (contactSearchResult.onResultTap != null) {
+ contactSearchResult.onResultTap!(context);
} else {
- routeToPage(context, ContactResultPage(widget.contactSearchResult));
+ routeToPage(context, ContactResultPage(contactSearchResult));
}
},
child: SizedBox(
@@ -266,7 +258,7 @@ class _ContactRecommendationState extends State<ContactRecommendation> {
final resolvedName = resolveDisplayName(contactUser);
final resolvedEmail = resolveKnownEmail(contactUser) ?? contactEmail;
if (resolvedName == resolvedEmail || resolvedName == "Someone") {
- return widget.contactSearchResult.name();
+ return contactSearchResult.name();
}
return resolvedName;
}
diff --git a/mobile/apps/photos/lib/utils/person_contact_linking_util.dart b/mobile/apps/photos/lib/utils/person_contact_linking_util.dart
index 43cecf9945..8ed0fbf814 100644
--- a/mobile/apps/photos/lib/utils/person_contact_linking_util.dart
+++ b/mobile/apps/photos/lib/utils/person_contact_linking_util.dart
@@ -1,6 +1,7 @@
import "package:collection/collection.dart";
import "package:ente_pure_utils/ente_pure_utils.dart";
import "package:flutter/widgets.dart";
+import "package:photos/core/configuration.dart";
import "package:photos/l10n/l10n.dart";
import "package:photos/models/ml/face/person.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
@@ -21,6 +22,22 @@ bool contactLinkEmailMatches(String? first, String? second) {
return normalizedFirst != null && normalizedFirst == normalizedSecond;
}
+bool isCurrentUserContactLinkEmail(String? email) {
+ return contactLinkEmailMatches(email, Configuration.instance.getEmail());
+}
+
+int? currentUserIDForContactLinkEmail(String? email) {
+ return isCurrentUserContactLinkEmail(email)
+ ? Configuration.instance.getUserID()
+ : null;
+}
+
+bool isCurrentUserContactLink({String? email, int? userID}) {
+ final currentUserID = Configuration.instance.getUserID();
+ return (currentUserID != null && userID == currentUserID) ||
+ isCurrentUserContactLinkEmail(email);
+}
+
Future<PersonEntity?> findPersonLinkedToContact({
required int contactUserId,
required String? email,
@@ -42,6 +59,17 @@ Future<PersonEntity?> findPersonLinkedToContact({
);
}
+Future<PersonEntity?> findPersonLinkedToEmail(String? email) async {
+ final normalizedEmail = normalizeContactLinkEmail(email);
+ if (normalizedEmail == null) {
+ return null;
+ }
+ final persons = await PersonService.instance.getPersons();
+ return persons.firstWhereOrNull(
+ (person) => contactLinkEmailMatches(person.data.email, normalizedEmail),
+ );
+}
+
bool isLinkedToDifferentContact(
PersonEntity person, {
required int contactUserId,
@@ -62,25 +90,12 @@ bool isLinkedToDifferentContact(
return !contactLinkEmailMatches(linkedEmail, email);
}
-Future<bool> checkIfEmailAlreadyAssignedToAPerson(String email) async {
- final persons = await PersonService.instance.getPersons();
- final normalizedEmail = normalizeContactLinkEmail(email);
- for (var person in persons) {
- if (contactLinkEmailMatches(person.data.email, normalizedEmail)) {
- return true;
- }
- }
- return false;
-}
-
Future<void> showAlreadyLinkedEmailDialog(
BuildContext context,
- String email,
-) async {
- final persons = await PersonService.instance.getPersons();
- final PersonEntity? person = persons.firstWhereOrNull(
- (person) => contactLinkEmailMatches(person.data.email, email),
- );
+ String email, {
+ PersonEntity? linkedPerson,
+}) async {
+ final person = linkedPerson ?? await findPersonLinkedToEmail(email);
if (person == null) {
return;
}
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.dart
index 6e405cd845..234e7ec556 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
@@ -102,19 +102,21 @@ void main() {
});
test("sets and clears contact link fields", () async {
- final linked = await personService.updateContactLink(
+ final linked = await personService.updateAttributes(
"person-1",
userID: 7,
+ syncLinkedContactName: false,
);
expect(linked.data.userID, 7);
expect(linked.data.email, "[email protected]");
- final cleared = await personService.updateContactLink(
+ final cleared = await personService.updateAttributes(
"person-1",
userID: null,
email: null,
+ syncLinkedContactName: false,
);
expect(cleared.data.userID, isNull);
diff --git a/mobile/apps/photos/test/services/photos_contacts_service_test.dart b/mobile/apps/photos/test/services/photos_contacts_service_test.dart
index b9019da635..bdafca23c2 100644
--- a/mobile/apps/photos/test/services/photos_contacts_service_test.dart
+++ b/mobile/apps/photos/test/services/photos_contacts_service_test.dart
@@ -65,11 +65,11 @@ void main() {
await service.debugOpenAndSync(session);
expect(service.hasHydratedCache, isTrue);
- expect(service.getCachedContactByUserId(7), isNotNull);
+ expect(service.getCachedContact(contactUserId: 7), isNotNull);
expect((await service.getContact(email: '[email protected]'))?.id, 'ct_1');
- expect(service.getCachedSavedNameByUserId(7), 'Alice');
+ expect(service.getCachedSavedName(contactUserId: 7), 'Alice');
expect(service.getCachedSavedName(email: '[email protected]'), 'Alice');
- expect(service.getCachedResolvedEmailByUserId(7), '[email protected]');
+ expect(service.getCachedResolvedEmail(contactUserId: 7), '[email protected]');
expect(
service.getCachedResolvedEmail(email: '[email protected]'),
@@ -136,16 +136,16 @@ void main() {
);
await service.debugOpenAndSync(nextSession);
- expect(service.getCachedSavedNameByUserId(9), 'Bob');
- expect(service.getCachedSavedNameByUserId(7), isNull);
+ expect(service.getCachedSavedName(contactUserId: 9), 'Bob');
+ expect(service.getCachedSavedName(contactUserId: 7), isNull);
contactsService.getContactsBarrier!.complete();
await oldOpenAndSync;
- expect(service.getCachedSavedNameByUserId(9), 'Bob');
- expect(service.getCachedResolvedEmailByUserId(9), '[email protected]');
- expect(service.getCachedSavedNameByUserId(7), isNull);
- expect(service.getCachedResolvedEmailByUserId(7), isNull);
+ expect(service.getCachedSavedName(contactUserId: 9), 'Bob');
+ expect(service.getCachedResolvedEmail(contactUserId: 9), '[email protected]');
+ expect(service.getCachedSavedName(contactUserId: 7), isNull);
+ expect(service.getCachedResolvedEmail(contactUserId: 7), isNull);
},
);
@@ -198,16 +198,16 @@ void main() {
);
await service.debugOpenAndSync(nextSession);
- expect(service.getCachedSavedNameByUserId(9), 'Bob');
- expect(service.getCachedSavedNameByUserId(7), isNull);
+ expect(service.getCachedSavedName(contactUserId: 9), 'Bob');
+ expect(service.getCachedSavedName(contactUserId: 7), isNull);
firstService.openBarrier!.complete();
await oldOpenAndSync;
expect(firstService.openCalls, 1);
expect(secondService.openCalls, 1);
- expect(service.getCachedSavedNameByUserId(9), 'Bob');
- expect(service.getCachedSavedNameByUserId(7), isNull);
+ expect(service.getCachedSavedName(contactUserId: 9), 'Bob');
+ expect(service.getCachedSavedName(contactUserId: 7), isNull);
});
test(
@@ -284,13 +284,13 @@ void main() {
test('logout event clears hydrated contact cache immediately', () async {
await service.debugOpenAndSync(session);
- expect(service.getCachedSavedNameByUserId(7), 'Alice');
+ expect(service.getCachedSavedName(contactUserId: 7), 'Alice');
Bus.instance.fire(UserLoggedOutEvent());
await Future<void>.delayed(Duration.zero);
- expect(service.getCachedSavedNameByUserId(7), isNull);
- expect(service.getCachedResolvedEmailByUserId(7), isNull);
+ expect(service.getCachedSavedName(contactUserId: 7), isNull);
+ expect(service.getCachedResolvedEmail(contactUserId: 7), isNull);
expect(service.getCachedProfilePictureBytesByUserId(7), isNull);
expect(service.hasHydratedCache, isFalse);
});