Skip to content

Commit

Permalink
Add pause when downloading
Browse files Browse the repository at this point in the history
  • Loading branch information
Drombeys committed May 1, 2024
1 parent 0d7f2a0 commit e87ae42
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public class DownloadResourcesService(ILogger<DownloadResourcesService> logger,
public async Task<IDictionary<string, Uri>?> GetFilesForDownloadAsync(IProgress<int> progress,
CancellationToken cancellationToken = default)
{
progress.Report(0);
var filesRes = new ConcurrentDictionary<string, Uri>();
_hashResources ??= await _gitStorageApiService
.DownloadJsonAsync<IList<GameResource>>(FileNameStorage.HashResources, UriStorage.BelarusApiUri, cancellationToken);
Expand Down
5 changes: 5 additions & 0 deletions src/ImeSense.Launchers.Belarus.Desktop/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ public static void Main(string[] args)
_mutex = new Mutex(initiallyOwned: false, _mutexName, out isMutexCreated);
} catch (Exception exception) {
Log.Error("{Message} \n {StackTrace}", exception.Message, exception.StackTrace);
Log.CloseAndFlush();
_mutex?.Dispose();
throw;
}
if (!isMutexCreated) {
return;
Expand All @@ -43,6 +46,8 @@ public static void Main(string[] args)
StartApp(args);
} catch (Exception exception) {
Log.Error("{Message} \n {StackTrace}", exception.Message, exception.StackTrace);
Log.CloseAndFlush();
_mutex?.Dispose();
throw;
}
#endif
Expand Down
1 change: 1 addition & 0 deletions src/ImeSense.Launchers.Belarus/Assets/Locales/eng.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,5 @@
<s:String x:Key="LocalizedStrings.CheckLauncherUpdate">Checking for launcher updates</s:String>
<s:String x:Key="LocalizedStrings.CheckGameUpdate">Checking for game updates</s:String>
<s:String x:Key="LocalizedStrings.LoadLocalData">Loading local data</s:String>
<s:String x:Key="LocalizedStrings.Pause">Pause</s:String>
</ResourceDictionary>
1 change: 1 addition & 0 deletions src/ImeSense.Launchers.Belarus/Assets/Locales/rus.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,5 @@
<s:String x:Key="LocalizedStrings.CheckLauncherUpdate">Проверка обновлений лаунчера</s:String>
<s:String x:Key="LocalizedStrings.CheckGameUpdate">Проверка обновлений игры</s:String>
<s:String x:Key="LocalizedStrings.LoadLocalData">Загрузка локальных данных</s:String>
<s:String x:Key="LocalizedStrings.Pause">Пауза</s:String>
</ResourceDictionary>
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public static IServiceCollection AddViewModels(this IServiceCollection services)
public static IServiceCollection AddViews(this IServiceCollection services)
{
services.AddTransient<AuthorizationView>();
services.AddSingleton<DownloadMenuView>();
services.AddTransient<DownloadMenuView>();
services.AddSingleton<GameMenuView>();
services.AddSingleton<LauncherView>();
services.AddSingleton<LinkView>();
Expand Down
82 changes: 56 additions & 26 deletions src/ImeSense.Launchers.Belarus/ViewModels/DownloadMenuViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ public class DownloadMenuViewModel : ReactiveObject
private readonly IWindowManager _windowManager;
private readonly IDownloadResourcesService _downloadResourcesService;
private readonly ILauncherStorage _launcherStorage;
private CancellationTokenSource _tokenSource = new();
private CancellationTokenSource _cts;

public CancellationToken CancellationToken { get; private set; }
public ReactiveCommand<LauncherViewModel, Unit> StartDownload { get; private set; } = null!;
public ReactiveCommand<Unit, Unit> Pause { get; private set; } = null!;
public ReactiveCommand<Unit, Unit> Close { get; private set; } = null!;

[Reactive] public int DownloadProgress { get; set; } = 0;
Expand All @@ -47,6 +49,7 @@ public DownloadMenuViewModel(ILogger<DownloadMenuViewModel>? logger,
_downloadResourcesService = downloadResourcesService;
_launcherStorage = launcherStorage;
IsDownload = false;
_cts = null!;

SetupCommands();
}
Expand All @@ -59,6 +62,7 @@ public DownloadMenuViewModel()
_windowManager = null!;
_downloadResourcesService = null!;
_launcherStorage = null!;
_cts = new();
}

public async Task UpdateAsync(LauncherViewModel launcherViewModel)
Expand All @@ -71,62 +75,88 @@ private void SetupCommands()
var isGitHubConnection = this.WhenAnyValue(x => x._launcherStorage.IsCheckGitHubConnection);

StartDownload = ReactiveCommand.CreateFromTask<LauncherViewModel>(DownloadsImplAsync, isGitHubConnection);
Pause = ReactiveCommand.Create(PauseImpl);
Close = ReactiveCommand.Create(CloseImpl);

StartDownload.ThrownExceptions.Merge(Close.ThrownExceptions)
.Throttle(TimeSpan.FromMilliseconds(250), RxApp.MainThreadScheduler)
.Subscribe(OnCommandException);
}

private void PauseImpl()
{
ClearData();
_cts?.Cancel();
}

private void ClearData()
{
DownloadProgress = 0;
DownloadFileName = string.Empty;
IsProgress = false;
IsDownload = false;
}

private void CloseImpl()
{
_tokenSource.Cancel();
_tokenSource.Dispose();
PauseImpl();

_windowManager.Close();
}

private async Task DownloadsImplAsync(LauncherViewModel launcherViewModel)
{
DownloadFileName = string.Empty;
var progress = new Progress<int>(percentage => {
_cts = new();
CancellationToken = _cts.Token;
ClearData();

IProgress<int> progress = new Progress<int>(percentage => {
DownloadProgress = percentage;
});

IsProgress = true;
StatusProgress = _localeManager.GetStringByKey("LocalizedStrings.IntegrityChecking");

var filesDownload = await _downloadResourcesService.GetFilesForDownloadAsync(progress);
var filesDownload = await _downloadResourcesService.GetFilesForDownloadAsync(progress, CancellationToken);

if (CancellationToken.IsCancellationRequested) {
launcherViewModel.SelectMenu();
PauseImpl();
return;
}

if (filesDownload != null && filesDownload.Any()) {
var countFiles = filesDownload.Count;
var numberFile = 0;
IsDownload = true;
try {
foreach (var file in filesDownload) {
numberFile++;
StatusProgress = _localeManager.GetStringByKey("LocalizedStrings.Files") +
$": {numberFile} / {countFiles}";
DownloadFileName = Path.GetFileName(file.Key);
await _downloadResourcesService.DownloadAsync(file.Key, file.Value, progress, _tokenSource.Token);
}
} catch (AggregateException ae) {
foreach (var e in ae.InnerExceptions) {
if (e is TaskCanceledException) {
} else {
//Console.WriteLine(e.Message);
}
foreach (var file in filesDownload) {
numberFile++;
StatusProgress = _localeManager.GetStringByKey("LocalizedStrings.Files") +
$": {numberFile} / {countFiles}";
DownloadFileName = Path.GetFileName(file.Key);
await _downloadResourcesService.DownloadAsync(file.Key, file.Value, progress, CancellationToken);

if (CancellationToken.IsCancellationRequested) {
PauseImpl();
launcherViewModel.SelectMenu();
return;
}
} finally {
_tokenSource.Cancel();
_tokenSource.Dispose();

progress.Report(0);
}
}

IsDownload = false;
DownloadFileName = string.Empty;
progress.Report(0);
ClearData();

launcherViewModel.SelectMenu();
}

private void OnCommandException(Exception exception)
=> _logger?.LogError("{Message}", exception.Message);
{
ClearData();

_logger?.LogError("{Message}", exception.Message);
_logger?.LogError("{Message}", exception.StackTrace);
}
}
13 changes: 12 additions & 1 deletion src/ImeSense.Launchers.Belarus/Views/DownloadMenuView.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,18 @@
Margin="0,5,0,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Foreground="LightGray" />
Foreground="LightGray"
Maximum="100"
Minimum="0" />

<Button
Content="{DynamicResource LocalizedStrings.Pause}"
Command="{Binding Pause}"
Margin="20"
HorizontalAlignment="Center"
HorizontalContentAlignment="Right"
Classes="styled"
FontSize="32" />
</StackPanel>
</StackPanel>
</DockPanel>
Expand Down

0 comments on commit e87ae42

Please sign in to comment.