123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266 |
- using Avalonia.Threading;
- using CommunityToolkit.Mvvm.Input;
- using PixiEditor.Extensions.Common.Localization;
- using PixiEditor.Models.Commands.Attributes.Commands;
- using PixiEditor.OperatingSystem;
- using PixiEditor.PixiAuth;
- using PixiEditor.PixiAuth.Exceptions;
- namespace PixiEditor.ViewModels.SubViewModels;
- internal class UserViewModel : SubViewModel<ViewModelMain>
- {
- private LocalizedString? lastError = null;
- public PixiAuthClient PixiAuthClient { get; }
- public User? User { get; private set; }
- public bool NotLoggedIn => User?.SessionId is null || User.SessionId == Guid.Empty;
- public bool WaitingForActivation => User is { SessionId: not null } && string.IsNullOrEmpty(User.SessionToken);
- public bool IsLoggedIn => User is { SessionId: not null } && !string.IsNullOrEmpty(User.SessionToken);
- public AsyncRelayCommand<string> RequestLoginCommand { get; }
- public AsyncRelayCommand TryValidateSessionCommand { get; }
- public AsyncRelayCommand ResendActivationCommand { get; }
- public AsyncRelayCommand LogoutCommand { get; }
- public LocalizedString? LastError
- {
- get => lastError;
- set => SetProperty(ref lastError, value);
- }
- private bool apiValid = true;
- public DateTime? TimeToEndTimeout { get; private set; } = null;
- public string TimeToEndTimeoutString
- {
- get
- {
- if (TimeToEndTimeout == null)
- {
- return string.Empty;
- }
- TimeSpan timeLeft = TimeToEndTimeout.Value - DateTime.Now;
- return timeLeft.TotalSeconds > 0 ? $"({timeLeft:ss})" : string.Empty;
- }
- }
- public UserViewModel(ViewModelMain owner) : base(owner)
- {
- RequestLoginCommand = new AsyncRelayCommand<string>(RequestLogin);
- TryValidateSessionCommand = new AsyncRelayCommand(TryValidateSession);
- ResendActivationCommand = new AsyncRelayCommand(ResendActivation, CanResendActivation);
- LogoutCommand = new AsyncRelayCommand(Logout);
- string baseUrl = BuildConstants.PixiEditorApiUrl;
- #if DEBUG
- if (baseUrl.Contains('{') && baseUrl.Contains('}'))
- {
- string? envUrl = Environment.GetEnvironmentVariable("PIXIEDITOR_API_URL");
- if (envUrl != null)
- {
- baseUrl = envUrl;
- }
- }
- #endif
- try
- {
- PixiAuthClient = new PixiAuthClient(baseUrl);
- }
- catch (UriFormatException e)
- {
- Console.WriteLine($"Invalid api URL format: {e.Message}");
- apiValid = false;
- }
- Task.Run(async () =>
- {
- await LoadUserData();
- await TryRefreshToken();
- });
- }
- public async Task RequestLogin(string email)
- {
- if (!apiValid) return;
- try
- {
- Guid? session = await PixiAuthClient.GenerateSession(email);
- if (session != null)
- {
- LastError = null;
- User = new User(email) { SessionId = session.Value };
- NotifyProperties();
- SaveUserInfo();
- }
- }
- catch (PixiAuthException authException)
- {
- LastError = new LocalizedString(authException.Message);
- }
- }
- public async Task ResendActivation()
- {
- if (!apiValid) return;
- if (User?.SessionId == null)
- {
- return;
- }
- try
- {
- await PixiAuthClient.ResendActivation(User.Email, User.SessionId.Value);
- TimeToEndTimeout = DateTime.Now.Add(TimeSpan.FromSeconds(60));
- RunTimeoutTimers(60);
- NotifyProperties();
- LastError = null;
- }
- catch (TooManyRequestsException e)
- {
- LastError = new LocalizedString(e.Message, e.TimeLeft);
- TimeToEndTimeout = DateTime.Now.Add(TimeSpan.FromSeconds(e.TimeLeft));
- RunTimeoutTimers(e.TimeLeft);
- NotifyProperties();
- }
- catch (PixiAuthException authException)
- {
- LastError = new LocalizedString(authException.Message);
- }
- }
- private void RunTimeoutTimers(double timeLeft)
- {
- DispatcherTimer.RunOnce(
- () =>
- {
- TimeToEndTimeout = null;
- NotifyProperties();
- },
- TimeSpan.FromSeconds(timeLeft));
- DispatcherTimer.Run(() =>
- {
- NotifyProperties();
- return TimeToEndTimeout != null;
- }, TimeSpan.FromSeconds(1));
- }
- public bool CanResendActivation()
- {
- return WaitingForActivation && TimeToEndTimeout == null;
- }
- public async Task<bool> TryRefreshToken()
- {
- if (!apiValid) return false;
- if (!IsLoggedIn)
- {
- return false;
- }
- try
- {
- string? token = await PixiAuthClient.RefreshToken(User.SessionId.Value, User.SessionToken);
- if (token != null)
- {
- User.SessionToken = token;
- NotifyProperties();
- SaveUserInfo();
- return true;
- }
- }
- catch (ForbiddenException e)
- {
- User = null;
- NotifyProperties();
- SaveUserInfo();
- LastError = new LocalizedString(e.Message);
- }
- catch (PixiAuthException authException)
- {
- LastError = new LocalizedString(authException.Message);
- }
- return false;
- }
- public async Task<bool> TryValidateSession()
- {
- if (!apiValid) return false;
- if (User?.SessionId == null)
- {
- return false;
- }
- try
- {
- string? token = await PixiAuthClient.TryClaimSessionToken(User.Email, User.SessionId.Value);
- if (token != null)
- {
- LastError = null;
- User.SessionToken = token;
- NotifyProperties();
- SaveUserInfo();
- return true;
- }
- }
- catch (BadRequestException ex)
- {
- if (ex.Message == "SESSION_NOT_VALIDATED")
- {
- LastError = null;
- }
- }
- catch (PixiAuthException authException)
- {
- LastError = new LocalizedString(authException.Message);
- }
- return false;
- }
- public async Task Logout()
- {
- if (!apiValid) return;
- if (!IsLoggedIn)
- {
- return;
- }
- User = null;
- NotifyProperties();
- SaveUserInfo();
- await PixiAuthClient.Logout(User.SessionId.Value, User.SessionToken);
- }
- public async Task SaveUserInfo()
- {
- await IOperatingSystem.Current.SecureStorage.SetValueAsync("UserData", User);
- }
- public async Task LoadUserData()
- {
- User = await IOperatingSystem.Current.SecureStorage.GetValueAsync<User>("UserData", null);
- }
- private void NotifyProperties()
- {
- OnPropertyChanged(nameof(User));
- OnPropertyChanged(nameof(NotLoggedIn));
- OnPropertyChanged(nameof(WaitingForActivation));
- OnPropertyChanged(nameof(IsLoggedIn));
- OnPropertyChanged(nameof(LastError));
- OnPropertyChanged(nameof(TimeToEndTimeout));
- OnPropertyChanged(nameof(TimeToEndTimeoutString));
- ResendActivationCommand.NotifyCanExecuteChanged();
- }
- }
|