Refactor last PR

pull/466/head
Tyrrrz 4 years ago
parent 69acb5bf76
commit 3861dba60c

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
@ -42,12 +43,31 @@ namespace DiscordChatExporter.Domain.Exporting
if (_reuseMedia && File.Exists(filePath))
return _pathCache[url] = filePath;
// Download it
Directory.CreateDirectory(_workingDirPath);
// This catches IOExceptions which is dangerous as we're working also with files
await Http.ExceptionPolicy.ExecuteAsync(async () =>
{
// This catches IOExceptions which is dangerous as we're working also with files
await _httpClient.DownloadAsync(url, filePath);
// Download the file
using var response = await _httpClient.GetAsync(url);
await using (var output = File.Create(filePath))
{
await response.Content.CopyToAsync(output);
}
// Try to set the file date according to the last-modified header
var lastModified = response.Content.Headers.TryGetValue("Last-Modified")?.Pipe(s =>
DateTimeOffset.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
? date
: (DateTimeOffset?) null
);
if (lastModified != null)
{
File.SetCreationTimeUtc(filePath, lastModified.Value.UtcDateTime);
File.SetLastWriteTimeUtc(filePath, lastModified.Value.UtcDateTime);
File.SetLastAccessTimeUtc(filePath, lastModified.Value.UtcDateTime);
}
});
return _pathCache[url] = filePath;

@ -1,27 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace DiscordChatExporter.Domain.Internal.Extensions
{
internal static class HttpClientExtensions
{
public static async ValueTask DownloadAsync(this HttpClient httpClient, string uri, string outputFilePath)
{
using var response = await httpClient.GetAsync(uri);
var output = File.Create(outputFilePath);
await response.Content.CopyToAsync(output);
IEnumerable<string> lastModifiedHeaderValues;
if (response.Content.Headers.TryGetValues("Last-Modified", out lastModifiedHeaderValues))
{
await output.DisposeAsync();
File.SetLastWriteTime(outputFilePath, DateTime.Parse(lastModifiedHeaderValues.First()));
}
}
}
}

@ -0,0 +1,12 @@
using System.Net.Http.Headers;
namespace DiscordChatExporter.Domain.Internal.Extensions
{
internal static class HttpExtensions
{
public static string? TryGetValue(this HttpContentHeaders headers, string name) =>
headers.TryGetValues(name, out var values)
? string.Concat(values)
: null;
}
}
Loading…
Cancel
Save