Skip to content

armgit / ente

Public Imported from GitHub
0

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

Implement native family management flow

ashilkne0e14de8c830
diff --git a/mobile/apps/photos/lib/gateways/users/users_gateway.dart b/mobile/apps/photos/lib/gateways/users/users_gateway.dart
index f31824ba63..61bb21a1ef 100644
--- a/mobile/apps/photos/lib/gateways/users/users_gateway.dart
+++ b/mobile/apps/photos/lib/gateways/users/users_gateway.dart
@@ -192,8 +192,94 @@ class UsersGateway {
/// Leave the family plan.
///
/// Endpoint: DELETE /family/leave
- Future<void> leaveFamilyPlan() async {
- await _enteDio.delete("/family/leave");
+ ///
+ /// Family management endpoints expect the dedicated `FAMILIES` JWT, not the
+ /// app session token.
+ Future<void> leaveFamilyPlan({
+ String? authToken,
+ }) async {
+ final familiesToken = authToken ?? await getFamiliesAuthToken();
+ await _enteDio.delete(
+ "/family/leave",
+ options: _familyAuthOptions(familiesToken),
+ );
+ }
+
+ /// Create a family with the current user as the admin.
+ ///
+ /// Endpoint: POST /family/create
+ Future<void> createFamily({
+ String? authToken,
+ }) async {
+ final familiesToken = authToken ?? await getFamiliesAuthToken();
+ await _enteDio.post(
+ "/family/create",
+ options: _familyAuthOptions(familiesToken),
+ );
+ }
+
+ /// Invite a user to join the current user's family.
+ ///
+ /// Endpoint: POST /family/add-member
+ Future<void> inviteFamilyMember({
+ required String email,
+ String? authToken,
+ }) async {
+ final familiesToken = authToken ?? await getFamiliesAuthToken();
+ await _enteDio.post(
+ "/family/add-member",
+ data: {
+ "email": email,
+ },
+ options: _familyAuthOptions(familiesToken),
+ );
+ }
+
+ /// Remove an active family member.
+ ///
+ /// Endpoint: DELETE /family/remove-member/:id
+ Future<void> removeFamilyMember(
+ String id, {
+ String? authToken,
+ }) async {
+ final familiesToken = authToken ?? await getFamiliesAuthToken();
+ await _enteDio.delete(
+ "/family/remove-member/$id",
+ options: _familyAuthOptions(familiesToken),
+ );
+ }
+
+ /// Revoke a pending family invite.
+ ///
+ /// Endpoint: DELETE /family/revoke-invite/:id
+ Future<void> revokeFamilyInvite(
+ String id, {
+ String? authToken,
+ }) async {
+ final familiesToken = authToken ?? await getFamiliesAuthToken();
+ await _enteDio.delete(
+ "/family/revoke-invite/$id",
+ options: _familyAuthOptions(familiesToken),
+ );
+ }
+
+ /// Update a family member's storage limit.
+ ///
+ /// Endpoint: PUT /family/modify-storage
+ Future<void> updateFamilyMemberStorage({
+ required String id,
+ int? storageLimit,
+ String? authToken,
+ }) async {
+ final familiesToken = authToken ?? await getFamiliesAuthToken();
+ await _enteDio.put(
+ "/family/modify-storage",
+ data: {
+ "id": id,
+ "storageLimit": storageLimit,
+ },
+ options: _familyAuthOptions(familiesToken),
+ );
}
/// Get the families portal token and URL.
@@ -208,6 +294,23 @@ class UsersGateway {
return response.data as Map<String, dynamic>;
}
+ Future<String> getFamiliesAuthToken() async {
+ final responseData = await getFamiliesToken();
+ final familiesToken = responseData["familiesToken"];
+ if (familiesToken is! String || familiesToken.isEmpty) {
+ throw StateError("Missing familiesToken in /users/families-token");
+ }
+ return familiesToken;
+ }
+
+ Options _familyAuthOptions(String familiesToken) {
+ return Options(
+ headers: {
+ "X-Auth-Token": familiesToken,
+ },
+ );
+ }
+
// ============================================================
// Key Attributes & Recovery
// ============================================================
diff --git a/mobile/apps/photos/lib/l10n/intl_en.arb b/mobile/apps/photos/lib/l10n/intl_en.arb
index ad45952078..8c28845fd8 100644
--- a/mobile/apps/photos/lib/l10n/intl_en.arb
+++ b/mobile/apps/photos/lib/l10n/intl_en.arb
@@ -667,6 +667,149 @@
}
},
"familyPlans": "Family plans",
+ "family": "Family",
+ "designedForFamilies": "Designed for families",
+ "shareYourSubscription": "Share your subscription with loved ones",
+ "shareStorageWith5Members": "Share storage with 5 members",
+ "privateSpaceForEveryMember": "Private space for every member",
+ "feedToEngageWithFamily": "A feed to engage with family",
+ "plansStartAt": "Plans start at {price}/month",
+ "@plansStartAt": {
+ "placeholders": {
+ "price": {
+ "type": "String",
+ "example": "$1.99"
+ }
+ }
+ },
+ "viewPlans": "View plans",
+ "bringYourFamilyAlong": "Bring your family along",
+ "yourPlanSupportsFamily": "Your plan already supports a family",
+ "addUpTo5MembersFree": "Add up to 5 members free",
+ "addFamilyMember": "Add family member",
+ "addMember": "Add member",
+ "inviteMembers": "Invite members",
+ "enterEmailAddresses": "Enter their email addresses. They need an Ente account.",
+ "emailAddress": "Email address",
+ "sendInvites": "Send invites",
+ "sendCountInvites": "{count, plural, =0 {Send invites} =1 {Send 1 invite} other {Send {count} invites}}",
+ "@sendCountInvites": {
+ "placeholders": {
+ "count": {
+ "type": "int",
+ "example": "2"
+ }
+ }
+ },
+ "enterAnEmailAddress": "Enter an email address",
+ "enterAValidEmailAddress": "Enter a valid email address",
+ "alreadyAdded": "Already added",
+ "thisUserIsNotOnEnte": "This user is not on Ente",
+ "emailNeedsEnteAccountForFamily": "{email} does not have an Ente account.\n\nSend them an invite and add them to your family once they've created an account on Ente.",
+ "@emailNeedsEnteAccountForFamily": {
+ "placeholders": {
+ "email": {
+ "type": "String",
+ "example": "[email protected]"
+ }
+ }
+ },
+ "invitesSent": "Invites sent",
+ "failedToInvite": "Couldn't invite {email}",
+ "@failedToInvite": {
+ "placeholders": {
+ "email": {
+ "type": "String",
+ "example": "[email protected]"
+ }
+ }
+ },
+ "failedToInviteCount": "Couldn't invite {count} members",
+ "@failedToInviteCount": {
+ "placeholders": {
+ "count": {
+ "type": "int",
+ "example": "2"
+ }
+ }
+ },
+ "storageUsedOfTotal": "{used} of {total} used",
+ "@storageUsedOfTotal": {
+ "placeholders": {
+ "used": {
+ "type": "String",
+ "example": "67 GB"
+ },
+ "total": {
+ "type": "String",
+ "example": "200 GB"
+ }
+ }
+ },
+ "members": "Members",
+ "pending": "Pending",
+ "closeFamilyPlan": "Close family plan",
+ "closeFamilyConfirmTitle": "Close family plan?",
+ "closeFamilyConfirmBody": "All members will lose access to shared storage. This cannot be undone.",
+ "editStorageLimit": "Edit storage limit",
+ "noLimitSet": "No limit set",
+ "removeFromFamily": "Remove from family",
+ "removeMemberConfirmTitle": "Remove member?",
+ "removeMemberConfirmBody": "{email} will lose access to shared storage.",
+ "@removeMemberConfirmBody": {
+ "placeholders": {
+ "email": {
+ "type": "String",
+ "example": "[email protected]"
+ }
+ }
+ },
+ "resendInvite": "Resend invite",
+ "revokeInviteConfirmTitle": "Revoke invite?",
+ "revokeInviteConfirmBody": "The invitation to {email} will be cancelled.",
+ "@revokeInviteConfirmBody": {
+ "placeholders": {
+ "email": {
+ "type": "String",
+ "example": "[email protected]"
+ }
+ }
+ },
+ "revoke": "Revoke",
+ "inviteResent": "Invite resent",
+ "memberStorageUsed": "{amount} used",
+ "@memberStorageUsed": {
+ "placeholders": {
+ "amount": {
+ "type": "String",
+ "example": "20 GB"
+ }
+ }
+ },
+ "storageLimit": "Storage limit",
+ "usingStorage": "Using {amount}",
+ "@usingStorage": {
+ "placeholders": {
+ "amount": {
+ "type": "String",
+ "example": "20 GB"
+ }
+ }
+ },
+ "storageLimitExplanation": "Set the maximum storage this member can use. They will not be able to upload once the limit is reached.",
+ "limit": "Limit",
+ "noLimit": "No limit",
+ "currentUsageNote": "Current usage: {amount}. Set to 0 for no limit.",
+ "@currentUsageNote": {
+ "placeholders": {
+ "amount": {
+ "type": "String",
+ "example": "20 GB"
+ }
+ }
+ },
+ "leaveFamilyConfirmTitle": "Leave family plan?",
+ "leaveFamilyConfirmBody": "You will lose access to shared storage.",
"referrals": "Referrals",
"notifications": "Notifications",
"sharedPhotoNotifications": "New shared photos and albums",
diff --git a/mobile/apps/photos/lib/models/user_details.dart b/mobile/apps/photos/lib/models/user_details.dart
index 09ebe5cdd0..4f7e02eeda 100644
--- a/mobile/apps/photos/lib/models/user_details.dart
+++ b/mobile/apps/photos/lib/models/user_details.dart
@@ -5,6 +5,29 @@ import 'package:collection/collection.dart';
import "package:photos/gateways/billing/models/subscription.dart";
import "package:photos/gateways/storage_bonus/models/bonus.dart";
+enum FamilyMemberStatus {
+ self("SELF"),
+ closed("CLOSED"),
+ invited("INVITED"),
+ accepted("ACCEPTED"),
+ declined("DECLINED"),
+ revoked("REVOKED"),
+ removed("REMOVED"),
+ left("LEFT"),
+ unknown("UNKNOWN");
+
+ const FamilyMemberStatus(this.serverValue);
+
+ final String serverValue;
+
+ static FamilyMemberStatus fromServerValue(String? value) {
+ return FamilyMemberStatus.values.firstWhereOrNull(
+ (status) => status.serverValue == value,
+ ) ??
+ FamilyMemberStatus.accepted;
+ }
+}
+
class UserDetails {
final String email;
final int usage;
@@ -36,13 +59,33 @@ class UserDetails {
return bonusData?.getAddOnBonuses().isNotEmpty ?? false;
}
+ FamilyMember? currentFamilyMember() {
+ if (familyData?.members == null) {
+ return null;
+ }
+ return familyData!.members!
+ .firstWhereOrNull((member) => member.email.trim() == email.trim());
+ }
+
bool isFamilyAdmin() {
assert(isPartOfFamily(), "verify user is part of family before calling");
- final FamilyMember currentUserMember = familyData!.members!
- .firstWhere((element) => element.email.trim() == email.trim());
+ final FamilyMember currentUserMember = currentFamilyMember()!;
return currentUserMember.isAdmin;
}
+ bool hasConfiguredFamily() {
+ final currentUserMember = currentFamilyMember();
+ if (currentUserMember == null) {
+ return false;
+ }
+ if (!currentUserMember.isAdmin) {
+ return true;
+ }
+ return familyData!.members!.any(
+ (member) => member.email.trim() != email.trim(),
+ );
+ }
+
// getFamilyOrPersonalUsage will return total usage for family if user
// belong to family group. Otherwise, it will return storage consumed by
// current user
@@ -69,8 +112,7 @@ class UserDetails {
// has set the storage limit for the user.
int? familyMemberStorageLimit() {
if (isPartOfFamily()) {
- final FamilyMember? currentUserMember = familyData!.members!
- .firstWhereOrNull((element) => element.email.trim() == email.trim());
+ final FamilyMember? currentUserMember = currentFamilyMember();
return currentUserMember?.storageLimit;
}
return null;
@@ -121,6 +163,7 @@ class FamilyMember {
final int usage;
final String id;
final bool isAdmin;
+ final FamilyMemberStatus status;
final int? storageLimit;
FamilyMember(
@@ -128,15 +171,23 @@ class FamilyMember {
this.usage,
this.id,
this.isAdmin,
+ this.status,
this.storageLimit,
);
+ bool get isPending => status == FamilyMemberStatus.invited;
+
+ bool get isActive =>
+ status == FamilyMemberStatus.accepted ||
+ status == FamilyMemberStatus.self;
+
factory FamilyMember.fromMap(Map<String, dynamic> map) {
return FamilyMember(
(map['email'] ?? '') as String,
- map['usage'] as int,
+ (map['usage'] ?? 0) as int,
map['id'] as String,
map['isAdmin'] as bool,
+ FamilyMemberStatus.fromServerValue(map['status'] as String?),
map['storageLimit'] as int?,
);
}
@@ -147,6 +198,7 @@ class FamilyMember {
'usage': usage,
'id': id,
'isAdmin': isAdmin,
+ 'status': status.serverValue,
'storageLimit': storageLimit,
};
}
@@ -196,15 +248,21 @@ class FamilyData {
// Storage available based on the family plan
final int storage;
final int expiryTime;
+ final int adminBonus;
FamilyData(
this.members,
this.storage,
this.expiryTime,
+ this.adminBonus,
);
int getTotalUsage() {
- return members!.map((e) => e.usage).toList().sum;
+ return members
+ ?.where((member) => member.isActive)
+ .map((e) => e.usage)
+ .sum ??
+ 0;
}
FamilyMember? getMemberByID(String id) {
@@ -221,6 +279,7 @@ class FamilyData {
members,
map['storage'] as int,
map['expiryTime'] as int,
+ (map['adminBonus'] ?? 0) as int,
);
}
@@ -229,6 +288,7 @@ class FamilyData {
'members': members?.map((x) => x.toMap()).toList(),
'storage': storage,
'expiryTime': expiryTime,
+ 'adminBonus': adminBonus,
};
}
diff --git a/mobile/apps/photos/lib/services/account/billing_service.dart b/mobile/apps/photos/lib/services/account/billing_service.dart
index 25710509d4..391209ffca 100644
--- a/mobile/apps/photos/lib/services/account/billing_service.dart
+++ b/mobile/apps/photos/lib/services/account/billing_service.dart
@@ -1,5 +1,6 @@
import 'dart:io';
+import 'package:ente_pure_utils/ente_pure_utils.dart';
import 'package:flutter/material.dart';
// import 'package:flutter/foundation.dart';
// import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
@@ -8,11 +9,9 @@ import 'package:logging/logging.dart';
import "package:photos/gateways/billing/billing_gateway.dart";
import 'package:photos/gateways/billing/models/billing_plan.dart';
import 'package:photos/gateways/billing/models/subscription.dart';
-import "package:photos/generated/l10n.dart";
import 'package:photos/models/user_details.dart';
import "package:photos/service_locator.dart";
-import 'package:photos/services/account/user_service.dart';
-import 'package:photos/ui/common/web_page.dart';
+import 'package:photos/ui/family/family_plan_page.dart';
import 'package:photos/utils/dialog_util.dart';
const kWebPaymentRedirectUrl = String.fromEnvironment(
@@ -138,39 +137,12 @@ class BillingService {
BuildContext context,
UserDetails userDetails,
) async {
- if (userDetails.subscription.productID == freeProductID &&
- !userDetails.hasPaidAddon()) {
- await showErrorDialog(
- context,
- AppLocalizations.of(context).familyPlans,
- AppLocalizations.of(context).familyPlanOverview,
- );
- return;
- }
- final dialog = createProgressDialog(
- context,
- AppLocalizations.of(context).pleaseWait,
- isDismissible: true,
- );
- await dialog.show();
try {
- final bool familyExist = userDetails.isPartOfFamily();
- final String url =
- await UserService.instance.getFamilyPortalUrl(familyExist);
-
- await dialog.hide();
- await Navigator.of(context).push(
- MaterialPageRoute(
- builder: (BuildContext context) {
- return WebPage(
- AppLocalizations.of(context).familyPlanPortalTitle,
- url,
- );
- },
- ),
+ await routeToPage(
+ context,
+ FamilyPlanPage(initialUserDetails: userDetails),
);
} catch (e) {
- await dialog.hide();
await showGenericErrorDialog(context: context, error: e);
}
}
diff --git a/mobile/apps/photos/lib/services/family_service.dart b/mobile/apps/photos/lib/services/family_service.dart
new file mode 100644
index 0000000000..7d20ff7b1e
--- /dev/null
+++ b/mobile/apps/photos/lib/services/family_service.dart
@@ -0,0 +1,116 @@
+import 'package:dio/dio.dart';
+import 'package:logging/logging.dart';
+import 'package:photos/core/event_bus.dart';
+import 'package:photos/events/user_details_changed_event.dart';
+import 'package:photos/models/user_details.dart';
+import 'package:photos/service_locator.dart';
+import 'package:photos/services/account/user_service.dart';
+
+class FamilyInviteFailure {
+ const FamilyInviteFailure({
+ required this.email,
+ required this.error,
+ });
+
+ final String email;
+ final Object error;
+}
+
+class FamilyInviteResult {
+ const FamilyInviteResult({
+ required this.failures,
+ });
+
+ final List<FamilyInviteFailure> failures;
+
+ bool get hasFailures => failures.isNotEmpty;
+}
+
+class FamilyService {
+ FamilyService._privateConstructor();
+
+ static final FamilyService instance = FamilyService._privateConstructor();
+
+ final _logger = Logger("FamilyService");
+
+ Future<UserDetails> refreshUserDetails() async {
+ final details = await UserService.instance.getUserDetailsV2(
+ memoryCount: false,
+ );
+ Bus.instance.fire(UserDetailsChangedEvent());
+ return details;
+ }
+
+ Future<FamilyInviteResult> inviteMembers({
+ required UserDetails userDetails,
+ required List<String> emails,
+ }) async {
+ final familyAuthToken = await usersGateway.getFamiliesAuthToken();
+ if (userDetails.familyData == null) {
+ await usersGateway.createFamily(authToken: familyAuthToken);
+ }
+
+ final failures = <FamilyInviteFailure>[];
+ for (final email in emails) {
+ try {
+ await usersGateway.inviteFamilyMember(
+ email: email,
+ authToken: familyAuthToken,
+ );
+ } catch (error, stackTrace) {
+ _logger.warning("Failed to invite $email", error, stackTrace);
+ failures.add(FamilyInviteFailure(email: email, error: error));
+ }
+ }
+
+ return FamilyInviteResult(failures: failures);
+ }
+
+ Future<void> resendInvite(FamilyMember member) async {
+ await usersGateway.inviteFamilyMember(email: member.email);
+ }
+
+ Future<void> revokeInvite(FamilyMember member) async {
+ await usersGateway.revokeFamilyInvite(member.id);
+ }
+
+ Future<void> removeMember(FamilyMember member) async {
+ await usersGateway.removeFamilyMember(member.id);
+ }
+
+ Future<void> updateMemberStorageLimit({
+ required FamilyMember member,
+ int? storageLimit,
+ }) async {
+ await usersGateway.updateFamilyMemberStorage(
+ id: member.id,
+ storageLimit: storageLimit,
+ );
+ }
+
+ Future<void> leaveFamily() async {
+ await UserService.instance.leaveFamilyPlan();
+ }
+
+ Future<void> closeFamily(UserDetails userDetails) async {
+ final members = userDetails.familyData?.members;
+ if (members == null) {
+ return;
+ }
+
+ for (final member in members) {
+ if (member.email.trim() == userDetails.email.trim()) {
+ continue;
+ }
+ if (member.isPending) {
+ await revokeInvite(member);
+ } else if (member.isActive) {
+ await removeMember(member);
+ }
+ }
+ }
+
+ static bool isNotFoundError(Object error) {
+ return error is DioException && error.response?.statusCode == 404;
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/family/edit_storage_limit_page.dart b/mobile/apps/photos/lib/ui/family/edit_storage_limit_page.dart
new file mode 100644
index 0000000000..0ea155c44b
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/family/edit_storage_limit_page.dart
@@ -0,0 +1,234 @@
+import 'dart:math' as math;
+
+import 'package:ente_pure_utils/ente_pure_utils.dart';
+import 'package:flutter/material.dart';
+import 'package:photos/generated/l10n.dart';
+import 'package:photos/models/user_details.dart';
+import 'package:photos/services/family_service.dart';
+import 'package:photos/theme/ente_theme.dart';
+import 'package:photos/ui/components/buttons/button_widget_v2.dart';
+import 'package:photos/ui/family/family_ui.dart';
+import 'package:photos/utils/dialog_util.dart';
+
+class EditStorageLimitPage extends StatefulWidget {
+ const EditStorageLimitPage({
+ required this.member,
+ required this.totalStorageInBytes,
+ required this.avatarColor,
+ super.key,
+ });
+
+ final FamilyMember member;
+ final int totalStorageInBytes;
+ final Color avatarColor;
+
+ @override
+ State<EditStorageLimitPage> createState() => _EditStorageLimitPageState();
+}
+
+class _EditStorageLimitPageState extends State<EditStorageLimitPage> {
+ static const _gigabyte = 1024 * 1024 * 1024;
+
+ late double _sliderValue;
+
+ double get _maxSliderValue =>
+ math.max(1, (widget.totalStorageInBytes / _gigabyte).ceilToDouble());
+
+ double get _minimumLimitedSliderValue =>
+ (widget.member.usage / _gigabyte).ceilToDouble();
+
+ int? get _selectedStorageLimit {
+ if (_sliderValue <= 0) {
+ return null;
+ }
+ return (_sliderValue * _gigabyte).round();
+ }
+
+ @override
+ void initState() {
+ super.initState();
+ _sliderValue = widget.member.storageLimit == null
+ ? 0
+ : (widget.member.storageLimit! / _gigabyte).roundToDouble();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final l10n = AppLocalizations.of(context);
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+
+ return FamilyPageScaffold(
+ title: l10n.storageLimit,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ CircleAvatar(
+ radius: 20,
+ backgroundColor: widget.avatarColor,
+ child: Text(
+ widget.member.email.substring(0, 1).toUpperCase(),
+ style: textTheme.bodyBold.copyWith(
+ color: Colors.white,
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ widget.member.email,
+ style: textTheme.body,
+ ),
+ const SizedBox(height: 2),
+ Text(
+ l10n.usingStorage(
+ amount: convertBytesToReadableFormat(
+ widget.member.usage,
+ ),
+ ),
+ style: textTheme.smallMuted,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 24),
+ Text(
+ l10n.storageLimitExplanation,
+ style: textTheme.bodyMuted.copyWith(height: 1.5),
+ ),
+ const SizedBox(height: 24),
+ Container(
+ padding: const EdgeInsets.all(20),
+ decoration: BoxDecoration(
+ color: colorScheme.fill,
+ borderRadius: BorderRadius.circular(16),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(
+ l10n.limit,
+ style: textTheme.bodyBold,
+ ),
+ Text(
+ _selectedStorageLimit == null
+ ? l10n.noLimit
+ : convertBytesToReadableFormat(
+ _selectedStorageLimit!,
+ ),
+ style: textTheme.h3Bold.copyWith(
+ color: colorScheme.greenBase,
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ SliderTheme(
+ data: SliderTheme.of(context).copyWith(
+ activeTrackColor: colorScheme.greenBase,
+ inactiveTrackColor: colorScheme.fillMuted,
+ thumbColor: colorScheme.greenBase,
+ overlayColor:
+ colorScheme.greenBase.withValues(alpha: 0.14),
+ ),
+ child: Slider(
+ value: _sliderValue.clamp(0, _maxSliderValue),
+ min: 0,
+ max: _maxSliderValue,
+ divisions: _maxSliderValue <= 500
+ ? _maxSliderValue.toInt()
+ : 500,
+ onChanged: (value) {
+ final roundedValue = value.roundToDouble();
+ final effectiveValue = roundedValue > 0 &&
+ roundedValue < _minimumLimitedSliderValue
+ ? _minimumLimitedSliderValue
+ : roundedValue;
+ setState(() {
+ _sliderValue = effectiveValue;
+ });
+ },
+ ),
+ ),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(
+ l10n.noLimit,
+ style: textTheme.miniMuted,
+ ),
+ Text(
+ convertBytesToReadableFormat(
+ widget.totalStorageInBytes,
+ ),
+ style: textTheme.miniMuted,
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 12),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4),
+ child: Text(
+ l10n.currentUsageNote(
+ amount:
+ convertBytesToReadableFormat(widget.member.usage),
+ ),
+ style: textTheme.smallFaint.copyWith(height: 1.5),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ ButtonWidgetV2(
+ buttonType: ButtonTypeV2.primary,
+ labelText: l10n.save,
+ onTap: _saveLimit,
+ ),
+ ],
+ ),
+ );
+ }
+
+ Future<void> _saveLimit() async {
+ try {
+ await FamilyService.instance.updateMemberStorageLimit(
+ member: widget.member,
+ storageLimit: _selectedStorageLimit,
+ );
+ if (mounted) {
+ Navigator.of(context).pop(true);
+ }
+ } catch (error) {
+ if (!mounted) {
+ throw const _HandledStorageLimitException();
+ }
+ await showGenericErrorDialog(context: context, error: error);
+ throw const _HandledStorageLimitException();
+ }
+ }
+}
+
+class _HandledStorageLimitException implements Exception {
+ const _HandledStorageLimitException();
+}
diff --git a/mobile/apps/photos/lib/ui/family/family_plan_page.dart b/mobile/apps/photos/lib/ui/family/family_plan_page.dart
new file mode 100644
index 0000000000..458fb7729d
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/family/family_plan_page.dart
@@ -0,0 +1,1064 @@
+import 'dart:async';
+import 'dart:math' as math;
+
+import 'package:collection/collection.dart';
+import 'package:ente_pure_utils/ente_pure_utils.dart';
+import 'package:flutter/material.dart';
+import 'package:photos/gateways/billing/models/billing_plan.dart';
+import 'package:photos/gateways/billing/models/subscription.dart';
+import 'package:photos/generated/l10n.dart';
+import 'package:photos/models/button_result.dart';
+import 'package:photos/models/user_details.dart';
+import 'package:photos/service_locator.dart';
+import 'package:photos/services/family_service.dart';
+import 'package:photos/theme/ente_theme.dart';
+import 'package:photos/ui/components/base_bottom_sheet.dart';
+import 'package:photos/ui/components/buttons/button_widget.dart';
+import 'package:photos/ui/components/buttons/button_widget_v2.dart';
+import 'package:photos/ui/family/edit_storage_limit_page.dart';
+import 'package:photos/ui/family/family_ui.dart';
+import 'package:photos/ui/family/invite_members_page.dart';
+import 'package:photos/ui/payment/subscription.dart';
+import 'package:photos/utils/dialog_util.dart';
+
+class FamilyPlanPage extends StatefulWidget {
+ const FamilyPlanPage({
+ required this.initialUserDetails,
+ super.key,
+ });
+
+ final UserDetails initialUserDetails;
+
+ @override
+ State<FamilyPlanPage> createState() => _FamilyPlanPageState();
+}
+
+class _FamilyPlanPageState extends State<FamilyPlanPage> {
+ late UserDetails _userDetails = widget.initialUserDetails;
+ String? _startingPrice;
+ bool _isRefreshing = false;
+
+ bool get _isFreeUser =>
+ _userDetails.subscription.productID == freeProductID &&
+ !_userDetails.hasPaidAddon();
+
+ bool get _showsDashboard => _userDetails.hasConfiguredFamily();
+
+ bool get _isAdmin =>
+ (_userDetails.currentFamilyMember()?.isAdmin ?? false) && _showsDashboard;
+
+ int get _remainingSlots {
+ final memberCount = _userDetails.familyData?.members
+ ?.where(
+ (member) => member.email.trim() != _userDetails.email.trim(),
+ )
+ .length ??
+ 0;
+ return math.max(0, 5 - memberCount);
+ }
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_refreshUserDetails());
+ if (_isFreeUser) {
+ unawaited(_loadStartingPrice());
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final content = _showsDashboard
+ ? _buildDashboard(context)
+ : _isFreeUser
+ ? _buildFreeAdvert(context)
+ : _buildPaidAdvert(context);
+
+ return FamilyPageScaffold(
+ title: _showsDashboard ? AppLocalizations.of(context).family : null,
+ child: Stack(
+ children: [
+ Positioned.fill(child: content),
+ if (_isRefreshing)
+ Positioned(
+ top: 0,
+ left: 0,
+ right: 0,
+ child: LinearProgressIndicator(
+ minHeight: 2,
+ color: getEnteColorScheme(context).greenBase,
+ backgroundColor: Colors.transparent,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildFreeAdvert(BuildContext context) {
+ final l10n = AppLocalizations.of(context);
+ return Column(
+ children: [
+ Expanded(
+ child: SingleChildScrollView(
+ child: Column(
+ children: [
+ const SizedBox(height: 8),
+ Image.asset(
+ "assets/ducky_share.png",
+ width: 200,
+ fit: BoxFit.contain,
+ ),
+ const SizedBox(height: 16),
+ _AdvertTitle(text: l10n.designedForFamilies),
+ const SizedBox(height: 12),
+ _AdvertBody(text: l10n.shareYourSubscription),
+ const SizedBox(height: 20),
+ _BenefitItem(
+ icon: Icons.group_outlined,
+ text: l10n.shareStorageWith5Members,
+ ),
+ _BenefitItem(
+ icon: Icons.lock_outline,
+ text: l10n.privateSpaceForEveryMember,
+ ),
+ _BenefitItem(
+ icon: Icons.forum_outlined,
+ text: l10n.feedToEngageWithFamily,
+ ),
+ if (_startingPrice != null) ...[
+ const SizedBox(height: 24),
+ Text(
+ l10n.plansStartAt(price: _startingPrice!),
+ style: getEnteTextTheme(context).smallFaint,
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ ButtonWidgetV2(
+ buttonType: ButtonTypeV2.primary,
+ labelText: l10n.viewPlans,
+ onTap: () async {
+ unawaited(routeToPage(context, getSubscriptionPage()));
+ },
+ ),
+ ],
+ );
+ }
+
+ Widget _buildPaidAdvert(BuildContext context) {
+ final l10n = AppLocalizations.of(context);
+ return Column(
+ children: [
+ Expanded(
+ child: SingleChildScrollView(
+ child: Column(
+ children: [
+ const SizedBox(height: 8),
+ Image.asset(
+ "assets/ducky_share.png",
+ width: 200,
+ fit: BoxFit.contain,
+ ),
+ const SizedBox(height: 16),
+ _AdvertTitle(text: l10n.bringYourFamilyAlong),
+ const SizedBox(height: 12),
+ _AdvertBody(text: l10n.yourPlanSupportsFamily),
+ const SizedBox(height: 20),
+ _BenefitItem(
+ icon: Icons.group_add_outlined,
+ text: l10n.addUpTo5MembersFree,
+ ),
+ _BenefitItem(
+ icon: Icons.lock_outline,
+ text: l10n.privateSpaceForEveryMember,
+ ),
+ _BenefitItem(
+ icon: Icons.forum_outlined,
+ text: l10n.feedToEngageWithFamily,
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ ButtonWidgetV2(
+ buttonType: ButtonTypeV2.primary,
+ labelText: l10n.addFamilyMember,
+ onTap: () async {
+ unawaited(_openInvitePage());
+ },
+ ),
+ ],
+ );
+ }
+
+ Widget _buildDashboard(BuildContext context) {
+ final l10n = AppLocalizations.of(context);
+ final members = _sortedMembersForList();
+ final activeMembers = _legendMembers();
+ final colorMap = _memberColorMap(activeMembers);
+
+ return RefreshIndicator(
+ onRefresh: () => _refreshUserDetails(showError: true),
+ child: ListView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ children: [
+ _FamilyStorageOverviewCard(
+ userDetails: _userDetails,
+ members: activeMembers,
+ colorMap: colorMap,
+ ),
+ const SizedBox(height: 16),
+ Padding(
+ padding: const EdgeInsets.only(left: 8, bottom: 8),
+ child: Text(
+ l10n.members,
+ style: getEnteTextTheme(context).smallMuted,
+ ),
+ ),
+ _FamilyMembersCard(
+ members: members,
+ userDetails: _userDetails,
+ colorMap: colorMap,
+ isAdminView: _isAdmin,
+ onMemberTap: _showMemberActions,
+ ),
+ const SizedBox(height: 24),
+ if (_isAdmin && _remainingSlots > 0) ...[
+ ButtonWidgetV2(
+ buttonType: ButtonTypeV2.primary,
+ labelText: l10n.addMember,
+ leadingWidget: const Icon(
+ Icons.person_add_outlined,
+ color: Colors.white,
+ size: 20,
+ ),
+ onTap: () async {
+ unawaited(_openInvitePage());
+ },
+ ),
+ const SizedBox(height: 12),
+ ButtonWidgetV2(
+ buttonType: ButtonTypeV2.tertiaryCritical,
+ labelText: l10n.closeFamilyPlan,
+ onTap: () async {
+ unawaited(_confirmCloseFamily());
+ },
+ ),
+ ],
+ if (_isAdmin && _remainingSlots == 0)
+ ButtonWidgetV2(
+ buttonType: ButtonTypeV2.tertiaryCritical,
+ labelText: l10n.closeFamilyPlan,
+ onTap: () async {
+ unawaited(_confirmCloseFamily());
+ },
+ ),
+ if (!_isAdmin)
+ ButtonWidgetV2(
+ buttonType: ButtonTypeV2.tertiaryCritical,
+ labelText: l10n.leaveFamilyPlan,
+ onTap: () async {
+ unawaited(_confirmLeaveFamily());
+ },
+ ),
+ const SizedBox(height: 16),
+ ],
+ ),
+ );
+ }
+
+ Future<void> _loadStartingPrice() async {
+ try {
+ final billingPlans = await billingService.getBillingPlans();
+ final cheapestPlan = billingPlans.plans
+ .where((plan) => plan.id != freeProductID && plan.price.isNotEmpty)
+ .map(_monthlyPriceForPlan)
+ .whereType<_MonthlyPrice>()
+ .sorted((a, b) => a.value.compareTo(b.value))
+ .firstOrNull;
+ if (mounted && cheapestPlan != null) {
+ setState(() => _startingPrice = cheapestPlan.displayPrice);
+ }
+ } catch (_) {}
+ }
+
+ Future<void> _refreshUserDetails({bool showError = false}) async {
+ if (_isRefreshing) {
+ return;
+ }
+ setState(() => _isRefreshing = true);
+ try {
+ final details = await FamilyService.instance.refreshUserDetails();
+ if (!mounted) {
+ return;
+ }
+ setState(() => _userDetails = details);
+ } catch (error) {
+ if (mounted && showError) {
+ await showGenericErrorDialog(context: context, error: error);
+ }
+ } finally {
+ if (mounted) {
+ setState(() => _isRefreshing = false);
+ }
+ }
+ }
+
+ Future<void> _openInvitePage() async {
+ final result = await routeToPage<InviteMembersPageResult>(
+ context,
+ InviteMembersPage(
+ userDetails: _userDetails,
+ remainingSlots: _remainingSlots,
+ ),
+ );
+ await _refreshUserDetails();
+ if (!mounted) {
+ return;
+ }
+ if (result?.invitesSent ?? false) {
+ showFamilySnackBar(context, AppLocalizations.of(context).invitesSent);
+ }
+ }
+
+ Future<void> _showMemberActions(FamilyMember member) async {
+ final isCurrentUser = member.email.trim() == _userDetails.email.trim();
+ if (!_isAdmin || isCurrentUser) {
+ return;
+ }
+
+ final l10n = AppLocalizations.of(context);
+ final colorMap = _memberColorMap(_legendMembers());
+ await showBaseBottomSheet<void>(
+ context,
+ title: member.email,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _ActionGroup(
+ children: member.isPending
+ ? [
+ _ActionTile(
+ icon: Icons.send_outlined,
+ title: l10n.resendInvite,
+ onTap: () async {
+ Navigator.of(context).pop();
+ await _resendInvite(member);
+ },
+ ),
+ _ActionTile(
+ icon: Icons.link_off_outlined,
+ title: l10n.revokeInvite,
+ isDestructive: true,
+ onTap: () async {
+ Navigator.of(context).pop();
+ await _confirmRevokeInvite(member);
+ },
+ ),
+ ]
+ : [
+ _ActionTile(
+ icon: Icons.tune,
+ title: l10n.editStorageLimit,
+ subtitle: member.storageLimit == null
+ ? l10n.noLimitSet
+ : convertBytesToReadableFormat(member.storageLimit!),
+ trailingChevron: true,
+ onTap: () async {
+ Navigator.of(context).pop();
+ await routeToPage(
+ context,
+ EditStorageLimitPage(
+ member: member,
+ totalStorageInBytes: _userDetails.getTotalStorage(),
+ avatarColor: colorMap[member.email] ??
+ getEnteColorScheme(context).greenBase,
+ ),
+ );
+ await _refreshUserDetails();
+ },
+ ),
+ _ActionTile(
+ icon: Icons.person_remove_outlined,
+ title: l10n.removeFromFamily,
+ isDestructive: true,
+ onTap: () async {
+ Navigator.of(context).pop();
+ await _confirmRemoveMember(member);
+ },
+ ),
+ ],
+ ),
+ ],
+ ),
+ );
+ }
+
+ Future<void> _resendInvite(FamilyMember member) async {
+ try {
+ await FamilyService.instance.resendInvite(member);
+ await _refreshUserDetails();
+ if (mounted) {
+ showFamilySnackBar(context, AppLocalizations.of(context).inviteResent);
+ }
+ } catch (error) {
+ if (mounted) {
+ await showGenericErrorDialog(context: context, error: error);
+ }
+ }
+ }
+
+ Future<void> _confirmRemoveMember(FamilyMember member) async {
+ final choice = await showChoiceDialog(
+ context,
+ title: AppLocalizations.of(context).removeMemberConfirmTitle,
+ body: AppLocalizations.of(context).removeMemberConfirmBody(
+ email: member.email,
+ ),
+ firstButtonLabel: AppLocalizations.of(context).remove,
+ secondButtonLabel: AppLocalizations.of(context).cancel,
+ isCritical: true,
+ firstButtonOnTap: () async {
+ await FamilyService.instance.removeMember(member);
+ },
+ );
+ await _handleDialogResult(choice);
+ }
+
+ Future<void> _confirmRevokeInvite(FamilyMember member) async {
+ final choice = await showChoiceDialog(
+ context,
+ title: AppLocalizations.of(context).revokeInviteConfirmTitle,
+ body: AppLocalizations.of(context).revokeInviteConfirmBody(
+ email: member.email,
+ ),
+ firstButtonLabel: AppLocalizations.of(context).revoke,
+ secondButtonLabel: AppLocalizations.of(context).cancel,
+ isCritical: true,
+ firstButtonOnTap: () async {
+ await FamilyService.instance.revokeInvite(member);
+ },
+ );
+ await _handleDialogResult(choice);
+ }
+
+ Future<void> _confirmCloseFamily() async {
+ final choice = await showChoiceDialog(
+ context,
+ title: AppLocalizations.of(context).closeFamilyConfirmTitle,
+ body: AppLocalizations.of(context).closeFamilyConfirmBody,
+ firstButtonLabel: AppLocalizations.of(context).closeFamilyPlan,
+ secondButtonLabel: AppLocalizations.of(context).cancel,
+ isCritical: true,
+ firstButtonOnTap: () async {
+ await FamilyService.instance.closeFamily(_userDetails);
+ },
+ );
+ await _handleDialogResult(choice);
+ }
+
+ Future<void> _confirmLeaveFamily() async {
+ final choice = await showChoiceDialog(
+ context,
+ title: AppLocalizations.of(context).leaveFamilyConfirmTitle,
+ body: AppLocalizations.of(context).leaveFamilyConfirmBody,
+ firstButtonLabel: AppLocalizations.of(context).leave,
+ secondButtonLabel: AppLocalizations.of(context).cancel,
+ isCritical: true,
+ firstButtonOnTap: () async {
+ await FamilyService.instance.leaveFamily();
+ },
+ );
+
+ if (!mounted || choice == null) {
+ return;
+ }
+ if (choice.action == ButtonAction.error) {
+ await showGenericErrorDialog(context: context, error: choice.exception);
+ return;
+ }
+ if (choice.action == ButtonAction.first) {
+ await _refreshUserDetails();
+ if (!mounted) {
+ return;
+ }
+ replacePage(context, getSubscriptionPage());
+ }
+ }
+
+ Future<void> _handleDialogResult(ButtonResult? choice) async {
+ if (!mounted || choice == null) {
+ return;
+ }
+ if (choice.action == ButtonAction.error) {
+ await showGenericErrorDialog(context: context, error: choice.exception);
+ return;
+ }
+ if (choice.action == ButtonAction.first) {
+ await _refreshUserDetails();
+ }
+ }
+
+ List<FamilyMember> _sortedMembersForList() {
+ final members =
+ List<FamilyMember>.from(_userDetails.familyData?.members ?? []);
+ final currentEmail = _userDetails.email.trim().toLowerCase();
+
+ members.sort((a, b) {
+ if (_isAdmin) {
+ if (a.email.trim().toLowerCase() == currentEmail) return -1;
+ if (b.email.trim().toLowerCase() == currentEmail) return 1;
+ if (a.isPending != b.isPending) return a.isPending ? 1 : -1;
+ return a.email.compareTo(b.email);
+ }
+
+ if (a.isAdmin != b.isAdmin) return a.isAdmin ? -1 : 1;
+ if (a.email.trim().toLowerCase() == currentEmail) return -1;
+ if (b.email.trim().toLowerCase() == currentEmail) return 1;
+ if (a.isPending != b.isPending) return a.isPending ? 1 : -1;
+ return a.email.compareTo(b.email);
+ });
+ return members;
+ }
+
+ List<FamilyMember> _legendMembers() {
+ final currentEmail = _userDetails.email.trim().toLowerCase();
+ final members = (_userDetails.familyData?.members ?? [])
+ .where((member) => member.isActive)
+ .toList();
+ members.sort((a, b) {
+ if (a.email.trim().toLowerCase() == currentEmail) return -1;
+ if (b.email.trim().toLowerCase() == currentEmail) return 1;
+ if (a.isAdmin != b.isAdmin) return a.isAdmin ? -1 : 1;
+ return a.email.compareTo(b.email);
+ });
+ return members;
+ }
+
+ Map<String, Color> _memberColorMap(List<FamilyMember> members) {
+ final colorScheme = getEnteColorScheme(context);
+ final palette = <Color>[
+ colorScheme.greenBase,
+ ...colorScheme.avatarColors,
+ colorScheme.primary500,
+ colorScheme.golden500,
+ ];
+ return {
+ for (final entry in members.indexed)
+ entry.$2.email: palette[entry.$1 % palette.length],
+ };
+ }
+
+ _MonthlyPrice? _monthlyPriceForPlan(BillingPlan plan) {
+ if (plan.price.isEmpty) {
+ return null;
+ }
+ if (plan.price.length < 2) {
+ return _MonthlyPrice(plan.price, double.infinity);
+ }
+
+ final currencySymbol = plan.price[0];
+ final rawPrice = plan.price.substring(1).replaceAll(",", "");
+ final parsedPrice = double.tryParse(rawPrice);
+ if (parsedPrice == null) {
+ return null;
+ }
+
+ final monthlyValue = plan.period == "year" ? parsedPrice / 12 : parsedPrice;
+ var displayValue = monthlyValue.toStringAsFixed(2);
+ if (displayValue.endsWith(".00")) {
+ displayValue = displayValue.substring(0, displayValue.length - 3);
+ }
+ return _MonthlyPrice("$currencySymbol$displayValue", monthlyValue);
+ }
+}
+
+class _AdvertTitle extends StatelessWidget {
+ const _AdvertTitle({required this.text});
+
+ final String text;
+
+ @override
+ Widget build(BuildContext context) {
+ return Text(
+ text,
+ style: getEnteTextTheme(context).h3Bold,
+ textAlign: TextAlign.center,
+ );
+ }
+}
+
+class _AdvertBody extends StatelessWidget {
+ const _AdvertBody({required this.text});
+
+ final String text;
+
+ @override
+ Widget build(BuildContext context) {
+ return Text(
+ text,
+ style: getEnteTextTheme(context).bodyMuted.copyWith(height: 1.5),
+ textAlign: TextAlign.center,
+ );
+ }
+}
+
+class _BenefitItem extends StatelessWidget {
+ const _BenefitItem({
+ required this.icon,
+ required this.text,
+ });
+
+ final IconData icon;
+ final String text;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ return Padding(
+ padding: const EdgeInsets.symmetric(vertical: 10),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Icon(icon, size: 20, color: colorScheme.greenBase),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ text,
+ style: textTheme.body,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _FamilyStorageOverviewCard extends StatelessWidget {
+ const _FamilyStorageOverviewCard({
+ required this.userDetails,
+ required this.members,
+ required this.colorMap,
+ });
+
+ final UserDetails userDetails;
+ final List<FamilyMember> members;
+ final Map<String, Color> colorMap;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ final l10n = AppLocalizations.of(context);
+ final totalUsed =
+ userDetails.familyData?.getTotalUsage() ?? userDetails.usage;
+ final totalStorage = userDetails.getTotalStorage();
+
+ return Container(
+ padding: const EdgeInsets.all(20),
+ decoration: BoxDecoration(
+ color: colorScheme.fill,
+ borderRadius: BorderRadius.circular(16),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: [
+ Text(
+ l10n.storage,
+ style: textTheme.bodyBold,
+ ),
+ Text(
+ l10n.storageUsedOfTotal(
+ used: convertBytesToReadableFormat(totalUsed),
+ total: convertBytesToReadableFormat(totalStorage),
+ ),
+ style: textTheme.smallMuted,
+ ),
+ ],
+ ),
+ const SizedBox(height: 14),
+ SizedBox(
+ height: 14,
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ var currentLeft = 0.0;
+ return Stack(
+ children: [
+ Container(
+ decoration: BoxDecoration(
+ color: colorScheme.fillMuted,
+ borderRadius: BorderRadius.circular(7),
+ ),
+ ),
+ for (final member in members)
+ Builder(
+ builder: (context) {
+ final width = totalStorage == 0
+ ? 0.0
+ : constraints.maxWidth *
+ (member.usage / totalStorage);
+ final segment = Positioned(
+ left: currentLeft,
+ child: Container(
+ width: width,
+ height: 14,
+ decoration: BoxDecoration(
+ color: colorMap[member.email],
+ borderRadius: BorderRadius.circular(7),
+ ),
+ ),
+ );
+ currentLeft += width;
+ return segment;
+ },
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ const SizedBox(height: 14),
+ Wrap(
+ spacing: 16,
+ runSpacing: 8,
+ children: [
+ for (final member in members)
+ Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(
+ width: 10,
+ height: 10,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: colorMap[member.email],
+ ),
+ ),
+ const SizedBox(width: 6),
+ Text(
+ _legendLabel(
+ currentEmail: userDetails.email,
+ member: member,
+ l10n: l10n,
+ ),
+ style: textTheme.miniMuted,
+ ),
+ ],
+ ),
+ ],
+ ),
+ ],
+ ),
+ );
+ }
+
+ String _legendLabel({
+ required String currentEmail,
+ required FamilyMember member,
+ required AppLocalizations l10n,
+ }) {
+ if (member.email.trim().toLowerCase() ==
+ currentEmail.trim().toLowerCase()) {
+ return l10n.you;
+ }
+ if (member.isAdmin) {
+ return l10n.admin;
+ }
+ return _emailLabel(member.email);
+ }
+}
+
+class _FamilyMembersCard extends StatelessWidget {
+ const _FamilyMembersCard({
+ required this.members,
+ required this.userDetails,
+ required this.colorMap,
+ required this.isAdminView,
+ required this.onMemberTap,
+ });
+
+ final List<FamilyMember> members;
+ final UserDetails userDetails;
+ final Map<String, Color> colorMap;
+ final bool isAdminView;
+ final ValueChanged<FamilyMember> onMemberTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+
+ return Container(
+ decoration: BoxDecoration(
+ color: colorScheme.fill,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Column(
+ children: [
+ for (final entry in members.indexed) ...[
+ _FamilyMemberRow(
+ member: entry.$2,
+ currentEmail: userDetails.email,
+ avatarColor: colorMap[entry.$2.email],
+ isAdminView: isAdminView,
+ onTap: () => onMemberTap(entry.$2),
+ ),
+ if (entry.$1 != members.length - 1)
+ Divider(
+ height: 1,
+ indent: 16,
+ endIndent: 16,
+ color: colorScheme.strokeSolid,
+ ),
+ ],
+ ],
+ ),
+ );
+ }
+}
+
+class _FamilyMemberRow extends StatelessWidget {
+ const _FamilyMemberRow({
+ required this.member,
+ required this.currentEmail,
+ required this.isAdminView,
+ required this.onTap,
+ this.avatarColor,
+ });
+
+ final FamilyMember member;
+ final String currentEmail;
+ final bool isAdminView;
+ final VoidCallback onTap;
+ final Color? avatarColor;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ final l10n = AppLocalizations.of(context);
+ final isCurrentUser =
+ member.email.trim().toLowerCase() == currentEmail.trim().toLowerCase();
+ final canTap = isAdminView && !isCurrentUser;
+ final backgroundColor = member.isPending
+ ? colorScheme.fillMuted
+ : avatarColor ?? colorScheme.greenBase;
+ final foregroundColor =
+ member.isPending ? colorScheme.contentLight : Colors.white;
+
+ return InkWell(
+ borderRadius: BorderRadius.circular(20),
+ onTap: canTap ? onTap : null,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ child: Row(
+ children: [
+ CircleAvatar(
+ radius: 20,
+ backgroundColor: backgroundColor,
+ child: Text(
+ member.email.substring(0, 1).toUpperCase(),
+ style: textTheme.bodyBold.copyWith(color: foregroundColor),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ member.email,
+ style: member.isPending
+ ? textTheme.body.copyWith(color: colorScheme.textMuted)
+ : textTheme.body,
+ ),
+ const SizedBox(height: 2),
+ Text(
+ member.isPending
+ ? l10n.pending
+ : l10n.memberStorageUsed(
+ amount: convertBytesToReadableFormat(member.usage),
+ ),
+ style: textTheme.smallMuted,
+ ),
+ ],
+ ),
+ ),
+ if (member.isAdmin) _BadgeChip(label: l10n.admin),
+ if (!isAdminView && isCurrentUser) ...[
+ if (member.isAdmin) const SizedBox(width: 8),
+ _BadgeChip(
+ label: l10n.you,
+ isMuted: true,
+ ),
+ ],
+ if (member.isPending) ...[
+ if (member.isAdmin || (!isAdminView && isCurrentUser))
+ const SizedBox(width: 8),
+ _BadgeChip(label: l10n.pending, isMuted: true),
+ ],
+ if (canTap) ...[
+ const SizedBox(width: 8),
+ Icon(
+ Icons.chevron_right,
+ size: 20,
+ color: colorScheme.contentLighter,
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _BadgeChip extends StatelessWidget {
+ const _BadgeChip({
+ required this.label,
+ this.isMuted = false,
+ });
+
+ final String label;
+ final bool isMuted;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
+ decoration: BoxDecoration(
+ color: isMuted ? colorScheme.fillMuted : colorScheme.greenBase,
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Text(
+ label,
+ style: textTheme.tinyBold.copyWith(
+ color: isMuted ? colorScheme.textMuted : Colors.white,
+ ),
+ ),
+ );
+ }
+}
+
+class _ActionGroup extends StatelessWidget {
+ const _ActionGroup({required this.children});
+
+ final List<_ActionTile> children;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+
+ return Container(
+ decoration: BoxDecoration(
+ color: colorScheme.fill,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Column(
+ children: [
+ for (final entry in children.indexed) ...[
+ entry.$2,
+ if (entry.$1 != children.length - 1)
+ Divider(
+ height: 1,
+ indent: 16,
+ endIndent: 16,
+ color: colorScheme.strokeSolid,
+ ),
+ ],
+ ],
+ ),
+ );
+ }
+}
+
+class _ActionTile extends StatelessWidget {
+ const _ActionTile({
+ required this.icon,
+ required this.title,
+ required this.onTap,
+ this.subtitle,
+ this.isDestructive = false,
+ this.trailingChevron = false,
+ });
+
+ final IconData icon;
+ final String title;
+ final String? subtitle;
+ final VoidCallback onTap;
+ final bool isDestructive;
+ final bool trailingChevron;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ final foregroundColor =
+ isDestructive ? colorScheme.redBase : colorScheme.content;
+
+ return InkWell(
+ borderRadius: BorderRadius.circular(20),
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
+ child: Row(
+ children: [
+ Icon(icon, size: 20, color: foregroundColor),
+ const SizedBox(width: 16),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ title,
+ style: textTheme.body.copyWith(color: foregroundColor),
+ ),
+ if (subtitle != null) ...[
+ const SizedBox(height: 2),
+ Text(
+ subtitle!,
+ style: textTheme.smallMuted,
+ ),
+ ],
+ ],
+ ),
+ ),
+ if (trailingChevron)
+ Icon(
+ Icons.chevron_right,
+ size: 18,
+ color: colorScheme.contentLighter,
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _MonthlyPrice {
+ const _MonthlyPrice(this.displayPrice, this.value);
+
+ final String displayPrice;
+ final double value;
+}
+
+String _emailLabel(String email) {
+ final localPart = email.split("@").first.trim();
+ if (localPart.isEmpty) {
+ return email;
+ }
+ return localPart.substring(0, 1).toUpperCase() +
+ (localPart.length > 1 ? localPart.substring(1) : "");
+}
diff --git a/mobile/apps/photos/lib/ui/family/family_ui.dart b/mobile/apps/photos/lib/ui/family/family_ui.dart
new file mode 100644
index 0000000000..e258f1062c
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/family/family_ui.dart
@@ -0,0 +1,80 @@
+import 'package:flutter/material.dart';
+import 'package:photos/theme/ente_theme.dart';
+
+Color familyPageBackgroundColor(BuildContext context) {
+ return Theme.of(context).brightness == Brightness.dark
+ ? const Color(0xFF161616)
+ : const Color(0xFFFAFAFA);
+}
+
+class FamilyPageScaffold extends StatelessWidget {
+ const FamilyPageScaffold({
+ required this.child,
+ this.title,
+ this.padding = const EdgeInsets.fromLTRB(16, 12, 16, 16),
+ super.key,
+ });
+
+ final Widget child;
+ final String? title;
+ final EdgeInsetsGeometry padding;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+
+ return Scaffold(
+ backgroundColor: familyPageBackgroundColor(context),
+ body: SafeArea(
+ child: Padding(
+ padding: padding,
+ child: Column(
+ children: [
+ Row(
+ children: [
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => Navigator.of(context).pop(),
+ child: SizedBox(
+ width: 32,
+ height: 32,
+ child: Icon(
+ Icons.arrow_back,
+ size: 24,
+ color: colorScheme.strokeBase,
+ ),
+ ),
+ ),
+ if (title != null) const SizedBox(width: 8),
+ if (title != null)
+ Expanded(
+ child: Text(
+ title!,
+ style: textTheme.largeBold,
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 16),
+ Expanded(child: child),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+void showFamilySnackBar(BuildContext context, String message) {
+ final messenger = ScaffoldMessenger.of(context);
+ messenger
+ ..hideCurrentSnackBar()
+ ..showSnackBar(
+ SnackBar(
+ content: Text(message),
+ behavior: SnackBarBehavior.floating,
+ margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
+ ),
+ );
+}
diff --git a/mobile/apps/photos/lib/ui/family/invite_members_page.dart b/mobile/apps/photos/lib/ui/family/invite_members_page.dart
new file mode 100644
index 0000000000..17df650492
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/family/invite_members_page.dart
@@ -0,0 +1,408 @@
+import 'package:email_validator/email_validator.dart';
+import 'package:flutter/material.dart';
+import 'package:photos/generated/l10n.dart';
+import 'package:photos/models/user_details.dart';
+import 'package:photos/services/account/user_service.dart';
+import 'package:photos/services/family_service.dart';
+import 'package:photos/theme/ente_theme.dart';
+import 'package:photos/ui/components/base_bottom_sheet.dart';
+import 'package:photos/ui/components/buttons/button_widget_v2.dart';
+import 'package:photos/ui/family/family_ui.dart';
+import 'package:photos/utils/dialog_util.dart';
+import 'package:photos/utils/share_util.dart';
+
+class InviteMembersPageResult {
+ const InviteMembersPageResult._(this.invitesSent);
+
+ const InviteMembersPageResult.invitesSent() : this._(true);
+
+ final bool invitesSent;
+}
+
+class InviteMembersPage extends StatefulWidget {
+ const InviteMembersPage({
+ required this.userDetails,
+ required this.remainingSlots,
+ super.key,
+ });
+
+ final UserDetails userDetails;
+ final int remainingSlots;
+
+ @override
+ State<InviteMembersPage> createState() => _InviteMembersPageState();
+}
+
+class _InviteMembersPageState extends State<InviteMembersPage> {
+ final _emailController = TextEditingController();
+ final _emailFocusNode = FocusNode();
+ final List<String> _emails = [];
+ late final Set<String> _existingEmails;
+
+ String? _errorMessage;
+ bool _isCheckingEmail = false;
+
+ bool get _canAddMore => _emails.length < widget.remainingSlots;
+
+ @override
+ void initState() {
+ super.initState();
+ _existingEmails = {
+ for (final member in widget.userDetails.familyData?.members ?? [])
+ member.email.trim().toLowerCase(),
+ };
+ }
+
+ @override
+ void dispose() {
+ _emailController.dispose();
+ _emailFocusNode.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final l10n = AppLocalizations.of(context);
+ final textTheme = getEnteTextTheme(context);
+
+ return FamilyPageScaffold(
+ title: l10n.inviteMembers,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ l10n.enterEmailAddresses,
+ style: textTheme.bodyMuted.copyWith(height: 1.5),
+ ),
+ const SizedBox(height: 16),
+ _buildInputRow(context),
+ if (_errorMessage != null) ...[
+ const SizedBox(height: 6),
+ Padding(
+ padding: const EdgeInsets.only(left: 4),
+ child: Text(
+ _errorMessage!,
+ style: textTheme.small.copyWith(
+ color: getEnteColorScheme(context).redBase,
+ ),
+ ),
+ ),
+ ],
+ if (_emails.isNotEmpty) const SizedBox(height: 16),
+ for (final email in _emails) ...[
+ _EmailChip(
+ email: email,
+ onRemove: () => _removeEmail(email),
+ ),
+ const SizedBox(height: 8),
+ ],
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ ButtonWidgetV2(
+ buttonType: ButtonTypeV2.primary,
+ isDisabled: _emails.isEmpty,
+ labelText: _sendInvitesLabel(l10n),
+ onTap: _handleSendInvites,
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildInputRow(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ final l10n = AppLocalizations.of(context);
+ final hasError = _errorMessage != null;
+
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 180),
+ height: 58,
+ decoration: BoxDecoration(
+ color: colorScheme.fill,
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(
+ color: hasError
+ ? colorScheme.redBase
+ : _emailFocusNode.hasFocus
+ ? colorScheme.greenBase
+ : colorScheme.strokeSolid,
+ ),
+ ),
+ child: TextField(
+ controller: _emailController,
+ focusNode: _emailFocusNode,
+ keyboardType: TextInputType.emailAddress,
+ textInputAction: TextInputAction.done,
+ autofocus: true,
+ enabled: !_isCheckingEmail && _canAddMore,
+ onChanged: (_) {
+ if (_errorMessage != null) {
+ setState(() {
+ _errorMessage = null;
+ });
+ }
+ },
+ onSubmitted: (_) => _addEmail(),
+ decoration: InputDecoration(
+ hintText: l10n.emailAddress,
+ hintStyle: textTheme.body.copyWith(
+ color: colorScheme.contentLighter,
+ ),
+ border: InputBorder.none,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 16,
+ vertical: 18,
+ ),
+ ),
+ style: textTheme.body,
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: (_isCheckingEmail || !_canAddMore) ? null : _addEmail,
+ child: Container(
+ width: 58,
+ height: 58,
+ decoration: BoxDecoration(
+ color: colorScheme.fill,
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(color: colorScheme.strokeSolid),
+ ),
+ child: Center(
+ child: _isCheckingEmail
+ ? SizedBox.square(
+ dimension: 20,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: colorScheme.greenBase,
+ ),
+ )
+ : Icon(
+ Icons.add,
+ size: 24,
+ color: _canAddMore
+ ? colorScheme.content
+ : colorScheme.contentLighter,
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ String _sendInvitesLabel(AppLocalizations l10n) {
+ return l10n.sendCountInvites(count: _emails.length);
+ }
+
+ Future<void> _addEmail() async {
+ if (_isCheckingEmail || !_canAddMore) {
+ return;
+ }
+
+ final l10n = AppLocalizations.of(context);
+ final email = _emailController.text.trim().toLowerCase();
+ if (email.isEmpty) {
+ setState(() => _errorMessage = l10n.enterAnEmailAddress);
+ return;
+ }
+ if (!EmailValidator.validate(email)) {
+ setState(() => _errorMessage = l10n.enterAValidEmailAddress);
+ return;
+ }
+ if (_emails.contains(email) || _existingEmails.contains(email)) {
+ setState(() => _errorMessage = l10n.alreadyAdded);
+ return;
+ }
+
+ setState(() {
+ _isCheckingEmail = true;
+ _errorMessage = null;
+ });
+
+ try {
+ final publicKey = await UserService.instance.getPublicKey(email);
+ if (publicKey == null) {
+ if (!mounted) {
+ return;
+ }
+ setState(() => _errorMessage = l10n.thisUserIsNotOnEnte);
+ await _showInviteToEnteSheet(email);
+ return;
+ }
+
+ if (!mounted) {
+ return;
+ }
+ setState(() {
+ _emails.add(email);
+ _emailController.clear();
+ _errorMessage = null;
+ });
+ _emailFocusNode.requestFocus();
+ } catch (error) {
+ if (!mounted) {
+ return;
+ }
+ await showGenericErrorDialog(context: context, error: error);
+ } finally {
+ if (mounted) {
+ setState(() => _isCheckingEmail = false);
+ }
+ }
+ }
+
+ void _removeEmail(String email) {
+ setState(() {
+ _emails.remove(email);
+ });
+ }
+
+ Future<void> _handleSendInvites() async {
+ try {
+ final result = await FamilyService.instance.inviteMembers(
+ userDetails: widget.userDetails,
+ emails: List<String>.from(_emails),
+ );
+ if (!mounted) {
+ return;
+ }
+
+ if (!result.hasFailures) {
+ Navigator.of(context).pop(const InviteMembersPageResult.invitesSent());
+ return;
+ }
+
+ final hadAnySuccess = result.failures.length < _emails.length;
+ final failedEmailSet =
+ result.failures.map((failure) => failure.email).toSet();
+ _existingEmails
+ .addAll(_emails.where((email) => !failedEmailSet.contains(email)));
+ if (hadAnySuccess) {
+ try {
+ await FamilyService.instance.refreshUserDetails();
+ } catch (_) {}
+ }
+
+ final failedEmails =
+ result.failures.map((failure) => failure.email).toList();
+ setState(() {
+ _emails
+ ..clear()
+ ..addAll(failedEmails);
+ });
+ showFamilySnackBar(
+ context,
+ failedEmails.length == 1
+ ? AppLocalizations.of(context)
+ .failedToInvite(email: failedEmails.first)
+ : AppLocalizations.of(context)
+ .failedToInviteCount(count: failedEmails.length),
+ );
+ throw const _HandledInviteActionException();
+ } catch (error) {
+ if (error is _HandledInviteActionException) {
+ rethrow;
+ }
+ if (!mounted) {
+ throw const _HandledInviteActionException();
+ }
+ await showGenericErrorDialog(context: context, error: error);
+ throw const _HandledInviteActionException();
+ }
+ }
+
+ Future<void> _showInviteToEnteSheet(String email) {
+ final l10n = AppLocalizations.of(context);
+ return showBaseBottomSheet<void>(
+ context,
+ title: l10n.inviteToEnte,
+ headerSpacing: 20,
+ crossAxisAlignment: CrossAxisAlignment.center,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ l10n.emailNeedsEnteAccountForFamily(email: email),
+ textAlign: TextAlign.center,
+ style: getEnteTextTheme(context).smallMuted,
+ ),
+ const SizedBox(height: 20),
+ ButtonWidgetV2(
+ buttonType: ButtonTypeV2.primary,
+ labelText: l10n.sendInvite,
+ onTap: () async {
+ await shareText(l10n.shareTextRecommendUsingEnte);
+ if (mounted) {
+ Navigator.of(context).pop();
+ }
+ },
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _EmailChip extends StatelessWidget {
+ const _EmailChip({
+ required this.email,
+ required this.onRemove,
+ });
+
+ final String email;
+ final VoidCallback onRemove;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+
+ return Container(
+ width: double.infinity,
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+ decoration: BoxDecoration(
+ color: colorScheme.fillFaint,
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ email,
+ style: textTheme.body,
+ ),
+ ),
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onRemove,
+ child: Icon(
+ Icons.close,
+ size: 18,
+ color: colorScheme.contentLighter,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _HandledInviteActionException implements Exception {
+ const _HandledInviteActionException();
+}