TF-1631 Implement FcmMessageController and FcmTokenController

(cherry picked from commit aa101127f5aab44b9d86880dd760e78b1d0c9368)
This commit is contained in:
dab246
2023-03-28 10:39:08 +07:00
committed by Dat Vu
parent 72906ceb3b
commit 62548698f8
4 changed files with 99 additions and 116 deletions
+2 -2
View File
@@ -39,7 +39,7 @@ import 'package:tmail_ui_user/features/push_notification/domain/usecases/destroy
import 'package:tmail_ui_user/features/push_notification/domain/usecases/get_fcm_subscription_local_interactor.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/bindings/fcm_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_controller.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/controller/fcm_message_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/main/bindings/network/binding_tag.dart';
@@ -232,7 +232,7 @@ abstract class BaseController extends GetxController
await LocalNotificationManager.instance.setUp();
}
FcmInteractorBindings().dependencies();
FcmController.instance.initialize(session: session, accountId: accountId);
FcmMessageController.instance.initialize(session: session, accountId: accountId);
} else {
throw NotSupportFCMException();
}
@@ -6,7 +6,6 @@ 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:jmap_dart_client/jmap/account_id.dart';
@@ -16,9 +15,9 @@ 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_authenticated_account_state.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';
@@ -26,7 +25,8 @@ import 'package:tmail_ui_user/features/login/domain/usecases/get_authenticated_a
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/bindings/fcm_interactor_bindings.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/controller/fcm_token_handler.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/controller/fcm_base_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/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/listener/mailbox_change_listener.dart';
@@ -35,7 +35,7 @@ import 'package:tmail_ui_user/features/push_notification/presentation/utils/fcm_
import 'package:tmail_ui_user/main/bindings/main_bindings.dart';
import 'package:tmail_ui_user/main/routes/route_navigation.dart';
class FcmController extends BaseController {
class FcmMessageController extends FcmBaseController {
AccountId? _currentAccountId;
Session? _currentSession;
@@ -43,19 +43,20 @@ class FcmController extends BaseController {
GetAuthenticatedAccountInteractor? _getAuthenticatedAccountInteractor;
DynamicUrlInterceptors? _dynamicUrlInterceptors;
AuthorizationInterceptors? _authorizationInterceptors;
FcmController._internal() {
FcmMessageController._internal() {
_listenFcmStream();
}
static final FcmController _instance = FcmController._internal();
static final FcmMessageController _instance = FcmMessageController._internal();
static FcmController get instance => _instance;
static FcmMessageController get instance => _instance;
void initialize({Session? session, AccountId? accountId}) {
_currentSession = session;
_currentAccountId = accountId;
FcmTokenHandler.instance.initialize();
FcmTokenController.instance.initialize();
}
void _listenFcmStream() async {
@@ -83,12 +84,12 @@ class FcmController extends BaseController {
Future<void> listenTokenStream() {
FcmService.instance.fcmTokenStream
.debounceTime(const Duration(milliseconds: FcmService.durationRefreshToken))
.listen(FcmTokenHandler.instance.handleTokenAction);
.listen(FcmTokenController.instance.handleTokenAction);
return Future.value();
}
void _handleForegroundMessageAction(RemoteMessage newRemoteMessage) {
log('FcmController::_handleForegroundMessageAction():remoteMessage: ${newRemoteMessage.data}');
log('FcmMessageController::_handleForegroundMessageAction():remoteMessage: ${newRemoteMessage.data}');
if (_currentAccountId != null && _currentSession != null) {
final stateChange = _convertRemoteMessageToStateChange(newRemoteMessage);
final mapTypeState = stateChange.getMapTypeState(_currentAccountId!);
@@ -97,7 +98,7 @@ class FcmController extends BaseController {
}
void _handleBackgroundMessageAction(RemoteMessage newRemoteMessage) async {
log('FcmController::_handleBackgroundMessageAction():remoteMessage: ${newRemoteMessage.data}');
log('FcmMessageController::_handleBackgroundMessageAction():remoteMessage: ${newRemoteMessage.data}');
_remoteMessageBackground = newRemoteMessage;
await _initialAppConfig();
_getAuthenticatedAccount();
@@ -113,7 +114,7 @@ class FcmController extends BaseController {
AccountId accountId, {
bool isForeground = true,
}) {
log('FcmController::_mappingTypeStateToAction():mapTypeState: $mapTypeState');
log('FcmMessageController::_mappingTypeStateToAction():mapTypeState: $mapTypeState');
final listTypeName = mapTypeState.keys
.map((value) => TypeName(value))
.toList();
@@ -124,7 +125,7 @@ class FcmController extends BaseController {
.whereNotNull()
.toList();
log('FcmController::_mappingTypeStateToAction():listEmailActions: $listEmailActions');
log('FcmMessageController::_mappingTypeStateToAction():listEmailActions: $listEmailActions');
if (listEmailActions.isNotEmpty) {
EmailChangeListener.instance.dispatchActions(listEmailActions);
@@ -136,7 +137,7 @@ class FcmController extends BaseController {
.whereNotNull()
.toList();
log('FcmController::_mappingTypeStateToAction():listMailboxActions: $listEmailActions');
log('FcmMessageController::_mappingTypeStateToAction():listMailboxActions: $listEmailActions');
if (listMailboxActions.isNotEmpty) {
MailboxChangeListener.instance.dispatchActions(listMailboxActions);
@@ -190,9 +191,10 @@ class FcmController extends BaseController {
try {
_getAuthenticatedAccountInteractor = getBinding<GetAuthenticatedAccountInteractor>();
_dynamicUrlInterceptors = getBinding<DynamicUrlInterceptors>();
FcmTokenHandler.instance.initialize();
_authorizationInterceptors = getBinding<AuthorizationInterceptors>();
FcmTokenController.instance.initialize();
} catch (e) {
logError('FcmController::_getBindings(): ${e.toString()}');
logError('FcmMessageController::_getBindings(): ${e.toString()}');
}
return Future.value(null);
}
@@ -202,35 +204,19 @@ class FcmController extends BaseController {
consumeState(_getAuthenticatedAccountInteractor!.execute());
} else {
_clearRemoteMessageBackground();
logError('FcmController::_getAuthenticatedAccount():_getAuthenticatedAccountInteractor is null');
}
}
void _handleFailureViewState(Failure failure) {
log('FcmController::_handleFailureViewState(): $failure');
_clearRemoteMessageBackground();
}
void _handleSuccessViewState(Success success) {
log('FcmController::_handleSuccessViewState(): $success');
if (success is GetAuthenticatedAccountSuccess) {
_handleGetAuthenticatedAccountSuccess(success);
} else if (success is GetStoredTokenOidcSuccess) {
_handleGetAccountByOidcSuccess(success);
} else if (success is GetCredentialViewState) {
_handleGetAccountByBasicAuthSuccess(success);
logError('FcmMessageController::_getAuthenticatedAccount():_getAuthenticatedAccountInteractor is null');
}
}
void _handleGetAuthenticatedAccountSuccess(GetAuthenticatedAccountSuccess success) {
_currentAccountId = success.account.accountId;
_dynamicUrlInterceptors?.changeBaseUrl(success.account.apiUrl);
log('FcmController::_handleGetAuthenticatedAccountSuccess():_currentAccountId: $_currentAccountId');
log('FcmMessageController::_handleGetAuthenticatedAccountSuccess():_currentAccountId: $_currentAccountId');
}
void _handleGetAccountByOidcSuccess(GetStoredTokenOidcSuccess storedTokenOidcSuccess) {
log('FcmController::_handleGetAccountByOidcSuccess():');
authorizationInterceptors.setTokenAndAuthorityOidc(
log('FcmMessageController::_handleGetAccountByOidcSuccess():');
_authorizationInterceptors?.setTokenAndAuthorityOidc(
newToken: storedTokenOidcSuccess.tokenOidc.toToken(),
newConfig: storedTokenOidcSuccess.oidcConfiguration
);
@@ -238,8 +224,8 @@ class FcmController extends BaseController {
}
void _handleGetAccountByBasicAuthSuccess(GetCredentialViewState credentialViewState) {
log('FcmController::_handleGetAccountByBasicAuthSuccess():');
authorizationInterceptors.setBasicAuthorization(
log('FcmMessageController::_handleGetAccountByBasicAuthSuccess():');
_authorizationInterceptors?.setBasicAuthorization(
credentialViewState.userName.userName,
credentialViewState.password.value,
);
@@ -247,7 +233,7 @@ class FcmController extends BaseController {
}
void _pushActionFromRemoteMessageBackground() {
log('FcmController::_pushActionFromRemoteMessageBackground():');
log('FcmMessageController::_pushActionFromRemoteMessageBackground():');
if (_remoteMessageBackground != null && _currentAccountId != null && _currentSession != null) {
final stateChange = _convertRemoteMessageToStateChange(_remoteMessageBackground!);
final mapTypeState = stateChange.getMapTypeState(_currentAccountId!);
@@ -261,11 +247,20 @@ class FcmController extends BaseController {
}
@override
void onData(Either<Failure, Success> newState) {
super.onData(newState);
newState.fold(_handleFailureViewState, _handleSuccessViewState);
void handleFailureViewState(Failure failure) {
log('FcmMessageController::_handleFailureViewState(): $failure');
_clearRemoteMessageBackground();
}
@override
void onDone() {}
void handleSuccessViewState(Success success) {
log('FcmMessageController::_handleSuccessViewState(): $success');
if (success is GetAuthenticatedAccountSuccess) {
_handleGetAuthenticatedAccountSuccess(success);
} else if (success is GetStoredTokenOidcSuccess) {
_handleGetAccountByOidcSuccess(success);
} else if (success is GetCredentialViewState) {
_handleGetAccountByBasicAuthSuccess(success);
}
}
}
@@ -3,7 +3,6 @@ import 'package:core/domain/extensions/datetime_extension.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/device_client_id.dart';
import 'package:fcm/model/firebase_expired_time.dart';
import 'package:fcm/model/firebase_subscription.dart';
@@ -20,17 +19,18 @@ import 'package:tmail_ui_user/features/push_notification/domain/usecases/get_fcm
import 'package:tmail_ui_user/features/push_notification/domain/usecases/get_firebase_subscription_interactor.dart';
import 'package:tmail_ui_user/features/push_notification/domain/usecases/register_new_token_interactor.dart';
import 'package:tmail_ui_user/features/push_notification/domain/usecases/store_subscription_interator.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/controller/fcm_base_controller.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/utils/fcm_utils.dart';
import 'package:tmail_ui_user/main/routes/route_navigation.dart';
import 'package:uuid/uuid.dart';
class FcmTokenHandler {
class FcmTokenController extends FcmBaseController {
FcmTokenHandler._internal();
FcmTokenController._internal();
static final FcmTokenHandler _instance = FcmTokenHandler._internal();
static final FcmTokenController _instance = FcmTokenController._internal();
static FcmTokenHandler get instance => _instance;
static FcmTokenController get instance => _instance;
static const int limitedTimeToExpire = 3;
static const int extensionTimeExpire = 7;
@@ -50,18 +50,18 @@ class FcmTokenHandler {
_registerNewTokenInteractor = getBinding<RegisterNewTokenInteractor>();
_getFCMSubscriptionLocalInteractor = getBinding<GetFCMSubscriptionLocalInteractor>();
} catch (e) {
logError('FcmTokenHandler::initialize(): ${e.toString()}');
logError('FcmTokenController::initialize(): ${e.toString()}');
}
}
void handleTokenAction(String? token) {
log('FcmTokenHandler::handleTokenAction():token: $token');
log('FcmTokenController::handleTokenAction():token: $token');
if (token != null) {
_fcmToken = FirebaseToken(token);
final deviceId = FcmUtils.instance.hashTokenToDeviceId(token);
_deviceClientId = DeviceClientId(deviceId);
log('FcmTokenHandler::handleTokenAction(): fcmToken: $_fcmToken');
log('FcmTokenHandler::handleTokenAction(): deviceId: $deviceId');
log('FcmTokenController::handleTokenAction(): fcmToken: $_fcmToken');
log('FcmTokenController::handleTokenAction(): deviceId: $deviceId');
_getFcmTokenFromBackend(deviceId);
} else {
_getFCMSubscriptionLocalAction();
@@ -70,68 +70,24 @@ class FcmTokenHandler {
void _getFcmTokenFromBackend(String deviceId) {
if (_getFirebaseSubscriptionInteractor != null) {
_consumeState(_getFirebaseSubscriptionInteractor!.execute(deviceId));
consumeState(_getFirebaseSubscriptionInteractor!.execute(deviceId));
}
}
void _storeSubscriptionAction(FCMSubscription fcmSubscription){
if (_storeSubscriptionInteractor != null) {
_consumeState(_storeSubscriptionInteractor!.execute(fcmSubscription));
}
}
void _consumeState(Stream<Either<Failure, Success>> newStateStream) {
newStateStream.listen(
_handleStateStream,
onError: (error, stackTrace) {
logError('FcmTokenHandler::consumeState():onError:error: $error');
logError('FcmTokenHandler::consumeState():onError:stackTrace: $stackTrace');
}
);
}
void _handleStateStream(Either<Failure, Success> newState) {
newState.fold(_handleFailureViewState, _handleSuccessViewState);
}
void _handleFailureViewState(Failure failure) {
log('FcmTokenHandler::_handleFailureViewState(): $failure');
if (failure is GetFirebaseSubscriptionFailure) {
if (_fcmToken != null && _deviceClientId != null) {
_handleRegisterNewToken(_fcmToken!, _deviceClientId!);
}
}
}
void _handleSuccessViewState(Success success) {
log('FcmTokenHandler::_handleSuccessViewState(): $success');
if (success is GetFirebaseSubscriptionSuccess) {
_deviceClientId = success.firebaseSubscription.deviceClientId;
final expireTime = success.firebaseSubscription.expires;
log('FcmTokenHandler::_handleSuccessViewState():_fcmToken: $_fcmToken');
if (_isTokenExpired(expireTime)) {
log('FcmTokenHandler::_handleSuccessViewState(): _isTokenExpired true');
_handleWhenTokenExpired();
}
} else if (success is RegisterNewTokenSuccess) {
final deviceId = success.firebaseSubscription.deviceClientId?.value;
final subscriptionId = success.firebaseSubscription.id?.id.value;
if (deviceId != null && subscriptionId != null) {
_storeSubscriptionAction(FCMSubscription(deviceId, subscriptionId));
}
} else if (success is GetFCMSubscriptionLocalSuccess) {
_getFcmTokenFromBackend(success.fcmSubscription.deviceId);
consumeState(_storeSubscriptionInteractor!.execute(fcmSubscription));
}
}
bool _isTokenExpired(FirebaseExpiredTime? expireTime) {
log('FcmTokenHandler::_isTokenExpired():expireTime: $expireTime');
log('FcmTokenController::_isTokenExpired():expireTime: $expireTime');
if (expireTime != null) {
final expireTimeLocal = expireTime.value.value.toLocal();
final currentTime = DateTime.now();
log('FcmTokenHandler::_isTokenExpired():expireTimeLocal: $expireTimeLocal');
log('FcmTokenHandler::_isTokenExpired():currentTime: $currentTime');
log('FcmTokenController::_isTokenExpired():expireTimeLocal: $expireTimeLocal');
log('FcmTokenController::_isTokenExpired():currentTime: $currentTime');
return currentTime.isBefore(expireTimeLocal) &&
expireTimeLocal.daysBetween(currentTime) <= limitedTimeToExpire;
@@ -142,14 +98,14 @@ class FcmTokenHandler {
void _handleWhenTokenExpired() {
if (_fcmToken == null || _deviceClientId == null) {
log('FcmTokenHandler::_handleSuccessViewState():_fcmToken or _deviceClientId is null');
log('FcmTokenController::_handleSuccessViewState():_fcmToken or _deviceClientId is null');
return;
}
final generateCreationId = Id(const Uuid().v4());
final newExpireTime = DateTime.now().add(const Duration(days: extensionTimeExpire));
log('FcmTokenHandler::_handleSuccessViewState():newExpireTime: $newExpireTime');
log('FcmTokenController::_handleSuccessViewState():newExpireTime: $newExpireTime');
final firebaseSubscription = FirebaseSubscription(
token: _fcmToken!,
expires: FirebaseExpiredTime(newExpireTime.toUTCDate()!),
@@ -157,7 +113,7 @@ class FcmTokenHandler {
types: [TypeName.emailType, TypeName.mailboxType, TypeName.emailDelivery]
);
log('FcmTokenHandler::_handleSuccessViewState():firebaseSubscription: $firebaseSubscription');
log('FcmTokenController::_handleSuccessViewState():firebaseSubscription: $firebaseSubscription');
_invokeRegisterNewTokenAction(RegisterNewTokenRequest(
generateCreationId,
firebaseSubscription
@@ -171,7 +127,7 @@ class FcmTokenHandler {
deviceClientId: deviceClientId,
types: [TypeName.emailType, TypeName.mailboxType, TypeName.emailDelivery]
);
log('FcmTokenHandler::_handleRegisterNewToken():firebaseSubscription: $firebaseSubscription');
log('FcmTokenController::_handleRegisterNewToken():firebaseSubscription: $firebaseSubscription');
_invokeRegisterNewTokenAction(RegisterNewTokenRequest(
generateCreationId,
firebaseSubscription
@@ -180,13 +136,45 @@ class FcmTokenHandler {
void _invokeRegisterNewTokenAction(RegisterNewTokenRequest newTokenRequest) {
if (_registerNewTokenInteractor != null) {
_consumeState(_registerNewTokenInteractor!.execute(newTokenRequest));
consumeState(_registerNewTokenInteractor!.execute(newTokenRequest));
}
}
void _getFCMSubscriptionLocalAction() {
if (_getFCMSubscriptionLocalInteractor != null) {
_consumeState(_getFCMSubscriptionLocalInteractor!.execute());
consumeState(_getFCMSubscriptionLocalInteractor!.execute());
}
}
@override
void handleFailureViewState(Failure failure) {
log('FcmTokenController::_handleFailureViewState(): $failure');
if (failure is GetFirebaseSubscriptionFailure) {
if (_fcmToken != null && _deviceClientId != null) {
_handleRegisterNewToken(_fcmToken!, _deviceClientId!);
}
}
}
@override
void handleSuccessViewState(Success success) {
log('FcmTokenController::_handleSuccessViewState(): $success');
if (success is GetFirebaseSubscriptionSuccess) {
_deviceClientId = success.firebaseSubscription.deviceClientId;
final expireTime = success.firebaseSubscription.expires;
log('FcmTokenController::_handleSuccessViewState():_fcmToken: $_fcmToken');
if (_isTokenExpired(expireTime)) {
log('FcmTokenController::_handleSuccessViewState(): _isTokenExpired true');
_handleWhenTokenExpired();
}
} else if (success is RegisterNewTokenSuccess) {
final deviceId = success.firebaseSubscription.deviceClientId?.value;
final subscriptionId = success.firebaseSubscription.id?.id.value;
if (deviceId != null && subscriptionId != null) {
_storeSubscriptionAction(FCMSubscription(deviceId, subscriptionId));
}
} else if (success is GetFCMSubscriptionLocalSuccess) {
_getFcmTokenFromBackend(success.fcmSubscription.deviceId);
}
}
}
@@ -3,7 +3,7 @@ import 'dart:async';
import 'package:core/utils/app_logger.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/controller/fcm_controller.dart';
import 'package:tmail_ui_user/features/push_notification/presentation/controller/fcm_message_controller.dart';
class FcmService {
@@ -37,7 +37,7 @@ class FcmService {
}
void handleFirebaseBackgroundMessage(RemoteMessage newRemoteMessage) {
FcmController.instance.initialize();
FcmMessageController.instance.initialize();
if (!backgroundMessageStreamController.isClosed) {
backgroundMessageStreamController.add(newRemoteMessage);
}
@@ -48,7 +48,7 @@ class FcmService {
if (fcmTokenStreamController.isClosed) {
log('FcmService::handleGetToken():fcmTokenStreamController: isClosed');
fcmTokenStreamController = StreamController<String?>.broadcast();
await FcmController.instance.listenTokenStream();
await FcmMessageController.instance.listenTokenStream();
}
if (!fcmTokenStreamController.isClosed) {
fcmTokenStreamController.add(currentToken);
@@ -60,7 +60,7 @@ class FcmService {
if (fcmTokenStreamController.isClosed) {
log('FcmService::handleRefreshToken():fcmTokenStreamController: isClosed');
fcmTokenStreamController = StreamController<String?>.broadcast();
await FcmController.instance.listenTokenStream();
await FcmMessageController.instance.listenTokenStream();
}
if (!fcmTokenStreamController.isClosed) {
fcmTokenStreamController.add(newToken);
@@ -70,15 +70,15 @@ class FcmService {
Future<void> recreateStreamController() async {
if (foregroundMessageStreamController.isClosed) {
foregroundMessageStreamController = StreamController<RemoteMessage>.broadcast();
await FcmController.instance.listenForegroundMessageStream();
await FcmMessageController.instance.listenForegroundMessageStream();
}
if (backgroundMessageStreamController.isClosed) {
backgroundMessageStreamController = StreamController<RemoteMessage>.broadcast();
await FcmController.instance.listenBackgroundMessageStream();
await FcmMessageController.instance.listenBackgroundMessageStream();
}
if (fcmTokenStreamController.isClosed) {
fcmTokenStreamController = StreamController<String?>.broadcast();
await FcmController.instance.listenTokenStream();
await FcmMessageController.instance.listenTokenStream();
}
return Future.value();
}