Files
Wino-Mail/Wino.Mail.ViewModels/ComposePageViewModel.cs

575 lines
20 KiB
C#
Raw Normal View History

2024-04-18 01:44:37 +02:00
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using MimeKit;
using Wino.Core.Domain;
using Wino.Core.Domain.Entities.Mail;
using Wino.Core.Domain.Entities.Shared;
2024-04-18 01:44:37 +02:00
using Wino.Core.Domain.Enums;
using Wino.Core.Domain.Exceptions;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Domain.Models.MailItem;
using Wino.Core.Domain.Models.Navigation;
using Wino.Core.Extensions;
using Wino.Core.Services;
using Wino.Mail.ViewModels.Data;
Full trust Wino Server implementation. (#295) * Separation of messages. Introducing Wino.Messages library. * Wino.Server and Wino.Packaging projects. Enabling full trust for UWP and app service connection manager basics. * Remove debug code. * Enable generating assembly info to deal with unsupported os platform warnings. * Fix server-client connection. * UIMessage communication. Single instancing for server and re-connection mechanism on suspension. * Removed IWinoSynchronizerFactory from UWP project. * Removal of background task service from core. * Delegating changes to UI and triggering new background synchronization. * Fix build error. * Moved core lib messages to Messaging project. * Better client-server communication. Handling of requests in the server. New synchronizer factory in the server. * WAM broker and MSAL token caching for OutlookAuthenticator. Handling account creation for Outlook. * WinoServerResponse basics. * Delegating protocol activation for Gmail authenticator. * Adding margin to searchbox to match action bar width. * Move libraries into lib folder. * Storing base64 encoded mime on draft creation instead of MimeMessage object. Fixes serialization/deserialization issue with S.T.Json * Scrollbar adjustments * WınoExpander for thread expander layout ıssue. * Handling synchronizer state changes. * Double init on background activation. * FIxing packaging issues and new Wino Mail launcher protocol for activation from full thrust process. * Remove debug deserialization. * Remove debug code. * Making sure the server connection is established when the app is launched. * Thrust -> Trust string replacement... * Rename package to Wino Mail * Enable translated values in the server. * Fixed an issue where toast activation can't find the clicked mail after the folder is initialized. * Revert debug code. * Change server background sync to every 3 minute and Inbox only synchronization. * Revert google auth changes. * App preferences page. * Changing tray icon visibility on preference change. * Start the server with invisible tray icon if set to invisible. * Reconnect button on the title bar. * Handling of toast actions. * Enable x86 build for server during packaging. * Get rid of old background tasks and v180 migration. * Terminate client when Exit clicked in server. * Introducing SynchronizationSource to prevent notifying UI after server tick synchronization. * Remove confirmAppClose restricted capability and unused debug code in manifest. * Closing the reconnect info popup when reconnect is clicked. * Custom RetryHandler for OutlookSynchronizer and separating client/server logs. * Running server on Windows startup. * Fix startup exe. * Fix for expander list view item paddings. * Force full sync on app launch instead of Inbox. * Fix draft creation. * Fix an issue with custom folder sync logic. * Reporting back account sync progress from server. * Fix sending drafts and missing notifications for imap. * Changing imap folder sync requirements. * Retain file count is set to 3. * Disabled swipe gestures temporarily due to native crash with SwipeControl * Save all attachments implementation. * Localization for save all attachments button. * Fix logging dates for logs. * Fixing ARM64 build. * Add ARM64 build config to packaging project. * Comment out OutOfProcPDB for ARM64. * Hnadling GONE response for Outlook folder synchronization.
2024-08-05 00:36:26 +02:00
using Wino.Messaging.Client.Mails;
using Wino.Messaging.Server;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
namespace Wino.Mail.ViewModels;
public partial class ComposePageViewModel : MailBaseViewModel
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
public Func<Task<string>> GetHTMLBodyFunction;
// When we send the message or discard it, we need to block the mime update
// Update is triggered when we leave the page.
private bool isUpdatingMimeBlocked = false;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private bool canSendMail => ComposingAccount != null && !IsLocalDraft && CurrentMimeMessage != null;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[NotifyCanExecuteChangedFor(nameof(DiscardCommand))]
[NotifyCanExecuteChangedFor(nameof(SendCommand))]
[ObservableProperty]
private MimeMessage currentMimeMessage = null;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private readonly BodyBuilder bodyBuilder = new BodyBuilder();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public bool IsLocalDraft => CurrentMailDraftItem?.MailCopy?.IsLocalDraft ?? true;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
#region Properties
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsLocalDraft))]
[NotifyCanExecuteChangedFor(nameof(DiscardCommand))]
[NotifyCanExecuteChangedFor(nameof(SendCommand))]
private MailItemViewModel currentMailDraftItem;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[ObservableProperty]
private bool isImportanceSelected;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[ObservableProperty]
private MessageImportance selectedMessageImportance;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[ObservableProperty]
private bool isCCBCCVisible;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[ObservableProperty]
private string subject;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(DiscardCommand))]
[NotifyCanExecuteChangedFor(nameof(SendCommand))]
private MailAccount composingAccount;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[ObservableProperty]
private List<MailAccountAlias> availableAliases;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[ObservableProperty]
private MailAccountAlias selectedAlias;
2025-02-16 11:54:23 +01:00
[ObservableProperty]
private bool isDraggingOverComposerGrid;
2025-02-16 11:54:23 +01:00
[ObservableProperty]
private bool isDraggingOverFilesDropZone;
2024-05-22 02:10:14 +02:00
2025-02-16 11:54:23 +01:00
[ObservableProperty]
private bool isDraggingOverImagesDropZone;
2025-02-16 11:54:23 +01:00
public ObservableCollection<MailAttachmentViewModel> IncludedAttachments { get; set; } = [];
public ObservableCollection<MailAccount> Accounts { get; set; } = [];
public ObservableCollection<AccountContact> ToItems { get; set; } = [];
public ObservableCollection<AccountContact> CCItems { get; set; } = [];
public ObservableCollection<AccountContact> BCCItems { get; set; } = [];
2024-05-22 02:10:14 +02:00
2025-02-16 11:54:23 +01:00
#endregion
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public INativeAppService NativeAppService { get; }
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private readonly IMailDialogService _dialogService;
private readonly IMailService _mailService;
private readonly IMimeFileService _mimeFileService;
private readonly IFileService _fileService;
private readonly IFolderService _folderService;
private readonly IAccountService _accountService;
private readonly IWinoRequestDelegator _worker;
public readonly IFontService FontService;
public readonly IPreferencesService PreferencesService;
private readonly IWinoServerConnectionManager _winoServerConnectionManager;
public readonly IContactService ContactService;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public ComposePageViewModel(IMailDialogService dialogService,
IMailService mailService,
IMimeFileService mimeFileService,
IFileService fileService,
INativeAppService nativeAppService,
IFolderService folderService,
IAccountService accountService,
IWinoRequestDelegator worker,
IContactService contactService,
IFontService fontService,
IPreferencesService preferencesService,
IWinoServerConnectionManager winoServerConnectionManager)
{
NativeAppService = nativeAppService;
ContactService = contactService;
FontService = fontService;
PreferencesService = preferencesService;
_folderService = folderService;
_dialogService = dialogService;
_mailService = mailService;
_mimeFileService = mimeFileService;
_fileService = fileService;
_accountService = accountService;
_worker = worker;
_winoServerConnectionManager = winoServerConnectionManager;
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[RelayCommand]
private async Task OpenAttachmentAsync(MailAttachmentViewModel attachmentViewModel)
{
if (string.IsNullOrEmpty(attachmentViewModel.FilePath)) return;
try
{
2025-02-16 11:54:23 +01:00
await NativeAppService.LaunchFileAsync(attachmentViewModel.FilePath);
}
2025-02-16 11:54:23 +01:00
catch
2025-02-16 11:35:43 +01:00
{
2025-02-16 11:54:23 +01:00
_dialogService.InfoBarMessage(Translator.Info_FailedToOpenFileTitle, Translator.Info_FailedToOpenFileMessage, InfoBarMessageType.Error);
}
2025-02-16 11:54:23 +01:00
}
2025-02-16 11:54:23 +01:00
[RelayCommand]
private async Task SaveAttachmentAsync(MailAttachmentViewModel attachmentViewModel)
{
if (attachmentViewModel.Content == null) return;
var pickedFilePath = await _dialogService.PickFilePathAsync(attachmentViewModel.FileName);
if (string.IsNullOrWhiteSpace(pickedFilePath)) return;
2025-02-16 11:54:23 +01:00
try
{
await _fileService.CopyFileAsync(attachmentViewModel.FilePath, pickedFilePath);
2025-02-16 11:35:43 +01:00
}
2025-02-16 11:54:23 +01:00
catch
{
2025-02-16 11:54:23 +01:00
_dialogService.InfoBarMessage(Translator.Info_FailedToOpenFileTitle, Translator.Info_FailedToOpenFileMessage, InfoBarMessageType.Error);
}
}
[RelayCommand]
private async Task AttachFilesAsync()
{
var pickedFiles = await _dialogService.PickFilesAsync("*");
2025-02-16 11:54:23 +01:00
if (pickedFiles?.Count == 0) return;
2025-02-16 11:54:23 +01:00
foreach (var file in pickedFiles)
{
var attachmentViewModel = new MailAttachmentViewModel(file);
IncludedAttachments.Add(attachmentViewModel);
}
2025-02-16 11:54:23 +01:00
}
2025-02-16 11:54:23 +01:00
[RelayCommand]
private void RemoveAttachment(MailAttachmentViewModel attachmentViewModel)
=> IncludedAttachments.Remove(attachmentViewModel);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[RelayCommand(CanExecute = nameof(canSendMail))]
private async Task SendAsync()
{
// TODO: More detailed mail validations.
if (!ToItems.Any())
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
await _dialogService.ShowMessageAsync(Translator.DialogMessage_ComposerMissingRecipientMessage,
Translator.DialogMessage_ComposerValidationFailedTitle,
WinoCustomMessageDialogIcon.Warning);
return;
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (string.IsNullOrEmpty(Subject))
{
var isConfirmed = await _dialogService.ShowConfirmationDialogAsync(Translator.DialogMessage_EmptySubjectConfirmationMessage, Translator.DialogMessage_EmptySubjectConfirmation, Translator.Buttons_Yes);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (!isConfirmed) return;
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (SelectedAlias == null)
{
_dialogService.InfoBarMessage(Translator.DialogMessage_AliasNotSelectedTitle, Translator.DialogMessage_AliasNotSelectedMessage, InfoBarMessageType.Error);
return;
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
// Save mime changes before sending.
await UpdateMimeChangesAsync().ConfigureAwait(false);
2025-02-16 11:54:23 +01:00
isUpdatingMimeBlocked = true;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
var assignedAccount = CurrentMailDraftItem.AssignedAccount;
var sentFolder = await _folderService.GetSpecialFolderByAccountIdAsync(assignedAccount.Id, SpecialFolderType.Sent);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
using MemoryStream memoryStream = new();
CurrentMimeMessage.WriteTo(FormatOptions.Default, memoryStream);
byte[] buffer = memoryStream.GetBuffer();
int count = (int)memoryStream.Length;
Full trust Wino Server implementation. (#295) * Separation of messages. Introducing Wino.Messages library. * Wino.Server and Wino.Packaging projects. Enabling full trust for UWP and app service connection manager basics. * Remove debug code. * Enable generating assembly info to deal with unsupported os platform warnings. * Fix server-client connection. * UIMessage communication. Single instancing for server and re-connection mechanism on suspension. * Removed IWinoSynchronizerFactory from UWP project. * Removal of background task service from core. * Delegating changes to UI and triggering new background synchronization. * Fix build error. * Moved core lib messages to Messaging project. * Better client-server communication. Handling of requests in the server. New synchronizer factory in the server. * WAM broker and MSAL token caching for OutlookAuthenticator. Handling account creation for Outlook. * WinoServerResponse basics. * Delegating protocol activation for Gmail authenticator. * Adding margin to searchbox to match action bar width. * Move libraries into lib folder. * Storing base64 encoded mime on draft creation instead of MimeMessage object. Fixes serialization/deserialization issue with S.T.Json * Scrollbar adjustments * WınoExpander for thread expander layout ıssue. * Handling synchronizer state changes. * Double init on background activation. * FIxing packaging issues and new Wino Mail launcher protocol for activation from full thrust process. * Remove debug deserialization. * Remove debug code. * Making sure the server connection is established when the app is launched. * Thrust -> Trust string replacement... * Rename package to Wino Mail * Enable translated values in the server. * Fixed an issue where toast activation can't find the clicked mail after the folder is initialized. * Revert debug code. * Change server background sync to every 3 minute and Inbox only synchronization. * Revert google auth changes. * App preferences page. * Changing tray icon visibility on preference change. * Start the server with invisible tray icon if set to invisible. * Reconnect button on the title bar. * Handling of toast actions. * Enable x86 build for server during packaging. * Get rid of old background tasks and v180 migration. * Terminate client when Exit clicked in server. * Introducing SynchronizationSource to prevent notifying UI after server tick synchronization. * Remove confirmAppClose restricted capability and unused debug code in manifest. * Closing the reconnect info popup when reconnect is clicked. * Custom RetryHandler for OutlookSynchronizer and separating client/server logs. * Running server on Windows startup. * Fix startup exe. * Fix for expander list view item paddings. * Force full sync on app launch instead of Inbox. * Fix draft creation. * Fix an issue with custom folder sync logic. * Reporting back account sync progress from server. * Fix sending drafts and missing notifications for imap. * Changing imap folder sync requirements. * Retain file count is set to 3. * Disabled swipe gestures temporarily due to native crash with SwipeControl * Save all attachments implementation. * Localization for save all attachments button. * Fix logging dates for logs. * Fixing ARM64 build. * Add ARM64 build config to packaging project. * Comment out OutOfProcPDB for ARM64. * Hnadling GONE response for Outlook folder synchronization.
2024-08-05 00:36:26 +02:00
2025-02-16 11:54:23 +01:00
var base64EncodedMessage = Convert.ToBase64String(buffer);
var draftSendPreparationRequest = new SendDraftPreparationRequest(CurrentMailDraftItem.MailCopy,
SelectedAlias,
sentFolder,
CurrentMailDraftItem.AssignedFolder,
CurrentMailDraftItem.AssignedAccount.Preferences,
base64EncodedMessage);
Full trust Wino Server implementation. (#295) * Separation of messages. Introducing Wino.Messages library. * Wino.Server and Wino.Packaging projects. Enabling full trust for UWP and app service connection manager basics. * Remove debug code. * Enable generating assembly info to deal with unsupported os platform warnings. * Fix server-client connection. * UIMessage communication. Single instancing for server and re-connection mechanism on suspension. * Removed IWinoSynchronizerFactory from UWP project. * Removal of background task service from core. * Delegating changes to UI and triggering new background synchronization. * Fix build error. * Moved core lib messages to Messaging project. * Better client-server communication. Handling of requests in the server. New synchronizer factory in the server. * WAM broker and MSAL token caching for OutlookAuthenticator. Handling account creation for Outlook. * WinoServerResponse basics. * Delegating protocol activation for Gmail authenticator. * Adding margin to searchbox to match action bar width. * Move libraries into lib folder. * Storing base64 encoded mime on draft creation instead of MimeMessage object. Fixes serialization/deserialization issue with S.T.Json * Scrollbar adjustments * WınoExpander for thread expander layout ıssue. * Handling synchronizer state changes. * Double init on background activation. * FIxing packaging issues and new Wino Mail launcher protocol for activation from full thrust process. * Remove debug deserialization. * Remove debug code. * Making sure the server connection is established when the app is launched. * Thrust -> Trust string replacement... * Rename package to Wino Mail * Enable translated values in the server. * Fixed an issue where toast activation can't find the clicked mail after the folder is initialized. * Revert debug code. * Change server background sync to every 3 minute and Inbox only synchronization. * Revert google auth changes. * App preferences page. * Changing tray icon visibility on preference change. * Start the server with invisible tray icon if set to invisible. * Reconnect button on the title bar. * Handling of toast actions. * Enable x86 build for server during packaging. * Get rid of old background tasks and v180 migration. * Terminate client when Exit clicked in server. * Introducing SynchronizationSource to prevent notifying UI after server tick synchronization. * Remove confirmAppClose restricted capability and unused debug code in manifest. * Closing the reconnect info popup when reconnect is clicked. * Custom RetryHandler for OutlookSynchronizer and separating client/server logs. * Running server on Windows startup. * Fix startup exe. * Fix for expander list view item paddings. * Force full sync on app launch instead of Inbox. * Fix draft creation. * Fix an issue with custom folder sync logic. * Reporting back account sync progress from server. * Fix sending drafts and missing notifications for imap. * Changing imap folder sync requirements. * Retain file count is set to 3. * Disabled swipe gestures temporarily due to native crash with SwipeControl * Save all attachments implementation. * Localization for save all attachments button. * Fix logging dates for logs. * Fixing ARM64 build. * Add ARM64 build config to packaging project. * Comment out OutOfProcPDB for ARM64. * Hnadling GONE response for Outlook folder synchronization.
2024-08-05 00:36:26 +02:00
2025-02-16 11:54:23 +01:00
await _worker.ExecuteAsync(draftSendPreparationRequest);
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public async Task UpdateMimeChangesAsync()
{
if (isUpdatingMimeBlocked || CurrentMimeMessage == null || ComposingAccount == null || CurrentMailDraftItem == null) return;
2024-08-18 22:45:23 +02:00
2025-02-16 11:54:23 +01:00
// Save recipients.
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
SaveAddressInfo(ToItems, CurrentMimeMessage.To);
SaveAddressInfo(CCItems, CurrentMimeMessage.Cc);
SaveAddressInfo(BCCItems, CurrentMimeMessage.Bcc);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
SaveImportance();
SaveSubject();
SaveFromAddress();
SaveReplyToAddress();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
await SaveAttachmentsAsync();
await SaveBodyAsync();
await UpdateMailCopyAsync();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
// Save mime file.
await _mimeFileService.SaveMimeMessageAsync(CurrentMailDraftItem.MailCopy.FileId, CurrentMimeMessage, ComposingAccount.Id).ConfigureAwait(false);
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private async Task UpdateMailCopyAsync()
{
CurrentMailDraftItem.Subject = CurrentMimeMessage.Subject;
CurrentMailDraftItem.PreviewText = CurrentMimeMessage.TextBody;
CurrentMailDraftItem.FromAddress = SelectedAlias.AliasAddress;
CurrentMailDraftItem.HasAttachments = CurrentMimeMessage.Attachments.Any();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
// Update database.
await _mailService.UpdateMailAsync(CurrentMailDraftItem.MailCopy);
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private async Task SaveAttachmentsAsync()
{
bodyBuilder.Attachments.Clear();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
foreach (var path in IncludedAttachments)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
if (path.Content == null) continue;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
await bodyBuilder.Attachments.AddAsync(path.FileName, new MemoryStream(path.Content));
}
2025-02-16 11:54:23 +01:00
}
2025-02-16 11:35:43 +01:00
2025-02-16 11:54:23 +01:00
private void SaveImportance()
{
CurrentMimeMessage.Importance = IsImportanceSelected ? SelectedMessageImportance : MessageImportance.Normal;
}
private void SaveSubject()
{
if (Subject != null)
{
2025-02-16 11:54:23 +01:00
CurrentMimeMessage.Subject = Subject;
}
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private async Task SaveBodyAsync()
{
if (GetHTMLBodyFunction != null)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
bodyBuilder.SetHtmlBody(await GetHTMLBodyFunction());
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
CurrentMimeMessage.Body = bodyBuilder.ToMessageBody();
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
[RelayCommand(CanExecute = nameof(canSendMail))]
private async Task DiscardAsync()
{
if (ComposingAccount == null)
{
_dialogService.InfoBarMessage(Translator.Info_MessageCorruptedTitle, Translator.Info_MessageCorruptedMessage, InfoBarMessageType.Error);
return;
}
2025-02-16 11:35:43 +01:00
2025-02-16 11:54:23 +01:00
var confirmation = await _dialogService.ShowConfirmationDialogAsync(Translator.DialogMessage_DiscardDraftConfirmationMessage,
Translator.DialogMessage_DiscardDraftConfirmationTitle,
Translator.Buttons_Yes);
if (confirmation)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
isUpdatingMimeBlocked = true;
// Don't send delete request for local drafts. Just delete the record and mime locally.
if (CurrentMailDraftItem.MailCopy.IsLocalDraft)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
await _mailService.DeleteMailAsync(ComposingAccount.Id, CurrentMailDraftItem.Id);
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
else
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
var deletePackage = new MailOperationPreperationRequest(MailOperation.HardDelete, CurrentMailDraftItem.MailCopy, ignoreHardDeleteProtection: true);
await _worker.ExecuteAsync(deletePackage).ConfigureAwait(false);
2024-04-18 01:44:37 +02:00
}
}
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public override void OnNavigatedFrom(NavigationMode mode, object parameters)
{
base.OnNavigatedFrom(mode, parameters);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
/// Do not put any code here.
/// Make sure to use Page's OnNavigatedTo instead.
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public override async void OnNavigatedTo(NavigationMode mode, object parameters)
{
base.OnNavigatedTo(mode, parameters);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (parameters != null && parameters is MailItemViewModel mailItem)
{
CurrentMailDraftItem = mailItem;
2025-02-16 11:54:23 +01:00
await TryPrepareComposeAsync(true);
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private async Task<bool> InitializeComposerAccountAsync()
{
if (CurrentMailDraftItem == null) return false;
2025-02-16 11:54:23 +01:00
if (ComposingAccount != null) return true;
2025-02-16 11:54:23 +01:00
var composingAccount = await _accountService.GetAccountAsync(CurrentMailDraftItem.AssignedAccount.Id).ConfigureAwait(false);
if (composingAccount == null) return false;
2025-02-16 11:54:23 +01:00
var aliases = await _accountService.GetAccountAliasesAsync(composingAccount.Id).ConfigureAwait(false);
2025-02-16 11:54:23 +01:00
if (aliases == null || !aliases.Any()) return false;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
// MailAccountAlias primaryAlias = aliases.Find(a => a.IsPrimary) ?? aliases.First();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
// Auto-select the correct alias from the message itself.
// If can't, fallback to primary alias.
2025-02-16 11:54:23 +01:00
MailAccountAlias primaryAlias = null;
2025-02-16 11:54:23 +01:00
if (!string.IsNullOrEmpty(CurrentMailDraftItem.FromAddress))
{
primaryAlias = aliases.Find(a => a.AliasAddress == CurrentMailDraftItem.FromAddress);
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
primaryAlias ??= await _accountService.GetPrimaryAccountAliasAsync(ComposingAccount.Id).ConfigureAwait(false);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
await ExecuteUIThread(() =>
{
ComposingAccount = composingAccount;
AvailableAliases = aliases;
SelectedAlias = primaryAlias;
});
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
return true;
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private async Task TryPrepareComposeAsync(bool downloadIfNeeded)
{
if (CurrentMailDraftItem == null) return;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
bool isComposerInitialized = await InitializeComposerAccountAsync();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (!isComposerInitialized) return;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
retry:
2025-02-16 11:54:23 +01:00
// Replying existing message.
MimeMessageInformation mimeMessageInformation = null;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
try
{
mimeMessageInformation = await _mimeFileService.GetMimeMessageInformationAsync(CurrentMailDraftItem.MailCopy.FileId, ComposingAccount.Id).ConfigureAwait(false);
}
catch (FileNotFoundException)
{
if (downloadIfNeeded)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
downloadIfNeeded = false;
2025-02-16 11:54:23 +01:00
var package = new DownloadMissingMessageRequested(CurrentMailDraftItem.AssignedAccount.Id, CurrentMailDraftItem.MailCopy);
var downloadResponse = await _winoServerConnectionManager.GetResponseAsync<bool, DownloadMissingMessageRequested>(package);
2025-02-16 11:54:23 +01:00
if (downloadResponse.IsSuccess)
{
goto retry;
2024-04-18 01:44:37 +02:00
}
}
2025-02-16 11:54:23 +01:00
else
_dialogService.InfoBarMessage(Translator.Info_ComposerMissingMIMETitle, Translator.Info_ComposerMissingMIMEMessage, InfoBarMessageType.Error);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
return;
}
catch (IOException)
{
_dialogService.InfoBarMessage(Translator.Busy, Translator.Exception_MailProcessing, InfoBarMessageType.Warning);
}
catch (ComposerMimeNotFoundException)
{
_dialogService.InfoBarMessage(Translator.Info_ComposerMissingMIMETitle, Translator.Info_ComposerMissingMIMEMessage, InfoBarMessageType.Error);
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (mimeMessageInformation == null)
return;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
var replyingMime = mimeMessageInformation.MimeMessage;
var mimeFilePath = mimeMessageInformation.Path;
2024-08-18 22:45:23 +02:00
2025-02-16 11:54:23 +01:00
var renderModel = _mimeFileService.GetMailRenderModel(replyingMime, mimeFilePath);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
await ExecuteUIThread(async () =>
{
// Extract information
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
CurrentMimeMessage = replyingMime;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
ToItems.Clear();
CCItems.Clear();
BCCItems.Clear();
2025-02-16 11:54:23 +01:00
await LoadAddressInfoAsync(replyingMime.To, ToItems);
await LoadAddressInfoAsync(replyingMime.Cc, CCItems);
await LoadAddressInfoAsync(replyingMime.Bcc, BCCItems);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
LoadAttachments();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (replyingMime.Cc.Any() || replyingMime.Bcc.Any())
IsCCBCCVisible = true;
2024-08-18 22:45:23 +02:00
2025-02-16 11:54:23 +01:00
Subject = replyingMime.Subject;
2025-02-16 11:35:43 +01:00
2025-02-16 11:54:23 +01:00
Messenger.Send(new CreateNewComposeMailRequested(renderModel));
});
}
2025-02-16 11:54:23 +01:00
private void LoadAttachments()
{
if (CurrentMimeMessage == null) return;
foreach (var attachment in CurrentMimeMessage.Attachments)
{
if (attachment.IsAttachment && attachment is MimePart attachmentPart)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
IncludedAttachments.Add(new MailAttachmentViewModel(attachmentPart));
2024-04-18 01:44:37 +02:00
}
}
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private async Task LoadAddressInfoAsync(InternetAddressList list, ObservableCollection<AccountContact> collection)
{
foreach (var item in list)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
if (item is MailboxAddress mailboxAddress)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
var foundContact = await ContactService.GetAddressInformationByAddressAsync(mailboxAddress.Address).ConfigureAwait(false)
?? new AccountContact() { Name = mailboxAddress.Name, Address = mailboxAddress.Address };
2025-02-16 11:54:23 +01:00
await ExecuteUIThread(() => { collection.Add(foundContact); });
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
else if (item is GroupAddress groupAddress)
await LoadAddressInfoAsync(groupAddress.Members, collection);
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
}
2025-02-16 11:54:23 +01:00
private void SaveFromAddress()
{
if (SelectedAlias == null) return;
2025-02-16 11:54:23 +01:00
CurrentMimeMessage.From.Clear();
2025-02-16 11:54:23 +01:00
// Try to get the sender name from the alias. If not, fallback to account sender name.
var senderName = SelectedAlias.AliasSenderName ?? ComposingAccount.SenderName;
2025-02-16 11:54:23 +01:00
CurrentMimeMessage.From.Add(new MailboxAddress(senderName, SelectedAlias.AliasAddress));
}
2025-02-16 11:54:23 +01:00
private void SaveReplyToAddress()
{
if (SelectedAlias == null) return;
2025-02-16 11:54:23 +01:00
if (!string.IsNullOrEmpty(SelectedAlias.ReplyToAddress))
{
if (!CurrentMimeMessage.ReplyTo.Any(a => a is MailboxAddress mailboxAddress && mailboxAddress.Address == SelectedAlias.ReplyToAddress))
{
2025-02-16 11:54:23 +01:00
CurrentMimeMessage.ReplyTo.Clear();
CurrentMimeMessage.ReplyTo.Add(new MailboxAddress(SelectedAlias.ReplyToAddress, SelectedAlias.ReplyToAddress));
}
}
2025-02-16 11:54:23 +01:00
}
2025-02-16 11:54:23 +01:00
private void SaveAddressInfo(IEnumerable<AccountContact> addresses, InternetAddressList list)
{
list.Clear();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
foreach (var item in addresses)
list.Add(new MailboxAddress(item.Name, item.Address));
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public async Task<AccountContact> GetAddressInformationAsync(string tokenText, ObservableCollection<AccountContact> collection)
{
// Get model from the service. This will make sure the name is properly included if there is any record.
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
var info = await ContactService.GetAddressInformationByAddressAsync(tokenText)
?? new AccountContact() { Name = tokenText, Address = tokenText };
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
// Don't add if there is already that address in the collection.
if (collection.Any(a => a.Address == info.Address))
return null;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
return info;
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public void NotifyAddressExists()
{
_dialogService.InfoBarMessage(Translator.Info_ContactExistsTitle, Translator.Info_ContactExistsMessage, InfoBarMessageType.Warning);
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public void NotifyInvalidEmail(string address)
{
_dialogService.InfoBarMessage(Translator.Info_InvalidAddressTitle, string.Format(Translator.Info_InvalidAddressMessage, address), InfoBarMessageType.Warning);
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
protected override async void OnMailUpdated(MailCopy updatedMail)
{
base.OnMailUpdated(updatedMail);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (CurrentMailDraftItem == null) return;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (updatedMail.UniqueId == CurrentMailDraftItem.UniqueId)
{
await ExecuteUIThread(() =>
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
CurrentMailDraftItem.MailCopy = updatedMail;
2025-02-16 11:54:23 +01:00
DiscardCommand.NotifyCanExecuteChanged();
SendCommand.NotifyCanExecuteChanged();
});
2024-04-18 01:44:37 +02:00
}
}
}