TF-4128 Separate download handling into independent class to decouple from views on web

This commit is contained in:
dab246
2025-10-28 16:44:40 +07:00
committed by Dat H. Pham
parent 832f8e1391
commit be8eaf6258
37 changed files with 955 additions and 1095 deletions
@@ -1,15 +1,168 @@
import 'dart:async';
import 'package:core/data/network/config/dynamic_url_interceptors.dart';
import 'package:core/data/network/download/download_manager.dart';
import 'package:core/presentation/extensions/color_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:core/utils/platform_info.dart';
import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/src/dialog/dialog_route.dart';
import 'package:http_parser/http_parser.dart';
import 'package:jmap_dart_client/jmap/account_id.dart';
import 'package:jmap_dart_client/jmap/core/session/session.dart';
import 'package:model/download/download_task_id.dart';
import 'package:model/email/attachment.dart';
import 'package:model/email/eml_attachment.dart';
import 'package:model/email/presentation_email.dart';
import 'package:model/extensions/presentation_email_extension.dart';
import 'package:model/extensions/session_extension.dart';
import 'package:pointer_interceptor/pointer_interceptor.dart';
import 'package:tmail_ui_user/features/base/base_controller.dart';
import 'package:tmail_ui_user/features/email/domain/exceptions/email_exceptions.dart';
import 'package:tmail_ui_user/features/email/domain/state/download_all_attachments_for_web_state.dart';
import 'package:tmail_ui_user/features/email/domain/state/download_attachment_for_web_state.dart';
import 'package:tmail_ui_user/features/email/domain/usecases/download_all_attachments_for_web_interactor.dart';
import 'package:tmail_ui_user/features/email/domain/usecases/download_attachment_for_web_interactor.dart';
import 'package:tmail_ui_user/features/email/presentation/extensions/attachment_extension.dart';
import 'package:tmail_ui_user/features/home/data/exceptions/session_exceptions.dart';
import 'package:tmail_ui_user/features/home/domain/extensions/session_extensions.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/action/download_ui_action.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/model/download/download_task_state.dart';
import 'package:tmail_ui_user/main/localizations/app_localizations.dart';
import 'package:tmail_ui_user/main/routes/route_navigation.dart';
import 'package:twake_previewer_flutter/core/constants/supported_charset.dart';
import 'package:twake_previewer_flutter/core/previewer_options/options/previewer_state.dart';
import 'package:twake_previewer_flutter/core/previewer_options/options/top_bar_options.dart';
import 'package:twake_previewer_flutter/core/previewer_options/previewer_options.dart';
import 'package:twake_previewer_flutter/twake_image_previewer/twake_image_previewer.dart';
import 'package:twake_previewer_flutter/twake_plain_text_previewer/twake_plain_text_previewer.dart';
import 'package:uuid/uuid.dart';
typedef UpdateDownloadTaskStateCallback = DownloadTaskState Function(DownloadTaskState currentState);
class DownloadController extends GetxController {
class DownloadController extends BaseController {
final DownloadAttachmentForWebInteractor _downloadAttachmentForWebInteractor;
final DownloadAllAttachmentsForWebInteractor
_downloadAllAttachmentsForWebInteractor;
final DownloadManager _downloadManager;
DownloadController(
this._downloadAttachmentForWebInteractor,
this._downloadAllAttachmentsForWebInteractor,
this._downloadManager,
);
final listDownloadTaskState = RxList<DownloadTaskState>();
final hideDownloadTaskbar = RxBool(false);
final downloadUIAction = Rxn<DownloadUIAction>();
final _downloadProgressStateController =
StreamController<Either<Failure, Success>>.broadcast();
StreamSubscription<Either<Failure, Success>>?
_downloadProgressStateSubscription;
@override
void onInit() {
super.onInit();
_registerDownloadProgressState();
}
void _registerDownloadProgressState() {
_downloadProgressStateSubscription = _downloadProgressStateController.stream
.listen(_onDownloadProgressStateChanged);
}
void _onDownloadProgressStateChanged(Either<Failure, Success> state) {
state.fold((_) => null, (success) {
if (success is StartDownloadAttachmentForWeb) {
_handleStartSingleDownload(success);
} else if (success is DownloadingAttachmentForWeb) {
_updateDownloadProgress(
success.taskId,
success.progress,
success.downloaded,
success.total,
);
} else if (success is StartDownloadAllAttachmentsForWeb) {
_handleStartAllDownload(success);
} else if (success is DownloadingAllAttachmentsForWeb) {
_updateDownloadProgress(
success.taskId,
success.progress,
success.downloaded,
success.total,
);
}
});
}
void _handleStartSingleDownload(StartDownloadAttachmentForWeb success) {
if (success.previewerSupported) return;
addDownloadTask(
DownloadTaskState(
taskId: success.taskId,
attachment: success.attachment,
onCancel: success.cancelToken?.cancel,
),
);
if (_hasValidContext) {
appToast.showToastMessage(
currentOverlayContext!,
AppLocalizations.of(currentContext!).your_download_has_started,
leadingSVGIconColor: AppColor.primaryColor,
leadingSVGIcon: imagePaths.icDownload,
);
}
}
void _handleStartAllDownload(StartDownloadAllAttachmentsForWeb success) {
addDownloadTask(
DownloadTaskState(
taskId: success.taskId,
attachment: success.attachment,
onCancel: () => success.cancelToken?.cancel(),
),
);
if (_hasValidContext) {
appToast.showToastSuccessMessage(
currentOverlayContext!,
AppLocalizations.of(currentContext!).creatingAnArchiveForDownloading,
leadingSVGIconColor: Colors.white,
leadingSVGIcon: imagePaths.icDownloadAll,
);
}
}
void _updateDownloadProgress(
DownloadTaskId taskId,
double progress,
int downloaded,
int total,
) {
final percent = progress.round();
log('$runtimeType::_updateDownloadProgress(): $percent%');
updateDownloadTaskByTaskId(taskId, (currentTask) {
return currentTask.copyWith(
progress: progress,
downloaded: downloaded,
total: total,
);
});
}
bool get _hasValidContext =>
currentOverlayContext != null && currentContext != null;
bool get notEmptyListDownloadTask => listDownloadTaskState.isNotEmpty;
@@ -43,4 +196,312 @@ class DownloadController extends GetxController {
hideDownloadTaskbar.value = true;
}
}
void downloadAttachmentForWeb({
required Attachment attachment,
required AccountId? accountId,
required Session? session,
bool previewerSupported = false,
}) {
if (accountId == null || session == null) {
consumeState(Stream.value(
Left(DownloadAttachmentForWebFailure(
attachment: attachment,
exception: NotFoundSessionException(),
)),
));
return;
}
final generateTaskId = DownloadTaskId(uuid.v4());
try {
final baseDownloadUrl = session.getDownloadUrl(
jmapUrl: dynamicUrlInterceptors.jmapUrl,
);
final cancelToken = CancelToken();
consumeState(_downloadAttachmentForWebInteractor.execute(
generateTaskId,
attachment,
accountId,
baseDownloadUrl,
onReceiveController: _downloadProgressStateController,
cancelToken: cancelToken,
previewerSupported: previewerSupported,
));
} catch (e) {
consumeState(Stream.value(
Left(DownloadAttachmentForWebFailure(
attachment: attachment,
taskId: generateTaskId,
exception: e,
)),
));
}
}
void downloadAllAttachmentsForWeb({
required String outputFileName,
required PresentationEmail? currentEmail,
required AccountId? accountId,
required Session? session,
bool previewerSupported = false,
}) {
final taskId = DownloadTaskId(uuid.v4());
if (accountId == null || session == null) {
consumeState(Stream.value(
Left(DownloadAllAttachmentsForWebFailure(
exception: NotFoundSessionException(),
taskId: taskId,
)),
));
return;
}
final downloadAllSupported = session.isDownloadAllSupported(accountId);
final emailId = currentEmail?.id;
if (!downloadAllSupported || emailId == null) {
consumeState(Stream.value(
Left(DownloadAllAttachmentsForWebFailure(taskId: taskId)),
));
return;
}
final baseDownloadAllUrl = session.getDownloadAllCapability(accountId)!.endpoint!;
final downloadAttachment = Attachment(
name: outputFileName,
type: MediaType('application', 'zip'),
);
final cancelToken = CancelToken();
consumeState(_downloadAllAttachmentsForWebInteractor.execute(
accountId,
emailId,
baseDownloadAllUrl,
downloadAttachment,
taskId,
onReceiveController: _downloadProgressStateController,
cancelToken: cancelToken,
));
}
void downloadMessageAsEML({
required PresentationEmail presentationEmail,
required AccountId? accountId,
required Session? session,
}) {
if (accountId == null || session == null) return;
final emlAttachment = presentationEmail.createEMLAttachment();
if (emlAttachment.blobId == null) {
consumeState(Stream.value(
Left(DownloadAttachmentForWebFailure(
exception: NotFoundEmailBlobIdException(),
)),
));
return;
}
final generateTaskId = DownloadTaskId(const Uuid().v4());
try {
final baseDownloadUrl = session.getDownloadUrl(
jmapUrl: getBinding<DynamicUrlInterceptors>()?.jmapUrl,
);
final cancelToken = CancelToken();
consumeState(_downloadAttachmentForWebInteractor.execute(
generateTaskId,
emlAttachment,
accountId,
baseDownloadUrl,
onReceiveController: _downloadProgressStateController,
cancelToken: cancelToken,
previewerSupported: false,
));
} catch (e) {
consumeState(Stream.value(Left(DownloadAttachmentForWebFailure(
attachment: emlAttachment,
taskId: generateTaskId,
exception: e,
))));
}
}
void _pushDownloadUIAction(DownloadUIAction action) {
downloadUIAction.value = action;
}
void _handleDownloadAttachmentForWebSuccess(
DownloadAttachmentForWebSuccess success,
) {
_pushDownloadUIAction(UpdateAttachmentsViewStateAction(
success.attachment.blobId,
success,
));
deleteDownloadTask(success.taskId);
if (!success.previewerSupported) {
_downloadManager.createAnchorElementDownloadFileWeb(
success.bytes,
success.attachment.generateFileName(),
);
return;
}
if (success.attachment.isImage) {
_previewImageFile(attachment: success.attachment, bytes: success.bytes);
} else if (success.attachment.isText || success.attachment.isJson) {
_previewTextPlainFile(
attachment: success.attachment,
bytes: success.bytes,
);
}
}
void _downloadAttachmentQuickly(Attachment attachment) {
if (PlatformInfo.isWeb) {
_pushDownloadUIAction(DownloadAttachmentsQuicklyAction(attachment));
}
}
void _previewImageFile({
required Uint8List bytes,
required Attachment attachment,
}) {
if (currentContext == null) return;
Navigator.of(currentContext!).push(GetDialogRoute(
pageBuilder: (context, _, __) => PointerInterceptor(
child: TwakeImagePreviewer(
bytes: bytes,
zoomable: true,
previewerOptions: const PreviewerOptions(
previewerState: PreviewerState.success,
),
topBarOptions: TopBarOptions(
title: attachment.generateFileName(),
onClose: () => Navigator.maybePop(context),
onDownload: currentContext == null
? null
: () => _downloadAttachmentQuickly(attachment),
),
),
),
barrierDismissible: false,
));
}
void _previewTextPlainFile({
required Uint8List bytes,
required Attachment attachment,
}) {
if (currentContext == null) return;
Navigator.of(currentContext!).push(GetDialogRoute(
pageBuilder: (context, _, __) => PointerInterceptor(
child: TwakePlainTextPreviewer(
supportedCharset: SupportedCharset.utf8,
bytes: bytes,
previewerOptions: PreviewerOptions(
previewerState: PreviewerState.success,
width: currentContext == null ? 200 : currentContext!.width * 0.8,
),
topBarOptions: TopBarOptions(
title: attachment.generateFileName(),
onClose: () => Navigator.maybePop(context),
onDownload: currentContext == null
? null
: () => _downloadAttachmentQuickly(attachment),
),
),
),
barrierDismissible: false,
));
}
void clearDownloadUIAction() {
downloadUIAction.value = null;
}
void _downloadAllAttachmentsForWebFailure(
DownloadAllAttachmentsForWebFailure failure,
) {
deleteDownloadTask(failure.taskId);
if (currentOverlayContext == null || currentContext == null) return;
final appLocalizations = AppLocalizations.of(currentContext!);
String message = failure.cancelToken?.isCancelled == true
? appLocalizations.downloadAttachmentHasBeenCancelled
: appLocalizations.attachment_download_failed;
appToast.showToastErrorMessage(currentOverlayContext!, message);
}
void _downloadAttachmentForWebFailureAction(DownloadAttachmentForWebFailure failure) {
if (failure.taskId != null) {
deleteDownloadTask(failure.taskId!);
}
if (failure.attachment != null) {
_pushDownloadUIAction(
UpdateAttachmentsViewStateAction(failure.attachment?.blobId, failure),
);
}
if (currentOverlayContext == null || currentContext == null) return;
final appLocalizations = AppLocalizations.of(currentContext!);
String message = appLocalizations.attachment_download_failed;
if (failure.attachment is EMLAttachment) {
message = appLocalizations.downloadMessageAsEMLFailed;
} else if (failure.cancelToken?.isCancelled == true) {
message = appLocalizations.downloadAttachmentHasBeenCancelled;
}
appToast.showToastErrorMessage(currentOverlayContext!, message);
}
@override
void handleSuccessViewState(Success success) {
if (success is DownloadAttachmentForWebSuccess) {
_handleDownloadAttachmentForWebSuccess(success);
} else if (success is StartDownloadAttachmentForWeb) {
_pushDownloadUIAction(UpdateAttachmentsViewStateAction(
success.attachment.blobId,
success,
));
} else if (success is DownloadingAttachmentForWeb) {
_pushDownloadUIAction(UpdateAttachmentsViewStateAction(
success.attachment.blobId,
success,
));
} else if (success is DownloadAllAttachmentsForWebSuccess) {
deleteDownloadTask(success.taskId);
} else {
super.handleSuccessViewState(success);
}
}
@override
void handleFailureViewState(Failure failure) {
if (failure is DownloadAllAttachmentsForWebFailure) {
_downloadAllAttachmentsForWebFailure(failure);
} else if (failure is DownloadAttachmentForWebFailure) {
_downloadAttachmentForWebFailureAction(failure);
} else {
super.handleFailureViewState(failure);
}
}
@override
void onClose() {
_downloadProgressStateSubscription?.cancel();
_downloadProgressStateSubscription = null;
_downloadProgressStateController.close();
super.onClose();
}
}
@@ -111,6 +111,7 @@ import 'package:tmail_ui_user/features/mailbox_dashboard/domain/usecases/remove_
import 'package:tmail_ui_user/features/mailbox_dashboard/domain/usecases/remove_email_drafts_interactor.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/domain/usecases/store_email_sort_order_interactor.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/action/dashboard_action.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/action/download_ui_action.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/controller/app_grid_dashboard_controller.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/controller/download/download_controller.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/controller/search_controller.dart' as search;
@@ -120,6 +121,7 @@ import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/extensions
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/extensions/handle_action_type_for_email_selection.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/extensions/handle_clear_mailbox_extension.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/extensions/handle_create_new_rule_filter.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/extensions/handle_download_extension.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/extensions/handle_preferences_setting_extension.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/extensions/handle_reactive_obx_variable_extension.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/extensions/handle_save_email_as_draft_extension.dart';
@@ -313,6 +315,7 @@ class MailboxDashBoardController extends ReloadableController
PaywallController? paywallController;
Worker? advancedSearchVisibleWorker;
Worker? searchInputFocusWorker;
Worker? _downloadUIActionWorker;
final StreamController<Either<Failure, Success>> _progressStateController =
StreamController<Either<Failure, Success>>.broadcast();
@@ -748,12 +751,26 @@ class MailboxDashBoardController extends ReloadableController
.listen(_handleRefreshActionWhenBackToApp);
_registerLocalNotificationStreamListener();
_registerDownloadUIActionListener();
}
void _registerLocalNotificationStreamListener() {
_notificationManager.localNotificationStream.listen(_handleClickLocalNotificationOnForeground);
}
void _registerDownloadUIActionListener() {
_downloadUIActionWorker = ever(
downloadController.downloadUIAction,
(action) {
if (action is DownloadAttachmentsQuicklyAction) {
downloadAttachmentForWeb(attachment: action.attachment);
downloadController.clearDownloadUIAction();
}
},
);
}
Future<void> _handleClickNotificationOnAndroidInTerminated() async {
_notificationManager.activatedNotificationClickedOnTerminate = true;
final notificationResponse = await _notificationManager.getCurrentNotificationResponse();
@@ -3325,6 +3342,8 @@ class MailboxDashBoardController extends ReloadableController
twakeAppManager.setHasComposer(false);
paywallController?.onClose();
paywallController = null;
_downloadUIActionWorker?.dispose();
_downloadUIActionWorker = null;
super.onClose();
}
}