π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add contact person picker draft linking
Neeraj Gupta939d99a72762
diff --git a/mobile/apps/photos/lib/l10n/intl_en.arb b/mobile/apps/photos/lib/l10n/intl_en.arbindex c9cbbcedec..67c9a779c0 100644--- a/mobile/apps/photos/lib/l10n/intl_en.arb+++ b/mobile/apps/photos/lib/l10n/intl_en.arb@@ -1863,6 +1863,7 @@"editContact": "Edit contact","autoFetchFromPeople": "Auto-fetch from people","useTheirNameAndPhoto": "Use their name and photo",+ "personAlreadyLinkedToAnotherContact": "This person is already linked to another contact.","savePerson": "Save person","saveContact": "Save contact","editPerson": "Edit person",@@ -2395,6 +2396,8 @@"@linkEmailToContactBannerCaption": {"description": "Caption for the 'Link email' title. It should be a continuation of the 'Link email' title. Just like how 'Link email' + 'for faster sharing' forms a proper sentence in English, the combination of these two strings should also be a proper sentence in other languages."},+ "selectPerson": "Select person",+ "selectPersonToLinkToThisContact": "Select a person to link to this contact","selectPersonToLink": "Select person to link","linkPersonToEmail": "Link person to {email}","@linkPersonToEmail": {diff --git a/mobile/apps/photos/lib/models/ml/face/person.dart b/mobile/apps/photos/lib/models/ml/face/person.dartindex e3c2e87dc0..6baeddc464 100644--- a/mobile/apps/photos/lib/models/ml/face/person.dart+++ b/mobile/apps/photos/lib/models/ml/face/person.dart@@ -85,8 +85,8 @@ class PersonData {bool? hideFromMemories,int? version,Object? birthDate = _personDataUnchanged,- String? email,- int? userID,+ Object? email = _personDataUnchanged,+ Object? userID = _personDataUnchanged,List<String>? rejectedFaceIDs,List<int>? manuallyAssigned,}) {@@ -100,8 +100,12 @@ class PersonData {birthDate: identical(birthDate, _personDataUnchanged)? this.birthDate: birthDate as String?,- email: email ?? this.email,- userID: userID ?? this.userID,+ email: identical(email, _personDataUnchanged)+ ? this.email+ : email as String?,+ userID: identical(userID, _personDataUnchanged)+ ? this.userID+ : userID as int?,rejectedFaceIDs:rejectedFaceIDs ?? List<String>.from(this.rejectedFaceIDs),manuallyAssigned: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.dartindex 5b4062d54a..0f1010eac1 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@@ -638,7 +638,7 @@ class PersonService {bool? hideFromMemories,int? version,Object? birthDate = _attributeNotProvided,- String? email,+ Object? email = _attributeNotProvided,}) async {final person = (await getPerson(id))!;var updatedData = person.data.copyWith(@@ -648,11 +648,13 @@ class PersonService {isPinned: isPinned,hideFromMemories: hideFromMemories,version: version,- email: email,);if (!identical(birthDate, _attributeNotProvided)) {updatedData = updatedData.copyWith(birthDate: birthDate as String?);}+ if (!identical(email, _attributeNotProvided)) {+ updatedData = updatedData.copyWith(email: email as String?);+ }final updatedPerson = person.copyWith(data: updatedData);await updatePerson(updatedPerson);await refreshPersonCache();@@ -666,6 +668,20 @@ class PersonService {return updatedPerson;}+ Future<PersonEntity> updateContactLink(+ String id, {+ required int? userID,+ required String? email,+ }) async {+ final person = (await getPerson(id))!;+ final updatedPerson = person.copyWith(+ data: person.data.copyWith(userID: userID, email: email),+ );+ await updatePerson(updatedPerson);+ await refreshPersonCache();+ return updatedPerson;+ }+Future<ManualPersonAssignmentResult> addManualFileAssignments({required String personID,required Set<int> fileIDs,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.dartnew file mode 100644index 0000000000..1c74c5ddfc--- /dev/null+++ b/mobile/apps/photos/lib/ui/viewer/search/result/contact_person_picker_page.dart@@ -0,0 +1,280 @@+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";+import "package:photos/utils/person_contact_linking_util.dart";++abstract class ContactPersonPickerResult {+ const ContactPersonPickerResult();+}++class ContactPersonPickerSelected extends ContactPersonPickerResult {+ const ContactPersonPickerSelected(this.person);++ final PersonEntity person;+}++class ContactPersonPickerPickPhoto extends ContactPersonPickerResult {+ const ContactPersonPickerPickPhoto();+}++class ContactPersonPickerUnlink extends ContactPersonPickerResult {+ const ContactPersonPickerUnlink();+}++class ContactPersonPickerPage extends StatefulWidget {+ const ContactPersonPickerPage({+ required this.contactUserId,+ required this.contactEmail,+ required this.linkedPerson,+ super.key,+ });++ final int contactUserId;+ final String contactEmail;+ final PersonEntity? linkedPerson;++ @override+ State<ContactPersonPickerPage> createState() =>+ _ContactPersonPickerPageState();+}++class _ContactPersonPickerPageState extends State<ContactPersonPickerPage> {+ 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;+ final l10n = AppLocalizations.of(context);++ return Scaffold(+ backgroundColor: colors.backgroundBase,+ 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!);+ },+ ),+ ],+ ),+ );+ }++ Widget _buildHeader(BuildContext context, AppLocalizations l10n) {+ final colors = context.componentColors;+ final topPadding = MediaQuery.paddingOf(context).top;+ final linkedPerson = widget.linkedPerson;++ return Padding(+ padding: EdgeInsets.fromLTRB(+ _horizontalPadding,+ topPadding + 24,+ _horizontalPadding,+ 20,+ ),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ l10n.selectPerson,+ style: TextStyles.h1Bold.copyWith(+ color: colors.textBase,+ height: 1.12,+ ),+ ),+ const SizedBox(height: 8),+ Text(+ l10n.selectPersonToLinkToThisContact,+ style: TextStyles.body.copyWith(color: colors.textLight),+ ),+ ],+ ),+ ),+ const SizedBox(width: Spacing.md),+ IconButtonComponent(+ variant: IconButtonComponentVariant.primary,+ shouldSurfaceExecutionStates: false,+ tooltip: linkedPerson == null+ ? l10n.setAContactPhoto+ : l10n.removeLink,+ icon: HugeIcon(+ icon: linkedPerson == null+ ? HugeIcons.strokeRoundedImageAdd02+ : HugeIcons.strokeRoundedCancel01,+ ),+ onTap: () {+ Navigator.of(context).pop(+ linkedPerson == null+ ? const ContactPersonPickerPickPhoto()+ : const ContactPersonPickerUnlink(),+ );+ },+ ),+ ],+ ),+ );+ }++ Widget _buildGrid(List<PersonEntity> persons) {+ return SliverPadding(+ padding: const EdgeInsets.fromLTRB(+ _horizontalPadding,+ 0,+ _horizontalPadding,+ 48,+ ),+ sliver: SliverLayoutBuilder(+ builder: (context, constraints) {+ const crossAxisCount = 3;+ final tileSize =+ (constraints.crossAxisExtent -+ (_gridGap * (crossAxisCount - 1))) /+ crossAxisCount;+ return SliverGrid(+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(+ crossAxisCount: crossAxisCount,+ mainAxisSpacing: 20,+ crossAxisSpacing: _gridGap,+ childAspectRatio: tileSize / (tileSize + 30),+ ),+ delegate: SliverChildBuilderDelegate(+ childCount: persons.length,+ (context, index) => _PersonTile(+ person: persons[index],+ size: tileSize,+ contactUserId: widget.contactUserId,+ contactEmail: widget.contactEmail,+ ),+ ),+ );+ },+ ),+ );+ }+}++class _PersonTile extends StatelessWidget {+ const _PersonTile({+ required this.person,+ required this.size,+ required this.contactUserId,+ required this.contactEmail,+ });++ final PersonEntity person;+ final double size;+ final int contactUserId;+ final String contactEmail;++ @override+ Widget build(BuildContext context) {+ final colors = context.componentColors;+ final pixelWidth = (size * MediaQuery.devicePixelRatioOf(context)).round();++ return GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ if (isLinkedToDifferentContact(+ person,+ contactUserId: contactUserId,+ email: contactEmail,+ )) {+ showShortToast(+ context,+ AppLocalizations.of(context).personAlreadyLinkedToAnotherContact,+ );+ return;+ }+ Navigator.of(context).pop(ContactPersonPickerSelected(person));+ },+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.center,+ children: [+ SizedBox.square(+ dimension: size,+ child: FaceThumbnailSquircleClip(+ borderRadius: faceThumbnailSquircleBorderRadius(size),+ child: ColoredBox(+ color: colors.strokeFaint,+ child: PersonFaceWidget(+ personId: person.remoteID,+ keepAlive: true,+ cachedPixelWidth: pixelWidth,+ ),+ ),+ ),+ ),+ const SizedBox(height: 6),+ Text(+ person.data.name,+ maxLines: 1,+ textAlign: TextAlign.center,+ overflow: TextOverflow.ellipsis,+ style: TextStyles.body.copyWith(+ color: colors.textBase,+ height: 20 / 14,+ ),+ ),+ ],+ ),+ );+ }+}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 ecf0fff890..ab09219e0f 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@@ -6,8 +6,12 @@ import "package:ente_pure_utils/ente_pure_utils.dart";import "package:flutter/material.dart";import "package:hugeicons/hugeicons.dart";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";import "package:photos/theme/ente_theme.dart";import "package:photos/ui/common/loading_widget.dart";@@ -16,10 +20,12 @@ import "package:photos/ui/components/buttons/button_widget.dart";import "package:photos/ui/components/models/button_type.dart";import "package:photos/ui/notification/toast.dart";import "package:photos/ui/viewer/people/face_thumbnail_squircle.dart";+import "package:photos/ui/viewer/search/result/contact_person_picker_page.dart";import "package:photos/ui/viewer/search/result/contact_photo_adjust_page.dart";import "package:photos/ui/viewer/search/result/contact_photo_picker_sheet.dart";import "package:photos/utils/contact_photo_util.dart";import "package:photos/utils/dialog_util.dart";+import "package:photos/utils/person_contact_linking_util.dart";import "package:photos/utils/thumbnail_util.dart";class EditContactPage extends StatefulWidget {@@ -51,6 +57,10 @@ class _EditContactPageState extends State<EditContactPage> {bool _photoDirty = false;Uint8List? _draftPhotoBytes;int _photoLoadGeneration = 0;+ PersonEntity? _initialLinkedPerson;+ PersonEntity? _draftLinkedPerson;+ bool _linkDirty = false;+ bool _unlinkDraft = false;@overridevoid initState() {@@ -70,6 +80,7 @@ class _EditContactPageState extends State<EditContactPage> {});_birthDateToPreserve = widget.existingContact?.data?.birthDate;_loadExistingPhoto();+ _loadLinkedPersonDraft();}@override@@ -82,7 +93,7 @@ class _EditContactPageState extends State<EditContactPage> {bool get _canSave => !_isSaving && _nameController.text.trim().isNotEmpty;String get _initialName => (widget.existingContact?.data?.name ?? "").trim();bool get _hasUnsavedChanges =>- _nameController.text.trim() != _initialName || _photoDirty;+ _nameController.text.trim() != _initialName || _photoDirty || _linkDirty;bool get _hasContactPhoto =>_draftPhotoBytes != null ||(!_photoDirty &&@@ -139,7 +150,7 @@ class _EditContactPageState extends State<EditContactPage> {width: _avatarSize,height: _avatarSize,child: GestureDetector(- onTap: _pickContactPhoto,+ onTap: _openAvatarEditor,child: Stack(clipBehavior: Clip.none,children: [@@ -149,7 +160,7 @@ class _EditContactPageState extends State<EditContactPage> {bottom: 0,child: _AvatarEditButton(size: _editBadgeSize,- onTap: _pickContactPhoto,+ onTap: _openAvatarEditor,),),],@@ -260,6 +271,143 @@ class _EditContactPageState extends State<EditContactPage> {});}+ Future<void> _loadLinkedPersonDraft() async {+ try {+ final linkedPerson = await findPersonLinkedToContact(+ contactUserId: widget.contactUserId,+ email: widget.email,+ );+ if (!mounted || linkedPerson == null) {+ return;+ }++ final needsContactLinkUpdate =+ linkedPerson.data.userID != widget.contactUserId ||+ !contactLinkEmailMatches(linkedPerson.data.email, widget.email);+ final shouldPrefillFromPerson = widget.existingContact == null;+ if (shouldPrefillFromPerson && _nameController.text.trim().isEmpty) {+ _nameController.text = linkedPerson.data.name;+ }+ setState(() {+ _initialLinkedPerson = linkedPerson;+ _draftLinkedPerson = linkedPerson;+ _unlinkDraft = false;+ _linkDirty = needsContactLinkUpdate;+ });++ if (shouldPrefillFromPerson && !_photoDirty && _draftPhotoBytes == null) {+ await _loadPersonPhotoDraft(linkedPerson, showError: false);+ }+ } catch (e, s) {+ _logger.warning("Failed to load linked person for contact", e, s);+ }+ }++ Future<void> _openAvatarEditor() async {+ if (_isSaving) {+ return;+ }+ List<PersonEntity> persons;+ try {+ persons = await PersonService.instance.getPersons();+ } catch (e, s) {+ _logger.warning(+ "Failed to load people before editing contact photo",+ e,+ s,+ );+ await _pickContactPhoto();+ return;+ }+ if (!mounted) {+ return;+ }+ if (persons.where((person) => !person.data.isIgnored).isEmpty) {+ await _pickContactPhoto();+ return;+ }++ final result = await routeToPage(+ context,+ ContactPersonPickerPage(+ contactUserId: widget.contactUserId,+ contactEmail: widget.email,+ linkedPerson: _unlinkDraft ? null : _draftLinkedPerson,+ ),+ );+ if (!mounted || result == null) {+ return;+ }+ if (result is ContactPersonPickerPickPhoto) {+ await _pickContactPhoto();+ return;+ }+ if (result is ContactPersonPickerUnlink) {+ setState(() {+ _draftLinkedPerson = null;+ _unlinkDraft = true;+ _linkDirty = _initialLinkedPerson != null;+ });+ return;+ }+ if (result is ContactPersonPickerSelected) {+ await _draftSelectedPerson(result.person);+ }+ }++ Future<void> _draftSelectedPerson(PersonEntity person) async {+ final success = await _loadPersonPhotoDraft(person, showError: true);+ if (!success || !mounted) {+ return;+ }+ _nameController.text = person.data.name;+ setState(() {+ _draftLinkedPerson = person;+ _unlinkDraft = false;+ _linkDirty =+ _initialLinkedPerson?.remoteID != person.remoteID ||+ person.data.userID != widget.contactUserId ||+ !contactLinkEmailMatches(person.data.email, widget.email);+ });+ }++ Future<bool> _loadPersonPhotoDraft(+ PersonEntity person, {+ required bool showError,+ }) async {+ final loadGeneration = ++_photoLoadGeneration;+ setState(() {+ _isLoadingPhoto = true;+ });+ Uint8List? photoBytes;+ try {+ photoBytes = await buildContactPhotoAttachmentBytesFromPerson(person);+ } catch (e, s) {+ _logger.warning("Failed to build contact photo from person", e, s);+ }+ if (!mounted || loadGeneration != _photoLoadGeneration) {+ return false;+ }+ if (photoBytes == null) {+ setState(() {+ _isLoadingPhoto = false;+ });+ if (showError) {+ showShortToast(+ context,+ AppLocalizations.of(context).couldNotLoadSelectedPhoto,+ );+ }+ return false;+ }+ setState(() {+ _draftPhotoBytes = photoBytes;+ _isLoadingPhoto = false;+ _photoDirty = true;+ });+ return true;+ }+Future<void> _pickContactPhoto() async {final result = await showContactPhotoPickerSheet(context,@@ -340,6 +488,7 @@ class _EditContactPageState extends State<EditContactPage> {);}}+ await _savePersonLinkChanges();if (!mounted) {return;}@@ -356,6 +505,49 @@ class _EditContactPageState extends State<EditContactPage> {}}+ Future<void> _savePersonLinkChanges() async {+ final previousPerson = _initialLinkedPerson;+ final selectedPerson = _unlinkDraft ? null : _draftLinkedPerson;+ final updatedPersons = <PersonEntity>[];++ if (previousPerson != null &&+ (selectedPerson == null ||+ selectedPerson.remoteID != previousPerson.remoteID)) {+ updatedPersons.add(+ await PersonService.instance.updateContactLink(+ previousPerson.remoteID,+ userID: null,+ email: null,+ ),+ );+ }++ if (selectedPerson != null) {+ final shouldUpdateSelectedLink =+ previousPerson?.remoteID != selectedPerson.remoteID ||+ selectedPerson.data.userID != widget.contactUserId ||+ !contactLinkEmailMatches(selectedPerson.data.email, widget.email);+ if (shouldUpdateSelectedLink) {+ updatedPersons.add(+ await PersonService.instance.updateContactLink(+ selectedPerson.remoteID,+ userID: widget.contactUserId,+ email: widget.email,+ ),+ );+ }+ }++ if (updatedPersons.isNotEmpty) {+ Bus.instance.fire(+ PeopleChangedEvent(+ person: updatedPersons.last,+ source: "edit_contact_link",+ ),+ );+ }+ }+Future<ButtonAction?> _showExitConfirmationDialog(BuildContext context,) async {diff --git a/mobile/apps/photos/lib/utils/person_contact_linking_util.dart b/mobile/apps/photos/lib/utils/person_contact_linking_util.dartindex 4e014e30e7..43cecf9945 100644--- a/mobile/apps/photos/lib/utils/person_contact_linking_util.dart+++ b/mobile/apps/photos/lib/utils/person_contact_linking_util.dart@@ -7,10 +7,66 @@ import "package:photos/services/machine_learning/face_ml/person/person_service.dimport "package:photos/ui/viewer/people/people_page.dart";import "package:photos/utils/dialog_util.dart";+String? normalizeContactLinkEmail(String? email) {+ final normalized = email?.trim().toLowerCase();+ if (normalized == null || normalized.isEmpty) {+ return null;+ }+ return normalized;+}++bool contactLinkEmailMatches(String? first, String? second) {+ final normalizedFirst = normalizeContactLinkEmail(first);+ final normalizedSecond = normalizeContactLinkEmail(second);+ return normalizedFirst != null && normalizedFirst == normalizedSecond;+}++Future<PersonEntity?> findPersonLinkedToContact({+ required int contactUserId,+ required String? email,+}) async {+ final persons = await PersonService.instance.getPersons();+ final PersonEntity? userIdMatch = persons.firstWhereOrNull(+ (person) => person.data.userID == contactUserId,+ );+ if (userIdMatch != null) {+ return userIdMatch;+ }++ final normalizedEmail = normalizeContactLinkEmail(email);+ if (normalizedEmail == null) {+ return null;+ }+ return persons.firstWhereOrNull(+ (person) => contactLinkEmailMatches(person.data.email, normalizedEmail),+ );+}++bool isLinkedToDifferentContact(+ PersonEntity person, {+ required int contactUserId,+ required String? email,+}) {+ final linkedUserId = person.data.userID;+ if (linkedUserId != null && linkedUserId != contactUserId) {+ return true;+ }+ if (linkedUserId == contactUserId) {+ return false;+ }++ final linkedEmail = normalizeContactLinkEmail(person.data.email);+ if (linkedEmail == null) {+ return false;+ }+ 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 (person.data.email == email) {+ if (contactLinkEmailMatches(person.data.email, normalizedEmail)) {return true;}}@@ -23,7 +79,7 @@ Future<void> showAlreadyLinkedEmailDialog() async {final persons = await PersonService.instance.getPersons();final PersonEntity? person = persons.firstWhereOrNull(- (person) => person.data.email == email,+ (person) => contactLinkEmailMatches(person.data.email, 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.dartnew file mode 100644index 0000000000..640625c050--- /dev/null+++ b/mobile/apps/photos/test/models/ml/face/person_contact_link_test.dart@@ -0,0 +1,233 @@+import "dart:convert";++import "package:flutter_test/flutter_test.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/services/entity_service.dart";+import "package:photos/services/machine_learning/face_ml/person/person_service.dart";+import "package:photos/utils/person_contact_linking_util.dart";+import "package:shared_preferences/shared_preferences.dart";++void main() {+ group("PersonData contact link", () {+ test("copyWith preserves link fields when omitted", () {+ final data = PersonData(+ name: "Alex",+ email: "[email protected]",+ userID: 7,+ );++ final updated = data.copyWith(name: "Alex R");++ expect(updated.name, "Alex R");+ expect(updated.email, "[email protected]");+ expect(updated.userID, 7);+ });++ test("copyWith clears email and userID", () {+ final data = PersonData(+ name: "Alex",+ email: "[email protected]",+ userID: 7,+ );++ final updated = data.copyWith(email: null, userID: null);++ expect(updated.email, isNull);+ expect(updated.userID, isNull);+ });+ });++ group("PersonService contact link", () {+ late _FakeEntityService entityService;+ late PersonService personService;++ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ entityService = _FakeEntityService()+ ..seed(+ PersonEntity(+ "person-1",+ PersonData(name: "Alex", email: "[email protected]", userID: 3),+ ),+ );+ personService = _TestPersonService(+ entityService,+ _FakeMLDataDB(),+ await SharedPreferences.getInstance(),+ );+ });++ test("sets and clears contact link fields", () async {+ final linked = await personService.updateContactLink(+ "person-1",+ userID: 7,+ email: "[email protected]",+ );++ expect(linked.data.userID, 7);+ expect(linked.data.email, "[email protected]");++ final cleared = await personService.updateContactLink(+ "person-1",+ userID: null,+ email: null,+ );++ expect(cleared.data.userID, isNull);+ expect(cleared.data.email, isNull);++ final stored = await entityService.getEntity(+ EntityType.cgroup,+ "person-1",+ );+ final storedJson = jsonDecode(stored!.data) as Map<String, dynamic>;+ expect(storedJson["userID"], isNull);+ expect(storedJson["email"], isNull);+ });++ test(+ "updateAttributes preserves contact link fields when omitted",+ () async {+ final updated = await personService.updateAttributes(+ "person-1",+ name: "Alex R",+ );++ expect(updated.data.name, "Alex R");+ expect(updated.data.userID, 3);+ expect(updated.data.email, "[email protected]");+ },+ );+ });++ group("contact link conflict rules", () {+ test("prefers userID and allows the same contact", () {+ final person = PersonEntity(+ "person-1",+ PersonData(name: "Alex", userID: 7, email: "[email protected]"),+ );++ expect(+ isLinkedToDifferentContact(+ person,+ contactUserId: 7,+ email: "[email protected]",+ ),+ isFalse,+ );+ });++ test("blocks a person linked to another userID", () {+ final person = PersonEntity(+ "person-1",+ PersonData(name: "Alex", userID: 8),+ );++ expect(+ isLinkedToDifferentContact(+ person,+ contactUserId: 7,+ email: "[email protected]",+ ),+ isTrue,+ );+ });++ test("uses normalized email for legacy email-only links", () {+ final samePerson = PersonEntity(+ "person-1",+ PersonData(name: "Alex", email: "[email protected]"),+ );+ final otherPerson = PersonEntity(+ "person-2",+ PersonData(name: "Sam", email: "[email protected]"),+ );++ expect(+ isLinkedToDifferentContact(+ samePerson,+ contactUserId: 7,+ email: " [email protected] ",+ ),+ isFalse,+ );+ expect(+ isLinkedToDifferentContact(+ otherPerson,+ contactUserId: 7,+ email: "[email protected]",+ ),+ isTrue,+ );+ });+ });+}++class _TestPersonService extends PersonService {+ _TestPersonService(super.entityService, super.faceMLDataDB, super.prefs);++ @override+ Future<void> refreshPersonCache({+ bool notifyListeners = false,+ String source = "",+ }) async {}+}++class _FakeEntityService implements EntityService {+ final Map<String, LocalEntityData> _entities = {};+ int _updatedAt = 1;++ void seed(PersonEntity person) {+ _entities[person.remoteID] = LocalEntityData(+ id: person.remoteID,+ type: EntityType.cgroup,+ data: jsonEncode(person.data.toJson()),+ ownerID: 1,+ updatedAt: _updatedAt,+ );+ }++ @override+ Future<List<LocalEntityData>> getEntities(EntityType type) async {+ return _entities.values.where((entity) => entity.type == type).toList();+ }++ @override+ Future<LocalEntityData?> getEntity(EntityType type, String id) async {+ final entity = _entities[id];+ return entity?.type == type ? entity : null;+ }++ @override+ Future<LocalEntityData> addOrUpdate(+ EntityType type,+ Map<String, dynamic> jsonMap, {+ String? id,+ bool addWithCustomID = false,+ }) async {+ final entityID = id ?? "person-${_entities.length + 1}";+ final entity = LocalEntityData(+ id: entityID,+ type: type,+ data: jsonEncode(jsonMap),+ ownerID: 1,+ updatedAt: ++_updatedAt,+ );+ _entities[entityID] = entity;+ return entity;+ }++ @override+ int lastSyncTime(EntityType type) => 0;++ @override+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);+}++class _FakeMLDataDB implements MLDataDB {+ @override+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);+}