From 1f20915b4dcfc7555fbe2c4c64d19c8c9fb71881 Mon Sep 17 00:00:00 2001 From: Alexey Golub Date: Sun, 19 Jul 2020 14:19:40 +0300 Subject: [PATCH] Use original file names for downloaded media Closes #327 --- .../Exporting/MediaDownloader.cs | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/DiscordChatExporter.Domain/Exporting/MediaDownloader.cs b/DiscordChatExporter.Domain/Exporting/MediaDownloader.cs index e5a74f8..ee8d718 100644 --- a/DiscordChatExporter.Domain/Exporting/MediaDownloader.cs +++ b/DiscordChatExporter.Domain/Exporting/MediaDownloader.cs @@ -9,38 +9,44 @@ using DiscordChatExporter.Domain.Internal.Extensions; namespace DiscordChatExporter.Domain.Exporting { - internal partial class MediaDownloader + internal class MediaDownloader { private readonly HttpClient _httpClient = Singleton.HttpClient; private readonly string _workingDirPath; - private readonly Dictionary _mediaPathMap = new Dictionary(); + private readonly Dictionary _pathMap = new Dictionary(); public MediaDownloader(string workingDirPath) { _workingDirPath = workingDirPath; } + private string GetRandomSuffix() => Guid.NewGuid().ToString().Replace("-", "").Substring(0, 8); + + private string GetFileNameFromUrl(string url) + { + var originalFileName = Regex.Match(url, @".+/([^?]*)").Groups[1].Value; + + if (string.IsNullOrWhiteSpace(originalFileName)) + return GetRandomSuffix(); + + return $"{Path.GetFileNameWithoutExtension(originalFileName)}-{GetRandomSuffix()}{Path.GetExtension(originalFileName)}"; + } + // HACK: ConfigureAwait() is crucial here to enable sync-over-async in HtmlMessageWriter public async ValueTask DownloadAsync(string url) { - if (_mediaPathMap.TryGetValue(url, out var cachedFilePath)) + if (_pathMap.TryGetValue(url, out var cachedFilePath)) return cachedFilePath; - var extension = Path.GetExtension(GetFileNameFromUrl(url)); - var fileName = $"{Guid.NewGuid()}{extension}"; + var fileName = GetFileNameFromUrl(url); var filePath = Path.Combine(_workingDirPath, fileName); Directory.CreateDirectory(_workingDirPath); await _httpClient.DownloadAsync(url, filePath).ConfigureAwait(false); - return _mediaPathMap[url] = filePath; + return _pathMap[url] = filePath; } } - - internal partial class MediaDownloader - { - private static string GetFileNameFromUrl(string url) => Regex.Match(url, @".+/([^?]*)").Groups[1].Value; - } } \ No newline at end of file