From 1321037c52cddf958e6a48aa69f8f15739595f90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E4=BB=99=E5=A5=B3?= Date: Fri, 17 Feb 2023 14:36:28 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96,=20=E6=94=B9=E6=88=90?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E8=AF=AD=E6=B3=95=E7=B3=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- v2rayN/v2rayN/Base/DownloaderHelper.cs | 133 +++++++-------- v2rayN/v2rayN/Base/HttpClientHelper.cs | 157 +++++++++--------- v2rayN/v2rayN/Base/StringEx.cs | 2 +- v2rayN/v2rayN/Handler/ConfigHandler.cs | 28 ++-- v2rayN/v2rayN/Handler/ProxySetting.cs | 7 +- v2rayN/v2rayN/Handler/ShareHandler.cs | 32 ++-- v2rayN/v2rayN/Tool/FileManager.cs | 59 +++---- v2rayN/v2rayN/Tool/Utils.cs | 215 +++++++++++-------------- 8 files changed, 281 insertions(+), 352 deletions(-) diff --git a/v2rayN/v2rayN/Base/DownloaderHelper.cs b/v2rayN/v2rayN/Base/DownloaderHelper.cs index 86ceac99..59879d04 100644 --- a/v2rayN/v2rayN/Base/DownloaderHelper.cs +++ b/v2rayN/v2rayN/Base/DownloaderHelper.cs @@ -13,7 +13,7 @@ namespace v2rayN.Base { } - 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)) { @@ -23,7 +23,7 @@ namespace v2rayN.Base var cancellationToken = new CancellationTokenSource(); cancellationToken.CancelAfter(timeout * 1000); - Uri uri = new Uri(url); + Uri uri = new(url); //Authorization Header var headers = new WebHeaderCollection(); if (!Utils.IsNullOrEmpty(uri.UserInfo)) @@ -45,23 +45,17 @@ namespace v2rayN.Base }; string text = string.Empty; - using (var downloader = new DownloadService(downloadOpt)) + using var downloader = new DownloadService(downloadOpt); + downloader.DownloadFileCompleted += (sender, value) => { - downloader.DownloadFileCompleted += (sender, value) => + if (value.Error != null) { - 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(); - } + throw new Exception(string.Format("{0}", value.Error.Message)); } - } + }; + using var stream = await downloader.DownloadFileTaskAsync(address: url, cancellationToken: cancellationToken.Token); + using StreamReader reader = new(stream); + text = reader.ReadToEnd(); downloadOpt = null; @@ -73,7 +67,7 @@ namespace v2rayN.Base { if (string.IsNullOrEmpty(url)) { - throw new ArgumentNullException("url"); + throw new ArgumentNullException(nameof(url)); } var cancellationToken = new CancellationTokenSource(); @@ -94,44 +88,42 @@ namespace v2rayN.Base int totalSecond = 0; var hasValue = false; double maxSpeed = 0; - using (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) => { - //downloader.DownloadStarted += (sender, value) => - //{ - // if (progress != null) - // { - // progress.Report("Start download data..."); - // } - //}; - downloader.DownloadProgressChanged += (sender, value) => + TimeSpan ts = (DateTime.Now - totalDatetime); + if (progress != null && ts.Seconds > totalSecond) { - TimeSpan ts = (DateTime.Now - totalDatetime); - if (progress != null && ts.Seconds > totalSecond) + hasValue = true; + totalSecond = ts.Seconds; + if (value.BytesPerSecondSpeed > maxSpeed) { - hasValue = true; - totalSecond = ts.Seconds; - if (value.BytesPerSecondSpeed > maxSpeed) - { - maxSpeed = value.BytesPerSecondSpeed; - var speed = (maxSpeed / 1000 / 1000).ToString("#0.0"); - progress.Report(speed); - } + 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 (progress != null) + if (!hasValue && value.Error != null) { - if (!hasValue && value.Error != null) - { - progress.Report(value.Error?.Message); - } + 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); downloadOpt = null; } @@ -167,38 +159,33 @@ namespace v2rayN.Base var progressPercentage = 0; var hasValue = false; - using (var downloader = new DownloadService(downloadOpt)) + using var downloader = new DownloadService(downloadOpt); + downloader.DownloadStarted += (sender, value) => { - downloader.DownloadStarted += (sender, value) => + 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) { - if (progress != null) - { - progress.Report(0); - } - }; - downloader.DownloadProgressChanged += (sender, value) => + progressPercentage = percent; + progress.Report(percent); + } + }; + downloader.DownloadFileCompleted += (sender, value) => + { + if (progress != null) { - hasValue = true; - var percent = (int)value.ProgressPercentage;// Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100); - if (progressPercentage != percent && percent % 10 == 0) + if (hasValue && value.Error == null) { - progressPercentage = percent; - progress.Report(percent); + progress.Report(101); } - }; - 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); downloadOpt = null; } diff --git a/v2rayN/v2rayN/Base/HttpClientHelper.cs b/v2rayN/v2rayN/Base/HttpClientHelper.cs index 4fbbc400..0c8bdab0 100644 --- a/v2rayN/v2rayN/Base/HttpClientHelper.cs +++ b/v2rayN/v2rayN/Base/HttpClientHelper.cs @@ -33,7 +33,7 @@ namespace v2rayN.Base return httpClientHelper; } } - public async Task GetAsync(string url) + public async Task GetAsync(string url) { if (string.IsNullOrEmpty(url)) { @@ -43,7 +43,7 @@ namespace v2rayN.Base return await response.Content.ReadAsStringAsync(); } - public async Task GetAsync(HttpClient client, string url, CancellationToken token) + public async Task GetAsync(HttpClient client, string url, CancellationToken token) { if (string.IsNullOrEmpty(url)) { @@ -54,7 +54,7 @@ namespace v2rayN.Base { throw new Exception(string.Format("{0}", response.StatusCode)); } - return await response.Content.ReadAsStringAsync(); + return await response.Content.ReadAsStringAsync(token); } public async Task PutAsync(string url, Dictionary headers) @@ -92,53 +92,48 @@ namespace v2rayN.Base var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L; var canReportProgress = total != -1 && progress != null; - using (var stream = await response.Content.ReadAsStreamAsync()) + using var stream = await response.Content.ReadAsStreamAsync(); + using var file = File.Create(fileName); + var totalRead = 0L; + var buffer = new byte[1024 * 1024]; + var isMoreToRead = true; + var progressPercentage = 0; + + do { - using (var file = File.Create(fileName)) + token.ThrowIfCancellationRequested(); + + var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); + + if (read == 0) { - var totalRead = 0L; - var buffer = new byte[1024 * 1024]; - var isMoreToRead = true; - var progressPercentage = 0; + isMoreToRead = false; + } + else + { + var data = new byte[read]; + buffer.ToList().CopyTo(0, data, 0, read); - do - { - token.ThrowIfCancellationRequested(); + // TODO: put here the code to write the file to disk + file.Write(data, 0, read); - var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); + totalRead += read; - if (read == 0) - { - 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 = Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100); - if (progressPercentage != percent && percent % 10 == 0) - { - progressPercentage = percent; - progress.Report(percent); - } - } - } - } while (isMoreToRead); - file.Close(); if (canReportProgress) { - progress.Report(101); - + var percent = Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100); + if (progressPercentage != percent && percent % 10 == 0) + { + progressPercentage = percent; + progress.Report(percent); + } } } + } while (isMoreToRead); + if (canReportProgress) + { + progress.Report(101); + } } @@ -146,7 +141,7 @@ namespace v2rayN.Base { if (string.IsNullOrEmpty(url)) { - throw new ArgumentNullException("url"); + throw new ArgumentNullException(nameof(url)); } var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); @@ -159,57 +154,55 @@ namespace v2rayN.Base //var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L; //var canReportProgress = total != -1 && progress != null; - using (var stream = await response.Content.ReadAsStreamAsync()) + using var stream = await response.Content.ReadAsStreamAsync(token); + var totalRead = 0L; + var buffer = new byte[1024 * 64]; + var isMoreToRead = true; + string progressSpeed = string.Empty; + DateTime totalDatetime = DateTime.Now; + int totalSecond = 0; + + do { - var totalRead = 0L; - var buffer = new byte[1024 * 64]; - var isMoreToRead = true; - string progressSpeed = string.Empty; - DateTime totalDatetime = DateTime.Now; - int totalSecond = 0; - - do + if (token.IsCancellationRequested) { - if (token.IsCancellationRequested) + if (totalRead > 0) { - if (totalRead > 0) - { - return; - } - else - { - token.ThrowIfCancellationRequested(); - } - } - - var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); - - if (read == 0) - { - isMoreToRead = false; + return; } else { - var data = new byte[read]; - buffer.ToList().CopyTo(0, data, 0, read); + token.ThrowIfCancellationRequested(); + } + } - // TODO: - totalRead += read; + var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); - TimeSpan ts = (DateTime.Now - totalDatetime); - if (progress != null && ts.Seconds > totalSecond) + if (read == 0) + { + isMoreToRead = false; + } + else + { + var data = new byte[read]; + buffer.ToList().CopyTo(0, data, 0, read); + + // TODO: + totalRead += read; + + TimeSpan 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) { - totalSecond = ts.Seconds; - var speed = (totalRead * 1d / ts.TotalMilliseconds / 1000).ToString("#0.0"); - if (progressSpeed != speed) - { - progressSpeed = speed; - progress.Report(speed); - } + progressSpeed = speed; + progress.Report(speed); } } - } while (isMoreToRead); - } + } + } while (isMoreToRead); } } diff --git a/v2rayN/v2rayN/Base/StringEx.cs b/v2rayN/v2rayN/Base/StringEx.cs index 8e5c8dbb..9aca7060 100644 --- a/v2rayN/v2rayN/Base/StringEx.cs +++ b/v2rayN/v2rayN/Base/StringEx.cs @@ -34,7 +34,7 @@ namespace v2rayN.Base public static IEnumerable NonWhiteSpaceLines(this TextReader reader) { - string line; + string? line; while ((line = reader.ReadLine()) != null) { if (line.IsWhiteSpace()) continue; diff --git a/v2rayN/v2rayN/Handler/ConfigHandler.cs b/v2rayN/v2rayN/Handler/ConfigHandler.cs index bfe31f80..0d32390c 100644 --- a/v2rayN/v2rayN/Handler/ConfigHandler.cs +++ b/v2rayN/v2rayN/Handler/ConfigHandler.cs @@ -1021,7 +1021,17 @@ namespace v2rayN.Handler return -1; } - ProfileItem profileItem = new ProfileItem(); + //判断str是否包含s的任意一个字符串 + static bool Containss(string str, params string[] s) + { + foreach (var item in s) + { + if (str.Contains(item, StringComparison.OrdinalIgnoreCase)) return true; + } + return false; + } + + ProfileItem profileItem = new(); //Is v2ray configuration V2rayConfig v2rayConfig = Utils.FromJson(clipboardData); if (v2rayConfig != null @@ -1038,9 +1048,7 @@ namespace v2rayN.Handler profileItem.remarks = "v2ray_custom"; } //Is Clash configuration - else if (clipboardData.IndexOf("port") >= 0 - && clipboardData.IndexOf("socks-port") >= 0 - && clipboardData.IndexOf("proxies") >= 0) + else if (Containss(clipboardData, "port", "socks-port", "proxies")) { var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.yaml"); File.WriteAllText(fileName, clipboardData); @@ -1050,12 +1058,7 @@ namespace v2rayN.Handler profileItem.remarks = "clash_custom"; } //Is hysteria configuration - else if (clipboardData.IndexOf("server") >= 0 - && clipboardData.IndexOf("up") >= 0 - && clipboardData.IndexOf("down") >= 0 - && clipboardData.IndexOf("listen") >= 0 - && clipboardData.IndexOf("") < 0 - && clipboardData.IndexOf("") < 0) + else if (Containss(clipboardData, "server", "up", "down", "listen", "", "")) { var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.json"); File.WriteAllText(fileName, clipboardData); @@ -1065,10 +1068,7 @@ namespace v2rayN.Handler profileItem.remarks = "hysteria_custom"; } //Is naiveproxy configuration - else if (clipboardData.IndexOf("listen") >= 0 - && clipboardData.IndexOf("proxy") >= 0 - && clipboardData.IndexOf("") < 0 - && clipboardData.IndexOf("") < 0) + else if (Containss(clipboardData, "listen", "proxy", "", "")) { var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.json"); File.WriteAllText(fileName, clipboardData); diff --git a/v2rayN/v2rayN/Handler/ProxySetting.cs b/v2rayN/v2rayN/Handler/ProxySetting.cs index 1a0d46db..045f6039 100644 --- a/v2rayN/v2rayN/Handler/ProxySetting.cs +++ b/v2rayN/v2rayN/Handler/ProxySetting.cs @@ -189,24 +189,21 @@ namespace v2rayN.Handler //判断是否使用代理 public static bool UsedProxy() { - RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); + using RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); if (rk.GetValue("ProxyEnable").ToString() == "1") { - rk.Close(); return true; } else { - rk.Close(); return false; } } //获得代理的IP和端口 public static string GetProxyProxyServer() { - RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); + using RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); string ProxyServer = rk.GetValue("ProxyServer").ToString(); - rk.Close(); return ProxyServer; } diff --git a/v2rayN/v2rayN/Handler/ShareHandler.cs b/v2rayN/v2rayN/Handler/ShareHandler.cs index 89f0647c..2b243ae3 100644 --- a/v2rayN/v2rayN/Handler/ShareHandler.cs +++ b/v2rayN/v2rayN/Handler/ShareHandler.cs @@ -21,28 +21,18 @@ namespace v2rayN.Handler { try { - string url = string.Empty; + string? url = string.Empty; - switch (item.configType) + url = item.configType switch { - case EConfigType.VMess: - url = ShareVmess(item); - break; - case EConfigType.Shadowsocks: - url = ShareShadowsocks(item); - break; - case EConfigType.Socks: - url = ShareSocks(item); - break; - case EConfigType.Trojan: - url = ShareTrojan(item); - break; - case EConfigType.VLESS: - url = ShareVLESS(item); - break; - default: - break; - } + EConfigType.VMess => ShareVmess(item), + EConfigType.Shadowsocks => ShareShadowsocks(item), + EConfigType.Socks => ShareSocks(item), + EConfigType.Trojan => ShareTrojan(item), + EConfigType.VLESS => ShareVLESS(item), + _ => null, + }; + return url; } catch (Exception ex) @@ -285,7 +275,7 @@ namespace v2rayN.Handler { msg = string.Empty; ProfileItem profileItem = new ProfileItem(); - + try { //载入配置文件 diff --git a/v2rayN/v2rayN/Tool/FileManager.cs b/v2rayN/v2rayN/Tool/FileManager.cs index c3d45263..ead61caf 100644 --- a/v2rayN/v2rayN/Tool/FileManager.cs +++ b/v2rayN/v2rayN/Tool/FileManager.cs @@ -10,8 +10,8 @@ namespace v2rayN.Tool { try { - using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) - fs.Write(content, 0, content.Length); + using FileStream fs = new(fileName, FileMode.Create, FileAccess.Write); + fs.Write(content); return true; } catch (Exception ex) @@ -20,25 +20,14 @@ namespace v2rayN.Tool } return false; } - + public static void UncompressFile(string fileName, byte[] content) { try { - // Because the uncompressed size of the file is unknown, - // we are using an arbitrary buffer size. - byte[] buffer = new byte[4096]; - int n; - - using (FileStream fs = File.Create(fileName)) - using (GZipStream input = new GZipStream(new MemoryStream(content), - CompressionMode.Decompress, false)) - { - while ((n = input.Read(buffer, 0, buffer.Length)) > 0) - { - fs.Write(buffer, 0, n); - } - } + using FileStream fs = File.Create(fileName); + using GZipStream input = new(new MemoryStream(content), CompressionMode.Decompress, false); + input.CopyTo(fs); } catch (Exception ex) { @@ -55,11 +44,9 @@ namespace v2rayN.Tool { try { - using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - using (StreamReader sr = new StreamReader(fs, encoding)) - { - return sr.ReadToEnd(); - } + using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using StreamReader sr = new(fs, encoding); + return sr.ReadToEnd(); } catch (Exception ex) { @@ -71,26 +58,24 @@ namespace v2rayN.Tool { try { - using (ZipArchive archive = ZipFile.OpenRead(fileName)) + using ZipArchive archive = ZipFile.OpenRead(fileName); + foreach (ZipArchiveEntry entry in archive.Entries) { - foreach (ZipArchiveEntry entry in archive.Entries) + if (entry.Length == 0) { - if (entry.Length == 0) + continue; + } + try + { + if (!Utils.IsNullOrEmpty(ignoredName) && entry.Name.Contains(ignoredName)) { continue; } - try - { - if (!Utils.IsNullOrEmpty(ignoredName) && entry.Name.Contains(ignoredName)) - { - continue; - } - entry.ExtractToFile(Path.Combine(toPath, entry.Name), true); - } - catch (IOException ex) - { - Utils.SaveLog(ex.Message, ex); - } + entry.ExtractToFile(Path.Combine(toPath, entry.Name), true); + } + catch (IOException ex) + { + Utils.SaveLog(ex.Message, ex); } } } diff --git a/v2rayN/v2rayN/Tool/Utils.cs b/v2rayN/v2rayN/Tool/Utils.cs index c4dbea64..70c5db62 100644 --- a/v2rayN/v2rayN/Tool/Utils.cs +++ b/v2rayN/v2rayN/Tool/Utils.cs @@ -48,11 +48,9 @@ namespace v2rayN try { Assembly assembly = Assembly.GetExecutingAssembly(); - using (Stream stream = assembly.GetManifestResourceStream(res)) - using (StreamReader reader = new StreamReader(stream)) - { - result = reader.ReadToEnd(); - } + using Stream stream = assembly.GetManifestResourceStream(res); + using StreamReader reader = new(stream); + result = reader.ReadToEnd(); } catch (Exception ex) { @@ -76,10 +74,8 @@ namespace v2rayN { return result; } - using (StreamReader reader = new StreamReader(res)) - { - result = reader.ReadToEnd(); - } + using StreamReader reader = new(res); + result = reader.ReadToEnd(); } catch (Exception ex) { @@ -150,20 +146,18 @@ namespace v2rayN int result; try { - using (StreamWriter file = File.CreateText(filePath)) + using StreamWriter file = File.CreateText(filePath); + JsonSerializer serializer; + if (nullValue) { - JsonSerializer serializer; - if (nullValue) - { - serializer = new JsonSerializer() { Formatting = Formatting.Indented }; - } - else - { - serializer = new JsonSerializer() { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore }; - } - - serializer.Serialize(file, obj); + serializer = new JsonSerializer() { Formatting = Formatting.Indented }; } + else + { + serializer = new JsonSerializer() { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore }; + } + + serializer.Serialize(file, obj); result = 0; } catch (Exception ex) @@ -248,7 +242,7 @@ namespace v2rayN try { str = str.Replace(Environment.NewLine, ""); - List list = new List(str.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)); + List list = new(str.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)); return list.OrderBy(x => x).ToList(); } catch (Exception ex) @@ -341,7 +335,7 @@ namespace v2rayN { try { - return (obj == null ? string.Empty : obj.ToString()); + return obj?.ToString() ?? string.Empty; } catch (Exception ex) { @@ -418,10 +412,9 @@ namespace v2rayN public static string GetMD5(string str) { - var md5 = MD5.Create(); byte[] byteOld = Encoding.UTF8.GetBytes(str); - byte[] byteNew = md5.ComputeHash(byteOld); - StringBuilder sb = new StringBuilder(); + byte[] byteNew = MD5.HashData(byteOld); + StringBuilder sb = new(32); foreach (byte b in byteNew) { sb.Append(b.ToString("x2")); @@ -444,7 +437,7 @@ namespace v2rayN } try { - Uri uri = new Uri(url); + Uri uri = new(url); if (uri.Host == uri.IdnHost) { return url; @@ -572,18 +565,14 @@ namespace v2rayN public static bool IsIpv6(string ip) { - IPAddress address; - if (IPAddress.TryParse(ip, out address)) + if (IPAddress.TryParse(ip, out IPAddress? address)) { - switch (address.AddressFamily) + return address.AddressFamily switch { - case AddressFamily.InterNetwork: - return false; - case AddressFamily.InterNetworkV6: - return true; - default: - return false; - } + AddressFamily.InterNetwork => false, + AddressFamily.InterNetworkV6 => true, + _ => false, + }; } return false; } @@ -688,11 +677,11 @@ namespace v2rayN public static string RegReadValue(string path, string name, string def) { - RegistryKey regKey = null; + RegistryKey? regKey = null; try { regKey = Registry.CurrentUser.OpenSubKey(path, false); - string value = regKey?.GetValue(name) as string; + string? value = regKey?.GetValue(name) as string; if (IsNullOrEmpty(value)) { return def; @@ -715,7 +704,7 @@ namespace v2rayN public static void RegWriteValue(string path, string name, object value) { - RegistryKey regKey = null; + RegistryKey? regKey = null; try { regKey = Registry.CurrentUser.CreateSubKey(path); @@ -747,14 +736,12 @@ namespace v2rayN public static bool CheckForDotNetVersion(int release = 528040) { const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"; - using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey)) + using RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey); + if (ndpKey != null && ndpKey.GetValue("Release") != null) { - if (ndpKey != null && ndpKey.GetValue("Release") != null) - { - return (int)ndpKey.GetValue("Release") >= release ? true : false; - } - return false; + return (int)ndpKey.GetValue("Release") >= release ? true : false; } + return false; } /// @@ -775,31 +762,29 @@ namespace v2rayN string taskDescription = description; string deamonFileName = fileName; - using (var taskService = new TaskService()) + using var taskService = new TaskService(); + var tasks = taskService.RootFolder.GetTasks(new Regex(TaskName)); + foreach (var t in tasks) { - var tasks = taskService.RootFolder.GetTasks(new Regex(TaskName)); - foreach (var t in tasks) - { - taskService.RootFolder.DeleteTask(t.Name); - } - if (string.IsNullOrEmpty(fileName)) - { - return; - } - - var task = taskService.NewTask(); - task.RegistrationInfo.Description = taskDescription; - task.Settings.DisallowStartIfOnBatteries = false; - task.Settings.StopIfGoingOnBatteries = false; - task.Settings.RunOnlyIfIdle = false; - task.Settings.IdleSettings.StopOnIdleEnd = false; - task.Settings.ExecutionTimeLimit = TimeSpan.Zero; - task.Triggers.Add(new LogonTrigger { UserId = logonUser, Delay = TimeSpan.FromMinutes(1) }); - task.Principal.RunLevel = TaskRunLevel.Highest; - task.Actions.Add(new ExecAction(deamonFileName)); - - taskService.RootFolder.RegisterTaskDefinition(TaskName, task); + taskService.RootFolder.DeleteTask(t.Name); } + if (string.IsNullOrEmpty(fileName)) + { + return; + } + + var task = taskService.NewTask(); + task.RegistrationInfo.Description = taskDescription; + task.Settings.DisallowStartIfOnBatteries = false; + task.Settings.StopIfGoingOnBatteries = false; + task.Settings.RunOnlyIfIdle = false; + task.Settings.IdleSettings.StopOnIdleEnd = false; + task.Settings.ExecutionTimeLimit = TimeSpan.Zero; + task.Triggers.Add(new LogonTrigger { UserId = logonUser, Delay = TimeSpan.FromMinutes(1) }); + task.Principal.RunLevel = TaskRunLevel.Highest; + task.Actions.Add(new ExecAction(deamonFileName)); + + taskService.RootFolder.RegisterTaskDefinition(TaskName, task); } #endregion @@ -908,16 +893,13 @@ namespace v2rayN public static T DeepCopy(T obj) { object retval; - using (MemoryStream ms = new MemoryStream()) - { - BinaryFormatter bf = new BinaryFormatter(); - //序列化成流 - bf.Serialize(ms, obj); - ms.Seek(0, SeekOrigin.Begin); - //反序列化成对象 - retval = bf.Deserialize(ms); - ms.Close(); - } + MemoryStream ms = new MemoryStream(); + BinaryFormatter bf = new BinaryFormatter(); + //序列化成流 + bf.Serialize(ms, obj); + ms.Seek(0, SeekOrigin.Begin); + //反序列化成对象 + retval = bf.Deserialize(ms); return (T)retval; } @@ -1075,14 +1057,11 @@ namespace v2rayN public static string UnGzip(byte[] buf) { - MemoryStream sb = new MemoryStream(); - using (GZipStream input = new GZipStream(new MemoryStream(buf), - CompressionMode.Decompress, - false)) - { - input.CopyTo(sb); - } - return Encoding.UTF8.GetString(sb.ToArray()); + using MemoryStream sb = new(); + using GZipStream input = new(new MemoryStream(buf), CompressionMode.Decompress, false); + input.CopyTo(sb); + sb.Position = 0; + return new StreamReader(sb, Encoding.UTF8).ReadToEnd(); } public static string GetBackupPath(string filename) @@ -1198,42 +1177,40 @@ namespace v2rayN { foreach (Screen screen in Screen.AllScreens) { - using (Bitmap fullImage = new Bitmap(screen.Bounds.Width, - screen.Bounds.Height)) + using Bitmap fullImage = new Bitmap(screen.Bounds.Width, + screen.Bounds.Height); + using (Graphics g = Graphics.FromImage(fullImage)) { - using (Graphics g = Graphics.FromImage(fullImage)) + g.CopyFromScreen(screen.Bounds.X, + screen.Bounds.Y, + 0, 0, + fullImage.Size, + CopyPixelOperation.SourceCopy); + } + int maxTry = 10; + for (int i = 0; i < maxTry; i++) + { + 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); + + double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width; + using (Graphics g = Graphics.FromImage(target)) { - g.CopyFromScreen(screen.Bounds.X, - screen.Bounds.Y, - 0, 0, - fullImage.Size, - CopyPixelOperation.SourceCopy); + g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height), + cropRect, + GraphicsUnit.Pixel); } - int maxTry = 10; - for (int i = 0; i < maxTry; i++) + + BitmapLuminanceSource source = new BitmapLuminanceSource(target); + BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); + QRCodeReader reader = new QRCodeReader(); + Result result = reader.decode(bitmap); + if (result != null) { - 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); - - double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width; - using (Graphics g = Graphics.FromImage(target)) - { - g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height), - cropRect, - GraphicsUnit.Pixel); - } - - BitmapLuminanceSource source = new BitmapLuminanceSource(target); - BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); - QRCodeReader reader = new QRCodeReader(); - Result result = reader.decode(bitmap); - if (result != null) - { - string ret = result.Text; - return ret; - } + string ret = result.Text; + return ret; } } }