Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][contacts] harden shared display sync and localize contact UI

Neeraj Gupta305fbec9daa3
diff --git a/mobile/apps/photos/lib/l10n/intl_en.arb b/mobile/apps/photos/lib/l10n/intl_en.arb
index abbb1ab1e4..42c60c536d 100644
--- a/mobile/apps/photos/lib/l10n/intl_en.arb
+++ b/mobile/apps/photos/lib/l10n/intl_en.arb
@@ -1223,6 +1223,16 @@
"clickOnTheOverflowMenu": "β€’ Click on the overflow menu",
"click": "β€’ Click",
"nothingToSeeHere": "Nothing to see here! πŸ‘€",
+ "addANameAndPhoto": "Add a name and photo",
+ "photosSharedByWillAppearHere": "Photos shared by {email} will appear here.",
+ "@photosSharedByWillAppearHere": {
+ "placeholders": {
+ "email": {
+ "type": "String",
+ "example": "[email protected]"
+ }
+ }
+ },
"selectFoldersToBackup": "<action>Select folders</action> to view and\nbackup on ente.",
"unarchiveAlbum": "Unarchive album",
"archiveAlbum": "Archive album",
@@ -1742,8 +1752,14 @@
"editEmailAlreadyLinked": "This email is already linked to {name}.",
"viewPersonToUnlink": "View {name} to unlink",
"enterName": "Enter name",
+ "editContact": "Edit contact",
+ "autoFetchFromPeople": "Auto-fetch from people",
+ "useTheirNameAndPhoto": "Use their name and photo",
"savePerson": "Save person",
+ "saveContact": "Save contact",
"editPerson": "Edit person",
+ "enterDateOfBirthHint": "Enter date of birth",
+ "setAContactPhoto": "Set a contact photo",
"mergedPhotos": "Merged photos",
"orMergeWithExistingPerson": "Or merge with existing",
"enterDateOfBirth": "Birthday (optional)",
diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dart
index a0074df522..dd59c5da63 100644
--- a/mobile/apps/photos/lib/services/photos_contacts_service.dart
+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart
@@ -31,16 +31,19 @@ class PhotosContactsService {
String? _sessionKey;
String? _sessionAuthToken;
bool _hasHydratedCache = false;
+ int _sessionGeneration = 0;
bool get hasHydratedCache => _hasHydratedCache;
Future<void> ensureReady() async {
if (!flagService.enableContact) {
+ _sessionGeneration += 1;
_resetSessionState(notify: true);
return;
}
final session = _buildSession();
if (session == null) {
+ _sessionGeneration += 1;
_resetSessionState(notify: true);
return;
}
@@ -54,13 +57,17 @@ class PhotosContactsService {
return;
}
if (_sessionKey != sessionKey) {
+ _sessionGeneration += 1;
_resetSessionState(notify: true);
}
_sessionKey = sessionKey;
_sessionAuthToken = session.authToken;
late final Future<void> readyFuture;
- readyFuture =
- _openAndSync(session).catchError((Object error, StackTrace stackTrace) {
+ final generation = _sessionGeneration;
+ readyFuture = _openAndSync(
+ session,
+ generation,
+ ).catchError((Object error, StackTrace stackTrace) {
if (identical(_readyFuture, readyFuture)) {
_readyFuture = null;
}
@@ -71,6 +78,9 @@ class PhotosContactsService {
}
Future<contacts.ContactRecord?> getContactByUserId(int contactUserId) async {
+ if (!flagService.enableContact) {
+ return null;
+ }
final cached = getCachedContactByUserId(contactUserId);
if (cached != null) {
return cached;
@@ -78,6 +88,9 @@ class PhotosContactsService {
return _runReadSafely(
() async {
await ensureReady();
+ if (_sessionKey == null) {
+ return null;
+ }
final contact = await _contacts.getContactByUserId(contactUserId);
if (contact == null || contact.isDeleted) {
return null;
@@ -125,6 +138,9 @@ class PhotosContactsService {
if (contactUserId == null) {
return null;
}
+ if (!flagService.enableContact) {
+ return null;
+ }
if (_resolvedProfilePictureUserIds.contains(contactUserId)) {
return _profilePictureBytesByUserId[contactUserId];
}
@@ -214,9 +230,14 @@ class PhotosContactsService {
@visibleForTesting
Future<void> debugOpenAndSync(contacts.ContactsSession session) async {
+ final sessionKey = _buildSessionKey(session);
+ if (_sessionKey != sessionKey) {
+ _sessionGeneration += 1;
+ _resetSessionState(notify: false);
+ }
_sessionKey = _buildSessionKey(session);
_sessionAuthToken = session.authToken;
- await _openAndSync(session);
+ await _openAndSync(session, _sessionGeneration);
}
@visibleForTesting
@@ -260,10 +281,23 @@ class PhotosContactsService {
return "${session.baseUrl}|${session.userId}";
}
- Future<void> _openAndSync(contacts.ContactsSession session) async {
+ Future<void> _openAndSync(
+ contacts.ContactsSession session,
+ int generation,
+ ) async {
await _contacts.open(session);
+ if (!_isSessionGenerationCurrent(generation, session)) {
+ return;
+ }
+
final cachedUserIdsBeforeHydration = _contactsByUserId.keys.toSet();
- final localContacts = await _hydrateCacheFromLocalDb();
+ final localContacts = await _contacts.getContacts();
+ if (!_isSessionGenerationCurrent(generation, session)) {
+ return;
+ }
+ for (final contact in localContacts) {
+ _cacheContact(contact);
+ }
_hasHydratedCache = true;
final newlyHydratedLocalUserIds = localContacts
.map((contact) => contact.contactUserId)
@@ -273,6 +307,9 @@ class PhotosContactsService {
var shouldRetrySync = false;
try {
final contactsDiff = await _contacts.sync();
+ if (!_isSessionGenerationCurrent(generation, session)) {
+ return;
+ }
for (final contact in contactsDiff) {
_invalidateProfilePictureCache(contact.contactUserId);
_cacheContact(contact);
@@ -281,6 +318,9 @@ class PhotosContactsService {
contactsDiff.map((contact) => contact.contactUserId),
);
} catch (e, s) {
+ if (!_isSessionGenerationCurrent(generation, session)) {
+ return;
+ }
shouldRetrySync = true;
_logger.warning(
"Failed to sync contacts after hydrating local cache",
@@ -296,6 +336,14 @@ class PhotosContactsService {
}
}
+ bool _isSessionGenerationCurrent(
+ int generation,
+ contacts.ContactsSession session,
+ ) {
+ return _sessionGeneration == generation &&
+ _sessionKey == _buildSessionKey(session);
+ }
+
void _notifyChanged(contacts.ContactRecord contact) {
_notifyContactsChanged({contact.contactUserId});
}
@@ -319,6 +367,14 @@ class PhotosContactsService {
);
return null;
}
+ if (_isContactsDatabaseNotConfiguredError(e)) {
+ _logger.warning(
+ "Contacts integration unavailable while contacts are disabled or not initialized during $description",
+ e,
+ s,
+ );
+ return null;
+ }
rethrow;
} catch (e, s) {
_logger.warning("Failed to $description", e, s);
@@ -331,6 +387,12 @@ class PhotosContactsService {
.contains("flutter_rust_bridge has not been initialized");
}
+ bool _isContactsDatabaseNotConfiguredError(StateError error) {
+ return error.message.contains(
+ "ContactsDatabase.configure(userId: ...) must be called first",
+ );
+ }
+
void _cacheContact(contacts.ContactRecord contact) {
final userId = contact.contactUserId;
if (contact.isDeleted) {
@@ -341,14 +403,6 @@ class PhotosContactsService {
_contactsByUserId[userId] = contact;
}
- Future<List<contacts.ContactRecord>> _hydrateCacheFromLocalDb() async {
- final localContacts = await _contacts.getContacts();
- for (final contact in localContacts) {
- _cacheContact(contact);
- }
- return localContacts;
- }
-
void _resetSessionState({required bool notify}) {
final hadCachedContacts = _contactsByUserId.isNotEmpty;
_contactsByUserId.clear();
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 2e26bd2939..f8dd2e2d36 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
@@ -39,6 +39,7 @@ class _ContactPhotoPickerSheet extends StatelessWidget {
@override
Widget build(BuildContext context) {
+ final l10n = AppLocalizations.of(context);
final isFileSelected = ValueNotifier(false);
final selectedFiles = SelectedFiles();
selectedFiles.addListener(() {
@@ -55,8 +56,8 @@ class _ContactPhotoPickerSheet extends StatelessWidget {
Expanded(
child: Column(
children: [
- const BottomOfTitleBarWidget(
- title: TitleBarTitleWidget(title: "Set a contact photo"),
+ BottomOfTitleBarWidget(
+ title: TitleBarTitleWidget(title: l10n.setAContactPhoto),
showCloseButton: true,
),
Expanded(
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/contact_result_page.dart b/mobile/apps/photos/lib/ui/viewer/search/result/contact_result_page.dart
index a2fb0530af..a4ed71526c 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/result/contact_result_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/contact_result_page.dart
@@ -480,6 +480,7 @@ class _UnsavedContactHeader extends StatelessWidget {
Widget build(BuildContext context) {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
+ final l10n = AppLocalizations.of(context);
return Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Column(
@@ -494,8 +495,8 @@ class _UnsavedContactHeader extends StatelessWidget {
),
const SizedBox(height: 20),
MenuItemWidgetNew(
- title: "Add a name and photo",
- subText: AppLocalizations.of(context).itemCount(count: itemCount),
+ title: l10n.addANameAndPhoto,
+ subText: l10n.itemCount(count: itemCount),
titleColor: colorScheme.textBase,
subTextStyle: textTheme.mini.copyWith(
color: colorScheme.textMuted,
@@ -546,6 +547,7 @@ class _UnsavedContactEmptyState extends StatelessWidget {
Widget build(BuildContext context) {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
+ final l10n = AppLocalizations.of(context);
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 36),
@@ -561,7 +563,7 @@ class _UnsavedContactEmptyState extends StatelessWidget {
),
const SizedBox(height: 12),
Text(
- "Nothing to see here",
+ l10n.nothingToSeeHere,
style: textTheme.largeBold.copyWith(
fontSize: 18,
height: 24 / 18,
@@ -569,7 +571,7 @@ class _UnsavedContactEmptyState extends StatelessWidget {
),
const SizedBox(height: 4),
Text(
- "Photos shared with or by $email will appear here.",
+ l10n.photosSharedByWillAppearHere(email: email),
textAlign: TextAlign.center,
style: textTheme.mini.copyWith(
color: colorScheme.textMuted,
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 8dd4f23989..ab82c11f5c 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
@@ -107,6 +107,7 @@ class _EditContactPageState extends State<EditContactPage> {
Widget build(BuildContext context) {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
+ final l10n = AppLocalizations.of(context);
return PopScope(
canPop: !_isSaving && !_hasUnsavedChanges,
@@ -140,7 +141,7 @@ class _EditContactPageState extends State<EditContactPage> {
backgroundColor: colorScheme.backgroundColour,
surfaceTintColor: Colors.transparent,
title: Text(
- "Edit contact",
+ l10n.editContact,
style: textTheme.h3Bold.copyWith(
fontSize: 20,
height: 28 / 20,
@@ -180,8 +181,8 @@ class _EditContactPageState extends State<EditContactPage> {
const SizedBox(height: 32),
if (_showAutofillRow) ...[
MenuItemWidgetNew(
- title: "Auto-fetch from people",
- subText: "Use their name and photo",
+ title: l10n.autoFetchFromPeople,
+ subText: l10n.useTheirNameAndPhoto,
titleToSubTextSpacing: 4,
subTextStyle: textTheme.mini.copyWith(
color: colorScheme.textMuted,
@@ -197,7 +198,7 @@ class _EditContactPageState extends State<EditContactPage> {
),
const SizedBox(height: 28),
],
- const _FieldLabel(text: "Email", isRequired: true),
+ _FieldLabel(text: l10n.email, isRequired: true),
const SizedBox(height: 8),
_InputShell(
child: Padding(
@@ -212,7 +213,7 @@ class _EditContactPageState extends State<EditContactPage> {
),
),
const SizedBox(height: 24),
- const _FieldLabel(text: "Name"),
+ _FieldLabel(text: l10n.name),
const SizedBox(height: 8),
_InputShell(
child: TextField(
@@ -220,7 +221,7 @@ class _EditContactPageState extends State<EditContactPage> {
textCapitalization: TextCapitalization.words,
style: textTheme.body,
decoration: InputDecoration(
- hintText: "Enter a name",
+ hintText: l10n.enterName,
hintStyle: textTheme.bodyFaint,
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(
@@ -231,7 +232,7 @@ class _EditContactPageState extends State<EditContactPage> {
),
),
const SizedBox(height: 24),
- const _FieldLabel(text: "Birthday"),
+ _FieldLabel(text: l10n.birthday),
const SizedBox(height: 8),
_BirthDateField(
value: _selectedBirthDate,
@@ -243,7 +244,7 @@ class _EditContactPageState extends State<EditContactPage> {
_selectedBirthDate = null;
});
},
- hintText: "Enter date of birth",
+ hintText: l10n.enterDateOfBirthHint,
),
],
),
@@ -962,6 +963,7 @@ class _SaveContactButton extends StatelessWidget {
Widget build(BuildContext context) {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
+ final l10n = AppLocalizations.of(context);
final backgroundColor =
isDisabled ? colorScheme.fillFaint : colorScheme.primary500;
final textColor =
@@ -981,7 +983,7 @@ class _SaveContactButton extends StatelessWidget {
),
child: Center(
child: Text(
- "Save contact",
+ l10n.saveContact,
style: textTheme.small.copyWith(
color: textColor,
fontWeight: FontWeight.w500,
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 f2483a1f37..34767d01bc 100644
--- a/mobile/apps/photos/test/services/photos_contacts_service_test.dart
+++ b/mobile/apps/photos/test/services/photos_contacts_service_test.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+import 'dart:collection';
import 'dart:typed_data';
import 'package:ente_contacts/contacts.dart' as contacts;
@@ -38,12 +40,72 @@ void main() {
await service.debugOpenAndSync(session);
expect(service.hasHydratedCache, isTrue);
+ expect(service.getCachedContactByUserId(7), isNotNull);
expect(service.getCachedSavedNameByUserId(7), 'Alice');
expect(service.getCachedResolvedEmailByUserId(7), '[email protected]');
- expect(await service.getContactByUserId(7), isNotNull);
expect(contactsService.openCalls, 1);
expect(contactsService.syncCalls, 1);
});
+
+ test(
+ 'stale in-flight debugOpenAndSync does not repopulate cache after session switch',
+ () async {
+ contactsService.getContactsBarrier = Completer<void>();
+ contactsService.getContactsStarted = Completer<void>();
+ contactsService.localContactsPages = Queue<List<contacts.ContactRecord>>.of([
+ const [
+ contacts.ContactRecord(
+ id: 'ct_old',
+ contactUserId: 7,
+ email: '[email protected]',
+ data: contacts.ContactData(contactUserId: 7, name: 'Alice'),
+ profilePictureAttachmentId: null,
+ isDeleted: false,
+ createdAt: 1,
+ updatedAt: 2,
+ ),
+ ],
+ const [
+ contacts.ContactRecord(
+ id: 'ct_new',
+ contactUserId: 9,
+ email: '[email protected]',
+ data: contacts.ContactData(contactUserId: 9, name: 'Bob'),
+ profilePictureAttachmentId: null,
+ isDeleted: false,
+ createdAt: 3,
+ updatedAt: 4,
+ ),
+ ],
+ ]);
+ contactsService.syncPages = Queue<List<contacts.ContactRecord>>.of([
+ const [],
+ const [],
+ ]);
+
+ final oldOpenAndSync = service.debugOpenAndSync(session);
+ await contactsService.getContactsStarted!.future;
+
+ final nextSession = contacts.ContactsSession(
+ baseUrl: session.baseUrl,
+ authToken: 'token-2',
+ userId: 2,
+ accountKey: Uint8List.fromList([9, 9, 9]),
+ );
+ await service.debugOpenAndSync(nextSession);
+
+ expect(service.getCachedSavedNameByUserId(9), 'Bob');
+ expect(service.getCachedSavedNameByUserId(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);
+ },
+ );
}
class FakeContactsService extends Fake implements contacts.ContactsService {
@@ -56,8 +118,13 @@ class FakeContactsService extends Fake implements contacts.ContactsService {
final List<contacts.ContactRecord> localContacts;
final List<contacts.ContactRecord> syncDiff;
final Object? syncError;
+ Queue<List<contacts.ContactRecord>>? localContactsPages;
+ Queue<List<contacts.ContactRecord>>? syncPages;
+ Completer<void>? getContactsBarrier;
+ Completer<void>? getContactsStarted;
int openCalls = 0;
int syncCalls = 0;
+ int getContactsCalls = 0;
@override
Future<void> open(contacts.ContactsSession session) async {
@@ -68,12 +135,29 @@ class FakeContactsService extends Fake implements contacts.ContactsService {
Future<List<contacts.ContactRecord>> getContacts({
bool includeDeleted = false,
}) async {
- return localContacts;
+ getContactsCalls += 1;
+ final pages = localContactsPages;
+ final response = pages != null && pages.isNotEmpty
+ ? pages.removeFirst()
+ : localContacts;
+ final started = getContactsStarted;
+ if (started != null && !started.isCompleted) {
+ started.complete();
+ }
+ final barrier = getContactsBarrier;
+ if (getContactsCalls == 1 && barrier != null && !barrier.isCompleted) {
+ await barrier.future;
+ }
+ return response;
}
@override
Future<List<contacts.ContactRecord>> sync() async {
syncCalls += 1;
+ final pages = syncPages;
+ if (pages != null && pages.isNotEmpty) {
+ return pages.removeFirst();
+ }
final error = syncError;
if (error != null) {
throw error;
diff --git a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
index 689218cd1c..e6fccb3c01 100644
--- a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
+++ b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
@@ -276,7 +276,7 @@ class ContactsDisplayService {
final contacts = _requireContacts();
await contacts.open(session);
if (!_isSessionGenerationCurrent(generation, session)) {
- return;
+ return;
}
final localContacts = await contacts.getContacts();
@@ -289,13 +289,25 @@ class ContactsDisplayService {
_notifyChanged();
}
- final diff = await contacts.sync();
- if (!_isSessionGenerationCurrent(generation, session)) {
- return;
- }
- final diffChanged = _cacheContacts(diff, invalidateProfilePictures: true);
- if (diffChanged.isNotEmpty) {
- _notifyChanged();
+ try {
+ final diff = await contacts.sync();
+ if (!_isSessionGenerationCurrent(generation, session)) {
+ return;
+ }
+ final diffChanged = _cacheContacts(diff, invalidateProfilePictures: true);
+ if (diffChanged.isNotEmpty) {
+ _notifyChanged();
+ }
+ } catch (error, stackTrace) {
+ if (!_isSessionGenerationCurrent(generation, session)) {
+ return;
+ }
+ _logger.warning(
+ 'Failed to sync shared contacts display cache after hydrating local cache',
+ error,
+ stackTrace,
+ );
+ _readyFuture = null;
}
}
diff --git a/mobile/packages/contacts/test/contacts_display_service_test.dart b/mobile/packages/contacts/test/contacts_display_service_test.dart
index a82af42272..31aece7b7d 100644
--- a/mobile/packages/contacts/test/contacts_display_service_test.dart
+++ b/mobile/packages/contacts/test/contacts_display_service_test.dart
@@ -253,6 +253,27 @@ void main() {
isNull,
);
});
+
+ test(
+ 'ensureReady keeps hydrated cache and retries later when sync fails',
+ () async {
+ await contactsService.open(session);
+ await contactsService.createContact(
+ const ContactData(contactUserId: 7, name: 'Alice'),
+ );
+ rustApi.ctx.diffError = StateError('boom');
+
+ await expectLater(displayService.ensureReady(session), completes);
+
+ expect(displayService.getCachedSavedName(contactUserId: 7), 'Alice');
+ expect(rustApi.ctx.getDiffCalls, 1);
+
+ rustApi.ctx.diffError = null;
+ rustApi.diffPages = [const []];
+
+ await expectLater(displayService.ensureReady(session), completes);
+ expect(rustApi.ctx.getDiffCalls, 2);
+ });
}
class FakeContactsRustApi implements ContactsRustApi {
@@ -290,6 +311,8 @@ class FakeContactsRustContext implements ContactsRustContext {
Completer<void>? diffBarrier;
Completer<void>? diffStarted;
Object? profilePictureError;
+ Object? diffError;
+ int getDiffCalls = 0;
@override
Future<ContactRecord> createContact(ContactData data) async {
@@ -365,12 +388,17 @@ class FakeContactsRustContext implements ContactsRustContext {
@override
Future<List<ContactRecord>> getDiff(int sinceTime, int limit) async {
+ getDiffCalls += 1;
final barrier = diffBarrier;
if (barrier != null) {
diffStarted?.complete();
diffBarrier = null;
await barrier.future;
}
+ final error = diffError;
+ if (error != null) {
+ throw error;
+ }
if (diffPages.isEmpty) {
return const [];
}