优化, 改成使用语法糖

pull/3305/head
小仙女 2023-02-17 14:36:28 +08:00
parent 6d4cbacd50
commit 1321037c52
8 changed files with 281 additions and 352 deletions

View File

@ -13,7 +13,7 @@ namespace v2rayN.Base
{ {
} }
public async Task<string> DownloadStringAsync(IWebProxy webProxy, string url, string? userAgent, int timeout) public async Task<string?> DownloadStringAsync(IWebProxy webProxy, string url, string? userAgent, int timeout)
{ {
if (string.IsNullOrEmpty(url)) if (string.IsNullOrEmpty(url))
{ {
@ -23,7 +23,7 @@ namespace v2rayN.Base
var cancellationToken = new CancellationTokenSource(); var cancellationToken = new CancellationTokenSource();
cancellationToken.CancelAfter(timeout * 1000); cancellationToken.CancelAfter(timeout * 1000);
Uri uri = new Uri(url); Uri uri = new(url);
//Authorization Header //Authorization Header
var headers = new WebHeaderCollection(); var headers = new WebHeaderCollection();
if (!Utils.IsNullOrEmpty(uri.UserInfo)) if (!Utils.IsNullOrEmpty(uri.UserInfo))
@ -45,23 +45,17 @@ namespace v2rayN.Base
}; };
string text = string.Empty; 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));
{
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();
}
} }
} };
using var stream = await downloader.DownloadFileTaskAsync(address: url, cancellationToken: cancellationToken.Token);
using StreamReader reader = new(stream);
text = reader.ReadToEnd();
downloadOpt = null; downloadOpt = null;
@ -73,7 +67,7 @@ namespace v2rayN.Base
{ {
if (string.IsNullOrEmpty(url)) if (string.IsNullOrEmpty(url))
{ {
throw new ArgumentNullException("url"); throw new ArgumentNullException(nameof(url));
} }
var cancellationToken = new CancellationTokenSource(); var cancellationToken = new CancellationTokenSource();
@ -94,44 +88,42 @@ namespace v2rayN.Base
int totalSecond = 0; int totalSecond = 0;
var hasValue = false; var hasValue = false;
double maxSpeed = 0; 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) => TimeSpan ts = (DateTime.Now - totalDatetime);
//{ if (progress != null && ts.Seconds > totalSecond)
// if (progress != null)
// {
// progress.Report("Start download data...");
// }
//};
downloader.DownloadProgressChanged += (sender, value) =>
{ {
TimeSpan ts = (DateTime.Now - totalDatetime); hasValue = true;
if (progress != null && ts.Seconds > totalSecond) totalSecond = ts.Seconds;
if (value.BytesPerSecondSpeed > maxSpeed)
{ {
hasValue = true; maxSpeed = value.BytesPerSecondSpeed;
totalSecond = ts.Seconds; var speed = (maxSpeed / 1000 / 1000).ToString("#0.0");
if (value.BytesPerSecondSpeed > maxSpeed) 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; downloadOpt = null;
} }
@ -167,38 +159,33 @@ namespace v2rayN.Base
var progressPercentage = 0; var progressPercentage = 0;
var hasValue = false; 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) progressPercentage = percent;
{ progress.Report(percent);
progress.Report(0); }
} };
}; downloader.DownloadFileCompleted += (sender, value) =>
downloader.DownloadProgressChanged += (sender, value) => {
if (progress != null)
{ {
hasValue = true; if (hasValue && value.Error == null)
var percent = (int)value.ProgressPercentage;// Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100);
if (progressPercentage != percent && percent % 10 == 0)
{ {
progressPercentage = percent; progress.Report(101);
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);
}
downloadOpt = null; downloadOpt = null;
} }

View File

@ -33,7 +33,7 @@ namespace v2rayN.Base
return httpClientHelper; return httpClientHelper;
} }
} }
public async Task<string> GetAsync(string url) public async Task<string?> GetAsync(string url)
{ {
if (string.IsNullOrEmpty(url)) if (string.IsNullOrEmpty(url))
{ {
@ -43,7 +43,7 @@ namespace v2rayN.Base
return await response.Content.ReadAsStringAsync(); return await response.Content.ReadAsStringAsync();
} }
public async Task<string> GetAsync(HttpClient client, string url, CancellationToken token) public async Task<string?> GetAsync(HttpClient client, string url, CancellationToken token)
{ {
if (string.IsNullOrEmpty(url)) if (string.IsNullOrEmpty(url))
{ {
@ -54,7 +54,7 @@ namespace v2rayN.Base
{ {
throw new Exception(string.Format("{0}", response.StatusCode)); 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<string, string> headers) public async Task PutAsync(string url, Dictionary<string, string> headers)
@ -92,53 +92,48 @@ namespace v2rayN.Base
var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L; var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L;
var canReportProgress = total != -1 && progress != null; 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; isMoreToRead = false;
var buffer = new byte[1024 * 1024]; }
var isMoreToRead = true; else
var progressPercentage = 0; {
var data = new byte[read];
buffer.ToList().CopyTo(0, data, 0, read);
do // TODO: put here the code to write the file to disk
{ file.Write(data, 0, read);
token.ThrowIfCancellationRequested();
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) 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)) if (string.IsNullOrEmpty(url))
{ {
throw new ArgumentNullException("url"); throw new ArgumentNullException(nameof(url));
} }
var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); 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 total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L;
//var canReportProgress = total != -1 && progress != null; //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; if (token.IsCancellationRequested)
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 (totalRead > 0)
{ {
if (totalRead > 0) return;
{
return;
}
else
{
token.ThrowIfCancellationRequested();
}
}
var read = await stream.ReadAsync(buffer, 0, buffer.Length, token);
if (read == 0)
{
isMoreToRead = false;
} }
else else
{ {
var data = new byte[read]; token.ThrowIfCancellationRequested();
buffer.ToList().CopyTo(0, data, 0, read); }
}
// TODO: var read = await stream.ReadAsync(buffer, 0, buffer.Length, token);
totalRead += read;
TimeSpan ts = (DateTime.Now - totalDatetime); if (read == 0)
if (progress != null && ts.Seconds > totalSecond) {
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; progressSpeed = speed;
var speed = (totalRead * 1d / ts.TotalMilliseconds / 1000).ToString("#0.0"); progress.Report(speed);
if (progressSpeed != speed)
{
progressSpeed = speed;
progress.Report(speed);
}
} }
} }
} while (isMoreToRead); }
} } while (isMoreToRead);
} }
} }

View File

@ -34,7 +34,7 @@ namespace v2rayN.Base
public static IEnumerable<string> NonWhiteSpaceLines(this TextReader reader) public static IEnumerable<string> NonWhiteSpaceLines(this TextReader reader)
{ {
string line; string? line;
while ((line = reader.ReadLine()) != null) while ((line = reader.ReadLine()) != null)
{ {
if (line.IsWhiteSpace()) continue; if (line.IsWhiteSpace()) continue;

View File

@ -1021,7 +1021,17 @@ namespace v2rayN.Handler
return -1; 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 //Is v2ray configuration
V2rayConfig v2rayConfig = Utils.FromJson<V2rayConfig>(clipboardData); V2rayConfig v2rayConfig = Utils.FromJson<V2rayConfig>(clipboardData);
if (v2rayConfig != null if (v2rayConfig != null
@ -1038,9 +1048,7 @@ namespace v2rayN.Handler
profileItem.remarks = "v2ray_custom"; profileItem.remarks = "v2ray_custom";
} }
//Is Clash configuration //Is Clash configuration
else if (clipboardData.IndexOf("port") >= 0 else if (Containss(clipboardData, "port", "socks-port", "proxies"))
&& clipboardData.IndexOf("socks-port") >= 0
&& clipboardData.IndexOf("proxies") >= 0)
{ {
var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.yaml"); var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.yaml");
File.WriteAllText(fileName, clipboardData); File.WriteAllText(fileName, clipboardData);
@ -1050,12 +1058,7 @@ namespace v2rayN.Handler
profileItem.remarks = "clash_custom"; profileItem.remarks = "clash_custom";
} }
//Is hysteria configuration //Is hysteria configuration
else if (clipboardData.IndexOf("server") >= 0 else if (Containss(clipboardData, "server", "up", "down", "listen", "<html>", "<body>"))
&& clipboardData.IndexOf("up") >= 0
&& clipboardData.IndexOf("down") >= 0
&& clipboardData.IndexOf("listen") >= 0
&& clipboardData.IndexOf("<html>") < 0
&& clipboardData.IndexOf("<body>") < 0)
{ {
var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.json"); var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.json");
File.WriteAllText(fileName, clipboardData); File.WriteAllText(fileName, clipboardData);
@ -1065,10 +1068,7 @@ namespace v2rayN.Handler
profileItem.remarks = "hysteria_custom"; profileItem.remarks = "hysteria_custom";
} }
//Is naiveproxy configuration //Is naiveproxy configuration
else if (clipboardData.IndexOf("listen") >= 0 else if (Containss(clipboardData, "listen", "proxy", "<html>", "<body>"))
&& clipboardData.IndexOf("proxy") >= 0
&& clipboardData.IndexOf("<html>") < 0
&& clipboardData.IndexOf("<body>") < 0)
{ {
var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.json"); var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.json");
File.WriteAllText(fileName, clipboardData); File.WriteAllText(fileName, clipboardData);

View File

@ -189,24 +189,21 @@ namespace v2rayN.Handler
//判断是否使用代理 //判断是否使用代理
public static bool UsedProxy() 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") if (rk.GetValue("ProxyEnable").ToString() == "1")
{ {
rk.Close();
return true; return true;
} }
else else
{ {
rk.Close();
return false; return false;
} }
} }
//获得代理的IP和端口 //获得代理的IP和端口
public static string GetProxyProxyServer() 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(); string ProxyServer = rk.GetValue("ProxyServer").ToString();
rk.Close();
return ProxyServer; return ProxyServer;
} }

View File

@ -21,28 +21,18 @@ namespace v2rayN.Handler
{ {
try try
{ {
string url = string.Empty; string? url = string.Empty;
switch (item.configType) url = item.configType switch
{ {
case EConfigType.VMess: EConfigType.VMess => ShareVmess(item),
url = ShareVmess(item); EConfigType.Shadowsocks => ShareShadowsocks(item),
break; EConfigType.Socks => ShareSocks(item),
case EConfigType.Shadowsocks: EConfigType.Trojan => ShareTrojan(item),
url = ShareShadowsocks(item); EConfigType.VLESS => ShareVLESS(item),
break; _ => null,
case EConfigType.Socks: };
url = ShareSocks(item);
break;
case EConfigType.Trojan:
url = ShareTrojan(item);
break;
case EConfigType.VLESS:
url = ShareVLESS(item);
break;
default:
break;
}
return url; return url;
} }
catch (Exception ex) catch (Exception ex)
@ -285,7 +275,7 @@ namespace v2rayN.Handler
{ {
msg = string.Empty; msg = string.Empty;
ProfileItem profileItem = new ProfileItem(); ProfileItem profileItem = new ProfileItem();
try try
{ {
//载入配置文件 //载入配置文件

View File

@ -10,8 +10,8 @@ namespace v2rayN.Tool
{ {
try try
{ {
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) using FileStream fs = new(fileName, FileMode.Create, FileAccess.Write);
fs.Write(content, 0, content.Length); fs.Write(content);
return true; return true;
} }
catch (Exception ex) catch (Exception ex)
@ -20,25 +20,14 @@ namespace v2rayN.Tool
} }
return false; return false;
} }
public static void UncompressFile(string fileName, byte[] content) public static void UncompressFile(string fileName, byte[] content)
{ {
try try
{ {
// Because the uncompressed size of the file is unknown, using FileStream fs = File.Create(fileName);
// we are using an arbitrary buffer size. using GZipStream input = new(new MemoryStream(content), CompressionMode.Decompress, false);
byte[] buffer = new byte[4096]; input.CopyTo(fs);
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);
}
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -55,11 +44,9 @@ namespace v2rayN.Tool
{ {
try try
{ {
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader sr = new StreamReader(fs, encoding)) using StreamReader sr = new(fs, encoding);
{ return sr.ReadToEnd();
return sr.ReadToEnd();
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -71,26 +58,24 @@ namespace v2rayN.Tool
{ {
try 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; continue;
} }
try entry.ExtractToFile(Path.Combine(toPath, entry.Name), true);
{ }
if (!Utils.IsNullOrEmpty(ignoredName) && entry.Name.Contains(ignoredName)) catch (IOException ex)
{ {
continue; Utils.SaveLog(ex.Message, ex);
}
entry.ExtractToFile(Path.Combine(toPath, entry.Name), true);
}
catch (IOException ex)
{
Utils.SaveLog(ex.Message, ex);
}
} }
} }
} }

View File

@ -48,11 +48,9 @@ namespace v2rayN
try try
{ {
Assembly assembly = Assembly.GetExecutingAssembly(); Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(res)) using Stream stream = assembly.GetManifestResourceStream(res);
using (StreamReader reader = new StreamReader(stream)) using StreamReader reader = new(stream);
{ result = reader.ReadToEnd();
result = reader.ReadToEnd();
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -76,10 +74,8 @@ namespace v2rayN
{ {
return result; return result;
} }
using (StreamReader reader = new StreamReader(res)) using StreamReader reader = new(res);
{ result = reader.ReadToEnd();
result = reader.ReadToEnd();
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -150,20 +146,18 @@ namespace v2rayN
int result; int result;
try try
{ {
using (StreamWriter file = File.CreateText(filePath)) using StreamWriter file = File.CreateText(filePath);
JsonSerializer serializer;
if (nullValue)
{ {
JsonSerializer serializer; serializer = new JsonSerializer() { Formatting = Formatting.Indented };
if (nullValue)
{
serializer = new JsonSerializer() { Formatting = Formatting.Indented };
}
else
{
serializer = new JsonSerializer() { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore };
}
serializer.Serialize(file, obj);
} }
else
{
serializer = new JsonSerializer() { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore };
}
serializer.Serialize(file, obj);
result = 0; result = 0;
} }
catch (Exception ex) catch (Exception ex)
@ -248,7 +242,7 @@ namespace v2rayN
try try
{ {
str = str.Replace(Environment.NewLine, ""); str = str.Replace(Environment.NewLine, "");
List<string> list = new List<string>(str.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)); List<string> list = new(str.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
return list.OrderBy(x => x).ToList(); return list.OrderBy(x => x).ToList();
} }
catch (Exception ex) catch (Exception ex)
@ -341,7 +335,7 @@ namespace v2rayN
{ {
try try
{ {
return (obj == null ? string.Empty : obj.ToString()); return obj?.ToString() ?? string.Empty;
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -418,10 +412,9 @@ namespace v2rayN
public static string GetMD5(string str) public static string GetMD5(string str)
{ {
var md5 = MD5.Create();
byte[] byteOld = Encoding.UTF8.GetBytes(str); byte[] byteOld = Encoding.UTF8.GetBytes(str);
byte[] byteNew = md5.ComputeHash(byteOld); byte[] byteNew = MD5.HashData(byteOld);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new(32);
foreach (byte b in byteNew) foreach (byte b in byteNew)
{ {
sb.Append(b.ToString("x2")); sb.Append(b.ToString("x2"));
@ -444,7 +437,7 @@ namespace v2rayN
} }
try try
{ {
Uri uri = new Uri(url); Uri uri = new(url);
if (uri.Host == uri.IdnHost) if (uri.Host == uri.IdnHost)
{ {
return url; return url;
@ -572,18 +565,14 @@ namespace v2rayN
public static bool IsIpv6(string ip) public static bool IsIpv6(string ip)
{ {
IPAddress address; if (IPAddress.TryParse(ip, out IPAddress? address))
if (IPAddress.TryParse(ip, out address))
{ {
switch (address.AddressFamily) return address.AddressFamily switch
{ {
case AddressFamily.InterNetwork: AddressFamily.InterNetwork => false,
return false; AddressFamily.InterNetworkV6 => true,
case AddressFamily.InterNetworkV6: _ => false,
return true; };
default:
return false;
}
} }
return false; return false;
} }
@ -688,11 +677,11 @@ namespace v2rayN
public static string RegReadValue(string path, string name, string def) public static string RegReadValue(string path, string name, string def)
{ {
RegistryKey regKey = null; RegistryKey? regKey = null;
try try
{ {
regKey = Registry.CurrentUser.OpenSubKey(path, false); regKey = Registry.CurrentUser.OpenSubKey(path, false);
string value = regKey?.GetValue(name) as string; string? value = regKey?.GetValue(name) as string;
if (IsNullOrEmpty(value)) if (IsNullOrEmpty(value))
{ {
return def; return def;
@ -715,7 +704,7 @@ namespace v2rayN
public static void RegWriteValue(string path, string name, object value) public static void RegWriteValue(string path, string name, object value)
{ {
RegistryKey regKey = null; RegistryKey? regKey = null;
try try
{ {
regKey = Registry.CurrentUser.CreateSubKey(path); regKey = Registry.CurrentUser.CreateSubKey(path);
@ -747,14 +736,12 @@ namespace v2rayN
public static bool CheckForDotNetVersion(int release = 528040) public static bool CheckForDotNetVersion(int release = 528040)
{ {
const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"; 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 (int)ndpKey.GetValue("Release") >= release ? true : false;
}
return false;
} }
return false;
} }
/// <summary> /// <summary>
@ -775,31 +762,29 @@ namespace v2rayN
string taskDescription = description; string taskDescription = description;
string deamonFileName = fileName; 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)); taskService.RootFolder.DeleteTask(t.Name);
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);
} }
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 #endregion
@ -908,16 +893,13 @@ namespace v2rayN
public static T DeepCopy<T>(T obj) public static T DeepCopy<T>(T obj)
{ {
object retval; object retval;
using (MemoryStream ms = new MemoryStream()) MemoryStream ms = new MemoryStream();
{ BinaryFormatter bf = new BinaryFormatter();
BinaryFormatter bf = new BinaryFormatter(); //序列化成流
//序列化成流 bf.Serialize(ms, obj);
bf.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin);
ms.Seek(0, SeekOrigin.Begin); //反序列化成对象
//反序列化成对象 retval = bf.Deserialize(ms);
retval = bf.Deserialize(ms);
ms.Close();
}
return (T)retval; return (T)retval;
} }
@ -1075,14 +1057,11 @@ namespace v2rayN
public static string UnGzip(byte[] buf) public static string UnGzip(byte[] buf)
{ {
MemoryStream sb = new MemoryStream(); using MemoryStream sb = new();
using (GZipStream input = new GZipStream(new MemoryStream(buf), using GZipStream input = new(new MemoryStream(buf), CompressionMode.Decompress, false);
CompressionMode.Decompress, input.CopyTo(sb);
false)) sb.Position = 0;
{ return new StreamReader(sb, Encoding.UTF8).ReadToEnd();
input.CopyTo(sb);
}
return Encoding.UTF8.GetString(sb.ToArray());
} }
public static string GetBackupPath(string filename) public static string GetBackupPath(string filename)
@ -1198,42 +1177,40 @@ namespace v2rayN
{ {
foreach (Screen screen in Screen.AllScreens) foreach (Screen screen in Screen.AllScreens)
{ {
using (Bitmap fullImage = new Bitmap(screen.Bounds.Width, using Bitmap fullImage = new Bitmap(screen.Bounds.Width,
screen.Bounds.Height)) 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, g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),
screen.Bounds.Y, cropRect,
0, 0, GraphicsUnit.Pixel);
fullImage.Size,
CopyPixelOperation.SourceCopy);
} }
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); string ret = result.Text;
int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry); return ret;
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;
}
} }
} }
} }