From 8d86aa2b72686d2dad4e3e8f46efcae157a5d157 Mon Sep 17 00:00:00 2001 From: 2dust <31833384+2dust@users.noreply.github.com> Date: Mon, 3 Nov 2025 19:41:02 +0800 Subject: [PATCH] Refactor ping and HTTP helpers, update usages Moved GetRealPingTime from HttpClientHelper to ConnectionHandler and refactored related methods for clarity. Removed unused and redundant HTTP helper methods. Updated DownloadService and SpeedtestService to use the new method signatures. Simplified UpdateService constructor using primary constructor syntax. --- .../ServiceLib/Handler/ConnectionHandler.cs | 36 +++- v2rayN/ServiceLib/Helper/HttpClientHelper.cs | 162 +----------------- v2rayN/ServiceLib/Services/DownloadService.cs | 4 +- .../ServiceLib/Services/SpeedtestService.cs | 2 +- v2rayN/ServiceLib/Services/UpdateService.cs | 12 +- 5 files changed, 41 insertions(+), 175 deletions(-) diff --git a/v2rayN/ServiceLib/Handler/ConnectionHandler.cs b/v2rayN/ServiceLib/Handler/ConnectionHandler.cs index ae3268ea..05825d93 100644 --- a/v2rayN/ServiceLib/Handler/ConnectionHandler.cs +++ b/v2rayN/ServiceLib/Handler/ConnectionHandler.cs @@ -6,7 +6,7 @@ public static class ConnectionHandler public static async Task RunAvailabilityCheck() { - var time = await GetRealPingTime(); + var time = await GetRealPingTimeInfo(); var ip = time > 0 ? await GetIPInfo() ?? Global.None : Global.None; return string.Format(ResUI.TestMeOutput, time, ip); @@ -39,7 +39,7 @@ public static class ConnectionHandler return $"({country ?? "unknown"}) {ip}"; } - private static async Task GetRealPingTime() + private static async Task GetRealPingTimeInfo() { var responseTime = -1; try @@ -50,7 +50,7 @@ public static class ConnectionHandler for (var i = 0; i < 2; i++) { - responseTime = await HttpClientHelper.Instance.GetRealPingTime(url, webProxy, 10); + responseTime = await GetRealPingTime(url, webProxy, 10); if (responseTime > 0) { break; @@ -65,4 +65,34 @@ public static class ConnectionHandler } return responseTime; } + + public static async Task GetRealPingTime(string url, IWebProxy? webProxy, int downloadTimeout) + { + var responseTime = -1; + try + { + using var cts = new CancellationTokenSource(); + cts.CancelAfter(TimeSpan.FromSeconds(downloadTimeout)); + using var client = new HttpClient(new SocketsHttpHandler() + { + Proxy = webProxy, + UseProxy = webProxy != null + }); + + List oneTime = new(); + for (var i = 0; i < 2; i++) + { + var timer = Stopwatch.StartNew(); + await client.GetAsync(url, cts.Token).ConfigureAwait(false); + timer.Stop(); + oneTime.Add((int)timer.Elapsed.TotalMilliseconds); + await Task.Delay(100); + } + responseTime = oneTime.Where(x => x > 0).OrderBy(x => x).FirstOrDefault(); + } + catch + { + } + return responseTime; + } } diff --git a/v2rayN/ServiceLib/Helper/HttpClientHelper.cs b/v2rayN/ServiceLib/Helper/HttpClientHelper.cs index cd971a89..0c9bd470 100644 --- a/v2rayN/ServiceLib/Helper/HttpClientHelper.cs +++ b/v2rayN/ServiceLib/Helper/HttpClientHelper.cs @@ -48,15 +48,7 @@ public class HttpClientHelper } return await httpClient.GetStringAsync(url); } - - public async Task GetAsync(HttpClient client, string url, CancellationToken token = default) - { - if (url.IsNullOrEmpty()) - { - return null; - } - return await client.GetStringAsync(url, token); - } + public async Task PutAsync(string url, Dictionary headers) { @@ -81,155 +73,5 @@ public class HttpClientHelper await httpClient.DeleteAsync(url); } - public static async Task DownloadFileAsync(HttpClient client, string url, string fileName, IProgress? progress, CancellationToken token = default) - { - ArgumentNullException.ThrowIfNull(url); - ArgumentNullException.ThrowIfNull(fileName); - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); - - if (!response.IsSuccessStatusCode) - { - throw new Exception(response.StatusCode.ToString()); - } - - var total = response.Content.Headers.ContentLength ?? -1L; - var canReportProgress = total != -1 && progress != null; - - await using var stream = await response.Content.ReadAsStreamAsync(token); - await using var file = File.Create(fileName); - var totalRead = 0L; - var buffer = new byte[1024 * 1024]; - var progressPercentage = 0; - - while (true) - { - token.ThrowIfCancellationRequested(); - - var read = await stream.ReadAsync(buffer, token); - totalRead += read; - - if (read == 0) - { - break; - } - await file.WriteAsync(buffer.AsMemory(0, read), token); - - if (canReportProgress) - { - var percent = (int)(100.0 * totalRead / total); - //if (progressPercentage != percent && percent % 10 == 0) - { - progressPercentage = percent; - progress?.Report(percent); - } - } - } - if (canReportProgress) - { - progress?.Report(101); - } - } - - public async Task DownloadDataAsync4Speed(HttpClient client, string url, IProgress progress, CancellationToken token = default) - { - if (url.IsNullOrEmpty()) - { - throw new ArgumentNullException(nameof(url)); - } - - var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); - - if (!response.IsSuccessStatusCode) - { - throw new Exception(response.StatusCode.ToString()); - } - - //var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L; - //var canReportProgress = total != -1 && progress != null; - - await using var stream = await response.Content.ReadAsStreamAsync(token); - var totalRead = 0L; - var buffer = new byte[1024 * 64]; - var isMoreToRead = true; - var progressSpeed = string.Empty; - var totalDatetime = DateTime.Now; - var totalSecond = 0; - - do - { - if (token.IsCancellationRequested) - { - if (totalRead > 0) - { - return; - } - else - { - token.ThrowIfCancellationRequested(); - } - } - - var read = await stream.ReadAsync(buffer, token); - - if (read == 0) - { - isMoreToRead = false; - } - else - { - var data = new byte[read]; - buffer.ToList().CopyTo(0, data, 0, read); - - totalRead += read; - - var ts = DateTime.Now - totalDatetime; - if (progress != null && ts.Seconds > totalSecond) - { - totalSecond = ts.Seconds; - var speed = (totalRead * 1d / ts.TotalMilliseconds / 1000).ToString("#0.0"); - if (progressSpeed != speed) - { - progressSpeed = speed; - progress.Report(speed); - } - } - } - } while (isMoreToRead); - } - - public async Task GetRealPingTime(string url, IWebProxy? webProxy, int downloadTimeout) - { - var responseTime = -1; - try - { - using var cts = new CancellationTokenSource(); - cts.CancelAfter(TimeSpan.FromSeconds(downloadTimeout)); - using var client = new HttpClient(new SocketsHttpHandler() - { - Proxy = webProxy, - UseProxy = webProxy != null - }); - - List oneTime = new(); - for (var i = 0; i < 2; i++) - { - var timer = Stopwatch.StartNew(); - await client.GetAsync(url, cts.Token).ConfigureAwait(false); - timer.Stop(); - oneTime.Add((int)timer.Elapsed.TotalMilliseconds); - await Task.Delay(100); - } - responseTime = oneTime.Where(x => x > 0).OrderBy(x => x).FirstOrDefault(); - } - catch //(Exception ex) - { - //Utile.SaveLog(ex.Message, ex); - } - return responseTime; - } + } diff --git a/v2rayN/ServiceLib/Services/DownloadService.cs b/v2rayN/ServiceLib/Services/DownloadService.cs index d4122964..fe0da3d6 100644 --- a/v2rayN/ServiceLib/Services/DownloadService.cs +++ b/v2rayN/ServiceLib/Services/DownloadService.cs @@ -71,7 +71,7 @@ public class DownloadService AllowAutoRedirect = false, Proxy = await GetWebProxy(blProxy) }; - HttpClient client = new(webRequestHandler); + var client = new HttpClient(webRequestHandler); var response = await client.GetAsync(url); if (response.StatusCode == HttpStatusCode.Redirect && response.Headers.Location is not null) @@ -156,7 +156,7 @@ public class DownloadService } using var cts = new CancellationTokenSource(); - var result = await HttpClientHelper.Instance.GetAsync(client, url, cts.Token).WaitAsync(TimeSpan.FromSeconds(timeout), cts.Token); + var result = await client.GetStringAsync(url, cts.Token).WaitAsync(TimeSpan.FromSeconds(timeout), cts.Token); return result; } catch (Exception ex) diff --git a/v2rayN/ServiceLib/Services/SpeedtestService.cs b/v2rayN/ServiceLib/Services/SpeedtestService.cs index 3cb5c2b6..600ba4d1 100644 --- a/v2rayN/ServiceLib/Services/SpeedtestService.cs +++ b/v2rayN/ServiceLib/Services/SpeedtestService.cs @@ -272,7 +272,7 @@ public class SpeedtestService(Config config, Func updateF private async Task DoRealPing(ServerTestItem it) { var webProxy = new WebProxy($"socks5://{Global.Loopback}:{it.Port}"); - var responseTime = await HttpClientHelper.Instance.GetRealPingTime(_config.SpeedTestItem.SpeedPingTestUrl, webProxy, 10); + var responseTime = await ConnectionHandler.GetRealPingTime(_config.SpeedTestItem.SpeedPingTestUrl, webProxy, 10); ProfileExManager.Instance.SetTestDelay(it.IndexId, responseTime); await UpdateFunc(it.IndexId, responseTime.ToString()); diff --git a/v2rayN/ServiceLib/Services/UpdateService.cs b/v2rayN/ServiceLib/Services/UpdateService.cs index f14f0a70..b5129fc7 100644 --- a/v2rayN/ServiceLib/Services/UpdateService.cs +++ b/v2rayN/ServiceLib/Services/UpdateService.cs @@ -1,18 +1,12 @@ namespace ServiceLib.Services; -public class UpdateService +public class UpdateService(Config config, Func updateFunc) { - private readonly Config? _config; - private readonly Func? _updateFunc; + private readonly Config? _config = config; + private readonly Func? _updateFunc = updateFunc; private readonly int _timeout = 30; private static readonly string _tag = "UpdateService"; - public UpdateService(Config config, Func updateFunc) - { - _config = config; - _updateFunc = updateFunc; - } - public async Task CheckUpdateGuiN(bool preRelease) { var url = string.Empty;