Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mobile] Enable library sharing (#11892)

neeraj-pilot73fedf3e9af2
diff --git a/mobile/apps/photos/changes/automatic-album-sharing.md b/mobile/apps/photos/changes/automatic-album-sharing.md
new file mode 100644
index 0000000000..15eb7d4872
--- /dev/null
+++ b/mobile/apps/photos/changes/automatic-album-sharing.md
@@ -0,0 +1 @@
+- (i) Automatic album sharing.
diff --git a/mobile/apps/photos/lib/gateways/collections/collection_share_gateway.dart b/mobile/apps/photos/lib/gateways/collections/collection_share_gateway.dart
index 0bc9277cda..9dd37d2503 100644
--- a/mobile/apps/photos/lib/gateways/collections/collection_share_gateway.dart
+++ b/mobile/apps/photos/lib/gateways/collections/collection_share_gateway.dart
@@ -1,4 +1,5 @@
import "package:dio/dio.dart";
+import "package:photos/gateways/collections/models/collection_share.dart";
import "package:photos/gateways/collections/models/public_url.dart";
import "package:photos/models/api/collection/user.dart";
@@ -80,6 +81,38 @@ class CollectionShareGateway {
return sharees;
}
+ Future<List<CollectionShareResult>> shareBulk({
+ required int recipientUserID,
+ required CollectionShareSource source,
+ required List<BulkCollectionShareItem> collections,
+ }) async {
+ final response = await _enteDio.post(
+ "/collections/share/bulk",
+ data: {
+ "recipientUserID": recipientUserID,
+ "source": source.name,
+ "collections": collections.map((item) => item.toJson()).toList(),
+ },
+ );
+ return _parseBulkResults(response.data);
+ }
+
+ Future<List<CollectionShareResult>> unshareBulk({
+ required int recipientUserID,
+ required CollectionShareSource source,
+ required List<int> collectionIDs,
+ }) async {
+ final response = await _enteDio.post(
+ "/collections/unshare/bulk",
+ data: {
+ "recipientUserID": recipientUserID,
+ "source": source.name,
+ "collectionIDs": collectionIDs,
+ },
+ );
+ return _parseBulkResults(response.data);
+ }
+
/// Creates a public share URL for a collection.
///
/// [collectionID] - The collection to create a public link for.
@@ -208,6 +241,15 @@ class CollectionShareGateway {
}
}
+List<CollectionShareResult> _parseBulkResults(dynamic data) =>
+ (data['results'] as List)
+ .map(
+ (result) => CollectionShareResult.fromJson(
+ Map<String, dynamic>.from(result as Map),
+ ),
+ )
+ .toList();
+
String? _extractErrorMessage(dynamic data) {
if (data is Map<String, dynamic>) {
return data["error"]?.toString();
diff --git a/mobile/apps/photos/lib/gateways/collections/models/collection_share.dart b/mobile/apps/photos/lib/gateways/collections/models/collection_share.dart
new file mode 100644
index 0000000000..910fc98eb2
--- /dev/null
+++ b/mobile/apps/photos/lib/gateways/collections/models/collection_share.dart
@@ -0,0 +1,57 @@
+enum CollectionShareSource { manual, automatic }
+
+enum CollectionShareStatus {
+ shared,
+ alreadyShared,
+ unshared,
+ alreadyUnshared,
+ notShared,
+ blockedPreviousRemoval,
+ failed,
+ unknown;
+
+ factory CollectionShareStatus.fromString(String value) => switch (value) {
+ 'shared' => shared,
+ 'already_shared' => alreadyShared,
+ 'unshared' => unshared,
+ 'already_unshared' => alreadyUnshared,
+ 'not_shared' => notShared,
+ 'blocked_previous_removal' => blockedPreviousRemoval,
+ 'failed' => failed,
+ _ => unknown,
+ };
+}
+
+class BulkCollectionShareItem {
+ const BulkCollectionShareItem({
+ required this.collectionID,
+ required this.encryptedKey,
+ required this.role,
+ });
+
+ final int collectionID;
+ final String encryptedKey;
+ final String role;
+
+ Map<String, dynamic> toJson() => {
+ 'collectionID': collectionID,
+ 'encryptedKey': encryptedKey,
+ 'role': role,
+ };
+}
+
+class CollectionShareResult {
+ const CollectionShareResult({
+ required this.collectionID,
+ required this.status,
+ });
+
+ final int collectionID;
+ final CollectionShareStatus status;
+
+ factory CollectionShareResult.fromJson(Map<String, dynamic> json) =>
+ CollectionShareResult(
+ collectionID: json['collectionID'] as int,
+ status: CollectionShareStatus.fromString(json['status'] as String),
+ );
+}
diff --git a/mobile/apps/photos/lib/gateways/users/users_gateway.dart b/mobile/apps/photos/lib/gateways/users/users_gateway.dart
index 3e3862ca58..76731733c2 100644
--- a/mobile/apps/photos/lib/gateways/users/users_gateway.dart
+++ b/mobile/apps/photos/lib/gateways/users/users_gateway.dart
@@ -88,11 +88,21 @@ class UsersGateway {
/// Returns null if the email is not associated with an Ente account.
///
/// Endpoint: GET /users/public-key
- Future<String?> getPublicKey(String email) async {
+ Future<String?> getPublicKey(String email) => _getPublicKey({"email": email});
+
+ /// Get the user's public key by user ID.
+ ///
+ /// Returns null if the user does not exist or has no public key.
+ ///
+ /// Endpoint: GET /users/public-key
+ Future<String?> getPublicKeyByUserID(int userID) =>
+ _getPublicKey({"userID": userID});
+
+ Future<String?> _getPublicKey(Map<String, Object> queryParameters) async {
try {
final response = await _enteDio.get(
"/users/public-key",
- queryParameters: {"email": email},
+ queryParameters: queryParameters,
);
return response.data["publicKey"] as String?;
} on DioException catch (e) {
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index dd1b53d192..f625d3a592 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -489,6 +489,9 @@ Future<void> _init(
await SyncService.instance.init(preferences);
_isSyncInitialized = true;
_logger.info("SyncService init done $tlog");
+ if (!isBackground && flagService.librarySharing) {
+ unawaited(librarySharingService.init());
+ }
if (!isBackground && flagService.internalUser) {
_logger.info("GalleryDownloadQueueService init $tlog");
diff --git a/mobile/apps/photos/lib/service_locator.dart b/mobile/apps/photos/lib/service_locator.dart
index 9055b0ec12..b809a4d03d 100644
--- a/mobile/apps/photos/lib/service_locator.dart
+++ b/mobile/apps/photos/lib/service_locator.dart
@@ -29,6 +29,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/location_service.dart";
import "package:photos/services/machine_learning/compute_controller.dart";
import "package:photos/services/machine_learning/face_ml/person/person_feedback_service.dart";
@@ -296,6 +298,14 @@ CollectionsService get collectionsService {
return _collectionsService!;
}
+LibrarySharingService? _librarySharingService;
+LibrarySharingService get librarySharingService {
+ _librarySharingService ??= LibrarySharingService(
+ localStore: LibrarySharingLocalStore(ServiceLocator.instance.prefs),
+ );
+ return _librarySharingService!;
+}
+
WrappedService? _wrappedService;
WrappedService get wrappedService {
_wrappedService ??= WrappedService.instance;
diff --git a/mobile/apps/photos/lib/services/account/user_service.dart b/mobile/apps/photos/lib/services/account/user_service.dart
index ca32c12c6a..cd8ff18e6f 100644
--- a/mobile/apps/photos/lib/services/account/user_service.dart
+++ b/mobile/apps/photos/lib/services/account/user_service.dart
@@ -60,7 +60,7 @@ class UserService {
static const kIsEmailMFAEnabled = "is_email_mfa_enabled";
final SRP6GroupParameters kDefaultSrpGroup = SRP6StandardGroups.rfc5054_4096;
- final _emailToPubKeyCache = TimedCache<String, String>(
+ final _publicKeyCache = TimedCache<Object, String>(
duration: const Duration(seconds: 10),
);
@@ -208,14 +208,23 @@ class UserService {
// getPublicKey returns null value if email id is not
// associated with another ente account
- Future<String?> getPublicKey(String email) async {
- final String? cachedPubKey = _emailToPubKeyCache.get(email);
+ Future<String?> getPublicKey(String email) =>
+ _getPublicKey(email, () => _gateway.getPublicKey(email));
+
+ Future<String?> getPublicKeyByUserID(int userID) =>
+ _getPublicKey(userID, () => _gateway.getPublicKeyByUserID(userID));
+
+ Future<String?> _getPublicKey(
+ Object cacheKey,
+ Future<String?> Function() fetch,
+ ) async {
+ final String? cachedPubKey = _publicKeyCache.get(cacheKey);
if (cachedPubKey != null) {
return cachedPubKey;
}
- final publicKey = await _gateway.getPublicKey(email);
+ final publicKey = await fetch();
if (publicKey != null) {
- _emailToPubKeyCache.set(email, publicKey);
+ _publicKeyCache.set(cacheKey, publicKey);
}
return publicKey;
}
diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dart
index bc5e552ad5..00482b433e 100644
--- a/mobile/apps/photos/lib/services/collections_service.dart
+++ b/mobile/apps/photos/lib/services/collections_service.dart
@@ -27,6 +27,7 @@ import 'package:photos/events/force_reload_home_gallery_event.dart';
import 'package:photos/events/local_photos_updated_event.dart';
import "package:photos/gateways/collections/collection_share_gateway.dart";
import 'package:photos/gateways/collections/models/collection_file_item.dart';
+import "package:photos/gateways/collections/models/collection_share.dart";
import 'package:photos/gateways/collections/models/create_request.dart';
import "package:photos/gateways/collections/models/metadata.dart";
import "package:photos/gateways/collections/models/public_url.dart";
@@ -872,6 +873,134 @@ class CollectionsService {
}
}
+ Future<Map<int, CollectionShareStatus>> shareBulk({
+ required int recipientUserID,
+ required String recipientEmail,
+ required String publicKey,
+ required Map<int, CollectionParticipantRole> roles,
+ required CollectionShareSource source,
+ }) async {
+ final recipientPublicKey = CryptoUtil.base642bin(publicKey);
+ final items = <BulkCollectionShareItem>[];
+ for (final entry in roles.entries) {
+ final encryptedKey = CryptoUtil.sealSync(
+ getCollectionKey(entry.key),
+ recipientPublicKey,
+ );
+ items.add(
+ BulkCollectionShareItem(
+ collectionID: entry.key,
+ encryptedKey: CryptoUtil.bin2base64(encryptedKey),
+ role: entry.value.toStringVal(),
+ ),
+ );
+ }
+ try {
+ final results = await collectionShareGateway.shareBulk(
+ recipientUserID: recipientUserID,
+ source: source,
+ collections: items,
+ );
+ _cacheBulkShares(
+ results,
+ recipientUserID: recipientUserID,
+ recipientEmail: recipientEmail,
+ roles: roles,
+ );
+ RemoteSyncService.instance.sync(silently: true).ignore();
+ return {for (final result in results) result.collectionID: result.status};
+ } on DioException catch (e) {
+ if (e.response?.statusCode == 402) {
+ throw SharingNotPermittedForFreeAccountsError();
+ }
+ rethrow;
+ }
+ }
+
+ Future<Map<int, CollectionShareStatus>> unshareBulk({
+ required int recipientUserID,
+ required List<int> collectionIDs,
+ required CollectionShareSource source,
+ }) async {
+ final results = await collectionShareGateway.unshareBulk(
+ recipientUserID: recipientUserID,
+ source: source,
+ collectionIDs: collectionIDs,
+ );
+ _cacheBulkUnshares(results, recipientUserID);
+ RemoteSyncService.instance.sync(silently: true).ignore();
+ return {for (final result in results) result.collectionID: result.status};
+ }
+
+ void _cacheBulkShares(
+ List<CollectionShareResult> results, {
+ required int recipientUserID,
+ required String recipientEmail,
+ required Map<int, CollectionParticipantRole> roles,
+ }) {
+ final updates = <Collection>[];
+ for (final result in results) {
+ if (result.status != CollectionShareStatus.shared) {
+ continue;
+ }
+ final collection = _collectionIDToCollections[result.collectionID];
+ final role = roles[result.collectionID];
+ if (collection == null || role == null) {
+ continue;
+ }
+ final sharees =
+ collection.sharees
+ .where((user) => user.id != recipientUserID)
+ .toList()
+ ..add(
+ User(
+ id: recipientUserID,
+ email: recipientEmail,
+ role: role.toStringVal(),
+ ),
+ );
+ updates.add(collection.copyWith(sharees: sharees));
+ }
+ _cacheBulkShareUpdates(updates);
+ }
+
+ void _cacheBulkUnshares(
+ List<CollectionShareResult> results,
+ int recipientUserID,
+ ) {
+ final updates = <Collection>[];
+ for (final result in results) {
+ if (result.status != CollectionShareStatus.unshared &&
+ result.status != CollectionShareStatus.alreadyUnshared &&
+ result.status != CollectionShareStatus.notShared) {
+ continue;
+ }
+ final collection = _collectionIDToCollections[result.collectionID];
+ if (collection == null) {
+ continue;
+ }
+ updates.add(
+ collection.copyWith(
+ sharees: collection.sharees
+ .where((user) => user.id != recipientUserID)
+ .toList(),
+ ),
+ );
+ }
+ _cacheBulkShareUpdates(updates);
+ }
+
+ void _cacheBulkShareUpdates(List<Collection> updates) {
+ if (updates.isEmpty) {
+ return;
+ }
+ for (final collection in updates) {
+ _collectionIDToCollections[collection.id] = collection;
+ }
+ Bus.instance.fire(ContactRelationshipsInvalidatedEvent());
+ unawaited(_db.insert(updates));
+ }
+
Future<void> trashNonEmptyCollection(Collection collection) async {
try {
await _turnOffDeviceFolderSync(collection);
diff --git a/mobile/apps/photos/lib/services/library_sharing_local_store.dart b/mobile/apps/photos/lib/services/library_sharing_local_store.dart
new file mode 100644
index 0000000000..03e577486f
--- /dev/null
+++ b/mobile/apps/photos/lib/services/library_sharing_local_store.dart
@@ -0,0 +1,143 @@
+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.dart
index 399a61aec1..f1528c2926 100644
--- a/mobile/apps/photos/lib/services/library_sharing_service.dart
+++ b/mobile/apps/photos/lib/services/library_sharing_service.dart
@@ -1,7 +1,21 @@
-import 'package:dio/dio.dart';
+import 'dart:async';
+
+import 'package:ente_pure_utils/ente_pure_utils.dart';
+import 'package:logging/logging.dart';
+import 'package:photos/core/configuration.dart';
+import 'package:photos/core/event_bus.dart';
+import 'package:photos/events/collection_updated_event.dart';
+import 'package:photos/events/user_details_changed_event.dart';
+import 'package:photos/gateways/collections/models/collection_share.dart';
import 'package:photos/models/collection/collection.dart';
+import 'package:photos/models/library_sharing/library_sharing_recipient.dart';
+import 'package:photos/models/metadata/collection_magic.dart';
+import 'package:photos/models/metadata/common_keys.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/utils/contact_string_util.dart';
+import 'package:synchronized/synchronized.dart';
const librarySharingRoles = [
CollectionParticipantRole.viewer,
@@ -9,6 +23,13 @@ const librarySharingRoles = [
CollectionParticipantRole.admin,
];
+const _bulkShareLimit = 100;
+const _reconcileEventSources = {
+ 'collections_updated',
+ 'createCollection',
+ 'collection_visibility_changed',
+};
+
CollectionParticipantRole? librarySharingRoleFor(
Collection collection,
int userID,
@@ -25,31 +46,61 @@ CollectionParticipantRole? librarySharingRoleFor(
abstract interface class LibrarySharingRepository {
Future<List<Collection>> getEligibleAlbums();
- Future<String?> getPublicKey(String email);
-
- Future<void> shareAlbum({
- required Collection collection,
- required String email,
- required String publicKey,
- required CollectionParticipantRole role,
+ Future<Set<int>> shareAlbums({
+ required LibrarySharingRecipient recipient,
+ required Map<int, CollectionParticipantRole> roles,
});
- Future<void> unshareAlbum({
- required Collection collection,
+ Future<Set<int>> unshareAlbums({
required int recipientUserID,
- required String email,
+ required List<int> collectionIDs,
});
+
+ Future<bool> isAutomaticSharingEnabled(int recipientUserID);
+
+ Future<Set<int>> enableAutomaticSharing({
+ required LibrarySharingRecipient recipient,
+ required CollectionParticipantRole role,
+ });
+
+ Future<void> disableAutomaticSharing(int recipientUserID);
}
class LibrarySharingService implements LibrarySharingRepository {
LibrarySharingService({
CollectionsService? collectionsService,
UserService? userService,
+ Configuration? configuration,
+ LibrarySharingLocalStore? localStore,
}) : _collectionsService = collectionsService ?? CollectionsService.instance,
- _userService = userService ?? UserService.instance;
+ _userService = userService ?? UserService.instance,
+ _configuration = configuration ?? Configuration.instance,
+ _localStore = localStore ?? LibrarySharingLocalStore();
final CollectionsService _collectionsService;
final UserService _userService;
+ final Configuration _configuration;
+ final LibrarySharingLocalStore _localStore;
+ final _logger = Logger('LibrarySharingService');
+ final _operationLock = Lock();
+
+ StreamSubscription<CollectionUpdatedEvent>? _collectionSubscription;
+ StreamSubscription<UserDetailsChangedEvent>? _userDetailsSubscription;
+ bool _isReconciling = false;
+ bool _reconcileAgain = false;
+
+ Future<void> init() async {
+ await _collectionSubscription?.cancel();
+ await _userDetailsSubscription?.cancel();
+ _collectionSubscription = Bus.instance
+ .on<CollectionUpdatedEvent>()
+ .where((event) => _reconcileEventSources.contains(event.source))
+ .listen((_) => reconcile().ignore());
+ _userDetailsSubscription = Bus.instance
+ .on<UserDetailsChangedEvent>()
+ .listen((_) => reconcile().ignore());
+ await reconcile();
+ }
@override
Future<List<Collection>> getEligibleAlbums() async {
@@ -58,51 +109,451 @@ class LibrarySharingService implements LibrarySharingRepository {
return albums;
}
- static bool _isEligibleAlbum(Collection collection) {
- final isShareableAlbum =
- collection.type == CollectionType.album ||
- collection.type == CollectionType.folder ||
- collection.type == CollectionType.favorites;
- return isShareableAlbum && !collection.isQuickLinkCollection();
+ @override
+ Future<Set<int>> shareAlbums({
+ required LibrarySharingRecipient recipient,
+ required Map<int, CollectionParticipantRole> roles,
+ }) => _operationLock.synchronized(() async {
+ final ownerUserID = _currentOwnerUserID();
+ final publicKey = await _requirePublicKey(recipient.userID);
+ final statuses = await _shareInBatches(
+ ownerUserID: ownerUserID,
+ recipientUserID: recipient.userID,
+ recipientEmail: recipient.email,
+ publicKey: publicKey,
+ roles: roles,
+ source: CollectionShareSource.manual,
+ );
+ final succeededIDs = statuses.entries
+ .where((entry) => _isShareSuccess(entry.value))
+ .map((entry) => entry.key)
+ .toSet();
+ final config = await _localStore.read(ownerUserID, recipient.userID);
+ if (config != null && succeededIDs.isNotEmpty) {
+ await _writeConfig(
+ ownerUserID,
+ config.copyWith(
+ unsharedBefore: config.unsharedBefore.difference(succeededIDs),
+ hidden: config.hidden.difference(succeededIDs),
+ ),
+ );
+ }
+ return roles.keys.toSet().difference(succeededIDs);
+ });
+
+ @override
+ Future<Set<int>> unshareAlbums({
+ required int recipientUserID,
+ required List<int> collectionIDs,
+ }) => _operationLock.synchronized(() async {
+ final ownerUserID = _currentOwnerUserID();
+ final statuses = await _unshareInBatches(
+ ownerUserID: ownerUserID,
+ recipientUserID: recipientUserID,
+ collectionIDs: collectionIDs,
+ source: CollectionShareSource.manual,
+ );
+ final succeededIDs = statuses.entries
+ .where((entry) => _isUnshareSuccess(entry.value))
+ .map((entry) => entry.key)
+ .toSet();
+ final config = await _localStore.read(ownerUserID, recipientUserID);
+ if (config != null && succeededIDs.isNotEmpty) {
+ await _writeConfig(
+ ownerUserID,
+ config.copyWith(
+ addedAutomatically: config.addedAutomatically.difference(
+ succeededIDs,
+ ),
+ unsharedBefore: {...config.unsharedBefore, ...succeededIDs},
+ ),
+ );
+ }
+ return collectionIDs.toSet().difference(succeededIDs);
+ });
+
+ Future<void> unshareAlbumFromAll(Collection collection) async {
+ final recipientUserIDs = collection.sharees
+ .map(
+ (sharee) =>
+ sharee.id ??
+ (throw StateError('A collection sharee has no user ID')),
+ )
+ .toList();
+ for (final recipientUserID in recipientUserIDs) {
+ final failedIDs = await unshareAlbums(
+ recipientUserID: recipientUserID,
+ collectionIDs: [collection.id],
+ );
+ if (failedIDs.isNotEmpty) {
+ throw StateError('Could not unshare collection ${collection.id}');
+ }
+ }
+ final updated = _collectionsService.getCollectionByID(collection.id);
+ if (updated == null) {
+ throw StateError('Collection ${collection.id} is not cached');
+ }
+ if (!identical(updated, collection)) {
+ collection.updateSharees(updated.sharees);
+ }
}
@override
- Future<String?> getPublicKey(String email) =>
- _userService.getPublicKey(email);
+ Future<bool> isAutomaticSharingEnabled(int recipientUserID) async {
+ final ownerUserID = _configuration.getUserID();
+ if (ownerUserID == null) {
+ return false;
+ }
+ return (await _localStore.read(ownerUserID, recipientUserID))?.enabled ??
+ false;
+ }
@override
- Future<void> shareAlbum({
- required Collection collection,
- required String email,
- required String publicKey,
+ Future<Set<int>> enableAutomaticSharing({
+ required LibrarySharingRecipient recipient,
required CollectionParticipantRole role,
}) async {
- await _collectionsService.share(collection.id, email, publicKey, role);
+ final failedIDs = await _operationLock.synchronized(
+ () => _enableAutomaticSharing(recipient, role),
+ );
+ if (failedIDs.isEmpty) {
+ await reconcile();
+ }
+ return failedIDs;
+ }
+
+ Future<Set<int>> _enableAutomaticSharing(
+ LibrarySharingRecipient recipient,
+ CollectionParticipantRole role,
+ ) async {
+ if (!librarySharingRoles.contains(role)) {
+ throw ArgumentError.value(role, 'role');
+ }
+ final ownerUserID = _currentOwnerUserID();
+ final publicKey = await _requirePublicKey(recipient.userID);
+ final existing = await _localStore.read(ownerUserID, recipient.userID);
+ var config =
+ (existing ??
+ LibrarySharingLocalConfig(
+ recipientUserID: recipient.userID,
+ enabled: false,
+ defaultRole: role,
+ ))
+ .copyWith(defaultRole: role);
+ final collections = _automaticallyShareableOwnedCollections(
+ ownerUserID,
+ ).toList();
+ config = _observeCollections(config, collections);
+ await _writeConfig(ownerUserID, config);
+
+ final roles = _automaticShareRoles(collections, config);
+ final statuses = roles.isEmpty
+ ? <int, CollectionShareStatus>{}
+ : await _shareInBatches(
+ ownerUserID: ownerUserID,
+ recipientUserID: recipient.userID,
+ recipientEmail: recipient.email,
+ publicKey: publicKey,
+ roles: roles,
+ source: CollectionShareSource.automatic,
+ );
+ config = _applyAutomaticShareResults(config, statuses);
+ final failedIDs = roles.keys
+ .where((id) => !_isAutomaticShareSuccess(statuses[id]))
+ .toSet();
+ await _writeConfig(
+ ownerUserID,
+ config.copyWith(enabled: failedIDs.isEmpty),
+ );
+ return failedIDs;
}
@override
- Future<void> unshareAlbum({
- required Collection collection,
+ Future<void> disableAutomaticSharing(int recipientUserID) =>
+ _operationLock.synchronized(() async {
+ final ownerUserID = _currentOwnerUserID();
+ final config = await _localStore.read(ownerUserID, recipientUserID);
+ if (config != null && config.enabled) {
+ await _writeConfig(ownerUserID, config.copyWith(enabled: false));
+ }
+ });
+
+ Future<void> reconcile() async {
+ if (_isReconciling) {
+ _reconcileAgain = true;
+ return;
+ }
+ _isReconciling = true;
+ try {
+ do {
+ _reconcileAgain = false;
+ await _reconcileAll();
+ } while (_reconcileAgain);
+ } finally {
+ _isReconciling = false;
+ }
+ }
+
+ Future<void> _reconcileAll() async {
+ final ownerUserID = _configuration.getUserID();
+ if (ownerUserID == null) {
+ return;
+ }
+ final configs = await _localStore.readAll(ownerUserID);
+ for (final config in configs.where((config) => config.enabled)) {
+ try {
+ await _operationLock.synchronized(() async {
+ final latest = await _localStore.read(
+ ownerUserID,
+ config.recipientUserID,
+ );
+ if (latest == null || !latest.enabled) {
+ return;
+ }
+ final activeFamilyMemberUserIDs = _activeFamilyMemberUserIDs();
+ if (activeFamilyMemberUserIDs != null &&
+ !activeFamilyMemberUserIDs.contains(latest.recipientUserID)) {
+ await _writeConfig(ownerUserID, latest.copyWith(enabled: false));
+ } else {
+ await _reconcileConfig(ownerUserID, latest);
+ }
+ });
+ } catch (error, stackTrace) {
+ _logger.warning(
+ 'Could not reconcile library sharing for ${config.recipientUserID}',
+ error,
+ stackTrace,
+ );
+ }
+ }
+ }
+
+ Future<void> _reconcileConfig(
+ int ownerUserID,
+ LibrarySharingLocalConfig config,
+ ) async {
+ final collections = _automaticallyShareableOwnedCollections(
+ ownerUserID,
+ ).toList();
+ config = _observeCollections(config, collections);
+ await _writeConfig(ownerUserID, config);
+
+ 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(config.recipientUserID),
+ roles: roles,
+ source: CollectionShareSource.automatic,
+ );
+ config = _applyAutomaticShareResults(config, statuses);
+ }
+ await _writeConfig(ownerUserID, config);
+ }
+
+ LibrarySharingLocalConfig _observeCollections(
+ LibrarySharingLocalConfig config,
+ List<Collection> collections,
+ ) {
+ final collectionIDs = collections
+ .map((collection) => collection.id)
+ .toSet();
+ return config.copyWith(
+ addedAutomatically: config.addedAutomatically.intersection(collectionIDs),
+ unsharedBefore: config.unsharedBefore.intersection(collectionIDs),
+ hidden: {
+ ...config.hidden.intersection(collectionIDs),
+ ...collections
+ .where(_isHiddenOwnedAlbum)
+ .map((collection) => collection.id),
+ },
+ );
+ }
+
+ Map<int, CollectionParticipantRole> _automaticShareRoles(
+ List<Collection> collections,
+ LibrarySharingLocalConfig config,
+ ) => {
+ for (final collection in collections)
+ if (!config.hidden.contains(collection.id) &&
+ !config.unsharedBefore.contains(collection.id) &&
+ librarySharingRoleFor(collection, config.recipientUserID) == null)
+ collection.id: collection.type == CollectionType.uncategorized
+ ? CollectionParticipantRole.viewer
+ : config.defaultRole,
+ };
+
+ LibrarySharingLocalConfig _applyAutomaticShareResults(
+ LibrarySharingLocalConfig config,
+ Map<int, CollectionShareStatus> statuses,
+ ) {
+ final addedAutomatically = {...config.addedAutomatically};
+ final unsharedBefore = {...config.unsharedBefore};
+ for (final entry in statuses.entries) {
+ if (entry.value == CollectionShareStatus.shared) {
+ addedAutomatically.add(entry.key);
+ } else if (entry.value == CollectionShareStatus.blockedPreviousRemoval) {
+ addedAutomatically.remove(entry.key);
+ unsharedBefore.add(entry.key);
+ }
+ }
+ return config.copyWith(
+ addedAutomatically: addedAutomatically,
+ unsharedBefore: unsharedBefore,
+ );
+ }
+
+ Future<Map<int, CollectionShareStatus>> _shareInBatches({
+ required int ownerUserID,
required int recipientUserID,
- required String email,
+ required String recipientEmail,
+ required String publicKey,
+ required Map<int, CollectionParticipantRole> roles,
+ required CollectionShareSource source,
}) async {
- try {
- await _collectionsService.unshare(collection.id, email);
- } on DioException catch (error, stackTrace) {
- if (error.response?.statusCode != 404) {
- Error.throwWithStackTrace(error, stackTrace);
+ final statuses = {
+ for (final id in roles.keys) id: CollectionShareStatus.failed,
+ };
+ for (final batch in roles.entries.toList().chunks(_bulkShareLimit)) {
+ _ensureCurrentOwner(ownerUserID);
+ try {
+ statuses.addAll(
+ await _collectionsService.shareBulk(
+ recipientUserID: recipientUserID,
+ recipientEmail: recipientEmail,
+ publicKey: publicKey,
+ roles: Map.fromEntries(batch),
+ source: source,
+ ),
+ );
+ } catch (error, stackTrace) {
+ _logger.warning('Bulk library share failed', error, stackTrace);
}
- // A 404 is idempotent only if fresh sharees confirm they are absent.
+ }
+ return statuses;
+ }
+
+ Future<Map<int, CollectionShareStatus>> _unshareInBatches({
+ required int ownerUserID,
+ required int recipientUserID,
+ required List<int> collectionIDs,
+ required CollectionShareSource source,
+ }) async {
+ final statuses = {
+ for (final id in collectionIDs) id: CollectionShareStatus.failed,
+ };
+ for (final batch in collectionIDs.chunks(_bulkShareLimit)) {
+ _ensureCurrentOwner(ownerUserID);
try {
- final sharees = await _collectionsService.refreshSharees(collection.id);
- if (!sharees.any((sharee) => sharee.id == recipientUserID)) {
- return;
- }
- } catch (_) {}
- Error.throwWithStackTrace(error, stackTrace);
+ statuses.addAll(
+ await _collectionsService.unshareBulk(
+ recipientUserID: recipientUserID,
+ collectionIDs: batch,
+ source: source,
+ ),
+ );
+ } catch (error, stackTrace) {
+ _logger.warning('Bulk library unshare failed', error, stackTrace);
+ }
}
+ return statuses;
}
+ Iterable<Collection> _eligibleAlbums() => _collectionsService
+ .getCollectionsForUI(includeUncategorized: false)
+ .where(_isShareableAlbum);
+
+ Iterable<Collection> _automaticallyShareableOwnedCollections(
+ int ownerUserID,
+ ) => _collectionsService.getActiveCollections().where(
+ (collection) =>
+ collection.isOwner(ownerUserID) &&
+ (_isShareableAlbum(collection) ||
+ collection.type == CollectionType.uncategorized),
+ );
+
+ static bool _isShareableAlbum(Collection collection) {
+ final isSupportedType =
+ collection.type == CollectionType.album ||
+ collection.type == CollectionType.folder ||
+ collection.type == CollectionType.favorites;
+ return isSupportedType &&
+ collection.magicMetadata.subType != subTypeSharedFilesCollection;
+ }
+
+ static bool _isHiddenOwnedAlbum(Collection collection) =>
+ collection.isDefaultHidden() ||
+ collection.mMdVersion > 0 &&
+ collection.magicMetadata.visibility == hiddenVisibility;
+
+ int _currentOwnerUserID() =>
+ _configuration.getUserID() ??
+ (throw StateError('Library sharing requires a signed-in account'));
+
+ void _ensureCurrentOwner(int ownerUserID) {
+ if (_configuration.getUserID() != ownerUserID) {
+ throw StateError('The active account changed during library sharing');
+ }
+ }
+
+ Future<void> _writeConfig(
+ int ownerUserID,
+ LibrarySharingLocalConfig config,
+ ) async {
+ _ensureCurrentOwner(ownerUserID);
+ await _localStore.write(ownerUserID, config);
+ }
+
+ Future<String> _requirePublicKey(int userID) async {
+ final publicKey = await _userService.getPublicKeyByUserID(userID);
+ if (publicKey == null || publicKey.isEmpty) {
+ throw StateError('No Ente public key found for recipient');
+ }
+ return publicKey;
+ }
+
+ String _recipientEmail(int recipientUserID) {
+ String? email;
+ for (final user in _userService.getRelevantContacts()) {
+ if (user.id == recipientUserID) {
+ email = knownContactEmailOrNull(user.email) ?? email;
+ }
+ }
+ return email ??
+ (throw StateError('No email found for library sharing recipient'));
+ }
+
+ Set<int>? _activeFamilyMemberUserIDs() {
+ // Temporary best-effort guard while Library Sharing is family-scoped;
+ // cached details can lag membership changes made on another client.
+ final userDetails = _userService.getCachedUserDetails();
+ if (userDetails == null) {
+ return null;
+ }
+ return userDetails.familyData?.members
+ ?.where((member) => member.isActive)
+ .map((member) => member.userID)
+ .whereType<int>()
+ .toSet() ??
+ const {};
+ }
+
+ bool _isShareSuccess(CollectionShareStatus? status) =>
+ status == CollectionShareStatus.shared ||
+ status == CollectionShareStatus.alreadyShared;
+
+ bool _isAutomaticShareSuccess(CollectionShareStatus? status) =>
+ _isShareSuccess(status) ||
+ status == CollectionShareStatus.blockedPreviousRemoval;
+
+ bool _isUnshareSuccess(CollectionShareStatus status) =>
+ status == CollectionShareStatus.unshared ||
+ status == CollectionShareStatus.alreadyUnshared ||
+ status == CollectionShareStatus.notShared;
+
Map<int, int> sharedAlbumCounts(Set<int> recipientUserIDs) {
if (recipientUserIDs.isEmpty) {
return const {};
@@ -117,8 +568,4 @@ class LibrarySharingService implements LibrarySharingRepository {
}
return counts;
}
-
- Iterable<Collection> _eligibleAlbums() => _collectionsService
- .getCollectionsForUI(includeUncategorized: false)
- .where(_isEligibleAlbum);
}
diff --git a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_controller.dart b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_controller.dart
index 6323b3e2ec..2ef933fd22 100644
--- a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_controller.dart
+++ b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_controller.dart
@@ -24,6 +24,7 @@ class LibrarySharingController extends ChangeNotifier {
int _failedCount = 0;
bool _isLoading = true;
bool _isMutating = false;
+ bool _isAutomaticSharingEnabled = false;
_LibrarySharingSelectionMode? _selectionMode;
bool _isDisposed = false;
@@ -38,6 +39,7 @@ class LibrarySharingController extends ChangeNotifier {
Object? get loadError => _loadError;
bool get isLoading => _isLoading;
bool get isMutating => _isMutating;
+ bool get isAutomaticSharingEnabled => _isAutomaticSharingEnabled;
bool get isFirstTime => _activeRoles.isEmpty;
bool get isAddingAlbums =>
isFirstTime || _selectionMode == _LibrarySharingSelectionMode.add;
@@ -68,6 +70,9 @@ class LibrarySharingController extends ChangeNotifier {
_loadError = null;
_notifyListeners();
try {
+ _isAutomaticSharingEnabled = await _repository.isAutomaticSharingEnabled(
+ recipient.userID,
+ );
await _reloadAlbums();
} catch (error) {
_loadError = error;
@@ -177,32 +182,9 @@ class LibrarySharingController extends ChangeNotifier {
}
_beginMutation();
- late final String publicKey;
- try {
- final key = await _repository.getPublicKey(recipient.email);
- if (key == null || key.isEmpty) {
- throw StateError('No Ente public key found for recipient');
- }
- publicKey = key;
- } catch (error, stackTrace) {
- _logger.warning(
- 'Failed to fetch recipient public key',
- error,
- stackTrace,
- );
- _isMutating = false;
- _notifyListeners();
- return false;
- }
-
return _mutateAlbums(
intendedRoles.keys.toSet(),
- (album, collectionID) => _repository.shareAlbum(
- collection: album,
- email: recipient.email,
- publicKey: publicKey,
- role: intendedRoles[collectionID]!,
- ),
+ () => _repository.shareAlbums(recipient: recipient, roles: intendedRoles),
onSucceeded: (collectionID) {
_activeRoles[collectionID] = intendedRoles[collectionID]!;
},
@@ -217,15 +199,67 @@ class LibrarySharingController extends ChangeNotifier {
_beginMutation();
return _mutateAlbums(
pendingIDs,
- (album, _) => _repository.unshareAlbum(
- collection: album,
+ () => _repository.unshareAlbums(
recipientUserID: recipient.userID,
- email: recipient.email,
+ collectionIDs: pendingIDs.toList(),
),
onSucceeded: _activeRoles.remove,
);
}
+ Future<bool> enableAutomaticSharing(CollectionParticipantRole role) async {
+ if (_isLoading || _isMutating || _isAutomaticSharingEnabled) {
+ return false;
+ }
+ _beginMutation();
+ try {
+ final failedIDs = await _repository.enableAutomaticSharing(
+ recipient: recipient,
+ role: role,
+ );
+ await _reloadAfterMutation();
+ _failedCount = failedIDs.length;
+ _isAutomaticSharingEnabled = failedIDs.isEmpty;
+ if (failedIDs.isEmpty) {
+ _selectionMode = null;
+ _clearSelectionState();
+ }
+ return failedIDs.isEmpty;
+ } catch (error, stackTrace) {
+ _logger.warning(
+ 'Failed to enable automatic library sharing',
+ error,
+ stackTrace,
+ );
+ return false;
+ } finally {
+ _isMutating = false;
+ _notifyListeners();
+ }
+ }
+
+ Future<bool> disableAutomaticSharing() async {
+ if (_isLoading || _isMutating || !_isAutomaticSharingEnabled) {
+ return false;
+ }
+ _beginMutation();
+ try {
+ await _repository.disableAutomaticSharing(recipient.userID);
+ _isAutomaticSharingEnabled = false;
+ return true;
+ } catch (error, stackTrace) {
+ _logger.warning(
+ 'Failed to disable automatic library sharing',
+ error,
+ stackTrace,
+ );
+ return false;
+ } finally {
+ _isMutating = false;
+ _notifyListeners();
+ }
+ }
+
void _beginMutation() {
_isMutating = true;
_failedCount = 0;
@@ -234,27 +268,15 @@ class LibrarySharingController extends ChangeNotifier {
Future<bool> _mutateAlbums(
Set<int> collectionIDs,
- Future<void> Function(Collection album, int collectionID) mutate, {
+ Future<Set<int>> Function() mutate, {
required ValueChanged<int> onSucceeded,
}) async {
- final failedIDs = <int>{};
- final albumsByID = {for (final album in _albums) album.id: album};
- for (final collectionID in collectionIDs) {
- final album = albumsByID[collectionID];
- if (album == null) {
- failedIDs.add(collectionID);
- continue;
- }
- try {
- await mutate(album, collectionID);
- } catch (error, stackTrace) {
- _logger.warning(
- 'Failed to update album $collectionID',
- error,
- stackTrace,
- );
- failedIDs.add(collectionID);
- }
+ late Set<int> failedIDs;
+ try {
+ failedIDs = {...await mutate()};
+ } catch (error, stackTrace) {
+ _logger.warning('Failed to update albums', error, stackTrace);
+ failedIDs = collectionIDs;
}
return _finishMutation(
collectionIDs,
@@ -274,6 +296,18 @@ class LibrarySharingController extends ChangeNotifier {
onSucceeded(id);
}
_selectedRoles.removeWhere((id, _) => !failedIDs.contains(id));
+ await _reloadAfterMutation();
+ failedIDs.removeWhere((id) => !_selectedRoles.containsKey(id));
+ _failedCount = failedIDs.length;
+ _isMutating = false;
+ if (failedIDs.isEmpty) {
+ _selectionMode = null;
+ }
+ _notifyListeners();
+ return failedIDs.isEmpty;
+ }
+
+ Future<void> _reloadAfterMutation() async {
try {
await _reloadAlbums();
} catch (error, stackTrace) {
@@ -283,14 +317,6 @@ class LibrarySharingController extends ChangeNotifier {
stackTrace,
);
}
- failedIDs.removeWhere((id) => !_selectedRoles.containsKey(id));
- _failedCount = failedIDs.length;
- _isMutating = false;
- if (failedIDs.isEmpty) {
- _selectionMode = null;
- }
- _notifyListeners();
- return failedIDs.isEmpty;
}
Future<void> _reloadAlbums() async {
diff --git a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_page.dart b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_page.dart
index bd54c50cb1..c0d5a43f34 100644
--- a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_page.dart
+++ b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_page.dart
@@ -6,7 +6,7 @@ import 'package:flutter/rendering.dart' show ScrollDirection;
import 'package:hugeicons/hugeicons.dart';
import 'package:photos/models/collection/collection.dart';
import 'package:photos/models/library_sharing/library_sharing_recipient.dart';
-import 'package:photos/services/library_sharing_service.dart';
+import 'package:photos/service_locator.dart' show librarySharingService;
import 'package:photos/ui/collections/flex_grid_view.dart';
import 'package:photos/ui/components/empty_state_component.dart';
import 'package:photos/ui/sharing/library_sharing/library_sharing_controller.dart';
@@ -34,7 +34,7 @@ class _LibrarySharingPageState extends State<LibrarySharingPage> {
widget.controller ??
LibrarySharingController(
recipient: widget.recipient,
- repository: LibrarySharingService(),
+ repository: librarySharingService,
);
late final bool _ownsController = widget.controller == null;
final ScrollController _scrollController = ScrollController();
@@ -274,12 +274,12 @@ class _LibrarySharingPageState extends State<LibrarySharingPage> {
MenuComponent(
title: LibrarySharingStrings.librarySharing,
subtitle: LibrarySharingStrings.shareAllYourAlbums,
- onTap: _showEnableLibrarySharing,
+ onTap: _toggleLibrarySharing,
trailing: IgnorePointer(
child: ExcludeSemantics(
child: ToggleSwitchComponent(
key: const ValueKey('library-sharing-toggle'),
- selected: false,
+ selected: _controller.isAutomaticSharingEnabled,
onChanged: (_) {},
),
),
@@ -409,14 +409,29 @@ class _LibrarySharingPageState extends State<LibrarySharingPage> {
}
}
- Future<void> _showEnableLibrarySharing() async {
- final shouldEnable = await showEnableLibrarySharingSheet(
+ Future<void> _toggleLibrarySharing() async {
+ if (_controller.isAutomaticSharingEnabled) {
+ await _showFailureIfNeeded(
+ await _controller.disableAutomaticSharing(),
+ _toggleLibrarySharing,
+ );
+ return;
+ }
+ final role = await showEnableLibrarySharingSheet(
context: context,
recipientLabel: _recipient.label,
);
- if (shouldEnable && mounted) {
- showToastComponent(context, LibrarySharingStrings.comingSoon);
+ if (role == null || !mounted) {
+ return;
}
+ await _enableLibrarySharing(role);
+ }
+
+ Future<void> _enableLibrarySharing(CollectionParticipantRole role) async {
+ await _showFailureIfNeeded(
+ await _controller.enableAutomaticSharing(role),
+ () => _enableLibrarySharing(role),
+ );
}
Future<void> _showFailureIfNeeded(
diff --git a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_sheets.dart b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_sheets.dart
index c7146d4053..4cb9d3ad9e 100644
--- a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_sheets.dart
+++ b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_sheets.dart
@@ -10,68 +10,64 @@ import 'package:photos/ui/sharing/library_sharing/library_sharing_strings.dart';
typedef LibrarySharingAlbumThumbnailBuilder =
Widget Function(BuildContext context, Collection album);
-Future<bool> showEnableLibrarySharingSheet({
+Future<CollectionParticipantRole?> showEnableLibrarySharingSheet({
required BuildContext context,
required String recipientLabel,
-}) async {
+}) {
var selectedRole = CollectionParticipantRole.viewer;
- return await showBottomSheetComponent<bool>(
- context: context,
- builder: (sheetContext) => StatefulBuilder(
- builder: (context, setState) {
- final colors = context.componentColors;
- return BottomSheetComponent(
- title: LibrarySharingStrings.enableLibrarySharing,
- borderSide: BorderSide(color: colors.strokeDark),
- content: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- LibrarySharingStrings.enableLibrarySharingMessage(
- recipientLabel,
+ return showBottomSheetComponent<CollectionParticipantRole>(
+ context: context,
+ builder: (sheetContext) => StatefulBuilder(
+ builder: (context, setState) {
+ final colors = context.componentColors;
+ return BottomSheetComponent(
+ title: LibrarySharingStrings.enableLibrarySharing,
+ borderSide: BorderSide(color: colors.strokeDark),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ LibrarySharingStrings.enableLibrarySharingMessage(
+ recipientLabel,
+ ),
+ style: TextStyles.body.copyWith(color: colors.textLight),
+ ),
+ const SizedBox(height: Spacing.lg),
+ Text(
+ LibrarySharingStrings.hiddenAlbumsNotShared,
+ style: TextStyles.body.copyWith(color: colors.textLight),
+ ),
+ const SizedBox(height: Spacing.lg),
+ MenuGroupComponent(
+ items: [
+ EntePopupMenuButton<CollectionParticipantRole>(
+ optionsBuilder: () => librarySharingRoleOptions(
+ context,
+ activeRole: selectedRole,
+ ),
+ onSelected: (role) => setState(() => selectedRole = role),
+ child: MenuComponent(
+ title: LibrarySharingStrings.role,
+ trailing: LibrarySharingRoleSelector(role: selectedRole),
),
- style: TextStyles.body.copyWith(color: colors.textLight),
- ),
- const SizedBox(height: Spacing.lg),
- Text(
- LibrarySharingStrings.hiddenAlbumsNotShared,
- style: TextStyles.body.copyWith(color: colors.textLight),
- ),
- const SizedBox(height: Spacing.lg),
- MenuGroupComponent(
- items: [
- EntePopupMenuButton<CollectionParticipantRole>(
- optionsBuilder: () => librarySharingRoleOptions(
- context,
- activeRole: selectedRole,
- ),
- onSelected: (role) =>
- setState(() => selectedRole = role),
- child: MenuComponent(
- title: LibrarySharingStrings.role,
- trailing: LibrarySharingRoleSelector(
- role: selectedRole,
- ),
- ),
- ),
- ],
),
],
),
- actions: [
- ButtonComponent(
- label: LibrarySharingStrings.enable,
- density: ButtonComponentDensity.compact,
- shouldSurfaceExecutionStates: false,
- onTap: () => Navigator.of(sheetContext).pop(true),
- ),
- ],
- );
- },
- ),
- ) ??
- false;
+ ],
+ ),
+ actions: [
+ ButtonComponent(
+ label: LibrarySharingStrings.enable,
+ density: ButtonComponentDensity.compact,
+ shouldSurfaceExecutionStates: false,
+ onTap: () => Navigator.of(sheetContext).pop(selectedRole),
+ ),
+ ],
+ );
+ },
+ ),
+ );
}
Future<bool?> showLibrarySharingRolesSheet({
diff --git a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_strings.dart b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_strings.dart
index 67e77f4cc2..c3ac530a0a 100644
--- a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_strings.dart
+++ b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_strings.dart
@@ -21,8 +21,6 @@ abstract final class LibrarySharingStrings {
'Hidden albums will not be shared. You can stop sharing any album at any time.',
);
static String get enable => pendingTranslation('Enable');
- static String get comingSoon => pendingTranslation('Coming soon');
-
static String sharedAlbumCount(int count) => switch (count) {
0 => pendingTranslation('No albums shared'),
1 => pendingTranslation('1 album shared'),
diff --git a/mobile/apps/photos/lib/ui/viewer/actions/album_selection_action_widget.dart b/mobile/apps/photos/lib/ui/viewer/actions/album_selection_action_widget.dart
index 6dce031cfa..2b8b54e714 100644
--- a/mobile/apps/photos/lib/ui/viewer/actions/album_selection_action_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/actions/album_selection_action_widget.dart
@@ -365,6 +365,15 @@ class _AlbumSelectionActionWidgetState
// Determine if we're hiding or unhiding based on first collection
final isUnhiding = collections.first.isHidden();
+ if (!await prepareSharedAlbumsForHiding(
+ context,
+ collections.where(
+ (collection) => collection.isOwner(userID) && !collection.isHidden(),
+ ),
+ )) {
+ return;
+ }
+ if (!mounted) return;
final dialog = createProgressDialog(
context,
isUnhiding ? context.strings.unhiding : context.strings.hiding,
@@ -390,6 +399,7 @@ class _AlbumSelectionActionWidgetState
prevVisibility: prevVisiblity,
isOwner: isOwner,
showProgressDialog: false,
+ skipSharedAlbumWarning: true,
);
}
if (!mounted) return;
diff --git a/mobile/apps/photos/lib/utils/magic_util.dart b/mobile/apps/photos/lib/utils/magic_util.dart
index 06875653a9..09baf10018 100644
--- a/mobile/apps/photos/lib/utils/magic_util.dart
+++ b/mobile/apps/photos/lib/utils/magic_util.dart
@@ -14,9 +14,12 @@ import 'package:photos/models/file/file.dart';
import "package:photos/models/metadata/collection_magic.dart";
import "package:photos/models/metadata/common_keys.dart";
import "package:photos/models/metadata/file_magic.dart";
+import 'package:photos/service_locator.dart' show librarySharingService;
import 'package:photos/services/collections_service.dart';
import 'package:photos/services/file_magic_service.dart';
import 'package:photos/ui/common/progress_dialog.dart';
+import 'package:photos/ui/components/buttons/button_widget.dart';
+import 'package:photos/ui/components/models/button_type.dart';
import 'package:photos/ui/notification/toast.dart';
import 'package:photos/utils/dialog_util.dart';
@@ -61,7 +64,16 @@ Future<void> changeCollectionVisibility(
required int prevVisibility,
bool isOwner = true,
bool showProgressDialog = true,
+ bool skipSharedAlbumWarning = false,
}) async {
+ if (isOwner &&
+ !skipSharedAlbumWarning &&
+ newVisibility == hiddenVisibility &&
+ prevVisibility != hiddenVisibility &&
+ !await prepareSharedAlbumsForHiding(context, [collection])) {
+ return;
+ }
+ if (!context.mounted) return;
final visibilityAction = _getVisibilityAction(
context,
newVisibility,
@@ -80,6 +92,13 @@ Future<void> changeCollectionVisibility(
final Map<String, dynamic> update = {magicKeyVisibility: newVisibility};
if (isOwner) {
await CollectionsService.instance.updateMagicMetadata(collection, update);
+ Bus.instance.fire(
+ CollectionUpdatedEvent(
+ collection.id,
+ const <EnteFile>[],
+ 'collection_visibility_changed',
+ ),
+ );
} else {
await CollectionsService.instance.updateShareeMagicMetadata(
collection,
@@ -107,6 +126,60 @@ Future<void> changeCollectionVisibility(
}
}
+Future<bool> prepareSharedAlbumsForHiding(
+ BuildContext context,
+ Iterable<Collection> collections,
+) async {
+ final sharedAlbums = collections
+ .where((collection) => collection.hasSharees)
+ .toList();
+ if (sharedAlbums.isEmpty) {
+ return true;
+ }
+ final result = await showChoiceDialog(
+ context,
+ title: context.strings.warning,
+ body: pendingTranslation(
+ sharedAlbums.length == 1
+ ? 'This album is currently being shared. Please unshare if you wish to hide its contents from receivers.'
+ : 'Some selected albums are currently being shared. Please unshare if you wish to hide their contents from receivers.',
+ ),
+ firstButtonLabel: context.strings.hide,
+ secondButtonLabel: pendingTranslation('Unshare and Hide'),
+ firstButtonType: ButtonType.neutral,
+ secondButtonType: ButtonType.critical,
+ secondButtonAction: ButtonAction.second,
+ icon: Icons.warning_amber_rounded,
+ );
+ if (result?.action == ButtonAction.first) {
+ return true;
+ }
+ if (result?.action != ButtonAction.second || !context.mounted) {
+ return false;
+ }
+
+ final dialog = createProgressDialog(context, context.strings.pleaseWait);
+ await dialog.show();
+ try {
+ for (final album in sharedAlbums) {
+ await librarySharingService.unshareAlbumFromAll(album);
+ }
+ await dialog.hide();
+ return context.mounted;
+ } catch (error, stackTrace) {
+ _logger.warning(
+ 'Failed to unshare albums before hiding',
+ error,
+ stackTrace,
+ );
+ await dialog.hide();
+ if (context.mounted) {
+ await showGenericErrorDialog(context: context, error: error);
+ }
+ return false;
+ }
+}
+
Future<void> changeSortOrder(
BuildContext context,
Collection collection,
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 fadf2b5f06..1343d9b9ba 100644
--- a/mobile/apps/photos/test/services/library_sharing_service_test.dart
+++ b/mobile/apps/photos/test/services/library_sharing_service_test.dart
@@ -1,131 +1,266 @@
-import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
+import 'package:photos/core/configuration.dart';
+import 'package:photos/gateways/collections/models/collection_share.dart';
import 'package:photos/models/api/collection/user.dart';
import 'package:photos/models/collection/collection.dart';
+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 '../ui/sharing/library_sharing_test_helpers.dart';
void main() {
- test('sharedAlbumCounts ignores unsupported participant roles', () {
- final collectionsService = _MockCollectionsService();
- final supportedAlbum = librarySharingTestAlbum(
- 1,
- recipientRole: CollectionParticipantRole.viewer,
- );
- final unsupportedAlbum = librarySharingTestAlbum(
- 2,
- recipientRole: CollectionParticipantRole.viewer,
+ test('batches automatic shares and shares uncategorized as viewer', () async {
+ final albums = [
+ for (var id = 1; id <= 100; id++) librarySharingTestAlbum(id),
+ librarySharingTestAlbum(101, type: CollectionType.uncategorized),
+ ];
+ final fixture = await _Fixture.create(albums, blockedIDs: {100});
+
+ expect(
+ await fixture.service.enableAutomaticSharing(
+ recipient: librarySharingTestRecipient,
+ role: CollectionParticipantRole.admin,
+ ),
+ isEmpty,
);
- unsupportedAlbum.sharees.single.role = 'EDITOR';
- collectionsService.collectionsForUI = [supportedAlbum, unsupportedAlbum];
+ expect(fixture.collectionsService.shareBatchSizes, [100, 1]);
expect(
- LibrarySharingService(
- collectionsService: collectionsService,
- ).sharedAlbumCounts({librarySharingTestRecipient.userID}),
- {librarySharingTestRecipient.userID: 1},
+ fixture.collectionsService.sharedRoles[101],
+ CollectionParticipantRole.viewer,
);
+ final config = await fixture.readConfig();
+ expect(config.addedAutomatically.length, 100);
+ expect(config.unsharedBefore, {100});
});
- group('LibrarySharingService.unshareAlbum', () {
- late _MockCollectionsService collectionsService;
- late LibrarySharingService service;
- late Collection album;
-
- setUp(() {
- collectionsService = _MockCollectionsService();
- service = LibrarySharingService(collectionsService: collectionsService);
- album = librarySharingTestAlbum(
- 1,
- recipientRole: CollectionParticipantRole.viewer,
+ test('hidden automatic shares remain until explicitly unshared', () async {
+ final album = librarySharingTestAlbum(1);
+ final fixture = await _Fixture.create([album]);
+ await fixture.service.enableAutomaticSharing(
+ recipient: librarySharingTestRecipient,
+ role: CollectionParticipantRole.viewer,
+ );
+
+ album.mMdVersion = 1;
+ album.mMdEncodedJson = '{"visibility":$hiddenVisibility}';
+ await fixture.service.reconcile();
+
+ var config = await fixture.readConfig();
+ expect(config.hidden, {album.id});
+ expect(config.addedAutomatically, {album.id});
+ expect(album.sharees, isNotEmpty);
+
+ await fixture.service.unshareAlbumFromAll(album);
+
+ config = await fixture.readConfig();
+ expect(config.addedAutomatically, isEmpty);
+ expect(config.unsharedBefore, {album.id});
+ expect(album.sharees, isEmpty);
+
+ album.mMdEncodedJson = '{"visibility":$visibleVisibility}';
+ await fixture.service.reconcile();
+
+ 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);
+ });
+
+ test(
+ 'stops automatic sharing when the recipient leaves the family',
+ () async {
+ final albums = [librarySharingTestAlbum(1)];
+ final fixture = await _Fixture.create(
+ albums,
+ activeFamilyMemberUserIDs: {librarySharingTestRecipient.userID},
+ );
+ await fixture.service.enableAutomaticSharing(
+ recipient: librarySharingTestRecipient,
+ role: CollectionParticipantRole.viewer,
);
- });
- test('accepts an already-absent recipient after a not-found response', () {
- final error = _dioException(404);
- collectionsService.unshareHandler = (_, _) => Future.error(error);
- collectionsService.refreshShareesHandler = (_) async => const <User>[];
+ fixture.userService.activeFamilyMemberUserIDs = {};
+ albums.add(librarySharingTestAlbum(2));
+ await fixture.service.reconcile();
expect(
- service.unshareAlbum(
- collection: album,
- recipientUserID: librarySharingTestRecipient.userID,
- email: librarySharingTestRecipient.email,
+ await fixture.service.isAutomaticSharingEnabled(
+ librarySharingTestRecipient.userID,
),
- completes,
+ isFalse,
);
- });
+ expect(albums.first.sharees, isNotEmpty);
+ expect(albums.last.sharees, isEmpty);
+ },
+ );
+}
- test('preserves non-idempotent unshare failures', () async {
- final error = _dioException(500);
- collectionsService.unshareHandler = (_, _) => Future.error(error);
+class _Fixture {
+ const _Fixture(
+ this.service,
+ this.collectionsService,
+ this.store,
+ this.userService,
+ );
- await expectLater(
- service.unshareAlbum(
- collection: album,
- recipientUserID: librarySharingTestRecipient.userID,
- email: librarySharingTestRecipient.email,
- ),
- throwsA(same(error)),
- );
- expect(collectionsService.refreshShareesCalls, 0);
- });
-
- test('preserves not-found when the recipient is still present', () async {
- final error = _dioException(404);
- collectionsService.unshareHandler = (_, _) => Future.error(error);
- collectionsService.refreshShareesHandler = (_) async => [
- User(
- id: librarySharingTestRecipient.userID,
- email: librarySharingTestRecipient.email,
- ),
- ];
+ final LibrarySharingService service;
+ final _FakeCollectionsService collectionsService;
+ final LibrarySharingLocalStore store;
+ final _FakeUserService userService;
- await expectLater(
- service.unshareAlbum(
- collection: album,
- recipientUserID: librarySharingTestRecipient.userID,
- email: librarySharingTestRecipient.email,
- ),
- throwsA(same(error)),
- );
- });
- });
+ static Future<_Fixture> create(
+ List<Collection> albums, {
+ Set<int> blockedIDs = const {},
+ Set<int>? activeFamilyMemberUserIDs,
+ }) async {
+ SharedPreferences.setMockInitialValues({});
+ final preferences = await SharedPreferences.getInstance();
+ final collectionsService = _FakeCollectionsService(albums, blockedIDs);
+ final store = LibrarySharingLocalStore(preferences);
+ final userService = _FakeUserService(activeFamilyMemberUserIDs);
+ return _Fixture(
+ LibrarySharingService(
+ collectionsService: collectionsService,
+ userService: userService,
+ configuration: _FakeConfiguration(),
+ localStore: store,
+ ),
+ collectionsService,
+ store,
+ userService,
+ );
+ }
+
+ Future<LibrarySharingLocalConfig> readConfig() async =>
+ (await store.read(1, librarySharingTestRecipient.userID))!;
}
-class _MockCollectionsService extends Mock implements CollectionsService {
- List<Collection> collectionsForUI = const [];
- late Future<List<User>> Function(int collectionID, String email)
- unshareHandler;
- Future<List<User>> Function(int collectionID)? refreshShareesHandler;
- int refreshShareesCalls = 0;
+class _FakeCollectionsService extends Mock implements CollectionsService {
+ _FakeCollectionsService(this.albums, this.blockedIDs);
+
+ final List<Collection> albums;
+ final Set<int> blockedIDs;
+ final List<int> shareBatchSizes = [];
+ final List<int> shareAttempts = [];
+ final List<int> unshareAttempts = [];
+ final Map<int, CollectionParticipantRole> sharedRoles = {};
@override
- List<Collection> getCollectionsForUI({
- bool includedShared = false,
- bool includeCollab = false,
- bool includeUncategorized = false,
- }) => collectionsForUI;
+ List<Collection> getActiveCollections() => albums;
@override
- Future<List<User>> unshare(int collectionID, String email) =>
- unshareHandler(collectionID, email);
+ Future<Map<int, CollectionShareStatus>> shareBulk({
+ required int recipientUserID,
+ required String recipientEmail,
+ required String publicKey,
+ required Map<int, CollectionParticipantRole> roles,
+ required CollectionShareSource source,
+ }) async {
+ shareBatchSizes.add(roles.length);
+ shareAttempts.addAll(roles.keys);
+ sharedRoles.addAll(roles);
+ for (final entry in roles.entries) {
+ if (blockedIDs.contains(entry.key)) {
+ continue;
+ }
+ albums
+ .firstWhere((album) => album.id == entry.key)
+ .sharees
+ .add(
+ User(
+ id: recipientUserID,
+ email: recipientEmail,
+ role: entry.value.toStringVal(),
+ ),
+ );
+ }
+ return {
+ for (final collectionID in roles.keys)
+ collectionID: blockedIDs.contains(collectionID)
+ ? CollectionShareStatus.blockedPreviousRemoval
+ : CollectionShareStatus.shared,
+ };
+ }
@override
- Future<List<User>> refreshSharees(int collectionID) {
- refreshShareesCalls++;
- return refreshShareesHandler?.call(collectionID) ??
- Future.value(const <User>[]);
+ Future<Map<int, CollectionShareStatus>> unshareBulk({
+ required int recipientUserID,
+ required List<int> collectionIDs,
+ required CollectionShareSource source,
+ }) async {
+ unshareAttempts.addAll(collectionIDs);
+ for (final id in collectionIDs) {
+ albums
+ .firstWhere((album) => album.id == id)
+ .sharees
+ .removeWhere((sharee) => sharee.id == recipientUserID);
+ }
+ return {for (final id in collectionIDs) id: CollectionShareStatus.unshared};
}
+
+ @override
+ Collection? getCollectionByID(int collectionID) =>
+ albums.firstWhere((album) => album.id == collectionID);
}
-DioException _dioException(int statusCode) {
- final requestOptions = RequestOptions(path: '/collections/unshare');
- return DioException(
- requestOptions: requestOptions,
- response: Response(requestOptions: requestOptions, statusCode: statusCode),
- );
+class _FakeUserService extends Mock implements UserService {
+ _FakeUserService(this.activeFamilyMemberUserIDs);
+
+ Set<int>? activeFamilyMemberUserIDs;
+
+ @override
+ Future<String?> getPublicKeyByUserID(int userID) async =>
+ userID == librarySharingTestRecipient.userID ? 'public-key' : null;
+
+ @override
+ List<User> getRelevantContacts() => [
+ User(
+ id: librarySharingTestRecipient.userID,
+ email: librarySharingTestRecipient.email,
+ ),
+ ];
+
+ @override
+ UserDetails? getCachedUserDetails() {
+ final userIDs = activeFamilyMemberUserIDs;
+ return userIDs == null ? null : _FakeUserDetails(userIDs);
+ }
+}
+
+class _FakeUserDetails extends Mock implements UserDetails {
+ _FakeUserDetails(Set<int> activeFamilyMemberUserIDs)
+ : familyData = FamilyData(
+ [
+ for (final userID in activeFamilyMemberUserIDs)
+ FamilyMember(
+ 0,
+ '$userID',
+ userID,
+ false,
+ FamilyMemberStatus.accepted,
+ null,
+ ),
+ ],
+ 0,
+ 0,
+ 0,
+ );
+
+ @override
+ final FamilyData familyData;
+}
+
+class _FakeConfiguration extends Mock implements Configuration {
+ @override
+ int? getUserID() => 1;
}
diff --git a/mobile/apps/photos/test/ui/sharing/library_sharing_controller_test.dart b/mobile/apps/photos/test/ui/sharing/library_sharing_controller_test.dart
index 7fb97c8bd4..3031ca3478 100644
--- a/mobile/apps/photos/test/ui/sharing/library_sharing_controller_test.dart
+++ b/mobile/apps/photos/test/ui/sharing/library_sharing_controller_test.dart
@@ -26,7 +26,6 @@ void main() {
controller.setRoleForSelection(CollectionParticipantRole.collaborator);
expect(await controller.applySelection(), isTrue);
- expect(repository.publicKeyRequests, 1);
expect(repository.sharedIDs, [2]);
expect(controller.activeRoleFor(1), CollectionParticipantRole.viewer);
expect(controller.activeRoleFor(2), CollectionParticipantRole.collaborator);
@@ -102,11 +101,9 @@ void main() {
controller.enterAddMode();
controller.toggleSelection(repository.albums[0]);
- await repository.shareAlbum(
- collection: repository.albums[0],
- email: librarySharingTestRecipient.email,
- publicKey: 'public-key',
- role: CollectionParticipantRole.viewer,
+ await repository.shareAlbums(
+ recipient: librarySharingTestRecipient,
+ roles: {repository.albums[0].id: CollectionParticipantRole.viewer},
);
await controller.load();
diff --git a/mobile/apps/photos/test/ui/sharing/library_sharing_page_test.dart b/mobile/apps/photos/test/ui/sharing/library_sharing_page_test.dart
index 5c97ba6b99..6c8b049df2 100644
--- a/mobile/apps/photos/test/ui/sharing/library_sharing_page_test.dart
+++ b/mobile/apps/photos/test/ui/sharing/library_sharing_page_test.dart
@@ -75,7 +75,7 @@ void main() {
expect(find.byType(ToggleSwitchComponent), findsNothing);
});
- testWidgets('library sharing banner opens the enable preview', (
+ testWidgets('library sharing banner enables and disables automatic sharing', (
tester,
) async {
final controller = _LayoutTestLibrarySharingController();
@@ -120,7 +120,17 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('Enable library sharing?'), findsNothing);
- expect(find.text('Coming soon'), findsOneWidget);
+ expect(
+ tester
+ .widget<ToggleSwitchComponent>(
+ find.byKey(const ValueKey('library-sharing-toggle')),
+ )
+ .selected,
+ isTrue,
+ );
+
+ await tester.tap(find.text('Library sharing'));
+ await tester.pumpAndSettle();
expect(
tester
.widget<ToggleSwitchComponent>(
@@ -129,7 +139,6 @@ void main() {
.selected,
isFalse,
);
- await tester.pump(const Duration(seconds: 5));
});
testWidgets('keeps the library sharing banner while albums are selected', (
diff --git a/mobile/apps/photos/test/ui/sharing/library_sharing_test_helpers.dart b/mobile/apps/photos/test/ui/sharing/library_sharing_test_helpers.dart
index 4185aeffc4..aac3e8cca5 100644
--- a/mobile/apps/photos/test/ui/sharing/library_sharing_test_helpers.dart
+++ b/mobile/apps/photos/test/ui/sharing/library_sharing_test_helpers.dart
@@ -22,7 +22,7 @@ class FakeLibrarySharingRepository implements LibrarySharingRepository {
Completer<void>? shareGate;
Completer<List<Collection>>? loadGate;
Object? loadFailure;
- int publicKeyRequests = 0;
+ bool automaticSharingEnabled = false;
@override
Future<List<Collection>> getEligibleAlbums() async {
@@ -38,51 +38,78 @@ class FakeLibrarySharingRepository implements LibrarySharingRepository {
}
@override
- Future<String?> getPublicKey(String email) async {
- publicKeyRequests++;
- return 'public-key';
+ Future<Set<int>> shareAlbums({
+ required LibrarySharingRecipient recipient,
+ required Map<int, CollectionParticipantRole> roles,
+ }) async {
+ await shareGate?.future;
+ final failedIDs = <int>{};
+ for (final entry in roles.entries) {
+ sharedIDs.add(entry.key);
+ sharedRoles.add(entry.value);
+ if (shareFailures.containsKey(entry.key)) {
+ failedIDs.add(entry.key);
+ continue;
+ }
+ final collection = albums.firstWhere((album) => album.id == entry.key);
+ collection.sharees.removeWhere((sharee) => sharee.id == recipient.userID);
+ collection.sharees.add(
+ User(
+ id: recipient.userID,
+ email: recipient.email,
+ role: entry.value.toStringVal(),
+ ),
+ );
+ }
+ return failedIDs;
}
@override
- Future<void> shareAlbum({
- required Collection collection,
- required String email,
- required String publicKey,
- required CollectionParticipantRole role,
+ Future<Set<int>> unshareAlbums({
+ required int recipientUserID,
+ required List<int> collectionIDs,
}) async {
- sharedIDs.add(collection.id);
- sharedRoles.add(role);
- await shareGate?.future;
- final failure = shareFailures[collection.id];
- if (failure != null) {
- throw failure;
+ for (final id in collectionIDs) {
+ unsharedIDs.add(id);
+ albums
+ .firstWhere((album) => album.id == id)
+ .sharees
+ .removeWhere((sharee) => sharee.id == recipientUserID);
}
- collection.sharees.removeWhere(
- (sharee) => sharee.id == librarySharingTestRecipient.userID,
- );
- collection.sharees.add(
- User(
- id: librarySharingTestRecipient.userID,
- email: email,
- role: role.toStringVal(),
- ),
- );
+ return const {};
}
@override
- Future<void> unshareAlbum({
- required Collection collection,
- required int recipientUserID,
- required String email,
+ Future<bool> isAutomaticSharingEnabled(int recipientUserID) async =>
+ automaticSharingEnabled;
+
+ @override
+ Future<Set<int>> enableAutomaticSharing({
+ required LibrarySharingRecipient recipient,
+ required CollectionParticipantRole role,
}) async {
- unsharedIDs.add(collection.id);
- collection.sharees.removeWhere((sharee) => sharee.id == recipientUserID);
+ final failures = await shareAlbums(
+ recipient: recipient,
+ roles: {
+ for (final album in albums)
+ if (librarySharingRoleFor(album, recipient.userID) == null)
+ album.id: role,
+ },
+ );
+ automaticSharingEnabled = failures.isEmpty;
+ return failures;
+ }
+
+ @override
+ Future<void> disableAutomaticSharing(int recipientUserID) async {
+ automaticSharingEnabled = false;
}
}
Collection librarySharingTestAlbum(
int id, {
CollectionParticipantRole? recipientRole,
+ CollectionType type = CollectionType.album,
}) {
return Collection(
id,
@@ -92,7 +119,7 @@ Collection librarySharingTestAlbum(
'Album $id',
null,
null,
- CollectionType.album,
+ type,
CollectionAttributes(),
[
if (recipientRole != null)