wabbajack/Wabbajack.Networking.WabbajackClientApi/Client.cs

337 lines
13 KiB
C#
Raw Normal View History

2021-09-27 12:42:46 +00:00
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
2021-10-21 03:18:15 +00:00
using System.Threading;
2021-09-27 12:42:46 +00:00
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Wabbajack.Common;
using Wabbajack.DTOs;
using Wabbajack.DTOs.CDN;
using Wabbajack.DTOs.JsonConverters;
2021-10-12 05:19:13 +00:00
using Wabbajack.DTOs.Logins;
2021-09-27 12:42:46 +00:00
using Wabbajack.DTOs.ModListValidation;
using Wabbajack.DTOs.Validation;
using Wabbajack.Hashing.xxHash64;
using Wabbajack.Networking.Http;
2021-10-12 05:19:13 +00:00
using Wabbajack.Networking.Http.Interfaces;
2021-09-27 12:42:46 +00:00
using Wabbajack.Paths;
using Wabbajack.Paths.IO;
2021-10-12 05:19:13 +00:00
using Wabbajack.RateLimiter;
2021-10-21 03:18:15 +00:00
using Wabbajack.VFS;
2021-09-27 12:42:46 +00:00
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
2021-10-23 16:51:17 +00:00
namespace Wabbajack.Networking.WabbajackClientApi;
public class Client
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
public static readonly long UploadedFileBlockSize = (long) 1024 * 1024 * 2;
private readonly HttpClient _client;
private readonly Configuration _configuration;
private readonly DTOSerializer _dtos;
private readonly IResource<FileHashCache> _hashLimiter;
private readonly IResource<HttpClient> _limiter;
private readonly ILogger<Client> _logger;
private readonly ParallelOptions _parallelOptions;
private readonly ITokenProvider<WabbajackApiState> _token;
public Client(ILogger<Client> logger, HttpClient client, ITokenProvider<WabbajackApiState> token,
DTOSerializer dtos,
IResource<HttpClient> limiter, IResource<FileHashCache> hashLimiter, Configuration configuration)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
_configuration = configuration;
_token = token;
_client = client;
_logger = logger;
_dtos = dtos;
_limiter = limiter;
_hashLimiter = hashLimiter;
}
2021-09-27 12:42:46 +00:00
2021-12-17 23:40:45 +00:00
private async ValueTask<HttpRequestMessage> MakeMessage(HttpMethod method, Uri uri, HttpContent? content = null)
2021-10-23 16:51:17 +00:00
{
var msg = new HttpRequestMessage(method, uri);
var key = (await _token.Get())!;
msg.Headers.Add(_configuration.MetricsKeyHeader, key.MetricsKey);
if (!string.IsNullOrWhiteSpace(key.AuthorKey))
msg.Headers.Add(_configuration.AuthorKeyHeader, key.AuthorKey);
2021-12-17 23:40:45 +00:00
if (content != null)
msg.Content = content;
2021-10-23 16:51:17 +00:00
return msg;
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async Task SendMetric(string action, string subject)
{
var msg = await MakeMessage(HttpMethod.Get,
new Uri($"{_configuration.BuildServerUrl}metrics/{action}/{subject}"));
await _client.SendAsync(msg);
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async Task<ServerAllowList> LoadDownloadAllowList()
{
var str = await _client.GetStringAsync(_configuration.ServerAllowList);
var d = new DeserializerBuilder()
.WithNamingConvention(PascalCaseNamingConvention.Instance)
.Build();
return d.Deserialize<ServerAllowList>(str);
}
2021-10-12 05:19:13 +00:00
2021-10-23 16:51:17 +00:00
public async Task<ServerAllowList> LoadMirrorAllowList()
{
var str = await _client.GetStringAsync(_configuration.MirrorAllowList);
var d = new DeserializerBuilder()
.WithNamingConvention(PascalCaseNamingConvention.Instance)
.Build();
return d.Deserialize<ServerAllowList>(str);
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async Task<Dictionary<Hash, ValidatedArchive>> LoadUpgradedArchives()
{
return (await _client.GetFromJsonAsync<ValidatedArchive[]>(_configuration.UpgradedArchives, _dtos.Options))!
.ToDictionary(d => d.Original.Hash);
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async Task<Archive[]> GetGameArchives(Game game, string version)
{
var url = $"https://raw.githubusercontent.com/wabbajack-tools/indexed-game-files/master/{game}/{version}.json";
return await _client.GetFromJsonAsync<Archive[]>(url, _dtos.Options) ?? Array.Empty<Archive>();
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async Task<Archive[]> GetArchivesForHash(Hash hash)
{
var msg = await MakeMessage(HttpMethod.Get,
new Uri($"{_configuration.BuildServerUrl}mod_files/by_hash/{hash.ToHex()}"));
return await _client.GetFromJsonAsync<Archive[]>(_limiter, msg, _dtos.Options) ?? Array.Empty<Archive>();
}
2021-12-18 16:14:39 +00:00
public Uri GetMirrorUrl(Hash archiveHash)
2021-10-23 16:51:17 +00:00
{
2021-12-18 16:14:39 +00:00
return new Uri($"{_configuration.MirrorServerUrl}{archiveHash.ToHex()}");
2021-10-23 16:51:17 +00:00
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async Task SendModListDefinition(ModList modList)
{
await using var fs = new MemoryStream();
await using var gzip = new GZipStream(fs, CompressionLevel.SmallestSize, true);
await _dtos.Serialize(modList, gzip);
await gzip.DisposeAsync();
fs.Position = 0;
var msg = new HttpRequestMessage(HttpMethod.Post,
$"{_configuration.BuildServerUrl}list_definitions/ingest");
msg.Headers.Add("x-compressed-body", "gzip");
msg.Content = new StreamContent(fs);
await _client.SendAsync(msg);
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async Task<ModListSummary[]> GetListStatuses()
{
return await _client.GetFromJsonAsync<ModListSummary[]>(
"https://raw.githubusercontent.com/wabbajack-tools/mod-lists/master/reports/modListSummary.json",
_dtos.Options) ?? Array.Empty<ModListSummary>();
}
public async Task<ValidatedModList> GetDetailedStatus(string machineURL)
{
return (await _client.GetFromJsonAsync<ValidatedModList>(
$"https://raw.githubusercontent.com/wabbajack-tools/mod-lists/master/reports/{machineURL}/status.json",
_dtos.Options))!;
}
2021-12-17 23:40:45 +00:00
IEnumerable<PartDefinition> Blocks(long size)
{
for (long block = 0; block * UploadedFileBlockSize < size; block++)
yield return new PartDefinition
{
Index = block,
Size = Math.Min(UploadedFileBlockSize, size - block * UploadedFileBlockSize),
Offset = block * UploadedFileBlockSize
};
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async Task<FileDefinition> GenerateFileDefinition(AbsolutePath path)
{
2021-09-27 12:42:46 +00:00
2021-12-17 23:40:45 +00:00
var parts = Blocks(path.Size()).ToArray();
2021-10-23 16:51:17 +00:00
var definition = new FileDefinition
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
OriginalFileName = path.FileName,
Size = path.Size(),
Hash = await path.Hash(),
Parts = await parts.PMapAll(async part =>
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
var buffer = new byte[part.Size];
using var job = await _hashLimiter.Begin("Hashing part", part.Size, CancellationToken.None);
await using (var fs = path.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
fs.Position = part.Offset;
await fs.ReadAsync(buffer);
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
part.Hash = await buffer.Hash(job);
return part;
}).ToArray()
};
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
return definition;
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async Task<ModlistMetadata[]> LoadLists(bool includeUnlisted = false)
{
var lists = new[]
{
"https://raw.githubusercontent.com/wabbajack-tools/mod-lists/master/modlists.json",
"https://raw.githubusercontent.com/wabbajack-tools/mod-lists/master/utility_modlists.json",
"https://raw.githubusercontent.com/wabbajack-tools/mod-lists/master/unlisted_modlists.json"
}
.Take(includeUnlisted ? 3 : 2);
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
return await lists.PMapAll(async url =>
await _client.GetFromJsonAsync<ModlistMetadata[]>(_limiter, new HttpRequestMessage(HttpMethod.Get, url),
_dtos.Options)!)
.SelectMany(x => x)
.ToArray();
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public Uri GetPatchUrl(Hash upgradeHash, Hash archiveHash)
{
return new Uri($"{_configuration.PatchBaseAddress}{upgradeHash.ToHex()}_{archiveHash.ToHex()}");
2021-09-27 12:42:46 +00:00
}
2021-12-17 23:40:45 +00:00
public async Task<ValidatedArchive> UploadPatch(ValidatedArchive validated, Stream data)
{
2021-12-17 23:40:45 +00:00
_logger.LogInformation("Uploading Patch {From} {To}", validated.Original.Hash, validated.PatchedFrom!.Hash);
var name = $"{validated.Original.Hash.ToHex()}_{validated.PatchedFrom.Hash.ToHex()}";
var blocks = Blocks(data.Length).ToArray();
foreach (var block in blocks)
{
_logger.LogInformation("Uploading Block {Idx}/{Max}", block.Index, blocks.Length);
data.Position = block.Offset;
var blockData = new byte[block.Size];
await data.ReadAsync(blockData);
var hash = await blockData.Hash();
using var result = await _client.SendAsync(await MakeMessage(HttpMethod.Post,
new Uri($"{_configuration.BuildServerUrl}patches?name={name}&start={block.Offset}"),
new ByteArrayContent(blockData)));
if (!result.IsSuccessStatusCode)
throw new HttpException(result);
var resultHash = Hash.FromHex(await result.Content.ReadAsStringAsync());
if (resultHash != hash)
throw new Exception($"Result Hash does not match expected hash {hash} vs {resultHash}");
}
validated.PatchUrl = new Uri($"https://patches.wabbajack.org/{name}");
return validated;
}
public async Task AddForceHealedPatch(ValidatedArchive validated)
{
var oldData = await GetGithubFile<ValidatedArchive[]>("wabbajack-tools", "mod-lists", "configs/forced_healing.json");
var content = oldData.Content.Append(validated).ToArray();
await UpdateGitHubFile("wabbajack-tools", "mod-lists", "configs/forced_healing.json", content, oldData.Sha);
}
private async Task UpdateGitHubFile<T>(string owner, string repo, string path, T content, string oldSha)
{
2021-12-18 00:14:45 +00:00
var json = _dtos.Serialize(content, writeIndented: true);
var msg = await MakeMessage(HttpMethod.Post,
2021-12-18 00:14:45 +00:00
new Uri($"{_configuration.BuildServerUrl}github/?owner={owner}&repo={repo}&path={path}&oldSha={oldSha}"));
msg.Content = new StringContent(json, Encoding.UTF8, "application/json");
using var result = await _client.SendAsync(msg);
if (!result.IsSuccessStatusCode)
throw new HttpException(result);
}
2021-12-18 16:14:39 +00:00
private async Task<(string Sha, T Content)> GetGithubFile<T>(string owner, string repo, string path, CancellationToken? token = null)
{
2021-12-18 16:14:39 +00:00
token ??= CancellationToken.None;
var msg = await MakeMessage(HttpMethod.Get,
2021-12-18 00:14:45 +00:00
new Uri($"{_configuration.BuildServerUrl}github/?owner={owner}&repo={repo}&path={path}"));
2021-12-18 16:14:39 +00:00
using var oldData = await _client.SendAsync(msg, token.Value);
if (!oldData.IsSuccessStatusCode)
throw new HttpException(oldData);
var sha = oldData.Headers.GetValues(_configuration.ResponseShaHeader).First();
2021-12-18 16:14:39 +00:00
return (sha, (await oldData.Content.ReadFromJsonAsync<T>(_dtos.Options, token.Value))!);
}
2021-12-17 23:40:45 +00:00
public async Task UploadMirror(FileDefinition definition, AbsolutePath file)
{
var hashAsHex = definition.Hash.ToHex();
_logger.LogInformation("Starting upload of {Name} ({Hash})", file.FileName, hashAsHex);
using var result = await _client.SendAsync(await MakeMessage(HttpMethod.Put,
new Uri($"{_configuration.BuildServerUrl}mirrored_files/create/{hashAsHex}"),
new StringContent(_dtos.Serialize(definition), Encoding.UTF8, "application/json")));
if (!result.IsSuccessStatusCode)
throw new HttpException(result);
_logger.LogInformation("Uploading Parts");
await using var dataIn = file.Open(FileMode.Open);
foreach (var (part, idx) in definition.Parts.Select((part, idx) => (part, idx)))
{
_logger.LogInformation("Uploading Part {Part}/{Max}", idx, definition.Parts.Length);
dataIn.Position = part.Offset;
var data = new byte[part.Size];
await dataIn.ReadAsync(data);
using var partResult = await _client.SendAsync(await MakeMessage(HttpMethod.Put,
new Uri($"{_configuration.BuildServerUrl}mirrored_files/{hashAsHex}/part/{idx}"),
new ByteArrayContent(data)));
if (!partResult.IsSuccessStatusCode)
throw new HttpException(result);
}
using var finalResult = await _client.SendAsync(await MakeMessage(HttpMethod.Put,
new Uri($"{_configuration.BuildServerUrl}mirrored_files/{hashAsHex}/finish")));
if (!finalResult.IsSuccessStatusCode)
throw new HttpException(result);
2021-12-18 16:14:39 +00:00
}
2021-12-17 23:40:45 +00:00
2021-12-18 16:14:39 +00:00
public async Task<FileDefinition[]> GetAllMirroredFileDefinitions(CancellationToken token)
{
return (await _client.GetFromJsonAsync<FileDefinition[]>($"{_configuration.BuildServerUrl}mirrored_files",
_dtos.Options, token))!;
}
public async Task<ValidatedArchive[]> GetAllPatches(CancellationToken token)
{
return (await _client.GetFromJsonAsync<ValidatedArchive[]>("https://raw.githubusercontent.com/wabbajack-tools/mod-lists/master/configs/forced_healing.json", _dtos.Options, token))!;
2021-12-17 23:40:45 +00:00
}
2021-12-19 22:20:24 +00:00
public async Task DeleteMirror(Hash hash)
{
_logger.LogInformation("Deleting mirror of {Hash}", hash);
var msg = await MakeMessage(HttpMethod.Delete, new Uri($"{_configuration.BuildServerUrl}mirrored_files/{hash.ToHex()}"));
var result = await _client.SendAsync(msg);
if (!result.IsSuccessStatusCode)
throw new HttpException(result);
}
2021-12-27 05:53:39 +00:00
public (IObservable<(Percent PercentDone, string Message)> Progress, Task<Uri> Task) UploadAuthorFile(AbsolutePath pickerTargetPath)
{
throw new NotImplementedException();
}
2021-09-27 12:42:46 +00:00
}