import 'dart:async'; import 'package:core/data/network/config/dynamic_url_interceptors.dart'; import 'package:core/presentation/state/failure.dart'; import 'package:core/presentation/state/success.dart'; import 'package:core/utils/app_logger.dart'; import 'package:core/utils/platform_info.dart'; import 'package:core/utils/sentry/sentry_config.dart'; import 'package:core/utils/sentry/sentry_manager.dart'; import 'package:flutter/foundation.dart'; import 'package:jmap_dart_client/jmap/account_id.dart'; import 'package:jmap_dart_client/jmap/core/session/session.dart'; import 'package:jmap_dart_client/jmap/core/user_name.dart'; import 'package:jmap_dart_client/jmap/push/state_change.dart'; import 'package:model/model.dart'; import 'package:rxdart/rxdart.dart'; import 'package:sentry_flutter/sentry_flutter.dart'; import 'package:tmail_ui_user/features/caching/config/hive_cache_config.dart'; import 'package:tmail_ui_user/features/caching/entries/sentry_configuration_cache.dart'; import 'package:tmail_ui_user/features/caching/extensions/sentry_cache_extensions.dart'; import 'package:tmail_ui_user/features/caching/manager/sentry_configuration_cache_manager.dart'; import 'package:tmail_ui_user/features/home/domain/extensions/session_extensions.dart'; import 'package:tmail_ui_user/features/home/domain/state/get_session_state.dart'; import 'package:tmail_ui_user/features/home/domain/usecases/get_session_interactor.dart'; import 'package:tmail_ui_user/features/home/presentation/home_bindings.dart'; import 'package:tmail_ui_user/features/login/data/network/interceptors/authorization_interceptors.dart'; import 'package:tmail_ui_user/features/login/domain/state/get_credential_state.dart'; import 'package:tmail_ui_user/features/login/domain/state/get_stored_token_oidc_state.dart'; import 'package:tmail_ui_user/features/login/domain/usecases/get_authenticated_account_interactor.dart'; import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/bindings/mailbox_dashboard_bindings.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/bindings/fcm_interactor_bindings.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/push_base_controller.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/extensions/state_change_extension.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/extensions/state_change_merge_extension.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/listener/email_change_listener.dart'; import 'package:tmail_ui_user/features/manage_account/data/local/preferences_setting_manager.dart'; import 'package:tmail_ui_user/features/manage_account/domain/model/preferences/preferences_setting.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/listener/label_change_listener.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/listener/mailbox_change_listener.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/model/state_change_account_filter.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/model/state_change_action_roles.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/services/fcm_service.dart'; import 'package:tmail_ui_user/features/push_notification/presentation/utils/fcm_utils.dart'; import 'package:tmail_ui_user/main/bindings/main_bindings.dart'; import 'package:tmail_ui_user/main/routes/route_navigation.dart'; /// Accumulates payloads and emits one batch after [debounce] of quiet time. /// /// A burst that never goes quiet still flushes [debounce] after the first /// payload of the window, so pending cannot grow without a bound. /// Prefer this over `buffer(debounce)`: that misses the first event on a broadcast stream. @visibleForTesting StreamSubscription> listenDebouncedBackgroundMessageBatches( Stream> source, void Function(List> batch) onBatch, void Function(Object error, StackTrace stackTrace) onError, { Duration debounce = const Duration( milliseconds: FcmUtils.durationBackgroundMessageComing, ), }) { final pending = >[]; Timer? trailing; Timer? maxWait; void flush() { trailing?.cancel(); trailing = null; maxWait?.cancel(); maxWait = null; if (pending.isEmpty) return; final batch = List.of(pending); pending.clear(); onBatch(batch); } void cancelTimers() { trailing?.cancel(); trailing = null; maxWait?.cancel(); maxWait = null; } final subscription = source.listen((payload) { pending.add(payload); trailing?.cancel(); trailing = Timer(debounce, flush); maxWait ??= Timer(debounce, flush); }, onError: onError, onDone: cancelTimers); return _OnCancelSubscription>(subscription, cancelTimers); } class _OnCancelSubscription implements StreamSubscription { _OnCancelSubscription(this._inner, this._onCancel); final StreamSubscription _inner; final void Function() _onCancel; var _didCancel = false; @override Future cancel() { if (!_didCancel) { _didCancel = true; _onCancel(); } return _inner.cancel(); } @override void onData(void Function(T data)? handleData) => _inner.onData(handleData); @override void onError(Function? handleError) => _inner.onError(handleError); @override void onDone(void Function()? handleDone) => _inner.onDone(handleDone); @override void pause([Future? resumeSignal]) => _inner.pause(resumeSignal); @override void resume() => _inner.resume(); @override bool get isPaused => _inner.isPaused; @override Future asFuture([E? futureValue]) => _inner.asFuture(futureValue); } /// Converts each payload on its own. One malformed payload does not drop the rest. @visibleForTesting StateChange? mergeBackgroundMessagePayloads( List> payloads, ) { return payloads .map((payload) { try { return FcmUtils.instance.convertFirebaseDataMessageToStateChange(payload); } catch (e, st) { logError( 'FcmMessageController::_handleBackgroundMessageBatch', exception: e, stackTrace: st, ); return null; } }) .whereType() .mergeAll(); } class FcmSentryRuntime { const FcmSentryRuntime(); bool get isAvailable => SentryManager.instance.isSentryAvailable; Future setReportingConsent(bool? consent) async { SentryManager.instance.setSentryReportingConsent(consent); await SentryManager.instance.pendingLifecycleTransition; } Future initialize(SentryConfig sentryConfig) { return SentryManager.instance.initializeWithSentryConfig(sentryConfig); } void setUser(SentryUser user) { SentryManager.instance.setUser(user); } void clearUser() { SentryManager.instance.clearUser(); } } class FcmSentrySetupCancellation { bool _isCancelled = false; bool get isCancelled => _isCancelled; void cancel() => _isCancelled = true; } class FcmMessageController extends PushBaseController { GetAuthenticatedAccountInteractor? _getAuthenticatedAccountInteractor; DynamicUrlInterceptors? _dynamicUrlInterceptors; AuthorizationInterceptors? _authorizationInterceptors; GetSessionInteractor? _getSessionInteractor; SentryConfigurationCache? _appliedSentryConfiguration; FcmMessageController._internal(); static final FcmMessageController _instance = FcmMessageController._internal(); static FcmMessageController get instance => _instance; @override void initialize({AccountId? accountId, Session? session}) { try { super.initialize(accountId: accountId, session: session); _listenTokenStream(); _listenBackgroundMessageStream(); } catch (e, st) { logError( 'FcmMessageController::initialize: throw exception', exception: e, stackTrace: st, ); } } void _listenBackgroundMessageStream() { final source = FcmService.instance.backgroundMessageStreamController?.stream; if (source == null) return; listenDebouncedBackgroundMessageBatches( source, _handleBackgroundMessageBatch, (e, st) { logError( 'FcmMessageController::_listenBackgroundMessageStream', exception: e, stackTrace: st, ); }, ); } void _listenTokenStream() { FcmService.instance.fcmTokenStreamController ?.stream .debounceTime(const Duration(milliseconds: FcmUtils.durationRefreshToken)) .listen( FcmTokenController.instance.onFcmTokenChanged, onError: (e, st) { logError( 'FcmMessageController::_listenTokenStream', exception: e, stackTrace: st, ); }, ); } void _handleBackgroundMessageBatch(List> payloads) async { logTrace('FcmMessageController::_handleBackgroundMessageBatch():payloads = ${payloads.length}'); final stateChange = mergeBackgroundMessagePayloads(payloads); if (stateChange == null) { logTrace('FcmMessageController::_handleBackgroundMessageBatch(): stateChange is null'); return; } logTrace('FcmMessageController::_handleBackgroundMessageBatch(): stateChange: ${stateChange.toString()}'); _getAuthenticatedAccount(stateChange: stateChange); } Future initialAppConfig() async { try { await MainBindings().dependencies(); await HiveCacheConfig.instance.setUp(); HomeBindings().dependencies(); MailboxDashBoardBindings().dependencies(); FcmInteractorBindings().dependencies(); _getInteractorBindings(); } catch (e, st) { logError( 'FcmMessageController::initialAppConfig: throw exception', exception: e, stackTrace: st, ); rethrow; } } Future setUpSentryConfiguration({ SentryConfigurationCacheManager? cacheManager, FcmSentryRuntime sentryRuntime = const FcmSentryRuntime(), FcmSentrySetupCancellation? cancellation, }) async { final cancellationToken = cancellation ?? FcmSentrySetupCancellation(); try { await _runSentrySetup( cacheManager: cacheManager ?? getBinding(), sentryRuntime: sentryRuntime, cancellation: cancellationToken, ); } catch (e, st) { await _handleSentrySetupFailure( e, st, cancellationToken, sentryRuntime, ); } } Future _runSentrySetup({ required SentryConfigurationCacheManager? cacheManager, required FcmSentryRuntime sentryRuntime, required FcmSentrySetupCancellation cancellation, }) async { if (await _invalidateSentrySetupIfCancelled( cancellation, sentryRuntime, )) { return; } if (cacheManager == null) { logWarning('FcmMessageController::setUpSentryConfiguration: SentryConfigurationCacheManager is null'); await invalidateSentrySetup( cancellation, sentryRuntime: sentryRuntime, ); return; } final configCache = await _loadAllowedSentryConfiguration(cacheManager); if (configCache == null || cancellation.isCancelled) { await invalidateSentrySetup( cancellation, sentryRuntime: sentryRuntime, ); return; } final canReuseSentryRuntime = sentryRuntime.isAvailable && _appliedSentryConfiguration == configCache; if (canReuseSentryRuntime) { await _refreshRunningSentrySetup( cacheManager, configCache, sentryRuntime, cancellation, ); return; } await _applySentryConfiguration( cacheManager, configCache, sentryRuntime, cancellation, ); } Future _refreshRunningSentrySetup( SentryConfigurationCacheManager cacheManager, SentryConfigurationCache configCache, FcmSentryRuntime sentryRuntime, FcmSentrySetupCancellation cancellation, ) async { await _restoreSentryUser(cacheManager, sentryRuntime, cancellation); if (!await _isSentryConfigurationStillAllowed( cacheManager, configCache, cancellation, )) { await invalidateSentrySetup( cancellation, sentryRuntime: sentryRuntime, ); } } Future _applySentryConfiguration( SentryConfigurationCacheManager cacheManager, SentryConfigurationCache configCache, FcmSentryRuntime sentryRuntime, FcmSentrySetupCancellation cancellation, ) async { await sentryRuntime.setReportingConsent(false); _appliedSentryConfiguration = null; if (await _invalidateSentrySetupIfCancelled( cancellation, sentryRuntime, )) { return; } await _restoreSentryUser(cacheManager, sentryRuntime, cancellation); if (await _invalidateSentrySetupIfCancelled( cancellation, sentryRuntime, )) { return; } await sentryRuntime.initialize(configCache.toSentryConfig()); if (!await _isSentryConfigurationStillAllowed( cacheManager, configCache, cancellation, )) { await invalidateSentrySetup( cancellation, sentryRuntime: sentryRuntime, ); return; } await sentryRuntime.setReportingConsent(true); if (await _invalidateSentrySetupIfCancelled( cancellation, sentryRuntime, )) { return; } if (sentryRuntime.isAvailable) { _appliedSentryConfiguration = configCache; } } Future _invalidateSentrySetupIfCancelled( FcmSentrySetupCancellation cancellation, FcmSentryRuntime sentryRuntime, ) async { if (!cancellation.isCancelled) return false; await invalidateSentrySetup( cancellation, sentryRuntime: sentryRuntime, ); return true; } Future _loadAllowedSentryConfiguration( SentryConfigurationCacheManager cacheManager, ) async { final SentryConfigurationCache configCache; try { configCache = await cacheManager.getSentryConfiguration(); } catch (e) { logWarning('FcmMessageController::setUpSentryConfiguration: SentryConfiguration not cached: $e'); return null; } if (!configCache.isAvailable) { logWarning('FcmMessageController::setUpSentryConfiguration: SentryConfiguration is not available'); return null; } if (!configCache.isReportingAllowed) { logTrace('FcmMessageController::setUpSentryConfiguration: Sentry reporting is not allowed'); return null; } return configCache; } Future _restoreSentryUser( SentryConfigurationCacheManager cacheManager, FcmSentryRuntime sentryRuntime, FcmSentrySetupCancellation cancellation, ) async { sentryRuntime.clearUser(); try { final userCache = await cacheManager.getSentryUser(); if (!cancellation.isCancelled) { sentryRuntime.setUser(userCache.toSentryUser()); } } catch (e) { logTrace('FcmMessageController::setUpSentryConfiguration: Sentry user not cached: $e'); // Acceptable — Sentry will start without user context } } Future _isSentryConfigurationStillAllowed( SentryConfigurationCacheManager cacheManager, SentryConfigurationCache expectedConfig, FcmSentrySetupCancellation cancellation, ) async { if (cancellation.isCancelled) return false; final latestConfig = await cacheManager.getSentryConfiguration(); if (cancellation.isCancelled) return false; if (!latestConfig.isAvailable) return false; if (!latestConfig.isReportingAllowed) return false; return latestConfig == expectedConfig; } Future _handleSentrySetupFailure( Object error, StackTrace stackTrace, FcmSentrySetupCancellation cancellation, FcmSentryRuntime sentryRuntime, ) async { try { await invalidateSentrySetup( cancellation, sentryRuntime: sentryRuntime, ); } catch (invalidationError, invalidationStackTrace) { logError( 'FcmMessageController::setUpSentryConfiguration: Cannot invalidate failed setup', exception: invalidationError, stackTrace: invalidationStackTrace, ); } logError( 'FcmMessageController::setUpSentryConfiguration: throw exception', exception: error, stackTrace: stackTrace, ); } Future invalidateSentrySetup( FcmSentrySetupCancellation cancellation, { FcmSentryRuntime sentryRuntime = const FcmSentryRuntime(), }) { cancellation.cancel(); _appliedSentryConfiguration = null; sentryRuntime.clearUser(); return sentryRuntime.setReportingConsent(false); } void _getInteractorBindings() { _getAuthenticatedAccountInteractor = getBinding(); _dynamicUrlInterceptors = getBinding(); _authorizationInterceptors = getBinding(); _getSessionInteractor = getBinding(); FcmTokenController.instance.initialBindingInteractor(); } void _getAuthenticatedAccount({required StateChange stateChange}) { if (_getAuthenticatedAccountInteractor != null) { consumeState(_getAuthenticatedAccountInteractor!.execute(stateChange: stateChange)); } else { logTrace( 'GetAuthenticatedAccountInteractor is null', ); } } void _handleGetAccountByOidcSuccess(GetStoredTokenOidcSuccess storedTokenOidcSuccess) { _dynamicUrlInterceptors?.setJmapUrl(storedTokenOidcSuccess.baseUrl.toString()); _authorizationInterceptors?.setTokenAndAuthorityOidc( newToken: storedTokenOidcSuccess.tokenOidc, newConfig: storedTokenOidcSuccess.oidcConfiguration, ); if (PlatformInfo.isAndroid) { _dynamicUrlInterceptors?.changeBaseUrl(storedTokenOidcSuccess.baseUrl.toString()); _getSessionAction(stateChange: storedTokenOidcSuccess.stateChange); } else { _dispatchPushOnNonAndroid( apiUrl: storedTokenOidcSuccess.personalAccount.apiUrl, accountId: storedTokenOidcSuccess.personalAccount.accountId, username: storedTokenOidcSuccess.personalAccount.userName, stateChange: storedTokenOidcSuccess.stateChange, ); } } void _handleGetAccountByBasicAuthSuccess(GetCredentialViewState credentialViewState) { _dynamicUrlInterceptors?.setJmapUrl(credentialViewState.baseUrl.toString()); _authorizationInterceptors?.setBasicAuthorization( credentialViewState.userName, credentialViewState.password, ); if (PlatformInfo.isAndroid) { _dynamicUrlInterceptors?.changeBaseUrl(credentialViewState.baseUrl.toString()); _getSessionAction(stateChange: credentialViewState.stateChange); } else { _dispatchPushOnNonAndroid( apiUrl: credentialViewState.personalAccount.apiUrl, accountId: credentialViewState.personalAccount.accountId, username: credentialViewState.personalAccount.userName, stateChange: credentialViewState.stateChange, ); } } void _dispatchPushOnNonAndroid({ required String? apiUrl, required AccountId? accountId, required UserName? username, required StateChange? stateChange, }) { _dynamicUrlInterceptors?.changeBaseUrl(apiUrl); final canPush = accountId != null && username != null && stateChange != null; if (!canPush) { logTrace('FcmMessageController::_dispatchPushOnNonAndroid: accountId or username or stateChange is null'); return; } _pushActionFromRemoteMessageBackground( accountId: accountId, userName: username, stateChange: stateChange, ); } void _getSessionAction({StateChange? stateChange}) { if (_getSessionInteractor != null) { consumeState(_getSessionInteractor!.execute(stateChange: stateChange)); } else { logTrace('FcmMessageController::_getSessionAction: _getSessionInteractor is null'); } } void _handleGetSessionSuccess(GetSessionSuccess success) { try { final apiUrl = success.session.getQualifiedApiUrl(baseUrl: _dynamicUrlInterceptors?.jmapUrl); final stateChange = success.stateChange; if (apiUrl.isNotEmpty && stateChange != null) { _dynamicUrlInterceptors?.changeBaseUrl(apiUrl); unawaited(_pushWithDelegatedAccounts(success.session, stateChange)); } else { logTrace( 'FcmMessageController::_handleGetSessionSuccess: Api url or state change is null', ); } } catch (e, st) { logError( 'FcmMessageController::_handleGetSessionSuccess:', exception: e, stackTrace: st, ); } } /// Android reads the session, so it also keeps the delegated accounts it lists while delegation is on. Future _pushWithDelegatedAccounts(Session session, StateChange stateChange) async { var settings = PreferencesSetting.initial(); try { settings = await getBinding()?.loadPreferences() ?? settings; } catch (e, st) { logWarning('FcmMessageController::_pushWithDelegatedAccounts: $e | $st'); } _pushActionFromRemoteMessageBackground( accountId: session.accountId, userName: session.username, stateChange: stateChange, session: session, delegatedAccountIds: notifiedDelegatedAccountIds(session, settings), ); } void _pushActionFromRemoteMessageBackground({ required AccountId accountId, required UserName userName, required StateChange stateChange, Session? session, Set delegatedAccountIds = const {}, }) { final filter = StateChangeAccountFilter( personalAccountId: accountId, delegatedAccountIds: delegatedAccountIds, includeDelegated: delegatedAccountIds.isNotEmpty, ); for (final changedAccountId in filter.accountsToProcess(stateChange)) { final mapTypeState = stateChange.getMapTypeState(changedAccountId); if (mapTypeState.isEmpty) continue; logTrace('FcmMessageController::_pushActionFromRemoteMessageBackground: Mapping type state to action ${mapTypeState.toString()}'); mappingTypeStateToAction( mapTypeState, changedAccountId, userName, emailChangeListener: EmailChangeListener.instance, mailboxChangeListener: MailboxChangeListener.instance, labelChangeListener: LabelChangeListener.instance, isForeground: false, session: session, roles: StateChangeActionRoles( updateDeliveryAndNotifications: filter.shouldKeepDelivery(changedAccountId), storeOfflineBodies: filter.shouldStoreOfflineBodies(changedAccountId), ), ); } } @override void handleFailureViewState(Failure failure) { log('FcmMessageController::_handleFailureViewState(): $failure'); if (failure is GetStoredTokenOidcFailure) { logTrace('FcmMessageController::GetStoredTokenOidcFailure: Get stored token oidc is failed'); } else if (failure is GetSessionFailure) { logTrace('FcmMessageController::GetSessionFailure: Get session is failed'); } } @override void handleSuccessViewState(Success success) { log('FcmMessageController::_handleSuccessViewState(): $success'); if (success is GetSessionSuccess) { _handleGetSessionSuccess(success); } else if (success is GetStoredTokenOidcSuccess) { _handleGetAccountByOidcSuccess(success); } else if (success is GetCredentialViewState) { _handleGetAccountByBasicAuthSuccess(success); } } }