TF-1842: Create SendingEmailBinding and implement in SendingEmailObserver

(cherry picked from commit 7ec20283d7d119857ab7e689139e226c15a2137c)
This commit is contained in:
HuyNguyen
2023-05-31 00:56:35 +07:00
committed by Dat Vu
parent d626fc6b4c
commit 36ab1316e2
7 changed files with 309 additions and 12 deletions
@@ -12,8 +12,8 @@ class AuthenticationInfoCacheManager {
authenticationInfoCache);
}
Future<AuthenticationInfoCache?> getAuthenticationInfoStored() {
return _authenticationInfoCacheClient.getItem(AuthenticationInfoCache.keyCacheValue);
Future<AuthenticationInfoCache?> getAuthenticationInfoStored({bool needToReopen = false}) {
return _authenticationInfoCacheClient.getItem(AuthenticationInfoCache.keyCacheValue, needToReopen: needToReopen);
}
Future<void> removeAuthenticationInfo() {
@@ -36,8 +36,8 @@ class CredentialRepositoryImpl extends CredentialRepository {
}
@override
Future<AuthenticationInfoCache?> getAuthenticationInfoStored() {
return _authenticationInfoCacheManager.getAuthenticationInfoStored();
Future<AuthenticationInfoCache?> getAuthenticationInfoStored({bool needToReopen = false}) {
return _authenticationInfoCacheManager.getAuthenticationInfoStored(needToReopen: needToReopen);
}
@override
@@ -9,7 +9,7 @@ abstract class CredentialRepository {
Future<void> storeAuthenticationInfo(AuthenticationInfoCache authenticationInfoCache);
Future<AuthenticationInfoCache?> getAuthenticationInfoStored();
Future<AuthenticationInfoCache?> getAuthenticationInfoStored({bool needToReopen = false});
Future<void> removeAuthenticationInfo();
}
@@ -20,7 +20,7 @@ class GetAuthenticatedAccountInteractor {
this._getStoredTokenOidcInteractor
);
Stream<Either<Failure, Success>> execute() async* {
Stream<Either<Failure, Success>> execute({bool needToReopen = false}) async* {
try {
yield Right<Failure, Success>(LoadingState());
final account = await _accountRepository.getCurrentAccount();
@@ -29,7 +29,7 @@ class GetAuthenticatedAccountInteractor {
if (account.authenticationType == AuthenticationType.oidc) {
yield* _getStoredTokenOidcInteractor.execute(account.id);
} else {
yield await _getCredentialInteractor.execute();
yield await _getCredentialInteractor.execute(needToReopen: needToReopen);
}
} catch (e) {
logError('GetAuthenticatedAccountInteractor::execute(): $e');
@@ -15,10 +15,10 @@ class GetCredentialInteractor {
GetCredentialInteractor(this.credentialRepository);
Future<Either<Failure, Success>> execute() async {
Future<Either<Failure, Success>> execute({bool needToReopen = false}) async {
try {
final baseUrl = await credentialRepository.getBaseUrl();
final authenticationInfo = await credentialRepository.getAuthenticationInfoStored();
final authenticationInfo = await credentialRepository.getAuthenticationInfoStored(needToReopen: needToReopen);
if (isCredentialValid(baseUrl) && authenticationInfo != null) {
return Right(GetCredentialViewState(
baseUrl,
@@ -0,0 +1,109 @@
import 'package:core/data/model/source_type/data_source_type.dart';
import 'package:core/data/network/dio_client.dart';
import 'package:core/utils/file_utils.dart';
import 'package:get/get.dart';
import 'package:tmail_ui_user/features/base/interactors_bindings.dart';
import 'package:tmail_ui_user/features/caching/clients/state_cache_client.dart';
import 'package:tmail_ui_user/features/composer/domain/usecases/send_email_interactor.dart';
import 'package:tmail_ui_user/features/email/data/datasource/email_datasource.dart';
import 'package:tmail_ui_user/features/email/data/datasource/html_datasource.dart';
import 'package:tmail_ui_user/features/email/data/datasource_impl/email_datasource_impl.dart';
import 'package:tmail_ui_user/features/email/data/datasource_impl/email_hive_cache_datasource_impl.dart';
import 'package:tmail_ui_user/features/email/data/datasource_impl/html_datasource_impl.dart';
import 'package:tmail_ui_user/features/email/data/local/html_analyzer.dart';
import 'package:tmail_ui_user/features/email/data/network/email_api.dart';
import 'package:tmail_ui_user/features/email/data/repository/email_repository_impl.dart';
import 'package:tmail_ui_user/features/email/domain/repository/email_repository.dart';
import 'package:tmail_ui_user/features/mailbox/data/datasource/mailbox_datasource.dart';
import 'package:tmail_ui_user/features/mailbox/data/datasource/state_datasource.dart';
import 'package:tmail_ui_user/features/mailbox/data/datasource_impl/mailbox_cache_datasource_impl.dart';
import 'package:tmail_ui_user/features/mailbox/data/datasource_impl/mailbox_datasource_impl.dart';
import 'package:tmail_ui_user/features/mailbox/data/datasource_impl/state_datasource_impl.dart';
import 'package:tmail_ui_user/features/mailbox/data/local/mailbox_cache_manager.dart';
import 'package:tmail_ui_user/features/mailbox/data/network/mailbox_api.dart';
import 'package:tmail_ui_user/features/mailbox/data/network/mailbox_isolate_worker.dart';
import 'package:tmail_ui_user/features/mailbox/data/repository/mailbox_repository_impl.dart';
import 'package:tmail_ui_user/features/mailbox/domain/repository/mailbox_repository.dart';
import 'package:tmail_ui_user/features/offline_mode/manager/detailed_email_cache_manager.dart';
import 'package:tmail_ui_user/features/offline_mode/manager/detailed_email_cache_worker_queue.dart';
import 'package:tmail_ui_user/features/offline_mode/manager/opened_email_cache_manager.dart';
import 'package:tmail_ui_user/features/offline_mode/manager/opened_email_cache_worker_queue.dart';
import 'package:tmail_ui_user/features/offline_mode/manager/sending_email_cache_manager.dart';
import 'package:tmail_ui_user/features/thread/data/local/email_cache_manager.dart';
import 'package:tmail_ui_user/main/exceptions/cache_exception_thrower.dart';
import 'package:tmail_ui_user/main/exceptions/remote_exception_thrower.dart';
class SendingEmailBindings extends InteractorsBindings {
@override
void bindingsDataSource() {
Get.lazyPut<EmailDataSource>(() => Get.find<EmailDataSourceImpl>());
Get.lazyPut<MailboxDataSource>(() => Get.find<MailboxDataSourceImpl>());
Get.lazyPut<HtmlDataSource>(() => Get.find<HtmlDataSourceImpl>());
Get.lazyPut<StateDataSource>(() => Get.find<StateDataSourceImpl>());
}
@override
void bindingsDataSourceImpl() {
Get.lazyPut(() => EmailDataSourceImpl(
Get.find<EmailAPI>(),
Get.find<RemoteExceptionThrower>()));
Get.lazyPut(() => MailboxDataSourceImpl(
Get.find<MailboxAPI>(),
Get.find<MailboxIsolateWorker>(),
Get.find<RemoteExceptionThrower>()));
Get.lazyPut(() => MailboxCacheDataSourceImpl(
Get.find<MailboxCacheManager>(),
Get.find<CacheExceptionThrower>()));
Get.lazyPut(() => HtmlDataSourceImpl(
Get.find<HtmlAnalyzer>(),
Get.find<DioClient>(),
Get.find<RemoteExceptionThrower>()));
Get.lazyPut(() => StateDataSourceImpl(
Get.find<StateCacheClient>(),
Get.find<CacheExceptionThrower>()));
Get.lazyPut(() => EmailHiveCacheDataSourceImpl(
Get.find<DetailedEmailCacheManager>(),
Get.find<OpenedEmailCacheManager>(),
Get.find<DetailedEmailCacheWorkerQueue>(),
Get.find<OpenedEmailCacheWorkerQueue>(),
Get.find<EmailCacheManager>(),
Get.find<SendingEmailCacheManager>(),
Get.find<FileUtils>(),
Get.find<CacheExceptionThrower>()));
}
@override
void bindingsInteractor() {
Get.lazyPut(() => SendEmailInteractor(
Get.find<EmailRepository>(),
Get.find<MailboxRepository>()
));
}
@override
void bindingsRepository() {
Get.lazyPut<EmailRepository>(() => Get.find<EmailRepositoryImpl>());
Get.lazyPut<MailboxRepository>(() => Get.find<MailboxRepositoryImpl>());
}
@override
void bindingsRepositoryImpl() {
Get.lazyPut(() => EmailRepositoryImpl(
{
DataSourceType.network: Get.find<EmailDataSource>(),
DataSourceType.hiveCache: Get.find<EmailHiveCacheDataSourceImpl>()
},
Get.find<HtmlDataSource>(),
Get.find<StateDataSource>(),
));
Get.lazyPut(() => MailboxRepositoryImpl(
{
DataSourceType.network: Get.find<MailboxDataSource>(),
DataSourceType.local: Get.find<MailboxCacheDataSourceImpl>()
},
Get.find<StateDataSource>(),
));
}
}
@@ -1,9 +1,50 @@
import 'package:core/data/network/config/dynamic_url_interceptors.dart';
import 'package:core/presentation/extensions/uri_extension.dart';
import 'package:core/presentation/resources/image_paths.dart';
import 'package:core/presentation/state/failure.dart';
import 'package:core/presentation/state/success.dart';
import 'package:core/presentation/utils/app_toast.dart';
import 'package:core/utils/app_logger.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:model/oidc/token_oidc.dart';
import 'package:tmail_ui_user/features/caching/config/hive_cache_config.dart';
import 'package:tmail_ui_user/features/composer/domain/extensions/sending_email_extension.dart';
import 'package:tmail_ui_user/features/composer/domain/model/sending_email.dart';
import 'package:tmail_ui_user/features/composer/domain/state/send_email_state.dart';
import 'package:tmail_ui_user/features/composer/domain/usecases/send_email_interactor.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';
import 'package:tmail_ui_user/features/login/domain/usecases/get_authenticated_account_interactor.dart';
import 'package:tmail_ui_user/features/mailbox/domain/model/create_new_mailbox_request.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/bindings/mailbox_dashboard_bindings.dart';
import 'package:tmail_ui_user/features/offline_mode/biding/sending_email_biding.dart';
import 'package:tmail_ui_user/features/offline_mode/observer/work_observer.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/localizations/app_localizations.dart';
import 'package:tmail_ui_user/main/routes/route_navigation.dart';
class SendingEmailObserver extends WorkObserver {
AccountId? _currentAccountId;
Session? _currentSession;
UserName? _userName;
Map<String, dynamic>? _inputData;
AppToast? _appToast;
ImagePaths? _imagePaths;
SendEmailInteractor? _sendEmailInteractor;
GetAuthenticatedAccountInteractor? _getAuthenticatedAccountInteractor;
DynamicUrlInterceptors? _dynamicUrlInterceptors;
AuthorizationInterceptors? _authorizationInterceptors;
GetSessionInteractor? _getSessionInteractor;
static SendingEmailObserver? _instance;
SendingEmailObserver._();
@@ -13,12 +54,159 @@ class SendingEmailObserver extends WorkObserver {
@override
Future<void> observe(String taskId, Map<String, dynamic> inputData) async {
log('SendingEmailObserver::observe():taskId: $taskId | inputData: $inputData');
_inputData = inputData;
_getAuthenticatedAccount();
return Future.value();
}
@override
Future<void> bindDI() async {
log('SendingEmailObserver::bindDI(): ');
return Future.value();
return await _initialAppConfig();
}
Future<void> _initialAppConfig() async {
await Future.wait([
MainBindings().dependencies(),
HiveCacheConfig().setUp()
]);
await Future.sync(() {
HomeBindings().dependencies();
MailboxDashBoardBindings().dependencies();
SendingEmailBindings().dependencies();
});
return await _getInteractorBindings();
}
@override
void handleFailureViewState(Failure failure) {
_clearDataQueue();
log('SendingEmailObserver::_handleFailureViewState(): $failure');
}
@override
void handleSuccessViewState(Success success) {
if (success is GetAuthenticatedAccountSuccess) {
_handleGetAuthenticatedAccountSuccess(success);
} else if (success is GetSessionSuccess) {
_handleGetSessionSuccess(success);
} else if (success is GetStoredTokenOidcSuccess) {
_handleGetAccountByOidcSuccess(success);
} else if (success is GetCredentialViewState) {
_handleGetAccountByBasicAuthSuccess(success);
} else if (success is SendEmailSuccess) {
if (currentOverlayContext != null && currentContext != null) {
_appToast?.showToastSuccessMessage(
currentOverlayContext!,
AppLocalizations.of(currentContext!).message_has_been_sent_successfully,
leadingSVGIcon: _imagePaths?.icSendSuccessToast);
}
}
}
Future<void> _getInteractorBindings() {
try {
_getAuthenticatedAccountInteractor = getBinding<GetAuthenticatedAccountInteractor>();
_dynamicUrlInterceptors = getBinding<DynamicUrlInterceptors>();
_authorizationInterceptors = getBinding<AuthorizationInterceptors>();
_getSessionInteractor = getBinding<GetSessionInteractor>();
_appToast = getBinding<AppToast>();
_imagePaths = getBinding<ImagePaths>();
_sendEmailInteractor = getBinding<SendEmailInteractor>();
} catch (e) {
logError('SendingEmailObserver::_getInteractorBindings(): ${e.toString()}');
}
return Future.value(null);
}
void _handleGetAuthenticatedAccountSuccess(GetAuthenticatedAccountSuccess success) {
_currentAccountId = success.account.accountId;
_userName = success.account.userName;
_dynamicUrlInterceptors?.changeBaseUrl(success.account.apiUrl);
log('SendingEmailObserver::_handleGetAuthenticatedAccountSuccess():_currentAccountId: $_currentAccountId | _userName: $_userName');
}
void _getSessionAction() {
if (_getSessionInteractor != null) {
consumeState(_getSessionInteractor!.execute());
} else {
_clearDataQueue();
logError('SendingEmailObserver::_getSessionAction():_getSessionInteractor is null');
}
}
void _getAuthenticatedAccount() {
if (_getAuthenticatedAccountInteractor != null) {
consumeState(_getAuthenticatedAccountInteractor!.execute(needToReopen: true));
} else {
_clearDataQueue();
logError('SendingEmailObserver::_getAuthenticatedAccount():_getAuthenticatedAccountInteractor is null');
}
}
void _handleGetSessionSuccess(GetSessionSuccess success) {
_currentSession = success.session;
_userName = success.session.username;
final jmapUrl = _dynamicUrlInterceptors?.jmapUrl;
final apiUrl = jmapUrl != null
? success.session.apiUrl.toQualifiedUrl(baseUrl: Uri.parse(jmapUrl)).toString()
: success.session.apiUrl.toString();
log('SendingEmailObserver::_handleGetSessionSuccess():jmapUrl: $jmapUrl | apiUrl: $apiUrl');
if (apiUrl.isNotEmpty) {
_dynamicUrlInterceptors?.changeBaseUrl(apiUrl);
_sendEmailAction();
} else {
_clearDataQueue();
logError('SendingEmailObserver::_handleGetSessionSuccess():apiUrl is null');
}
}
void _handleGetAccountByBasicAuthSuccess(GetCredentialViewState credentialViewState) {
log('SendingEmailObserver::_handleGetAccountByBasicAuthSuccess()');
_dynamicUrlInterceptors?.setJmapUrl(credentialViewState.baseUrl.toString());
_authorizationInterceptors?.setBasicAuthorization(
credentialViewState.userName.value,
credentialViewState.password.value,
);
_dynamicUrlInterceptors?.changeBaseUrl(credentialViewState.baseUrl.toString());
_getSessionAction();
}
void _sendEmailAction() {
log('SendingEmailObserver::_sendEmailAction()');
if (_sendEmailInteractor != null && _inputData != null && _currentSession != null && _currentAccountId != null) {
final sendingEmail = SendingEmail.fromJson(_inputData!);
consumeState(_sendEmailInteractor!.execute(
_currentSession!,
_currentAccountId!,
sendingEmail.toEmailRequest(),
mailboxRequest: CreateNewMailboxRequest(
sendingEmail.creationIdRequest!,
sendingEmail.mailboxNameRequest!,
isSubscribed: true,
)
));
} else {
logError('SendingEmailObserver::_sendEmailAction():_sendEmailInteractor is null');
}
}
void _handleGetAccountByOidcSuccess(GetStoredTokenOidcSuccess storedTokenOidcSuccess) {
log('FcmMessageController::_handleGetAccountByOidcSuccess():');
_dynamicUrlInterceptors?.setJmapUrl(storedTokenOidcSuccess.baseUrl.toString());
_authorizationInterceptors?.setTokenAndAuthorityOidc(
newToken: storedTokenOidcSuccess.tokenOidc.toToken(),
newConfig: storedTokenOidcSuccess.oidcConfiguration
);
_dynamicUrlInterceptors?.changeBaseUrl(storedTokenOidcSuccess.baseUrl.toString());
_getSessionAction();
}
void _clearDataQueue() {
_inputData = null;
}
}