mirror of https://github.com/2dust/v2rayN
Refactor Utils
parent
4eb443e547
commit
6b99b7eec5
|
@ -2,7 +2,6 @@
|
|||
using CliWrap.Buffered;
|
||||
using System.Collections.Specialized;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
|
@ -11,13 +10,12 @@ using System.Runtime.InteropServices;
|
|||
using System.Security.Cryptography;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace ServiceLib.Common
|
||||
{
|
||||
public class Utils
|
||||
{
|
||||
#region 资源Json操作
|
||||
#region 资源操作
|
||||
|
||||
/// <summary>
|
||||
/// 获取嵌入文本资源
|
||||
|
@ -26,12 +24,12 @@ namespace ServiceLib.Common
|
|||
/// <returns></returns>
|
||||
public static string GetEmbedText(string res)
|
||||
{
|
||||
string result = string.Empty;
|
||||
var result = string.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
Assembly assembly = Assembly.GetExecutingAssembly();
|
||||
using Stream? stream = assembly.GetManifestResourceStream(res);
|
||||
var assembly = Assembly.GetExecutingAssembly();
|
||||
using var stream = assembly.GetManifestResourceStream(res);
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
using StreamReader reader = new(stream);
|
||||
result = reader.ReadToEnd();
|
||||
|
@ -51,11 +49,10 @@ namespace ServiceLib.Common
|
|||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(res))
|
||||
if (File.Exists(res))
|
||||
{
|
||||
return null;
|
||||
return File.ReadAllText(res);
|
||||
}
|
||||
return File.ReadAllText(res);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
@ -64,14 +61,15 @@ namespace ServiceLib.Common
|
|||
return null;
|
||||
}
|
||||
|
||||
#endregion 资源Json操作
|
||||
#endregion 资源操作
|
||||
|
||||
#region 转换函数
|
||||
|
||||
/// <summary>
|
||||
/// List<string>转逗号分隔的字符串
|
||||
/// 转逗号分隔的字符串
|
||||
/// </summary>
|
||||
/// <param name="lst"></param>
|
||||
/// <param name="wrap"></param>
|
||||
/// <returns></returns>
|
||||
public static string List2String(List<string>? lst, bool wrap = false)
|
||||
{
|
||||
|
@ -93,35 +91,40 @@ namespace ServiceLib.Common
|
|||
catch (Exception ex)
|
||||
{
|
||||
Logging.SaveLog(ex.Message, ex);
|
||||
return string.Empty;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 逗号分隔的字符串,转List<string>
|
||||
/// 逗号分隔的字符串
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static List<string> String2List(string str)
|
||||
public static List<string>? String2List(string? str)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (str == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
str = str.Replace(Environment.NewLine, "");
|
||||
return new List<string>(str.Split(',', StringSplitOptions.RemoveEmptyEntries));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logging.SaveLog(ex.Message, ex);
|
||||
return [];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 逗号分隔的字符串,先排序后转List<string>
|
||||
/// 逗号分隔的字符串,先排序后转List
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static List<string> String2ListSorted(string str)
|
||||
public static List<string>? String2ListSorted(string str)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -133,8 +136,8 @@ namespace ServiceLib.Common
|
|||
catch (Exception ex)
|
||||
{
|
||||
Logging.SaveLog(ex.Message, ex);
|
||||
return [];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -146,14 +149,14 @@ namespace ServiceLib.Common
|
|||
{
|
||||
try
|
||||
{
|
||||
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
|
||||
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
|
||||
return Convert.ToBase64String(plainTextBytes);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logging.SaveLog("Base64Encode", ex);
|
||||
return string.Empty;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -179,30 +182,24 @@ namespace ServiceLib.Common
|
|||
plainText = plainText.PadRight(plainText.Length + 4 - plainText.Length % 4, '=');
|
||||
}
|
||||
|
||||
byte[] data = Convert.FromBase64String(plainText);
|
||||
var data = Convert.FromBase64String(plainText);
|
||||
return Encoding.UTF8.GetString(data);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logging.SaveLog("Base64Decode", ex);
|
||||
return string.Empty;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转Int
|
||||
/// </summary>
|
||||
/// <param name="obj"></param>
|
||||
/// <returns></returns>
|
||||
public static int ToInt(object? obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Convert.ToInt32(obj ?? string.Empty);
|
||||
}
|
||||
catch //(Exception ex)
|
||||
catch
|
||||
{
|
||||
//SaveLog(ex.Message, ex);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
@ -213,50 +210,47 @@ namespace ServiceLib.Common
|
|||
{
|
||||
return Convert.ToBoolean(obj);
|
||||
}
|
||||
catch //(Exception ex)
|
||||
catch
|
||||
{
|
||||
//SaveLog(ex.Message, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static string ToString(object obj)
|
||||
public static string ToString(object? obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return obj?.ToString() ?? string.Empty;
|
||||
}
|
||||
catch// (Exception ex)
|
||||
catch
|
||||
{
|
||||
//SaveLog(ex.Message, ex);
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// byte 转成 有两位小数点的 方便阅读的数据
|
||||
/// 比如 2.50 MB
|
||||
/// byte 转成 有两位小数点的 方便阅读的数据 比如 2.50 MB
|
||||
/// </summary>
|
||||
/// <param name="amount">bytes</param>
|
||||
/// <param name="result">转换之后的数据</param>
|
||||
/// <param name="unit">单位</param>
|
||||
public static void ToHumanReadable(long amount, out double result, out string unit)
|
||||
private static void ToHumanReadable(long amount, out double result, out string unit)
|
||||
{
|
||||
uint factor = 1024u;
|
||||
var factor = 1024u;
|
||||
//long KBs = amount / factor;
|
||||
long KBs = amount;
|
||||
var KBs = amount;
|
||||
if (KBs > 0)
|
||||
{
|
||||
// multi KB
|
||||
long MBs = KBs / factor;
|
||||
var MBs = KBs / factor;
|
||||
if (MBs > 0)
|
||||
{
|
||||
// multi MB
|
||||
long GBs = MBs / factor;
|
||||
var GBs = MBs / factor;
|
||||
if (GBs > 0)
|
||||
{
|
||||
// multi GB
|
||||
long TBs = GBs / factor;
|
||||
var TBs = GBs / factor;
|
||||
if (TBs > 0)
|
||||
{
|
||||
result = TBs + ((GBs % factor) / (factor + 0.0));
|
||||
|
@ -284,20 +278,18 @@ namespace ServiceLib.Common
|
|||
|
||||
public static string HumanFy(long amount)
|
||||
{
|
||||
ToHumanReadable(amount, out double result, out string unit);
|
||||
return $"{string.Format("{0:f1}", result)} {unit}";
|
||||
ToHumanReadable(amount, out var result, out var unit);
|
||||
return $"{result:f1} {unit}";
|
||||
}
|
||||
|
||||
public static string UrlEncode(string url)
|
||||
{
|
||||
return Uri.EscapeDataString(url);
|
||||
//return HttpUtility.UrlEncode(url);
|
||||
}
|
||||
|
||||
public static string UrlDecode(string url)
|
||||
{
|
||||
return Uri.UnescapeDataString(url);
|
||||
//return HttpUtility.UrlDecode(url);
|
||||
}
|
||||
|
||||
public static NameValueCollection ParseQueryString(string query)
|
||||
|
@ -308,10 +300,10 @@ namespace ServiceLib.Common
|
|||
return result;
|
||||
}
|
||||
|
||||
var parts = query[1..].Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
var parts = query[1..].Split('&', StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (var part in parts)
|
||||
{
|
||||
var keyValue = part.Split(['=']);
|
||||
var keyValue = part.Split('=');
|
||||
if (keyValue.Length != 2)
|
||||
{
|
||||
continue;
|
||||
|
@ -328,12 +320,12 @@ namespace ServiceLib.Common
|
|||
return result;
|
||||
}
|
||||
|
||||
public static string GetMD5(string str)
|
||||
public static string GetMd5(string str)
|
||||
{
|
||||
byte[] byteOld = Encoding.UTF8.GetBytes(str);
|
||||
byte[] byteNew = MD5.HashData(byteOld);
|
||||
var byteOld = Encoding.UTF8.GetBytes(str);
|
||||
var byteNew = MD5.HashData(byteOld);
|
||||
StringBuilder sb = new(32);
|
||||
foreach (byte b in byteNew)
|
||||
foreach (var b in byteNew)
|
||||
{
|
||||
sb.Append(b.ToString("x2"));
|
||||
}
|
||||
|
@ -373,12 +365,12 @@ namespace ServiceLib.Common
|
|||
{
|
||||
if (plainText.IsNullOrEmpty()) return false;
|
||||
var buffer = new Span<byte>(new byte[plainText.Length]);
|
||||
return Convert.TryFromBase64String(plainText, buffer, out int _);
|
||||
return Convert.TryFromBase64String(plainText, buffer, out var _);
|
||||
}
|
||||
|
||||
public static string Convert2Comma(string text)
|
||||
{
|
||||
if (Utils.IsNullOrEmpty(text))
|
||||
if (IsNullOrEmpty(text))
|
||||
{
|
||||
return text;
|
||||
}
|
||||
|
@ -396,16 +388,7 @@ namespace ServiceLib.Common
|
|||
/// <returns></returns>
|
||||
public static bool IsNumeric(string oText)
|
||||
{
|
||||
try
|
||||
{
|
||||
int var1 = ToInt(oText);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logging.SaveLog(ex.Message, ex);
|
||||
return false;
|
||||
}
|
||||
return oText.All(char.IsNumber);
|
||||
}
|
||||
|
||||
public static bool IsNullOrEmpty(string? text)
|
||||
|
@ -414,11 +397,7 @@ namespace ServiceLib.Common
|
|||
{
|
||||
return true;
|
||||
}
|
||||
if (text == "null")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return text == "null";
|
||||
}
|
||||
|
||||
public static bool IsNotEmpty(string? text)
|
||||
|
@ -426,41 +405,6 @@ namespace ServiceLib.Common
|
|||
return !string.IsNullOrEmpty(text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证IP地址是否合法
|
||||
/// </summary>
|
||||
/// <param name="ip"></param>
|
||||
public static bool IsIP(string ip)
|
||||
{
|
||||
//如果为空
|
||||
if (IsNullOrEmpty(ip))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
//清除要验证字符串中的空格
|
||||
//ip = ip.TrimEx();
|
||||
//可能是CIDR
|
||||
if (ip.IndexOf(@"/") > 0)
|
||||
{
|
||||
string[] cidr = ip.Split('/');
|
||||
if (cidr.Length == 2)
|
||||
{
|
||||
if (!IsNumeric(cidr[0]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
ip = cidr[0];
|
||||
}
|
||||
}
|
||||
|
||||
//模式字符串
|
||||
string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
|
||||
|
||||
//验证
|
||||
return IsMatch(ip, pattern);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证Domain地址是否合法
|
||||
/// </summary>
|
||||
|
@ -476,19 +420,9 @@ namespace ServiceLib.Common
|
|||
return Uri.CheckHostName(domain) == UriHostNameType.Dns;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证输入字符串是否与模式字符串匹配,匹配返回true
|
||||
/// </summary>
|
||||
/// <param name="input">输入字符串</param>
|
||||
/// <param name="pattern">模式字符串</param>
|
||||
public static bool IsMatch(string input, string pattern)
|
||||
{
|
||||
return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase);
|
||||
}
|
||||
|
||||
public static bool IsIpv6(string ip)
|
||||
{
|
||||
if (IPAddress.TryParse(ip, out IPAddress? address))
|
||||
if (IPAddress.TryParse(ip, out var address))
|
||||
{
|
||||
return address.AddressFamily switch
|
||||
{
|
||||
|
@ -504,43 +438,20 @@ namespace ServiceLib.Common
|
|||
|
||||
#region 测速
|
||||
|
||||
public static void SetSecurityProtocol(bool enableSecurityProtocolTls13)
|
||||
private static bool PortInUse(int port)
|
||||
{
|
||||
if (enableSecurityProtocolTls13)
|
||||
{
|
||||
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
|
||||
}
|
||||
else
|
||||
{
|
||||
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
|
||||
}
|
||||
ServicePointManager.DefaultConnectionLimit = 256;
|
||||
}
|
||||
|
||||
public static bool PortInUse(int port)
|
||||
{
|
||||
bool inUse = false;
|
||||
try
|
||||
{
|
||||
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
|
||||
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
|
||||
|
||||
var lstIpEndPoints = new List<IPEndPoint>(IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners());
|
||||
|
||||
foreach (IPEndPoint endPoint in ipEndPoints)
|
||||
{
|
||||
if (endPoint.Port == port)
|
||||
{
|
||||
inUse = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
|
||||
var ipEndPoints = ipProperties.GetActiveTcpListeners();
|
||||
//var lstIpEndPoints = new List<IPEndPoint>(IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners());
|
||||
return ipEndPoints.Any(endPoint => endPoint.Port == port);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logging.SaveLog(ex.Message, ex);
|
||||
}
|
||||
return inUse;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static int GetFreePort(int defaultPort = 9090)
|
||||
|
@ -554,7 +465,7 @@ namespace ServiceLib.Common
|
|||
|
||||
TcpListener l = new(IPAddress.Loopback, 0);
|
||||
l.Start();
|
||||
int port = ((IPEndPoint)l.LocalEndpoint).Port;
|
||||
var port = ((IPEndPoint)l.LocalEndpoint).Port;
|
||||
l.Stop();
|
||||
return port;
|
||||
}
|
||||
|
@ -578,23 +489,18 @@ namespace ServiceLib.Common
|
|||
{
|
||||
if (blFull)
|
||||
{
|
||||
return string.Format("{0} - V{1} - {2}",
|
||||
Global.AppName,
|
||||
GetVersionInfo(),
|
||||
File.GetLastWriteTime(GetExePath()).ToString("yyyy/MM/dd"));
|
||||
return $"{Global.AppName} - V{GetVersionInfo()} - {File.GetLastWriteTime(GetExePath()):yyyy/MM/dd}";
|
||||
}
|
||||
else
|
||||
{
|
||||
return string.Format("{0}/{1}",
|
||||
Global.AppName,
|
||||
GetVersionInfo());
|
||||
return $"{Global.AppName}/{GetVersionInfo()}";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logging.SaveLog(ex.Message, ex);
|
||||
return Global.AppName;
|
||||
}
|
||||
return Global.AppName;
|
||||
}
|
||||
|
||||
public static string GetVersionInfo()
|
||||
|
@ -614,7 +520,7 @@ namespace ServiceLib.Common
|
|||
/// 取得GUID
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetGUID(bool full = true)
|
||||
public static string GetGuid(bool full = true)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -634,14 +540,6 @@ namespace ServiceLib.Common
|
|||
return string.Empty;
|
||||
}
|
||||
|
||||
public static string GetDownloadFileName(string url)
|
||||
{
|
||||
var fileName = Path.GetFileName(url);
|
||||
fileName += "_temp";
|
||||
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public static bool IsGuidByParse(string strSrc)
|
||||
{
|
||||
return Guid.TryParse(strSrc, out _);
|
||||
|
@ -667,12 +565,12 @@ namespace ServiceLib.Common
|
|||
public static Dictionary<string, string> GetSystemHosts()
|
||||
{
|
||||
var systemHosts = new Dictionary<string, string>();
|
||||
var hostfile = @"C:\Windows\System32\drivers\etc\hosts";
|
||||
var hostFile = @"C:\Windows\System32\drivers\etc\hosts";
|
||||
try
|
||||
{
|
||||
if (File.Exists(hostfile))
|
||||
if (File.Exists(hostFile))
|
||||
{
|
||||
var hosts = File.ReadAllText(hostfile).Replace("\r", "");
|
||||
var hosts = File.ReadAllText(hostFile).Replace("\r", "");
|
||||
var hostsList = hosts.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
foreach (var host in hostsList)
|
||||
|
@ -693,10 +591,10 @@ namespace ServiceLib.Common
|
|||
|
||||
public static async Task<string?> GetCliWrapOutput(string filePath, string? arg)
|
||||
{
|
||||
return await GetCliWrapOutput(filePath, arg != null ? [arg] : null);
|
||||
return await GetCliWrapOutput(filePath, arg != null ? new List<string>() { arg } : null);
|
||||
}
|
||||
|
||||
public static async Task<string?> GetCliWrapOutput(string filePath, IEnumerable<string>? args)
|
||||
private static async Task<string?> GetCliWrapOutput(string filePath, IEnumerable<string>? args)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
@ -736,7 +634,7 @@ namespace ServiceLib.Common
|
|||
/// <returns></returns>
|
||||
public static string GetPath(string fileName)
|
||||
{
|
||||
string startupPath = StartupPath();
|
||||
var startupPath = StartupPath();
|
||||
if (IsNullOrEmpty(fileName))
|
||||
{
|
||||
return startupPath;
|
||||
|
@ -760,113 +658,104 @@ namespace ServiceLib.Common
|
|||
|
||||
public static string GetTempPath(string filename = "")
|
||||
{
|
||||
string _tempPath = Path.Combine(StartupPath(), "guiTemps");
|
||||
if (!Directory.Exists(_tempPath))
|
||||
var tempPath = Path.Combine(StartupPath(), "guiTemps");
|
||||
if (!Directory.Exists(tempPath))
|
||||
{
|
||||
Directory.CreateDirectory(_tempPath);
|
||||
Directory.CreateDirectory(tempPath);
|
||||
}
|
||||
if (Utils.IsNullOrEmpty(filename))
|
||||
if (IsNullOrEmpty(filename))
|
||||
{
|
||||
return _tempPath;
|
||||
return tempPath;
|
||||
}
|
||||
else
|
||||
{
|
||||
return Path.Combine(_tempPath, filename);
|
||||
return Path.Combine(tempPath, filename);
|
||||
}
|
||||
}
|
||||
|
||||
public static string UnGzip(byte[] buf)
|
||||
{
|
||||
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)
|
||||
{
|
||||
string _tempPath = Path.Combine(StartupPath(), "guiBackups");
|
||||
if (!Directory.Exists(_tempPath))
|
||||
var tempPath = Path.Combine(StartupPath(), "guiBackups");
|
||||
if (!Directory.Exists(tempPath))
|
||||
{
|
||||
Directory.CreateDirectory(_tempPath);
|
||||
Directory.CreateDirectory(tempPath);
|
||||
}
|
||||
return Path.Combine(_tempPath, filename);
|
||||
return Path.Combine(tempPath, filename);
|
||||
}
|
||||
|
||||
public static string GetConfigPath(string filename = "")
|
||||
{
|
||||
string _tempPath = Path.Combine(StartupPath(), "guiConfigs");
|
||||
if (!Directory.Exists(_tempPath))
|
||||
var tempPath = Path.Combine(StartupPath(), "guiConfigs");
|
||||
if (!Directory.Exists(tempPath))
|
||||
{
|
||||
Directory.CreateDirectory(_tempPath);
|
||||
Directory.CreateDirectory(tempPath);
|
||||
}
|
||||
if (Utils.IsNullOrEmpty(filename))
|
||||
{
|
||||
return _tempPath;
|
||||
return tempPath;
|
||||
}
|
||||
else
|
||||
{
|
||||
return Path.Combine(_tempPath, filename);
|
||||
return Path.Combine(tempPath, filename);
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetBinPath(string filename, string? coreType = null)
|
||||
{
|
||||
string _tempPath = Path.Combine(StartupPath(), "bin");
|
||||
if (!Directory.Exists(_tempPath))
|
||||
var tempPath = Path.Combine(StartupPath(), "bin");
|
||||
if (!Directory.Exists(tempPath))
|
||||
{
|
||||
Directory.CreateDirectory(_tempPath);
|
||||
Directory.CreateDirectory(tempPath);
|
||||
}
|
||||
if (coreType != null)
|
||||
{
|
||||
_tempPath = Path.Combine(_tempPath, coreType.ToString());
|
||||
if (!Directory.Exists(_tempPath))
|
||||
tempPath = Path.Combine(tempPath, coreType.ToString());
|
||||
if (!Directory.Exists(tempPath))
|
||||
{
|
||||
Directory.CreateDirectory(_tempPath);
|
||||
Directory.CreateDirectory(tempPath);
|
||||
}
|
||||
}
|
||||
if (Utils.IsNullOrEmpty(filename))
|
||||
if (IsNullOrEmpty(filename))
|
||||
{
|
||||
return _tempPath;
|
||||
return tempPath;
|
||||
}
|
||||
else
|
||||
{
|
||||
return Path.Combine(_tempPath, filename);
|
||||
return Path.Combine(tempPath, filename);
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetLogPath(string filename = "")
|
||||
{
|
||||
string _tempPath = Path.Combine(StartupPath(), "guiLogs");
|
||||
if (!Directory.Exists(_tempPath))
|
||||
var tempPath = Path.Combine(StartupPath(), "guiLogs");
|
||||
if (!Directory.Exists(tempPath))
|
||||
{
|
||||
Directory.CreateDirectory(_tempPath);
|
||||
Directory.CreateDirectory(tempPath);
|
||||
}
|
||||
if (Utils.IsNullOrEmpty(filename))
|
||||
{
|
||||
return _tempPath;
|
||||
return tempPath;
|
||||
}
|
||||
else
|
||||
{
|
||||
return Path.Combine(_tempPath, filename);
|
||||
return Path.Combine(tempPath, filename);
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetFontsPath(string filename = "")
|
||||
{
|
||||
string _tempPath = Path.Combine(StartupPath(), "guiFonts");
|
||||
if (!Directory.Exists(_tempPath))
|
||||
var tempPath = Path.Combine(StartupPath(), "guiFonts");
|
||||
if (!Directory.Exists(tempPath))
|
||||
{
|
||||
Directory.CreateDirectory(_tempPath);
|
||||
Directory.CreateDirectory(tempPath);
|
||||
}
|
||||
if (Utils.IsNullOrEmpty(filename))
|
||||
{
|
||||
return _tempPath;
|
||||
return tempPath;
|
||||
}
|
||||
else
|
||||
{
|
||||
return Path.Combine(_tempPath, filename);
|
||||
return Path.Combine(tempPath, filename);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -882,14 +771,7 @@ namespace ServiceLib.Common
|
|||
|
||||
public static string GetExeName(string name)
|
||||
{
|
||||
if (IsWindows())
|
||||
{
|
||||
return $"{name}.exe";
|
||||
}
|
||||
else
|
||||
{
|
||||
return name;
|
||||
}
|
||||
return IsWindows() ? $"{name}.exe" : name;
|
||||
}
|
||||
|
||||
public static bool IsAdministrator()
|
||||
|
@ -901,7 +783,7 @@ namespace ServiceLib.Common
|
|||
else
|
||||
{
|
||||
var id = GetLinuxUserId().Result ?? "1000";
|
||||
if (int.TryParse(id, out int userId))
|
||||
if (int.TryParse(id, out var userId))
|
||||
{
|
||||
return userId == 0;
|
||||
}
|
||||
|
@ -914,7 +796,8 @@ namespace ServiceLib.Common
|
|||
|
||||
private static async Task<string?> GetLinuxUserId()
|
||||
{
|
||||
return await GetCliWrapOutput("/bin/bash", ["-c", "id -u"]);
|
||||
var arg = new List<string>() { "-c", "id -u" };
|
||||
return await GetCliWrapOutput("/bin/bash", arg);
|
||||
}
|
||||
|
||||
#endregion Platform
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
using System.Data;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Web;
|
||||
|
||||
namespace ServiceLib.Handler
|
||||
{
|
||||
|
@ -494,7 +493,7 @@ namespace ServiceLib.Handler
|
|||
return -1;
|
||||
}
|
||||
var ext = Path.GetExtension(fileName);
|
||||
string newFileName = $"{Utils.GetGUID()}{ext}";
|
||||
string newFileName = $"{Utils.GetGuid()}{ext}";
|
||||
//newFileName = Path.Combine(Utile.GetTempPath(), newFileName);
|
||||
|
||||
try
|
||||
|
@ -934,7 +933,7 @@ namespace ServiceLib.Handler
|
|||
var maxSort = -1;
|
||||
if (Utils.IsNullOrEmpty(profileItem.indexId))
|
||||
{
|
||||
profileItem.indexId = Utils.GetGUID(false);
|
||||
profileItem.indexId = Utils.GetGuid(false);
|
||||
maxSort = ProfileExHandler.Instance.GetMaxSort();
|
||||
}
|
||||
if (!toFile && maxSort < 0)
|
||||
|
@ -1002,7 +1001,7 @@ namespace ServiceLib.Handler
|
|||
|
||||
public static int AddCustomServer4Multiple(Config config, List<ProfileItem> selecteds, ECoreType coreType, out string indexId)
|
||||
{
|
||||
indexId = Utils.GetMD5(Global.CoreMultipleLoadConfigFileName);
|
||||
indexId = Utils.GetMd5(Global.CoreMultipleLoadConfigFileName);
|
||||
string configPath = Utils.GetConfigPath(Global.CoreMultipleLoadConfigFileName);
|
||||
if (CoreConfigHandler.GenerateClientMultipleLoadConfig(config, configPath, selecteds, coreType, out string msg) != 0)
|
||||
{
|
||||
|
@ -1341,7 +1340,7 @@ namespace ServiceLib.Handler
|
|||
try
|
||||
{
|
||||
var uri = new Uri(url);
|
||||
var queryVars = HttpUtility.ParseQueryString(uri.Query);
|
||||
var queryVars = Utils.ParseQueryString(uri.Query);
|
||||
subItem.remarks = queryVars["remarks"] ?? "import_sub";
|
||||
}
|
||||
catch (UriFormatException)
|
||||
|
@ -1378,7 +1377,7 @@ namespace ServiceLib.Handler
|
|||
|
||||
if (Utils.IsNullOrEmpty(item.id))
|
||||
{
|
||||
item.id = Utils.GetGUID(false);
|
||||
item.id = Utils.GetGuid(false);
|
||||
|
||||
if (item.sort <= 0)
|
||||
{
|
||||
|
@ -1461,7 +1460,7 @@ namespace ServiceLib.Handler
|
|||
{
|
||||
if (Utils.IsNullOrEmpty(item.id))
|
||||
{
|
||||
item.id = Utils.GetGUID(false);
|
||||
item.id = Utils.GetGuid(false);
|
||||
}
|
||||
|
||||
if (SQLiteHelper.Instance.Replace(item) > 0)
|
||||
|
@ -1495,14 +1494,14 @@ namespace ServiceLib.Handler
|
|||
|
||||
foreach (var item in lstRules)
|
||||
{
|
||||
item.id = Utils.GetGUID(false);
|
||||
item.id = Utils.GetGuid(false);
|
||||
}
|
||||
routingItem.ruleNum = lstRules.Count;
|
||||
routingItem.ruleSet = JsonUtils.Serialize(lstRules, false);
|
||||
|
||||
if (Utils.IsNullOrEmpty(routingItem.id))
|
||||
{
|
||||
routingItem.id = Utils.GetGUID(false);
|
||||
routingItem.id = Utils.GetGuid(false);
|
||||
}
|
||||
|
||||
if (SQLiteHelper.Instance.Replace(routingItem) > 0)
|
||||
|
@ -1711,7 +1710,7 @@ namespace ServiceLib.Handler
|
|||
{
|
||||
if (Utils.IsNullOrEmpty(item.id))
|
||||
{
|
||||
item.id = Utils.GetGUID(false);
|
||||
item.id = Utils.GetGuid(false);
|
||||
}
|
||||
|
||||
if (SQLiteHelper.Instance.Replace(item) > 0)
|
||||
|
|
|
@ -197,7 +197,7 @@ namespace ServiceLib.Handler.Fmt
|
|||
|
||||
protected static string WriteAllText(string strData, string ext = "json")
|
||||
{
|
||||
var fileName = Utils.GetTempPath($"{Utils.GetGUID(false)}.{ext}");
|
||||
var fileName = Utils.GetTempPath($"{Utils.GetGuid(false)}.{ext}");
|
||||
File.WriteAllText(fileName, strData);
|
||||
return fileName;
|
||||
}
|
||||
|
|
|
@ -70,12 +70,12 @@
|
|||
item.network = Global.DefaultNetwork;
|
||||
item.headerType = Global.None;
|
||||
|
||||
item.configVersion = Utils.ToInt(vmessQRCode.v);
|
||||
item.configVersion = vmessQRCode.v;
|
||||
item.remarks = Utils.ToString(vmessQRCode.ps);
|
||||
item.address = Utils.ToString(vmessQRCode.add);
|
||||
item.port = Utils.ToInt(vmessQRCode.port);
|
||||
item.port = vmessQRCode.port;
|
||||
item.id = Utils.ToString(vmessQRCode.id);
|
||||
item.alterId = Utils.ToInt(vmessQRCode.aid);
|
||||
item.alterId = vmessQRCode.aid;
|
||||
item.security = Utils.ToString(vmessQRCode.scy);
|
||||
|
||||
item.security = Utils.IsNotEmpty(vmessQRCode.scy) ? vmessQRCode.scy : Global.DefaultSecurity;
|
||||
|
|
|
@ -58,7 +58,7 @@ namespace ServiceLib.Models
|
|||
return summary;
|
||||
}
|
||||
|
||||
public List<string> GetAlpn()
|
||||
public List<string>? GetAlpn()
|
||||
{
|
||||
if (Utils.IsNullOrEmpty(alpn))
|
||||
{
|
||||
|
|
|
@ -120,10 +120,10 @@
|
|||
public string? version { get; set; }
|
||||
public string? network { get; set; }
|
||||
public string? packet_encoding { get; set; }
|
||||
public string[]? local_address { get; set; }
|
||||
public List<string>? local_address { get; set; }
|
||||
public string? private_key { get; set; }
|
||||
public string? peer_public_key { get; set; }
|
||||
public int[]? reserved { get; set; }
|
||||
public List<int>? reserved { get; set; }
|
||||
public int? mtu { get; set; }
|
||||
public string? plugin { get; set; }
|
||||
public string? plugin_opts { get; set; }
|
||||
|
@ -138,11 +138,11 @@
|
|||
public class Tls4Sbox
|
||||
{
|
||||
public bool enabled { get; set; }
|
||||
public string server_name { get; set; }
|
||||
public string? server_name { get; set; }
|
||||
public bool? insecure { get; set; }
|
||||
public List<string> alpn { get; set; }
|
||||
public Utls4Sbox utls { get; set; }
|
||||
public Reality4Sbox reality { get; set; }
|
||||
public List<string>? alpn { get; set; }
|
||||
public Utls4Sbox? utls { get; set; }
|
||||
public Reality4Sbox? reality { get; set; }
|
||||
}
|
||||
|
||||
public class Multiplex4Sbox
|
||||
|
|
|
@ -647,12 +647,12 @@ namespace ServiceLib.Models
|
|||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string path { get; set; }
|
||||
public string? path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public List<string> host { get; set; }
|
||||
public List<string>? host { get; set; }
|
||||
}
|
||||
|
||||
public class QuicSettings4Ray
|
||||
|
|
|
@ -678,8 +678,8 @@ namespace ServiceLib.Services.CoreConfig
|
|||
{
|
||||
outbound.private_key = node.id;
|
||||
outbound.peer_public_key = node.publicKey;
|
||||
outbound.reserved = Utils.String2List(node.path).Select(int.Parse).ToArray();
|
||||
outbound.local_address = [.. Utils.String2List(node.requestHost)];
|
||||
outbound.reserved = Utils.String2List(node.path)?.Select(int.Parse).ToList();
|
||||
outbound.local_address = Utils.String2List(node.requestHost);
|
||||
outbound.mtu = Utils.ToInt(node.shortId.IsNullOrEmpty() ? Global.TunMtus.FirstOrDefault() : node.shortId);
|
||||
break;
|
||||
}
|
||||
|
@ -732,7 +732,7 @@ namespace ServiceLib.Services.CoreConfig
|
|||
}
|
||||
else if (Utils.IsNotEmpty(node.requestHost))
|
||||
{
|
||||
server_name = Utils.String2List(node.requestHost)[0];
|
||||
server_name = Utils.String2List(node.requestHost)?.First();
|
||||
}
|
||||
var tls = new Tls4Sbox()
|
||||
{
|
||||
|
|
|
@ -829,7 +829,7 @@ namespace ServiceLib.Services.CoreConfig
|
|||
}
|
||||
else if (Utils.IsNotEmpty(host))
|
||||
{
|
||||
tlsSettings.serverName = Utils.String2List(host)[0];
|
||||
tlsSettings.serverName = Utils.String2List(host)?.First();
|
||||
}
|
||||
streamSettings.tlsSettings = tlsSettings;
|
||||
}
|
||||
|
|
|
@ -30,7 +30,7 @@ namespace ServiceLib.Services
|
|||
{
|
||||
try
|
||||
{
|
||||
Utils.SetSecurityProtocol(AppHandler.Instance.Config.guiItem.enableSecurityProtocolTls13);
|
||||
SetSecurityProtocol(AppHandler.Instance.Config.guiItem.enableSecurityProtocolTls13);
|
||||
|
||||
var progress = new Progress<string>();
|
||||
progress.ProgressChanged += (sender, value) =>
|
||||
|
@ -62,7 +62,7 @@ namespace ServiceLib.Services
|
|||
{
|
||||
try
|
||||
{
|
||||
Utils.SetSecurityProtocol(AppHandler.Instance.Config.guiItem.enableSecurityProtocolTls13);
|
||||
SetSecurityProtocol(AppHandler.Instance.Config.guiItem.enableSecurityProtocolTls13);
|
||||
UpdateCompleted?.Invoke(this, new ResultEventArgs(false, $"{ResUI.Downloading} {url}"));
|
||||
|
||||
var progress = new Progress<double>();
|
||||
|
@ -92,7 +92,7 @@ namespace ServiceLib.Services
|
|||
|
||||
public async Task<string?> UrlRedirectAsync(string url, bool blProxy)
|
||||
{
|
||||
Utils.SetSecurityProtocol(AppHandler.Instance.Config.guiItem.enableSecurityProtocolTls13);
|
||||
SetSecurityProtocol(AppHandler.Instance.Config.guiItem.enableSecurityProtocolTls13);
|
||||
var webRequestHandler = new SocketsHttpHandler
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
|
@ -181,7 +181,7 @@ namespace ServiceLib.Services
|
|||
{
|
||||
try
|
||||
{
|
||||
Utils.SetSecurityProtocol(AppHandler.Instance.Config.guiItem.enableSecurityProtocolTls13);
|
||||
SetSecurityProtocol(AppHandler.Instance.Config.guiItem.enableSecurityProtocolTls13);
|
||||
var webProxy = GetWebProxy(blProxy);
|
||||
var client = new HttpClient(new SocketsHttpHandler()
|
||||
{
|
||||
|
@ -226,7 +226,7 @@ namespace ServiceLib.Services
|
|||
{
|
||||
try
|
||||
{
|
||||
Utils.SetSecurityProtocol(AppHandler.Instance.Config.guiItem.enableSecurityProtocolTls13);
|
||||
SetSecurityProtocol(AppHandler.Instance.Config.guiItem.enableSecurityProtocolTls13);
|
||||
|
||||
var webProxy = GetWebProxy(blProxy);
|
||||
|
||||
|
@ -337,5 +337,18 @@ namespace ServiceLib.Services
|
|||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetSecurityProtocol(bool enableSecurityProtocolTls13)
|
||||
{
|
||||
if (enableSecurityProtocolTls13)
|
||||
{
|
||||
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
|
||||
}
|
||||
else
|
||||
{
|
||||
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
|
||||
}
|
||||
ServicePointManager.DefaultConnectionLimit = 256;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -56,7 +56,7 @@ namespace ServiceLib.Services
|
|||
_updateFunc?.Invoke(false, args.Msg);
|
||||
|
||||
url = args.Url;
|
||||
fileName = Utils.GetTempPath(Utils.GetGUID());
|
||||
fileName = Utils.GetTempPath(Utils.GetGuid());
|
||||
await downloadHandle.DownloadFileAsync(url, fileName, true, _timeout);
|
||||
}
|
||||
else
|
||||
|
@ -108,7 +108,7 @@ namespace ServiceLib.Services
|
|||
|
||||
url = args.Url;
|
||||
var ext = Path.GetExtension(url);
|
||||
fileName = Utils.GetTempPath(Utils.GetGUID() + ext);
|
||||
fileName = Utils.GetTempPath(Utils.GetGuid() + ext);
|
||||
await downloadHandle.DownloadFileAsync(url, fileName, true, _timeout);
|
||||
}
|
||||
else
|
||||
|
@ -451,7 +451,7 @@ namespace ServiceLib.Services
|
|||
_config = config;
|
||||
_updateFunc = updateFunc;
|
||||
var url = string.Format(Global.GeoUrl, geoName);
|
||||
var fileName = Utils.GetTempPath(Utils.GetGUID());
|
||||
var fileName = Utils.GetTempPath(Utils.GetGuid());
|
||||
|
||||
DownloadService downloadHandle = new();
|
||||
downloadHandle.UpdateCompleted += (sender2, args) =>
|
||||
|
|
|
@ -85,7 +85,7 @@ namespace ServiceLib.ViewModels
|
|||
private async Task RemoteRestore()
|
||||
{
|
||||
DisplayOperationMsg();
|
||||
var fileName = Utils.GetTempPath(Utils.GetGUID());
|
||||
var fileName = Utils.GetTempPath(Utils.GetGuid());
|
||||
var result = await WebDavHandler.Instance.GetRawFile(fileName);
|
||||
if (result)
|
||||
{
|
||||
|
|
|
@ -34,7 +34,7 @@ namespace ServiceLib.ViewModels
|
|||
|
||||
if (rulesItem.id.IsNullOrEmpty())
|
||||
{
|
||||
rulesItem.id = Utils.GetGUID(false);
|
||||
rulesItem.id = Utils.GetGuid(false);
|
||||
rulesItem.outboundTag = Global.ProxyTag;
|
||||
rulesItem.enabled = true;
|
||||
SelectedSource = rulesItem;
|
||||
|
|
|
@ -232,7 +232,7 @@ namespace ServiceLib.ViewModels
|
|||
var item = SelectedRouting;
|
||||
foreach (var it in _rules)
|
||||
{
|
||||
it.id = Utils.GetGUID(false);
|
||||
it.id = Utils.GetGuid(false);
|
||||
}
|
||||
item.ruleNum = _rules.Count;
|
||||
item.ruleSet = JsonUtils.Serialize(_rules, false);
|
||||
|
@ -322,7 +322,7 @@ namespace ServiceLib.ViewModels
|
|||
}
|
||||
foreach (var rule in lstRules)
|
||||
{
|
||||
rule.id = Utils.GetGUID(false);
|
||||
rule.id = Utils.GetGuid(false);
|
||||
}
|
||||
|
||||
if (blReplace)
|
||||
|
|
|
@ -43,7 +43,7 @@ public partial class App : Application
|
|||
|
||||
private void OnStartup(string[]? Args)
|
||||
{
|
||||
var exePathKey = Utils.GetMD5(Utils.GetExePath());
|
||||
var exePathKey = Utils.GetMd5(Utils.GetExePath());
|
||||
|
||||
var rebootas = (Args ?? new string[] { }).Any(t => t == Global.RebootAs);
|
||||
//ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, exePathKey, out bool bCreatedNew);
|
||||
|
|
|
@ -272,7 +272,7 @@ namespace v2rayN.Desktop.Views
|
|||
private void btnGUID_Click(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
txtId.Text =
|
||||
txtId5.Text = Utils.GetGUID();
|
||||
txtId5.Text = Utils.GetGuid();
|
||||
}
|
||||
|
||||
private void SetHeaderType()
|
||||
|
|
|
@ -26,7 +26,7 @@ namespace v2rayN
|
|||
/// <param name="e"></param>
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
var exePathKey = Utils.GetMD5(Utils.GetExePath());
|
||||
var exePathKey = Utils.GetMd5(Utils.GetExePath());
|
||||
|
||||
var rebootas = (e.Args ?? new string[] { }).Any(t => t == Global.RebootAs);
|
||||
ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, exePathKey, out bool bCreatedNew);
|
||||
|
|
|
@ -218,7 +218,7 @@ namespace v2rayN
|
|||
{
|
||||
try
|
||||
{
|
||||
var autoRunName = $"{AutoRunName}_{Utils.GetMD5(Utils.StartupPath())}";
|
||||
var autoRunName = $"{AutoRunName}_{Utils.GetMd5(Utils.StartupPath())}";
|
||||
//delete first
|
||||
RegWriteValue(AutoRunRegPath, autoRunName, "");
|
||||
if (Utils.IsAdministrator())
|
||||
|
|
|
@ -267,7 +267,7 @@ namespace v2rayN.Views
|
|||
private void btnGUID_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
txtId.Text =
|
||||
txtId5.Text = Utils.GetGUID();
|
||||
txtId5.Text = Utils.GetGuid();
|
||||
}
|
||||
|
||||
private void SetHeaderType()
|
||||
|
|
Loading…
Reference in New Issue