From c6384b59a5d3066235f7c3a86f686ed3a049f8a6 Mon Sep 17 00:00:00 2001 From: Jaex Date: Thu, 25 Aug 2022 07:43:40 +0300 Subject: [PATCH] fixed #6460: Get real file name from web server before download --- ShareX.HelpersLib/Helpers/URLHelpers.cs | 32 +++++++++++++++++++++++++ ShareX/WorkerTask.cs | 10 ++++++++ 2 files changed, 42 insertions(+) diff --git a/ShareX.HelpersLib/Helpers/URLHelpers.cs b/ShareX.HelpersLib/Helpers/URLHelpers.cs index 5964bb7d4..f521da588 100644 --- a/ShareX.HelpersLib/Helpers/URLHelpers.cs +++ b/ShareX.HelpersLib/Helpers/URLHelpers.cs @@ -30,6 +30,7 @@ You should have received a copy of the GNU General Public License using System.Diagnostics; using System.Globalization; using System.Linq; +using System.Net; using System.Security; using System.Text; using System.Text.RegularExpressions; @@ -366,6 +367,37 @@ public static string GetFileName(string path) return path; } + public static string GetFileNameFromWebServer(string url) + { + string fileName = null; + + try + { + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + request.Method = "HEAD"; + request.UserAgent = ShareXResources.UserAgent; + + using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) + { + string contentDisposition = response.Headers["Content-Disposition"]; + + if (!string.IsNullOrEmpty(contentDisposition)) + { + string fileNameMarker = "filename=\""; + int beginIndex = contentDisposition.IndexOf(fileNameMarker, StringComparison.OrdinalIgnoreCase); + contentDisposition = contentDisposition.Substring(beginIndex + fileNameMarker.Length); + int fileNameLength = contentDisposition.IndexOf("\""); + fileName = contentDisposition.Substring(0, fileNameLength); + } + } + } + catch + { + } + + return fileName; + } + public static bool IsFileURL(string url) { int index = url.LastIndexOf('/'); diff --git a/ShareX/WorkerTask.cs b/ShareX/WorkerTask.cs index 371b5a683..2fcd76a0f 100644 --- a/ShareX/WorkerTask.cs +++ b/ShareX/WorkerTask.cs @@ -1052,6 +1052,16 @@ private bool DownloadFromURL(bool upload) string url = Info.Result.URL.Trim(); Info.Result.URL = ""; + if (!Info.TaskSettings.UploadSettings.FileUploadUseNamePattern) + { + string fileName = URLHelpers.GetFileNameFromWebServer(url); + + if (!string.IsNullOrEmpty(fileName)) + { + Info.FileName = FileHelpers.SanitizeFileName(fileName); + } + } + string screenshotsFolder = TaskHelpers.GetScreenshotsFolder(Info.TaskSettings); Info.FilePath = TaskHelpers.HandleExistsFile(screenshotsFolder, Info.FileName, Info.TaskSettings);