π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mobile][photos] new cast ux
Priyanshu Dangare4d719c7b15d3
diff --git a/mobile/apps/photos/assets/2.0x/empty_casts.png b/mobile/apps/photos/assets/2.0x/empty_casts.pngnew file mode 100644index 0000000000..6f3115f263Binary files /dev/null and b/mobile/apps/photos/assets/2.0x/empty_casts.png differdiff --git a/mobile/apps/photos/assets/3.0x/empty_casts.png b/mobile/apps/photos/assets/3.0x/empty_casts.pngnew file mode 100644index 0000000000..010c40414aBinary files /dev/null and b/mobile/apps/photos/assets/3.0x/empty_casts.png differdiff --git a/mobile/apps/photos/assets/empty_casts.png b/mobile/apps/photos/assets/empty_casts.pngnew file mode 100644index 0000000000..551b092788Binary files /dev/null and b/mobile/apps/photos/assets/empty_casts.png differdiff --git a/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart b/mobile/apps/photos/lib/gateways/cast/cast_gateway.dartindex dc6797b900..7e468112dc 100644--- a/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart+++ b/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart@@ -5,12 +5,14 @@ class CastInfo {final String deviceIP;final String deviceID;final DateTime lastUsedAt;+ final String? deviceName;CastInfo({required this.collectionID,required this.deviceIP,required this.deviceID,required this.lastUsedAt,+ required this.deviceName,});factory CastInfo.fromJson(dynamic json) {@@ -19,6 +21,7 @@ class CastInfo {deviceIP: json["deviceIP"],deviceID: json["deviceID"],lastUsedAt: DateTime.fromMicrosecondsSinceEpoch(json["lastUsedAt"]),+ deviceName: json["deviceName"],);}}diff --git a/mobile/apps/photos/lib/l10n/intl_en.arb b/mobile/apps/photos/lib/l10n/intl_en.arbindex 2f8ef87489..e3fd870a31 100644--- a/mobile/apps/photos/lib/l10n/intl_en.arb+++ b/mobile/apps/photos/lib/l10n/intl_en.arb@@ -9,6 +9,8 @@"email": "Email","cancel": "Cancel","cast": "Cast",+ "castSessions": "Cast sessions",+ "noSessionsFound": "No sessions found!","verify": "Verify","invalidEmailAddress": "Invalid email address","validEmailAddress": "Valid email address",@@ -1842,8 +1844,8 @@"removePersonLabel": "Remove person label","removePersonTag": "Remove person tag","areYouSureRemoveThisPersonTag": "Are you sure you want to remove this person tag?",- "autoPairDesc": "Auto pair works only with devices that support Chromecast.",- "manualPairDesc": "Pair with PIN works with any screen you wish to view your album on.",+ "pairWithAutoDesc": "Auto pair works only with devices that support Cast.",+ "pairWithCodeDesc": "Pair with PIN works with any screen you wish to view your album on.","connectToDevice": "Connect to device","autoCastDialogBody": "You'll see available Cast devices here.","autoCastiOSPermission": "Make sure Local Network permissions are turned on for the Ente Photos app, in Settings.",@@ -1855,7 +1857,7 @@"pairingComplete": "Pairing complete","savingEdits": "Saving edits...","autoPair": "Auto pair",- "pairWithPin": "Pair with PIN",+ "pairUsingCode": "Pair using code","faceRecognition": "Face recognition","foundFaces": "Found faces","clusteringProgress": "Clustering progress",diff --git a/mobile/apps/photos/lib/ui/cast/cast.dart b/mobile/apps/photos/lib/ui/cast/cast.dartnew file mode 100644index 0000000000..f624e85cd2--- /dev/null+++ b/mobile/apps/photos/lib/ui/cast/cast.dart@@ -0,0 +1,47 @@+import "dart:io";++import "package:ente_components/ente_components.dart";+import "package:flutter/widgets.dart";+import "package:hugeicons/hugeicons.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/cast/pair_with_auto.dart";+import "package:photos/ui/cast/pair_with_code.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),+ ButtonComponent(+ label: l10n.autoPair,+ variant: .secondary,+ leading: const HugeIcon(icon: HugeIcons.strokeRoundedTvSmart),+ onTap: () async {+ await showPairWithAutoSheet(context);+ },+ ),+ Text(l10n.pairWithCodeDesc, style: textStyle.bodyMuted),+ ButtonComponent(+ label: l10n.pairUsingCode,+ variant: .secondary,+ leading: const HugeIcon(icon: HugeIcons.strokeRoundedTv02),+ onTap: () async {+ await showPairWithCodeSheet(context, collection);+ },+ ),+ ],+ ),+ );+}diff --git a/mobile/apps/photos/lib/ui/cast/choose.dart b/mobile/apps/photos/lib/ui/cast/choose.dartdeleted file mode 100644index cf012c4e11..0000000000--- a/mobile/apps/photos/lib/ui/cast/choose.dart+++ /dev/null@@ -1,72 +0,0 @@-import "package:flutter/material.dart";-import "package:hugeicons/hugeicons.dart";-import "package:photos/generated/l10n.dart";-import "package:photos/l10n/l10n.dart";-import "package:photos/theme/ente_theme.dart";-import "package:photos/ui/components/buttons/button_widget.dart";-import "package:photos/ui/components/models/button_type.dart";--class CastChooseDialog extends StatefulWidget {- const CastChooseDialog({super.key});-- @override- State<CastChooseDialog> createState() => _CastChooseDialogState();-}--class _CastChooseDialogState extends State<CastChooseDialog> {- final bool doesUserExist = true;-- @override- Widget build(BuildContext context) {- final textStyle = getEnteTextTheme(context);- final AlertDialog alert = AlertDialog(- title: Text(context.l10n.playOnTv, style: textStyle.largeBold),- content: Column(- crossAxisAlignment: CrossAxisAlignment.start,- mainAxisSize: MainAxisSize.min,- children: [- const SizedBox(height: 8),- Text(- AppLocalizations.of(context).autoPairDesc,- style: textStyle.bodyMuted,- ),- const SizedBox(height: 12),- ButtonWidget(- labelText: AppLocalizations.of(context).autoPair,- iconWidget: const HugeIcon(- icon: HugeIcons.strokeRoundedTvSmart,- size: 20,- ),- buttonType: ButtonType.neutral,- buttonSize: ButtonSize.large,- shouldStickToDarkTheme: true,- buttonAction: ButtonAction.first,- shouldSurfaceExecutionStates: false,- isInAlert: true,- ),- const SizedBox(height: 36),- Text(- AppLocalizations.of(context).manualPairDesc,- style: textStyle.bodyMuted,- ),- const SizedBox(height: 12),- ButtonWidget(- labelText: AppLocalizations.of(context).pairWithPin,- buttonType: ButtonType.neutral,- iconWidget: const HugeIcon(- icon: HugeIcons.strokeRoundedTv02,- size: 20,- ),- buttonSize: ButtonSize.large,- isInAlert: true,-- shouldStickToDarkTheme: true,- buttonAction: ButtonAction.second,- shouldSurfaceExecutionStates: false,- ),- ],- ),- );- return alert;- }-}diff --git a/mobile/apps/photos/lib/ui/cast/pair_with_auto.dart b/mobile/apps/photos/lib/ui/cast/pair_with_auto.dartnew file mode 100644index 0000000000..1efc16d262--- /dev/null+++ b/mobile/apps/photos/lib/ui/cast/pair_with_auto.dart@@ -0,0 +1,61 @@+import "package:ente_components/ente_components.dart";+import "package:flutter/widgets.dart";+import "package:photos/generated/l10n.dart";+import "package:photos/service_locator.dart";+import "package:photos/ui/common/loading_widget.dart";++Future<void> _pairWithAuto() async {}++Future<void> showPairWithAutoSheet(BuildContext context) async {}++class PairWithAutoSheet extends StatefulWidget {+ const PairWithAutoSheet({super.key});++ @override+ State<PairWithAutoSheet> createState() => _PairWithAutoSheetState();+}++class _PairWithAutoSheetState extends State<PairWithAutoSheet> {+ @override+ Widget build(BuildContext context) {+ final l10n = AppLocalizations.of(context);++ return BottomSheetComponent(+ title: l10n.connectToDevice,+ content: Text(+ l10n.autoCastDialogBody + "\n" + l10n.autoCastiOSPermission,+ ),+ actions: [+ FutureBuilder(+ future: castService.searchDevices(),+ builder: (_, snapshot) {+ if (snapshot.hasError) {+ return Center(child: Text('Error: ${snapshot.error.toString()}'));+ }+ if (!snapshot.hasData) {+ return const EnteLoadingWidget();+ }+ if (snapshot.data!.isEmpty) {+ return Center(child: Text(l10n.noDeviceFound));+ }+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: snapshot.data!.map((result) {+ final device = result.$2;+ final name = result.$1;+ return ButtonComponent(label: name, onTap: () async {});+ }),+ );+ },+ ),+ ButtonComponent(+ label: l10n.pair,+ variant: ButtonComponentVariant.primary,+ onTap: () async {+ await _pairWithAuto();+ },+ ),+ ],+ );+ }+}diff --git a/mobile/apps/photos/lib/ui/cast/pair_with_code.dart b/mobile/apps/photos/lib/ui/cast/pair_with_code.dartnew file mode 100644index 0000000000..7da18fb79a--- /dev/null+++ b/mobile/apps/photos/lib/ui/cast/pair_with_code.dart@@ -0,0 +1,106 @@+import "package:ente_components/ente_components.dart";+import "package:flutter/widgets.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/ui/notification/toast.dart";+import "package:photos/utils/dialog_util.dart";+import "package:uuid/uuid.dart";++Future<bool> _pairWithCode(+ BuildContext context,+ Collection collection,+ String code,+) async {+ final gw = CastGateway(NetworkClient.instance.enteDio);+ final publicKey = await gw.getPublicKey(code);+ if (publicKey == null) {+ return false;+ }+ final castToken = const Uuid().v4();+ final castData = collectionsService.getCastData(+ castToken,+ collection,+ publicKey,+ );+ await gw.publishCastPayload(code, castData, collection.id, castToken);+ return true;+}++Future<void> showPairWithCodeSheet(+ BuildContext context,+ Collection collection,+) async {+ return await showBottomSheetComponent(+ context: context,+ builder: (_) => _PairWithCodeSheet(collection: collection),+ );+}++class _PairWithCodeSheet extends StatefulWidget {+ final Collection collection;++ const _PairWithCodeSheet({required this.collection});++ @override+ State<_PairWithCodeSheet> createState() => _PairWithCodeSheetState();+}++class _PairWithCodeSheetState extends State<_PairWithCodeSheet> {+ final _controller = TextEditingController();++ @override+ void dispose() {+ _controller.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final l10n = AppLocalizations.of(context);+ final logger = Logger("PairWithCodeSheet");+ return BottomSheetComponent(+ title: l10n.castAlbum,+ content: Text(l10n.castInstruction(castUrl: flagService.castUrl)),+ actions: [+ TextInputComponent(+ controller: _controller,+ maxLength: 6,+ autocorrect: false,+ autofocus: true,+ hintText: l10n.pairUsingCode,+ keyboardType: .streetAddress,+ ),+ ButtonComponent(+ label: l10n.pair,+ variant: .primary,+ onTap: () async {+ try {+ if (!await _pairWithCode(+ context,+ widget.collection,+ _controller.text,+ )) {+ showToast(context, l10n.deviceNotFound);+ }+ } catch (e, s) {+ if (e is CastIPMismatchException) {+ await showErrorDialog(+ context,+ l10n.castIPMismatchTitle,+ l10n.castIPMismatchBody,+ );+ } else {+ logger.severe('Failed to pair with code: ', e, s);+ await showGenericErrorDialog(context: context, error: e);+ }+ }+ },+ ),+ ],+ );+ }+}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 2be3fecc59..cf2c12fd86 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@@ -6,9 +6,9 @@ import "package:photos/core/network/network.dart";import "package:photos/gateways/cast/cast_gateway.dart";import "package:photos/generated/l10n.dart";import "package:photos/services/collections_service.dart";+import "package:photos/theme/ente_theme.dart";import "package:photos/ui/settings/components/settings_item.dart";import "package:photos/ui/settings/components/settings_page_scaffold.dart";-import "package:photos/utils/dialog_util.dart";import 'package:timeago/timeago.dart' as timeago;class CastSettingsPage extends StatefulWidget {@@ -31,9 +31,10 @@ class _CastSettingsPageState extends State<CastSettingsPage> {Widget build(BuildContext context) {final l10n = AppLocalizations.of(context);final gw = CastGateway(NetworkClient.instance.enteDio);+ final textTheme = getEnteTextTheme(context);return SettingsPageScaffold(- title: l10n.cast,+ title: l10n.castSessions,children: [FutureBuilder(future: _castSessionsFuture,@@ -44,13 +45,25 @@ class _CastSettingsPageState extends State<CastSettingsPage> {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) {@@ -61,13 +74,14 @@ class _CastSettingsPageState extends State<CastSettingsPage> {session.collectionID.toString();return [SettingsItem(- title: "$title on ${session.deviceIP}",+ title:+ "$title on ${session.deviceName ?? session.deviceIP}",subtitle: timeago.format(session.lastUsedAt),- icon: HugeIcons.strokeRoundedTv01,+ icon: HugeIcons.strokeRoundedTvSmart,+ showOnlyLoadingState: true,trailing: IconButtonComponent(- icon: HugeIcon(+ icon: const HugeIcon(icon: HugeIcons.strokeRoundedCancel01,- color: context.componentColors.warning,size: IconSizes.small,strokeWidth: 1.6,),@@ -91,18 +105,25 @@ class _CastSettingsPageState extends State<CastSettingsPage> {Future<void> _revokeSession(CastGateway gw, CastInfo session) async {final l10n = AppLocalizations.of(context);- final result = await showChoiceDialog(- context,- title: l10n.stopCastingTitle,- body: l10n.stopCastingBody,- firstButtonLabel: l10n.yes,- secondButtonLabel: l10n.no,+ await showBottomSheetComponent<void>(+ context: context,+ builder: (sheetContext) => BottomSheetComponent(+ title: l10n.stopCastingTitle,+ message: l10n.stopCastingBody,+ illustration: Image.asset("assets/warning-grey.png"),+ actions: [+ ButtonComponent(+ label: l10n.stopCastingTitle,+ variant: ButtonComponentVariant.critical,+ onTap: () async {+ Navigator.of(sheetContext).pop();+ await gw.revokeSession(session);+ await _refresh();+ },+ ),+ ],+ ),);- if (result?.action != .first) {- return;- }- await gw.revokeSession(session);- await _refresh();}Future<List<CastInfo>> _load() {diff --git a/mobile/apps/photos/lib/ui/settings_page.dart b/mobile/apps/photos/lib/ui/settings_page.dartindex ca45f462df..2ff97365ed 100644--- a/mobile/apps/photos/lib/ui/settings_page.dart+++ b/mobile/apps/photos/lib/ui/settings_page.dart@@ -431,8 +431,8 @@ class _SettingsBody extends StatelessWidget {),if (flagService.enableMultiCast)_buildMenuItem(- title: AppLocalizations.of(context).cast,- icon: HugeIcons.strokeRoundedTv02,+ title: AppLocalizations.of(context).castSessions,+ icon: HugeIcons.strokeRoundedTvSmart,onTap: () async {await routeToPage(context, const CastSettingsPage());},diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/gallery_app_bar_widget.dart b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_app_bar_widget.dartindex d2255e9ad1..175a79a308 100644--- a/mobile/apps/photos/lib/ui/viewer/gallery/gallery_app_bar_widget.dart+++ b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_app_bar_widget.dart@@ -3,7 +3,6 @@ import 'dart:io';import "package:ente_components/ente_components.dart";import 'package:ente_pure_utils/ente_pure_utils.dart';-import "package:flutter/foundation.dart";import 'package:flutter/material.dart';import "package:hugeicons/hugeicons.dart";import "package:local_auth/local_auth.dart";@@ -11,16 +10,12 @@ import 'package:logging/logging.dart';import 'package:photos/core/configuration.dart';import "package:photos/core/constants.dart";import 'package:photos/core/event_bus.dart';-import "package:photos/core/network/network.dart";import "package:photos/db/files_db.dart";import "package:photos/events/collection_meta_event.dart";import "package:photos/events/guest_view_event.dart";import "package:photos/events/magic_sort_change_event.dart";import 'package:photos/events/subscription_purchased_event.dart';-import "package:photos/gateways/cast/cast_gateway.dart";import "package:photos/generated/l10n.dart";-import "package:photos/l10n/l10n.dart";-import "package:photos/models/button_result.dart";import 'package:photos/models/collection/collection.dart';import 'package:photos/models/device_collection.dart';import "package:photos/models/file/file.dart";@@ -34,8 +29,7 @@ import "package:photos/services/files_service.dart";import "package:photos/states/location_screen_state.dart";import "package:photos/theme/ente_theme.dart";import 'package:photos/ui/actions/collection/collection_sharing_actions.dart';-import "package:photos/ui/cast/auto.dart";-import "package:photos/ui/cast/choose.dart";+import "package:photos/ui/cast/cast.dart";import "package:photos/ui/collections/album/smart_album_people.dart";import "package:photos/ui/common/web_page.dart";import 'package:photos/ui/components/action_sheet_widget.dart';@@ -59,7 +53,6 @@ import 'package:photos/utils/delete_file_util.dart';import 'package:photos/utils/dialog_util.dart';import "package:photos/utils/file_download_util.dart";import 'package:photos/utils/magic_util.dart';-import "package:uuid/uuid.dart";class GalleryAppBarWidget extends StatefulWidget {static const double toolbarHeight = kToolbarHeight;@@ -568,7 +561,7 @@ class _GalleryAppBarWidgetState extends State<GalleryAppBarWidget> {} else if (value == AlbumPopupAction.leave) {await _leaveAlbum(context);} else if (value == AlbumPopupAction.castAlbum) {- await _castChoiceDialog();+ await showCastSheet(context, widget.collection!);} else if (value == AlbumPopupAction.autoAddPhotos) {await routeToPage(context,@@ -1188,134 +1181,134 @@ class _GalleryAppBarWidgetState extends State<GalleryAppBarWidget> {setState(() {});}- Future<void> _castChoiceDialog() async {- final gw = CastGateway(NetworkClient.instance.enteDio);-- if (!flagService.enableMultiCast) {- if (castService.getActiveSessions().isNotEmpty) {- await showChoiceDialog(- context,- title: AppLocalizations.of(context).stopCastingTitle,- firstButtonLabel: AppLocalizations.of(context).yes,- secondButtonLabel: AppLocalizations.of(context).no,- body: AppLocalizations.of(context).stopCastingBody,- firstButtonOnTap: () async {- gw.revokeAllTokens().ignore();- await castService.closeActiveCasts();- },- );- return;- }- // stop any existing cast session- gw.revokeAllTokens().ignore();- } else {- await castService.closeActiveCasts();- }-- if (!Platform.isAndroid && !kDebugMode) {- await _pairWithPin(gw, '');- } else {- final result = await showDialog<ButtonResult?>(- context: context,- barrierDismissible: true,- useRootNavigator: false,- builder: (BuildContext context) {- return const CastChooseDialog();- },- );- if (result == null) {- return;- }- // wait to allow the dialog to close- await Future.delayed(const Duration(milliseconds: 100));- if (result.action == ButtonAction.first) {- await showDialog(- useRootNavigator: false,- context: context,- barrierDismissible: true,- builder: (BuildContext bContext) {- return AutoCastDialog((device) async {- await _castPair(bContext, gw, device);- Navigator.pop(bContext);- });- },- );- }- if (result.action == ButtonAction.second) {- await _pairWithPin(gw, '');- }- }- }-- Future<void> _pairWithPin(CastGateway gw, String code) async {- await showTextInputDialog(- context,- title: context.l10n.playOnTv,- body: AppLocalizations.of(- context,- ).castInstruction(castUrl: flagService.castUrl),- submitButtonLabel: AppLocalizations.of(context).pair,- textInputType: TextInputType.streetAddress,- hintText: context.l10n.deviceCodeHint,- showOnlyLoadingState: true,- alwaysShowSuccessState: false,- initialValue: code,- onSubmit: (String text) async {- final bool paired = await _castPair(context, gw, text);- if (!paired) {- Future.delayed(Duration.zero, () => _pairWithPin(gw, code));- }- },- );- }-- String lastCode = '';- Future<bool> _castPair(- BuildContext bContext,- CastGateway gw,- String code,- ) async {- try {- if (lastCode == code) {- return false;- }- lastCode = code;- _logger.info("Casting album to device with code $code");- final String? publicKey = await gw.getPublicKey(code);- if (publicKey == null) {- showToast(context, AppLocalizations.of(context).deviceNotFound);-- return false;- }- final String castToken = const Uuid().v4().toString();- final castPayload = CollectionsService.instance.getCastData(- castToken,- widget.collection!,- publicKey,- );- await gw.publishCastPayload(- code,- castPayload,- widget.collection!.id,- castToken,- );- _logger.info("cast album completed");- return true;- } catch (e, s) {- lastCode = '';- _logger.severe("Failed to cast album", e, s);- if (e is CastIPMismatchException) {- await showErrorDialog(- context,- AppLocalizations.of(context).castIPMismatchTitle,- AppLocalizations.of(context).castIPMismatchBody,- );- } else {- await showGenericErrorDialog(context: bContext, error: e);- }- return false;- }- }+ // Future<void> _castChoiceDialog() async {+ // final gw = CastGateway(NetworkClient.instance.enteDio);++ // if (!flagService.enableMultiCast) {+ // if (castService.getActiveSessions().isNotEmpty) {+ // await showChoiceDialog(+ // context,+ // title: AppLocalizations.of(context).stopCastingTitle,+ // firstButtonLabel: AppLocalizations.of(context).yes,+ // secondButtonLabel: AppLocalizations.of(context).no,+ // body: AppLocalizations.of(context).stopCastingBody,+ // firstButtonOnTap: () async {+ // gw.revokeAllTokens().ignore();+ // await castService.closeActiveCasts();+ // },+ // );+ // return;+ // }+ // // stop any existing cast session+ // gw.revokeAllTokens().ignore();+ // } else {+ // await castService.closeActiveCasts();+ // }++ // if (!Platform.isAndroid && !kDebugMode) {+ // await _pairWithPin(gw, '');+ // } else {+ // final result = await showDialog<ButtonResult?>(+ // context: context,+ // barrierDismissible: true,+ // useRootNavigator: false,+ // builder: (BuildContext context) {+ // return const CastChooseDialog();+ // },+ // );+ // if (result == null) {+ // return;+ // }+ // // wait to allow the dialog to close+ // await Future.delayed(const Duration(milliseconds: 100));+ // if (result.action == ButtonAction.first) {+ // await showDialog(+ // useRootNavigator: false,+ // context: context,+ // barrierDismissible: true,+ // builder: (BuildContext bContext) {+ // return AutoCastDialog((device) async {+ // await _castPair(bContext, gw, device);+ // Navigator.pop(bContext);+ // });+ // },+ // );+ // }+ // if (result.action == ButtonAction.second) {+ // await _pairWithPin(gw, '');+ // }+ // }+ // }++ // Future<void> _pairWithPin(CastGateway gw, String code) async {+ // await showTextInputDialog(+ // context,+ // title: context.l10n.playOnTv,+ // body: AppLocalizations.of(+ // context,+ // ).castInstruction(castUrl: flagService.castUrl),+ // submitButtonLabel: AppLocalizations.of(context).pair,+ // textInputType: TextInputType.streetAddress,+ // hintText: context.l10n.deviceCodeHint,+ // showOnlyLoadingState: true,+ // alwaysShowSuccessState: false,+ // initialValue: code,+ // onSubmit: (String text) async {+ // final bool paired = await _castPair(context, gw, text);+ // if (!paired) {+ // Future.delayed(Duration.zero, () => _pairWithPin(gw, code));+ // }+ // },+ // );+ // }++ // String lastCode = '';+ // Future<bool> _castPair(+ // BuildContext bContext,+ // CastGateway gw,+ // String code,+ // ) async {+ // try {+ // if (lastCode == code) {+ // return false;+ // }+ // lastCode = code;+ // _logger.info("Casting album to device with code $code");+ // final String? publicKey = await gw.getPublicKey(code);+ // if (publicKey == null) {+ // showToast(context, AppLocalizations.of(context).deviceNotFound);++ // return false;+ // }+ // final String castToken = const Uuid().v4().toString();+ // final castPayload = CollectionsService.instance.getCastData(+ // castToken,+ // widget.collection!,+ // publicKey,+ // );+ // await gw.publishCastPayload(+ // code,+ // castPayload,+ // widget.collection!.id,+ // castToken,+ // );+ // _logger.info("cast album completed");+ // return true;+ // } catch (e, s) {+ // lastCode = '';+ // _logger.severe("Failed to cast album", e, s);+ // if (e is CastIPMismatchException) {+ // await showErrorDialog(+ // context,+ // AppLocalizations.of(context).castIPMismatchTitle,+ // AppLocalizations.of(context).castIPMismatchBody,+ // );+ // } else {+ // await showGenericErrorDialog(context: bContext, error: e);+ // }+ // return false;+ // }+ // }Future<void> _onGalleryGuestViewClick() async {if (await LocalAuthentication().isDeviceSupported()) {diff --git a/server/ente/cast/entity.go b/server/ente/cast/entity.goindex 62befaf82a..4d24c18bf2 100644--- a/server/ente/cast/entity.go+++ b/server/ente/cast/entity.go@@ -11,7 +11,8 @@ type CastRequest struct {}type RegisterDeviceRequest struct {- PublicKey string `json:"publicKey" binding:"required"`+ PublicKey string `json:"publicKey" binding:"required"`+ DeviceName *string `json:"deviceName"`}type AuthContext struct {@@ -24,4 +25,5 @@ type CastInfo struct {CollectionID int64 `json:"collectionID"`DeviceIP string `json:"deviceIP"`LastUsedAt int64 `json:"lastUsedAt"`+ DeviceName *string `json:"deviceName"`}diff --git a/server/migrations/78_cast.up.sql b/server/migrations/78_cast.up.sqlindex 602db3b9ac..8d4d90c6d5 100644--- a/server/migrations/78_cast.up.sql+++ b/server/migrations/78_cast.up.sql@@ -6,6 +6,7 @@ CREATE TABLE IF NOT EXISTS castingpublic_key VARCHAR(512) NOT NULL,collection_id BIGINT,cast_user BIGINT,+ device_name VARCHAR(512) DEFAULT NULL,encrypted_payload text,token VARCHAR(512),is_deleted BOOLEAN DEFAULT FALSE,diff --git a/server/pkg/controller/cast/controller.go b/server/pkg/controller/cast/controller.goindex 7813780170..dac719ddb5 100644--- a/server/pkg/controller/cast/controller.go+++ b/server/pkg/controller/cast/controller.go@@ -29,7 +29,7 @@ func NewController(castRepo *castRepo.Repository,}func (c *Controller) RegisterDevice(ctx *gin.Context, request *cast.RegisterDeviceRequest) (string, error) {- return c.CastRepo.AddCode(ctx, request.PublicKey, network.GetClientIP(ctx))+ return c.CastRepo.AddCode(ctx, request.PublicKey, network.GetClientIP(ctx), request.DeviceName)}func (c *Controller) GetAllDevices(ctx *gin.Context, userID int64) ([]cast.CastInfo, error) {diff --git a/server/pkg/repo/cast/repo.go b/server/pkg/repo/cast/repo.goindex 7fc76ec786..1c7488c9e3 100644--- a/server/pkg/repo/cast/repo.go+++ b/server/pkg/repo/cast/repo.go@@ -17,13 +17,13 @@ type Repository struct {DB *sql.DB}-func (r *Repository) AddCode(ctx context.Context, pubKey string, ip string) (string, error) {+func (r *Repository) AddCode(ctx context.Context, pubKey string, ip string, deviceName *string) (string, error) {codeValue, err := random.GenerateAlphaNumString(6)if err != nil {return "", err}codeValue = strings.ToUpper(codeValue)- _, err = r.DB.ExecContext(ctx, "INSERT INTO casting (code, public_key, id, ip) VALUES ($1, $2, $3, $4)", codeValue, pubKey, uuid.New(), ip)+ _, err = r.DB.ExecContext(ctx, "INSERT INTO casting (code, public_key, id, ip, device_name) VALUES ($1, $2, $3, $4, $5)", codeValue, pubKey, uuid.New(), ip, deviceName)if err != nil {return "", err}@@ -31,7 +31,7 @@ func (r *Repository) AddCode(ctx context.Context, pubKey string, ip string) (str}func (r *Repository) GetAllDevices(ctx context.Context, userID int64) ([]cast.CastInfo, error) {- rows, err := r.DB.QueryContext(ctx, "SELECT id, collection_id, ip, last_used_at FROM casting WHERE cast_user = $1 and is_deleted=false ORDER BY created_at DESC", userID)+ rows, err := r.DB.QueryContext(ctx, "SELECT id, collection_id, ip, last_used_at, device_name FROM casting WHERE cast_user = $1 and is_deleted=false ORDER BY created_at DESC", userID)if err != nil {return nil, stacktrace.Propagate(err, "failed to query devices")}@@ -39,7 +39,7 @@ func (r *Repository) GetAllDevices(ctx context.Context, userID int64) ([]cast.Cadevices := make([]cast.CastInfo, 0)for rows.Next() {var device cast.CastInfo- if err := rows.Scan(&device.DeviceID, &device.CollectionID, &device.DeviceIP, &device.LastUsedAt); err != nil {+ if err := rows.Scan(&device.DeviceID, &device.CollectionID, &device.DeviceIP, &device.LastUsedAt, &device.DeviceName); err != nil {return nil, stacktrace.Propagate(err, "failed to scan device row")}devices = append(devices, device)diff --git a/web/apps/cast/package.json b/web/apps/cast/package.jsonindex d28d9900fc..2e6074ae36 100644--- a/web/apps/cast/package.json+++ b/web/apps/cast/package.json@@ -5,7 +5,8 @@"dependencies": {"ente-accounts": "*","ente-base": "*",- "ente-media": "*"+ "ente-media": "*",+ "node-device-detector": "2.2.5"},"devDependencies": {"@types/chromecast-caf-receiver": "6.0.26",diff --git a/web/apps/cast/src/services/pair.ts b/web/apps/cast/src/services/pair.tsindex db521ccb95..9c171c860f 100644--- a/web/apps/cast/src/services/pair.ts+++ b/web/apps/cast/src/services/pair.ts@@ -4,8 +4,11 @@ import log from "ente-base/log";import { apiURL } from "ente-base/origins";import { wait } from "ente-utils/promise";import { nullToUndefined } from "ente-utils/transform";+import DeviceDetector from "node-device-detector";import { z } from "zod";+const deviceDetector = new DeviceDetector({ skipBotDetection: true });+export interface Registration {/** A pairing code shown on the screen. A client can use this to connect. */pairingCode: string;@@ -89,7 +92,10 @@ export const register = async (): Promise<Registration> => {let pairingCode: string | undefined;while (true) {try {- pairingCode = await registerDevice(publicKey);+ pairingCode = await registerDevice({+ publicKey,+ deviceName: deviceNameFromUserAgent(navigator.userAgent),+ });} catch (e) {log.error("Failed to register public key with server", e);}@@ -106,17 +112,28 @@ export const register = async (): Promise<Registration> => {** @returns A device code that can be used to pair with us.*/-const registerDevice = async (publicKey: string) => {+const registerDevice = async (params: {+ publicKey: string;+ deviceName?: string;+}) => {const res = await fetch(await apiURL("/cast/device-info"), {method: "POST",headers: publicRequestHeaders(),- body: JSON.stringify({ publicKey }),+ body: JSON.stringify(params),});ensureOk(res);return z.object({ deviceCode: z.string() }).parse(await res.json()).deviceCode;};+const deviceNameFromUserAgent = (userAgent: string) => {+ const { device, os } = deviceDetector.detect(userAgent);+ return device.model || toTitleCase(device.type) || os.name || undefined;+};++const toTitleCase = (value: string) =>+ value ? value[0]!.toUpperCase() + value.slice(1) : "";+/*** The structure of the (decrypted) payload that is published (e.g.) by* `publishCastPayload` on the photos web/desktop app.diff --git a/web/package-lock.json b/web/package-lock.jsonindex c41c4e135c..efee1be60d 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -133,7 +133,8 @@"dependencies": {"ente-accounts": "*","ente-base": "*",- "ente-media": "*"+ "ente-media": "*",+ "node-device-detector": "2.2.5"},"devDependencies": {"@types/chromecast-caf-receiver": "6.0.26",@@ -8525,6 +8526,16 @@}}},+ "node_modules/node-device-detector": {+ "version": "2.2.5",+ "resolved": "https://registry.npmjs.org/node-device-detector/-/node-device-detector-2.2.5.tgz",+ "integrity": "sha512-5HZI7nMDHGNnFMjWcmSnoJM5X57ZnmyTCIiW6AxYrJGCbpNjgiV8u8z3HAUSykf6PbXgI1/BqY3dlNova+1LNg==",+ "license": "MIT",+ "engines": {+ "node": ">= 10.x",+ "npm": ">= 6.x"+ }+ },"node_modules/node-exports-info": {"version": "1.6.0","resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.0.tgz",