TF-1217 Handle fcm message on foreground/background/terminate
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
|
||||
import 'package:fcm/model/type_name.dart';
|
||||
import 'package:jmap_dart_client/jmap/account_id.dart';
|
||||
import 'package:tmail_ui_user/features/base/action/ui_action.dart';
|
||||
import 'package:jmap_dart_client/jmap/core/state.dart' as jmap;
|
||||
|
||||
class SynchronizeEmailOnForegroundAction extends FcmStateChangeAction {
|
||||
|
||||
final AccountId accountId;
|
||||
|
||||
SynchronizeEmailOnForegroundAction(
|
||||
TypeName typeName,
|
||||
jmap.State newState,
|
||||
this.accountId
|
||||
) : super(typeName, newState);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [typeName, newState, accountId];
|
||||
}
|
||||
|
||||
class PushNotificationAction extends FcmStateChangeAction {
|
||||
|
||||
final AccountId accountId;
|
||||
|
||||
PushNotificationAction(
|
||||
TypeName typeName,
|
||||
jmap.State newState,
|
||||
this.accountId
|
||||
) : super(typeName, newState);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [typeName, newState, accountId];
|
||||
}
|
||||
|
||||
class StoreEmailStateChangeToRefreshAction extends FcmStateChangeAction {
|
||||
|
||||
final AccountId accountId;
|
||||
|
||||
StoreEmailStateChangeToRefreshAction(
|
||||
TypeName typeName,
|
||||
jmap.State newState,
|
||||
this.accountId
|
||||
) : super(typeName, newState);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [typeName, newState, accountId];
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:tmail_ui_user/features/push_notification/presentation/config/firebase_options.dart';
|
||||
import 'package:tmail_ui_user/features/push_notification/presentation/services/fcm_receiver.dart';
|
||||
|
||||
class FcmConfiguration {
|
||||
|
||||
static void initialize() async {
|
||||
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
|
||||
_initMessageListener();
|
||||
}
|
||||
|
||||
static void _initMessageListener() {
|
||||
FcmReceiver.instance.onForegroundMessage();
|
||||
FcmReceiver.instance.onMessageOpenedApp();
|
||||
FcmReceiver.instance.onBackgroundMessage();
|
||||
FcmReceiver.instance.getFcmToken();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
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:dartz/dartz.dart';
|
||||
import 'package:fcm/model/type_name.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:jmap_dart_client/jmap/account_id.dart';
|
||||
import 'package:jmap_dart_client/jmap/core/state.dart' as jmap;
|
||||
import 'package:jmap_dart_client/jmap/push/state_change.dart';
|
||||
import 'package:model/oidc/token_oidc.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
import 'package:tmail_ui_user/features/base/action/ui_action.dart';
|
||||
import 'package:tmail_ui_user/features/base/base_controller.dart';
|
||||
import 'package:tmail_ui_user/features/caching/config/hive_cache_config.dart';
|
||||
import 'package:tmail_ui_user/features/home/presentation/home_bindings.dart';
|
||||
import 'package:tmail_ui_user/features/login/data/network/config/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/action/fcm_action.dart';
|
||||
import 'package:tmail_ui_user/features/push_notification/presentation/extensions/state_change_extension.dart';
|
||||
import 'package:tmail_ui_user/features/push_notification/presentation/listener/email_change_listener.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/features/session/domain/state/get_session_state.dart';
|
||||
import 'package:tmail_ui_user/features/session/domain/usecases/get_session_interactor.dart';
|
||||
import 'package:tmail_ui_user/main/bindings/main_bindings.dart';
|
||||
|
||||
class FcmController extends BaseController {
|
||||
|
||||
AccountId? _currentAccountId;
|
||||
RemoteMessage? _remoteMessageBackground;
|
||||
|
||||
GetAuthenticatedAccountInteractor? _getAuthenticatedAccountInteractor;
|
||||
DynamicUrlInterceptors? _dynamicUrlInterceptors;
|
||||
AuthorizationInterceptors? _authorizationInterceptors;
|
||||
GetSessionInteractor? _getSessionInteractor;
|
||||
|
||||
FcmController._internal() {
|
||||
_listenFcmMessageStream();
|
||||
}
|
||||
|
||||
static final FcmController _instance = FcmController._internal();
|
||||
|
||||
static FcmController get instance => _instance;
|
||||
|
||||
void initialize({AccountId? accountId}) {
|
||||
_currentAccountId = accountId;
|
||||
}
|
||||
|
||||
void _listenFcmMessageStream() {
|
||||
log('FcmController::_listenFcmMessageStream():');
|
||||
FcmService.instance.foregroundMessageStream
|
||||
.throttleTime(const Duration(milliseconds: FcmService.durationMessageComing))
|
||||
.listen(_handleForegroundMessageAction);
|
||||
|
||||
FcmService.instance.backgroundMessageStream
|
||||
.throttleTime(const Duration(milliseconds: FcmService.durationMessageComing))
|
||||
.listen(_handleBackgroundMessageAction);
|
||||
}
|
||||
|
||||
void _handleForegroundMessageAction(RemoteMessage newRemoteMessage) {
|
||||
log('FcmController::_handleForegroundMessageAction():remoteMessage: ${newRemoteMessage.data}');
|
||||
if (_currentAccountId != null) {
|
||||
final stateChange = _convertRemoteMessageToStateChange(newRemoteMessage);
|
||||
final mapTypeState = stateChange.getMapTypeState(_currentAccountId!);
|
||||
_mappingTypeStateToAction(mapTypeState, _currentAccountId!);
|
||||
}
|
||||
}
|
||||
|
||||
void _handleBackgroundMessageAction(RemoteMessage newRemoteMessage) async {
|
||||
log('FcmController::_handleBackgroundMessageAction():remoteMessage: ${newRemoteMessage.data}');
|
||||
_remoteMessageBackground = newRemoteMessage;
|
||||
await _initialAppConfig();
|
||||
_getAuthenticatedAccount();
|
||||
}
|
||||
|
||||
StateChange? _convertRemoteMessageToStateChange(RemoteMessage newRemoteMessage) {
|
||||
return FcmUtils.instance.convertFirebaseDataMessageToStateChange(newRemoteMessage.data);
|
||||
}
|
||||
|
||||
void _mappingTypeStateToAction(
|
||||
Map<String, dynamic> mapTypeState,
|
||||
AccountId accountId, {
|
||||
bool isForeground = true,
|
||||
}) {
|
||||
log('FcmController::_mappingTypeStateToAction():mapTypeState: $mapTypeState');
|
||||
final listTypeName = mapTypeState.keys
|
||||
.map((value) => TypeName(value))
|
||||
.toList();
|
||||
|
||||
final listEmailActions = listTypeName
|
||||
.map((typeName) => toFcmAction(typeName, accountId, mapTypeState, isForeground))
|
||||
.whereNotNull()
|
||||
.toList();
|
||||
|
||||
log('FcmController::_mappingTypeStateToAction():listEmailActions: $listEmailActions');
|
||||
|
||||
if (listEmailActions.isNotEmpty) {
|
||||
EmailChangeListener.instance.dispatchActions(listEmailActions);
|
||||
}
|
||||
}
|
||||
|
||||
FcmAction? toFcmAction(
|
||||
TypeName typeName,
|
||||
AccountId accountId,
|
||||
Map<String, dynamic> mapTypeState,
|
||||
isForeground
|
||||
) {
|
||||
final newState = jmap.State(mapTypeState[typeName.value]);
|
||||
if (typeName == TypeName.emailType) {
|
||||
if (isForeground) {
|
||||
return SynchronizeEmailOnForegroundAction(typeName, newState, accountId);
|
||||
} else {
|
||||
return StoreEmailStateChangeToRefreshAction(typeName, newState, accountId);
|
||||
}
|
||||
} else if (typeName == TypeName.emailDelivery) {
|
||||
if (!isForeground) {
|
||||
return PushNotificationAction(typeName, newState, accountId);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> _initialAppConfig() async {
|
||||
await Future.wait([
|
||||
MainBindings().dependencies(),
|
||||
HiveCacheConfig().setUp()
|
||||
]);
|
||||
|
||||
await Future.sync(() {
|
||||
HomeBindings().dependencies();
|
||||
MailboxDashBoardBindings().dependencies();
|
||||
});
|
||||
|
||||
_getInteractorBindings();
|
||||
}
|
||||
|
||||
void _getInteractorBindings() {
|
||||
try {
|
||||
_getAuthenticatedAccountInteractor = Get.find<GetAuthenticatedAccountInteractor>();
|
||||
_dynamicUrlInterceptors = Get.find<DynamicUrlInterceptors>();
|
||||
_authorizationInterceptors = Get.find<AuthorizationInterceptors>();
|
||||
_getSessionInteractor = Get.find<GetSessionInteractor>();
|
||||
} catch (e) {
|
||||
logError('FcmController::_getBindings(): ${e.toString()}');
|
||||
}
|
||||
}
|
||||
|
||||
void _getAuthenticatedAccount() async {
|
||||
if (_getAuthenticatedAccountInteractor != null) {
|
||||
consumeState(_getAuthenticatedAccountInteractor!.execute());
|
||||
} else {
|
||||
_clearRemoteMessageBackground();
|
||||
logError('FcmController::_getAuthenticatedAccount():_getAuthenticatedAccountInteractor is null');
|
||||
}
|
||||
}
|
||||
|
||||
void _handleFailureViewState(Failure failure) {
|
||||
log('FcmController::_handleFailureViewState(): $failure');
|
||||
_clearRemoteMessageBackground();
|
||||
}
|
||||
|
||||
void _handleSuccessViewState(Success success) {
|
||||
if (success is GetStoredTokenOidcSuccess) {
|
||||
_getSessionWithTokenOidc(success);
|
||||
} else if (success is GetCredentialViewState) {
|
||||
_getSessionWithBasicAuth(success);
|
||||
} else if (success is GetSessionSuccess) {
|
||||
_handleGetSessionSuccess(success);
|
||||
}
|
||||
}
|
||||
|
||||
void _getSessionWithTokenOidc(GetStoredTokenOidcSuccess storedTokenOidcSuccess) {
|
||||
_dynamicUrlInterceptors?.changeBaseUrl(storedTokenOidcSuccess.baseUrl.toString());
|
||||
_authorizationInterceptors?.setTokenAndAuthorityOidc(
|
||||
newToken: storedTokenOidcSuccess.tokenOidc.toToken(),
|
||||
newConfig: storedTokenOidcSuccess.oidcConfiguration
|
||||
);
|
||||
_getSession();
|
||||
}
|
||||
|
||||
void _getSessionWithBasicAuth(GetCredentialViewState credentialViewState) {
|
||||
_dynamicUrlInterceptors?.changeBaseUrl(credentialViewState.baseUrl.origin);
|
||||
_authorizationInterceptors?.setBasicAuthorization(
|
||||
credentialViewState.userName.userName,
|
||||
credentialViewState.password.value,
|
||||
);
|
||||
_getSession();
|
||||
}
|
||||
|
||||
void _getSession() async {
|
||||
if (_getSessionInteractor != null) {
|
||||
consumeState(_getSessionInteractor!.execute().asStream());
|
||||
} else {
|
||||
_clearRemoteMessageBackground();
|
||||
logError('FcmController::_getSession(): _getSessionInteractor is null');
|
||||
}
|
||||
}
|
||||
|
||||
void _handleGetSessionSuccess(GetSessionSuccess success) {
|
||||
final sessionCurrent = success.session;
|
||||
final apiUrl = sessionCurrent.apiUrl.toString();
|
||||
_currentAccountId = sessionCurrent.accounts.keys.first;
|
||||
|
||||
_dynamicUrlInterceptors?.changeBaseUrl(apiUrl);
|
||||
|
||||
if (_remoteMessageBackground != null && _currentAccountId != null) {
|
||||
final stateChange = _convertRemoteMessageToStateChange(_remoteMessageBackground!);
|
||||
final mapTypeState = stateChange.getMapTypeState(_currentAccountId!);
|
||||
_mappingTypeStateToAction(mapTypeState, _currentAccountId!, isForeground: false);
|
||||
}
|
||||
_clearRemoteMessageBackground();
|
||||
}
|
||||
|
||||
void _clearRemoteMessageBackground() {
|
||||
_remoteMessageBackground = null;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_clearRemoteMessageBackground();
|
||||
FcmService.instance.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void onData(Either<Failure, Success> newState) {
|
||||
super.onData(newState);
|
||||
newState.fold(_handleFailureViewState, _handleSuccessViewState);
|
||||
}
|
||||
|
||||
@override
|
||||
void onDone() {}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
|
||||
import 'package:jmap_dart_client/jmap/account_id.dart';
|
||||
import 'package:jmap_dart_client/jmap/push/state_change.dart';
|
||||
|
||||
extension StateChangeExtension on StateChange? {
|
||||
|
||||
Map<String, dynamic> getMapTypeState(AccountId accountId) {
|
||||
return this?.changed[accountId]?.typeState ?? {};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
import 'package:tmail_ui_user/features/base/action/ui_action.dart';
|
||||
|
||||
abstract class ChangeListener {
|
||||
void dispatchActions(List<Action> actions);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
|
||||
import 'package:core/utils/app_logger.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:jmap_dart_client/jmap/account_id.dart';
|
||||
import 'package:jmap_dart_client/jmap/core/state.dart' as jmap;
|
||||
import 'package:tmail_ui_user/features/base/action/ui_action.dart';
|
||||
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/action/dashboard_action.dart';
|
||||
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller.dart';
|
||||
import 'package:tmail_ui_user/features/push_notification/presentation/action/fcm_action.dart';
|
||||
import 'package:tmail_ui_user/features/push_notification/presentation/listener/change_listener.dart';
|
||||
|
||||
class EmailChangeListener extends ChangeListener {
|
||||
|
||||
MailboxDashBoardController? _dashBoardController;
|
||||
|
||||
EmailChangeListener._internal() {
|
||||
try {
|
||||
_dashBoardController = Get.find<MailboxDashBoardController>();
|
||||
} catch (e) {
|
||||
logError('EmailChangeListener::_internal(): IS NOT REGISTERED: ${e.toString()}');
|
||||
}
|
||||
}
|
||||
|
||||
static final EmailChangeListener _instance = EmailChangeListener._internal();
|
||||
|
||||
static EmailChangeListener get instance => _instance;
|
||||
|
||||
@override
|
||||
void dispatchActions(List<Action> actions) {
|
||||
log('EmailChangeListener::dispatchActions():actions: $actions');
|
||||
for (var action in actions) {
|
||||
if (action is SynchronizeEmailOnForegroundAction) {
|
||||
_synchronizeEmailOnForegroundAction(action.newState);
|
||||
} else if (action is PushNotificationAction) {
|
||||
_pushNotificationAction(action.newState, action.accountId);
|
||||
} else if (action is StoreEmailStateChangeToRefreshAction) {
|
||||
_handleStoreEmailStateChangeToRefreshAction(action.newState, action.accountId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _synchronizeEmailOnForegroundAction(jmap.State newState) {
|
||||
log('EmailChangeListener::_synchronizeEmailAction():newState: $newState');
|
||||
if (_dashBoardController != null) {
|
||||
_dashBoardController!.dispatchAction(RefreshChangedEmailAction(newState));
|
||||
}
|
||||
}
|
||||
|
||||
void _pushNotificationAction(jmap.State newState, AccountId accountId) {
|
||||
log('EmailChangeListener::_pushNotificationAction():newState: $newState');
|
||||
}
|
||||
|
||||
void _handleStoreEmailStateChangeToRefreshAction(jmap.State newState, AccountId accountId) {
|
||||
log('EmailChangeListener::_handleStoreEmailStateChangeToRefreshAction():newState: $newState');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
|
||||
import 'package:core/utils/app_logger.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:tmail_ui_user/features/push_notification/presentation/services/fcm_service.dart';
|
||||
|
||||
int semaphoreBackground = 0;
|
||||
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> handleFirebaseBackgroundMessage(RemoteMessage message) async {
|
||||
if (semaphoreBackground != 0) {
|
||||
return;
|
||||
}
|
||||
semaphoreBackground = 1;
|
||||
Future.delayed(const Duration(milliseconds: FcmService.durationMessageComing)).then((_) => semaphoreBackground = 0);
|
||||
|
||||
log('FcmReceiver::handleFirebaseBackgroundMessage(): ${message.data}');
|
||||
FcmService.instance.handleFirebaseBackgroundMessage(message);
|
||||
}
|
||||
|
||||
class FcmReceiver {
|
||||
FcmReceiver._internal();
|
||||
|
||||
static final FcmReceiver _instance = FcmReceiver._internal();
|
||||
|
||||
static FcmReceiver get instance => _instance;
|
||||
|
||||
void onForegroundMessage() {
|
||||
FirebaseMessaging.onMessage.listen(FcmService.instance.handleFirebaseForegroundMessage);
|
||||
}
|
||||
|
||||
void onMessageOpenedApp() {
|
||||
FirebaseMessaging.onMessageOpenedApp.listen(FcmService.instance.handleFirebaseMessageOpenedApp);
|
||||
}
|
||||
|
||||
void onBackgroundMessage() {
|
||||
FirebaseMessaging.onBackgroundMessage(handleFirebaseBackgroundMessage);
|
||||
}
|
||||
|
||||
void getFcmToken() async {
|
||||
final token = await FirebaseMessaging.instance.getToken();
|
||||
log('FcmReceiver::onFcmToken():token: $token');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:core/utils/app_logger.dart';
|
||||
import 'package:fcm/model/firebase_token.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:tmail_ui_user/features/push_notification/presentation/controller/fcm_controller.dart';
|
||||
|
||||
class FcmService {
|
||||
|
||||
static const int durationMessageComing = 2000;
|
||||
|
||||
final StreamController<RemoteMessage> foregroundMessageStreamController = StreamController<RemoteMessage>.broadcast();
|
||||
Stream<RemoteMessage> get foregroundMessageStream => foregroundMessageStreamController.stream;
|
||||
|
||||
final StreamController<RemoteMessage> backgroundMessageStreamController = StreamController<RemoteMessage>.broadcast();
|
||||
Stream<RemoteMessage> get backgroundMessageStream => backgroundMessageStreamController.stream;
|
||||
|
||||
FirebaseToken? currentToken;
|
||||
int semaphore = 0;
|
||||
|
||||
FcmService._internal();
|
||||
|
||||
static final FcmService _instance = FcmService._internal();
|
||||
|
||||
static FcmService get instance => _instance;
|
||||
|
||||
void handleFirebaseForegroundMessage(RemoteMessage newRemoteMessage) {
|
||||
if (semaphore != 0) {
|
||||
return;
|
||||
}
|
||||
semaphore = 1;
|
||||
Future.delayed(const Duration(milliseconds: durationMessageComing)).then((_) => semaphore = 0);
|
||||
|
||||
foregroundMessageStreamController.add(newRemoteMessage);
|
||||
}
|
||||
|
||||
void handleFirebaseBackgroundMessage(RemoteMessage newRemoteMessage) {
|
||||
FcmController.instance.initialize();
|
||||
backgroundMessageStreamController.add(newRemoteMessage);
|
||||
}
|
||||
|
||||
void handleFirebaseMessageOpenedApp(RemoteMessage newRemoteMessage) {
|
||||
log('FcmService::handleFirebaseMessageOpenedApp():newRemoteMessage: ${newRemoteMessage.data}');
|
||||
}
|
||||
|
||||
void _closeStream() {
|
||||
foregroundMessageStreamController.close();
|
||||
backgroundMessageStreamController.close();
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_closeStream();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user