import 'dart:async'; import 'package:core/core.dart'; import 'package:flutter/services.dart' as services; import 'package:contact/contact/model/capability_contact.dart'; import 'package:dartz/dartz.dart'; import 'package:fcm/model/firebase_capability.dart'; import 'package:fcm/model/firebase_registration_id.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:forward/forward/capability_forward.dart'; import 'package:get/get.dart'; import 'package:jmap_dart_client/jmap/account_id.dart'; import 'package:jmap_dart_client/jmap/core/capability/capability_identifier.dart'; import 'package:jmap_dart_client/jmap/core/capability/websocket_capability.dart'; import 'package:jmap_dart_client/jmap/core/session/session.dart'; import 'package:model/model.dart'; import 'package:rule_filter/rule_filter/capability_rule_filter.dart'; import 'package:tmail_ui_user/features/base/before_reconnect_manager.dart'; import 'package:tmail_ui_user/features/base/sentry_session_cleanup.dart'; import 'package:tmail_ui_user/features/base/mixin/emit_state_mixin.dart'; import 'package:tmail_ui_user/features/base/extensions/discard_web_composers_on_logout_extension.dart'; import 'package:tmail_ui_user/features/base/extensions/handle_company_server_login_info_extension.dart'; import 'package:tmail_ui_user/features/base/mixin/logout_mixin.dart'; import 'package:tmail_ui_user/features/delegation/presentation/cleanup_ended_delegations.dart'; import 'package:tmail_ui_user/features/delegation/presentation/utils/sign_in_email_link.dart'; import 'package:tmail_ui_user/features/delegation/presentation/providers/delegation_session_cleanup.dart'; import 'package:tmail_ui_user/features/base/mixin/popup_context_menu_action_mixin.dart'; import 'package:tmail_ui_user/features/caching/caching_manager.dart'; import 'package:tmail_ui_user/features/delegation/presentation/bridge/active_account_source.dart'; import 'package:tmail_ui_user/features/email/presentation/bindings/mdn_interactor_bindings.dart'; import 'package:tmail_ui_user/features/home/domain/extensions/session_extensions.dart'; import 'package:tmail_ui_user/features/login/data/network/config/oidc_constant.dart'; import 'package:tmail_ui_user/features/login/data/network/interceptors/authorization_interceptors.dart'; import 'package:tmail_ui_user/features/login/domain/exceptions/logout_exception.dart'; import 'package:tmail_ui_user/features/login/domain/state/get_company_server_login_info_state.dart'; import 'package:tmail_ui_user/features/login/domain/usecases/delete_authority_oidc_interactor.dart'; import 'package:tmail_ui_user/features/login/domain/usecases/delete_credential_interactor.dart'; import 'package:tmail_ui_user/features/login/domain/usecases/get_company_server_login_info_interactor.dart'; import 'package:tmail_ui_user/features/login/presentation/login_form_type.dart'; import 'package:tmail_ui_user/features/login/presentation/model/login_arguments.dart'; import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/bindings/contact_autocomplete_bindings.dart'; import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/bindings/tmail_autocomplete_bindings.dart'; import 'package:tmail_ui_user/features/manage_account/data/local/language_cache_manager.dart'; import 'package:tmail_ui_user/features/manage_account/domain/state/log_out_oidc_state.dart'; import 'package:tmail_ui_user/features/manage_account/domain/usecases/log_out_oidc_interactor.dart'; import 'package:tmail_ui_user/features/manage_account/presentation/email_rules/bindings/email_rules_interactor_bindings.dart'; import 'package:tmail_ui_user/features/manage_account/presentation/forward/bindings/forwarding_interactors_bindings.dart'; import 'package:tmail_ui_user/features/push_notification/domain/exceptions/fcm_exception.dart'; import 'package:tmail_ui_user/features/push_notification/domain/exceptions/web_socket_exceptions.dart'; import 'package:tmail_ui_user/features/push_notification/domain/state/destroy_firebase_registration_state.dart'; import 'package:tmail_ui_user/features/push_notification/domain/state/get_stored_firebase_registration_state.dart'; import 'package:tmail_ui_user/features/push_notification/domain/usecases/destroy_firebase_registration_interactor.dart'; import 'package:tmail_ui_user/features/push_notification/domain/usecases/get_stored_firebase_registration_interactor.dart'; import 'package:tmail_ui_user/features/composer/presentation/manager/attachment_keyword_config_manager.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/bindings/fcm_interactor_bindings.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/notifier/fcm_bindings_registration_notifier.dart'; import 'package:tmail_ui_user/main/providers/app_provider_container.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/bindings/web_socket_interactor_bindings.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/config/fcm_configuration.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/controller/fcm_message_controller.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/controller/fcm_token_controller.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/controller/web_socket_controller.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/notification/local_notification_manager.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/services/fcm_receiver.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/services/fcm_service.dart'; import 'package:tmail_ui_user/main/bindings/network/binding_tag.dart'; import 'package:tmail_ui_user/main/error/capability_validator.dart'; import 'package:tmail_ui_user/main/exceptions/remote/authentication_exception.dart'; import 'package:tmail_ui_user/main/exceptions/remote/method_level_exception.dart'; import 'package:tmail_ui_user/main/exceptions/remote/network_exception.dart'; import 'package:tmail_ui_user/main/localizations/app_localizations.dart'; import 'package:tmail_ui_user/main/routes/app_routes.dart'; import 'package:tmail_ui_user/main/routes/route_navigation.dart'; import 'package:tmail_ui_user/main/utils/app_config.dart'; import 'package:tmail_ui_user/main/universal_import/html_stub.dart' as html; import 'package:tmail_ui_user/main/utils/toast_manager.dart'; import 'package:tmail_ui_user/features/base/urgent_exception_handler.dart'; import 'package:tmail_ui_user/main/utils/twake_app_manager.dart'; import 'package:uuid/uuid.dart'; abstract class BaseController extends GetxController with PopupContextMenuActionMixin, LogoutMixin, EmitStateMixin implements UrgentExceptionHandler { final CachingManager cachingManager = Get.find(); final LanguageCacheManager languageCacheManager = Get.find(); final AuthorizationInterceptors authorizationInterceptors = Get.find(); final AuthorizationInterceptors authorizationIsolateInterceptors = Get.find(tag: BindingTag.isolateTag); final DynamicUrlInterceptors dynamicUrlInterceptors = Get.find(); final DeleteCredentialInteractor deleteCredentialInteractor = Get.find(); final LogoutOidcInteractor logoutOidcInteractor = Get.find(); final DeleteAuthorityOidcInteractor deleteAuthorityOidcInteractor = Get.find(); final AppToast appToast = Get.find(); final ImagePaths imagePaths = Get.find(); final ResponsiveUtils responsiveUtils = Get.find(); final Uuid uuid = Get.find(); final ToastManager toastManager = Get.find(); final TwakeAppManager twakeAppManager = Get.find(); bool _isFcmEnabled = false; GetStoredFirebaseRegistrationInteractor? _getStoredFirebaseRegistrationInteractor; DestroyFirebaseRegistrationInteractor? _destroyFirebaseRegistrationInteractor; GetCompanyServerLoginInfoInteractor? getCompanyServerLoginInfoInteractor; StreamSubscription? _onBeforeUnloadBrowserSubscription; StreamSubscription? _onUnloadBrowserSubscription; final viewState = Rx>(Right(UIState.idle)); FpsCallback? fpsCallback; @override void onReady() { super.onReady(); if (PlatformInfo.isWeb) { _triggerBrowserReloadListener(); } } void _triggerBrowserReloadListener() { _onBeforeUnloadBrowserSubscription = html.window.onBeforeUnload.listen(onBeforeUnloadBrowserListener); _onUnloadBrowserSubscription = html.window.onUnload.listen(onUnloadBrowserListener); } Future onBeforeUnloadBrowserListener(html.Event event) async {} Future onUnloadBrowserListener(html.Event event) async {} @override void onClose() { if (PlatformInfo.isWeb) { _onBeforeUnloadBrowserSubscription?.cancel(); _onUnloadBrowserSubscription?.cancel(); } super.onClose(); } void consumeState(Stream> newStateStream) async { newStateStream.listen(onData, onError: onError, onDone: onDone); } void dispatchState(Either newState) { viewState.value = newState; } void clearState() { viewState.value = Right(UIState.idle); } void onData(Either newState) { viewState.value = newState; viewState.value.fold(onDataFailureViewState, handleSuccessViewState); } void onError(dynamic error, StackTrace stackTrace) { logWarning('$runtimeType::onError():Error: $error | StackTrace: $stackTrace'); final isUrgentException = validateUrgentException(error); if (isUrgentException) { handleUrgentException(exception: error); } else { handleErrorViewState(error, stackTrace); } } void onDone() {} @override bool validateUrgentException(dynamic exception) { return exception is NoNetworkError || exception is BadCredentialsException || exception is ConnectionError || exception is RefreshTokenFailedException; } void handleErrorViewState(Object error, StackTrace stackTrace) {} @override void handleUrgentException({Failure? failure, Exception? exception}) { if (PlatformInfo.isWeb) { handleUrgentExceptionOnWeb(failure: failure, exception: exception); } else if (PlatformInfo.isMobile) { handleUrgentExceptionOnMobile(failure: failure, exception: exception); } else { throw const NoSupportPlatformException(); } } void handleUrgentExceptionOnMobile({Failure? failure, Exception? exception}) { logWarning('$runtimeType::handleUrgentExceptionOnMobile():Failure: $failure | Exception: $exception'); if (exception is ConnectionError) { _handleConnectionErrorException(); } else if (exception is BadCredentialsException) { handleBadCredentialsException(); } else if (exception is RefreshTokenFailedException) { handleRefreshTokenFailedException(); } } void handleUrgentExceptionOnWeb({Failure? failure, Exception? exception}) { logWarning( '$runtimeType::handleUrgentExceptionOnWeb(): exception=${exception.runtimeType} | ' 'failure=${failure.runtimeType}', webConsoleEnabled: true, ); if (exception is NoNetworkError) { _handleNotNetworkErrorException(); } else if (exception is ConnectionError) { _handleConnectionErrorException(); } else if (exception is BadCredentialsException) { handleBadCredentialsException(); } else if (exception is RefreshTokenFailedException) { handleRefreshTokenFailedException(); } else { logWarning( '$runtimeType::handleUrgentExceptionOnWeb(): NO branch matched — ' 'will NOT navigate to login. exception=${exception.runtimeType}', webConsoleEnabled: true, ); } } Future _executeBeforeReconnectAndLogOut({required String reason}) async { twakeAppManager.setExecutingBeforeReconnect(true); await executeBeforeReconnect(); logError( '$runtimeType::_executeBeforeReconnectAndLogOut: ' 'forcing logout after web save-and-reconnect | reason=$reason', extras: {'auth_error_type': reason}, webConsoleEnabled: true, ); keepSignInEmailLinkOfCurrentPage(); clearDataAndGoToLoginPage(); } void onCancelReconnectWhenSessionExpired() {} void _handleConnectionErrorException() { if (currentOverlayContext != null && currentContext != null) { appToast.showToastErrorMessage( currentOverlayContext!, AppLocalizations.of(currentContext!).connectionError); } } void showBlockedLinkToast() { if (currentOverlayContext == null || currentContext == null) return; appToast.showToastErrorMessage( currentOverlayContext!, AppLocalizations.of(currentContext!).linkCannotBeOpened); } void _handleNotNetworkErrorException() { if (currentOverlayContext != null && currentContext != null) { appToast.showToastMessage( currentOverlayContext!, AppLocalizations.of(currentContext!).no_internet_connection, actionName: AppLocalizations.of(currentContext!).skip, onActionClick: ToastView.dismiss, leadingSVGIcon: imagePaths.icNotConnection, backgroundColor: AppColor.textFieldErrorBorderColor, textColor: Colors.white, infinityToast: true); } } void handleBadCredentialsException() { log( '$runtimeType::handleBadCredentialsException: hasComposer=${twakeAppManager.hasComposer}', webConsoleEnabled: true, ); if (twakeAppManager.hasComposer) { _performSaveAndReconnection(reason: 'bad_credentials_401'); } else { _performReconnection(reason: 'bad_credentials_401'); } } void _performSaveAndReconnection({required String reason}) { if (PlatformInfo.isWeb) { log( '$runtimeType::_performSaveAndReconnection: web save-and-reconnect path', webConsoleEnabled: true, ); _executeBeforeReconnectAndLogOut(reason: reason); } else if (PlatformInfo.isMobile) { logError( '$runtimeType::_performSaveAndReconnection: ' 'forcing logout on mobile after save-and-reconnect | reason=$reason', extras: {'auth_error_type': reason}, ); clearDataAndGoToLoginPage(); } } void _performReconnection({required String reason}) { logError( '$runtimeType::_performReconnection: ' 'forcing logout | reason=$reason', extras: {'auth_error_type': reason}, webConsoleEnabled: true, ); keepSignInEmailLinkOfCurrentPage(); clearDataAndGoToLoginPage(); } void handleRefreshTokenFailedException() { log( '$runtimeType::handleRefreshTokenFailedException: ' 'hasComposer=${twakeAppManager.hasComposer}', webConsoleEnabled: true, ); if (twakeAppManager.hasComposer) { _performSaveAndReconnection(reason: 'refresh_token_400'); } else { _performReconnection(reason: 'refresh_token_400'); } } void onDataFailureViewState(Failure failure) { log('$runtimeType::onDataFailureViewState:failure = ${failure.runtimeType}'); if (failure is FeatureFailure) { final isUrgentException = validateUrgentException(failure.exception); if (isUrgentException) { handleUrgentException(failure: failure, exception: failure.exception); } else { handleFailureViewState(failure); } } else { handleFailureViewState(failure); } } void handleFailureViewState(Failure failure) async { logWarning('$runtimeType::handleFailureViewState():Failure = $failure'); if (failure is LogoutOidcFailure) { if (_isFcmEnabled) { _getStoredFirebaseRegistrationFromCache(); } else { await clearDataAndGoToLoginPage(); } } else if (failure is GetStoredFirebaseRegistrationFailure || failure is DestroyFirebaseRegistrationFailure) { await clearDataAndGoToLoginPage(); } else if (failure is GetCompanyServerLoginInfoFailure) { handleGetCompanyServerLoginInfoFailure(); } } void handleSuccessViewState(Success success) async { log('$runtimeType::handleSuccessViewState():Success = ${success.runtimeType}'); if (success is LogoutOidcSuccess) { if (_isFcmEnabled) { _getStoredFirebaseRegistrationFromCache(); } else { await clearDataAndGoToLoginPage(); } } else if (success is GetStoredFirebaseRegistrationSuccess) { _destroyFirebaseRegistration(success.firebaseRegistration.id!); } else if (success is DestroyFirebaseRegistrationSuccess) { await clearDataAndGoToLoginPage(); } else if (success is GetCompanyServerLoginInfoSuccess) { handleGetCompanyServerLoginInfoSuccess(success.serverLoginInfo); } } void startFpsMeter() { FpsManager().start(); fpsCallback = (fpsInfo) { log('$runtimeType::startFpsMeter(): $fpsInfo'); }; if (fpsCallback != null) { FpsManager().addFpsCallback(fpsCallback!); } } void stopFpsMeter() { FpsManager().stop(); if (fpsCallback != null) { FpsManager().removeFpsCallback(fpsCallback!); } } void injectAutoCompleteBindings(Session? session, AccountId? accountId) { try { ContactAutoCompleteBindings().dependencies(); requireCapability(session!, accountId!, [tmailContactCapabilityIdentifier]); TMailAutoCompleteBindings().dependencies(); } catch (e) { logWarning('$runtimeType::injectAutoCompleteBindings(): exception: $e'); } } void injectMdnBindings(Session? session, AccountId? accountId) { try { requireCapability(session!, accountId!, [CapabilityIdentifier.jmapMdn]); MdnInteractorBindings().dependencies(); } catch(e) { logWarning('$runtimeType::injectMdnBindings(): exception: $e'); } } void injectForwardBindings(Session? session, AccountId? accountId) { try { requireCapability(session!, accountId!, [capabilityForward]); ForwardingInteractorsBindings().dependencies(); } catch(e) { logWarning('$runtimeType::injectForwardBindings(): exception: $e'); } } void injectRuleFilterBindings(Session? session, AccountId? accountId) { try { requireCapability(session!, accountId!, [capabilityRuleFilter]); EmailRulesInteractorBindings().dependencies(); } catch(e) { logWarning('$runtimeType::injectRuleFilterBindings(): exception: $e'); } } Future injectFCMBindings(Session? session, AccountId? accountId) async { try { requireCapability(session!, accountId!, [FirebaseCapability.fcmIdentifier]); log('$runtimeType::injectFCMBindings: fcmAvailable = ${AppConfig.fcmAvailable}'); if (AppConfig.fcmAvailable) { await FcmConfiguration.initialize(); FcmInteractorBindings().dependencies(); appProviderContainer.read(fcmBindingsRegistrationProvider.notifier).registered(); FcmService.instance.initialStreamController(); FcmMessageController.instance.initialize(accountId: accountId, session: session); FcmTokenController.instance.initialBindingInteractor(); await FcmReceiver.instance.onInitialFcmListener(); if (PlatformInfo.isMobile) { await LocalNotificationManager.instance.setUp(groupId: session.username.value); } } else { throw const NotSupportFCMException(); } } catch(e) { logWarning('$runtimeType::injectFCMBindings(): exception: $e'); } } void injectWebSocket({ Session? session, AccountId? personalAccountId, bool isLabelAvailable = false, }) { try { log('$runtimeType::injectWebSocket: isLabelAvailable is $isLabelAvailable'); requireCapability( session!, personalAccountId!, [ CapabilityIdentifier.jmapWebSocket, CapabilityIdentifier.jmapWebSocketTicket ] ); final wsCapability = session.getCapabilityProperties( personalAccountId, CapabilityIdentifier.jmapWebSocket); if (wsCapability?.supportsPush != true) { throw WebSocketPushNotSupportedException(); } WebSocketInteractorBindings().dependencies(); WebSocketController.instance.initialize( accountId: personalAccountId, session: session, isLabelAvailable: isLabelAvailable, ); } catch(e) { logWarning('$runtimeType::injectWebSocket(): exception: $e'); } } AuthenticationType get authenticationType => authorizationInterceptors.authenticationType; bool get isAuthenticatedWithOidc => authenticationType == AuthenticationType.oidc; bool _isFcmActivated(Session session, AccountId accountId) => FirebaseCapability.fcmIdentifier.isSupported(session, accountId) && AppConfig.fcmAvailable; void goToLogin() { if (PlatformInfo.isMobile) { getCompanyServerLoginInfo(popAllRoute: false); } else { navigateToLoginPage(); } } void removeAllPageAndGoToLogin() { if (PlatformInfo.isMobile) { getCompanyServerLoginInfo(popAllRoute: true); } else { navigateToLoginPage(); } } void navigateToTwakeWelcomePage() { popAndPush(AppRoutes.twakeWelcome); } void navigateToLoginPage() { if (Get.currentRoute == AppRoutes.login) { log( '$runtimeType::navigateToLoginPage: SKIPPED — already on login route', webConsoleEnabled: true, ); return; } log( '$runtimeType::navigateToLoginPage: navigating to login from ' 'currentRoute=${Get.currentRoute}', webConsoleEnabled: true, ); pushAndPopAll( AppRoutes.login, arguments: LoginArguments(LoginFormType.none)); } void logout( BuildContext context, Session? session, AccountId? accountId, String ownEmailAddress, ) { if (PlatformInfo.isMobile) { showLogoutConfirmDialog( context: context, userAddress: ownEmailAddress, onConfirmAction: () => _handleLogoutAction(session, accountId), ); } else { _handleLogoutAction(session, accountId); } } // Web basic auth keeps one login copy per tab; a user sign out must invalidate the others. void _revokeOtherTabsOnWebBasicAuth() { if (PlatformInfo.isWeb && !isAuthenticatedWithOidc) { cachingManager.revokeOtherTabs(); } } Future _handleLogoutAction(Session? session, AccountId? accountId) async { _revokeOtherTabsOnWebBasicAuth(); // A forced logout keeps the page for the same user, a sign out must not hand it to the next one on this tab. discardSignInEmailLink(); if (session == null || accountId == null) { await clearDataAndGoToLoginPage(); return; } await discardWebComposersOnLogout(session, accountId); await removeDelegatedComposerSnapshotsOnLogout( session: session, personalAccountId: accountId, ); await cachingManager.clearMailDataCached(); _isFcmEnabled = _isFcmActivated(session, accountId); if (isAuthenticatedWithOidc) { consumeState(logoutOidcInteractor.execute()); } else { if (_isFcmEnabled) { _getStoredFirebaseRegistrationFromCache(); } else { await clearDataAndGoToLoginPage(); } } } /// Logs out before signing in to another account, then runs exactly one /// callback. It completes only once that callback completed, so a caller /// can hold a lock across the whole account switch. Future logoutToSignInNewAccount({ required Session session, required AccountId accountId, required FutureOr Function() onSuccessCallback, required FutureOr Function({Object? exception}) onFailureCallback, }) async { _LogoutToSignInOutcome outcome; try { _revokeOtherTabsOnWebBasicAuth(); await removeDelegatedComposerSnapshotsOnLogout( session: session, personalAccountId: accountId, ); _isFcmEnabled = _isFcmActivated(session, accountId); outcome = await _logoutToSignIn(); } catch (e) { logWarning('BaseController::logoutToSignInNewAccount:Exception = $e'); outcome = _LogoutToSignInOutcome.failed; } switch (outcome) { case _LogoutToSignInOutcome.loggedOut: await onSuccessCallback(); case _LogoutToSignInOutcome.oidcLogoutCancelled: await onFailureCallback(exception: UserCancelledLogoutOIDCFlowException()); case _LogoutToSignInOutcome.failed: await onFailureCallback(); } } Future<_LogoutToSignInOutcome> _logoutToSignIn() async { if (!isAuthenticatedWithOidc) { await _handleDeleteFCMAndClearData(); return _LogoutToSignInOutcome.loggedOut; } final logoutViewState = await logoutOidcInteractor.execute().last; final isLoggedOut = logoutViewState.fold( (failure) => false, (success) => success is LogoutOidcSuccess, ); final isCancelledByUser = logoutViewState.fold( (failure) => failure is LogoutOidcFailure && _validateUserCancelledLogoutOidcFlow(failure.exception), (success) => false, ); if (!isLoggedOut && !isCancelledByUser) return _LogoutToSignInOutcome.failed; await _handleDeleteFCMAndClearData(); return isLoggedOut ? _LogoutToSignInOutcome.loggedOut : _LogoutToSignInOutcome.oidcLogoutCancelled; } bool _validateUserCancelledLogoutOidcFlow(dynamic exception) { return exception is services.PlatformException && exception.code == OIDCConstant.endSessionFailedCode; } Future _handleDeleteFCMAndClearData() async { if (_isFcmEnabled) { await _handleDeleteFCMRegistration(); } await clearAllData(); } Future _handleDeleteFCMRegistration() async { _getStoredFirebaseRegistrationInteractor = getBinding(); if (_getStoredFirebaseRegistrationInteractor == null) return; try { final fcmRegistration = await _getStoredFirebaseRegistrationInteractor?.execute().last; fcmRegistration?.foldSuccess( onSuccess: (success) async { _destroyFirebaseRegistrationInteractor = getBinding(); await _destroyFirebaseRegistrationInteractor?.execute(success.firebaseRegistration.id!).last; }, onFailure: (failure) {}, ); } catch (e) { logWarning('BaseController::_handleDeleteFCMRegistration:Exception = $e'); } } void _destroyFirebaseRegistration(FirebaseRegistrationId firebaseRegistrationId) async { _destroyFirebaseRegistrationInteractor = getBinding(); if (_destroyFirebaseRegistrationInteractor != null) { consumeState(_destroyFirebaseRegistrationInteractor!.execute(firebaseRegistrationId)); } else { await clearDataAndGoToLoginPage(); } } void _getStoredFirebaseRegistrationFromCache() async { _getStoredFirebaseRegistrationInteractor = getBinding(); if (_getStoredFirebaseRegistrationInteractor != null) { consumeState(_getStoredFirebaseRegistrationInteractor!.execute()); } else { await clearDataAndGoToLoginPage(); } } Future executeBeforeReconnect() async { final beforeReconnectManager = getBinding(); await beforeReconnectManager?.executeBeforeReconnectListeners(); } Future clearDataAndGoToLoginPage() async { log( '$runtimeType::clearDataAndGoToLoginPage: clearing data then routing to login', webConsoleEnabled: true, ); await clearAllData(); log( '$runtimeType::clearDataAndGoToLoginPage: data cleared, calling removeAllPageAndGoToLogin', webConsoleEnabled: true, ); removeAllPageAndGoToLogin(); } /// Several entry points call this, some without awaiting. Overlapping runs /// used to close Hive while another run was still writing to it, so they are /// serialised through a single shared future. Future clearAllData({BuildContext? context}) => twakeAppManager.runClearDataOnce( () => _clearAllData(context ?? currentContext), ); Future _clearAllData(BuildContext? context) async { if (context != null) { try { endDelegationSession(context); } catch (error, stackTrace) { logError( 'BaseController::_clearAllData: could not end delegation session', exception: error, stackTrace: stackTrace, ); } } // Also covers a logout without context, where endDelegationSession never runs. getBinding()?.clear(); await _clearSentryForSessionEnd(); try { // Read before clear() flips it to none. final wasAuthenticatedWithOidc = isAuthenticatedWithOidc; authorizationInterceptors.clear(); authorizationIsolateInterceptors.clear(); await Future.wait([ if (wasAuthenticatedWithOidc) deleteAuthorityOidcInteractor.execute() else deleteCredentialInteractor.execute(), cachingManager.clearAll(), languageCacheManager.removeLanguage(), ]); await cachingManager.closeHive(); } catch (e) { logWarning('BaseController::clearAllData: Cannot clear all data: $e'); } finally { AttachmentKeywordConfigManager().clearCache(); } } Future _clearSentryForSessionEnd() async { try { final sentrySessionCleanup = getBinding(); if (sentrySessionCleanup == null) { SentryManager.instance.clearUser(); return; } await sentrySessionCleanup.clearForSessionEnd(); } catch (e, st) { logError( 'BaseController::_clearSentryForSessionEnd: Cannot clear Sentry session', exception: e, stackTrace: st, ); } } int getMinInputLengthAutocomplete({ required Session session, required AccountId accountId, }) { final minInputLength = session.getMinInputLengthAutocomplete(accountId); return minInputLength?.value.toInt() ?? AppConfig.defaultMinInputLengthAutocomplete; } /// Built when the retry toast shows, which may be long before Retry is tapped. VoidCallback retryActionOf(Stream> retry) => () => consumeState(retry); void showRetryToast(FeatureFailure failure) { if (currentOverlayContext == null || currentContext == null) return; final exception = failure.exception; final errorMessage = exception is MethodLevelErrors && exception.message != null ? AppLocalizations.of(currentContext!).unexpectedError(exception.message!) : AppLocalizations.of(currentContext!).unknownError; appToast.showToastMessageWithMultipleActions( currentOverlayContext!, errorMessage, actions: [ if (failure.onRetry != null) ( actionName: AppLocalizations.of(currentContext!).retry, onActionClick: retryActionOf(failure.onRetry!), actionIcon: SvgPicture.asset(imagePaths.icUndo), ), ( actionName: AppLocalizations.of(currentContext!).close, onActionClick: () => ToastView.dismiss(), actionIcon: SvgPicture.asset( imagePaths.icClose, colorFilter: Colors.white.asFilter(), ), ) ], backgroundColor: AppColor.toastErrorBackgroundColor, textColor: Colors.white, infinityToast: true, ); } } enum _LogoutToSignInOutcome { loggedOut, oidcLogoutCancelled, failed }