67 lines
2.3 KiB
C#
67 lines
2.3 KiB
C#
using System.Security.Cryptography;
|
||
using DTLib.Extensions;
|
||
using Mlaumcherb.Client.Avalonia.зримое;
|
||
using Mlaumcherb.Client.Avalonia.классы;
|
||
using Mlaumcherb.Client.Avalonia.холопы;
|
||
using static Mlaumcherb.Client.Avalonia.сеть.NetworkHelper;
|
||
|
||
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||
|
||
public class VersionFileDownloadTaskFactory : INetworkTaskFactory
|
||
{
|
||
private GameVersionDescriptor _descriptor;
|
||
private IOPath _filePath;
|
||
private SHA1 _hasher;
|
||
|
||
public VersionFileDownloadTaskFactory(GameVersionDescriptor descriptor)
|
||
{
|
||
_descriptor = descriptor;
|
||
_filePath = PathHelper.GetVersionJarFilePath(_descriptor.id);
|
||
_hasher = SHA1.Create();
|
||
}
|
||
|
||
public Task<NetworkTask?> CreateAsync(bool checkHashes)
|
||
{
|
||
NetworkTask? networkTask = null;
|
||
if (!CheckFiles(checkHashes))
|
||
networkTask = new NetworkTask(
|
||
$"version file '{_descriptor.id}'",
|
||
GetTotalSize(),
|
||
Download
|
||
);
|
||
return Task.FromResult(networkTask);
|
||
}
|
||
|
||
private bool CheckFiles(bool checkHashes)
|
||
{
|
||
if (!File.Exists(_filePath))
|
||
return false;
|
||
|
||
if (!checkHashes)
|
||
return true;
|
||
|
||
if (_descriptor.downloads is null)
|
||
return true;
|
||
|
||
using var fs = File.OpenRead(_filePath);
|
||
string hash = _hasher.ComputeHash(fs).HashToString();
|
||
return hash == _descriptor.downloads.client.sha1;
|
||
}
|
||
|
||
private long GetTotalSize()
|
||
{
|
||
if(_descriptor.downloads is null)
|
||
return 0;
|
||
return _descriptor.downloads.client.size;
|
||
}
|
||
|
||
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||
{
|
||
if (_descriptor.downloads is null)
|
||
throw new Exception($"can't download version file '{_descriptor.id}' because it has no download url");
|
||
|
||
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading version file '{_descriptor.id}'");
|
||
await DownloadFile(_descriptor.downloads.client.url, _filePath, ct, pr.AddBytesCount);
|
||
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading version file '{_descriptor.id}'");
|
||
}
|
||
} |