Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🎉 Added NUnit tests #29

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ jobs:
nuget restore ror-updater.sln
msbuild /p:Configuration=Release /p:Platform="Any CPU" -p:RestorePackagesConfig=true /m ror-updater.sln

- name: Test
run: |
cd Tests\bin\Release\
..\..\..\packages\NUnit.ConsoleRunner.3.16.0\tools\nunit3-console.exe tests.dll

- name: Create redis folder
run: cmake -P ./tools/copy_build.cmake

Expand All @@ -31,7 +36,7 @@ jobs:
with:
name: listgenerator
path: redist/listgenerator

- name: Upload client
uses: actions/upload-artifact@v3
with:
Expand Down
163 changes: 15 additions & 148 deletions Client/Pages/UpdatePage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using ror_updater.Tasks;

namespace ror_updater
{
Expand All @@ -32,27 +33,17 @@ namespace ror_updater
/// </summary>
public partial class UpdatePage : UserControl, ISwitchable
{
private readonly WebClient _webClient;

private readonly CancellationTokenSource _cancel = new();

private static bool _hasErrored = false;
private RunUpdate _updateTask;

public UpdatePage()
{
InitializeComponent();
((INotifyCollectionChanged)LogWindow.Items).CollectionChanged += ListView_CollectionChanged;

_webClient = new WebClient();
var wc = new WebClient();

OverallProgress.Maximum = App.Instance.ReleaseInfoData.Filelist.Count;
_webClient.DownloadProgressChanged += ProgressChanged;

RunFileUpdate();
}

private async void RunFileUpdate()
{
wc.DownloadProgressChanged += ProgressChanged;
// The Progress<T> constructor captures our UI context,
// so the lambda will be run on the UI thread.
// https://blog.stephencleary.com/2012/02/reporting-progress-from-async-tasks.html
Expand All @@ -61,21 +52,28 @@ private async void RunFileUpdate()
OverallProgress.Value = fileid;
ProgressLabel.Content = fileid + "/" + App.Instance.ReleaseInfoData.Filelist.Count;
});

_updateTask = new RunUpdate(AddToLogFile, progress, wc);

RunFileUpdate();
}

private async void RunFileUpdate()
{
// DoProcessing is run on the thread pool.
switch (App.Choice)
{
case UpdateChoice.INSTALL:
Welcome_Label.Content = "Installing Rigs of Rods";
await Task.Run(() => InstallGame(progress), _cancel.Token);
await _updateTask.InstallGame();
break;
case UpdateChoice.UPDATE:
Welcome_Label.Content = "Updating Rigs of Rods";
await Task.Run(() => UpdateGame(progress), _cancel.Token);
await _updateTask.UpdateGame();
break;
case UpdateChoice.REPAIR:
Welcome_Label.Content = "Repairing Rigs of Rods";
await Task.Run(() => UpdateGame(progress), _cancel.Token);
await _updateTask.UpdateGame();
break;
default:
throw new ArgumentOutOfRangeException();
Expand All @@ -84,77 +82,6 @@ private async void RunFileUpdate()
PageManager.Switch(new UpdateDonePage());
}

private async Task InstallGame(IProgress<int> progress)
{
Utils.LOG(Utils.LogPrefix.INFO, "Installing Game...");

var i = 0;
foreach (var file in App.Instance.ReleaseInfoData.Filelist)
{
if (_cancel.IsCancellationRequested) break;
AddToLogFile($"Downloading file: {file.Directory.TrimStart('.')}/{file.Name}");
await DownloadFile(file.Directory, file.Name);
progress?.Report(i++);
}

Utils.LOG(Utils.LogPrefix.INFO, "Done.");
}

private async Task UpdateGame(IProgress<int> progress)
{
Utils.LOG(Utils.LogPrefix.INFO, "Updating Game...");

var filesStatus = new List<FileStatus>();

AddToLogFile("Checking for outdated files...");
var i = 0;
foreach (var file in App.Instance.ReleaseInfoData.Filelist)
{
if (_cancel.IsCancellationRequested) break;
var fileStatus = HashFile(file);
AddToLogFile($"Checking file: {file.Directory.TrimStart('.')}/{file.Name}");
filesStatus.Add(new FileStatus { File = file, Status = fileStatus });
progress?.Report(i++);
}

AddToLogFile("Done, updating outdated files now...");

i = 0;
foreach (var item in filesStatus)
{
if (_cancel.IsCancellationRequested) break;
progress?.Report(i++);

switch (item.Status)
{
case HashResult.UPTODATE:
Utils.LOG(Utils.LogPrefix.INFO, $"file up to date: {item.File.Name}");
AddToLogFile($"File up to date: {item.File.Directory.TrimStart('.')}/{item.File.Name}");
break;
case HashResult.OUTOFDATE:
AddToLogFile($"File out of date: {item.File.Directory.TrimStart('.')}/{item.File.Name}");
Utils.LOG(Utils.LogPrefix.INFO, $"File out of date: {item.File.Name}");
await DownloadFile(item.File.Directory, item.File.Name);
break;
case HashResult.NOT_FOUND:
Utils.LOG(Utils.LogPrefix.INFO, $"File doesnt exits: {item.File.Name}");
AddToLogFile(
$"Downloading new file: {item.File.Directory.TrimStart('.')}/{item.File.Name}");
await DownloadFile(item.File.Directory, item.File.Name);
break;
default:
throw new ArgumentOutOfRangeException();
}

if (_hasErrored)
{
CancelOperation();
return;
}
}

Utils.LOG(Utils.LogPrefix.INFO, "Done.");
}

private void button_back_Click(object sender, RoutedEventArgs e)
{
Expand All @@ -166,9 +93,7 @@ private void button_back_Click(object sender, RoutedEventArgs e)

private void CancelOperation()
{
_cancel.Cancel();
_webClient.CancelAsync();
_cancel.Dispose();
_updateTask.Cancel();
Utils.LOG(Utils.LogPrefix.INFO, "Update has been canceled");
PageManager.Switch(new ChoicePage());
}
Expand All @@ -195,64 +120,6 @@ private void ListView_CollectionChanged(object sender, NotifyCollectionChangedEv
LogWindow.ScrollIntoView(e.NewItems[0]);
}

HashResult HashFile(PFileInfo item)
{
string sFileHash = null;
var filePath = $"{item.Directory}/{item.Name}";

Utils.LOG(Utils.LogPrefix.INFO, $"Checking file: {item.Name}");

if (!File.Exists(filePath)) return HashResult.NOT_FOUND;
sFileHash = Utils.GetFileHash(filePath);
Utils.LOG(Utils.LogPrefix.INFO,
$"{item.Name} Hash: Local: {sFileHash.ToLower()} Online: {item.Hash.ToLower()}");
return sFileHash.ToLower().Equals(item.Hash.ToLower())
? HashResult.UPTODATE
: HashResult.OUTOFDATE;
}

private async Task DownloadFile(string dir, string file)
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);

Thread.Sleep(100);
var dest = $"{dir}/{file}";
var path = dir.Replace(".", "");
var dlLink = $"{App.Instance.CDNUrl}/{path}/{file}";

try
{
Utils.LOG(Utils.LogPrefix.INFO, $"ULR: {dlLink}");
Utils.LOG(Utils.LogPrefix.INFO, $"File: {dest}");
await _webClient.DownloadFileTaskAsync(new Uri(dlLink), dest);
}
catch (WebException ex) when (ex.Status == WebExceptionStatus.RequestCanceled)
{
_hasErrored = true;
Utils.LOG(Utils.LogPrefix.INFO, ex.ToString());
}
catch (Exception ex)
{
_hasErrored = true;
Utils.LOG(Utils.LogPrefix.ERROR, ex.ToString());
MessageBox.Show($"Failed to download file: {dest}", "Error", MessageBoxButton.OK,
MessageBoxImage.Error);
}
}

private class FileStatus
{
public PFileInfo File;
public HashResult Status;
}

private enum HashResult
{
UPTODATE,
OUTOFDATE,
NOT_FOUND
}

#region ISwitchable Members

Expand Down
148 changes: 148 additions & 0 deletions Client/Tasks/RunUpdate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace ror_updater.Tasks;

public class RunUpdate
{
private readonly WebClient _webClient;

private readonly CancellationTokenSource _cancel = new();

private Action<string> _logCallback;
private IProgress<int> _progress;


public RunUpdate(Action<string> callback, IProgress<int> progress, WebClient webClient)
{
_logCallback = callback;
_progress = progress;
_webClient = webClient;
}


public async Task InstallGame()
{
Utils.LOG(Utils.LogPrefix.INFO, "Installing Game...");

var i = 0;
foreach (var file in App.Instance.ReleaseInfoData.Filelist)
{
if (_cancel.IsCancellationRequested) break;
AddToLogFile($"Downloading file: {file.Directory.TrimStart('.')}/{file.Name}");
await DownloadFile(file.Directory, file.Name);
_progress?.Report(i++);
}

Utils.LOG(Utils.LogPrefix.INFO, "Done.");
}

public async Task UpdateGame()
{
Utils.LOG(Utils.LogPrefix.INFO, "Updating Game...");

var filesStatus = new List<FileStatus>();

AddToLogFile("Checking for outdated files...");
var i = 0;
foreach (var file in App.Instance.ReleaseInfoData.Filelist)
{
if (_cancel.IsCancellationRequested) break;
var fileStatus = HashFile(file);
AddToLogFile($"Checking file: {file.Directory.TrimStart('.')}/{file.Name}");
filesStatus.Add(new FileStatus { File = file, Status = fileStatus });
_progress?.Report(i++);
}

AddToLogFile("Done, updating outdated files now...");

i = 0;
foreach (var item in filesStatus)
{
if (_cancel.IsCancellationRequested) break;
_progress?.Report(i++);

switch (item.Status)
{
case HashResult.UPTODATE:
Utils.LOG(Utils.LogPrefix.INFO, $"file up to date: {item.File.Name}");
AddToLogFile($"File up to date: {item.File.Directory.TrimStart('.')}/{item.File.Name}");
break;
case HashResult.OUTOFDATE:
AddToLogFile($"File out of date: {item.File.Directory.TrimStart('.')}/{item.File.Name}");
Utils.LOG(Utils.LogPrefix.INFO, $"File out of date: {item.File.Name}");
await DownloadFile(item.File.Directory, item.File.Name);
break;
case HashResult.NOT_FOUND:
Utils.LOG(Utils.LogPrefix.INFO, $"File doesnt exits: {item.File.Name}");
AddToLogFile(
$"Downloading new file: {item.File.Directory.TrimStart('.')}/{item.File.Name}");
await DownloadFile(item.File.Directory, item.File.Name);
break;
default:
throw new ArgumentOutOfRangeException();
}
}

Utils.LOG(Utils.LogPrefix.INFO, "Done.");
}

public void Cancel()
{
_cancel.Cancel();
}

HashResult HashFile(PFileInfo item)
{
string sFileHash = null;
var filePath = $"{item.Directory}/{item.Name}";

Utils.LOG(Utils.LogPrefix.INFO, $"Checking file: {item.Name}");

if (!File.Exists(filePath)) return HashResult.NOT_FOUND;
sFileHash = Utils.GetFileHash(filePath);
Utils.LOG(Utils.LogPrefix.INFO,
$"{item.Name} Hash: Local: {sFileHash.ToLower()} Online: {item.Hash.ToLower()}");
return sFileHash.ToLower().Equals(item.Hash.ToLower())
? HashResult.UPTODATE
: HashResult.OUTOFDATE;
}

private async Task DownloadFile(string dir, string file)
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);

Thread.Sleep(100);
var dest = $"{dir}/{file}";
var path = dir.Replace(".", "");
var dlLink = $"{App.Instance.CDNUrl}/{path}/{file}";

Utils.LOG(Utils.LogPrefix.INFO, $"ULR: {dlLink}");
Utils.LOG(Utils.LogPrefix.INFO, $"File: {dest}");
await _webClient.DownloadFileTaskAsync(new Uri(dlLink), dest);
}

private void AddToLogFile(string s)
{
_logCallback(s);
}

private class FileStatus
{
public PFileInfo File;
public HashResult Status;
}

private enum HashResult
{
UPTODATE,
OUTOFDATE,
NOT_FOUND
}
}
Loading