TF-1631 Handle session on background message

(cherry picked from commit 78e7c362beb783efd3894a929345ed84ffcd6404)
This commit is contained in:
dab246
2023-03-28 13:32:10 +07:00
committed by Dat Vu
parent 62548698f8
commit 91b2cbae00
8 changed files with 83 additions and 31 deletions
+4 -4
View File
@@ -228,11 +228,11 @@ abstract class BaseController extends GetxController
final mapEnvData = Map<String, String>.from(dotenv.env); final mapEnvData = Map<String, String>.from(dotenv.env);
await AppUtils.loadFcmConfigFileToEnv(currentMapEnvData: mapEnvData); await AppUtils.loadFcmConfigFileToEnv(currentMapEnvData: mapEnvData);
FcmConfiguration.initialize(); FcmConfiguration.initialize();
if (!BuildUtils.isWeb) {
await LocalNotificationManager.instance.setUp();
}
FcmInteractorBindings().dependencies(); FcmInteractorBindings().dependencies();
FcmMessageController.instance.initialize(session: session, accountId: accountId); FcmMessageController.instance.initializeFromAccountId(accountId);
if (!BuildUtils.isWeb) {
LocalNotificationManager.instance.setUp();
}
} else { } else {
throw NotSupportFCMException(); throw NotSupportFCMException();
} }
@@ -21,7 +21,7 @@ class SynchronizeEmailOnForegroundAction extends FcmStateChangeAction {
class PushNotificationAction extends FcmStateChangeAction { class PushNotificationAction extends FcmStateChangeAction {
final Session session; final Session? session;
final AccountId accountId; final AccountId accountId;
PushNotificationAction( PushNotificationAction(
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:core/data/network/config/dynamic_url_interceptors.dart'; import 'package:core/data/network/config/dynamic_url_interceptors.dart';
import 'package:core/presentation/extensions/uri_extension.dart';
import 'package:core/presentation/state/failure.dart'; import 'package:core/presentation/state/failure.dart';
import 'package:core/presentation/state/success.dart'; import 'package:core/presentation/state/success.dart';
import 'package:core/utils/app_logger.dart'; import 'package:core/utils/app_logger.dart';
@@ -32,6 +33,8 @@ import 'package:tmail_ui_user/features/push_notification/presentation/listener/e
import 'package:tmail_ui_user/features/push_notification/presentation/listener/mailbox_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/services/fcm_service.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/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'; import 'package:tmail_ui_user/main/bindings/main_bindings.dart';
import 'package:tmail_ui_user/main/routes/route_navigation.dart'; import 'package:tmail_ui_user/main/routes/route_navigation.dart';
@@ -44,6 +47,7 @@ class FcmMessageController extends FcmBaseController {
GetAuthenticatedAccountInteractor? _getAuthenticatedAccountInteractor; GetAuthenticatedAccountInteractor? _getAuthenticatedAccountInteractor;
DynamicUrlInterceptors? _dynamicUrlInterceptors; DynamicUrlInterceptors? _dynamicUrlInterceptors;
AuthorizationInterceptors? _authorizationInterceptors; AuthorizationInterceptors? _authorizationInterceptors;
GetSessionInteractor? _getSessionInteractor;
FcmMessageController._internal() { FcmMessageController._internal() {
_listenFcmStream(); _listenFcmStream();
@@ -53,12 +57,13 @@ class FcmMessageController extends FcmBaseController {
static FcmMessageController get instance => _instance; static FcmMessageController get instance => _instance;
void initialize({Session? session, AccountId? accountId}) { void initializeFromAccountId(AccountId accountId) {
_currentSession = session;
_currentAccountId = accountId; _currentAccountId = accountId;
FcmTokenController.instance.initialize(); FcmTokenController.instance.initialize();
} }
void initialize() {}
void _listenFcmStream() async { void _listenFcmStream() async {
await Future.wait([ await Future.wait([
listenForegroundMessageStream(), listenForegroundMessageStream(),
@@ -89,11 +94,11 @@ class FcmMessageController extends FcmBaseController {
} }
void _handleForegroundMessageAction(RemoteMessage newRemoteMessage) { void _handleForegroundMessageAction(RemoteMessage newRemoteMessage) {
log('FcmMessageController::_handleForegroundMessageAction():remoteMessage: ${newRemoteMessage.data}'); log('FcmMessageController::_handleForegroundMessageAction():remoteMessage: ${newRemoteMessage.data} | _currentAccountId: $_currentAccountId');
if (_currentAccountId != null && _currentSession != null) { if (_currentAccountId != null) {
final stateChange = _convertRemoteMessageToStateChange(newRemoteMessage); final stateChange = _convertRemoteMessageToStateChange(newRemoteMessage);
final mapTypeState = stateChange.getMapTypeState(_currentAccountId!); final mapTypeState = stateChange.getMapTypeState(_currentAccountId!);
_mappingTypeStateToAction(_currentSession!, mapTypeState, _currentAccountId!); _mappingTypeStateToAction(mapTypeState, _currentAccountId!);
} }
} }
@@ -109,10 +114,10 @@ class FcmMessageController extends FcmBaseController {
} }
void _mappingTypeStateToAction( void _mappingTypeStateToAction(
Session session,
Map<String, dynamic> mapTypeState, Map<String, dynamic> mapTypeState,
AccountId accountId, { AccountId accountId, {
bool isForeground = true, bool isForeground = true,
Session? session
}) { }) {
log('FcmMessageController::_mappingTypeStateToAction():mapTypeState: $mapTypeState'); log('FcmMessageController::_mappingTypeStateToAction():mapTypeState: $mapTypeState');
final listTypeName = mapTypeState.keys final listTypeName = mapTypeState.keys
@@ -121,7 +126,7 @@ class FcmMessageController extends FcmBaseController {
final listEmailActions = listTypeName final listEmailActions = listTypeName
.where((typeName) => typeName == TypeName.emailType || typeName == TypeName.emailDelivery) .where((typeName) => typeName == TypeName.emailType || typeName == TypeName.emailDelivery)
.map((typeName) => toFcmAction(session, typeName, accountId, mapTypeState, isForeground)) .map((typeName) => toFcmAction(typeName, accountId, mapTypeState, isForeground, session: session))
.whereNotNull() .whereNotNull()
.toList(); .toList();
@@ -133,7 +138,7 @@ class FcmMessageController extends FcmBaseController {
final listMailboxActions = listTypeName final listMailboxActions = listTypeName
.where((typeName) => typeName == TypeName.mailboxType) .where((typeName) => typeName == TypeName.mailboxType)
.map((typeName) => toFcmAction(session, typeName, accountId, mapTypeState, isForeground)) .map((typeName) => toFcmAction(typeName, accountId, mapTypeState, isForeground))
.whereNotNull() .whereNotNull()
.toList(); .toList();
@@ -145,11 +150,13 @@ class FcmMessageController extends FcmBaseController {
} }
FcmAction? toFcmAction( FcmAction? toFcmAction(
Session session,
TypeName typeName, TypeName typeName,
AccountId accountId, AccountId accountId,
Map<String, dynamic> mapTypeState, Map<String, dynamic> mapTypeState,
isForeground isForeground,
{
Session? session
}
) { ) {
final newState = jmap.State(mapTypeState[typeName.value]); final newState = jmap.State(mapTypeState[typeName.value]);
if (typeName == TypeName.emailType) { if (typeName == TypeName.emailType) {
@@ -192,6 +199,7 @@ class FcmMessageController extends FcmBaseController {
_getAuthenticatedAccountInteractor = getBinding<GetAuthenticatedAccountInteractor>(); _getAuthenticatedAccountInteractor = getBinding<GetAuthenticatedAccountInteractor>();
_dynamicUrlInterceptors = getBinding<DynamicUrlInterceptors>(); _dynamicUrlInterceptors = getBinding<DynamicUrlInterceptors>();
_authorizationInterceptors = getBinding<AuthorizationInterceptors>(); _authorizationInterceptors = getBinding<AuthorizationInterceptors>();
_getSessionInteractor = getBinding<GetSessionInteractor>();
FcmTokenController.instance.initialize(); FcmTokenController.instance.initialize();
} catch (e) { } catch (e) {
logError('FcmMessageController::_getBindings(): ${e.toString()}'); logError('FcmMessageController::_getBindings(): ${e.toString()}');
@@ -210,34 +218,74 @@ class FcmMessageController extends FcmBaseController {
void _handleGetAuthenticatedAccountSuccess(GetAuthenticatedAccountSuccess success) { void _handleGetAuthenticatedAccountSuccess(GetAuthenticatedAccountSuccess success) {
_currentAccountId = success.account.accountId; _currentAccountId = success.account.accountId;
_dynamicUrlInterceptors?.changeBaseUrl(success.account.apiUrl); if (!FcmUtils.instance.isMobileAndroid) {
_dynamicUrlInterceptors?.changeBaseUrl(success.account.apiUrl);
}
log('FcmMessageController::_handleGetAuthenticatedAccountSuccess():_currentAccountId: $_currentAccountId'); log('FcmMessageController::_handleGetAuthenticatedAccountSuccess():_currentAccountId: $_currentAccountId');
} }
void _handleGetAccountByOidcSuccess(GetStoredTokenOidcSuccess storedTokenOidcSuccess) { void _handleGetAccountByOidcSuccess(GetStoredTokenOidcSuccess storedTokenOidcSuccess) {
log('FcmMessageController::_handleGetAccountByOidcSuccess():'); log('FcmMessageController::_handleGetAccountByOidcSuccess():');
_dynamicUrlInterceptors?.setJmapUrl(storedTokenOidcSuccess.baseUrl.toString());
_authorizationInterceptors?.setTokenAndAuthorityOidc( _authorizationInterceptors?.setTokenAndAuthorityOidc(
newToken: storedTokenOidcSuccess.tokenOidc.toToken(), newToken: storedTokenOidcSuccess.tokenOidc.toToken(),
newConfig: storedTokenOidcSuccess.oidcConfiguration newConfig: storedTokenOidcSuccess.oidcConfiguration
); );
_pushActionFromRemoteMessageBackground();
if (FcmUtils.instance.isMobileAndroid) {
_dynamicUrlInterceptors?.changeBaseUrl(storedTokenOidcSuccess.baseUrl.toString());
_getSessionAction();
} else {
_pushActionFromRemoteMessageBackground();
}
} }
void _handleGetAccountByBasicAuthSuccess(GetCredentialViewState credentialViewState) { void _handleGetAccountByBasicAuthSuccess(GetCredentialViewState credentialViewState) {
log('FcmMessageController::_handleGetAccountByBasicAuthSuccess():'); log('FcmMessageController::_handleGetAccountByBasicAuthSuccess():');
_dynamicUrlInterceptors?.setJmapUrl(credentialViewState.baseUrl.toString());
_authorizationInterceptors?.setBasicAuthorization( _authorizationInterceptors?.setBasicAuthorization(
credentialViewState.userName.userName, credentialViewState.userName.userName,
credentialViewState.password.value, credentialViewState.password.value,
); );
_pushActionFromRemoteMessageBackground(); if (FcmUtils.instance.isMobileAndroid) {
_dynamicUrlInterceptors?.changeBaseUrl(credentialViewState.baseUrl.toString());
_getSessionAction();
} else {
_pushActionFromRemoteMessageBackground();
}
}
void _getSessionAction() {
if (_getSessionInteractor != null) {
consumeState(_getSessionInteractor!.execute().asStream());
} else {
_clearRemoteMessageBackground();
logError('FcmMessageController::_getSessionAction():_getSessionInteractor is null');
}
}
void _handleGetSessionSuccess(GetSessionSuccess success) {
_currentSession = success.session;
final jmapUrl = _dynamicUrlInterceptors?.jmapUrl;
final apiUrl = jmapUrl != null
? success.session.apiUrl.toQualifiedUrl(baseUrl: Uri.parse(jmapUrl)).toString()
: success.session.apiUrl.toString();
log('FcmMessageController::_pushActionFromRemoteMessageBackground():jmapUrl: $jmapUrl | apiUrl: $apiUrl');
if (apiUrl.isNotEmpty) {
_dynamicUrlInterceptors?.changeBaseUrl(apiUrl);
_pushActionFromRemoteMessageBackground();
} else {
_clearRemoteMessageBackground();
logError('FcmMessageController::_handleGetSessionSuccess():apiUrl is null');
}
} }
void _pushActionFromRemoteMessageBackground() { void _pushActionFromRemoteMessageBackground() {
log('FcmMessageController::_pushActionFromRemoteMessageBackground():'); log('FcmMessageController::_pushActionFromRemoteMessageBackground():_remoteMessageBackground: $_remoteMessageBackground | _currentAccountId: $_currentAccountId | _currentSession: $_currentSession');
if (_remoteMessageBackground != null && _currentAccountId != null && _currentSession != null) { if (_remoteMessageBackground != null && _currentAccountId != null) {
final stateChange = _convertRemoteMessageToStateChange(_remoteMessageBackground!); final stateChange = _convertRemoteMessageToStateChange(_remoteMessageBackground!);
final mapTypeState = stateChange.getMapTypeState(_currentAccountId!); final mapTypeState = stateChange.getMapTypeState(_currentAccountId!);
_mappingTypeStateToAction(_currentSession!, mapTypeState, _currentAccountId!, isForeground: false); _mappingTypeStateToAction(mapTypeState, _currentAccountId!, isForeground: false, session: _currentSession);
} }
_clearRemoteMessageBackground(); _clearRemoteMessageBackground();
} }
@@ -257,6 +305,8 @@ class FcmMessageController extends FcmBaseController {
log('FcmMessageController::_handleSuccessViewState(): $success'); log('FcmMessageController::_handleSuccessViewState(): $success');
if (success is GetAuthenticatedAccountSuccess) { if (success is GetAuthenticatedAccountSuccess) {
_handleGetAuthenticatedAccountSuccess(success); _handleGetAuthenticatedAccountSuccess(success);
} else if (success is GetSessionSuccess) {
_handleGetSessionSuccess(success);
} else if (success is GetStoredTokenOidcSuccess) { } else if (success is GetStoredTokenOidcSuccess) {
_handleGetAccountByOidcSuccess(success); _handleGetAccountByOidcSuccess(success);
} else if (success is GetCredentialViewState) { } else if (success is GetCredentialViewState) {
@@ -82,9 +82,10 @@ class EmailChangeListener extends ChangeListener {
} }
} }
void _pushNotificationAction(jmap.State newState, AccountId accountId, Session session) { void _pushNotificationAction(jmap.State newState, AccountId accountId, Session? session) {
_newState = newState; _newState = newState;
_accountId = accountId; _accountId = accountId;
_session = session;
log('EmailChangeListener::_pushNotificationAction():newState: $newState'); log('EmailChangeListener::_pushNotificationAction():newState: $newState');
if (BuildUtils.isWeb) { if (BuildUtils.isWeb) {
@@ -184,7 +185,7 @@ class EmailChangeListener extends ChangeListener {
if (_newState != null) { if (_newState != null) {
_storeEmailDeliveryStateAction(_newState!); _storeEmailDeliveryStateAction(_newState!);
if (!BuildUtils.isWeb && Platform.isAndroid) { if (FcmUtils.instance.isMobileAndroid) {
_handleLocalPushNotification(success.emailList); _handleLocalPushNotification(success.emailList);
} }
} }
@@ -131,6 +131,9 @@ class LocalNotificationManager {
EmailAddress? emailAddress, EmailAddress? emailAddress,
String? payload String? payload
}) async { }) async {
if (!_notificationsEnabled) {
return;
}
final inboxStyleInformation = InboxStyleInformation( final inboxStyleInformation = InboxStyleInformation(
[message?.addBlockTag('p', attribute: 'style="color:#6D7885;"') ?? ''], [message?.addBlockTag('p', attribute: 'style="color:#6D7885;"') ?? ''],
htmlFormatLines: true, htmlFormatLines: true,
@@ -1,8 +1,8 @@
import 'package:core/utils/app_logger.dart'; import 'package:core/utils/app_logger.dart';
import 'package:core/utils/build_utils.dart';
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/services/fcm_service.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/utils/app_utils.dart'; import 'package:tmail_ui_user/main/utils/app_utils.dart';
@pragma('vm:entry-point') @pragma('vm:entry-point')
@@ -30,7 +30,7 @@ class FcmReceiver {
try { try {
final currentToken = await FirebaseMessaging.instance.getToken(vapidKey: AppUtils.fcmVapidPublicKey); final currentToken = await FirebaseMessaging.instance.getToken(vapidKey: AppUtils.fcmVapidPublicKey);
log('FcmReceiver::onFcmToken():currentToken: $currentToken'); log('FcmReceiver::onFcmToken():currentToken: $currentToken');
if (BuildUtils.isWeb) { if (!FcmUtils.instance.isMobileAndroid) {
FcmService.instance.handleGetToken(currentToken); FcmService.instance.handleGetToken(currentToken);
} }
} catch(e) { } catch(e) {
@@ -108,4 +108,6 @@ class FcmUtils {
log('FcmUtils::hashCodeTokenToDeviceId():deviceId: $deviceId'); log('FcmUtils::hashCodeTokenToDeviceId():deviceId: $deviceId');
return deviceId; return deviceId;
} }
bool get isMobileAndroid => !BuildUtils.isWeb && Platform.isAndroid;
} }
@@ -1,5 +1,5 @@
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:tmail_ui_user/features/base/base_bindings.dart'; import 'package:tmail_ui_user/features/base/interactors_bindings.dart';
import 'package:tmail_ui_user/features/session/data/datasource/session_datasource.dart'; import 'package:tmail_ui_user/features/session/data/datasource/session_datasource.dart';
import 'package:tmail_ui_user/features/session/data/datasource_impl/session_datasource_impl.dart'; import 'package:tmail_ui_user/features/session/data/datasource_impl/session_datasource_impl.dart';
import 'package:tmail_ui_user/features/session/data/network/session_api.dart'; import 'package:tmail_ui_user/features/session/data/network/session_api.dart';
@@ -8,11 +8,7 @@ import 'package:tmail_ui_user/features/session/domain/repository/session_reposit
import 'package:tmail_ui_user/features/session/domain/usecases/get_session_interactor.dart'; import 'package:tmail_ui_user/features/session/domain/usecases/get_session_interactor.dart';
import 'package:tmail_ui_user/main/exceptions/remote_exception_thrower.dart'; import 'package:tmail_ui_user/main/exceptions/remote_exception_thrower.dart';
class SessionBindings extends BaseBindings { class SessionBindings extends InteractorsBindings {
@override
void bindingsController() {
}
@override @override
void bindingsDataSource() { void bindingsDataSource() {