Skip to content

armgit / ente

Public Imported from GitHub
0

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

Simplify user and contact identity resolution

Neeraj Gupta12402fabe7ed
diff --git a/mobile/apps/locker/lib/services/collections/collections_service.dart b/mobile/apps/locker/lib/services/collections/collections_service.dart
index 03c6c8eb2f..3e0fffcdd0 100644
--- a/mobile/apps/locker/lib/services/collections/collections_service.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_service.dart
@@ -875,62 +875,47 @@ class CollectionService {
/// - Owners of collections shared to user.
/// - All collaborators of collections in which user is a collaborator or
/// a viewer.
- List<User> getRelevantContacts() {
- final List<User> relevantUsers = [];
- final existingEmails = <String>{};
+ List<UserSuggestion> getRelevantContacts() {
final int ownerID = Configuration.instance.getUserID()!;
final String ownerEmail = Configuration.instance.getEmail()!;
- existingEmails.add(ownerEmail);
+ final suggestions = <UserSuggestion>[];
+ final existingEmails = <String>{ownerEmail};
+
+ void add(String email, {int? userID}) {
+ if (email.isNotEmpty && existingEmails.add(email)) {
+ suggestions.add(UserSuggestion(email, userID: userID));
+ }
+ }
for (final c in getActiveCollections()) {
- // Add collaborators and viewers of collections owned by user
if (c.owner.id == ownerID) {
+ // Collaborators and viewers of collections owned by user
for (final User u in c.sharees) {
- if (u.id != null && u.email.isNotEmpty) {
- if (!existingEmails.contains(u.email)) {
- relevantUsers.add(u);
- existingEmails.add(u.email);
- }
- }
+ add(u.email, userID: u.id);
}
- } else if (c.owner.id != null && c.owner.email.isNotEmpty) {
+ } else if (c.owner.email.isNotEmpty) {
// Add owners of collections shared with user
- if (!existingEmails.contains(c.owner.email)) {
- relevantUsers.add(c.owner);
- existingEmails.add(c.owner.email);
- }
- // Add collaborators of collections shared with user where user is a
- // viewer or a collaborator
- for (final User u in c.sharees) {
- if (u.id != null &&
- u.email.isNotEmpty &&
- u.email == ownerEmail &&
- (u.isCollaborator || u.isViewer)) {
- for (final User u in c.sharees) {
- if (u.id != null && u.email.isNotEmpty && u.isCollaborator) {
- if (!existingEmails.contains(u.email)) {
- relevantUsers.add(u);
- existingEmails.add(u.email);
- }
- }
+ add(c.owner.email, userID: c.owner.id);
+ // Collaborators of collections in which user participates
+ final participates = c.sharees.any(
+ (u) => u.email == ownerEmail && (u.isCollaborator || u.isViewer),
+ );
+ if (participates) {
+ for (final User u in c.sharees) {
+ if (u.isCollaborator) {
+ add(u.email, userID: u.id);
}
- break;
}
}
}
}
- // Add user's family members
- final cachedUserDetails = UserService.instance.getCachedUserDetails();
- if (cachedUserDetails?.familyData?.members?.isNotEmpty ?? false) {
- for (final member in cachedUserDetails!.familyData!.members!) {
- if (!existingEmails.contains(member.email)) {
- relevantUsers.add(User(email: member.email));
- existingEmails.add(member.email);
- }
- }
+ final familyMembers =
+ UserService.instance.getCachedUserDetails()?.familyData?.members ?? [];
+ for (final member in familyMembers) {
+ add(member.email, userID: member.userID);
}
- return relevantUsers;
+ return suggestions;
}
String getPublicUrl(Collection c) {
diff --git a/mobile/apps/locker/lib/services/collections/models/collection.dart b/mobile/apps/locker/lib/services/collections/models/collection.dart
index d1229c2aea..9376c7e2fc 100644
--- a/mobile/apps/locker/lib/services/collections/models/collection.dart
+++ b/mobile/apps/locker/lib/services/collections/models/collection.dart
@@ -113,7 +113,7 @@ class Collection {
}
bool isOwner(int userID) {
- return (owner.id ?? -100) == userID;
+ return owner.id == userID;
}
bool isDownloadEnabledForPublicLink() {
diff --git a/mobile/apps/locker/lib/services/db/locker_db.dart b/mobile/apps/locker/lib/services/db/locker_db.dart
index b2084489ff..858431cac2 100644
--- a/mobile/apps/locker/lib/services/db/locker_db.dart
+++ b/mobile/apps/locker/lib/services/db/locker_db.dart
@@ -659,8 +659,6 @@ class LockerDB extends EnteBaseDatabase {
Map<String, dynamic> _collectionPayloadToMap(Collection collection) {
return {
'owner_email': collection.owner.email,
- // ignore: deprecated_member_use
- 'owner_name': collection.owner.name,
'name': collection.name,
'attributes_version': collection.attributes.version,
'attributes_encrypted_path': collection.attributes.encryptedPath,
@@ -682,9 +680,8 @@ class LockerDB extends EnteBaseDatabase {
final payload = _collectionPayloadFromRow(map);
final owner = User(
- id: map['owner_id'] as int?,
+ id: map['owner_id'] as int,
email: payload['owner_email'] as String? ?? '',
- name: payload['owner_name'] as String?,
);
final attributes = CollectionAttributes(
@@ -755,7 +752,6 @@ class LockerDB extends EnteBaseDatabase {
return {
'owner_email': map['owner_email'],
- 'owner_name': map['owner_name'],
'name': map['name'],
'attributes_version': map['attributes_version'],
'attributes_encrypted_path': map['attributes_encrypted_path'],
@@ -779,7 +775,7 @@ class LockerDB extends EnteBaseDatabase {
throw Exception('Invalid collections row: missing encrypted key');
}
- final owner = User(id: map['owner_id'] as int?, email: '');
+ final owner = User(id: map['owner_id'] as int, email: '');
final collection = Collection(
map['id'] as int,
owner,
diff --git a/mobile/apps/locker/lib/ui/components/collection_list_widget.dart b/mobile/apps/locker/lib/ui/components/collection_list_widget.dart
index 8e92b00713..50d585e427 100644
--- a/mobile/apps/locker/lib/ui/components/collection_list_widget.dart
+++ b/mobile/apps/locker/lib/ui/components/collection_list_widget.dart
@@ -210,7 +210,6 @@ class CollectionListWidget extends StatelessWidget {
child: UserAvatarWidget(
owner,
type: AvatarType.mini,
- thumbnailView: true,
config: Configuration.instance,
),
);
diff --git a/mobile/apps/locker/lib/ui/components/file_list_widget.dart b/mobile/apps/locker/lib/ui/components/file_list_widget.dart
index 20695dc430..c17b57b72f 100644
--- a/mobile/apps/locker/lib/ui/components/file_list_widget.dart
+++ b/mobile/apps/locker/lib/ui/components/file_list_widget.dart
@@ -204,7 +204,6 @@ class FileListWidget extends StatelessWidget {
child: UserAvatarWidget(
owner,
type: AvatarType.mini,
- thumbnailView: true,
config: Configuration.instance,
),
);
diff --git a/mobile/apps/locker/lib/ui/sharing/add_email_bottom_sheet.dart b/mobile/apps/locker/lib/ui/sharing/add_email_bottom_sheet.dart
index 731a5cd13c..095e1cffd2 100644
--- a/mobile/apps/locker/lib/ui/sharing/add_email_bottom_sheet.dart
+++ b/mobile/apps/locker/lib/ui/sharing/add_email_bottom_sheet.dart
@@ -59,7 +59,7 @@ class _AddEmailSheetState extends State<AddEmailSheet> {
final _scrollController = ScrollController();
late CollectionActions _collectionActions;
- late List<User> _suggestedUsers;
+ late List<UserSuggestion> _suggestedUsers;
@override
void initState() {
@@ -182,7 +182,7 @@ class _AddEmailSheetState extends State<AddEmailSheet> {
title: user.resolvedDisplayName,
),
leadingIconSize: 24.0,
- leadingIconWidget: UserAvatarWidget(
+ leadingIconWidget: UserAvatarWidget.suggestion(
user,
type: AvatarType.mini,
config: Configuration.instance,
@@ -362,48 +362,39 @@ class _AddEmailSheetState extends State<AddEmailSheet> {
}
}
- List<User> _getSuggestedUsers() {
- final List<User> suggestedUsers = [];
- final Set<String> existingEmails = {};
-
- existingEmails.add(Configuration.instance.getEmail() ?? "");
+ List<UserSuggestion> _getSuggestedUsers() {
final int ownerID = Configuration.instance.getUserID()!;
+ final suggestedUsers = <UserSuggestion>[];
+ final existingEmails = <String>{Configuration.instance.getEmail() ?? ""};
+
+ void add(String email, {int? userID}) {
+ if (email.isNotEmpty && existingEmails.add(email)) {
+ suggestedUsers.add(UserSuggestion(email, userID: userID));
+ }
+ }
for (final c in CollectionService.instance.getActiveCollections()) {
if (c.owner.id == ownerID) {
for (final User u in c.sharees) {
- if (u.id != null &&
- u.email.isNotEmpty &&
- !existingEmails.contains(u.email)) {
- existingEmails.add(u.email);
- suggestedUsers.add(u);
- }
+ add(u.email, userID: u.id);
}
- } else if (c.owner.id != null &&
- c.owner.email.isNotEmpty &&
- !existingEmails.contains(c.owner.email)) {
- existingEmails.add(c.owner.email);
- suggestedUsers.add(c.owner);
+ } else {
+ add(c.owner.email, userID: c.owner.id);
}
}
- final cachedUserDetails = UserService.instance.getCachedUserDetails();
- if (cachedUserDetails != null &&
- (cachedUserDetails.familyData?.members?.isNotEmpty ?? false)) {
- for (final member in cachedUserDetails.familyData!.members!) {
- if (!existingEmails.contains(member.email)) {
- existingEmails.add(member.email);
- suggestedUsers.add(User(email: member.email));
- }
- }
+ final familyMembers =
+ UserService.instance.getCachedUserDetails()?.familyData?.members ?? [];
+ for (final member in familyMembers) {
+ add(member.email, userID: member.userID);
}
- suggestedUsers.sort((a, b) => a.email.compareTo(b.email));
- suggestedUsers.sort(
- (a, b) => a.resolvedDisplayName.toLowerCase().compareTo(
+ suggestedUsers.sort((a, b) {
+ final byName = a.resolvedDisplayName.toLowerCase().compareTo(
b.resolvedDisplayName.toLowerCase(),
- ),
- );
+ );
+ return byName != 0 ? byName : a.email.compareTo(b.email);
+ });
return suggestedUsers;
}
diff --git a/mobile/apps/locker/lib/ui/sharing/album_share_info_widget.dart b/mobile/apps/locker/lib/ui/sharing/album_share_info_widget.dart
index 83f0494069..aa5612281e 100644
--- a/mobile/apps/locker/lib/ui/sharing/album_share_info_widget.dart
+++ b/mobile/apps/locker/lib/ui/sharing/album_share_info_widget.dart
@@ -37,7 +37,6 @@ class AlbumSharesIcons extends StatelessWidget {
left: overlapPadding * index,
child: UserAvatarWidget(
sharees[index],
- thumbnailView: removeBorder,
type: type,
config: Configuration.instance,
),
diff --git a/mobile/apps/locker/lib/ui/sharing/share_collection_bottom_sheet.dart b/mobile/apps/locker/lib/ui/sharing/share_collection_bottom_sheet.dart
index 2025a4a9b3..91efd36818 100644
--- a/mobile/apps/locker/lib/ui/sharing/share_collection_bottom_sheet.dart
+++ b/mobile/apps/locker/lib/ui/sharing/share_collection_bottom_sheet.dart
@@ -90,7 +90,6 @@ class _ShareCollectionSheetState extends State<ShareCollectionSheet> {
Widget _buildShareesList() {
final colors = context.componentColors;
- final currentUserId = Configuration.instance.getUserID() ?? -1;
final List<User> allUsers = [];
@@ -144,7 +143,6 @@ class _ShareCollectionSheetState extends State<ShareCollectionSheet> {
leadingIconSize: 24,
leadingIconWidget: UserAvatarWidget(
user,
- currentUserID: currentUserId,
config: Configuration.instance,
type: AvatarType.mini,
),
@@ -296,7 +294,7 @@ class _ShareCollectionSheetState extends State<ShareCollectionSheet> {
builder: (_) => BottomSheetComponent(
title: context.strings.changePermissions,
message: context.strings.cannotAddMoreFilesAfterBecomingViewer(
- name: user.displayName ?? user.email,
+ name: user.resolvedDisplayName,
),
illustration: LockerBottomSheetIllustration.warningGrey,
actions: [
@@ -336,7 +334,7 @@ class _ShareCollectionSheetState extends State<ShareCollectionSheet> {
builder: (_) => BottomSheetComponent(
title: context.strings.removeWithQuestionMark,
message: context.strings.removeCollectionParticipantBody(
- userEmail: user.displayName ?? user.email,
+ userEmail: user.resolvedDisplayName,
),
illustration: LockerBottomSheetIllustration.warningGrey,
actions: [
diff --git a/mobile/apps/photos/lib/emergency/emergency_page.dart b/mobile/apps/photos/lib/emergency/emergency_page.dart
index 0a5b760ae0..63336cc3b7 100644
--- a/mobile/apps/photos/lib/emergency/emergency_page.dart
+++ b/mobile/apps/photos/lib/emergency/emergency_page.dart
@@ -3,7 +3,6 @@ import "dart:async";
import "package:ente_strings/ente_strings.dart";
import "package:flutter/foundation.dart";
import "package:flutter/material.dart";
-import "package:photos/core/configuration.dart";
import "package:photos/emergency/components/email_action_sheet.dart";
import "package:photos/emergency/components/trusted_contact_sheet.dart";
import "package:photos/emergency/emergency_service.dart";
@@ -30,13 +29,11 @@ class EmergencyPage extends StatefulWidget {
}
class _EmergencyPageState extends State<EmergencyPage> {
- late int currentUserID;
EmergencyInfo? info;
@override
void initState() {
super.initState();
- currentUserID = Configuration.instance.getUserID()!;
Future.delayed(const Duration(seconds: 0), () async {
unawaited(_fetchData());
});
@@ -122,7 +119,6 @@ class _EmergencyPageState extends State<EmergencyPage> {
leadingIconWidget: UserAvatarWidget(
emergencyUser,
type: AvatarType.medium,
- currentUserID: currentUserID,
),
menuItemColor: colorScheme.fillFaint,
trailingWidget: _buildTrailingWidget(showWarning: false),
@@ -166,7 +162,6 @@ class _EmergencyPageState extends State<EmergencyPage> {
leadingIconWidget: UserAvatarWidget(
emergencyUser,
type: AvatarType.medium,
- currentUserID: currentUserID,
),
menuItemColor: colorScheme.fillFaint,
trailingWidget: _buildTrailingWidget(
@@ -272,7 +267,6 @@ class _EmergencyPageState extends State<EmergencyPage> {
leadingIconWidget: UserAvatarWidget(
emergencyUser,
type: AvatarType.medium,
- currentUserID: currentUserID,
),
menuItemColor: colorScheme.fillFaint,
trailingWidget: _buildTrailingWidget(
diff --git a/mobile/apps/photos/lib/emergency/select_contact_page.dart b/mobile/apps/photos/lib/emergency/select_contact_page.dart
index d1f0c1a552..ae6dbf6d66 100644
--- a/mobile/apps/photos/lib/emergency/select_contact_page.dart
+++ b/mobile/apps/photos/lib/emergency/select_contact_page.dart
@@ -67,7 +67,7 @@ class _AddContactSheetState extends State<AddContactSheet> {
Widget build(BuildContext context) {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
- final List<User> suggestedUsers = _getSuggestedUser();
+ final List<UserSuggestion> suggestedUsers = _getSuggestedUser();
final List<String> emailsToAdd = _emailsToAdd;
final bool canAdd = emailsToAdd.isNotEmpty;
final String? emailForVerification = _emailForVerification;
@@ -124,12 +124,11 @@ class _AddContactSheetState extends State<AddContactSheet> {
listIndex: index,
isLastItem: isLastItem,
child: MenuItemWidgetNew(
- title: resolveDisplayName(user),
+ title: resolveSuggestionDisplayName(user),
titleColor: colorScheme.textMuted,
- leadingIconWidget: UserAvatarWidget(
+ leadingIconWidget: UserAvatarWidget.suggestion(
user,
type: AvatarType.medium,
- currentUserID: Configuration.instance.getUserID()!,
),
leadingIconSize: 24,
menuItemColor: Colors.transparent,
@@ -292,46 +291,35 @@ class _AddContactSheetState extends State<AddContactSheet> {
await showVerifyIdentitySheet(context, self: false, email: emailToAdd);
}
- List<User> _getSuggestedUser() {
- final List<User> suggestedUsers = [];
- final Set<String> existingEmails = {};
+ List<UserSuggestion> _getSuggestedUser() {
final int ownerID = Configuration.instance.getUserID()!;
- existingEmails.add(Configuration.instance.getEmail()!);
+ final suggestedUsers = <UserSuggestion>[];
+ final existingEmails = <String>{Configuration.instance.getEmail()!};
- for (final contact in widget.emergencyInfo.othersEmergencyContact) {
- if (!existingEmails.contains(contact.user.email)) {
- existingEmails.add(contact.user.email);
- suggestedUsers.add(contact.user);
+ void add(String email, {int? userID}) {
+ if (email.isNotEmpty && existingEmails.add(email)) {
+ suggestedUsers.add(UserSuggestion(email, userID: userID));
}
}
+ for (final contact in widget.emergencyInfo.othersEmergencyContact) {
+ add(contact.user.email, userID: contact.user.id);
+ }
+
for (final c in CollectionsService.instance.getActiveCollections()) {
if (c.owner.id == ownerID) {
for (final User u in c.sharees) {
- if (u.id != null &&
- u.email.isNotEmpty &&
- !existingEmails.contains(u.email)) {
- existingEmails.add(u.email);
- suggestedUsers.add(u);
- }
+ add(u.email, userID: u.id);
}
- } else if (c.owner.id != null &&
- c.owner.email.isNotEmpty &&
- !existingEmails.contains(c.owner.email)) {
- existingEmails.add(c.owner.email);
- suggestedUsers.add(c.owner);
+ } else {
+ add(c.owner.email, userID: c.owner.id);
}
}
- final cachedUserDetails = UserService.instance.getCachedUserDetails();
- if (cachedUserDetails != null &&
- (cachedUserDetails.familyData?.members?.isNotEmpty ?? false)) {
- for (final member in cachedUserDetails.familyData!.members!) {
- if (!existingEmails.contains(member.email)) {
- existingEmails.add(member.email);
- suggestedUsers.add(User(email: member.email));
- }
- }
+ final familyMembers =
+ UserService.instance.getCachedUserDetails()?.familyData?.members ?? [];
+ for (final member in familyMembers) {
+ add(member.email, userID: member.userID);
}
if (_textController.text.trim().isNotEmpty) {
suggestedUsers.removeWhere(
diff --git a/mobile/apps/photos/lib/extensions/user_extension.dart b/mobile/apps/photos/lib/extensions/user_extension.dart
index 1b8a263f37..5a2b08c725 100644
--- a/mobile/apps/photos/lib/extensions/user_extension.dart
+++ b/mobile/apps/photos/lib/extensions/user_extension.dart
@@ -1,17 +1,13 @@
import "package:photos/models/api/collection/user.dart";
+import "package:photos/models/ml/face/person.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
extension UserExtension on User {
- Map<String, String>? get _partialPersonData => PersonService.instance
- .getCachedPartialPersonData(userID: id, email: email);
+ PersonEntity? get _person => _personFor(id, email);
- //Some initial users have name in name field.
- String? get displayName =>
- _partialPersonData?[PersonService.kNameKey] ??
- // ignore: deprecated_member_use_from_same_package
- ((name?.isEmpty ?? true) ? null : name);
+ String? get displayName => _person?.data.name ?? label;
- String? get linkedPersonID => _partialPersonData?[PersonService.kPersonIDKey];
+ String? get linkedPersonID => _person?.remoteID;
String get nameOrEmail {
if (PersonService.isInitialized) {
@@ -21,3 +17,12 @@ extension UserExtension on User {
}
}
}
+
+extension UserSuggestionExtension on UserSuggestion {
+ PersonEntity? get _person => _personFor(userID, email);
+
+ String? get displayName => _person?.data.name ?? label;
+}
+
+PersonEntity? _personFor(int? userID, String email) =>
+ PersonService.instance.getCachedPersonForUser(userID, email);
diff --git a/mobile/apps/photos/lib/models/api/collection/user.dart b/mobile/apps/photos/lib/models/api/collection/user.dart
index 02d9fdfb99..9b6ac232e1 100644
--- a/mobile/apps/photos/lib/models/api/collection/user.dart
+++ b/mobile/apps/photos/lib/models/api/collection/user.dart
@@ -1,16 +1,15 @@
import "dart:convert";
+// TODO(neeraj): Move User and UserSuggestion to a shared package.
class User {
- int? id;
+ final int id;
String email;
- @Deprecated(
- "Use displayName() extension method instead. Note: Some early users have"
- " value in name field.",
- )
- String? name;
+
+ /// Local-only display name for anonymous social actors; never serialized.
+ final String? label;
String? role;
- User({this.id, required this.email, this.name, this.role});
+ User({required this.id, required this.email, this.label, this.role});
bool get isViewer => role == null || role?.toUpperCase() == 'VIEWER';
@@ -20,15 +19,13 @@ class User {
bool get isAdmin => role != null && role?.toUpperCase() == 'ADMIN';
Map<String, dynamic> toMap() {
- // ignore: deprecated_member_use_from_same_package
- return {'id': id, 'email': email, 'name': name, "role": role};
+ return {'id': id, 'email': email, "role": role};
}
static User fromMap(Map<String, dynamic> map) {
return User(
- id: map['id'],
- email: map['email'],
- name: map['name'],
+ id: map['id'] as int,
+ email: map['email'] as String,
role: map['role'] ?? 'VIEWER',
);
}
@@ -37,3 +34,16 @@ class User {
factory User.fromJson(String source) => User.fromMap(json.decode(source));
}
+
+class UserSuggestion {
+ const UserSuggestion(this.email, {this.userID, this.label});
+
+ factory UserSuggestion.fromUser(User user) =>
+ UserSuggestion(user.email, userID: user.id, label: user.label);
+
+ final int? userID;
+ final String email;
+
+ /// Local-only display label; see [User.label].
+ final String? label;
+}
diff --git a/mobile/apps/photos/lib/models/collection/collection.dart b/mobile/apps/photos/lib/models/collection/collection.dart
index 6c369cc02a..cbcc78148b 100644
--- a/mobile/apps/photos/lib/models/collection/collection.dart
+++ b/mobile/apps/photos/lib/models/collection/collection.dart
@@ -155,12 +155,8 @@ class Collection {
!hasSharees;
}
- List<User> getSharees() {
- return sharees;
- }
-
bool isOwner(int userID) {
- return (owner.id ?? -100) == userID;
+ return owner.id == userID;
}
bool isAdmin(int userID) {
diff --git a/mobile/apps/photos/lib/models/social/comment_author_utils.dart b/mobile/apps/photos/lib/models/social/comment_author_utils.dart
index 05b3681849..af937517ab 100644
--- a/mobile/apps/photos/lib/models/social/comment_author_utils.dart
+++ b/mobile/apps/photos/lib/models/social/comment_author_utils.dart
@@ -10,7 +10,11 @@ class CommentAuthorResolver {
required User Function(int userID) registeredUserResolver,
}) {
if (comment.isAnonymous) {
- return _anonymousUserForComment(comment, anonDisplayNames);
+ return anonymousSocialUser(
+ userID: comment.userID,
+ anonUserID: comment.anonUserID,
+ anonDisplayNames: anonDisplayNames,
+ );
}
return _registeredUserCache.putIfAbsent(
@@ -24,18 +28,19 @@ class CommentAuthorResolver {
}
}
-User _anonymousUserForComment(
- Comment comment,
- Map<String, String> anonDisplayNames,
-) {
- final anonID = _normalizedAnonID(comment);
+User anonymousSocialUser({
+ required int userID,
+ required String? anonUserID,
+ required Map<String, String> anonDisplayNames,
+}) {
+ final anonID = _normalizeAnonID(anonUserID);
final displayName = anonID != null
? (anonDisplayNames[anonID] ?? anonID)
: "Anonymous";
return User(
- id: comment.userID,
+ id: userID,
email: "${anonID ?? "anonymous"}@unknown.com",
- name: displayName,
+ label: displayName,
);
}
@@ -80,6 +85,10 @@ String? _normalizedAnonID(Comment comment) {
if (!comment.isAnonymous) {
return null;
}
- final anonID = comment.anonUserID?.trim();
+ return _normalizeAnonID(comment.anonUserID);
+}
+
+String? _normalizeAnonID(String? value) {
+ final anonID = value?.trim();
return anonID == null || anonID.isEmpty ? null : anonID;
}
diff --git a/mobile/apps/photos/lib/models/social/feed_data_provider.dart b/mobile/apps/photos/lib/models/social/feed_data_provider.dart
index c073a6e83c..5bebb64e70 100644
--- a/mobile/apps/photos/lib/models/social/feed_data_provider.dart
+++ b/mobile/apps/photos/lib/models/social/feed_data_provider.dart
@@ -626,9 +626,6 @@ class FeedDataProvider {
.where((collection) => (collection.sharedAt ?? 0) > 0)
.map((collection) {
final ownerID = collection.owner.id;
- if (ownerID == null) {
- return null;
- }
final sharedFileIDs = initialSharedFileIDsByCollection[collection.id];
return FeedItem(
type: FeedItemType.sharedCollection,
@@ -644,7 +641,6 @@ class FeedDataProvider {
collectionName: collectionNames[collection.id],
);
})
- .whereType<FeedItem>()
.toList();
}
diff --git a/mobile/apps/photos/lib/services/account/user_service.dart b/mobile/apps/photos/lib/services/account/user_service.dart
index c29c114c8e..725b798b59 100644
--- a/mobile/apps/photos/lib/services/account/user_service.dart
+++ b/mobile/apps/photos/lib/services/account/user_service.dart
@@ -1246,74 +1246,53 @@ class UserService {
/// a viewer.
/// - All family members of user.
/// - All contacts linked to a person.
- List<User> getRelevantContacts() {
- final List<User> relevantUsers = [];
- final existingEmails = <String>{};
+ List<UserSuggestion> getRelevantContacts() {
final int ownerID = Configuration.instance.getUserID()!;
final String ownerEmail = Configuration.instance.getEmail()!;
- existingEmails.add(ownerEmail);
+ final suggestions = <UserSuggestion>[];
+ final existingEmails = <String>{ownerEmail};
+
+ void add(String email, {int? userID}) {
+ if (email.isNotEmpty && existingEmails.add(email)) {
+ suggestions.add(UserSuggestion(email, userID: userID));
+ }
+ }
for (final c in CollectionsService.instance.getActiveCollections()) {
- // Add collaborators and viewers of collections owned by user
if (c.owner.id == ownerID) {
+ // Collaborators and viewers of collections owned by user
for (final User u in c.sharees) {
- if (u.id != null && u.email.isNotEmpty) {
- if (!existingEmails.contains(u.email)) {
- relevantUsers.add(u);
- existingEmails.add(u.email);
- }
- }
- }
- } else if (c.owner.id != null && c.owner.email.isNotEmpty) {
- // Add owners of collections shared with user
- if (!existingEmails.contains(c.owner.email)) {
- relevantUsers.add(c.owner);
- existingEmails.add(c.owner.email);
+ add(u.email, userID: u.id);
}
- // Add collaborators of collections shared with user where user is a
- // viewer or a collaborator
- for (final User u in c.sharees) {
- if (u.id != null &&
- u.email.isNotEmpty &&
+ } else if (c.owner.email.isNotEmpty) {
+ // Owners of collections shared with user
+ add(c.owner.email, userID: c.owner.id);
+ // Collaborators of collections in which user participates
+ final participates = c.sharees.any(
+ (u) =>
u.email == ownerEmail &&
- (u.isAdmin || u.isCollaborator || u.isViewer)) {
- for (final User u in c.sharees) {
- if (u.id != null &&
- u.email.isNotEmpty &&
- (u.isCollaborator || u.isAdmin)) {
- if (!existingEmails.contains(u.email)) {
- relevantUsers.add(u);
- existingEmails.add(u.email);
- }
- }
+ (u.isAdmin || u.isCollaborator || u.isViewer),
+ );
+ if (participates) {
+ for (final User u in c.sharees) {
+ if (u.isCollaborator || u.isAdmin) {
+ add(u.email, userID: u.id);
}
- break;
}
}
}
}
- // Add user's family members
- final cachedUserDetails = getCachedUserDetails();
- if (cachedUserDetails?.familyData?.members?.isNotEmpty ?? false) {
- for (final member in cachedUserDetails!.familyData!.members!) {
- if (!existingEmails.contains(member.email)) {
- relevantUsers.add(User(id: member.userID, email: member.email));
- existingEmails.add(member.email);
- }
- }
+ final familyMembers =
+ getCachedUserDetails()?.familyData?.members ?? const <FamilyMember>[];
+ for (final member in familyMembers) {
+ add(member.email, userID: member.userID);
}
- // Add contacts linked to people
- final cachedEmailToPartialPersonData =
- PersonService.instance.emailToPartialPersonDataMapCache;
- for (final email in cachedEmailToPartialPersonData.keys) {
- if (!existingEmails.contains(email)) {
- relevantUsers.add(User(email: email));
- existingEmails.add(email);
- }
+ for (final email in PersonService.instance.cachedLinkedPersonEmails) {
+ add(email);
}
- return relevantUsers;
+ return suggestions;
}
}
diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dart
index faf2be973f..70eec2d82d 100644
--- a/mobile/apps/photos/lib/services/collections_service.dart
+++ b/mobile/apps/photos/lib/services/collections_service.dart
@@ -785,7 +785,7 @@ class CollectionsService {
if (collection.owner.id == userID) {
_cachedUserIdToUser[userID] = collection.owner;
} else {
- final matchingUser = collection.getSharees().firstWhereOrNull(
+ final matchingUser = collection.sharees.firstWhereOrNull(
(u) => u.id == userID,
);
if (matchingUser != null) {
diff --git a/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart b/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart
index f472b7610a..8074db0e54 100644
--- a/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart
+++ b/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart
@@ -3,55 +3,56 @@ import "package:photos/models/api/collection/user.dart";
import "package:photos/services/photos_contacts_service.dart";
import "package:photos/utils/contact_string_util.dart";
-String resolveDisplayName(User user) {
- final savedName = _savedContactName(user);
- if (savedName != null) {
- return savedName;
- }
+typedef ResolvedUserIdentity = ({String displayName, String? knownEmail});
+
+/// Precedence: saved contact name β†’ linked person name / local label β†’
+/// known email β†’ "Someone".
+ResolvedUserIdentity resolveSuggestionIdentity(UserSuggestion suggestion) {
+ final contact = PhotosContactsService.instance.getCachedContact(
+ contactUserId: suggestion.userID,
+ email: suggestion.email,
+ );
+ final knownEmail =
+ knownContactEmailOrNull(contact?.email) ??
+ knownContactEmailOrNull(suggestion.email);
+ return (
+ displayName:
+ trimToNull(contact?.data?.name) ??
+ trimToNull(suggestion.displayName) ??
+ knownEmail ??
+ "Someone",
+ knownEmail: knownEmail,
+ );
+}
- final personName = user.displayName?.trim();
- if (personName != null && personName.isNotEmpty) {
- return personName;
- }
+String resolveSuggestionDisplayName(UserSuggestion suggestion) =>
+ resolveSuggestionIdentity(suggestion).displayName;
- return resolveKnownEmail(user) ?? "Someone";
-}
+String resolveDisplayName(User user) =>
+ resolveSuggestionDisplayName(UserSuggestion.fromUser(user));
-String? resolveKnownEmail(User user) {
- final contactUserId = _validContactUserId(user);
- final savedEmail = knownContactEmailOrNull(
- PhotosContactsService.instance.getCachedResolvedEmail(
- contactUserId: contactUserId,
- email: contactUserId == null ? user.email : null,
- ),
- );
- if (savedEmail != null) {
- return savedEmail;
- }
+String? resolveKnownSuggestionEmail(UserSuggestion suggestion) =>
+ resolveSuggestionIdentity(suggestion).knownEmail;
- return knownContactEmailOrNull(user.email);
-}
+String? resolveKnownEmail(User user) =>
+ resolveKnownSuggestionEmail(UserSuggestion.fromUser(user));
-bool matchesResolvedContactQuery(User user, String lowerCaseQuery) {
+bool matchesResolvedSuggestionQuery(
+ UserSuggestion suggestion,
+ String lowerCaseQuery,
+) {
if (lowerCaseQuery.isEmpty) {
return true;
}
-
- final resolvedName = resolveDisplayName(user).toLowerCase();
- final resolvedEmail = (resolveKnownEmail(user) ?? user.email).toLowerCase();
- return resolvedName.contains(lowerCaseQuery) ||
- resolvedEmail.contains(lowerCaseQuery);
+ final identity = resolveSuggestionIdentity(suggestion);
+ return identity.displayName.toLowerCase().contains(lowerCaseQuery) ||
+ (identity.knownEmail ?? suggestion.email).toLowerCase().contains(
+ lowerCaseQuery,
+ );
}
-String? _savedContactName(User user) {
- final contactUserId = _validContactUserId(user);
- return PhotosContactsService.instance.getCachedSavedName(
- contactUserId: contactUserId,
- email: contactUserId == null ? user.email : null,
- );
-}
-
-int? _validContactUserId(User user) {
- final userId = user.id;
- return userId != null && userId > 0 ? userId : null;
-}
+bool matchesResolvedContactQuery(User user, String lowerCaseQuery) =>
+ matchesResolvedSuggestionQuery(
+ UserSuggestion.fromUser(user),
+ lowerCaseQuery,
+ );
diff --git a/mobile/apps/photos/lib/services/contacts/direct_contact_users.dart b/mobile/apps/photos/lib/services/contacts/direct_contact_users.dart
index a63952ec62..8e1d45ab6a 100644
--- a/mobile/apps/photos/lib/services/contacts/direct_contact_users.dart
+++ b/mobile/apps/photos/lib/services/contacts/direct_contact_users.dart
@@ -21,7 +21,7 @@ List<User> buildDirectContactUsers({
void addUser(User user) {
final userId = user.id;
- if (userId == null || userId <= 0 || userId == ownerUserId) {
+ if (userId <= 0 || userId == ownerUserId) {
return;
}
final normalizedEmail = normalizeContactLinkEmail(
@@ -45,8 +45,9 @@ List<User> buildDirectContactUsers({
}
for (final member in familyMembers) {
- if (member.isActive) {
- addUser(User(id: member.userID, email: member.email));
+ final userID = member.userID;
+ if (member.isActive && userID != null) {
+ addUser(User(id: userID, email: member.email));
}
}
diff --git a/mobile/apps/photos/lib/services/library_sharing_service.dart b/mobile/apps/photos/lib/services/library_sharing_service.dart
index 243784d178..73e0de7324 100644
--- a/mobile/apps/photos/lib/services/library_sharing_service.dart
+++ b/mobile/apps/photos/lib/services/library_sharing_service.dart
@@ -196,11 +196,7 @@ class LibrarySharingService implements LibrarySharingRepository {
Future<void> unshareAlbumFromAll(Collection collection) async {
final recipientUserIDs = collection.sharees
- .map(
- (sharee) =>
- sharee.id ??
- (throw StateError('A collection sharee has no user ID')),
- )
+ .map((sharee) => sharee.id)
.toList();
for (final recipientUserID in recipientUserIDs) {
final failedIDs = await unshareAlbums(
@@ -565,7 +561,7 @@ class LibrarySharingService implements LibrarySharingRepository {
String _recipientEmail(int recipientUserID) {
String? email;
for (final user in _userService.getRelevantContacts()) {
- if (user.id == recipientUserID) {
+ if (user.userID == recipientUserID) {
email = knownContactEmailOrNull(user.email) ?? email;
}
}
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 7fdd235dd5..29f53593cb 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
@@ -44,8 +44,8 @@ class PersonService {
final PhotosContactsService _contactsService;
final Future<Uint8List?> Function(PersonEntity) _contactPhotoBuilder;
final int? Function() _currentUserIDProvider;
- final _emailToPartialPersonDataMapCache = <String, Map<String, String>>{};
- final _userIdToPartialPersonDataMapCache = <int, Map<String, String>>{};
+ final _personsByEmail = <String, PersonEntity>{};
+ final _personsByUserId = <int, PersonEntity>{};
final _autoContactCreationsByUserId =
<int, Future<contacts.ContactRecord?>>{};
@@ -64,8 +64,6 @@ class PersonService {
// instance
static PersonService? _instance;
- static const kPersonIDKey = "person_id";
- static const kNameKey = "name";
static const double kDefaultAutoMergeThreshold = 0.24;
static double autoMergeThreshold = kDefaultAutoMergeThreshold;
@@ -98,22 +96,62 @@ class PersonService {
}
}
- Map<String, Map<String, String>> get emailToPartialPersonDataMapCache =>
- _emailToPartialPersonDataMapCache;
+ Iterable<String> get cachedLinkedPersonEmails => _personsByEmail.values
+ .map((person) => person.data.email)
+ .whereType<String>();
+
+ /// Prefers an account ID link, then supports legacy email-only person links.
+ PersonEntity? getCachedPersonForUser(int? userID, String email) {
+ final requestedUserID = userID != null && userID > 0 ? userID : null;
+ final userIdMatch = requestedUserID == null
+ ? null
+ : _personsByUserId[requestedUserID];
+ if (userIdMatch != null) return userIdMatch;
+
+ final normalizedEmail = normalizeContactLinkEmail(email);
+ if (normalizedEmail == null) return null;
+ final emailMatch = _personsByEmail[normalizedEmail];
+ return emailMatch != null &&
+ _canUseEmailFallback(emailMatch, requestedUserID)
+ ? emailMatch
+ : null;
+ }
- Map<String, String>? getCachedPartialPersonData({
+ static PersonEntity? findPersonForUser(
+ Iterable<PersonEntity> persons, {
required int? userID,
- required String email,
+ required String? email,
+ String? excludedPersonID,
}) {
- final userIdMatch = userID != null && userID > 0
- ? _userIdToPartialPersonDataMapCache[userID]
- : null;
- return userIdMatch ?? _emailToPartialPersonDataMapCache[email];
+ bool include(PersonEntity person) => person.remoteID != excludedPersonID;
+ final requestedUserID = userID != null && userID > 0 ? userID : null;
+ if (requestedUserID != null) {
+ for (final person in persons) {
+ if (include(person) && person.data.userID == requestedUserID) {
+ return person;
+ }
+ }
+ }
+
+ final normalizedEmail = normalizeContactLinkEmail(email);
+ if (normalizedEmail == null) return null;
+ for (final person in persons) {
+ if (include(person) &&
+ _canUseEmailFallback(person, requestedUserID) &&
+ normalizeContactLinkEmail(person.data.email) == normalizedEmail) {
+ return person;
+ }
+ }
+ return null;
+ }
+
+ static bool _canUseEmailFallback(PersonEntity person, int? requestedUserID) {
+ return requestedUserID == null || person.data.userID == null;
}
void clearCache() {
- _emailToPartialPersonDataMapCache.clear();
- _userIdToPartialPersonDataMapCache.clear();
+ _personsByEmail.clear();
+ _personsByUserId.clear();
_invalidatePersonCache();
_cachedRemoteSyncTime = 0;
}
@@ -180,20 +218,16 @@ class PersonService {
_cachedPersonsById = {
for (final person in persons) person.remoteID: person,
};
- _emailToPartialPersonDataMapCache.clear();
- _userIdToPartialPersonDataMapCache.clear();
+ _personsByEmail.clear();
+ _personsByUserId.clear();
for (PersonEntity person in persons) {
- final partialData = {
- kPersonIDKey: person.remoteID,
- kNameKey: person.data.name,
- };
- final email = person.data.email;
- if (email != null && email.isNotEmpty) {
- _emailToPartialPersonDataMapCache[email] = partialData;
+ final email = normalizeContactLinkEmail(person.data.email);
+ if (email != null) {
+ _personsByEmail[email] = person;
}
final userID = person.data.userID;
if (userID != null && userID > 0) {
- _userIdToPartialPersonDataMapCache[userID] = partialData;
+ _personsByUserId[userID] = person;
}
}
diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dart
index e8b8d87d1b..e939e5c765 100644
--- a/mobile/apps/photos/lib/services/photos_contacts_service.dart
+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart
@@ -6,88 +6,50 @@ 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";
+/// Photos-specific session and event adapter for the shared contact directory.
class PhotosContactsService {
PhotosContactsService._privateConstructor()
- : _contactsServiceFactory = (() => contacts.ContactsService(
- preferences: ServiceLocator.instance.prefs,
- )) {
- _attachSessionResetListeners();
+ : _store = contacts.ContactDirectory(
+ contactsServiceFactory: () => contacts.ContactsService(
+ preferences: ServiceLocator.instance.prefs,
+ ),
+ onContactsChanged: _notifyContactsChanged,
+ profilePictureFailureTtl: Duration.zero,
+ ) {
+ _attachSessionResetListener();
}
@visibleForTesting
PhotosContactsService.forTesting({
contacts.ContactsService? contactsService,
contacts.ContactsService Function()? contactsServiceFactory,
- }) : _contacts = contactsService,
- _contactsServiceFactory =
- contactsServiceFactory ??
- (contactsService != null ? () => contactsService : null) {
- _attachSessionResetListeners();
+ }) : _store = contacts.ContactDirectory(
+ contactsService: contactsService,
+ contactsServiceFactory: contactsServiceFactory,
+ onContactsChanged: _notifyContactsChanged,
+ profilePictureFailureTtl: Duration.zero,
+ ) {
+ _attachSessionResetListener();
}
static final PhotosContactsService instance =
PhotosContactsService._privateConstructor();
- final contacts.ContactsService Function()? _contactsServiceFactory;
+ final contacts.ContactDirectory _store;
final _logger = Logger("PhotosContactsService");
- // Deleted records evict entries; these indexes contain active contacts only.
- final Map<int, contacts.ContactRecord> _activeContactsByUserId = {};
- final Map<String, contacts.ContactRecord> _activeContactsByNormalizedEmail =
- {};
- 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;
- bool _hasHydratedCache = false;
- int _sessionGeneration = 0;
+ bool get hasHydratedCache => _store.hasHydratedCache;
- bool get hasHydratedCache => _hasHydratedCache;
-
- bool get needsWarmup => !_hasHydratedCache || _readyFuture == null;
+ bool get needsWarmup => _store.needsWarmup;
Future<void> ensureReady() async {
final session = _buildSession();
if (session == null) {
- _sessionGeneration += 1;
- _resetSessionState(notify: true);
- return;
- }
- final sessionKey = _buildSessionKey(session);
- if (_readyFuture != null && _sessionKey == sessionKey) {
- final contacts = _requireContacts();
- await _readyFuture;
- if (_sessionAuthToken != session.authToken) {
- await contacts.updateAuthToken(session.authToken);
- _sessionAuthToken = session.authToken;
- }
+ _store.clearSession();
return;
}
- if (_sessionKey != sessionKey) {
- _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) {
- if (identical(_readyFuture, readyFuture)) {
- _readyFuture = null;
- }
- throw error;
- },
- );
- _readyFuture = readyFuture;
- return readyFuture;
+ await _store.ensureReady(session);
}
Future<contacts.ContactRecord?> getContact({
@@ -100,24 +62,6 @@ class PhotosContactsService {
}
return _runReadSafely(() async {
await ensureReady();
- final hydratedCached = getCachedContact(
- contactUserId: contactUserId,
- email: email,
- );
- if (hydratedCached != null) {
- return hydratedCached;
- }
- if (contactUserId == null) {
- return null;
- }
- final contacts = _activeContactsOrNull();
- if (contacts == null) {
- return null;
- }
- final contact = await contacts.getContactByUserId(contactUserId);
- if (contact != null) {
- _cacheContact(contact);
- }
return getCachedContact(contactUserId: contactUserId, email: email);
}, description: "load contact for user $contactUserId");
}
@@ -125,136 +69,43 @@ class PhotosContactsService {
contacts.ContactRecord? getCachedContact({
int? contactUserId,
String? email,
- }) {
- if (_sessionKey == null) {
- return null;
- }
- if (contactUserId != null) {
- return _activeContactsByUserId[contactUserId];
- }
- final normalizedEmail = normalizeContactLinkEmail(email);
- return normalizedEmail == null
- ? null
- : _activeContactsByNormalizedEmail[normalizedEmail];
- }
+ }) => _store.getCachedContact(contactUserId: contactUserId, email: email);
- List<contacts.ContactRecord> getCachedContacts() {
- if (_sessionKey == null) {
- return const [];
- }
- return List.unmodifiable(_activeContactsByUserId.values);
- }
+ List<contacts.ContactRecord> getCachedContacts() =>
+ _store.getCachedContacts();
- String? getCachedSavedName({int? contactUserId, String? email}) {
- return trimToNull(
- getCachedContact(contactUserId: contactUserId, email: email)?.data?.name,
- );
- }
+ String? getCachedSavedName({int? contactUserId, String? email}) =>
+ _store.getCachedSavedName(contactUserId: contactUserId, email: email);
- String? getCachedResolvedEmail({int? contactUserId, String? email}) {
- return trimToNull(
- getCachedContact(contactUserId: contactUserId, email: email)?.email,
- );
- }
+ String? getCachedResolvedEmail({int? contactUserId, String? email}) =>
+ _store.getCachedResolvedEmail(contactUserId: contactUserId, email: email);
- Uint8List? getCachedProfilePictureBytesByUserId(int? contactUserId) {
- if (!hasResolvedProfilePictureByUserId(contactUserId)) {
- return null;
- }
- return _profilePictureBytesByUserId[contactUserId!];
- }
+ Uint8List? getCachedProfilePictureBytesByUserId(int? contactUserId) =>
+ _store.getCachedProfilePictureBytesByUserId(contactUserId);
- bool hasResolvedProfilePictureByUserId(int? contactUserId) {
- return contactUserId != null &&
- _sessionKey != null &&
- _resolvedProfilePictureUserIds.contains(contactUserId);
- }
+ bool hasResolvedProfilePictureByUserId(int? contactUserId) =>
+ _store.hasResolvedProfilePictureByUserId(contactUserId);
Future<Uint8List?> getProfilePictureBytesByUserId(int? contactUserId) async {
if (contactUserId == null) {
return null;
}
- if (_sessionKey == null) {
- return null;
- }
- if (hasResolvedProfilePictureByUserId(contactUserId)) {
- return _profilePictureBytesByUserId[contactUserId];
- }
- final contact = await getContact(contactUserId: contactUserId);
- if (contact == null) {
- if (_hasHydratedCache) {
- _profilePictureBytesByUserId.remove(contactUserId);
- _resolvedProfilePictureUserIds.add(contactUserId);
- }
- return null;
- }
- if (_resolvedProfilePictureUserIds.contains(contactUserId)) {
- return _profilePictureBytesByUserId[contactUserId];
- }
- final inflightLoad = _profilePictureLoadsByUserId[contactUserId];
- if (inflightLoad != null) {
- return inflightLoad;
- }
- final load = _loadProfilePictureBytes(contact);
- _profilePictureLoadsByUserId[contactUserId] = load;
- return load.whenComplete(() {
- _profilePictureLoadsByUserId.remove(contactUserId);
- });
- }
-
- Future<Uint8List?> _loadProfilePictureBytes(
- contacts.ContactRecord contact,
- ) async {
- final contactUserId = contact.contactUserId;
- final attachmentId = contact.profilePictureAttachmentId;
- if (attachmentId == null) {
- _profilePictureBytesByUserId.remove(contactUserId);
- _resolvedProfilePictureUserIds.add(contactUserId);
- return null;
- }
- final contactId = contact.id;
- try {
- final bytes = await _requireContacts().getProfilePicture(contactId);
- final latestContact = _activeContactsByUserId[contactUserId];
- if (latestContact == null ||
- latestContact.isDeleted ||
- latestContact.id != contactId ||
- latestContact.profilePictureAttachmentId != attachmentId) {
- return _profilePictureBytesByUserId[contactUserId];
- }
- _profilePictureBytesByUserId[contactUserId] = bytes;
- _resolvedProfilePictureUserIds.add(contactUserId);
- return bytes;
- } catch (e, s) {
- _logger.warning(
- "Failed to load contact profile picture for user $contactUserId",
- e,
- s,
- );
- return null;
+ if (_store.hasResolvedProfilePictureByUserId(contactUserId)) {
+ return _store.getCachedProfilePictureBytesByUserId(contactUserId);
}
+ await getContact(contactUserId: contactUserId);
+ return _store.getProfilePictureBytesByUserId(contactUserId);
}
Future<contacts.ContactRecord> createOrUpdateContact({
required int contactUserId,
required String name,
}) async {
- final contactsService = await _ensureReadyForWrite();
- final trimmedName = name.trim();
- final existing = await contactsService.getContactByUserId(
- contactUserId,
- includeDeleted: true,
- );
- final data = contacts.ContactData(
+ await ensureReady();
+ return _store.createOrUpdateContact(
contactUserId: contactUserId,
- name: trimmedName,
+ name: name,
);
- final contact = existing == null
- ? await contactsService.createContact(data)
- : await contactsService.updateContact(existing.id, data);
- _cacheContact(contact);
- _notifyChanged(contact);
- return contact;
}
Future<contacts.ContactRecord?> createContactWithProfilePictureIfAbsent({
@@ -262,108 +113,41 @@ class PhotosContactsService {
required String name,
required Uint8List bytes,
}) async {
- final contactsService = await _ensureReadyForWrite();
- if (!identical(contactsService, _activeContactsOrNull())) {
- return null;
- }
- final generation = _sessionGeneration;
- final existing = await contactsService.getContactByUserId(
- contactUserId,
- includeDeleted: true,
- );
- if (generation != _sessionGeneration) {
- return null;
- }
- if (existing != null) {
- if (!existing.isDeleted) {
- _cacheContact(existing);
- return existing;
- }
- return null;
- }
-
- final contact = await contactsService.createContact(
- contacts.ContactData(contactUserId: contactUserId, name: name.trim()),
+ await ensureReady();
+ return _store.createContactWithProfilePictureIfAbsent(
+ contactUserId: contactUserId,
+ name: name,
+ bytes: bytes,
);
- if (generation != _sessionGeneration) {
- return null;
- }
- late contacts.ContactRecord updated;
- try {
- updated = await contactsService.setProfilePicture(contact.id, bytes);
- } catch (_) {
- if (generation != _sessionGeneration ||
- !identical(contactsService, _activeContactsOrNull())) {
- rethrow;
- }
- updated = await contactsService.setProfilePicture(contact.id, bytes);
- }
- if (generation != _sessionGeneration) {
- return null;
- }
- _cacheContact(updated);
- _profilePictureBytesByUserId[updated.contactUserId] = bytes;
- _resolvedProfilePictureUserIds.add(updated.contactUserId);
- _notifyChanged(updated);
- return updated;
}
Future<contacts.ContactRecord> setProfilePicture({
required String contactId,
required Uint8List bytes,
}) async {
- final contactsService = await _ensureReadyForWrite();
- final contact = await contactsService.setProfilePicture(contactId, bytes);
- _cacheContact(contact);
- _profilePictureBytesByUserId[contact.contactUserId] = bytes;
- _resolvedProfilePictureUserIds.add(contact.contactUserId);
- _notifyChanged(contact);
- return contact;
+ await ensureReady();
+ return _store.setProfilePicture(contactId: contactId, bytes: bytes);
}
Future<contacts.ContactRecord> deleteProfilePicture({
required String contactId,
}) async {
- final contactsService = await _ensureReadyForWrite();
- final contact = await contactsService.deleteProfilePicture(contactId);
- _cacheContact(contact);
- _profilePictureBytesByUserId.remove(contact.contactUserId);
- _resolvedProfilePictureUserIds.add(contact.contactUserId);
- _notifyChanged(contact);
- return contact;
+ await ensureReady();
+ return _store.deleteProfilePicture(contactId: contactId);
}
@visibleForTesting
- Future<void> debugOpenAndSync(contacts.ContactsSession session) async {
- final sessionKey = _buildSessionKey(session);
- if (_sessionKey != sessionKey) {
- _sessionGeneration += 1;
- _resetSessionState(notify: false);
- }
- _contacts ??= _newContactsService();
- final currentContacts = _requireContacts();
- _sessionKey = _buildSessionKey(session);
- _sessionAuthToken = session.authToken;
- await _openAndSync(currentContacts, session, _sessionGeneration);
- }
+ Future<void> debugOpenAndSync(contacts.ContactsSession session) =>
+ _store.ensureReady(session);
@visibleForTesting
void debugHydrateContacts(
- List<contacts.ContactRecord> contacts, {
+ List<contacts.ContactRecord> records, {
bool markHydrated = false,
- }) {
- for (final contact in contacts) {
- _cacheContact(contact);
- }
- if (markHydrated) {
- _hasHydratedCache = true;
- }
- }
+ }) => _store.debugHydrateContacts(records, markHydrated: markHydrated);
@visibleForTesting
- void debugReset({bool notify = false}) {
- _resetSessionState(notify: notify);
- }
+ void debugReset({bool notify = false}) => _store.clearSession(notify: notify);
contacts.ContactsSession? _buildSession() {
final config = Configuration.instance;
@@ -384,108 +168,32 @@ class PhotosContactsService {
);
}
- String _buildSessionKey(contacts.ContactsSession session) {
- return "${session.baseUrl}|${session.userId}";
- }
-
- Future<void> _openAndSync(
- contacts.ContactsService contactsService,
- contacts.ContactsSession session,
- int generation,
- ) async {
- await contactsService.open(session);
- if (!_isSessionGenerationCurrent(generation, session)) {
- return;
- }
-
- final cachedUserIdsBeforeHydration = _activeContactsByUserId.keys.toSet();
- final localContacts = await contactsService.getContacts();
- if (!_isSessionGenerationCurrent(generation, session)) {
- return;
- }
- for (final contact in localContacts) {
- _cacheContact(contact);
- }
- _hasHydratedCache = true;
- final newlyHydratedLocalUserIds = localContacts
- .map((contact) => contact.contactUserId)
- .where((userId) => !cachedUserIdsBeforeHydration.contains(userId))
- .toSet();
- final changedUserIds = <int>{...newlyHydratedLocalUserIds};
- var shouldRetrySync = false;
- try {
- final contactsDiff = await contactsService.sync();
- if (!_isSessionGenerationCurrent(generation, session)) {
- return;
- }
- for (final contact in contactsDiff) {
- _invalidateProfilePictureCache(contact.contactUserId);
- _cacheContact(contact);
- }
- changedUserIds.addAll(
- 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",
- e,
- s,
- );
- }
- if (changedUserIds.isNotEmpty) {
- _notifyContactsChanged(changedUserIds);
- }
- if (shouldRetrySync && _sessionKey == _buildSessionKey(session)) {
- _readyFuture = null;
- }
- }
-
- bool _isSessionGenerationCurrent(
- int generation,
- contacts.ContactsSession session,
- ) {
- return _sessionGeneration == generation &&
- _sessionKey == _buildSessionKey(session);
- }
-
- void _notifyChanged(contacts.ContactRecord contact) {
- _notifyContactsChanged({contact.contactUserId});
- }
-
- void _notifyContactsChanged(Set<int>? contactUserIds) {
- Bus.instance.fire(ContactsChangedEvent(contactUserIds: contactUserIds));
- }
-
Future<T?> _runReadSafely<T>(
Future<T?> Function() task, {
required String description,
}) async {
try {
return await task();
- } on StateError catch (e, s) {
- if (_isRustInitializationError(e)) {
+ } on StateError catch (error, stackTrace) {
+ if (_isRustInitializationError(error)) {
_logger.warning(
"Contacts integration unavailable while Rust bindings are not initialized during $description. Photos initializes EntePhotosRust in main.dart, but ente_contacts calls into package:ente_rust.",
- e,
- s,
+ error,
+ stackTrace,
);
return null;
}
- if (_isContactsDatabaseNotConfiguredError(e)) {
+ if (_isContactsDatabaseNotConfiguredError(error)) {
_logger.warning(
"Contacts integration unavailable while contacts are disabled or not initialized during $description",
- e,
- s,
+ error,
+ stackTrace,
);
return null;
}
rethrow;
- } catch (e, s) {
- _logger.warning("Failed to $description", e, s);
+ } catch (error, stackTrace) {
+ _logger.warning("Failed to $description", error, stackTrace);
return null;
}
}
@@ -502,94 +210,13 @@ class PhotosContactsService {
);
}
- void _cacheContact(contacts.ContactRecord contact) {
- final userId = contact.contactUserId;
- final existing = _activeContactsByUserId[userId];
- final previousEmail = normalizeContactLinkEmail(existing?.email);
- if (previousEmail != null &&
- _activeContactsByNormalizedEmail[previousEmail]?.contactUserId ==
- userId) {
- _activeContactsByNormalizedEmail.remove(previousEmail);
- }
- if (contact.isDeleted) {
- _activeContactsByUserId.remove(userId);
- _invalidateProfilePictureCache(userId);
- return;
- }
- _activeContactsByUserId[userId] = contact;
- final normalizedEmail = normalizeContactLinkEmail(contact.email);
- if (normalizedEmail != null) {
- _activeContactsByNormalizedEmail[normalizedEmail] = contact;
- }
- if (existing?.profilePictureAttachmentId !=
- contact.profilePictureAttachmentId) {
- _invalidateProfilePictureCache(userId);
- }
- }
-
- void _resetSessionState({required bool notify}) {
- final hadCachedContacts = _activeContactsByUserId.isNotEmpty;
- _activeContactsByUserId.clear();
- _activeContactsByNormalizedEmail.clear();
- _profilePictureBytesByUserId.clear();
- _resolvedProfilePictureUserIds.clear();
- _profilePictureLoadsByUserId.clear();
- _readyFuture = null;
- _contacts = null;
- _sessionKey = null;
- _sessionAuthToken = null;
- _hasHydratedCache = false;
- if (notify && hadCachedContacts) {
- _notifyContactsChanged(null);
- }
- }
-
- void _invalidateProfilePictureCache(int contactUserId) {
- _profilePictureBytesByUserId.remove(contactUserId);
- _resolvedProfilePictureUserIds.remove(contactUserId);
- _profilePictureLoadsByUserId.remove(contactUserId);
+ static void _notifyContactsChanged(Set<int>? contactUserIds) {
+ Bus.instance.fire(ContactsChangedEvent(contactUserIds: contactUserIds));
}
- void _attachSessionResetListeners() {
+ void _attachSessionResetListener() {
Bus.instance.on<UserLoggedOutEvent>().listen((_) {
- _sessionGeneration += 1;
- _resetSessionState(notify: true);
+ _store.clearSession();
});
}
-
- 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/services/search_service.dart b/mobile/apps/photos/lib/services/search_service.dart
index 1fc38d52be..7ff484a6c8 100644
--- a/mobile/apps/photos/lib/services/search_service.dart
+++ b/mobile/apps/photos/lib/services/search_service.dart
@@ -109,7 +109,7 @@ class SearchService {
List<Collection> collections,
) {
final contactUserId = user.id;
- if (contactUserId == null || contactUserId <= 0) {
+ if (contactUserId <= 0) {
throw ArgumentError.value(
contactUserId,
"user.id",
@@ -163,7 +163,7 @@ class SearchService {
final contactsByUserId = <int, User>{};
for (final contact in directContacts) {
contactsToFiles[contact] = [];
- contactsByUserId[contact.id!] = contact;
+ contactsByUserId[contact.id] = contact;
}
for (final file in allFiles) {
@@ -195,7 +195,7 @@ class SearchService {
continue;
}
final contactUserId = collection.owner.id;
- if (contactUserId != null && contactUserId > 0) {
+ if (contactUserId > 0) {
collectionsByUserId
.putIfAbsent(contactUserId, () => [])
.add(collection);
@@ -232,7 +232,7 @@ class SearchService {
User user,
) async {
final userId = user.id;
- if (userId == null || userId <= 0) {
+ if (userId <= 0) {
return null;
}
@@ -269,7 +269,7 @@ class SearchService {
bool _isSameContactUser(User source, User target) {
final sourceId = source.id;
final targetId = target.id;
- if (sourceId != null && targetId != null && sourceId > 0 && targetId > 0) {
+ if (sourceId > 0 && targetId > 0) {
return sourceId == targetId;
}
return source.email == target.email;
@@ -1930,9 +1930,9 @@ class SearchService {
return aName.compareTo(bName);
});
- final limitedEntries = limit != null
- ? _preserveEmailOnlyContactsWithinLimit(sortedEntries, limit)
- : sortedEntries;
+ final limitedEntries = limit == null
+ ? sortedEntries
+ : sortedEntries.take(limit).toList();
return _toContactSearchResults(limitedEntries, peopleToSharedAlbums);
} catch (e) {
@@ -1950,37 +1950,6 @@ class SearchService {
.toList();
}
- List<MapEntry<User, List<EnteFile>>> _preserveEmailOnlyContactsWithinLimit(
- List<MapEntry<User, List<EnteFile>>> sortedEntries,
- int limit,
- ) {
- if (limit <= 0) {
- return const [];
- }
- final limitedEntries = sortedEntries.take(limit).toList();
- if (limitedEntries.length < limit ||
- limitedEntries.any((entry) => entry.key.id == null)) {
- return limitedEntries;
- }
-
- final includedEmails = limitedEntries
- .map((entry) => entry.key.email)
- .toSet();
- MapEntry<User, List<EnteFile>>? overflowEmailOnly;
- for (final entry in sortedEntries.skip(limit)) {
- if (entry.key.id == null && !includedEmails.contains(entry.key.email)) {
- overflowEmailOnly = entry;
- break;
- }
- }
- if (overflowEmailOnly == null) {
- return limitedEntries;
- }
-
- limitedEntries[limitedEntries.length - 1] = overflowEmailOnly;
- return limitedEntries;
- }
-
Future<List<EnteFile>> _getFilesInYear(List<int> durationOfYear) async {
return await FilesDB.instance.getFilesCreatedWithinDurations(
[durationOfYear],
diff --git a/mobile/apps/photos/lib/services/social_notification_coordinator.dart b/mobile/apps/photos/lib/services/social_notification_coordinator.dart
index 15b95533eb..3d3a2efc28 100644
--- a/mobile/apps/photos/lib/services/social_notification_coordinator.dart
+++ b/mobile/apps/photos/lib/services/social_notification_coordinator.dart
@@ -438,7 +438,6 @@ class SocialNotificationCoordinator {
final ownerID = collection.owner.id;
if (sharedAt == null ||
sharedAt <= cutoffTime ||
- ownerID == null ||
hiddenCollectionIds.contains(collection.id)) {
continue;
}
diff --git a/mobile/apps/photos/lib/ui/collections/album/list_item.dart b/mobile/apps/photos/lib/ui/collections/album/list_item.dart
index a5c78b0e92..67f6dff491 100644
--- a/mobile/apps/photos/lib/ui/collections/album/list_item.dart
+++ b/mobile/apps/photos/lib/ui/collections/album/list_item.dart
@@ -236,11 +236,10 @@ class AlbumListItemWidget extends StatelessWidget {
key: const ValueKey("owner"),
collection.owner,
type: AvatarType.medium,
- thumbnailView: true,
);
}
if (collection.hasSharees) {
- final sharees = collection.getSharees();
+ final sharees = collection.sharees;
final int total = sharees.length;
final int limit = total > 2 ? 1 : 2;
final int displayCount = total.clamp(1, limit).toInt();
diff --git a/mobile/apps/photos/lib/ui/collections/album/row_item.dart b/mobile/apps/photos/lib/ui/collections/album/row_item.dart
index d618f233d3..92303c5b04 100644
--- a/mobile/apps/photos/lib/ui/collections/album/row_item.dart
+++ b/mobile/apps/photos/lib/ui/collections/album/row_item.dart
@@ -188,7 +188,7 @@ class AlbumRowItemWidget extends StatelessWidget {
child: SizedBox(
height: getAvatarSize(AvatarType.xs),
child: _AlbumRowSharePillContent(
- sharees: c.getSharees(),
+ sharees: c.sharees,
trailingWidget: linkIcon,
),
),
@@ -231,7 +231,6 @@ class AlbumRowItemWidget extends StatelessWidget {
children: [
UserAvatarWidget(
c.owner,
- thumbnailView: true,
type: AvatarType.xs,
),
Positioned.fill(
@@ -434,11 +433,7 @@ class _AlbumRowSharePillContent extends StatelessWidget {
displayCount,
(index) => Positioned(
left: overlapPadding * index,
- child: UserAvatarWidget(
- sharees[index],
- thumbnailView: true,
- type: type,
- ),
+ child: UserAvatarWidget(sharees[index], type: type),
),
);
diff --git a/mobile/apps/photos/lib/ui/family/family_plan_page.dart b/mobile/apps/photos/lib/ui/family/family_plan_page.dart
index 01e334fcfc..f66c4da515 100644
--- a/mobile/apps/photos/lib/ui/family/family_plan_page.dart
+++ b/mobile/apps/photos/lib/ui/family/family_plan_page.dart
@@ -403,17 +403,16 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
if (userID == null) {
continue;
}
- final personData = PersonService.instance.getCachedPartialPersonData(
- userID: userID,
- email: member.email,
+ final person = PersonService.instance.getCachedPersonForUser(
+ userID,
+ member.email,
);
- final personID = personData?[PersonService.kPersonIDKey];
- if (personID == null) {
+ if (person == null) {
continue;
}
- idsByUserId[userID] = personID;
- final personName = personData?[PersonService.kNameKey]?.trim();
- if (personName != null && personName.isNotEmpty) {
+ idsByUserId[userID] = person.remoteID;
+ final personName = person.data.name.trim();
+ if (personName.isNotEmpty) {
namesByUserId[userID] = personName;
}
}
@@ -534,10 +533,9 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
: savedContactName;
final linkedPersonId = member.userID == null || !PersonService.isInitialized
? null
- : PersonService.instance.getCachedPartialPersonData(
- userID: member.userID,
- email: member.email,
- )?[PersonService.kPersonIDKey];
+ : PersonService.instance
+ .getCachedPersonForUser(member.userID, member.email)
+ ?.remoteID;
final l10n = context.strings;
await showBottomSheetComponent<void>(
context: context,
diff --git a/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart b/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart
index ef29146e1f..ea1184795f 100644
--- a/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart
+++ b/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart
@@ -34,7 +34,7 @@ class _AddParticipantPage extends State<AddParticipantPage> {
bool _emailIsValid = false;
bool isKeypadOpen = false;
late CollectionActions collectionActions;
- late List<User> _suggestedUsers;
+ late List<UserSuggestion> _suggestedUsers;
// Focus nodes are necessary
final textFieldFocusNode = FocusNode();
@@ -58,7 +58,7 @@ class _AddParticipantPage extends State<AddParticipantPage> {
Widget build(BuildContext context) {
final filterSuggestedUsers = _suggestedUsers
.where(
- (element) => _matchesUserQuery(
+ (element) => matchesResolvedSuggestionQuery(
element,
_textController.text.trim().toLowerCase(),
),
@@ -75,7 +75,7 @@ class _AddParticipantPage extends State<AddParticipantPage> {
);
}
- List<Widget> _slivers(List<User> filterSuggestedUsers) {
+ List<Widget> _slivers(List<UserSuggestion> filterSuggestedUsers) {
final footerDescriptions = [
if (filterSuggestedUsers.isNotEmpty)
ShareSectionDescription(
@@ -180,7 +180,7 @@ class _AddParticipantPage extends State<AddParticipantPage> {
];
}
- Widget _suggestedUserItem(List<User> users, int index) {
+ Widget _suggestedUserItem(List<UserSuggestion> users, int index) {
final currentUser = users[index];
final borderRadius = MenuGroupComponent.itemBorderRadius(
index: index,
@@ -196,11 +196,14 @@ class _AddParticipantPage extends State<AddParticipantPage> {
),
child: ShareMenuItem(
key: ValueKey(
- '${currentUser.email}-${resolveDisplayName(currentUser)}',
+ '${currentUser.email}-${resolveSuggestionDisplayName(currentUser)}',
),
- title: resolveDisplayName(currentUser),
+ title: resolveSuggestionDisplayName(currentUser),
titleColor: context.componentColors.textLight,
- leading: UserAvatarWidget(currentUser, type: AvatarType.medium),
+ leading: UserAvatarWidget.suggestion(
+ currentUser,
+ type: AvatarType.medium,
+ ),
trailing: _selectedEmails.contains(currentUser.email)
? shareCheck(context)
: null,
@@ -424,7 +427,7 @@ class _AddParticipantPage extends State<AddParticipantPage> {
return;
}
}
- _suggestedUsers.insert(0, User(email: _newEmail));
+ _suggestedUsers.insert(0, UserSuggestion(_newEmail));
_selectedEmails.add(_newEmail);
_clearEmailField();
textFieldFocusNode.unfocus();
@@ -432,7 +435,7 @@ class _AddParticipantPage extends State<AddParticipantPage> {
}
}
- List<User> _getSuggestedUser() {
+ List<UserSuggestion> _getSuggestedUser() {
final Set<String> existingEmails = {};
final collections = widget.collections;
if (collections.isEmpty) {
@@ -442,7 +445,7 @@ class _AddParticipantPage extends State<AddParticipantPage> {
for (final Collection collection in collections) {
for (final User u in collection.sharees) {
- if (u.id != null && u.email.isNotEmpty) {
+ if (u.email.isNotEmpty) {
existingEmails.add(u.email);
}
}
@@ -453,12 +456,12 @@ class _AddParticipantPage extends State<AddParticipantPage> {
}
}
- final List<User> suggestedUsers = UserService.instance.getRelevantContacts()
+ final suggestedUsers = UserService.instance.getRelevantContacts()
..removeWhere((element) => existingEmails.contains(element.email));
if (_textController.text.trim().isNotEmpty) {
suggestedUsers.removeWhere(
- (element) => !_matchesUserQuery(
+ (element) => !matchesResolvedSuggestionQuery(
element,
_textController.text.trim().toLowerCase(),
),
@@ -502,13 +505,4 @@ class _AddParticipantPage extends State<AddParticipantPage> {
}
}
- bool _matchesUserQuery(User user, String lowerCaseQuery) {
- if (lowerCaseQuery.isEmpty) {
- return true;
- }
- final resolvedName = resolveDisplayName(user).toLowerCase();
- final resolvedEmail = (resolveKnownEmail(user) ?? user.email).toLowerCase();
- return resolvedName.contains(lowerCaseQuery) ||
- resolvedEmail.contains(lowerCaseQuery);
- }
}
diff --git a/mobile/apps/photos/lib/ui/sharing/album_participants_page.dart b/mobile/apps/photos/lib/ui/sharing/album_participants_page.dart
index add2473143..2e6cf0cdb1 100644
--- a/mobile/apps/photos/lib/ui/sharing/album_participants_page.dart
+++ b/mobile/apps/photos/lib/ui/sharing/album_participants_page.dart
@@ -80,12 +80,12 @@ class _AlbumParticipantsPageState extends State<AlbumParticipantsPage> {
_collection.type != CollectionType.uncategorized &&
!isOwner &&
hasActivePublicLink;
- final int participants = 1 + _collection.getSharees().length;
+ final int participants = 1 + _collection.sharees.length;
final User owner = _collection.owner;
if (owner.id == currentUserID && owner.email == "") {
owner.email = Configuration.instance.getEmail()!;
}
- final List<User> allSharees = _collection.getSharees();
+ final List<User> allSharees = _collection.sharees;
final List<User> admins = [];
final List<User> collaborators = [];
final List<User> viewers = [];
@@ -128,7 +128,7 @@ class _AlbumParticipantsPageState extends State<AlbumParticipantsPage> {
title: isOwner
? context.strings.you
: _nameIfAvailableElseEmail(owner),
- leading: UserAvatarWidget(owner, currentUserID: currentUserID),
+ leading: UserAvatarWidget(owner),
isDisabled: true,
),
],
@@ -199,11 +199,7 @@ class _AlbumParticipantsPageState extends State<AlbumParticipantsPage> {
title: user.id == currentUserID
? context.strings.you
: _nameIfAvailableElseEmail(user),
- leading: UserAvatarWidget(
- user,
- type: AvatarType.medium,
- currentUserID: currentUserID,
- ),
+ leading: UserAvatarWidget(user, type: AvatarType.medium),
showChevron: canManageParticipants && user.id != currentUserID,
isDisabled: !canManageParticipants || user.id == currentUserID,
onTap: canManageParticipants && user.id != currentUserID
diff --git a/mobile/apps/photos/lib/ui/sharing/album_share_info_widget.dart b/mobile/apps/photos/lib/ui/sharing/album_share_info_widget.dart
index 0e78af2164..ceba9ec886 100644
--- a/mobile/apps/photos/lib/ui/sharing/album_share_info_widget.dart
+++ b/mobile/apps/photos/lib/ui/sharing/album_share_info_widget.dart
@@ -34,11 +34,7 @@ class AlbumSharesIcons extends StatelessWidget {
displayCount,
(index) => Positioned(
left: overlapPadding * index,
- child: UserAvatarWidget(
- sharees[index],
- thumbnailView: removeBorder,
- type: type,
- ),
+ child: UserAvatarWidget(sharees[index], type: type),
),
);
diff --git a/mobile/apps/photos/lib/ui/sharing/manage_album_participant.dart b/mobile/apps/photos/lib/ui/sharing/manage_album_participant.dart
index 8f960c5c97..6d2dafa207 100644
--- a/mobile/apps/photos/lib/ui/sharing/manage_album_participant.dart
+++ b/mobile/apps/photos/lib/ui/sharing/manage_album_participant.dart
@@ -30,14 +30,30 @@ class _ManageIndividualParticipantState
final CollectionActions collectionActions = CollectionActions(
CollectionsService.instance,
);
+ late CollectionParticipantRole _role;
+
+ @override
+ void initState() {
+ super.initState();
+ _role = CollectionParticipantRoleExtn.fromString(widget.user.role);
+ }
+
+ Future<void> _changeRole(CollectionParticipantRole role) async {
+ final changed = await collectionActions.addEmailToCollection(
+ context,
+ widget.collection,
+ widget.user.email,
+ role,
+ );
+ if (changed && mounted) setState(() => _role = role);
+ }
@override
Widget build(BuildContext context) {
- final isAdmin = widget.user.isAdmin;
- final isCollaborator = widget.user.isCollaborator;
- final isViewer = widget.user.isViewer;
+ final isAdmin = _role == CollectionParticipantRole.admin;
+ final isCollaborator = _role == CollectionParticipantRole.collaborator;
+ final isViewer = _role == CollectionParticipantRole.viewer;
final resolvedName = resolveDisplayName(widget.user);
- bool isConvertToViewSuccess = false;
return ShareScaffold(
title: context.strings.manage,
subtitle: resolvedName,
@@ -51,20 +67,7 @@ class _ManageIndividualParticipantState
trailing: isAdmin ? shareCheck(context) : null,
onTap: isAdmin
? null
- : () async {
- final result = await collectionActions
- .addEmailToCollection(
- context,
- widget.collection,
- widget.user.email,
- CollectionParticipantRole.admin,
- );
- if (result && mounted) {
- widget.user.role = CollectionParticipantRole.admin
- .toStringVal();
- setState(() => {});
- }
- },
+ : () => _changeRole(CollectionParticipantRole.admin),
),
ShareMenuItem(
title: context.strings.collaborator,
@@ -72,21 +75,7 @@ class _ManageIndividualParticipantState
trailing: isCollaborator ? shareCheck(context) : null,
onTap: isCollaborator
? null
- : () async {
- final result = await collectionActions
- .addEmailToCollection(
- context,
- widget.collection,
- widget.user.email,
- CollectionParticipantRole.collaborator,
- );
- if (result && mounted) {
- widget.user.role = CollectionParticipantRole
- .collaborator
- .toStringVal();
- setState(() => {});
- }
- },
+ : () => _changeRole(CollectionParticipantRole.collaborator),
),
ShareMenuItem(
title: context.strings.viewer,
@@ -106,31 +95,18 @@ class _ManageIndividualParticipantState
),
isCritical: true,
);
- if (actionResult?.action != null) {
- if (actionResult!.action == ButtonAction.first) {
- try {
- if (!context.mounted) return;
- isConvertToViewSuccess = await collectionActions
- .addEmailToCollection(
- context,
- widget.collection,
- widget.user.email,
- CollectionParticipantRole.viewer,
- );
- } catch (e) {
- if (!context.mounted) return;
- await showGenericErrorDialog(
- context: context,
- error: e,
- );
- }
- if (isConvertToViewSuccess && mounted) {
- isConvertToViewSuccess = false;
- widget.user.role = CollectionParticipantRole.viewer
- .toStringVal();
- setState(() => {});
- }
- }
+ if (actionResult?.action != ButtonAction.first ||
+ !context.mounted) {
+ return;
+ }
+ try {
+ await _changeRole(CollectionParticipantRole.viewer);
+ } catch (e) {
+ if (!context.mounted) return;
+ await showGenericErrorDialog(
+ context: context,
+ error: e,
+ );
}
},
),
diff --git a/mobile/apps/photos/lib/ui/sharing/share_collection_page.dart b/mobile/apps/photos/lib/ui/sharing/share_collection_page.dart
index 181a5368a3..3cf91fb115 100644
--- a/mobile/apps/photos/lib/ui/sharing/share_collection_page.dart
+++ b/mobile/apps/photos/lib/ui/sharing/share_collection_page.dart
@@ -256,17 +256,14 @@ class EmailItemWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
- if (collection.getSharees().isEmpty) {
+ if (collection.sharees.isEmpty) {
return const SizedBox.shrink();
- } else if (collection.getSharees().length == 1) {
- final User? user = collection.getSharees().firstOrNull;
+ } else if (collection.sharees.length == 1) {
+ final User? user = collection.sharees.firstOrNull;
final resolvedName = user == null ? '' : resolveDisplayName(user);
return ShareMenuItem(
title: resolvedName,
- leading: UserAvatarWidget(
- collection.getSharees().first,
- thumbnailView: false,
- ),
+ leading: UserAvatarWidget(collection.sharees.first),
showChevron: true,
onTap: () async {
if (onTap != null) {
@@ -275,7 +272,7 @@ class EmailItemWidget extends StatelessWidget {
},
);
} else {
- final sharees = collection.getSharees();
+ final sharees = collection.sharees;
const avatarSize = 24.0;
final total = sharees.length;
final limit = total > 2 ? 1 : 2;
diff --git a/mobile/apps/photos/lib/ui/sharing/user_avator_widget.dart b/mobile/apps/photos/lib/ui/sharing/user_avator_widget.dart
index 7556dad42a..db1f434f19 100644
--- a/mobile/apps/photos/lib/ui/sharing/user_avator_widget.dart
+++ b/mobile/apps/photos/lib/ui/sharing/user_avator_widget.dart
@@ -23,35 +23,39 @@ Color getUserAvatarColor(BuildContext context, User user) {
}
AvatarIdentity getUserAvatarIdentity(User user) {
+ return getUserSuggestionAvatarIdentity(UserSuggestion.fromUser(user));
+}
+
+AvatarIdentity getUserSuggestionAvatarIdentity(UserSuggestion suggestion) {
+ final resolved = resolveSuggestionIdentity(suggestion);
return AvatarIdentity.account(
- label: resolveDisplayName(user),
- email: resolveKnownEmail(user) ?? user.email,
- userID: user.id,
+ label: resolved.displayName,
+ email: resolved.knownEmail ?? suggestion.email,
+ userID: suggestion.userID,
+ currentUserID: Configuration.instance.getUserID(),
currentUserEmail: Configuration.instance.getEmail(),
);
}
class UserAvatarWidget extends StatefulWidget {
- final User user;
+ final UserSuggestion suggestion;
final AvatarType type;
- final int currentUserID;
- final bool thumbnailView;
- final bool addStroke;
- final AvatarIdentity? fallbackIdentity;
- const UserAvatarWidget(
- this.user, {
+ UserAvatarWidget(User user, {super.key, this.type = AvatarType.medium})
+ : suggestion = UserSuggestion.fromUser(user);
+
+ const UserAvatarWidget.suggestion(
+ this.suggestion, {
super.key,
- this.currentUserID = -1,
this.type = AvatarType.medium,
- this.thumbnailView = false,
- this.addStroke = true,
- this.fallbackIdentity,
});
+ int? get userID => suggestion.userID;
+ String get email => suggestion.email;
+ AvatarIdentity get identity => getUserSuggestionAvatarIdentity(suggestion);
+
@override
State<UserAvatarWidget> createState() => _UserAvatarWidgetState();
- static const strokeWidth = 1.0;
}
class _UserAvatarWidgetState extends State<UserAvatarWidget> {
@@ -83,7 +87,7 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
_contactsChangedSubscription = Bus.instance
.on<ContactsChangedEvent>()
.listen((event) {
- if (event.matchesContactUserId(widget.user.id)) {
+ if (event.matchesContactUserId(widget.userID)) {
_reload();
}
});
@@ -92,8 +96,7 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
@override
void didUpdateWidget(covariant UserAvatarWidget oldWidget) {
super.didUpdateWidget(oldWidget);
- if (oldWidget.user.email != widget.user.email ||
- oldWidget.user.id != widget.user.id) {
+ if (oldWidget.email != widget.email || oldWidget.userID != widget.userID) {
_reload();
}
}
@@ -110,22 +113,22 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
_debouncer.run(() async {
if (!mounted) return;
setState(() {
- final data = PersonService.instance.getCachedPartialPersonData(
- userID: widget.user.id,
- email: widget.user.email,
+ final person = PersonService.instance.getCachedPersonForUser(
+ widget.userID,
+ widget.email,
);
- if (data != null && data.containsKey(PersonService.kPersonIDKey)) {
+ if (person != null) {
_canUsePersonFaceWidget = true;
- _personId = data[PersonService.kPersonIDKey] as String;
+ _personId = person.remoteID;
lastSyncTimeForKey = PersonService.instance.lastRemoteSyncTime();
} else {
_canUsePersonFaceWidget = false;
_personId = null;
}
_contactPhotoBytes = PhotosContactsService.instance
- .getCachedProfilePictureBytesByUserId(widget.user.id);
+ .getCachedProfilePictureBytesByUserId(widget.userID);
});
- final userId = widget.user.id;
+ final userId = widget.userID;
if (userId == null ||
PhotosContactsService.instance.hasResolvedProfilePictureByUserId(
userId,
@@ -137,7 +140,7 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
.getProfilePictureBytesByUserId(userId);
if (!mounted ||
loadGeneration != _photoLoadGeneration ||
- widget.user.id != userId) {
+ widget.userID != userId) {
return;
}
setState(() {
@@ -184,35 +187,20 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
}
},
)
- : _InitialsCircularAvatar(
- user: widget.user,
- type: widget.type,
- fallbackIdentity: widget.fallbackIdentity,
- ),
+ : AvatarIdentityWidget(widget.identity, widget.type),
),
)
- : _InitialsCircularAvatar(
- user: widget.user,
- type: widget.type,
- fallbackIdentity: widget.fallbackIdentity,
- );
+ : AvatarIdentityWidget(widget.identity, widget.type);
}
}
-class _InitialsCircularAvatar extends StatelessWidget {
- final User user;
+class AvatarIdentityWidget extends StatelessWidget {
+ final AvatarIdentity identity;
final AvatarType type;
- final AvatarIdentity? fallbackIdentity;
- const _InitialsCircularAvatar({
- required this.user,
- required this.type,
- required this.fallbackIdentity,
- });
+ const AvatarIdentityWidget(this.identity, this.type, {super.key});
@override
Widget build(BuildContext context) {
- final identity = fallbackIdentity ?? getUserAvatarIdentity(user);
-
final avatarStyle = getAvatarStyle(context, type);
final double size = avatarStyle.item1;
final TextStyle textStyle = avatarStyle.item2;
@@ -270,12 +258,12 @@ double getAvatarSize(AvatarType type) {
}
class UserInitialsAvatar extends StatelessWidget {
- final User user;
- const UserInitialsAvatar(this.user, {super.key});
+ final UserSuggestion suggestion;
+ const UserInitialsAvatar(this.suggestion, {super.key});
@override
Widget build(BuildContext context) {
- final identity = getUserAvatarIdentity(user);
+ final identity = getUserSuggestionAvatarIdentity(suggestion);
return Container(
color: avatarBackgroundColor(context, identity),
child: Center(
diff --git a/mobile/apps/photos/lib/ui/social/comment_likes_bottom_sheet.dart b/mobile/apps/photos/lib/ui/social/comment_likes_bottom_sheet.dart
index b0a3e656cf..cb19750994 100644
--- a/mobile/apps/photos/lib/ui/social/comment_likes_bottom_sheet.dart
+++ b/mobile/apps/photos/lib/ui/social/comment_likes_bottom_sheet.dart
@@ -2,6 +2,7 @@ import "package:ente_icons/ente_icons.dart";
import "package:ente_strings/ente_strings.dart";
import "package:flutter/material.dart";
import "package:photos/models/api/collection/user.dart";
+import "package:photos/models/social/comment_author_utils.dart";
import "package:photos/models/social/reaction.dart";
import "package:photos/models/social/social_data_provider.dart";
import "package:photos/services/collections_service.dart";
@@ -87,14 +88,10 @@ class _CommentLikesBottomSheetState extends State<CommentLikesBottomSheet> {
User _getUserForReaction(Reaction reaction) {
if (reaction.isAnonymous) {
- final anonID = reaction.anonUserID;
- final displayName = anonID != null
- ? (_anonDisplayNames[anonID] ?? anonID)
- : "Anonymous";
- return User(
- id: reaction.userID,
- email: "${anonID ?? "anonymous"}@unknown.com",
- name: displayName,
+ return anonymousSocialUser(
+ userID: reaction.userID,
+ anonUserID: reaction.anonUserID,
+ anonDisplayNames: _anonDisplayNames,
);
}
@@ -210,12 +207,7 @@ class _CommentLikeListItem extends StatelessWidget {
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
- UserAvatarWidget(
- user,
- currentUserID: currentUserID,
- type: AvatarType.regular,
- addStroke: false,
- ),
+ UserAvatarWidget(user, type: AvatarType.regular),
const SizedBox(width: 12),
Expanded(
child: user.id == currentUserID
diff --git a/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart b/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
index e6a2436cde..da0b9e3e9f 100644
--- a/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
+++ b/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
@@ -6,6 +6,7 @@ import "package:flutter/material.dart";
import "package:photos/core/configuration.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/models/collection/collection.dart";
+import "package:photos/models/social/comment_author_utils.dart";
import "package:photos/models/social/reaction.dart";
import "package:photos/models/social/social_data_provider.dart";
import "package:photos/services/collections_service.dart";
@@ -372,14 +373,10 @@ class _LikesList extends StatelessWidget {
User _getUserForReaction(Reaction reaction) {
if (reaction.isAnonymous) {
- final anonID = reaction.anonUserID;
- final displayName = anonID != null
- ? (anonDisplayNames[anonID] ?? anonID)
- : "Anonymous";
- return User(
- id: reaction.userID,
- email: "${anonID ?? "anonymous"}@unknown.com",
- name: displayName,
+ return anonymousSocialUser(
+ userID: reaction.userID,
+ anonUserID: reaction.anonUserID,
+ anonDisplayNames: anonDisplayNames,
);
}
@@ -432,12 +429,7 @@ class _LikeListItem extends StatelessWidget {
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
- UserAvatarWidget(
- user,
- currentUserID: currentUserID,
- type: AvatarType.regular,
- addStroke: false,
- ),
+ UserAvatarWidget(user, type: AvatarType.regular),
const SizedBox(width: 12),
Expanded(
child: user.id == currentUserID
diff --git a/mobile/apps/photos/lib/ui/social/social_actor_contact_navigation.dart b/mobile/apps/photos/lib/ui/social/social_actor_contact_navigation.dart
index 6779e2c91a..b7562ad27b 100644
--- a/mobile/apps/photos/lib/ui/social/social_actor_contact_navigation.dart
+++ b/mobile/apps/photos/lib/ui/social/social_actor_contact_navigation.dart
@@ -18,7 +18,7 @@ bool canOpenSocialActorContactDestination(
required int currentUserID,
}) {
final userId = user.id;
- if (userId == null || userId <= 0 || userId == currentUserID) {
+ if (userId <= 0 || userId == currentUserID) {
return false;
}
return resolveKnownEmail(user) != null;
@@ -38,7 +38,7 @@ Future<void> openSocialActorContactDestination(
return;
}
- final userId = user.id!;
+ final userId = user.id;
final email = resolveKnownEmail(user);
if (email == null) {
return;
diff --git a/mobile/apps/photos/lib/ui/social/widgets/comment_bubble_widget.dart b/mobile/apps/photos/lib/ui/social/widgets/comment_bubble_widget.dart
index f334e86882..c405ab8244 100644
--- a/mobile/apps/photos/lib/ui/social/widgets/comment_bubble_widget.dart
+++ b/mobile/apps/photos/lib/ui/social/widgets/comment_bubble_widget.dart
@@ -897,25 +897,13 @@ class _Header extends StatelessWidget {
mainAxisSize: MainAxisSize.max,
children: [
if (!isOwnComment) ...[
- UserAvatarWidget(
- user,
- currentUserID: currentUserID,
- type: AvatarType.regular,
- thumbnailView: true,
- addStroke: false,
- ),
+ UserAvatarWidget(user, type: AvatarType.regular),
const SizedBox(width: 10),
Flexible(child: headerText),
] else ...[
Flexible(child: headerText),
const SizedBox(width: 10),
- UserAvatarWidget(
- user,
- currentUserID: currentUserID,
- type: AvatarType.regular,
- thumbnailView: true,
- addStroke: false,
- ),
+ UserAvatarWidget(user, type: AvatarType.regular),
],
],
);
diff --git a/mobile/apps/photos/lib/ui/social/widgets/feed_item_widget.dart b/mobile/apps/photos/lib/ui/social/widgets/feed_item_widget.dart
index 86881628be..2263d5b534 100644
--- a/mobile/apps/photos/lib/ui/social/widgets/feed_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/social/widgets/feed_item_widget.dart
@@ -4,6 +4,7 @@ import "package:flutter/material.dart";
import "package:photos/db/files_db.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/models/file/file.dart";
+import "package:photos/models/social/comment_author_utils.dart";
import "package:photos/models/social/feed_item.dart";
import "package:photos/services/collections_service.dart";
import "package:photos/theme/colors.dart";
@@ -404,12 +405,7 @@ class _StackedAvatars extends StatelessWidget {
width: 1.167,
),
),
- child: UserAvatarWidget(
- actors.first,
- type: AvatarType.regular,
- currentUserID: currentUserID,
- addStroke: false,
- ),
+ child: UserAvatarWidget(actors.first, type: AvatarType.regular),
),
),
// Second (back) avatar
@@ -423,12 +419,7 @@ class _StackedAvatars extends StatelessWidget {
width: 1.167,
),
),
- child: UserAvatarWidget(
- actors[1],
- type: AvatarType.regular,
- currentUserID: currentUserID,
- addStroke: false,
- ),
+ child: UserAvatarWidget(actors[1], type: AvatarType.regular),
),
),
],
@@ -444,12 +435,7 @@ class _StackedAvatars extends StatelessWidget {
shape: BoxShape.circle,
border: Border.all(color: colorScheme.backgroundColour, width: 1.167),
),
- child: UserAvatarWidget(
- user,
- type: AvatarType.regular,
- currentUserID: currentUserID,
- addStroke: false,
- ),
+ child: UserAvatarWidget(user, type: AvatarType.regular),
);
}
@@ -473,11 +459,13 @@ class _StackedAvatars extends StatelessWidget {
final userID = feedItem.actorUserIDs[i];
final anonID = feedItem.actorAnonIDs[i];
- if (userID <= 0 && anonID != null) {
- // Anonymous user - use decrypted display name if available
- final displayName = anonDisplayNames[anonID] ?? anonID;
+ if (userID <= 0) {
users.add(
- User(id: userID, email: "[email protected]", name: displayName),
+ anonymousSocialUser(
+ userID: userID,
+ anonUserID: anonID,
+ anonDisplayNames: anonDisplayNames,
+ ),
);
} else {
// Get user from collections service
@@ -703,10 +691,12 @@ class _FeedTextContent extends StatelessWidget {
final userID = feedItem.primaryActorUserID;
final anonID = feedItem.primaryActorAnonID;
- if (userID <= 0 && anonID != null) {
- // Anonymous user - use decrypted display name if available
- final displayName = anonDisplayNames[anonID] ?? anonID;
- return User(id: userID, email: "[email protected]", name: displayName);
+ if (userID <= 0) {
+ return anonymousSocialUser(
+ userID: userID,
+ anonUserID: anonID,
+ anonDisplayNames: anonDisplayNames,
+ );
}
return CollectionsService.instance.resolveUserIdentity(
diff --git a/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dart b/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dart
index 947df908c2..8cdbd685b6 100644
--- a/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dart
+++ b/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dart
@@ -623,11 +623,7 @@ class _LatestCommentPillState extends State<_LatestCommentPill> {
color: Colors.white,
shape: BoxShape.circle,
),
- child: UserAvatarWidget(
- widget.author,
- type: AvatarType.small,
- currentUserID: widget.currentUserID,
- ),
+ child: UserAvatarWidget(widget.author, type: AvatarType.small),
),
),
],
diff --git a/mobile/apps/photos/lib/ui/viewer/file/file_icons_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/file_icons_widget.dart
index bb6327bc02..3882d29ad2 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/file_icons_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/file_icons_widget.dart
@@ -135,15 +135,20 @@ class VideoOverlayDuration extends StatelessWidget {
}
class OwnerAvatarOverlayIcon extends StatelessWidget {
- final User user;
+ final User? user;
+ final AvatarIdentity? identity;
final AvatarType type;
- final AvatarIdentity? fallbackIdentity;
const OwnerAvatarOverlayIcon(
this.user, {
super.key,
this.type = AvatarType.small,
- this.fallbackIdentity,
- });
+ }) : identity = null;
+
+ const OwnerAvatarOverlayIcon.identity(
+ this.identity, {
+ super.key,
+ this.type = AvatarType.small,
+ }) : user = null;
@override
Widget build(BuildContext context) {
@@ -151,12 +156,9 @@ class OwnerAvatarOverlayIcon extends StatelessWidget {
alignment: Alignment.topRight,
child: Padding(
padding: const EdgeInsets.only(right: 4, top: 4),
- child: UserAvatarWidget(
- user,
- type: type,
- thumbnailView: true,
- fallbackIdentity: fallbackIdentity,
- ),
+ child: user == null
+ ? AvatarIdentityWidget(identity!, type)
+ : UserAvatarWidget(user!, type: type),
),
);
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file/thumbnail_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/thumbnail_widget.dart
index f9f30c0c22..d998cd1525 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/thumbnail_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/thumbnail_widget.dart
@@ -14,7 +14,6 @@ import 'package:photos/db/files_db.dart';
import 'package:photos/db/trash_db.dart';
import 'package:photos/events/files_updated_event.dart';
import 'package:photos/events/local_photos_updated_event.dart';
-import 'package:photos/models/api/collection/user.dart';
import 'package:photos/models/file/extensions/file_props.dart';
import 'package:photos/models/file/file.dart';
import 'package:photos/models/file/file_type.dart';
@@ -229,12 +228,9 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
);
} else if (widget.file.isCollect) {
contentChildren.add(
- OwnerAvatarOverlayIcon(
- User(email: '', name: widget.file.uploaderName),
+ OwnerAvatarOverlayIcon.identity(
+ AvatarIdentity.publicUploader(widget.file.uploaderName!),
type: widget.ownerAvatarType,
- fallbackIdentity: AvatarIdentity.publicUploader(
- label: widget.file.uploaderName!,
- ),
),
);
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/added_by_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/added_by_widget.dart
index 2851540791..56b87b3602 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/added_by_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/added_by_widget.dart
@@ -23,7 +23,7 @@ class AddedByWidget extends StatelessWidget {
if (uploaderName == null || uploaderName.isEmpty) {
return const SizedBox.shrink();
}
- identity = AvatarIdentity.publicUploader(label: uploaderName);
+ identity = AvatarIdentity.publicUploader(uploaderName);
} else {
if (file.ownerID == null) {
return const SizedBox.shrink();
diff --git a/mobile/apps/photos/lib/ui/viewer/search/contact_avatar_widget.dart b/mobile/apps/photos/lib/ui/viewer/search/contact_avatar_widget.dart
index 36d48649c0..77d37edce9 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/contact_avatar_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/contact_avatar_widget.dart
@@ -5,7 +5,6 @@ import "package:flutter/material.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/events/contacts_changed_event.dart";
import "package:photos/models/api/collection/user.dart";
-import "package:photos/services/contacts/contact_identity_resolver.dart";
import "package:photos/services/photos_contacts_service.dart";
import "package:photos/ui/sharing/user_avator_widget.dart";
import "package:photos/ui/viewer/people/face_thumbnail_squircle.dart";
@@ -100,7 +99,9 @@ class _ContactAvatarWidgetState extends State<ContactAvatarWidget> {
},
);
}
- return UserInitialsAvatar(_fallbackUser());
+ return UserInitialsAvatar(
+ UserSuggestion(widget.email, userID: widget.contactUserId),
+ );
},
);
return SizedBox(
@@ -123,14 +124,4 @@ class _ContactAvatarWidgetState extends State<ContactAvatarWidget> {
widget.contactUserId,
);
}
-
- User _fallbackUser() {
- final baseUser = User(id: widget.contactUserId, email: widget.email);
- return User(
- id: widget.contactUserId,
- email: resolveKnownEmail(baseUser) ?? widget.email,
- // ignore: deprecated_member_use_from_same_package
- name: resolveDisplayName(baseUser),
- );
- }
}
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 4adecb2cf6..215dfb59b3 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
@@ -307,13 +307,13 @@ class _ContactResultPageState extends State<ContactResultPage> {
),
);
if (updated is contacts.ContactRecord && mounted) {
- final personData = PersonService.instance.getCachedPartialPersonData(
- userID: _contactUserId,
- email: _contactEmail,
+ final person = PersonService.instance.getCachedPersonForUser(
+ _contactUserId,
+ _contactEmail,
);
setState(() {
_savedContact = updated;
- _personId = personData?[PersonService.kPersonIDKey];
+ _personId = person?.remoteID;
});
}
}
diff --git a/mobile/apps/photos/lib/utils/avatar_util.dart b/mobile/apps/photos/lib/utils/avatar_util.dart
index 44c23aed5a..fbf7a734de 100644
--- a/mobile/apps/photos/lib/utils/avatar_util.dart
+++ b/mobile/apps/photos/lib/utils/avatar_util.dart
@@ -22,13 +22,16 @@ class AvatarIdentity {
required String label,
required String? email,
required int? userID,
+ int? currentUserID,
required String? currentUserEmail,
String? personID,
}) {
final normalizedEmail = normalizeAvatarEmail(email);
- final role =
- normalizedEmail != null &&
- normalizedEmail == normalizeAvatarEmail(currentUserEmail)
+ final isCurrentUser =
+ (userID != null && userID > 0 && userID == currentUserID) ||
+ (normalizedEmail != null &&
+ normalizedEmail == normalizeAvatarEmail(currentUserEmail));
+ final role = isCurrentUser
? AvatarIdentityRole.currentUser
: AvatarIdentityRole.standard;
return AvatarIdentity._(
@@ -44,7 +47,7 @@ class AvatarIdentity {
);
}
- factory AvatarIdentity.publicUploader({required String label}) {
+ factory AvatarIdentity.publicUploader(String label) {
return AvatarIdentity._(
label: label,
key: avatarIdentityKey(name: label),
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 2fbc354b49..bd3c380d77 100644
--- a/mobile/apps/photos/lib/utils/person_contact_linking_util.dart
+++ b/mobile/apps/photos/lib/utils/person_contact_linking_util.dart
@@ -1,4 +1,3 @@
-import "package:collection/collection.dart";
import "package:ente_pure_utils/ente_pure_utils.dart";
import "package:ente_strings/ente_strings.dart";
import "package:flutter/widgets.dart";
@@ -36,19 +35,10 @@ Future<PersonEntity?> findPersonLinkedToContact({
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),
+ return PersonService.findPersonForUser(
+ persons,
+ userID: contactUserId,
+ email: email,
);
}
@@ -61,25 +51,11 @@ Future<PersonEntity?> findPersonLinkedToEmail(
return null;
}
final persons = await PersonService.instance.getPersons();
- bool includePerson(PersonEntity person) =>
- person.remoteID != excludedPersonId;
- if (isCurrentUserContactLinkEmail(normalizedEmail)) {
- final currentUserMatch = persons.firstWhereOrNull(
- (person) =>
- includePerson(person) &&
- isCurrentUserContactLink(
- email: person.data.email,
- userID: person.data.userID,
- ),
- );
- if (currentUserMatch != null) {
- return currentUserMatch;
- }
- }
- return persons.firstWhereOrNull(
- (person) =>
- includePerson(person) &&
- contactLinkEmailMatches(person.data.email, normalizedEmail),
+ return PersonService.findPersonForUser(
+ persons,
+ userID: currentUserIDForContactLinkEmail(normalizedEmail),
+ email: normalizedEmail,
+ excludedPersonID: excludedPersonId,
);
}
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 ffe3ba79d4..8c2d45299c 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
@@ -115,6 +115,47 @@ void main() {
expect(storedJson["email"], isNull);
});
+ test(
+ "matching keeps IDs authoritative with normalized legacy fallback",
+ () {
+ final persons = [
+ PersonEntity(
+ "legacy-person",
+ PersonData(name: "Legacy", email: " [email protected] "),
+ ),
+ PersonEntity(
+ "other-user",
+ PersonData(name: "Other", email: "[email protected]", userID: 8),
+ ),
+ ];
+
+ expect(
+ PersonService.findPersonForUser(
+ persons,
+ userID: 8,
+ email: "[email protected]",
+ )?.remoteID,
+ "other-user",
+ );
+ expect(
+ PersonService.findPersonForUser(
+ persons,
+ userID: 7,
+ email: "[email protected]",
+ )?.remoteID,
+ "legacy-person",
+ );
+ expect(
+ PersonService.findPersonForUser(
+ persons,
+ userID: 7,
+ email: " [email protected] ",
+ ),
+ isNull,
+ );
+ },
+ );
+
test("updateAttributes syncs changed name to linked contact", () async {
final updated = await personService.updateAttributes(
"person-1",
diff --git a/mobile/apps/photos/test/models/social/comment_author_utils_test.dart b/mobile/apps/photos/test/models/social/comment_author_utils_test.dart
index 985d5ae455..fdca2ee7bb 100644
--- a/mobile/apps/photos/test/models/social/comment_author_utils_test.dart
+++ b/mobile/apps/photos/test/models/social/comment_author_utils_test.dart
@@ -26,21 +26,8 @@ void main() {
registeredUserResolver: _registeredUser,
);
- expect(firstUser.id, secondUser.id);
- expect(firstUser.toMap()["name"], "Alice");
- expect(secondUser.toMap()["name"], "Bob");
- });
-
- test("falls back to anonUserID when display name is missing", () {
- final resolver = CommentAuthorResolver();
- final user = resolver.resolve(
- comment: _comment(id: "comment-1", userID: -1, anonUserID: "anon-a"),
- anonDisplayNames: const {},
- registeredUserResolver: _registeredUser,
- );
-
- expect(user.toMap()["name"], "anon-a");
- expect(user.email, "[email protected]");
+ expect(firstUser.label, "Alice");
+ expect(secondUser.label, "Bob");
});
});
@@ -108,6 +95,6 @@ User _registeredUser(int userID) {
return User(
id: userID,
- name: "User $userID",
+ label: "User $userID",
);
}
diff --git a/mobile/apps/photos/test/services/contacts/direct_contact_users_test.dart b/mobile/apps/photos/test/services/contacts/direct_contact_users_test.dart
index 9bc9ad3b39..554d0cabaf 100644
--- a/mobile/apps/photos/test/services/contacts/direct_contact_users_test.dart
+++ b/mobile/apps/photos/test/services/contacts/direct_contact_users_test.dart
@@ -46,7 +46,6 @@ void main() {
users.singleWhere((user) => user.email == "[email protected]").id,
6,
);
- expect(users.every((user) => user.id != null && user.id! > 0), isTrue);
});
test("deduplicates by user id after an email change", () {
@@ -70,67 +69,8 @@ void main() {
],
);
- expect(users, hasLength(1));
- expect(users.single.id, 5);
expect(users.single.email, "[email protected]");
});
-
- test("excludes candidates without a positive user id", () {
- final users = buildDirectContactUsers(
- ownerUserId: 1,
- ownerEmail: "[email protected]",
- collections: [
- _collection(
- owner: User(id: 1, email: "[email protected]"),
- sharees: [User(email: "[email protected]")],
- ),
- _collection(
- owner: User(email: "[email protected]"),
- sharees: const [],
- ),
- ],
- familyMembers: [
- _familyMember(
- FamilyMemberStatus.accepted,
- ),
- ],
- savedContacts: [
- _savedContact(
- id: "contact-1",
- userID: 0,
- email: "[email protected]",
- ),
- ],
- );
-
- expect(users, isEmpty);
- });
-
- test("excludes saved contacts without a known email", () {
- final users = buildDirectContactUsers(
- ownerUserId: 1,
- ownerEmail: "[email protected]",
- collections: const [],
- familyMembers: const [],
- savedContacts: [
- _savedContact(
- id: "missing-email",
- userID: 2,
- email: null,
- name: "Missing",
- ),
- _savedContact(
- id: "placeholder-email",
- userID: 3,
- email: "[email protected]",
- name: "Placeholder",
- ),
- ],
- );
-
- expect(users, isEmpty);
- });
}
contacts.ContactRecord _savedContact({
diff --git a/mobile/apps/photos/test/services/library_sharing_service_test.dart b/mobile/apps/photos/test/services/library_sharing_service_test.dart
index 7ed0b27a8c..4f181f2a80 100644
--- a/mobile/apps/photos/test/services/library_sharing_service_test.dart
+++ b/mobile/apps/photos/test/services/library_sharing_service_test.dart
@@ -23,11 +23,6 @@ void main() {
];
final fixture = await _Fixture.create(albums, blockedIDs: {100, 101});
- expect(
- (await fixture.service.getEligibleAlbums()).last.type,
- CollectionType.uncategorized,
- );
-
final result = await fixture.service.enableAutomaticSharing(
recipient: librarySharingTestRecipient,
role: CollectionParticipantRole.admin,
@@ -36,13 +31,6 @@ void main() {
expect(result.failedIDs, isEmpty);
expect(result.previouslyUnsharedIDs, {100, 101});
expect(fixture.collectionsService.shareBatchSizes, [100, 1]);
- expect(fixture.collectionsService.recipientEmails, [
- librarySharingTestRecipient.email,
- librarySharingTestRecipient.email,
- ]);
- expect(fixture.userService.publicKeyEmails, [
- librarySharingTestRecipient.email,
- ]);
expect(
fixture.collectionsService.sharedRoles[101],
CollectionParticipantRole.viewer,
@@ -82,8 +70,6 @@ void main() {
config = await fixture.readConfig();
expect(config.hidden, {album.id});
expect(config.addedAutomatically, isEmpty);
- expect(fixture.collectionsService.shareAttempts, [album.id]);
- expect(fixture.collectionsService.unshareAttempts, [album.id]);
expect(album.sharees, isEmpty);
});
@@ -174,14 +160,6 @@ void main() {
await fixture.service.reconcile();
expect(fixture.userService.userDetailsFetches, 3);
expect(await fixture.isAutomaticSharingEnabled(), isFalse);
- expect(fixture.collectionsService.shareBatchSizes, [
- 1,
- 100,
- 1,
- 100,
- 100,
- 100,
- ]);
expect(albums.last.sharees, isEmpty);
},
);
@@ -242,9 +220,6 @@ class _FakeCollectionsService extends Mock implements CollectionsService {
final Set<int> blockedIDs;
Object? shareError;
final List<int> shareBatchSizes = [];
- final List<String> recipientEmails = [];
- final List<int> shareAttempts = [];
- final List<int> unshareAttempts = [];
final Map<int, CollectionParticipantRole> sharedRoles = {};
@override
@@ -271,11 +246,9 @@ class _FakeCollectionsService extends Mock implements CollectionsService {
required CollectionShareSource source,
}) async {
shareBatchSizes.add(roles.length);
- recipientEmails.add(recipientEmail);
if (shareError != null) {
throw shareError!;
}
- shareAttempts.addAll(roles.keys);
sharedRoles.addAll(roles);
for (final entry in roles.entries) {
if (blockedIDs.contains(entry.key)) {
@@ -306,7 +279,6 @@ class _FakeCollectionsService extends Mock implements CollectionsService {
required List<int> collectionIDs,
required CollectionShareSource source,
}) async {
- unshareAttempts.addAll(collectionIDs);
for (final id in collectionIDs) {
albums
.firstWhere((album) => album.id == id)
@@ -328,19 +300,15 @@ class _FakeUserService extends Mock implements UserService {
Set<int>? refreshedActiveFamilyMemberUserIDs;
Object? userDetailsError;
int userDetailsFetches = 0;
- final List<String> publicKeyEmails = [];
@override
- Future<String?> getPublicKey(String email) async {
- publicKeyEmails.add(email);
- return email == librarySharingTestRecipient.email ? 'public-key' : null;
- }
+ Future<String?> getPublicKey(String email) async => 'public-key';
@override
- List<User> getRelevantContacts() => [
- User(
- id: librarySharingTestRecipient.userID,
- email: librarySharingTestRecipient.email,
+ List<UserSuggestion> getRelevantContacts() => [
+ UserSuggestion(
+ librarySharingTestRecipient.email,
+ userID: librarySharingTestRecipient.userID,
),
];
diff --git a/mobile/apps/photos/test/utils/avatar_util_test.dart b/mobile/apps/photos/test/utils/avatar_util_test.dart
index 44f6a8ef6e..a5e4e6bb97 100644
--- a/mobile/apps/photos/test/utils/avatar_util_test.dart
+++ b/mobile/apps/photos/test/utils/avatar_util_test.dart
@@ -1,5 +1,3 @@
-import "package:ente_components/ente_components.dart";
-import "package:flutter/material.dart";
import "package:flutter_test/flutter_test.dart";
import "package:photos/utils/avatar_util.dart";
@@ -21,25 +19,6 @@ void main() {
expect(before.key, "email:[email protected]");
expect(after.key, before.key);
- expect(before.role, AvatarIdentityRole.standard);
- });
-
- test("falls back through stable IDs before name", () {
- expect(
- AvatarIdentity.account(
- label: "Alice",
- email: "[email protected]",
- userID: 7,
- currentUserEmail: null,
- ).key,
- "user:7",
- );
- expect(
- avatarIdentityKey(personID: "person-1", name: "Alice"),
- "person:person-1",
- );
- expect(avatarIdentityKey(name: " Alice Smith "), "name:alice smith");
- expect(avatarIdentityKey(userID: -1, name: "Alice"), "name:alice");
});
test("anonymous identity is independent of its display name", () {
@@ -58,68 +37,17 @@ void main() {
expect(before.key, "anonymous:anon-1");
expect(after.key, before.key);
- expect(after.role, AvatarIdentityRole.standard);
});
- test("marks the signed-in email as the current-user role", () {
+ test("marks the signed-in account as the current-user role", () {
final identity = AvatarIdentity.account(
label: "Alice",
email: " [email protected] ",
userID: 7,
- currentUserEmail: "[email protected]",
+ currentUserID: 7,
+ currentUserEmail: "[email protected]",
);
expect(identity.role, AvatarIdentityRole.currentUser);
- expect(identity.key, "email:[email protected]");
- });
-
- test("component colors preserve explicit black avatar roles", () {
- final currentUser = AvatarIdentity.account(
- label: "Alice",
- email: "[email protected]",
- userID: 7,
- currentUserEmail: "[email protected]",
- );
- final publicUploader = AvatarIdentity.publicUploader(label: "Alice");
-
- expect(
- avatarComponentColorForAvatarIdentity(currentUser),
- AvatarComponentColor.black,
- );
- expect(
- avatarComponentColorForAvatarIdentity(publicUploader),
- AvatarComponentColor.black,
- );
- });
-
- testWidgets("standard avatar backgrounds use the component palette", (
- tester,
- ) async {
- final identity = AvatarIdentity.account(
- label: "Alice",
- email: "[email protected]",
- userID: 7,
- currentUserEmail: null,
- );
- late Color actual;
- late Color expected;
-
- await tester.pumpWidget(
- MaterialApp(
- theme: ComponentTheme.lightTheme(),
- home: Builder(
- builder: (context) {
- actual = avatarBackgroundColor(context, identity);
- expected = avatarComponentColorValue(
- context,
- avatarComponentColorForIdentity(identity.key),
- );
- return const SizedBox.shrink();
- },
- ),
- ),
- );
-
- expect(actual, expected);
});
}
diff --git a/mobile/packages/contacts/lib/contacts.dart b/mobile/packages/contacts/lib/contacts.dart
index c502ece7d0..f1ec673c34 100644
--- a/mobile/packages/contacts/lib/contacts.dart
+++ b/mobile/packages/contacts/lib/contacts.dart
@@ -9,5 +9,6 @@ export 'src/db/contacts_database.dart';
export 'src/models/contact_data.dart';
export 'src/models/contact_record.dart';
export 'src/models/contacts_session.dart';
+export 'src/service/contact_directory.dart';
export 'src/service/contacts_display_service.dart';
export 'src/service/contacts_service.dart';
diff --git a/mobile/packages/contacts/lib/src/service/contact_directory.dart b/mobile/packages/contacts/lib/src/service/contact_directory.dart
new file mode 100644
index 0000000000..05c77441c5
--- /dev/null
+++ b/mobile/packages/contacts/lib/src/service/contact_directory.dart
@@ -0,0 +1,497 @@
+import 'dart:async';
+
+import 'package:ente_contacts/src/models/contact_data.dart';
+import 'package:ente_contacts/src/models/contact_record.dart';
+import 'package:ente_contacts/src/models/contacts_session.dart';
+import 'package:ente_contacts/src/service/contacts_service.dart';
+import 'package:flutter/foundation.dart';
+import 'package:logging/logging.dart';
+
+typedef ContactsServiceFactory = ContactsService Function();
+
+/// Account-scoped, observable contact cache over [ContactsService].
+class ContactDirectory {
+ ContactDirectory({
+ ContactsService? contactsService,
+ ContactsServiceFactory? contactsServiceFactory,
+ void Function(Set<int>? contactUserIds)? onContactsChanged,
+ Logger? logger,
+ Duration profilePictureFailureTtl = const Duration(minutes: 1),
+ }) : _contactsServiceFactory =
+ contactsServiceFactory ??
+ (contactsService == null ? null : () => contactsService),
+ _logger = logger ?? Logger('ContactDirectory'),
+ _profilePictureFailureTtl = profilePictureFailureTtl,
+ _onContactsChanged = onContactsChanged;
+
+ final ContactsServiceFactory? _contactsServiceFactory;
+ final Logger _logger;
+ final Duration _profilePictureFailureTtl;
+ final void Function(Set<int>? contactUserIds)? _onContactsChanged;
+ final ValueNotifier<int> _revision = ValueNotifier(0);
+ final Map<int, ValueNotifier<int>> _contactRevisions = {};
+ final Map<int, ContactRecord> _contactsByUserId = {};
+ final Map<String, ContactRecord> _contactsByEmail = {};
+ final Map<int, Uint8List?> _picturesByUserId = {};
+ final Map<int, Future<Uint8List?>> _pictureLoads = {};
+ final Map<int, DateTime> _pictureFailureUntil = {};
+
+ _ActiveContacts? _active;
+ bool _hasHydratedCache = false;
+
+ ValueListenable<int> get revision => _revision;
+
+ ValueListenable<int> revisionForContact(int contactUserId) =>
+ _contactRevisions.putIfAbsent(contactUserId, () => ValueNotifier(0));
+
+ bool get hasHydratedCache => _hasHydratedCache;
+ bool get needsWarmup => !_hasHydratedCache || _active?.ready == null;
+
+ Future<void> ensureReady(ContactsSession session) async {
+ final key = _sessionKey(session);
+ var active = _active;
+ if (active?.key != key) {
+ _clear(notify: true);
+ active = _ActiveContacts(
+ key: key,
+ authToken: session.authToken,
+ service: _newContactsService(),
+ );
+ _active = active;
+ }
+
+ final ready = active!.ready;
+ if (ready == null) {
+ final opening = _hydrate(active, session);
+ active.ready = opening;
+ try {
+ await opening;
+ } catch (error, stackTrace) {
+ if (_isActive(active)) active.ready = null;
+ _logger.warning('Failed to open contacts store', error, stackTrace);
+ rethrow;
+ }
+ } else {
+ await ready;
+ }
+
+ if (!_isActive(active) || active.authToken == session.authToken) return;
+ await active.service.updateAuthToken(session.authToken);
+ if (_isActive(active)) active.authToken = session.authToken;
+ }
+
+ Future<void> resetLocalState() async {
+ final service = _active?.service;
+ _clear(notify: true);
+ await service?.resetLocalState();
+ }
+
+ void clearSession({bool notify = true}) => _clear(notify: notify);
+
+ /// Positive account IDs are authoritative and never fall back to email;
+ /// email lookup is only for identities without a known account ID.
+ ContactRecord? getCachedContact({int? contactUserId, String? email}) {
+ if (contactUserId != null && contactUserId > 0) {
+ return _contactsByUserId[contactUserId];
+ }
+ final normalized = _normalizeEmail(email);
+ return normalized == null ? null : _contactsByEmail[normalized];
+ }
+
+ String? getCachedSavedName({int? contactUserId, String? email}) =>
+ _trimToNull(
+ getCachedContact(
+ contactUserId: contactUserId,
+ email: email,
+ )?.data?.name,
+ );
+
+ String? getCachedResolvedEmail({int? contactUserId, String? email}) =>
+ _trimToNull(
+ getCachedContact(contactUserId: contactUserId, email: email)?.email,
+ );
+
+ List<ContactRecord> getCachedContacts() =>
+ List.unmodifiable(_contactsByUserId.values);
+
+ Uint8List? getCachedProfilePictureBytesByUserId(int? contactUserId) =>
+ hasResolvedProfilePictureByUserId(contactUserId)
+ ? _picturesByUserId[contactUserId]
+ : null;
+
+ bool hasResolvedProfilePictureByUserId(int? contactUserId) =>
+ contactUserId != null && _picturesByUserId.containsKey(contactUserId);
+
+ void preloadProfilePictureByUserId(int? contactUserId) {
+ if (contactUserId == null ||
+ _active == null ||
+ hasResolvedProfilePictureByUserId(contactUserId) ||
+ _pictureLoads.containsKey(contactUserId)) {
+ return;
+ }
+ final contact = getCachedContact(contactUserId: contactUserId);
+ if (contact == null) {
+ if (_hasHydratedCache) _picturesByUserId[contactUserId] = null;
+ return;
+ }
+ final failureUntil = _pictureFailureUntil[contactUserId];
+ if (failureUntil?.isAfter(DateTime.now()) ?? false) return;
+
+ final active = _requireActive();
+ late final Future<Uint8List?> load;
+ load = _loadPicture(active, contact).whenComplete(() {
+ if (identical(_pictureLoads[contactUserId], load)) {
+ _pictureLoads.remove(contactUserId);
+ }
+ });
+ _pictureLoads[contactUserId] = load;
+ unawaited(load);
+ }
+
+ Future<Uint8List?> getProfilePictureBytesByUserId(int? contactUserId) async {
+ if (contactUserId == null || _active == null) return null;
+ if (hasResolvedProfilePictureByUserId(contactUserId)) {
+ return _picturesByUserId[contactUserId];
+ }
+ preloadProfilePictureByUserId(contactUserId);
+ return _pictureLoads[contactUserId] ?? _picturesByUserId[contactUserId];
+ }
+
+ Future<ContactRecord> createOrUpdateContact({
+ required int contactUserId,
+ required String name,
+ }) async {
+ final active = _requireActive();
+ final existing = await active.service.getContactByUserId(
+ contactUserId,
+ includeDeleted: true,
+ );
+ _requireActiveSession(active);
+ final data = ContactData(contactUserId: contactUserId, name: name.trim());
+ final contact = existing == null
+ ? await active.service.createContact(data)
+ : await active.service.updateContact(existing.id, data);
+ _requireActiveSession(active);
+ _cacheAndNotify(contact);
+ return contact;
+ }
+
+ Future<ContactRecord?> createContactWithProfilePictureIfAbsent({
+ required int contactUserId,
+ required String name,
+ required Uint8List bytes,
+ }) async {
+ final active = _requireActive();
+ final existing = await active.service.getContactByUserId(
+ contactUserId,
+ includeDeleted: true,
+ );
+ if (!_isActive(active)) return null;
+ if (existing != null) {
+ if (!existing.isDeleted) _cache(existing);
+ return existing.isDeleted ? null : existing;
+ }
+
+ final created = await active.service.createContact(
+ ContactData(contactUserId: contactUserId, name: name.trim()),
+ );
+ if (!_isActive(active)) return null;
+ late ContactRecord updated;
+ try {
+ updated = await active.service.setProfilePicture(created.id, bytes);
+ } catch (_) {
+ if (!_isActive(active)) rethrow;
+ updated = await active.service.setProfilePicture(created.id, bytes);
+ }
+ if (!_isActive(active)) return null;
+ _cachePicture(updated, bytes);
+ return updated;
+ }
+
+ Future<ContactRecord> setProfilePicture({
+ required String contactId,
+ required Uint8List bytes,
+ }) async {
+ final active = _requireActive();
+ final contact = await active.service.setProfilePicture(contactId, bytes);
+ _requireActiveSession(active);
+ _cachePicture(contact, bytes);
+ return contact;
+ }
+
+ Future<ContactRecord> deleteProfilePicture({
+ required String contactId,
+ }) async {
+ final active = _requireActive();
+ final contact = await active.service.deleteProfilePicture(contactId);
+ _requireActiveSession(active);
+ _cache(contact);
+ _picturesByUserId[contact.contactUserId] = null;
+ _pictureFailureUntil.remove(contact.contactUserId);
+ _notifyContacts({contact.contactUserId});
+ return contact;
+ }
+
+ void debugHydrateContacts(
+ List<ContactRecord> contacts, {
+ bool markHydrated = false,
+ bool notify = false,
+ }) {
+ final changed = _cacheAll(contacts);
+ if (markHydrated) _hasHydratedCache = true;
+ if (notify && changed.isNotEmpty) _notifyContacts(changed);
+ }
+
+ void debugSetProfilePictureBytes({
+ required int contactUserId,
+ Uint8List? bytes,
+ bool notify = true,
+ }) {
+ _picturesByUserId[contactUserId] = bytes;
+ _pictureFailureUntil.remove(contactUserId);
+ _pictureLoads.remove(contactUserId);
+ if (notify) _notifyContactDisplay(contactUserId);
+ }
+
+ Future<void> debugReset({bool clearLocalState = true}) async {
+ final service = _active?.service;
+ if (clearLocalState) await service?.resetLocalState();
+ _clear(notify: false);
+ _revision.value = 0;
+ }
+
+ Future<void> _hydrate(_ActiveContacts active, ContactsSession session) async {
+ await active.service.open(session);
+ if (!_isActive(active)) return;
+
+ final knownUserIds = _contactsByUserId.keys.toSet();
+ final local = await active.service.getContacts();
+ if (!_isActive(active)) return;
+ final localChanged = _cacheAll(local);
+ _hasHydratedCache = true;
+ if (localChanged.isNotEmpty) {
+ _notifyDisplay();
+ _notifyContactDisplayAll(localChanged);
+ }
+ final changedUserIds = local
+ .map((contact) => contact.contactUserId)
+ .where((userId) => !knownUserIds.contains(userId))
+ .toSet();
+
+ try {
+ final diff = await active.service.sync();
+ if (!_isActive(active)) return;
+ final diffChanged = _cacheAll(diff);
+ if (diffChanged.isNotEmpty) {
+ _notifyDisplay();
+ _notifyContactDisplayAll(diffChanged);
+ }
+ changedUserIds.addAll(diff.map((contact) => contact.contactUserId));
+ } catch (error, stackTrace) {
+ if (!_isActive(active)) return;
+ active.ready = null;
+ _logger.warning(
+ 'Failed to sync contacts after hydrating local cache',
+ error,
+ stackTrace,
+ );
+ }
+ if (changedUserIds.isNotEmpty) _notifyRecordListeners(changedUserIds);
+ }
+
+ Future<Uint8List?> _loadPicture(
+ _ActiveContacts active,
+ ContactRecord contact,
+ ) async {
+ final attachmentId = contact.profilePictureAttachmentId;
+ if (attachmentId == null) {
+ _picturesByUserId[contact.contactUserId] = null;
+ return null;
+ }
+ try {
+ final bytes = await active.service.getProfilePicture(contact.id);
+ if (!_isActive(active)) return null;
+ if (!_isCurrentPicture(contact, attachmentId)) {
+ return _picturesByUserId[contact.contactUserId];
+ }
+ _picturesByUserId[contact.contactUserId] = bytes;
+ _pictureFailureUntil.remove(contact.contactUserId);
+ _notifyContactDisplay(contact.contactUserId);
+ return bytes;
+ } catch (error, stackTrace) {
+ if (!_isActive(active)) return null;
+ if (!_isCurrentPicture(contact, attachmentId)) {
+ return _picturesByUserId[contact.contactUserId];
+ }
+ _pictureFailureUntil[contact.contactUserId] = DateTime.now().add(
+ _profilePictureFailureTtl,
+ );
+ _logger.info(
+ 'Failed to load contact profile picture for user ${contact.contactUserId}',
+ error,
+ stackTrace,
+ );
+ return null;
+ }
+ }
+
+ Set<int> _cacheAll(List<ContactRecord> contacts) {
+ final changed = <int>{};
+ for (final contact in contacts) {
+ if (_cache(contact)) {
+ changed.add(contact.contactUserId);
+ }
+ }
+ return changed;
+ }
+
+ bool _cache(ContactRecord contact) {
+ final previous = _contactsByUserId[contact.contactUserId];
+ final previousEmail = _normalizeEmail(previous?.email);
+ if (previousEmail != null &&
+ _contactsByEmail[previousEmail]?.contactUserId ==
+ contact.contactUserId) {
+ _contactsByEmail.remove(previousEmail);
+ }
+ if (contact.isDeleted) {
+ _contactsByUserId.remove(contact.contactUserId);
+ if (previous != null) {
+ _invalidatePicture(contact.contactUserId);
+ }
+ return previous != null;
+ }
+
+ _contactsByUserId[contact.contactUserId] = contact;
+ final email = _normalizeEmail(contact.email);
+ if (email != null) _contactsByEmail[email] = contact;
+ if (previous?.profilePictureAttachmentId !=
+ contact.profilePictureAttachmentId) {
+ _invalidatePicture(contact.contactUserId);
+ }
+ return !_sameContact(previous, contact);
+ }
+
+ bool _sameContact(ContactRecord? a, ContactRecord b) =>
+ a != null &&
+ a.id == b.id &&
+ a.updatedAt == b.updatedAt &&
+ a.isDeleted == b.isDeleted &&
+ a.email == b.email &&
+ a.data?.name == b.data?.name &&
+ a.profilePictureAttachmentId == b.profilePictureAttachmentId;
+
+ void _cacheAndNotify(ContactRecord contact) {
+ _cache(contact);
+ _notifyContacts({contact.contactUserId});
+ }
+
+ void _cachePicture(ContactRecord contact, Uint8List bytes) {
+ _cache(contact);
+ _picturesByUserId[contact.contactUserId] = bytes;
+ _pictureFailureUntil.remove(contact.contactUserId);
+ _notifyContacts({contact.contactUserId});
+ }
+
+ void _clear({required bool notify}) {
+ final hadContacts = _contactsByUserId.isNotEmpty;
+ final contactUserIds = _contactsByUserId.keys.toList(growable: false);
+ final hadDisplayState = hadContacts || _picturesByUserId.isNotEmpty;
+ _active = null;
+ _hasHydratedCache = false;
+ _contactsByUserId.clear();
+ _contactsByEmail.clear();
+ _picturesByUserId.clear();
+ _pictureLoads.clear();
+ _pictureFailureUntil.clear();
+ if (notify && hadDisplayState) _notifyDisplay();
+ if (notify) _notifyContactDisplayAll(contactUserIds);
+ if (notify && hadContacts) _notifyRecordListeners(null);
+ }
+
+ void _invalidatePicture(int contactUserId) {
+ _picturesByUserId.remove(contactUserId);
+ _pictureLoads.remove(contactUserId);
+ _pictureFailureUntil.remove(contactUserId);
+ }
+
+ void _notifyContacts(Set<int> contactUserIds) {
+ _notifyDisplay();
+ _notifyContactDisplayAll(contactUserIds);
+ _notifyRecordListeners(contactUserIds);
+ }
+
+ void _notifyDisplay() => _revision.value += 1;
+
+ void _notifyContactDisplay(int contactUserId) {
+ final revision = _contactRevisions[contactUserId];
+ if (revision != null) revision.value += 1;
+ }
+
+ void _notifyContactDisplayAll(Iterable<int> contactUserIds) {
+ for (final contactUserId in contactUserIds) {
+ _notifyContactDisplay(contactUserId);
+ }
+ }
+
+ void _notifyRecordListeners(Set<int>? contactUserIds) {
+ _onContactsChanged?.call(contactUserIds);
+ }
+
+ bool _isCurrentPicture(ContactRecord contact, String attachmentId) {
+ final current = _contactsByUserId[contact.contactUserId];
+ return current?.id == contact.id &&
+ current?.profilePictureAttachmentId == attachmentId;
+ }
+
+ _ActiveContacts _requireActive() {
+ final active = _active;
+ if (active == null) {
+ throw StateError(
+ 'ContactDirectory.ensureReady(...) must be called first',
+ );
+ }
+ return active;
+ }
+
+ void _requireActiveSession(_ActiveContacts active) {
+ if (!_isActive(active)) {
+ throw StateError('Contacts session changed while applying an update');
+ }
+ }
+
+ bool _isActive(_ActiveContacts active) => identical(active, _active);
+
+ ContactsService _newContactsService() {
+ final factory = _contactsServiceFactory;
+ if (factory == null) {
+ throw StateError('ContactDirectory requires a contacts service factory');
+ }
+ return factory();
+ }
+
+ String _sessionKey(ContactsSession session) =>
+ '${session.baseUrl}|${session.userId}';
+
+ String? _normalizeEmail(String? value) {
+ final normalized = value?.trim().toLowerCase();
+ return normalized == null || normalized.isEmpty ? null : normalized;
+ }
+
+ String? _trimToNull(String? value) {
+ final trimmed = value?.trim();
+ return trimmed == null || trimmed.isEmpty ? null : trimmed;
+ }
+}
+
+class _ActiveContacts {
+ _ActiveContacts({
+ required this.key,
+ required this.authToken,
+ required this.service,
+ });
+
+ final String key;
+ final ContactsService service;
+ String authToken;
+ Future<void>? ready;
+}
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 2923efc089..9718062bda 100644
--- a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
+++ b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
@@ -1,235 +1,100 @@
-import 'dart:async';
-
import 'package:ente_contacts/src/models/contact_record.dart';
import 'package:ente_contacts/src/models/contacts_session.dart';
+import 'package:ente_contacts/src/service/contact_directory.dart';
import 'package:ente_contacts/src/service/contacts_service.dart';
import 'package:flutter/foundation.dart';
-import 'package:logging/logging.dart';
import 'package:shared_preferences/shared_preferences.dart';
+/// Read-oriented compatibility facade over the shared [ContactDirectory].
class ContactsDisplayService {
- ContactsDisplayService._privateConstructor();
+ ContactsDisplayService._privateConstructor() : _store = ContactDirectory();
static final ContactsDisplayService instance =
ContactsDisplayService._privateConstructor();
- static const Duration _profilePictureFailureTtl = Duration(minutes: 1);
-
- final Logger _logger = Logger('ContactsDisplayService');
- final ValueNotifier<int> _changes = ValueNotifier<int>(0);
- final Map<int, ContactRecord> _contactsByUserId = {};
- final Map<String, ContactRecord> _contactsByNormalizedEmail = {};
- final Map<int, String?> _normalizedEmailByUserId = {};
- final Map<int, Uint8List?> _profilePictureBytesByUserId = {};
- final Set<int> _resolvedProfilePictureUserIds = {};
- final Map<int, Future<Uint8List?>> _profilePictureLoadsByUserId = {};
- final Map<int, DateTime> _profilePictureFailureUntilByUserId = {};
-
- SharedPreferences? _preferences;
- ContactsService Function()? _contactsServiceFactory;
- ContactsService? _contacts;
- ContactsSession? _session;
- String? _sessionKey;
- String? _sessionAuthToken;
- Future<void>? _readyFuture;
- bool _hasHydratedCache = false;
- int _sessionGeneration = 0;
+ ContactDirectory _store;
- ValueListenable<int> get changes => _changes;
+ ValueListenable<int> get changes => _store.revision;
- bool get hasHydratedCache => _hasHydratedCache;
+ ValueListenable<int> changesFor({int? contactUserId, String? email}) {
+ final resolvedUserId = _resolvedContactUserId(
+ contactUserId: contactUserId,
+ email: email,
+ );
+ return resolvedUserId == null
+ ? changes
+ : _store.revisionForContact(resolvedUserId);
+ }
void init({
required SharedPreferences preferences,
ContactsService? contactsService,
ContactsService Function()? contactsServiceFactory,
}) {
- _preferences = preferences;
- _contactsServiceFactory =
- contactsServiceFactory ??
- (contactsService != null ? () => contactsService : null);
- _contacts ??= contactsService;
- }
-
- Future<void> ensureReady(ContactsSession session) async {
- final sessionKey = _buildSessionKey(session);
- if (_readyFuture != null && _sessionKey == sessionKey) {
- final contacts = _requireContacts();
- await _readyFuture;
- if (_sessionAuthToken != session.authToken) {
- await contacts.updateAuthToken(session.authToken);
- _sessionAuthToken = session.authToken;
- _session = session;
- }
- return;
- }
-
- if (_sessionKey != sessionKey) {
- _sessionGeneration += 1;
- _clearCachedState(notify: true);
- }
- _contacts ??= _newContactsService();
- final currentContacts = _requireContacts();
-
- _session = session;
- _sessionKey = sessionKey;
- _sessionAuthToken = session.authToken;
-
- late final Future<void> readyFuture;
- final generation = _sessionGeneration;
- readyFuture = _openAndSync(currentContacts, session, generation).catchError(
- (Object error, StackTrace stackTrace) {
- if (identical(_readyFuture, readyFuture)) {
- _readyFuture = null;
- }
- _logger.warning(
- 'Failed to hydrate shared contacts display cache',
- error,
- stackTrace,
- );
- throw error;
- },
+ _store = ContactDirectory(
+ contactsService: contactsService,
+ contactsServiceFactory:
+ contactsServiceFactory ??
+ (contactsService == null
+ ? () => ContactsService(preferences: preferences)
+ : null),
);
- _readyFuture = readyFuture;
- await readyFuture;
}
- Future<void> updateAuthToken(String authToken) async {
- final contacts = _contacts;
- final session = _session;
- if (contacts == null || session == null) {
- return;
- }
- if (_sessionAuthToken == authToken) {
- return;
- }
- await contacts.updateAuthToken(authToken);
- _sessionAuthToken = authToken;
- _session = ContactsSession(
- baseUrl: session.baseUrl,
- authToken: authToken,
- userId: session.userId,
- accountKey: session.accountKey,
- accountKeyProvider: session.accountKeyProvider,
- userAgent: session.userAgent,
- clientPackage: session.clientPackage,
- clientVersion: session.clientVersion,
- );
- }
+ Future<void> ensureReady(ContactsSession session) =>
+ _store.ensureReady(session);
- Future<void> resetLocalState() async {
- final contacts = _contacts;
- _sessionGeneration += 1;
- _clearCachedState(notify: true);
- await contacts?.resetLocalState();
- }
+ Future<void> resetLocalState() => _store.resetLocalState();
- ContactRecord? getCachedContact({int? contactUserId, String? email}) {
- final cachedByUserId = _contactByUserIdOrNull(contactUserId);
- if (cachedByUserId != null) {
- return cachedByUserId;
- }
- return _contactByEmailOrNull(email);
- }
+ ContactRecord? getCachedContact({int? contactUserId, String? email}) =>
+ _store.getCachedContact(contactUserId: contactUserId, email: email);
- String? getCachedSavedName({int? contactUserId, String? email}) {
- final savedName = getCachedContact(
- contactUserId: contactUserId,
- email: email,
- )?.data?.name;
- if (savedName == null) {
- return null;
- }
- final trimmed = savedName.trim();
- return trimmed.isEmpty ? null : trimmed;
- }
+ String? getCachedSavedName({int? contactUserId, String? email}) =>
+ _store.getCachedSavedName(contactUserId: contactUserId, email: email);
+
+ String? getCachedResolvedEmail({int? contactUserId, String? email}) =>
+ _store.getCachedResolvedEmail(contactUserId: contactUserId, email: email);
- String? getCachedResolvedEmail({int? contactUserId, String? email}) {
- final resolved = getCachedContact(
+ Uint8List? getCachedProfilePictureBytes({int? contactUserId, String? email}) {
+ final resolvedUserId = _resolvedContactUserId(
contactUserId: contactUserId,
email: email,
- )?.email;
- if (resolved == null) {
- return null;
- }
- final trimmed = resolved.trim();
- return trimmed.isEmpty ? null : trimmed;
+ );
+ return _store.getCachedProfilePictureBytesByUserId(resolvedUserId);
}
- Uint8List? getCachedProfilePictureBytes({int? contactUserId, String? email}) {
+ bool hasResolvedProfilePicture({int? contactUserId, String? email}) {
final resolvedUserId = _resolvedContactUserId(
contactUserId: contactUserId,
email: email,
);
- if (resolvedUserId == null ||
- !_resolvedProfilePictureUserIds.contains(resolvedUserId)) {
- return null;
- }
- return _profilePictureBytesByUserId[resolvedUserId];
+ return _store.hasResolvedProfilePictureByUserId(resolvedUserId);
}
- bool hasResolvedProfilePicture({int? contactUserId, String? email}) {
+ void preloadProfilePicture({int? contactUserId, String? email}) {
final resolvedUserId = _resolvedContactUserId(
contactUserId: contactUserId,
email: email,
);
- return resolvedUserId != null &&
- _resolvedProfilePictureUserIds.contains(resolvedUserId);
+ _store.preloadProfilePictureByUserId(resolvedUserId ?? contactUserId);
}
Future<Uint8List?> getProfilePictureBytes({
int? contactUserId,
String? email,
- }) async {
- final contact = getCachedContact(
+ }) {
+ final resolvedUserId = _resolvedContactUserId(
contactUserId: contactUserId,
email: email,
);
- if (contact == null) {
- if (_hasHydratedCache) {
- final resolvedUserId = contactUserId;
- if (resolvedUserId != null) {
- _profilePictureBytesByUserId.remove(resolvedUserId);
- _resolvedProfilePictureUserIds.add(resolvedUserId);
- }
- }
- return null;
- }
-
- final contactUserIdValue = contact.contactUserId;
- if (_resolvedProfilePictureUserIds.contains(contactUserIdValue)) {
- return _profilePictureBytesByUserId[contactUserIdValue];
- }
-
- final failureUntil =
- _profilePictureFailureUntilByUserId[contactUserIdValue];
- final now = DateTime.now();
- if (failureUntil != null && failureUntil.isAfter(now)) {
- return null;
- }
-
- final inflightLoad = _profilePictureLoadsByUserId[contactUserIdValue];
- if (inflightLoad != null) {
- return inflightLoad;
- }
-
- final load = _loadProfilePictureBytes(contact);
- _profilePictureLoadsByUserId[contactUserIdValue] = load;
- return load.whenComplete(() {
- _profilePictureLoadsByUserId.remove(contactUserIdValue);
- });
+ return _store.getProfilePictureBytesByUserId(
+ resolvedUserId ?? contactUserId,
+ );
}
@visibleForTesting
Future<void> debugReset({bool clearLocalState = true}) async {
- final contacts = _contacts;
- if (clearLocalState) {
- await contacts?.resetLocalState();
- }
- _clearCachedState(notify: false);
- if (_changes.value != 0) {
- _changes.value = 0;
- }
+ await _store.debugReset(clearLocalState: clearLocalState);
}
@visibleForTesting
@@ -237,11 +102,7 @@ class ContactsDisplayService {
List<ContactRecord> contacts, {
bool notify = true,
}) {
- final changedUserIds = _cacheContacts(contacts);
- _hasHydratedCache = true;
- if (notify && changedUserIds.isNotEmpty) {
- _notifyChanged();
- }
+ _store.debugHydrateContacts(contacts, markHydrated: true, notify: notify);
}
@visibleForTesting
@@ -250,164 +111,11 @@ class ContactsDisplayService {
Uint8List? bytes,
bool notify = true,
}) {
- if (bytes == null) {
- _profilePictureBytesByUserId.remove(contactUserId);
- } else {
- _profilePictureBytesByUserId[contactUserId] = bytes;
- }
- _resolvedProfilePictureUserIds.add(contactUserId);
- _profilePictureFailureUntilByUserId.remove(contactUserId);
- _profilePictureLoadsByUserId.remove(contactUserId);
- if (notify) {
- _notifyChanged();
- }
- }
-
- Future<void> _openAndSync(
- ContactsService contacts,
- ContactsSession session,
- int generation,
- ) async {
- await contacts.open(session);
- if (!_isSessionGenerationCurrent(generation, session)) {
- return;
- }
-
- final localContacts = await contacts.getContacts();
- if (!_isSessionGenerationCurrent(generation, session)) {
- return;
- }
- final localChanged = _cacheContacts(localContacts);
- _hasHydratedCache = true;
- if (localChanged.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;
- }
- }
-
- Future<Uint8List?> _loadProfilePictureBytes(ContactRecord contact) async {
- final attachmentId = contact.profilePictureAttachmentId;
- if (attachmentId == null) {
- _profilePictureBytesByUserId.remove(contact.contactUserId);
- _resolvedProfilePictureUserIds.add(contact.contactUserId);
- return null;
- }
-
- try {
- final bytes = await _requireContacts().getProfilePicture(contact.id);
- final latestContact = _contactsByUserId[contact.contactUserId];
- if (latestContact == null ||
- latestContact.isDeleted ||
- latestContact.id != contact.id ||
- latestContact.profilePictureAttachmentId != attachmentId) {
- return _profilePictureBytesByUserId[contact.contactUserId];
- }
- _profilePictureBytesByUserId[contact.contactUserId] = bytes;
- _resolvedProfilePictureUserIds.add(contact.contactUserId);
- _profilePictureFailureUntilByUserId.remove(contact.contactUserId);
- _notifyChanged();
- return bytes;
- } catch (error, stackTrace) {
- _profilePictureFailureUntilByUserId[contact.contactUserId] =
- DateTime.now().add(_profilePictureFailureTtl);
- _logger.info(
- 'Failed to load shared contact profile picture for user ${contact.contactUserId}',
- error,
- stackTrace,
- );
- return null;
- }
- }
-
- Set<int> _cacheContacts(
- List<ContactRecord> contacts, {
- bool invalidateProfilePictures = false,
- }) {
- final changedUserIds = <int>{};
- for (final contact in contacts) {
- if (_cacheContact(
- contact,
- invalidateProfilePicture: invalidateProfilePictures,
- )) {
- changedUserIds.add(contact.contactUserId);
- }
- }
- return changedUserIds;
- }
-
- bool _cacheContact(
- ContactRecord contact, {
- required bool invalidateProfilePicture,
- }) {
- final existing = _contactsByUserId[contact.contactUserId];
- final previousEmail = _normalizedEmailByUserId[contact.contactUserId];
- if (previousEmail != null) {
- _contactsByNormalizedEmail.remove(previousEmail);
- }
-
- if (contact.isDeleted) {
- final wasCached = existing != null;
- _contactsByUserId.remove(contact.contactUserId);
- _normalizedEmailByUserId.remove(contact.contactUserId);
- if (invalidateProfilePicture || wasCached) {
- _invalidateProfilePictureCache(contact.contactUserId);
- }
- return wasCached;
- }
-
- final normalizedEmail = _normalizeEmail(contact.email);
- if (normalizedEmail != null) {
- _contactsByNormalizedEmail[normalizedEmail] = contact;
- }
- _normalizedEmailByUserId[contact.contactUserId] = normalizedEmail;
- _contactsByUserId[contact.contactUserId] = contact;
- if (invalidateProfilePicture) {
- _invalidateProfilePictureCache(contact.contactUserId);
- }
- return existing != contact;
- }
-
- ContactRecord? _contactByUserIdOrNull(int? contactUserId) {
- if (contactUserId == null) {
- return null;
- }
- final contact = _contactsByUserId[contactUserId];
- if (contact == null || contact.isDeleted) {
- return null;
- }
- return contact;
- }
-
- ContactRecord? _contactByEmailOrNull(String? email) {
- final normalizedEmail = _normalizeEmail(email);
- if (normalizedEmail == null) {
- return null;
- }
- final contact = _contactsByNormalizedEmail[normalizedEmail];
- if (contact == null || contact.isDeleted) {
- return null;
- }
- return contact;
+ _store.debugSetProfilePictureBytes(
+ contactUserId: contactUserId,
+ bytes: bytes,
+ notify: notify,
+ );
}
int? _resolvedContactUserId({int? contactUserId, String? email}) {
@@ -416,80 +124,4 @@ class ContactsDisplayService {
email: email,
)?.contactUserId;
}
-
- String _buildSessionKey(ContactsSession session) {
- return '${session.baseUrl}|${session.userId}';
- }
-
- String? _normalizeEmail(String? email) {
- if (email == null) {
- return null;
- }
- final trimmed = email.trim().toLowerCase();
- return trimmed.isEmpty ? null : trimmed;
- }
-
- ContactsService _requireContacts() {
- final contacts = _contacts;
- if (contacts == null) {
- throw StateError(
- 'ContactsDisplayService.init(preferences: ...) must be called before use',
- );
- }
- return contacts;
- }
-
- ContactsService _newContactsService() {
- final factory = _contactsServiceFactory;
- if (factory != null) {
- return factory();
- }
- final preferences = _preferences;
- if (preferences == null) {
- throw StateError(
- 'ContactsDisplayService.init(preferences: ...) must be called before use',
- );
- }
- return ContactsService(preferences: preferences);
- }
-
- bool _isSessionGenerationCurrent(int generation, ContactsSession session) {
- return _sessionGeneration == generation &&
- _sessionKey == _buildSessionKey(session);
- }
-
- void _clearCachedState({required bool notify}) {
- final hadCachedState =
- _contactsByUserId.isNotEmpty ||
- _contactsByNormalizedEmail.isNotEmpty ||
- _profilePictureBytesByUserId.isNotEmpty ||
- _resolvedProfilePictureUserIds.isNotEmpty;
- _contactsByUserId.clear();
- _contactsByNormalizedEmail.clear();
- _normalizedEmailByUserId.clear();
- _profilePictureBytesByUserId.clear();
- _resolvedProfilePictureUserIds.clear();
- _profilePictureLoadsByUserId.clear();
- _profilePictureFailureUntilByUserId.clear();
- _readyFuture = null;
- _contacts = null;
- _session = null;
- _sessionKey = null;
- _sessionAuthToken = null;
- _hasHydratedCache = false;
- if (notify && hadCachedState) {
- _notifyChanged();
- }
- }
-
- void _invalidateProfilePictureCache(int contactUserId) {
- _profilePictureBytesByUserId.remove(contactUserId);
- _resolvedProfilePictureUserIds.remove(contactUserId);
- _profilePictureLoadsByUserId.remove(contactUserId);
- _profilePictureFailureUntilByUserId.remove(contactUserId);
- }
-
- void _notifyChanged() {
- _changes.value += 1;
- }
}
diff --git a/mobile/packages/contacts/test/contacts_display_service_test.dart b/mobile/packages/contacts/test/contacts_display_service_test.dart
index cb7ec2d50b..7fca86a140 100644
--- a/mobile/packages/contacts/test/contacts_display_service_test.dart
+++ b/mobile/packages/contacts/test/contacts_display_service_test.dart
@@ -1,5 +1,4 @@
import 'dart:async';
-import 'dart:collection';
import 'dart:io';
import 'dart:typed_data';
@@ -59,18 +58,7 @@ void main() {
'ensureReady hydrates cached display data and notifies listeners',
() async {
rustApi.diffPages = [
- [
- const ContactRecord(
- id: 'ct_1',
- contactUserId: 7,
- email: '[email protected]',
- data: ContactData(contactUserId: 7, name: 'Alice'),
- profilePictureAttachmentId: 'att_1',
- isDeleted: false,
- createdAt: 1,
- updatedAt: 2,
- ),
- ],
+ [_contact(attachmentID: 'att_1')],
const [],
];
var notifications = 0;
@@ -80,10 +68,6 @@ void main() {
await displayService.ensureReady(session);
expect(displayService.getCachedSavedName(contactUserId: 7), 'Alice');
- expect(
- displayService.getCachedResolvedEmail(email: '[email protected]'),
- );
expect(notifications, greaterThan(0));
displayService.changes.removeListener(listener);
@@ -92,18 +76,7 @@ void main() {
test('profile picture loads are single-flight per contact', () async {
rustApi.diffPages = [
- [
- const ContactRecord(
- id: 'ct_1',
- contactUserId: 7,
- email: '[email protected]',
- data: ContactData(contactUserId: 7, name: 'Alice'),
- profilePictureAttachmentId: 'att_1',
- isDeleted: false,
- createdAt: 1,
- updatedAt: 2,
- ),
- ],
+ [_contact(attachmentID: 'att_1')],
const [],
];
rustApi.ctx.profilePictureBarrier = Completer<void>();
@@ -124,20 +97,55 @@ void main() {
expect(rustApi.ctx.getProfilePictureCalls, 1);
});
+ test('positive user id does not fall back to email', () {
+ displayService.debugHydrateContacts([_contact()], notify: false);
+
+ expect(
+ displayService.getCachedContact(
+ contactUserId: 99,
+ email: '[email protected]',
+ ),
+ isNull,
+ );
+ expect(
+ displayService.getCachedContact(email: '[email protected]')?.contactUserId,
+ 7,
+ );
+ });
+
+ test('picture changes notify only the matching contact', () {
+ displayService.debugHydrateContacts([
+ _contact(attachmentID: 'att_1'),
+ _contact(
+ userID: 8,
+ email: '[email protected]',
+ name: 'Bob',
+ attachmentID: 'att_2',
+ ),
+ ], notify: false);
+ var aliceChanges = 0;
+ var bobChanges = 0;
+ final alice = displayService.changesFor(contactUserId: 7);
+ final bob = displayService.changesFor(contactUserId: 8);
+ void onAliceChanged() => aliceChanges += 1;
+ void onBobChanged() => bobChanges += 1;
+ alice.addListener(onAliceChanged);
+ bob.addListener(onBobChanged);
+
+ displayService.debugSetProfilePictureBytes(
+ contactUserId: 7,
+ bytes: Uint8List.fromList([1]),
+ );
+
+ expect(aliceChanges, 1);
+ expect(bobChanges, 0);
+ alice.removeListener(onAliceChanged);
+ bob.removeListener(onBobChanged);
+ });
+
test('profile picture failures are briefly negative-cached', () async {
rustApi.diffPages = [
- [
- const ContactRecord(
- id: 'ct_1',
- contactUserId: 7,
- email: '[email protected]',
- data: ContactData(contactUserId: 7, name: 'Alice'),
- profilePictureAttachmentId: 'att_1',
- isDeleted: false,
- createdAt: 1,
- updatedAt: 2,
- ),
- ],
+ [_contact(attachmentID: 'att_1')],
const [],
];
rustApi.ctx.profilePictureError = StateError('boom');
@@ -148,7 +156,6 @@ void main() {
await displayService.getProfilePictureBytes(contactUserId: 7),
isNull,
);
- expect(rustApi.ctx.getProfilePictureCalls, 1);
expect(
await displayService.getProfilePictureBytes(contactUserId: 7),
isNull,
@@ -160,18 +167,7 @@ void main() {
'stale in-flight profile picture load does not overwrite newer contact',
() async {
rustApi.diffPages = [
- [
- const ContactRecord(
- id: 'ct_1',
- contactUserId: 7,
- email: '[email protected]',
- data: ContactData(contactUserId: 7, name: 'Alice'),
- profilePictureAttachmentId: 'att_old',
- isDeleted: false,
- createdAt: 1,
- updatedAt: 2,
- ),
- ],
+ [_contact(attachmentID: 'att_old')],
const [],
];
rustApi.ctx.profilePictureBarrier = Completer<void>();
@@ -186,24 +182,21 @@ void main() {
final pending = displayService.getProfilePictureBytes(contactUserId: 7);
displayService.debugHydrateContacts([
- const ContactRecord(
- id: 'ct_1',
- contactUserId: 7,
- email: '[email protected]',
- data: ContactData(contactUserId: 7, name: 'Alice'),
- profilePictureAttachmentId: 'att_new',
- isDeleted: false,
- createdAt: 1,
- updatedAt: 3,
- ),
+ _contact(attachmentID: 'att_new', updatedAt: 3),
], notify: false);
+ final newPicture = Uint8List.fromList([4, 5, 6]);
+ displayService.debugSetProfilePictureBytes(
+ contactUserId: 7,
+ bytes: newPicture,
+ notify: false,
+ );
rustApi.ctx.profilePictureBarrier!.complete();
- expect(await pending, isNull);
+ expect(await pending, newPicture);
expect(
displayService.getCachedProfilePictureBytes(contactUserId: 7),
- isNull,
+ newPicture,
);
},
);
@@ -215,18 +208,7 @@ void main() {
rustApi.ctx.diffBarrier = diffBarrier;
rustApi.ctx.diffStarted = Completer<void>();
rustApi.diffPages = [
- [
- const ContactRecord(
- id: 'ct_old',
- contactUserId: 7,
- email: '[email protected]',
- data: ContactData(contactUserId: 7, name: 'Alice'),
- profilePictureAttachmentId: null,
- isDeleted: false,
- createdAt: 1,
- updatedAt: 2,
- ),
- ],
+ [_contact(id: 'ct_old')],
const [],
];
@@ -247,52 +229,9 @@ void main() {
await oldEnsureReady;
expect(displayService.getCachedSavedName(contactUserId: 7), isNull);
- expect(
- displayService.getCachedResolvedEmail(email: '[email protected]'),
- isNull,
- );
},
);
- test('session switch creates a fresh contacts service instance', () async {
- final rustApiForFirstSession = FakeContactsRustApi();
- final rustApiForSecondSession = FakeContactsRustApi();
- final services = Queue<ContactsService>.of([
- ContactsService(
- preferences: preferences,
- database: ContactsDatabase(directoryResolver: () async => tempDir),
- rustApi: rustApiForFirstSession,
- ),
- ContactsService(
- preferences: preferences,
- database: ContactsDatabase(directoryResolver: () async => tempDir),
- rustApi: rustApiForSecondSession,
- ),
- ]);
-
- await displayService.debugReset(clearLocalState: false);
- displayService.init(
- preferences: preferences,
- contactsServiceFactory: () => services.removeFirst(),
- );
-
- rustApiForFirstSession.diffPages = [const []];
- await displayService.ensureReady(session);
-
- final nextSession = ContactsSession(
- baseUrl: session.baseUrl,
- authToken: 'token-2',
- userId: 2,
- accountKey: Uint8List.fromList([9, 9, 9]),
- );
- rustApiForSecondSession.diffPages = [const []];
- await displayService.ensureReady(nextSession);
-
- expect(rustApiForFirstSession.openCalls, 1);
- expect(rustApiForSecondSession.openCalls, 1);
- expect(services, isEmpty);
- });
-
test(
'ensureReady keeps hydrated cache and retries later when sync fails',
() async {
@@ -310,21 +249,37 @@ void main() {
rustApi.ctx.diffError = null;
rustApi.diffPages = [const []];
- await expectLater(displayService.ensureReady(session), completes);
+ await displayService.ensureReady(session);
expect(rustApi.ctx.getDiffCalls, 2);
},
);
}
+ContactRecord _contact({
+ String id = 'ct_1',
+ int userID = 7,
+ String email = '[email protected]',
+ String name = 'Alice',
+ String? attachmentID,
+ int updatedAt = 2,
+}) => ContactRecord(
+ id: id,
+ contactUserId: userID,
+ email: email,
+ data: ContactData(contactUserId: userID, name: name),
+ profilePictureAttachmentId: attachmentID,
+ isDeleted: false,
+ createdAt: 1,
+ updatedAt: updatedAt,
+);
+
class FakeContactsRustApi implements ContactsRustApi {
FakeContactsRustContext ctx = FakeContactsRustContext();
FakeContactsRustContext? nextOpenContext;
List<List<ContactRecord>> diffPages = const [];
- int openCalls = 0;
@override
Future<OpenContactsContextResult> open(OpenContactsContextInput input) async {
- openCalls += 1;
final context = nextOpenContext ?? ctx;
nextOpenContext = null;
context.userIdValue = input.userId;
@@ -342,13 +297,9 @@ class FakeContactsRustApi implements ContactsRustApi {
class FakeContactsRustContext implements ContactsRustContext {
int userIdValue = 0;
- final Map<String, ContactRecord> records = {};
- final Map<String, Uint8List> attachments = {};
final Map<String, Uint8List> profilePictureBytesByContactId = {};
List<List<ContactRecord>> diffPages = [];
- int getAttachmentCalls = 0;
int getProfilePictureCalls = 0;
- String nextAttachmentId = 'att_profile';
Completer<void>? profilePictureBarrier;
Completer<void>? diffBarrier;
Completer<void>? diffStarted;
@@ -358,7 +309,7 @@ class FakeContactsRustContext implements ContactsRustContext {
@override
Future<ContactRecord> createContact(ContactData data) async {
- final record = ContactRecord(
+ return ContactRecord(
id: 'ct_created',
contactUserId: data.contactUserId,
@@ -368,8 +319,6 @@ class FakeContactsRustContext implements ContactsRustContext {
createdAt: 1,
updatedAt: 1,
);
- records[record.id] = record;
- return record;
}
@override
@@ -379,56 +328,6 @@ class FakeContactsRustContext implements ContactsRustContext {
header: 'enc-header',
);
- @override
- Future<void> deleteContact(String contactId) async {
- final existing = records[contactId];
- if (existing != null) {
- records[contactId] = ContactRecord(
- id: existing.id,
- contactUserId: existing.contactUserId,
- email: existing.email,
- data: null,
- profilePictureAttachmentId: null,
- isDeleted: true,
- createdAt: existing.createdAt,
- updatedAt: existing.updatedAt + 1,
- );
- }
- }
-
- @override
- Future<ContactRecord> deleteAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- ) async {
- final existing = records[contactId]!;
- final updated = ContactRecord(
- id: existing.id,
- contactUserId: existing.contactUserId,
- email: existing.email,
- data: existing.data,
- profilePictureAttachmentId: null,
- isDeleted: existing.isDeleted,
- createdAt: existing.createdAt,
- updatedAt: existing.updatedAt + 1,
- );
- records[contactId] = updated;
- final previousAttachmentId = existing.profilePictureAttachmentId;
- if (previousAttachmentId != null) {
- attachments.remove(previousAttachmentId);
- }
- return updated;
- }
-
- @override
- Future<ContactRecord> deleteProfilePicture(String contactId) {
- return deleteAttachment(contactId, ContactAttachmentType.profilePicture);
- }
-
- @override
- Future<ContactRecord> getContact(String contactId) async =>
- records[contactId]!;
-
@override
Future<List<ContactRecord>> getDiff(int sinceTime, int limit) async {
getDiffCalls += 1;
@@ -447,21 +346,9 @@ class FakeContactsRustContext implements ContactsRustContext {
}
final first = diffPages.first;
diffPages = diffPages.sublist(1);
- for (final record in first) {
- records[record.id] = record;
- }
return first;
}
- @override
- Future<Uint8List> getAttachment(
- ContactAttachmentType attachmentType,
- String attachmentId,
- ) async {
- getAttachmentCalls += 1;
- return attachments[attachmentId]!;
- }
-
@override
Future<Uint8List> getProfilePicture(String contactId) async {
getProfilePictureCalls += 1;
@@ -476,62 +363,11 @@ class FakeContactsRustContext implements ContactsRustContext {
return profilePictureBytesByContactId[contactId]!;
}
- @override
- Future<ContactRecord> setAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- Uint8List attachmentBytes,
- ) async {
- final existing = records[contactId]!;
- final updated = ContactRecord(
- id: existing.id,
- contactUserId: existing.contactUserId,
- email: existing.email,
- data: existing.data,
- profilePictureAttachmentId: nextAttachmentId,
- isDeleted: existing.isDeleted,
- createdAt: existing.createdAt,
- updatedAt: existing.updatedAt + 1,
- );
- records[contactId] = updated;
- attachments[nextAttachmentId] = attachmentBytes;
- return updated;
- }
-
- @override
- Future<ContactRecord> setProfilePicture(
- String contactId,
- Uint8List profilePicture,
- ) {
- return setAttachment(
- contactId,
- ContactAttachmentType.profilePicture,
- profilePicture,
- );
- }
-
@override
Future<void> updateAuthToken(String authToken) async {}
@override
- Future<ContactRecord> updateContact(
- String contactId,
- ContactData data,
- ) async {
- final existing = records[contactId]!;
- final updated = ContactRecord(
- id: existing.id,
- contactUserId: existing.contactUserId,
- email: existing.email,
- data: data,
- profilePictureAttachmentId: existing.profilePictureAttachmentId,
- isDeleted: existing.isDeleted,
- createdAt: existing.createdAt,
- updatedAt: existing.updatedAt + 1,
- );
- records[contactId] = updated;
- return updated;
- }
+ dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
@override
int userId() => userIdValue;
diff --git a/mobile/packages/legacy/lib/pages/emergency_page.dart b/mobile/packages/legacy/lib/pages/emergency_page.dart
index 00bb833a54..a63fda4c72 100644
--- a/mobile/packages/legacy/lib/pages/emergency_page.dart
+++ b/mobile/packages/legacy/lib/pages/emergency_page.dart
@@ -49,14 +49,12 @@ class EmergencyPage extends StatefulWidget {
}
class _EmergencyPageState extends State<EmergencyPage> {
- late int currentUserID;
EmergencyInfo? info;
List<LegacyKit> legacyKits = [];
@override
void initState() {
super.initState();
- currentUserID = widget.config.getUserID()!;
Future.delayed(const Duration(seconds: 0), () async {
unawaited(_fetchData());
});
@@ -182,7 +180,6 @@ class _EmergencyPageState extends State<EmergencyPage> {
leadingIconWidget: UserAvatarWidget(
recoverSession.emergencyContact,
type: AvatarType.mini,
- currentUserID: currentUserID,
config: widget.config,
),
menuItemColor: colorScheme.fillFaint,
@@ -254,7 +251,6 @@ class _EmergencyPageState extends State<EmergencyPage> {
child: UserAvatarWidget(
contact.emergencyContact,
type: AvatarType.small,
- currentUserID: currentUserID,
config: widget.config,
),
),
@@ -372,7 +368,6 @@ class _EmergencyPageState extends State<EmergencyPage> {
child: UserAvatarWidget(
currentUser.user,
type: AvatarType.small,
- currentUserID: currentUserID,
config: widget.config,
),
),
diff --git a/mobile/packages/legacy/lib/pages/select_contact_page.dart b/mobile/packages/legacy/lib/pages/select_contact_page.dart
index 6c3c364340..64a215f5a1 100644
--- a/mobile/packages/legacy/lib/pages/select_contact_page.dart
+++ b/mobile/packages/legacy/lib/pages/select_contact_page.dart
@@ -77,7 +77,7 @@ class _AddContactSheetState extends State<AddContactSheet> {
builder: (context, _, _) {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
- final List<User> suggestedUsers = _getSuggestedUser();
+ final List<UserSuggestion> suggestedUsers = _getSuggestedUser();
final bool canAdd = selectedEmail.isNotEmpty || _emailIsValid;
return SingleChildScrollView(
@@ -184,7 +184,7 @@ class _AddContactSheetState extends State<AddContactSheet> {
}
Widget _buildExistingContactsSection(
- List<User> suggestedUsers,
+ List<UserSuggestion> suggestedUsers,
EnteColorScheme colorScheme,
EnteTextTheme textTheme,
) {
@@ -226,12 +226,10 @@ class _AddContactSheetState extends State<AddContactSheet> {
),
),
leadingIconSize: 24.0,
- leadingIconWidget: UserAvatarWidget(
+ leadingIconWidget: UserAvatarWidget.suggestion(
user,
type: AvatarType.mini,
- currentUserID: widget.config.getUserID()!,
config: widget.config,
- thumbnailView: false,
),
menuItemColor: colorScheme.fillFaint,
pressedColor: colorScheme.fillFaintPressed,
@@ -401,29 +399,25 @@ class _AddContactSheetState extends State<AddContactSheet> {
);
}
- List<User> _getSuggestedUser() {
- final List<User> suggestedUsers = [];
- final Set<String> existingEmails = {};
+ List<UserSuggestion> _getSuggestedUser() {
+ final suggestedUsers = <UserSuggestion>[];
+ final existingEmails = <String>{widget.config.getEmail() ?? ""};
- existingEmails.add(widget.config.getEmail() ?? "");
+ void add(String email, {int? userID}) {
+ if (email.isNotEmpty && existingEmails.add(email)) {
+ suggestedUsers.add(UserSuggestion(email, userID: userID));
+ }
+ }
- // Get suggested users from othersEmergencyContact (people who added you)
+ // People who added you as their emergency contact
for (final contact in widget.emergencyInfo.othersEmergencyContact) {
- if (!existingEmails.contains(contact.user.email)) {
- existingEmails.add(contact.user.email);
- suggestedUsers.add(contact.user);
- }
+ add(contact.user.email, userID: contact.user.id);
}
- final cachedUserDetails = UserService.instance.getCachedUserDetails();
- if (cachedUserDetails != null &&
- (cachedUserDetails.familyData?.members?.isNotEmpty ?? false)) {
- for (final member in cachedUserDetails.familyData!.members!) {
- if (!existingEmails.contains(member.email)) {
- existingEmails.add(member.email);
- suggestedUsers.add(User(email: member.email));
- }
- }
+ final familyMembers =
+ UserService.instance.getCachedUserDetails()?.familyData?.members ?? [];
+ for (final member in familyMembers) {
+ add(member.email, userID: member.userID);
}
// Filter by search text
diff --git a/mobile/packages/sharing/lib/extensions/user_extension.dart b/mobile/packages/sharing/lib/extensions/user_extension.dart
index b76762b016..1d1e218f72 100644
--- a/mobile/packages/sharing/lib/extensions/user_extension.dart
+++ b/mobile/packages/sharing/lib/extensions/user_extension.dart
@@ -1,49 +1,60 @@
import 'package:ente_contacts/contacts.dart';
import "package:ente_sharing/models/user.dart";
-extension UserExtension on User {
- //Some initial users have name in name field.
- String? get displayName =>
- // ignore: deprecated_member_use_from_same_package, deprecated_member_use
- ((name?.isEmpty ?? true) ? null : name);
+typedef ResolvedUserIdentity = ({String displayName, String email});
+extension UserExtension on User {
String get nameOrEmail {
return email.substring(0, email.indexOf("@"));
}
- String get resolvedDisplayName {
- final savedName = ContactsDisplayService.instance.getCachedSavedName(
- contactUserId: id,
- email: email,
- );
- if (savedName != null) {
- return savedName;
- }
- final currentDisplayName = displayName?.trim();
- if (currentDisplayName != null && currentDisplayName.isNotEmpty) {
- return currentDisplayName;
- }
- return resolvedEmail;
- }
+ String get resolvedDisplayName => resolvedUserDisplayName(id, email);
- String get resolvedEmail {
- final savedEmail = ContactsDisplayService.instance.getCachedResolvedEmail(
- contactUserId: id,
- email: email,
- );
- if (savedEmail != null) {
- return savedEmail;
- }
- return email;
- }
+ String get resolvedEmail => resolvedUserEmail(id, email);
- bool matchesResolvedNameOrEmail(String query) {
- final normalizedQuery = query.trim().toLowerCase();
- if (normalizedQuery.isEmpty) {
- return true;
- }
- return resolvedDisplayName.toLowerCase().contains(normalizedQuery) ||
- resolvedEmail.toLowerCase().contains(normalizedQuery) ||
- email.toLowerCase().contains(normalizedQuery);
- }
+ bool matchesResolvedNameOrEmail(String query) =>
+ _matchesResolvedNameOrEmail(id, email, query);
+}
+
+extension UserSuggestionExtension on UserSuggestion {
+ String get resolvedDisplayName => resolvedUserDisplayName(userID, email);
+
+ String get resolvedEmail => resolvedUserEmail(userID, email);
+
+ bool matchesResolvedNameOrEmail(String query) =>
+ _matchesResolvedNameOrEmail(userID, email, query);
+}
+
+String resolvedUserDisplayName(int? userID, String email) {
+ return resolveUserIdentity(userID, email).displayName;
+}
+
+String resolvedUserEmail(int? userID, String email) {
+ return resolveUserIdentity(userID, email).email;
+}
+
+ResolvedUserIdentity resolveUserIdentity(int? userID, String email) {
+ final contact = ContactsDisplayService.instance.getCachedContact(
+ contactUserId: userID,
+ email: email,
+ );
+ final resolvedEmail = _trimToNull(contact?.email) ?? email;
+ return (
+ displayName: _trimToNull(contact?.data?.name) ?? resolvedEmail,
+ email: resolvedEmail,
+ );
+}
+
+bool _matchesResolvedNameOrEmail(int? userID, String email, String query) {
+ final normalizedQuery = query.trim().toLowerCase();
+ if (normalizedQuery.isEmpty) return true;
+ final identity = resolveUserIdentity(userID, email);
+ return identity.displayName.toLowerCase().contains(normalizedQuery) ||
+ identity.email.toLowerCase().contains(normalizedQuery) ||
+ email.toLowerCase().contains(normalizedQuery);
+}
+
+String? _trimToNull(String? value) {
+ final trimmed = value?.trim();
+ return trimmed == null || trimmed.isEmpty ? null : trimmed;
}
diff --git a/mobile/packages/sharing/lib/models/user.dart b/mobile/packages/sharing/lib/models/user.dart
index 02d9fdfb99..5f198d4b7c 100644
--- a/mobile/packages/sharing/lib/models/user.dart
+++ b/mobile/packages/sharing/lib/models/user.dart
@@ -1,16 +1,11 @@
import "dart:convert";
class User {
- int? id;
+ final int id;
String email;
- @Deprecated(
- "Use displayName() extension method instead. Note: Some early users have"
- " value in name field.",
- )
- String? name;
String? role;
- User({this.id, required this.email, this.name, this.role});
+ User({required this.id, required this.email, this.role});
bool get isViewer => role == null || role?.toUpperCase() == 'VIEWER';
@@ -20,15 +15,13 @@ class User {
bool get isAdmin => role != null && role?.toUpperCase() == 'ADMIN';
Map<String, dynamic> toMap() {
- // ignore: deprecated_member_use_from_same_package
- return {'id': id, 'email': email, 'name': name, "role": role};
+ return {'id': id, 'email': email, "role": role};
}
static User fromMap(Map<String, dynamic> map) {
return User(
- id: map['id'],
- email: map['email'],
- name: map['name'],
+ id: map['id'] as int,
+ email: map['email'] as String,
role: map['role'] ?? 'VIEWER',
);
}
@@ -37,3 +30,13 @@ class User {
factory User.fromJson(String source) => User.fromMap(json.decode(source));
}
+
+class UserSuggestion {
+ const UserSuggestion(this.email, {this.userID});
+
+ factory UserSuggestion.fromUser(User user) =>
+ UserSuggestion(user.email, userID: user.id);
+
+ final int? userID;
+ final String email;
+}
diff --git a/mobile/packages/sharing/lib/resolved_user_builder.dart b/mobile/packages/sharing/lib/resolved_user_builder.dart
index d3734e6d90..4dd6e7124b 100644
--- a/mobile/packages/sharing/lib/resolved_user_builder.dart
+++ b/mobile/packages/sharing/lib/resolved_user_builder.dart
@@ -23,7 +23,10 @@ class ResolvedUserBuilder extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<int>(
- valueListenable: ContactsDisplayService.instance.changes,
+ valueListenable: ContactsDisplayService.instance.changesFor(
+ contactUserId: user.id,
+ email: user.email,
+ ),
builder: (context, _, _) =>
builder(context, user.resolvedDisplayName, user.email),
);
diff --git a/mobile/packages/sharing/lib/user_avator_widget.dart b/mobile/packages/sharing/lib/user_avator_widget.dart
index 603c9149bc..b86a72da92 100644
--- a/mobile/packages/sharing/lib/user_avator_widget.dart
+++ b/mobile/packages/sharing/lib/user_avator_widget.dart
@@ -1,4 +1,3 @@
-import 'dart:async';
import 'dart:typed_data';
import 'package:ente_configuration/base_configuration.dart';
@@ -11,81 +10,78 @@ import 'package:tuple/tuple.dart';
enum AvatarType { small, mini, tiny, extra }
+bool _usesBlackAvatar(int? userID, String email, BaseConfiguration config) {
+ return (userID != null &&
+ (userID < 0 || (userID > 0 && userID == config.getUserID()))) ||
+ email == config.getEmail();
+}
+
+void _preloadProfilePicture(int? userID, String email) {
+ ContactsDisplayService.instance.preloadProfilePicture(
+ contactUserId: userID,
+ email: email,
+ );
+}
+
class UserAvatarWidget extends StatefulWidget {
- final User user;
+ final int? userID;
+ final String email;
final AvatarType type;
- final int currentUserID;
- final bool thumbnailView;
final BaseConfiguration config;
- const UserAvatarWidget(
- this.user, {
+ UserAvatarWidget(
+ User user, {
+ super.key,
+ this.type = AvatarType.mini,
+ required this.config,
+ }) : userID = user.id,
+ email = user.email;
+
+ UserAvatarWidget.suggestion(
+ UserSuggestion suggestion, {
super.key,
- this.currentUserID = -1,
this.type = AvatarType.mini,
- this.thumbnailView = false,
required this.config,
- });
+ }) : userID = suggestion.userID,
+ email = suggestion.email;
@override
State<UserAvatarWidget> createState() => _UserAvatarWidgetState();
-
- static const strokeWidth = 1.0;
}
class _UserAvatarWidgetState extends State<UserAvatarWidget> {
@override
void initState() {
super.initState();
- _preloadProfilePictureIfPossible();
+ _preloadProfilePicture(widget.userID, widget.email);
}
@override
void didUpdateWidget(covariant UserAvatarWidget oldWidget) {
super.didUpdateWidget(oldWidget);
- if (oldWidget.user.id != widget.user.id ||
- oldWidget.user.email != widget.user.email) {
- _preloadProfilePictureIfPossible();
- }
- }
-
- void _preloadProfilePictureIfPossible() {
- final displayService = ContactsDisplayService.instance;
- if (displayService.hasResolvedProfilePicture(
- contactUserId: widget.user.id,
- email: widget.user.email,
- )) {
- return;
- }
- if (displayService.getCachedContact(
- contactUserId: widget.user.id,
- email: widget.user.email,
- ) ==
- null) {
- return;
+ if (oldWidget.userID != widget.userID || oldWidget.email != widget.email) {
+ _preloadProfilePicture(widget.userID, widget.email);
}
- unawaited(
- displayService.getProfilePictureBytes(
- contactUserId: widget.user.id,
- email: widget.user.email,
- ),
- );
}
@override
Widget build(BuildContext context) {
final double size = getAvatarSize(widget.type);
return ValueListenableBuilder<int>(
- valueListenable: ContactsDisplayService.instance.changes,
+ valueListenable: ContactsDisplayService.instance.changesFor(
+ contactUserId: widget.userID,
+ email: widget.email,
+ ),
builder: (context, _, _) {
- _preloadProfilePictureIfPossible();
+ _preloadProfilePicture(widget.userID, widget.email);
return SizedBox(
height: size,
width: size,
child: _CircularAvatar(
- user: widget.user,
- type: widget.type,
- config: widget.config,
+ widget.userID,
+ widget.email,
+ widget.type,
+ widget.config,
),
);
},
@@ -94,37 +90,32 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
}
class _CircularAvatar extends StatelessWidget {
- final User user;
+ final int? userID;
+ final String email;
final AvatarType type;
final BaseConfiguration config;
- const _CircularAvatar({
- required this.user,
- required this.type,
- required this.config,
- });
+ const _CircularAvatar(this.userID, this.email, this.type, this.config);
@override
Widget build(BuildContext context) {
final profilePictureBytes = ContactsDisplayService.instance
- .getCachedProfilePictureBytes(
- contactUserId: user.id,
- email: user.email,
- );
+ .getCachedProfilePictureBytes(contactUserId: userID, email: email);
final avatarStyle = _getAvatarStyle(context, type);
final double size = avatarStyle.item1;
if (profilePictureBytes != null) {
- return _CirclePhotoAvatar(bytes: profilePictureBytes, size: size);
+ return _CirclePhotoAvatar(profilePictureBytes, size);
}
final colorScheme = getEnteColorScheme(context);
- final displayLabel = user.resolvedDisplayName;
+ final identity = resolveUserIdentity(userID, email);
+ final displayLabel = identity.displayName;
final displayChar = displayLabel.isEmpty
? " "
: displayLabel.substring(0, 1);
- final avatarSeed = user.resolvedEmail;
+ final avatarSeed = identity.email;
Color decorationColor;
- if ((user.id != null && user.id! < 0) || user.email == config.getEmail()) {
+ if (_usesBlackAvatar(userID, email, config)) {
decorationColor = Colors.black;
} else {
decorationColor =
@@ -184,55 +175,30 @@ class FirstLetterUserAvatar extends StatefulWidget {
}
class _FirstLetterUserAvatarState extends State<FirstLetterUserAvatar> {
- late String? currentUserEmail;
- late User user;
-
@override
void initState() {
super.initState();
- user = widget.user;
- currentUserEmail = widget.config.getEmail();
- _preloadProfilePictureIfPossible();
+ _preloadProfilePicture(widget.user.id, widget.user.email);
}
@override
void didUpdateWidget(covariant FirstLetterUserAvatar oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.user != widget.user) {
- user = widget.user;
- _preloadProfilePictureIfPossible();
- }
- }
-
- void _preloadProfilePictureIfPossible() {
- final displayService = ContactsDisplayService.instance;
- if (displayService.hasResolvedProfilePicture(
- contactUserId: user.id,
- email: user.email,
- )) {
- return;
+ _preloadProfilePicture(widget.user.id, widget.user.email);
}
- if (displayService.getCachedContact(
- contactUserId: user.id,
- email: user.email,
- ) ==
- null) {
- return;
- }
- unawaited(
- displayService.getProfilePictureBytes(
- contactUserId: user.id,
- email: user.email,
- ),
- );
}
@override
Widget build(BuildContext context) {
+ final user = widget.user;
return ValueListenableBuilder<int>(
- valueListenable: ContactsDisplayService.instance.changes,
+ valueListenable: ContactsDisplayService.instance.changesFor(
+ contactUserId: user.id,
+ email: user.email,
+ ),
builder: (context, _, _) {
- _preloadProfilePictureIfPossible();
+ _preloadProfilePicture(user.id, user.email);
final profilePictureBytes = ContactsDisplayService.instance
.getCachedProfilePictureBytes(
contactUserId: user.id,
@@ -247,14 +213,14 @@ class _FirstLetterUserAvatarState extends State<FirstLetterUserAvatar> {
}
final colorScheme = getEnteColorScheme(context);
- final displayLabel = user.resolvedDisplayName;
+ final identity = resolveUserIdentity(user.id, user.email);
+ final displayLabel = identity.displayName;
final displayChar = displayLabel.isEmpty
? " "
: displayLabel.substring(0, 1);
- final avatarSeed = user.resolvedEmail;
+ final avatarSeed = identity.email;
Color decorationColor;
- if ((user.id != null && user.id! < 0) ||
- user.email == currentUserEmail) {
+ if (_usesBlackAvatar(user.id, user.email, widget.config)) {
decorationColor = Colors.black;
} else {
decorationColor =
@@ -283,7 +249,7 @@ class _CirclePhotoAvatar extends StatelessWidget {
final Uint8List bytes;
final double size;
- const _CirclePhotoAvatar({required this.bytes, required this.size});
+ const _CirclePhotoAvatar(this.bytes, this.size);
@override
Widget build(BuildContext context) {
diff --git a/mobile/packages/sharing/test/user_avator_widget_test.dart b/mobile/packages/sharing/test/user_avator_widget_test.dart
index ab579a3b67..d7d6cbb6b8 100644
--- a/mobile/packages/sharing/test/user_avator_widget_test.dart
+++ b/mobile/packages/sharing/test/user_avator_widget_test.dart
@@ -1,3 +1,4 @@
+import 'dart:convert';
import 'dart:typed_data';
import 'package:ente_configuration/base_configuration.dart';
@@ -9,8 +10,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
- TestWidgetsFlutterBinding.ensureInitialized();
-
late ContactsDisplayService displayService;
setUp(() async {
@@ -112,76 +111,7 @@ class _TestConfiguration extends BaseConfiguration {
int? getUserID() => 1;
}
-Uint8List _validPngBytes() {
- return Uint8List.fromList(const [
- 137,
- 80,
- 78,
- 71,
- 13,
- 10,
- 26,
- 10,
- 0,
- 0,
- 0,
- 13,
- 73,
- 72,
- 68,
- 82,
- 0,
- 0,
- 0,
- 1,
- 0,
- 0,
- 0,
- 1,
- 8,
- 6,
- 0,
- 0,
- 0,
- 31,
- 21,
- 196,
- 137,
- 0,
- 0,
- 0,
- 13,
- 73,
- 68,
- 65,
- 84,
- 120,
- 156,
- 99,
- 248,
- 255,
- 255,
- 63,
- 0,
- 5,
- 254,
- 2,
- 254,
- 167,
- 53,
- 129,
- 132,
- 0,
- 0,
- 0,
- 0,
- 73,
- 69,
- 78,
- 68,
- 174,
- 66,
- 96,
- 130,
- ]);
-}
+Uint8List _validPngBytes() => base64Decode(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4//8/'
+ 'AAX+Av6nNYGEAAAAAElFTkSuQmCC',
+);