Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][photos] isolate contacts session state and localize picker UI

Neeraj Gupta1c8a76d6a913
diff --git a/mobile/apps/photos/lib/l10n/intl_en.arb b/mobile/apps/photos/lib/l10n/intl_en.arb
index 42c60c536d..351f7472e1 100644
--- a/mobile/apps/photos/lib/l10n/intl_en.arb
+++ b/mobile/apps/photos/lib/l10n/intl_en.arb
@@ -2989,6 +2989,10 @@
"@couldNotLoadAlbums": {
"description": "Error when albums fail to load"
},
+ "couldNotLoadSelectedPhoto": "Could not load selected photo",
+ "@couldNotLoadSelectedPhoto": {
+ "description": "Toast when the selected contact photo cannot be loaded"
+ },
"albumsCount": "{count, plural, =1{1 album} other{{count} albums}}",
"@albumsCount": {
"description": "Number of albums with pluralization",
diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dart
index 291dc83f25..b14edea16a 100644
--- a/mobile/apps/photos/lib/services/photos_contacts_service.dart
+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart
@@ -8,25 +8,29 @@ import "package:photos/service_locator.dart";
class PhotosContactsService {
PhotosContactsService._privateConstructor()
- : _contacts = contacts.ContactsService(
- preferences: ServiceLocator.instance.prefs,
- );
+ : _contactsServiceFactory = (() => contacts.ContactsService(
+ preferences: ServiceLocator.instance.prefs,
+ ));
@visibleForTesting
PhotosContactsService.forTesting({
- required contacts.ContactsService contactsService,
- }) : _contacts = contactsService;
+ contacts.ContactsService? contactsService,
+ contacts.ContactsService Function()? contactsServiceFactory,
+ }) : _contacts = contactsService,
+ _contactsServiceFactory = contactsServiceFactory ??
+ (contactsService != null ? () => contactsService : null);
static final PhotosContactsService instance =
PhotosContactsService._privateConstructor();
- final contacts.ContactsService _contacts;
+ final contacts.ContactsService Function()? _contactsServiceFactory;
final _logger = Logger("PhotosContactsService");
final Map<int, contacts.ContactRecord> _contactsByUserId = {};
final Map<int, Uint8List?> _profilePictureBytesByUserId = {};
final Set<int> _resolvedProfilePictureUserIds = {};
final Map<int, Future<Uint8List?>> _profilePictureLoadsByUserId = {};
+ contacts.ContactsService? _contacts;
Future<void>? _readyFuture;
String? _sessionKey;
String? _sessionAuthToken;
@@ -52,9 +56,10 @@ class PhotosContactsService {
}
final sessionKey = _buildSessionKey(session);
if (_readyFuture != null && _sessionKey == sessionKey) {
+ final contacts = _requireContacts();
await _readyFuture;
if (_sessionAuthToken != session.authToken) {
- await _contacts.updateAuthToken(session.authToken);
+ await contacts.updateAuthToken(session.authToken);
_sessionAuthToken = session.authToken;
}
return;
@@ -63,11 +68,14 @@ class PhotosContactsService {
_sessionGeneration += 1;
_resetSessionState(notify: true);
}
+ _contacts ??= _newContactsService();
+ final currentContacts = _requireContacts();
_sessionKey = sessionKey;
_sessionAuthToken = session.authToken;
late final Future<void> readyFuture;
final generation = _sessionGeneration;
readyFuture = _openAndSync(
+ currentContacts,
session,
generation,
).catchError((Object error, StackTrace stackTrace) {
@@ -91,10 +99,11 @@ class PhotosContactsService {
return _runReadSafely(
() async {
await ensureReady();
- if (_sessionKey == null) {
+ final contacts = _activeContactsOrNull();
+ if (contacts == null) {
return null;
}
- final contact = await _contacts.getContactByUserId(contactUserId);
+ final contact = await contacts.getContactByUserId(contactUserId);
if (contact == null || contact.isDeleted) {
return null;
}
@@ -161,14 +170,21 @@ class PhotosContactsService {
Future<Uint8List?> _loadProfilePictureBytesByUserId(int contactUserId) async {
final contact = await getContactByUserId(contactUserId);
final attachmentId = contact?.profilePictureAttachmentId;
- if (contact == null || attachmentId == null) {
+ if (contact == null) {
+ if (_hasHydratedCache && _sessionKey != null) {
+ _profilePictureBytesByUserId.remove(contactUserId);
+ _resolvedProfilePictureUserIds.add(contactUserId);
+ }
+ return null;
+ }
+ if (attachmentId == null) {
_profilePictureBytesByUserId.remove(contactUserId);
_resolvedProfilePictureUserIds.add(contactUserId);
return null;
}
final contactId = contact.id;
try {
- final bytes = await _contacts.getProfilePicture(contactId);
+ final bytes = await _requireContacts().getProfilePicture(contactId);
final latestContact = _contactsByUserId[contactUserId];
if (latestContact == null ||
latestContact.isDeleted ||
@@ -194,14 +210,14 @@ class PhotosContactsService {
required String name,
String? birthDate,
}) async {
- await ensureReady();
+ final contactsService = await _ensureReadyForWrite();
final trimmedName = name.trim();
final trimmedBirthDate = birthDate?.trim();
final normalizedBirthDate =
trimmedBirthDate == null || trimmedBirthDate.isEmpty
? null
: trimmedBirthDate;
- final existing = await _contacts.getContactByUserId(
+ final existing = await contactsService.getContactByUserId(
contactUserId,
includeDeleted: true,
);
@@ -211,8 +227,8 @@ class PhotosContactsService {
birthDate: normalizedBirthDate,
);
final contact = existing == null
- ? await _contacts.createContact(data)
- : await _contacts.updateContact(existing.id, data);
+ ? await contactsService.createContact(data)
+ : await contactsService.updateContact(existing.id, data);
_cacheContact(contact);
_notifyChanged(contact);
return contact;
@@ -222,8 +238,8 @@ class PhotosContactsService {
required String contactId,
required Uint8List bytes,
}) async {
- await ensureReady();
- final contact = await _contacts.setProfilePicture(contactId, bytes);
+ final contactsService = await _ensureReadyForWrite();
+ final contact = await contactsService.setProfilePicture(contactId, bytes);
_cacheContact(contact);
_profilePictureBytesByUserId[contact.contactUserId] = bytes;
_resolvedProfilePictureUserIds.add(contact.contactUserId);
@@ -238,9 +254,11 @@ class PhotosContactsService {
_sessionGeneration += 1;
_resetSessionState(notify: false);
}
+ _contacts ??= _newContactsService();
+ final currentContacts = _requireContacts();
_sessionKey = _buildSessionKey(session);
_sessionAuthToken = session.authToken;
- await _openAndSync(session, _sessionGeneration);
+ await _openAndSync(currentContacts, session, _sessionGeneration);
}
@visibleForTesting
@@ -285,16 +303,17 @@ class PhotosContactsService {
}
Future<void> _openAndSync(
+ contacts.ContactsService contactsService,
contacts.ContactsSession session,
int generation,
) async {
- await _contacts.open(session);
+ await contactsService.open(session);
if (!_isSessionGenerationCurrent(generation, session)) {
return;
}
final cachedUserIdsBeforeHydration = _contactsByUserId.keys.toSet();
- final localContacts = await _contacts.getContacts();
+ final localContacts = await contactsService.getContacts();
if (!_isSessionGenerationCurrent(generation, session)) {
return;
}
@@ -309,7 +328,7 @@ class PhotosContactsService {
final changedUserIds = <int>{...newlyHydratedLocalUserIds};
var shouldRetrySync = false;
try {
- final contactsDiff = await _contacts.sync();
+ final contactsDiff = await contactsService.sync();
if (!_isSessionGenerationCurrent(generation, session)) {
return;
}
@@ -398,12 +417,17 @@ class PhotosContactsService {
void _cacheContact(contacts.ContactRecord contact) {
final userId = contact.contactUserId;
+ final existing = _contactsByUserId[userId];
if (contact.isDeleted) {
_contactsByUserId.remove(userId);
_invalidateProfilePictureCache(userId);
return;
}
_contactsByUserId[userId] = contact;
+ if (existing?.profilePictureAttachmentId !=
+ contact.profilePictureAttachmentId) {
+ _invalidateProfilePictureCache(userId);
+ }
}
void _resetSessionState({required bool notify}) {
@@ -413,6 +437,7 @@ class PhotosContactsService {
_resolvedProfilePictureUserIds.clear();
_profilePictureLoadsByUserId.clear();
_readyFuture = null;
+ _contacts = null;
_sessionKey = null;
_sessionAuthToken = null;
_hasHydratedCache = false;
@@ -426,4 +451,42 @@ class PhotosContactsService {
_resolvedProfilePictureUserIds.remove(contactUserId);
_profilePictureLoadsByUserId.remove(contactUserId);
}
+
+ contacts.ContactsService _newContactsService() {
+ final factory = _contactsServiceFactory;
+ if (factory != null) {
+ return factory();
+ }
+ throw StateError(
+ "PhotosContactsService was not initialized with a contacts service factory",
+ );
+ }
+
+ contacts.ContactsService _requireContacts() {
+ final contacts = _contacts;
+ if (contacts == null) {
+ throw StateError(
+ "PhotosContactsService.ensureReady() must be called before use",
+ );
+ }
+ return contacts;
+ }
+
+ contacts.ContactsService? _activeContactsOrNull() {
+ if (_sessionKey == null) {
+ return null;
+ }
+ return _contacts;
+ }
+
+ Future<contacts.ContactsService> _ensureReadyForWrite() async {
+ await ensureReady();
+ final contacts = _activeContactsOrNull();
+ if (contacts == null) {
+ throw StateError(
+ "Contacts are unavailable without an active session",
+ );
+ }
+ return contacts;
+ }
}
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 0013825787..a615963c90 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
@@ -239,9 +239,7 @@ class _LinkContactToPersonSelectionPageState
final slivers = <Widget>[
SearchableAppBar(
title: Text(
- widget.mode == PersonSelectionMode.autofillContact
- ? "Select a person"
- : context.l10n.selectPersonToLink,
+ context.l10n.selectPersonToLink,
),
onSearch: _updateSearchQuery,
onSearchClosed: _clearSearchQuery,
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 ab82c11f5c..c388dd4c2c 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
@@ -358,7 +358,10 @@ class _EditContactPageState extends State<EditContactPage> {
_isLoadingPhoto = false;
});
if (sourceBytes == null) {
- showShortToast(context, "Could not load selected photo");
+ showShortToast(
+ context,
+ AppLocalizations.of(context).couldNotLoadSelectedPhoto,
+ );
return;
}
final croppedBytes = await routeToPage(
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 ee02f4c53d..42f283c4c8 100644
--- a/mobile/apps/photos/test/services/photos_contacts_service_test.dart
+++ b/mobile/apps/photos/test/services/photos_contacts_service_test.dart
@@ -2,11 +2,31 @@ import 'dart:async';
import 'dart:collection';
import 'dart:typed_data';
+import 'package:dio/dio.dart';
import 'package:ente_contacts/contacts.dart' as contacts;
import 'package:flutter_test/flutter_test.dart';
+import 'package:package_info_plus/package_info_plus.dart';
+import 'package:photos/service_locator.dart';
import 'package:photos/services/photos_contacts_service.dart';
+import 'package:shared_preferences/shared_preferences.dart';
void main() {
+ setUpAll(() async {
+ SharedPreferences.setMockInitialValues({});
+ final prefs = await SharedPreferences.getInstance();
+ ServiceLocator.instance.init(
+ prefs,
+ Dio(),
+ Dio(),
+ PackageInfo(
+ appName: 'Photos',
+ packageName: 'photos',
+ version: '1.0.0',
+ buildNumber: '1',
+ ),
+ );
+ });
+
late FakeContactsService contactsService;
late PhotosContactsService service;
late contacts.ContactsSession session;
@@ -108,6 +128,105 @@ void main() {
expect(service.getCachedResolvedEmailByUserId(7), isNull);
},
);
+
+ test(
+ 'session switch creates a fresh contacts service instance',
+ () async {
+ final firstService = FakeContactsService(
+ localContacts: 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,
+ ),
+ ],
+ );
+ final secondService = FakeContactsService(
+ localContacts: 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,
+ ),
+ ],
+ );
+ final services = Queue<FakeContactsService>.of([
+ firstService,
+ secondService,
+ ]);
+ service = PhotosContactsService.forTesting(
+ contactsServiceFactory: () => services.removeFirst(),
+ );
+
+ firstService.openBarrier = Completer<void>();
+ final oldOpenAndSync = service.debugOpenAndSync(session);
+ await firstService.openStarted!.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);
+
+ firstService.openBarrier!.complete();
+ await oldOpenAndSync;
+
+ expect(firstService.openCalls, 1);
+ expect(secondService.openCalls, 1);
+ expect(service.getCachedSavedNameByUserId(9), 'Bob');
+ expect(service.getCachedSavedNameByUserId(7), isNull);
+ },
+ );
+
+ test(
+ 'profile picture retry is restored when local hydration later adds an attachment',
+ () async {
+ contactsService = FakeContactsService(localContacts: const []);
+ service =
+ PhotosContactsService.forTesting(contactsService: contactsService);
+
+ await service.debugOpenAndSync(session);
+ expect(await service.getProfilePictureBytesByUserId(7), isNull);
+
+ contactsService.profilePictureBytesByContactId['ct_1'] =
+ Uint8List.fromList([1, 2, 3]);
+ service.debugHydrateContacts(
+ const [
+ contacts.ContactRecord(
+ id: 'ct_1',
+ contactUserId: 7,
+ email: '[email protected]',
+ data: contacts.ContactData(contactUserId: 7, name: 'Alice'),
+ profilePictureAttachmentId: 'att_1',
+ isDeleted: false,
+ createdAt: 1,
+ updatedAt: 2,
+ ),
+ ],
+ );
+
+ expect(
+ await service.getProfilePictureBytesByUserId(7),
+ Uint8List.fromList([1, 2, 3]),
+ );
+ expect(contactsService.getProfilePictureCalls, 1);
+ },
+ );
}
class FakeContactsService extends Fake implements contacts.ContactsService {
@@ -122,15 +241,27 @@ class FakeContactsService extends Fake implements contacts.ContactsService {
final Object? syncError;
Queue<List<contacts.ContactRecord>>? localContactsPages;
Queue<List<contacts.ContactRecord>>? syncPages;
+ final Map<String, Uint8List> profilePictureBytesByContactId = {};
+ Completer<void>? openBarrier;
+ Completer<void>? openStarted;
Completer<void>? getContactsBarrier;
Completer<void>? getContactsStarted;
int openCalls = 0;
int syncCalls = 0;
int getContactsCalls = 0;
+ int getProfilePictureCalls = 0;
@override
Future<void> open(contacts.ContactsSession session) async {
openCalls += 1;
+ final started = openStarted ??= Completer<void>();
+ if (!started.isCompleted) {
+ started.complete();
+ }
+ final barrier = openBarrier;
+ if (barrier != null && !barrier.isCompleted) {
+ await barrier.future;
+ }
}
@override
@@ -165,4 +296,14 @@ class FakeContactsService extends Fake implements contacts.ContactsService {
}
return syncDiff;
}
+
+ @override
+ Future<Uint8List> getProfilePicture(String contactId) async {
+ getProfilePictureCalls += 1;
+ final bytes = profilePictureBytesByContactId[contactId];
+ if (bytes == null) {
+ throw StateError('missing profile picture');
+ }
+ return bytes;
+ }
}