π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Sync Library Sharing state through user entities
Neeraj Guptaaa319ef2b9af
diff --git a/mobile/apps/photos/lib/gateways/entity/entity_gateway.dart b/mobile/apps/photos/lib/gateways/entity/entity_gateway.dartindex c42419651f..fe76c93b40 100644--- a/mobile/apps/photos/lib/gateways/entity/entity_gateway.dart+++ b/mobile/apps/photos/lib/gateways/entity/entity_gateway.dart@@ -59,8 +59,9 @@ class EntityGateway {EntityType type,String id,String encryptedData,- String header,- ) async {+ String header, {+ int? expectedUpdatedAt,+ }) async {final response = await _enteDio.put("/user-entity/entity",data: {@@ -68,6 +69,7 @@ class EntityGateway {"encryptedData": encryptedData,"header": header,"type": type.name,+ "expectedUpdatedAt": ?expectedUpdatedAt,},);return EntityData.fromMap(response.data);diff --git a/mobile/apps/photos/lib/gateways/entity/models/type.dart b/mobile/apps/photos/lib/gateways/entity/models/type.dartindex 0fbb8aef89..c6c3b448a7 100644--- a/mobile/apps/photos/lib/gateways/entity/models/type.dart+++ b/mobile/apps/photos/lib/gateways/entity/models/type.dart@@ -4,7 +4,8 @@ enum EntityType {cgroup,unknown,smartAlbum,- memory;+ memory,+ libraryShare;bool get isZipped {switch (this) {@@ -28,6 +29,8 @@ enum EntityType {return "smart_album";case EntityType.memory:return "memory";+ case EntityType.libraryShare:+ return "library_share";case EntityType.unknown:return "unknown";}diff --git a/mobile/apps/photos/lib/service_locator.dart b/mobile/apps/photos/lib/service_locator.dartindex 4f92744e4a..37a5a17141 100644--- a/mobile/apps/photos/lib/service_locator.dart+++ b/mobile/apps/photos/lib/service_locator.dart@@ -31,8 +31,8 @@ import "package:photos/services/backup_preference_service.dart";import "package:photos/services/collections_service.dart";import "package:photos/services/entity_service.dart";import "package:photos/services/filedata/filedata_service.dart";-import "package:photos/services/library_sharing_local_store.dart";import "package:photos/services/library_sharing_service.dart";+import "package:photos/services/library_sharing_store.dart";import "package:photos/services/location_service.dart";import "package:photos/services/machine_learning/compute_controller.dart";import "package:photos/services/magic_cache_service.dart";@@ -294,7 +294,7 @@ CollectionsService get collectionsService {LibrarySharingService? _librarySharingService;LibrarySharingService get librarySharingService {_librarySharingService ??= LibrarySharingService(- localStore: LibrarySharingLocalStore(ServiceLocator.instance.prefs),+ store: LibrarySharingEntityStore(entityService),);return _librarySharingService!;}diff --git a/mobile/apps/photos/lib/services/entity_service.dart b/mobile/apps/photos/lib/services/entity_service.dartindex 41e801680d..82ff20fdb6 100644--- a/mobile/apps/photos/lib/services/entity_service.dart+++ b/mobile/apps/photos/lib/services/entity_service.dart@@ -61,6 +61,7 @@ class EntityService {Map<String, dynamic> jsonMap, {String? id,bool addWithCustomID = false,+ int? expectedUpdatedAt,}) async {final String plainText = jsonEncode(jsonMap);final key = await getOrCreateEntityKey(type);@@ -86,7 +87,13 @@ class EntityService {final EntityData data = id == null || addWithCustomID? await _gateway.createEntity(type, id, encryptedData, header)- : await _gateway.updateEntity(type, id, encryptedData, header);+ : await _gateway.updateEntity(+ type,+ id,+ encryptedData,+ header,+ expectedUpdatedAt: expectedUpdatedAt,+ );final localData = LocalEntityData(id: data.id,type: type,diff --git a/mobile/apps/photos/lib/services/library_sharing_local_store.dart b/mobile/apps/photos/lib/services/library_sharing_local_store.dartdeleted file mode 100644index 03e577486f..0000000000--- a/mobile/apps/photos/lib/services/library_sharing_local_store.dart+++ /dev/null@@ -1,143 +0,0 @@-import 'dart:convert';--import 'package:logging/logging.dart';-import 'package:photos/models/collection/collection.dart';-import 'package:shared_preferences/shared_preferences.dart';--const _keyPrefix = 'library_sharing_local_';--class LibrarySharingLocalConfig {- const LibrarySharingLocalConfig({- required this.recipientUserID,- required this.enabled,- required this.defaultRole,- this.addedAutomatically = const {},- this.unsharedBefore = const {},- this.hidden = const {},- });-- final int recipientUserID;- final bool enabled;- final CollectionParticipantRole defaultRole;- final Set<int> addedAutomatically;- final Set<int> unsharedBefore;- final Set<int> hidden;-- LibrarySharingLocalConfig copyWith({- bool? enabled,- CollectionParticipantRole? defaultRole,- Set<int>? addedAutomatically,- Set<int>? unsharedBefore,- Set<int>? hidden,- }) => LibrarySharingLocalConfig(- recipientUserID: recipientUserID,- enabled: enabled ?? this.enabled,- defaultRole: defaultRole ?? this.defaultRole,- addedAutomatically: addedAutomatically ?? this.addedAutomatically,- unsharedBefore: unsharedBefore ?? this.unsharedBefore,- hidden: hidden ?? this.hidden,- );-- Map<String, dynamic> toJson() => {- 'recipientUserID': recipientUserID,- 'enabled': enabled,- 'defaultRole': defaultRole.name,- 'addedAutomatically': addedAutomatically.toList()..sort(),- 'unsharedBefore': unsharedBefore.toList()..sort(),- 'hidden': hidden.toList()..sort(),- };-- factory LibrarySharingLocalConfig.fromJson(Map<String, dynamic> json) {- final role = CollectionParticipantRoleExtn.fromString(- json['defaultRole'] as String?,- );- return LibrarySharingLocalConfig(- recipientUserID: json['recipientUserID'] as int,- enabled: json['enabled'] as bool? ?? false,- defaultRole: switch (role) {- CollectionParticipantRole.viewer ||- CollectionParticipantRole.collaborator ||- CollectionParticipantRole.admin => role,- _ => CollectionParticipantRole.viewer,- },- addedAutomatically: _intSet(json['addedAutomatically']),- unsharedBefore: _intSet(json['unsharedBefore']),- hidden: _intSet(json['hidden']),- );- }-}--class LibrarySharingLocalStore {- LibrarySharingLocalStore([SharedPreferences? preferences])- : _preferences = preferences;-- final SharedPreferences? _preferences;- final _logger = Logger('LibrarySharingLocalStore');-- Future<LibrarySharingLocalConfig?> read(- int ownerUserID,- int recipientUserID,- ) async {- final preferences = _preferences ?? await SharedPreferences.getInstance();- final key = _key(ownerUserID, recipientUserID);- final encoded = preferences.getString(key);- if (encoded == null) {- return null;- }- try {- final config = LibrarySharingLocalConfig.fromJson(- Map<String, dynamic>.from(jsonDecode(encoded) as Map),- );- if (config.recipientUserID != recipientUserID) {- throw const FormatException('Recipient does not match storage key');- }- return config;- } catch (error, stackTrace) {- _logger.warning(- 'Discarding invalid local library sharing state',- error,- stackTrace,- );- await preferences.remove(key);- return null;- }- }-- Future<List<LibrarySharingLocalConfig>> readAll(int ownerUserID) async {- final preferences = _preferences ?? await SharedPreferences.getInstance();- final prefix = '$_keyPrefix${ownerUserID}_';- final configs = <LibrarySharingLocalConfig>[];- for (final key in preferences.getKeys().where(- (key) => key.startsWith(prefix),- )) {- final recipientUserID = int.tryParse(key.substring(prefix.length));- if (recipientUserID == null) {- continue;- }- final config = await read(ownerUserID, recipientUserID);- if (config != null) {- configs.add(config);- }- }- return configs;- }-- Future<void> write(int ownerUserID, LibrarySharingLocalConfig config) async {- final preferences = _preferences ?? await SharedPreferences.getInstance();- final key = _key(ownerUserID, config.recipientUserID);- final encoded = jsonEncode(config.toJson());- if (preferences.getString(key) == encoded) {- return;- }- final didWrite = await preferences.setString(key, encoded);- if (!didWrite) {- throw StateError('Could not persist local library sharing state');- }- }-- String _key(int ownerUserID, int recipientUserID) =>- '$_keyPrefix${ownerUserID}_$recipientUserID';-}--Set<int> _intSet(dynamic value) =>- value is List ? value.whereType<int>().toSet() : <int>{};diff --git a/mobile/apps/photos/lib/services/library_sharing_service.dart b/mobile/apps/photos/lib/services/library_sharing_service.dartindex 73e0de7324..c88763126d 100644--- a/mobile/apps/photos/lib/services/library_sharing_service.dart+++ b/mobile/apps/photos/lib/services/library_sharing_service.dart@@ -15,7 +15,7 @@ import 'package:photos/models/metadata/common_keys.dart';import 'package:photos/models/user_details.dart';import 'package:photos/services/account/user_service.dart';import 'package:photos/services/collections_service.dart';-import 'package:photos/services/library_sharing_local_store.dart';+import 'package:photos/services/library_sharing_store.dart';import 'package:photos/utils/contact_string_util.dart';import 'package:synchronized/synchronized.dart';@@ -85,16 +85,16 @@ class LibrarySharingService implements LibrarySharingRepository {CollectionsService? collectionsService,UserService? userService,Configuration? configuration,- LibrarySharingLocalStore? localStore,+ required LibrarySharingStore store,}) : _collectionsService = collectionsService ?? CollectionsService.instance,_userService = userService ?? UserService.instance,_configuration = configuration ?? Configuration.instance,- _localStore = localStore ?? LibrarySharingLocalStore();+ _store = store;final CollectionsService _collectionsService;final UserService _userService;final Configuration _configuration;- final LibrarySharingLocalStore _localStore;+ final LibrarySharingStore _store;final _logger = Logger('LibrarySharingService');final _operationLock = Lock();@@ -137,6 +137,7 @@ class LibrarySharingService implements LibrarySharingRepository {required Map<int, CollectionParticipantRole> roles,}) => _operationLock.synchronized(() async {final ownerUserID = _currentOwnerUserID();+ await _store.sync();final publicKey = await _requirePublicKey(recipient.email);final statuses = await _shareInBatches(ownerUserID: ownerUserID,@@ -150,7 +151,7 @@ class LibrarySharingService implements LibrarySharingRepository {.where((entry) => _isShareSuccess(entry.value)).map((entry) => entry.key).toSet();- final config = await _localStore.read(ownerUserID, recipient.userID);+ final config = await _store.read(ownerUserID, recipient.userID);if (config != null && succeededIDs.isNotEmpty) {await _writeConfig(ownerUserID,@@ -169,6 +170,7 @@ class LibrarySharingService implements LibrarySharingRepository {required List<int> collectionIDs,}) => _operationLock.synchronized(() async {final ownerUserID = _currentOwnerUserID();+ await _store.sync();final statuses = await _unshareInBatches(ownerUserID: ownerUserID,recipientUserID: recipientUserID,@@ -179,7 +181,7 @@ class LibrarySharingService implements LibrarySharingRepository {.where((entry) => _isUnshareSuccess(entry.value)).map((entry) => entry.key).toSet();- final config = await _localStore.read(ownerUserID, recipientUserID);+ final config = await _store.read(ownerUserID, recipientUserID);if (config != null && succeededIDs.isNotEmpty) {await _writeConfig(ownerUserID,@@ -222,8 +224,8 @@ class LibrarySharingService implements LibrarySharingRepository {if (ownerUserID == null) {return false;}- return (await _localStore.read(ownerUserID, recipientUserID))?.enabled ??- false;+ await _store.sync();+ return (await _store.read(ownerUserID, recipientUserID))?.enabled ?? false;}@override@@ -248,11 +250,12 @@ class LibrarySharingService implements LibrarySharingRepository {throw ArgumentError.value(role, 'role');}final ownerUserID = _currentOwnerUserID();+ await _store.sync();final publicKey = await _requirePublicKey(recipient.email);- final existing = await _localStore.read(ownerUserID, recipient.userID);+ final existing = await _store.read(ownerUserID, recipient.userID);var config =(existing ??- LibrarySharingLocalConfig(+ LibrarySharingConfig(recipientUserID: recipient.userID,enabled: false,defaultRole: role,@@ -262,7 +265,7 @@ class LibrarySharingService implements LibrarySharingRepository {ownerUserID,).toList();config = _observeCollections(config, collections);- await _writeConfig(ownerUserID, config);+ config = await _writeConfig(ownerUserID, config);final roles = _automaticShareRoles(collections, config);final statuses = roles.isEmpty@@ -299,7 +302,8 @@ class LibrarySharingService implements LibrarySharingRepository {Future<void> disableAutomaticSharing(int recipientUserID) =>_operationLock.synchronized(() async {final ownerUserID = _currentOwnerUserID();- final config = await _localStore.read(ownerUserID, recipientUserID);+ await _store.sync();+ final config = await _store.read(ownerUserID, recipientUserID);if (config != null && config.enabled) {await _writeConfig(ownerUserID, config.copyWith(enabled: false));}@@ -326,14 +330,21 @@ class LibrarySharingService implements LibrarySharingRepository {if (ownerUserID == null) {return;}- final configs = await _localStore.readAll(ownerUserID);+ try {+ await _store.sync();+ } catch (error, stackTrace) {+ _logger.warning(+ 'Could not sync library sharing state',+ error,+ stackTrace,+ );+ return;+ }+ final configs = await _store.readAll(ownerUserID);for (final config in configs.where((config) => config.enabled)) {try {await _operationLock.synchronized(() async {- final latest = await _localStore.read(- ownerUserID,- config.recipientUserID,- );+ final latest = await _store.read(ownerUserID, config.recipientUserID);if (latest == null || !latest.enabled) {return;}@@ -364,32 +375,36 @@ class LibrarySharingService implements LibrarySharingRepository {Future<void> _reconcileConfig(int ownerUserID,- LibrarySharingLocalConfig config,+ LibrarySharingConfig config,) async {final collections = _automaticallyShareableOwnedCollections(ownerUserID,).toList();config = _observeCollections(config, collections);- await _writeConfig(ownerUserID, config);+ config = await _writeConfig(ownerUserID, config);+ if (!config.enabled) {+ return;+ }final roles = _automaticShareRoles(collections, config);- if (roles.isNotEmpty) {- final recipientEmail = _recipientEmail(config.recipientUserID);- final statuses = await _shareInBatches(- ownerUserID: ownerUserID,- recipientUserID: config.recipientUserID,- recipientEmail: recipientEmail,- publicKey: await _requirePublicKey(recipientEmail),- roles: roles,- source: CollectionShareSource.automatic,- );- config = _applyAutomaticShareResults(config, statuses);+ if (roles.isEmpty) {+ return;}+ final recipientEmail = _recipientEmail(config.recipientUserID);+ final statuses = await _shareInBatches(+ ownerUserID: ownerUserID,+ recipientUserID: config.recipientUserID,+ recipientEmail: recipientEmail,+ publicKey: await _requirePublicKey(recipientEmail),+ roles: roles,+ source: CollectionShareSource.automatic,+ );+ config = _applyAutomaticShareResults(config, statuses);await _writeConfig(ownerUserID, config);}- LibrarySharingLocalConfig _observeCollections(- LibrarySharingLocalConfig config,+ LibrarySharingConfig _observeCollections(+ LibrarySharingConfig config,List<Collection> collections,) {final collectionIDs = collections@@ -409,7 +424,7 @@ class LibrarySharingService implements LibrarySharingRepository {Map<int, CollectionParticipantRole> _automaticShareRoles(List<Collection> collections,- LibrarySharingLocalConfig config,+ LibrarySharingConfig config,) => {for (final collection in collections)if (!config.hidden.contains(collection.id) &&@@ -421,8 +436,8 @@ class LibrarySharingService implements LibrarySharingRepository {),};- LibrarySharingLocalConfig _applyAutomaticShareResults(- LibrarySharingLocalConfig config,+ LibrarySharingConfig _applyAutomaticShareResults(+ LibrarySharingConfig config,Map<int, CollectionShareStatus> statuses,) {final addedAutomatically = {...config.addedAutomatically};@@ -542,12 +557,12 @@ class LibrarySharingService implements LibrarySharingRepository {}}- Future<void> _writeConfig(+ Future<LibrarySharingConfig> _writeConfig(int ownerUserID,- LibrarySharingLocalConfig config,- ) async {+ LibrarySharingConfig config,+ ) {_ensureCurrentOwner(ownerUserID);- await _localStore.write(ownerUserID, config);+ return _store.write(ownerUserID, config);}Future<String> _requirePublicKey(String email) async {@@ -571,7 +586,7 @@ class LibrarySharingService implements LibrarySharingRepository {Future<void> _refreshFamilyAndHandleIneligibleRecipient(int ownerUserID,- LibrarySharingLocalConfig config,+ LibrarySharingConfig config,) async {UserDetails userDetails;try {diff --git a/mobile/apps/photos/lib/services/library_sharing_store.dart b/mobile/apps/photos/lib/services/library_sharing_store.dartnew file mode 100644index 0000000000..d4f410fe74--- /dev/null+++ b/mobile/apps/photos/lib/services/library_sharing_store.dart@@ -0,0 +1,242 @@+import 'dart:convert';++import 'package:dio/dio.dart';+import 'package:logging/logging.dart';+import 'package:photos/gateways/entity/models/type.dart';+import 'package:photos/models/collection/collection.dart';+import 'package:photos/models/local_entity_data.dart';+import 'package:photos/services/entity_service.dart';++class LibrarySharingConfig {+ const LibrarySharingConfig({+ required this.recipientUserID,+ required this.enabled,+ required this.defaultRole,+ this.addedAutomatically = const {},+ this.unsharedBefore = const {},+ this.hidden = const {},+ this.updatedAt,+ this.base,+ });++ static const schemaVersion = 1;++ final int recipientUserID;+ final bool enabled;+ final CollectionParticipantRole defaultRole;+ final Set<int> addedAutomatically;+ final Set<int> unsharedBefore;+ final Set<int> hidden;+ final int? updatedAt;+ final LibrarySharingConfig? base;++ LibrarySharingConfig copyWith({+ bool? enabled,+ CollectionParticipantRole? defaultRole,+ Set<int>? addedAutomatically,+ Set<int>? unsharedBefore,+ Set<int>? hidden,+ int? updatedAt,+ LibrarySharingConfig? base,+ }) => LibrarySharingConfig(+ recipientUserID: recipientUserID,+ enabled: enabled ?? this.enabled,+ defaultRole: defaultRole ?? this.defaultRole,+ addedAutomatically: addedAutomatically ?? this.addedAutomatically,+ unsharedBefore: unsharedBefore ?? this.unsharedBefore,+ hidden: hidden ?? this.hidden,+ updatedAt: updatedAt ?? this.updatedAt,+ base: base ?? this.base,+ );++ LibrarySharingConfig _synced(int updatedAt) =>+ copyWith(updatedAt: updatedAt, base: this);++ Map<String, dynamic> toJson() => {+ 'version': schemaVersion,+ 'recipientUserID': recipientUserID,+ 'enabled': enabled,+ 'defaultRole': defaultRole.name,+ 'addedAutomatically': addedAutomatically.toList()..sort(),+ 'unsharedBefore': unsharedBefore.toList()..sort(),+ 'hidden': hidden.toList()..sort(),+ };++ factory LibrarySharingConfig.fromJson(Map<String, dynamic> json) {+ if (json['version'] != schemaVersion) {+ throw const FormatException('Unsupported library sharing version');+ }+ final recipientUserID = json['recipientUserID'];+ if (recipientUserID is! int || recipientUserID <= 0) {+ throw const FormatException('Invalid library sharing recipient');+ }+ final role = CollectionParticipantRoleExtn.fromString(+ json['defaultRole'] as String?,+ );+ return LibrarySharingConfig(+ recipientUserID: recipientUserID,+ enabled: json['enabled'] as bool? ?? false,+ defaultRole: switch (role) {+ CollectionParticipantRole.viewer ||+ CollectionParticipantRole.collaborator ||+ CollectionParticipantRole.admin => role,+ _ => CollectionParticipantRole.viewer,+ },+ addedAutomatically: _intSet(json['addedAutomatically']),+ unsharedBefore: _intSet(json['unsharedBefore']),+ hidden: _intSet(json['hidden']),+ );+ }+}++abstract interface class LibrarySharingStore {+ Future<void> sync();++ Future<LibrarySharingConfig?> read(int ownerUserID, int recipientUserID);++ Future<List<LibrarySharingConfig>> readAll(int ownerUserID);++ Future<LibrarySharingConfig> write(+ int ownerUserID,+ LibrarySharingConfig config,+ );+}++class LibrarySharingEntityStore implements LibrarySharingStore {+ LibrarySharingEntityStore(this._entityService);++ static const _type = EntityType.libraryShare;+ static const _writeAttempts = 2;++ final EntityService _entityService;+ final _logger = Logger('LibrarySharingEntityStore');++ @override+ Future<void> sync() async {+ if (await _entityService.syncEntity(_type) < 0) {+ throw StateError('Could not sync library sharing state');+ }+ }++ @override+ Future<LibrarySharingConfig?> read(+ int ownerUserID,+ int recipientUserID,+ ) async {+ final entity = await _entityService.getEntity(+ _type,+ _entityID(ownerUserID, recipientUserID),+ );+ return entity == null ? null : _decode(entity, ownerUserID);+ }++ @override+ Future<List<LibrarySharingConfig>> readAll(int ownerUserID) async {+ final configs = <LibrarySharingConfig>[];+ for (final entity in await _entityService.getEntities(_type)) {+ if (entity.ownerID != ownerUserID) {+ continue;+ }+ try {+ configs.add(_decode(entity, ownerUserID));+ } catch (error, stackTrace) {+ _logger.warning(+ 'Ignoring invalid library sharing entity ${entity.id}',+ error,+ stackTrace,+ );+ }+ }+ return configs;+ }++ @override+ Future<LibrarySharingConfig> write(+ int ownerUserID,+ LibrarySharingConfig config,+ ) async {+ final id = _entityID(ownerUserID, config.recipientUserID);+ final base = config.base;+ var desired = config;+ var expectedUpdatedAt = config.updatedAt;++ for (var attempt = 0; attempt < _writeAttempts; attempt++) {+ try {+ final saved = await _entityService.addOrUpdate(+ _type,+ desired.toJson(),+ id: id,+ addWithCustomID: expectedUpdatedAt == null,+ expectedUpdatedAt: expectedUpdatedAt,+ );+ return desired._synced(saved.updatedAt);+ } on DioException catch (error) {+ if (error.response?.statusCode != 409 ||+ attempt == _writeAttempts - 1) {+ rethrow;+ }+ await sync();+ final current = await _entityService.getEntity(_type, id);+ if (current != null) {+ desired = _merge(base, desired, _decode(current, ownerUserID));+ }+ expectedUpdatedAt = current?.updatedAt;+ }+ }+ throw StateError('Could not save library sharing state');+ }++ LibrarySharingConfig _decode(LocalEntityData entity, int ownerUserID) {+ final config = LibrarySharingConfig.fromJson(+ Map<String, dynamic>.from(jsonDecode(entity.data) as Map),+ );+ if (entity.ownerID != ownerUserID ||+ config.recipientUserID == ownerUserID ||+ entity.id != _entityID(ownerUserID, config.recipientUserID)) {+ throw const FormatException(+ 'Library sharing recipient does not match ID',+ );+ }+ return config._synced(entity.updatedAt);+ }++ LibrarySharingConfig _merge(+ LibrarySharingConfig? base,+ LibrarySharingConfig desired,+ LibrarySharingConfig remote,+ ) {+ final baseAddedAutomatically = base?.addedAutomatically ?? const <int>{};+ final baseUnsharedBefore = base?.unsharedBefore ?? const <int>{};+ final baseHidden = base?.hidden ?? const <int>{};+ return LibrarySharingConfig(+ recipientUserID: desired.recipientUserID,+ enabled: base == null || desired.enabled != base.enabled+ ? desired.enabled+ : remote.enabled,+ defaultRole: base == null || desired.defaultRole != base.defaultRole+ ? desired.defaultRole+ : remote.defaultRole,+ addedAutomatically: _mergeSet(+ baseAddedAutomatically,+ desired.addedAutomatically,+ remote.addedAutomatically,+ ),+ unsharedBefore: _mergeSet(+ baseUnsharedBefore,+ desired.unsharedBefore,+ remote.unsharedBefore,+ ),+ hidden: _mergeSet(baseHidden, desired.hidden, remote.hidden),+ );+ }++ String _entityID(int ownerUserID, int recipientUserID) =>+ 'ls_${ownerUserID}_$recipientUserID';+}++Set<int> _mergeSet(Set<int> base, Set<int> desired, Set<int> remote) =>+ {...remote, ...desired.difference(base)}+ ..removeAll(base.difference(desired));++Set<int> _intSet(dynamic value) =>+ value is List ? value.whereType<int>().toSet() : <int>{};diff --git a/mobile/apps/photos/lib/ui/family/family_plan_page.dart b/mobile/apps/photos/lib/ui/family/family_plan_page.dartindex f66c4da515..a45ffcefcc 100644--- a/mobile/apps/photos/lib/ui/family/family_plan_page.dart+++ b/mobile/apps/photos/lib/ui/family/family_plan_page.dart@@ -61,7 +61,7 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {late UserDetails _userDetails = widget.initialUserDetails;late final LibrarySharingService _librarySharingService =- LibrarySharingService();+ librarySharingService;final Map<int, contacts.ContactRecord?> _contactsByUserId = {};final Map<int, Uint8List?> _profilePictureBytesByUserId = {};Map<int, int> _sharedAlbumCountsByUserId = const {};diff --git a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dartindex 7cf14bddce..3876925e8e 100644--- a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart+++ b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart@@ -15,6 +15,7 @@ class FlagService {static const int _commentsFlag = 1 << 1;static const int _videoStreamingFlag = 1 << 3;static const int _castSessionsV2Flag = 1 << 5;+ static const int _librarySharingFlag = 1 << 7;static const int _cfUploadWorkerRolloutPercent = 20;static const String _userIdKey = "user_id";@@ -54,7 +55,8 @@ class FlagService {bool get largeBackupStandby => internalUser;- bool get librarySharing => internalUser;+ bool get librarySharing =>+ internalUser && _isServerFlagEnabled(_librarySharingFlag);bool get webGPUEnabled => true;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.dartindex e187374f2b..7cc41ab8ec 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@@ -469,6 +469,7 @@ class _FakeEntityService implements EntityService {Map<String, dynamic> jsonMap, {String? id,bool addWithCustomID = false,+ int? expectedUpdatedAt,}) async {final entityID = id ?? "person-${_entities.length + 1}";final entity = LocalEntityData(diff --git a/mobile/apps/photos/test/services/library_sharing_service_test.dart b/mobile/apps/photos/test/services/library_sharing_service_test.dartindex 4f181f2a80..c7302de381 100644--- a/mobile/apps/photos/test/services/library_sharing_service_test.dart+++ b/mobile/apps/photos/test/services/library_sharing_service_test.dart@@ -9,9 +9,8 @@ import 'package:photos/models/metadata/common_keys.dart';import 'package:photos/models/user_details.dart';import 'package:photos/services/account/user_service.dart';import 'package:photos/services/collections_service.dart';-import 'package:photos/services/library_sharing_local_store.dart';import 'package:photos/services/library_sharing_service.dart';-import 'package:shared_preferences/shared_preferences.dart';+import 'package:photos/services/library_sharing_store.dart';import '../ui/sharing/library_sharing_test_helpers.dart';@@ -101,6 +100,21 @@ void main() {},);+ test('does not reconcile after a concurrent remote disable', () async {+ final album = librarySharingTestAlbum(1);+ final fixture = await _Fixture.create([album]);+ fixture.store._config = LibrarySharingConfig(+ recipientUserID: librarySharingTestRecipient.userID,+ enabled: true,+ defaultRole: CollectionParticipantRole.viewer,+ );+ fixture.store.disableOnNextWrite = true;++ await fixture.service.reconcile();++ expect(album.sharees, isEmpty);+ });+test('stops bulk sharing on a recipient identity mismatch', () async {final albums = [for (var id = 1; id <= 101; id++) librarySharingTestAlbum(id),@@ -175,7 +189,7 @@ class _Fixture {final LibrarySharingService service;final _FakeCollectionsService collectionsService;- final LibrarySharingLocalStore store;+ final _MemoryLibrarySharingStore store;final _FakeUserService userService;static Future<_Fixture> create(@@ -184,21 +198,19 @@ class _Fixture {Set<int>? activeFamilyMemberUserIDs,Object? shareError,}) async {- SharedPreferences.setMockInitialValues({});- final preferences = await SharedPreferences.getInstance();final collectionsService = _FakeCollectionsService(albums,blockedIDs,shareError,);- final store = LibrarySharingLocalStore(preferences);+ final store = _MemoryLibrarySharingStore();final userService = _FakeUserService(activeFamilyMemberUserIDs);return _Fixture(LibrarySharingService(collectionsService: collectionsService,userService: userService,configuration: _FakeConfiguration(),- localStore: store,+ store: store,),collectionsService,store,@@ -206,13 +218,45 @@ class _Fixture {);}- Future<LibrarySharingLocalConfig> readConfig() async =>+ Future<LibrarySharingConfig> readConfig() async =>(await store.read(1, librarySharingTestRecipient.userID))!;Future<bool> isAutomaticSharingEnabled() =>service.isAutomaticSharingEnabled(librarySharingTestRecipient.userID);}+class _MemoryLibrarySharingStore implements LibrarySharingStore {+ LibrarySharingConfig? _config;+ bool disableOnNextWrite = false;++ @override+ Future<void> sync() async {}++ @override+ Future<LibrarySharingConfig?> read(+ int ownerUserID,+ int recipientUserID,+ ) async => _config?.recipientUserID == recipientUserID ? _config : null;++ @override+ Future<List<LibrarySharingConfig>> readAll(int ownerUserID) async => [+ ?_config,+ ];++ @override+ Future<LibrarySharingConfig> write(+ int ownerUserID,+ LibrarySharingConfig config,+ ) async {+ if (disableOnNextWrite) {+ config = config.copyWith(enabled: false);+ disableOnNextWrite = false;+ }+ _config = config;+ return config;+ }+}+class _FakeCollectionsService extends Mock implements CollectionsService {_FakeCollectionsService(this.albums, this.blockedIDs, this.shareError);diff --git a/mobile/apps/photos/test/services/library_sharing_store_test.dart b/mobile/apps/photos/test/services/library_sharing_store_test.dartnew file mode 100644index 0000000000..1a1326a3b5--- /dev/null+++ b/mobile/apps/photos/test/services/library_sharing_store_test.dart@@ -0,0 +1,109 @@+import 'dart:convert';++import 'package:dio/dio.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:photos/gateways/entity/models/type.dart';+import 'package:photos/models/collection/collection.dart';+import 'package:photos/models/local_entity_data.dart';+import 'package:photos/services/entity_service.dart';+import 'package:photos/services/library_sharing_store.dart';++void main() {+ test('merges remote changes after a version conflict', () async {+ final entityService = _ConflictEntityService();+ final store = LibrarySharingEntityStore(entityService);+ final base = (await store.read(1, 2))!;++ final unchangedService = _ConflictEntityService();+ final unchangedStore = LibrarySharingEntityStore(unchangedService);+ await unchangedStore.write(1, (await unchangedStore.read(1, 2))!);+ expect(unchangedService._writes, 2);++ final saved = await store.write(+ 1,+ base.copyWith(unsharedBefore: {}, hidden: {3}),+ );+ expect(saved.enabled, isTrue);+ expect(saved.defaultRole, CollectionParticipantRole.admin);+ expect(saved.addedAutomatically, {4});+ expect(saved.unsharedBefore, {2});+ expect(saved.hidden, {3});+ });++ test('fails when remote sync fails', () async {+ final entityService = _ConflictEntityService()..syncResult = -1;++ await expectLater(+ LibrarySharingEntityStore(entityService).sync(),+ throwsStateError,+ );+ });+}++class _ConflictEntityService implements EntityService {+ _ConflictEntityService() : current = _entity(_base, 1);++ LocalEntityData current;+ int syncResult = 1;+ var _writes = 0;++ @override+ Future<LocalEntityData?> getEntity(EntityType type, String id) async =>+ current;++ @override+ Future<int> syncEntity(EntityType type) async {+ if (syncResult >= 0) {+ current = _entity(_remote, 2);+ }+ return syncResult;+ }++ @override+ Future<LocalEntityData> addOrUpdate(+ EntityType type,+ Map<String, dynamic> jsonMap, {+ String? id,+ bool addWithCustomID = false,+ int? expectedUpdatedAt,+ }) async {+ expect(id, 'ls_1_2');+ expect(expectedUpdatedAt, _writes == 0 ? 1 : 2);+ if (_writes++ == 0) {+ final options = RequestOptions(path: '/user-entity/entity');+ throw DioException(+ requestOptions: options,+ response: Response(requestOptions: options, statusCode: 409),+ );+ }+ current = _entity(LibrarySharingConfig.fromJson(jsonMap), 3);+ return current;+ }++ @override+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);+}++const _base = LibrarySharingConfig(+ recipientUserID: 2,+ enabled: false,+ defaultRole: CollectionParticipantRole.viewer,+ unsharedBefore: {1},+);++const _remote = LibrarySharingConfig(+ recipientUserID: 2,+ enabled: true,+ defaultRole: CollectionParticipantRole.admin,+ addedAutomatically: {4},+ unsharedBefore: {1, 2},+);++LocalEntityData _entity(LibrarySharingConfig config, int updatedAt) =>+ LocalEntityData(+ id: 'ls_1_2',+ type: EntityType.libraryShare,+ data: jsonEncode(config.toJson()),+ ownerID: 1,+ updatedAt: updatedAt,+ );