Files
Wino-Mail/Wino.Core.ViewModels/SettingOptionsPageViewModel.cs
T

601 lines
22 KiB
C#
Raw Normal View History

2026-03-14 14:14:58 +01:00
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
2026-03-06 04:04:14 +01:00
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
2024-04-18 01:44:37 +02:00
using CommunityToolkit.Mvvm.Messaging;
using Wino.Core.Domain;
2026-03-14 21:03:52 +01:00
using Wino.Core.Domain.Entities.Shared;
2024-04-18 01:44:37 +02:00
using Wino.Core.Domain.Enums;
2026-03-06 04:04:14 +01:00
using Wino.Core.Domain.Interfaces;
using Wino.Core.Domain.Models.Navigation;
2026-03-14 21:03:52 +01:00
using Wino.Core.Domain.Models.Personalization;
2026-03-12 19:04:47 +01:00
using Wino.Core.Domain.Models.Settings;
2026-03-14 21:03:52 +01:00
using Wino.Core.Domain.Models.Translations;
2026-03-14 14:14:58 +01:00
using Wino.Core.Extensions;
2026-03-14 21:03:52 +01:00
using Wino.Core.ViewModels.Data;
2026-03-18 09:00:26 +01:00
using Wino.Mail.Api.Contracts.Ai;
2026-03-14 21:03:52 +01:00
using Wino.Mail.ViewModels.Data;
using Wino.Messaging.Client.Navigation;
2026-03-18 09:00:26 +01:00
using Wino.Messaging.UI;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
namespace Wino.Core.ViewModels;
2026-03-18 09:00:26 +01:00
public partial class SettingOptionsPageViewModel : CoreBaseViewModel,
IRecipient<WinoAccountSignedInMessage>,
IRecipient<WinoAccountSignedOutMessage>
2024-04-18 01:44:37 +02:00
{
2026-03-18 09:00:26 +01:00
private const string BuyAiPackUrl = "https://example.com/wino-ai-pack";
2026-03-06 04:04:14 +01:00
private readonly INativeAppService _nativeAppService;
private readonly IAccountService _accountService;
2026-03-14 14:14:58 +01:00
private readonly IMimeStorageService _mimeStorageService;
2026-03-09 00:28:10 +01:00
private readonly IStoreRatingService _storeRatingService;
2026-03-14 21:03:52 +01:00
private readonly ITranslationService _translationService;
private readonly INewThemeService _newThemeService;
private readonly IPreferencesService _preferencesService;
private readonly IProviderService _providerService;
2026-03-18 09:00:26 +01:00
private readonly IWinoAccountProfileService _profileService;
private readonly IMailDialogService _dialogService;
2026-03-14 21:03:52 +01:00
private bool _isInitializingSettings;
private bool _isAppearanceSelectionPaused;
2026-03-06 04:04:14 +01:00
2026-03-09 00:28:10 +01:00
public string GitHubUrl => AppUrls.GitHub;
2026-03-06 12:31:37 +01:00
public string PaypalUrl => AppUrls.Paypal;
2026-03-14 14:14:58 +01:00
public string WebsiteUrl => AppUrls.Website;
public string PrivacyPolicyUrl => AppUrls.PrivacyPolicy;
public ObservableCollection<SettingsNavigationItemInfo> SearchSuggestions { get; } = [];
2026-03-14 21:03:52 +01:00
public ObservableCollection<IAccountProviderDetailViewModel> Accounts { get; } = [];
public ObservableCollection<AppColorViewModel> Colors { get; } = [];
public List<ElementThemeContainer> ElementThemes { get; } =
[
new(ApplicationElementTheme.Light, Translator.ElementTheme_Light),
new(ApplicationElementTheme.Dark, Translator.ElementTheme_Dark),
new(ApplicationElementTheme.Default, Translator.ElementTheme_Default),
];
public bool HasAccounts => Accounts.Count > 0;
2026-03-06 12:31:37 +01:00
2026-03-06 04:04:14 +01:00
[ObservableProperty]
public partial string VersionText { get; set; } = string.Empty;
[ObservableProperty]
public partial string AccountSummaryText { get; set; } = string.Empty;
[ObservableProperty]
public partial int AccountCount { get; set; }
2026-03-14 14:14:58 +01:00
[ObservableProperty]
public partial string StorageSummaryText { get; set; } = string.Empty;
[ObservableProperty]
public partial string SearchQuery { get; set; } = string.Empty;
2026-03-14 21:03:52 +01:00
[ObservableProperty]
public partial List<AppLanguageModel> AvailableLanguages { get; set; } = [];
[ObservableProperty]
public partial AppLanguageModel SelectedLanguage { get; set; }
[ObservableProperty]
public partial ElementThemeContainer SelectedElementTheme { get; set; }
[ObservableProperty]
public partial AppColorViewModel SelectedAppColor { get; set; }
[ObservableProperty]
public partial bool UseAccentColor { get; set; }
2026-03-18 09:00:26 +01:00
// Wino Account hero card properties
[ObservableProperty]
public partial bool IsWinoAccountBusy { get; set; }
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsWinoAccountSignedOut))]
[NotifyPropertyChangedFor(nameof(CanShowBuyAiPack))]
public partial bool IsWinoAccountSignedIn { get; set; }
[ObservableProperty]
public partial string WinoAccountEmail { get; set; } = string.Empty;
[ObservableProperty]
public partial string WinoAccountStatusText { get; set; } = string.Empty;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanShowBuyAiPack))]
public partial bool HasAiPack { get; set; }
[ObservableProperty]
public partial string AiPackStateText { get; set; } = Translator.WinoAccount_Management_AiPackInactive;
[ObservableProperty]
public partial string AiUsageSummary { get; set; } = string.Empty;
[ObservableProperty]
public partial string AiBillingPeriodSummary { get; set; } = string.Empty;
[ObservableProperty]
public partial double AiUsagePercent { get; set; }
public bool IsWinoAccountSignedOut => !IsWinoAccountSignedIn;
public bool CanShowAiUsage => HasAiPack;
public bool CanShowBuyAiPack => IsWinoAccountSignedIn && !HasAiPack;
2026-03-09 00:28:10 +01:00
public SettingOptionsPageViewModel(INativeAppService nativeAppService,
2026-03-14 21:03:52 +01:00
IAccountService accountService,
IMimeStorageService mimeStorageService,
IStoreRatingService storeRatingService,
ITranslationService translationService,
INewThemeService newThemeService,
IPreferencesService preferencesService,
2026-03-18 09:00:26 +01:00
IProviderService providerService,
IWinoAccountProfileService profileService,
IMailDialogService dialogService)
2026-03-06 04:04:14 +01:00
{
_nativeAppService = nativeAppService;
_accountService = accountService;
2026-03-14 14:14:58 +01:00
_mimeStorageService = mimeStorageService;
2026-03-09 00:28:10 +01:00
_storeRatingService = storeRatingService;
2026-03-14 21:03:52 +01:00
_translationService = translationService;
_newThemeService = newThemeService;
_preferencesService = preferencesService;
_providerService = providerService;
2026-03-18 09:00:26 +01:00
_profileService = profileService;
_dialogService = dialogService;
2026-03-06 04:04:14 +01:00
}
public override void OnNavigatedTo(NavigationMode mode, object parameters)
{
base.OnNavigatedTo(mode, parameters);
VersionText = string.Format("{0}{1}", Translator.SettingsAboutVersion, _nativeAppService.GetFullAppVersion());
2026-03-14 14:14:58 +01:00
SearchQuery = string.Empty;
SearchSuggestions.Clear();
StorageSummaryText = Translator.SettingsHome_StorageLoading;
2026-03-14 21:03:52 +01:00
InitializeQuickSettings();
2026-03-14 14:14:58 +01:00
_ = LoadDashboardAsync();
2026-03-18 09:00:26 +01:00
_ = LoadWinoAccountAsync();
2026-03-14 14:14:58 +01:00
}
public void UpdateSearchSuggestions(string query)
{
SearchQuery = query;
SearchSuggestions.Clear();
foreach (var result in SettingsNavigationInfoProvider.Search(query, AccountSummaryText).Take(6))
{
SearchSuggestions.Add(result);
}
}
public SettingsNavigationItemInfo GetBestSearchSuggestion(string query)
=> SettingsNavigationInfoProvider.Search(query, AccountSummaryText).FirstOrDefault();
public void NavigateToSetting(SettingsNavigationItemInfo item)
{
if (item?.PageType is WinoPage pageType)
{
NavigateSubDetail(pageType);
}
2026-03-06 04:04:14 +01:00
}
2026-03-14 21:03:52 +01:00
public void NavigateToAccount(IAccountProviderDetailViewModel account)
{
if (account == null)
{
return;
}
Messenger.Send(new BreadcrumbNavigationRequested(Translator.SettingsManageAccountSettings_Title, WinoPage.ManageAccountsPage));
switch (account)
{
case AccountProviderDetailViewModel accountDetails:
Messenger.Send(new BreadcrumbNavigationRequested(accountDetails.Account.Name, WinoPage.AccountDetailsPage, accountDetails.Account.Id));
break;
case MergedAccountProviderDetailViewModel mergedAccount:
Messenger.Send(new BreadcrumbNavigationRequested(mergedAccount.MergedInbox.Name, WinoPage.MergedAccountDetailsPage, mergedAccount));
break;
}
}
public void NavigateToAddAccount()
{
Messenger.Send(new BreadcrumbNavigationRequested(Translator.SettingsManageAccountSettings_Title, WinoPage.ManageAccountsPage));
Messenger.Send(new BreadcrumbNavigationRequested(Translator.WelcomeWizard_Step2Title, WinoPage.ProviderSelectionPage));
}
2026-03-14 14:14:58 +01:00
private async Task LoadDashboardAsync()
2026-03-06 04:04:14 +01:00
{
2026-03-14 21:03:52 +01:00
var accounts = (await _accountService.GetAccountsAsync().ConfigureAwait(false) ?? []).ToList();
2026-03-14 14:14:58 +01:00
var count = accounts.Count;
Dictionary<Guid, long> storageSizeMap = count == 0
? []
: await _mimeStorageService.GetAccountsMimeStorageSizesAsync(accounts.Select(account => account.Id)).ConfigureAwait(false);
var totalStorageBytes = storageSizeMap.Values.Sum();
2026-03-14 21:03:52 +01:00
var groupedAccountItems = CreateAccountItems(accounts);
2026-03-06 04:04:14 +01:00
await ExecuteUIThread(() =>
{
AccountCount = count;
AccountSummaryText = string.Format(Translator.SettingsOptions_AccountsSummary, count);
2026-03-14 21:03:52 +01:00
Accounts.Clear();
foreach (var account in groupedAccountItems)
{
Accounts.Add(account);
}
OnPropertyChanged(nameof(HasAccounts));
2026-03-14 14:14:58 +01:00
StorageSummaryText = totalStorageBytes == 0
? Translator.SettingsHome_StorageEmptySummary
: string.Format(Translator.SettingsStorage_TotalUsage, totalStorageBytes.GetBytesReadable());
if (!string.IsNullOrWhiteSpace(SearchQuery))
{
UpdateSearchSuggestions(SearchQuery);
}
2026-03-06 04:04:14 +01:00
});
}
2026-03-14 21:03:52 +01:00
private void InitializeQuickSettings()
{
_isInitializingSettings = true;
InitializeColors();
InitializeLanguageOptions();
InitializeAppearanceOptions();
_isInitializingSettings = false;
}
private void InitializeLanguageOptions()
{
AvailableLanguages = _translationService.GetAvailableLanguages();
SelectedLanguage = AvailableLanguages.FirstOrDefault(language => language.Language == _preferencesService.CurrentLanguage)
?? AvailableLanguages.FirstOrDefault();
}
private void InitializeColors()
{
Colors.Clear();
foreach (var color in _newThemeService.GetAvailableAccountColors().Distinct(StringComparer.OrdinalIgnoreCase))
{
Colors.Add(new AppColorViewModel(color));
}
var systemAccentColor = _newThemeService.GetSystemAccentColorHex();
if (Colors.All(color => !string.Equals(color.Hex, systemAccentColor, StringComparison.OrdinalIgnoreCase)))
{
Colors.Add(new AppColorViewModel(systemAccentColor, true));
}
else
{
var matchingAccentColor = Colors.First(color => string.Equals(color.Hex, systemAccentColor, StringComparison.OrdinalIgnoreCase));
Colors.Remove(matchingAccentColor);
Colors.Add(new AppColorViewModel(systemAccentColor, true));
}
}
private void InitializeAppearanceOptions()
{
_isAppearanceSelectionPaused = true;
var currentAccentColor = _newThemeService.AccentColor;
if (!string.IsNullOrWhiteSpace(currentAccentColor) &&
Colors.All(color => !string.Equals(color.Hex, currentAccentColor, StringComparison.OrdinalIgnoreCase)))
{
Colors.Insert(0, new AppColorViewModel(currentAccentColor));
}
SelectedElementTheme = ElementThemes.FirstOrDefault(theme => theme.NativeTheme == _newThemeService.RootTheme)
?? ElementThemes.LastOrDefault();
if (string.IsNullOrWhiteSpace(currentAccentColor))
{
SelectedAppColor = Colors.LastOrDefault(color => color.IsAccentColor) ?? Colors.LastOrDefault();
UseAccentColor = true;
}
else
{
SelectedAppColor = Colors.FirstOrDefault(color => string.Equals(color.Hex, currentAccentColor, StringComparison.OrdinalIgnoreCase))
?? Colors.FirstOrDefault();
UseAccentColor = SelectedAppColor?.IsAccentColor == true;
}
_isAppearanceSelectionPaused = false;
}
private List<IAccountProviderDetailViewModel> CreateAccountItems(List<MailAccount> accounts)
{
var groupedAccounts = accounts
.OrderBy(account => account.MergedInboxId == null ? 1 : 0)
.ThenBy(account => account.Order)
.ThenBy(account => account.Name)
.GroupBy(account => account.MergedInboxId);
var accountItems = new List<IAccountProviderDetailViewModel>();
foreach (var accountGroup in groupedAccounts)
{
if (accountGroup.Key == null)
{
accountItems.AddRange(accountGroup.Select(CreateAccountProviderDetails));
continue;
}
var mergedInbox = accountGroup.First().MergedInbox;
var holdingAccounts = accountGroup
.Select(CreateAccountProviderDetails)
.ToList();
var mergedAccount = new MergedAccountProviderDetailViewModel(mergedInbox, holdingAccounts)
{
ProviderDetail = holdingAccounts.FirstOrDefault()?.ProviderDetail
};
accountItems.Add(mergedAccount);
}
return accountItems;
}
private AccountProviderDetailViewModel CreateAccountProviderDetails(MailAccount account)
{
var provider = _providerService.GetProviderDetail(account.ProviderType);
return new AccountProviderDetailViewModel(provider, account);
}
partial void OnSelectedLanguageChanged(AppLanguageModel value)
{
if (_isInitializingSettings || value == null)
{
return;
}
_ = ApplyLanguageAsync(value);
}
partial void OnSelectedElementThemeChanged(ElementThemeContainer value)
{
if (_isInitializingSettings || value == null)
{
return;
}
_newThemeService.RootTheme = value.NativeTheme;
}
partial void OnSelectedAppColorChanged(AppColorViewModel value)
{
if (_isInitializingSettings || _isAppearanceSelectionPaused || value == null)
{
return;
}
_isAppearanceSelectionPaused = true;
UseAccentColor = value.IsAccentColor;
_isAppearanceSelectionPaused = false;
_newThemeService.AccentColor = value.Hex;
}
partial void OnUseAccentColorChanged(bool value)
{
if (_isInitializingSettings || _isAppearanceSelectionPaused || Colors.Count == 0)
{
return;
}
var accentColor = Colors.LastOrDefault(color => color.IsAccentColor);
var fallbackColor = Colors.FirstOrDefault(color => !color.IsAccentColor) ?? Colors.FirstOrDefault();
var targetColor = value ? accentColor : SelectedAppColor?.IsAccentColor == true ? fallbackColor : SelectedAppColor;
if (targetColor == null || ReferenceEquals(targetColor, SelectedAppColor))
{
return;
}
_isAppearanceSelectionPaused = true;
SelectedAppColor = targetColor;
_isAppearanceSelectionPaused = false;
_newThemeService.AccentColor = targetColor.Hex;
}
private async Task ApplyLanguageAsync(AppLanguageModel language)
{
await _translationService.InitializeLanguageAsync(language.Language);
}
2026-03-18 09:00:26 +01:00
// Wino Account message recipients
protected override void RegisterRecipients()
{
base.RegisterRecipients();
Messenger.Register<WinoAccountSignedInMessage>(this);
Messenger.Register<WinoAccountSignedOutMessage>(this);
}
protected override void UnregisterRecipients()
{
base.UnregisterRecipients();
Messenger.Unregister<WinoAccountSignedInMessage>(this);
Messenger.Unregister<WinoAccountSignedOutMessage>(this);
}
public void Receive(WinoAccountSignedInMessage message)
=> _ = LoadWinoAccountAsync();
public void Receive(WinoAccountSignedOutMessage message)
=> _ = ResetWinoAccountStateAsync();
// Wino Account hero card commands and helpers
[RelayCommand]
private async Task WinoAccountRegisterAsync()
{
var account = await _dialogService.ShowWinoAccountRegistrationDialogAsync();
if (account == null) return;
_dialogService.InfoBarMessage(Translator.GeneralTitle_Info,
string.Format(Translator.WinoAccount_RegisterSuccessMessage, account.Email),
InfoBarMessageType.Success);
await LoadWinoAccountAsync();
}
[RelayCommand]
private async Task WinoAccountSignInAsync()
{
var account = await _dialogService.ShowWinoAccountLoginDialogAsync();
if (account == null) return;
_dialogService.InfoBarMessage(Translator.GeneralTitle_Info,
string.Format(Translator.WinoAccount_LoginSuccessMessage, account.Email),
InfoBarMessageType.Success);
await LoadWinoAccountAsync();
}
[RelayCommand]
private async Task WinoAccountSignOutAsync()
{
var account = await _profileService.GetActiveAccountAsync().ConfigureAwait(false);
if (account == null) return;
await _profileService.SignOutAsync().ConfigureAwait(false);
_dialogService.InfoBarMessage(Translator.GeneralTitle_Info,
string.Format(Translator.WinoAccount_SignOut_SuccessMessage, account.Email),
InfoBarMessageType.Success);
await ResetWinoAccountStateAsync();
}
[RelayCommand]
private async Task OpenBuyAiPackPageAsync() => await _nativeAppService.LaunchUriAsync(new Uri(BuyAiPackUrl));
[RelayCommand]
private void NavigateToWinoAccountManagement()
=> NavigateSubDetail(WinoPage.WinoAccountManagementPage);
private async Task LoadWinoAccountAsync()
{
await ExecuteUIThread(() => IsWinoAccountBusy = true);
try
{
2026-03-18 17:43:56 +01:00
var account = await _profileService.GetAuthenticatedAccountAsync().ConfigureAwait(false);
2026-03-18 09:00:26 +01:00
if (account == null)
{
await ResetWinoAccountStateAsync();
return;
}
2026-03-18 17:43:56 +01:00
var currentUserResponse = await _profileService.GetCurrentUserAsync().ConfigureAwait(false);
var aiStatusResponse = await _profileService.GetAiStatusAsync().ConfigureAwait(false);
2026-03-18 09:00:26 +01:00
var resolvedEmail = currentUserResponse.IsSuccess && currentUserResponse.Result != null
? currentUserResponse.Result.Email
: account.Email;
var resolvedStatus = currentUserResponse.IsSuccess && currentUserResponse.Result != null
? currentUserResponse.Result.AccountStatus
: account.AccountStatus;
await ExecuteUIThread(() =>
{
IsWinoAccountSignedIn = true;
WinoAccountEmail = resolvedEmail;
WinoAccountStatusText = string.Format(Translator.WinoAccount_Management_StatusLabel, resolvedStatus);
});
UpdateAiPackState(aiStatusResponse.IsSuccess ? aiStatusResponse.Result : null);
}
catch
{
await ResetWinoAccountStateAsync();
}
finally
{
await ExecuteUIThread(() => IsWinoAccountBusy = false);
}
}
private async Task ResetWinoAccountStateAsync()
{
await ExecuteUIThread(() =>
{
IsWinoAccountSignedIn = false;
WinoAccountEmail = string.Empty;
WinoAccountStatusText = string.Empty;
HasAiPack = false;
AiPackStateText = Translator.WinoAccount_Management_AiPackInactive;
AiUsageSummary = string.Empty;
AiBillingPeriodSummary = string.Empty;
AiUsagePercent = 0;
});
}
private void UpdateAiPackState(AiStatusResultDto aiStatus)
{
var hasAiPack = aiStatus?.HasAiPack == true;
var usageText = Translator.WinoAccount_Management_AiPackUnknownUsage;
var billingText = string.Empty;
var usagePercent = 0d;
if (hasAiPack && aiStatus?.Used is int used && aiStatus.MonthlyLimit is int limit && aiStatus.Remaining is int remaining)
{
usageText = string.Format(Translator.WinoAccount_Management_AiPackUsage, used, limit, remaining);
usagePercent = limit > 0 ? (double)used / limit * 100 : 0;
}
if (hasAiPack && aiStatus?.CurrentPeriodStartUtc is DateTimeOffset periodStart && aiStatus.CurrentPeriodEndUtc is DateTimeOffset periodEnd)
{
billingText = string.Format(Translator.WinoAccount_Management_AiPackBillingPeriod, periodStart.LocalDateTime, periodEnd.LocalDateTime);
}
_ = ExecuteUIThread(() =>
{
HasAiPack = hasAiPack;
AiPackStateText = hasAiPack
? Translator.WinoAccount_Management_AiPackActive
: Translator.WinoAccount_Management_AiPackInactive;
AiUsageSummary = hasAiPack ? usageText : string.Empty;
AiBillingPeriodSummary = hasAiPack ? billingText : string.Empty;
AiUsagePercent = usagePercent;
});
}
2025-02-16 11:54:23 +01:00
[RelayCommand]
public void NavigateSubDetail(object type)
{
if (type is WinoPage pageType)
2024-04-18 01:44:37 +02:00
{
2026-03-12 19:04:47 +01:00
var pageInfo = SettingsNavigationInfoProvider.GetInfo(pageType, AccountSummaryText);
Messenger.Send(new BreadcrumbNavigationRequested(pageInfo.Title, pageType));
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
}
2026-03-09 00:28:10 +01:00
[RelayCommand]
private async Task NavigateExternalAsync(object target)
{
if (target is not string stringTarget || string.IsNullOrWhiteSpace(stringTarget))
return;
if (stringTarget == "Store")
{
await _storeRatingService.LaunchStorePageForReviewAsync();
return;
}
await _nativeAppService.LaunchUriAsync(new Uri(stringTarget));
}
2024-04-18 01:44:37 +02:00
}