Simplify HTTP client management

pull/709/head^2
Tyrrrz 3 years ago
parent ea31b1b270
commit acfe102e7f

@ -16,21 +16,10 @@ namespace DiscordChatExporter.Core.Discord
{
public class DiscordClient
{
private readonly HttpClient _httpClient;
private readonly AuthToken _token;
private readonly Uri _baseUri = new("https://discord.com/api/v8/", UriKind.Absolute);
public DiscordClient(HttpClient httpClient, AuthToken token)
{
_httpClient = httpClient;
_token = token;
}
public DiscordClient(AuthToken token)
: this(Http.Client, token)
{
}
public DiscordClient(AuthToken token) => _token = token;
private async ValueTask<HttpResponseMessage> GetResponseAsync(string url) =>
await Http.ResponsePolicy.ExecuteAsync(async () =>
@ -38,7 +27,7 @@ namespace DiscordChatExporter.Core.Discord
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_baseUri, url));
request.Headers.Authorization = _token.GetAuthenticationHeader();
return await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
return await Http.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
});
private async ValueTask<JsonElement> GetJsonResponseAsync(string url)

@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
@ -14,23 +13,18 @@ namespace DiscordChatExporter.Core.Exporting
{
internal partial class MediaDownloader
{
private readonly HttpClient _httpClient;
private readonly string _workingDirPath;
private readonly bool _reuseMedia;
// URL -> Local file path
// File paths of already downloaded media
private readonly Dictionary<string, string> _pathCache = new(StringComparer.Ordinal);
public MediaDownloader(HttpClient httpClient, string workingDirPath, bool reuseMedia)
public MediaDownloader(string workingDirPath, bool reuseMedia)
{
_httpClient = httpClient;
_workingDirPath = workingDirPath;
_reuseMedia = reuseMedia;
}
public MediaDownloader(string workingDirPath, bool reuseMedia)
: this(Http.Client, workingDirPath, reuseMedia) {}
public async ValueTask<string> DownloadAsync(string url)
{
if (_pathCache.TryGetValue(url, out var cachedFilePath))
@ -49,7 +43,7 @@ namespace DiscordChatExporter.Core.Exporting
await Http.ExceptionPolicy.ExecuteAsync(async () =>
{
// Download the file
using var response = await _httpClient.GetAsync(url);
using var response = await Http.Client.GetAsync(url);
await using (var output = File.Create(filePath))
{
await response.Content.CopyToAsync(output);

@ -94,7 +94,8 @@ namespace DiscordChatExporter.Gui.ViewModels
{
_updateService.FinalizeUpdate(true);
RequestClose();
});
}
);
}
catch
{

Loading…
Cancel
Save