diff --git a/v2rayN/AmazTool/AmazTool.csproj b/v2rayN/AmazTool/AmazTool.csproj
index 4657a889..9ed751be 100644
--- a/v2rayN/AmazTool/AmazTool.csproj
+++ b/v2rayN/AmazTool/AmazTool.csproj
@@ -2,6 +2,7 @@
Exe
+ en-US
diff --git a/v2rayN/AmazTool/UpgradeApp.cs b/v2rayN/AmazTool/UpgradeApp.cs
index caa269f4..6bdfdcda 100644
--- a/v2rayN/AmazTool/UpgradeApp.cs
+++ b/v2rayN/AmazTool/UpgradeApp.cs
@@ -4,7 +4,7 @@ using System.Text;
namespace AmazTool;
-internal class UpgradeApp
+internal static class UpgradeApp
{
public static void Upgrade(string fileName)
{
@@ -25,7 +25,7 @@ internal class UpgradeApp
foreach (var pp in existing)
{
var path = pp.MainModule?.FileName ?? "";
- if (path.StartsWith(Utils.GetPath(Utils.V2rayN)))
+ if (path.StartsWith(Utils.GetPath(Utils.V2rayN), StringComparison.OrdinalIgnoreCase))
{
pp?.Kill();
pp?.WaitForExit(1000);
@@ -74,7 +74,7 @@ internal class UpgradeApp
var entryOutputPath = Utils.GetPath(fullName);
Directory.CreateDirectory(Path.GetDirectoryName(entryOutputPath)!);
//In the bin folder, if the file already exists, it will be skipped
- if (fullName.StartsWith("bin") && File.Exists(entryOutputPath))
+ if (fullName.AsSpan().StartsWith("bin", StringComparison.OrdinalIgnoreCase) && File.Exists(entryOutputPath))
{
continue;
}
diff --git a/v2rayN/AmazTool/Utils.cs b/v2rayN/AmazTool/Utils.cs
index df13ecf6..72d4bbf3 100644
--- a/v2rayN/AmazTool/Utils.cs
+++ b/v2rayN/AmazTool/Utils.cs
@@ -2,7 +2,7 @@ using System.Diagnostics;
namespace AmazTool;
-internal class Utils
+internal static class Utils
{
public static string GetExePath()
{
diff --git a/v2rayN/Directory.Build.props b/v2rayN/Directory.Build.props
index 884ca180..d864c835 100644
--- a/v2rayN/Directory.Build.props
+++ b/v2rayN/Directory.Build.props
@@ -8,7 +8,7 @@
net10.0
true
true
- CA1031;CS1591;NU1507;CA1416;IDE0058;IDE0053;IDE0200;NETSDK1206
+ CA1031;CS1591;NU1507;CA1416;IDE0058;IDE0053;IDE0200;IDE0022;NETSDK1206
annotations
enable
2dust
diff --git a/v2rayN/ServiceLib/Global.cs b/v2rayN/ServiceLib/AppConfig.cs
similarity index 99%
rename from v2rayN/ServiceLib/Global.cs
rename to v2rayN/ServiceLib/AppConfig.cs
index 94a66fa5..87eb1f66 100644
--- a/v2rayN/ServiceLib/Global.cs
+++ b/v2rayN/ServiceLib/AppConfig.cs
@@ -1,6 +1,6 @@
namespace ServiceLib;
-public class Global
+public class AppConfig
{
#region const
diff --git a/v2rayN/ServiceLib/Base/MyReactiveObject.cs b/v2rayN/ServiceLib/Base/MyReactiveObject.cs
index 50563151..df89cfde 100644
--- a/v2rayN/ServiceLib/Base/MyReactiveObject.cs
+++ b/v2rayN/ServiceLib/Base/MyReactiveObject.cs
@@ -2,6 +2,6 @@ namespace ServiceLib.Base;
public class MyReactiveObject : ReactiveObject
{
- protected static Config? _config;
- protected Func>? _updateView;
+ protected static Config? Config { get; set; }
+ protected Func>? UpdateView { get; set; }
}
diff --git a/v2rayN/ServiceLib/Common/Extension.cs b/v2rayN/ServiceLib/Common/Extension.cs
index b6ee8154..80df575e 100644
--- a/v2rayN/ServiceLib/Common/Extension.cs
+++ b/v2rayN/ServiceLib/Common/Extension.cs
@@ -45,9 +45,9 @@ public static class Extension
}
}
- public static string TrimEx(this string? value)
+ public static string TrimSafe(this string? value)
{
- return value == null ? string.Empty : value.Trim();
+ return value?.Trim() ?? string.Empty;
}
public static string RemovePrefix(this string value, char prefix)
@@ -57,17 +57,26 @@ public static class Extension
public static string RemovePrefix(this string value, string prefix)
{
- return value.StartsWith(prefix) ? value[prefix.Length..] : value;
+ return value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? value[prefix.Length..] : value;
}
- public static string UpperFirstChar(this string value)
+ public static string UpperFirstChar(this string? value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
- return char.ToUpper(value.First()) + value[1..];
+ if (char.IsUpper(value[0]))
+ {
+ return value;
+ }
+
+ return string.Create(value.Length, value, (span, oldStr) =>
+ {
+ oldStr.AsSpan().CopyTo(span);
+ span[0] = char.ToUpper(span[0], CultureInfo.InvariantCulture);
+ });
}
public static string AppendQuotes(this string value)
diff --git a/v2rayN/ServiceLib/Common/FileUtils.cs b/v2rayN/ServiceLib/Common/FileUtils.cs
index 2f86b60a..bf9cb723 100644
--- a/v2rayN/ServiceLib/Common/FileUtils.cs
+++ b/v2rayN/ServiceLib/Common/FileUtils.cs
@@ -41,7 +41,7 @@ public static class FileUtils
{
FileInfo fileInfo = new(fileName);
using var originalFileStream = fileInfo.OpenRead();
- using var decompressedFileStream = File.Create(toName != null ? Path.Combine(toPath, toName) : toPath);
+ using var decompressedFileStream = File.Create(toName is not null ? Path.Combine(toPath, toName) : toPath);
using GZipStream decompressionStream = new(originalFileStream, CompressionMode.Decompress);
decompressionStream.CopyTo(decompressedFileStream);
}
diff --git a/v2rayN/ServiceLib/Common/JsonUtils.cs b/v2rayN/ServiceLib/Common/JsonUtils.cs
index 7e2b7f78..f617dbfb 100644
--- a/v2rayN/ServiceLib/Common/JsonUtils.cs
+++ b/v2rayN/ServiceLib/Common/JsonUtils.cs
@@ -100,7 +100,7 @@ public class JsonUtils
var result = string.Empty;
try
{
- if (obj == null)
+ if (obj is null)
{
return result;
}
@@ -125,7 +125,7 @@ public class JsonUtils
var result = string.Empty;
try
{
- if (obj == null)
+ if (obj is null)
{
return result;
}
diff --git a/v2rayN/ServiceLib/Common/Logging.cs b/v2rayN/ServiceLib/Common/Logging.cs
index fdd49f5c..c34f7782 100644
--- a/v2rayN/ServiceLib/Common/Logging.cs
+++ b/v2rayN/ServiceLib/Common/Logging.cs
@@ -47,7 +47,7 @@ public class Logging
_logger2.Debug($"{strTitle},{ex.Message}");
_logger2.Debug(ex.StackTrace);
- if (ex?.InnerException != null)
+ if (ex?.InnerException is not null)
{
_logger2.Error(ex.InnerException);
}
diff --git a/v2rayN/ServiceLib/Common/ProcUtils.cs b/v2rayN/ServiceLib/Common/ProcUtils.cs
index ce487c7a..71f337cf 100644
--- a/v2rayN/ServiceLib/Common/ProcUtils.cs
+++ b/v2rayN/ServiceLib/Common/ProcUtils.cs
@@ -53,7 +53,7 @@ public static class ProcUtils
ProcessStartInfo startInfo = new()
{
UseShellExecute = true,
- Arguments = Global.RebootAs,
+ Arguments = AppConfig.RebootAs,
WorkingDirectory = Utils.StartupPath(),
FileName = Utils.GetExePath().AppendQuotes(),
Verb = blAdmin ? "runas" : null,
diff --git a/v2rayN/ServiceLib/Common/QRCodeUtils.cs b/v2rayN/ServiceLib/Common/QRCodeUtils.cs
index d9015367..ade0e70b 100644
--- a/v2rayN/ServiceLib/Common/QRCodeUtils.cs
+++ b/v2rayN/ServiceLib/Common/QRCodeUtils.cs
@@ -42,7 +42,7 @@ public class QRCodeUtils
}
}
- if (lastDtle != null)
+ if (lastDtle is not null)
{
throw lastDtle;
}
@@ -52,7 +52,7 @@ public class QRCodeUtils
public static string? ParseBarcode(string? fileName)
{
- if (fileName == null || !File.Exists(fileName))
+ if (fileName is null || !File.Exists(fileName))
{
return null;
}
@@ -96,7 +96,7 @@ public class QRCodeUtils
var reader = new BarcodeReader();
var result = reader.Decode(bitmap);
- if (result != null && result.Text.IsNotEmpty())
+ if (result is not null && result.Text.IsNotEmpty())
{
return result.Text;
}
diff --git a/v2rayN/ServiceLib/Common/Utils.cs b/v2rayN/ServiceLib/Common/Utils.cs
index fe2b1549..50163803 100644
--- a/v2rayN/ServiceLib/Common/Utils.cs
+++ b/v2rayN/ServiceLib/Common/Utils.cs
@@ -9,6 +9,9 @@ public class Utils
{
private static readonly string _tag = "Utils";
+ private static readonly char[] LineSeparators = { '\r', '\n' };
+ private static readonly char[] FieldSeparators = { ' ', '\t' };
+
#region Conversion Functions
///
@@ -19,7 +22,7 @@ public class Utils
///
public static string List2String(List? lst, bool wrap = false)
{
- if (lst == null || lst.Count == 0)
+ if (lst is null || lst.Count == 0)
{
return string.Empty;
}
@@ -141,7 +144,7 @@ public class Utils
{
try
{
- return Convert.ToBoolean(obj);
+ return Convert.ToBoolean(obj, CultureInfo.InvariantCulture);
}
catch
{
@@ -232,13 +235,8 @@ public class Utils
{
var byteOld = Encoding.UTF8.GetBytes(str);
var byteNew = MD5.HashData(byteOld);
- StringBuilder sb = new(32);
- foreach (var b in byteNew)
- {
- sb.Append(b.ToString("x2"));
- }
- return sb.ToString();
+ return Convert.ToHexStringLower(byteNew);
}
catch (Exception ex)
{
@@ -264,7 +262,7 @@ public class Utils
using var md5 = MD5.Create();
using var stream = File.OpenRead(filePath);
var hash = md5.ComputeHash(stream);
- return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
+ return Convert.ToHexStringLower(hash);
}
catch (Exception ex)
{
@@ -335,24 +333,24 @@ public class Utils
public static Dictionary> ParseHostsToDictionary(string hostsContent)
{
var userHostsMap = hostsContent
- .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
+ .Split(LineSeparators, StringSplitOptions.RemoveEmptyEntries)
.Select(line => line.Trim())
// skip full-line comments
- .Where(line => !string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
+ .Where(line => !string.IsNullOrWhiteSpace(line) && !line.StartsWith('#'))
// strip inline comments (truncate at '#')
.Select(line =>
{
var index = line.IndexOf('#');
- return index >= 0 ? line.Substring(0, index).Trim() : line;
+ return index >= 0 ? line[..index].Trim() : line;
})
// ensure line still contains valid parts
.Where(line => !string.IsNullOrWhiteSpace(line) && line.Contains(' '))
- .Select(line => line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries))
+ .Select(line => line.Split(FieldSeparators, StringSplitOptions.RemoveEmptyEntries))
.Where(parts => parts.Length >= 2)
- .GroupBy(parts => parts[0])
+ .GroupBy(parts => parts[0], StringComparer.OrdinalIgnoreCase)
.ToDictionary(
group => group.Key,
- group => group.SelectMany(parts => parts.Skip(1)).ToList()
+ group => group.SelectMany(parts => parts.Skip(1)).Distinct(StringComparer.OrdinalIgnoreCase).ToList()
);
return userHostsMap;
@@ -660,15 +658,15 @@ public class Utils
try
{
return blFull
- ? $"{Global.AppName} - V{GetVersionInfo()} - {RuntimeInformation.ProcessArchitecture}"
- : $"{Global.AppName}/{GetVersionInfo()}";
+ ? $"{AppConfig.AppName} - V{GetVersionInfo()} - {RuntimeInformation.ProcessArchitecture}"
+ : $"{AppConfig.AppName}/{GetVersionInfo()}";
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
}
- return Global.AppName;
+ return AppConfig.AppName;
}
public static string GetVersionInfo()
@@ -695,23 +693,16 @@ public class Utils
///
public static string GetGuid(bool full = true)
{
- try
+ var guid = Guid.NewGuid();
+
+ if (full)
{
- if (full)
- {
- return Guid.NewGuid().ToString("D");
- }
- else
- {
- return BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0).ToString();
- }
- }
- catch (Exception ex)
- {
- Logging.SaveLog(_tag, ex);
+ return guid.ToString("D");
}
- return string.Empty;
+ Span buffer = stackalloc byte[16];
+ guid.TryWriteBytes(buffer);
+ return BitConverter.ToInt64(buffer).ToString(CultureInfo.InvariantCulture);
}
public static bool IsGuidByParse(string strSrc)
@@ -722,22 +713,22 @@ public class Utils
public static Dictionary GetSystemHosts()
{
var systemHosts = new Dictionary();
- var hostFile = @"C:\Windows\System32\drivers\etc\hosts";
+ var hostFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts");
try
{
if (File.Exists(hostFile))
{
- var hosts = File.ReadAllText(hostFile).Replace("\r", "");
- var hostsList = hosts.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
+ var hostsList = File.ReadAllText(hostFile)
+ .Split(LineSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (var host in hostsList)
{
- if (host.StartsWith("#"))
+ if (host.StartsWith('#'))
{
continue;
}
- var hostItem = host.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
+ var hostItem = host.Split(FieldSeparators, StringSplitOptions.RemoveEmptyEntries);
if (hostItem.Length < 2)
{
continue;
@@ -757,7 +748,7 @@ public class Utils
public static async Task GetCliWrapOutput(string filePath, string? arg)
{
- return await GetCliWrapOutput(filePath, arg != null ? new List() { arg } : null);
+ return await GetCliWrapOutput(filePath, arg is not null ? new List() { arg } : null);
}
public static async Task GetCliWrapOutput(string filePath, IEnumerable? args)
@@ -765,7 +756,7 @@ public class Utils
try
{
var cmd = Cli.Wrap(filePath);
- if (args != null)
+ if (args is not null)
{
if (args.Count() == 1)
{
@@ -854,7 +845,7 @@ public class Utils
public static string StartupPath()
{
- if (Environment.GetEnvironmentVariable(Global.LocalAppData) == "1")
+ if (Environment.GetEnvironmentVariable(AppConfig.LocalAppData) == "1")
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "v2rayN");
}
@@ -917,9 +908,9 @@ public class Utils
Directory.CreateDirectory(tempPath);
}
- if (coreType != null)
+ if (coreType is not null)
{
- tempPath = Path.Combine(tempPath, coreType.ToLower().ToString());
+ tempPath = Path.Combine(tempPath, coreType.ToLower(CultureInfo.InvariantCulture).ToString());
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
@@ -1058,7 +1049,7 @@ public class Utils
private static async Task GetLinuxUserId()
{
var arg = new List() { "-c", "id -u" };
- return await GetCliWrapOutput(Global.LinuxBash, arg);
+ return await GetCliWrapOutput(AppConfig.LinuxBash, arg);
}
public static async Task SetLinuxChmod(string? fileName)
@@ -1078,7 +1069,7 @@ public class Utils
fileName = fileName.AppendQuotes();
}
var arg = new List() { "-c", $"chmod +x {fileName}" };
- return await GetCliWrapOutput(Global.LinuxBash, arg);
+ return await GetCliWrapOutput(AppConfig.LinuxBash, arg);
}
public static bool SetUnixFileMode(string? fileName)
@@ -1104,11 +1095,11 @@ public class Utils
return false;
}
- public static async Task GetLinuxFontFamily(string lang)
+ public static async Task GetLinuxFontFamily()
{
// var arg = new List() { "-c", $"fc-list :lang={lang} family" };
var arg = new List() { "-c", $"fc-list : family" };
- return await GetCliWrapOutput(Global.LinuxBash, arg);
+ return await GetCliWrapOutput(AppConfig.LinuxBash, arg);
}
public static string? GetHomePath()
diff --git a/v2rayN/ServiceLib/Common/YamlUtils.cs b/v2rayN/ServiceLib/Common/YamlUtils.cs
index a95e1b0a..45fc5f83 100644
--- a/v2rayN/ServiceLib/Common/YamlUtils.cs
+++ b/v2rayN/ServiceLib/Common/YamlUtils.cs
@@ -41,7 +41,7 @@ public class YamlUtils
public static string ToYaml(object? obj)
{
var result = string.Empty;
- if (obj == null)
+ if (obj is null)
{
return result;
}
diff --git a/v2rayN/ServiceLib/GlobalUsings.cs b/v2rayN/ServiceLib/GlobalUsings.cs
index d38ccc06..8ae97d0e 100644
--- a/v2rayN/ServiceLib/GlobalUsings.cs
+++ b/v2rayN/ServiceLib/GlobalUsings.cs
@@ -1,5 +1,7 @@
global using System.Collections.Concurrent;
+global using System.ComponentModel;
global using System.Diagnostics;
+global using System.Globalization;
global using System.Net;
global using System.Net.NetworkInformation;
global using System.Net.Sockets;
diff --git a/v2rayN/ServiceLib/Handler/AutoStartupHandler.cs b/v2rayN/ServiceLib/Handler/AutoStartupHandler.cs
index bc86cd7f..4006671d 100644
--- a/v2rayN/ServiceLib/Handler/AutoStartupHandler.cs
+++ b/v2rayN/ServiceLib/Handler/AutoStartupHandler.cs
@@ -44,7 +44,7 @@ public static class AutoStartupHandler
private static async Task ClearTaskWindows()
{
var autoRunName = GetAutoRunNameWindows();
- WindowsUtils.RegWriteValue(Global.AutoRunRegPath, autoRunName, "");
+ WindowsUtils.RegWriteValue(AppConfig.AutoRunRegPath, autoRunName, "");
if (Utils.IsAdministrator())
{
AutoStartTaskService(autoRunName, "", "");
@@ -65,7 +65,7 @@ public static class AutoStartupHandler
}
else
{
- WindowsUtils.RegWriteValue(Global.AutoRunRegPath, autoRunName, exePath.AppendQuotes());
+ WindowsUtils.RegWriteValue(AppConfig.AutoRunRegPath, autoRunName, exePath.AppendQuotes());
}
}
catch (Exception ex)
@@ -117,7 +117,7 @@ public static class AutoStartupHandler
private static string GetAutoRunNameWindows()
{
- return $"{Global.AutoRunName}_{Utils.GetMd5(Utils.StartupPath())}";
+ return $"{AppConfig.AutoRunName}_{Utils.GetMd5(Utils.StartupPath())}";
}
#endregion Windows
@@ -141,7 +141,7 @@ public static class AutoStartupHandler
{
try
{
- var linuxConfig = EmbedUtils.GetEmbedText(Global.LinuxAutostartConfig);
+ var linuxConfig = EmbedUtils.GetEmbedText(AppConfig.LinuxAutostartConfig);
if (linuxConfig.IsNotEmpty())
{
linuxConfig = linuxConfig.Replace("$ExecPath$", Utils.GetExePath());
@@ -159,7 +159,7 @@ public static class AutoStartupHandler
private static string GetHomePathLinux()
{
- var homePath = Path.Combine(Utils.GetHomePath(), ".config", "autostart", $"{Global.AppName}.desktop");
+ var homePath = Path.Combine(Utils.GetHomePath(), ".config", "autostart", $"{AppConfig.AppName}.desktop");
Directory.CreateDirectory(Path.GetDirectoryName(homePath));
return homePath;
}
@@ -176,7 +176,7 @@ public static class AutoStartupHandler
if (File.Exists(launchAgentPath))
{
var args = new[] { "-c", $"launchctl unload -w \"{launchAgentPath}\"" };
- await Utils.GetCliWrapOutput(Global.LinuxBash, args);
+ await Utils.GetCliWrapOutput(AppConfig.LinuxBash, args);
File.Delete(launchAgentPath);
}
@@ -196,7 +196,7 @@ public static class AutoStartupHandler
await File.WriteAllTextAsync(launchAgentPath, plistContent);
var args = new[] { "-c", $"launchctl load -w \"{launchAgentPath}\"" };
- await Utils.GetCliWrapOutput(Global.LinuxBash, args);
+ await Utils.GetCliWrapOutput(AppConfig.LinuxBash, args);
}
catch (Exception ex)
{
@@ -207,7 +207,7 @@ public static class AutoStartupHandler
private static string GetLaunchAgentPathMacOS()
{
var homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
- var launchAgentPath = Path.Combine(homePath, "Library", "LaunchAgents", $"{Global.AppName}-LaunchAgent.plist");
+ var launchAgentPath = Path.Combine(homePath, "Library", "LaunchAgents", $"{AppConfig.AppName}-LaunchAgent.plist");
Directory.CreateDirectory(Path.GetDirectoryName(launchAgentPath));
return launchAgentPath;
}
@@ -221,7 +221,7 @@ public static class AutoStartupHandler
Label
- {Global.AppName}-LaunchAgent
+ {AppConfig.AppName}-LaunchAgent
ProgramArguments
/bin/sh
diff --git a/v2rayN/ServiceLib/Handler/ConfigHandler.cs b/v2rayN/ServiceLib/Handler/ConfigHandler.cs
index 5877d012..5731478b 100644
--- a/v2rayN/ServiceLib/Handler/ConfigHandler.cs
+++ b/v2rayN/ServiceLib/Handler/ConfigHandler.cs
@@ -4,7 +4,7 @@ namespace ServiceLib.Handler;
public static class ConfigHandler
{
- private static readonly string _configRes = Global.ConfigFileName;
+ private static readonly string _configRes = AppConfig.ConfigFileName;
private static readonly string _tag = "ConfigHandler";
#region ConfigHandler
@@ -42,7 +42,7 @@ public static class ConfigHandler
MuxEnabled = false,
};
- if (config.Inbound == null)
+ if (config.Inbound is null)
{
config.Inbound = new List();
InItem inItem = new()
@@ -67,7 +67,7 @@ public static class ConfigHandler
config.RoutingBasicItem ??= new();
if (config.RoutingBasicItem.DomainStrategy.IsNullOrEmpty())
{
- config.RoutingBasicItem.DomainStrategy = Global.DomainStrategies.First();
+ config.RoutingBasicItem.DomainStrategy = AppConfig.DomainStrategies.First();
}
config.KcpItem ??= new KcpItem
@@ -104,16 +104,17 @@ public static class ConfigHandler
if (config.UiItem.CurrentLanguage.IsNullOrEmpty())
{
- config.UiItem.CurrentLanguage = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.Equals("zh", StringComparison.CurrentCultureIgnoreCase)
- ? Global.Languages.First()
- : Global.Languages[2];
+ config.UiItem.CurrentLanguage = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName
+ .Equals("zh", StringComparison.OrdinalIgnoreCase)
+ ? AppConfig.Languages.First()
+ : AppConfig.Languages[2];
}
config.ConstItem ??= new ConstItem();
config.SimpleDNSItem ??= InitBuiltinSimpleDNS();
config.SimpleDNSItem.GlobalFakeIp ??= true;
- config.SimpleDNSItem.BootstrapDNS ??= Global.DomainPureIPDNSAddress.FirstOrDefault();
+ config.SimpleDNSItem.BootstrapDNS ??= AppConfig.DomainPureIPDNSAddress.FirstOrDefault();
config.SpeedTestItem ??= new();
if (config.SpeedTestItem.SpeedTestTimeout < 10)
@@ -122,11 +123,11 @@ public static class ConfigHandler
}
if (config.SpeedTestItem.SpeedTestUrl.IsNullOrEmpty())
{
- config.SpeedTestItem.SpeedTestUrl = Global.SpeedTestUrls.First();
+ config.SpeedTestItem.SpeedTestUrl = AppConfig.SpeedTestUrls.First();
}
if (config.SpeedTestItem.SpeedPingTestUrl.IsNullOrEmpty())
{
- config.SpeedTestItem.SpeedPingTestUrl = Global.SpeedPingTestUrls.First();
+ config.SpeedTestItem.SpeedPingTestUrl = AppConfig.SpeedPingTestUrls.First();
}
if (config.SpeedTestItem.MixedConcurrencyCount < 1)
{
@@ -142,7 +143,7 @@ public static class ConfigHandler
config.Mux4SboxItem ??= new()
{
- Protocol = Global.SingboxMuxs.First(),
+ Protocol = AppConfig.SingboxMuxs.First(),
MaxConnections = 8
};
@@ -165,7 +166,7 @@ public static class ConfigHandler
if (config.SystemProxyItem.SystemProxyExceptions.IsNullOrEmpty())
{
- config.SystemProxyItem.SystemProxyExceptions = Utils.IsWindows() ? Global.SystemProxyExceptionsWindows : Global.SystemProxyExceptionsLinux;
+ config.SystemProxyItem.SystemProxyExceptions = Utils.IsWindows() ? AppConfig.SystemProxyExceptionsWindows : AppConfig.SystemProxyExceptionsLinux;
}
return config;
@@ -287,16 +288,16 @@ public static class ConfigHandler
{
profileItem.ConfigType = EConfigType.VMess;
- profileItem.Address = profileItem.Address.TrimEx();
- profileItem.Id = profileItem.Id.TrimEx();
- profileItem.Security = profileItem.Security.TrimEx();
- profileItem.Network = profileItem.Network.TrimEx();
- profileItem.HeaderType = profileItem.HeaderType.TrimEx();
- profileItem.RequestHost = profileItem.RequestHost.TrimEx();
- profileItem.Path = profileItem.Path.TrimEx();
- profileItem.StreamSecurity = profileItem.StreamSecurity.TrimEx();
+ profileItem.Address = profileItem.Address.TrimSafe();
+ profileItem.Id = profileItem.Id.TrimSafe();
+ profileItem.Security = profileItem.Security.TrimSafe();
+ profileItem.Network = profileItem.Network.TrimSafe();
+ profileItem.HeaderType = profileItem.HeaderType.TrimSafe();
+ profileItem.RequestHost = profileItem.RequestHost.TrimSafe();
+ profileItem.Path = profileItem.Path.TrimSafe();
+ profileItem.StreamSecurity = profileItem.StreamSecurity.TrimSafe();
- if (!Global.VmessSecurities.Contains(profileItem.Security))
+ if (!AppConfig.VmessSecurities.Contains(profileItem.Security))
{
return -1;
}
@@ -361,7 +362,7 @@ public static class ConfigHandler
else if (profileItem.ConfigType.IsGroupType())
{
var profileGroupItem = await AppManager.Instance.GetProfileGroupItem(it.IndexId);
- await AddGroupServerCommon(config, profileItem, profileGroupItem, true);
+ await AddGroupServerCommon(profileItem, profileGroupItem, true);
}
else
{
@@ -407,7 +408,7 @@ public static class ConfigHandler
return 0;
}
- if (await SQLiteHelper.Instance.TableAsync().FirstOrDefaultAsync(t => t.IndexId == config.IndexId) != null)
+ if (await SQLiteHelper.Instance.TableAsync().FirstOrDefaultAsync(t => t.IndexId == config.IndexId) is not null)
{
return 0;
}
@@ -443,76 +444,42 @@ public static class ConfigHandler
/// Move a server in the list to a different position
/// Supports moving to top, up, down, bottom or specific position
///
- /// Current configuration
/// List of server profiles
/// Index of the server to move
/// Direction to move the server
/// Target position when using EMove.Position
/// 0 if successful, -1 if failed
- public static async Task MoveServer(Config config, List lstProfile, int index, EMove eMove, int pos = -1)
+ public static Task MoveServer(List lstProfile, int index, EMove eMove, int pos = -1)
{
var count = lstProfile.Count;
- if (index < 0 || index > lstProfile.Count - 1)
+ if (index < 0 || index >= count)
{
- return -1;
+ return Task.FromResult(-1);
}
- for (var i = 0; i < lstProfile.Count; i++)
+ if ((eMove is EMove.Top or EMove.Up && index == 0) ||
+ (eMove is EMove.Down or EMove.Bottom && index == count - 1))
+ {
+ return Task.FromResult(0);
+ }
+
+ for (var i = 0; i < count; i++)
{
ProfileExManager.Instance.SetSort(lstProfile[i].IndexId, (i + 1) * 10);
}
- var sort = 0;
- switch (eMove)
+ var sort = eMove switch
{
- case EMove.Top:
- {
- if (index == 0)
- {
- return 0;
- }
- sort = ProfileExManager.Instance.GetSort(lstProfile.First().IndexId) - 1;
-
- break;
- }
- case EMove.Up:
- {
- if (index == 0)
- {
- return 0;
- }
- sort = ProfileExManager.Instance.GetSort(lstProfile[index - 1].IndexId) - 1;
-
- break;
- }
-
- case EMove.Down:
- {
- if (index == count - 1)
- {
- return 0;
- }
- sort = ProfileExManager.Instance.GetSort(lstProfile[index + 1].IndexId) + 1;
-
- break;
- }
- case EMove.Bottom:
- {
- if (index == count - 1)
- {
- return 0;
- }
- sort = ProfileExManager.Instance.GetSort(lstProfile[^1].IndexId) + 1;
-
- break;
- }
- case EMove.Position:
- sort = (pos * 10) + 1;
- break;
- }
+ EMove.Top => ProfileExManager.Instance.GetSort(lstProfile[0].IndexId) - 1,
+ EMove.Up => ProfileExManager.Instance.GetSort(lstProfile[index - 1].IndexId) - 1,
+ EMove.Down => ProfileExManager.Instance.GetSort(lstProfile[index + 1].IndexId) + 1,
+ EMove.Bottom => ProfileExManager.Instance.GetSort(lstProfile[^1].IndexId) + 1,
+ EMove.Position => (pos * 10) + 1,
+ _ => 0
+ };
ProfileExManager.Instance.SetSort(lstProfile[index].IndexId, sort);
- return await Task.FromResult(0);
+ return Task.FromResult(0);
}
///
@@ -552,7 +519,7 @@ public static class ConfigHandler
profileItem.ConfigType = EConfigType.Custom;
if (profileItem.Remarks.IsNullOrEmpty())
{
- profileItem.Remarks = $"import custom@{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}";
+ profileItem.Remarks = $"import custom@{DateTime.Now:yyyy/MM/dd HH:mm:ss}";
}
await AddServerCommon(config, profileItem, true);
@@ -564,17 +531,13 @@ public static class ConfigHandler
/// Edit an existing custom server configuration
/// Updates the server's properties without changing the file
///
- /// Current configuration
/// Profile item with updated properties
/// 0 if successful, -1 if failed
- public static async Task EditCustomServer(Config config, ProfileItem profileItem)
+ public static async Task EditCustomServer(ProfileItem profileItem)
{
var item = await AppManager.Instance.GetProfileItem(profileItem.IndexId);
- if (item is null)
- {
- item = profileItem;
- }
- else
+
+ if (item is not null)
{
item.Remarks = profileItem.Remarks;
item.Address = profileItem.Address;
@@ -583,14 +546,9 @@ public static class ConfigHandler
item.PreSocksPort = profileItem.PreSocksPort;
}
- if (await SQLiteHelper.Instance.UpdateAsync(item) > 0)
- {
- return 0;
- }
- else
- {
- return -1;
- }
+ item ??= profileItem;
+
+ return await SQLiteHelper.Instance.UpdateAsync(item) > 0 ? 0 : -1;
//ToJsonFile(config);
}
@@ -607,9 +565,9 @@ public static class ConfigHandler
{
profileItem.ConfigType = EConfigType.Shadowsocks;
- profileItem.Address = profileItem.Address.TrimEx();
- profileItem.Id = profileItem.Id.TrimEx();
- profileItem.Security = profileItem.Security.TrimEx();
+ profileItem.Address = profileItem.Address.TrimSafe();
+ profileItem.Id = profileItem.Id.TrimSafe();
+ profileItem.Security = profileItem.Security.TrimSafe();
if (!AppManager.Instance.GetShadowsocksSecurities(profileItem).Contains(profileItem.Security))
{
@@ -637,7 +595,7 @@ public static class ConfigHandler
{
profileItem.ConfigType = EConfigType.SOCKS;
- profileItem.Address = profileItem.Address.TrimEx();
+ profileItem.Address = profileItem.Address.TrimSafe();
await AddServerCommon(config, profileItem, toFile);
@@ -656,7 +614,7 @@ public static class ConfigHandler
{
profileItem.ConfigType = EConfigType.HTTP;
- profileItem.Address = profileItem.Address.TrimEx();
+ profileItem.Address = profileItem.Address.TrimSafe();
await AddServerCommon(config, profileItem, toFile);
@@ -675,11 +633,11 @@ public static class ConfigHandler
{
profileItem.ConfigType = EConfigType.Trojan;
- profileItem.Address = profileItem.Address.TrimEx();
- profileItem.Id = profileItem.Id.TrimEx();
+ profileItem.Address = profileItem.Address.TrimSafe();
+ profileItem.Id = profileItem.Id.TrimSafe();
if (profileItem.StreamSecurity.IsNullOrEmpty())
{
- profileItem.StreamSecurity = Global.StreamSecurity;
+ profileItem.StreamSecurity = AppConfig.StreamSecurity;
}
if (profileItem.Id.IsNullOrEmpty())
{
@@ -705,14 +663,14 @@ public static class ConfigHandler
profileItem.ConfigType = EConfigType.Hysteria2;
//profileItem.CoreType = ECoreType.sing_box;
- profileItem.Address = profileItem.Address.TrimEx();
- profileItem.Id = profileItem.Id.TrimEx();
- profileItem.Path = profileItem.Path.TrimEx();
+ profileItem.Address = profileItem.Address.TrimSafe();
+ profileItem.Id = profileItem.Id.TrimSafe();
+ profileItem.Path = profileItem.Path.TrimSafe();
profileItem.Network = string.Empty;
if (profileItem.StreamSecurity.IsNullOrEmpty())
{
- profileItem.StreamSecurity = Global.StreamSecurity;
+ profileItem.StreamSecurity = AppConfig.StreamSecurity;
}
if (profileItem.Id.IsNullOrEmpty())
{
@@ -738,19 +696,19 @@ public static class ConfigHandler
profileItem.ConfigType = EConfigType.TUIC;
profileItem.CoreType = ECoreType.sing_box;
- profileItem.Address = profileItem.Address.TrimEx();
- profileItem.Id = profileItem.Id.TrimEx();
- profileItem.Security = profileItem.Security.TrimEx();
+ profileItem.Address = profileItem.Address.TrimSafe();
+ profileItem.Id = profileItem.Id.TrimSafe();
+ profileItem.Security = profileItem.Security.TrimSafe();
profileItem.Network = string.Empty;
- if (!Global.TuicCongestionControls.Contains(profileItem.HeaderType))
+ if (!AppConfig.TuicCongestionControls.Contains(profileItem.HeaderType))
{
- profileItem.HeaderType = Global.TuicCongestionControls.FirstOrDefault()!;
+ profileItem.HeaderType = AppConfig.TuicCongestionControls.FirstOrDefault()!;
}
if (profileItem.StreamSecurity.IsNullOrEmpty())
{
- profileItem.StreamSecurity = Global.StreamSecurity;
+ profileItem.StreamSecurity = AppConfig.StreamSecurity;
}
if (profileItem.Alpn.IsNullOrEmpty())
{
@@ -778,15 +736,15 @@ public static class ConfigHandler
{
profileItem.ConfigType = EConfigType.WireGuard;
- profileItem.Address = profileItem.Address.TrimEx();
- profileItem.Id = profileItem.Id.TrimEx();
- profileItem.PublicKey = profileItem.PublicKey.TrimEx();
- profileItem.Path = profileItem.Path.TrimEx();
- profileItem.RequestHost = profileItem.RequestHost.TrimEx();
+ profileItem.Address = profileItem.Address.TrimSafe();
+ profileItem.Id = profileItem.Id.TrimSafe();
+ profileItem.PublicKey = profileItem.PublicKey.TrimSafe();
+ profileItem.Path = profileItem.Path.TrimSafe();
+ profileItem.RequestHost = profileItem.RequestHost.TrimSafe();
profileItem.Network = string.Empty;
if (profileItem.ShortId.IsNullOrEmpty())
{
- profileItem.ShortId = Global.TunMtus.First().ToString();
+ profileItem.ShortId = AppConfig.TunMtus[0].ToString(CultureInfo.InvariantCulture);
}
if (profileItem.Id.IsNullOrEmpty())
@@ -812,13 +770,13 @@ public static class ConfigHandler
profileItem.ConfigType = EConfigType.Anytls;
profileItem.CoreType = ECoreType.sing_box;
- profileItem.Address = profileItem.Address.TrimEx();
- profileItem.Id = profileItem.Id.TrimEx();
- profileItem.Security = profileItem.Security.TrimEx();
+ profileItem.Address = profileItem.Address.TrimSafe();
+ profileItem.Id = profileItem.Id.TrimSafe();
+ profileItem.Security = profileItem.Security.TrimSafe();
profileItem.Network = string.Empty;
if (profileItem.StreamSecurity.IsNullOrEmpty())
{
- profileItem.StreamSecurity = Global.StreamSecurity;
+ profileItem.StreamSecurity = AppConfig.StreamSecurity;
}
if (profileItem.Id.IsNullOrEmpty())
{
@@ -864,10 +822,10 @@ public static class ConfigHandler
Delay = t33?.Delay ?? 0,
Speed = t33?.Speed ?? 0,
Sort = t33?.Sort ?? 0,
- TodayDown = (t22?.TodayDown ?? 0).ToString("D16"),
- TodayUp = (t22?.TodayUp ?? 0).ToString("D16"),
- TotalDown = (t22?.TotalDown ?? 0).ToString("D16"),
- TotalUp = (t22?.TotalUp ?? 0).ToString("D16"),
+ TodayDown = (t22?.TodayDown ?? 0).ToString("D16", CultureInfo.InvariantCulture),
+ TodayUp = (t22?.TodayUp ?? 0).ToString("D16", CultureInfo.InvariantCulture),
+ TotalDown = (t22?.TotalDown ?? 0).ToString("D16", CultureInfo.InvariantCulture),
+ TotalUp = (t22?.TotalUp ?? 0).ToString("D16", CultureInfo.InvariantCulture),
}).ToList();
Enum.TryParse(colName, true, out EServerColName name);
@@ -956,18 +914,18 @@ public static class ConfigHandler
{
profileItem.ConfigType = EConfigType.VLESS;
- profileItem.Address = profileItem.Address.TrimEx();
- profileItem.Id = profileItem.Id.TrimEx();
- profileItem.Security = profileItem.Security.TrimEx();
- profileItem.Network = profileItem.Network.TrimEx();
- profileItem.HeaderType = profileItem.HeaderType.TrimEx();
- profileItem.RequestHost = profileItem.RequestHost.TrimEx();
- profileItem.Path = profileItem.Path.TrimEx();
- profileItem.StreamSecurity = profileItem.StreamSecurity.TrimEx();
+ profileItem.Address = profileItem.Address.TrimSafe();
+ profileItem.Id = profileItem.Id.TrimSafe();
+ profileItem.Security = profileItem.Security.TrimSafe();
+ profileItem.Network = profileItem.Network.TrimSafe();
+ profileItem.HeaderType = profileItem.HeaderType.TrimSafe();
+ profileItem.RequestHost = profileItem.RequestHost.TrimSafe();
+ profileItem.Path = profileItem.Path.TrimSafe();
+ profileItem.StreamSecurity = profileItem.StreamSecurity.TrimSafe();
- if (!Global.Flows.Contains(profileItem.Flow))
+ if (!AppConfig.Flows.Contains(profileItem.Flow))
{
- profileItem.Flow = Global.Flows.First();
+ profileItem.Flow = AppConfig.Flows.First();
}
if (profileItem.Id.IsNullOrEmpty())
{
@@ -975,7 +933,7 @@ public static class ConfigHandler
}
if (profileItem.Security.IsNullOrEmpty())
{
- profileItem.Security = Global.None;
+ profileItem.Security = AppConfig.None;
}
await AddServerCommon(config, profileItem, toFile);
@@ -993,7 +951,7 @@ public static class ConfigHandler
public static async Task> DedupServerList(Config config, string subId)
{
var lstProfile = await AppManager.Instance.ProfileItems(subId);
- if (lstProfile == null)
+ if (lstProfile is null)
{
return new Tuple(0, 0);
}
@@ -1035,8 +993,8 @@ public static class ConfigHandler
if (profileItem.StreamSecurity.IsNotEmpty())
{
- if (profileItem.StreamSecurity != Global.StreamSecurity
- && profileItem.StreamSecurity != Global.StreamSecurityReality)
+ if (profileItem.StreamSecurity is not AppConfig.StreamSecurity
+ and not AppConfig.StreamSecurityReality)
{
profileItem.StreamSecurity = string.Empty;
}
@@ -1044,18 +1002,20 @@ public static class ConfigHandler
{
if (profileItem.AllowInsecure.IsNullOrEmpty())
{
- profileItem.AllowInsecure = config.CoreBasicItem.DefAllowInsecure.ToString().ToLower();
+ profileItem.AllowInsecure = config.CoreBasicItem.DefAllowInsecure
+ .ToString()
+ .ToLowerInvariant();
}
- if (profileItem.Fingerprint.IsNullOrEmpty() && profileItem.StreamSecurity == Global.StreamSecurityReality)
+ if (profileItem.Fingerprint.IsNullOrEmpty() && profileItem.StreamSecurity == AppConfig.StreamSecurityReality)
{
profileItem.Fingerprint = config.CoreBasicItem.DefFingerprint;
}
}
}
- if (profileItem.Network.IsNotEmpty() && !Global.Networks.Contains(profileItem.Network))
+ if (profileItem.Network.IsNotEmpty() && !AppConfig.Networks.Contains(profileItem.Network))
{
- profileItem.Network = Global.DefaultNetwork;
+ profileItem.Network = AppConfig.DefaultNetwork;
}
var maxSort = -1;
@@ -1080,7 +1040,7 @@ public static class ConfigHandler
return 0;
}
- public static async Task AddGroupServerCommon(Config config, ProfileItem profileItem, ProfileGroupItem profileGroupItem, bool toFile = true)
+ public static async Task AddGroupServerCommon(ProfileItem profileItem, ProfileGroupItem profileGroupItem, bool toFile = true)
{
var maxSort = -1;
if (profileItem.IndexId.IsNullOrEmpty())
@@ -1097,7 +1057,7 @@ public static class ConfigHandler
if (toFile)
{
await SQLiteHelper.Instance.ReplaceAsync(profileItem);
- if (profileGroupItem != null)
+ if (profileGroupItem is not null)
{
profileGroupItem.IndexId = profileItem.IndexId;
await ProfileGroupItemManager.Instance.SaveItemAsync(profileGroupItem);
@@ -1121,7 +1081,7 @@ public static class ConfigHandler
/// True if the profiles match, false otherwise
private static bool CompareProfileItem(ProfileItem? o, ProfileItem? n, bool remarks)
{
- if (o == null || n == null)
+ if (o is null || n is null)
{
return false;
}
@@ -1142,11 +1102,11 @@ public static class ConfigHandler
&& AreEqual(o.Fingerprint, n.Fingerprint)
&& AreEqual(o.PublicKey, n.PublicKey)
&& AreEqual(o.ShortId, n.ShortId)
- && (!remarks || o.Remarks == n.Remarks);
+ && (!remarks || string.Equals(o.Remarks, n.Remarks, StringComparison.Ordinal));
static bool AreEqual(string? a, string? b)
{
- return string.Equals(a, b) || (string.IsNullOrEmpty(a) && string.IsNullOrEmpty(b));
+ return string.Equals(a ?? "", b ?? "", StringComparison.Ordinal);
}
}
@@ -1154,15 +1114,14 @@ public static class ConfigHandler
/// Remove a single server profile by its index ID
/// Deletes the configuration file if it's a custom config
///
- /// Current configuration
/// Index ID of the profile to remove
/// 0 if successful
- private static async Task RemoveProfileItem(Config config, string indexId)
+ private static async Task RemoveProfileItem(string indexId)
{
try
{
var item = await AppManager.Instance.GetProfileItem(indexId);
- if (item == null)
+ if (item is null)
{
return 0;
}
@@ -1185,12 +1144,11 @@ public static class ConfigHandler
/// Create a group server that combines multiple servers for load balancing
/// Generates a configuration file that references multiple servers
///
- /// Current configuration
/// Selected servers to combine
/// Core type to use (Xray or sing_box)
/// Load balancing algorithm
/// Result object with success state and data
- public static async Task AddGroupServer4Multiple(Config config, List selecteds, ECoreType coreType, EMultipleLoad multipleLoad, string? subId)
+ public static async Task AddGroupServer4Multiple(List selecteds, ECoreType coreType, EMultipleLoad multipleLoad, string? subId)
{
var result = new RetResult();
@@ -1237,7 +1195,7 @@ public static class ConfigHandler
MultipleLoad = multipleLoad,
IndexId = indexId,
};
- var ret = await AddGroupServerCommon(config, profile, profileGroup, true);
+ var ret = await AddGroupServerCommon(profile, profileGroup, true);
result.Success = ret == 0;
result.Data = indexId;
return result;
@@ -1269,7 +1227,7 @@ public static class ConfigHandler
{
CoreType = ECoreType.sing_box,
ConfigType = EConfigType.SOCKS,
- Address = Global.Loopback,
+ Address = AppConfig.Loopback,
SpiderX = tun2SocksAddress, // Tun2SocksAddress
Port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks)
};
@@ -1281,7 +1239,7 @@ public static class ConfigHandler
{
CoreType = preCoreType,
ConfigType = EConfigType.SOCKS,
- Address = Global.Loopback,
+ Address = AppConfig.Loopback,
Port = node.PreSocksPort.Value,
};
}
@@ -1352,7 +1310,10 @@ public static class ConfigHandler
foreach (var str in arrData)
{
//maybe sub
- if (!isSub && (str.StartsWith(Global.HttpsProtocol) || str.StartsWith(Global.HttpProtocol)))
+ if (
+ !isSub && (str.StartsWith(AppConfig.HttpsProtocol, StringComparison.OrdinalIgnoreCase)
+ || str.StartsWith(AppConfig.HttpProtocol, StringComparison.OrdinalIgnoreCase))
+ )
{
if (await AddSubItem(config, str) == 0)
{
@@ -1438,7 +1399,7 @@ public static class ConfigHandler
{
lstProfiles = V2rayFmt.ResolveFullArray(strData, subRemarks);
}
- if (lstProfiles != null && lstProfiles.Count > 0)
+ if (lstProfiles is not null && lstProfiles.Count > 0)
{
if (isSub && subid.IsNotEmpty())
{
@@ -1462,31 +1423,30 @@ public static class ConfigHandler
}
ProfileItem? profileItem = null;
- //Is sing-box configuration
- if (profileItem is null)
- {
- profileItem = SingboxFmt.ResolveFull(strData, subRemarks);
- }
- //Is v2ray configuration
- if (profileItem is null)
- {
- profileItem = V2rayFmt.ResolveFull(strData, subRemarks);
- }
+
//Is Html Page
if (profileItem is null && HtmlPageFmt.IsHtmlPage(strData))
{
return -1;
}
- //Is Clash configuration
- if (profileItem is null)
+
+ var resolvers = new Func[]
{
- profileItem = ClashFmt.ResolveFull(strData, subRemarks);
- }
- //Is hysteria configuration
- if (profileItem is null)
+ SingboxFmt.ResolveFull,
+ V2rayFmt.ResolveFull,
+ ClashFmt.ResolveFull,
+ Hysteria2Fmt.ResolveFull2
+ };
+
+ foreach (var resolver in resolvers)
{
- profileItem = Hysteria2Fmt.ResolveFull2(strData, subRemarks);
+ profileItem ??= resolver(strData, subRemarks);
+ if (profileItem is not null)
+ {
+ break;
+ }
}
+
if (profileItem is null || profileItem.Address.IsNullOrEmpty())
{
return -1;
@@ -1600,24 +1560,24 @@ public static class ConfigHandler
}
//Select active node
- if (activeProfile != null)
+ if (activeProfile is not null)
{
var lstSub = await AppManager.Instance.ProfileItems(subid);
var existItem = lstSub?.FirstOrDefault(t => config.UiItem.EnableUpdateSubOnlyRemarksExist ? t.Remarks == activeProfile.Remarks : CompareProfileItem(t, activeProfile, true));
- if (existItem != null)
+ if (existItem is not null)
{
await ConfigHandler.SetDefaultServerIndex(config, existItem.IndexId);
}
}
//Keep the last traffic statistics
- if (lstOriSub != null)
+ if (lstOriSub is not null)
{
var lstSub = await AppManager.Instance.ProfileItems(subid);
foreach (var item in lstSub)
{
var existItem = lstOriSub?.FirstOrDefault(t => config.UiItem.EnableUpdateSubOnlyRemarksExist ? t.Remarks == item.Remarks : CompareProfileItem(t, item, true));
- if (existItem != null)
+ if (existItem is not null)
{
await StatisticsManager.Instance.CloneServerStatItem(existItem.IndexId, item.IndexId);
}
@@ -1653,12 +1613,12 @@ public static class ConfigHandler
};
var uri = Utils.TryUri(url);
- if (uri == null)
+ if (uri is null)
{
return -1;
}
//Do not allow http protocol
- if (url.StartsWith(Global.HttpProtocol) && !Utils.IsPrivateNetwork(uri.IdnHost))
+ if (url.StartsWith(AppConfig.HttpProtocol, StringComparison.OrdinalIgnoreCase) && !Utils.IsPrivateNetwork(uri.IdnHost))
{
//TODO Temporary reminder to be removed later
NoticeManager.Instance.Enqueue(ResUI.InsecureUrlProtocol);
@@ -1835,7 +1795,7 @@ public static class ConfigHandler
}
var lstRules = JsonUtils.Deserialize>(strData);
- if (lstRules == null)
+ if (lstRules is null)
{
return -1;
}
@@ -2028,14 +1988,14 @@ public static class ConfigHandler
}
var template = JsonUtils.Deserialize(templateContent);
- if (template == null)
+ if (template is null)
{
return await InitBuiltinRouting(config, blImportAdvancedRules); // fallback
}
var items = await AppManager.Instance.RoutingItems();
var maxSort = items.Count;
- if (!blImportAdvancedRules && items.Where(t => t.Remarks.StartsWith(template.Version)).ToList().Count > 0)
+ if (!blImportAdvancedRules && items.Where(t => t.Remarks.StartsWith(template.Version, StringComparison.OrdinalIgnoreCase)).ToList().Count > 0)
{
return 0;
}
@@ -2088,20 +2048,20 @@ public static class ConfigHandler
//TODO Temporary code to be removed later
var lockItem = items?.FirstOrDefault(t => t.Locked == true);
- if (lockItem != null)
+ if (lockItem is not null)
{
await ConfigHandler.RemoveRoutingItem(lockItem);
items = await AppManager.Instance.RoutingItems();
}
- if (!blImportAdvancedRules && items.Count(u => u.Remarks.StartsWith(ver)) > 0)
+ if (!blImportAdvancedRules && items.Any(u => u.Remarks.StartsWith(ver, StringComparison.OrdinalIgnoreCase)))
{
//migrate
//TODO Temporary code to be removed later
if (config.RoutingBasicItem.RoutingIndexId.IsNotEmpty())
{
var item = items.FirstOrDefault(t => t.Id == config.RoutingBasicItem.RoutingIndexId);
- if (item != null)
+ if (item is not null)
{
await SetDefaultRouting(config, item);
}
@@ -2119,7 +2079,7 @@ public static class ConfigHandler
Url = string.Empty,
Sort = maxSort + 1,
};
- await AddBatchRoutingRules(item2, EmbedUtils.GetEmbedText(Global.CustomRoutingFileName + "white"));
+ await AddBatchRoutingRules(item2, EmbedUtils.GetEmbedText(AppConfig.CustomRoutingFileName + "white"));
//Blacklist
var item3 = new RoutingItem()
@@ -2128,7 +2088,7 @@ public static class ConfigHandler
Url = string.Empty,
Sort = maxSort + 2,
};
- await AddBatchRoutingRules(item3, EmbedUtils.GetEmbedText(Global.CustomRoutingFileName + "black"));
+ await AddBatchRoutingRules(item3, EmbedUtils.GetEmbedText(AppConfig.CustomRoutingFileName + "black"));
//Global
var item1 = new RoutingItem()
@@ -2137,7 +2097,7 @@ public static class ConfigHandler
Url = string.Empty,
Sort = maxSort + 3,
};
- await AddBatchRoutingRules(item1, EmbedUtils.GetEmbedText(Global.CustomRoutingFileName + "global"));
+ await AddBatchRoutingRules(item1, EmbedUtils.GetEmbedText(AppConfig.CustomRoutingFileName + "global"));
if (!blImportAdvancedRules)
{
@@ -2217,7 +2177,7 @@ public static class ConfigHandler
/// 0 if successful, -1 if failed
public static async Task SaveDNSItems(Config config, DNSItem item)
{
- if (item == null)
+ if (item is null)
{
return -1;
}
@@ -2256,7 +2216,7 @@ public static class ConfigHandler
}
var template = JsonUtils.Deserialize(templateContent);
- if (template == null)
+ if (template is null)
{
return currentItem;
}
@@ -2292,9 +2252,9 @@ public static class ConfigHandler
FakeIP = false,
GlobalFakeIp = true,
BlockBindingQuery = true,
- DirectDNS = Global.DomainDirectDNSAddress.FirstOrDefault(),
- RemoteDNS = Global.DomainRemoteDNSAddress.FirstOrDefault(),
- BootstrapDNS = Global.DomainPureIPDNSAddress.FirstOrDefault(),
+ DirectDNS = AppConfig.DomainDirectDNSAddress.FirstOrDefault(),
+ RemoteDNS = AppConfig.DomainRemoteDNSAddress.FirstOrDefault(),
+ BootstrapDNS = AppConfig.DomainPureIPDNSAddress.FirstOrDefault(),
};
}
@@ -2308,7 +2268,7 @@ public static class ConfigHandler
}
var template = JsonUtils.Deserialize(templateContent);
- if (template == null)
+ if (template is null)
{
return null;
}
@@ -2345,7 +2305,7 @@ public static class ConfigHandler
public static async Task SaveFullConfigTemplate(Config config, FullConfigTemplateItem item)
{
- if (item == null)
+ if (item is null)
{
return -1;
}
@@ -2392,15 +2352,15 @@ public static class ConfigHandler
break;
case EPresetType.Russia:
- config.ConstItem.GeoSourceUrl = Global.GeoFilesSources[1];
- config.ConstItem.SrsSourceUrl = Global.SingboxRulesetSources[1];
- config.ConstItem.RouteRulesTemplateSourceUrl = Global.RoutingRulesSources[1];
+ config.ConstItem.GeoSourceUrl = AppConfig.GeoFilesSources[1];
+ config.ConstItem.SrsSourceUrl = AppConfig.SingboxRulesetSources[1];
+ config.ConstItem.RouteRulesTemplateSourceUrl = AppConfig.RoutingRulesSources[1];
- var xrayDnsRussia = await GetExternalDNSItem(ECoreType.Xray, Global.DNSTemplateSources[1] + "v2ray.json");
- var singboxDnsRussia = await GetExternalDNSItem(ECoreType.sing_box, Global.DNSTemplateSources[1] + "sing_box.json");
- var simpleDnsRussia = await GetExternalSimpleDNSItem(Global.DNSTemplateSources[1] + "simple_dns.json");
+ var xrayDnsRussia = await GetExternalDNSItem(ECoreType.Xray, AppConfig.DNSTemplateSources[1] + "v2ray.json");
+ var singboxDnsRussia = await GetExternalDNSItem(ECoreType.sing_box, AppConfig.DNSTemplateSources[1] + "sing_box.json");
+ var simpleDnsRussia = await GetExternalSimpleDNSItem(AppConfig.DNSTemplateSources[1] + "simple_dns.json");
- if (simpleDnsRussia == null)
+ if (simpleDnsRussia is null)
{
xrayDnsRussia.Enabled = true;
singboxDnsRussia.Enabled = true;
@@ -2415,15 +2375,15 @@ public static class ConfigHandler
break;
case EPresetType.Iran:
- config.ConstItem.GeoSourceUrl = Global.GeoFilesSources[2];
- config.ConstItem.SrsSourceUrl = Global.SingboxRulesetSources[2];
- config.ConstItem.RouteRulesTemplateSourceUrl = Global.RoutingRulesSources[2];
+ config.ConstItem.GeoSourceUrl = AppConfig.GeoFilesSources[2];
+ config.ConstItem.SrsSourceUrl = AppConfig.SingboxRulesetSources[2];
+ config.ConstItem.RouteRulesTemplateSourceUrl = AppConfig.RoutingRulesSources[2];
- var xrayDnsIran = await GetExternalDNSItem(ECoreType.Xray, Global.DNSTemplateSources[2] + "v2ray.json");
- var singboxDnsIran = await GetExternalDNSItem(ECoreType.sing_box, Global.DNSTemplateSources[2] + "sing_box.json");
- var simpleDnsIran = await GetExternalSimpleDNSItem(Global.DNSTemplateSources[2] + "simple_dns.json");
+ var xrayDnsIran = await GetExternalDNSItem(ECoreType.Xray, AppConfig.DNSTemplateSources[2] + "v2ray.json");
+ var singboxDnsIran = await GetExternalDNSItem(ECoreType.sing_box, AppConfig.DNSTemplateSources[2] + "sing_box.json");
+ var simpleDnsIran = await GetExternalSimpleDNSItem(AppConfig.DNSTemplateSources[2] + "simple_dns.json");
- if (simpleDnsIran == null)
+ if (simpleDnsIran is null)
{
xrayDnsIran.Enabled = true;
singboxDnsIran.Enabled = true;
@@ -2448,7 +2408,7 @@ public static class ConfigHandler
public static WindowSizeItem? GetWindowSizeItem(Config config, string typeName)
{
var sizeItem = config?.UiItem?.WindowSizeItem?.FirstOrDefault(t => t.TypeName == typeName);
- if (sizeItem == null || sizeItem.Width <= 0 || sizeItem.Height <= 0)
+ if (sizeItem is null || sizeItem.Width <= 0 || sizeItem.Height <= 0)
{
return null;
}
@@ -2459,7 +2419,7 @@ public static class ConfigHandler
public static int SaveWindowSizeItem(Config config, string typeName, double width, double height)
{
var sizeItem = config?.UiItem?.WindowSizeItem?.FirstOrDefault(t => t.TypeName == typeName);
- if (sizeItem == null)
+ if (sizeItem is null)
{
sizeItem = new WindowSizeItem { TypeName = typeName };
config.UiItem.WindowSizeItem.Add(sizeItem);
diff --git a/v2rayN/ServiceLib/Handler/ConnectionHandler.cs b/v2rayN/ServiceLib/Handler/ConnectionHandler.cs
index 05825d93..497f64dd 100644
--- a/v2rayN/ServiceLib/Handler/ConnectionHandler.cs
+++ b/v2rayN/ServiceLib/Handler/ConnectionHandler.cs
@@ -7,7 +7,7 @@ public static class ConnectionHandler
public static async Task RunAvailabilityCheck()
{
var time = await GetRealPingTimeInfo();
- var ip = time > 0 ? await GetIPInfo() ?? Global.None : Global.None;
+ var ip = time > 0 ? await GetIPInfo() ?? AppConfig.None : AppConfig.None;
return string.Format(ResUI.TestMeOutput, time, ip);
}
@@ -22,13 +22,13 @@ public static class ConnectionHandler
var downloadHandle = new DownloadService();
var result = await downloadHandle.TryDownloadString(url, true, "");
- if (result == null)
+ if (result is null)
{
return null;
}
var ipInfo = JsonUtils.Deserialize(result);
- if (ipInfo == null)
+ if (ipInfo is null)
{
return null;
}
@@ -45,7 +45,7 @@ public static class ConnectionHandler
try
{
var port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks);
- var webProxy = new WebProxy($"socks5://{Global.Loopback}:{port}");
+ var webProxy = new WebProxy($"socks5://{AppConfig.Loopback}:{port}");
var url = AppManager.Instance.Config.SpeedTestItem.SpeedPingTestUrl;
for (var i = 0; i < 2; i++)
@@ -76,7 +76,7 @@ public static class ConnectionHandler
using var client = new HttpClient(new SocketsHttpHandler()
{
Proxy = webProxy,
- UseProxy = webProxy != null
+ UseProxy = webProxy is not null
});
List oneTime = new();
diff --git a/v2rayN/ServiceLib/Handler/CoreConfigHandler.cs b/v2rayN/ServiceLib/Handler/CoreConfigHandler.cs
index f51e2051..159ea262 100644
--- a/v2rayN/ServiceLib/Handler/CoreConfigHandler.cs
+++ b/v2rayN/ServiceLib/Handler/CoreConfigHandler.cs
@@ -7,10 +7,13 @@ public static class CoreConfigHandler
{
private static readonly string _tag = "CoreConfigHandler";
+ private static readonly CompositeFormat _successfulConfigFormat =
+ CompositeFormat.Parse(ResUI.SuccessfulConfiguration);
+
public static async Task GenerateClientConfig(ProfileItem node, string? fileName)
{
var config = AppManager.Instance.Config;
- var result = new RetResult();
+ RetResult result;
if (node.ConfigType == EConfigType.Custom)
{
@@ -33,7 +36,7 @@ public static class CoreConfigHandler
{
return result;
}
- if (fileName.IsNotEmpty() && result.Data != null)
+ if (fileName.IsNotEmpty() && result.Data is not null)
{
await File.WriteAllTextAsync(fileName, result.Data.ToString());
}
@@ -46,7 +49,7 @@ public static class CoreConfigHandler
var ret = new RetResult();
try
{
- if (node == null || fileName is null)
+ if (node is null || fileName is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -78,7 +81,7 @@ public static class CoreConfigHandler
return ret;
}
- ret.Msg = string.Format(ResUI.SuccessfulConfiguration, "");
+ ret.Msg = string.Format(CultureInfo.CurrentCulture, _successfulConfigFormat, "");
ret.Success = true;
return await Task.FromResult(ret);
}
@@ -111,7 +114,7 @@ public static class CoreConfigHandler
public static async Task GenerateClientSpeedtestConfig(Config config, ProfileItem node, ServerTestItem testItem, string fileName)
{
- var result = new RetResult();
+ RetResult result;
var initPort = AppManager.Instance.GetLocalPort(EInboundProtocol.speedtest);
var port = Utils.GetFreePort(initPort + testItem.QueueNum);
testItem.Port = port;
diff --git a/v2rayN/ServiceLib/Handler/Fmt/AnytlsFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/AnytlsFmt.cs
index f098b6a4..c2080b4a 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/AnytlsFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/AnytlsFmt.cs
@@ -7,7 +7,7 @@ public class AnytlsFmt : BaseFmt
msg = ResUI.ConfigurationFormatIncorrect;
var parsedUrl = Utils.TryUri(str);
- if (parsedUrl == null)
+ if (parsedUrl is null)
{
return null;
}
@@ -30,7 +30,7 @@ public class AnytlsFmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
- if (item == null)
+ if (item is null)
{
return null;
}
@@ -41,7 +41,7 @@ public class AnytlsFmt : BaseFmt
}
var pw = item.Id;
var dicQuery = new Dictionary();
- ToUriQuery(item, Global.None, ref dicQuery);
+ ToUriQuery(item, AppConfig.None, ref dicQuery);
return ToUri(EConfigType.Anytls, item.Address, item.Port, pw, dicQuery, remark);
}
diff --git a/v2rayN/ServiceLib/Handler/Fmt/BaseFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/BaseFmt.cs
index 8bd3c3de..f336f249 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/BaseFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/BaseFmt.cs
@@ -32,7 +32,7 @@ public class BaseFmt
}
else
{
- if (securityDef != null)
+ if (securityDef is not null)
{
dicQuery.Add("security", securityDef);
}
@@ -62,7 +62,7 @@ public class BaseFmt
dicQuery.Add("pqv", Utils.UrlEncode(item.Mldsa65Verify));
}
- if (item.StreamSecurity.Equals(Global.StreamSecurity))
+ if (item.StreamSecurity.Equals(AppConfig.StreamSecurity, StringComparison.OrdinalIgnoreCase))
{
if (item.Alpn.IsNotEmpty())
{
@@ -84,7 +84,7 @@ public class BaseFmt
switch (item.Network)
{
case nameof(ETransport.tcp):
- dicQuery.Add("headerType", item.HeaderType.IsNotEmpty() ? item.HeaderType : Global.None);
+ dicQuery.Add("headerType", item.HeaderType.IsNotEmpty() ? item.HeaderType : AppConfig.None);
if (item.RequestHost.IsNotEmpty())
{
dicQuery.Add("host", Utils.UrlEncode(item.RequestHost));
@@ -92,7 +92,7 @@ public class BaseFmt
break;
case nameof(ETransport.kcp):
- dicQuery.Add("headerType", item.HeaderType.IsNotEmpty() ? item.HeaderType : Global.None);
+ dicQuery.Add("headerType", item.HeaderType.IsNotEmpty() ? item.HeaderType : AppConfig.None);
if (item.Path.IsNotEmpty())
{
dicQuery.Add("seed", Utils.UrlEncode(item.Path));
@@ -120,14 +120,14 @@ public class BaseFmt
{
dicQuery.Add("path", Utils.UrlEncode(item.Path));
}
- if (item.HeaderType.IsNotEmpty() && Global.XhttpMode.Contains(item.HeaderType))
+ if (item.HeaderType.IsNotEmpty() && AppConfig.XhttpMode.Contains(item.HeaderType))
{
dicQuery.Add("mode", Utils.UrlEncode(item.HeaderType));
}
if (item.Extra.IsNotEmpty())
{
var node = JsonUtils.ParseJson(item.Extra);
- var extra = node != null
+ var extra = node is not null
? JsonUtils.Serialize(node, new JsonSerializerOptions
{
WriteIndented = false,
@@ -153,7 +153,7 @@ public class BaseFmt
break;
case nameof(ETransport.quic):
- dicQuery.Add("headerType", item.HeaderType.IsNotEmpty() ? item.HeaderType : Global.None);
+ dicQuery.Add("headerType", item.HeaderType.IsNotEmpty() ? item.HeaderType : AppConfig.None);
dicQuery.Add("quicSecurity", Utils.UrlEncode(item.RequestHost));
dicQuery.Add("key", Utils.UrlEncode(item.Path));
break;
@@ -163,7 +163,7 @@ public class BaseFmt
{
dicQuery.Add("authority", Utils.UrlEncode(item.RequestHost));
dicQuery.Add("serviceName", Utils.UrlEncode(item.Path));
- if (item.HeaderType is Global.GrpcGunMode or Global.GrpcMultiMode)
+ if (item.HeaderType is AppConfig.GrpcGunMode or AppConfig.GrpcMultiMode)
{
dicQuery.Add("mode", Utils.UrlEncode(item.HeaderType));
}
@@ -191,7 +191,7 @@ public class BaseFmt
private static int ToUriQueryAllowInsecure(ProfileItem item, ref Dictionary dicQuery)
{
- if (item.AllowInsecure.Equals(Global.AllowInsecure.First()))
+ if (item.AllowInsecure.Equals(AppConfig.AllowInsecure.First(), StringComparison.OrdinalIgnoreCase))
{
// Add two for compatibility
dicQuery.Add("insecure", "1");
@@ -222,11 +222,11 @@ public class BaseFmt
if (_allowInsecureArray.Any(k => GetQueryDecoded(query, k) == "1"))
{
- item.AllowInsecure = Global.AllowInsecure.First();
+ item.AllowInsecure = AppConfig.AllowInsecure.First();
}
else if (_allowInsecureArray.Any(k => GetQueryDecoded(query, k) == "0"))
{
- item.AllowInsecure = Global.AllowInsecure.Skip(1).First();
+ item.AllowInsecure = AppConfig.AllowInsecure.Skip(1).First();
}
else
{
@@ -237,12 +237,12 @@ public class BaseFmt
switch (item.Network)
{
case nameof(ETransport.tcp):
- item.HeaderType = GetQueryValue(query, "headerType", Global.None);
+ item.HeaderType = GetQueryValue(query, "headerType", AppConfig.None);
item.RequestHost = GetQueryDecoded(query, "host");
break;
case nameof(ETransport.kcp):
- item.HeaderType = GetQueryValue(query, "headerType", Global.None);
+ item.HeaderType = GetQueryValue(query, "headerType", AppConfig.None);
item.Path = GetQueryDecoded(query, "seed");
break;
@@ -260,7 +260,7 @@ public class BaseFmt
if (extraDecoded.IsNotEmpty())
{
var node = JsonUtils.ParseJson(extraDecoded);
- if (node != null)
+ if (node is not null)
{
extraDecoded = JsonUtils.Serialize(node, new JsonSerializerOptions
{
@@ -281,15 +281,15 @@ public class BaseFmt
break;
case nameof(ETransport.quic):
- item.HeaderType = GetQueryValue(query, "headerType", Global.None);
- item.RequestHost = GetQueryValue(query, "quicSecurity", Global.None);
+ item.HeaderType = GetQueryValue(query, "headerType", AppConfig.None);
+ item.RequestHost = GetQueryValue(query, "quicSecurity", AppConfig.None);
item.Path = GetQueryDecoded(query, "key");
break;
case nameof(ETransport.grpc):
item.RequestHost = GetQueryDecoded(query, "authority");
item.Path = GetQueryDecoded(query, "serviceName");
- item.HeaderType = GetQueryDecoded(query, "mode", Global.GrpcGunMode);
+ item.HeaderType = GetQueryDecoded(query, "mode", AppConfig.GrpcGunMode);
break;
default:
@@ -300,7 +300,7 @@ public class BaseFmt
protected static bool Contains(string str, params string[] s)
{
- return s.All(item => str.Contains(item, StringComparison.OrdinalIgnoreCase));
+ return s.All(item => str.Contains(item, StringComparison.Ordinal));
}
protected static string WriteAllText(string strData, string ext = "json")
@@ -312,12 +312,12 @@ public class BaseFmt
protected static string ToUri(EConfigType eConfigType, string address, object port, string userInfo, Dictionary? dicQuery, string? remark)
{
- var query = dicQuery != null
+ var query = dicQuery is not null
? ("?" + string.Join("&", dicQuery.Select(x => x.Key + "=" + x.Value).ToArray()))
: string.Empty;
var url = $"{Utils.UrlEncode(userInfo)}@{GetIpv6(address)}:{port}";
- return $"{Global.ProtocolShares[eConfigType]}{url}{query}{remark}";
+ return $"{AppConfig.ProtocolShares[eConfigType]}{url}{query}{remark}";
}
protected static string GetQueryValue(NameValueCollection query, string key, string defaultValue = "")
diff --git a/v2rayN/ServiceLib/Handler/Fmt/FmtHandler.cs b/v2rayN/ServiceLib/Handler/Fmt/FmtHandler.cs
index 4fc251b7..bf069b8c 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/FmtHandler.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/FmtHandler.cs
@@ -33,58 +33,29 @@ public class FmtHandler
public static ProfileItem? ResolveConfig(string config, out string msg)
{
- msg = ResUI.ConfigurationFormatIncorrect;
+ var span = config.AsSpan().Trim();
+ if (span.IsEmpty)
+ {
+ msg = ResUI.FailedReadConfiguration;
+ return null;
+ }
try
{
- var str = config.TrimEx();
- if (str.IsNullOrEmpty())
+ return span switch
{
- msg = ResUI.FailedReadConfiguration;
- return null;
- }
-
- if (str.StartsWith(Global.ProtocolShares[EConfigType.VMess]))
- {
- return VmessFmt.Resolve(str, out msg);
- }
- else if (str.StartsWith(Global.ProtocolShares[EConfigType.Shadowsocks]))
- {
- return ShadowsocksFmt.Resolve(str, out msg);
- }
- else if (str.StartsWith(Global.ProtocolShares[EConfigType.SOCKS]))
- {
- return SocksFmt.Resolve(str, out msg);
- }
- else if (str.StartsWith(Global.ProtocolShares[EConfigType.Trojan]))
- {
- return TrojanFmt.Resolve(str, out msg);
- }
- else if (str.StartsWith(Global.ProtocolShares[EConfigType.VLESS]))
- {
- return VLESSFmt.Resolve(str, out msg);
- }
- else if (str.StartsWith(Global.ProtocolShares[EConfigType.Hysteria2]) || str.StartsWith(Global.Hysteria2ProtocolShare))
- {
- return Hysteria2Fmt.Resolve(str, out msg);
- }
- else if (str.StartsWith(Global.ProtocolShares[EConfigType.TUIC]))
- {
- return TuicFmt.Resolve(str, out msg);
- }
- else if (str.StartsWith(Global.ProtocolShares[EConfigType.WireGuard]))
- {
- return WireguardFmt.Resolve(str, out msg);
- }
- else if (str.StartsWith(Global.ProtocolShares[EConfigType.Anytls]))
- {
- return AnytlsFmt.Resolve(str, out msg);
- }
- else
- {
- msg = ResUI.NonvmessOrssProtocol;
- return null;
- }
+ _ when IsProtocol(span, EConfigType.VMess) => VmessFmt.Resolve(config, out msg),
+ _ when IsProtocol(span, EConfigType.Shadowsocks) => ShadowsocksFmt.Resolve(config, out msg),
+ _ when IsProtocol(span, EConfigType.SOCKS) => SocksFmt.Resolve(config, out msg),
+ _ when IsProtocol(span, EConfigType.Trojan) => TrojanFmt.Resolve(config, out msg),
+ _ when IsProtocol(span, EConfigType.VLESS) => VLESSFmt.Resolve(config, out msg),
+ _ when IsProtocol(span, EConfigType.Hysteria2) || span.StartsWith(AppConfig.Hysteria2ProtocolShare,
+ StringComparison.OrdinalIgnoreCase) => Hysteria2Fmt.Resolve(config, out msg),
+ _ when IsProtocol(span, EConfigType.TUIC) => TuicFmt.Resolve(config, out msg),
+ _ when IsProtocol(span, EConfigType.WireGuard) => WireguardFmt.Resolve(config, out msg),
+ _ when IsProtocol(span, EConfigType.Anytls) => AnytlsFmt.Resolve(config, out msg),
+ _ => HandleUnknown(out msg)
+ };
}
catch (Exception ex)
{
@@ -93,4 +64,16 @@ public class FmtHandler
return null;
}
}
+
+ private static bool IsProtocol(ReadOnlySpan strSpan, EConfigType type)
+ {
+ var prefix = AppConfig.ProtocolShares[type].AsSpan();
+ return strSpan.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static ProfileItem? HandleUnknown(out string msg)
+ {
+ msg = ResUI.NonvmessOrssProtocol;
+ return null;
+ }
}
diff --git a/v2rayN/ServiceLib/Handler/Fmt/Hysteria2Fmt.cs b/v2rayN/ServiceLib/Handler/Fmt/Hysteria2Fmt.cs
index d92bd0c8..1bd93211 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/Hysteria2Fmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/Hysteria2Fmt.cs
@@ -11,7 +11,7 @@ public class Hysteria2Fmt : BaseFmt
};
var url = Utils.TryUri(str);
- if (url == null)
+ if (url is null)
{
return null;
}
@@ -35,13 +35,11 @@ public class Hysteria2Fmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
- if (item == null)
+ if (item is null)
{
return null;
}
- var url = string.Empty;
-
var remark = string.Empty;
if (item.Remarks.IsNotEmpty())
{
diff --git a/v2rayN/ServiceLib/Handler/Fmt/ShadowsocksFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/ShadowsocksFmt.cs
index 62f9e120..8226048f 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/ShadowsocksFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/ShadowsocksFmt.cs
@@ -8,7 +8,7 @@ public class ShadowsocksFmt : BaseFmt
ProfileItem? item;
item = ResolveSSLegacy(str) ?? ResolveSip002(str);
- if (item == null)
+ if (item is null)
{
return null;
}
@@ -24,7 +24,7 @@ public class ShadowsocksFmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
- if (item == null)
+ if (item is null)
{
return null;
}
@@ -46,7 +46,7 @@ public class ShadowsocksFmt : BaseFmt
var plugin = string.Empty;
var pluginArgs = string.Empty;
- if (item.Network == nameof(ETransport.tcp) && item.HeaderType == Global.TcpHeaderHttp)
+ if (item.Network == nameof(ETransport.tcp) && item.HeaderType == AppConfig.TcpHeaderHttp)
{
plugin = "obfs-local";
pluginArgs = $"obfs=http;obfs-host={item.RequestHost};";
@@ -66,7 +66,7 @@ public class ShadowsocksFmt : BaseFmt
{
pluginArgs += "mode=quic;";
}
- if (item.StreamSecurity == Global.StreamSecurity)
+ if (item.StreamSecurity == AppConfig.StreamSecurity)
{
pluginArgs += "tls;";
var certs = CertPemManager.ParsePemChain(item.Cert);
@@ -146,7 +146,7 @@ public class ShadowsocksFmt : BaseFmt
private static ProfileItem? ResolveSip002(string result)
{
var parsedUrl = Utils.TryUri(result);
- if (parsedUrl == null)
+ if (parsedUrl is null)
{
return null;
}
@@ -183,7 +183,7 @@ public class ShadowsocksFmt : BaseFmt
}
var queryParameters = Utils.ParseQueryString(parsedUrl.Query);
- if (queryParameters["plugin"] != null)
+ if (queryParameters["plugin"] is not null)
{
var pluginStr = queryParameters["plugin"];
var pluginParts = pluginStr.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
@@ -211,8 +211,8 @@ public class ShadowsocksFmt : BaseFmt
if ((!obfsMode.IsNullOrEmpty()) && obfsMode.Contains("obfs=http") && obfsHost.IsNotEmpty())
{
obfsHost = obfsHost.Replace("obfs-host=", "");
- item.Network = Global.DefaultNetwork;
- item.HeaderType = Global.TcpHeaderHttp;
+ item.Network = AppConfig.DefaultNetwork;
+ item.HeaderType = AppConfig.TcpHeaderHttp;
item.RequestHost = obfsHost;
}
}
@@ -249,7 +249,7 @@ public class ShadowsocksFmt : BaseFmt
if (hasTls)
{
- item.StreamSecurity = Global.StreamSecurity;
+ item.StreamSecurity = AppConfig.StreamSecurity;
if (!certRaw.IsNullOrEmpty())
{
diff --git a/v2rayN/ServiceLib/Handler/Fmt/SingboxFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/SingboxFmt.cs
index 969895d6..33178373 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/SingboxFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/SingboxFmt.cs
@@ -15,7 +15,7 @@ public class SingboxFmt : BaseFmt
{
var objectString = JsonUtils.Serialize(configObject);
var profileIt = ResolveFull(objectString, subRemarks);
- if (profileIt != null)
+ if (profileIt is not null)
{
lstResult.Add(profileIt);
}
@@ -26,10 +26,10 @@ public class SingboxFmt : BaseFmt
public static ProfileItem? ResolveFull(string strData, string? subRemarks)
{
var config = JsonUtils.ParseJson(strData);
- if (config?["inbounds"] == null
- || config["outbounds"] == null
- || config["route"] == null
- || config["dns"] == null)
+ if (config?["inbounds"] is null
+ || config["outbounds"] is null
+ || config["route"] is null
+ || config["dns"] is null)
{
return null;
}
diff --git a/v2rayN/ServiceLib/Handler/Fmt/SocksFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/SocksFmt.cs
index ae837793..f3270a85 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/SocksFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/SocksFmt.cs
@@ -7,7 +7,7 @@ public class SocksFmt : BaseFmt
msg = ResUI.ConfigurationFormatIncorrect;
var item = ResolveSocksNew(str) ?? ResolveSocks(str);
- if (item == null)
+ if (item is null)
{
return null;
}
@@ -23,7 +23,7 @@ public class SocksFmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
- if (item == null)
+ if (item is null)
{
return null;
}
@@ -43,7 +43,7 @@ public class SocksFmt : BaseFmt
{
ConfigType = EConfigType.SOCKS
};
- result = result[Global.ProtocolShares[EConfigType.SOCKS].Length..];
+ result = result[AppConfig.ProtocolShares[EConfigType.SOCKS].Length..];
//remark
var indexRemark = result.IndexOf('#');
if (indexRemark > 0)
@@ -87,7 +87,7 @@ public class SocksFmt : BaseFmt
private static ProfileItem? ResolveSocksNew(string result)
{
var parsedUrl = Utils.TryUri(result);
- if (parsedUrl == null)
+ if (parsedUrl is null)
{
return null;
}
diff --git a/v2rayN/ServiceLib/Handler/Fmt/TrojanFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/TrojanFmt.cs
index dc4794d8..f1dbbc33 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/TrojanFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/TrojanFmt.cs
@@ -12,7 +12,7 @@ public class TrojanFmt : BaseFmt
};
var url = Utils.TryUri(str);
- if (url == null)
+ if (url is null)
{
return null;
}
@@ -30,7 +30,7 @@ public class TrojanFmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
- if (item == null)
+ if (item is null)
{
return null;
}
diff --git a/v2rayN/ServiceLib/Handler/Fmt/TuicFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/TuicFmt.cs
index 1c5aded6..1d49f03e 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/TuicFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/TuicFmt.cs
@@ -12,7 +12,7 @@ public class TuicFmt : BaseFmt
};
var url = Utils.TryUri(str);
- if (url == null)
+ if (url is null)
{
return null;
}
@@ -21,7 +21,7 @@ public class TuicFmt : BaseFmt
item.Port = url.Port;
item.Remarks = url.GetComponents(UriComponents.Fragment, UriFormat.Unescaped);
var rawUserInfo = Utils.UrlDecode(url.UserInfo);
- var userInfoParts = rawUserInfo.Split(new[] { ':' }, 2);
+ var userInfoParts = rawUserInfo.Split(':', 2);
if (userInfoParts.Length == 2)
{
item.Id = userInfoParts.First();
@@ -37,7 +37,7 @@ public class TuicFmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
- if (item == null)
+ if (item is null)
{
return null;
}
diff --git a/v2rayN/ServiceLib/Handler/Fmt/V2rayFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/V2rayFmt.cs
index 6db45fcd..84f699ac 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/V2rayFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/V2rayFmt.cs
@@ -15,7 +15,7 @@ public class V2rayFmt : BaseFmt
{
var objectString = JsonUtils.Serialize(configObject);
var profileIt = ResolveFull(objectString, subRemarks);
- if (profileIt != null)
+ if (profileIt is not null)
{
lstResult.Add(profileIt);
}
@@ -27,9 +27,9 @@ public class V2rayFmt : BaseFmt
public static ProfileItem? ResolveFull(string strData, string? subRemarks)
{
var config = JsonUtils.ParseJson(strData);
- if (config?["inbounds"] == null
- || config["outbounds"] == null
- || config["routing"] == null)
+ if (config?["inbounds"] is null
+ || config["outbounds"] is null
+ || config["routing"] is null)
{
return null;
}
diff --git a/v2rayN/ServiceLib/Handler/Fmt/VLESSFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/VLESSFmt.cs
index 3048b51c..126a734c 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/VLESSFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/VLESSFmt.cs
@@ -9,11 +9,11 @@ public class VLESSFmt : BaseFmt
ProfileItem item = new()
{
ConfigType = EConfigType.VLESS,
- Security = Global.None
+ Security = AppConfig.None
};
var url = Utils.TryUri(str);
- if (url == null)
+ if (url is null)
{
return null;
}
@@ -24,7 +24,7 @@ public class VLESSFmt : BaseFmt
item.Id = Utils.UrlDecode(url.UserInfo);
var query = Utils.ParseQueryString(url.Query);
- item.Security = GetQueryValue(query, "encryption", Global.None);
+ item.Security = GetQueryValue(query, "encryption", AppConfig.None);
item.StreamSecurity = GetQueryValue(query, "security");
ResolveUriQuery(query, ref item);
@@ -33,7 +33,7 @@ public class VLESSFmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
- if (item == null)
+ if (item is null)
{
return null;
}
@@ -50,9 +50,9 @@ public class VLESSFmt : BaseFmt
}
else
{
- dicQuery.Add("encryption", Global.None);
+ dicQuery.Add("encryption", AppConfig.None);
}
- ToUriQuery(item, Global.None, ref dicQuery);
+ ToUriQuery(item, AppConfig.None, ref dicQuery);
return ToUri(EConfigType.VLESS, item.Address, item.Port, item.Id, dicQuery, remark);
}
diff --git a/v2rayN/ServiceLib/Handler/Fmt/VmessFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/VmessFmt.cs
index e6535d6e..a9bbace5 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/VmessFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/VmessFmt.cs
@@ -19,14 +19,14 @@ public class VmessFmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
- if (item == null)
+ if (item is null)
{
return null;
}
var vmessQRCode = new VmessQRCode
{
v = item.ConfigVersion,
- ps = item.Remarks.TrimEx(),
+ ps = item.Remarks.TrimSafe(),
add = item.Address,
port = item.Port,
id = item.Id,
@@ -40,12 +40,12 @@ public class VmessFmt : BaseFmt
sni = item.Sni,
alpn = item.Alpn,
fp = item.Fingerprint,
- insecure = item.AllowInsecure.Equals(Global.AllowInsecure.First()) ? "1" : "0"
+ insecure = item.AllowInsecure.Equals(AppConfig.AllowInsecure[0], StringComparison.OrdinalIgnoreCase) ? "1" : "0"
};
var url = JsonUtils.Serialize(vmessQRCode);
url = Utils.Base64Encode(url);
- url = $"{Global.ProtocolShares[EConfigType.VMess]}{url}";
+ url = $"{AppConfig.ProtocolShares[EConfigType.VMess]}{url}";
return url;
}
@@ -58,18 +58,18 @@ public class VmessFmt : BaseFmt
ConfigType = EConfigType.VMess
};
- result = result[Global.ProtocolShares[EConfigType.VMess].Length..];
+ result = result[AppConfig.ProtocolShares[EConfigType.VMess].Length..];
result = Utils.Base64Decode(result);
var vmessQRCode = JsonUtils.Deserialize(result);
- if (vmessQRCode == null)
+ if (vmessQRCode is null)
{
msg = ResUI.FailedConversionConfiguration;
return null;
}
- item.Network = Global.DefaultNetwork;
- item.HeaderType = Global.None;
+ item.Network = AppConfig.DefaultNetwork;
+ item.HeaderType = AppConfig.None;
item.ConfigVersion = vmessQRCode.v;
item.Remarks = Utils.ToString(vmessQRCode.ps);
@@ -79,7 +79,7 @@ public class VmessFmt : BaseFmt
item.AlterId = vmessQRCode.aid;
item.Security = Utils.ToString(vmessQRCode.scy);
- item.Security = vmessQRCode.scy.IsNotEmpty() ? vmessQRCode.scy : Global.DefaultSecurity;
+ item.Security = vmessQRCode.scy.IsNotEmpty() ? vmessQRCode.scy : AppConfig.DefaultSecurity;
if (vmessQRCode.net.IsNotEmpty())
{
item.Network = vmessQRCode.net;
@@ -95,7 +95,7 @@ public class VmessFmt : BaseFmt
item.Sni = Utils.ToString(vmessQRCode.sni);
item.Alpn = Utils.ToString(vmessQRCode.alpn);
item.Fingerprint = Utils.ToString(vmessQRCode.fp);
- item.AllowInsecure = vmessQRCode.insecure == "1" ? Global.AllowInsecure.First() : string.Empty;
+ item.AllowInsecure = vmessQRCode.insecure == "1" ? AppConfig.AllowInsecure.First() : string.Empty;
return item;
}
@@ -109,7 +109,7 @@ public class VmessFmt : BaseFmt
};
var url = Utils.TryUri(str);
- if (url == null)
+ if (url is null)
{
return null;
}
diff --git a/v2rayN/ServiceLib/Handler/Fmt/WireguardFmt.cs b/v2rayN/ServiceLib/Handler/Fmt/WireguardFmt.cs
index 6ceb945d..937f583f 100644
--- a/v2rayN/ServiceLib/Handler/Fmt/WireguardFmt.cs
+++ b/v2rayN/ServiceLib/Handler/Fmt/WireguardFmt.cs
@@ -12,7 +12,7 @@ public class WireguardFmt : BaseFmt
};
var url = Utils.TryUri(str);
- if (url == null)
+ if (url is null)
{
return null;
}
@@ -34,7 +34,7 @@ public class WireguardFmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
- if (item == null)
+ if (item is null)
{
return null;
}
diff --git a/v2rayN/ServiceLib/Handler/SubscriptionHandler.cs b/v2rayN/ServiceLib/Handler/SubscriptionHandler.cs
index 4edd6c72..8f5ab852 100644
--- a/v2rayN/ServiceLib/Handler/SubscriptionHandler.cs
+++ b/v2rayN/ServiceLib/Handler/SubscriptionHandler.cs
@@ -59,8 +59,8 @@ public static class SubscriptionHandler
private static bool IsValidSubscription(SubItem item, string subId)
{
- var id = item.Id.TrimEx();
- var url = item.Url.TrimEx();
+ var id = item.Id.TrimSafe();
+ var url = item.Url.TrimSafe();
if (id.IsNullOrEmpty() || url.IsNullOrEmpty())
{
@@ -72,7 +72,7 @@ public static class SubscriptionHandler
return false;
}
- if (!url.StartsWith(Global.HttpsProtocol) && !url.StartsWith(Global.HttpProtocol))
+ if (!url.StartsWith(AppConfig.HttpsProtocol) && !url.StartsWith(AppConfig.HttpProtocol))
{
return false;
}
@@ -109,7 +109,7 @@ public static class SubscriptionHandler
var result = await DownloadMainSubscription(config, item, blProxy, downloadHandle);
// Process additional subscription links (if any)
- if (item.ConvertTarget.IsNullOrEmpty() && item.MoreUrl.TrimEx().IsNotEmpty())
+ if (item.ConvertTarget.IsNullOrEmpty() && item.MoreUrl.TrimSafe().IsNotEmpty())
{
result = await DownloadAdditionalSubscriptions(item, result, blProxy, downloadHandle);
}
@@ -120,13 +120,13 @@ public static class SubscriptionHandler
private static async Task DownloadMainSubscription(Config config, SubItem item, bool blProxy, DownloadService downloadHandle)
{
// Prepare subscription URL and download directly
- var url = Utils.GetPunycode(item.Url.TrimEx());
+ var url = Utils.GetPunycode(item.Url.TrimSafe());
// If conversion is needed
if (item.ConvertTarget.IsNotEmpty())
{
var subConvertUrl = config.ConstItem.SubConvertUrl.IsNullOrEmpty()
- ? Global.SubConvertUrls.FirstOrDefault()
+ ? AppConfig.SubConvertUrls.FirstOrDefault()
: config.ConstItem.SubConvertUrl;
url = string.Format(subConvertUrl!, Utils.UrlEncode(url));
@@ -138,7 +138,7 @@ public static class SubscriptionHandler
if (!url.Contains("config="))
{
- url += string.Format("&config={0}", Global.SubConvertConfig.FirstOrDefault());
+ url += string.Format("&config={0}", AppConfig.SubConvertConfig.FirstOrDefault());
}
}
@@ -157,7 +157,7 @@ public static class SubscriptionHandler
}
// Process additional URL list
- var lstUrl = item.MoreUrl.TrimEx().Split(",") ?? [];
+ var lstUrl = item.MoreUrl.TrimSafe().Split(",") ?? [];
foreach (var it in lstUrl)
{
var url2 = Utils.GetPunycode(it);
diff --git a/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingLinux.cs b/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingLinux.cs
index 4929c72e..ea1a4563 100644
--- a/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingLinux.cs
+++ b/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingLinux.cs
@@ -2,7 +2,7 @@ namespace ServiceLib.Handler.SysProxy;
public static class ProxySettingLinux
{
- private static readonly string _proxySetFileName = $"{Global.ProxySetLinuxShellFileName.Replace(Global.NamespaceSample, "")}.sh";
+ private static readonly string _proxySetFileName = $"{AppConfig.ProxySetLinuxShellFileName.Replace(AppConfig.NamespaceSample, "")}.sh";
public static async Task SetProxy(string host, int port, string exceptions)
{
@@ -21,7 +21,7 @@ public static class ProxySettingLinux
var customSystemProxyScriptPath = AppManager.Instance.Config.SystemProxyItem?.CustomSystemProxyScriptPath;
var fileName = (customSystemProxyScriptPath.IsNotEmpty() && File.Exists(customSystemProxyScriptPath))
? customSystemProxyScriptPath
- : await FileUtils.CreateLinuxShellFile(_proxySetFileName, EmbedUtils.GetEmbedText(Global.ProxySetLinuxShellFileName), false);
+ : await FileUtils.CreateLinuxShellFile(_proxySetFileName, EmbedUtils.GetEmbedText(AppConfig.ProxySetLinuxShellFileName), false);
// TODO: temporarily notify which script is being used
NoticeManager.Instance.SendMessage(fileName);
diff --git a/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingOSX.cs b/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingOSX.cs
index 56fbe24d..e2a82d70 100644
--- a/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingOSX.cs
+++ b/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingOSX.cs
@@ -2,7 +2,7 @@ namespace ServiceLib.Handler.SysProxy;
public static class ProxySettingOSX
{
- private static readonly string _proxySetFileName = $"{Global.ProxySetOSXShellFileName.Replace(Global.NamespaceSample, "")}.sh";
+ private static readonly string _proxySetFileName = $"{AppConfig.ProxySetOSXShellFileName.Replace(AppConfig.NamespaceSample, "")}.sh";
public static async Task SetProxy(string host, int port, string exceptions)
{
@@ -26,7 +26,7 @@ public static class ProxySettingOSX
var customSystemProxyScriptPath = AppManager.Instance.Config.SystemProxyItem?.CustomSystemProxyScriptPath;
var fileName = (customSystemProxyScriptPath.IsNotEmpty() && File.Exists(customSystemProxyScriptPath))
? customSystemProxyScriptPath
- : await FileUtils.CreateLinuxShellFile(_proxySetFileName, EmbedUtils.GetEmbedText(Global.ProxySetOSXShellFileName), false);
+ : await FileUtils.CreateLinuxShellFile(_proxySetFileName, EmbedUtils.GetEmbedText(AppConfig.ProxySetOSXShellFileName), false);
// TODO: temporarily notify which script is being used
NoticeManager.Instance.SendMessage(fileName);
diff --git a/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingWindows.cs b/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingWindows.cs
index 8dc2f335..ca5403ca 100644
--- a/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingWindows.cs
+++ b/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingWindows.cs
@@ -2,7 +2,7 @@ using static ServiceLib.Handler.SysProxy.ProxySettingWindows.InternetConnectionO
namespace ServiceLib.Handler.SysProxy;
-public static class ProxySettingWindows
+public static partial class ProxySettingWindows
{
private const string _regPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
@@ -121,7 +121,7 @@ public static class ProxySettingWindows
// default stuff
list.dwSize = Marshal.SizeOf(list);
- if (connectionName != null)
+ if (connectionName is not null)
{
list.szConnection = Marshal.StringToHGlobalAuto(connectionName); // !! remember to deallocate memory 3
}
@@ -201,29 +201,29 @@ public static class ProxySettingWindows
///
/// A list of RAS connection names. May be empty list if no dial up connection.
/// Error message with win32 error code
- private static IEnumerable EnumerateRasEntries()
+ private static List EnumerateRasEntries()
{
var entries = 0;
// attempt to query with 1 entry buffer
var rasEntryNames = new RASENTRYNAME[1];
- var bufferSize = Marshal.SizeOf(typeof(RASENTRYNAME));
- rasEntryNames[0].dwSize = Marshal.SizeOf(typeof(RASENTRYNAME));
+ var bufferSize = Marshal.SizeOf();
+ rasEntryNames[0].dwSize = Marshal.SizeOf();
var result = NativeMethods.RasEnumEntries(null, null, rasEntryNames, ref bufferSize, ref entries);
// increase buffer if the buffer is not large enough
if (result == (uint)ErrorCode.ERROR_BUFFER_TOO_SMALL)
{
- rasEntryNames = new RASENTRYNAME[bufferSize / Marshal.SizeOf(typeof(RASENTRYNAME))];
+ rasEntryNames = new RASENTRYNAME[bufferSize / Marshal.SizeOf()];
for (var i = 0; i < rasEntryNames.Length; i++)
{
- rasEntryNames[i].dwSize = Marshal.SizeOf(typeof(RASENTRYNAME));
+ rasEntryNames[i].dwSize = Marshal.SizeOf();
}
result = NativeMethods.RasEnumEntries(null, null, rasEntryNames, ref bufferSize, ref entries);
}
if (result == 0)
{
- var entryNames = new List();
+ var entryNames = new List(entries);
for (var i = 0; i < entries; i++)
{
entryNames.Add(rasEntryNames[i].szEntryName);
@@ -231,7 +231,7 @@ public static class ProxySettingWindows
return entryNames;
}
- throw new ApplicationException($"RasEnumEntries failed with error code: {result}");
+ throw new Win32Exception((int)result);
}
#region WinInet structures
@@ -340,11 +340,11 @@ public static class ProxySettingWindows
#endregion WinInet enums
- internal static class NativeMethods
+ internal static partial class NativeMethods
{
- [DllImport("WinInet.dll", SetLastError = true, CharSet = CharSet.Auto)]
+ [LibraryImport("WinInet.dll", EntryPoint = "InternetSetOptionW", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool InternetSetOption(nint hInternet, InternetOption dwOption, nint lpBuffer, int dwBufferLength);
+ public static partial bool InternetSetOption(nint hInternet, InternetOption dwOption, nint lpBuffer, int dwBufferLength);
[DllImport("Rasapi32.dll", CharSet = CharSet.Auto)]
public static extern uint RasEnumEntries(
diff --git a/v2rayN/ServiceLib/Handler/SysProxy/SysProxyHandler.cs b/v2rayN/ServiceLib/Handler/SysProxy/SysProxyHandler.cs
index 21453591..dab49536 100644
--- a/v2rayN/ServiceLib/Handler/SysProxy/SysProxyHandler.cs
+++ b/v2rayN/ServiceLib/Handler/SysProxy/SysProxyHandler.cs
@@ -30,11 +30,11 @@ public static class SysProxyHandler
break;
}
case ESysProxyType.ForcedChange when Utils.IsLinux():
- await ProxySettingLinux.SetProxy(Global.Loopback, port, exceptions);
+ await ProxySettingLinux.SetProxy(AppConfig.Loopback, port, exceptions);
break;
case ESysProxyType.ForcedChange when Utils.IsMacOS():
- await ProxySettingOSX.SetProxy(Global.Loopback, port, exceptions);
+ await ProxySettingOSX.SetProxy(AppConfig.Loopback, port, exceptions);
break;
case ESysProxyType.ForcedClear when Utils.IsWindows():
@@ -74,15 +74,14 @@ public static class SysProxyHandler
strExceptions = $";{strExceptions}";
}
- strProxy = string.Empty;
if (config.SystemProxyItem.SystemProxyAdvancedProtocol.IsNullOrEmpty())
{
- strProxy = $"{Global.Loopback}:{port}";
+ strProxy = $"{AppConfig.Loopback}:{port}";
}
else
{
strProxy = config.SystemProxyItem.SystemProxyAdvancedProtocol
- .Replace("{ip}", Global.Loopback)
+ .Replace("{ip}", AppConfig.Loopback)
.Replace("{http_port}", port.ToString())
.Replace("{socks_port}", port.ToString());
}
@@ -92,7 +91,7 @@ public static class SysProxyHandler
{
var portPac = AppManager.Instance.GetLocalPort(EInboundProtocol.pac);
await PacManager.Instance.StartAsync(port, portPac);
- var strProxy = $"{Global.HttpProtocol}{Global.Loopback}:{portPac}/pac?t={DateTime.Now.Ticks}";
+ var strProxy = $"{AppConfig.HttpProtocol}{AppConfig.Loopback}:{portPac}/pac?t={DateTime.Now.Ticks}";
ProxySettingWindows.SetProxy(strProxy, "", 4);
}
}
diff --git a/v2rayN/ServiceLib/Helper/DownloaderHelper.cs b/v2rayN/ServiceLib/Helper/DownloaderHelper.cs
index 907d416f..96505ff6 100644
--- a/v2rayN/ServiceLib/Helper/DownloaderHelper.cs
+++ b/v2rayN/ServiceLib/Helper/DownloaderHelper.cs
@@ -2,12 +2,9 @@ using Downloader;
namespace ServiceLib.Helper;
-public class DownloaderHelper
+public static class DownloaderHelper
{
- private static readonly Lazy _instance = new(() => new());
- public static DownloaderHelper Instance => _instance.Value;
-
- public async Task DownloadStringAsync(IWebProxy? webProxy, string url, string? userAgent, int timeout)
+ public static async Task DownloadStringAsync(IWebProxy? webProxy, string url, string? userAgent, int timeout)
{
if (url.IsNullOrEmpty())
{
@@ -38,7 +35,7 @@ public class DownloaderHelper
await using var downloader = new Downloader.DownloadService(downloadOpt);
downloader.DownloadFileCompleted += (sender, value) =>
{
- if (value.Error != null)
+ if (value.Error is not null)
{
throw value.Error;
}
@@ -53,7 +50,7 @@ public class DownloaderHelper
return await reader.ReadToEndAsync(cts.Token);
}
- public async Task DownloadDataAsync4Speed(IWebProxy webProxy, string url, IProgress progress, int timeout)
+ public static async Task DownloadDataAsync4Speed(IWebProxy webProxy, string url, IProgress progress, int timeout)
{
if (url.IsNullOrEmpty())
{
@@ -78,14 +75,14 @@ public class DownloaderHelper
downloader.DownloadProgressChanged += (sender, value) =>
{
- if (progress != null && value.BytesPerSecondSpeed > 0)
+ if (progress is not null && value.BytesPerSecondSpeed > 0)
{
hasValue = true;
if (value.BytesPerSecondSpeed > maxSpeed)
{
maxSpeed = value.BytesPerSecondSpeed;
}
-
+
var ts = DateTime.Now - lastUpdateTime;
if (ts.TotalMilliseconds >= 1000)
{
@@ -97,14 +94,14 @@ public class DownloaderHelper
};
downloader.DownloadFileCompleted += (sender, value) =>
{
- if (progress != null)
+ if (progress is not null)
{
if (hasValue && maxSpeed > 0)
{
var finalSpeed = (maxSpeed / 1000 / 1000).ToString("#0.0");
progress.Report(finalSpeed);
}
- else if (value.Error != null)
+ else if (value.Error is not null)
{
progress.Report(value.Error?.Message);
}
@@ -122,7 +119,7 @@ public class DownloaderHelper
downloadOpt = null;
}
- public async Task DownloadFileAsync(IWebProxy? webProxy, string url, string fileName, IProgress progress, int timeout)
+ public static async Task DownloadFileAsync(IWebProxy? webProxy, string url, string fileName, IProgress progress, int timeout)
{
if (url.IsNullOrEmpty())
{
@@ -164,13 +161,13 @@ public class DownloaderHelper
};
downloader.DownloadFileCompleted += (sender, value) =>
{
- if (progress != null)
+ if (progress is not null)
{
- if (hasValue && value.Error == null)
+ if (hasValue && value.Error is null)
{
progress.Report(101);
}
- else if (value.Error != null)
+ else if (value.Error is not null)
{
throw value.Error;
}
diff --git a/v2rayN/ServiceLib/Manager/ActionPrecheckManager.cs b/v2rayN/ServiceLib/Manager/ActionPrecheckManager.cs
index 74e5f5ef..a1d01d49 100644
--- a/v2rayN/ServiceLib/Manager/ActionPrecheckManager.cs
+++ b/v2rayN/ServiceLib/Manager/ActionPrecheckManager.cs
@@ -107,12 +107,12 @@ public class ActionPrecheckManager
if (coreType == ECoreType.sing_box)
{
var transportError = ValidateSingboxTransport(item.ConfigType, net);
- if (transportError != null)
+ if (transportError is not null)
{
errors.Add(transportError);
}
- if (!Global.SingboxSupportConfigType.Contains(item.ConfigType))
+ if (!AppConfig.SingboxSupportConfigType.Contains(item.ConfigType))
{
errors.Add(string.Format(ResUI.CoreNotSupportProtocol,
nameof(ECoreType.sing_box), item.ConfigType.ToString()));
@@ -121,7 +121,7 @@ public class ActionPrecheckManager
else if (coreType is ECoreType.Xray)
{
// Xray core does not support these protocols
- if (!Global.XraySupportConfigType.Contains(item.ConfigType))
+ if (!AppConfig.XraySupportConfigType.Contains(item.ConfigType))
{
errors.Add(string.Format(ResUI.CoreNotSupportProtocol,
nameof(ECoreType.Xray), item.ConfigType.ToString()));
@@ -144,7 +144,7 @@ public class ActionPrecheckManager
errors.Add(string.Format(ResUI.InvalidProperty, "Id"));
}
- if (!Global.Flows.Contains(item.Flow))
+ if (!AppConfig.Flows.Contains(item.Flow))
{
errors.Add(string.Format(ResUI.InvalidProperty, "Flow"));
}
@@ -157,7 +157,7 @@ public class ActionPrecheckManager
errors.Add(string.Format(ResUI.InvalidProperty, "Id"));
}
- if (string.IsNullOrEmpty(item.Security) || !Global.SsSecuritiesInSingbox.Contains(item.Security))
+ if (string.IsNullOrEmpty(item.Security) || !AppConfig.SsSecuritiesInSingbox.Contains(item.Security))
{
errors.Add(string.Format(ResUI.InvalidProperty, "Security"));
}
@@ -165,7 +165,7 @@ public class ActionPrecheckManager
break;
}
- if (item.StreamSecurity == Global.StreamSecurity)
+ if (item.StreamSecurity == AppConfig.StreamSecurity)
{
// check certificate validity
if (!item.Cert.IsNullOrEmpty()
@@ -176,7 +176,7 @@ public class ActionPrecheckManager
}
}
- if (item.StreamSecurity == Global.StreamSecurityReality)
+ if (item.StreamSecurity == AppConfig.StreamSecurityReality)
{
if (item.PublicKey.IsNullOrEmpty())
{
@@ -330,7 +330,7 @@ public class ActionPrecheckManager
var coreType = AppManager.Instance.GetCoreType(item, item.ConfigType);
var routing = await ConfigHandler.GetDefaultRouting(AppManager.Instance.Config);
- if (routing == null)
+ if (routing is null)
{
return errors;
}
@@ -344,7 +344,7 @@ public class ActionPrecheckManager
}
var outboundTag = ruleItem.OutboundTag;
- if (outboundTag.IsNullOrEmpty() || Global.OutboundTags.Contains(outboundTag))
+ if (outboundTag.IsNullOrEmpty() || AppConfig.OutboundTags.Contains(outboundTag))
{
continue;
}
diff --git a/v2rayN/ServiceLib/Manager/AppManager.cs b/v2rayN/ServiceLib/Manager/AppManager.cs
index 6c20022a..0cfab30a 100644
--- a/v2rayN/ServiceLib/Manager/AppManager.cs
+++ b/v2rayN/ServiceLib/Manager/AppManager.cs
@@ -5,11 +5,10 @@ public sealed class AppManager
#region Property
private static readonly Lazy _instance = new(() => new());
- private Config _config;
private int? _statePort;
private int? _statePort2;
public static AppManager Instance => _instance.Value;
- public Config Config => _config;
+ public Config Config { get; private set; }
public int StatePort
{
@@ -25,7 +24,7 @@ public sealed class AppManager
get
{
_statePort2 ??= Utils.GetFreePort(GetLocalPort(EInboundProtocol.api2));
- return _statePort2.Value + (_config.TunModeItem.EnableTun ? 1 : 0);
+ return _statePort2.Value + (Config.TunModeItem.EnableTun ? 1 : 0);
}
}
@@ -56,17 +55,17 @@ public sealed class AppManager
{
if (Utils.HasWritePermission() == false)
{
- Environment.SetEnvironmentVariable(Global.LocalAppData, "1", EnvironmentVariableTarget.Process);
+ Environment.SetEnvironmentVariable(AppConfig.LocalAppData, "1", EnvironmentVariableTarget.Process);
}
Logging.Setup();
var config = ConfigHandler.LoadConfig();
- if (config == null)
+ if (config is null)
{
return false;
}
- _config = config;
- Thread.CurrentThread.CurrentUICulture = new(_config.UiItem.CurrentLanguage);
+ Config = config;
+ Thread.CurrentThread.CurrentUICulture = new(Config.UiItem.CurrentLanguage);
//Under Win10
if (Utils.IsWindows() && Environment.OSVersion.Version.Major < 10)
@@ -88,7 +87,7 @@ public sealed class AppManager
public bool InitComponents()
{
Logging.SaveLog($"v2rayN start up | {Utils.GetRuntimeInfo()}");
- Logging.LoggingEnabled(_config.GuiItem.EnableLog);
+ Logging.LoggingEnabled(Config.GuiItem.EnableLog);
//First determine the port value
_ = StatePort;
@@ -110,11 +109,11 @@ public sealed class AppManager
{
Logging.SaveLog("AppExitAsync Begin");
- await SysProxyHandler.UpdateSysProxy(_config, true);
+ await SysProxyHandler.UpdateSysProxy(Config, true);
AppEvents.AppExitRequested.Publish();
await Task.Delay(50); //Wait for AppExitRequested to be processed
- await ConfigHandler.SaveConfig(_config);
+ await ConfigHandler.SaveConfig(Config);
await ProfileExManager.Instance.SaveTo();
await StatisticsManager.Instance.SaveTo();
await CoreManager.Instance.CoreStop();
@@ -149,7 +148,7 @@ public sealed class AppManager
public int GetLocalPort(EInboundProtocol protocol)
{
- var localPort = _config.Inbound.FirstOrDefault(t => t.Protocol == nameof(EInboundProtocol.socks))?.LocalPort ?? 10808;
+ var localPort = Config.Inbound.FirstOrDefault(t => t.Protocol == nameof(EInboundProtocol.socks))?.LocalPort ?? 10808;
return localPort + (int)protocol;
}
@@ -274,25 +273,25 @@ public sealed class AppManager
switch (coreType)
{
case ECoreType.v2fly:
- return Global.SsSecurities;
+ return AppConfig.SsSecurities;
case ECoreType.Xray:
- return Global.SsSecuritiesInXray;
+ return AppConfig.SsSecuritiesInXray;
case ECoreType.sing_box:
- return Global.SsSecuritiesInSingbox;
+ return AppConfig.SsSecuritiesInSingbox;
}
- return Global.SsSecuritiesInSingbox;
+ return AppConfig.SsSecuritiesInSingbox;
}
public ECoreType GetCoreType(ProfileItem profileItem, EConfigType eConfigType)
{
- if (profileItem?.CoreType != null)
+ if (profileItem?.CoreType is not null)
{
return (ECoreType)profileItem.CoreType;
}
- var item = _config.CoreTypeItem?.FirstOrDefault(it => it.ConfigType == eConfigType);
+ var item = Config.CoreTypeItem?.FirstOrDefault(it => it.ConfigType == eConfigType);
return item?.CoreType ?? ECoreType.Xray;
}
diff --git a/v2rayN/ServiceLib/Manager/CertPemManager.cs b/v2rayN/ServiceLib/Manager/CertPemManager.cs
index dfefc746..79c12fce 100644
--- a/v2rayN/ServiceLib/Manager/CertPemManager.cs
+++ b/v2rayN/ServiceLib/Manager/CertPemManager.cs
@@ -225,7 +225,7 @@ public class CertPemManager
await ssl.AuthenticateAsClientAsync(sslOptions, cts.Token);
var remote = ssl.RemoteCertificate;
- if (remote == null)
+ if (remote is null)
{
return (null, null);
}
@@ -308,7 +308,7 @@ public class CertPemManager
X509Chain? chain,
SslPolicyErrors sslPolicyErrors)
{
- if (certificate == null)
+ if (certificate is null)
{
return false;
}
@@ -409,7 +409,7 @@ public class CertPemManager
/// Concatenated PEM certificates string
public static string ConcatenatePemChain(IEnumerable pemList)
{
- if (pemList == null)
+ if (pemList is null)
{
return string.Empty;
}
diff --git a/v2rayN/ServiceLib/Manager/ClashApiManager.cs b/v2rayN/ServiceLib/Manager/ClashApiManager.cs
index e34f838d..55f0eb6e 100644
--- a/v2rayN/ServiceLib/Manager/ClashApiManager.cs
+++ b/v2rayN/ServiceLib/Manager/ClashApiManager.cs
@@ -23,7 +23,7 @@ public sealed class ClashApiManager
var result2 = await HttpClientHelper.Instance.TryGetAsync(url2);
var clashProviders = JsonUtils.Deserialize(result2);
- if (clashProxies != null || clashProviders != null)
+ if (clashProxies is not null || clashProviders is not null)
{
_proxies = clashProxies?.proxies;
return new Tuple(clashProxies, clashProviders);
@@ -41,14 +41,14 @@ public sealed class ClashApiManager
{
if (blAll)
{
- if (_proxies == null)
+ if (_proxies is null)
{
await GetClashProxiesAsync();
}
lstProxy = new List();
foreach (var kv in _proxies ?? [])
{
- if (Global.notAllowTestType.Contains(kv.Value.type?.ToLower()))
+ if (AppConfig.notAllowTestType.Contains(kv.Value.type?.ToLower()))
{
continue;
}
@@ -70,7 +70,7 @@ public sealed class ClashApiManager
var tasks = new List();
foreach (var it in lstProxy)
{
- if (Global.notAllowTestType.Contains(it.Type.ToLower()))
+ if (AppConfig.notAllowTestType.Contains(it.Type.ToLower()))
{
continue;
}
@@ -123,7 +123,7 @@ public sealed class ClashApiManager
public async Task ClashConfigUpdate(Dictionary headers)
{
- if (_proxies == null)
+ if (_proxies is null)
{
return;
}
@@ -182,6 +182,6 @@ public sealed class ClashApiManager
private string GetApiUrl()
{
- return $"{Global.HttpProtocol}{Global.Loopback}:{AppManager.Instance.StatePort2}";
+ return $"{AppConfig.HttpProtocol}{AppConfig.Loopback}:{AppManager.Instance.StatePort2}";
}
}
diff --git a/v2rayN/ServiceLib/Manager/CoreAdminManager.cs b/v2rayN/ServiceLib/Manager/CoreAdminManager.cs
index 254688e4..fc1f7e53 100644
--- a/v2rayN/ServiceLib/Manager/CoreAdminManager.cs
+++ b/v2rayN/ServiceLib/Manager/CoreAdminManager.cs
@@ -14,7 +14,7 @@ public class CoreAdminManager
public async Task Init(Config config, Func updateFunc)
{
- if (_config != null)
+ if (_config is not null)
{
return;
}
@@ -67,14 +67,14 @@ public class CoreAdminManager
try
{
- var shellFileName = Utils.IsMacOS() ? Global.KillAsSudoOSXShellFileName : Global.KillAsSudoLinuxShellFileName;
+ var shellFileName = Utils.IsMacOS() ? AppConfig.KillAsSudoOSXShellFileName : AppConfig.KillAsSudoLinuxShellFileName;
var shFilePath = await FileUtils.CreateLinuxShellFile("kill_as_sudo.sh", EmbedUtils.GetEmbedText(shellFileName), true);
if (shFilePath.Contains(' '))
{
shFilePath = shFilePath.AppendQuotes();
}
var arg = new List() { "-c", $"sudo -S {shFilePath} {_linuxSudoPid}" };
- var result = await Cli.Wrap(Global.LinuxBash)
+ var result = await Cli.Wrap(AppConfig.LinuxBash)
.WithArguments(arg)
.WithStandardInputPipe(PipeSource.FromString(AppManager.Instance.LinuxSudoPwd))
.ExecuteBufferedAsync();
diff --git a/v2rayN/ServiceLib/Manager/CoreInfoManager.cs b/v2rayN/ServiceLib/Manager/CoreInfoManager.cs
index 2e11ccab..46f0e029 100644
--- a/v2rayN/ServiceLib/Manager/CoreInfoManager.cs
+++ b/v2rayN/ServiceLib/Manager/CoreInfoManager.cs
@@ -13,7 +13,7 @@ public sealed class CoreInfoManager
public CoreInfo? GetCoreInfo(ECoreType coreType)
{
- if (_coreInfo == null)
+ if (_coreInfo is null)
{
InitCoreInfo();
}
@@ -22,7 +22,7 @@ public sealed class CoreInfoManager
public List GetCoreInfo()
{
- if (_coreInfo == null)
+ if (_coreInfo is null)
{
InitCoreInfo();
}
@@ -63,7 +63,7 @@ public sealed class CoreInfoManager
{
CoreType = ECoreType.v2rayN,
Url = GetCoreUrl(ECoreType.v2rayN),
- ReleaseApiUrl = urlN.Replace(Global.GithubUrl, Global.GithubApiUrl),
+ ReleaseApiUrl = urlN.Replace(AppConfig.GithubUrl, AppConfig.GithubApiUrl),
DownloadUrlWin64 = urlN + "/download/{0}/v2rayN-windows-64.zip",
DownloadUrlWinArm64 = urlN + "/download/{0}/v2rayN-windows-arm64.zip",
DownloadUrlLinux64 = urlN + "/download/{0}/v2rayN-linux-64.zip",
@@ -82,7 +82,7 @@ public sealed class CoreInfoManager
VersionArg = "-version",
Environment = new Dictionary()
{
- { Global.V2RayLocalAsset, Utils.GetBinPath("") },
+ { AppConfig.V2RayLocalAsset, Utils.GetBinPath("") },
},
},
@@ -96,7 +96,7 @@ public sealed class CoreInfoManager
VersionArg = "version",
Environment = new Dictionary()
{
- { Global.V2RayLocalAsset, Utils.GetBinPath("") },
+ { AppConfig.V2RayLocalAsset, Utils.GetBinPath("") },
},
},
@@ -106,7 +106,7 @@ public sealed class CoreInfoManager
CoreExes = ["xray"],
Arguments = "run -c {0}",
Url = GetCoreUrl(ECoreType.Xray),
- ReleaseApiUrl = urlXray.Replace(Global.GithubUrl, Global.GithubApiUrl),
+ ReleaseApiUrl = urlXray.Replace(AppConfig.GithubUrl, AppConfig.GithubApiUrl),
DownloadUrlWin64 = urlXray + "/download/{0}/Xray-windows-64.zip",
DownloadUrlWinArm64 = urlXray + "/download/{0}/Xray-windows-arm64-v8a.zip",
DownloadUrlLinux64 = urlXray + "/download/{0}/Xray-linux-64.zip",
@@ -117,8 +117,8 @@ public sealed class CoreInfoManager
VersionArg = "-version",
Environment = new Dictionary()
{
- { Global.XrayLocalAsset, Utils.GetBinPath("") },
- { Global.XrayLocalCert, Utils.GetBinPath("") },
+ { AppConfig.XrayLocalAsset, Utils.GetBinPath("") },
+ { AppConfig.XrayLocalCert, Utils.GetBinPath("") },
},
},
@@ -128,7 +128,7 @@ public sealed class CoreInfoManager
CoreExes = GetMihomoCoreExes(),
Arguments = "-f {0}" + PortableMode(),
Url = GetCoreUrl(ECoreType.mihomo),
- ReleaseApiUrl = urlMihomo.Replace(Global.GithubUrl, Global.GithubApiUrl),
+ ReleaseApiUrl = urlMihomo.Replace(AppConfig.GithubUrl, AppConfig.GithubApiUrl),
DownloadUrlWin64 = urlMihomo + "/download/{0}/mihomo-windows-amd64-v1-{0}.zip",
DownloadUrlWinArm64 = urlMihomo + "/download/{0}/mihomo-windows-arm64-{0}.zip",
DownloadUrlLinux64 = urlMihomo + "/download/{0}/mihomo-linux-amd64-v1-{0}.gz",
@@ -170,7 +170,7 @@ public sealed class CoreInfoManager
Arguments = "run -c {0} --disable-color",
Url = GetCoreUrl(ECoreType.sing_box),
- ReleaseApiUrl = urlSingbox.Replace(Global.GithubUrl, Global.GithubApiUrl),
+ ReleaseApiUrl = urlSingbox.Replace(AppConfig.GithubUrl, AppConfig.GithubApiUrl),
DownloadUrlWin64 = urlSingbox + "/download/{0}/sing-box-{1}-windows-amd64.zip",
DownloadUrlWinArm64 = urlSingbox + "/download/{0}/sing-box-{1}-windows-arm64.zip",
DownloadUrlLinux64 = urlSingbox + "/download/{0}/sing-box-{1}-linux-amd64.tar.gz",
@@ -246,7 +246,7 @@ public sealed class CoreInfoManager
private static string GetCoreUrl(ECoreType eCoreType)
{
- return $"{Global.GithubUrl}/{Global.CoreUrls[eCoreType]}/releases";
+ return $"{AppConfig.GithubUrl}/{AppConfig.CoreUrls[eCoreType]}/releases";
}
private static List? GetMihomoCoreExes()
diff --git a/v2rayN/ServiceLib/Manager/CoreManager.cs b/v2rayN/ServiceLib/Manager/CoreManager.cs
index 79dbdeb0..0ce82159 100644
--- a/v2rayN/ServiceLib/Manager/CoreManager.cs
+++ b/v2rayN/ServiceLib/Manager/CoreManager.cs
@@ -11,7 +11,7 @@ public class CoreManager
private WindowsJobService? _processJob;
private ProcessService? _processService;
private ProcessService? _processPreService;
- private bool _linuxSudo = false;
+ private bool _linuxSudo;
private Func? _updateFunc;
private const string _tag = "CoreHandler";
@@ -21,7 +21,7 @@ public class CoreManager
_updateFunc = updateFunc;
//Copy the bin folder to the storage location (for init)
- if (Environment.GetEnvironmentVariable(Global.LocalAppData) == "1")
+ if (Environment.GetEnvironmentVariable(AppConfig.LocalAppData) == "1")
{
var fromPath = Utils.GetBaseDirectory("bin");
var toPath = Utils.GetBinPath("");
@@ -59,13 +59,13 @@ public class CoreManager
public async Task LoadCore(ProfileItem? node)
{
- if (node == null)
+ if (node is null)
{
await UpdateFunc(false, ResUI.CheckServerSettings);
return;
}
- var fileName = Utils.GetBinConfigPath(Global.CoreConfigFileName);
+ var fileName = Utils.GetBinConfigPath(AppConfig.CoreConfigFileName);
var result = await CoreConfigHandler.GenerateClientConfig(node, fileName);
if (result.Success != true)
{
@@ -87,7 +87,7 @@ public class CoreManager
await CoreStart(node);
await CoreStartPreService(node);
- if (_processService != null)
+ if (_processService is not null)
{
await UpdateFunc(true, $"{node.GetSummary()}");
}
@@ -95,8 +95,8 @@ public class CoreManager
public async Task LoadCoreConfigSpeedtest(List selecteds)
{
- var coreType = selecteds.Any(t => Global.SingboxOnlyConfigType.Contains(t.ConfigType)) ? ECoreType.sing_box : ECoreType.Xray;
- var fileName = string.Format(Global.CoreSpeedtestConfigFileName, Utils.GetGuid(false));
+ var coreType = selecteds.Any(t => AppConfig.SingboxOnlyConfigType.Contains(t.ConfigType)) ? ECoreType.sing_box : ECoreType.Xray;
+ var fileName = string.Format(AppConfig.CoreSpeedtestConfigFileName, Utils.GetGuid(false));
var configPath = Utils.GetBinConfigPath(fileName);
var result = await CoreConfigHandler.GenerateClientSpeedtestConfig(_config, configPath, selecteds, coreType);
await UpdateFunc(false, result.Msg);
@@ -120,7 +120,7 @@ public class CoreManager
return null;
}
- var fileName = string.Format(Global.CoreSpeedtestConfigFileName, Utils.GetGuid(false));
+ var fileName = string.Format(AppConfig.CoreSpeedtestConfigFileName, Utils.GetGuid(false));
var configPath = Utils.GetBinConfigPath(fileName);
var result = await CoreConfigHandler.GenerateClientSpeedtestConfig(_config, node, testItem, configPath);
if (result.Success != true)
@@ -143,14 +143,14 @@ public class CoreManager
_linuxSudo = false;
}
- if (_processService != null)
+ if (_processService is not null)
{
await _processService.StopAsync();
_processService.Dispose();
_processService = null;
}
- if (_processPreService != null)
+ if (_processPreService is not null)
{
await _processPreService.StopAsync();
_processPreService.Dispose();
@@ -171,7 +171,7 @@ public class CoreManager
var coreInfo = CoreInfoManager.Instance.GetCoreInfo(coreType);
var displayLog = node.ConfigType != EConfigType.Custom || node.DisplayLog;
- var proc = await RunProcess(coreInfo, Global.CoreConfigFileName, displayLog, true);
+ var proc = await RunProcess(coreInfo, AppConfig.CoreConfigFileName, displayLog, true);
if (proc is null)
{
return;
@@ -181,19 +181,19 @@ public class CoreManager
private async Task CoreStartPreService(ProfileItem node)
{
- if (_processService != null && !_processService.HasExited)
+ if (_processService is not null && !_processService.HasExited)
{
var coreType = AppManager.Instance.GetCoreType(node, node.ConfigType);
var itemSocks = await ConfigHandler.GetPreSocksItem(_config, node, coreType);
- if (itemSocks != null)
+ if (itemSocks is not null)
{
var preCoreType = itemSocks.CoreType ?? ECoreType.sing_box;
- var fileName = Utils.GetBinConfigPath(Global.CorePreConfigFileName);
+ var fileName = Utils.GetBinConfigPath(AppConfig.CorePreConfigFileName);
var result = await CoreConfigHandler.GenerateClientConfig(itemSocks, fileName);
if (result.Success)
{
var coreInfo = CoreInfoManager.Instance.GetCoreInfo(preCoreType);
- var proc = await RunProcess(coreInfo, Global.CorePreConfigFileName, true, true);
+ var proc = await RunProcess(coreInfo, AppConfig.CorePreConfigFileName, true, true);
if (proc is null)
{
return;
diff --git a/v2rayN/ServiceLib/Manager/PacManager.cs b/v2rayN/ServiceLib/Manager/PacManager.cs
index 92c0b5ba..09b5419c 100644
--- a/v2rayN/ServiceLib/Manager/PacManager.cs
+++ b/v2rayN/ServiceLib/Manager/PacManager.cs
@@ -40,7 +40,7 @@ public class PacManager
if (!File.Exists(fileName))
{
- var pac = EmbedUtils.GetEmbedText(Global.PacFileName);
+ var pac = EmbedUtils.GetEmbedText(AppConfig.PacFileName);
await File.AppendAllTextAsync(fileName, pac);
}
@@ -94,7 +94,7 @@ public class PacManager
public void Stop()
{
- if (_tcpListener == null)
+ if (_tcpListener is null)
{
return;
}
diff --git a/v2rayN/ServiceLib/Manager/ProfileExManager.cs b/v2rayN/ServiceLib/Manager/ProfileExManager.cs
index 739bd550..21b2fc83 100644
--- a/v2rayN/ServiceLib/Manager/ProfileExManager.cs
+++ b/v2rayN/ServiceLib/Manager/ProfileExManager.cs
@@ -161,7 +161,7 @@ public class ProfileExManager
public int GetSort(string indexId)
{
var profileEx = _lstProfileEx.FirstOrDefault(t => t.IndexId == indexId);
- if (profileEx == null)
+ if (profileEx is null)
{
return 0;
}
@@ -174,6 +174,6 @@ public class ProfileExManager
{
return 0;
}
- return _lstProfileEx.Max(t => t == null ? 0 : t.Sort);
+ return _lstProfileEx.Max(t => t is null ? 0 : t.Sort);
}
}
diff --git a/v2rayN/ServiceLib/Manager/ProfileGroupItemManager.cs b/v2rayN/ServiceLib/Manager/ProfileGroupItemManager.cs
index 041b1c78..5856fb40 100644
--- a/v2rayN/ServiceLib/Manager/ProfileGroupItemManager.cs
+++ b/v2rayN/ServiceLib/Manager/ProfileGroupItemManager.cs
@@ -148,7 +148,7 @@ public class ProfileGroupItemManager
try
{
var lst = await SQLiteHelper.Instance.TableAsync().Where(t => t.IndexId == item.IndexId).ToListAsync();
- if (lst != null && lst.Count > 0)
+ if (lst is not null && lst.Count > 0)
{
await SQLiteHelper.Instance.UpdateAllAsync(new List { item });
}
@@ -194,7 +194,7 @@ public class ProfileGroupItemManager
{
Instance.TryGet(indexId, out var groupItem);
- if (groupItem == null || groupItem.ChildItems.IsNullOrEmpty())
+ if (groupItem is null || groupItem.ChildItems.IsNullOrEmpty())
{
return false;
}
@@ -202,7 +202,7 @@ public class ProfileGroupItemManager
var childIds = Utils.String2List(groupItem.ChildItems)
.Where(p => !string.IsNullOrEmpty(p))
.ToList();
- if (childIds == null)
+ if (childIds is null)
{
return false;
}
@@ -226,7 +226,7 @@ public class ProfileGroupItemManager
public static async Task<(List Items, ProfileGroupItem? Group)> GetChildProfileItems(string? indexId)
{
Instance.TryGet(indexId, out var profileGroupItem);
- if (profileGroupItem == null || profileGroupItem.NotHasChild())
+ if (profileGroupItem is null || profileGroupItem.NotHasChild())
{
return (new List(), profileGroupItem);
}
@@ -240,7 +240,7 @@ public class ProfileGroupItemManager
public static async Task> GetChildProfileItems(ProfileGroupItem? group)
{
- if (group == null || group.ChildItems.IsNullOrEmpty())
+ if (group is null || group.ChildItems.IsNullOrEmpty())
{
return new();
}
@@ -250,7 +250,7 @@ public class ProfileGroupItemManager
.Select(AppManager.Instance.GetProfileItem)
))
.Where(p =>
- p != null &&
+ p is not null &&
p.IsValid() &&
p.ConfigType != EConfigType.Custom
)
@@ -260,14 +260,14 @@ public class ProfileGroupItemManager
public static async Task> GetSubChildProfileItems(ProfileGroupItem? group)
{
- if (group == null || group.SubChildItems.IsNullOrEmpty())
+ if (group is null || group.SubChildItems.IsNullOrEmpty())
{
return new();
}
var childProfiles = await AppManager.Instance.ProfileItems(group.SubChildItems);
return childProfiles.Where(p =>
- p != null &&
+ p is not null &&
p.IsValid() &&
!p.ConfigType.IsComplexType() &&
(group.Filter.IsNullOrEmpty() || Regex.IsMatch(p.Remarks, group.Filter))
@@ -279,7 +279,7 @@ public class ProfileGroupItemManager
{
// include grand children
var childAddresses = new HashSet();
- if (!Instance.TryGet(indexId, out var groupItem) || groupItem == null)
+ if (!Instance.TryGet(indexId, out var groupItem) || groupItem is null)
{
return childAddresses;
}
@@ -295,7 +295,7 @@ public class ProfileGroupItemManager
foreach (var childId in childIds)
{
var childNode = await AppManager.Instance.GetProfileItem(childId);
- if (childNode == null)
+ if (childNode is null)
{
continue;
}
@@ -321,7 +321,7 @@ public class ProfileGroupItemManager
{
// include grand children
var childAddresses = new HashSet();
- if (!Instance.TryGet(indexId, out var groupItem) || groupItem == null)
+ if (!Instance.TryGet(indexId, out var groupItem) || groupItem is null)
{
return childAddresses;
}
@@ -335,7 +335,7 @@ public class ProfileGroupItemManager
{
continue;
}
- if (childNode.StreamSecurity == Global.StreamSecurity
+ if (childNode.StreamSecurity == AppConfig.StreamSecurity
&& childNode.EchConfigList?.Contains("://") == true)
{
var idx = childNode.EchConfigList.IndexOf('+');
@@ -353,14 +353,14 @@ public class ProfileGroupItemManager
foreach (var childId in childIds)
{
var childNode = await AppManager.Instance.GetProfileItem(childId);
- if (childNode == null)
+ if (childNode is null)
{
continue;
}
if (!childNode.IsComplex() && !childNode.EchConfigList.IsNullOrEmpty())
{
- if (childNode.StreamSecurity == Global.StreamSecurity
+ if (childNode.StreamSecurity == AppConfig.StreamSecurity
&& childNode.EchConfigList?.Contains("://") == true)
{
var idx = childNode.EchConfigList.IndexOf('+');
diff --git a/v2rayN/ServiceLib/Manager/StatisticsManager.cs b/v2rayN/ServiceLib/Manager/StatisticsManager.cs
index 1e439a7f..477259c5 100644
--- a/v2rayN/ServiceLib/Manager/StatisticsManager.cs
+++ b/v2rayN/ServiceLib/Manager/StatisticsManager.cs
@@ -7,13 +7,12 @@ public class StatisticsManager
private Config _config;
private ServerStatItem? _serverStatItem;
- private List _lstServerStat;
private Func? _updateFunc;
private StatisticsXrayService? _statisticsXray;
private StatisticsSingboxService? _statisticsSingbox;
private static readonly string _tag = "StatisticsHandler";
- public List ServerStat => _lstServerStat;
+ public List ServerStat { get; private set; }
public async Task Init(Config config, Func updateFunc)
{
@@ -45,16 +44,16 @@ public class StatisticsManager
{
await SQLiteHelper.Instance.ExecuteAsync($"delete from ServerStatItem ");
_serverStatItem = null;
- _lstServerStat = new();
+ ServerStat = new();
}
public async Task SaveTo()
{
try
{
- if (_lstServerStat != null)
+ if (ServerStat is not null)
{
- await SQLiteHelper.Instance.UpdateAllAsync(_lstServerStat);
+ await SQLiteHelper.Instance.UpdateAllAsync(ServerStat);
}
}
catch (Exception ex)
@@ -65,7 +64,7 @@ public class StatisticsManager
public async Task CloneServerStatItem(string indexId, string toIndexId)
{
- if (_lstServerStat == null)
+ if (ServerStat is null)
{
return;
}
@@ -75,8 +74,8 @@ public class StatisticsManager
return;
}
- var stat = _lstServerStat.FirstOrDefault(t => t.IndexId == indexId);
- if (stat == null)
+ var stat = ServerStat.FirstOrDefault(t => t.IndexId == indexId);
+ if (stat is null)
{
return;
}
@@ -84,7 +83,7 @@ public class StatisticsManager
var toStat = JsonUtils.DeepCopy(stat);
toStat.IndexId = toIndexId;
await SQLiteHelper.Instance.ReplaceAsync(toStat);
- _lstServerStat.Add(toStat);
+ ServerStat.Add(toStat);
}
private async Task InitData()
@@ -94,7 +93,7 @@ public class StatisticsManager
var ticks = DateTime.Now.Date.Ticks;
await SQLiteHelper.Instance.ExecuteAsync($"update ServerStatItem set todayUp = 0,todayDown=0,dateNow={ticks} where dateNow<>{ticks}");
- _lstServerStat = await SQLiteHelper.Instance.TableAsync().ToListAsync();
+ ServerStat = await SQLiteHelper.Instance.TableAsync().ToListAsync();
}
private async Task UpdateServerStatHandler(ServerSpeedItem server)
@@ -129,15 +128,15 @@ public class StatisticsManager
private async Task GetServerStatItem(string indexId)
{
var ticks = DateTime.Now.Date.Ticks;
- if (_serverStatItem != null && _serverStatItem.IndexId != indexId)
+ if (_serverStatItem is not null && _serverStatItem.IndexId != indexId)
{
_serverStatItem = null;
}
- if (_serverStatItem == null)
+ if (_serverStatItem is null)
{
- _serverStatItem = _lstServerStat.FirstOrDefault(t => t.IndexId == indexId);
- if (_serverStatItem == null)
+ _serverStatItem = ServerStat.FirstOrDefault(t => t.IndexId == indexId);
+ if (_serverStatItem is null)
{
_serverStatItem = new ServerStatItem
{
@@ -149,7 +148,7 @@ public class StatisticsManager
DateNow = ticks
};
await SQLiteHelper.Instance.ReplaceAsync(_serverStatItem);
- _lstServerStat.Add(_serverStatItem);
+ ServerStat.Add(_serverStatItem);
}
}
diff --git a/v2rayN/ServiceLib/Manager/WebDavManager.cs b/v2rayN/ServiceLib/Manager/WebDavManager.cs
index 54c31a1b..c03c28b3 100644
--- a/v2rayN/ServiceLib/Manager/WebDavManager.cs
+++ b/v2rayN/ServiceLib/Manager/WebDavManager.cs
@@ -10,7 +10,7 @@ public sealed class WebDavManager
private readonly Config? _config;
private WebDavClient? _client;
private string? _lastDescription;
- private string _webDir = Global.AppName + "_backup";
+ private string _webDir = AppConfig.AppName + "_backup";
private readonly string _webFileName = "backup.zip";
private readonly string _tag = "WebDav--";
@@ -29,18 +29,18 @@ public sealed class WebDavManager
{
throw new ArgumentException("webdav parameter error or null");
}
- if (_client != null)
+ if (_client is not null)
{
_client?.Dispose();
_client = null;
}
if (_config.WebDavItem.DirName.IsNullOrEmpty())
{
- _webDir = Global.AppName + "_backup";
+ _webDir = AppConfig.AppName + "_backup";
}
else
{
- _webDir = _config.WebDavItem.DirName.TrimEx();
+ _webDir = _config.WebDavItem.DirName.TrimSafe();
}
// Ensure BaseAddress URL ends with a trailing slash
diff --git a/v2rayN/ServiceLib/Models/ConfigItems.cs b/v2rayN/ServiceLib/Models/ConfigItems.cs
index eeb88deb..61dc1308 100644
--- a/v2rayN/ServiceLib/Models/ConfigItems.cs
+++ b/v2rayN/ServiceLib/Models/ConfigItems.cs
@@ -72,7 +72,7 @@ public class GUIItem
public bool KeepOlderDedupl { get; set; }
public int AutoUpdateInterval { get; set; }
public int TrayMenuServersLimit { get; set; } = 20;
- public bool EnableHWA { get; set; } = false;
+ public bool EnableHWA { get; set; }
public bool EnableLog { get; set; } = true;
}
@@ -99,7 +99,7 @@ public class UIItem
public bool EnableDragDropSort { get; set; }
public bool DoubleClick2Activate { get; set; }
public bool AutoHideStartup { get; set; }
- public bool Hide2TrayWhenClose { get; set; }
+ public bool Hide2TrayWhenClose { get; set; }
public bool MacOSShowInDock { get; set; }
public List MainColumnItem { get; set; }
public List WindowSizeItem { get; set; }
diff --git a/v2rayN/ServiceLib/Models/ProfileItem.cs b/v2rayN/ServiceLib/Models/ProfileItem.cs
index b5424265..a04a19d6 100644
--- a/v2rayN/ServiceLib/Models/ProfileItem.cs
+++ b/v2rayN/ServiceLib/Models/ProfileItem.cs
@@ -28,10 +28,10 @@ public class ProfileItem : ReactiveObject
public string GetSummary()
{
- var summary = $"[{ConfigType.ToString()}] ";
+ var summary = $"[{ConfigType}] ";
if (IsComplex())
{
- summary += $"[{CoreType.ToString()}]{Remarks}";
+ summary += $"[{CoreType}]{Remarks}";
}
else
{
@@ -54,11 +54,11 @@ public class ProfileItem : ReactiveObject
public string GetNetwork()
{
- if (Network.IsNullOrEmpty() || !Global.Networks.Contains(Network))
+ if (Network.IsNullOrEmpty() || !AppConfig.Networks.Contains(Network))
{
- return Global.DefaultNetwork;
+ return AppConfig.DefaultNetwork;
}
- return Network.TrimEx();
+ return Network.TrimSafe();
}
public bool IsComplex()
@@ -94,7 +94,7 @@ public class ProfileItem : ReactiveObject
return false;
}
- if (!Global.Flows.Contains(Flow))
+ if (!AppConfig.Flows.Contains(Flow))
{
return false;
}
@@ -107,7 +107,7 @@ public class ProfileItem : ReactiveObject
return false;
}
- if (string.IsNullOrEmpty(Security) || !Global.SsSecuritiesInSingbox.Contains(Security))
+ if (string.IsNullOrEmpty(Security) || !AppConfig.SsSecuritiesInSingbox.Contains(Security))
{
return false;
}
@@ -116,7 +116,7 @@ public class ProfileItem : ReactiveObject
}
if ((ConfigType is EConfigType.VLESS or EConfigType.Trojan)
- && StreamSecurity == Global.StreamSecurityReality
+ && StreamSecurity == AppConfig.StreamSecurityReality
&& PublicKey.IsNullOrEmpty())
{
return false;
diff --git a/v2rayN/ServiceLib/Models/SemanticVersion.cs b/v2rayN/ServiceLib/Models/SemanticVersion.cs
index 78463434..eeebdebb 100644
--- a/v2rayN/ServiceLib/Models/SemanticVersion.cs
+++ b/v2rayN/ServiceLib/Models/SemanticVersion.cs
@@ -82,7 +82,7 @@ public class SemanticVersion
public string ToVersionString(string? prefix = null)
{
- if (prefix == null)
+ if (prefix is null)
{
return version;
}
diff --git a/v2rayN/ServiceLib/Models/V2rayConfig.cs b/v2rayN/ServiceLib/Models/V2rayConfig.cs
index d9575432..734a64eb 100644
--- a/v2rayN/ServiceLib/Models/V2rayConfig.cs
+++ b/v2rayN/ServiceLib/Models/V2rayConfig.cs
@@ -128,7 +128,7 @@ public class Outboundsettings4Ray
public string? secretKey { get; set; }
- public Object? address { get; set; }
+ public object? address { get; set; }
public int? port { get; set; }
public List? peers { get; set; }
diff --git a/v2rayN/ServiceLib/ServiceLib.csproj b/v2rayN/ServiceLib/ServiceLib.csproj
index 8cfbf8ca..40180a6e 100644
--- a/v2rayN/ServiceLib/ServiceLib.csproj
+++ b/v2rayN/ServiceLib/ServiceLib.csproj
@@ -2,6 +2,8 @@
Library
+ en-US
+ true
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigClashService.cs b/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigClashService.cs
index b9fcc126..b5831590 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigClashService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigClashService.cs
@@ -3,20 +3,15 @@ namespace ServiceLib.Services.CoreConfig;
///
/// Core configuration file processing class
///
-public class CoreConfigClashService
+public class CoreConfigClashService(Config config)
{
- private Config _config;
+ private readonly Config _config = config;
private static readonly string _tag = "CoreConfigClashService";
- public CoreConfigClashService(Config config)
- {
- _config = config;
- }
-
public async Task GenerateClientCustomConfig(ProfileItem node, string? fileName)
{
var ret = new RetResult();
- if (node == null || fileName is null)
+ if (node is null || fileName is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -26,7 +21,7 @@ public class CoreConfigClashService
try
{
- if (node == null)
+ if (node is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -66,7 +61,7 @@ public class CoreConfigClashService
}
var fileContent = YamlUtils.FromYaml>(txtFile);
- if (fileContent == null)
+ if (fileContent is null)
{
ret.Msg = ResUI.FailedConversionConfiguration;
return ret;
@@ -78,7 +73,7 @@ public class CoreConfigClashService
fileContent["log-level"] = GetLogLevel(_config.CoreBasicItem.Loglevel);
//external-controller
- fileContent["external-controller"] = $"{Global.Loopback}:{AppManager.Instance.StatePort2}";
+ fileContent["external-controller"] = $"{AppConfig.Loopback}:{AppManager.Instance.StatePort2}";
fileContent.Remove("secret");
//allow-lan
if (_config.Inbound.First().AllowLANConn)
@@ -110,11 +105,11 @@ public class CoreConfigClashService
//enable tun mode
if (_config.TunModeItem.EnableTun)
{
- var tun = EmbedUtils.GetEmbedText(Global.ClashTunYaml);
+ var tun = EmbedUtils.GetEmbedText(AppConfig.ClashTunYaml);
if (tun.IsNotEmpty())
{
var tunContent = YamlUtils.FromYaml>(tun);
- if (tunContent != null)
+ if (tunContent is not null)
{
fileContent["tun"] = tunContent["tun"];
}
@@ -161,17 +156,17 @@ public class CoreConfigClashService
return;
}
- var path = Utils.GetConfigPath(Global.ClashMixinConfigFileName);
+ var path = Utils.GetConfigPath(AppConfig.ClashMixinConfigFileName);
if (!File.Exists(path))
{
- var mixin = EmbedUtils.GetEmbedText(Global.ClashMixinYaml);
+ var mixin = EmbedUtils.GetEmbedText(AppConfig.ClashMixinYaml);
await File.AppendAllTextAsync(path, mixin);
}
- var txtFile = await File.ReadAllTextAsync(Utils.GetConfigPath(Global.ClashMixinConfigFileName));
+ var txtFile = await File.ReadAllTextAsync(Utils.GetConfigPath(AppConfig.ClashMixinConfigFileName));
var mixinContent = YamlUtils.FromYaml>(txtFile);
- if (mixinContent == null)
+ if (mixinContent is null)
{
return;
}
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/CoreConfigSingboxService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/CoreConfigSingboxService.cs
index 397e9340..8f70b883 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/CoreConfigSingboxService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/CoreConfigSingboxService.cs
@@ -12,7 +12,7 @@ public partial class CoreConfigSingboxService(Config config)
var ret = new RetResult();
try
{
- if (node == null
+ if (node is null
|| !node.IsValid())
{
ret.Msg = ResUI.CheckServerSettings;
@@ -38,7 +38,7 @@ public partial class CoreConfigSingboxService(Config config)
}
}
- var result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient);
+ var result = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleClient);
if (result.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
@@ -46,7 +46,7 @@ public partial class CoreConfigSingboxService(Config config)
}
var singboxConfig = JsonUtils.Deserialize(result);
- if (singboxConfig == null)
+ if (singboxConfig is null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
@@ -61,7 +61,7 @@ public partial class CoreConfigSingboxService(Config config)
singboxConfig.outbounds.RemoveAt(0);
var endpoints = new Endpoints4Sbox();
await GenEndpoint(node, endpoints);
- endpoints.tag = Global.ProxyTag;
+ endpoints.tag = AppConfig.ProxyTag;
singboxConfig.endpoints = new() { endpoints };
}
else
@@ -98,7 +98,7 @@ public partial class CoreConfigSingboxService(Config config)
var ret = new RetResult();
try
{
- if (_config == null)
+ if (_config is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -106,8 +106,8 @@ public partial class CoreConfigSingboxService(Config config)
ret.Msg = ResUI.InitialConfiguration;
- var result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient);
- var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound);
+ var result = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleClient);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
@@ -115,7 +115,7 @@ public partial class CoreConfigSingboxService(Config config)
}
var singboxConfig = JsonUtils.Deserialize(result);
- if (singboxConfig == null)
+ if (singboxConfig is null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
@@ -142,7 +142,7 @@ public partial class CoreConfigSingboxService(Config config)
foreach (var it in selecteds)
{
- if (!Global.SingboxSupportConfigType.Contains(it.ConfigType))
+ if (!AppConfig.SingboxSupportConfigType.Contains(it.ConfigType))
{
continue;
}
@@ -158,7 +158,7 @@ public partial class CoreConfigSingboxService(Config config)
//find unused port
var port = initPort;
- for (var k = initPort; k < Global.MaxPort; k++)
+ for (var k = initPort; k < AppConfig.MaxPort; k++)
{
if (lstIpEndPoints?.FindIndex(_it => _it.Port == k) >= 0)
{
@@ -185,7 +185,7 @@ public partial class CoreConfigSingboxService(Config config)
//inbound
Inbound4Sbox inbound = new()
{
- listen = Global.Loopback,
+ listen = AppConfig.Loopback,
listen_port = port,
type = EInboundProtocol.mixed.ToString(),
};
@@ -199,7 +199,7 @@ public partial class CoreConfigSingboxService(Config config)
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
}
- var tag = Global.ProxyTag + inbound.listen_port.ToString();
+ var tag = AppConfig.ProxyTag + inbound.listen_port.ToString();
server.tag = tag;
if (server is Endpoints4Sbox endpoint)
{
@@ -221,7 +221,7 @@ public partial class CoreConfigSingboxService(Config config)
}
var rawDNSItem = await AppManager.Instance.GetDNSItem(ECoreType.sing_box);
- if (rawDNSItem != null && rawDNSItem.Enabled == true)
+ if (rawDNSItem is not null && rawDNSItem.Enabled == true)
{
await GenDnsDomainsCompatible(singboxConfig, rawDNSItem);
}
@@ -231,7 +231,7 @@ public partial class CoreConfigSingboxService(Config config)
}
singboxConfig.route.default_domain_resolver = new()
{
- server = Global.SingboxLocalDNSTag,
+ server = AppConfig.SingboxLocalDNSTag,
};
ret.Success = true;
@@ -251,7 +251,7 @@ public partial class CoreConfigSingboxService(Config config)
var ret = new RetResult();
try
{
- if (node == null
+ if (node is null
|| !node.IsValid())
{
ret.Msg = ResUI.CheckServerSettings;
@@ -265,7 +265,7 @@ public partial class CoreConfigSingboxService(Config config)
ret.Msg = ResUI.InitialConfiguration;
- var result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient);
+ var result = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleClient);
if (result.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
@@ -273,7 +273,7 @@ public partial class CoreConfigSingboxService(Config config)
}
var singboxConfig = JsonUtils.Deserialize(result);
- if (singboxConfig == null)
+ if (singboxConfig is null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
@@ -285,7 +285,7 @@ public partial class CoreConfigSingboxService(Config config)
singboxConfig.outbounds.RemoveAt(0);
var endpoints = new Endpoints4Sbox();
await GenEndpoint(node, endpoints);
- endpoints.tag = Global.ProxyTag;
+ endpoints.tag = AppConfig.ProxyTag;
singboxConfig.endpoints = new() { endpoints };
}
else
@@ -294,7 +294,7 @@ public partial class CoreConfigSingboxService(Config config)
}
await GenMoreOutbounds(node, singboxConfig);
var item = await AppManager.Instance.GetDNSItem(ECoreType.sing_box);
- if (item != null && item.Enabled == true)
+ if (item is not null && item.Enabled == true)
{
await GenDnsDomainsCompatible(singboxConfig, item);
}
@@ -304,7 +304,7 @@ public partial class CoreConfigSingboxService(Config config)
}
singboxConfig.route.default_domain_resolver = new()
{
- server = Global.SingboxLocalDNSTag,
+ server = AppConfig.SingboxLocalDNSTag,
};
singboxConfig.route.rules.Clear();
@@ -312,7 +312,7 @@ public partial class CoreConfigSingboxService(Config config)
singboxConfig.inbounds.Add(new()
{
tag = $"{EInboundProtocol.mixed}{port}",
- listen = Global.Loopback,
+ listen = AppConfig.Loopback,
listen_port = port,
type = EInboundProtocol.mixed.ToString(),
});
@@ -335,7 +335,7 @@ public partial class CoreConfigSingboxService(Config config)
var ret = new RetResult();
try
{
- if (_config == null)
+ if (_config is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -343,8 +343,8 @@ public partial class CoreConfigSingboxService(Config config)
ret.Msg = ResUI.InitialConfiguration;
- var result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient);
- var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound);
+ var result = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleClient);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
@@ -352,7 +352,7 @@ public partial class CoreConfigSingboxService(Config config)
}
var singboxConfig = JsonUtils.Deserialize(result);
- if (singboxConfig == null)
+ if (singboxConfig is null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
@@ -392,7 +392,7 @@ public partial class CoreConfigSingboxService(Config config)
var ret = new RetResult();
try
{
- if (_config == null)
+ if (_config is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -400,8 +400,8 @@ public partial class CoreConfigSingboxService(Config config)
ret.Msg = ResUI.InitialConfiguration;
- var result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient);
- var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound);
+ var result = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleClient);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
@@ -409,7 +409,7 @@ public partial class CoreConfigSingboxService(Config config)
}
var singboxConfig = JsonUtils.Deserialize(result);
- if (singboxConfig == null)
+ if (singboxConfig is null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
@@ -447,7 +447,7 @@ public partial class CoreConfigSingboxService(Config config)
public async Task GenerateClientCustomConfig(ProfileItem node, string? fileName)
{
var ret = new RetResult();
- if (node == null || fileName is null)
+ if (node is null || fileName is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -457,7 +457,7 @@ public partial class CoreConfigSingboxService(Config config)
try
{
- if (node == null)
+ if (node is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -484,11 +484,11 @@ public partial class CoreConfigSingboxService(Config config)
return ret;
}
- if (node.Address == Global.CoreMultipleLoadConfigFileName)
+ if (node.Address == AppConfig.CoreMultipleLoadConfigFileName)
{
var txtFile = File.ReadAllText(addressFileName);
var singboxConfig = JsonUtils.Deserialize(txtFile);
- if (singboxConfig == null)
+ if (singboxConfig is null)
{
File.Copy(addressFileName, fileName);
}
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxConfigTemplateService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxConfigTemplateService.cs
index 6fe9b35a..3030fcc2 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxConfigTemplateService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxConfigTemplateService.cs
@@ -5,7 +5,7 @@ public partial class CoreConfigSingboxService
private async Task ApplyFullConfigTemplate(SingboxConfig singboxConfig)
{
var fullConfigTemplate = await AppManager.Instance.GetFullConfigTemplateItem(ECoreType.sing_box);
- if (fullConfigTemplate == null || !fullConfigTemplate.Enabled)
+ if (fullConfigTemplate is null || !fullConfigTemplate.Enabled)
{
return JsonUtils.Serialize(singboxConfig);
}
@@ -17,7 +17,7 @@ public partial class CoreConfigSingboxService
}
var fullConfigTemplateNode = JsonNode.Parse(fullConfigTemplateItem);
- if (fullConfigTemplateNode == null)
+ if (fullConfigTemplateNode is null)
{
return JsonUtils.Serialize(singboxConfig);
}
@@ -42,7 +42,7 @@ public partial class CoreConfigSingboxService
fullConfigTemplateNode["outbounds"] = customOutboundsNode;
// Process endpoints
- if (singboxConfig.endpoints != null && singboxConfig.endpoints.Count > 0)
+ if (singboxConfig.endpoints is not null && singboxConfig.endpoints.Count > 0)
{
var customEndpointsNode = fullConfigTemplateNode["endpoints"] is JsonArray endpoints ? endpoints : new JsonArray();
foreach (var endpoint in singboxConfig.endpoints)
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxDnsService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxDnsService.cs
index fa089140..b02428e4 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxDnsService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxDnsService.cs
@@ -7,7 +7,7 @@ public partial class CoreConfigSingboxService
try
{
var item = await AppManager.Instance.GetDNSItem(ECoreType.sing_box);
- if (item != null && item.Enabled == true)
+ if (item is not null && item.Enabled == true)
{
return await GenDnsCompatible(node, singboxConfig);
}
@@ -22,22 +22,22 @@ public partial class CoreConfigSingboxService
// final dns
var routing = await ConfigHandler.GetDefaultRouting(_config);
var useDirectDns = false;
- if (routing != null)
+ if (routing is not null)
{
var rules = JsonUtils.Deserialize>(routing.RuleSet) ?? [];
useDirectDns = rules?.LastOrDefault() is { } lastRule &&
- lastRule.OutboundTag == Global.DirectTag &&
+ lastRule.OutboundTag == AppConfig.DirectTag &&
(lastRule.Port == "0-65535" ||
lastRule.Network == "tcp,udp" ||
lastRule.Ip?.Contains("0.0.0.0/0") == true);
}
- singboxConfig.dns.final = useDirectDns ? Global.SingboxDirectDNSTag : Global.SingboxRemoteDNSTag;
+ singboxConfig.dns.final = useDirectDns ? AppConfig.SingboxDirectDNSTag : AppConfig.SingboxRemoteDNSTag;
if ((!useDirectDns) && simpleDNSItem.FakeIP == true && simpleDNSItem.GlobalFakeIp == false)
{
singboxConfig.dns.rules.Add(new()
{
- server = Global.SingboxFakeDNSTag,
+ server = AppConfig.SingboxFakeDNSTag,
query_type = new List { 1, 28 }, // A and AAAA
rewrite_ttl = 1,
});
@@ -57,29 +57,29 @@ public partial class CoreConfigSingboxService
var finalDns = await GenDnsDomains(singboxConfig, simpleDNSItem);
var directDns = ParseDnsAddress(simpleDNSItem.DirectDNS);
- directDns.tag = Global.SingboxDirectDNSTag;
- directDns.domain_resolver = Global.SingboxLocalDNSTag;
+ directDns.tag = AppConfig.SingboxDirectDNSTag;
+ directDns.domain_resolver = AppConfig.SingboxLocalDNSTag;
var remoteDns = ParseDnsAddress(simpleDNSItem.RemoteDNS);
- remoteDns.tag = Global.SingboxRemoteDNSTag;
- remoteDns.detour = Global.ProxyTag;
- remoteDns.domain_resolver = Global.SingboxLocalDNSTag;
+ remoteDns.tag = AppConfig.SingboxRemoteDNSTag;
+ remoteDns.detour = AppConfig.ProxyTag;
+ remoteDns.domain_resolver = AppConfig.SingboxLocalDNSTag;
var hostsDns = new Server4Sbox
{
- tag = Global.SingboxHostsDNSTag,
+ tag = AppConfig.SingboxHostsDNSTag,
type = "hosts",
predefined = new(),
};
if (simpleDNSItem.AddCommonHosts == true)
{
- hostsDns.predefined = Global.PredefinedHosts;
+ hostsDns.predefined = AppConfig.PredefinedHosts;
}
if (simpleDNSItem.UseSystemHosts == true)
{
var systemHosts = Utils.GetSystemHosts();
- if (systemHosts != null && systemHosts.Count > 0)
+ if (systemHosts is not null && systemHosts.Count > 0)
{
foreach (var host in systemHosts)
{
@@ -102,15 +102,15 @@ public partial class CoreConfigSingboxService
{
if (finalDns.server == host.Key)
{
- finalDns.domain_resolver = Global.SingboxHostsDNSTag;
+ finalDns.domain_resolver = AppConfig.SingboxHostsDNSTag;
}
if (remoteDns.server == host.Key)
{
- remoteDns.domain_resolver = Global.SingboxHostsDNSTag;
+ remoteDns.domain_resolver = AppConfig.SingboxHostsDNSTag;
}
if (directDns.server == host.Key)
{
- directDns.domain_resolver = Global.SingboxHostsDNSTag;
+ directDns.domain_resolver = AppConfig.SingboxHostsDNSTag;
}
}
@@ -125,7 +125,7 @@ public partial class CoreConfigSingboxService
{
var fakeip = new Server4Sbox
{
- tag = Global.SingboxFakeDNSTag,
+ tag = AppConfig.SingboxFakeDNSTag,
type = "fakeip",
inet4_range = "198.18.0.0/15",
inet6_range = "fc00::/18",
@@ -137,22 +137,22 @@ public partial class CoreConfigSingboxService
var (_, dnsServer) = ParseEchParam(node?.EchConfigList);
if (dnsServer is not null)
{
- dnsServer.tag = Global.SingboxEchDNSTag;
+ dnsServer.tag = AppConfig.SingboxEchDNSTag;
if (dnsServer.server is not null
&& hostsDns.predefined.ContainsKey(dnsServer.server))
{
- dnsServer.domain_resolver = Global.SingboxHostsDNSTag;
+ dnsServer.domain_resolver = AppConfig.SingboxHostsDNSTag;
}
else
{
- dnsServer.domain_resolver = Global.SingboxLocalDNSTag;
+ dnsServer.domain_resolver = AppConfig.SingboxLocalDNSTag;
}
singboxConfig.dns.servers.Add(dnsServer);
}
else if (node?.ConfigType.IsGroupType() == true)
{
var echDnsObject = JsonUtils.DeepCopy(directDns);
- echDnsObject.tag = Global.SingboxEchDNSTag;
+ echDnsObject.tag = AppConfig.SingboxEchDNSTag;
singboxConfig.dns.servers.Add(echDnsObject);
}
@@ -162,7 +162,7 @@ public partial class CoreConfigSingboxService
private async Task GenDnsDomains(SingboxConfig singboxConfig, SimpleDNSItem? simpleDNSItem)
{
var finalDns = ParseDnsAddress(simpleDNSItem.BootstrapDNS);
- finalDns.tag = Global.SingboxLocalDNSTag;
+ finalDns.tag = AppConfig.SingboxLocalDNSTag;
singboxConfig.dns ??= new Dns4Sbox();
singboxConfig.dns.servers ??= new List();
singboxConfig.dns.servers.Add(finalDns);
@@ -176,16 +176,16 @@ public partial class CoreConfigSingboxService
singboxConfig.dns.rules.AddRange(new[]
{
- new Rule4Sbox { ip_accept_any = true, server = Global.SingboxHostsDNSTag },
+ new Rule4Sbox { ip_accept_any = true, server = AppConfig.SingboxHostsDNSTag },
new Rule4Sbox
{
- server = Global.SingboxRemoteDNSTag,
+ server = AppConfig.SingboxRemoteDNSTag,
strategy = simpleDNSItem.SingboxStrategy4Proxy.NullIfEmpty(),
clash_mode = ERuleMode.Global.ToString()
},
new Rule4Sbox
{
- server = Global.SingboxDirectDNSTag,
+ server = AppConfig.SingboxDirectDNSTag,
strategy = simpleDNSItem.SingboxStrategy4Direct.NullIfEmpty(),
clash_mode = ERuleMode.Direct.ToString()
}
@@ -198,7 +198,7 @@ public partial class CoreConfigSingboxService
singboxConfig.dns.rules.Add(new()
{
query_type = new List { 64, 65 },
- server = Global.SingboxEchDNSTag,
+ server = AppConfig.SingboxEchDNSTag,
domain = echDomain is not null ? new List { echDomain } : null,
});
}
@@ -210,7 +210,7 @@ public partial class CoreConfigSingboxService
singboxConfig.dns.rules.Add(new()
{
query_type = new List { 64, 65 },
- server = Global.SingboxEchDNSTag,
+ server = AppConfig.SingboxEchDNSTag,
domain = queryServerNames,
});
}
@@ -228,11 +228,11 @@ public partial class CoreConfigSingboxService
if (simpleDNSItem.FakeIP == true && simpleDNSItem.GlobalFakeIp == true)
{
- var fakeipFilterRule = JsonUtils.Deserialize(EmbedUtils.GetEmbedText(Global.SingboxFakeIPFilterFileName));
+ var fakeipFilterRule = JsonUtils.Deserialize(EmbedUtils.GetEmbedText(AppConfig.SingboxFakeIPFilterFileName));
fakeipFilterRule.invert = true;
var rule4Fake = new Rule4Sbox
{
- server = Global.SingboxFakeDNSTag,
+ server = AppConfig.SingboxFakeDNSTag,
type = "logical",
mode = "and",
rewrite_ttl = 1,
@@ -249,7 +249,7 @@ public partial class CoreConfigSingboxService
}
var routing = await ConfigHandler.GetDefaultRouting(_config);
- if (routing == null)
+ if (routing is null)
{
return 0;
}
@@ -306,9 +306,9 @@ public partial class CoreConfigSingboxService
continue;
}
- if (item.OutboundTag == Global.DirectTag)
+ if (item.OutboundTag == AppConfig.DirectTag)
{
- rule.server = Global.SingboxDirectDNSTag;
+ rule.server = AppConfig.SingboxDirectDNSTag;
rule.strategy = string.IsNullOrEmpty(simpleDNSItem.SingboxStrategy4Direct) ? null : simpleDNSItem.SingboxStrategy4Direct;
if (expectedIPsRegions.Count > 0 && rule.geosite?.Count > 0)
@@ -327,7 +327,7 @@ public partial class CoreConfigSingboxService
}
}
}
- else if (item.OutboundTag == Global.BlockTag)
+ else if (item.OutboundTag == AppConfig.BlockTag)
{
rule.action = "predefined";
rule.rcode = "NXDOMAIN";
@@ -337,12 +337,12 @@ public partial class CoreConfigSingboxService
if (simpleDNSItem.FakeIP == true && simpleDNSItem.GlobalFakeIp == false)
{
var rule4Fake = JsonUtils.DeepCopy(rule);
- rule4Fake.server = Global.SingboxFakeDNSTag;
+ rule4Fake.server = AppConfig.SingboxFakeDNSTag;
rule4Fake.query_type = new List { 1, 28 }; // A and AAAA
rule4Fake.rewrite_ttl = 1;
singboxConfig.dns.rules.Add(rule4Fake);
}
- rule.server = Global.SingboxRemoteDNSTag;
+ rule.server = AppConfig.SingboxRemoteDNSTag;
rule.strategy = string.IsNullOrEmpty(simpleDNSItem.SingboxStrategy4Proxy) ? null : simpleDNSItem.SingboxStrategy4Proxy;
}
@@ -360,11 +360,11 @@ public partial class CoreConfigSingboxService
var strDNS = string.Empty;
if (_config.TunModeItem.EnableTun)
{
- strDNS = string.IsNullOrEmpty(item?.TunDNS) ? EmbedUtils.GetEmbedText(Global.TunSingboxDNSFileName) : item?.TunDNS;
+ strDNS = string.IsNullOrEmpty(item?.TunDNS) ? EmbedUtils.GetEmbedText(AppConfig.TunSingboxDNSFileName) : item?.TunDNS;
}
else
{
- strDNS = string.IsNullOrEmpty(item?.NormalDNS) ? EmbedUtils.GetEmbedText(Global.DNSSingboxNormalFileName) : item?.NormalDNS;
+ strDNS = string.IsNullOrEmpty(item?.NormalDNS) ? EmbedUtils.GetEmbedText(AppConfig.DNSSingboxNormalFileName) : item?.NormalDNS;
}
var dns4Sbox = JsonUtils.Deserialize(strDNS);
@@ -374,7 +374,7 @@ public partial class CoreConfigSingboxService
}
singboxConfig.dns = dns4Sbox;
- if (dns4Sbox.servers != null && dns4Sbox.servers.Count > 0 && dns4Sbox.servers.First().address.IsNullOrEmpty())
+ if (dns4Sbox.servers is not null && dns4Sbox.servers.Count > 0 && dns4Sbox.servers.First().address.IsNullOrEmpty())
{
await GenDnsDomainsCompatible(singboxConfig, item);
}
@@ -398,9 +398,9 @@ public partial class CoreConfigSingboxService
dns4Sbox.servers ??= [];
dns4Sbox.rules ??= [];
- var tag = Global.SingboxLocalDNSTag;
+ var tag = AppConfig.SingboxLocalDNSTag;
- var finalDnsAddress = string.IsNullOrEmpty(dnsItem?.DomainDNSAddress) ? Global.DomainPureIPDNSAddress.FirstOrDefault() : dnsItem?.DomainDNSAddress;
+ var finalDnsAddress = string.IsNullOrEmpty(dnsItem?.DomainDNSAddress) ? AppConfig.DomainPureIPDNSAddress.FirstOrDefault() : dnsItem?.DomainDNSAddress;
var localDnsServer = ParseDnsAddress(finalDnsAddress);
localDnsServer.tag = tag;
@@ -417,12 +417,12 @@ public partial class CoreConfigSingboxService
dns4Sbox.servers ??= [];
dns4Sbox.rules ??= [];
- var tag = Global.SingboxLocalDNSTag;
+ var tag = AppConfig.SingboxLocalDNSTag;
dns4Sbox.servers.Add(new()
{
tag = tag,
- address = string.IsNullOrEmpty(dnsItem?.DomainDNSAddress) ? Global.DomainPureIPDNSAddress.FirstOrDefault() : dnsItem?.DomainDNSAddress,
- detour = Global.DirectTag,
+ address = string.IsNullOrEmpty(dnsItem?.DomainDNSAddress) ? AppConfig.DomainPureIPDNSAddress.FirstOrDefault() : dnsItem?.DomainDNSAddress,
+ detour = AppConfig.DirectTag,
strategy = string.IsNullOrEmpty(dnsItem?.DomainStrategy4Freedom) ? null : dnsItem?.DomainStrategy4Freedom,
});
dns4Sbox.rules.Insert(0, new()
@@ -432,7 +432,7 @@ public partial class CoreConfigSingboxService
});
dns4Sbox.rules.Insert(0, new()
{
- server = dns4Sbox.servers.Where(t => t.detour == Global.ProxyTag).Select(t => t.tag).FirstOrDefault() ?? "remote",
+ server = dns4Sbox.servers.Where(t => t.detour == AppConfig.ProxyTag).Select(t => t.tag).FirstOrDefault() ?? "remote",
clash_mode = ERuleMode.Global.ToString()
});
@@ -441,7 +441,7 @@ public partial class CoreConfigSingboxService
.Select(t => t.server)
.Distinct()
.ToList();
- if (lstDomain != null && lstDomain.Count > 0)
+ if (lstDomain is not null && lstDomain.Count > 0)
{
dns4Sbox.rules.Insert(0, new()
{
@@ -456,7 +456,7 @@ public partial class CoreConfigSingboxService
private async Task GenOutboundDnsRule(ProfileItem? node, SingboxConfig singboxConfig)
{
- if (node == null)
+ if (node is null)
{
return 0;
}
@@ -466,7 +466,7 @@ public partial class CoreConfigSingboxService
{
domain.Add(node.Address);
}
- if (node.Address == Global.Loopback && node.SpiderX.IsNotEmpty()) // Tun2SocksAddress
+ if (node.Address == AppConfig.Loopback && node.SpiderX.IsNotEmpty()) // Tun2SocksAddress
{
domain.AddRange(Utils.String2List(node.SpiderX)
.Where(Utils.IsDomain)
@@ -481,7 +481,7 @@ public partial class CoreConfigSingboxService
singboxConfig.dns.rules ??= new List();
singboxConfig.dns.rules.Insert(0, new Rule4Sbox
{
- server = Global.SingboxLocalDNSTag,
+ server = AppConfig.SingboxLocalDNSTag,
domain = domain,
});
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxInboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxInboundService.cs
index 4e14c688..c75d3fe1 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxInboundService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxInboundService.cs
@@ -16,7 +16,7 @@ public partial class CoreConfigSingboxService
{
type = EInboundProtocol.mixed.ToString(),
tag = EInboundProtocol.socks.ToString(),
- listen = Global.Loopback,
+ listen = AppConfig.Loopback,
};
singboxConfig.inbounds.Add(inbound);
@@ -53,14 +53,14 @@ public partial class CoreConfigSingboxService
{
if (_config.TunModeItem.Mtu <= 0)
{
- _config.TunModeItem.Mtu = Global.TunMtus.First();
+ _config.TunModeItem.Mtu = AppConfig.TunMtus.First();
}
if (_config.TunModeItem.Stack.IsNullOrEmpty())
{
- _config.TunModeItem.Stack = Global.TunStacks.First();
+ _config.TunModeItem.Stack = AppConfig.TunStacks.First();
}
- var tunInbound = JsonUtils.Deserialize(EmbedUtils.GetEmbedText(Global.TunSingboxInboundFileName)) ?? new Inbound4Sbox { };
+ var tunInbound = JsonUtils.Deserialize(EmbedUtils.GetEmbedText(AppConfig.TunSingboxInboundFileName)) ?? new Inbound4Sbox { };
tunInbound.interface_name = Utils.IsMacOS() ? $"utun{new Random().Next(99)}" : "singbox_tun";
tunInbound.mtu = _config.TunModeItem.Mtu;
tunInbound.auto_route = _config.TunModeItem.AutoRoute;
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxLogService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxLogService.cs
index 59e65471..8f79ab7c 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxLogService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxLogService.cs
@@ -21,7 +21,7 @@ public partial class CoreConfigSingboxService
default:
break;
}
- if (_config.CoreBasicItem.Loglevel == Global.None)
+ if (_config.CoreBasicItem.Loglevel == AppConfig.None)
{
singboxConfig.log.disabled = true;
}
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxOutboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxOutboundService.cs
index e2c0d502..3a2608b1 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxOutboundService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxOutboundService.cs
@@ -8,7 +8,7 @@ public partial class CoreConfigSingboxService
{
outbound.server = node.Address;
outbound.server_port = node.Port;
- outbound.type = Global.ProtocolTypes[node.ConfigType];
+ outbound.type = AppConfig.ProtocolTypes[node.ConfigType];
switch (node.ConfigType)
{
@@ -16,13 +16,13 @@ public partial class CoreConfigSingboxService
{
outbound.uuid = node.Id;
outbound.alter_id = node.AlterId;
- if (Global.VmessSecurities.Contains(node.Security))
+ if (AppConfig.VmessSecurities.Contains(node.Security))
{
outbound.security = node.Security;
}
else
{
- outbound.security = Global.DefaultSecurity;
+ outbound.security = AppConfig.DefaultSecurity;
}
await GenOutboundMux(node, outbound);
@@ -31,10 +31,10 @@ public partial class CoreConfigSingboxService
}
case EConfigType.Shadowsocks:
{
- outbound.method = AppManager.Instance.GetShadowsocksSecurities(node).Contains(node.Security) ? node.Security : Global.None;
+ outbound.method = AppManager.Instance.GetShadowsocksSecurities(node).Contains(node.Security) ? node.Security : AppConfig.None;
outbound.password = node.Id;
- if (node.Network == nameof(ETransport.tcp) && node.HeaderType == Global.TcpHeaderHttp)
+ if (node.Network == nameof(ETransport.tcp) && node.HeaderType == AppConfig.TcpHeaderHttp)
{
outbound.plugin = "obfs-local";
outbound.plugin_opts = $"obfs=http;obfs-host={node.RequestHost};";
@@ -55,7 +55,7 @@ public partial class CoreConfigSingboxService
{
pluginArgs += "mode=quic;";
}
- if (node.StreamSecurity == Global.StreamSecurity)
+ if (node.StreamSecurity == AppConfig.StreamSecurity)
{
pluginArgs += "tls;";
var certs = CertPemManager.ParsePemChain(node.Cert);
@@ -141,7 +141,7 @@ public partial class CoreConfigSingboxService
outbound.obfs = new()
{
type = "salamander",
- password = node.Path.TrimEx(),
+ password = node.Path.TrimSafe(),
};
}
@@ -192,7 +192,7 @@ public partial class CoreConfigSingboxService
try
{
endpoint.address = Utils.String2List(node.RequestHost);
- endpoint.type = Global.ProtocolTypes[node.ConfigType];
+ endpoint.type = AppConfig.ProtocolTypes[node.ConfigType];
switch (node.ConfigType)
{
@@ -208,7 +208,7 @@ public partial class CoreConfigSingboxService
allowed_ips = new() { "0.0.0.0/0", "::/0" },
};
endpoint.private_key = node.Id;
- endpoint.mtu = node.ShortId.IsNullOrEmpty() ? Global.TunMtus.First() : node.ShortId.ToInt();
+ endpoint.mtu = node.ShortId.IsNullOrEmpty() ? AppConfig.TunMtus.First() : node.ShortId.ToInt();
endpoint.peers = new() { peer };
break;
}
@@ -225,7 +225,7 @@ public partial class CoreConfigSingboxService
{
try
{
- var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (node.ConfigType == EConfigType.WireGuard)
{
var endpoint = JsonUtils.Deserialize(txtOutbound);
@@ -282,7 +282,7 @@ public partial class CoreConfigSingboxService
{
try
{
- if (node.StreamSecurity is not (Global.StreamSecurityReality or Global.StreamSecurity))
+ if (node.StreamSecurity is not (AppConfig.StreamSecurityReality or AppConfig.StreamSecurity))
{
return await Task.FromResult(0);
}
@@ -315,7 +315,7 @@ public partial class CoreConfigSingboxService
fingerprint = node.Fingerprint.IsNullOrEmpty() ? _config.CoreBasicItem.DefFingerprint : node.Fingerprint
};
}
- if (node.StreamSecurity == Global.StreamSecurity)
+ if (node.StreamSecurity == AppConfig.StreamSecurity)
{
var certs = CertPemManager.ParsePemChain(node.Cert);
if (certs.Count > 0)
@@ -324,7 +324,7 @@ public partial class CoreConfigSingboxService
tls.insecure = false;
}
}
- else if (node.StreamSecurity == Global.StreamSecurityReality)
+ else if (node.StreamSecurity == AppConfig.StreamSecurityReality)
{
tls.reality = new Reality4Sbox()
{
@@ -363,7 +363,7 @@ public partial class CoreConfigSingboxService
break;
case nameof(ETransport.tcp): //http
- if (node.HeaderType == Global.TcpHeaderHttp)
+ if (node.HeaderType == AppConfig.TcpHeaderHttp)
{
transport.type = nameof(ETransport.http);
transport.host = node.RequestHost.IsNullOrEmpty() ? null : Utils.String2List(node.RequestHost);
@@ -433,7 +433,7 @@ public partial class CoreConfigSingboxService
default:
break;
}
- if (transport.type != null)
+ if (transport.type is not null)
{
outbound.transport = transport;
}
@@ -445,7 +445,7 @@ public partial class CoreConfigSingboxService
return await Task.FromResult(0);
}
- private async Task GenGroupOutbound(ProfileItem node, SingboxConfig singboxConfig, string baseTagName = Global.ProxyTag, bool ignoreOriginChain = false)
+ private async Task GenGroupOutbound(ProfileItem node, SingboxConfig singboxConfig, string baseTagName = AppConfig.ProxyTag, bool ignoreOriginChain = false)
{
try
{
@@ -508,18 +508,18 @@ public partial class CoreConfigSingboxService
}
//current proxy
- BaseServer4Sbox? outbound = singboxConfig.endpoints?.FirstOrDefault(t => t.tag == Global.ProxyTag, null);
+ BaseServer4Sbox? outbound = singboxConfig.endpoints?.FirstOrDefault(t => t.tag == AppConfig.ProxyTag, null);
outbound ??= singboxConfig.outbounds.First();
- var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
//Previous proxy
var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
string? prevOutboundTag = null;
if (prevNode is not null
- && Global.SingboxSupportConfigType.Contains(prevNode.ConfigType))
+ && AppConfig.SingboxSupportConfigType.Contains(prevNode.ConfigType))
{
- prevOutboundTag = $"prev-{Global.ProxyTag}";
+ prevOutboundTag = $"prev-{AppConfig.ProxyTag}";
var prevServer = await GenServer(prevNode);
prevServer.tag = prevOutboundTag;
if (prevServer is Endpoints4Sbox endpoint)
@@ -555,12 +555,12 @@ public partial class CoreConfigSingboxService
return 0;
}
- private async Task GenOutboundsListWithChain(List nodes, SingboxConfig singboxConfig, EMultipleLoad multipleLoad, string baseTagName = Global.ProxyTag)
+ private async Task GenOutboundsListWithChain(List nodes, SingboxConfig singboxConfig, EMultipleLoad multipleLoad, string baseTagName = AppConfig.ProxyTag)
{
try
{
// Get outbound template and initialize lists
- var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (txtOutbound.IsNullOrEmpty())
{
return 0;
@@ -610,7 +610,7 @@ public partial class CoreConfigSingboxService
string? prevTag = null;
var currentServer = await GenServer(node);
var nextServer = nextProxyCache.GetValueOrDefault(node.Subid, null);
- if (nextServer != null)
+ if (nextServer is not null)
{
nextServer = JsonUtils.DeepCopy(nextServer);
}
@@ -631,7 +631,7 @@ public partial class CoreConfigSingboxService
{
var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
if (prevNode is not null
- && Global.SingboxSupportConfigType.Contains(prevNode.ConfigType))
+ && AppConfig.SingboxSupportConfigType.Contains(prevNode.ConfigType))
{
var prevOutbound = JsonUtils.Deserialize(txtOutbound);
await GenOutbound(prevNode, prevOutbound);
@@ -707,7 +707,7 @@ public partial class CoreConfigSingboxService
.Concat(resultOutbounds)
.Concat(resultEndpoints)
.ToList();
- await AddRangeOutbounds(serverList, singboxConfig, baseTagName == Global.ProxyTag);
+ await AddRangeOutbounds(serverList, singboxConfig, baseTagName == AppConfig.ProxyTag);
}
catch (Exception ex)
{
@@ -721,7 +721,7 @@ public partial class CoreConfigSingboxService
{
try
{
- var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (!prevOutboundTag.IsNullOrEmpty())
{
@@ -731,7 +731,7 @@ public partial class CoreConfigSingboxService
// Next proxy
var nextNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.NextProfile);
if (nextNode is not null
- && Global.SingboxSupportConfigType.Contains(nextNode.ConfigType))
+ && AppConfig.SingboxSupportConfigType.Contains(nextNode.ConfigType))
{
nextOutbound ??= await GenServer(nextNode);
nextOutbound.tag = outbound.tag;
@@ -748,7 +748,7 @@ public partial class CoreConfigSingboxService
return null;
}
- private async Task GenOutboundsList(List nodes, SingboxConfig singboxConfig, EMultipleLoad multipleLoad, string baseTagName = Global.ProxyTag)
+ private async Task GenOutboundsList(List nodes, SingboxConfig singboxConfig, EMultipleLoad multipleLoad, string baseTagName = AppConfig.ProxyTag)
{
var resultOutbounds = new List();
var resultEndpoints = new List(); // For endpoints
@@ -756,7 +756,7 @@ public partial class CoreConfigSingboxService
for (var i = 0; i < nodes.Count; i++)
{
var node = nodes[i];
- if (node == null)
+ if (node is null)
{
continue;
}
@@ -830,11 +830,11 @@ public partial class CoreConfigSingboxService
serverList = serverList.Concat(resultOutbounds)
.Concat(resultEndpoints)
.ToList();
- await AddRangeOutbounds(serverList, singboxConfig, baseTagName == Global.ProxyTag);
+ await AddRangeOutbounds(serverList, singboxConfig, baseTagName == AppConfig.ProxyTag);
return await Task.FromResult(0);
}
- private async Task GenChainOutboundsList(List nodes, SingboxConfig singboxConfig, string baseTagName = Global.ProxyTag)
+ private async Task GenChainOutboundsList(List nodes, SingboxConfig singboxConfig, string baseTagName = AppConfig.ProxyTag)
{
// Based on actual network flow instead of data packets
var nodesReverse = nodes.AsEnumerable().Reverse().ToList();
@@ -877,7 +877,7 @@ public partial class CoreConfigSingboxService
serverList = serverList.Concat(resultOutbounds)
.Concat(resultEndpoints)
.ToList();
- await AddRangeOutbounds(serverList, singboxConfig, baseTagName == Global.ProxyTag);
+ await AddRangeOutbounds(serverList, singboxConfig, baseTagName == AppConfig.ProxyTag);
return await Task.FromResult(0);
}
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRoutingService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRoutingService.cs
index 58bcaf99..02467073 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRoutingService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRoutingService.cs
@@ -6,17 +6,17 @@ public partial class CoreConfigSingboxService
{
try
{
- singboxConfig.route.final = Global.ProxyTag;
+ singboxConfig.route.final = AppConfig.ProxyTag;
var item = _config.SimpleDNSItem;
- var defaultDomainResolverTag = Global.SingboxDirectDNSTag;
- var directDNSStrategy = item.SingboxStrategy4Direct.IsNullOrEmpty() ? Global.SingboxDomainStrategy4Out.FirstOrDefault() : item.SingboxStrategy4Direct;
+ var defaultDomainResolverTag = AppConfig.SingboxDirectDNSTag;
+ var directDNSStrategy = item.SingboxStrategy4Direct.IsNullOrEmpty() ? AppConfig.SingboxDomainStrategy4Out.FirstOrDefault() : item.SingboxStrategy4Direct;
var rawDNSItem = await AppManager.Instance.GetDNSItem(ECoreType.sing_box);
- if (rawDNSItem != null && rawDNSItem.Enabled == true)
+ if (rawDNSItem is not null && rawDNSItem.Enabled == true)
{
- defaultDomainResolverTag = Global.SingboxLocalDNSTag;
- directDNSStrategy = rawDNSItem.DomainStrategy4Freedom.IsNullOrEmpty() ? Global.SingboxDomainStrategy4Out.FirstOrDefault() : rawDNSItem.DomainStrategy4Freedom;
+ defaultDomainResolverTag = AppConfig.SingboxLocalDNSTag;
+ directDNSStrategy = rawDNSItem.DomainStrategy4Freedom.IsNullOrEmpty() ? AppConfig.SingboxDomainStrategy4Out.FirstOrDefault() : rawDNSItem.DomainStrategy4Freedom;
}
singboxConfig.route.default_domain_resolver = new()
{
@@ -28,8 +28,8 @@ public partial class CoreConfigSingboxService
{
singboxConfig.route.auto_detect_interface = true;
- var tunRules = JsonUtils.Deserialize>(EmbedUtils.GetEmbedText(Global.TunSingboxRulesFileName));
- if (tunRules != null)
+ var tunRules = JsonUtils.Deserialize>(EmbedUtils.GetEmbedText(AppConfig.TunSingboxRulesFileName));
+ if (tunRules is not null)
{
singboxConfig.route.rules.AddRange(tunRules);
}
@@ -44,7 +44,7 @@ public partial class CoreConfigSingboxService
singboxConfig.route.rules.Add(new()
{
- outbound = Global.DirectTag,
+ outbound = AppConfig.DirectTag,
process_name = lstDirectExe
});
}
@@ -73,7 +73,7 @@ public partial class CoreConfigSingboxService
var hostsDomains = new List();
var dnsItem = await AppManager.Instance.GetDNSItem(ECoreType.sing_box);
- if (dnsItem == null || dnsItem.Enabled == false)
+ if (dnsItem is null || dnsItem.Enabled == false)
{
var simpleDNSItem = _config.SimpleDNSItem;
if (!simpleDNSItem.Hosts.IsNullOrEmpty())
@@ -104,12 +104,12 @@ public partial class CoreConfigSingboxService
singboxConfig.route.rules.Add(new()
{
- outbound = Global.DirectTag,
+ outbound = AppConfig.DirectTag,
clash_mode = ERuleMode.Direct.ToString()
});
singboxConfig.route.rules.Add(new()
{
- outbound = Global.ProxyTag,
+ outbound = AppConfig.ProxyTag,
clash_mode = ERuleMode.Global.ToString()
});
@@ -124,14 +124,14 @@ public partial class CoreConfigSingboxService
action = "resolve",
strategy = domainStrategy
};
- if (_config.RoutingBasicItem.DomainStrategy == Global.IPOnDemand)
+ if (_config.RoutingBasicItem.DomainStrategy == AppConfig.IPOnDemand)
{
singboxConfig.route.rules.Add(resolveRule);
}
var routing = await ConfigHandler.GetDefaultRouting(_config);
var ipRules = new List();
- if (routing != null)
+ if (routing is not null)
{
var rules = JsonUtils.Deserialize>(routing.RuleSet);
foreach (var item1 in rules ?? [])
@@ -154,7 +154,7 @@ public partial class CoreConfigSingboxService
}
}
}
- if (_config.RoutingBasicItem.DomainStrategy == Global.IPIfNonMatch)
+ if (_config.RoutingBasicItem.DomainStrategy == AppConfig.IPIfNonMatch)
{
singboxConfig.route.rules.Add(resolveRule);
foreach (var item2 in ipRules)
@@ -202,7 +202,7 @@ public partial class CoreConfigSingboxService
{
try
{
- if (item == null)
+ if (item is null)
{
return 0;
}
@@ -326,7 +326,7 @@ public partial class CoreConfigSingboxService
}
if (!hasDomainIp
- && (rule.port != null || rule.port_range != null || rule.protocol != null || rule.inbound != null || rule.network != null))
+ && (rule.port is not null || rule.port_range is not null || rule.protocol is not null || rule.inbound is not null || rule.network is not null))
{
rules.Add(rule);
}
@@ -352,7 +352,7 @@ public partial class CoreConfigSingboxService
else if (domain.StartsWith("regexp:"))
{
rule.domain_regex ??= [];
- rule.domain_regex?.Add(domain.Replace(Global.RoutingRuleComma, ",").Substring(7));
+ rule.domain_regex?.Add(domain.Replace(AppConfig.RoutingRuleComma, ",").Substring(7));
}
else if (domain.StartsWith("domain:"))
{
@@ -412,23 +412,23 @@ public partial class CoreConfigSingboxService
private async Task GenRoutingUserRuleOutbound(string outboundTag, SingboxConfig singboxConfig)
{
- if (Global.OutboundTags.Contains(outboundTag))
+ if (AppConfig.OutboundTags.Contains(outboundTag))
{
return outboundTag;
}
var node = await AppManager.Instance.GetProfileItemViaRemarks(outboundTag);
- if (node == null
- || (!Global.SingboxSupportConfigType.Contains(node.ConfigType)
+ if (node is null
+ || (!AppConfig.SingboxSupportConfigType.Contains(node.ConfigType)
&& !node.ConfigType.IsGroupType()))
{
- return Global.ProxyTag;
+ return AppConfig.ProxyTag;
}
- var tag = $"{node.IndexId}-{Global.ProxyTag}";
+ var tag = $"{node.IndexId}-{AppConfig.ProxyTag}";
if (singboxConfig.outbounds.Any(o => o.tag == tag)
- || (singboxConfig.endpoints != null && singboxConfig.endpoints.Any(e => e.tag == tag)))
+ || (singboxConfig.endpoints is not null && singboxConfig.endpoints.Any(e => e.tag == tag)))
{
return tag;
}
@@ -440,13 +440,13 @@ public partial class CoreConfigSingboxService
{
return tag;
}
- return Global.ProxyTag;
+ return AppConfig.ProxyTag;
}
var server = await GenServer(node);
if (server is null)
{
- return Global.ProxyTag;
+ return AppConfig.ProxyTag;
}
server.tag = tag;
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRulesetService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRulesetService.cs
index 7d26ca2f..bd406598 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRulesetService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxRulesetService.cs
@@ -6,7 +6,7 @@ public partial class CoreConfigSingboxService
{
static void AddRuleSets(List ruleSets, List? rule_set)
{
- if (rule_set != null)
+ if (rule_set is not null)
{
ruleSets.AddRange(rule_set);
}
@@ -67,9 +67,9 @@ public partial class CoreConfigSingboxService
if (result.IsNotEmpty())
{
customRulesets = (JsonUtils.Deserialize>(result) ?? [])
- .Where(t => t.tag != null)
- .Where(t => t.type != null)
- .Where(t => t.format != null)
+ .Where(t => t.tag is not null)
+ .Where(t => t.type is not null)
+ .Where(t => t.format is not null)
.ToList();
}
}
@@ -82,8 +82,10 @@ public partial class CoreConfigSingboxService
foreach (var item in new HashSet(ruleSets))
{
if (item.IsNullOrEmpty())
- { continue; }
- var customRuleset = customRulesets.FirstOrDefault(t => t.tag != null && t.tag.Equals(item));
+ {
+ continue;
+ }
+ var customRuleset = customRulesets.FirstOrDefault(t => t.tag is not null && t.tag.Equals(item));
if (customRuleset is null)
{
var pathSrs = Path.Combine(localSrss, $"{item}.srs");
@@ -100,7 +102,7 @@ public partial class CoreConfigSingboxService
else
{
var srsUrl = string.IsNullOrEmpty(_config.ConstItem.SrsSourceUrl)
- ? Global.SingboxRulesetUrl
+ ? AppConfig.SingboxRulesetUrl
: _config.ConstItem.SrsSourceUrl;
customRuleset = new()
@@ -109,7 +111,7 @@ public partial class CoreConfigSingboxService
format = "binary",
tag = item,
url = string.Format(srsUrl, item.StartsWith(geosite) ? geosite : geoip, item),
- download_detour = Global.ProxyTag
+ download_detour = AppConfig.ProxyTag
};
}
}
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxStatisticService.cs b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxStatisticService.cs
index c3acd810..1cb94edf 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxStatisticService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/Singbox/SingboxStatisticService.cs
@@ -4,12 +4,12 @@ public partial class CoreConfigSingboxService
{
private async Task GenExperimental(SingboxConfig singboxConfig)
{
- //if (_config.guiItem.enableStatistics)
+ //if (Config.guiItem.enableStatistics)
{
singboxConfig.experimental ??= new Experimental4Sbox();
singboxConfig.experimental.clash_api = new Clash_Api4Sbox()
{
- external_controller = $"{Global.Loopback}:{AppManager.Instance.StatePort2}",
+ external_controller = $"{AppConfig.Loopback}:{AppManager.Instance.StatePort2}",
};
}
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/CoreConfigV2rayService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/CoreConfigV2rayService.cs
index d753fb3c..39a2f05b 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/CoreConfigV2rayService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/CoreConfigV2rayService.cs
@@ -12,7 +12,7 @@ public partial class CoreConfigV2rayService(Config config)
var ret = new RetResult();
try
{
- if (node == null
+ if (node is null
|| !node.IsValid())
{
ret.Msg = ResUI.CheckServerSettings;
@@ -39,7 +39,7 @@ public partial class CoreConfigV2rayService(Config config)
}
}
- var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
+ var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleClient);
if (result.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
@@ -47,7 +47,7 @@ public partial class CoreConfigV2rayService(Config config)
}
var v2rayConfig = JsonUtils.Deserialize(result);
- if (v2rayConfig == null)
+ if (v2rayConfig is null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
@@ -86,7 +86,7 @@ public partial class CoreConfigV2rayService(Config config)
try
{
- if (_config == null)
+ if (_config is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -94,8 +94,8 @@ public partial class CoreConfigV2rayService(Config config)
ret.Msg = ResUI.InitialConfiguration;
- var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
- var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
+ var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleClient);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
@@ -103,7 +103,7 @@ public partial class CoreConfigV2rayService(Config config)
}
var v2rayConfig = JsonUtils.Deserialize(result);
- if (v2rayConfig == null)
+ if (v2rayConfig is null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
@@ -124,7 +124,7 @@ public partial class CoreConfigV2rayService(Config config)
await GenDns(null, v2rayConfig);
await GenStatistic(v2rayConfig);
- var defaultBalancerTag = $"{Global.ProxyTag}{Global.BalancerTagSuffix}";
+ var defaultBalancerTag = $"{AppConfig.ProxyTag}{AppConfig.BalancerTagSuffix}";
//add rule
var rules = v2rayConfig.routing.rules;
@@ -136,7 +136,7 @@ public partial class CoreConfigV2rayService(Config config)
foreach (var rule in rules)
{
- if (rule.outboundTag == null)
+ if (rule.outboundTag is null)
{
continue;
}
@@ -148,7 +148,7 @@ public partial class CoreConfigV2rayService(Config config)
continue;
}
- var outboundWithSuffix = rule.outboundTag + Global.BalancerTagSuffix;
+ var outboundWithSuffix = rule.outboundTag + AppConfig.BalancerTagSuffix;
if (balancerTagSet.Contains(outboundWithSuffix))
{
rule.balancerTag = outboundWithSuffix;
@@ -156,7 +156,7 @@ public partial class CoreConfigV2rayService(Config config)
}
}
}
- if (v2rayConfig.routing.domainStrategy == Global.IPIfNonMatch)
+ if (v2rayConfig.routing.domainStrategy == AppConfig.IPIfNonMatch)
{
v2rayConfig.routing.rules.Add(new()
{
@@ -194,7 +194,7 @@ public partial class CoreConfigV2rayService(Config config)
try
{
- if (_config == null)
+ if (_config is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -202,8 +202,8 @@ public partial class CoreConfigV2rayService(Config config)
ret.Msg = ResUI.InitialConfiguration;
- var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
- var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
+ var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleClient);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
@@ -211,7 +211,7 @@ public partial class CoreConfigV2rayService(Config config)
}
var v2rayConfig = JsonUtils.Deserialize(result);
- if (v2rayConfig == null)
+ if (v2rayConfig is null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
@@ -250,7 +250,7 @@ public partial class CoreConfigV2rayService(Config config)
var ret = new RetResult();
try
{
- if (_config == null)
+ if (_config is null)
{
ret.Msg = ResUI.CheckServerSettings;
return ret;
@@ -258,8 +258,8 @@ public partial class CoreConfigV2rayService(Config config)
ret.Msg = ResUI.InitialConfiguration;
- var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
- var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
+ var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleClient);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
@@ -267,7 +267,7 @@ public partial class CoreConfigV2rayService(Config config)
}
var v2rayConfig = JsonUtils.Deserialize(result);
- if (v2rayConfig == null)
+ if (v2rayConfig is null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
@@ -294,7 +294,7 @@ public partial class CoreConfigV2rayService(Config config)
foreach (var it in selecteds)
{
- if (!Global.XraySupportConfigType.Contains(it.ConfigType))
+ if (!AppConfig.XraySupportConfigType.Contains(it.ConfigType))
{
continue;
}
@@ -310,7 +310,7 @@ public partial class CoreConfigV2rayService(Config config)
//find unused port
var port = initPort;
- for (var k = initPort; k < Global.MaxPort; k++)
+ for (var k = initPort; k < AppConfig.MaxPort; k++)
{
if (lstIpEndPoints?.FindIndex(_it => _it.Port == k) >= 0)
{
@@ -337,7 +337,7 @@ public partial class CoreConfigV2rayService(Config config)
//inbound
Inbounds4Ray inbound = new()
{
- listen = Global.Loopback,
+ listen = AppConfig.Loopback,
port = port,
protocol = EInboundProtocol.mixed.ToString(),
};
@@ -347,7 +347,7 @@ public partial class CoreConfigV2rayService(Config config)
//outbound
var outbound = JsonUtils.Deserialize(txtOutbound);
await GenOutbound(item, outbound);
- outbound.tag = Global.ProxyTag + inbound.port.ToString();
+ outbound.tag = AppConfig.ProxyTag + inbound.port.ToString();
v2rayConfig.outbounds.Add(outbound);
//rule
@@ -378,7 +378,7 @@ public partial class CoreConfigV2rayService(Config config)
var ret = new RetResult();
try
{
- if (node == null
+ if (node is null
|| !node.IsValid())
{
ret.Msg = ResUI.CheckServerSettings;
@@ -391,7 +391,7 @@ public partial class CoreConfigV2rayService(Config config)
return ret;
}
- var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
+ var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleClient);
if (result.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
@@ -399,7 +399,7 @@ public partial class CoreConfigV2rayService(Config config)
}
var v2rayConfig = JsonUtils.Deserialize(result);
- if (v2rayConfig == null)
+ if (v2rayConfig is null)
{
ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret;
@@ -414,7 +414,7 @@ public partial class CoreConfigV2rayService(Config config)
v2rayConfig.inbounds.Add(new()
{
tag = $"{EInboundProtocol.socks}{port}",
- listen = Global.Loopback,
+ listen = AppConfig.Loopback,
port = port,
protocol = EInboundProtocol.mixed.ToString(),
});
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayBalancerService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayBalancerService.cs
index 35a220c6..34b594af 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayBalancerService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayBalancerService.cs
@@ -2,7 +2,7 @@ namespace ServiceLib.Services.CoreConfig;
public partial class CoreConfigV2rayService
{
- private async Task GenObservatory(V2rayConfig v2rayConfig, EMultipleLoad multipleLoad, string baseTagName = Global.ProxyTag)
+ private async Task GenObservatory(V2rayConfig v2rayConfig, EMultipleLoad multipleLoad, string baseTagName = AppConfig.ProxyTag)
{
// Collect all existing subject selectors from both observatories
var subjectSelectors = new List();
@@ -83,7 +83,7 @@ public partial class CoreConfigV2rayService
return await Task.FromResult(0);
}
- private async Task GenBalancer(V2rayConfig v2rayConfig, EMultipleLoad multipleLoad, string selector = Global.ProxyTag)
+ private async Task GenBalancer(V2rayConfig v2rayConfig, EMultipleLoad multipleLoad, string selector = AppConfig.ProxyTag)
{
var strategyType = multipleLoad switch
{
@@ -93,7 +93,7 @@ public partial class CoreConfigV2rayService
EMultipleLoad.LeastLoad => "leastLoad",
_ => "roundRobin",
};
- var balancerTag = $"{selector}{Global.BalancerTagSuffix}";
+ var balancerTag = $"{selector}{AppConfig.BalancerTagSuffix}";
var balancer = new BalancersItem4Ray
{
selector = [selector],
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayConfigTemplateService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayConfigTemplateService.cs
index 1f2583ff..767f4b95 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayConfigTemplateService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayConfigTemplateService.cs
@@ -5,13 +5,13 @@ public partial class CoreConfigV2rayService
private async Task ApplyFullConfigTemplate(V2rayConfig v2rayConfig)
{
var fullConfigTemplate = await AppManager.Instance.GetFullConfigTemplateItem(ECoreType.Xray);
- if (fullConfigTemplate == null || !fullConfigTemplate.Enabled || fullConfigTemplate.Config.IsNullOrEmpty())
+ if (fullConfigTemplate is null || !fullConfigTemplate.Enabled || fullConfigTemplate.Config.IsNullOrEmpty())
{
return JsonUtils.Serialize(v2rayConfig);
}
var fullConfigTemplateNode = JsonNode.Parse(fullConfigTemplate.Config);
- if (fullConfigTemplateNode == null)
+ if (fullConfigTemplateNode is null)
{
return JsonUtils.Serialize(v2rayConfig);
}
@@ -23,11 +23,11 @@ public partial class CoreConfigV2rayService
// Modify existing rules in custom config
var rulesNode = fullConfigTemplateNode["routing"]?["rules"];
- if (rulesNode != null)
+ if (rulesNode is not null)
{
foreach (var rule in rulesNode.AsArray())
{
- if (rule["outboundTag"]?.GetValue() == Global.ProxyTag)
+ if (rule["outboundTag"]?.GetValue() == AppConfig.ProxyTag)
{
rule.AsObject().Remove("outboundTag");
rule["balancerTag"] = balancer.tag;
@@ -36,7 +36,7 @@ public partial class CoreConfigV2rayService
}
// Ensure routing node exists
- if (fullConfigTemplateNode["routing"] == null)
+ if (fullConfigTemplateNode["routing"] is null)
{
fullConfigTemplateNode["routing"] = new JsonObject();
}
@@ -58,9 +58,9 @@ public partial class CoreConfigV2rayService
}
}
- if (v2rayConfig.observatory != null)
+ if (v2rayConfig.observatory is not null)
{
- if (fullConfigTemplateNode["observatory"] == null)
+ if (fullConfigTemplateNode["observatory"] is null)
{
fullConfigTemplateNode["observatory"] = JsonNode.Parse(JsonUtils.Serialize(v2rayConfig.observatory));
}
@@ -72,9 +72,9 @@ public partial class CoreConfigV2rayService
}
}
- if (v2rayConfig.burstObservatory != null)
+ if (v2rayConfig.burstObservatory is not null)
{
- if (fullConfigTemplateNode["burstObservatory"] == null)
+ if (fullConfigTemplateNode["burstObservatory"] is null)
{
fullConfigTemplateNode["burstObservatory"] = JsonNode.Parse(JsonUtils.Serialize(v2rayConfig.burstObservatory));
}
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayDnsService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayDnsService.cs
index 6ba45895..272e321a 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayDnsService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayDnsService.cs
@@ -7,19 +7,19 @@ public partial class CoreConfigV2rayService
try
{
var item = await AppManager.Instance.GetDNSItem(ECoreType.Xray);
- if (item != null && item.Enabled == true)
+ if (item is not null && item.Enabled == true)
{
var result = await GenDnsCompatible(node, v2rayConfig);
- if (v2rayConfig.routing.domainStrategy == Global.IPIfNonMatch)
+ if (v2rayConfig.routing.domainStrategy == AppConfig.IPIfNonMatch)
{
// DNS routing
- v2rayConfig.dns.tag = Global.DnsTag;
+ v2rayConfig.dns.tag = AppConfig.DnsTag;
v2rayConfig.routing.rules.Add(new RulesItem4Ray
{
type = "field",
- inboundTag = new List { Global.DnsTag },
- outboundTag = Global.ProxyTag,
+ inboundTag = new List { AppConfig.DnsTag },
+ outboundTag = AppConfig.ProxyTag,
});
}
@@ -31,29 +31,26 @@ public partial class CoreConfigV2rayService
//Outbound Freedom domainStrategy
if (domainStrategy4Freedom.IsNotEmpty())
{
- var outbound = v2rayConfig.outbounds.FirstOrDefault(t => t is { protocol: "freedom", tag: Global.DirectTag });
- if (outbound != null)
+ var outbound = v2rayConfig.outbounds.FirstOrDefault(t => t is { protocol: "freedom", tag: AppConfig.DirectTag });
+ outbound?.settings = new()
{
- outbound.settings = new()
- {
- domainStrategy = domainStrategy4Freedom,
- userLevel = 0
- };
- }
+ domainStrategy = domainStrategy4Freedom,
+ userLevel = 0
+ };
}
await GenDnsServers(node, v2rayConfig, simpleDNSItem);
await GenDnsHosts(v2rayConfig, simpleDNSItem);
- if (v2rayConfig.routing.domainStrategy == Global.IPIfNonMatch)
+ if (v2rayConfig.routing.domainStrategy == AppConfig.IPIfNonMatch)
{
// DNS routing
- v2rayConfig.dns.tag = Global.DnsTag;
+ v2rayConfig.dns.tag = AppConfig.DnsTag;
v2rayConfig.routing.rules.Add(new RulesItem4Ray
{
type = "field",
- inboundTag = new List { Global.DnsTag },
- outboundTag = Global.ProxyTag,
+ inboundTag = new List { AppConfig.DnsTag },
+ outboundTag = AppConfig.ProxyTag,
});
}
}
@@ -106,8 +103,8 @@ public partial class CoreConfigV2rayService
});
}
- var directDNSAddress = ParseDnsAddresses(simpleDNSItem?.DirectDNS, Global.DomainDirectDNSAddress.FirstOrDefault());
- var remoteDNSAddress = ParseDnsAddresses(simpleDNSItem?.RemoteDNS, Global.DomainRemoteDNSAddress.FirstOrDefault());
+ var directDNSAddress = ParseDnsAddresses(simpleDNSItem?.DirectDNS, AppConfig.DomainDirectDNSAddress.FirstOrDefault());
+ var remoteDNSAddress = ParseDnsAddresses(simpleDNSItem?.RemoteDNS, AppConfig.DomainRemoteDNSAddress.FirstOrDefault());
var directDomainList = new List();
var directGeositeList = new List();
@@ -117,7 +114,7 @@ public partial class CoreConfigV2rayService
var expectedIPs = new List();
var regionNames = new HashSet();
- var bootstrapDNSAddress = ParseDnsAddresses(simpleDNSItem?.BootstrapDNS, Global.DomainPureIPDNSAddress.FirstOrDefault());
+ var bootstrapDNSAddress = ParseDnsAddresses(simpleDNSItem?.BootstrapDNS, AppConfig.DomainPureIPDNSAddress.FirstOrDefault());
var dnsServerDomains = new List();
foreach (var dns in directDNSAddress)
@@ -171,7 +168,7 @@ public partial class CoreConfigV2rayService
var routing = await ConfigHandler.GetDefaultRouting(_config);
List? rules = null;
- if (routing != null)
+ if (routing is not null)
{
rules = JsonUtils.Deserialize>(routing.RuleSet) ?? [];
foreach (var item in rules)
@@ -193,9 +190,9 @@ public partial class CoreConfigV2rayService
continue;
}
- var normalizedDomain = domain.Replace(Global.RoutingRuleComma, ",");
+ var normalizedDomain = domain.Replace(AppConfig.RoutingRuleComma, ",");
- if (item.OutboundTag == Global.DirectTag)
+ if (item.OutboundTag == AppConfig.DirectTag)
{
if (normalizedDomain.StartsWith("geosite:") || normalizedDomain.StartsWith("ext:"))
{
@@ -206,7 +203,7 @@ public partial class CoreConfigV2rayService
directDomainList.Add(normalizedDomain);
}
}
- else if (item.OutboundTag != Global.BlockTag)
+ else if (item.OutboundTag != AppConfig.BlockTag)
{
if (normalizedDomain.StartsWith("geosite:") || normalizedDomain.StartsWith("ext:"))
{
@@ -235,7 +232,7 @@ public partial class CoreConfigV2rayService
{
var profileNode = await AppManager.Instance.GetProfileItemViaRemarks(profile);
if (profileNode is not null
- && Global.XraySupportConfigType.Contains(profileNode.ConfigType)
+ && AppConfig.XraySupportConfigType.Contains(profileNode.ConfigType)
&& Utils.IsDomain(profileNode.Address))
{
directDomainList.Add(profileNode.Address);
@@ -269,7 +266,7 @@ public partial class CoreConfigV2rayService
}
var useDirectDns = rules?.LastOrDefault() is { } lastRule
- && lastRule.OutboundTag == Global.DirectTag
+ && lastRule.OutboundTag == AppConfig.DirectTag
&& (lastRule.Port == "0-65535"
|| lastRule.Network == "tcp,udp"
|| lastRule.Ip?.Contains("0.0.0.0/0") == true);
@@ -280,7 +277,7 @@ public partial class CoreConfigV2rayService
return 0;
}
- private async Task GenDnsHosts(V2rayConfig v2rayConfig, SimpleDNSItem simpleDNSItem)
+ private static async Task GenDnsHosts(V2rayConfig v2rayConfig, SimpleDNSItem simpleDNSItem)
{
if (simpleDNSItem.AddCommonHosts == false && simpleDNSItem.UseSystemHosts == false && simpleDNSItem.Hosts.IsNullOrEmpty())
{
@@ -290,7 +287,7 @@ public partial class CoreConfigV2rayService
v2rayConfig.dns.hosts ??= new Dictionary();
if (simpleDNSItem.AddCommonHosts == true)
{
- v2rayConfig.dns.hosts = Global.PredefinedHosts.ToDictionary(
+ v2rayConfig.dns.hosts = AppConfig.PredefinedHosts.ToDictionary(
kvp => kvp.Key,
kvp => (object)kvp.Value
);
@@ -301,7 +298,7 @@ public partial class CoreConfigV2rayService
var systemHosts = Utils.GetSystemHosts();
var normalHost = v2rayConfig?.dns?.hosts;
- if (normalHost != null && systemHosts?.Count > 0)
+ if (normalHost is not null && systemHosts?.Count > 0)
{
foreach (var host in systemHosts)
{
@@ -331,19 +328,18 @@ public partial class CoreConfigV2rayService
var domainStrategy4Freedom = item?.DomainStrategy4Freedom;
if (normalDNS.IsNullOrEmpty())
{
- normalDNS = EmbedUtils.GetEmbedText(Global.DNSV2rayNormalFileName);
+ normalDNS = EmbedUtils.GetEmbedText(AppConfig.DNSV2rayNormalFileName);
}
//Outbound Freedom domainStrategy
if (domainStrategy4Freedom.IsNotEmpty())
{
- var outbound = v2rayConfig.outbounds.FirstOrDefault(t => t is { protocol: "freedom", tag: Global.DirectTag });
- if (outbound != null)
- {
- outbound.settings = new();
- outbound.settings.domainStrategy = domainStrategy4Freedom;
- outbound.settings.userLevel = 0;
- }
+ var outbound = v2rayConfig.outbounds.FirstOrDefault(t => t is { protocol: "freedom", tag: AppConfig.DirectTag });
+ outbound?.settings = new()
+ {
+ domainStrategy = domainStrategy4Freedom,
+ userLevel = 0
+ };
}
var obj = JsonUtils.ParseJson(normalDNS);
@@ -366,11 +362,11 @@ public partial class CoreConfigV2rayService
if (systemHosts.Count > 0)
{
var normalHost1 = obj["hosts"];
- if (normalHost1 != null)
+ if (normalHost1 is not null)
{
foreach (var host in systemHosts)
{
- if (normalHost1[host.Key] != null)
+ if (normalHost1[host.Key] is not null)
{
continue;
}
@@ -381,7 +377,7 @@ public partial class CoreConfigV2rayService
}
}
var normalHost = obj["hosts"];
- if (normalHost != null)
+ if (normalHost is not null)
{
foreach (var hostProp in normalHost.AsObject().ToList())
{
@@ -403,14 +399,14 @@ public partial class CoreConfigV2rayService
return 0;
}
- private async Task GenDnsDomainsCompatible(ProfileItem? node, JsonNode dns, DNSItem? dnsItem)
+ private static async Task GenDnsDomainsCompatible(ProfileItem? node, JsonNode dns, DNSItem? dnsItem)
{
- if (node == null)
+ if (node is null)
{
return 0;
}
var servers = dns["servers"];
- if (servers != null)
+ if (servers is not null)
{
var domainList = new List();
if (Utils.IsDomain(node.Address))
@@ -423,7 +419,7 @@ public partial class CoreConfigV2rayService
// Previous proxy
var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
if (prevNode is not null
- && Global.SingboxSupportConfigType.Contains(prevNode.ConfigType)
+ && AppConfig.SingboxSupportConfigType.Contains(prevNode.ConfigType)
&& Utils.IsDomain(prevNode.Address))
{
domainList.Add(prevNode.Address);
@@ -432,7 +428,7 @@ public partial class CoreConfigV2rayService
// Next proxy
var nextNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.NextProfile);
if (nextNode is not null
- && Global.SingboxSupportConfigType.Contains(nextNode.ConfigType)
+ && AppConfig.SingboxSupportConfigType.Contains(nextNode.ConfigType)
&& Utils.IsDomain(nextNode.Address))
{
domainList.Add(nextNode.Address);
@@ -442,7 +438,7 @@ public partial class CoreConfigV2rayService
{
var dnsServer = new DnsServer4Ray()
{
- address = string.IsNullOrEmpty(dnsItem?.DomainDNSAddress) ? Global.DomainPureIPDNSAddress.FirstOrDefault() : dnsItem?.DomainDNSAddress,
+ address = string.IsNullOrEmpty(dnsItem?.DomainDNSAddress) ? AppConfig.DomainPureIPDNSAddress.FirstOrDefault() : dnsItem?.DomainDNSAddress,
skipFallback = true,
domains = domainList
};
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayInboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayInboundService.cs
index 2cbdfe88..0620da38 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayInboundService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayInboundService.cs
@@ -30,7 +30,7 @@ public partial class CoreConfigV2rayService
if (_config.Inbound.First().User.IsNotEmpty() && _config.Inbound.First().Pass.IsNotEmpty())
{
inbound3.settings.auth = "password";
- inbound3.settings.accounts = new List { new AccountsItem4Ray() { user = _config.Inbound.First().User, pass = _config.Inbound.First().Pass } };
+ inbound3.settings.accounts = new List { new() { user = _config.Inbound.First().User, pass = _config.Inbound.First().Pass } };
}
}
else
@@ -48,14 +48,14 @@ public partial class CoreConfigV2rayService
private Inbounds4Ray GetInbound(InItem inItem, EInboundProtocol protocol, bool bSocks)
{
- var result = EmbedUtils.GetEmbedText(Global.V2raySampleInbound);
+ var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleInbound);
if (result.IsNullOrEmpty())
{
return new();
}
var inbound = JsonUtils.Deserialize(result);
- if (inbound == null)
+ if (inbound is null)
{
return new();
}
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs
index 3db5a420..d177ccf3 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayOutboundService.cs
@@ -37,14 +37,14 @@ public partial class CoreConfigV2rayService
usersItem.id = node.Id;
usersItem.alterId = node.AlterId;
- usersItem.email = Global.UserEMail;
- if (Global.VmessSecurities.Contains(node.Security))
+ usersItem.email = AppConfig.UserEMail;
+ if (AppConfig.VmessSecurities.Contains(node.Security))
{
usersItem.security = node.Security;
}
else
{
- usersItem.security = Global.DefaultSecurity;
+ usersItem.security = AppConfig.DefaultSecurity;
}
await GenOutboundMux(node, outbound, muxEnabled, muxEnabled);
@@ -139,7 +139,7 @@ public partial class CoreConfigV2rayService
usersItem = vnextItem.users.First();
}
usersItem.id = node.Id;
- usersItem.email = Global.UserEMail;
+ usersItem.email = AppConfig.UserEMail;
usersItem.encryption = node.Security;
if (node.Flow.IsNullOrEmpty())
@@ -185,9 +185,9 @@ public partial class CoreConfigV2rayService
version = 2,
address = node.Address,
port = node.Port,
+ vnext = null,
+ servers = null
};
- outbound.settings.vnext = null;
- outbound.settings.servers = null;
break;
}
case EConfigType.WireGuard:
@@ -207,7 +207,7 @@ public partial class CoreConfigV2rayService
address = Utils.String2List(node.RequestHost),
secretKey = node.Id,
reserved = Utils.String2List(node.Path)?.Select(int.Parse).ToList(),
- mtu = node.ShortId.IsNullOrEmpty() ? Global.TunMtus.First() : node.ShortId.ToInt(),
+ mtu = node.ShortId.IsNullOrEmpty() ? AppConfig.TunMtus.First() : node.ShortId.ToInt(),
peers = new List { peer }
};
outbound.settings = setting;
@@ -217,7 +217,7 @@ public partial class CoreConfigV2rayService
}
}
- outbound.protocol = Global.ProtocolTypes[node.ConfigType];
+ outbound.protocol = AppConfig.ProtocolTypes[node.ConfigType];
if (node.ConfigType == EConfigType.Hysteria2)
{
outbound.protocol = "hysteria";
@@ -268,15 +268,15 @@ public partial class CoreConfigV2rayService
network = "hysteria";
}
streamSettings.network = network;
- var host = node.RequestHost.TrimEx();
- var path = node.Path.TrimEx();
- var sni = node.Sni.TrimEx();
+ var host = node.RequestHost.TrimSafe();
+ var path = node.Path.TrimSafe();
+ var sni = node.Sni.TrimSafe();
var useragent = "";
if (!_config.CoreBasicItem.DefUserAgent.IsNullOrEmpty())
{
try
{
- useragent = Global.UserAgentTexts[_config.CoreBasicItem.DefUserAgent];
+ useragent = AppConfig.UserAgentTexts[_config.CoreBasicItem.DefUserAgent];
}
catch (KeyNotFoundException)
{
@@ -285,7 +285,7 @@ public partial class CoreConfigV2rayService
}
//if tls
- if (node.StreamSecurity == Global.StreamSecurity)
+ if (node.StreamSecurity == AppConfig.StreamSecurity)
{
streamSettings.security = node.StreamSecurity;
@@ -330,7 +330,7 @@ public partial class CoreConfigV2rayService
}
//if Reality
- if (node.StreamSecurity == Global.StreamSecurityReality)
+ if (node.StreamSecurity == AppConfig.StreamSecurityReality)
{
streamSettings.security = node.StreamSecurity;
@@ -355,19 +355,18 @@ public partial class CoreConfigV2rayService
KcpSettings4Ray kcpSettings = new()
{
mtu = _config.KcpItem.Mtu,
- tti = _config.KcpItem.Tti
- };
+ tti = _config.KcpItem.Tti,
+ uplinkCapacity = _config.KcpItem.UplinkCapacity,
+ downlinkCapacity = _config.KcpItem.DownlinkCapacity,
- kcpSettings.uplinkCapacity = _config.KcpItem.UplinkCapacity;
- kcpSettings.downlinkCapacity = _config.KcpItem.DownlinkCapacity;
-
- kcpSettings.congestion = _config.KcpItem.Congestion;
- kcpSettings.readBufferSize = _config.KcpItem.ReadBufferSize;
- kcpSettings.writeBufferSize = _config.KcpItem.WriteBufferSize;
- kcpSettings.header = new Header4Ray
- {
- type = node.HeaderType,
- domain = host.NullIfEmpty()
+ congestion = _config.KcpItem.Congestion,
+ readBufferSize = _config.KcpItem.ReadBufferSize,
+ writeBufferSize = _config.KcpItem.WriteBufferSize,
+ header = new Header4Ray
+ {
+ type = node.HeaderType,
+ domain = host.NullIfEmpty()
+ }
};
if (path.IsNotEmpty())
{
@@ -377,8 +376,10 @@ public partial class CoreConfigV2rayService
break;
//ws
case nameof(ETransport.ws):
- WsSettings4Ray wsSettings = new();
- wsSettings.headers = new Headers4Ray();
+ WsSettings4Ray wsSettings = new()
+ {
+ headers = new Headers4Ray()
+ };
if (host.IsNotEmpty())
{
@@ -423,7 +424,7 @@ public partial class CoreConfigV2rayService
{
xhttpSettings.host = host;
}
- if (node.HeaderType.IsNotEmpty() && Global.XhttpMode.Contains(node.HeaderType))
+ if (node.HeaderType.IsNotEmpty() && AppConfig.XhttpMode.Contains(node.HeaderType))
{
xhttpSettings.mode = node.HeaderType;
}
@@ -461,7 +462,7 @@ public partial class CoreConfigV2rayService
}
};
streamSettings.quicSettings = quicsettings;
- if (node.StreamSecurity == Global.StreamSecurity)
+ if (node.StreamSecurity == AppConfig.StreamSecurity)
{
if (sni.IsNotEmpty())
{
@@ -479,7 +480,7 @@ public partial class CoreConfigV2rayService
{
authority = host.NullIfEmpty(),
serviceName = path,
- multiMode = node.HeaderType == Global.GrpcMultiMode,
+ multiMode = node.HeaderType == AppConfig.GrpcMultiMode,
idle_timeout = _config.GrpcItem.IdleTimeout,
health_check_timeout = _config.GrpcItem.HealthCheckTimeout,
permit_without_stream = _config.GrpcItem.PermitWithoutStream,
@@ -513,13 +514,13 @@ public partial class CoreConfigV2rayService
if (node.Path.IsNotEmpty())
{
streamSettings.udpmasks =
- [new() { type = "salamander", settings = new() { password = node.Path.TrimEx(), } }];
+ [new() { type = "salamander", settings = new() { password = node.Path.TrimSafe(), } }];
}
break;
default:
//tcp
- if (node.HeaderType == Global.TcpHeaderHttp)
+ if (node.HeaderType == AppConfig.TcpHeaderHttp)
{
TcpSettings4Ray tcpSettings = new()
{
@@ -530,7 +531,7 @@ public partial class CoreConfigV2rayService
};
//request Host
- var request = EmbedUtils.GetEmbedText(Global.V2raySampleHttpRequestFileName);
+ var request = EmbedUtils.GetEmbedText(AppConfig.V2raySampleHttpRequestFileName);
var arrHost = host.Split(',');
var host2 = string.Join(",".AppendQuotes(), arrHost);
request = request.Replace("$requestHost$", $"{host2.AppendQuotes()}");
@@ -557,7 +558,7 @@ public partial class CoreConfigV2rayService
return 0;
}
- private async Task GenGroupOutbound(ProfileItem node, V2rayConfig v2rayConfig, string baseTagName = Global.ProxyTag, bool ignoreOriginChain = false)
+ private async Task GenGroupOutbound(ProfileItem node, V2rayConfig v2rayConfig, string baseTagName = AppConfig.ProxyTag, bool ignoreOriginChain = false)
{
try
{
@@ -620,7 +621,7 @@ public partial class CoreConfigV2rayService
var fragmentOutbound = new Outbounds4Ray
{
protocol = "freedom",
- tag = $"frag-{Global.ProxyTag}",
+ tag = $"frag-{AppConfig.ProxyTag}",
settings = new()
{
fragment = new()
@@ -654,17 +655,17 @@ public partial class CoreConfigV2rayService
//current proxy
var outbound = v2rayConfig.outbounds.First();
- var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
//Previous proxy
var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
string? prevOutboundTag = null;
if (prevNode is not null
- && Global.XraySupportConfigType.Contains(prevNode.ConfigType))
+ && AppConfig.XraySupportConfigType.Contains(prevNode.ConfigType))
{
var prevOutbound = JsonUtils.Deserialize(txtOutbound);
await GenOutbound(prevNode, prevOutbound);
- prevOutboundTag = $"prev-{Global.ProxyTag}";
+ prevOutboundTag = $"prev-{AppConfig.ProxyTag}";
prevOutbound.tag = prevOutboundTag;
v2rayConfig.outbounds.Add(prevOutbound);
}
@@ -683,12 +684,12 @@ public partial class CoreConfigV2rayService
return 0;
}
- private async Task GenOutboundsListWithChain(List nodes, V2rayConfig v2rayConfig, string baseTagName = Global.ProxyTag)
+ private async Task GenOutboundsListWithChain(List nodes, V2rayConfig v2rayConfig, string baseTagName = AppConfig.ProxyTag)
{
try
{
// Get template and initialize list
- var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (txtOutbound.IsNullOrEmpty())
{
return 0;
@@ -731,7 +732,7 @@ public partial class CoreConfigV2rayService
string? prevTag = null;
var currentOutbound = JsonUtils.Deserialize(txtOutbound);
var nextOutbound = nextProxyCache.GetValueOrDefault(node.Subid, null);
- if (nextOutbound != null)
+ if (nextOutbound is not null)
{
nextOutbound = JsonUtils.DeepCopy(nextOutbound);
}
@@ -752,7 +753,7 @@ public partial class CoreConfigV2rayService
{
var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
if (prevNode is not null
- && Global.XraySupportConfigType.Contains(prevNode.ConfigType))
+ && AppConfig.XraySupportConfigType.Contains(prevNode.ConfigType))
{
var prevOutbound = JsonUtils.Deserialize(txtOutbound);
await GenOutbound(prevNode, prevOutbound);
@@ -778,7 +779,7 @@ public partial class CoreConfigV2rayService
}
// Merge results: first the main chain outbounds, then other outbounds, and finally utility outbounds
- if (baseTagName == Global.ProxyTag)
+ if (baseTagName == AppConfig.ProxyTag)
{
resultOutbounds.AddRange(prevOutbounds);
resultOutbounds.AddRange(v2rayConfig.outbounds);
@@ -814,7 +815,7 @@ public partial class CoreConfigV2rayService
{
try
{
- var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (!prevOutboundTag.IsNullOrEmpty())
{
@@ -827,9 +828,9 @@ public partial class CoreConfigV2rayService
// Next proxy
var nextNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.NextProfile);
if (nextNode is not null
- && Global.XraySupportConfigType.Contains(nextNode.ConfigType))
+ && AppConfig.XraySupportConfigType.Contains(nextNode.ConfigType))
{
- if (nextOutbound == null)
+ if (nextOutbound is null)
{
nextOutbound = JsonUtils.Deserialize(txtOutbound);
await GenOutbound(nextNode, nextOutbound);
@@ -851,13 +852,13 @@ public partial class CoreConfigV2rayService
return null;
}
- private async Task GenOutboundsList(List nodes, V2rayConfig v2rayConfig, string baseTagName = Global.ProxyTag)
+ private async Task GenOutboundsList(List nodes, V2rayConfig v2rayConfig, string baseTagName = AppConfig.ProxyTag)
{
var resultOutbounds = new List();
for (var i = 0; i < nodes.Count; i++)
{
var node = nodes[i];
- if (node == null)
+ if (node is null)
{
continue;
}
@@ -880,7 +881,7 @@ public partial class CoreConfigV2rayService
};
continue;
}
- var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (txtOutbound.IsNullOrEmpty())
{
break;
@@ -894,7 +895,7 @@ public partial class CoreConfigV2rayService
outbound.tag = baseTagName + (i + 1).ToString();
resultOutbounds.Add(outbound);
}
- if (baseTagName == Global.ProxyTag)
+ if (baseTagName == AppConfig.ProxyTag)
{
resultOutbounds.AddRange(v2rayConfig.outbounds);
v2rayConfig.outbounds = resultOutbounds;
@@ -906,7 +907,7 @@ public partial class CoreConfigV2rayService
return await Task.FromResult(0);
}
- private async Task GenChainOutboundsList(List nodes, V2rayConfig v2rayConfig, string baseTagName = Global.ProxyTag)
+ private async Task GenChainOutboundsList(List nodes, V2rayConfig v2rayConfig, string baseTagName = AppConfig.ProxyTag)
{
// Based on actual network flow instead of data packets
var nodesReverse = nodes.AsEnumerable().Reverse().ToList();
@@ -914,7 +915,7 @@ public partial class CoreConfigV2rayService
for (var i = 0; i < nodesReverse.Count; i++)
{
var node = nodesReverse[i];
- var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (txtOutbound.IsNullOrEmpty())
{
break;
@@ -947,7 +948,7 @@ public partial class CoreConfigV2rayService
resultOutbounds.Add(outbound);
}
- if (baseTagName == Global.ProxyTag)
+ if (baseTagName == AppConfig.ProxyTag)
{
resultOutbounds.AddRange(v2rayConfig.outbounds);
v2rayConfig.outbounds = resultOutbounds;
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayRoutingService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayRoutingService.cs
index 96984094..578b747d 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayRoutingService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayRoutingService.cs
@@ -6,12 +6,12 @@ public partial class CoreConfigV2rayService
{
try
{
- if (v2rayConfig.routing?.rules != null)
+ if (v2rayConfig.routing?.rules is not null)
{
v2rayConfig.routing.domainStrategy = _config.RoutingBasicItem.DomainStrategy;
var routing = await ConfigHandler.GetDefaultRouting(_config);
- if (routing != null)
+ if (routing is not null)
{
if (routing.DomainStrategy.IsNotEmpty())
{
@@ -47,7 +47,7 @@ public partial class CoreConfigV2rayService
{
try
{
- if (rule == null)
+ if (rule is null)
{
return 0;
}
@@ -95,7 +95,7 @@ public partial class CoreConfigV2rayService
{
it.domain.RemoveAt(k);
}
- it.domain[k] = it.domain[k].Replace(Global.RoutingRuleComma, ",");
+ it.domain[k] = it.domain[k].Replace(AppConfig.RoutingRuleComma, ",");
}
v2rayConfig.routing.rules.Add(it);
hasDomainIp = true;
@@ -123,7 +123,7 @@ public partial class CoreConfigV2rayService
if (rule.port.IsNotEmpty()
|| rule.protocol?.Count > 0
|| rule.inboundTag?.Count > 0
- || rule.network != null
+ || rule.network is not null
)
{
var it = JsonUtils.DeepCopy(rule);
@@ -141,21 +141,21 @@ public partial class CoreConfigV2rayService
private async Task GenRoutingUserRuleOutbound(string outboundTag, V2rayConfig v2rayConfig)
{
- if (Global.OutboundTags.Contains(outboundTag))
+ if (AppConfig.OutboundTags.Contains(outboundTag))
{
return outboundTag;
}
var node = await AppManager.Instance.GetProfileItemViaRemarks(outboundTag);
- if (node == null
- || (!Global.XraySupportConfigType.Contains(node.ConfigType)
+ if (node is null
+ || (!AppConfig.XraySupportConfigType.Contains(node.ConfigType)
&& !node.ConfigType.IsGroupType()))
{
- return Global.ProxyTag;
+ return AppConfig.ProxyTag;
}
- var tag = $"{node.IndexId}-{Global.ProxyTag}";
+ var tag = $"{node.IndexId}-{AppConfig.ProxyTag}";
if (v2rayConfig.outbounds.Any(p => p.tag == tag))
{
return tag;
@@ -168,10 +168,10 @@ public partial class CoreConfigV2rayService
{
return tag;
}
- return Global.ProxyTag;
+ return AppConfig.ProxyTag;
}
- var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
+ var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
var outbound = JsonUtils.Deserialize(txtOutbound);
await GenOutbound(node, outbound);
outbound.tag = tag;
diff --git a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayStatisticService.cs b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayStatisticService.cs
index b2ec37b4..e2fecbc4 100644
--- a/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayStatisticService.cs
+++ b/v2rayN/ServiceLib/Services/CoreConfig/V2ray/V2rayStatisticService.cs
@@ -26,10 +26,10 @@ public partial class CoreConfigV2rayService
Inbounds4Ray apiInbound = new();
Inboundsettings4Ray apiInboundSettings = new();
apiInbound.tag = tag;
- apiInbound.listen = Global.Loopback;
+ apiInbound.listen = AppConfig.Loopback;
apiInbound.port = AppManager.Instance.StatePort;
- apiInbound.protocol = Global.InboundAPIProtocol;
- apiInboundSettings.address = Global.Loopback;
+ apiInbound.protocol = AppConfig.InboundAPIProtocol;
+ apiInboundSettings.address = AppConfig.Loopback;
apiInbound.settings = apiInboundSettings;
v2rayConfig.inbounds.Add(apiInbound);
}
diff --git a/v2rayN/ServiceLib/Services/DownloadService.cs b/v2rayN/ServiceLib/Services/DownloadService.cs
index 77d3a7c1..24787bcc 100644
--- a/v2rayN/ServiceLib/Services/DownloadService.cs
+++ b/v2rayN/ServiceLib/Services/DownloadService.cs
@@ -13,14 +13,14 @@ public class DownloadService
private static readonly string _tag = "DownloadService";
- public async Task DownloadDataAsync(string url, WebProxy webProxy, int downloadTimeout, Func updateFunc)
+ public static async Task DownloadDataAsync(string url, WebProxy webProxy, int downloadTimeout, Func updateFunc)
{
try
{
var progress = new Progress();
progress.ProgressChanged += (sender, value) => updateFunc?.Invoke(false, $"{value}");
- await DownloaderHelper.Instance.DownloadDataAsync4Speed(webProxy,
+ await DownloaderHelper.DownloadDataAsync4Speed(webProxy,
url,
progress,
downloadTimeout);
@@ -28,7 +28,7 @@ public class DownloadService
catch (Exception ex)
{
await updateFunc?.Invoke(false, ex.Message);
- if (ex.InnerException != null)
+ if (ex.InnerException is not null)
{
await updateFunc?.Invoke(false, ex.InnerException.Message);
}
@@ -46,7 +46,7 @@ public class DownloadService
progress.ProgressChanged += (sender, value) => UpdateCompleted?.Invoke(this, new UpdateResult(value > 100, $"...{value}%"));
var webProxy = await GetWebProxy(blProxy);
- await DownloaderHelper.Instance.DownloadFileAsync(webProxy,
+ await DownloaderHelper.DownloadFileAsync(webProxy,
url,
fileName,
progress,
@@ -57,7 +57,7 @@ public class DownloadService
Logging.SaveLog(_tag, ex);
Error?.Invoke(this, new ErrorEventArgs(ex));
- if (ex.InnerException != null)
+ if (ex.InnerException is not null)
{
Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
}
@@ -66,22 +66,22 @@ public class DownloadService
public async Task UrlRedirectAsync(string url, bool blProxy)
{
- var webRequestHandler = new SocketsHttpHandler
+ using var webRequestHandler = new SocketsHttpHandler
{
AllowAutoRedirect = false,
Proxy = await GetWebProxy(blProxy)
};
- var client = new HttpClient(webRequestHandler);
+ using var client = new HttpClient(webRequestHandler);
+ using var response = await client.GetAsync(url);
- var response = await client.GetAsync(url);
if (response.StatusCode == HttpStatusCode.Redirect && response.Headers.Location is not null)
{
return response.Headers.Location.ToString();
}
else
{
- Error?.Invoke(this, new ErrorEventArgs(new Exception("StatusCode error: " + response.StatusCode)));
- Logging.SaveLog("StatusCode error: " + url);
+ Error?.Invoke(this, new ErrorEventArgs(new HttpRequestException($"StatusCode error: {response.StatusCode}", null, response.StatusCode)));
+ Logging.SaveLog($"StatusCode error: {url}");
return null;
}
}
@@ -100,7 +100,7 @@ public class DownloadService
{
Logging.SaveLog(_tag, ex);
Error?.Invoke(this, new ErrorEventArgs(ex));
- if (ex.InnerException != null)
+ if (ex.InnerException is not null)
{
Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
}
@@ -118,7 +118,7 @@ public class DownloadService
{
Logging.SaveLog(_tag, ex);
Error?.Invoke(this, new ErrorEventArgs(ex));
- if (ex.InnerException != null)
+ if (ex.InnerException is not null)
{
Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
}
@@ -139,7 +139,7 @@ public class DownloadService
var client = new HttpClient(new SocketsHttpHandler()
{
Proxy = webProxy,
- UseProxy = webProxy != null
+ UseProxy = webProxy is not null
});
if (userAgent.IsNullOrEmpty())
@@ -163,7 +163,7 @@ public class DownloadService
{
Logging.SaveLog(_tag, ex);
Error?.Invoke(this, new ErrorEventArgs(ex));
- if (ex.InnerException != null)
+ if (ex.InnerException is not null)
{
Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
}
@@ -185,14 +185,14 @@ public class DownloadService
{
userAgent = Utils.GetVersion(false);
}
- var result = await DownloaderHelper.Instance.DownloadStringAsync(webProxy, url, userAgent, timeout);
+ var result = await DownloaderHelper.DownloadStringAsync(webProxy, url, userAgent, timeout);
return result;
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
Error?.Invoke(this, new ErrorEventArgs(ex));
- if (ex.InnerException != null)
+ if (ex.InnerException is not null)
{
Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
}
@@ -200,22 +200,22 @@ public class DownloadService
return null;
}
- private async Task GetWebProxy(bool blProxy)
+ private static async Task GetWebProxy(bool blProxy)
{
if (!blProxy)
{
return null;
}
var port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks);
- if (await SocketCheck(Global.Loopback, port) == false)
+ if (await SocketCheck(AppConfig.Loopback, port) == false)
{
return null;
}
- return new WebProxy($"socks5://{Global.Loopback}:{port}");
+ return new WebProxy($"socks5://{AppConfig.Loopback}:{port}");
}
- private async Task SocketCheck(string ip, int port)
+ private static async Task SocketCheck(string ip, int port)
{
try
{
diff --git a/v2rayN/ServiceLib/Services/ProcessService.cs b/v2rayN/ServiceLib/Services/ProcessService.cs
index 0f7161e3..bc681756 100644
--- a/v2rayN/ServiceLib/Services/ProcessService.cs
+++ b/v2rayN/ServiceLib/Services/ProcessService.cs
@@ -39,7 +39,7 @@ public class ProcessService : IDisposable
EnableRaisingEvents = true
};
- if (environmentVars != null)
+ if (environmentVars is not null)
{
foreach (var kv in environmentVars)
{
diff --git a/v2rayN/ServiceLib/Services/SpeedtestService.cs b/v2rayN/ServiceLib/Services/SpeedtestService.cs
index 207f7dfc..420b9d28 100644
--- a/v2rayN/ServiceLib/Services/SpeedtestService.cs
+++ b/v2rayN/ServiceLib/Services/SpeedtestService.cs
@@ -7,6 +7,9 @@ public class SpeedtestService(Config config, Func updateF
private readonly Func? _updateFunc = updateFunc;
private static readonly ConcurrentBag _lstExitLoop = new();
+ private static readonly CompositeFormat _speedtestingTestFailedPart =
+ CompositeFormat.Parse(ResUI.SpeedtestingTestFailedPart);
+
public void RunLoop(ESpeedActionType actionType, List selecteds)
{
Task.Run(async () =>
@@ -128,7 +131,7 @@ public class SpeedtestService(Config config, Func updateF
var responseTime = await GetTcpingTime(it.Address, it.Port);
ProfileExManager.Instance.SetTestDelay(it.IndexId, responseTime);
- await UpdateFunc(it.IndexId, responseTime.ToString());
+ await UpdateFunc(it.IndexId, responseTime.ToString(CultureInfo.InvariantCulture));
}
catch (Exception ex)
{
@@ -143,7 +146,7 @@ public class SpeedtestService(Config config, Func updateF
{
if (pageSize <= 0)
{
- pageSize = lstSelected.Count < Global.SpeedTestPageSize ? lstSelected.Count : Global.SpeedTestPageSize;
+ pageSize = lstSelected.Count < AppConfig.SpeedTestPageSize ? lstSelected.Count : AppConfig.SpeedTestPageSize;
}
var lstTest = GetTestBatchItem(lstSelected, pageSize);
@@ -168,7 +171,7 @@ public class SpeedtestService(Config config, Func updateF
return;
}
- await UpdateFunc("", string.Format(ResUI.SpeedtestingTestFailedPart, lstFailed.Count));
+ await UpdateFunc("", string.Format(CultureInfo.InvariantCulture, _speedtestingTestFailedPart, lstFailed.Count));
if (pageSizeNext > _config.SpeedTestItem.MixedConcurrencyCount)
{
@@ -220,7 +223,7 @@ public class SpeedtestService(Config config, Func updateF
}
finally
{
- if (processService != null)
+ if (processService is not null)
{
await processService?.StopAsync();
}
@@ -231,7 +234,6 @@ public class SpeedtestService(Config config, Func updateF
private async Task RunMixedTestAsync(List selecteds, int concurrencyCount, bool blSpeedTest, string exitLoopKey)
{
using var concurrencySemaphore = new SemaphoreSlim(concurrencyCount);
- var downloadHandle = new DownloadService();
List tasks = new();
foreach (var it in selecteds)
{
@@ -267,7 +269,7 @@ public class SpeedtestService(Config config, Func updateF
if (delay > 0)
{
- await DoSpeedTest(downloadHandle, it);
+ await DoSpeedTest(it);
}
else
{
@@ -281,7 +283,7 @@ public class SpeedtestService(Config config, Func updateF
}
finally
{
- if (processService != null)
+ if (processService is not null)
{
await processService?.StopAsync();
}
@@ -294,25 +296,24 @@ public class SpeedtestService(Config config, Func updateF
private async Task DoRealPing(ServerTestItem it)
{
- var webProxy = new WebProxy($"socks5://{Global.Loopback}:{it.Port}");
+ var webProxy = new WebProxy($"socks5://{AppConfig.Loopback}:{it.Port}");
var responseTime = await ConnectionHandler.GetRealPingTime(_config.SpeedTestItem.SpeedPingTestUrl, webProxy, 10);
ProfileExManager.Instance.SetTestDelay(it.IndexId, responseTime);
- await UpdateFunc(it.IndexId, responseTime.ToString());
+ await UpdateFunc(it.IndexId, responseTime.ToString(CultureInfo.InvariantCulture));
return responseTime;
}
- private async Task DoSpeedTest(DownloadService downloadHandle, ServerTestItem it)
+ private async Task DoSpeedTest(ServerTestItem it)
{
await UpdateFunc(it.IndexId, "", ResUI.Speedtesting);
- var webProxy = new WebProxy($"socks5://{Global.Loopback}:{it.Port}");
+ var webProxy = new WebProxy($"socks5://{AppConfig.Loopback}:{it.Port}");
var url = _config.SpeedTestItem.SpeedTestUrl;
var timeout = _config.SpeedTestItem.SpeedTestTimeout;
- await downloadHandle.DownloadDataAsync(url, webProxy, timeout, async (success, msg) =>
+ await DownloadService.DownloadDataAsync(url, webProxy, timeout, async (success, msg) =>
{
- decimal.TryParse(msg, out var dec);
- if (dec > 0)
+ if (decimal.TryParse(msg, out var dec) && dec > 0)
{
ProfileExManager.Instance.SetTestSpeed(it.IndexId, dec);
}
@@ -320,7 +321,7 @@ public class SpeedtestService(Config config, Func updateF
});
}
- private async Task GetTcpingTime(string url, int port)
+ private static async Task GetTcpingTime(string url, int port)
{
var responseTime = -1;
@@ -350,11 +351,11 @@ public class SpeedtestService(Config config, Func updateF
return responseTime;
}
- private List> GetTestBatchItem(List lstSelected, int pageSize)
+ private static List> GetTestBatchItem(List lstSelected, int pageSize)
{
List> lstTest = new();
- var lst1 = lstSelected.Where(t => Global.XraySupportConfigType.Contains(t.ConfigType)).ToList();
- var lst2 = lstSelected.Where(t => Global.SingboxOnlyConfigType.Contains(t.ConfigType)).ToList();
+ var lst1 = lstSelected.Where(t => AppConfig.XraySupportConfigType.Contains(t.ConfigType)).ToList();
+ var lst2 = lstSelected.Where(t => AppConfig.SingboxOnlyConfigType.Contains(t.ConfigType)).ToList();
for (var num = 0; num < (int)Math.Ceiling(lst1.Count * 1.0 / pageSize); num++)
{
diff --git a/v2rayN/ServiceLib/Services/Statistics/StatisticsSingboxService.cs b/v2rayN/ServiceLib/Services/Statistics/StatisticsSingboxService.cs
index 7d663322..8669170d 100644
--- a/v2rayN/ServiceLib/Services/Statistics/StatisticsSingboxService.cs
+++ b/v2rayN/ServiceLib/Services/Statistics/StatisticsSingboxService.cs
@@ -8,7 +8,7 @@ public class StatisticsSingboxService
private bool _exitFlag;
private ClientWebSocket? webSocket;
private readonly Func? _updateFunc;
- private string Url => $"ws://{Global.Loopback}:{AppManager.Instance.StatePort2}/traffic";
+ private string Url => $"ws://{AppConfig.Loopback}:{AppManager.Instance.StatePort2}/traffic";
private static readonly string _tag = "StatisticsSingboxService";
public StatisticsSingboxService(Config config, Func updateFunc)
@@ -26,7 +26,7 @@ public class StatisticsSingboxService
try
{
- if (webSocket == null)
+ if (webSocket is null)
{
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(Url), CancellationToken.None);
@@ -40,11 +40,8 @@ public class StatisticsSingboxService
try
{
_exitFlag = true;
- if (webSocket != null)
- {
- webSocket.Abort();
- webSocket = null;
- }
+ webSocket?.Abort();
+ webSocket = null;
}
catch (Exception ex)
{
@@ -65,7 +62,7 @@ public class StatisticsSingboxService
{
continue;
}
- if (webSocket != null)
+ if (webSocket is not null)
{
if (webSocket.State is WebSocketState.Aborted or WebSocketState.Closed)
{
@@ -112,7 +109,7 @@ public class StatisticsSingboxService
try
{
var trafficItem = JsonUtils.Deserialize(source);
- if (trafficItem != null)
+ if (trafficItem is not null)
{
up = trafficItem.Up;
down = trafficItem.Down;
diff --git a/v2rayN/ServiceLib/Services/Statistics/StatisticsXrayService.cs b/v2rayN/ServiceLib/Services/Statistics/StatisticsXrayService.cs
index a64fed00..7d35efea 100644
--- a/v2rayN/ServiceLib/Services/Statistics/StatisticsXrayService.cs
+++ b/v2rayN/ServiceLib/Services/Statistics/StatisticsXrayService.cs
@@ -7,7 +7,7 @@ public class StatisticsXrayService
private readonly Config _config;
private bool _exitFlag;
private readonly Func? _updateFunc;
- private string Url => $"{Global.HttpProtocol}{Global.Loopback}:{AppManager.Instance.StatePort}/debug/vars";
+ private string Url => $"{AppConfig.HttpProtocol}{AppConfig.Loopback}:{AppManager.Instance.StatePort}/debug/vars";
public StatisticsXrayService(Config config, Func updateFunc)
{
@@ -36,7 +36,7 @@ public class StatisticsXrayService
}
var result = await HttpClientHelper.Instance.TryGetAsync(Url);
- if (result != null)
+ if (result is not null)
{
var server = ParseOutput(result) ?? new ServerSpeedItem();
await _updateFunc?.Invoke(server);
@@ -54,7 +54,7 @@ public class StatisticsXrayService
try
{
var source = JsonUtils.Deserialize(result);
- if (source?.stats?.outbound == null)
+ if (source?.stats?.outbound is null)
{
return null;
}
@@ -63,18 +63,18 @@ public class StatisticsXrayService
foreach (var key in source.stats.outbound.Keys.Cast())
{
var value = source.stats.outbound[key];
- if (value == null)
+ if (value is null)
{
continue;
}
var state = JsonUtils.Deserialize(value.ToString());
- if (key.StartsWith(Global.ProxyTag))
+ if (key.StartsWith(AppConfig.ProxyTag))
{
server.ProxyUp += state.uplink / linkBase;
server.ProxyDown += state.downlink / linkBase;
}
- else if (key == Global.DirectTag)
+ else if (key == AppConfig.DirectTag)
{
server.DirectUp = state.uplink / linkBase;
server.DirectDown = state.downlink / linkBase;
diff --git a/v2rayN/ServiceLib/Services/UpdateService.cs b/v2rayN/ServiceLib/Services/UpdateService.cs
index d368108c..39ea39d6 100644
--- a/v2rayN/ServiceLib/Services/UpdateService.cs
+++ b/v2rayN/ServiceLib/Services/UpdateService.cs
@@ -136,7 +136,7 @@ public class UpdateService(Config config, Func updateFunc)
if (preRelease)
{
var url = coreInfo?.ReleaseApiUrl;
- var result = await downloadHandle.TryDownloadString(url, true, Global.AppName);
+ var result = await downloadHandle.TryDownloadString(url, true, AppConfig.AppName);
if (result.IsNullOrEmpty())
{
return new UpdateResult(false, "");
@@ -151,7 +151,7 @@ public class UpdateService(Config config, Func updateFunc)
{
var url = Path.Combine(coreInfo.Url, "latest");
var lastUrl = await downloadHandle.UrlRedirectAsync(url, true);
- if (lastUrl == null)
+ if (lastUrl is null)
{
return new UpdateResult(false, "");
}
@@ -327,7 +327,7 @@ public class UpdateService(Config config, Func updateFunc)
private async Task UpdateGeoFiles()
{
var geoUrl = string.IsNullOrEmpty(_config?.ConstItem.GeoSourceUrl)
- ? Global.GeoUrl
+ ? AppConfig.GeoUrl
: _config.ConstItem.GeoSourceUrl;
List files = ["geosite", "geoip"];
@@ -349,7 +349,7 @@ public class UpdateService(Config config, Func updateFunc)
return;
}
- foreach (var url in Global.OtherGeoUrls)
+ foreach (var url in AppConfig.OtherGeoUrls)
{
var fileName = Path.GetFileName(url);
var targetPath = Utils.GetBinPath($"{fileName}");
@@ -415,7 +415,7 @@ public class UpdateService(Config config, Func updateFunc)
private async Task UpdateSrsFile(string type, string srsName)
{
var srsUrl = string.IsNullOrEmpty(_config.ConstItem.SrsSourceUrl)
- ? Global.SingboxRulesetUrl
+ ? AppConfig.SingboxRulesetUrl
: _config.ConstItem.SrsSourceUrl;
var fileName = $"{type}-{srsName}.srs";
diff --git a/v2rayN/ServiceLib/Services/WindowsJobService.cs b/v2rayN/ServiceLib/Services/WindowsJobService.cs
index ffd4a36a..7aeec4e3 100644
--- a/v2rayN/ServiceLib/Services/WindowsJobService.cs
+++ b/v2rayN/ServiceLib/Services/WindowsJobService.cs
@@ -3,7 +3,7 @@ namespace ServiceLib.Services;
///
/// http://stackoverflow.com/questions/6266820/working-example-of-createjobobject-setinformationjobobject-pinvoke-in-net
///
-public sealed class WindowsJobService : IDisposable
+public sealed partial class WindowsJobService : IDisposable
{
private nint handle = nint.Zero;
@@ -99,18 +99,20 @@ public sealed class WindowsJobService : IDisposable
#region Interop
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- private static extern nint CreateJobObject(nint a, string? lpName);
+ [LibraryImport("kernel32.dll", EntryPoint = "CreateJobObjectW", StringMarshalling = StringMarshalling.Utf16)]
+ private static partial nint CreateJobObject(nint a, string? lpName);
- [DllImport("kernel32.dll", SetLastError = true)]
- private static extern bool SetInformationJobObject(nint hJob, JobObjectInfoType infoType, nint lpJobObjectInfo, uint cbJobObjectInfoLength);
-
- [DllImport("kernel32.dll", SetLastError = true)]
- private static extern bool AssignProcessToJobObject(nint job, nint process);
-
- [DllImport("kernel32.dll", SetLastError = true)]
+ [LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool CloseHandle(nint hObject);
+ private static partial bool SetInformationJobObject(nint hJob, JobObjectInfoType infoType, nint lpJobObjectInfo, uint cbJobObjectInfoLength);
+
+ [LibraryImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool AssignProcessToJobObject(nint job, nint process);
+
+ [LibraryImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool CloseHandle(nint hObject);
#endregion Interop
}
diff --git a/v2rayN/ServiceLib/ViewModels/AddGroupServerViewModel.cs b/v2rayN/ServiceLib/ViewModels/AddGroupServerViewModel.cs
index 5b0778a5..8b7a8c1d 100644
--- a/v2rayN/ServiceLib/ViewModels/AddGroupServerViewModel.cs
+++ b/v2rayN/ServiceLib/ViewModels/AddGroupServerViewModel.cs
@@ -39,12 +39,12 @@ public class AddGroupServerViewModel : MyReactiveObject
public AddGroupServerViewModel(ProfileItem profileItem, Func>? updateView)
{
- _config = AppManager.Instance.Config;
- _updateView = updateView;
+ Config = AppManager.Instance.Config;
+ UpdateView = updateView;
var canEditRemove = this.WhenAnyValue(
x => x.SelectedChild,
- SelectedChild => SelectedChild != null && !SelectedChild.Remarks.IsNullOrEmpty());
+ SelectedChild => SelectedChild is not null && !SelectedChild.Remarks.IsNullOrEmpty());
RemoveCmd = ReactiveCommand.CreateFromTask(async () =>
{
@@ -97,13 +97,13 @@ public class AddGroupServerViewModel : MyReactiveObject
Filter = profileGroup?.Filter;
var childItemMulti = ProfileGroupItemManager.Instance.GetOrCreateAndMarkDirty(SelectedSource?.IndexId);
- if (childItemMulti != null)
+ if (childItemMulti is not null)
{
var childIndexIds = Utils.String2List(childItemMulti.ChildItems) ?? [];
foreach (var item in childIndexIds)
{
var child = await AppManager.Instance.GetProfileItem(item);
- if (child == null)
+ if (child is null)
{
continue;
}
@@ -114,14 +114,14 @@ public class AddGroupServerViewModel : MyReactiveObject
public async Task ChildRemoveAsync()
{
- if (SelectedChild == null || SelectedChild.IndexId.IsNullOrEmpty())
+ if (SelectedChild is null || SelectedChild.IndexId.IsNullOrEmpty())
{
NoticeManager.Instance.Enqueue(ResUI.PleaseSelectServer);
return;
}
foreach (var it in SelectedChildren ?? [SelectedChild])
{
- if (it != null)
+ if (it is not null)
{
ChildItemsObs.Remove(it);
}
@@ -131,7 +131,7 @@ public class AddGroupServerViewModel : MyReactiveObject
public async Task MoveServer(EMove eMove)
{
- if (SelectedChild == null || SelectedChild.IndexId.IsNullOrEmpty())
+ if (SelectedChild is null || SelectedChild.IndexId.IsNullOrEmpty())
{
NoticeManager.Instance.Enqueue(ResUI.PleaseSelectServer);
return;
@@ -236,10 +236,10 @@ public class AddGroupServerViewModel : MyReactiveObject
return;
}
- if (await ConfigHandler.AddGroupServerCommon(_config, SelectedSource, profileGroup, true) == 0)
+ if (await ConfigHandler.AddGroupServerCommon(SelectedSource, profileGroup, true) == 0)
{
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
- _updateView?.Invoke(EViewAction.CloseWindow, null);
+ UpdateView?.Invoke(EViewAction.CloseWindow, null);
}
else
{
diff --git a/v2rayN/ServiceLib/ViewModels/AddServer2ViewModel.cs b/v2rayN/ServiceLib/ViewModels/AddServer2ViewModel.cs
index cbc97642..4e7312ae 100644
--- a/v2rayN/ServiceLib/ViewModels/AddServer2ViewModel.cs
+++ b/v2rayN/ServiceLib/ViewModels/AddServer2ViewModel.cs
@@ -15,12 +15,12 @@ public class AddServer2ViewModel : MyReactiveObject
public AddServer2ViewModel(ProfileItem profileItem, Func>? updateView)
{
- _config = AppManager.Instance.Config;
- _updateView = updateView;
+ Config = AppManager.Instance.Config;
+ UpdateView = updateView;
BrowseServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
- _updateView?.Invoke(EViewAction.BrowseServer, null);
+ UpdateView?.Invoke(EViewAction.BrowseServer, null);
await Task.CompletedTask;
});
EditServerCmd = ReactiveCommand.CreateFromTask(async () =>
@@ -52,10 +52,10 @@ public class AddServer2ViewModel : MyReactiveObject
}
SelectedSource.CoreType = CoreType.IsNullOrEmpty() ? null : (ECoreType)Enum.Parse(typeof(ECoreType), CoreType);
- if (await ConfigHandler.EditCustomServer(_config, SelectedSource) == 0)
+ if (await ConfigHandler.EditCustomServer(SelectedSource) == 0)
{
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
- _updateView?.Invoke(EViewAction.CloseWindow, null);
+ UpdateView?.Invoke(EViewAction.CloseWindow, null);
}
else
{
@@ -73,7 +73,7 @@ public class AddServer2ViewModel : MyReactiveObject
var item = await AppManager.Instance.GetProfileItem(SelectedSource.IndexId);
item ??= SelectedSource;
item.Address = fileName;
- if (await ConfigHandler.AddCustomServer(_config, item, false) == 0)
+ if (await ConfigHandler.AddCustomServer(Config, item, false) == 0)
{
NoticeManager.Instance.Enqueue(ResUI.SuccessfullyImportedCustomServer);
if (item.IndexId.IsNotEmpty())
diff --git a/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs b/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs
index 775274d7..a277ca4d 100644
--- a/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs
+++ b/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs
@@ -23,8 +23,8 @@ public class AddServerViewModel : MyReactiveObject
public AddServerViewModel(ProfileItem profileItem, Func>? updateView)
{
- _config = AppManager.Instance.Config;
- _updateView = updateView;
+ Config = AppManager.Instance.Config;
+ UpdateView = updateView;
FetchCertCmd = ReactiveCommand.CreateFromTask(async () =>
{
@@ -50,8 +50,8 @@ public class AddServerViewModel : MyReactiveObject
if (profileItem.IndexId.IsNullOrEmpty())
{
- profileItem.Network = Global.DefaultNetwork;
- profileItem.HeaderType = Global.None;
+ profileItem.Network = AppConfig.DefaultNetwork;
+ profileItem.HeaderType = AppConfig.None;
profileItem.RequestHost = "";
profileItem.StreamSecurity = "";
SelectedSource = profileItem;
@@ -80,7 +80,7 @@ public class AddServerViewModel : MyReactiveObject
}
var port = SelectedSource.Port.ToString();
if (port.IsNullOrEmpty() || !Utils.IsNumeric(port)
- || SelectedSource.Port <= 0 || SelectedSource.Port >= Global.MaxPort)
+ || SelectedSource.Port <= 0 || SelectedSource.Port >= AppConfig.MaxPort)
{
NoticeManager.Instance.Enqueue(ResUI.FillCorrectServerPort);
return;
@@ -110,10 +110,10 @@ public class AddServerViewModel : MyReactiveObject
SelectedSource.Cert = Cert.IsNullOrEmpty() ? string.Empty : Cert;
SelectedSource.CertSha = CertSha.IsNullOrEmpty() ? string.Empty : CertSha;
- if (await ConfigHandler.AddServer(_config, SelectedSource) == 0)
+ if (await ConfigHandler.AddServer(Config, SelectedSource) == 0)
{
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
- _updateView?.Invoke(EViewAction.CloseWindow, null);
+ UpdateView?.Invoke(EViewAction.CloseWindow, null);
}
else
{
@@ -156,7 +156,7 @@ public class AddServerViewModel : MyReactiveObject
private async Task FetchCert()
{
- if (SelectedSource.StreamSecurity != Global.StreamSecurity)
+ if (SelectedSource.StreamSecurity != AppConfig.StreamSecurity)
{
return;
}
@@ -186,7 +186,7 @@ public class AddServerViewModel : MyReactiveObject
private async Task FetchCertChain()
{
- if (SelectedSource.StreamSecurity != Global.StreamSecurity)
+ if (SelectedSource.StreamSecurity != AppConfig.StreamSecurity)
{
return;
}
diff --git a/v2rayN/ServiceLib/ViewModels/BackupAndRestoreViewModel.cs b/v2rayN/ServiceLib/ViewModels/BackupAndRestoreViewModel.cs
index dbe3b24d..7128955f 100644
--- a/v2rayN/ServiceLib/ViewModels/BackupAndRestoreViewModel.cs
+++ b/v2rayN/ServiceLib/ViewModels/BackupAndRestoreViewModel.cs
@@ -17,8 +17,8 @@ public class BackupAndRestoreViewModel : MyReactiveObject
public BackupAndRestoreViewModel(Func>? updateView)
{
- _config = AppManager.Instance.Config;
- _updateView = updateView;
+ Config = AppManager.Instance.Config;
+ UpdateView = updateView;
WebDavCheckCmd = ReactiveCommand.CreateFromTask(async () =>
{
@@ -33,7 +33,7 @@ public class BackupAndRestoreViewModel : MyReactiveObject
await RemoteRestore();
});
- SelectedSource = JsonUtils.DeepCopy(_config.WebDavItem);
+ SelectedSource = JsonUtils.DeepCopy(Config.WebDavItem);
}
private void DisplayOperationMsg(string msg = "")
@@ -44,8 +44,8 @@ public class BackupAndRestoreViewModel : MyReactiveObject
private async Task WebDavCheck()
{
DisplayOperationMsg();
- _config.WebDavItem = SelectedSource;
- _ = await ConfigHandler.SaveConfig(_config);
+ Config.WebDavItem = SelectedSource;
+ _ = await ConfigHandler.SaveConfig(Config);
var result = await WebDavManager.Instance.CheckConnection();
if (result)
@@ -145,7 +145,7 @@ public class BackupAndRestoreViewModel : MyReactiveObject
{
if (Utils.UpgradeAppExists(out var upgradeFileName))
{
- _ = ProcUtils.ProcessStart(upgradeFileName, Global.RebootAs, Utils.StartupPath());
+ _ = ProcUtils.ProcessStart(upgradeFileName, AppConfig.RebootAs, Utils.StartupPath());
}
}
AppManager.Instance.Shutdown(true);
diff --git a/v2rayN/ServiceLib/ViewModels/CheckUpdateViewModel.cs b/v2rayN/ServiceLib/ViewModels/CheckUpdateViewModel.cs
index 7bcb36ea..b43f5494 100644
--- a/v2rayN/ServiceLib/ViewModels/CheckUpdateViewModel.cs
+++ b/v2rayN/ServiceLib/ViewModels/CheckUpdateViewModel.cs
@@ -13,22 +13,22 @@ public class CheckUpdateViewModel : MyReactiveObject
public CheckUpdateViewModel(Func>? updateView)
{
- _config = AppManager.Instance.Config;
- _updateView = updateView;
+ Config = AppManager.Instance.Config;
+ base.UpdateView = updateView;
CheckUpdateCmd = ReactiveCommand.CreateFromTask(CheckUpdate);
CheckUpdateCmd.ThrownExceptions.Subscribe(ex =>
{
Logging.SaveLog(_tag, ex);
- _ = UpdateView(_v2rayN, ex.Message);
+ _ = UpdateViewAsync(_v2rayN, ex.Message);
});
- EnableCheckPreReleaseUpdate = _config.CheckUpdateItem.CheckPreReleaseUpdate;
+ EnableCheckPreReleaseUpdate = Config.CheckUpdateItem.CheckPreReleaseUpdate;
this.WhenAnyValue(
x => x.EnableCheckPreReleaseUpdate,
y => y == true)
- .Subscribe(c => _config.CheckUpdateItem.CheckPreReleaseUpdate = EnableCheckPreReleaseUpdate);
+ .Subscribe(c => Config.CheckUpdateItem.CheckPreReleaseUpdate = EnableCheckPreReleaseUpdate);
RefreshCheckUpdateItems();
}
@@ -65,7 +65,7 @@ public class CheckUpdateViewModel : MyReactiveObject
return new()
{
- IsSelected = _config.CheckUpdateItem.SelectedCoreTypes?.Contains(coreType) ?? true,
+ IsSelected = Config.CheckUpdateItem.SelectedCoreTypes?.Contains(coreType) ?? true,
CoreType = coreType,
Remarks = ResUI.menuCheckUpdate,
};
@@ -73,8 +73,8 @@ public class CheckUpdateViewModel : MyReactiveObject
private async Task SaveSelectedCoreTypes()
{
- _config.CheckUpdateItem.SelectedCoreTypes = CheckUpdateModels.Where(t => t.IsSelected == true).Select(t => t.CoreType ?? "").ToList();
- await ConfigHandler.SaveConfig(_config);
+ Config.CheckUpdateItem.SelectedCoreTypes = CheckUpdateModels.Where(t => t.IsSelected == true).Select(t => t.CoreType ?? "").ToList();
+ await ConfigHandler.SaveConfig(Config);
}
private async Task CheckUpdate()
@@ -97,7 +97,7 @@ public class CheckUpdateViewModel : MyReactiveObject
continue;
}
- await UpdateView(item.CoreType, "...");
+ await UpdateViewAsync(item.CoreType, "...");
if (item.CoreType == _geo)
{
await CheckUpdateGeo();
@@ -106,7 +106,7 @@ public class CheckUpdateViewModel : MyReactiveObject
{
if (Utils.IsPackagedInstall())
{
- await UpdateView(_v2rayN, "Not Support");
+ await UpdateViewAsync(_v2rayN, "Not Support");
continue;
}
await CheckUpdateN(EnableCheckPreReleaseUpdate);
@@ -127,7 +127,7 @@ public class CheckUpdateViewModel : MyReactiveObject
private void UpdatedPlusPlus(string coreType, string fileName)
{
var item = _lstUpdated.FirstOrDefault(x => x.CoreType == coreType);
- if (item == null)
+ if (item is null)
{
return;
}
@@ -142,13 +142,13 @@ public class CheckUpdateViewModel : MyReactiveObject
{
async Task _updateUI(bool success, string msg)
{
- await UpdateView(_geo, msg);
+ await UpdateViewAsync(_geo, msg);
if (success)
{
UpdatedPlusPlus(_geo, "");
}
}
- await new UpdateService(_config, _updateUI).UpdateGeoFileAll()
+ await new UpdateService(Config, _updateUI).UpdateGeoFileAll()
.ContinueWith(t => UpdatedPlusPlus(_geo, ""));
}
@@ -156,14 +156,14 @@ public class CheckUpdateViewModel : MyReactiveObject
{
async Task _updateUI(bool success, string msg)
{
- await UpdateView(_v2rayN, msg);
+ await UpdateViewAsync(_v2rayN, msg);
if (success)
{
- await UpdateView(_v2rayN, ResUI.OperationSuccess);
+ await UpdateViewAsync(_v2rayN, ResUI.OperationSuccess);
UpdatedPlusPlus(_v2rayN, msg);
}
}
- await new UpdateService(_config, _updateUI).CheckUpdateGuiN(preRelease)
+ await new UpdateService(Config, _updateUI).CheckUpdateGuiN(preRelease)
.ContinueWith(t => UpdatedPlusPlus(_v2rayN, ""));
}
@@ -171,16 +171,16 @@ public class CheckUpdateViewModel : MyReactiveObject
{
async Task _updateUI(bool success, string msg)
{
- await UpdateView(model.CoreType, msg);
+ await UpdateViewAsync(model.CoreType, msg);
if (success)
{
- await UpdateView(model.CoreType, ResUI.MsgUpdateV2rayCoreSuccessfullyMore);
+ await UpdateViewAsync(model.CoreType, ResUI.MsgUpdateV2rayCoreSuccessfullyMore);
UpdatedPlusPlus(model.CoreType, msg);
}
}
var type = (ECoreType)Enum.Parse(typeof(ECoreType), model.CoreType);
- await new UpdateService(_config, _updateUI).CheckUpdateCore(type, preRelease)
+ await new UpdateService(Config, _updateUI).CheckUpdateCore(type, preRelease)
.ContinueWith(t => UpdatedPlusPlus(model.CoreType, ""));
}
@@ -235,7 +235,7 @@ public class CheckUpdateViewModel : MyReactiveObject
}
if (!Utils.UpgradeAppExists(out var upgradeFileName))
{
- await UpdateView(_v2rayN, ResUI.UpgradeAppNotExistTip);
+ await UpdateViewAsync(_v2rayN, ResUI.UpgradeAppNotExistTip);
NoticeManager.Instance.SendMessageAndEnqueue(ResUI.UpgradeAppNotExistTip);
Logging.SaveLog("UpgradeApp does not exist");
return;
@@ -249,7 +249,7 @@ public class CheckUpdateViewModel : MyReactiveObject
}
catch (Exception ex)
{
- await UpdateView(_v2rayN, ex.Message);
+ await UpdateViewAsync(_v2rayN, ex.Message);
}
}
@@ -300,7 +300,7 @@ public class CheckUpdateViewModel : MyReactiveObject
}
}
- await UpdateView(item.CoreType, ResUI.MsgUpdateV2rayCoreSuccessfully);
+ await UpdateViewAsync(item.CoreType, ResUI.MsgUpdateV2rayCoreSuccessfully);
if (File.Exists(fileName))
{
@@ -309,7 +309,7 @@ public class CheckUpdateViewModel : MyReactiveObject
}
}
- private async Task UpdateView(string coreType, string msg)
+ private async Task UpdateViewAsync(string coreType, string msg)
{
var item = new CheckUpdateModel()
{
@@ -328,7 +328,7 @@ public class CheckUpdateViewModel : MyReactiveObject
public async Task UpdateViewResult(CheckUpdateModel model)
{
var found = CheckUpdateModels.FirstOrDefault(t => t.CoreType == model.CoreType);
- if (found == null)
+ if (found is null)
{
return;
}
diff --git a/v2rayN/ServiceLib/ViewModels/ClashConnectionsViewModel.cs b/v2rayN/ServiceLib/ViewModels/ClashConnectionsViewModel.cs
index 48500f3e..0dde17e1 100644
--- a/v2rayN/ServiceLib/ViewModels/ClashConnectionsViewModel.cs
+++ b/v2rayN/ServiceLib/ViewModels/ClashConnectionsViewModel.cs
@@ -18,18 +18,18 @@ public class ClashConnectionsViewModel : MyReactiveObject
public ClashConnectionsViewModel(Func