Skip to content

Commit

Permalink
Refactor locale manager module
Browse files Browse the repository at this point in the history
  • Loading branch information
Drombeys committed Apr 24, 2024
1 parent 716a6e6 commit 9e0e457
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 146 deletions.
14 changes: 7 additions & 7 deletions src/ImeSense.Launchers.Belarus.Avalonia/App.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ private IServiceCollection ConfigureServices()
services.AddTransient<IAuthenticationValidator, AuthenticationValidator>();
services.AddTransient<IStartGameValidator, StartGameValidator>();
services.AddSingleton<ILauncherStorage, MemoryLauncherStorage>();
services.AddSingleton<ILocaleManager, LocaleManager>();
services.AddSingleton<IApplicationLocaleManager, AxamlLocaleManager>();
services.AddTransient<IReleaseComparerService<GitHubRelease>, ReleaseComparerService>();
services.AddTransient<IUpdaterService, UpdaterService>();
services.AddSingleton<AuthenticationViewModelValidator>();
Expand Down Expand Up @@ -117,27 +117,27 @@ public override async void OnFrameworkInitializationCompleted()
await userManager.LoadAsync();
initializerManager.InitializeLocale();

var localeManager = _serviceProvider.GetRequiredService<ILocaleManager>();
var locale = userManager.UserSettings?.Locale?.Key!;
var localeManager = _serviceProvider.GetRequiredService<IApplicationLocaleManager>();

var splashScreenViewModel = _serviceProvider.GetRequiredService<SplashScreenViewModel>();
var mainViewModel = _serviceProvider.GetRequiredService<MainWindowViewModel>();
desktop.MainWindow = new MainWindow {
DataContext = mainViewModel
};
desktop.MainWindow.Show();

try {
mainViewModel.ShowSplashScreenImpl(splashScreenViewModel);
splashScreenViewModel.Progress++;
splashScreenViewModel.InformationMessage = new InformationMessage(
localeManager.GetStringByKey("LocalizedStrings.Loading", locale),
localeManager.GetStringByKey("LocalizedStrings.AccessingRepository", locale));
localeManager.GetStringByKey("LocalizedStrings.Loading"),
localeManager.GetStringByKey("LocalizedStrings.AccessingRepository"));
//await Task.Delay(2000, splashScreenViewModel.CancellationToken);
await initializerManager.InitializeAsync();
splashScreenViewModel.Progress++;
splashScreenViewModel.InformationMessage = new InformationMessage(
localeManager.GetStringByKey("LocalizedStrings.Loading", locale),
localeManager.GetStringByKey("LocalizedStrings.DataInitialization", locale));
localeManager.GetStringByKey("LocalizedStrings.Loading"),
localeManager.GetStringByKey("LocalizedStrings.DataInitialization"));
//await Task.Delay(2000, splashScreenViewModel.CancellationToken);
await mainViewModel.InitializeAsync();
splashScreenViewModel.Progress++;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,30 @@

namespace ImeSense.Launchers.Belarus.Avalonia.Manager;

public class LocaleManager : ILocaleManager
public class AxamlLocaleManager : IApplicationLocaleManager
{
private string _locale = string.Empty;

public void SetLocale(string locale)
{
_locale = locale;

App.Current?.Resources.Clear();
var resource = new ResourceInclude(new Uri("avares://SBLauncher/Assets/Locales/")) {

Check warning on line 17 in src/ImeSense.Launchers.Belarus.Avalonia/Manager/AxamlLocaleManager.cs

View workflow job for this annotation

GitHub Actions / Publish launcher (windows-2022, Release, win-x64, net8.0)

Using member 'Avalonia.Markup.Xaml.Styling.ResourceInclude.ResourceInclude(Uri)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. StyleInclude and ResourceInclude use AvaloniaXamlLoader.Load which dynamically loads referenced assembly with Avalonia resources. Note, StyleInclude and ResourceInclude defined in XAML are resolved compile time and are safe with trimming and AOT.
Source = new Uri($"avares://SBLauncher/Assets/Locales/{locale}.axaml"),
Source = new Uri($"avares://SBLauncher/Assets/Locales/{_locale}.axaml"),
};
App.Current?.Resources.MergedDictionaries.Add(resource);
}

public string GetStringByKey(string key, string locale)
public string GetLocale()
{
return _locale;
}

public string GetStringByKey(string key)
{
var resources = new ResourceInclude(new Uri("avares://SBLauncher/Assets/Locales/")) {

Check warning on line 30 in src/ImeSense.Launchers.Belarus.Avalonia/Manager/AxamlLocaleManager.cs

View workflow job for this annotation

GitHub Actions / Publish launcher (windows-2022, Release, win-x64, net8.0)

Using member 'Avalonia.Markup.Xaml.Styling.ResourceInclude.ResourceInclude(Uri)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. StyleInclude and ResourceInclude use AvaloniaXamlLoader.Load which dynamically loads referenced assembly with Avalonia resources. Note, StyleInclude and ResourceInclude defined in XAML are resolved compile time and are safe with trimming and AOT.
Source = new Uri($"avares://SBLauncher/Assets/Locales/{locale}.axaml"),
Source = new Uri($"avares://SBLauncher/Assets/Locales/{_locale}.axaml"),
};
var control = new Control {
Resources = resources.Loaded,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class AuthorizationViewModel : ReactiveValidationObject, IDisposable
{
private readonly ILogger<AuthorizationViewModel> _logger;
private readonly ILauncherStorage _launcherStorage;
private readonly ILocaleManager _localeManager;
private readonly IApplicationLocaleManager _localeManager;

private readonly IWindowManager _windowManager;
private readonly UserManager _userManager;
Expand All @@ -44,7 +44,7 @@ public class AuthorizationViewModel : ReactiveValidationObject, IDisposable
public ReactiveCommand<Unit, Unit> Close { get; private set; } = null!;

public AuthorizationViewModel(ILogger<AuthorizationViewModel> logger,
ILauncherStorage launcherStorage, ILocaleManager localeManager,
ILauncherStorage launcherStorage, IApplicationLocaleManager localeManager,
IWindowManager windowManager, UserManager userManager,
AuthenticationViewModelValidator authenticationViewModelValidator,
LauncherViewModel launcherViewModel)
Expand Down Expand Up @@ -77,8 +77,7 @@ public void ShowLauncherImpl(MainWindowViewModel mainWindowViewModel)
{
var username = Username.Trim();
if (string.IsNullOrWhiteSpace(username)) {
throw new Exception(_localeManager.GetStringByKey("LocalizedStrings.UsernameNotEntered",
SelectedLanguage.Key));
throw new Exception(_localeManager.GetStringByKey("LocalizedStrings.UsernameNotEntered"));
}

if (_userManager is null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@ namespace ImeSense.Launchers.Belarus.Avalonia.ViewModels;
public class DownloadMenuViewModel : ReactiveObject
{
private readonly ILogger<DownloadMenuViewModel> _logger;
private readonly ILocaleManager _localeManager;
private readonly IApplicationLocaleManager _localeManager;

private readonly IWindowManager _windowManager;
private readonly IDownloadResourcesService _downloadResourcesService;
private readonly UserManager _userManager;
private readonly ILauncherStorage _launcherStorage;
private CancellationTokenSource _tokenSource = new();

Expand All @@ -38,17 +37,15 @@ public class DownloadMenuViewModel : ReactiveObject
[Reactive] public bool IsDownload { get; set; }

public DownloadMenuViewModel(ILogger<DownloadMenuViewModel> logger,
ILocaleManager localeManager,
IApplicationLocaleManager localeManager,
IWindowManager windowManager,
IDownloadResourcesService downloadResourcesService,
UserManager userManager,
ILauncherStorage launcherStorage)
{
_logger = logger;
_localeManager = localeManager;
_windowManager = windowManager ?? throw new ArgumentNullException(nameof(windowManager));
_downloadResourcesService = downloadResourcesService ?? throw new ArgumentNullException(nameof(downloadResourcesService));
_userManager = userManager;
_windowManager = windowManager;
_downloadResourcesService = downloadResourcesService;
_launcherStorage = launcherStorage;
IsDownload = false;

Expand All @@ -63,7 +60,6 @@ public DownloadMenuViewModel()
_localeManager = null!;
_windowManager = null!;
_downloadResourcesService = null!;
_userManager = null!;
_launcherStorage = null!;
}

Expand Down Expand Up @@ -94,23 +90,13 @@ private void CloseImpl()

private async Task DownloadsImplAsync(LauncherViewModel launcherViewModel)
{
if (_userManager is null) {
throw new NullReferenceException("User manager object is null");
}
if (_userManager.UserSettings is null) {
throw new NullReferenceException("User settings object is null");
}
if (_userManager.UserSettings.Locale is null) {
throw new NullReferenceException("User settings locale object is null");
}

DownloadFileName = string.Empty;
var progress = new Progress<int>(percentage => {
DownloadProgress = percentage;
});

IsProgress = true;
StatusProgress = _localeManager.GetStringByKey("LocalizedStrings.IntegrityChecking", _userManager.UserSettings.Locale.Key);
StatusProgress = _localeManager.GetStringByKey("LocalizedStrings.IntegrityChecking");

var filesDownload = await _downloadResourcesService.GetFilesForDownloadAsync(progress);
if (filesDownload != null && filesDownload.Any()) {
Expand All @@ -120,7 +106,7 @@ private async Task DownloadsImplAsync(LauncherViewModel launcherViewModel)
try {
foreach (var file in filesDownload) {
numberFile++;
StatusProgress = _localeManager.GetStringByKey("LocalizedStrings.Files", _userManager.UserSettings.Locale.Key) +
StatusProgress = _localeManager.GetStringByKey("LocalizedStrings.Files") +
$": {numberFile} / {countFiles}";
DownloadFileName = Path.GetFileName(file.Key);
await _downloadResourcesService.DownloadAsync(file.Key, file.Value, progress, _tokenSource.Token);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public class NewsSliderViewModel : ReactiveObject
private readonly ILogger<NewsSliderViewModel> _logger;
private readonly ViewModelLocator _viewModelLocator;
private readonly ILauncherStorage _launcherStorage;
private readonly UserManager _userManager;

[Reactive] public int NumPage { get; set; }
[Reactive] public NewsViewModel? SelectedNewsViewModel { get; private set; }
Expand All @@ -28,24 +29,18 @@ public class NewsSliderViewModel : ReactiveObject

public ReactiveCommand<Unit, Unit> GoNext { get; set; } = null!;
public ReactiveCommand<Unit, Unit> GoBack { get; set; } = null!;
public UserManager UserManager { get; set; }

public NewsSliderViewModel(ILogger<NewsSliderViewModel> logger, ViewModelLocator viewModelLocator,
UserManager userManager, ILauncherStorage launcherStorage, ILocaleManager localeManager)
UserManager userManager, ILauncherStorage launcherStorage, IApplicationLocaleManager localeManager)
{
logger.LogInformation("NewsSliderViewModel CTOR");

if (userManager.UserSettings is not null) {
var locale = userManager.UserSettings.Locale;
if (locale is not null) {
News = [new(localeManager.GetStringByKey("LocalizedStrings.Warning", locale.Key),
localeManager.GetStringByKey("LocalizedStrings.LoadNews", locale.Key))];
}
}
News = [new(localeManager.GetStringByKey("LocalizedStrings.Warning"),
localeManager.GetStringByKey("LocalizedStrings.LoadNews"))];

_logger = logger;
_viewModelLocator = viewModelLocator;
UserManager = userManager;
_userManager = userManager;
_launcherStorage = launcherStorage;
LinkViewModel = viewModelLocator.LinkViewModel;

Expand All @@ -59,13 +54,13 @@ public NewsSliderViewModel(ILogger<NewsSliderViewModel> logger, ViewModelLocator
_logger.LogInformation("Language has been changed!");
ReloadNews(lang);
}, canLoadNews);
this.WhenAnyValue(x => x.UserManager.UserSettings!.Locale)
this.WhenAnyValue(x => x._userManager.UserSettings!.Locale)
.InvokeCommand(reloadNewsCommand);

this.WhenAnyValue(x => x._launcherStorage.NewsContents)
.Where(news => news != null && news.Any())
.Subscribe((n) => {
var locale = UserManager.UserSettings!.Locale;
var locale = _userManager.UserSettings!.Locale;
ReloadNews(locale);
});
}
Expand Down Expand Up @@ -96,7 +91,7 @@ public NewsSliderViewModel()

LinkViewModel = null!;
_viewModelLocator = null!;
UserManager = null!;
_userManager = null!;
_launcherStorage = null!;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class StartGameViewModel : ReactiveValidationObject, IDisposable
{
private readonly ILogger<StartGameViewModel> _logger;
private readonly UserManager _userManager;
private readonly ILocaleManager _localeManager;
private readonly IApplicationLocaleManager _localeManager;
private readonly IWindowManager _windowManager;
private readonly StartGameViewModelValidator _startGameViewModelValidator;

Expand All @@ -31,7 +31,7 @@ public class StartGameViewModel : ReactiveValidationObject, IDisposable
public ReactiveCommand<MainWindowViewModel, Unit> Back { get; private set; } = null!;

public StartGameViewModel(ILogger<StartGameViewModel> logger, UserManager userManager,
IWindowManager windowManager, ILocaleManager localeManager,
IWindowManager windowManager, IApplicationLocaleManager localeManager,
StartGameViewModelValidator startGameViewModelValidator)
{
_logger = logger;
Expand Down Expand Up @@ -110,22 +110,18 @@ private void StartGameImpl()
if (_userManager.UserSettings is null) {
throw new NullReferenceException("User settings object is null");
}
if (_userManager.UserSettings.Locale is null) {
throw new NullReferenceException("User settings locale object is null");
}

if (string.IsNullOrWhiteSpace(IpAddress)) {
throw new Exception(_localeManager.GetStringByKey("LocalizedStrings.NoIpAddressEntered",
_userManager.UserSettings.Locale.Key));
throw new Exception(_localeManager.GetStringByKey("LocalizedStrings.NoIpAddressEntered"));
}

_userManager.UserSettings.IpAddress = IpAddress;
_userManager.Save();

var process = Core.Launcher.Launch(path: @"binaries\xrEngine.exe",
arguments: new List<string> {
arguments: [
@$"-start -center_screen -silent_error_mode client({_userManager.UserSettings.IpAddress}/name={ _userManager.UserSettings.Username})"
});
]);

process?.Start();
_windowManager.Close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,68 +6,29 @@

namespace ImeSense.Launchers.Belarus.Avalonia.ViewModels.Validators;

public sealed class AuthenticationViewModelValidator
public sealed class AuthenticationViewModelValidator(IAuthenticationValidator validator, IApplicationLocaleManager localeManager)
{
private readonly IAuthenticationValidator _validator;
private readonly ILocaleManager _localeManager;
private readonly UserManager _userManager;

public AuthenticationViewModelValidator(IAuthenticationValidator validator, ILocaleManager localeManager,
UserManager userManager)
{
_validator = validator;
_localeManager = localeManager;
_userManager = userManager;
}
private readonly IAuthenticationValidator _validator = validator;
private readonly IApplicationLocaleManager _localeManager = localeManager;

public ValidationHelper EnsureUsernameNotEmpty(AuthorizationViewModel authorizationViewModel)
{
if (_userManager is null) {
throw new NullReferenceException("User manager object is null");
}
if (_userManager.UserSettings is null) {
throw new NullReferenceException("User settings object is null");
}
if (_userManager.UserSettings.Locale is null) {
throw new NullReferenceException("User settings locale object is null");
}

return authorizationViewModel.ValidationRule(viewModel => viewModel.Username,
username => username != null && _validator.IsUsernameNotEmpty(username),
_localeManager.GetStringByKey("LocalizedStrings.EnterNickName", _userManager.UserSettings.Locale.Key));
_localeManager.GetStringByKey("LocalizedStrings.EnterNickName"));
}

public ValidationHelper EnsureUsernameCorrectLength(AuthorizationViewModel authorizationViewModel)
{
if (_userManager is null) {
throw new NullReferenceException("User manager object is null");
}
if (_userManager.UserSettings is null) {
throw new NullReferenceException("User settings object is null");
}
if (_userManager.UserSettings.Locale is null) {
throw new NullReferenceException("User settings locale object is null");
}

return authorizationViewModel.ValidationRule(viewModel => viewModel.Username,
username => username != null && _validator.IsUsernameCorrectLength(username),
_localeManager.GetStringByKey("LocalizedStrings.TooLongNickname", _userManager.UserSettings.Locale.Key));
_localeManager.GetStringByKey("LocalizedStrings.TooLongNickname"));
}

public ValidationHelper EnsureUsernameCorrectCharacters(AuthorizationViewModel authorizationViewModel)
{
if (_userManager is null) {
throw new NullReferenceException("User manager object is null");
}
if (_userManager.UserSettings is null) {
throw new NullReferenceException("User settings object is null");
}
if (_userManager.UserSettings.Locale is null) {
throw new NullReferenceException("User settings locale object is null");
}

return authorizationViewModel.ValidationRule(viewModel => viewModel.Username,
username => username != null && _validator.IsUsernameCorrectCharacters(username),
_localeManager.GetStringByKey("LocalizedStrings.InvalidCharacters", _userManager.UserSettings.Locale.Key));
_localeManager.GetStringByKey("LocalizedStrings.InvalidCharacters"));
}
}
Loading

0 comments on commit 9e0e457

Please sign in to comment.