Skip to content

refactor: deeplink handler #7802

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 52 additions & 76 deletions frontend/appflowy_flutter/lib/startup/tasks/appflowy_cloud_task.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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()}');
Expand All @@ -50,6 +56,7 @@ class AppFlowyCloudDeepLink {
}

late final StreamSubscription<Uri?> _deepLinkSubscription;
late final DeepLinkHandlerRegistry _deepLinkHandlerRegistry;

Future<void> dispose() async {
Log.debug('AppFlowyCloudDeepLink: $hashCode dispose');
Expand Down Expand Up @@ -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>{};

Expand Down Expand Up @@ -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 listeners
class _AppLinkWrapper {
_AppLinkWrapper._() {
Expand Down
Original file line number Diff line number Diff line change
@@ -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,
}
Original file line number Diff line number Diff line change
@@ -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',
),
);
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
Loading
Loading