Skip to content

armgit / ente

Public Imported from GitHub
0

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

Use batch sharing in album sharing flow

AmanRajSinghMouryaae07badca975
diff --git a/mobile/apps/photos/changes/batch-album-sharing.md b/mobile/apps/photos/changes/batch-album-sharing.md
new file mode 100644
index 0000000000..56293f4086
--- /dev/null
+++ b/mobile/apps/photos/changes/batch-album-sharing.md
@@ -0,0 +1 @@
+- Faster album sharing with multiple people.
diff --git a/mobile/apps/photos/lib/services/account/user_service.dart b/mobile/apps/photos/lib/services/account/user_service.dart
index e7df1ad414..f1d5ca471d 100644
--- a/mobile/apps/photos/lib/services/account/user_service.dart
+++ b/mobile/apps/photos/lib/services/account/user_service.dart
@@ -254,13 +254,11 @@ class UserService {
}
Future<List<String?>> _getPublicKeyBatch(List<String> emails) async {
- if (flagService.internalUser) {
- try {
- return await _gateway.getPublicKeys(emails);
- } on DioException catch (error) {
- if (error.response?.statusCode != 404) {
- rethrow;
- }
+ try {
+ return await _gateway.getPublicKeys(emails);
+ } on DioException catch (error) {
+ if (error.response?.statusCode != 404) {
+ rethrow;
}
}
diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dart
index ec0b3db089..12832e953d 100644
--- a/mobile/apps/photos/lib/services/collections_service.dart
+++ b/mobile/apps/photos/lib/services/collections_service.dart
@@ -15,7 +15,6 @@ import 'package:photos/core/configuration.dart';
import 'package:photos/core/constants.dart';
import 'package:photos/core/errors.dart';
import 'package:photos/core/event_bus.dart';
-import 'package:photos/core/network/api_response.dart';
import 'package:photos/db/collections_db.dart';
import 'package:photos/db/device_files_db.dart';
import 'package:photos/db/files_db.dart';
@@ -885,7 +884,6 @@ class CollectionsService {
);
final collectionKey = getCollectionKey(collectionID);
final shareRole = role.toStringVal();
- var useLegacyAPI = !flagService.internalUser;
try {
for (final batch in publicKeys.entries.toList().chunks(_shareBatchSize)) {
final encryptedKeys = <String, String>{};
@@ -897,28 +895,13 @@ class CollectionsService {
encryptedKeys[entry.key] = CryptoUtil.bin2base64(encryptedKey);
}
- if (!useLegacyAPI) {
- try {
- sharees = await collectionShareGateway.shareBatch(
- collectionID: collectionID,
- encryptedKeys: encryptedKeys,
- role: shareRole,
- );
- _cacheSharees(_collectionIDToCollections[collectionID]!, sharees);
- RemoteSyncService.instance.sync(silently: true).ignore();
- continue;
- } on UnexpectedApiResponseException catch (error) {
- if (error.response?.statusCode != 404) rethrow;
- useLegacyAPI = true;
- }
- }
-
- sharees = await _shareBatchLegacy(
- collectionID,
- encryptedKeys,
- shareRole,
- sharees,
+ sharees = await collectionShareGateway.shareBatch(
+ collectionID: collectionID,
+ encryptedKeys: encryptedKeys,
+ role: shareRole,
);
+ _cacheSharees(_collectionIDToCollections[collectionID]!, sharees);
+ RemoteSyncService.instance.sync(silently: true).ignore();
}
return sharees;
} on DioException catch (error) {
@@ -929,26 +912,6 @@ class CollectionsService {
}
}
- Future<List<User>> _shareBatchLegacy(
- int collectionID,
- Map<String, String> encryptedKeys,
- String role,
- List<User> initialSharees,
- ) async {
- var sharees = initialSharees;
- for (final entry in encryptedKeys.entries) {
- sharees = await collectionShareGateway.share(
- collectionID: collectionID,
- email: entry.key,
- encryptedKey: entry.value,
- role: role,
- );
- _cacheSharees(_collectionIDToCollections[collectionID]!, sharees);
- RemoteSyncService.instance.sync(silently: true).ignore();
- }
- return sharees;
- }
-
Future<List<User>> unshare(int collectionID, String email) async {
try {
final sharees = await collectionShareGateway.unshare(
diff --git a/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart b/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart
index 69caf47f56..f4d5bcc913 100644
--- a/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart
+++ b/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart
@@ -7,6 +7,7 @@ import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:photos/core/configuration.dart';
import "package:photos/core/errors.dart";
+import "package:photos/core/network/api_response.dart";
import 'package:photos/db/files_db.dart';
import 'package:photos/gateways/collections/models/create_request.dart';
import "package:photos/models/api/collection/user.dart";
@@ -246,6 +247,95 @@ class CollectionActions {
}
}
+ Future<Set<String>> addEmailsToCollections(
+ BuildContext context,
+ List<Collection> collections,
+ Set<String> emails,
+ CollectionParticipantRole role,
+ ) async {
+ final validEmails = <String>{};
+ final ownEmail = Configuration.instance.getEmail()?.trim().toLowerCase();
+ for (final email in emails) {
+ if (!context.mounted) return {};
+ if (!isValidEmail(email)) {
+ await showErrorDialog(
+ context,
+ context.strings.invalidEmailAddress,
+ context.strings.enterValidEmail,
+ );
+ } else if (email == ownEmail) {
+ await showErrorDialog(
+ context,
+ context.strings.oops,
+ context.strings.youCannotShareWithYourself,
+ );
+ } else {
+ validEmails.add(email);
+ }
+ }
+
+ final publicKeys = <String, String>{};
+ try {
+ final keys = await UserService.instance.getPublicKeys(validEmails);
+ for (final entry in keys.entries) {
+ if (!context.mounted) return {};
+ final publicKey = entry.value;
+ if (publicKey == null || publicKey.isEmpty) {
+ await showInviteDialog(context, entry.key);
+ } else {
+ publicKeys[entry.key] = publicKey;
+ }
+ }
+ } catch (e) {
+ logger.severe("Failed to get public keys", e);
+ if (context.mounted) {
+ await showGenericErrorDialog(context: context, error: e);
+ }
+ return {};
+ }
+ if (publicKeys.isEmpty) return {};
+
+ try {
+ for (final collection in collections) {
+ if (!context.mounted) return {};
+ final sharees = await collectionsService.shareBatch(
+ collection.id,
+ publicKeys,
+ role,
+ );
+ collection.updateSharees(sharees);
+ }
+ return publicKeys.keys.toSet();
+ } catch (e) {
+ if (!context.mounted) return {};
+ if (e is UnexpectedApiResponseException &&
+ e.response?.statusCode == 404) {
+ final sharedEmails = <String>{};
+ for (final email in publicKeys.keys) {
+ var result = false;
+ for (final collection in collections) {
+ if (!context.mounted) return sharedEmails;
+ result = await addEmailToCollection(
+ context,
+ collection,
+ email,
+ role,
+ );
+ }
+ if (result) sharedEmails.add(email);
+ }
+ return sharedEmails;
+ }
+ if (e is SharingNotPermittedForFreeAccountsError) {
+ await _showUnSupportedAlert(context);
+ } else {
+ logger.severe("Failed to share collection", e);
+ await showGenericErrorDialog(context: context, error: e);
+ }
+ return {};
+ }
+ }
+
Future<bool> addEmailToCollection(
BuildContext context,
Collection collection,
@@ -316,7 +406,7 @@ class CollectionActions {
return false;
} else {
try {
- final newSharees = await CollectionsService.instance.share(
+ final newSharees = await collectionsService.share(
collection.id,
email,
publicKey,
diff --git a/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart b/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart
index 10e14e8f1d..5a1a7f8878 100644
--- a/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart
+++ b/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart
@@ -247,36 +247,7 @@ class _AddParticipantPage extends State<AddParticipantPage> {
count: _selectedEmails.length,
),
isDisabled: _selectedEmails.isEmpty,
- onTap: () async {
- final results = <bool>[];
- final collections = widget.collections;
-
- for (String email in _selectedEmails) {
- bool result = false;
- for (Collection collection in collections) {
- result = await collectionActions.addEmailToCollection(
- context,
- collection,
- email,
- CollectionParticipantRole.collaborator,
- );
- }
- results.add(result);
- }
-
- final noOfSuccessfullAdds = results.where((e) => e).length;
- if (!mounted) return;
- showToast(
- context,
- context.strings.collaboratorsSuccessfullyAdded(
- count: noOfSuccessfullAdds,
- ),
- );
-
- if (!results.any((e) => e == false) && mounted) {
- Navigator.of(context).pop(true);
- }
- },
+ onTap: () => _shareSelected(CollectionParticipantRole.collaborator),
),
);
}
@@ -287,36 +258,7 @@ class _AddParticipantPage extends State<AddParticipantPage> {
size: ButtonComponentSize.large,
label: context.strings.addViewers(count: _selectedEmails.length),
isDisabled: _selectedEmails.isEmpty,
- onTap: () async {
- final results = <bool>[];
- final collections = widget.collections;
-
- for (final email in _selectedEmails) {
- bool result = false;
- for (final collection in collections) {
- result = await collectionActions.addEmailToCollection(
- context,
- collection,
- email,
- CollectionParticipantRole.viewer,
- );
- }
- results.add(result);
- }
-
- final noOfSuccessfullAdds = results.where((e) => e).length;
- if (!mounted) return;
- showToast(
- context,
- context.strings.viewersSuccessfullyAdded(
- count: noOfSuccessfullAdds,
- ),
- );
-
- if (!results.any((e) => e == false) && mounted) {
- Navigator.of(context).pop(true);
- }
- },
+ onTap: () => _shareSelected(CollectionParticipantRole.viewer),
),
);
}
@@ -329,40 +271,41 @@ class _AddParticipantPage extends State<AddParticipantPage> {
size: ButtonComponentSize.large,
label: context.strings.addAdmins(count: _selectedEmails.length),
isDisabled: _selectedEmails.isEmpty,
- onTap: () async {
- final results = <bool>[];
- final collections = widget.collections;
-
- for (final email in _selectedEmails) {
- bool result = false;
- for (final collection in collections) {
- result = await collectionActions.addEmailToCollection(
- context,
- collection,
- email,
- CollectionParticipantRole.admin,
- );
- }
- results.add(result);
- }
-
- final successful = results.where((e) => e).length;
- if (!mounted) return;
- showToast(
- context,
- context.strings.adminsSuccessfullyAdded(count: successful),
- );
-
- if (!results.any((e) => e == false) && mounted) {
- Navigator.of(context).pop(true);
- }
- },
+ onTap: () => _shareSelected(CollectionParticipantRole.admin),
),
);
}
return widgets;
}
+ Future<void> _shareSelected(CollectionParticipantRole role) async {
+ final emails = _selectedEmails
+ .map((email) => email.trim().toLowerCase())
+ .toSet();
+ final collections = List<Collection>.of(widget.collections);
+ final sharedEmails = await collectionActions.addEmailsToCollections(
+ context,
+ collections,
+ emails,
+ role,
+ );
+ if (!mounted) return;
+ final count = sharedEmails.length;
+ final message = switch (role) {
+ CollectionParticipantRole.viewer =>
+ context.strings.viewersSuccessfullyAdded(count: count),
+ CollectionParticipantRole.collaborator =>
+ context.strings.collaboratorsSuccessfullyAdded(count: count),
+ CollectionParticipantRole.admin =>
+ context.strings.adminsSuccessfullyAdded(count: count),
+ _ => throw ArgumentError.value(role, "role"),
+ };
+ showToast(context, message);
+ if (count == emails.length) {
+ Navigator.of(context).pop(true);
+ }
+ }
+
void clearFocus() {
_clearEmailField();
textFieldFocusNode.unfocus();
@@ -410,14 +353,12 @@ class _AddParticipantPage extends State<AddParticipantPage> {
if (!_emailIsValid) {
return;
}
- final result = await collectionActions.doesEmailHaveAccount(
- context,
- _newEmail,
- );
- if (result && mounted) {
+ final email = _newEmail;
+ final result = await collectionActions.doesEmailHaveAccount(context, email);
+ if (result && mounted && _newEmail == email) {
setState(() {
for (var suggestedUser in _suggestedUsers) {
- if (suggestedUser.email == _newEmail) {
+ if (suggestedUser.email == email) {
_selectedEmails.add(suggestedUser.email);
_clearEmailField();
textFieldFocusNode.unfocus();
@@ -425,8 +366,8 @@ class _AddParticipantPage extends State<AddParticipantPage> {
return;
}
}
- _suggestedUsers.insert(0, UserSuggestion(_newEmail));
- _selectedEmails.add(_newEmail);
+ _suggestedUsers.insert(0, UserSuggestion(email));
+ _selectedEmails.add(email);
_clearEmailField();
textFieldFocusNode.unfocus();
});
diff --git a/mobile/apps/photos/test/ui/actions/collection/collection_sharing_actions_test.dart b/mobile/apps/photos/test/ui/actions/collection/collection_sharing_actions_test.dart
new file mode 100644
index 0000000000..be765cda09
--- /dev/null
+++ b/mobile/apps/photos/test/ui/actions/collection/collection_sharing_actions_test.dart
@@ -0,0 +1,467 @@
+import "package:dio/dio.dart";
+import "package:ente_strings/ente_strings.dart";
+import "package:flutter/material.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:package_info_plus/package_info_plus.dart";
+import "package:photos/core/configuration.dart";
+import "package:photos/core/errors.dart";
+import "package:photos/core/network/api_response.dart";
+import "package:photos/ente_theme_data.dart";
+import "package:photos/models/api/collection/user.dart";
+import "package:photos/models/collection/collection.dart";
+import "package:photos/service_locator.dart";
+import "package:photos/services/collections_service.dart";
+import "package:photos/ui/actions/collection/collection_sharing_actions.dart";
+import "package:shared_preferences/shared_preferences.dart";
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late _KeyRequests keys;
+
+ setUpAll(() async {
+ SharedPreferences.setMockInitialValues({
+ "email": "[email protected]",
+ "remote_flags": "{}",
+ });
+ final preferences = await SharedPreferences.getInstance();
+ final dio = Dio();
+ dio.interceptors.add(
+ InterceptorsWrapper(
+ onRequest: (options, handler) {
+ keys.respond(options, handler);
+ },
+ ),
+ );
+ ServiceLocator.instance.init(
+ preferences,
+ dio,
+ Dio(),
+ Dio(),
+ PackageInfo(
+ appName: "Photos",
+ packageName: "photos",
+ version: "1.0.0",
+ buildNumber: "1",
+ ),
+ );
+ // These actions only need Configuration's preferences-backed email.
+ // The remaining platform initialization is unavailable in widget tests.
+ try {
+ await Configuration.instance.init(preferences);
+ } catch (_) {}
+ // Construct the flag refresher outside the widget-test fake clock.
+ expect(flagService.internalUser, isTrue);
+ });
+
+ setUp(() async {
+ keys = _KeyRequests();
+ await localSettings.setInternalUserDisabled(false);
+ });
+
+ for (final role in [
+ CollectionParticipantRole.viewer,
+ CollectionParticipantRole.collaborator,
+ CollectionParticipantRole.admin,
+ ]) {
+ testWidgets("shares both albums with both recipients as ${role.name}", (
+ tester,
+ ) async {
+ final context = await _pumpContext(tester);
+ final service = _SharingService();
+ final albums = [_Album(1), _Album(2)];
+ final emails = {"${role.name}[email protected]", "${role.name}[email protected]"};
+ albums.first.sharees = [User(id: 1, email: emails.first, role: "VIEWER")];
+
+ final result = CollectionActions(
+ service,
+ ).addEmailsToCollections(context, albums, emails, role);
+ await tester.pumpAndSettle();
+
+ expect(await result, emails);
+ expect(keys.requests.map((request) => request.path), [
+ "/users/public-keys",
+ ]);
+ expect(service.calls.map((call) => call.$1), [1, 2]);
+ for (final call in service.calls) {
+ expect(call.$2.keys, unorderedEquals(emails));
+ expect(call.$3, role);
+ }
+ for (final album in albums) {
+ expect(
+ album.sharees.map((user) => user.email),
+ unorderedEquals(emails),
+ );
+ expect(
+ album.sharees.every((user) => user.role == role.toStringVal()),
+ isTrue,
+ );
+ }
+ });
+ }
+
+ testWidgets(
+ "batch 404 resolves individually and excludes the missing account",
+ (tester) async {
+ final context = await _pumpContext(tester);
+ final service = _SharingService();
+ keys.missing.add("[email protected]");
+ final result = CollectionActions(service).addEmailsToCollections(
+ context,
+ [_Album(1)],
+ CollectionParticipantRole.viewer,
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text(context.strings.inviteToEnte), findsOneWidget);
+ expect(service.calls, isEmpty);
+ Navigator.of(context).pop();
+ await tester.pumpAndSettle();
+
+ expect(await result, {"[email protected]"});
+ expect(service.calls.single.$2.keys, ["[email protected]"]);
+ expect(keys.requests.map((request) => request.path), [
+ "/users/public-keys",
+ "/users/public-key",
+ "/users/public-key",
+ ]);
+ },
+ );
+
+ testWidgets("non-internal users use batch key lookup", (tester) async {
+ await localSettings.setInternalUserDisabled(true);
+ expect(flagService.internalUser, isFalse);
+ final context = await _pumpContext(tester);
+ final emails = {"[email protected]", "[email protected]"};
+ final result = CollectionActions(_SharingService()).addEmailsToCollections(
+ context,
+ [_Album(1)],
+ emails,
+ CollectionParticipantRole.viewer,
+ );
+ await tester.pumpAndSettle();
+
+ expect(await result, emails);
+ expect(keys.requests.map((request) => request.path), [
+ "/users/public-keys",
+ ]);
+ });
+
+ testWidgets("unavailable batch endpoint falls back to single-key lookups", (
+ tester,
+ ) async {
+ await localSettings.setInternalUserDisabled(true);
+ keys.batchUnavailable = true;
+ final context = await _pumpContext(tester);
+ final emails = {"[email protected]", "[email protected]"};
+ final result = CollectionActions(_SharingService()).addEmailsToCollections(
+ context,
+ [_Album(1)],
+ emails,
+ CollectionParticipantRole.viewer,
+ );
+ await tester.pumpAndSettle();
+
+ expect(await result, emails);
+ expect(keys.requests.map((request) => request.path), [
+ "/users/public-keys",
+ "/users/public-key",
+ "/users/public-key",
+ ]);
+ });
+
+ for (final failedAlbum in [1, 2]) {
+ testWidgets(
+ "batch failure on album $failedAlbum returns no success count",
+ (tester) async {
+ final context = await _pumpContext(tester);
+ final service = _SharingService()
+ ..errors[failedAlbum] = StateError("share failed");
+ final albums = [_Album(1), _Album(2)];
+ final emails = {
+ for (var index = 0; index < 11; index++)
+ "batch${failedAlbum}[email protected]",
+ };
+ final result = CollectionActions(service).addEmailsToCollections(
+ context,
+ albums,
+ emails,
+ CollectionParticipantRole.collaborator,
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text(context.strings.error), findsOneWidget);
+ Navigator.of(context).pop();
+ await tester.pumpAndSettle();
+
+ expect(await result, isEmpty);
+ expect(service.calls, hasLength(failedAlbum));
+ expect(service.singleCalls, isEmpty);
+ expect(albums.first.sharees, hasLength(failedAlbum == 1 ? 0 : 11));
+ expect(albums.last.sharees, isEmpty);
+ expect(
+ keys.requests.map(
+ (request) => (request.data["emails"] as List).length,
+ ),
+ [10, 1],
+ );
+ },
+ );
+ }
+
+ for (final upgradeRequired in [false, true]) {
+ testWidgets(
+ "legacy fallback continues after ${upgradeRequired ? 'subscription' : 'recipient'} failure",
+ (tester) async {
+ final context = await _pumpContext(tester);
+ final emails = {
+ for (var index = 0; index < 3; index++)
+ "legacy${upgradeRequired}[email protected]",
+ };
+ final service = _SharingService()
+ ..errors[1] = _unexpectedResponse(404)
+ ..singleErrors[(1, emails.elementAt(1))] = upgradeRequired
+ ? SharingNotPermittedForFreeAccountsError()
+ : StateError("share failed");
+ final album = _Album(1);
+ final result = CollectionActions(service).addEmailsToCollections(
+ context,
+ [album],
+ emails,
+ CollectionParticipantRole.collaborator,
+ );
+ await tester.pumpAndSettle();
+
+ expect(
+ find.text(
+ upgradeRequired
+ ? context.strings.subscribeToEnableSharing
+ : context.strings.error,
+ ),
+ findsOneWidget,
+ );
+ Navigator.of(context).pop();
+ await tester.pumpAndSettle();
+
+ expect(await result, {emails.first, emails.last});
+ expect(service.calls, hasLength(1));
+ expect(service.singleCalls.map((call) => call.$2), emails.toList());
+ expect(album.sharees.map((user) => user.email), [
+ emails.first,
+ emails.last,
+ ]);
+ expect(
+ service.singleCalls.every(
+ (call) => call.$3 == CollectionParticipantRole.collaborator,
+ ),
+ isTrue,
+ );
+ },
+ );
+ }
+
+ testWidgets(
+ "legacy fallback retains recipient-first album order and results",
+ (tester) async {
+ final context = await _pumpContext(tester);
+ final emails = {"[email protected]", "[email protected]"};
+ final service = _SharingService()
+ ..errors[1] = _unexpectedResponse(404)
+ ..singleErrors[(1, emails.first)] = StateError("share failed");
+ final albums = [_Album(1), _Album(2)];
+ final result = CollectionActions(service).addEmailsToCollections(
+ context,
+ albums,
+ emails,
+ CollectionParticipantRole.viewer,
+ );
+ await tester.pumpAndSettle();
+ expect(find.text(context.strings.error), findsOneWidget);
+ Navigator.of(context).pop();
+ await tester.pumpAndSettle();
+
+ // The previous picker counted the last album's result for each recipient.
+ expect(await result, emails);
+ expect(service.singleCalls.map((call) => (call.$1, call.$2)), [
+ (1, emails.first),
+ (2, emails.first),
+ (1, emails.last),
+ (2, emails.last),
+ ]);
+ expect(service.calls, hasLength(1));
+ expect(albums.first.sharees.map((user) => user.email), [emails.last]);
+ expect(albums.last.sharees.map((user) => user.email), emails.toList());
+ },
+ );
+
+ for (final unexpected in [false, true]) {
+ testWidgets("does not fall back for ${unexpected ? '503' : 'API 404'}", (
+ tester,
+ ) async {
+ final context = await _pumpContext(tester);
+ final request = RequestOptions(path: "/collections/share/batch");
+ final service = _SharingService()
+ ..errors[1] = unexpected
+ ? _unexpectedResponse(503)
+ : DioException(
+ requestOptions: request,
+ response: Response<dynamic>(
+ requestOptions: request,
+ statusCode: 404,
+ data: {"code": "NOT_FOUND"},
+ ),
+ type: DioExceptionType.badResponse,
+ );
+ final result = CollectionActions(service).addEmailsToCollections(
+ context,
+ [_Album(1)],
+ CollectionParticipantRole.viewer,
+ );
+ await tester.pumpAndSettle();
+ expect(find.text(context.strings.error), findsOneWidget);
+ Navigator.of(context).pop();
+ await tester.pumpAndSettle();
+
+ expect(await result, isEmpty);
+ expect(service.singleCalls, isEmpty);
+ });
+ }
+
+ testWidgets("subscription failures show the existing upgrade prompt", (
+ tester,
+ ) async {
+ final context = await _pumpContext(tester);
+ final service = _SharingService()
+ ..errors[1] = SharingNotPermittedForFreeAccountsError();
+ final result = CollectionActions(service).addEmailsToCollections(
+ context,
+ [_Album(1)],
+ CollectionParticipantRole.viewer,
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text(context.strings.subscribeToEnableSharing), findsOneWidget);
+ expect(find.text(context.strings.subscribe), findsOneWidget);
+ Navigator.of(context).pop();
+ await tester.pumpAndSettle();
+ expect(await result, isEmpty);
+ });
+}
+
+UnexpectedApiResponseException _unexpectedResponse(int status) {
+ final request = RequestOptions(path: "/collections/share/batch");
+ return UnexpectedApiResponseException(
+ request,
+ Response<String>(
+ requestOptions: request,
+ statusCode: status,
+ data: "endpoint unavailable",
+ ),
+ DioExceptionType.badResponse,
+ );
+}
+
+Future<BuildContext> _pumpContext(WidgetTester tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: lightThemeData,
+ localizationsDelegates: StringsLocalizations.localizationsDelegates,
+ supportedLocales: StringsLocalizations.supportedLocales,
+ home: const Scaffold(body: SizedBox(key: ValueKey("host"))),
+ ),
+ );
+ return tester.element(find.byKey(const ValueKey("host")));
+}
+
+class _KeyRequests {
+ final requests = <RequestOptions>[];
+ final missing = <String>{};
+ bool batchUnavailable = false;
+
+ void respond(RequestOptions options, RequestInterceptorHandler handler) {
+ requests.add(options);
+ final batch = options.path == "/users/public-keys";
+ final emails = batch
+ ? (options.data["emails"] as List).cast<String>()
+ : [options.queryParameters["email"] as String];
+ if ((batch && batchUnavailable) || emails.any(missing.contains)) {
+ handler.reject(
+ DioException(
+ requestOptions: options,
+ response: Response<dynamic>(
+ requestOptions: options,
+ statusCode: 404,
+ data: <String, dynamic>{},
+ ),
+ type: DioExceptionType.badResponse,
+ ),
+ );
+ } else {
+ handler.resolve(
+ Response<dynamic>(
+ requestOptions: options,
+ statusCode: 200,
+ data: batch
+ ? {"publicKeys": emails.map((email) => "key-$email").toList()}
+ : {"publicKey": "key-${emails.single}"},
+ ),
+ );
+ }
+ }
+}
+
+class _SharingService extends Fake implements CollectionsService {
+ final calls = <(int, Map<String, String>, CollectionParticipantRole)>[];
+ final errors = <int, Object>{};
+ final singleCalls = <(int, String, CollectionParticipantRole)>[];
+ final singleErrors = <(int, String), Object>{};
+ final _sharees = <int, List<User>>{};
+
+ @override
+ Future<List<User>> shareBatch(
+ int collectionID,
+ Map<String, String> publicKeys,
+ CollectionParticipantRole role,
+ ) async {
+ calls.add((collectionID, Map.of(publicKeys), role));
+ final error = errors[collectionID];
+ if (error != null) throw error;
+ final emails = publicKeys.keys.toList();
+ return [
+ for (var index = 0; index < emails.length; index++)
+ User(id: index + 1, email: emails[index], role: role.toStringVal()),
+ ];
+ }
+
+ @override
+ Future<List<User>> share(
+ int collectionID,
+ String email,
+ String publicKey,
+ CollectionParticipantRole role,
+ ) async {
+ singleCalls.add((collectionID, email, role));
+ final error = singleErrors[(collectionID, email)];
+ if (error != null) throw error;
+ final sharees = _sharees.putIfAbsent(collectionID, () => []);
+ sharees.add(
+ User(id: sharees.length + 1, email: email, role: role.toStringVal()),
+ );
+ return List.of(sharees);
+ }
+}
+
+class _Album extends Fake implements Collection {
+ _Album(this.id);
+
+ @override
+ final int id;
+
+ @override
+ List<User> sharees = [];
+
+ @override
+ void updateSharees(List<User> users) => sharees = users;
+}