From 2147d12ac85e5c8d29c2e56fe9d24cea0704b976 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E4=BB=99=E5=A5=B3?= Date: Mon, 20 Feb 2023 18:16:30 +0800 Subject: [PATCH] update --- v2rayN/v2rayN/Base/DownloaderHelper.cs | 6 +- v2rayN/v2rayN/Base/HttpClientHelper.cs | 130 ++++++------------ v2rayN/v2rayN/Base/StringEx.cs | 7 +- v2rayN/v2rayN/Handler/ConfigHandler.cs | 15 +- v2rayN/v2rayN/Handler/CoreConfigHandler.cs | 91 +++++------- v2rayN/v2rayN/Handler/DownloadHandle.cs | 46 ++----- v2rayN/v2rayN/Handler/LazyConfig.cs | 6 +- v2rayN/v2rayN/Handler/SpeedtestHandler.cs | 2 +- v2rayN/v2rayN/Tool/Utils.cs | 37 ++--- .../ViewModels/OptionSettingViewModel.cs | 4 +- v2rayN/v2rayUpgrade/MainForm.cs | 2 +- 11 files changed, 123 insertions(+), 223 deletions(-) diff --git a/v2rayN/v2rayN/Base/DownloaderHelper.cs b/v2rayN/v2rayN/Base/DownloaderHelper.cs index d457dcba..c7357506 100644 --- a/v2rayN/v2rayN/Base/DownloaderHelper.cs +++ b/v2rayN/v2rayN/Base/DownloaderHelper.cs @@ -9,7 +9,7 @@ namespace v2rayN.Base private static readonly Lazy _instance = new(() => new()); public static DownloaderHelper Instance => _instance.Value; - public async Task DownloadStringAsync(IWebProxy webProxy, string url, string? userAgent, int timeout) + public async Task DownloadStringAsync(IWebProxy? webProxy, string url, string? userAgent, int timeout) { if (string.IsNullOrEmpty(url)) { @@ -45,7 +45,7 @@ namespace v2rayN.Base { if (value.Error != null) { - throw new Exception(string.Format("{0}", value.Error.Message)); + throw value.Error; } }; using var stream = await downloader.DownloadFileTaskAsync(address: url, cancellationToken: cancellationToken.Token); @@ -122,7 +122,7 @@ namespace v2rayN.Base downloadOpt = null; } - public async Task DownloadFileAsync(IWebProxy webProxy, string url, string fileName, IProgress progress, int timeout) + public async Task DownloadFileAsync(IWebProxy? webProxy, string url, string fileName, IProgress progress, int timeout) { if (string.IsNullOrEmpty(url)) { diff --git a/v2rayN/v2rayN/Base/HttpClientHelper.cs b/v2rayN/v2rayN/Base/HttpClientHelper.cs index 04139c76..e40d948e 100644 --- a/v2rayN/v2rayN/Base/HttpClientHelper.cs +++ b/v2rayN/v2rayN/Base/HttpClientHelper.cs @@ -1,6 +1,8 @@ using System.IO; using System.Net.Http; using System.Net.Http.Headers; +using System.Net.Mime; +using System.Text; namespace v2rayN.Base { @@ -8,86 +10,46 @@ namespace v2rayN.Base /// public class HttpClientHelper { - private static HttpClientHelper httpClientHelper = null; - private HttpClient httpClient; - - /// - /// - private HttpClientHelper() { } - - /// - /// - /// - public static HttpClientHelper GetInstance() + private readonly static Lazy _instance = new(() => { - if (httpClientHelper != null) - { - return httpClientHelper; - } - else - { - HttpClientHelper httpClientHelper = new(); + HttpClientHandler handler = new() { UseCookies = false }; + HttpClientHelper helper = new(new HttpClient(handler)); + return helper; + }); + public static HttpClientHelper Instance => _instance.Value; + private readonly HttpClient httpClient; + + private HttpClientHelper(HttpClient httpClient) => this.httpClient = httpClient; - HttpClientHandler handler = new() { UseCookies = false }; - httpClientHelper.httpClient = new HttpClient(handler); - return httpClientHelper; - } - } public async Task GetAsync(string url) { - if (string.IsNullOrEmpty(url)) - { - return null; - } - HttpResponseMessage response = await httpClient.GetAsync(url); - - return await response.Content.ReadAsStringAsync(); + if (string.IsNullOrEmpty(url)) return null; + return await httpClient.GetStringAsync(url); } - public async Task GetAsync(HttpClient client, string url, CancellationToken token) + + public async Task GetAsync(HttpClient client, string url, CancellationToken token = default) { - if (string.IsNullOrEmpty(url)) - { - return null; - } - HttpResponseMessage response = await client.GetAsync(url, token); - if (!response.IsSuccessStatusCode) - { - throw new Exception(string.Format("{0}", response.StatusCode)); - } - return await response.Content.ReadAsStringAsync(token); + if (string.IsNullOrWhiteSpace(url)) return null; + return await client.GetStringAsync(url, token); } public async Task PutAsync(string url, Dictionary headers) { - var myContent = Utils.ToJson(headers); - var buffer = System.Text.Encoding.UTF8.GetBytes(myContent); - var byteContent = new ByteArrayContent(buffer); - byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + var jsonContent = Utils.ToJson(headers); + var content = new StringContent(jsonContent, Encoding.UTF8, MediaTypeNames.Application.Json); - var result = await httpClient.PutAsync(url, byteContent); + var result = await httpClient.PutAsync(url, content); } - public async Task DownloadFileAsync(HttpClient client, string url, string fileName, IProgress progress, CancellationToken token) + public static async Task DownloadFileAsync(HttpClient client, string url, string fileName, IProgress? progress, CancellationToken token = default) { - if (string.IsNullOrEmpty(url)) - { - throw new ArgumentNullException(nameof(url)); - } - if (string.IsNullOrEmpty(fileName)) - { - throw new ArgumentNullException(nameof(fileName)); - } - if (File.Exists(fileName)) - { - File.Delete(fileName); - } + ArgumentNullException.ThrowIfNull(url); + ArgumentNullException.ThrowIfNull(fileName); + if (File.Exists(fileName)) File.Delete(fileName); - var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); + using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); - if (!response.IsSuccessStatusCode) - { - throw new Exception(string.Format("{0}", response.StatusCode)); - } + if (!response.IsSuccessStatusCode) throw new Exception(response.StatusCode.ToString()); var total = response.Content.Headers.ContentLength ?? -1L; var canReportProgress = total != -1 && progress != null; @@ -96,48 +58,36 @@ namespace v2rayN.Base using var file = File.Create(fileName); var totalRead = 0L; var buffer = new byte[1024 * 1024]; - var isMoreToRead = true; var progressPercentage = 0; - do + while (true) { token.ThrowIfCancellationRequested(); var read = await stream.ReadAsync(buffer, token); + totalRead += read; - if (read == 0) + if (read == 0) break; + file.Write(buffer, 0, read); + + if (canReportProgress) { - isMoreToRead = false; - } - else - { - var data = new byte[read]; - buffer.ToList().CopyTo(0, data, 0, read); - - // TODO: put here the code to write the file to disk - file.Write(data, 0, read); - - totalRead += read; - - if (canReportProgress) + var percent = (int)(100.0 * totalRead / total); + //if (progressPercentage != percent && percent % 10 == 0) { - var percent = Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100); - if (progressPercentage != percent && percent % 10 == 0) - { - progressPercentage = percent; - progress.Report(percent); - } + progressPercentage = percent; + progress!.Report(percent); } } - } while (isMoreToRead); + } if (canReportProgress) { - progress.Report(101); + progress!.Report(101); } } - public async Task DownloadDataAsync4Speed(HttpClient client, string url, IProgress progress, CancellationToken token) + public async Task DownloadDataAsync4Speed(HttpClient client, string url, IProgress progress, CancellationToken token = default) { if (string.IsNullOrEmpty(url)) { @@ -148,7 +98,7 @@ namespace v2rayN.Base if (!response.IsSuccessStatusCode) { - throw new Exception(string.Format("{0}", response.StatusCode)); + throw new Exception(response.StatusCode.ToString()); } //var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L; diff --git a/v2rayN/v2rayN/Base/StringEx.cs b/v2rayN/v2rayN/Base/StringEx.cs index 1aad19d5..132da686 100644 --- a/v2rayN/v2rayN/Base/StringEx.cs +++ b/v2rayN/v2rayN/Base/StringEx.cs @@ -1,15 +1,16 @@ -using System.IO; +using System.Diagnostics.CodeAnalysis; +using System.IO; namespace v2rayN.Base { static class StringEx { - public static bool IsNullOrEmpty(this string value) + public static bool IsNullOrEmpty([NotNullWhen(false)] this string? value) { return string.IsNullOrEmpty(value); } - public static bool IsNullOrWhiteSpace(this string value) + public static bool IsNullOrWhiteSpace([NotNullWhen(false)] this string? value) { return string.IsNullOrWhiteSpace(value); } diff --git a/v2rayN/v2rayN/Handler/ConfigHandler.cs b/v2rayN/v2rayN/Handler/ConfigHandler.cs index 78d95e15..f1ec1c74 100644 --- a/v2rayN/v2rayN/Handler/ConfigHandler.cs +++ b/v2rayN/v2rayN/Handler/ConfigHandler.cs @@ -1042,11 +1042,8 @@ namespace v2rayN.Handler ProfileItem profileItem = new(); //Is v2ray configuration V2rayConfig? v2rayConfig = Utils.FromJson(clipboardData); - if (v2rayConfig != null - && v2rayConfig.inbounds != null - && v2rayConfig.inbounds.Count > 0 - && v2rayConfig.outbounds != null - && v2rayConfig.outbounds.Count > 0) + if (v2rayConfig?.inbounds?.Count > 0 + && v2rayConfig.outbounds?.Count > 0) { var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.json"); File.WriteAllText(fileName, clipboardData); @@ -1100,7 +1097,7 @@ namespace v2rayN.Handler { RemoveServerViaSubid(ref config, subid, isSub); } - if (isSub && lstOriSub != null && lstOriSub.Count == 1) + if (isSub && lstOriSub?.Count == 1) { profileItem.indexId = lstOriSub[0].indexId; } @@ -1137,16 +1134,16 @@ namespace v2rayN.Handler //SsSIP008 var lstSsServer = Utils.FromJson>(clipboardData); - if (lstSsServer == null || lstSsServer.Count <= 0) + if (lstSsServer?.Count <= 0) { var ssSIP008 = Utils.FromJson(clipboardData); - if (ssSIP008?.servers != null && ssSIP008.servers.Count > 0) + if (ssSIP008?.servers?.Count > 0) { lstSsServer = ssSIP008.servers; } } - if (lstSsServer != null && lstSsServer.Count > 0) + if (lstSsServer?.Count > 0) { int counter = 0; foreach (var it in lstSsServer) diff --git a/v2rayN/v2rayN/Handler/CoreConfigHandler.cs b/v2rayN/v2rayN/Handler/CoreConfigHandler.cs index c5e345f0..4b5bc51e 100644 --- a/v2rayN/v2rayN/Handler/CoreConfigHandler.cs +++ b/v2rayN/v2rayN/Handler/CoreConfigHandler.cs @@ -184,8 +184,7 @@ namespace v2rayN.Handler { try { - if (v2rayConfig.routing != null - && v2rayConfig.routing.rules != null) + if (v2rayConfig.routing?.rules != null) { v2rayConfig.routing.domainStrategy = config.routingBasicItem.domainStrategy; v2rayConfig.routing.domainMatcher = Utils.IsNullOrEmpty(config.routingBasicItem.domainMatcher) ? null : config.routingBasicItem.domainMatcher; @@ -241,25 +240,25 @@ namespace v2rayN.Handler { rules.port = null; } - if (rules.domain != null && rules.domain.Count == 0) + if (rules.domain?.Count == 0) { rules.domain = null; } - if (rules.ip != null && rules.ip.Count == 0) + if (rules.ip?.Count == 0) { rules.ip = null; } - if (rules.protocol != null && rules.protocol.Count == 0) + if (rules.protocol?.Count == 0) { rules.protocol = null; } - if (rules.inboundTag != null && rules.inboundTag.Count == 0) + if (rules.inboundTag?.Count == 0) { rules.inboundTag = null; } var hasDomainIp = false; - if (rules.domain != null && rules.domain.Count > 0) + if (rules.domain?.Count > 0) { var it = Utils.DeepCopy(rules); it.ip = null; @@ -275,7 +274,7 @@ namespace v2rayN.Handler v2rayConfig.routing.rules.Add(it); hasDomainIp = true; } - if (rules.ip != null && rules.ip.Count > 0) + if (rules.ip?.Count > 0) { var it = Utils.DeepCopy(rules); it.domain = null; @@ -286,8 +285,8 @@ namespace v2rayN.Handler if (!hasDomainIp) { if (!Utils.IsNullOrEmpty(rules.port) - || (rules.protocol != null && rules.protocol.Count > 0) - || (rules.inboundTag != null && rules.inboundTag.Count > 0) + || (rules.protocol?.Count > 0) + || (rules.inboundTag?.Count > 0) ) { var it = Utils.DeepCopy(rules); @@ -789,7 +788,7 @@ namespace v2rayN.Handler } var obj = Utils.ParseJson(config.remoteDNS); - if (obj != null && obj.ContainsKey("servers")) + if (obj?.ContainsKey("servers") == true) { v2rayConfig.dns = obj; } @@ -1171,30 +1170,24 @@ namespace v2rayN.Handler profileItem.remarks = $"import@{DateTime.Now.ToShortDateString()}"; //tcp or kcp - if (outbound.streamSettings != null - && outbound.streamSettings.network != null + if (outbound.streamSettings?.network != null && !Utils.IsNullOrEmpty(outbound.streamSettings.network)) { profileItem.network = outbound.streamSettings.network; } //tcp http - if (outbound.streamSettings != null - && outbound.streamSettings.tcpSettings != null - && outbound.streamSettings.tcpSettings.header != null + if (outbound.streamSettings?.tcpSettings?.header != null && !Utils.IsNullOrEmpty(outbound.streamSettings.tcpSettings.header.type)) { if (outbound.streamSettings.tcpSettings.header.type == Global.TcpHeaderHttp) { profileItem.headerType = outbound.streamSettings.tcpSettings.header.type; - string request = Convert.ToString(outbound.streamSettings.tcpSettings.header.request); + string? request = Convert.ToString(outbound.streamSettings.tcpSettings.header.request); if (!Utils.IsNullOrEmpty(request)) { - V2rayTcpRequest v2rayTcpRequest = Utils.FromJson(request); - if (v2rayTcpRequest != null - && v2rayTcpRequest.headers != null - && v2rayTcpRequest.headers.Host != null - && v2rayTcpRequest.headers.Host.Count > 0) + V2rayTcpRequest? v2rayTcpRequest = Utils.FromJson(request); + if (v2rayTcpRequest?.headers?.Host?.Count > 0) { profileItem.requestHost = v2rayTcpRequest.headers.Host[0]; } @@ -1202,17 +1195,14 @@ namespace v2rayN.Handler } } //kcp - if (outbound.streamSettings != null - && outbound.streamSettings.kcpSettings != null - && outbound.streamSettings.kcpSettings.header != null + if (outbound?.streamSettings?.kcpSettings?.header != null && !Utils.IsNullOrEmpty(outbound.streamSettings.kcpSettings.header.type)) { profileItem.headerType = outbound.streamSettings.kcpSettings.header.type; } //ws - if (outbound.streamSettings != null - && outbound.streamSettings.wsSettings != null) + if (outbound?.streamSettings?.wsSettings != null) { if (!Utils.IsNullOrEmpty(outbound.streamSettings.wsSettings.path)) { @@ -1226,24 +1216,20 @@ namespace v2rayN.Handler } //h2 - if (outbound.streamSettings != null - && outbound.streamSettings.httpSettings != null) + if (outbound?.streamSettings?.httpSettings != null) { if (!Utils.IsNullOrEmpty(outbound.streamSettings.httpSettings.path)) { profileItem.path = outbound.streamSettings.httpSettings.path; } - if (outbound.streamSettings.httpSettings.host != null - && outbound.streamSettings.httpSettings.host.Count > 0) + if (outbound.streamSettings.httpSettings.host?.Count > 0) { profileItem.requestHost = Utils.List2String(outbound.streamSettings.httpSettings.host); } } //tls - if (outbound.streamSettings != null - && outbound.streamSettings.security != null - && outbound.streamSettings.security == Global.StreamSecurity) + if (outbound?.streamSettings?.security == Global.StreamSecurity) { profileItem.streamSecurity = Global.StreamSecurity; } @@ -1265,7 +1251,7 @@ namespace v2rayN.Handler try { - string result = Utils.LoadResource(fileName); + string? result = Utils.LoadResource(fileName); if (Utils.IsNullOrEmpty(result)) { msg = ResUI.FailedReadConfiguration; @@ -1309,30 +1295,24 @@ namespace v2rayN.Handler profileItem.remarks = $"import@{DateTime.Now.ToShortDateString()}"; //tcp or kcp - if (inbound.streamSettings != null - && inbound.streamSettings.network != null + if (inbound.streamSettings?.network != null && !Utils.IsNullOrEmpty(inbound.streamSettings.network)) { profileItem.network = inbound.streamSettings.network; } //tcp http - if (inbound.streamSettings != null - && inbound.streamSettings.tcpSettings != null - && inbound.streamSettings.tcpSettings.header != null + if (inbound.streamSettings?.tcpSettings?.header != null && !Utils.IsNullOrEmpty(inbound.streamSettings.tcpSettings.header.type)) { if (inbound.streamSettings.tcpSettings.header.type == Global.TcpHeaderHttp) { profileItem.headerType = inbound.streamSettings.tcpSettings.header.type; - string request = Convert.ToString(inbound.streamSettings.tcpSettings.header.request); + string? request = Convert.ToString(inbound.streamSettings.tcpSettings.header.request); if (!Utils.IsNullOrEmpty(request)) { - V2rayTcpRequest v2rayTcpRequest = Utils.FromJson(request); - if (v2rayTcpRequest != null - && v2rayTcpRequest.headers != null - && v2rayTcpRequest.headers.Host != null - && v2rayTcpRequest.headers.Host.Count > 0) + V2rayTcpRequest? v2rayTcpRequest = Utils.FromJson(request); + if (v2rayTcpRequest?.headers?.Host?.Count > 0) { profileItem.requestHost = v2rayTcpRequest.headers.Host[0]; } @@ -1349,8 +1329,7 @@ namespace v2rayN.Handler //} //ws - if (inbound.streamSettings != null - && inbound.streamSettings.wsSettings != null) + if (inbound.streamSettings?.wsSettings != null) { if (!Utils.IsNullOrEmpty(inbound.streamSettings.wsSettings.path)) { @@ -1364,24 +1343,20 @@ namespace v2rayN.Handler } //h2 - if (inbound.streamSettings != null - && inbound.streamSettings.httpSettings != null) + if (inbound.streamSettings?.httpSettings != null) { if (!Utils.IsNullOrEmpty(inbound.streamSettings.httpSettings.path)) { profileItem.path = inbound.streamSettings.httpSettings.path; } - if (inbound.streamSettings.httpSettings.host != null - && inbound.streamSettings.httpSettings.host.Count > 0) + if (inbound.streamSettings.httpSettings.host?.Count > 0) { profileItem.requestHost = Utils.List2String(inbound.streamSettings.httpSettings.host); } } //tls - if (inbound.streamSettings != null - && inbound.streamSettings.security != null - && inbound.streamSettings.security == Global.StreamSecurity) + if (inbound.streamSettings?.security == Global.StreamSecurity) { profileItem.streamSecurity = Global.StreamSecurity; } @@ -1486,11 +1461,11 @@ namespace v2rayN.Handler var port = httpPort; for (int k = httpPort; k < Global.MaxPort; k++) { - if (lstIpEndPoints != null && lstIpEndPoints.FindIndex(_it => _it.Port == k) >= 0) + if (lstIpEndPoints?.FindIndex(_it => _it.Port == k) >= 0) { continue; } - if (lstTcpConns != null && lstTcpConns.FindIndex(_it => _it.LocalEndPoint.Port == k) >= 0) + if (lstTcpConns?.FindIndex(_it => _it.LocalEndPoint.Port == k) >= 0) { continue; } @@ -1501,7 +1476,7 @@ namespace v2rayN.Handler } //Port In Used - if (lstIpEndPoints != null && lstIpEndPoints.FindIndex(_it => _it.Port == port) >= 0) + if (lstIpEndPoints?.FindIndex(_it => _it.Port == port) >= 0) { continue; } diff --git a/v2rayN/v2rayN/Handler/DownloadHandle.cs b/v2rayN/v2rayN/Handler/DownloadHandle.cs index bdd70373..0c1e24e2 100644 --- a/v2rayN/v2rayN/Handler/DownloadHandle.cs +++ b/v2rayN/v2rayN/Handler/DownloadHandle.cs @@ -14,7 +14,7 @@ namespace v2rayN.Handler /// class DownloadHandle { - public event EventHandler UpdateCompleted; + public event EventHandler? UpdateCompleted; public event ErrorEventHandler? Error; @@ -73,11 +73,7 @@ namespace v2rayN.Handler var progress = new Progress(); progress.ProgressChanged += (sender, value) => { - if (UpdateCompleted != null) - { - string msg = $"...{value}%"; - UpdateCompleted(this, new ResultEventArgs(value > 100, msg)); - } + UpdateCompleted?.Invoke(this, new ResultEventArgs(value > 100, $"...{value}%")); }; var webProxy = GetWebProxy(blProxy); @@ -110,9 +106,9 @@ namespace v2rayN.Handler HttpClient client = new(webRequestHandler); HttpResponseMessage response = await client.GetAsync(url); - if (response.StatusCode.ToString() == "Redirect") + if (response.StatusCode == HttpStatusCode.Redirect && response.Headers.Location is not null) { - return response.Headers.Location?.ToString(); + return response.Headers.Location.ToString(); } else { @@ -199,7 +195,7 @@ namespace v2rayN.Handler if (Utils.IsNullOrEmpty(userAgent)) { - userAgent = $"{Utils.GetVersion(false)}"; + userAgent = Utils.GetVersion(false); } client.DefaultRequestHeaders.UserAgent.TryParseAdd(userAgent); @@ -213,7 +209,7 @@ namespace v2rayN.Handler var cts = new CancellationTokenSource(); cts.CancelAfter(1000 * 30); - var result = await HttpClientHelper.GetInstance().GetAsync(client, url, cts.Token); + var result = await HttpClientHelper.Instance.GetAsync(client, url, cts.Token); return result; } catch (Exception ex) @@ -242,7 +238,7 @@ namespace v2rayN.Handler if (Utils.IsNullOrEmpty(userAgent)) { - userAgent = $"{Utils.GetVersion(false)}"; + userAgent = Utils.GetVersion(false); } var result = await DownloaderHelper.Instance.DownloadStringAsync(webProxy, url, userAgent, 30); return result; @@ -260,7 +256,7 @@ namespace v2rayN.Handler } - public int RunAvailabilityCheck(WebProxy? webProxy) + public int RunAvailabilityCheck(IWebProxy? webProxy) { try { @@ -290,7 +286,7 @@ namespace v2rayN.Handler } } - public string GetRealPingTime(string url, WebProxy webProxy, int downloadTimeout, out int responseTime) + public string GetRealPingTime(string url, IWebProxy? webProxy, int downloadTimeout, out int responseTime) { string msg = string.Empty; responseTime = -1; @@ -300,18 +296,14 @@ namespace v2rayN.Handler myHttpWebRequest.Timeout = downloadTimeout * 1000; myHttpWebRequest.Proxy = webProxy; - Stopwatch timer = new(); - timer.Start(); + Stopwatch timer = Stopwatch.StartNew(); - HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); + using HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); if (myHttpWebResponse.StatusCode is not HttpStatusCode.OK and not HttpStatusCode.NoContent) { msg = myHttpWebResponse.StatusDescription; } - timer.Stop(); responseTime = timer.Elapsed.Milliseconds; - - myHttpWebResponse.Close(); } catch (Exception ex) { @@ -338,25 +330,17 @@ namespace v2rayN.Handler private bool SocketCheck(string ip, int port) { - Socket? sock = null; try { - IPAddress ipa = IPAddress.Parse(ip); - IPEndPoint point = new(ipa, port); - sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + IPEndPoint point = new(IPAddress.Parse(ip), port); + using Socket? sock = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(point); return true; } - catch { } - finally + catch (Exception) { - if (sock != null) - { - sock.Close(); - sock.Dispose(); - } + return false; } - return false; } } } diff --git a/v2rayN/v2rayN/Handler/LazyConfig.cs b/v2rayN/v2rayN/Handler/LazyConfig.cs index 101f433e..ed915c24 100644 --- a/v2rayN/v2rayN/Handler/LazyConfig.cs +++ b/v2rayN/v2rayN/Handler/LazyConfig.cs @@ -108,7 +108,7 @@ namespace v2rayN.Handler } if (!Utils.IsNullOrEmpty(filter)) { - if (filter.Contains("'")) + if (filter.Contains('\'')) { filter = filter.Replace("'", ""); } @@ -156,7 +156,7 @@ namespace v2rayN.Handler public ECoreType GetCoreType(ProfileItem profileItem, EConfigType eConfigType) { - if (profileItem != null && profileItem.coreType != null) + if (profileItem?.coreType != null) { return (ECoreType)profileItem.coreType; } @@ -179,7 +179,7 @@ namespace v2rayN.Handler { InitCoreInfo(); } - return coreInfos.Where(t => t.coreType == coreType).FirstOrDefault(); + return coreInfos!.FirstOrDefault(t => t.coreType == coreType); } public List? GetCoreInfos() diff --git a/v2rayN/v2rayN/Handler/SpeedtestHandler.cs b/v2rayN/v2rayN/Handler/SpeedtestHandler.cs index 20dae157..fd782f9a 100644 --- a/v2rayN/v2rayN/Handler/SpeedtestHandler.cs +++ b/v2rayN/v2rayN/Handler/SpeedtestHandler.cs @@ -319,7 +319,7 @@ namespace v2rayN.Handler await RunSpeedTestMulti(); } - public string GetRealPingTime(DownloadHandle downloadHandle, WebProxy webProxy) + public string GetRealPingTime(DownloadHandle downloadHandle, IWebProxy webProxy) { string status = downloadHandle.GetRealPingTime(_config.speedTestItem.speedPingTestUrl, webProxy, 10, out int responseTime); //string output = Utils.IsNullOrEmpty(status) ? FormatOut(responseTime, "ms") : status; diff --git a/v2rayN/v2rayN/Tool/Utils.cs b/v2rayN/v2rayN/Tool/Utils.cs index 4cc1b7c1..2e883376 100644 --- a/v2rayN/v2rayN/Tool/Utils.cs +++ b/v2rayN/v2rayN/Tool/Utils.cs @@ -65,24 +65,18 @@ namespace v2rayN /// 取得存储资源 /// /// - public static string LoadResource(string res) + public static string? LoadResource(string res) { - string result = string.Empty; - try { - if (!File.Exists(res)) - { - return result; - } - using StreamReader reader = new(res); - result = reader.ReadToEnd(); + if (!File.Exists(res)) return null; + return File.ReadAllText(res); } catch (Exception ex) { SaveLog(ex.Message, ex); } - return result; + return null; } /// @@ -91,7 +85,7 @@ namespace v2rayN /// /// /// - public static T? FromJson(string strJson) + public static T? FromJson(string? strJson) { try { @@ -172,8 +166,7 @@ namespace v2rayN { try { - JObject obj = JObject.Parse(strJson); - return obj; + return JObject.Parse(strJson); } catch (Exception ex) { @@ -204,7 +197,7 @@ namespace v2rayN } else { - return string.Join(",", lst.ToArray()); + return string.Join(",", lst); } } catch (Exception ex) @@ -738,9 +731,9 @@ namespace v2rayN { const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"; using RegistryKey? ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey); - if (ndpKey != null && ndpKey.GetValue("Release") != null) + if (ndpKey?.GetValue("Release") != null) { - return (int)ndpKey.GetValue("Release") >= release ? true : false; + return (int)ndpKey.GetValue("Release") >= release; } return false; } @@ -1161,7 +1154,7 @@ namespace v2rayN var logger = LogManager.GetLogger("Log2"); logger.Debug($"{strTitle},{ex.Message}"); logger.Debug(ex.StackTrace); - if (ex != null && ex.InnerException != null) + if (ex?.InnerException != null) { logger.Error(ex.InnerException); } @@ -1193,8 +1186,8 @@ namespace v2rayN { int marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry); int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry); - Rectangle cropRect = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2); - Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height); + Rectangle cropRect = new(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2); + Bitmap target = new(screen.Bounds.Width, screen.Bounds.Height); double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width; using (Graphics g = Graphics.FromImage(target)) @@ -1204,9 +1197,9 @@ namespace v2rayN GraphicsUnit.Pixel); } - BitmapLuminanceSource source = new BitmapLuminanceSource(target); - BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); - QRCodeReader reader = new QRCodeReader(); + BitmapLuminanceSource source = new(target); + BinaryBitmap bitmap = new(new HybridBinarizer(source)); + QRCodeReader reader = new(); Result result = reader.decode(bitmap); if (result != null) { diff --git a/v2rayN/v2rayN/ViewModels/OptionSettingViewModel.cs b/v2rayN/v2rayN/ViewModels/OptionSettingViewModel.cs index 6aeef8f2..bb64314c 100644 --- a/v2rayN/v2rayN/ViewModels/OptionSettingViewModel.cs +++ b/v2rayN/v2rayN/ViewModels/OptionSettingViewModel.cs @@ -253,7 +253,7 @@ namespace v2rayN.ViewModels } var obj = Utils.ParseJson(remoteDNS); - if (obj != null && obj.ContainsKey("servers")) + if (obj?.ContainsKey("servers") == true) { } else @@ -277,7 +277,7 @@ namespace v2rayN.ViewModels //} //Core - _config.inbound[0].localPort = Utils.ToInt(localPort); + _config.inbound[0].localPort = localPort; _config.inbound[0].udpEnabled = udpEnabled; _config.inbound[0].sniffingEnabled = sniffingEnabled; _config.inbound[0].routeOnly = routeOnly; diff --git a/v2rayN/v2rayUpgrade/MainForm.cs b/v2rayN/v2rayUpgrade/MainForm.cs index fe2ee592..27e69ded 100644 --- a/v2rayN/v2rayUpgrade/MainForm.cs +++ b/v2rayN/v2rayUpgrade/MainForm.cs @@ -93,7 +93,7 @@ namespace v2rayUpgrade } string entryOuputPath = GetPath(fullName); - Directory.CreateDirectory(Path.GetDirectoryName(entryOuputPath) ?? ""); + Directory.CreateDirectory(Path.GetDirectoryName(entryOuputPath)!); entry.ExtractToFile(entryOuputPath, true); } catch (Exception ex)