import 'dart:async'; import 'package:core/data/model/preview_attachment.dart'; import 'package:core/data/network/download/downloaded_response.dart'; import 'package:core/domain/extensions/datetime_extension.dart'; import 'package:core/presentation/extensions/string_extension.dart'; import 'package:core/presentation/resources/image_paths.dart'; import 'package:core/presentation/utils/html_transformer/transform_configuration.dart'; import 'package:core/utils/app_logger.dart'; import 'package:core/utils/file_utils.dart'; import 'package:core/utils/preview_eml_file_utils.dart'; import 'package:dio/dio.dart'; import 'package:email_recovery/email_recovery/email_recovery_action.dart'; import 'package:email_recovery/email_recovery/email_recovery_action_id.dart'; import 'package:filesize/filesize.dart'; import 'package:get/get.dart'; import 'package:jmap_dart_client/jmap/account_id.dart'; import 'package:jmap_dart_client/jmap/core/error/set_error.dart'; import 'package:jmap_dart_client/jmap/core/id.dart'; import 'package:jmap_dart_client/jmap/core/properties/properties.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/mail/email/email.dart'; import 'package:jmap_dart_client/jmap/mail/email/keyword_identifier.dart'; import 'package:model/model.dart'; import 'package:tmail_ui_user/features/composer/domain/model/email_request.dart'; import 'package:tmail_ui_user/features/email/data/datasource/email_datasource.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/domain/extensions/email_attachment_classifier_extension.dart'; import 'package:tmail_ui_user/features/email/domain/model/detailed_email.dart'; import 'package:tmail_ui_user/features/email/domain/model/move_to_mailbox_request.dart'; import 'package:tmail_ui_user/features/email/domain/model/preview_email_eml_request.dart'; import 'package:tmail_ui_user/features/email/domain/model/restore_deleted_message_request.dart'; import 'package:tmail_ui_user/features/email/domain/model/view_entire_message_request.dart'; import 'package:tmail_ui_user/features/email/presentation/extensions/attachment_extension.dart'; import 'package:tmail_ui_user/features/email/presentation/model/eml_previewer.dart'; import 'package:tmail_ui_user/features/mailbox/domain/model/create_new_mailbox_request.dart'; import 'package:tmail_ui_user/features/sending_queue/domain/model/sending_email.dart'; import 'package:tmail_ui_user/main/exceptions/thrower/exception_thrower.dart'; import 'package:tmail_ui_user/main/exceptions/thrower/send_email_exception_thrower.dart'; class EmailDataSourceImpl extends EmailDataSource { final EmailAPI emailAPI; final ExceptionThrower _exceptionThrower; final ExceptionThrower _sendEmailExceptionThrower = Get.find(); final PreviewEmlFileUtils _previewEmailUtils = Get.find(); final HtmlAnalyzer _htmlAnalyzer = Get.find(); final FileUtils _fileUtils = Get.find(); final ImagePaths _imagePaths = Get.find(); EmailDataSourceImpl(this.emailAPI, this._exceptionThrower); @override Future getEmailContent( Session session, AccountId accountId, EmailId emailId, {Properties? additionalProperties} ) { return Future.sync(() async { return await emailAPI.getEmailContent( session, accountId, emailId, additionalProperties: additionalProperties); }).catchError(_exceptionThrower.throwException); } @override Future sendEmail( Session session, AccountId accountId, EmailRequest emailRequest, { CreateNewMailboxRequest? mailboxRequest, CancelToken? cancelToken, } ) async { try { return await emailAPI.sendEmail( session, accountId, emailRequest, mailboxRequest: mailboxRequest, cancelToken: cancelToken ); } catch (error, stackTrace) { return await _sendEmailExceptionThrower.throwException(error, stackTrace); } } @override Future<({ List emailIdsSuccess, Map mapErrors, })> markAsRead( Session session, AccountId accountId, List emailIds, ReadActions readActions, ) { return Future.sync(() async { return await emailAPI.markAsRead(session, accountId, emailIds, readActions); }).catchError(_exceptionThrower.throwException); } @override Future exportAttachment( Attachment attachment, AccountId accountId, String baseDownloadUrl, AccountRequest accountRequest, CancelToken cancelToken ) { return Future.sync(() async { return await emailAPI.exportAttachment(attachment, accountId, baseDownloadUrl, accountRequest, cancelToken); }).catchError(_exceptionThrower.throwException); } @override Future<({ List emailIdsSuccess, Map mapErrors, })> moveToMailbox( Session session, AccountId accountId, MoveToMailboxRequest moveRequest, ) { return Future.sync(() async { return await emailAPI.moveToMailbox(session, accountId, moveRequest); }).catchError(_exceptionThrower.throwException); } @override Future<({ List emailIdsSuccess, Map mapErrors, })> markAsStar( Session session, AccountId accountId, List emailIds, MarkStarAction markStarAction, ) { return Future.sync(() async { return await emailAPI.markAsStar( session, accountId, emailIds, markStarAction, ); }).catchError(_exceptionThrower.throwException); } @override Future saveEmailAsDrafts( Session session, AccountId accountId, Email email, {CancelToken? cancelToken} ) { return Future.sync(() async { return await emailAPI.saveEmailAsDrafts( session, accountId, email, cancelToken: cancelToken ); }).catchError(_exceptionThrower.throwException); } @override Future removeEmailDrafts( Session session, AccountId accountId, EmailId emailId, {CancelToken? cancelToken} ) { return Future.sync(() async { return await emailAPI.removeEmailDrafts( session, accountId, emailId, cancelToken: cancelToken ); }).catchError(_exceptionThrower.throwException); } @override Future updateEmailDrafts( Session session, AccountId accountId, Email newEmail, EmailId oldEmailId, { CancelToken? cancelToken, bool isUpdateDraftToClose = false, } ) { return Future.sync(() async { return await emailAPI.updateEmailDrafts( session, accountId, newEmail, oldEmailId, cancelToken: cancelToken, isUpdateDraftToClose: isUpdateDraftToClose, ); }).catchError(_exceptionThrower.throwException); } @override Future saveEmailAsTemplate( Session session, AccountId accountId, Email email, { CreateNewMailboxRequest? createNewMailboxRequest, CancelToken? cancelToken } ) { return Future.sync(() async { return await emailAPI.saveEmailAsTemplate( session, accountId, email, createNewMailboxRequest: createNewMailboxRequest, cancelToken: cancelToken ); }).catchError(_exceptionThrower.throwException); } @override Future updateEmailTemplate( Session session, AccountId accountId, Email newEmail, EmailId oldEmailId, {CancelToken? cancelToken} ) { return Future.sync(() async { return await emailAPI.updateEmailTemplate( session, accountId, newEmail, oldEmailId, cancelToken: cancelToken ); }).catchError(_exceptionThrower.throwException); } @override Future<({ List emailIdsSuccess, Map mapErrors, })> deleteMultipleEmailsPermanently( Session session, AccountId accountId, List emailIds, ) { return Future.sync(() async { return await emailAPI.deleteMultipleEmailsPermanently( session, accountId, emailIds, ); }).catchError(_exceptionThrower.throwException); } @override Future deleteEmailPermanently( Session session, AccountId accountId, EmailId emailId, {CancelToken? cancelToken} ) { return Future.sync(() async { return await emailAPI.deleteEmailPermanently( session, accountId, emailId, cancelToken: cancelToken ); }).catchError(_exceptionThrower.throwException); } @override Future storeDetailedNewEmail(Session session, AccountId accountId, DetailedEmail detailedEmail) { throw UnimplementedError(); } @override Future getDetailedEmailById(Session session, AccountId accountId, EmailId emailId) { return Future.sync(() async { return await emailAPI.getDetailedEmailById(session, accountId, emailId); }).catchError(_exceptionThrower.throwException); } @override Future storeEmail(Session session, AccountId accountId, Email email) { throw UnimplementedError(); } @override Future storeOpenedEmail(Session session, AccountId accountId, DetailedEmail detailedEmail) { throw UnimplementedError(); } @override Future getStoredOpenedEmail(Session session, AccountId accountId, EmailId emailId) { throw UnimplementedError(); } @override Future getStoredNewEmail(Session session, AccountId accountId, EmailId emailId) { throw UnimplementedError(); } @override Future getStoredEmail(Session session, AccountId accountId, EmailId emailId) { throw UnimplementedError(); } @override Future storeSendingEmail(AccountId accountId, UserName userName, SendingEmail sendingEmail) { throw UnimplementedError(); } @override Future> getAllSendingEmails(AccountId accountId, UserName userName) { throw UnimplementedError(); } @override Future deleteSendingEmail(AccountId accountId, UserName userName, String sendingId) { throw UnimplementedError(); } @override Future updateSendingEmail(AccountId accountId, UserName userName, SendingEmail newSendingEmail) { throw UnimplementedError(); } @override Future> updateMultipleSendingEmail(AccountId accountId, UserName userName, List newSendingEmails) { throw UnimplementedError(); } @override Future> deleteMultipleSendingEmail(AccountId accountId, UserName userName, List sendingIds) { throw UnimplementedError(); } @override Future getStoredSendingEmail(AccountId accountId, UserName userName, String sendingId) { throw UnimplementedError(); } @override Future unsubscribeMail(Session session, AccountId accountId, EmailId emailId) { return Future.sync(() async { return await emailAPI.unsubscribeMail(session, accountId, emailId); }).catchError(_exceptionThrower.throwException); } @override Future restoreDeletedMessage(RestoredDeletedMessageRequest restoredDeletedMessageRequest) { return Future.sync(() async { return await emailAPI.restoreDeletedMessage(restoredDeletedMessageRequest); }).catchError(_exceptionThrower.throwException); } @override Future getRestoredDeletedMessage(EmailRecoveryActionId emailRecoveryActionId) { return Future.sync(() async { return await emailAPI.getRestoredDeletedMessage(emailRecoveryActionId); }).catchError(_exceptionThrower.throwException); } @override Future markAsAnswered(Session session, AccountId accountId, List emailIds) { throw UnimplementedError(); } @override Future markAsForwarded(Session session, AccountId accountId, List emailIds) { throw UnimplementedError(); } @override Future> parseEmailByBlobIds(AccountId accountId, Set blobIds) { return Future.sync(() async { return await emailAPI.parseEmailByBlobIds(accountId, blobIds); }).catchError(_exceptionThrower.throwException); } @override Future generatePreviewEmailEMLContent(PreviewEmailEMLRequest previewEmailEMLRequest) { return Future.sync(() async { final email = previewEmailEMLRequest.email; final appLocalizations = previewEmailEMLRequest.appLocalizations; final locale = previewEmailEMLRequest.locale.toLanguageTag(); final presentationAttachments = email.toPresentationAttachments(); final listAttachments = presentationAttachments.attachments; final listInlineImages = presentationAttachments.inlineImages; final mapCidImageDownloadUrl = listInlineImages.toMapCidImageDownloadUrl( accountId: previewEmailEMLRequest.accountId, downloadUrl: previewEmailEMLRequest.baseDownloadUrl, ); final emailContentEscaped = await _transformEmailContent( email.emailContentList, mapCidImageDownloadUrl, ); final sender = email.from?.isNotEmpty == true ? email.from!.first : null; final receiveTime = email.getReceivedAt( newLocale: locale, pattern: email.receivedAt?.value.toLocal().toPatternForPrinting(locale) ); final sentTime = email.getSentAt( newLocale: locale, pattern: email.sentAt?.value.toLocal().toPatternForPrinting(locale) ); final List listPreviewAttachment = []; if (listAttachments.isNotEmpty) { await Future.forEach(listAttachments, (attachment) async { final iconBase64Data = await _fileUtils.convertImageAssetToBase64( attachment.getIcon(_imagePaths)); final previewAttachment = PreviewAttachment( iconBase64Data: iconBase64Data, name: (attachment.name ?? '').sanitizedBidiForDisplay, size: filesize(attachment.size?.value), link: attachment.hyperLink, ); listPreviewAttachment.add(previewAttachment); }); } final attachmentIconBase64Data = email.hasAttachment == true ? await _fileUtils.convertImageAssetToBase64(_imagePaths.icAttachment) : ''; final previewEmlHtmlDocument = _previewEmailUtils.generatePreviewEml( appName: appLocalizations.app_name, ownEmailAddress: previewEmailEMLRequest.ownEmailAddress, subjectPrefix: appLocalizations.subject, subject: previewEmailEMLRequest.email.subject ?? '', emailContent: emailContentEscaped, senderName: sender?.name ?? '', senderEmailAddress: sender?.email ?? '', dateTime: receiveTime.isNotEmpty ? receiveTime : sentTime, fromPrefix: appLocalizations.from_email_address_prefix, toPrefix: appLocalizations.to_email_address_prefix, ccPrefix: appLocalizations.cc_email_address_prefix, bccPrefix: appLocalizations.bcc_email_address_prefix, replyToPrefix: appLocalizations.replyToEmailAddressPrefix, titleAttachment: listPreviewAttachment.length > 1 ? appLocalizations.attachments.toLowerCase() : appLocalizations.attachment.toLowerCase(), attachmentIcon: attachmentIconBase64Data, toAddress: email.to?.listEmailAddressToString(isFullEmailAddress: true), ccAddress: email.cc?.listEmailAddressToString(isFullEmailAddress: true), bccAddress: email.bcc?.listEmailAddressToString(isFullEmailAddress: true), replyToAddress: email.replyTo?.listEmailAddressToString(isFullEmailAddress: true), listAttachment: listPreviewAttachment, ); return previewEmlHtmlDocument; }).catchError(_exceptionThrower.throwException); } Future _transformEmailContent( List emailContents, Map mapCidImageDownloadUrl, ) async { try { final transformConfiguration = TransformConfiguration.forPreviewEmailOnPlatform(); final listEmailContent = await Future.wait(emailContents .map((emailContent) async => await _htmlAnalyzer.transformEmailContent( emailContent, mapCidImageDownloadUrl, transformConfiguration, )) .toList()); return listEmailContent.asHtmlString; } catch (e) { logWarning('EmailDataSourceImpl::_transformEmailContent:Exception = $e'); return ''; } } @override Future sharePreviewEmailEMLContent(EMLPreviewer emlPreviewer) { throw UnimplementedError(); } @override Future getPreviewEmailEMLContentShared(String keyStored) { throw UnimplementedError(); } @override Future storePreviewEMLContentToSessionStorage(EMLPreviewer emlPreviewer) { throw UnimplementedError(); } @override Future removePreviewEmailEMLContentShared(String keyStored) { throw UnimplementedError(); } @override Future getPreviewEMLContentInMemory(String keyStored) { throw UnimplementedError(); } @override Future exportAllAttachments( AccountId accountId, EmailId emailId, String baseDownloadAllUrl, String outputFileName, AccountRequest accountRequest, { CancelToken? cancelToken, }) => Future.sync(() async { return await emailAPI.exportAllAttachments( accountId, emailId, baseDownloadAllUrl, outputFileName, accountRequest, cancelToken: cancelToken, ); }).catchError(_exceptionThrower.throwException); @override Future generateEntireMessageAsDocument(ViewEntireMessageRequest entireMessageRequest) { throw UnimplementedError(); } @override Future addLabelToEmail( Session session, AccountId accountId, EmailId emailId, KeyWordIdentifier labelKeyword, ) { return Future.sync(() async { return await emailAPI.addLabelToEmail( session, accountId, emailId, labelKeyword, ); }).catchError(_exceptionThrower.throwException); } @override Future<({ List emailIdsSuccess, Map mapErrors, })> addLabelToThread( Session session, AccountId accountId, List emailIds, KeyWordIdentifier labelKeyword, ) { return Future.sync(() async { return await emailAPI.addLabelToThread( session, accountId, emailIds, labelKeyword, ); }).catchError(_exceptionThrower.throwException); } @override Future removeLabelFromEmail( Session session, AccountId accountId, EmailId emailId, KeyWordIdentifier labelKeyword, ) { return Future.sync(() async { return await emailAPI.removeLabelFromEmail( session, accountId, emailId, labelKeyword, ); }).catchError(_exceptionThrower.throwException); } @override Future<({ List emailIdsSuccess, Map mapErrors, })> removeLabelFromThread( Session session, AccountId accountId, List emailIds, KeyWordIdentifier labelKeyword, ) { return Future.sync(() async { return await emailAPI.removeLabelFromThread( session, accountId, emailIds, labelKeyword, ); }).catchError(_exceptionThrower.throwException); } @override Future<({ List emailIdsSuccess, Map mapErrors, })> addListLabelToListEmail( Session session, AccountId accountId, List emailIds, List labelKeywords, ) { return Future.sync(() async { return await emailAPI.addListLabelToListEmail( session, accountId, emailIds, labelKeywords, ); }).catchError(_exceptionThrower.throwException); } }