Skip to content

armgit / ente

Public Imported from GitHub
0

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

Tighten contact and person data handling

Neeraj Gupta22758b1513f3
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 dcc84cf9a1..eb2f8bee90 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
@@ -53,6 +53,8 @@ class PersonService {
static double autoMergeThreshold = kDefaultAutoMergeThreshold;
Future<List<PersonEntity>>? _cachedPersonsFuture;
+ Map<String, PersonEntity>? _cachedPersonsById;
+ int _personCacheGeneration = 0;
int _lastCacheRefreshTime = 0;
static PersonService get instance {
@@ -84,15 +86,22 @@ class PersonService {
void clearCache() {
_emailToPartialPersonDataMapCache.clear();
- _cachedPersonsFuture = null;
+ _invalidatePersonCache();
_lastCacheRefreshTime = 0;
}
+ void _invalidatePersonCache() {
+ _cachedPersonsFuture = null;
+ _cachedPersonsById = null;
+ _personCacheGeneration++;
+ }
+
Future<void> refreshPersonCache({
bool notifyListeners = false,
String source = "",
}) async {
- _lastCacheRefreshTime = 0;
+ _invalidatePersonCache();
+ _lastCacheRefreshTime = lastRemoteSyncTime();
// wait to ensure cache is refreshed
final _ = await getPersons();
if (notifyListeners) {
@@ -119,15 +128,19 @@ class PersonService {
}
Future<List<PersonEntity>> getPersons() async {
- if (_lastCacheRefreshTime != lastRemoteSyncTime()) {
- _lastCacheRefreshTime = lastRemoteSyncTime();
- _cachedPersonsFuture = null; // Invalidate cache
+ final remoteSyncTime = lastRemoteSyncTime();
+ if (_lastCacheRefreshTime != remoteSyncTime) {
+ _lastCacheRefreshTime = remoteSyncTime;
+ _invalidatePersonCache();
+ }
+ if (_cachedPersonsFuture == null) {
+ final generation = _personCacheGeneration;
+ _cachedPersonsFuture = _fetchAndCachePersons(generation);
}
- _cachedPersonsFuture ??= _fetchAndCachePersons();
return _cachedPersonsFuture!;
}
- Future<List<PersonEntity>> _fetchAndCachePersons() async {
+ Future<List<PersonEntity>> _fetchAndCachePersons(int generation) async {
logger.finest("reading all persons from local db");
final entities = await entityService.getEntities(EntityType.cgroup);
final persons = await Computer.shared().compute(
@@ -135,6 +148,12 @@ class PersonService {
param: {"entity": entities},
taskName: "decode_person_entities",
);
+ if (generation != _personCacheGeneration) {
+ return persons;
+ }
+ _cachedPersonsById = {
+ for (final person in persons) person.remoteID: person,
+ };
_emailToPartialPersonDataMapCache.clear();
for (PersonEntity person in persons) {
if (person.data.email != null && person.data.email!.isNotEmpty) {
@@ -166,13 +185,17 @@ class PersonService {
});
}
+ PersonEntity? getCachedPerson(String id) {
+ if (_lastCacheRefreshTime != lastRemoteSyncTime()) {
+ return null;
+ }
+ return _cachedPersonsById?[id];
+ }
+
Future<Map<String, PersonEntity>> getPersonsMap() async {
final persons = await getPersons();
- final Map<String, PersonEntity> map = {};
- for (var person in persons) {
- map[person.remoteID] = person;
- }
- return map;
+ return _cachedPersonsById ??
+ {for (final person in persons) person.remoteID: person};
}
Future<void> reconcileClusters() async {
@@ -685,7 +708,6 @@ class PersonService {
await _contactsService.createOrUpdateContact(
contactUserId: contact.contactUserId,
name: name,
- birthDate: contact.data?.birthDate,
);
}
@@ -767,8 +789,7 @@ class PersonService {
}) async {
final result = await entityService.addOrUpdate(type, jsonMap, id: id);
_lastCacheRefreshTime = 0; // Invalidate cache
- _cachedPersonsFuture =
- null; // Force refresh even if last sync time unchanged
+ _invalidatePersonCache();
return result;
}
diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dart
index 97e9e0746d..46decbd2a0 100644
--- a/mobile/apps/photos/lib/services/photos_contacts_service.dart
+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart
@@ -6,6 +6,7 @@ import "package:photos/core/event_bus.dart";
import "package:photos/events/contacts_changed_event.dart";
import "package:photos/events/user_logged_out_event.dart";
import "package:photos/service_locator.dart";
+import "package:photos/utils/contact_string_util.dart";
class PhotosContactsService {
PhotosContactsService._privateConstructor()
@@ -130,25 +131,17 @@ class PhotosContactsService {
}
String? getCachedSavedName({int? contactUserId, String? email}) {
- return _trimmedNonEmpty(
+ return trimToNull(
getCachedContact(contactUserId: contactUserId, email: email)?.data?.name,
);
}
String? getCachedResolvedEmail({int? contactUserId, String? email}) {
- return _trimmedNonEmpty(
+ return trimToNull(
getCachedContact(contactUserId: contactUserId, email: email)?.email,
);
}
- String? _trimmedNonEmpty(String? value) {
- if (value == null) {
- return null;
- }
- final trimmed = value.trim();
- return trimmed.isEmpty ? null : trimmed;
- }
-
Uint8List? getCachedProfilePictureBytesByUserId(int? contactUserId) {
if (!hasResolvedProfilePictureByUserId(contactUserId)) {
return null;
@@ -230,15 +223,9 @@ class PhotosContactsService {
Future<contacts.ContactRecord> createOrUpdateContact({
required int contactUserId,
required String name,
- String? birthDate,
}) async {
final contactsService = await _ensureReadyForWrite();
final trimmedName = name.trim();
- final trimmedBirthDate = birthDate?.trim();
- final normalizedBirthDate =
- trimmedBirthDate == null || trimmedBirthDate.isEmpty
- ? null
- : trimmedBirthDate;
final existing = await contactsService.getContactByUserId(
contactUserId,
includeDeleted: true,
@@ -246,7 +233,6 @@ class PhotosContactsService {
final data = contacts.ContactData(
contactUserId: contactUserId,
name: trimmedName,
- birthDate: normalizedBirthDate,
);
final contact = existing == null
? await contactsService.createContact(data)
@@ -453,7 +439,7 @@ class PhotosContactsService {
void _cacheContact(contacts.ContactRecord contact) {
final userId = contact.contactUserId;
final existing = _contactsByUserId[userId];
- final previousEmail = _normalizeEmail(existing?.email);
+ final previousEmail = normalizeContactLinkEmail(existing?.email);
if (previousEmail != null &&
_contactsByNormalizedEmail[previousEmail]?.contactUserId == userId) {
_contactsByNormalizedEmail.remove(previousEmail);
@@ -464,7 +450,7 @@ class PhotosContactsService {
return;
}
_contactsByUserId[userId] = contact;
- final normalizedEmail = _normalizeEmail(contact.email);
+ final normalizedEmail = normalizeContactLinkEmail(contact.email);
if (normalizedEmail != null) {
_contactsByNormalizedEmail[normalizedEmail] = contact;
}
@@ -522,7 +508,7 @@ class PhotosContactsService {
}
contacts.ContactRecord? _contactByEmailOrNull(String? email) {
- final normalizedEmail = _normalizeEmail(email);
+ final normalizedEmail = normalizeContactLinkEmail(email);
if (normalizedEmail == null) {
return null;
}
@@ -533,14 +519,6 @@ class PhotosContactsService {
return contact;
}
- String? _normalizeEmail(String? email) {
- if (email == null) {
- return null;
- }
- final trimmed = email.trim().toLowerCase();
- return trimmed.isEmpty ? null : trimmed;
- }
-
void _attachSessionResetListeners() {
Bus.instance.on<UserLoggedOutEvent>().listen((_) {
_sessionGeneration += 1;
diff --git a/mobile/apps/photos/lib/ui/common/date_input.dart b/mobile/apps/photos/lib/ui/common/date_input.dart
index dc0c90e15c..0fab20e35a 100644
--- a/mobile/apps/photos/lib/ui/common/date_input.dart
+++ b/mobile/apps/photos/lib/ui/common/date_input.dart
@@ -1,182 +1,138 @@
-import 'package:flutter/material.dart';
-import 'package:intl/intl.dart';
+import "package:ente_components/ente_components.dart";
+import "package:flutter/material.dart";
+import "package:hugeicons/hugeicons.dart";
+import "package:intl/intl.dart";
import "package:photos/l10n/l10n.dart";
-import "package:photos/theme/ente_theme.dart";
class DatePickerField extends StatefulWidget {
- final String? initialValue;
- final String? hintText;
- final void Function(DateTime?)? onChanged;
- final DateTime? firstDate;
- final DateTime? lastDate;
- final bool isRequired; // New parameter for optional/required state
-
const DatePickerField({
super.key,
this.initialValue,
+ this.label,
this.hintText,
this.onChanged,
+ this.onValidityChanged,
this.firstDate,
this.lastDate,
- this.isRequired = true, // Default to required for backward compatibility
+ this.isRequired = true,
});
+ final String? initialValue;
+ final String? label;
+ final String? hintText;
+ final ValueChanged<DateTime?>? onChanged;
+ final ValueChanged<bool>? onValidityChanged;
+ final DateTime? firstDate;
+ final DateTime? lastDate;
+ final bool isRequired;
+
@override
State<DatePickerField> createState() => _DatePickerFieldState();
}
class _DatePickerFieldState extends State<DatePickerField> {
- final TextEditingController _controller = TextEditingController();
+ final _controller = TextEditingController();
DateTime? _selectedDate;
bool _hasError = false;
- bool isUSLocale = false;
-
- @override
- void initState() {
- super.initState();
- if (widget.initialValue != null) {
- _controller.text = widget.initialValue!;
- _tryParseDate(widget.initialValue!, initialParse: true).ignore();
- }
- }
-
- Future<void> _tryParseDate(String value, {bool initialParse = false}) async {
- Locale? locale = await getLocale();
- locale ??= const Locale('en', 'US');
- isUSLocale = locale.toString().toLowerCase().contains('us');
- // If the field is empty and not required, reset error state and clear date
- if (value.isEmpty && !widget.isRequired) {
- setState(() {
- _selectedDate = null;
- _hasError = false;
- });
- widget.onChanged?.call(null);
- return;
- }
-
- // Skip validation for empty optional fields
- if (value.isEmpty) {
- return;
- }
+ bool _initialized = false;
+ bool _isUSLocale = false;
- try {
- // Try parsing different date formats
- DateTime? parsed;
- final List<String> formats = isUSLocale
- ? [
- 'MM/dd/yyyy',
- 'MM-dd-yyyy',
- 'yyyy-MM-dd', // Corrected format
- ]
- : [
- 'dd/MM/yyyy',
- 'dd-MM-yyyy',
- 'yyyy-MM-dd', // Corrected format
- ];
+ String get _displayFormat => _isUSLocale ? 'MM/dd/yyyy' : 'dd/MM/yyyy';
- for (String format in formats) {
- try {
- parsed = DateFormat(format).parseStrict(value);
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ if (_initialized) return;
+
+ final locale = Localizations.localeOf(context);
+ Locale? formatLocale;
+ for (final deviceLocale
+ in WidgetsBinding.instance.platformDispatcher.locales) {
+ if (deviceLocale.languageCode == locale.languageCode) {
+ if (deviceLocale.countryCode == locale.countryCode) {
+ formatLocale = deviceLocale;
break;
- } catch (_) {
- continue;
}
+ formatLocale ??= deviceLocale;
}
+ }
+ _isUSLocale = (formatLocale ?? locale).countryCode == 'US';
+ _selectedDate = _parseDate(widget.initialValue ?? '');
+ _controller.text = _selectedDate == null
+ ? widget.initialValue ?? ''
+ : _formatDate(_selectedDate!);
+ _hasError = _controller.text.isNotEmpty && _selectedDate == null;
+ _initialized = true;
+ }
- if (parsed != null) {
- // Validate date range if specified
- bool isValid = true;
- if (widget.firstDate != null && parsed.isBefore(widget.firstDate!)) {
- isValid = false;
- }
- if (widget.lastDate != null && parsed.isAfter(widget.lastDate!)) {
- isValid = false;
- }
-
- setState(() {
- _selectedDate = isValid ? parsed : null;
- _hasError = !isValid;
- });
-
- if (isValid) {
- if (initialParse) {
- _controller.text = isUSLocale
- ? DateFormat('MM-dd-yyyy').format(parsed)
- : DateFormat('dd-MM-yyyy').format(parsed);
- }
- widget.onChanged?.call(parsed);
- }
- } else {
- setState(() {
- _selectedDate = null;
- _hasError = true;
- });
- }
- } catch (e) {
- setState(() {
- _selectedDate = null;
- _hasError = true;
- });
+ DateTime? _parseDate(String value) {
+ final formats = _isUSLocale
+ ? const ['MM/dd/yyyy', 'MM-dd-yyyy', 'yyyy-MM-dd']
+ : const ['dd/MM/yyyy', 'dd-MM-yyyy', 'yyyy-MM-dd'];
+ for (final format in formats) {
+ try {
+ return DateFormat(format).parseStrict(value.trim());
+ } catch (_) {}
}
+ return null;
+ }
+
+ String _formatDate(DateTime date) => DateFormat(_displayFormat).format(date);
+
+ void _onTextChanged(String value) {
+ final trimmedValue = value.trim();
+ final parsed = trimmedValue.isEmpty ? null : _parseDate(trimmedValue);
+ final isValid = trimmedValue.isEmpty
+ ? !widget.isRequired
+ : parsed != null &&
+ (widget.firstDate == null ||
+ !parsed.isBefore(widget.firstDate!)) &&
+ (widget.lastDate == null || !parsed.isAfter(widget.lastDate!));
+
+ setState(() {
+ _selectedDate = isValid ? parsed : null;
+ _hasError = !isValid;
+ });
+ widget.onValidityChanged?.call(isValid);
+ widget.onChanged?.call(isValid ? parsed : null);
}
Future<void> _showDatePicker() async {
- final Locale locale = await getFormatLocale();
+ final locale = await getFormatLocale();
if (!mounted) return;
- final DateTime? picked = await showDatePicker(
+ final picked = await showDatePicker(
context: context,
locale: locale,
initialDate: _selectedDate ?? DateTime.now(),
firstDate: widget.firstDate ?? DateTime(1900),
lastDate: widget.lastDate ?? DateTime(2100),
);
-
- if (picked != null) {
- setState(() {
- _selectedDate = picked;
- _hasError = false;
- _controller.text = isUSLocale
- ? DateFormat('MM-dd-yyyy').format(picked)
- : DateFormat('dd-MM-yyyy').format(picked);
- });
- widget.onChanged?.call(picked);
+ if (picked != null && mounted) {
+ _controller.text = _formatDate(picked);
}
}
@override
Widget build(BuildContext context) {
- return TextFormField(
+ return TextInputComponent(
controller: _controller,
- onChanged: (value) => _tryParseDate(value),
- decoration: InputDecoration(
- focusedBorder: OutlineInputBorder(
- borderRadius: const BorderRadius.all(Radius.circular(8.0)),
- borderSide: BorderSide(
- color: getEnteColorScheme(context).strokeMuted,
- ),
- ),
- fillColor: getEnteColorScheme(context).fillFaint,
- filled: true,
- hintText:
- widget.hintText ??
- "Enter date (DD/MM/YYYY)${widget.isRequired ? '' : ' (optional)'}",
- hintStyle: getEnteTextTheme(context).bodyFaint,
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 16,
- vertical: 14,
- ),
- border: UnderlineInputBorder(
- borderSide: BorderSide.none,
- borderRadius: BorderRadius.circular(8),
- ),
- suffixIcon: IconButton(
- icon: const Icon(Icons.calendar_today),
- onPressed: _showDatePicker,
- color: _hasError
- ? getEnteColorScheme(context).warning500
- : getEnteColorScheme(context).strokeMuted,
- ),
+ label: widget.label,
+ hintText: widget.hintText,
+ keyboardType: TextInputType.datetime,
+ autocorrect: false,
+ enableSuggestions: false,
+ isRequired: widget.isRequired,
+ message: _hasError ? _displayFormat.toUpperCase() : null,
+ messageType: _hasError
+ ? TextInputComponentMessageType.error
+ : TextInputComponentMessageType.helper,
+ suffix: HugeIcon(
+ icon: HugeIcons.strokeRoundedCalendar03,
+ color: context.componentColors.textLighter,
+ size: IconSizes.small,
),
+ onSuffixTap: _showDatePicker,
+ onChanged: _onTextChanged,
);
}
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.dart
index c21a0a2785..31767b33eb 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
@@ -87,7 +87,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
_peopleChangedSubscription = Bus.instance.on<PeopleChangedEvent>().listen((
event,
) {
- if (mounted && event.person?.remoteID == widget.personId) {
+ if (mounted && isPerson && event.person?.remoteID == widget.personId) {
setState(() => faceCropFuture = _startFaceCropLoad());
}
});
@@ -279,7 +279,9 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
? MLDataDB.localGalleryInstance
: MLDataDB.instance;
if (isPerson && !isLocalGalleryMode) {
- personEntity = await PersonService.instance.getPerson(widget.personId!);
+ personEntity =
+ PersonService.instance.getCachedPerson(widget.personId!) ??
+ await PersonService.instance.getPerson(widget.personId!);
if (personEntity == null) {
_logger.severe(
"Person with ID ${widget.personId} not found, cannot get cover face.",
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 b49a7cc3a3..247166c6aa 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
@@ -15,6 +15,7 @@ import "package:photos/models/ml/face/person.dart";
import "package:photos/services/machine_learning/face_ml/feedback/cluster_feedback.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
import "package:photos/theme/ente_theme.dart";
+import "package:photos/ui/common/date_input.dart";
import "package:photos/ui/components/action_sheet_widget.dart";
import "package:photos/ui/components/buttons/button_widget.dart";
import "package:photos/ui/components/models/button_type.dart";
@@ -25,6 +26,7 @@ import "package:photos/ui/viewer/people/face_thumbnail_squircle.dart";
import "package:photos/ui/viewer/people/merge_clusters_to_person_sheet.dart";
import "package:photos/ui/viewer/people/person_clusters_page.dart";
import "package:photos/ui/viewer/people/person_face_widget.dart";
+import "package:photos/utils/contact_string_util.dart";
import "package:photos/utils/dialog_util.dart";
import "package:photos/utils/person_contact_linking_util.dart";
@@ -49,18 +51,11 @@ class SaveOrEditPerson extends StatefulWidget {
State<SaveOrEditPerson> createState() => _SaveOrEditPersonState();
}
-String? _trimEmptyToNull(String? value) {
- final trimmedValue = value?.trim();
- if (trimmedValue == null || trimmedValue.isEmpty) {
- return null;
- }
- return trimmedValue;
-}
-
class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
static const int _maxSuggestedPersons = 3;
String _inputName = "";
String? _selectedDate;
+ bool _isBirthdayValid = true;
String? _email;
bool _isMe = false;
bool _isMeAssignedToAnotherPerson = true;
@@ -73,7 +68,7 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
late final TextEditingController _nameController;
List<PersonEntity> _allPersons = [];
- String? get _emailToSave => _trimEmptyToNull(_email);
+ String? get _emailToSave => trimToNull(_email);
int? get _currentUserIDToSave =>
currentUserIDForContactLinkEmail(_emailToSave);
@@ -86,7 +81,7 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
bool get _isMeChanged => widget.isEditing && _isMe != _initiallyIsMe;
bool get _contactLinkEmailChanged =>
- widget.isEditing && _emailToSave != _trimEmptyToNull(person?.data.email);
+ widget.isEditing && _emailToSave != trimToNull(person?.data.email);
bool get _shouldClearContactUserID =>
person?.data.userID != null &&
@@ -251,11 +246,9 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
children: [
ButtonComponent(
label: context.l10n.savePerson,
- isDisabled: !changed || _inputName.trim().isEmpty,
+ isDisabled: !_canSave,
shouldShowSuccessState: false,
- onTap: changed && _inputName.trim().isNotEmpty
- ? _savePerson
- : null,
+ onTap: _canSave ? _savePerson : null,
),
if (!widget.isEditing) ...[
const SizedBox(height: Spacing.sm),
@@ -315,29 +308,17 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
}
Widget _buildBirthdayInput() {
- final date = DateTime.tryParse(_selectedDate ?? "");
- final hasBirthday = date != null;
- return GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: _pickBirthday,
- child: TextInputComponent(
- key: ValueKey(_selectedDate),
- label: context.l10n.birthday,
- hintText: context.l10n.enterDateOfBirth,
- initialValue: date == null
- ? null
- : MaterialLocalizations.of(context).formatMediumDate(date),
- readOnly: true,
- suffix: HugeIcon(
- icon: hasBirthday
- ? HugeIcons.strokeRoundedCancel01
- : HugeIcons.strokeRoundedCalendar03,
- color: context.componentColors.textLighter,
- size: IconSizes.small,
- ),
- onSuffixTap: hasBirthday
- ? () => setState(() => _selectedDate = null)
- : _pickBirthday,
+ return DatePickerField(
+ label: context.l10n.birthday,
+ hintText: context.l10n.enterDateOfBirthHint,
+ firstDate: DateTime(100),
+ lastDate: DateTime.now(),
+ initialValue: _selectedDate,
+ isRequired: false,
+ onValidityChanged: (isValid) =>
+ setState(() => _isBirthdayValid = isValid),
+ onChanged: (date) => setState(
+ () => _selectedDate = date?.toIso8601String().split("T").first,
),
);
}
@@ -358,21 +339,6 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
);
}
- Future<void> _pickBirthday() async {
- final locale = await getFormatLocale();
- if (!mounted) return;
- final picked = await showDatePicker(
- context: context,
- locale: locale,
- initialDate: DateTime.tryParse(_selectedDate ?? "") ?? DateTime.now(),
- firstDate: DateTime(100),
- lastDate: DateTime.now(),
- );
- if (picked != null && mounted) {
- setState(() => _selectedDate = picked.toIso8601String().split("T").first);
- }
- }
-
void _setIsMe(bool selected) {
setState(() {
_isMe = selected;
@@ -662,18 +628,20 @@ class _SaveOrEditPersonState extends State<SaveOrEditPerson> {
bool get changed => widget.isEditing
? (_inputName.trim() != person!.data.name ||
_selectedDate != person!.data.birthDate ||
- _emailToSave != _trimEmptyToNull(person!.data.email) ||
+ _emailToSave != trimToNull(person!.data.email) ||
_isMeChanged ||
- _shouldUpdateContactUserID ||
_isPinned != person!.data.isPinned ||
_hideFromMemories != person!.data.hideFromMemories)
: _inputName.trim().isNotEmpty;
+ bool get _canSave =>
+ changed && _inputName.trim().isNotEmpty && _isBirthdayValid;
+
Future<PersonEntity?> updatePerson(BuildContext context) async {
try {
final emailToSave = _emailToSave;
if (emailToSave != null &&
- emailToSave != _trimEmptyToNull(person!.data.email)) {
+ emailToSave != trimToNull(person!.data.email)) {
final linkedPerson = await findPersonLinkedToEmail(
emailToSave,
excludedPersonId: person!.remoteID,
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 12aa882995..774a31a966 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
@@ -53,7 +53,6 @@ class _EditContactPageState extends State<EditContactPage> {
final _logger = Logger("EditContactPage");
late final TextEditingController _nameController;
late final FocusNode _nameFocusNode;
- late final String? _birthDateToPreserve;
bool _isSaving = false;
bool _isLoadingPhoto = false;
bool _photoDirty = false;
@@ -80,7 +79,6 @@ class _EditContactPageState extends State<EditContactPage> {
setState(() {});
}
});
- _birthDateToPreserve = widget.existingContact?.data?.birthDate;
_loadExistingPhoto();
_loadLinkedPersonDraft();
}
@@ -303,9 +301,6 @@ class _EditContactPageState extends State<EditContactPage> {
return;
}
- final needsContactLinkUpdate = _personNeedsContactLinkUpdate(
- linkedPerson,
- );
final shouldPrefillFromPerson = widget.existingContact == null;
if (shouldPrefillFromPerson && _nameController.text.trim().isEmpty) {
_nameController.text = linkedPerson.data.name;
@@ -314,7 +309,6 @@ class _EditContactPageState extends State<EditContactPage> {
_initialLinkedPerson = linkedPerson;
_draftLinkedPerson = linkedPerson;
_unlinkDraft = false;
- _linkDirty = needsContactLinkUpdate;
});
if (shouldPrefillFromPerson && !_photoDirty && _draftPhotoBytes == null) {
@@ -489,7 +483,7 @@ class _EditContactPageState extends State<EditContactPage> {
setState(() {
_isLoadingPhoto = true;
});
- final photoBytes = await normalizeContactPhotoAttachmentBytes(croppedBytes);
+ final photoBytes = await compressThumbnailToSizeLimit(croppedBytes);
if (!mounted) {
return;
}
@@ -513,7 +507,6 @@ class _EditContactPageState extends State<EditContactPage> {
var saved = await PhotosContactsService.instance.createOrUpdateContact(
contactUserId: widget.contactUserId,
name: contactName,
- birthDate: _birthDateToPreserve,
);
if (_photoDirty) {
final draftPhotoBytes = _draftPhotoBytes;
diff --git a/mobile/apps/photos/lib/utils/contact_photo_util.dart b/mobile/apps/photos/lib/utils/contact_photo_util.dart
index 8b8fa8a4a1..73462163d2 100644
--- a/mobile/apps/photos/lib/utils/contact_photo_util.dart
+++ b/mobile/apps/photos/lib/utils/contact_photo_util.dart
@@ -1,6 +1,5 @@
import "dart:typed_data";
-import "package:photos/core/constants.dart";
import "package:photos/db/files_db.dart";
import "package:photos/db/ml/db.dart";
import "package:photos/models/file/file.dart";
@@ -11,21 +10,6 @@ import "package:photos/services/machine_learning/ml_result.dart";
import "package:photos/services/search_service.dart";
import "package:photos/utils/face/face_thumbnail_cache.dart";
-const _maxContactPhotoCompressionAttempts = 2;
-
-Future<Uint8List> normalizeContactPhotoAttachmentBytes(
- Uint8List sourceBytes,
-) async {
- var bytes = sourceBytes;
- var attempts = 0;
- while (bytes.length > thumbnailDataLimit &&
- attempts < _maxContactPhotoCompressionAttempts) {
- bytes = await compressThumbnail(bytes);
- attempts++;
- }
- return bytes;
-}
-
Future<Uint8List?> buildContactPhotoAttachmentBytesFromFace({
required EnteFile file,
required Face face,
@@ -40,7 +24,7 @@ Future<Uint8List?> buildContactPhotoAttachmentBytesFromFace({
if (croppedBytes == null) {
return null;
}
- return normalizeContactPhotoAttachmentBytes(croppedBytes);
+ return compressThumbnailToSizeLimit(croppedBytes);
}
Future<Uint8List?> buildContactPhotoAttachmentBytesFromPerson(
diff --git a/mobile/apps/photos/lib/utils/contact_string_util.dart b/mobile/apps/photos/lib/utils/contact_string_util.dart
new file mode 100644
index 0000000000..2e1bd81b6b
--- /dev/null
+++ b/mobile/apps/photos/lib/utils/contact_string_util.dart
@@ -0,0 +1,8 @@
+String? trimToNull(String? value) {
+ final trimmed = value?.trim();
+ return trimmed == null || trimmed.isEmpty ? null : trimmed;
+}
+
+String? normalizeContactLinkEmail(String? email) {
+ return trimToNull(email)?.toLowerCase();
+}
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 8c2d826af9..11d1cf6fa2 100644
--- a/mobile/apps/photos/lib/utils/person_contact_linking_util.dart
+++ b/mobile/apps/photos/lib/utils/person_contact_linking_util.dart
@@ -6,15 +6,11 @@ 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";
import "package:photos/ui/viewer/people/people_page.dart";
+import "package:photos/utils/contact_string_util.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;
-}
+export "package:photos/utils/contact_string_util.dart"
+ show normalizeContactLinkEmail;
bool contactLinkEmailMatches(String? first, String? second) {
final normalizedFirst = normalizeContactLinkEmail(first);
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 02b159f1e7..5abee80519 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
@@ -82,11 +82,7 @@ void main() {
id: "contact-1",
contactUserId: 3,
- data: contacts.ContactData(
- contactUserId: 3,
- name: "Old Contact",
- birthDate: "2001-04-02",
- ),
+ data: contacts.ContactData(contactUserId: 3, name: "Old Contact"),
profilePictureAttachmentId: null,
isDeleted: false,
createdAt: 1,
@@ -143,7 +139,6 @@ void main() {
expect(contactsService.createOrUpdateCalls, 1);
expect(contactsService.lastUpdatedContactUserId, 3);
expect(contactsService.lastUpdatedName, "Alex R");
- expect(contactsService.lastUpdatedBirthDate, "2001-04-02");
});
test("updateAttributes does not sync unchanged person name", () async {
@@ -253,7 +248,6 @@ class _FakePhotosContactsService implements PhotosContactsService {
int createOrUpdateCalls = 0;
int? lastUpdatedContactUserId;
String? lastUpdatedName;
- String? lastUpdatedBirthDate;
void seed(contacts.ContactRecord value) {
contact = value;
@@ -282,12 +276,10 @@ class _FakePhotosContactsService implements PhotosContactsService {
Future<contacts.ContactRecord> createOrUpdateContact({
required int contactUserId,
required String name,
- String? birthDate,
}) async {
createOrUpdateCalls += 1;
lastUpdatedContactUserId = contactUserId;
lastUpdatedName = name.trim();
- lastUpdatedBirthDate = birthDate;
final saved = contact;
return contacts.ContactRecord(
id: saved?.id ?? "contact-$contactUserId",
@@ -296,7 +288,6 @@ class _FakePhotosContactsService implements PhotosContactsService {
data: contacts.ContactData(
contactUserId: contactUserId,
name: name.trim(),
- birthDate: birthDate,
),
profilePictureAttachmentId: saved?.profilePictureAttachmentId,
isDeleted: false,
diff --git a/mobile/apps/photos/test/ui/common/date_input_test.dart b/mobile/apps/photos/test/ui/common/date_input_test.dart
new file mode 100644
index 0000000000..c50619e793
--- /dev/null
+++ b/mobile/apps/photos/test/ui/common/date_input_test.dart
@@ -0,0 +1,44 @@
+import "package:ente_components/ente_components.dart";
+import "package:flutter/material.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/ui/common/date_input.dart";
+
+void main() {
+ testWidgets('supports typed optional dates', (tester) async {
+ DateTime? selectedDate;
+ bool? isValid;
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ComponentTheme.lightTheme(),
+ home: Scaffold(
+ body: DatePickerField(
+ initialValue: '2000-07-14',
+ firstDate: DateTime(100),
+ lastDate: DateTime(2100),
+ isRequired: false,
+ onChanged: (date) => selectedDate = date,
+ onValidityChanged: (value) => isValid = value,
+ ),
+ ),
+ ),
+ );
+
+ final field = find.byType(TextField);
+ expect(tester.widget<TextField>(field).controller!.text, '07/14/2000');
+
+ await tester.enterText(field, '12/31/2000');
+ expect(selectedDate, DateTime(2000, 12, 31));
+ expect(isValid, isTrue);
+
+ await tester.enterText(field, '02/30/2000');
+ await tester.pump();
+ expect(selectedDate, isNull);
+ expect(isValid, isFalse);
+ expect(find.text('MM/DD/YYYY'), findsOneWidget);
+
+ await tester.enterText(field, '');
+ await tester.pump();
+ expect(isValid, isTrue);
+ expect(find.text('MM/DD/YYYY'), findsNothing);
+ });
+}
diff --git a/mobile/packages/contacts/lib/src/models/contact_data.dart b/mobile/packages/contacts/lib/src/models/contact_data.dart
index d337f1abe8..1f6a43faf8 100644
--- a/mobile/packages/contacts/lib/src/models/contact_data.dart
+++ b/mobile/packages/contacts/lib/src/models/contact_data.dart
@@ -3,25 +3,18 @@ import 'dart:convert';
class ContactData {
final int contactUserId;
final String name;
- final String? birthDate;
- const ContactData({
- required this.contactUserId,
- required this.name,
- this.birthDate,
- });
+ const ContactData({required this.contactUserId, required this.name});
Map<String, dynamic> toJson() => {
'contactUserId': contactUserId,
'name': name,
- if (birthDate != null) 'birthDate': birthDate,
};
factory ContactData.fromJson(Map<String, dynamic> json) {
return ContactData(
contactUserId: json['contactUserId'] as int,
name: json['name'] as String,
- birthDate: json['birthDate'] as String?,
);
}
diff --git a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
index 99d19e2b29..7247cd0007 100644
--- a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
+++ b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
@@ -170,7 +170,6 @@ class _FrbContactsRustContext implements ContactsRustContext {
data: rust.ContactData(
contactUserId: data.contactUserId,
name: data.name,
- birthDate: data.birthDate,
),
),
);
@@ -198,7 +197,6 @@ class _FrbContactsRustContext implements ContactsRustContext {
data: rust.ContactData(
contactUserId: data.contactUserId,
name: data.name,
- birthDate: data.birthDate,
),
),
);
@@ -282,11 +280,7 @@ rust.AttachmentType _toRustAttachmentType(
ContactRecord _fromRustRecord(rust.ContactRecord record) {
final data = record.isDeleted
? null
- : ContactData(
- contactUserId: record.contactUserId,
- name: record.name!,
- birthDate: record.birthDate,
- );
+ : ContactData(contactUserId: record.contactUserId, name: record.name!);
return ContactRecord(
id: record.id,
contactUserId: record.contactUserId,
diff --git a/mobile/packages/contacts/test/contact_data_test.dart b/mobile/packages/contacts/test/contact_data_test.dart
new file mode 100644
index 0000000000..c490e86910
--- /dev/null
+++ b/mobile/packages/contacts/test/contact_data_test.dart
@@ -0,0 +1,14 @@
+import 'package:ente_contacts/contacts.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ test('ignores legacy birth date', () {
+ final data = ContactData.fromJson({
+ 'contactUserId': 2,
+ 'name': 'B',
+ 'birthDate': '2001-04-02',
+ });
+
+ expect(data.toJson(), {'contactUserId': 2, 'name': 'B'});
+ });
+}
diff --git a/mobile/packages/contacts/test/contacts_service_test.dart b/mobile/packages/contacts/test/contacts_service_test.dart
index 983ba19f94..fc017577e5 100644
--- a/mobile/packages/contacts/test/contacts_service_test.dart
+++ b/mobile/packages/contacts/test/contacts_service_test.dart
@@ -47,11 +47,7 @@ void main() {
id: 'ct_1',
contactUserId: 2,
- data: ContactData(
- contactUserId: 2,
- name: 'B',
- birthDate: '2001-04-02',
- ),
+ data: ContactData(contactUserId: 2, name: 'B'),
profilePictureAttachmentId: 'att_1',
isDeleted: false,
createdAt: 10,
diff --git a/rust/bindings/frb/ente-rust/src/api/contacts.rs b/rust/bindings/frb/ente-rust/src/api/contacts.rs
index 1adfb8a03e..e9a91b8110 100644
--- a/rust/bindings/frb/ente-rust/src/api/contacts.rs
+++ b/rust/bindings/frb/ente-rust/src/api/contacts.rs
@@ -137,8 +137,6 @@ pub struct ContactData {
pub contact_user_id: i64,
/// User-chosen display name for the contact.
pub name: String,
- /// Optional birthday in `yyyy-MM-dd` format.
- pub birth_date: Option<String>,
}
impl From<ContactData> for CoreContactData {
@@ -146,7 +144,6 @@ impl From<ContactData> for CoreContactData {
Self {
contact_user_id: value.contact_user_id,
name: value.name,
- birth_date: value.birth_date,
}
}
}
@@ -163,8 +160,6 @@ pub struct ContactRecord {
pub email: Option<String>,
/// Client-managed display name from the encrypted payload.
pub name: Option<String>,
- /// Optional birthday from the encrypted payload.
- pub birth_date: Option<String>,
/// Current profile picture attachment id, if any.
pub profile_picture_attachment_id: Option<String>,
/// Whether this record is a tombstone.
@@ -182,7 +177,6 @@ impl From<CoreContactRecord> for ContactRecord {
contact_user_id: value.contact_user_id,
email: value.email,
name: value.name,
- birth_date: value.birth_date,
profile_picture_attachment_id: value.profile_picture_attachment_id,
is_deleted: value.is_deleted,
created_at: value.created_at,
diff --git a/rust/bindings/wasm/ente-wasm/src/contacts.rs b/rust/bindings/wasm/ente-wasm/src/contacts.rs
index 2d1c445f1c..00c01911e1 100644
--- a/rust/bindings/wasm/ente-wasm/src/contacts.rs
+++ b/rust/bindings/wasm/ente-wasm/src/contacts.rs
@@ -93,7 +93,6 @@ struct ContactRecordJs {
contact_user_id: i64,
email: Option<String>,
name: Option<String>,
- birth_date: Option<String>,
#[serde(rename = "profilePictureAttachmentID")]
profile_picture_attachment_id: Option<String>,
is_deleted: bool,
@@ -115,7 +114,6 @@ impl From<ente_contacts::ContactRecord> for ContactRecordJs {
contact_user_id: value.contact_user_id,
email: value.email,
name: value.name,
- birth_date: value.birth_date,
profile_picture_attachment_id: value.profile_picture_attachment_id,
is_deleted: value.is_deleted,
created_at: value.created_at,
diff --git a/rust/crates/contacts/src/client.rs b/rust/crates/contacts/src/client.rs
index f9666293d3..55b009458a 100644
--- a/rust/crates/contacts/src/client.rs
+++ b/rust/crates/contacts/src/client.rs
@@ -834,7 +834,6 @@ impl ContactsCtx {
contact_user_id: entity.contact_user_id,
email: None,
name: None,
- birth_date: None,
profile_picture_attachment_id: None,
is_deleted: true,
created_at: entity.created_at,
@@ -865,7 +864,6 @@ impl ContactsCtx {
contact_user_id: entity.contact_user_id,
email: entity.email,
name: Some(data.name),
- birth_date: data.birth_date,
profile_picture_attachment_id: entity.profile_picture_attachment_id,
is_deleted: false,
created_at: entity.created_at,
diff --git a/rust/crates/contacts/src/models.rs b/rust/crates/contacts/src/models.rs
index 990c253e86..adf45b05e1 100644
--- a/rust/crates/contacts/src/models.rs
+++ b/rust/crates/contacts/src/models.rs
@@ -26,8 +26,6 @@ pub struct WrappedRootContactKey {
pub struct ContactData {
pub contact_user_id: i64,
pub name: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub birth_date: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -36,9 +34,27 @@ pub struct ContactRecord {
pub contact_user_id: i64,
pub email: Option<String>,
pub name: Option<String>,
- pub birth_date: Option<String>,
pub profile_picture_attachment_id: Option<String>,
pub is_deleted: bool,
pub created_at: i64,
pub updated_at: i64,
}
+
+#[cfg(test)]
+mod tests {
+ use super::ContactData;
+
+ #[test]
+ fn contact_data_ignores_legacy_birth_date() {
+ let data: ContactData =
+ serde_json::from_str(r#"{"contactUserId":42,"name":"Alex","birthDate":"2001-04-02"}"#)
+ .unwrap();
+
+ assert_eq!(data.contact_user_id, 42);
+ assert_eq!(data.name, "Alex");
+ assert_eq!(
+ serde_json::to_string(&data).unwrap(),
+ r#"{"contactUserId":42,"name":"Alex"}"#,
+ );
+ }
+}
diff --git a/rust/crates/contacts/tests/contacts_mock.rs b/rust/crates/contacts/tests/contacts_mock.rs
index 4ca6c54d9a..c6bcdf28fe 100644
--- a/rust/crates/contacts/tests/contacts_mock.rs
+++ b/rust/crates/contacts/tests/contacts_mock.rs
@@ -9,7 +9,6 @@ fn sample_contact() -> ContactData {
ContactData {
contact_user_id: 42,
name: "B Test".to_string(),
- birth_date: Some("2001-04-01".to_string()),
}
}
diff --git a/rust/e2e/tests/full_e2e.rs b/rust/e2e/tests/full_e2e.rs
index a60ab6d848..189bff6227 100644
--- a/rust/e2e/tests/full_e2e.rs
+++ b/rust/e2e/tests/full_e2e.rs
@@ -135,7 +135,6 @@ async fn run_contacts_stage(pair: &legacy::LegacyPair) {
let initial_data = ContactData {
contact_user_id: pair.trusted.user_id,
name: "Trusted Contact".to_string(),
- birth_date: Some("2001-04-01".to_string()),
};
let contact = pair.owner_ctx.create_contact(&initial_data).await.unwrap();
@@ -153,13 +152,11 @@ async fn run_contacts_stage(pair: &legacy::LegacyPair) {
&ContactData {
contact_user_id: pair.trusted.user_id,
name: "Trusted Contact Updated".to_string(),
- birth_date: Some("2001-04-02".to_string()),
},
)
.await
.unwrap();
assert_eq!(updated.name.as_deref(), Some("Trusted Contact Updated"));
- assert_eq!(updated.birth_date.as_deref(), Some("2001-04-02"));
let diff = pair.owner_ctx.get_diff(0, 5000).await.unwrap();
assert!(diff.iter().any(|entry| entry.id == contact.id));