Bring projects, wikis, and teams together with AI. AppFlowy is the AI collaborative workspace where you achieve more without losing control of your data. The leading open source Notion alternative.
Dart blogconfluence-alternativecontent-managementcontent-servicesdocumentationflutternote-takingnotion-alternativeproject-managementtask-managementteam-collaborationwiki
refactor: deeplink handler (#7802)
Lucas48d6a71d96ce
diff --git a/frontend/appflowy_flutter/lib/startup/tasks/appflowy_cloud_task.dart b/frontend/appflowy_flutter/lib/startup/tasks/appflowy_cloud_task.dartindex 144c058ccc..892b9df2ff 100644--- a/frontend/appflowy_flutter/lib/startup/tasks/appflowy_cloud_task.dart+++ b/frontend/appflowy_flutter/lib/startup/tasks/appflowy_cloud_task.dart@@ -5,15 +5,15 @@ import 'package:app_links/app_links.dart';import 'package:appflowy/env/cloud_env.dart';import 'package:appflowy/startup/startup.dart';import 'package:appflowy/startup/tasks/app_widget.dart';+import 'package:appflowy/startup/tasks/deeplink/deeplink_handler.dart';+import 'package:appflowy/startup/tasks/deeplink/expire_login_deeplink_handler.dart';+import 'package:appflowy/startup/tasks/deeplink/invitation_deeplink_handler.dart';+import 'package:appflowy/startup/tasks/deeplink/login_deeplink_handler.dart';+import 'package:appflowy/startup/tasks/deeplink/payment_deeplink_handler.dart';import 'package:appflowy/user/application/auth/auth_error.dart';-import 'package:appflowy/user/application/auth/auth_service.dart';-import 'package:appflowy/user/application/auth/device_id.dart';import 'package:appflowy/user/application/user_auth_listener.dart';-import 'package:appflowy/workspace/application/subscription_success_listenable/subscription_success_listenable.dart';import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';-import 'package:appflowy_backend/dispatch/dispatch.dart';import 'package:appflowy_backend/log.dart';-import 'package:appflowy_backend/protobuf/flowy-error/code.pb.dart';import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';import 'package:appflowy_result/appflowy_result.dart';@@ -24,6 +24,12 @@ const appflowyDeepLinkSchema = 'appflowy-flutter';class AppFlowyCloudDeepLink {AppFlowyCloudDeepLink() {+ _deepLinkHandlerRegistry = DeepLinkHandlerRegistry.instance+ ..register(LoginDeepLinkHandler())+ ..register(PaymentDeepLinkHandler())+ ..register(InvitationDeepLinkHandler())+ ..register(ExpireLoginDeepLinkHandler());+_deepLinkSubscription = _AppLinkWrapper.instance.listen((Uri? uri) async {Log.info('onDeepLink: ${uri.toString()}');@@ -50,6 +56,7 @@ class AppFlowyCloudDeepLink {}late final StreamSubscription<Uri?> _deepLinkSubscription;+ late final DeepLinkHandlerRegistry _deepLinkHandlerRegistry;Future<void> dispose() async {Log.debug('AppFlowyCloudDeepLink: $hashCode dispose');@@ -101,84 +108,69 @@ class AppFlowyCloudDeepLink {return;}- if (_isPaymentSuccessUri(uri)) {- Log.debug("Payment success deep link: ${uri.toString()}");- final plan = uri.queryParameters['plan'];- return getIt<SubscriptionSuccessListenable>().onPaymentSuccess(plan);- }-- return _isAuthCallbackDeepLink(uri).fold(- (_) async {- final deviceId = await getDeviceId();- final payload = OauthSignInPB(- authenticator: AuthTypePB.Server,- map: {- AuthServiceMapKeys.signInURL: uri.toString(),- AuthServiceMapKeys.deviceId: deviceId,- },- );- _stateNotifier?.value = DeepLinkResult(state: DeepLinkState.loading);- final result = await UserEventOauthSignIn(payload).send();-- _stateNotifier?.value = DeepLinkResult(- state: DeepLinkState.finish,- result: result,- );- // If there is no completer, runAppFlowy() will be called.- if (_completer == null) {- await result.fold(- (_) async {- await runAppFlowy();- },- (err) {- Log.error(err);+ await _deepLinkHandlerRegistry.processDeepLink(+ uri: uri,+ onStateChange: (handler, state) {+ // only handle the login deep link+ if (handler is LoginDeepLinkHandler) {+ _stateNotifier?.value = DeepLinkResult(state: state);+ }+ },+ onResult: (handler, result) async {+ if (handler is LoginDeepLinkHandler &&+ result is FlowyResult<UserProfilePB, FlowyError>) {+ // If there is no completer, runAppFlowy() will be called.+ if (_completer == null) {+ await result.fold(+ (_) async {+ await runAppFlowy();+ },+ (err) {+ Log.error(err);+ final context = AppGlobals.rootNavKey.currentState?.context;+ if (context != null) {+ showToastNotification(+ message: err.msg,+ );+ }+ },+ );+ } else {+ _completer?.complete(result);+ completer = null;+ }+ } else if (handler is ExpireLoginDeepLinkHandler) {+ result.onFailure(+ (error) {final context = AppGlobals.rootNavKey.currentState?.context;if (context != null) {showToastNotification(- message: err.msg,+ message: error.msg,+ type: ToastificationType.error,);}},);- } else {- _completer?.complete(result);- completer = null;}},- (err) {- Log.error('onDeepLinkError: Unexpected deep link: $err');+ onError: (error) {+ Log.error('onDeepLinkError: Unexpected deep link: $error');if (_completer == null) {final context = AppGlobals.rootNavKey.currentState?.context;if (context != null) {showToastNotification(- message: err.msg,+ message: error.msg,type: ToastificationType.error,);}} else {- _completer?.complete(FlowyResult.failure(err));+ _completer?.complete(FlowyResult.failure(error));completer = null;}},);}- FlowyResult<void, FlowyError> _isAuthCallbackDeepLink(Uri uri) {- if (uri.fragment.contains('access_token')) {- return FlowyResult.success(null);- }-- return FlowyResult.failure(- FlowyError.create()- ..code = ErrorCode.MissingAuthField- ..msg = uri.path,- );- }-- bool _isPaymentSuccessUri(Uri uri) {- return uri.host == 'payment-success';- }-Uri? _buildDeepLinkUri(GotrueTokenResponsePB gotrueTokenResponse) {final params = <String, String>{};@@ -266,22 +258,6 @@ class InitAppFlowyCloudTask extends LaunchTask {}}-class DeepLinkResult {- DeepLinkResult({- required this.state,- this.result,- });-- final DeepLinkState state;- final FlowyResult<UserProfilePB, FlowyError>? result;-}--enum DeepLinkState {- none,- loading,- finish,-}-// wrapper for AppLinks to support multiple listenersclass _AppLinkWrapper {_AppLinkWrapper._() {diff --git a/frontend/appflowy_flutter/lib/startup/tasks/deeplink/deeplink_handler.dart b/frontend/appflowy_flutter/lib/startup/tasks/deeplink/deeplink_handler.dartnew file mode 100644index 0000000000..67c10fbaa1--- /dev/null+++ b/frontend/appflowy_flutter/lib/startup/tasks/deeplink/deeplink_handler.dart@@ -0,0 +1,94 @@+import 'dart:async';++import 'package:appflowy_backend/log.dart';+import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';+import 'package:appflowy_result/appflowy_result.dart';++typedef DeepLinkResultHandler = void Function(+ DeepLinkHandler handler,+ FlowyResult<dynamic, FlowyError> result,+);++typedef DeepLinkStateHandler = void Function(+ DeepLinkHandler handler,+ DeepLinkState state,+);++typedef DeepLinkErrorHandler = void Function(+ FlowyError error,+);++abstract class DeepLinkHandler<T> {+ /// Checks if this handler should handle the given URI+ bool canHandle(Uri uri);++ /// Handles the deep link URI++ Future<FlowyResult<T, FlowyError>> handle({+ required Uri uri,+ required DeepLinkStateHandler onStateChange,+ });+}++class DeepLinkHandlerRegistry {+ DeepLinkHandlerRegistry._();+ static final instance = DeepLinkHandlerRegistry._();++ final List<DeepLinkHandler> _handlers = [];++ /// Register a new DeepLink handler+ void register(DeepLinkHandler handler) {+ _handlers.add(handler);+ }++ Future<void> processDeepLink({+ required Uri uri,+ required DeepLinkStateHandler onStateChange,+ required DeepLinkResultHandler onResult,+ required DeepLinkErrorHandler onError,+ }) async {+ Log.info('Processing DeepLink: ${uri.toString()}');++ bool handled = false;++ for (final handler in _handlers) {+ if (handler.canHandle(uri)) {+ Log.info('Handler ${handler.runtimeType} will handle the DeepLink');++ final result = await handler.handle(+ uri: uri,+ onStateChange: onStateChange,+ );++ onResult(handler, result);++ handled = true;+ break;+ }+ }++ if (!handled) {+ Log.error('No handler found for DeepLink: ${uri.toString()}');++ onError(+ FlowyError(msg: 'No handler found for DeepLink: ${uri.toString()}'),+ );+ }+ }+}++class DeepLinkResult<T> {+ DeepLinkResult({+ required this.state,+ this.result,+ });+ final DeepLinkState state;+ final FlowyResult<T, FlowyError>? result;+}++enum DeepLinkState {+ none,+ loading,+ finish,+ error,+}diff --git a/frontend/appflowy_flutter/lib/startup/tasks/deeplink/expire_login_deeplink_handler.dart b/frontend/appflowy_flutter/lib/startup/tasks/deeplink/expire_login_deeplink_handler.dartnew file mode 100644index 0000000000..d7513cdc01--- /dev/null+++ b/frontend/appflowy_flutter/lib/startup/tasks/deeplink/expire_login_deeplink_handler.dart@@ -0,0 +1,31 @@+import 'dart:async';++import 'package:appflowy/startup/tasks/deeplink/deeplink_handler.dart';+import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';+import 'package:appflowy_result/appflowy_result.dart';++/// Expire login deeplink example:+/// appflowy-flutter:%23error=access_denied&error_code=403&error_description=Email+link+is+invalid+or+has+expired+class ExpireLoginDeepLinkHandler extends DeepLinkHandler<void> {+ @override+ bool canHandle(Uri uri) {+ final isExpireLogin = uri.toString().contains('error=access_denied');+ if (!isExpireLogin) {+ return false;+ }++ return true;+ }++ @override+ Future<FlowyResult<void, FlowyError>> handle({+ required Uri uri,+ required DeepLinkStateHandler onStateChange,+ }) async {+ return FlowyResult.failure(+ FlowyError(+ msg: 'Magic link is invalid or has expired',+ ),+ );+ }+}diff --git a/frontend/appflowy_flutter/lib/startup/tasks/deeplink/invitation_deeplink_handler.dart b/frontend/appflowy_flutter/lib/startup/tasks/deeplink/invitation_deeplink_handler.dartnew file mode 100644index 0000000000..264cc81b8c--- /dev/null+++ b/frontend/appflowy_flutter/lib/startup/tasks/deeplink/invitation_deeplink_handler.dart@@ -0,0 +1,67 @@+import 'dart:async';++import 'package:appflowy/startup/tasks/deeplink/deeplink_handler.dart';+import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/workspace_notifier.dart';+import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';+import 'package:appflowy_result/appflowy_result.dart';++// invitation callback deeplink example:+// appflowy-flutter://invitation-callback?workspace_id=b2d11122-1fc8-474d-9ef1-ec12fea7ffe8&user_id=275966408418922496+class InvitationDeepLinkHandler extends DeepLinkHandler<void> {+ static const invitationCallbackHost = 'invitation-callback';+ static const invitationCallbackWorkspaceId = 'workspace_id';+ static const invitationCallbackEmail = 'email';++ @override+ bool canHandle(Uri uri) {+ final isInvitationCallback = uri.host == invitationCallbackHost;+ if (!isInvitationCallback) {+ return false;+ }++ final containsWorkspaceId =+ uri.queryParameters.containsKey(invitationCallbackWorkspaceId);+ if (!containsWorkspaceId) {+ return false;+ }++ final containsEmail =+ uri.queryParameters.containsKey(invitationCallbackEmail);+ if (!containsEmail) {+ return false;+ }++ return true;+ }++ @override+ Future<FlowyResult<void, FlowyError>> handle({+ required Uri uri,+ required DeepLinkStateHandler onStateChange,+ }) async {+ final workspaceId = uri.queryParameters[invitationCallbackWorkspaceId];+ final email = uri.queryParameters[invitationCallbackEmail];+ if (workspaceId == null) {+ return FlowyResult.failure(+ FlowyError(+ msg: 'Workspace ID is required',+ ),+ );+ }++ if (email == null) {+ return FlowyResult.failure(+ FlowyError(+ msg: 'Email is required',+ ),+ );+ }++ openWorkspaceNotifier.value = WorkspaceNotifyValue(+ workspaceId: workspaceId,+ email: email,+ );++ return FlowyResult.success(null);+ }+}diff --git a/frontend/appflowy_flutter/lib/startup/tasks/deeplink/login_deeplink_handler.dart b/frontend/appflowy_flutter/lib/startup/tasks/deeplink/login_deeplink_handler.dartnew file mode 100644index 0000000000..5ed8073e2a--- /dev/null+++ b/frontend/appflowy_flutter/lib/startup/tasks/deeplink/login_deeplink_handler.dart@@ -0,0 +1,44 @@+import 'dart:async';++import 'package:appflowy/startup/tasks/deeplink/deeplink_handler.dart';+import 'package:appflowy/user/application/auth/auth_service.dart';+import 'package:appflowy/user/application/auth/device_id.dart';+import 'package:appflowy_backend/dispatch/dispatch.dart';+import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';+import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';+import 'package:appflowy_result/appflowy_result.dart';++class LoginDeepLinkHandler extends DeepLinkHandler<UserProfilePB> {+ @override+ bool canHandle(Uri uri) {+ final containsAccessToken = uri.fragment.contains('access_token');+ if (!containsAccessToken) {+ return false;+ }++ return true;+ }++ @override+ Future<FlowyResult<UserProfilePB, FlowyError>> handle({+ required Uri uri,+ required DeepLinkStateHandler onStateChange,+ }) async {+ final deviceId = await getDeviceId();+ final payload = OauthSignInPB(+ authenticator: AuthTypePB.Server,+ map: {+ AuthServiceMapKeys.signInURL: uri.toString(),+ AuthServiceMapKeys.deviceId: deviceId,+ },+ );++ onStateChange(this, DeepLinkState.loading);++ final result = await UserEventOauthSignIn(payload).send();++ onStateChange(this, DeepLinkState.finish);++ return result;+ }+}diff --git a/frontend/appflowy_flutter/lib/startup/tasks/deeplink/payment_deeplink_handler.dart b/frontend/appflowy_flutter/lib/startup/tasks/deeplink/payment_deeplink_handler.dartnew file mode 100644index 0000000000..d5703a2d7a--- /dev/null+++ b/frontend/appflowy_flutter/lib/startup/tasks/deeplink/payment_deeplink_handler.dart@@ -0,0 +1,24 @@+import 'package:appflowy/startup/startup.dart';+import 'package:appflowy/startup/tasks/deeplink/deeplink_handler.dart';+import 'package:appflowy/workspace/application/subscription_success_listenable/subscription_success_listenable.dart';+import 'package:appflowy_backend/log.dart';+import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';+import 'package:appflowy_result/appflowy_result.dart';++class PaymentDeepLinkHandler extends DeepLinkHandler {+ @override+ bool canHandle(Uri uri) {+ return uri.host == 'payment-success';+ }++ @override+ Future<FlowyResult<dynamic, FlowyError>> handle({+ required Uri uri,+ required DeepLinkStateHandler onStateChange,+ }) async {+ Log.debug("Payment success deep link: ${uri.toString()}");+ final plan = uri.queryParameters['plan'];+ getIt<SubscriptionSuccessListenable>().onPaymentSuccess(plan);+ return FlowyResult.success(null);+ }+}diff --git a/frontend/appflowy_flutter/lib/user/application/sign_in_bloc.dart b/frontend/appflowy_flutter/lib/user/application/sign_in_bloc.dartindex 9691a1269b..2e28db48ad 100644--- a/frontend/appflowy_flutter/lib/user/application/sign_in_bloc.dart+++ b/frontend/appflowy_flutter/lib/user/application/sign_in_bloc.dart@@ -2,6 +2,7 @@ import 'package:appflowy/env/cloud_env.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/startup/startup.dart';import 'package:appflowy/startup/tasks/appflowy_cloud_task.dart';+import 'package:appflowy/startup/tasks/deeplink/deeplink_handler.dart';import 'package:appflowy/user/application/auth/auth_service.dart';import 'package:appflowy_backend/log.dart';import 'package:appflowy_backend/protobuf/flowy-error/code.pb.dart';@@ -130,6 +131,8 @@ class SignInBloc extends Bloc<SignInEvent, SignInState> {if (newState != null) {emit(newState);}+ case DeepLinkState.error:+ emit(state.copyWith(isSubmitting: false));}}@@ -138,6 +141,14 @@ class SignInBloc extends Bloc<SignInEvent, SignInState> {required String email,required String password,}) async {+ emit(+ state.copyWith(+ isSubmitting: true,+ emailError: null,+ passwordError: null,+ successOrFail: null,+ ),+ );final result = await authService.signInWithEmailPassword(email: email,password: password,diff --git a/frontend/appflowy_flutter/lib/user/presentation/screens/sign_in_screen/widgets/continue_with/continue_with_password_page.dart b/frontend/appflowy_flutter/lib/user/presentation/screens/sign_in_screen/widgets/continue_with/continue_with_password_page.dartindex 1e2ed6e100..45989516c4 100644--- a/frontend/appflowy_flutter/lib/user/presentation/screens/sign_in_screen/widgets/continue_with/continue_with_password_page.dart+++ b/frontend/appflowy_flutter/lib/user/presentation/screens/sign_in_screen/widgets/continue_with/continue_with_password_page.dart@@ -32,6 +32,8 @@ class _ContinueWithPasswordPageState extends State<ContinueWithPasswordPage> {final passwordController = TextEditingController();final inputPasswordKey = GlobalKey<AFTextFieldState>();+ bool isSubmitting = false;+@overridevoid dispose() {passwordController.dispose();@@ -60,6 +62,12 @@ class _ContinueWithPasswordPageState extends State<ContinueWithPasswordPage> {} else {inputPasswordKey.currentState?.clearError();}++ if (isSubmitting != state.isSubmitting) {+ setState(() {+ isSubmitting = state.isSubmitting;+ });+ }},child: Column(mainAxisAlignment: MainAxisAlignment.center,@@ -123,6 +131,16 @@ class _ContinueWithPasswordPageState extends State<ContinueWithPasswordPage> {List<Widget> _buildPasswordSection() {final theme = AppFlowyTheme.of(context);final iconSize = 20.0;+ final textStyle = AFButtonSize.l.buildTextStyle(context);+ final textHeight = textStyle.height;+ final textFontSize = textStyle.fontSize;++ // the indicator height is the height of the text style.+ double indicatorHeight = 20;+ if (textHeight != null && textFontSize != null) {+ indicatorHeight = textHeight * textFontSize;+ }+return [// Password inputAFTextField(@@ -144,38 +162,67 @@ class _ContinueWithPasswordPageState extends State<ContinueWithPasswordPage> {onSubmitted: widget.onEnterPassword,),// todo: ask designer to provide the spacing- VSpace(8),+ // VSpace(8),// Forgot password button- Align(- alignment: Alignment.centerLeft,- child: AFGhostTextButton(- text: LocaleKeys.signIn_forgotPassword.tr(),- size: AFButtonSize.s,- padding: EdgeInsets.zero,- onTap: widget.onForgotPassword,- textColor: (context, isHovering, disabled) {- final theme = AppFlowyTheme.of(context);- if (isHovering) {- return theme.fillColorScheme.themeThickHover;- }- return theme.textColorScheme.theme;- },- ),- ),+ // Align(+ // alignment: Alignment.centerLeft,+ // child: AFGhostTextButton(+ // text: LocaleKeys.signIn_forgotPassword.tr(),+ // size: AFButtonSize.s,+ // padding: EdgeInsets.zero,+ // onTap: widget.onForgotPassword,+ // textColor: (context, isHovering, disabled) {+ // final theme = AppFlowyTheme.of(context);+ // if (isHovering) {+ // return theme.fillColorScheme.themeThickHover;+ // }+ // return theme.textColorScheme.theme;+ // },+ // ),+ // ),VSpace(20),// Continue button- AFFilledTextButton.primary(- text: LocaleKeys.web_continue.tr(),- onTap: () => widget.onEnterPassword(passwordController.text),- size: AFButtonSize.l,- alignment: Alignment.center,- ),+ isSubmitting+ ? _buildIndicator(indicatorHeight: indicatorHeight)+ : _buildContinueButton(textStyle: textStyle),VSpace(20),];}+ Widget _buildContinueButton({+ required TextStyle textStyle,+ }) {+ return AFFilledTextButton.primary(+ text: LocaleKeys.web_continue.tr(),+ textStyle: textStyle.copyWith(+ color: AppFlowyTheme.of(context).textColorScheme.onFill,+ ),+ onTap: () => widget.onEnterPassword(passwordController.text),+ size: AFButtonSize.l,+ alignment: Alignment.center,+ );+ }++ Widget _buildIndicator({+ required double indicatorHeight,+ }) {+ return AFFilledButton.disabled(+ size: AFButtonSize.l,+ builder: (context, isHovering, disabled) {+ return Align(+ child: SizedBox.square(+ dimension: indicatorHeight,+ child: CircularProgressIndicator(+ strokeWidth: 3.0,+ ),+ ),+ );+ },+ );+ }+List<Widget> _buildBackToLogin() {return [AFGhostTextButton(diff --git a/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dart b/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dartindex d14f258462..567d4a86e2 100644--- a/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dart+++ b/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dart@@ -20,6 +20,7 @@ part 'user_workspace_bloc.freezed.dart';class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {UserWorkspaceBloc({required this.userProfile,+ this.initialWorkspaceId,}) : _userService = UserBackendService(userId: userProfile.id),_listener = UserListener(userProfile: userProfile),super(UserWorkspaceState.initial()) {@@ -40,7 +41,9 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {},);- final result = await _fetchWorkspaces();+ final result = await _fetchWorkspaces(+ initialWorkspaceId: initialWorkspaceId,+ );final currentWorkspace = result.$1;final workspaces = result.$2;final isCollabWorkspaceOn =@@ -67,8 +70,10 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {),);},- fetchWorkspaces: () async {- final result = await _fetchWorkspaces();+ fetchWorkspaces: (initialWorkspaceId) async {+ final result = await _fetchWorkspaces(+ initialWorkspaceId: initialWorkspaceId,+ );final currentWorkspace = result.$1;final workspaces = result.$2;@@ -432,22 +437,24 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {final UserProfilePB userProfile;final UserBackendService _userService;final UserListener _listener;+ final String? initialWorkspaceId;Future<(UserWorkspacePB? currentWorkspace,List<UserWorkspacePB> workspaces,bool shouldOpenWorkspace,- )> _fetchWorkspaces() async {+ )> _fetchWorkspaces({String? initialWorkspaceId}) async {try {final currentWorkspace =await UserBackendService.getCurrentWorkspace().getOrThrow();+ final currentWorkspaceId = initialWorkspaceId ?? currentWorkspace.id;final workspaces = await _userService.getWorkspaces().getOrThrow();if (workspaces.isEmpty) {workspaces.add(convertWorkspacePBToUserWorkspace(currentWorkspace));}final currentWorkspaceInList = workspaces- .firstWhereOrNull((e) => e.workspaceId == currentWorkspace.id) ??+ .firstWhereOrNull((e) => e.workspaceId == currentWorkspaceId) ??workspaces.firstOrNull;return (currentWorkspaceInList,@@ -474,7 +481,8 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {@freezedclass UserWorkspaceEvent with _$UserWorkspaceEvent {const factory UserWorkspaceEvent.initial() = Initial;- const factory UserWorkspaceEvent.fetchWorkspaces() = FetchWorkspaces;+ const factory UserWorkspaceEvent.fetchWorkspaces({String? initialWorkspaceId}) =+ FetchWorkspaces;const factory UserWorkspaceEvent.createWorkspace(String name,AuthTypePB authType,diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart b/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dartindex 4ff5ccbf67..aa2326ac8c 100644--- a/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart+++ b/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart@@ -24,7 +24,7 @@ import '_sidebar_import_notion.dart';const createWorkspaceButtonKey = ValueKey('createWorkspaceButton');@visibleForTesting-const importNotionButtonKey = ValueKey('importNotinoButton');+const importNotionButtonKey = ValueKey('importNotionButton');class WorkspacesMenu extends StatefulWidget {const WorkspacesMenu({diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/sidebar_workspace.dart b/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/sidebar_workspace.dartindex 50ea9d83c7..02a0aa4665 100644--- a/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/sidebar_workspace.dart+++ b/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/sidebar_workspace.dart@@ -5,11 +5,13 @@ import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';import 'package:appflowy/workspace/presentation/home/menu/sidebar/shared/sidebar_setting.dart';import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_icon.dart';import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart';+import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/workspace_notifier.dart';import 'package:appflowy/workspace/presentation/notifications/widgets/notification_button.dart';import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';import 'package:appflowy_backend/log.dart';import 'package:appflowy_backend/protobuf/flowy-error/code.pbenum.dart';import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';+import 'package:collection/collection.dart';import 'package:easy_localization/easy_localization.dart';import 'package:flowy_infra_ui/flowy_infra_ui.dart';import 'package:flutter/material.dart';@@ -28,10 +30,20 @@ class _SidebarWorkspaceState extends State<SidebarWorkspace> {Loading? loadingIndicator;final ValueNotifier<bool> onHover = ValueNotifier(false);+ int maxRetryCount = 3;+ int retryCount = 0;++ @override+ void initState() {+ super.initState();++ openWorkspaceNotifier.addListener(_openWorkspaceFromInvitation);+ }@overridevoid dispose() {onHover.dispose();+ openWorkspaceNotifier.removeListener(_openWorkspaceFromInvitation);super.dispose();}@@ -147,6 +159,7 @@ class _SidebarWorkspaceState extends State<SidebarWorkspace> {(s) => LocaleKeys.workspace_openSuccess.tr(),(e) => '${LocaleKeys.workspace_openFailed.tr()}: ${e.msg}',);+break;case UserWorkspaceActionType.updateIcon:message = result.fold(@@ -160,8 +173,9 @@ class _SidebarWorkspaceState extends State<SidebarWorkspace> {(e) => '${LocaleKeys.workspace_renameFailed.tr()}: ${e.msg}',);break;- case UserWorkspaceActionType.none:+case UserWorkspaceActionType.fetchWorkspaces:+ case UserWorkspaceActionType.none:case UserWorkspaceActionType.leave:message = null;break;@@ -177,6 +191,78 @@ class _SidebarWorkspaceState extends State<SidebarWorkspace> {);}}++ // This function is a workaround, when we support open the workspace from invitation deep link,+ // we should refactor the code here+ void _openWorkspaceFromInvitation() {+ final value = openWorkspaceNotifier.value;+ final workspaceId = value?.workspaceId;+ final email = value?.email;++ if (workspaceId == null) {+ Log.info('No workspace id to open');+ return;+ }++ if (email == null) {+ Log.info('Open workspace from invitation with no email');+ return;+ }++ final state = context.read<UserWorkspaceBloc>().state;+ final currentWorkspace = state.currentWorkspace;+ if (currentWorkspace?.workspaceId == workspaceId) {+ Log.info('Already in the workspace');+ return;+ }++ if (email != widget.userProfile.email) {+ Log.info(+ 'Current user email: ${widget.userProfile.email} is not the same as the email in the invitation: $email',+ );+ return;+ }++ final openWorkspace = state.workspaces.firstWhereOrNull(+ (workspace) => workspace.workspaceId == workspaceId,+ );++ if (openWorkspace == null) {+ Log.error('Workspace not found, try to fetch workspaces');++ context.read<UserWorkspaceBloc>().add(+ UserWorkspaceEvent.fetchWorkspaces(+ initialWorkspaceId: workspaceId,+ ),+ );++ Future.delayed(+ Duration(milliseconds: 250 + retryCount * 250),+ () {+ if (retryCount >= maxRetryCount) {+ openWorkspaceNotifier.value = null;+ retryCount = 0;+ Log.error('Failed to open workspace from invitation');+ return;+ }++ retryCount++;+ _openWorkspaceFromInvitation();+ },+ );++ return;+ }++ context.read<UserWorkspaceBloc>().add(+ UserWorkspaceEvent.openWorkspace(+ workspaceId,+ openWorkspace.workspaceAuthType,+ ),+ );++ openWorkspaceNotifier.value = null;+ }}class SidebarSwitchWorkspaceButton extends StatefulWidget {@@ -202,48 +288,47 @@ class _SidebarSwitchWorkspaceButtonState@overrideWidget build(BuildContext context) {- return AppFlowyPopover(- direction: PopoverDirection.bottomWithCenterAligned,- offset: const Offset(0, 5),- constraints: const BoxConstraints(maxWidth: 300, maxHeight: 600),- margin: EdgeInsets.zero,- animationDuration: Durations.short3,- beginScaleFactor: 1.0,- beginOpacity: 0.8,- controller: _popoverController,- triggerActions: PopoverTriggerFlags.none,- onOpen: () {- context- .read<UserWorkspaceBloc>()- .add(const UserWorkspaceEvent.fetchWorkspaces());- },- onClose: () {- Log.info('close workspace menu');- },- popupBuilder: (_) {- return BlocProvider<UserWorkspaceBloc>.value(- value: context.read<UserWorkspaceBloc>(),- child: BlocBuilder<UserWorkspaceBloc, UserWorkspaceState>(- builder: (context, state) {- final currentWorkspace = state.currentWorkspace;- final workspaces = state.workspaces;- if (currentWorkspace == null) {- return const SizedBox.shrink();- }- Log.info('open workspace menu');- return WorkspacesMenu(- userProfile: widget.userProfile,- currentWorkspace: currentWorkspace,- workspaces: workspaces,- );- },- ),- );- },- child: _SideBarSwitchWorkspaceButtonChild(- currentWorkspace: widget.currentWorkspace,- popoverController: _popoverController,- isHover: widget.isHover,+ return BlocProvider(+ create: (context) => context.read<UserWorkspaceBloc>(),+ child: AppFlowyPopover(+ direction: PopoverDirection.bottomWithCenterAligned,+ offset: const Offset(0, 5),+ constraints: const BoxConstraints(maxWidth: 300, maxHeight: 600),+ margin: EdgeInsets.zero,+ animationDuration: Durations.short3,+ beginScaleFactor: 1.0,+ beginOpacity: 0.8,+ controller: _popoverController,+ triggerActions: PopoverTriggerFlags.none,+ onOpen: () {+ context+ .read<UserWorkspaceBloc>()+ .add(const UserWorkspaceEvent.fetchWorkspaces());+ },+ popupBuilder: (_) {+ return BlocProvider<UserWorkspaceBloc>.value(+ value: context.read<UserWorkspaceBloc>(),+ child: BlocBuilder<UserWorkspaceBloc, UserWorkspaceState>(+ builder: (context, state) {+ final currentWorkspace = state.currentWorkspace;+ final workspaces = state.workspaces;+ if (currentWorkspace == null) {+ return const SizedBox.shrink();+ }+ return WorkspacesMenu(+ userProfile: widget.userProfile,+ currentWorkspace: currentWorkspace,+ workspaces: workspaces,+ );+ },+ ),+ );+ },+ child: _SideBarSwitchWorkspaceButtonChild(+ currentWorkspace: widget.currentWorkspace,+ popoverController: _popoverController,+ isHover: widget.isHover,+ ),),);}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/workspace_notifier.dart b/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/workspace_notifier.dartnew file mode 100644index 0000000000..535d1469be--- /dev/null+++ b/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/workspace_notifier.dart@@ -0,0 +1,15 @@+// Workaround for open workspace from invitation deep link+import 'package:flutter/material.dart';++ValueNotifier<WorkspaceNotifyValue?> openWorkspaceNotifier =+ ValueNotifier(null);++class WorkspaceNotifyValue {+ WorkspaceNotifyValue({+ this.workspaceId,+ this.email,+ });++ final String? workspaceId;+ final String? email;+}diff --git a/frontend/appflowy_flutter/macos/Podfile.lock b/frontend/appflowy_flutter/macos/Podfile.lockindex 7f2c82ad2f..b846196707 100644--- a/frontend/appflowy_flutter/macos/Podfile.lock+++ b/frontend/appflowy_flutter/macos/Podfile.lock@@ -167,11 +167,11 @@ SPEC CHECKSUMS:share_plus: 510bf0af1a42cd602274b4629920c9649c52f4ccshared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7Sparkle: 5f8960a7a119aa7d45dacc0d5837017170bc5675- sqflite_darwin: 5a7236e3b501866c1c9befc6771dfd73ffb8702d- super_native_extensions: 85efee3a7495b46b04befcfc86ed12069264ebf3- url_launcher_macos: c82c93949963e55b228a30115bd219499a6fe404- webview_flutter_wkwebview: 0982481e3d9c78fd5c6f62a002fcd24fc791f1e4- window_manager: 990c8e348c4da2a93b81da638245d40554ec9436+ sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0+ super_native_extensions: c2795d6d9aedf4a79fae25cb6160b71b50549189+ url_launcher_macos: 0fba8ddabfc33ce0a9afe7c5fef5aab3d8d2d673+ webview_flutter_wkwebview: 44d4dee7d7056d5ad185d25b38404436d56c547c+ window_manager: e8d0b1431ab6c454f2b5c9ae26004bbfa43469aaPODFILE CHECKSUM: 0532f3f001ca3110b8be345d6491fff690e95823diff --git a/frontend/appflowy_flutter/test/unit_test/deeplink/deeplink_test.dart b/frontend/appflowy_flutter/test/unit_test/deeplink/deeplink_test.dartnew file mode 100644index 0000000000..75a6fb060c--- /dev/null+++ b/frontend/appflowy_flutter/test/unit_test/deeplink/deeplink_test.dart@@ -0,0 +1,57 @@+import 'package:appflowy/startup/tasks/deeplink/deeplink_handler.dart';+import 'package:appflowy/startup/tasks/deeplink/invitation_deeplink_handler.dart';+import 'package:appflowy/startup/tasks/deeplink/login_deeplink_handler.dart';+import 'package:appflowy/startup/tasks/deeplink/payment_deeplink_handler.dart';+import 'package:flutter_test/flutter_test.dart';++void main() {+ group('deep link handler: ', () {+ final deepLinkHandlerRegistry = DeepLinkHandlerRegistry.instance+ ..register(LoginDeepLinkHandler())+ ..register(PaymentDeepLinkHandler())+ ..register(InvitationDeepLinkHandler());++ test('invitation deep link handler', () {+ final uri = Uri.parse(+ 'appflowy-flutter://[email protected]&workspace_id=123',+ );+ deepLinkHandlerRegistry.processDeepLink(+ uri: uri,+ onStateChange: (handler, state) {+ expect(handler, isA<InvitationDeepLinkHandler>());+ },+ onResult: (handler, result) {+ expect(handler, isA<InvitationDeepLinkHandler>());+ expect(result.isSuccess, true);+ },+ onError: (error) {+ expect(error, isNull);+ },+ );+ });++ test('login deep link handler', () {+ final uri =+ Uri.parse('appflowy-flutter://login-callback#access_token=123');+ expect(LoginDeepLinkHandler().canHandle(uri), true);+ });++ test('payment deep link handler', () {+ final uri = Uri.parse('appflowy-flutter://payment-success');+ expect(PaymentDeepLinkHandler().canHandle(uri), true);+ });++ test('unknown deep link handler', () {+ final uri =+ Uri.parse('appflowy-flutter://unknown-callback?workspace_id=123');+ deepLinkHandlerRegistry.processDeepLink(+ uri: uri,+ onStateChange: (handler, state) {},+ onResult: (handler, result) {},+ onError: (error) {+ expect(error, isNotNull);+ },+ );+ });+ });+}