Optimize file download

pull/3234/head
2dust 2023-02-09 14:54:54 +08:00
parent 7eb869ab1d
commit ec59249d79
2 changed files with 118 additions and 88 deletions

View File

@ -13,6 +13,62 @@ namespace v2rayN.Base
{ {
} }
public async Task<string> DownloadStringAsync(IWebProxy webProxy, string url, string? userAgent, int timeout)
{
if (string.IsNullOrEmpty(url))
{
return null;
}
var cancellationToken = new CancellationTokenSource();
cancellationToken.CancelAfter(timeout * 1000);
Uri uri = new Uri(url);
//Authorization Header
var headers = new WebHeaderCollection();
if (!Utils.IsNullOrEmpty(uri.UserInfo))
{
headers.Add(HttpRequestHeader.Authorization, "Basic " + Utils.Base64Encode(uri.UserInfo));
}
var downloadOpt = new DownloadConfiguration()
{
Timeout = timeout * 1000,
MaxTryAgainOnFailover = 2,
RequestConfiguration =
{
Headers = headers,
UserAgent = userAgent,
Timeout = timeout * 1000,
Proxy = webProxy
}
};
string text = string.Empty;
using (var downloader = new DownloadService(downloadOpt))
{
downloader.DownloadFileCompleted += (sender, value) =>
{
if (value.Error != null)
{
throw new Exception(string.Format("{0}", value.Error.Message));
}
};
using (var stream = await downloader.DownloadFileTaskAsync(address: url, cancellationToken: cancellationToken.Token))
{
using (StreamReader reader = new StreamReader(stream))
{
text = reader.ReadToEnd();
}
}
}
downloadOpt = null;
return text;
}
public async Task DownloadDataAsync4Speed(IWebProxy webProxy, string url, IProgress<string> progress, int timeout) public async Task DownloadDataAsync4Speed(IWebProxy webProxy, string url, IProgress<string> progress, int timeout)
{ {
if (string.IsNullOrEmpty(url)) if (string.IsNullOrEmpty(url))
@ -38,52 +94,45 @@ namespace v2rayN.Base
int totalSecond = 0; int totalSecond = 0;
var hasValue = false; var hasValue = false;
double maxSpeed = 0; double maxSpeed = 0;
var downloader = new DownloadService(downloadOpt); using (var downloader = new DownloadService(downloadOpt))
//downloader.DownloadStarted += (sender, value) =>
//{
// if (progress != null)
// {
// progress.Report("Start download data...");
// }
//};
downloader.DownloadProgressChanged += (sender, value) =>
{ {
TimeSpan ts = (DateTime.Now - totalDatetime); //downloader.DownloadStarted += (sender, value) =>
if (progress != null && ts.Seconds > totalSecond) //{
// if (progress != null)
// {
// progress.Report("Start download data...");
// }
//};
downloader.DownloadProgressChanged += (sender, value) =>
{ {
hasValue = true; TimeSpan ts = (DateTime.Now - totalDatetime);
totalSecond = ts.Seconds; if (progress != null && ts.Seconds > totalSecond)
if (value.BytesPerSecondSpeed > maxSpeed)
{ {
maxSpeed = value.BytesPerSecondSpeed; hasValue = true;
var speed = (maxSpeed / 1000 / 1000).ToString("#0.0"); totalSecond = ts.Seconds;
progress.Report(speed); if (value.BytesPerSecondSpeed > maxSpeed)
{
maxSpeed = value.BytesPerSecondSpeed;
var speed = (maxSpeed / 1000 / 1000).ToString("#0.0");
progress.Report(speed);
}
} }
} };
}; downloader.DownloadFileCompleted += (sender, value) =>
downloader.DownloadFileCompleted += (sender, value) =>
{
if (progress != null)
{ {
if (!hasValue && value.Error != null) if (progress != null)
{ {
progress.Report(value.Error?.Message); if (!hasValue && value.Error != null)
{
progress.Report(value.Error?.Message);
}
} }
} };
}; progress.Report("......");
progress.Report("......");
await downloader.DownloadFileTaskAsync(address: url, cancellationToken: cancellationToken.Token); await downloader.DownloadFileTaskAsync(address: url, cancellationToken: cancellationToken.Token);
//var stream = await downloader.DownloadFileTaskAsync(url); }
//using (StreamReader reader = new StreamReader(stream))
//{
// string text = reader.ReadToEnd();
// stream.Dispose();
//}
downloader.Dispose();
downloader = null;
downloadOpt = null; downloadOpt = null;
} }
@ -118,39 +167,39 @@ namespace v2rayN.Base
var progressPercentage = 0; var progressPercentage = 0;
var hasValue = false; var hasValue = false;
var downloader = new DownloadService(downloadOpt); using (var downloader = new DownloadService(downloadOpt))
downloader.DownloadStarted += (sender, value) =>
{ {
if (progress != null) downloader.DownloadStarted += (sender, value) =>
{ {
progress.Report(0); if (progress != null)
}
};
downloader.DownloadProgressChanged += (sender, value) =>
{
hasValue = true;
var percent = (int)value.ProgressPercentage;// Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100);
if (progressPercentage != percent && percent % 10 == 0)
{
progressPercentage = percent;
progress.Report(percent);
}
};
downloader.DownloadFileCompleted += (sender, value) =>
{
if (progress != null)
{
if (hasValue && value.Error == null)
{ {
progress.Report(101); progress.Report(0);
} }
} };
}; downloader.DownloadProgressChanged += (sender, value) =>
{
hasValue = true;
var percent = (int)value.ProgressPercentage;// Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100);
if (progressPercentage != percent && percent % 10 == 0)
{
progressPercentage = percent;
progress.Report(percent);
}
};
downloader.DownloadFileCompleted += (sender, value) =>
{
if (progress != null)
{
if (hasValue && value.Error == null)
{
progress.Report(101);
}
}
};
await downloader.DownloadFileTaskAsync(url, fileName, cancellationToken: cancellationToken.Token); await downloader.DownloadFileTaskAsync(url, fileName, cancellationToken: cancellationToken.Token);
}
downloader.Dispose();
downloader = null;
downloadOpt = null; downloadOpt = null;
} }
} }

View File

@ -2,7 +2,6 @@
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets; using System.Net.Sockets;
using v2rayN.Base; using v2rayN.Base;
using v2rayN.Resx; using v2rayN.Resx;
@ -80,7 +79,8 @@ namespace v2rayN.Handler
} }
}; };
_ = DownloaderHelper.Instance.DownloadFileAsync(GetWebProxy(blProxy), var webProxy = GetWebProxy(blProxy);
_ = DownloaderHelper.Instance.DownloadFileAsync(webProxy,
url, url,
Utils.GetTempPath(Utils.GetDownloadFileName(url)), Utils.GetTempPath(Utils.GetDownloadFileName(url)),
progress, progress,
@ -129,28 +129,9 @@ namespace v2rayN.Handler
try try
{ {
Utils.SetSecurityProtocol(LazyConfig.Instance.GetConfig().enableSecurityProtocolTls13); Utils.SetSecurityProtocol(LazyConfig.Instance.GetConfig().enableSecurityProtocolTls13);
var client = new HttpClient(new SocketsHttpHandler()
{
Proxy = GetWebProxy(blProxy)
});
if (Utils.IsNullOrEmpty(userAgent)) var webProxy = GetWebProxy(blProxy);
{ var result = await DownloaderHelper.Instance.DownloadStringAsync(webProxy, url, userAgent, 30);
userAgent = $"{Utils.GetVersion(false)}";
}
client.DefaultRequestHeaders.UserAgent.TryParseAdd(userAgent);
Uri uri = new Uri(url);
//Authorization Header
if (!Utils.IsNullOrEmpty(uri.UserInfo))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Utils.Base64Encode(uri.UserInfo));
}
var cts = new CancellationTokenSource();
cts.CancelAfter(1000 * 30);
var result = await HttpClientHelper.GetInstance().GetAsync(client, url, cts.Token);
return result; return result;
} }
catch (Exception ex) catch (Exception ex)