2021-09-27 12:42:46 +00:00
|
|
|
using System;
|
|
|
|
using System.Buffers;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Linq;
|
|
|
|
using System.Net.Http;
|
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using Wabbajack.RateLimiter;
|
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
namespace Wabbajack.Networking.Http;
|
|
|
|
|
|
|
|
public static class HttpClientExtensions
|
2021-09-27 12:42:46 +00:00
|
|
|
{
|
2021-10-23 16:51:17 +00:00
|
|
|
public static IEnumerable<(string Key, string Value)> GetSetCookies(this HttpResponseMessage response)
|
2021-09-27 12:42:46 +00:00
|
|
|
{
|
2021-10-23 16:51:17 +00:00
|
|
|
if (!response.Headers.TryGetValues("set-cookie", out var values))
|
|
|
|
return Array.Empty<(string, string)>();
|
2021-09-27 12:42:46 +00:00
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
return values
|
|
|
|
.SelectMany(h => h.Split(";"))
|
|
|
|
.Select(h => h.Split("="))
|
|
|
|
.Where(h => h.Length == 2)
|
|
|
|
.Select(h => (h[0], h[1]));
|
|
|
|
}
|
2021-09-27 12:42:46 +00:00
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
public static async Task<IMemoryOwner<byte>> ReadAsByteArrayAsync(this HttpContent content, IJob job,
|
|
|
|
CancellationToken token)
|
|
|
|
{
|
|
|
|
await using var stream = await content.ReadAsStreamAsync(token);
|
|
|
|
var memory = MemoryPool<byte>.Shared.Rent((int) job.Size);
|
2021-09-27 12:42:46 +00:00
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
while (job.Current < job.Size)
|
|
|
|
{
|
|
|
|
var read = await stream.ReadAsync(memory.Memory[(int) job.Current..(int) job.Size], token);
|
|
|
|
await job.Report(read, token);
|
|
|
|
}
|
2021-09-27 12:42:46 +00:00
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
if (job.Current != job.Size)
|
|
|
|
throw new Exception("Overread error");
|
2021-09-27 12:42:46 +00:00
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
return memory;
|
2021-09-27 12:42:46 +00:00
|
|
|
}
|
|
|
|
}
|