π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Revamp cast pairing flow and sessions list
Priyanshu Dangare3c530bfbbada
diff --git a/mobile/apps/photos/lib/l10n/intl_en.arb b/mobile/apps/photos/lib/l10n/intl_en.arbindex e3fd870a31..050d286cbd 100644--- a/mobile/apps/photos/lib/l10n/intl_en.arb+++ b/mobile/apps/photos/lib/l10n/intl_en.arb@@ -1794,7 +1794,7 @@"playOnTv": "Play album on TV","pair": "Pair","deviceNotFound": "Device not found",- "castInstruction": "Visit {castUrl} on the device you want to pair.\n\nEnter the code below to play the album on your TV.",+ "castInstruction": "Visit {castUrl} on the device you want to pair.","@castInstruction": {"description": "Instructions shown when pairing a device to play an album on TV.","placeholders": {diff --git a/mobile/apps/photos/lib/ui/cast/auto.dart b/mobile/apps/photos/lib/ui/cast/auto.dartindex 14ef0b497b..3ef1296ff0 100644--- a/mobile/apps/photos/lib/ui/cast/auto.dart+++ b/mobile/apps/photos/lib/ui/cast/auto.dart@@ -19,7 +19,6 @@ class AutoCastDialog extends StatefulWidget {}class _AutoCastDialogState extends State<AutoCastDialog> {- final bool doesUserExist = true;final Set<Object> _isDeviceTapInProgress = {};@overridediff --git a/mobile/apps/photos/lib/ui/cast/cast.dart b/mobile/apps/photos/lib/ui/cast/cast.dartindex f624e85cd2..e08d6c59f3 100644--- a/mobile/apps/photos/lib/ui/cast/cast.dart+++ b/mobile/apps/photos/lib/ui/cast/cast.dart@@ -1,5 +1,3 @@-import "dart:io";-import "package:ente_components/ente_components.dart";import "package:flutter/widgets.dart";import "package:hugeicons/hugeicons.dart";@@ -9,38 +7,40 @@ import "package:photos/service_locator.dart";import "package:photos/theme/ente_theme.dart";import "package:photos/ui/cast/pair_with_auto.dart";import "package:photos/ui/cast/pair_with_code.dart";+import "package:photos/ui/settings/cast/cast_settings_page.dart";Future<void> showCastSheet(BuildContext context, Collection collection) async {final l10n = AppLocalizations.of(context);final textStyle = getEnteTextTheme(context);- // Automatic pair is only supported on Android as it uses the Chromecast SDK- if (!Platform.isAndroid) {- return await showPairWithCodeSheet(context, collection);- }await castService.closeActiveCasts();return showBottomSheetComponent(context: context,builder: (_) => BottomSheetComponent(title: l10n.castAlbum,actions: [- Text(l10n.pairWithAutoDesc, style: textStyle.bodyMuted),+ Text(l10n.pairWithAutoDesc, style: textStyle.smallMuted),ButtonComponent(label: l10n.autoPair,variant: .secondary,leading: const HugeIcon(icon: HugeIcons.strokeRoundedTvSmart),+ shouldSurfaceExecutionStates: false,onTap: () async {- await showPairWithAutoSheet(context);+ Navigator.of(context).pop();+ await showPairWithAutoSheet(context, collection);},),- Text(l10n.pairWithCodeDesc, style: textStyle.bodyMuted),+ Text(l10n.pairWithCodeDesc, style: textStyle.smallMuted),ButtonComponent(label: l10n.pairUsingCode,variant: .secondary,leading: const HugeIcon(icon: HugeIcons.strokeRoundedTv02),+ shouldSurfaceExecutionStates: false,onTap: () async {+ Navigator.of(context).pop();await showPairWithCodeSheet(context, collection);},),+ const CastSessionsList(showTitle: true, fallback: SizedBox.shrink()),],),);diff --git a/mobile/apps/photos/lib/ui/cast/pair_with_auto.dart b/mobile/apps/photos/lib/ui/cast/pair_with_auto.dartindex 1efc16d262..0e828fe6af 100644--- a/mobile/apps/photos/lib/ui/cast/pair_with_auto.dart+++ b/mobile/apps/photos/lib/ui/cast/pair_with_auto.dart@@ -1,61 +1,214 @@+import "dart:async";+import "dart:io";++import "package:ente_cast/ente_cast.dart";import "package:ente_components/ente_components.dart";-import "package:flutter/widgets.dart";+import "package:flutter/material.dart";+import "package:logging/logging.dart";+import "package:photos/core/network/network.dart";+import "package:photos/gateways/cast/cast_gateway.dart";import "package:photos/generated/l10n.dart";+import "package:photos/models/collection/collection.dart";import "package:photos/service_locator.dart";+import "package:photos/theme/ente_theme.dart";import "package:photos/ui/common/loading_widget.dart";+import "package:photos/ui/notification/toast.dart";+import "package:photos/utils/dialog_util.dart";+import "package:uuid/uuid.dart";-Future<void> _pairWithAuto() async {}+class _DeviceNotFoundException implements Exception {+ const _DeviceNotFoundException();+}-Future<void> showPairWithAutoSheet(BuildContext context) async {}+Future<void> _pairWithAuto(+ BuildContext context,+ Collection collection,+ String code,+) async {+ final gw = CastGateway(NetworkClient.instance.enteDio);+ final publicKey = await gw.getPublicKey(code);+ if (publicKey == null) {+ throw const _DeviceNotFoundException();+ }+ final castToken = const Uuid().v4();+ final castData = collectionsService.getCastData(+ castToken,+ collection,+ publicKey,+ );+ await gw.publishCastPayload(code, castData, collection.id, castToken);+}-class PairWithAutoSheet extends StatefulWidget {- const PairWithAutoSheet({super.key});+/// Shows the auto-pairing sheet for Cast devices.+Future<void> showPairWithAutoSheet(+ BuildContext context,+ Collection collection,+) async {+ await showBottomSheetComponent<void>(+ context: context,+ builder: (_) => _PairWithAutoSheet(collection: collection),+ );+}++class _PairWithAutoSheet extends StatefulWidget {+ final Collection collection;++ const _PairWithAutoSheet({required this.collection});@override- State<PairWithAutoSheet> createState() => _PairWithAutoSheetState();+ State<_PairWithAutoSheet> createState() => _PairWithAutoSheetState();}-class _PairWithAutoSheetState extends State<PairWithAutoSheet> {+class _PairWithAutoSheetState extends State<_PairWithAutoSheet> {+ final _devicesInProgress = <Object>{};+ final _logger = Logger("PairWithAutoSheet");+@overrideWidget build(BuildContext context) {final l10n = AppLocalizations.of(context);-+ final textStyles = getEnteTextTheme(context);+ final body = Platform.isIOS+ ? "${l10n.autoCastDialogBody}\n${l10n.autoCastiOSPermission}"+ : l10n.autoCastDialogBody;return BottomSheetComponent(title: l10n.connectToDevice,- content: Text(- l10n.autoCastDialogBody + "\n" + l10n.autoCastiOSPermission,- ),+ content: Text(body, style: textStyles.smallMuted),actions: [- FutureBuilder(+ FutureBuilder<List<(String, Object)>>(future: castService.searchDevices(),builder: (_, snapshot) {if (snapshot.hasError) {- return Center(child: Text('Error: ${snapshot.error.toString()}'));+ return Center(child: Text("Error: ${snapshot.error}"));}if (!snapshot.hasData) {return const EnteLoadingWidget();}if (snapshot.data!.isEmpty) {- return Center(child: Text(l10n.noDeviceFound));+ final colors = context.componentColors;+ return Container(+ width: double.infinity,+ padding: const EdgeInsets.symmetric(+ horizontal: Spacing.xl,+ vertical: 14,+ ),+ decoration: BoxDecoration(+ color: colors.fillDark,+ borderRadius: Radii.buttonBorder,+ ),+ child: Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Image.asset(+ "assets/warning-yellow.png",+ width: IconSizes.small,+ height: IconSizes.small,+ ),+ const SizedBox(width: Spacing.sm),+ Flexible(+ child: Text(+ l10n.noDeviceFound,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.center,+ style: TextStyles.bodyBold.copyWith(+ color: colors.textLightest,+ ),+ ),+ ),+ ],+ ),+ );}return Column(crossAxisAlignment: CrossAxisAlignment.start,children: snapshot.data!.map((result) {final device = result.$2;final name = result.$1;- return ButtonComponent(label: name, onTap: () async {});- }),+ return ButtonComponent(+ label: name,+ variant: .secondary,+ isDisabled: _devicesInProgress.contains(device),+ onTap: () async => _connectToDevice(context, device),+ );+ }).toList(),);},),- ButtonComponent(- label: l10n.pair,- variant: ButtonComponentVariant.primary,- onTap: () async {- await _pairWithAuto();- },- ),],);}++ Future<void> _connectToDevice(BuildContext context, Object device) async {+ if (_devicesInProgress.contains(device)) {+ return;+ }+ setState(() => _devicesInProgress.add(device));+ final pairing = Completer<void>();+ try {+ await castService.connectDevice(+ context,+ device,+ collectionID: widget.collection.id,+ onMessage: (message) async {+ if (pairing.isCompleted) {+ return;+ }+ final code = message[CastMessageType.pairCode]?["code"];+ if (code is! String) {+ return;+ }+ await _handlePairCode(context, device, code);+ pairing.complete();+ },+ );+ await pairing.future;+ } catch (e, s) {+ await _handleError(context, device, e, s);+ }+ }++ Future<void> _handlePairCode(+ BuildContext context,+ Object device,+ String code,+ ) async {+ try {+ await _pairWithAuto(context, widget.collection, code);+ if (mounted) {+ await Navigator.maybePop(context);+ }+ } catch (e, s) {+ await _handleError(context, device, e, s);+ } finally {+ if (mounted) {+ setState(() => _devicesInProgress.remove(device));+ }+ }+ }++ Future<void> _handleError(+ BuildContext context,+ Object device,+ Object error,+ StackTrace stackTrace,+ ) async {+ final l10n = AppLocalizations.of(context);+ _logger.severe("Failed to pair automatically", error, stackTrace);+ if (mounted) {+ setState(() => _devicesInProgress.remove(device));+ }+ if (error is CastIPMismatchException) {+ await showErrorDialog(+ context,+ l10n.castIPMismatchTitle,+ l10n.castIPMismatchBody,+ );+ return;+ }+ if (error is _DeviceNotFoundException) {+ showToast(context, l10n.deviceNotFound);+ return;+ }+ await showGenericErrorDialog(context: context, error: error);+ }}diff --git a/mobile/apps/photos/lib/ui/cast/pair_with_code.dart b/mobile/apps/photos/lib/ui/cast/pair_with_code.dartindex 7da18fb79a..ce87b6f4f4 100644--- a/mobile/apps/photos/lib/ui/cast/pair_with_code.dart+++ b/mobile/apps/photos/lib/ui/cast/pair_with_code.dart@@ -6,6 +6,7 @@ import "package:photos/gateways/cast/cast_gateway.dart";import "package:photos/generated/l10n.dart";import "package:photos/models/collection/collection.dart";import "package:photos/service_locator.dart";+import "package:photos/theme/ente_theme.dart";import "package:photos/ui/notification/toast.dart";import "package:photos/utils/dialog_util.dart";import "package:uuid/uuid.dart";@@ -62,9 +63,13 @@ class _PairWithCodeSheetState extends State<_PairWithCodeSheet> {Widget build(BuildContext context) {final l10n = AppLocalizations.of(context);final logger = Logger("PairWithCodeSheet");+ final textStyles = getEnteTextTheme(context);return BottomSheetComponent(title: l10n.castAlbum,- content: Text(l10n.castInstruction(castUrl: flagService.castUrl)),+ content: Text(+ l10n.castInstruction(castUrl: flagService.castUrl),+ style: textStyles.smallMuted,+ ),actions: [TextInputComponent(controller: _controller,diff --git a/mobile/apps/photos/lib/ui/settings/cast/cast_settings_page.dart b/mobile/apps/photos/lib/ui/settings/cast/cast_settings_page.dartindex cf2c12fd86..099abe790b 100644--- a/mobile/apps/photos/lib/ui/settings/cast/cast_settings_page.dart+++ b/mobile/apps/photos/lib/ui/settings/cast/cast_settings_page.dart@@ -1,4 +1,3 @@-import "package:collection/collection.dart";import "package:ente_components/ente_components.dart";import "package:flutter/material.dart";import "package:hugeicons/hugeicons.dart";@@ -11,100 +10,105 @@ import "package:photos/ui/settings/components/settings_item.dart";import "package:photos/ui/settings/components/settings_page_scaffold.dart";import 'package:timeago/timeago.dart' as timeago;-class CastSettingsPage extends StatefulWidget {+class CastSettingsPage extends StatelessWidget {const CastSettingsPage({super.key});@override- State<CastSettingsPage> createState() => _CastSettingsPageState();+ Widget build(BuildContext context) {+ final l10n = AppLocalizations.of(context);+ final textTheme = getEnteTextTheme(context);+ return SettingsPageScaffold(+ title: l10n.castSessions,+ children: [+ CastSessionsList(+ showTitle: false,+ fallback: Column(+ mainAxisAlignment: MainAxisAlignment.center,+ crossAxisAlignment: CrossAxisAlignment.center,+ children: [+ SizedBox(height: MediaQuery.sizeOf(context).height * 0.5 - 200),+ Image.asset("assets/empty_casts.png"),+ const SizedBox(height: 16),+ Text(l10n.noSessionsFound, style: textTheme.h4Bold),+ ],+ ),+ ),+ ],+ );+ }+}++/// Displays active cast sessions or the provided fallback when empty.+class CastSessionsList extends StatefulWidget {+ /// Creates a cast sessions list.+ const CastSessionsList({+ required this.showTitle,+ required this.fallback,+ super.key,+ });++ /// Whether to display the active sessions title.+ final bool showTitle;++ /// Widget shown when there are no cast sessions.+ final Widget fallback;++ @override+ State<CastSessionsList> createState() => _CastSessionsListState();}-class _CastSettingsPageState extends State<CastSettingsPage> {- Future<List<CastInfo>>? _castSessionsFuture;+class _CastSessionsListState extends State<CastSessionsList> {+ late Future<List<CastInfo>> _sessionsFuture;@overridevoid initState() {super.initState();- _castSessionsFuture = _load();+ _sessionsFuture = CastGateway(+ NetworkClient.instance.enteDio,+ ).getAllCastSessions();}@overrideWidget build(BuildContext context) {final l10n = AppLocalizations.of(context);- final gw = CastGateway(NetworkClient.instance.enteDio);final textTheme = getEnteTextTheme(context);-- return SettingsPageScaffold(- title: l10n.castSessions,- children: [- FutureBuilder(- future: _castSessionsFuture,- builder: (context, snapshot) {- if (snapshot.connectionState == ConnectionState.waiting) {- return const Center(child: CircularProgressIndicator());- }- if (snapshot.hasError) {- throw snapshot.error!;- }- if (!snapshot.hasData || snapshot.data == null) {- throw Exception(- "There is no data returned by getAllCastSessions",- );- }- if (snapshot.data!.isEmpty) {- return Column(- mainAxisAlignment: MainAxisAlignment.center,- crossAxisAlignment: CrossAxisAlignment.center,- children: [- SizedBox(- height: MediaQuery.sizeOf(context).height * 0.5 - 200,- ),- Image.asset("assets/empty_casts.png"),- const SizedBox(height: 16),- Text(l10n.noSessionsFound, style: textTheme.h4Bold),- ],- );- }- return Column(- children: snapshot.data!- .map((session) {- final collection = CollectionsService.instance- .getCollectionByID(session.collectionID);- final title =- collection?.displayName ??- session.collectionID.toString();- return [- SettingsItem(- title:- "$title on ${session.deviceName ?? session.deviceIP}",- subtitle: timeago.format(session.lastUsedAt),- icon: HugeIcons.strokeRoundedTvSmart,- showOnlyLoadingState: true,- trailing: IconButtonComponent(- icon: const HugeIcon(- icon: HugeIcons.strokeRoundedCancel01,- size: IconSizes.small,- strokeWidth: 1.6,- ),- onTap: () async {- await _revokeSession(gw, session);- },- shouldShowSuccessConfirmation: false,- ),- ),- const SizedBox(height: 16),- ];- })- .flattened- .toList(),- );- },- ),- ],+ return FutureBuilder(+ future: _sessionsFuture,+ builder: (context, snapshot) {+ if (snapshot.connectionState == ConnectionState.waiting) {+ return const Center(child: CircularProgressIndicator());+ }+ if (snapshot.hasError) {+ throw snapshot.error!;+ }+ if (!snapshot.hasData || snapshot.data == null) {+ throw Exception("There is no data returned by getAllCastSessions");+ }+ if (snapshot.data!.isEmpty) {+ return widget.fallback;+ }+ return Column(+ children: [+ if (widget.showTitle) ...[+ Text(l10n.activeSessions, style: textTheme.h4Bold),+ const SizedBox(height: 16),+ ],+ for (final session in snapshot.data!) ...[+ _CastSessionItem(+ session: session,+ onRevokeSession: _revokeSession,+ ),+ const SizedBox(height: 16),+ ],+ ],+ );+ },);}- Future<void> _revokeSession(CastGateway gw, CastInfo session) async {+ Future<void> _revokeSession(CastInfo session) async {final l10n = AppLocalizations.of(context);+ final gw = CastGateway(NetworkClient.instance.enteDio);await showBottomSheetComponent<void>(context: context,builder: (sheetContext) => BottomSheetComponent(@@ -118,7 +122,7 @@ class _CastSettingsPageState extends State<CastSettingsPage> {onTap: () async {Navigator.of(sheetContext).pop();await gw.revokeSession(session);- await _refresh();+ _refresh();},),],@@ -126,14 +130,46 @@ class _CastSettingsPageState extends State<CastSettingsPage> {);}- Future<List<CastInfo>> _load() {- final gw = CastGateway(NetworkClient.instance.enteDio);- return gw.getAllCastSessions();- }-- Future<void> _refresh() async {+ void _refresh() {setState(() {- _castSessionsFuture = _load();+ _sessionsFuture = CastGateway(+ NetworkClient.instance.enteDio,+ ).getAllCastSessions();});}}++class _CastSessionItem extends StatelessWidget {+ const _CastSessionItem({+ required this.session,+ required this.onRevokeSession,+ });++ final CastInfo session;+ final Future<void> Function(CastInfo session) onRevokeSession;++ @override+ Widget build(BuildContext context) {+ final collection = CollectionsService.instance.getCollectionByID(+ session.collectionID,+ );+ final title = collection?.displayName ?? session.collectionID.toString();+ return SettingsItem(+ title: "$title on ${session.deviceName ?? session.deviceIP}",+ subtitle: timeago.format(session.lastUsedAt),+ icon: HugeIcons.strokeRoundedTvSmart,+ showOnlyLoadingState: true,+ trailing: IconButtonComponent(+ icon: const HugeIcon(+ icon: HugeIcons.strokeRoundedCancel01,+ size: IconSizes.small,+ strokeWidth: 1.6,+ ),+ onTap: () async {+ await onRevokeSession(session);+ },+ shouldShowSuccessConfirmation: false,+ ),+ );+ }+}