Use HttpClient in DownloadStringAsync function

This commit is contained in:
Jaex 2023-10-27 09:41:53 +03:00
parent 8b28b836e4
commit d32a050db7
12 changed files with 92 additions and 95 deletions

View file

@ -31,7 +31,6 @@ You should have received a copy of the GNU General Public License
using System.ComponentModel; using System.ComponentModel;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
namespace ShareX.HelpersLib namespace ShareX.HelpersLib
@ -247,19 +246,16 @@ private async void tsmiImportURL_Click(object sender, EventArgs e)
string json = null; string json = null;
await Task.Run(() => try
{ {
try json = await URLHelpers.DownloadStringAsync(url);
{ }
json = URLHelpers.DownloadString(url); catch (Exception ex)
} {
catch (Exception ex) DebugHelper.WriteException(ex);
{ MessageBox.Show(Resources.Helpers_DownloadString_Download_failed_ + "\r\n" + ex, "ShareX - " + Resources.Error,
DebugHelper.WriteException(ex); MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(Resources.Helpers_DownloadString_Download_failed_ + "\r\n" + ex, "ShareX - " + Resources.Error, }
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
});
OnImportRequested(json); OnImportRequested(json);
OnImportCompleted(); OnImportCompleted();

View file

@ -33,7 +33,6 @@ You should have received a copy of the GNU General Public License
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Cache;
using System.Net.Http; using System.Net.Http;
using System.Net.Sockets; using System.Net.Sockets;
using System.Security; using System.Security;
@ -639,43 +638,37 @@ public static async Task DownloadFileAsync(string url, string filePath)
await Task.Run(() => DownloadFile(url, filePath)); await Task.Run(() => DownloadFile(url, filePath));
} }
public static string DownloadString(string url, bool noCache = true) public static async Task<string> DownloadStringAsync(string url)
{ {
string response = null; string response = null;
if (!string.IsNullOrEmpty(url)) if (!string.IsNullOrEmpty(url))
{ {
using (WebClient wc = new WebClient()) HttpClient client = HttpClientFactory.Create();
{
if (noCache)
{
wc.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
}
wc.Encoding = Encoding.UTF8; using (HttpResponseMessage responseMessage = await client.GetAsync(url))
wc.Headers.Add(HttpRequestHeader.UserAgent, ShareXResources.UserAgent); {
wc.Proxy = HelpersOptions.CurrentProxy.GetWebProxy(); if (responseMessage.IsSuccessStatusCode)
response = wc.DownloadString(url); {
response = await responseMessage.Content.ReadAsStringAsync();
}
} }
} }
return response; return response;
} }
public static async Task<string> DownloadStringAsync(string url, bool noCache = true)
{
return await Task.Run(() => DownloadString(url, noCache));
}
public static async Task<Bitmap> DownloadImageAsync(string url) public static async Task<Bitmap> DownloadImageAsync(string url)
{ {
Bitmap bmp = null;
HttpClient client = HttpClientFactory.Create(); HttpClient client = HttpClientFactory.Create();
using (HttpResponseMessage response = await client.GetAsync(url)) using (HttpResponseMessage responseMessage = await client.GetAsync(url))
{ {
if (response.IsSuccessStatusCode && response.Content.Headers.ContentType != null) if (responseMessage.IsSuccessStatusCode && responseMessage.Content.Headers.ContentType != null)
{ {
string mediaType = response.Content.Headers.ContentType.MediaType; string mediaType = responseMessage.Content.Headers.ContentType.MediaType;
string[] supportedImageTypes = new string[] string[] supportedImageTypes = new string[]
{ {
@ -688,12 +681,12 @@ public static async Task<Bitmap> DownloadImageAsync(string url)
if (supportedImageTypes.Contains(mediaType, StringComparer.OrdinalIgnoreCase)) if (supportedImageTypes.Contains(mediaType, StringComparer.OrdinalIgnoreCase))
{ {
byte[] data = await response.Content.ReadAsByteArrayAsync(); byte[] data = await responseMessage.Content.ReadAsByteArrayAsync();
MemoryStream ms = new MemoryStream(data); MemoryStream ms = new MemoryStream(data);
try try
{ {
return new Bitmap(ms); bmp = new Bitmap(ms);
} }
catch catch
{ {
@ -703,7 +696,7 @@ public static async Task<Bitmap> DownloadImageAsync(string url)
} }
} }
return null; return bmp;
} }
public static int GetRandomUnusedPort() public static int GetRandomUnusedPort()

View file

@ -24,6 +24,7 @@ You should have received a copy of the GNU General Public License
#endregion License Information (GPL v3) #endregion License Information (GPL v3)
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers;
namespace ShareX.HelpersLib namespace ShareX.HelpersLib
{ {
@ -41,7 +42,11 @@ public static HttpClient Create()
}; };
client = new HttpClient(clientHandler); client = new HttpClient(clientHandler);
client.DefaultRequestHeaders.Add("User-Agent", ShareXResources.UserAgent); client.DefaultRequestHeaders.UserAgent.ParseAdd(ShareXResources.UserAgent);
client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue()
{
NoCache = true
};
} }
return client; return client;

View file

@ -24,6 +24,7 @@ You should have received a copy of the GNU General Public License
#endregion License Information (GPL v3) #endregion License Information (GPL v3)
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Threading.Tasks;
namespace ShareX.HelpersLib namespace ShareX.HelpersLib
{ {
@ -34,10 +35,10 @@ public class AppVeyor
private const string APIURL = "https://ci.appveyor.com/api"; private const string APIURL = "https://ci.appveyor.com/api";
public AppVeyorProject GetProjectByBranch(string branch = "master") public async Task<AppVeyorProject> GetProjectByBranch(string branch = "master")
{ {
string url = $"{APIURL}/projects/{AccountName}/{ProjectSlug}/branch/{branch}"; string url = $"{APIURL}/projects/{AccountName}/{ProjectSlug}/branch/{branch}";
string response = URLHelpers.DownloadString(url); string response = await URLHelpers.DownloadStringAsync(url);
if (!string.IsNullOrEmpty(response)) if (!string.IsNullOrEmpty(response))
{ {
@ -47,10 +48,10 @@ public AppVeyorProject GetProjectByBranch(string branch = "master")
return null; return null;
} }
public AppVeyorProjectArtifact[] GetArtifacts(string jobId) public async Task<AppVeyorProjectArtifact[]> GetArtifacts(string jobId)
{ {
string url = $"{APIURL}/buildjobs/{jobId}/artifacts"; string url = $"{APIURL}/buildjobs/{jobId}/artifacts";
string response = URLHelpers.DownloadString(url); string response = await URLHelpers.DownloadStringAsync(url);
if (!string.IsNullOrEmpty(response)) if (!string.IsNullOrEmpty(response))
{ {

View file

@ -25,6 +25,7 @@ You should have received a copy of the GNU General Public License
using System; using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace ShareX.HelpersLib namespace ShareX.HelpersLib
{ {
@ -32,7 +33,7 @@ public class AppVeyorUpdateChecker : UpdateChecker
{ {
public string Branch { get; set; } = "master"; public string Branch { get; set; } = "master";
public override void CheckUpdate() public override async Task CheckUpdateAsync()
{ {
try try
{ {
@ -42,7 +43,7 @@ public override void CheckUpdate()
ProjectSlug = "sharex" ProjectSlug = "sharex"
}; };
AppVeyorProject project = appveyor.GetProjectByBranch(Branch); AppVeyorProject project = await appveyor.GetProjectByBranch(Branch);
if (!project.build.status.Equals("success", StringComparison.OrdinalIgnoreCase) && if (!project.build.status.Equals("success", StringComparison.OrdinalIgnoreCase) &&
!project.build.status.Equals("running", StringComparison.OrdinalIgnoreCase)) !project.build.status.Equals("running", StringComparison.OrdinalIgnoreCase))
@ -60,7 +61,7 @@ public override void CheckUpdate()
throw new Exception("Unable to find successful release build."); throw new Exception("Unable to find successful release build.");
} }
AppVeyorProjectArtifact[] artifacts = appveyor.GetArtifacts(job.jobId); AppVeyorProjectArtifact[] artifacts = await appveyor.GetArtifacts(job.jobId);
string deploymentName; string deploymentName;

View file

@ -26,6 +26,7 @@ You should have received a copy of the GNU General Public License
using Newtonsoft.Json; using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
namespace ShareX.HelpersLib namespace ShareX.HelpersLib
{ {
@ -47,11 +48,11 @@ public GitHubUpdateChecker(string owner, string repo)
Repo = repo; Repo = repo;
} }
public override void CheckUpdate() public override async Task CheckUpdateAsync()
{ {
try try
{ {
GitHubRelease latestRelease = GetLatestRelease(IncludePreRelease); GitHubRelease latestRelease = await GetLatestRelease(IncludePreRelease);
if (UpdateReleaseInfo(latestRelease, IsPortable, IsPortable)) if (UpdateReleaseInfo(latestRelease, IsPortable, IsPortable))
{ {
@ -67,11 +68,11 @@ public override void CheckUpdate()
Status = UpdateStatus.UpdateCheckFailed; Status = UpdateStatus.UpdateCheckFailed;
} }
public virtual string GetLatestDownloadURL(bool isBrowserDownloadURL) public virtual async Task<string> GetLatestDownloadURL(bool isBrowserDownloadURL)
{ {
try try
{ {
GitHubRelease latestRelease = GetLatestRelease(IncludePreRelease); GitHubRelease latestRelease = await GetLatestRelease(IncludePreRelease);
if (UpdateReleaseInfo(latestRelease, IsPortable, isBrowserDownloadURL)) if (UpdateReleaseInfo(latestRelease, IsPortable, isBrowserDownloadURL))
{ {
@ -86,11 +87,11 @@ public virtual string GetLatestDownloadURL(bool isBrowserDownloadURL)
return null; return null;
} }
protected List<GitHubRelease> GetReleases() protected async Task<List<GitHubRelease>> GetReleases()
{ {
List<GitHubRelease> releases = null; List<GitHubRelease> releases = null;
string response = URLHelpers.DownloadString(ReleasesURL); string response = await URLHelpers.DownloadStringAsync(ReleasesURL);
if (!string.IsNullOrEmpty(response)) if (!string.IsNullOrEmpty(response))
{ {
@ -105,11 +106,11 @@ protected List<GitHubRelease> GetReleases()
return releases; return releases;
} }
protected GitHubRelease GetLatestRelease() protected async Task<GitHubRelease> GetLatestRelease()
{ {
GitHubRelease latestRelease = null; GitHubRelease latestRelease = null;
string response = URLHelpers.DownloadString(LatestReleaseURL); string response = await URLHelpers.DownloadStringAsync(LatestReleaseURL);
if (!string.IsNullOrEmpty(response)) if (!string.IsNullOrEmpty(response))
{ {
@ -119,13 +120,13 @@ protected GitHubRelease GetLatestRelease()
return latestRelease; return latestRelease;
} }
protected GitHubRelease GetLatestRelease(bool includePreRelease) protected async Task<GitHubRelease> GetLatestRelease(bool includePreRelease)
{ {
GitHubRelease latestRelease = null; GitHubRelease latestRelease = null;
if (includePreRelease) if (includePreRelease)
{ {
List<GitHubRelease> releases = GetReleases(); List<GitHubRelease> releases = await GetReleases();
if (releases != null && releases.Count > 0) if (releases != null && releases.Count > 0)
{ {
@ -134,7 +135,7 @@ protected GitHubRelease GetLatestRelease(bool includePreRelease)
} }
else else
{ {
latestRelease = GetLatestRelease(); latestRelease = await GetLatestRelease();
} }
return latestRelease; return latestRelease;

View file

@ -24,6 +24,7 @@ You should have received a copy of the GNU General Public License
#endregion License Information (GPL v3) #endregion License Information (GPL v3)
using System; using System;
using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Timer = System.Threading.Timer; using Timer = System.Threading.Timer;
@ -58,7 +59,7 @@ public void ConfigureAutoUpdate()
{ {
if (updateTimer == null) if (updateTimer == null)
{ {
updateTimer = new Timer(state => CheckUpdate(), null, TimeSpan.Zero, UpdateCheckInterval); updateTimer = new Timer(TimerCallback, null, TimeSpan.Zero, UpdateCheckInterval);
} }
} }
else else
@ -68,12 +69,17 @@ public void ConfigureAutoUpdate()
} }
} }
private void CheckUpdate() private async void TimerCallback(object state)
{
await CheckUpdate();
}
private async Task CheckUpdate()
{ {
if (AutoUpdateEnabled && !UpdateMessageBox.IsOpen) if (AutoUpdateEnabled && !UpdateMessageBox.IsOpen)
{ {
UpdateChecker updateChecker = CreateUpdateChecker(); UpdateChecker updateChecker = CreateUpdateChecker();
updateChecker.CheckUpdate(); await updateChecker.CheckUpdateAsync();
if (UpdateMessageBox.Start(updateChecker, firstUpdateCheck) == DialogResult.No) if (UpdateMessageBox.Start(updateChecker, firstUpdateCheck) == DialogResult.No)
{ {

View file

@ -81,12 +81,7 @@ public void RefreshStatus()
} }
} }
public abstract void CheckUpdate(); public abstract Task CheckUpdateAsync();
public Task CheckUpdateAsync()
{
return Task.Run(CheckUpdate);
}
public void DownloadUpdate() public void DownloadUpdate()
{ {

View file

@ -25,6 +25,7 @@ You should have received a copy of the GNU General Public License
using System; using System;
using System.IO; using System.IO;
using System.Threading.Tasks;
using System.Xml; using System.Xml;
using System.Xml.Linq; using System.Xml.Linq;
@ -41,11 +42,11 @@ public XMLUpdateChecker(string url, string applicationName)
ApplicationName = applicationName; ApplicationName = applicationName;
} }
public override void CheckUpdate() public override async Task CheckUpdateAsync()
{ {
try try
{ {
string response = URLHelpers.DownloadString(URL); string response = await URLHelpers.DownloadStringAsync(URL);
using (StringReader sr = new StringReader(response)) using (StringReader sr = new StringReader(response))
using (XmlTextReader xml = new XmlTextReader(sr)) using (XmlTextReader xml = new XmlTextReader(sr))

View file

@ -25,16 +25,17 @@ You should have received a copy of the GNU General Public License
using ShareX.HelpersLib; using ShareX.HelpersLib;
using System; using System;
using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
namespace ShareX.MediaLib namespace ShareX.MediaLib
{ {
public static class FFmpegGitHubDownloader public static class FFmpegGitHubDownloader
{ {
public static DialogResult DownloadFFmpeg(bool async, DownloaderForm.DownloaderInstallEventHandler installRequested) public static async Task<DialogResult> DownloadFFmpeg(bool async, DownloaderForm.DownloaderInstallEventHandler installRequested)
{ {
FFmpegUpdateChecker updateChecker = new FFmpegUpdateChecker("ShareX", "FFmpeg"); FFmpegUpdateChecker updateChecker = new FFmpegUpdateChecker("ShareX", "FFmpeg");
string url = updateChecker.GetLatestDownloadURL(true); string url = await updateChecker.GetLatestDownloadURL(true);
using (DownloaderForm form = new DownloaderForm(url, "ffmpeg.zip")) using (DownloaderForm form = new DownloaderForm(url, "ffmpeg.zip"))
{ {

View file

@ -73,35 +73,31 @@ public void UpdateTheme()
} }
} }
public void Start() public async Task Start()
{ {
Task.Run(() => NewsManager = new NewsManager();
//NewsManager.LastReadDate = Program.Settings.NewsLastReadDate;
await NewsManager.UpdateNews();
NewsManager.UpdateUnread();
if (NewsManager != null && NewsManager.NewsItems != null)
{ {
NewsManager = new NewsManager(); SuspendLayout();
//NewsManager.LastReadDate = Program.Settings.NewsLastReadDate;
NewsManager.UpdateNews(); foreach (NewsItem item in NewsManager.NewsItems)
NewsManager.UpdateUnread();
}).ContinueInCurrentContext(() =>
{
if (NewsManager != null && NewsManager.NewsItems != null)
{ {
SuspendLayout(); if (item != null)
foreach (NewsItem item in NewsManager.NewsItems)
{ {
if (item != null) AddNewsItem(item);
{
AddNewsItem(item);
}
} }
UpdateUnreadStatus();
ResumeLayout();
OnNewsLoaded();
} }
});
UpdateUnreadStatus();
ResumeLayout();
OnNewsLoaded();
}
} }
protected void OnNewsLoaded() protected void OnNewsLoaded()

View file

@ -29,6 +29,7 @@ You should have received a copy of the GNU General Public License
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace ShareX namespace ShareX
{ {
@ -39,11 +40,11 @@ public class NewsManager
public bool IsUnread => UnreadCount > 0; public bool IsUnread => UnreadCount > 0;
public int UnreadCount => NewsItems != null ? NewsItems.Count(x => x.IsUnread) : 0; public int UnreadCount => NewsItems != null ? NewsItems.Count(x => x.IsUnread) : 0;
public void UpdateNews() public async Task UpdateNews()
{ {
try try
{ {
NewsItems = GetNews(); NewsItems = await GetNews();
} }
catch (Exception e) catch (Exception e)
{ {
@ -62,10 +63,10 @@ public void UpdateUnread()
} }
} }
private List<NewsItem> GetNews() private async Task<List<NewsItem>> GetNews()
{ {
string url = URLHelpers.CombineURL(Links.Website, "news.json"); string url = URLHelpers.CombineURL(Links.Website, "news.json");
string response = URLHelpers.DownloadString(url); string response = await URLHelpers.DownloadStringAsync(url);
if (!string.IsNullOrEmpty(response)) if (!string.IsNullOrEmpty(response))
{ {