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>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; - AutoRefresh = _config.ClashUIItem.ConnectionsAutoRefresh; + Config = AppManager.Instance.Config; + UpdateView = updateView; + AutoRefresh = Config.ClashUIItem.ConnectionsAutoRefresh; var canEditRemove = this.WhenAnyValue( x => x.SelectedSource, - selectedSource => selectedSource != null && selectedSource.Id.IsNotEmpty()); + selectedSource => selectedSource is not null && selectedSource.Id.IsNotEmpty()); this.WhenAnyValue( x => x.AutoRefresh, y => y == true) - .Subscribe(c => { _config.ClashUIItem.ConnectionsAutoRefresh = AutoRefresh; }); + .Subscribe(c => { Config.ClashUIItem.ConnectionsAutoRefresh = AutoRefresh; }); ConnectionCloseCmd = ReactiveCommand.CreateFromTask(async () => { await ClashConnectionClose(false); @@ -51,7 +51,7 @@ public class ClashConnectionsViewModel : MyReactiveObject private async Task GetClashConnections() { var ret = await ClashApiManager.Instance.GetClashConnectionsAsync(); - if (ret == null) + if (ret is null) { return; } @@ -133,12 +133,12 @@ public class ClashConnectionsViewModel : MyReactiveObject continue; } - if (_config.ClashUIItem.ConnectionsRefreshInterval <= 0) + if (Config.ClashUIItem.ConnectionsRefreshInterval <= 0) { continue; } - if (numOfExecuted % _config.ClashUIItem.ConnectionsRefreshInterval != 0) + if (numOfExecuted % Config.ClashUIItem.ConnectionsRefreshInterval != 0) { continue; } diff --git a/v2rayN/ServiceLib/ViewModels/ClashProxiesViewModel.cs b/v2rayN/ServiceLib/ViewModels/ClashProxiesViewModel.cs index 6628e11d..0acb9aa1 100644 --- a/v2rayN/ServiceLib/ViewModels/ClashProxiesViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/ClashProxiesViewModel.cs @@ -35,8 +35,8 @@ public class ClashProxiesViewModel : MyReactiveObject public ClashProxiesViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; ProxiesReloadCmd = ReactiveCommand.CreateFromTask(async () => { @@ -58,15 +58,15 @@ public class ClashProxiesViewModel : MyReactiveObject SelectedGroup = new(); SelectedDetail = new(); - AutoRefresh = _config.ClashUIItem.ProxiesAutoRefresh; - SortingSelected = _config.ClashUIItem.ProxiesSorting; - RuleModeSelected = (int)_config.ClashUIItem.RuleMode; + AutoRefresh = Config.ClashUIItem.ProxiesAutoRefresh; + SortingSelected = Config.ClashUIItem.ProxiesSorting; + RuleModeSelected = (int)Config.ClashUIItem.RuleMode; #region WhenAnyValue && ReactiveCommand this.WhenAnyValue( x => x.SelectedGroup, - y => y != null && y.Name.IsNotEmpty()) + y => y is not null && y.Name.IsNotEmpty()) .Subscribe(c => RefreshProxyDetails(c)); this.WhenAnyValue( @@ -82,7 +82,7 @@ public class ClashProxiesViewModel : MyReactiveObject this.WhenAnyValue( x => x.AutoRefresh, y => y == true) - .Subscribe(c => { _config.ClashUIItem.ProxiesAutoRefresh = AutoRefresh; }); + .Subscribe(c => { Config.ClashUIItem.ProxiesAutoRefresh = AutoRefresh; }); #endregion WhenAnyValue && ReactiveCommand @@ -109,7 +109,7 @@ public class ClashProxiesViewModel : MyReactiveObject { return; } - if (_config.ClashUIItem.RuleMode == (ERuleMode)RuleModeSelected) + if (Config.ClashUIItem.RuleMode == (ERuleMode)RuleModeSelected) { return; } @@ -118,7 +118,7 @@ public class ClashProxiesViewModel : MyReactiveObject public async Task SetRuleModeCheck(ERuleMode mode) { - if (_config.ClashUIItem.RuleMode == mode) + if (Config.ClashUIItem.RuleMode == mode) { return; } @@ -131,9 +131,9 @@ public class ClashProxiesViewModel : MyReactiveObject { return; } - if (SortingSelected != _config.ClashUIItem.ProxiesSorting) + if (SortingSelected != Config.ClashUIItem.ProxiesSorting) { - _config.ClashUIItem.ProxiesSorting = SortingSelected; + Config.ClashUIItem.ProxiesSorting = SortingSelected; } RefreshProxyDetails(c); @@ -149,7 +149,7 @@ public class ClashProxiesViewModel : MyReactiveObject private async Task SetRuleMode(ERuleMode mode) { - _config.ClashUIItem.RuleMode = mode; + Config.ClashUIItem.RuleMode = mode; if (mode != ERuleMode.Unchanged) { @@ -164,7 +164,7 @@ public class ClashProxiesViewModel : MyReactiveObject private async Task GetClashProxies(bool refreshUI) { var ret = await ClashApiManager.Instance.GetClashProxiesAsync(); - if (ret?.Item1 == null || ret.Item2 == null) + if (ret?.Item1 is null || ret.Item2 is null) { return; } @@ -179,7 +179,7 @@ public class ClashProxiesViewModel : MyReactiveObject public async Task RefreshProxyGroups() { - if (_proxies == null) + if (_proxies is null) { return; } @@ -188,7 +188,7 @@ public class ClashProxiesViewModel : MyReactiveObject ProxyGroups.Clear(); var proxyGroups = ClashApiManager.Instance.GetClashProxyGroups(); - if (proxyGroups != null && proxyGroups.Count > 0) + if (proxyGroups is not null && proxyGroups.Count > 0) { foreach (var it in proxyGroups) { @@ -197,7 +197,7 @@ public class ClashProxiesViewModel : MyReactiveObject continue; } var item = _proxies[it.name]; - if (!Global.allowSelectType.Contains(item.type.ToLower())) + if (!AppConfig.allowSelectType.Contains(item.type.ToLower())) { continue; } @@ -213,12 +213,12 @@ public class ClashProxiesViewModel : MyReactiveObject //from api foreach (var kv in _proxies) { - if (!Global.allowSelectType.Contains(kv.Value.type.ToLower())) + if (!AppConfig.allowSelectType.Contains(kv.Value.type.ToLower())) { continue; } var item = ProxyGroups.FirstOrDefault(t => t.Name == kv.Key); - if (item != null && item.Name.IsNotEmpty()) + if (item is not null && item.Name.IsNotEmpty()) { continue; } @@ -230,9 +230,9 @@ public class ClashProxiesViewModel : MyReactiveObject }); } - if (ProxyGroups != null && ProxyGroups.Count > 0) + if (ProxyGroups is not null && ProxyGroups.Count > 0) { - if (selectedName != null && ProxyGroups.Any(t => t.Name == selectedName)) + if (selectedName is not null && ProxyGroups.Any(t => t.Name == selectedName)) { SelectedGroup = ProxyGroups.FirstOrDefault(t => t.Name == selectedName); } @@ -260,13 +260,13 @@ public class ClashProxiesViewModel : MyReactiveObject { return; } - if (_proxies == null) + if (_proxies is null) { return; } _proxies.TryGetValue(name, out var proxy); - if (proxy?.all == null) + if (proxy?.all is null) { return; } @@ -274,7 +274,7 @@ public class ClashProxiesViewModel : MyReactiveObject foreach (var item in proxy.all) { var proxy2 = TryGetProxy(item); - if (proxy2 == null) + if (proxy2 is null) { continue; } @@ -308,24 +308,24 @@ public class ClashProxiesViewModel : MyReactiveObject private ProxiesItem? TryGetProxy(string name) { - if (_proxies == null) + if (_proxies is null) { return null; } _proxies.TryGetValue(name, out var proxy2); - if (proxy2 != null) + if (proxy2 is not null) { return proxy2; } //from providers - if (_providers != null) + if (_providers is not null) { foreach (var kv in _providers) { - if (Global.proxyVehicleType.Contains(kv.Value.vehicleType.ToLower())) + if (AppConfig.proxyVehicleType.Contains(kv.Value.vehicleType.ToLower())) { var proxy3 = kv.Value.proxies.FirstOrDefault(t => t.name == name); - if (proxy3 != null) + if (proxy3 is not null) { return proxy3; } @@ -337,11 +337,11 @@ public class ClashProxiesViewModel : MyReactiveObject public async Task SetActiveProxy() { - if (SelectedGroup == null || SelectedGroup.Name.IsNullOrEmpty()) + if (SelectedGroup is null || SelectedGroup.Name.IsNullOrEmpty()) { return; } - if (SelectedDetail == null || SelectedDetail.Name.IsNullOrEmpty()) + if (SelectedDetail is null || SelectedDetail.Name.IsNullOrEmpty()) { return; } @@ -356,7 +356,7 @@ public class ClashProxiesViewModel : MyReactiveObject return; } var selectedProxy = TryGetProxy(name); - if (selectedProxy == null || selectedProxy.type != "Selector") + if (selectedProxy is null || selectedProxy.type != "Selector") { NoticeManager.Instance.Enqueue(ResUI.OperationFailed); return; @@ -366,7 +366,7 @@ public class ClashProxiesViewModel : MyReactiveObject selectedProxy.now = nameNode; var group = ProxyGroups.FirstOrDefault(it => it.Name == SelectedGroup.Name); - if (group != null) + if (group is not null) { group.Now = nameNode; var group2 = JsonUtils.DeepCopy(group); @@ -381,7 +381,7 @@ public class ClashProxiesViewModel : MyReactiveObject { ClashApiManager.Instance.ClashProxiesDelayTest(blAll, ProxyDetails.ToList(), async (item, result) => { - if (item == null || result.IsNullOrEmpty()) + if (item is null || result.IsNullOrEmpty()) { return; } @@ -400,18 +400,18 @@ public class ClashProxiesViewModel : MyReactiveObject public async Task ProxiesDelayTestResult(SpeedTestResult result) { var detail = ProxyDetails.FirstOrDefault(it => it.Name == result.IndexId); - if (detail == null) + if (detail is null) { return; } var dicResult = JsonUtils.Deserialize>(result.Delay); - if (dicResult != null && dicResult.TryGetValue("delay", out var value)) + if (dicResult is not null && dicResult.TryGetValue("delay", out var value)) { detail.Delay = Convert.ToInt32(value.ToString()); detail.DelayName = $"{detail.Delay}ms"; } - else if (dicResult != null && dicResult.TryGetValue("message", out var value1)) + else if (dicResult is not null && dicResult.TryGetValue("message", out var value1)) { detail.Delay = _delayTimeout; detail.DelayName = $"{value1}"; @@ -441,11 +441,11 @@ public class ClashProxiesViewModel : MyReactiveObject { continue; } - if (_config.ClashUIItem.ProxiesAutoDelayTestInterval <= 0) + if (Config.ClashUIItem.ProxiesAutoDelayTestInterval <= 0) { continue; } - if (numOfExecuted % _config.ClashUIItem.ProxiesAutoDelayTestInterval != 0) + if (numOfExecuted % Config.ClashUIItem.ProxiesAutoDelayTestInterval != 0) { continue; } diff --git a/v2rayN/ServiceLib/ViewModels/DNSSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/DNSSettingViewModel.cs index d53b960d..4733e9e0 100644 --- a/v2rayN/ServiceLib/ViewModels/DNSSettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/DNSSettingViewModel.cs @@ -35,20 +35,20 @@ public class DNSSettingViewModel : MyReactiveObject public DNSSettingViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; SaveCmd = ReactiveCommand.CreateFromTask(SaveSettingAsync); ImportDefConfig4V2rayCompatibleCmd = ReactiveCommand.CreateFromTask(async () => { - NormalDNSCompatible = EmbedUtils.GetEmbedText(Global.DNSV2rayNormalFileName); + NormalDNSCompatible = EmbedUtils.GetEmbedText(AppConfig.DNSV2rayNormalFileName); await Task.CompletedTask; }); ImportDefConfig4SingboxCompatibleCmd = ReactiveCommand.CreateFromTask(async () => { - NormalDNS2Compatible = EmbedUtils.GetEmbedText(Global.DNSSingboxNormalFileName); - TunDNS2Compatible = EmbedUtils.GetEmbedText(Global.TunSingboxDNSFileName); + NormalDNS2Compatible = EmbedUtils.GetEmbedText(AppConfig.DNSSingboxNormalFileName); + TunDNS2Compatible = EmbedUtils.GetEmbedText(AppConfig.TunSingboxDNSFileName); await Task.CompletedTask; }); @@ -61,8 +61,8 @@ public class DNSSettingViewModel : MyReactiveObject private async Task Init() { - _config = AppManager.Instance.Config; - var item = _config.SimpleDNSItem; + Config = AppManager.Instance.Config; + var item = Config.SimpleDNSItem; UseSystemHosts = item.UseSystemHosts; AddCommonHosts = item.AddCommonHosts; FakeIP = item.FakeIP; @@ -93,23 +93,23 @@ public class DNSSettingViewModel : MyReactiveObject private async Task SaveSettingAsync() { - _config.SimpleDNSItem.UseSystemHosts = UseSystemHosts; - _config.SimpleDNSItem.AddCommonHosts = AddCommonHosts; - _config.SimpleDNSItem.FakeIP = FakeIP; - _config.SimpleDNSItem.BlockBindingQuery = BlockBindingQuery; - _config.SimpleDNSItem.DirectDNS = DirectDNS; - _config.SimpleDNSItem.RemoteDNS = RemoteDNS; - _config.SimpleDNSItem.BootstrapDNS = BootstrapDNS; - _config.SimpleDNSItem.RayStrategy4Freedom = RayStrategy4Freedom; - _config.SimpleDNSItem.SingboxStrategy4Direct = SingboxStrategy4Direct; - _config.SimpleDNSItem.SingboxStrategy4Proxy = SingboxStrategy4Proxy; - _config.SimpleDNSItem.Hosts = Hosts; - _config.SimpleDNSItem.DirectExpectedIPs = DirectExpectedIPs; + Config.SimpleDNSItem.UseSystemHosts = UseSystemHosts; + Config.SimpleDNSItem.AddCommonHosts = AddCommonHosts; + Config.SimpleDNSItem.FakeIP = FakeIP; + Config.SimpleDNSItem.BlockBindingQuery = BlockBindingQuery; + Config.SimpleDNSItem.DirectDNS = DirectDNS; + Config.SimpleDNSItem.RemoteDNS = RemoteDNS; + Config.SimpleDNSItem.BootstrapDNS = BootstrapDNS; + Config.SimpleDNSItem.RayStrategy4Freedom = RayStrategy4Freedom; + Config.SimpleDNSItem.SingboxStrategy4Direct = SingboxStrategy4Direct; + Config.SimpleDNSItem.SingboxStrategy4Proxy = SingboxStrategy4Proxy; + Config.SimpleDNSItem.Hosts = Hosts; + Config.SimpleDNSItem.DirectExpectedIPs = DirectExpectedIPs; if (NormalDNSCompatible.IsNotEmpty()) { var obj = JsonUtils.ParseJson(NormalDNSCompatible); - if (obj != null && obj["servers"] != null) + if (obj is not null && obj["servers"] is not null) { } else @@ -124,7 +124,7 @@ public class DNSSettingViewModel : MyReactiveObject if (NormalDNS2Compatible.IsNotEmpty()) { var obj2 = JsonUtils.Deserialize(NormalDNS2Compatible); - if (obj2 == null) + if (obj2 is null) { NoticeManager.Instance.Enqueue(ResUI.FillCorrectDNSText); return; @@ -133,7 +133,7 @@ public class DNSSettingViewModel : MyReactiveObject if (TunDNS2Compatible.IsNotEmpty()) { var obj2 = JsonUtils.Deserialize(TunDNS2Compatible); - if (obj2 == null) + if (obj2 is null) { NoticeManager.Instance.Enqueue(ResUI.FillCorrectDNSText); return; @@ -146,7 +146,7 @@ public class DNSSettingViewModel : MyReactiveObject item1.DomainDNSAddress = DomainDNSAddressCompatible; item1.UseSystemHosts = UseSystemHostsCompatible; item1.NormalDNS = NormalDNSCompatible; - await ConfigHandler.SaveDNSItems(_config, item1); + await ConfigHandler.SaveDNSItems(Config, item1); var item2 = await AppManager.Instance.GetDNSItem(ECoreType.sing_box); item2.Enabled = SBCustomDNSEnableCompatible; @@ -154,12 +154,12 @@ public class DNSSettingViewModel : MyReactiveObject item2.DomainDNSAddress = DomainDNSAddress2Compatible; item2.NormalDNS = JsonUtils.Serialize(JsonUtils.ParseJson(NormalDNS2Compatible)); item2.TunDNS = JsonUtils.Serialize(JsonUtils.ParseJson(TunDNS2Compatible)); - await ConfigHandler.SaveDNSItems(_config, item2); + await ConfigHandler.SaveDNSItems(Config, item2); - await ConfigHandler.SaveConfig(_config); - if (_updateView != null) + await ConfigHandler.SaveConfig(Config); + if (UpdateView is not null) { - await _updateView(EViewAction.CloseWindow, null); + await UpdateView(EViewAction.CloseWindow, null); } } } diff --git a/v2rayN/ServiceLib/ViewModels/FullConfigTemplateViewModel.cs b/v2rayN/ServiceLib/ViewModels/FullConfigTemplateViewModel.cs index 3a50b52e..d7de510e 100644 --- a/v2rayN/ServiceLib/ViewModels/FullConfigTemplateViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/FullConfigTemplateViewModel.cs @@ -37,8 +37,8 @@ public class FullConfigTemplateViewModel : MyReactiveObject public FullConfigTemplateViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; SaveCmd = ReactiveCommand.CreateFromTask(async () => { await SaveSettingAsync(); @@ -76,7 +76,7 @@ public class FullConfigTemplateViewModel : MyReactiveObject } NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); - _ = _updateView?.Invoke(EViewAction.CloseWindow, null); + _ = UpdateView?.Invoke(EViewAction.CloseWindow, null); } private async Task SaveXrayConfigAsync() @@ -90,7 +90,7 @@ public class FullConfigTemplateViewModel : MyReactiveObject item.AddProxyOnly = AddProxyOnly4Ray; item.ProxyDetour = ProxyDetour4Ray; - await ConfigHandler.SaveFullConfigTemplate(_config, item); + await ConfigHandler.SaveFullConfigTemplate(Config, item); return true; } @@ -107,7 +107,7 @@ public class FullConfigTemplateViewModel : MyReactiveObject item.AddProxyOnly = AddProxyOnly4Singbox; item.ProxyDetour = ProxyDetour4Singbox; - await ConfigHandler.SaveFullConfigTemplate(_config, item); + await ConfigHandler.SaveFullConfigTemplate(Config, item); return true; } } diff --git a/v2rayN/ServiceLib/ViewModels/GlobalHotkeySettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/GlobalHotkeySettingViewModel.cs index 581007f1..4cd26bd0 100644 --- a/v2rayN/ServiceLib/ViewModels/GlobalHotkeySettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/GlobalHotkeySettingViewModel.cs @@ -8,10 +8,10 @@ public class GlobalHotkeySettingViewModel : MyReactiveObject public GlobalHotkeySettingViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; - _globalHotkeys = JsonUtils.DeepCopy(_config.GlobalHotkeys); + _globalHotkeys = JsonUtils.DeepCopy(Config.GlobalHotkeys); SaveCmd = ReactiveCommand.CreateFromTask(async () => { @@ -22,7 +22,7 @@ public class GlobalHotkeySettingViewModel : MyReactiveObject public KeyEventItem GetKeyEventItem(EGlobalHotkey eg) { var item = _globalHotkeys.FirstOrDefault((it) => it.EGlobalHotkey == eg); - if (item != null) + if (item is not null) { return item; } @@ -47,11 +47,11 @@ public class GlobalHotkeySettingViewModel : MyReactiveObject private async Task SaveSettingAsync() { - _config.GlobalHotkeys = _globalHotkeys; + Config.GlobalHotkeys = _globalHotkeys; - if (await ConfigHandler.SaveConfig(_config) == 0) + if (await ConfigHandler.SaveConfig(Config) == 0) { - _updateView?.Invoke(EViewAction.CloseWindow, null); + UpdateView?.Invoke(EViewAction.CloseWindow, null); } else { diff --git a/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs b/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs index a09ad4de..a4fb0e2a 100644 --- a/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs @@ -70,8 +70,8 @@ public class MainWindowViewModel : MyReactiveObject public MainWindowViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; BlIsWindows = Utils.IsWindows(); #region WhenAnyValue && ReactiveCommand @@ -158,11 +158,11 @@ public class MainWindowViewModel : MyReactiveObject }); SubGroupUpdateCmd = ReactiveCommand.CreateFromTask(async () => { - await UpdateSubscriptionProcess(_config.SubIndexId, false); + await UpdateSubscriptionProcess(Config.SubIndexId, false); }); SubGroupUpdateViaProxyCmd = ReactiveCommand.CreateFromTask(async () => { - await UpdateSubscriptionProcess(_config.SubIndexId, true); + await UpdateSubscriptionProcess(Config.SubIndexId, true); }); //Setting @@ -184,7 +184,7 @@ public class MainWindowViewModel : MyReactiveObject }); GlobalHotkeySettingCmd = ReactiveCommand.CreateFromTask(async () => { - if (await _updateView?.Invoke(EViewAction.GlobalHotkeySettingWindow, null) == true) + if (await UpdateView?.Invoke(EViewAction.GlobalHotkeySettingWindow, null) == true) { NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); } @@ -255,17 +255,17 @@ public class MainWindowViewModel : MyReactiveObject { AppManager.Instance.ShowInTaskbar = true; - //await ConfigHandler.InitBuiltinRouting(_config); - await ConfigHandler.InitBuiltinDNS(_config); - await ConfigHandler.InitBuiltinFullConfigTemplate(_config); + //await ConfigHandler.InitBuiltinRouting(Config); + await ConfigHandler.InitBuiltinDNS(Config); + await ConfigHandler.InitBuiltinFullConfigTemplate(Config); await ProfileExManager.Instance.Init(); await ProfileGroupItemManager.Instance.Init(); - await CoreManager.Instance.Init(_config, UpdateHandler); - TaskManager.Instance.RegUpdateTask(_config, UpdateTaskHandler); + await CoreManager.Instance.Init(Config, UpdateHandler); + TaskManager.Instance.RegUpdateTask(Config, UpdateTaskHandler); - if (_config.GuiItem.EnableStatistics || _config.GuiItem.DisplayRealTimeSpeed) + if (Config.GuiItem.EnableStatistics || Config.GuiItem.DisplayRealTimeSpeed) { - await StatisticsManager.Instance.Init(_config, UpdateStatisticsHandler); + await StatisticsManager.Instance.Init(Config, UpdateStatisticsHandler); } await RefreshServers(); @@ -291,13 +291,13 @@ public class MainWindowViewModel : MyReactiveObject NoticeManager.Instance.SendMessageEx(msg); if (success) { - var indexIdOld = _config.IndexId; + var indexIdOld = Config.IndexId; await RefreshServers(); - if (indexIdOld != _config.IndexId) + if (indexIdOld != Config.IndexId) { await Reload(); } - if (_config.UiItem.EnableAutoAdjustMainLvColWidth) + if (Config.UiItem.EnableAutoAdjustMainLvColWidth) { AppEvents.AdjustMainLvColWidthRequested.Publish(); } @@ -338,7 +338,7 @@ public class MainWindowViewModel : MyReactiveObject { ProfileItem item = new() { - Subid = _config.SubIndexId, + Subid = Config.SubIndexId, ConfigType = eConfigType, IsSub = false, }; @@ -346,20 +346,20 @@ public class MainWindowViewModel : MyReactiveObject bool? ret = false; if (eConfigType == EConfigType.Custom) { - ret = await _updateView?.Invoke(EViewAction.AddServer2Window, item); + ret = await UpdateView?.Invoke(EViewAction.AddServer2Window, item); } else if (eConfigType.IsGroupType()) { - ret = await _updateView?.Invoke(EViewAction.AddGroupServerWindow, item); + ret = await UpdateView?.Invoke(EViewAction.AddGroupServerWindow, item); } else { - ret = await _updateView?.Invoke(EViewAction.AddServerWindow, item); + ret = await UpdateView?.Invoke(EViewAction.AddServerWindow, item); } if (ret == true) { await RefreshServers(); - if (item.IndexId == _config.IndexId) + if (item.IndexId == Config.IndexId) { await Reload(); } @@ -368,12 +368,12 @@ public class MainWindowViewModel : MyReactiveObject public async Task AddServerViaClipboardAsync(string? clipboardData) { - if (clipboardData == null) + if (clipboardData is null) { - await _updateView?.Invoke(EViewAction.AddServerViaClipboard, null); + await UpdateView?.Invoke(EViewAction.AddServerViaClipboard, null); return; } - var ret = await ConfigHandler.AddBatchServers(_config, clipboardData, _config.SubIndexId, false); + var ret = await ConfigHandler.AddBatchServers(Config, clipboardData, Config.SubIndexId, false); if (ret > 0) { RefreshSubscriptions(); @@ -388,7 +388,7 @@ public class MainWindowViewModel : MyReactiveObject public async Task AddServerViaScanAsync() { - _updateView?.Invoke(EViewAction.ScanScreenTask, null); + UpdateView?.Invoke(EViewAction.ScanScreenTask, null); await Task.CompletedTask; } @@ -400,7 +400,7 @@ public class MainWindowViewModel : MyReactiveObject public async Task AddServerViaImageAsync() { - _updateView?.Invoke(EViewAction.ScanImageTask, null); + UpdateView?.Invoke(EViewAction.ScanImageTask, null); await Task.CompletedTask; } @@ -423,7 +423,7 @@ public class MainWindowViewModel : MyReactiveObject } else { - var ret = await ConfigHandler.AddBatchServers(_config, result, _config.SubIndexId, false); + var ret = await ConfigHandler.AddBatchServers(Config, result, Config.SubIndexId, false); if (ret > 0) { RefreshSubscriptions(); @@ -443,7 +443,7 @@ public class MainWindowViewModel : MyReactiveObject private async Task SubSettingAsync() { - if (await _updateView?.Invoke(EViewAction.SubSettingWindow, null) == true) + if (await UpdateView?.Invoke(EViewAction.SubSettingWindow, null) == true) { RefreshSubscriptions(); } @@ -451,7 +451,7 @@ public class MainWindowViewModel : MyReactiveObject public async Task UpdateSubscriptionProcess(string subId, bool blProxy) { - await Task.Run(async () => await SubscriptionHandler.UpdateProcess(_config, subId, blProxy, UpdateTaskHandler)); + await Task.Run(async () => await SubscriptionHandler.UpdateProcess(Config, subId, blProxy, UpdateTaskHandler)); } #endregion Subscription @@ -460,7 +460,7 @@ public class MainWindowViewModel : MyReactiveObject private async Task OptionSettingAsync() { - var ret = await _updateView?.Invoke(EViewAction.OptionSettingWindow, null); + var ret = await UpdateView?.Invoke(EViewAction.OptionSettingWindow, null); if (ret == true) { AppEvents.InboundDisplayRequested.Publish(); @@ -470,10 +470,10 @@ public class MainWindowViewModel : MyReactiveObject private async Task RoutingSettingAsync() { - var ret = await _updateView?.Invoke(EViewAction.RoutingSettingWindow, null); + var ret = await UpdateView?.Invoke(EViewAction.RoutingSettingWindow, null); if (ret == true) { - await ConfigHandler.InitBuiltinRouting(_config); + await ConfigHandler.InitBuiltinRouting(Config); AppEvents.RoutingsMenuRefreshRequested.Publish(); await Reload(); } @@ -481,7 +481,7 @@ public class MainWindowViewModel : MyReactiveObject private async Task DNSSettingAsync() { - var ret = await _updateView?.Invoke(EViewAction.DNSSettingWindow, null); + var ret = await UpdateView?.Invoke(EViewAction.DNSSettingWindow, null); if (ret == true) { await Reload(); @@ -490,7 +490,7 @@ public class MainWindowViewModel : MyReactiveObject private async Task FullConfigTemplateAsync() { - var ret = await _updateView?.Invoke(EViewAction.FullConfigTemplateWindow, null); + var ret = await UpdateView?.Invoke(EViewAction.FullConfigTemplateWindow, null); if (ret == true) { await Reload(); @@ -541,7 +541,7 @@ public class MainWindowViewModel : MyReactiveObject { SetReloadEnabled(false); - var msgs = await ActionPrecheckManager.Instance.Check(_config.IndexId); + var msgs = await ActionPrecheckManager.Instance.Check(Config.IndexId); if (msgs.Count > 0) { foreach (var msg in msgs) @@ -555,7 +555,7 @@ public class MainWindowViewModel : MyReactiveObject await Task.Run(async () => { await LoadCore(); - await SysProxyHandler.UpdateSysProxy(_config, false); + await SysProxyHandler.UpdateSysProxy(Config, false); await Task.Delay(1000); }); AppEvents.TestServerRequested.Publish(); @@ -597,7 +597,7 @@ public class MainWindowViewModel : MyReactiveObject private async Task LoadCore() { - var node = await ConfigHandler.GetDefaultServer(_config); + var node = await ConfigHandler.GetDefaultServer(Config); await CoreManager.Instance.LoadCore(node); } @@ -607,12 +607,12 @@ public class MainWindowViewModel : MyReactiveObject public async Task ApplyRegionalPreset(EPresetType type) { - await ConfigHandler.ApplyRegionalPreset(_config, type); - await ConfigHandler.InitRouting(_config); + await ConfigHandler.ApplyRegionalPreset(Config, type); + await ConfigHandler.InitRouting(Config); AppEvents.RoutingsMenuRefreshRequested.Publish(); - await ConfigHandler.SaveConfig(_config); - await new UpdateService(_config, UpdateTaskHandler).UpdateGeoFileAll(); + await ConfigHandler.SaveConfig(Config); + await new UpdateService(Config, UpdateTaskHandler).UpdateGeoFileAll(); await Reload(); } diff --git a/v2rayN/ServiceLib/ViewModels/MsgViewModel.cs b/v2rayN/ServiceLib/ViewModels/MsgViewModel.cs index 68bf71b5..bfb1385b 100644 --- a/v2rayN/ServiceLib/ViewModels/MsgViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/MsgViewModel.cs @@ -15,10 +15,10 @@ public class MsgViewModel : MyReactiveObject public MsgViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; - MsgFilter = _config.MsgUIItem.MainMsgFilter ?? string.Empty; - AutoRefresh = _config.MsgUIItem.AutoRefresh ?? true; + Config = AppManager.Instance.Config; + UpdateView = updateView; + MsgFilter = Config.MsgUIItem.MainMsgFilter ?? string.Empty; + AutoRefresh = Config.MsgUIItem.AutoRefresh ?? true; this.WhenAnyValue( x => x.MsgFilter) @@ -27,7 +27,7 @@ public class MsgViewModel : MyReactiveObject this.WhenAnyValue( x => x.AutoRefresh, y => y == true) - .Subscribe(c => _config.MsgUIItem.AutoRefresh = AutoRefresh); + .Subscribe(c => Config.MsgUIItem.AutoRefresh = AutoRefresh); AppEvents.SendMsgViewRequested .AsObservable() @@ -64,7 +64,7 @@ public class MsgViewModel : MyReactiveObject sb.Append(line); } - await _updateView?.Invoke(EViewAction.DispatcherShowMsg, sb.ToString()); + await UpdateView?.Invoke(EViewAction.DispatcherShowMsg, sb.ToString()); } finally { @@ -105,7 +105,7 @@ public class MsgViewModel : MyReactiveObject private void DoMsgFilter() { - _config.MsgUIItem.MainMsgFilter = MsgFilter; + Config.MsgUIItem.MainMsgFilter = MsgFilter; _lastMsgFilterNotAvailable = false; } } diff --git a/v2rayN/ServiceLib/ViewModels/OptionSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/OptionSettingViewModel.cs index 86251873..95870427 100644 --- a/v2rayN/ServiceLib/ViewModels/OptionSettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/OptionSettingViewModel.cs @@ -117,8 +117,8 @@ public class OptionSettingViewModel : MyReactiveObject public OptionSettingViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; BlIsWindows = Utils.IsWindows(); BlIsLinux = Utils.IsLinux(); BlIsIsMacOS = Utils.IsMacOS(); @@ -134,11 +134,11 @@ public class OptionSettingViewModel : MyReactiveObject private async Task Init() { - await _updateView?.Invoke(EViewAction.InitSettingFont, null); + await UpdateView?.Invoke(EViewAction.InitSettingFont, null); #region Core - var inbound = _config.Inbound.First(); + var inbound = Config.Inbound.First(); localPort = inbound.LocalPort; SecondLocalPortEnabled = inbound.SecondLocalPortEnabled; udpEnabled = inbound.UdpEnabled; @@ -148,80 +148,80 @@ public class OptionSettingViewModel : MyReactiveObject newPort4LAN = inbound.NewPort4LAN; user = inbound.User; pass = inbound.Pass; - muxEnabled = _config.CoreBasicItem.MuxEnabled; - logEnabled = _config.CoreBasicItem.LogEnabled; - loglevel = _config.CoreBasicItem.Loglevel; - defAllowInsecure = _config.CoreBasicItem.DefAllowInsecure; - defFingerprint = _config.CoreBasicItem.DefFingerprint; - defUserAgent = _config.CoreBasicItem.DefUserAgent; - mux4SboxProtocol = _config.Mux4SboxItem.Protocol; - enableCacheFile4Sbox = _config.CoreBasicItem.EnableCacheFile4Sbox; - hyUpMbps = _config.HysteriaItem.UpMbps; - hyDownMbps = _config.HysteriaItem.DownMbps; - enableFragment = _config.CoreBasicItem.EnableFragment; + muxEnabled = Config.CoreBasicItem.MuxEnabled; + logEnabled = Config.CoreBasicItem.LogEnabled; + loglevel = Config.CoreBasicItem.Loglevel; + defAllowInsecure = Config.CoreBasicItem.DefAllowInsecure; + defFingerprint = Config.CoreBasicItem.DefFingerprint; + defUserAgent = Config.CoreBasicItem.DefUserAgent; + mux4SboxProtocol = Config.Mux4SboxItem.Protocol; + enableCacheFile4Sbox = Config.CoreBasicItem.EnableCacheFile4Sbox; + hyUpMbps = Config.HysteriaItem.UpMbps; + hyDownMbps = Config.HysteriaItem.DownMbps; + enableFragment = Config.CoreBasicItem.EnableFragment; #endregion Core #region Core KCP - //Kcpmtu = _config.kcpItem.mtu; - //Kcptti = _config.kcpItem.tti; - //KcpuplinkCapacity = _config.kcpItem.uplinkCapacity; - //KcpdownlinkCapacity = _config.kcpItem.downlinkCapacity; - //KcpreadBufferSize = _config.kcpItem.readBufferSize; - //KcpwriteBufferSize = _config.kcpItem.writeBufferSize; - //Kcpcongestion = _config.kcpItem.congestion; + //Kcpmtu = Config.kcpItem.mtu; + //Kcptti = Config.kcpItem.tti; + //KcpuplinkCapacity = Config.kcpItem.uplinkCapacity; + //KcpdownlinkCapacity = Config.kcpItem.downlinkCapacity; + //KcpreadBufferSize = Config.kcpItem.readBufferSize; + //KcpwriteBufferSize = Config.kcpItem.writeBufferSize; + //Kcpcongestion = Config.kcpItem.congestion; #endregion Core KCP #region UI - AutoRun = _config.GuiItem.AutoRun; - EnableStatistics = _config.GuiItem.EnableStatistics; - DisplayRealTimeSpeed = _config.GuiItem.DisplayRealTimeSpeed; - KeepOlderDedupl = _config.GuiItem.KeepOlderDedupl; - EnableAutoAdjustMainLvColWidth = _config.UiItem.EnableAutoAdjustMainLvColWidth; - EnableUpdateSubOnlyRemarksExist = _config.UiItem.EnableUpdateSubOnlyRemarksExist; - AutoHideStartup = _config.UiItem.AutoHideStartup; - Hide2TrayWhenClose = _config.UiItem.Hide2TrayWhenClose; - MacOSShowInDock = _config.UiItem.MacOSShowInDock; - EnableDragDropSort = _config.UiItem.EnableDragDropSort; - DoubleClick2Activate = _config.UiItem.DoubleClick2Activate; - AutoUpdateInterval = _config.GuiItem.AutoUpdateInterval; - TrayMenuServersLimit = _config.GuiItem.TrayMenuServersLimit; - CurrentFontFamily = _config.UiItem.CurrentFontFamily; - SpeedTestTimeout = _config.SpeedTestItem.SpeedTestTimeout; - SpeedTestUrl = _config.SpeedTestItem.SpeedTestUrl; - MixedConcurrencyCount = _config.SpeedTestItem.MixedConcurrencyCount; - SpeedPingTestUrl = _config.SpeedTestItem.SpeedPingTestUrl; - EnableHWA = _config.GuiItem.EnableHWA; - SubConvertUrl = _config.ConstItem.SubConvertUrl; - MainGirdOrientation = (int)_config.UiItem.MainGirdOrientation; - GeoFileSourceUrl = _config.ConstItem.GeoSourceUrl; - SrsFileSourceUrl = _config.ConstItem.SrsSourceUrl; - RoutingRulesSourceUrl = _config.ConstItem.RouteRulesTemplateSourceUrl; - IPAPIUrl = _config.SpeedTestItem.IPAPIUrl; + AutoRun = Config.GuiItem.AutoRun; + EnableStatistics = Config.GuiItem.EnableStatistics; + DisplayRealTimeSpeed = Config.GuiItem.DisplayRealTimeSpeed; + KeepOlderDedupl = Config.GuiItem.KeepOlderDedupl; + EnableAutoAdjustMainLvColWidth = Config.UiItem.EnableAutoAdjustMainLvColWidth; + EnableUpdateSubOnlyRemarksExist = Config.UiItem.EnableUpdateSubOnlyRemarksExist; + AutoHideStartup = Config.UiItem.AutoHideStartup; + Hide2TrayWhenClose = Config.UiItem.Hide2TrayWhenClose; + MacOSShowInDock = Config.UiItem.MacOSShowInDock; + EnableDragDropSort = Config.UiItem.EnableDragDropSort; + DoubleClick2Activate = Config.UiItem.DoubleClick2Activate; + AutoUpdateInterval = Config.GuiItem.AutoUpdateInterval; + TrayMenuServersLimit = Config.GuiItem.TrayMenuServersLimit; + CurrentFontFamily = Config.UiItem.CurrentFontFamily; + SpeedTestTimeout = Config.SpeedTestItem.SpeedTestTimeout; + SpeedTestUrl = Config.SpeedTestItem.SpeedTestUrl; + MixedConcurrencyCount = Config.SpeedTestItem.MixedConcurrencyCount; + SpeedPingTestUrl = Config.SpeedTestItem.SpeedPingTestUrl; + EnableHWA = Config.GuiItem.EnableHWA; + SubConvertUrl = Config.ConstItem.SubConvertUrl; + MainGirdOrientation = (int)Config.UiItem.MainGirdOrientation; + GeoFileSourceUrl = Config.ConstItem.GeoSourceUrl; + SrsFileSourceUrl = Config.ConstItem.SrsSourceUrl; + RoutingRulesSourceUrl = Config.ConstItem.RouteRulesTemplateSourceUrl; + IPAPIUrl = Config.SpeedTestItem.IPAPIUrl; #endregion UI #region System proxy - notProxyLocalAddress = _config.SystemProxyItem.NotProxyLocalAddress; - systemProxyAdvancedProtocol = _config.SystemProxyItem.SystemProxyAdvancedProtocol; - systemProxyExceptions = _config.SystemProxyItem.SystemProxyExceptions; - CustomSystemProxyPacPath = _config.SystemProxyItem.CustomSystemProxyPacPath; - CustomSystemProxyScriptPath = _config.SystemProxyItem.CustomSystemProxyScriptPath; + notProxyLocalAddress = Config.SystemProxyItem.NotProxyLocalAddress; + systemProxyAdvancedProtocol = Config.SystemProxyItem.SystemProxyAdvancedProtocol; + systemProxyExceptions = Config.SystemProxyItem.SystemProxyExceptions; + CustomSystemProxyPacPath = Config.SystemProxyItem.CustomSystemProxyPacPath; + CustomSystemProxyScriptPath = Config.SystemProxyItem.CustomSystemProxyScriptPath; #endregion System proxy #region Tun mode - TunAutoRoute = _config.TunModeItem.AutoRoute; - TunStrictRoute = _config.TunModeItem.StrictRoute; - TunStack = _config.TunModeItem.Stack; - TunMtu = _config.TunModeItem.Mtu; - TunEnableExInbound = _config.TunModeItem.EnableExInbound; - TunEnableIPv6Address = _config.TunModeItem.EnableIPv6Address; + TunAutoRoute = Config.TunModeItem.AutoRoute; + TunStrictRoute = Config.TunModeItem.StrictRoute; + TunStack = Config.TunModeItem.Stack; + TunMtu = Config.TunModeItem.Mtu; + TunEnableExInbound = Config.TunModeItem.EnableExInbound; + TunEnableIPv6Address = Config.TunModeItem.EnableIPv6Address; #endregion Tun mode @@ -230,25 +230,25 @@ public class OptionSettingViewModel : MyReactiveObject private async Task InitCoreType() { - if (_config.CoreTypeItem == null) + if (Config.CoreTypeItem is null) { - _config.CoreTypeItem = new List(); + Config.CoreTypeItem = new List(); } - foreach (EConfigType it in Enum.GetValues(typeof(EConfigType))) + foreach (var it in Enum.GetValues().Select(v => v)) { - if (_config.CoreTypeItem.FindIndex(t => t.ConfigType == it) >= 0) + if (Config.CoreTypeItem.FindIndex(t => t.ConfigType == it) >= 0) { continue; } - _config.CoreTypeItem.Add(new CoreTypeItem() + Config.CoreTypeItem.Add(new CoreTypeItem() { ConfigType = it, CoreType = ECoreType.Xray }); } - _config.CoreTypeItem.ForEach(it => + Config.CoreTypeItem.ForEach(it => { var type = it.CoreType.ToString(); switch ((int)it.ConfigType) @@ -292,17 +292,17 @@ public class OptionSettingViewModel : MyReactiveObject private async Task SaveSettingAsync() { if (localPort.ToString().IsNullOrEmpty() || !Utils.IsNumeric(localPort.ToString()) - || localPort <= 0 || localPort >= Global.MaxPort) + || localPort <= 0 || localPort >= AppConfig.MaxPort) { NoticeManager.Instance.Enqueue(ResUI.FillLocalListeningPort); return; } - var needReboot = EnableStatistics != _config.GuiItem.EnableStatistics - || DisplayRealTimeSpeed != _config.GuiItem.DisplayRealTimeSpeed - || EnableDragDropSort != _config.UiItem.EnableDragDropSort - || EnableHWA != _config.GuiItem.EnableHWA - || CurrentFontFamily != _config.UiItem.CurrentFontFamily - || MainGirdOrientation != (int)_config.UiItem.MainGirdOrientation; + var needReboot = EnableStatistics != Config.GuiItem.EnableStatistics + || DisplayRealTimeSpeed != Config.GuiItem.DisplayRealTimeSpeed + || EnableDragDropSort != Config.UiItem.EnableDragDropSort + || EnableHWA != Config.GuiItem.EnableHWA + || CurrentFontFamily != Config.UiItem.CurrentFontFamily + || MainGirdOrientation != (int)Config.UiItem.MainGirdOrientation; //if (Utile.IsNullOrEmpty(Kcpmtu.ToString()) || !Utile.IsNumeric(Kcpmtu.ToString()) // || Utile.IsNullOrEmpty(Kcptti.ToString()) || !Utile.IsNumeric(Kcptti.ToString()) @@ -316,83 +316,83 @@ public class OptionSettingViewModel : MyReactiveObject //} //Core - _config.Inbound.First().LocalPort = localPort; - _config.Inbound.First().SecondLocalPortEnabled = SecondLocalPortEnabled; - _config.Inbound.First().UdpEnabled = udpEnabled; - _config.Inbound.First().SniffingEnabled = sniffingEnabled; - _config.Inbound.First().DestOverride = destOverride?.ToList(); - _config.Inbound.First().RouteOnly = routeOnly; - _config.Inbound.First().AllowLANConn = allowLANConn; - _config.Inbound.First().NewPort4LAN = newPort4LAN; - _config.Inbound.First().User = user; - _config.Inbound.First().Pass = pass; - if (_config.Inbound.Count > 1) + Config.Inbound.First().LocalPort = localPort; + Config.Inbound.First().SecondLocalPortEnabled = SecondLocalPortEnabled; + Config.Inbound.First().UdpEnabled = udpEnabled; + Config.Inbound.First().SniffingEnabled = sniffingEnabled; + Config.Inbound.First().DestOverride = destOverride?.ToList(); + Config.Inbound.First().RouteOnly = routeOnly; + Config.Inbound.First().AllowLANConn = allowLANConn; + Config.Inbound.First().NewPort4LAN = newPort4LAN; + Config.Inbound.First().User = user; + Config.Inbound.First().Pass = pass; + if (Config.Inbound.Count > 1) { - _config.Inbound.RemoveAt(1); + Config.Inbound.RemoveAt(1); } - _config.CoreBasicItem.LogEnabled = logEnabled; - _config.CoreBasicItem.Loglevel = loglevel; - _config.CoreBasicItem.MuxEnabled = muxEnabled; - _config.CoreBasicItem.DefAllowInsecure = defAllowInsecure; - _config.CoreBasicItem.DefFingerprint = defFingerprint; - _config.CoreBasicItem.DefUserAgent = defUserAgent; - _config.Mux4SboxItem.Protocol = mux4SboxProtocol; - _config.CoreBasicItem.EnableCacheFile4Sbox = enableCacheFile4Sbox; - _config.HysteriaItem.UpMbps = hyUpMbps; - _config.HysteriaItem.DownMbps = hyDownMbps; - _config.CoreBasicItem.EnableFragment = enableFragment; + Config.CoreBasicItem.LogEnabled = logEnabled; + Config.CoreBasicItem.Loglevel = loglevel; + Config.CoreBasicItem.MuxEnabled = muxEnabled; + Config.CoreBasicItem.DefAllowInsecure = defAllowInsecure; + Config.CoreBasicItem.DefFingerprint = defFingerprint; + Config.CoreBasicItem.DefUserAgent = defUserAgent; + Config.Mux4SboxItem.Protocol = mux4SboxProtocol; + Config.CoreBasicItem.EnableCacheFile4Sbox = enableCacheFile4Sbox; + Config.HysteriaItem.UpMbps = hyUpMbps; + Config.HysteriaItem.DownMbps = hyDownMbps; + Config.CoreBasicItem.EnableFragment = enableFragment; - _config.GuiItem.AutoRun = AutoRun; - _config.GuiItem.EnableStatistics = EnableStatistics; - _config.GuiItem.DisplayRealTimeSpeed = DisplayRealTimeSpeed; - _config.GuiItem.KeepOlderDedupl = KeepOlderDedupl; - _config.UiItem.EnableAutoAdjustMainLvColWidth = EnableAutoAdjustMainLvColWidth; - _config.UiItem.EnableUpdateSubOnlyRemarksExist = EnableUpdateSubOnlyRemarksExist; - _config.UiItem.AutoHideStartup = AutoHideStartup; - _config.UiItem.Hide2TrayWhenClose = Hide2TrayWhenClose; - _config.UiItem.MacOSShowInDock = MacOSShowInDock; - _config.GuiItem.AutoUpdateInterval = AutoUpdateInterval; - _config.UiItem.EnableDragDropSort = EnableDragDropSort; - _config.UiItem.DoubleClick2Activate = DoubleClick2Activate; - _config.GuiItem.TrayMenuServersLimit = TrayMenuServersLimit; - _config.UiItem.CurrentFontFamily = CurrentFontFamily; - _config.SpeedTestItem.SpeedTestTimeout = SpeedTestTimeout; - _config.SpeedTestItem.MixedConcurrencyCount = MixedConcurrencyCount; - _config.SpeedTestItem.SpeedTestUrl = SpeedTestUrl; - _config.SpeedTestItem.SpeedPingTestUrl = SpeedPingTestUrl; - _config.GuiItem.EnableHWA = EnableHWA; - _config.ConstItem.SubConvertUrl = SubConvertUrl; - _config.UiItem.MainGirdOrientation = (EGirdOrientation)MainGirdOrientation; - _config.ConstItem.GeoSourceUrl = GeoFileSourceUrl; - _config.ConstItem.SrsSourceUrl = SrsFileSourceUrl; - _config.ConstItem.RouteRulesTemplateSourceUrl = RoutingRulesSourceUrl; - _config.SpeedTestItem.IPAPIUrl = IPAPIUrl; + Config.GuiItem.AutoRun = AutoRun; + Config.GuiItem.EnableStatistics = EnableStatistics; + Config.GuiItem.DisplayRealTimeSpeed = DisplayRealTimeSpeed; + Config.GuiItem.KeepOlderDedupl = KeepOlderDedupl; + Config.UiItem.EnableAutoAdjustMainLvColWidth = EnableAutoAdjustMainLvColWidth; + Config.UiItem.EnableUpdateSubOnlyRemarksExist = EnableUpdateSubOnlyRemarksExist; + Config.UiItem.AutoHideStartup = AutoHideStartup; + Config.UiItem.Hide2TrayWhenClose = Hide2TrayWhenClose; + Config.UiItem.MacOSShowInDock = MacOSShowInDock; + Config.GuiItem.AutoUpdateInterval = AutoUpdateInterval; + Config.UiItem.EnableDragDropSort = EnableDragDropSort; + Config.UiItem.DoubleClick2Activate = DoubleClick2Activate; + Config.GuiItem.TrayMenuServersLimit = TrayMenuServersLimit; + Config.UiItem.CurrentFontFamily = CurrentFontFamily; + Config.SpeedTestItem.SpeedTestTimeout = SpeedTestTimeout; + Config.SpeedTestItem.MixedConcurrencyCount = MixedConcurrencyCount; + Config.SpeedTestItem.SpeedTestUrl = SpeedTestUrl; + Config.SpeedTestItem.SpeedPingTestUrl = SpeedPingTestUrl; + Config.GuiItem.EnableHWA = EnableHWA; + Config.ConstItem.SubConvertUrl = SubConvertUrl; + Config.UiItem.MainGirdOrientation = (EGirdOrientation)MainGirdOrientation; + Config.ConstItem.GeoSourceUrl = GeoFileSourceUrl; + Config.ConstItem.SrsSourceUrl = SrsFileSourceUrl; + Config.ConstItem.RouteRulesTemplateSourceUrl = RoutingRulesSourceUrl; + Config.SpeedTestItem.IPAPIUrl = IPAPIUrl; //systemProxy - _config.SystemProxyItem.SystemProxyExceptions = systemProxyExceptions; - _config.SystemProxyItem.NotProxyLocalAddress = notProxyLocalAddress; - _config.SystemProxyItem.SystemProxyAdvancedProtocol = systemProxyAdvancedProtocol; - _config.SystemProxyItem.CustomSystemProxyPacPath = CustomSystemProxyPacPath; - _config.SystemProxyItem.CustomSystemProxyScriptPath = CustomSystemProxyScriptPath; + Config.SystemProxyItem.SystemProxyExceptions = systemProxyExceptions; + Config.SystemProxyItem.NotProxyLocalAddress = notProxyLocalAddress; + Config.SystemProxyItem.SystemProxyAdvancedProtocol = systemProxyAdvancedProtocol; + Config.SystemProxyItem.CustomSystemProxyPacPath = CustomSystemProxyPacPath; + Config.SystemProxyItem.CustomSystemProxyScriptPath = CustomSystemProxyScriptPath; //tun mode - _config.TunModeItem.AutoRoute = TunAutoRoute; - _config.TunModeItem.StrictRoute = TunStrictRoute; - _config.TunModeItem.Stack = TunStack; - _config.TunModeItem.Mtu = TunMtu; - _config.TunModeItem.EnableExInbound = TunEnableExInbound; - _config.TunModeItem.EnableIPv6Address = TunEnableIPv6Address; + Config.TunModeItem.AutoRoute = TunAutoRoute; + Config.TunModeItem.StrictRoute = TunStrictRoute; + Config.TunModeItem.Stack = TunStack; + Config.TunModeItem.Mtu = TunMtu; + Config.TunModeItem.EnableExInbound = TunEnableExInbound; + Config.TunModeItem.EnableIPv6Address = TunEnableIPv6Address; //coreType await SaveCoreType(); - if (await ConfigHandler.SaveConfig(_config) == 0) + if (await ConfigHandler.SaveConfig(Config) == 0) { - await AutoStartupHandler.UpdateTask(_config); + await AutoStartupHandler.UpdateTask(Config); AppManager.Instance.Reset(); NoticeManager.Instance.Enqueue(needReboot ? ResUI.NeedRebootTips : ResUI.OperationSuccess); - _updateView?.Invoke(EViewAction.CloseWindow, null); + UpdateView?.Invoke(EViewAction.CloseWindow, null); } else { @@ -402,10 +402,10 @@ public class OptionSettingViewModel : MyReactiveObject private async Task SaveCoreType() { - for (var k = 1; k <= _config.CoreTypeItem.Count; k++) + for (var k = 1; k <= Config.CoreTypeItem.Count; k++) { - var item = _config.CoreTypeItem[k - 1]; - var type = string.Empty; + var item = Config.CoreTypeItem[k - 1]; + string type; switch ((int)item.ConfigType) { case 1: diff --git a/v2rayN/ServiceLib/ViewModels/ProfilesSelectViewModel.cs b/v2rayN/ServiceLib/ViewModels/ProfilesSelectViewModel.cs index 7301882c..fd193d58 100644 --- a/v2rayN/ServiceLib/ViewModels/ProfilesSelectViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/ProfilesSelectViewModel.cs @@ -5,14 +5,9 @@ public class ProfilesSelectViewModel : MyReactiveObject #region private prop private string _serverFilter = string.Empty; - private Dictionary _dicHeaderSort = new(); + private readonly Dictionary _dicHeaderSort = new(); private string _subIndexId = string.Empty; - // ConfigType filter state: default include-mode with all types selected - private List _filterConfigTypes = new(); - - private bool _filterExclude = false; - #endregion private prop #region ObservableCollection @@ -35,16 +30,16 @@ public class ProfilesSelectViewModel : MyReactiveObject // Include/Exclude filter for ConfigType public List FilterConfigTypes { - get => _filterConfigTypes; - set => this.RaiseAndSetIfChanged(ref _filterConfigTypes, value); - } + get; + set => this.RaiseAndSetIfChanged(ref field, value); + } = new(); [Reactive] public bool FilterExclude { - get => _filterExclude; - set => this.RaiseAndSetIfChanged(ref _filterExclude, value); - } + get; + set => this.RaiseAndSetIfChanged(ref field, value); + } = false; #endregion ObservableCollection @@ -52,20 +47,20 @@ public class ProfilesSelectViewModel : MyReactiveObject public ProfilesSelectViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; - _subIndexId = _config.SubIndexId ?? string.Empty; + Config = AppManager.Instance.Config; + UpdateView = updateView; + _subIndexId = Config.SubIndexId ?? string.Empty; #region WhenAnyValue && ReactiveCommand this.WhenAnyValue( x => x.SelectedSub, - y => y != null && !y.Remarks.IsNullOrEmpty() && _subIndexId != y.Id) + y => y is not null && !y.Remarks.IsNullOrEmpty() && _subIndexId != y.Id) .Subscribe(async c => await SubSelectedChangedAsync(c)); this.WhenAnyValue( x => x.ServerFilter, - y => y != null && _serverFilter != y) + y => y is not null && _serverFilter != y) .Subscribe(async c => await ServerFilterChanged(c)); // React to ConfigType filter changes @@ -108,7 +103,7 @@ public class ProfilesSelectViewModel : MyReactiveObject public bool CanOk() { - return SelectedProfile != null && !SelectedProfile.IndexId.IsNullOrEmpty(); + return SelectedProfile is not null && !SelectedProfile.IndexId.IsNullOrEmpty(); } public bool SelectFinish() @@ -117,7 +112,7 @@ public class ProfilesSelectViewModel : MyReactiveObject { return false; } - _updateView?.Invoke(EViewAction.CloseWindow, null); + UpdateView?.Invoke(EViewAction.CloseWindow, null); return true; } @@ -135,7 +130,7 @@ public class ProfilesSelectViewModel : MyReactiveObject await RefreshServers(); - await _updateView?.Invoke(EViewAction.ProfilesFocus, null); + await UpdateView?.Invoke(EViewAction.ProfilesFocus, null); } private async Task ServerFilterChanged(bool c) @@ -158,14 +153,14 @@ public class ProfilesSelectViewModel : MyReactiveObject private async Task RefreshServersBiz() { - var lstModel = await GetProfileItemsEx(_subIndexId, _serverFilter); + var lstModel = await GetProfileItemsEx(_serverFilter); ProfileItems.Clear(); ProfileItems.AddRange(lstModel); if (lstModel.Count > 0) { - var selected = lstModel.FirstOrDefault(t => t.IndexId == _config.IndexId); - if (selected != null) + var selected = lstModel.FirstOrDefault(t => t.IndexId == Config.IndexId); + if (selected is not null) { SelectedProfile = selected; } @@ -175,7 +170,7 @@ public class ProfilesSelectViewModel : MyReactiveObject } } - await _updateView?.Invoke(EViewAction.DispatcherRefreshServersBiz, null); + await UpdateView?.Invoke(EViewAction.DispatcherRefreshServersBiz, null); } public async Task RefreshSubscriptions() @@ -188,7 +183,7 @@ public class ProfilesSelectViewModel : MyReactiveObject { SubItems.Add(item); } - if (_subIndexId != null && SubItems.FirstOrDefault(t => t.Id == _subIndexId) != null) + if (_subIndexId is not null && SubItems.FirstOrDefault(t => t.Id == _subIndexId) is not null) { SelectedSub = SubItems.FirstOrDefault(t => t.Id == _subIndexId); } @@ -198,7 +193,7 @@ public class ProfilesSelectViewModel : MyReactiveObject } } - private async Task?> GetProfileItemsEx(string subid, string filter) + private async Task?> GetProfileItemsEx(string filter) { var lstModel = await AppManager.Instance.ProfileItems(_subIndexId, filter); lstModel = (from t in lstModel @@ -214,11 +209,11 @@ public class ProfilesSelectViewModel : MyReactiveObject StreamSecurity = t.StreamSecurity, Subid = t.Subid, SubRemarks = t.SubRemarks, - IsActive = t.IndexId == _config.IndexId, + IsActive = t.IndexId == Config.IndexId, }).OrderBy(t => t.Sort).ToList(); // Apply ConfigType filter (include or exclude) - if (FilterConfigTypes != null && FilterConfigTypes.Count > 0) + if (FilterConfigTypes is not null && FilterConfigTypes.Count > 0) { if (FilterExclude) { @@ -251,7 +246,7 @@ public class ProfilesSelectViewModel : MyReactiveObject public async Task?> GetProfileItems() { - if (SelectedProfiles == null || SelectedProfiles.Count == 0) + if (SelectedProfiles is null || SelectedProfiles.Count == 0) { return null; } @@ -263,7 +258,7 @@ public class ProfilesSelectViewModel : MyReactiveObject continue; } var item = await AppManager.Instance.GetProfileItem(sp.IndexId); - if (item != null) + if (item is not null) { lst.Add(item); } @@ -284,13 +279,12 @@ public class ProfilesSelectViewModel : MyReactiveObject } var prop = typeof(ProfileItemModel).GetProperty(colName); - if (prop == null) + if (prop is null) { return; } - - _dicHeaderSort.TryAdd(colName, true); - var asc = _dicHeaderSort[colName]; +; + var asc = _dicHeaderSort.GetValueOrDefault(colName, true); var comparer = Comparer.Create((a, b) => { diff --git a/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs b/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs index 0e141b74..603b25b0 100644 --- a/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs @@ -6,7 +6,7 @@ public class ProfilesViewModel : MyReactiveObject private List _lstProfile; private string _serverFilter = string.Empty; - private Dictionary _dicHeaderSort = new(); + private readonly Dictionary _dicHeaderSort = new(); private SpeedtestService? _speedtestService; #endregion private prop @@ -56,7 +56,7 @@ public class ProfilesViewModel : MyReactiveObject public ReactiveCommand MoveUpCmd { get; } public ReactiveCommand MoveDownCmd { get; } - public ReactiveCommand MoveBottomCmd { get; } + public ReactiveCommand MoveBottomCmd { get; } public ReactiveCommand MoveToGroupCmd { get; } //servers ping @@ -86,27 +86,27 @@ public class ProfilesViewModel : MyReactiveObject public ProfilesViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; #region WhenAnyValue && ReactiveCommand var canEditRemove = this.WhenAnyValue( x => x.SelectedProfile, - selectedSource => selectedSource != null && !selectedSource.IndexId.IsNullOrEmpty()); + selectedSource => selectedSource is not null && !selectedSource.IndexId.IsNullOrEmpty()); this.WhenAnyValue( x => x.SelectedSub, - y => y != null && !y.Remarks.IsNullOrEmpty() && _config.SubIndexId != y.Id) + y => y is not null && !y.Remarks.IsNullOrEmpty() && Config.SubIndexId != y.Id) .Subscribe(async c => await SubSelectedChangedAsync(c)); this.WhenAnyValue( x => x.SelectedMoveToGroup, - y => y != null && !y.Remarks.IsNullOrEmpty()) + y => y is not null && !y.Remarks.IsNullOrEmpty()) .Subscribe(async c => await MoveToGroup(c)); this.WhenAnyValue( x => x.ServerFilter, - y => y != null && _serverFilter != y) + y => y is not null && _serverFilter != y) .Subscribe(async c => await ServerFilterChanged(c)); //servers delete @@ -303,7 +303,7 @@ public class ProfilesViewModel : MyReactiveObject return; } var item = ProfileItems.FirstOrDefault(it => it.IndexId == result.IndexId); - if (item == null) + if (item is null) { return; } @@ -322,7 +322,7 @@ public class ProfilesViewModel : MyReactiveObject public async Task UpdateStatistics(ServerSpeedItem update) { - if (!_config.GuiItem.EnableStatistics + if (!Config.GuiItem.EnableStatistics || (update.ProxyUp + update.ProxyDown) <= 0 || DateTime.Now.Second % 3 != 0) { @@ -332,7 +332,7 @@ public class ProfilesViewModel : MyReactiveObject try { var item = ProfileItems.FirstOrDefault(it => it.IndexId == update.IndexId); - if (item != null) + if (item is not null) { item.TodayDown = Utils.HumanFy(update.TodayDown); item.TodayUp = Utils.HumanFy(update.TodayUp); @@ -356,11 +356,11 @@ public class ProfilesViewModel : MyReactiveObject { return; } - _config.SubIndexId = SelectedSub?.Id; + Config.SubIndexId = SelectedSub?.Id; await RefreshServers(); - await _updateView?.Invoke(EViewAction.ProfilesFocus, null); + await UpdateView?.Invoke(EViewAction.ProfilesFocus, null); } private async Task ServerFilterChanged(bool c) @@ -385,15 +385,15 @@ public class ProfilesViewModel : MyReactiveObject private async Task RefreshServersBiz() { - var lstModel = await GetProfileItemsEx(_config.SubIndexId, _serverFilter); + var lstModel = await GetProfileItemsEx(Config.SubIndexId, _serverFilter); _lstProfile = JsonUtils.Deserialize>(JsonUtils.Serialize(lstModel)) ?? []; ProfileItems.Clear(); ProfileItems.AddRange(lstModel); if (lstModel.Count > 0) { - var selected = lstModel.FirstOrDefault(t => t.IndexId == _config.IndexId); - if (selected != null) + var selected = lstModel.FirstOrDefault(t => t.IndexId == Config.IndexId); + if (selected is not null) { SelectedProfile = selected; } @@ -403,7 +403,7 @@ public class ProfilesViewModel : MyReactiveObject } } - await _updateView?.Invoke(EViewAction.DispatcherRefreshServersBiz, null); + await UpdateView?.Invoke(EViewAction.DispatcherRefreshServersBiz, null); } private async Task RefreshSubscriptions() @@ -416,9 +416,9 @@ public class ProfilesViewModel : MyReactiveObject { SubItems.Add(item); } - if (_config.SubIndexId != null && SubItems.FirstOrDefault(t => t.Id == _config.SubIndexId) != null) + if (Config.SubIndexId is not null && SubItems.FirstOrDefault(t => t.Id == Config.SubIndexId) is not null) { - SelectedSub = SubItems.FirstOrDefault(t => t.Id == _config.SubIndexId); + SelectedSub = SubItems.FirstOrDefault(t => t.Id == Config.SubIndexId); } else { @@ -428,11 +428,11 @@ public class ProfilesViewModel : MyReactiveObject private async Task?> GetProfileItemsEx(string subid, string filter) { - var lstModel = await AppManager.Instance.ProfileItems(_config.SubIndexId, filter); + var lstModel = await AppManager.Instance.ProfileItems(Config.SubIndexId, filter); - await ConfigHandler.SetDefaultServer(_config, lstModel); + await ConfigHandler.SetDefaultServer(Config, lstModel); - var lstServerStat = (_config.GuiItem.EnableStatistics ? StatisticsManager.Instance.ServerStat : null) ?? []; + var lstServerStat = (Config.GuiItem.EnableStatistics ? StatisticsManager.Instance.ServerStat : null) ?? []; var lstProfileExs = await ProfileExManager.Instance.GetProfileExs(); lstModel = (from t in lstModel join t2 in lstServerStat on t.IndexId equals t2.IndexId into t2b @@ -451,16 +451,16 @@ public class ProfilesViewModel : MyReactiveObject StreamSecurity = t.StreamSecurity, Subid = t.Subid, SubRemarks = t.SubRemarks, - IsActive = t.IndexId == _config.IndexId, + IsActive = t.IndexId == Config.IndexId, Sort = t33?.Sort ?? 0, Delay = t33?.Delay ?? 0, Speed = t33?.Speed ?? 0, DelayVal = t33?.Delay != 0 ? $"{t33?.Delay}" : string.Empty, SpeedVal = t33?.Speed > 0 ? $"{t33?.Speed}" : t33?.Message ?? string.Empty, - TodayDown = t22 == null ? "" : Utils.HumanFy(t22.TodayDown), - TodayUp = t22 == null ? "" : Utils.HumanFy(t22.TodayUp), - TotalDown = t22 == null ? "" : Utils.HumanFy(t22.TotalDown), - TotalUp = t22 == null ? "" : Utils.HumanFy(t22.TotalUp) + TodayDown = t22 is null ? "" : Utils.HumanFy(t22.TodayDown), + TodayUp = t22 is null ? "" : Utils.HumanFy(t22.TodayUp), + TotalDown = t22 is null ? "" : Utils.HumanFy(t22.TotalDown), + TotalUp = t22 is null ? "" : Utils.HumanFy(t22.TotalUp) }).OrderBy(t => t.Sort).ToList(); return lstModel; @@ -473,7 +473,7 @@ public class ProfilesViewModel : MyReactiveObject private async Task?> GetProfileItems(bool latest) { var lstSelected = new List(); - if (SelectedProfiles == null || SelectedProfiles.Count <= 0) + if (SelectedProfiles is null || SelectedProfiles.Count <= 0) { return null; } @@ -515,20 +515,20 @@ public class ProfilesViewModel : MyReactiveObject bool? ret = false; if (eConfigType == EConfigType.Custom) { - ret = await _updateView?.Invoke(EViewAction.AddServer2Window, item); + ret = await UpdateView?.Invoke(EViewAction.AddServer2Window, item); } else if (eConfigType.IsGroupType()) { - ret = await _updateView?.Invoke(EViewAction.AddGroupServerWindow, item); + ret = await UpdateView?.Invoke(EViewAction.AddGroupServerWindow, item); } else { - ret = await _updateView?.Invoke(EViewAction.AddServerWindow, item); + ret = await UpdateView?.Invoke(EViewAction.AddServerWindow, item); } if (ret == true) { await RefreshServers(); - if (item.IndexId == _config.IndexId) + if (item.IndexId == Config.IndexId) { Reload(); } @@ -538,17 +538,17 @@ public class ProfilesViewModel : MyReactiveObject public async Task RemoveServerAsync() { var lstSelected = await GetProfileItems(true); - if (lstSelected == null) + if (lstSelected is null) { return; } - if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) + if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false) { return; } - var exists = lstSelected.Exists(t => t.IndexId == _config.IndexId); + var exists = lstSelected.Exists(t => t.IndexId == Config.IndexId); - await ConfigHandler.RemoveServers(_config, lstSelected); + await ConfigHandler.RemoveServers(Config, lstSelected); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); if (lstSelected.Count == ProfileItems.Count) { @@ -563,12 +563,12 @@ public class ProfilesViewModel : MyReactiveObject private async Task RemoveDuplicateServer() { - if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) + if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false) { return; } - var tuple = await ConfigHandler.DedupServerList(_config, _config.SubIndexId); + var tuple = await ConfigHandler.DedupServerList(Config, Config.SubIndexId); if (tuple.Item1 > 0 || tuple.Item2 > 0) { await RefreshServers(); @@ -580,11 +580,11 @@ public class ProfilesViewModel : MyReactiveObject private async Task CopyServer() { var lstSelected = await GetProfileItems(false); - if (lstSelected == null) + if (lstSelected is null) { return; } - if (await ConfigHandler.CopyServer(_config, lstSelected) == 0) + if (await ConfigHandler.CopyServer(Config, lstSelected) == 0) { await RefreshServers(); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); @@ -606,7 +606,7 @@ public class ProfilesViewModel : MyReactiveObject { return; } - if (indexId == _config.IndexId) + if (indexId == Config.IndexId) { return; } @@ -617,7 +617,7 @@ public class ProfilesViewModel : MyReactiveObject return; } - if (await ConfigHandler.SetDefaultServerIndex(_config, indexId) == 0) + if (await ConfigHandler.SetDefaultServerIndex(Config, indexId) == 0) { await RefreshServers(); Reload(); @@ -638,24 +638,24 @@ public class ProfilesViewModel : MyReactiveObject return; } - await _updateView?.Invoke(EViewAction.ShareServer, url); + await UpdateView?.Invoke(EViewAction.ShareServer, url); } private async Task GenGroupMultipleServer(ECoreType coreType, EMultipleLoad multipleLoad) { var lstSelected = await GetProfileItems(true); - if (lstSelected == null) + if (lstSelected is null) { return; } - var ret = await ConfigHandler.AddGroupServer4Multiple(_config, lstSelected, coreType, multipleLoad, SelectedSub?.Id); + var ret = await ConfigHandler.AddGroupServer4Multiple(lstSelected, coreType, multipleLoad, SelectedSub?.Id); if (ret.Success != true) { NoticeManager.Instance.Enqueue(ResUI.OperationFailed); return; } - if (ret?.Data?.ToString() == _config.IndexId) + if (ret?.Data?.ToString() == Config.IndexId) { await RefreshServers(); Reload(); @@ -675,7 +675,7 @@ public class ProfilesViewModel : MyReactiveObject _dicHeaderSort.TryAdd(colName, true); _dicHeaderSort.TryGetValue(colName, out var asc); - if (await ConfigHandler.SortServers(_config, _config.SubIndexId, colName, asc) != 0) + if (await ConfigHandler.SortServers(Config, Config.SubIndexId, colName, asc) != 0) { return; } @@ -685,7 +685,7 @@ public class ProfilesViewModel : MyReactiveObject public async Task RemoveInvalidServerResult() { - var count = await ConfigHandler.RemoveInvalidServerResult(_config, _config.SubIndexId); + var count = await ConfigHandler.RemoveInvalidServerResult(Config, Config.SubIndexId); await RefreshServers(); NoticeManager.Instance.Enqueue(string.Format(ResUI.RemoveInvalidServerResultTip, count)); } @@ -699,12 +699,12 @@ public class ProfilesViewModel : MyReactiveObject } var lstSelected = await GetProfileItems(true); - if (lstSelected == null) + if (lstSelected is null) { return; } - await ConfigHandler.MoveToGroup(_config, lstSelected, SelectedMoveToGroup.Id); + await ConfigHandler.MoveToGroup(Config, lstSelected, SelectedMoveToGroup.Id); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); await RefreshServers(); @@ -726,7 +726,7 @@ public class ProfilesViewModel : MyReactiveObject { return; } - if (await ConfigHandler.MoveServer(_config, _lstProfile, index, eMove) == 0) + if (await ConfigHandler.MoveServer(_lstProfile, index, eMove) == 0) { await RefreshServers(); } @@ -737,7 +737,7 @@ public class ProfilesViewModel : MyReactiveObject var targetIndex = ProfileItems.IndexOf(targetItem); if (startIndex >= 0 && targetIndex >= 0 && startIndex != targetIndex) { - if (await ConfigHandler.MoveServer(_config, _lstProfile, startIndex, EMove.Position, targetIndex) == 0) + if (await ConfigHandler.MoveServer(_lstProfile, startIndex, EMove.Position, targetIndex) == 0) { await RefreshServers(); } @@ -757,12 +757,12 @@ public class ProfilesViewModel : MyReactiveObject } var lstSelected = await GetProfileItems(false); - if (lstSelected == null) + if (lstSelected is null) { return; } - _speedtestService ??= new SpeedtestService(_config, async (SpeedTestResult result) => + _speedtestService ??= new SpeedtestService(Config, async (SpeedTestResult result) => { RxApp.MainThreadScheduler.Schedule(result, (scheduler, result) => { @@ -808,13 +808,13 @@ public class ProfilesViewModel : MyReactiveObject } else { - await _updateView?.Invoke(EViewAction.SetClipboardData, result.Data); + await UpdateView?.Invoke(EViewAction.SetClipboardData, result.Data); NoticeManager.Instance.SendMessage(ResUI.OperationSuccess); } } else { - await _updateView?.Invoke(EViewAction.SaveFileDialog, item); + await UpdateView?.Invoke(EViewAction.SaveFileDialog, item); } } @@ -838,7 +838,7 @@ public class ProfilesViewModel : MyReactiveObject public async Task Export2ShareUrlAsync(bool blEncode) { var lstSelected = await GetProfileItems(true); - if (lstSelected == null) + if (lstSelected is null) { return; } @@ -858,11 +858,11 @@ public class ProfilesViewModel : MyReactiveObject { if (blEncode) { - await _updateView?.Invoke(EViewAction.SetClipboardData, Utils.Base64Encode(sb.ToString())); + await UpdateView?.Invoke(EViewAction.SetClipboardData, Utils.Base64Encode(sb.ToString())); } else { - await _updateView?.Invoke(EViewAction.SetClipboardData, sb.ToString()); + await UpdateView?.Invoke(EViewAction.SetClipboardData, sb.ToString()); } NoticeManager.Instance.SendMessage(ResUI.BatchExportURLSuccessfully); } @@ -881,13 +881,13 @@ public class ProfilesViewModel : MyReactiveObject } else { - item = await AppManager.Instance.GetSubItem(_config.SubIndexId); + item = await AppManager.Instance.GetSubItem(Config.SubIndexId); if (item is null) { return; } } - if (await _updateView?.Invoke(EViewAction.SubEditWindow, item) == true) + if (await UpdateView?.Invoke(EViewAction.SubEditWindow, item) == true) { await RefreshSubscriptions(); await SubSelectedChangedAsync(true); @@ -896,17 +896,17 @@ public class ProfilesViewModel : MyReactiveObject private async Task DeleteSubAsync() { - var item = await AppManager.Instance.GetSubItem(_config.SubIndexId); + var item = await AppManager.Instance.GetSubItem(Config.SubIndexId); if (item is null) { return; } - if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) + if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false) { return; } - await ConfigHandler.DeleteSubItem(_config, item.Id); + await ConfigHandler.DeleteSubItem(Config, item.Id); await RefreshSubscriptions(); await SubSelectedChangedAsync(true); diff --git a/v2rayN/ServiceLib/ViewModels/RoutingRuleDetailsViewModel.cs b/v2rayN/ServiceLib/ViewModels/RoutingRuleDetailsViewModel.cs index e984ab64..646f0bfb 100644 --- a/v2rayN/ServiceLib/ViewModels/RoutingRuleDetailsViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/RoutingRuleDetailsViewModel.cs @@ -27,8 +27,8 @@ public class RoutingRuleDetailsViewModel : MyReactiveObject public RoutingRuleDetailsViewModel(RulesItem rulesItem, Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; SaveCmd = ReactiveCommand.CreateFromTask(async () => { @@ -38,7 +38,7 @@ public class RoutingRuleDetailsViewModel : MyReactiveObject if (rulesItem.Id.IsNullOrEmpty()) { rulesItem.Id = Utils.GetGuid(false); - rulesItem.OutboundTag = Global.ProxyTag; + rulesItem.OutboundTag = AppConfig.ProxyTag; rulesItem.Enabled = true; SelectedSource = rulesItem; } @@ -73,7 +73,7 @@ public class RoutingRuleDetailsViewModel : MyReactiveObject } SelectedSource.Protocol = ProtocolItems?.ToList(); SelectedSource.InboundTag = InboundTagItems?.ToList(); - SelectedSource.RuleType = RuleType.IsNullOrEmpty() ? null : (ERuleType)Enum.Parse(typeof(ERuleType), RuleType); + SelectedSource.RuleType = RuleType.IsNullOrEmpty() ? null : Enum.Parse(RuleType); var hasRule = SelectedSource.Domain?.Count > 0 || SelectedSource.Ip?.Count > 0 @@ -88,6 +88,6 @@ public class RoutingRuleDetailsViewModel : MyReactiveObject return; } //NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); - await _updateView?.Invoke(EViewAction.CloseWindow, null); + await UpdateView?.Invoke(EViewAction.CloseWindow, null); } } diff --git a/v2rayN/ServiceLib/ViewModels/RoutingRuleSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/RoutingRuleSettingViewModel.cs index 71d42218..d2f5a390 100644 --- a/v2rayN/ServiceLib/ViewModels/RoutingRuleSettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/RoutingRuleSettingViewModel.cs @@ -29,12 +29,12 @@ public class RoutingRuleSettingViewModel : MyReactiveObject public RoutingRuleSettingViewModel(RoutingItem routingItem, Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; var canEditRemove = this.WhenAnyValue( x => x.SelectedSource, - selectedSource => selectedSource != null && !selectedSource.OutboundTag.IsNullOrEmpty()); + selectedSource => selectedSource is not null && !selectedSource.OutboundTag.IsNullOrEmpty()); RuleAddCmd = ReactiveCommand.CreateFromTask(async () => { @@ -42,7 +42,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject }); ImportRulesFromFileCmd = ReactiveCommand.CreateFromTask(async () => { - await _updateView?.Invoke(EViewAction.ImportRulesFromFile, null); + await UpdateView?.Invoke(EViewAction.ImportRulesFromFile, null); }); ImportRulesFromClipboardCmd = ReactiveCommand.CreateFromTask(async () => { @@ -129,7 +129,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject return; } } - if (await _updateView?.Invoke(EViewAction.RoutingRuleDetailsWindow, item) == true) + if (await UpdateView?.Invoke(EViewAction.RoutingRuleDetailsWindow, item) == true) { if (blNew) { @@ -146,14 +146,14 @@ public class RoutingRuleSettingViewModel : MyReactiveObject NoticeManager.Instance.Enqueue(ResUI.PleaseSelectRules); return; } - if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) + if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false) { return; } foreach (var it in SelectedSources ?? [SelectedSource]) { var item = _rules.FirstOrDefault(t => t.Id == it?.Id); - if (item != null) + if (item is not null) { _rules.Remove(item); } @@ -189,7 +189,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; - await _updateView?.Invoke(EViewAction.SetClipboardData, JsonUtils.Serialize(lst, options)); + await UpdateView?.Invoke(EViewAction.SetClipboardData, JsonUtils.Serialize(lst, options)); } } @@ -202,7 +202,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject } var item = _rules.FirstOrDefault(t => t.Id == SelectedSource?.Id); - if (item == null) + if (item is null) { return; } @@ -229,10 +229,10 @@ public class RoutingRuleSettingViewModel : MyReactiveObject item.RuleNum = _rules.Count; item.RuleSet = JsonUtils.Serialize(_rules, false); - if (await ConfigHandler.SaveRoutingItem(_config, item) == 0) + if (await ConfigHandler.SaveRoutingItem(Config, item) == 0) { NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); - _updateView?.Invoke(EViewAction.CloseWindow, null); + UpdateView?.Invoke(EViewAction.CloseWindow, null); } else { @@ -264,9 +264,9 @@ public class RoutingRuleSettingViewModel : MyReactiveObject public async Task ImportRulesFromClipboardAsync(string? clipboardData) { - if (clipboardData == null) + if (clipboardData is null) { - await _updateView?.Invoke(EViewAction.ImportRulesFromClipboard, null); + await UpdateView?.Invoke(EViewAction.ImportRulesFromClipboard, null); return; } var ret = await AddBatchRoutingRulesAsync(SelectedRouting, clipboardData); @@ -299,7 +299,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject private async Task AddBatchRoutingRulesAsync(RoutingItem routingItem, string? clipboardData) { var blReplace = false; - if (await _updateView?.Invoke(EViewAction.AddBatchRoutingRulesYesNo, null) == false) + if (await UpdateView?.Invoke(EViewAction.AddBatchRoutingRulesYesNo, null) == false) { blReplace = true; } @@ -308,7 +308,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject return -1; } var lstRules = JsonUtils.Deserialize>(clipboardData); - if (lstRules == null) + if (lstRules is null) { return -1; } diff --git a/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs index 8f62f2d0..cb8e1958 100644 --- a/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs @@ -29,12 +29,12 @@ public class RoutingSettingViewModel : MyReactiveObject public RoutingSettingViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; var canEditRemove = this.WhenAnyValue( x => x.SelectedSource, - selectedSource => selectedSource != null && !selectedSource.Remarks.IsNullOrEmpty()); + selectedSource => selectedSource is not null && !selectedSource.Remarks.IsNullOrEmpty()); RoutingAdvancedAddCmd = ReactiveCommand.CreateFromTask(async () => { @@ -65,10 +65,10 @@ public class RoutingSettingViewModel : MyReactiveObject { SelectedSource = new(); - DomainStrategy = _config.RoutingBasicItem.DomainStrategy; - DomainStrategy4Singbox = _config.RoutingBasicItem.DomainStrategy4Singbox; + DomainStrategy = Config.RoutingBasicItem.DomainStrategy; + DomainStrategy4Singbox = Config.RoutingBasicItem.DomainStrategy4Singbox; - await ConfigHandler.InitBuiltinRouting(_config); + await ConfigHandler.InitBuiltinRouting(Config); await RefreshRoutingItems(); } @@ -98,13 +98,13 @@ public class RoutingSettingViewModel : MyReactiveObject private async Task SaveRoutingAsync() { - _config.RoutingBasicItem.DomainStrategy = DomainStrategy; - _config.RoutingBasicItem.DomainStrategy4Singbox = DomainStrategy4Singbox; + Config.RoutingBasicItem.DomainStrategy = DomainStrategy; + Config.RoutingBasicItem.DomainStrategy4Singbox = DomainStrategy4Singbox; - if (await ConfigHandler.SaveConfig(_config) == 0) + if (await ConfigHandler.SaveConfig(Config) == 0) { NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); - _updateView?.Invoke(EViewAction.CloseWindow, null); + UpdateView?.Invoke(EViewAction.CloseWindow, null); } else { @@ -129,7 +129,7 @@ public class RoutingSettingViewModel : MyReactiveObject return; } } - if (await _updateView?.Invoke(EViewAction.RoutingRuleSettingWindow, item) == true) + if (await UpdateView?.Invoke(EViewAction.RoutingRuleSettingWindow, item) == true) { await RefreshRoutingItems(); IsModified = true; @@ -143,14 +143,14 @@ public class RoutingSettingViewModel : MyReactiveObject NoticeManager.Instance.Enqueue(ResUI.PleaseSelectRules); return; } - if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) + if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false) { return; } foreach (var it in SelectedSources ?? [SelectedSource]) { var item = await AppManager.Instance.GetRoutingItem(it?.Id); - if (item != null) + if (item is not null) { await ConfigHandler.RemoveRoutingItem(item); } @@ -169,7 +169,7 @@ public class RoutingSettingViewModel : MyReactiveObject return; } - if (await ConfigHandler.SetDefaultRouting(_config, item) == 0) + if (await ConfigHandler.SetDefaultRouting(Config, item) == 0) { await RefreshRoutingItems(); IsModified = true; @@ -178,7 +178,7 @@ public class RoutingSettingViewModel : MyReactiveObject private async Task RoutingAdvancedImportRules() { - if (await ConfigHandler.InitRouting(_config, true) == 0) + if (await ConfigHandler.InitRouting(Config, true) == 0) { await RefreshRoutingItems(); IsModified = true; diff --git a/v2rayN/ServiceLib/ViewModels/StatusBarViewModel.cs b/v2rayN/ServiceLib/ViewModels/StatusBarViewModel.cs index b8cd142e..6aeffb7a 100644 --- a/v2rayN/ServiceLib/ViewModels/StatusBarViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/StatusBarViewModel.cs @@ -3,6 +3,9 @@ namespace ServiceLib.ViewModels; public class StatusBarViewModel : MyReactiveObject { private static readonly Lazy _instance = new(() => new(null)); + + private static readonly CompositeFormat _speedDisplayFormat = CompositeFormat.Parse(ResUI.SpeedDisplayText); + public static StatusBarViewModel Instance => _instance.Value; #region ObservableCollection @@ -94,35 +97,35 @@ public class StatusBarViewModel : MyReactiveObject public StatusBarViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; + Config = AppManager.Instance.Config; SelectedRouting = new(); SelectedServer = new(); RunningServerToolTipText = "-"; BlSystemProxyPacVisible = Utils.IsWindows(); BlIsNonWindows = Utils.IsNonWindows(); - if (_config.TunModeItem.EnableTun && AllowEnableTun()) + if (Config.TunModeItem.EnableTun && AllowEnableTun()) { EnableTun = true; } else { - _config.TunModeItem.EnableTun = EnableTun = false; + Config.TunModeItem.EnableTun = EnableTun = false; } #region WhenAnyValue && ReactiveCommand this.WhenAnyValue( x => x.SelectedRouting, - y => y != null && !y.Remarks.IsNullOrEmpty()) + y => y is not null && !y.Remarks.IsNullOrEmpty()) .Subscribe(async c => await RoutingSelectedChangedAsync(c)); this.WhenAnyValue( x => x.SelectedServer, - y => y != null && !y.Text.IsNullOrEmpty()) + y => y is not null && !y.Text.IsNullOrEmpty()) .Subscribe(ServerSelectedChanged); - SystemProxySelected = (int)_config.SystemProxyItem.SysProxyType; + SystemProxySelected = (int)Config.SystemProxyItem.SysProxyType; this.WhenAnyValue( x => x.SystemProxySelected, y => y >= 0) @@ -131,7 +134,7 @@ public class StatusBarViewModel : MyReactiveObject this.WhenAnyValue( x => x.EnableTun, y => y == true) - .Subscribe(async c => await DoEnableTun(c)); + .Subscribe(async c => await DoEnableTun()); CopyProxyCmdToClipboardCmd = ReactiveCommand.CreateFromTask(async () => { @@ -193,7 +196,7 @@ public class StatusBarViewModel : MyReactiveObject #region AppEvents - if (updateView != null) + if (updateView is not null) { InitUpdateView(updateView); } @@ -230,16 +233,16 @@ public class StatusBarViewModel : MyReactiveObject private async Task Init() { - await ConfigHandler.InitBuiltinRouting(_config); + await ConfigHandler.InitBuiltinRouting(Config); await RefreshRoutingsMenu(); await InboundDisplayStatus(); - await ChangeSystemProxyAsync(_config.SystemProxyItem.SysProxyType, true); + await ChangeSystemProxyAsync(Config.SystemProxyItem.SysProxyType, true); } public void InitUpdateView(Func>? updateView) { - _updateView = updateView; - if (_updateView != null) + UpdateView = updateView; + if (UpdateView is not null) { AppEvents.ProfilesRefreshRequested .AsObservable() @@ -251,33 +254,33 @@ public class StatusBarViewModel : MyReactiveObject private async Task CopyProxyCmdToClipboard() { var cmd = Utils.IsWindows() ? "set" : "export"; - var address = $"{Global.Loopback}:{AppManager.Instance.GetLocalPort(EInboundProtocol.socks)}"; + var address = $"{AppConfig.Loopback}:{AppManager.Instance.GetLocalPort(EInboundProtocol.socks)}"; var sb = new StringBuilder(); - sb.AppendLine($"{cmd} http_proxy={Global.HttpProtocol}{address}"); - sb.AppendLine($"{cmd} https_proxy={Global.HttpProtocol}{address}"); - sb.AppendLine($"{cmd} all_proxy={Global.Socks5Protocol}{address}"); + sb.AppendLine($"{cmd} http_proxy={AppConfig.HttpProtocol}{address}"); + sb.AppendLine($"{cmd} https_proxy={AppConfig.HttpProtocol}{address}"); + sb.AppendLine($"{cmd} all_proxy={AppConfig.Socks5Protocol}{address}"); sb.AppendLine(""); - sb.AppendLine($"{cmd} HTTP_PROXY={Global.HttpProtocol}{address}"); - sb.AppendLine($"{cmd} HTTPS_PROXY={Global.HttpProtocol}{address}"); - sb.AppendLine($"{cmd} ALL_PROXY={Global.Socks5Protocol}{address}"); + sb.AppendLine($"{cmd} HTTP_PROXY={AppConfig.HttpProtocol}{address}"); + sb.AppendLine($"{cmd} HTTPS_PROXY={AppConfig.HttpProtocol}{address}"); + sb.AppendLine($"{cmd} ALL_PROXY={AppConfig.Socks5Protocol}{address}"); - await _updateView?.Invoke(EViewAction.SetClipboardData, sb.ToString()); + await UpdateView?.Invoke(EViewAction.SetClipboardData, sb.ToString()); } - private async Task AddServerViaClipboard() + private static async Task AddServerViaClipboard() { AppEvents.AddServerViaClipboardRequested.Publish(); await Task.Delay(1000); } - private async Task AddServerViaScan() + private static async Task AddServerViaScan() { AppEvents.AddServerViaScanRequested.Publish(); await Task.Delay(1000); } - private async Task UpdateSubscriptionProcess(bool blProxy) + private static async Task UpdateSubscriptionProcess(bool blProxy) { AppEvents.SubscriptionsUpdateRequested.Publish(blProxy); await Task.Delay(1000); @@ -288,8 +291,8 @@ public class StatusBarViewModel : MyReactiveObject await RefreshServersMenu(); //display running server - var running = await ConfigHandler.GetDefaultServer(_config); - if (running != null) + var running = await ConfigHandler.GetDefaultServer(Config); + if (running is not null) { RunningServerDisplay = RunningServerToolTipText = running.GetSummary(); @@ -303,10 +306,10 @@ public class StatusBarViewModel : MyReactiveObject private async Task RefreshServersMenu() { - var lstModel = await AppManager.Instance.ProfileItems(_config.SubIndexId, ""); + var lstModel = await AppManager.Instance.ProfileItems(Config.SubIndexId, ""); Servers.Clear(); - if (lstModel.Count > _config.GuiItem.TrayMenuServersLimit) + if (lstModel.Count > Config.GuiItem.TrayMenuServersLimit) { BlServers = false; return; @@ -320,7 +323,7 @@ public class StatusBarViewModel : MyReactiveObject var item = new ComboItem() { ID = it.IndexId, Text = name }; Servers.Add(item); - if (_config.IndexId == it.IndexId) + if (Config.IndexId == it.IndexId) { SelectedServer = item; } @@ -333,7 +336,7 @@ public class StatusBarViewModel : MyReactiveObject { return; } - if (SelectedServer == null) + if (SelectedServer is null) { return; } @@ -346,8 +349,8 @@ public class StatusBarViewModel : MyReactiveObject public async Task TestServerAvailability() { - var item = await ConfigHandler.GetDefaultServer(_config); - if (item == null) + var item = await ConfigHandler.GetDefaultServer(Config); + if (item is null) { return; } @@ -380,21 +383,21 @@ public class StatusBarViewModel : MyReactiveObject private async Task SetListenerType(ESysProxyType type) { - if (_config.SystemProxyItem.SysProxyType == type) + if (Config.SystemProxyItem.SysProxyType == type) { return; } - _config.SystemProxyItem.SysProxyType = type; + Config.SystemProxyItem.SysProxyType = type; await ChangeSystemProxyAsync(type, true); - NoticeManager.Instance.SendMessageEx($"{ResUI.TipChangeSystemProxy} - {_config.SystemProxyItem.SysProxyType}"); + NoticeManager.Instance.SendMessageEx($"{ResUI.TipChangeSystemProxy} - {Config.SystemProxyItem.SysProxyType}"); - SystemProxySelected = (int)_config.SystemProxyItem.SysProxyType; - await ConfigHandler.SaveConfig(_config); + SystemProxySelected = (int)Config.SystemProxyItem.SysProxyType; + await ConfigHandler.SaveConfig(Config); } public async Task ChangeSystemProxyAsync(ESysProxyType type, bool blChange) { - await SysProxyHandler.UpdateSysProxy(_config, false); + await SysProxyHandler.UpdateSysProxy(Config, false); BlSystemProxyClear = type == ESysProxyType.ForcedClear; BlSystemProxySet = type == ESysProxyType.ForcedChange; @@ -403,7 +406,7 @@ public class StatusBarViewModel : MyReactiveObject if (blChange) { - _updateView?.Invoke(EViewAction.DispatcherRefreshIcon, null); + UpdateView?.Invoke(EViewAction.DispatcherRefreshIcon, null); } } @@ -430,7 +433,7 @@ public class StatusBarViewModel : MyReactiveObject return; } - if (SelectedRouting == null) + if (SelectedRouting is null) { return; } @@ -441,11 +444,11 @@ public class StatusBarViewModel : MyReactiveObject return; } - if (await ConfigHandler.SetDefaultRouting(_config, item) == 0) + if (await ConfigHandler.SetDefaultRouting(Config, item) == 0) { NoticeManager.Instance.SendMessageEx(ResUI.TipChangeRouting); AppEvents.ReloadRequested.Publish(); - _updateView?.Invoke(EViewAction.DispatcherRefreshIcon, null); + UpdateView?.Invoke(EViewAction.DispatcherRefreshIcon, null); } } @@ -455,46 +458,46 @@ public class StatusBarViewModel : MyReactiveObject { return; } - if (_config.SystemProxyItem.SysProxyType == (ESysProxyType)SystemProxySelected) + if (Config.SystemProxyItem.SysProxyType == (ESysProxyType)SystemProxySelected) { return; } await SetListenerType((ESysProxyType)SystemProxySelected); } - private async Task DoEnableTun(bool c) + private async Task DoEnableTun() { - if (_config.TunModeItem.EnableTun == EnableTun) + if (Config.TunModeItem.EnableTun == EnableTun) { return; } - _config.TunModeItem.EnableTun = EnableTun; + Config.TunModeItem.EnableTun = EnableTun; if (EnableTun && AllowEnableTun() == false) { // When running as a non-administrator, reboot to administrator mode if (Utils.IsWindows()) { - _config.TunModeItem.EnableTun = false; + Config.TunModeItem.EnableTun = false; await AppManager.Instance.RebootAsAdmin(); return; } else { - bool? passwordResult = await _updateView?.Invoke(EViewAction.PasswordInput, null); + bool? passwordResult = await UpdateView?.Invoke(EViewAction.PasswordInput, null); if (passwordResult == false) { - _config.TunModeItem.EnableTun = false; + Config.TunModeItem.EnableTun = false; return; } } } - await ConfigHandler.SaveConfig(_config); + await ConfigHandler.SaveConfig(Config); AppEvents.ReloadRequested.Publish(); } - private bool AllowEnableTun() + private static bool AllowEnableTun() { if (Utils.IsWindows()) { @@ -519,30 +522,30 @@ public class StatusBarViewModel : MyReactiveObject { StringBuilder sb = new(); sb.Append($"[{EInboundProtocol.mixed}:{AppManager.Instance.GetLocalPort(EInboundProtocol.socks)}"); - if (_config.Inbound.First().SecondLocalPortEnabled) + if (Config.Inbound.First().SecondLocalPortEnabled) { sb.Append($",{AppManager.Instance.GetLocalPort(EInboundProtocol.socks2)}"); } sb.Append(']'); InboundDisplay = $"{ResUI.LabLocal}:{sb}"; - if (_config.Inbound.First().AllowLANConn) + if (Config.Inbound.First().AllowLANConn) { - var lan = _config.Inbound.First().NewPort4LAN + var lan = Config.Inbound.First().NewPort4LAN ? $"[{EInboundProtocol.mixed}:{AppManager.Instance.GetLocalPort(EInboundProtocol.socks3)}]" : $"[{EInboundProtocol.mixed}:{AppManager.Instance.GetLocalPort(EInboundProtocol.socks)}]"; InboundLanDisplay = $"{ResUI.LabLAN}:{lan}"; } else { - InboundLanDisplay = $"{ResUI.LabLAN}:{Global.None}"; + InboundLanDisplay = $"{ResUI.LabLAN}:{AppConfig.None}"; } await Task.CompletedTask; } public async Task UpdateStatistics(ServerSpeedItem update) { - if (!_config.GuiItem.DisplayRealTimeSpeed) + if (!Config.GuiItem.DisplayRealTimeSpeed) { return; } @@ -551,13 +554,13 @@ public class StatusBarViewModel : MyReactiveObject { if (AppManager.Instance.IsRunningCore(ECoreType.sing_box)) { - SpeedProxyDisplay = string.Format(ResUI.SpeedDisplayText, EInboundProtocol.mixed, Utils.HumanFy(update.ProxyUp), Utils.HumanFy(update.ProxyDown)); + SpeedProxyDisplay = string.Format(CultureInfo.CurrentCulture, _speedDisplayFormat, EInboundProtocol.mixed, Utils.HumanFy(update.ProxyUp), Utils.HumanFy(update.ProxyDown)); SpeedDirectDisplay = string.Empty; } else { - SpeedProxyDisplay = string.Format(ResUI.SpeedDisplayText, Global.ProxyTag, Utils.HumanFy(update.ProxyUp), Utils.HumanFy(update.ProxyDown)); - SpeedDirectDisplay = string.Format(ResUI.SpeedDisplayText, Global.DirectTag, Utils.HumanFy(update.DirectUp), Utils.HumanFy(update.DirectDown)); + SpeedProxyDisplay = string.Format(CultureInfo.CurrentCulture, _speedDisplayFormat, AppConfig.ProxyTag, Utils.HumanFy(update.ProxyUp), Utils.HumanFy(update.ProxyDown)); + SpeedDirectDisplay = string.Format(CultureInfo.CurrentCulture, _speedDisplayFormat, AppConfig.DirectTag, Utils.HumanFy(update.DirectUp), Utils.HumanFy(update.DirectDown)); } } catch diff --git a/v2rayN/ServiceLib/ViewModels/SubEditViewModel.cs b/v2rayN/ServiceLib/ViewModels/SubEditViewModel.cs index 344f4ac8..865bde7e 100644 --- a/v2rayN/ServiceLib/ViewModels/SubEditViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/SubEditViewModel.cs @@ -9,8 +9,8 @@ public class SubEditViewModel : MyReactiveObject public SubEditViewModel(SubItem subItem, Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; SaveCmd = ReactiveCommand.CreateFromTask(async () => { @@ -33,23 +33,23 @@ public class SubEditViewModel : MyReactiveObject if (url.IsNotEmpty()) { var uri = Utils.TryUri(url); - if (uri == null) + if (uri is null) { NoticeManager.Instance.Enqueue(ResUI.InvalidUrlTip); return; } //Do not allow http protocol - if (url.StartsWith(Global.HttpProtocol) && !Utils.IsPrivateNetwork(uri.IdnHost)) + if (url.StartsWith(AppConfig.HttpProtocol) && !Utils.IsPrivateNetwork(uri.IdnHost)) { NoticeManager.Instance.Enqueue(ResUI.InsecureUrlProtocol); //return; } } - if (await ConfigHandler.AddSubItem(_config, SelectedSource) == 0) + if (await ConfigHandler.AddSubItem(Config, SelectedSource) == 0) { NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); - _updateView?.Invoke(EViewAction.CloseWindow, null); + UpdateView?.Invoke(EViewAction.CloseWindow, null); } else { diff --git a/v2rayN/ServiceLib/ViewModels/SubSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/SubSettingViewModel.cs index ce0f6fa7..0757ea85 100644 --- a/v2rayN/ServiceLib/ViewModels/SubSettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/SubSettingViewModel.cs @@ -17,12 +17,12 @@ public class SubSettingViewModel : MyReactiveObject public SubSettingViewModel(Func>? updateView) { - _config = AppManager.Instance.Config; - _updateView = updateView; + Config = AppManager.Instance.Config; + UpdateView = updateView; var canEditRemove = this.WhenAnyValue( x => x.SelectedSource, - selectedSource => selectedSource != null && !selectedSource.Id.IsNullOrEmpty()); + selectedSource => selectedSource is not null && !selectedSource.Id.IsNullOrEmpty()); SubAddCmd = ReactiveCommand.CreateFromTask(async () => { @@ -38,7 +38,7 @@ public class SubSettingViewModel : MyReactiveObject }, canEditRemove); SubShareCmd = ReactiveCommand.CreateFromTask(async () => { - await _updateView?.Invoke(EViewAction.ShareSub, SelectedSource?.Url); + await UpdateView?.Invoke(EViewAction.ShareSub, SelectedSource?.Url); }, canEditRemove); _ = Init(); @@ -72,7 +72,7 @@ public class SubSettingViewModel : MyReactiveObject return; } } - if (await _updateView?.Invoke(EViewAction.SubEditWindow, item) == true) + if (await UpdateView?.Invoke(EViewAction.SubEditWindow, item) == true) { await RefreshSubItems(); IsModified = true; @@ -81,14 +81,14 @@ public class SubSettingViewModel : MyReactiveObject private async Task DeleteSubAsync() { - if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) + if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false) { return; } foreach (var it in SelectedSources ?? [SelectedSource]) { - await ConfigHandler.DeleteSubItem(_config, it.Id); + await ConfigHandler.DeleteSubItem(Config, it.Id); } await RefreshSubItems(); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); diff --git a/v2rayN/v2rayN.Desktop/Common/AppBuilderExtension.cs b/v2rayN/v2rayN.Desktop/Common/AppBuilderExtension.cs index 4266b91f..79f276d1 100644 --- a/v2rayN/v2rayN.Desktop/Common/AppBuilderExtension.cs +++ b/v2rayN/v2rayN.Desktop/Common/AppBuilderExtension.cs @@ -6,7 +6,7 @@ public static class AppBuilderExtension { var fallbacks = new List(); - var notoSansSc = new FontFamily(Path.Combine(Global.AvaAssets, "Fonts#Noto Sans SC")); + var notoSansSc = new FontFamily(Path.Combine(AppConfig.AvaAssets, "Fonts#Noto Sans SC")); fallbacks.Add(new FontFallback { FontFamily = notoSansSc }); if (OperatingSystem.IsLinux()) diff --git a/v2rayN/v2rayN.Desktop/Common/AvaUtils.cs b/v2rayN/v2rayN.Desktop/Common/AvaUtils.cs index cca01643..bc636bef 100644 --- a/v2rayN/v2rayN.Desktop/Common/AvaUtils.cs +++ b/v2rayN/v2rayN.Desktop/Common/AvaUtils.cs @@ -2,7 +2,7 @@ using Avalonia.Input.Platform; namespace v2rayN.Desktop.Common; -internal class AvaUtils +internal static class AvaUtils { public static async Task GetClipboardData(Window owner) { @@ -48,7 +48,7 @@ internal class AvaUtils return new(fileName); } - var uri = new Uri(Path.Combine(Global.AvaAssets, $"NotifyIcon{index}.ico")); + var uri = new Uri(Path.Combine(AppConfig.AvaAssets, $"NotifyIcon{index}.ico")); using var bitmap = new Bitmap(AssetLoader.Open(uri)); return new(bitmap); } diff --git a/v2rayN/v2rayN.Desktop/Common/UI.cs b/v2rayN/v2rayN.Desktop/Common/UI.cs index c17d8947..c1d10c98 100644 --- a/v2rayN/v2rayN.Desktop/Common/UI.cs +++ b/v2rayN/v2rayN.Desktop/Common/UI.cs @@ -3,9 +3,9 @@ using MsBox.Avalonia; namespace v2rayN.Desktop.Common; -internal class UI +internal static class UI { - private static readonly string caption = Global.AppName; + private static readonly string caption = AppConfig.AppName; public static async Task ShowYesNo(Window owner, string msg) { @@ -28,7 +28,7 @@ internal class UI FileTypeFilter = filter is null ? [FilePickerFileTypes.All, FilePickerFileTypes.ImagePng] : [filter] }); - return files.FirstOrDefault()?.TryGetLocalPath(); + return files is [var first, ..] ? first.TryGetLocalPath() : null; } public static async Task SaveFileDialog(Window owner, string filter) diff --git a/v2rayN/v2rayN.Desktop/Manager/HotkeyManager.cs b/v2rayN/v2rayN.Desktop/Manager/HotkeyManager.cs index f803c538..a0c36588 100644 --- a/v2rayN/v2rayN.Desktop/Manager/HotkeyManager.cs +++ b/v2rayN/v2rayN.Desktop/Manager/HotkeyManager.cs @@ -6,7 +6,7 @@ namespace v2rayN.Desktop.Manager; public sealed class HotkeyManager { private static readonly Lazy _instance = new(() => new()); - public static HotkeyManager Instance = _instance.Value; + public static HotkeyManager Instance => _instance.Value; private readonly Dictionary _hotkeyTriggerDic = new(); private GlobalHotKeys.HotKeyManager? _hotKeyManager; @@ -14,7 +14,7 @@ public sealed class HotkeyManager private event Action? _updateFunc; - public bool IsPause { get; set; } = false; + public bool IsPause { get; set; } public void Init(Config config, Action updateFunc) { diff --git a/v2rayN/v2rayN.Desktop/Program.cs b/v2rayN/v2rayN.Desktop/Program.cs index 70c43130..8c64bdc8 100644 --- a/v2rayN/v2rayN.Desktop/Program.cs +++ b/v2rayN/v2rayN.Desktop/Program.cs @@ -2,7 +2,7 @@ using v2rayN.Desktop.Common; namespace v2rayN.Desktop; -internal class Program +internal static class Program { public static EventWaitHandle ProgramStarted; @@ -27,7 +27,7 @@ internal class Program if (Utils.IsWindows()) { var exePathKey = Utils.GetMd5(Utils.GetExePath()); - var rebootas = (Args ?? []).Any(t => t == Global.RebootAs); + var rebootas = (Args ?? []).Any(t => t == AppConfig.RebootAs); ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, exePathKey, out var bCreatedNew); if (!rebootas && !bCreatedNew) { diff --git a/v2rayN/v2rayN.Desktop/ViewModels/ThemeSettingViewModel.cs b/v2rayN/v2rayN.Desktop/ViewModels/ThemeSettingViewModel.cs index c84a2887..35bacb6e 100644 --- a/v2rayN/v2rayN.Desktop/ViewModels/ThemeSettingViewModel.cs +++ b/v2rayN/v2rayN.Desktop/ViewModels/ThemeSettingViewModel.cs @@ -15,7 +15,7 @@ public class ThemeSettingViewModel : MyReactiveObject public ThemeSettingViewModel() { - _config = AppManager.Instance.Config; + Config = AppManager.Instance.Config; BindingUI(); RestoreUI(); @@ -30,71 +30,64 @@ public class ThemeSettingViewModel : MyReactiveObject private void BindingUI() { - CurrentTheme = _config.UiItem.CurrentTheme; - CurrentFontSize = _config.UiItem.CurrentFontSize; - CurrentLanguage = _config.UiItem.CurrentLanguage; + CurrentTheme = Config.UiItem.CurrentTheme; + CurrentFontSize = Config.UiItem.CurrentFontSize; + CurrentLanguage = Config.UiItem.CurrentLanguage; this.WhenAnyValue(x => x.CurrentTheme) - .Subscribe(c => + .Where(t => t != Config.UiItem.CurrentTheme) + .Select(c => Observable.FromAsync(async () => { - if (_config.UiItem.CurrentTheme != CurrentTheme) - { - _config.UiItem.CurrentTheme = CurrentTheme; - ModifyTheme(); - ConfigHandler.SaveConfig(_config); - } - }); + Config.UiItem.CurrentTheme = c; + ModifyTheme(); + await ConfigHandler.SaveConfig(Config); + })) + .Concat() + .Subscribe(); - this.WhenAnyValue( - x => x.CurrentFontSize, - y => y > 0) - .Subscribe(c => + this.WhenAnyValue(x => x.CurrentFontSize) + .Where(s => s >= AppConfig.MinFontSize && s != Config.UiItem.CurrentFontSize) + .Select(c => Observable.FromAsync(async () => { - if (_config.UiItem.CurrentFontSize != CurrentFontSize && CurrentFontSize >= Global.MinFontSize) - { - _config.UiItem.CurrentFontSize = CurrentFontSize; - ModifyFontSize(); - ConfigHandler.SaveConfig(_config); - } - }); + Config.UiItem.CurrentFontSize = c; + ModifyFontSize(); + await ConfigHandler.SaveConfig(Config); + })) + .Concat() + .Subscribe(); - this.WhenAnyValue( - x => x.CurrentLanguage, - y => y != null && !y.IsNullOrEmpty()) - .Subscribe(c => + this.WhenAnyValue(x => x.CurrentLanguage) + .Where(l => l.IsNotEmpty() && l != Config.UiItem.CurrentLanguage) + .Select(c => Observable.FromAsync(async () => { - if (CurrentLanguage.IsNotEmpty() && _config.UiItem.CurrentLanguage != CurrentLanguage) - { - _config.UiItem.CurrentLanguage = CurrentLanguage; - Thread.CurrentThread.CurrentUICulture = new(CurrentLanguage); - ConfigHandler.SaveConfig(_config); - NoticeManager.Instance.Enqueue(ResUI.NeedRebootTips); - } - }); + Config.UiItem.CurrentLanguage = c; + Thread.CurrentThread.CurrentUICulture = new(c); + await ConfigHandler.SaveConfig(Config); + NoticeManager.Instance.Enqueue(ResUI.NeedRebootTips); + })) + .Concat() + .Subscribe(); } private void ModifyTheme() { var app = Application.Current; - if (app is not null) + app?.RequestedThemeVariant = CurrentTheme switch { - app.RequestedThemeVariant = CurrentTheme switch - { - nameof(ETheme.Dark) => ThemeVariant.Dark, - nameof(ETheme.Light) => ThemeVariant.Light, - nameof(ETheme.Aquatic) => SemiTheme.Aquatic, - nameof(ETheme.Desert) => SemiTheme.Desert, - nameof(ETheme.Dusk) => SemiTheme.Dusk, - nameof(ETheme.NightSky) => SemiTheme.NightSky, - _ => ThemeVariant.Default, - }; - } + nameof(ETheme.Dark) => ThemeVariant.Dark, + nameof(ETheme.Light) => ThemeVariant.Light, + nameof(ETheme.Aquatic) => SemiTheme.Aquatic, + nameof(ETheme.Desert) => SemiTheme.Desert, + nameof(ETheme.Dusk) => SemiTheme.Dusk, + nameof(ETheme.NightSky) => SemiTheme.NightSky, + _ => ThemeVariant.Default, + }; } private void ModifyFontSize() { double size = CurrentFontSize; - if (size < Global.MinFontSize) + if (size < AppConfig.MinFontSize) { return; } @@ -121,7 +114,7 @@ public class ThemeSettingViewModel : MyReactiveObject ModifyFontSizeEx(size); } - private void ModifyFontSizeEx(double size) + private static void ModifyFontSizeEx(double size) { //DataGrid var rowHeight = 20 + (size / 2); @@ -130,9 +123,9 @@ public class ThemeSettingViewModel : MyReactiveObject Application.Current?.Styles.Add(style); } - private void ModifyFontFamily() + private static void ModifyFontFamily() { - var currentFontFamily = _config.UiItem.CurrentFontFamily; + var currentFontFamily = Config.UiItem.CurrentFontFamily; if (currentFontFamily.IsNullOrEmpty()) { return; diff --git a/v2rayN/v2rayN.Desktop/Views/AddGroupServerWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/AddGroupServerWindow.axaml.cs index 26827350..50adab19 100644 --- a/v2rayN/v2rayN.Desktop/Views/AddGroupServerWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/AddGroupServerWindow.axaml.cs @@ -19,7 +19,7 @@ public partial class AddGroupServerWindow : WindowBase ViewModel = new AddGroupServerViewModel(profileItem, UpdateViewHandler); - cmbCoreType.ItemsSource = Global.CoreTypes; + cmbCoreType.ItemsSource = AppConfig.CoreTypes; cmbPolicyGroupType.ItemsSource = new List { ResUI.TbLeastPing, @@ -162,9 +162,6 @@ public partial class AddGroupServerWindow : WindowBase private void LstChild_SelectionChanged(object? sender, SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedChildren = lstChild.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedChildren = lstChild.SelectedItems.Cast().ToList(); } } diff --git a/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml.cs index 9220e8ae..14f623d9 100644 --- a/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/AddServerWindow.axaml.cs @@ -22,26 +22,26 @@ public partial class AddServerWindow : WindowBase ViewModel = new AddServerViewModel(profileItem, UpdateViewHandler); - cmbCoreType.ItemsSource = Global.CoreTypes.AppendEmpty(); - cmbNetwork.ItemsSource = Global.Networks; - cmbFingerprint.ItemsSource = Global.Fingerprints; - cmbFingerprint2.ItemsSource = Global.Fingerprints; - cmbAllowInsecure.ItemsSource = Global.AllowInsecure; - cmbAlpn.ItemsSource = Global.Alpns; - cmbEchForceQuery.ItemsSource = Global.EchForceQuerys; + cmbCoreType.ItemsSource = AppConfig.CoreTypes.AppendEmpty(); + cmbNetwork.ItemsSource = AppConfig.Networks; + cmbFingerprint.ItemsSource = AppConfig.Fingerprints; + cmbFingerprint2.ItemsSource = AppConfig.Fingerprints; + cmbAllowInsecure.ItemsSource = AppConfig.AllowInsecure; + cmbAlpn.ItemsSource = AppConfig.Alpns; + cmbEchForceQuery.ItemsSource = AppConfig.EchForceQuerys; var lstStreamSecurity = new List(); lstStreamSecurity.Add(string.Empty); - lstStreamSecurity.Add(Global.StreamSecurity); + lstStreamSecurity.Add(AppConfig.StreamSecurity); switch (profileItem.ConfigType) { case EConfigType.VMess: gridVMess.IsVisible = true; - cmbSecurity.ItemsSource = Global.VmessSecurities; + cmbSecurity.ItemsSource = AppConfig.VmessSecurities; if (profileItem.Security.IsNullOrEmpty()) { - profileItem.Security = Global.DefaultSecurity; + profileItem.Security = AppConfig.DefaultSecurity; } break; @@ -57,18 +57,18 @@ public partial class AddServerWindow : WindowBase case EConfigType.VLESS: gridVLESS.IsVisible = true; - lstStreamSecurity.Add(Global.StreamSecurityReality); - cmbFlow5.ItemsSource = Global.Flows; + lstStreamSecurity.Add(AppConfig.StreamSecurityReality); + cmbFlow5.ItemsSource = AppConfig.Flows; if (profileItem.Security.IsNullOrEmpty()) { - profileItem.Security = Global.None; + profileItem.Security = AppConfig.None; } break; case EConfigType.Trojan: gridTrojan.IsVisible = true; - lstStreamSecurity.Add(Global.StreamSecurityReality); - cmbFlow6.ItemsSource = Global.Flows; + lstStreamSecurity.Add(AppConfig.StreamSecurityReality); + cmbFlow6.ItemsSource = AppConfig.Flows; break; case EConfigType.Hysteria2: @@ -87,7 +87,7 @@ public partial class AddServerWindow : WindowBase cmbFingerprint.IsEnabled = false; cmbFingerprint.SelectedValue = string.Empty; - cmbHeaderType8.ItemsSource = Global.TuicCongestionControls; + cmbHeaderType8.ItemsSource = AppConfig.TuicCongestionControls; break; case EConfigType.WireGuard: @@ -101,7 +101,7 @@ public partial class AddServerWindow : WindowBase case EConfigType.Anytls: gridAnytls.IsVisible = true; - lstStreamSecurity.Add(Global.StreamSecurityReality); + lstStreamSecurity.Add(AppConfig.StreamSecurityReality); cmbCoreType.IsEnabled = false; break; } @@ -232,12 +232,12 @@ public partial class AddServerWindow : WindowBase private void CmbStreamSecurity_SelectionChanged(object? sender, SelectionChangedEventArgs e) { var security = cmbStreamSecurity.SelectedItem.ToString(); - if (security == Global.StreamSecurityReality) + if (security == AppConfig.StreamSecurityReality) { gridRealityMore.IsVisible = true; gridTlsMore.IsVisible = false; } - else if (security == Global.StreamSecurity) + else if (security == AppConfig.StreamSecurity) { gridRealityMore.IsVisible = false; gridTlsMore.IsVisible = true; @@ -262,7 +262,7 @@ public partial class AddServerWindow : WindowBase var network = cmbNetwork.SelectedItem.ToString(); if (network.IsNullOrEmpty()) { - lstHeaderType.Add(Global.None); + lstHeaderType.Add(AppConfig.None); cmbHeaderType.ItemsSource = lstHeaderType; cmbHeaderType.SelectedIndex = 0; return; @@ -270,26 +270,26 @@ public partial class AddServerWindow : WindowBase if (network == nameof(ETransport.tcp)) { - lstHeaderType.Add(Global.None); - lstHeaderType.Add(Global.TcpHeaderHttp); + lstHeaderType.Add(AppConfig.None); + lstHeaderType.Add(AppConfig.TcpHeaderHttp); } else if (network is nameof(ETransport.kcp) or nameof(ETransport.quic)) { - lstHeaderType.Add(Global.None); - lstHeaderType.AddRange(Global.KcpHeaderTypes); + lstHeaderType.Add(AppConfig.None); + lstHeaderType.AddRange(AppConfig.KcpHeaderTypes); } else if (network is nameof(ETransport.xhttp)) { - lstHeaderType.AddRange(Global.XhttpMode); + lstHeaderType.AddRange(AppConfig.XhttpMode); } else if (network == nameof(ETransport.grpc)) { - lstHeaderType.Add(Global.GrpcGunMode); - lstHeaderType.Add(Global.GrpcMultiMode); + lstHeaderType.Add(AppConfig.GrpcGunMode); + lstHeaderType.Add(AppConfig.GrpcMultiMode); } else { - lstHeaderType.Add(Global.None); + lstHeaderType.Add(AppConfig.None); } cmbHeaderType.ItemsSource = lstHeaderType; cmbHeaderType.SelectedIndex = 0; @@ -300,7 +300,7 @@ public partial class AddServerWindow : WindowBase var network = cmbNetwork.SelectedItem.ToString(); if (network.IsNullOrEmpty()) { - network = Global.DefaultNetwork; + network = AppConfig.DefaultNetwork; } labHeaderType.IsVisible = true; btnExtra.IsVisible = false; diff --git a/v2rayN/v2rayN.Desktop/Views/BackupAndRestoreView.axaml.cs b/v2rayN/v2rayN.Desktop/Views/BackupAndRestoreView.axaml.cs index 391f2892..7b2920de 100644 --- a/v2rayN/v2rayN.Desktop/Views/BackupAndRestoreView.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/BackupAndRestoreView.axaml.cs @@ -4,7 +4,7 @@ namespace v2rayN.Desktop.Views; public partial class BackupAndRestoreView : ReactiveUserControl { - private Window? _window; + private readonly Window? _window; public BackupAndRestoreView() { diff --git a/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml.cs index e673a025..60106e83 100644 --- a/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/DNSSettingWindow.axaml.cs @@ -15,18 +15,18 @@ public partial class DNSSettingWindow : WindowBase btnCancel.Click += (s, e) => Close(); ViewModel = new DNSSettingViewModel(UpdateViewHandler); - cmbRayFreedomDNSStrategy.ItemsSource = Global.DomainStrategy4Freedoms; - cmbSBDirectDNSStrategy.ItemsSource = Global.SingboxDomainStrategy4Out; - cmbSBRemoteDNSStrategy.ItemsSource = Global.SingboxDomainStrategy4Out; - cmbDirectDNS.ItemsSource = Global.DomainDirectDNSAddress; - cmbRemoteDNS.ItemsSource = Global.DomainRemoteDNSAddress; - cmbBootstrapDNS.ItemsSource = Global.DomainPureIPDNSAddress; - cmbDirectExpectedIPs.ItemsSource = Global.ExpectedIPs; + cmbRayFreedomDNSStrategy.ItemsSource = AppConfig.DomainStrategy4Freedoms; + cmbSBDirectDNSStrategy.ItemsSource = AppConfig.SingboxDomainStrategy4Out; + cmbSBRemoteDNSStrategy.ItemsSource = AppConfig.SingboxDomainStrategy4Out; + cmbDirectDNS.ItemsSource = AppConfig.DomainDirectDNSAddress; + cmbRemoteDNS.ItemsSource = AppConfig.DomainRemoteDNSAddress; + cmbBootstrapDNS.ItemsSource = AppConfig.DomainPureIPDNSAddress; + cmbDirectExpectedIPs.ItemsSource = AppConfig.ExpectedIPs; - cmbdomainStrategy4FreedomCompatible.ItemsSource = Global.DomainStrategy4Freedoms; - cmbdomainStrategy4OutCompatible.ItemsSource = Global.SingboxDomainStrategy4Out; - cmbdomainDNSAddressCompatible.ItemsSource = Global.DomainPureIPDNSAddress; - cmbdomainDNSAddress2Compatible.ItemsSource = Global.DomainPureIPDNSAddress; + cmbdomainStrategy4FreedomCompatible.ItemsSource = AppConfig.DomainStrategy4Freedoms; + cmbdomainStrategy4OutCompatible.ItemsSource = AppConfig.SingboxDomainStrategy4Out; + cmbdomainDNSAddressCompatible.ItemsSource = AppConfig.DomainPureIPDNSAddress; + cmbdomainDNSAddress2Compatible.ItemsSource = AppConfig.DomainPureIPDNSAddress; this.WhenActivated(disposables => { diff --git a/v2rayN/v2rayN.Desktop/Views/GlobalHotkeySettingWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/GlobalHotkeySettingWindow.axaml.cs index 599eba7e..8ccaa3f1 100644 --- a/v2rayN/v2rayN.Desktop/Views/GlobalHotkeySettingWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/GlobalHotkeySettingWindow.axaml.cs @@ -99,7 +99,7 @@ public partial class GlobalHotkeySettingWindow : WindowBase { private static Config _config; + private static readonly CompositeFormat _menuWebsiteItemFormat = CompositeFormat.Parse(ResUI.menuWebsiteItem); private readonly WindowNotificationManager? _manager; private CheckUpdateView? _checkUpdateView; private BackupAndRestoreView? _backupAndRestoreView; - private bool _blCloseByUser = false; + private bool _blCloseByUser; public MainWindow() { @@ -316,7 +317,7 @@ public partial class MainWindow : WindowBase private void MenuPromotion_Click(object? sender, RoutedEventArgs e) { - ProcUtils.ProcessStart($"{Utils.Base64Decode(Global.PromotionUrl)}?t={DateTime.Now.Ticks}"); + ProcUtils.ProcessStart($"{Utils.Base64Decode(AppConfig.PromotionUrl)}?t={DateTime.Now.Ticks}"); } private void MenuSettingsSetUWP_Click(object? sender, RoutedEventArgs e) @@ -333,7 +334,7 @@ public partial class MainWindow : WindowBase } } - public async Task ScanScreenTaskAsync() + public static async Task ScanScreenTaskAsync() { //ShowHideWindow(false); @@ -487,10 +488,11 @@ public partial class MainWindow : WindowBase .Where(t => t.CoreType is not ECoreType.v2fly and not ECoreType.hysteria)) { + var coreName = it.CoreType.ToString().Replace("_", " "); var item = new MenuItem() { Tag = it.Url?.Replace(@"/releases", ""), - Header = string.Format(ResUI.menuWebsiteItem, it.CoreType.ToString().Replace("_", " ")).UpperFirstChar() + Header = string.Format(CultureInfo.CurrentCulture, _menuWebsiteItemFormat, coreName).UpperFirstChar() }; item.Click += MenuItem_Click; menuHelp.Items.Add(item); diff --git a/v2rayN/v2rayN.Desktop/Views/MsgView.axaml.cs b/v2rayN/v2rayN.Desktop/Views/MsgView.axaml.cs index 78b0a4a1..87cc3939 100644 --- a/v2rayN/v2rayN.Desktop/Views/MsgView.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/MsgView.axaml.cs @@ -18,7 +18,7 @@ public partial class MsgView : ReactiveUserControl this.Bind(ViewModel, vm => vm.AutoRefresh, v => v.togAutoRefresh.IsChecked).DisposeWith(disposables); }); - TextEditorKeywordHighlighter.Attach(txtMsg, Global.LogLevelColors.ToDictionary( + TextEditorKeywordHighlighter.Attach(txtMsg, AppConfig.LogLevelColors.ToDictionary( kv => kv.Key, kv => (IBrush)new SolidColorBrush(Color.Parse(kv.Value)) )); @@ -78,13 +78,13 @@ public partial class MsgView : ReactiveUserControl private async void menuMsgViewCopy_Click(object? sender, RoutedEventArgs e) { - var data = txtMsg.SelectedText.TrimEx(); + var data = txtMsg.SelectedText.TrimSafe(); await AvaUtils.SetClipboardData(this, data); } private async void menuMsgViewCopyAll_Click(object? sender, RoutedEventArgs e) { - var data = txtMsg.Text.TrimEx(); + var data = txtMsg.Text.TrimSafe(); await AvaUtils.SetClipboardData(this, data); } diff --git a/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs index 5d0009d8..8c47962a 100644 --- a/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs @@ -21,38 +21,38 @@ public partial class OptionSettingWindow : WindowBase btnBrowseCustomSystemProxyPacPath.Click += BtnBrowseCustomSystemProxyPacPath_Click; btnBrowseCustomSystemProxyScriptPath.Click += BtnBrowseCustomSystemProxyScriptPath_Click; - clbdestOverride.ItemsSource = Global.destOverrideProtocols; + clbdestOverride.ItemsSource = AppConfig.destOverrideProtocols; _config.Inbound.First().DestOverride?.ForEach(it => { clbdestOverride.SelectedItems.Add(it); }); - cmbsystemProxyAdvancedProtocol.ItemsSource = Global.IEProxyProtocols; - cmbloglevel.ItemsSource = Global.LogLevels; - cmbdefFingerprint.ItemsSource = Global.Fingerprints; - cmbdefUserAgent.ItemsSource = Global.UserAgent; - cmbmux4SboxProtocol.ItemsSource = Global.SingboxMuxs; - cmbMtu.ItemsSource = Global.TunMtus; - cmbStack.ItemsSource = Global.TunStacks; + cmbsystemProxyAdvancedProtocol.ItemsSource = AppConfig.IEProxyProtocols; + cmbloglevel.ItemsSource = AppConfig.LogLevels; + cmbdefFingerprint.ItemsSource = AppConfig.Fingerprints; + cmbdefUserAgent.ItemsSource = AppConfig.UserAgent; + cmbmux4SboxProtocol.ItemsSource = AppConfig.SingboxMuxs; + cmbMtu.ItemsSource = AppConfig.TunMtus; + cmbStack.ItemsSource = AppConfig.TunStacks; - cmbCoreType1.ItemsSource = Global.CoreTypes; - cmbCoreType2.ItemsSource = Global.CoreTypes; - cmbCoreType3.ItemsSource = Global.CoreTypes; - cmbCoreType4.ItemsSource = Global.CoreTypes; - cmbCoreType5.ItemsSource = Global.CoreTypes; - cmbCoreType6.ItemsSource = Global.CoreTypes; - cmbCoreType7.ItemsSource = Global.CoreTypes; - cmbCoreType9.ItemsSource = Global.CoreTypes; + cmbCoreType1.ItemsSource = AppConfig.CoreTypes; + cmbCoreType2.ItemsSource = AppConfig.CoreTypes; + cmbCoreType3.ItemsSource = AppConfig.CoreTypes; + cmbCoreType4.ItemsSource = AppConfig.CoreTypes; + cmbCoreType5.ItemsSource = AppConfig.CoreTypes; + cmbCoreType6.ItemsSource = AppConfig.CoreTypes; + cmbCoreType7.ItemsSource = AppConfig.CoreTypes; + cmbCoreType9.ItemsSource = AppConfig.CoreTypes; cmbMixedConcurrencyCount.ItemsSource = Enumerable.Range(2, 7).ToList(); cmbSpeedTestTimeout.ItemsSource = Enumerable.Range(2, 5).Select(i => i * 5).ToList(); - cmbSpeedTestUrl.ItemsSource = Global.SpeedTestUrls; - cmbSpeedPingTestUrl.ItemsSource = Global.SpeedPingTestUrls; - cmbSubConvertUrl.ItemsSource = Global.SubConvertUrls; - cmbGetFilesSourceUrl.ItemsSource = Global.GeoFilesSources; - cmbSrsFilesSourceUrl.ItemsSource = Global.SingboxRulesetSources; - cmbRoutingRulesSourceUrl.ItemsSource = Global.RoutingRulesSources; - cmbIPAPIUrl.ItemsSource = Global.IPAPIUrls; + cmbSpeedTestUrl.ItemsSource = AppConfig.SpeedTestUrls; + cmbSpeedPingTestUrl.ItemsSource = AppConfig.SpeedPingTestUrls; + cmbSubConvertUrl.ItemsSource = AppConfig.SubConvertUrls; + cmbGetFilesSourceUrl.ItemsSource = AppConfig.GeoFilesSources; + cmbSrsFilesSourceUrl.ItemsSource = AppConfig.SingboxRulesetSources; + cmbRoutingRulesSourceUrl.ItemsSource = AppConfig.RoutingRulesSources; + cmbIPAPIUrl.ItemsSource = AppConfig.IPAPIUrls; cmbMainGirdOrientation.ItemsSource = Utils.GetEnumNames(); @@ -153,7 +153,7 @@ public partial class OptionSettingWindow : WindowBase cmbcurrentFontFamily.ItemsSource = lstFonts; } - private async Task> GetFonts() + private static async Task> GetFonts() { var lstFonts = new List(); try @@ -164,7 +164,7 @@ public partial class OptionSettingWindow : WindowBase } else if (Utils.IsNonWindows()) { - var result = await Utils.GetLinuxFontFamily("zh"); + var result = await Utils.GetLinuxFontFamily(); if (result.IsNullOrEmpty()) { return lstFonts; @@ -188,10 +188,7 @@ public partial class OptionSettingWindow : WindowBase private void ClbdestOverride_SelectionChanged(object? sender, SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.destOverride = clbdestOverride.SelectedItems.Cast().ToList(); - } + ViewModel?.destOverride = clbdestOverride.SelectedItems.Cast().ToList(); } private async void BtnBrowseCustomSystemProxyPacPath_Click(object? sender, RoutedEventArgs e) diff --git a/v2rayN/v2rayN.Desktop/Views/ProfilesSelectWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/ProfilesSelectWindow.axaml.cs index 297c9ae0..0e108d99 100644 --- a/v2rayN/v2rayN.Desktop/Views/ProfilesSelectWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/ProfilesSelectWindow.axaml.cs @@ -9,7 +9,7 @@ public partial class ProfilesSelectWindow : WindowBase public Task ProfileItem => GetProfileItem(); public Task?> ProfileItems => GetProfileItems(); - private bool _allowMultiSelect = false; + private bool _allowMultiSelect; public ProfilesSelectWindow() { @@ -77,10 +77,7 @@ public partial class ProfilesSelectWindow : WindowBase private void LstProfiles_SelectionChanged(object? sender, SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedProfiles = lstProfiles.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedProfiles = lstProfiles.SelectedItems.Cast().ToList(); } private void LstProfiles_LoadingRow(object? sender, DataGridRowEventArgs e) diff --git a/v2rayN/v2rayN.Desktop/Views/ProfilesView.axaml.cs b/v2rayN/v2rayN.Desktop/Views/ProfilesView.axaml.cs index aaebb518..c0bec059 100644 --- a/v2rayN/v2rayN.Desktop/Views/ProfilesView.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/ProfilesView.axaml.cs @@ -6,7 +6,7 @@ namespace v2rayN.Desktop.Views; public partial class ProfilesView : ReactiveUserControl { private static Config _config; - private Window? _window; + private readonly Window? _window; public ProfilesView() { @@ -28,7 +28,7 @@ public partial class ProfilesView : ReactiveUserControl lstProfiles.DoubleTapped += LstProfiles_DoubleTapped; lstProfiles.LoadingRow += LstProfiles_LoadingRow; lstProfiles.Sorting += LstProfiles_Sorting; - //if (_config.uiItem.enableDragDropSort) + //if (Config.uiItem.enableDragDropSort) //{ // lstProfiles.AllowDrop = true; // lstProfiles.PreviewMouseLeftButtonDown += LstProfiles_PreviewMouseLeftButtonDown; @@ -208,7 +208,7 @@ public partial class ProfilesView : ReactiveUserControl return await Task.FromResult(true); } - public async Task ShareServer(string url) + public static async Task ShareServer(string url) { if (url.IsNullOrEmpty()) { @@ -229,10 +229,7 @@ public partial class ProfilesView : ReactiveUserControl private void lstProfiles_SelectionChanged(object? sender, SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedProfiles = lstProfiles.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedProfiles = lstProfiles.SelectedItems.Cast().ToList(); } private void LstProfiles_DoubleTapped(object? sender, Avalonia.Input.TappedEventArgs e) @@ -424,7 +421,7 @@ public partial class ProfilesView : ReactiveUserControl item2.Width = new DataGridLength(item.Width, DataGridLengthUnitType.Pixel); item2.DisplayIndex = displayIndex++; } - if (item.Name.ToLower().StartsWith("to")) + if (item.Name.StartsWith("to", StringComparison.OrdinalIgnoreCase)) { item2.IsVisible = _config.GuiItem.EnableStatistics; } diff --git a/v2rayN/v2rayN.Desktop/Views/QrcodeView.axaml.cs b/v2rayN/v2rayN.Desktop/Views/QrcodeView.axaml.cs index 3f1e7149..71612987 100644 --- a/v2rayN/v2rayN.Desktop/Views/QrcodeView.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/QrcodeView.axaml.cs @@ -17,7 +17,7 @@ public partial class QrcodeView : UserControl txtContent.GotFocus += (_, _) => Dispatcher.UIThread.Post(() => { txtContent.SelectAll(); }); } - private Bitmap? GetQRCode(string? url) + private static Bitmap? GetQRCode(string? url) { try { @@ -31,7 +31,7 @@ public partial class QrcodeView : UserControl } } - private Bitmap? ByteToBitmap(byte[]? bytes) + private static Bitmap? ByteToBitmap(byte[]? bytes) { if (bytes is null) { diff --git a/v2rayN/v2rayN.Desktop/Views/RoutingRuleDetailsWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/RoutingRuleDetailsWindow.axaml.cs index e2979244..4740ddf8 100644 --- a/v2rayN/v2rayN.Desktop/Views/RoutingRuleDetailsWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/RoutingRuleDetailsWindow.axaml.cs @@ -20,10 +20,10 @@ public partial class RoutingRuleDetailsWindow : WindowBase().AppendEmpty(); if (!rulesItem.Id.IsNullOrEmpty()) @@ -74,18 +74,12 @@ public partial class RoutingRuleDetailsWindow : WindowBase().ToList(); - } + ViewModel?.ProtocolItems = clbProtocol.SelectedItems.Cast().ToList(); } private void ClbInboundTag_SelectionChanged(object? sender, SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.InboundTagItems = clbInboundTag.SelectedItems.Cast().ToList(); - } + ViewModel?.InboundTagItems = clbInboundTag.SelectedItems.Cast().ToList(); } private void linkRuleobjectDoc_Click(object? sender, RoutedEventArgs e) diff --git a/v2rayN/v2rayN.Desktop/Views/RoutingRuleSettingWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/RoutingRuleSettingWindow.axaml.cs index 076307ec..1a9f82d8 100644 --- a/v2rayN/v2rayN.Desktop/Views/RoutingRuleSettingWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/RoutingRuleSettingWindow.axaml.cs @@ -25,8 +25,8 @@ public partial class RoutingRuleSettingWindow : WindowBase { @@ -168,10 +168,7 @@ public partial class RoutingRuleSettingWindow : WindowBase().ToList(); - } + ViewModel?.SelectedSources = lstRules.SelectedItems.Cast().ToList(); } private void LstRules_DoubleTapped(object? sender, Avalonia.Input.TappedEventArgs e) diff --git a/v2rayN/v2rayN.Desktop/Views/RoutingSettingWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/RoutingSettingWindow.axaml.cs index 719acf94..f95b1764 100644 --- a/v2rayN/v2rayN.Desktop/Views/RoutingSettingWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/RoutingSettingWindow.axaml.cs @@ -5,7 +5,7 @@ namespace v2rayN.Desktop.Views; public partial class RoutingSettingWindow : WindowBase { - private bool _manualClose = false; + private bool _manualClose; public RoutingSettingWindow() { @@ -21,8 +21,8 @@ public partial class RoutingSettingWindow : WindowBase ViewModel = new RoutingSettingViewModel(UpdateViewHandler); - cmbdomainStrategy.ItemsSource = Global.DomainStrategies; - cmbdomainStrategy4Singbox.ItemsSource = Global.DomainStrategies4Singbox; + cmbdomainStrategy.ItemsSource = AppConfig.DomainStrategies; + cmbdomainStrategy4Singbox.ItemsSource = AppConfig.DomainStrategies4Singbox; this.WhenActivated(disposables => { @@ -104,10 +104,7 @@ public partial class RoutingSettingWindow : WindowBase private void lstRoutings_SelectionChanged(object? sender, SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedSources = lstRoutings.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedSources = lstRoutings.SelectedItems.Cast().ToList(); } private void LstRoutings_DoubleTapped(object? sender, TappedEventArgs e) diff --git a/v2rayN/v2rayN.Desktop/Views/StatusBarView.axaml.cs b/v2rayN/v2rayN.Desktop/Views/StatusBarView.axaml.cs index c5d9ef80..c7fb7ae0 100644 --- a/v2rayN/v2rayN.Desktop/Views/StatusBarView.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/StatusBarView.axaml.cs @@ -69,7 +69,7 @@ public partial class StatusBarView : ReactiveUserControl return await Task.FromResult(true); } - private void RefreshIcon() + private static void RefreshIcon() { if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { diff --git a/v2rayN/v2rayN.Desktop/Views/SubEditWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/SubEditWindow.axaml.cs index 9d749ba8..c2adbc1c 100644 --- a/v2rayN/v2rayN.Desktop/Views/SubEditWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/SubEditWindow.axaml.cs @@ -18,7 +18,7 @@ public partial class SubEditWindow : WindowBase ViewModel = new SubEditViewModel(subItem, UpdateViewHandler); - cmbConvertTarget.ItemsSource = Global.SubConvertTargets; + cmbConvertTarget.ItemsSource = AppConfig.SubConvertTargets; this.WhenActivated(disposables => { diff --git a/v2rayN/v2rayN.Desktop/Views/SubSettingWindow.axaml.cs b/v2rayN/v2rayN.Desktop/Views/SubSettingWindow.axaml.cs index f12a3cf6..0d669690 100644 --- a/v2rayN/v2rayN.Desktop/Views/SubSettingWindow.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/SubSettingWindow.axaml.cs @@ -6,7 +6,7 @@ namespace v2rayN.Desktop.Views; public partial class SubSettingWindow : WindowBase { - private bool _manualClose = false; + private bool _manualClose; public SubSettingWindow() { @@ -74,7 +74,7 @@ public partial class SubSettingWindow : WindowBase return await Task.FromResult(true); } - private async Task ShareSub(string url) + private static async Task ShareSub(string url) { if (url.IsNullOrEmpty()) { @@ -91,10 +91,7 @@ public partial class SubSettingWindow : WindowBase private void LstSubscription_SelectionChanged(object? sender, SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedSources = lstSubscription.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedSources = lstSubscription.SelectedItems.Cast().ToList(); } private void menuClose_Click(object? sender, RoutedEventArgs e) diff --git a/v2rayN/v2rayN.Desktop/Views/SudoPasswordInputView.axaml.cs b/v2rayN/v2rayN.Desktop/Views/SudoPasswordInputView.axaml.cs index 6373c683..8468e4ba 100644 --- a/v2rayN/v2rayN.Desktop/Views/SudoPasswordInputView.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/SudoPasswordInputView.axaml.cs @@ -58,13 +58,13 @@ public partial class SudoPasswordInputView : UserControl } } - private async Task CheckSudoPasswordAsync(string password) + private static async Task CheckSudoPasswordAsync(string password) { try { // Use sudo echo command to verify password var arg = new List() { "-c", "sudo -S echo SUDO_CHECK" }; - var result = await CliWrap.Cli.Wrap(Global.LinuxBash) + var result = await CliWrap.Cli.Wrap(AppConfig.LinuxBash) .WithArguments(arg) .WithStandardInputPipe(CliWrap.PipeSource.FromString(password)) .ExecuteBufferedAsync(); diff --git a/v2rayN/v2rayN.Desktop/Views/ThemeSettingView.axaml.cs b/v2rayN/v2rayN.Desktop/Views/ThemeSettingView.axaml.cs index d3103b11..b2828c27 100644 --- a/v2rayN/v2rayN.Desktop/Views/ThemeSettingView.axaml.cs +++ b/v2rayN/v2rayN.Desktop/Views/ThemeSettingView.axaml.cs @@ -13,8 +13,8 @@ public partial class ThemeSettingView : ReactiveUserControl(); - cmbCurrentFontSize.ItemsSource = Enumerable.Range(Global.MinFontSize, Global.MinFontSizeCount).ToList(); - cmbCurrentLanguage.ItemsSource = Global.Languages; + cmbCurrentFontSize.ItemsSource = Enumerable.Range(AppConfig.MinFontSize, AppConfig.MinFontSizeCount).ToList(); + cmbCurrentLanguage.ItemsSource = AppConfig.Languages; this.WhenActivated(disposables => { diff --git a/v2rayN/v2rayN/App.xaml.cs b/v2rayN/v2rayN/App.xaml.cs index ca56311b..dfd2241b 100644 --- a/v2rayN/v2rayN/App.xaml.cs +++ b/v2rayN/v2rayN/App.xaml.cs @@ -22,7 +22,7 @@ public partial class App : Application { var exePathKey = Utils.GetMd5(Utils.GetExePath()); - var rebootas = (e.Args ?? Array.Empty()).Any(t => t == Global.RebootAs); + var rebootas = (e.Args ?? Array.Empty()).Any(t => t == AppConfig.RebootAs); ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, exePathKey, out var bCreatedNew); if (!rebootas && !bCreatedNew) { diff --git a/v2rayN/v2rayN/Common/UI.cs b/v2rayN/v2rayN/Common/UI.cs index 4ad19a09..e93f5c2d 100644 --- a/v2rayN/v2rayN/Common/UI.cs +++ b/v2rayN/v2rayN/Common/UI.cs @@ -4,7 +4,7 @@ namespace v2rayN.Common; internal class UI { - private static readonly string caption = Global.AppName; + private static readonly string caption = AppConfig.AppName; public static void Show(string msg) { diff --git a/v2rayN/v2rayN/Common/WindowsUtils.cs b/v2rayN/v2rayN/Common/WindowsUtils.cs index 0bf149ca..ce7d96b4 100644 --- a/v2rayN/v2rayN/Common/WindowsUtils.cs +++ b/v2rayN/v2rayN/Common/WindowsUtils.cs @@ -5,7 +5,7 @@ using Microsoft.Win32; namespace v2rayN.Common; -internal static class WindowsUtils +internal static partial class WindowsUtils { private static readonly string _tag = "WindowsUtils"; @@ -39,8 +39,8 @@ internal static class WindowsUtils } } - [DllImport("dwmapi.dll")] - public static extern int DwmSetWindowAttribute(nint hwnd, DWMWINDOWATTRIBUTE attribute, ref int attributeValue, uint attributeSize); + [LibraryImport("dwmapi.dll")] + public static partial int DwmSetWindowAttribute(nint hwnd, DWMWINDOWATTRIBUTE attribute, ref int attributeValue, uint attributeSize); public static ImageSource IconToImageSource(Icon icon) { diff --git a/v2rayN/v2rayN/Manager/HotkeyManager.cs b/v2rayN/v2rayN/Manager/HotkeyManager.cs index 6b6bc546..97bf20f2 100644 --- a/v2rayN/v2rayN/Manager/HotkeyManager.cs +++ b/v2rayN/v2rayN/Manager/HotkeyManager.cs @@ -1,12 +1,15 @@ namespace v2rayN.Manager; -public sealed class HotkeyManager +public sealed partial class HotkeyManager { private static readonly Lazy _instance = new(() => new()); public static HotkeyManager Instance = _instance.Value; private const int WmHotkey = 0x0312; private readonly Dictionary> _hotkeyTriggerDic = new(); + private static readonly CompositeFormat _registerGlobalHotkeySuccessfully = + CompositeFormat.Parse(ResUI.RegisterGlobalHotkeySuccessfully); + public bool IsPause { get; set; } = false; public event Action? UpdateViewEvent; @@ -63,24 +66,24 @@ public sealed class HotkeyManager { foreach (var _hotkeyCode in _hotkeyTriggerDic.Keys) { - var hotkeyInfo = GetHotkeyInfo(_hotkeyCode); + var (fsModifiers, vKey, hotkeyStr, Names) = GetHotkeyInfo(_hotkeyCode); var isSuccess = false; var msg = string.Empty; Application.Current?.Dispatcher.Invoke(() => { - isSuccess = RegisterHotKey(nint.Zero, _hotkeyCode, hotkeyInfo.fsModifiers, hotkeyInfo.vKey); + isSuccess = RegisterHotKey(nint.Zero, _hotkeyCode, fsModifiers, vKey); }); - foreach (var name in hotkeyInfo.Names) + foreach (var name in Names) { if (isSuccess) { - msg = string.Format(ResUI.RegisterGlobalHotkeySuccessfully, $"{name}({hotkeyInfo.hotkeyStr})"); + msg = string.Format(CultureInfo.CurrentCulture, _registerGlobalHotkeySuccessfully, $"{name}({hotkeyStr})"); } else { var errInfo = new Win32Exception(Marshal.GetLastWin32Error()).Message; - msg = string.Format(ResUI.RegisterGlobalHotkeyFailed, $"{name}({hotkeyInfo.hotkeyStr})", errInfo); + msg = string.Format(CultureInfo.CurrentCulture, _registerGlobalHotkeySuccessfully, $"{name}({hotkeyStr})", errInfo); } UpdateViewEvent?.Invoke(false, msg); } @@ -111,17 +114,17 @@ public sealed class HotkeyManager var key = KeyInterop.KeyFromVirtualKey(vKey); if ((modify & KeyModifiers.Ctrl) == KeyModifiers.Ctrl) { - hotkeyStr.Append($"{KeyModifiers.Ctrl}+"); + hotkeyStr.Append(CultureInfo.InvariantCulture, $"{KeyModifiers.Ctrl}+"); } if ((modify & KeyModifiers.Alt) == KeyModifiers.Alt) { - hotkeyStr.Append($"{KeyModifiers.Alt}+"); + hotkeyStr.Append(CultureInfo.InvariantCulture, $"{KeyModifiers.Alt}+"); } if ((modify & KeyModifiers.Shift) == KeyModifiers.Shift) { - hotkeyStr.Append($"{KeyModifiers.Shift}+"); + hotkeyStr.Append(CultureInfo.InvariantCulture, $"{KeyModifiers.Shift}+"); } hotkeyStr.Append(key.ToString()); @@ -165,11 +168,13 @@ public sealed class HotkeyManager } } - [DllImport("user32.dll", SetLastError = true)] - private static extern bool RegisterHotKey(nint hWnd, int id, int fsModifiers, int vlc); + [LibraryImport("user32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool RegisterHotKey(nint hWnd, int id, int fsModifiers, int vlc); - [DllImport("user32.dll", SetLastError = true)] - private static extern bool UnregisterHotKey(nint hWnd, int id); + [LibraryImport("user32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool UnregisterHotKey(nint hWnd, int id); [Flags] private enum KeyModifiers diff --git a/v2rayN/v2rayN/ViewModels/ThemeSettingViewModel.cs b/v2rayN/v2rayN/ViewModels/ThemeSettingViewModel.cs index 2d663eb1..1350db55 100644 --- a/v2rayN/v2rayN/ViewModels/ThemeSettingViewModel.cs +++ b/v2rayN/v2rayN/ViewModels/ThemeSettingViewModel.cs @@ -9,8 +9,7 @@ public class ThemeSettingViewModel : MyReactiveObject { private readonly PaletteHelper _paletteHelper = new(); - private IObservableCollection _swatches = new ObservableCollectionExtended(); - public IObservableCollection Swatches => _swatches; + public IObservableCollection Swatches { get; } = new ObservableCollectionExtended(); [Reactive] public Swatch SelectedSwatch { get; set; } @@ -23,9 +22,9 @@ public class ThemeSettingViewModel : MyReactiveObject public ThemeSettingViewModel() { - _config = AppManager.Instance.Config; + Config = AppManager.Instance.Config; - RegisterSystemColorSet(_config, ModifyTheme); + RegisterSystemColorSet(Config, ModifyTheme); BindingUI(); RestoreUI(); @@ -35,9 +34,9 @@ public class ThemeSettingViewModel : MyReactiveObject { ModifyTheme(); ModifyFontSize(); - if (!_config.UiItem.ColorPrimaryName.IsNullOrEmpty()) + if (!Config.UiItem.ColorPrimaryName.IsNullOrEmpty()) { - var swatch = new SwatchesProvider().Swatches.FirstOrDefault(t => t.Name == _config.UiItem.ColorPrimaryName); + var swatch = new SwatchesProvider().Swatches.FirstOrDefault(t => t.Name == Config.UiItem.ColorPrimaryName); if (swatch != null && swatch.ExemplarHue != null && swatch.ExemplarHue?.Color != null) @@ -49,25 +48,25 @@ public class ThemeSettingViewModel : MyReactiveObject private void BindingUI() { - _swatches.AddRange(new SwatchesProvider().Swatches); - if (!_config.UiItem.ColorPrimaryName.IsNullOrEmpty()) + Swatches.AddRange(new SwatchesProvider().Swatches); + if (!Config.UiItem.ColorPrimaryName.IsNullOrEmpty()) { - SelectedSwatch = _swatches.FirstOrDefault(t => t.Name == _config.UiItem.ColorPrimaryName); + SelectedSwatch = Swatches.FirstOrDefault(t => t.Name == Config.UiItem.ColorPrimaryName); } - CurrentTheme = _config.UiItem.CurrentTheme; - CurrentFontSize = _config.UiItem.CurrentFontSize; - CurrentLanguage = _config.UiItem.CurrentLanguage; + CurrentTheme = Config.UiItem.CurrentTheme; + CurrentFontSize = Config.UiItem.CurrentFontSize; + CurrentLanguage = Config.UiItem.CurrentLanguage; this.WhenAnyValue( x => x.CurrentTheme, y => y != null && !y.IsNullOrEmpty()) .Subscribe(c => { - if (_config.UiItem.CurrentTheme != CurrentTheme) + if (Config.UiItem.CurrentTheme != CurrentTheme) { - _config.UiItem.CurrentTheme = CurrentTheme; + Config.UiItem.CurrentTheme = CurrentTheme; ModifyTheme(); - ConfigHandler.SaveConfig(_config); + ConfigHandler.SaveConfig(Config); } }); @@ -83,11 +82,11 @@ public class ThemeSettingViewModel : MyReactiveObject { return; } - if (_config.UiItem.ColorPrimaryName != SelectedSwatch?.Name) + if (Config.UiItem.ColorPrimaryName != SelectedSwatch?.Name) { - _config.UiItem.ColorPrimaryName = SelectedSwatch?.Name; + Config.UiItem.ColorPrimaryName = SelectedSwatch?.Name; ChangePrimaryColor(SelectedSwatch.ExemplarHue.Color); - ConfigHandler.SaveConfig(_config); + ConfigHandler.SaveConfig(Config); } }); @@ -96,11 +95,11 @@ public class ThemeSettingViewModel : MyReactiveObject y => y > 0) .Subscribe(c => { - if (_config.UiItem.CurrentFontSize != CurrentFontSize) + if (Config.UiItem.CurrentFontSize != CurrentFontSize) { - _config.UiItem.CurrentFontSize = CurrentFontSize; + Config.UiItem.CurrentFontSize = CurrentFontSize; ModifyFontSize(); - ConfigHandler.SaveConfig(_config); + ConfigHandler.SaveConfig(Config); } }); @@ -109,11 +108,11 @@ public class ThemeSettingViewModel : MyReactiveObject y => y != null && !y.IsNullOrEmpty()) .Subscribe(c => { - if (CurrentLanguage.IsNotEmpty() && _config.UiItem.CurrentLanguage != CurrentLanguage) + if (CurrentLanguage.IsNotEmpty() && Config.UiItem.CurrentLanguage != CurrentLanguage) { - _config.UiItem.CurrentLanguage = CurrentLanguage; + Config.UiItem.CurrentLanguage = CurrentLanguage; Thread.CurrentThread.CurrentUICulture = new(CurrentLanguage); - ConfigHandler.SaveConfig(_config); + ConfigHandler.SaveConfig(Config); NoticeManager.Instance.Enqueue(ResUI.NeedRebootTips); } }); @@ -138,7 +137,7 @@ public class ThemeSettingViewModel : MyReactiveObject private void ModifyFontSize() { double size = (long)CurrentFontSize; - if (size < Global.MinFontSize) + if (size < AppConfig.MinFontSize) { return; } diff --git a/v2rayN/v2rayN/Views/AddGroupServerWindow.xaml.cs b/v2rayN/v2rayN/Views/AddGroupServerWindow.xaml.cs index 14f5a7bf..94329de8 100644 --- a/v2rayN/v2rayN/Views/AddGroupServerWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/AddGroupServerWindow.xaml.cs @@ -14,7 +14,7 @@ public partial class AddGroupServerWindow ViewModel = new AddGroupServerViewModel(profileItem, UpdateViewHandler); - cmbCoreType.ItemsSource = Global.CoreTypes; + cmbCoreType.ItemsSource = AppConfig.CoreTypes; cmbPolicyGroupType.ItemsSource = new List { ResUI.TbLeastPing, @@ -138,10 +138,7 @@ public partial class AddGroupServerWindow private void LstChild_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedChildren = lstChild.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedChildren = lstChild.SelectedItems.Cast().ToList(); } private void MenuSelectAllChild_Click(object sender, RoutedEventArgs e) diff --git a/v2rayN/v2rayN/Views/AddServerWindow.xaml.cs b/v2rayN/v2rayN/Views/AddServerWindow.xaml.cs index 1136220d..d2d09632 100644 --- a/v2rayN/v2rayN/Views/AddServerWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/AddServerWindow.xaml.cs @@ -17,26 +17,26 @@ public partial class AddServerWindow ViewModel = new AddServerViewModel(profileItem, UpdateViewHandler); - cmbCoreType.ItemsSource = Global.CoreTypes.AppendEmpty(); - cmbNetwork.ItemsSource = Global.Networks; - cmbFingerprint.ItemsSource = Global.Fingerprints; - cmbFingerprint2.ItemsSource = Global.Fingerprints; - cmbAllowInsecure.ItemsSource = Global.AllowInsecure; - cmbAlpn.ItemsSource = Global.Alpns; - cmbEchForceQuery.ItemsSource = Global.EchForceQuerys; + cmbCoreType.ItemsSource = AppConfig.CoreTypes.AppendEmpty(); + cmbNetwork.ItemsSource = AppConfig.Networks; + cmbFingerprint.ItemsSource = AppConfig.Fingerprints; + cmbFingerprint2.ItemsSource = AppConfig.Fingerprints; + cmbAllowInsecure.ItemsSource = AppConfig.AllowInsecure; + cmbAlpn.ItemsSource = AppConfig.Alpns; + cmbEchForceQuery.ItemsSource = AppConfig.EchForceQuerys; var lstStreamSecurity = new List(); lstStreamSecurity.Add(string.Empty); - lstStreamSecurity.Add(Global.StreamSecurity); + lstStreamSecurity.Add(AppConfig.StreamSecurity); switch (profileItem.ConfigType) { case EConfigType.VMess: gridVMess.Visibility = Visibility.Visible; - cmbSecurity.ItemsSource = Global.VmessSecurities; + cmbSecurity.ItemsSource = AppConfig.VmessSecurities; if (profileItem.Security.IsNullOrEmpty()) { - profileItem.Security = Global.DefaultSecurity; + profileItem.Security = AppConfig.DefaultSecurity; } break; @@ -52,18 +52,18 @@ public partial class AddServerWindow case EConfigType.VLESS: gridVLESS.Visibility = Visibility.Visible; - lstStreamSecurity.Add(Global.StreamSecurityReality); - cmbFlow5.ItemsSource = Global.Flows; + lstStreamSecurity.Add(AppConfig.StreamSecurityReality); + cmbFlow5.ItemsSource = AppConfig.Flows; if (profileItem.Security.IsNullOrEmpty()) { - profileItem.Security = Global.None; + profileItem.Security = AppConfig.None; } break; case EConfigType.Trojan: gridTrojan.Visibility = Visibility.Visible; - lstStreamSecurity.Add(Global.StreamSecurityReality); - cmbFlow6.ItemsSource = Global.Flows; + lstStreamSecurity.Add(AppConfig.StreamSecurityReality); + cmbFlow6.ItemsSource = AppConfig.Flows; break; case EConfigType.Hysteria2: @@ -82,7 +82,7 @@ public partial class AddServerWindow cmbFingerprint.IsEnabled = false; cmbFingerprint.Text = string.Empty; - cmbHeaderType8.ItemsSource = Global.TuicCongestionControls; + cmbHeaderType8.ItemsSource = AppConfig.TuicCongestionControls; break; case EConfigType.WireGuard: @@ -97,7 +97,7 @@ public partial class AddServerWindow case EConfigType.Anytls: gridAnytls.Visibility = Visibility.Visible; cmbCoreType.IsEnabled = false; - lstStreamSecurity.Add(Global.StreamSecurityReality); + lstStreamSecurity.Add(AppConfig.StreamSecurityReality); break; } cmbStreamSecurity.ItemsSource = lstStreamSecurity; @@ -229,12 +229,12 @@ public partial class AddServerWindow private void CmbStreamSecurity_SelectionChanged(object sender, SelectionChangedEventArgs e) { var security = cmbStreamSecurity.SelectedItem.ToString(); - if (security == Global.StreamSecurityReality) + if (security == AppConfig.StreamSecurityReality) { gridRealityMore.Visibility = Visibility.Visible; gridTlsMore.Visibility = Visibility.Hidden; } - else if (security == Global.StreamSecurity) + else if (security == AppConfig.StreamSecurity) { gridRealityMore.Visibility = Visibility.Hidden; gridTlsMore.Visibility = Visibility.Visible; @@ -259,7 +259,7 @@ public partial class AddServerWindow var network = cmbNetwork.SelectedItem.ToString(); if (network.IsNullOrEmpty()) { - lstHeaderType.Add(Global.None); + lstHeaderType.Add(AppConfig.None); cmbHeaderType.ItemsSource = lstHeaderType; cmbHeaderType.SelectedIndex = 0; return; @@ -267,26 +267,26 @@ public partial class AddServerWindow if (network == nameof(ETransport.tcp)) { - lstHeaderType.Add(Global.None); - lstHeaderType.Add(Global.TcpHeaderHttp); + lstHeaderType.Add(AppConfig.None); + lstHeaderType.Add(AppConfig.TcpHeaderHttp); } else if (network is nameof(ETransport.kcp) or nameof(ETransport.quic)) { - lstHeaderType.Add(Global.None); - lstHeaderType.AddRange(Global.KcpHeaderTypes); + lstHeaderType.Add(AppConfig.None); + lstHeaderType.AddRange(AppConfig.KcpHeaderTypes); } else if (network is nameof(ETransport.xhttp)) { - lstHeaderType.AddRange(Global.XhttpMode); + lstHeaderType.AddRange(AppConfig.XhttpMode); } else if (network == nameof(ETransport.grpc)) { - lstHeaderType.Add(Global.GrpcGunMode); - lstHeaderType.Add(Global.GrpcMultiMode); + lstHeaderType.Add(AppConfig.GrpcGunMode); + lstHeaderType.Add(AppConfig.GrpcMultiMode); } else { - lstHeaderType.Add(Global.None); + lstHeaderType.Add(AppConfig.None); } cmbHeaderType.ItemsSource = lstHeaderType; cmbHeaderType.SelectedIndex = 0; @@ -297,7 +297,7 @@ public partial class AddServerWindow var network = cmbNetwork.SelectedItem.ToString(); if (network.IsNullOrEmpty()) { - network = Global.DefaultNetwork; + network = AppConfig.DefaultNetwork; } labHeaderType.Visibility = Visibility.Visible; popExtra.Visibility = Visibility.Hidden; diff --git a/v2rayN/v2rayN/Views/DNSSettingWindow.xaml.cs b/v2rayN/v2rayN/Views/DNSSettingWindow.xaml.cs index 4242063c..561bc266 100644 --- a/v2rayN/v2rayN/Views/DNSSettingWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/DNSSettingWindow.xaml.cs @@ -13,18 +13,18 @@ public partial class DNSSettingWindow ViewModel = new DNSSettingViewModel(UpdateViewHandler); - cmbRayFreedomDNSStrategy.ItemsSource = Global.DomainStrategy4Freedoms; - cmbSBDirectDNSStrategy.ItemsSource = Global.SingboxDomainStrategy4Out; - cmbSBRemoteDNSStrategy.ItemsSource = Global.SingboxDomainStrategy4Out; - cmbDirectDNS.ItemsSource = Global.DomainDirectDNSAddress; - cmbRemoteDNS.ItemsSource = Global.DomainRemoteDNSAddress; - cmbBootstrapDNS.ItemsSource = Global.DomainPureIPDNSAddress; - cmbDirectExpectedIPs.ItemsSource = Global.ExpectedIPs; + cmbRayFreedomDNSStrategy.ItemsSource = AppConfig.DomainStrategy4Freedoms; + cmbSBDirectDNSStrategy.ItemsSource = AppConfig.SingboxDomainStrategy4Out; + cmbSBRemoteDNSStrategy.ItemsSource = AppConfig.SingboxDomainStrategy4Out; + cmbDirectDNS.ItemsSource = AppConfig.DomainDirectDNSAddress; + cmbRemoteDNS.ItemsSource = AppConfig.DomainRemoteDNSAddress; + cmbBootstrapDNS.ItemsSource = AppConfig.DomainPureIPDNSAddress; + cmbDirectExpectedIPs.ItemsSource = AppConfig.ExpectedIPs; - cmbdomainStrategy4FreedomCompatible.ItemsSource = Global.DomainStrategy4Freedoms; - cmbdomainStrategy4OutCompatible.ItemsSource = Global.SingboxDomainStrategy4Out; - cmbdomainDNSAddressCompatible.ItemsSource = Global.DomainPureIPDNSAddress; - cmbdomainDNSAddress2Compatible.ItemsSource = Global.DomainPureIPDNSAddress; + cmbdomainStrategy4FreedomCompatible.ItemsSource = AppConfig.DomainStrategy4Freedoms; + cmbdomainStrategy4OutCompatible.ItemsSource = AppConfig.SingboxDomainStrategy4Out; + cmbdomainDNSAddressCompatible.ItemsSource = AppConfig.DomainPureIPDNSAddress; + cmbdomainDNSAddress2Compatible.ItemsSource = AppConfig.DomainPureIPDNSAddress; this.WhenActivated(disposables => { diff --git a/v2rayN/v2rayN/Views/MainWindow.xaml.cs b/v2rayN/v2rayN/Views/MainWindow.xaml.cs index 93e62aad..d5745a44 100644 --- a/v2rayN/v2rayN/Views/MainWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/MainWindow.xaml.cs @@ -315,7 +315,7 @@ public partial class MainWindow private void MenuPromotion_Click(object sender, RoutedEventArgs e) { - ProcUtils.ProcessStart($"{Utils.Base64Decode(Global.PromotionUrl)}?t={DateTime.Now.Ticks}"); + ProcUtils.ProcessStart($"{Utils.Base64Decode(AppConfig.PromotionUrl)}?t={DateTime.Now.Ticks}"); } private void MenuSettingsSetUWP_Click(object sender, RoutedEventArgs e) diff --git a/v2rayN/v2rayN/Views/MsgView.xaml.cs b/v2rayN/v2rayN/Views/MsgView.xaml.cs index bccb4a5e..9f56abe5 100644 --- a/v2rayN/v2rayN/Views/MsgView.xaml.cs +++ b/v2rayN/v2rayN/Views/MsgView.xaml.cs @@ -21,7 +21,7 @@ public partial class MsgView menuMsgViewCopyAll.Click += menuMsgViewCopyAll_Click; menuMsgViewClear.Click += menuMsgViewClear_Click; - cmbMsgFilter.ItemsSource = Global.PresetMsgFilters; + cmbMsgFilter.ItemsSource = AppConfig.PresetMsgFilters; } private async Task UpdateViewHandler(EViewAction action, object? obj) @@ -71,7 +71,7 @@ public partial class MsgView private void menuMsgViewCopy_Click(object sender, System.Windows.RoutedEventArgs e) { - var data = txtMsg.SelectedText.TrimEx(); + var data = txtMsg.SelectedText.TrimSafe(); WindowsUtils.SetClipboardData(data); } diff --git a/v2rayN/v2rayN/Views/OptionSettingWindow.xaml.cs b/v2rayN/v2rayN/Views/OptionSettingWindow.xaml.cs index 8aa0cd02..009088b7 100644 --- a/v2rayN/v2rayN/Views/OptionSettingWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/OptionSettingWindow.xaml.cs @@ -18,38 +18,38 @@ public partial class OptionSettingWindow clbdestOverride.SelectionChanged += ClbdestOverride_SelectionChanged; btnBrowseCustomSystemProxyPacPath.Click += BtnBrowseCustomSystemProxyPacPath_Click; - clbdestOverride.ItemsSource = Global.destOverrideProtocols; + clbdestOverride.ItemsSource = AppConfig.destOverrideProtocols; _config.Inbound.First().DestOverride?.ForEach(it => { clbdestOverride.SelectedItems.Add(it); }); - cmbsystemProxyAdvancedProtocol.ItemsSource = Global.IEProxyProtocols; - cmbloglevel.ItemsSource = Global.LogLevels; - cmbdefFingerprint.ItemsSource = Global.Fingerprints; - cmbdefUserAgent.ItemsSource = Global.UserAgent; - cmbmux4SboxProtocol.ItemsSource = Global.SingboxMuxs; - cmbMtu.ItemsSource = Global.TunMtus; - cmbStack.ItemsSource = Global.TunStacks; + cmbsystemProxyAdvancedProtocol.ItemsSource = AppConfig.IEProxyProtocols; + cmbloglevel.ItemsSource = AppConfig.LogLevels; + cmbdefFingerprint.ItemsSource = AppConfig.Fingerprints; + cmbdefUserAgent.ItemsSource = AppConfig.UserAgent; + cmbmux4SboxProtocol.ItemsSource = AppConfig.SingboxMuxs; + cmbMtu.ItemsSource = AppConfig.TunMtus; + cmbStack.ItemsSource = AppConfig.TunStacks; - cmbCoreType1.ItemsSource = Global.CoreTypes; - cmbCoreType2.ItemsSource = Global.CoreTypes; - cmbCoreType3.ItemsSource = Global.CoreTypes; - cmbCoreType4.ItemsSource = Global.CoreTypes; - cmbCoreType5.ItemsSource = Global.CoreTypes; - cmbCoreType6.ItemsSource = Global.CoreTypes; - cmbCoreType7.ItemsSource = Global.CoreTypes; - cmbCoreType9.ItemsSource = Global.CoreTypes; + cmbCoreType1.ItemsSource = AppConfig.CoreTypes; + cmbCoreType2.ItemsSource = AppConfig.CoreTypes; + cmbCoreType3.ItemsSource = AppConfig.CoreTypes; + cmbCoreType4.ItemsSource = AppConfig.CoreTypes; + cmbCoreType5.ItemsSource = AppConfig.CoreTypes; + cmbCoreType6.ItemsSource = AppConfig.CoreTypes; + cmbCoreType7.ItemsSource = AppConfig.CoreTypes; + cmbCoreType9.ItemsSource = AppConfig.CoreTypes; cmbMixedConcurrencyCount.ItemsSource = Enumerable.Range(2, 7).ToList(); cmbSpeedTestTimeout.ItemsSource = Enumerable.Range(2, 5).Select(i => i * 5).ToList(); - cmbSpeedTestUrl.ItemsSource = Global.SpeedTestUrls; - cmbSpeedPingTestUrl.ItemsSource = Global.SpeedPingTestUrls; - cmbSubConvertUrl.ItemsSource = Global.SubConvertUrls; - cmbGetFilesSourceUrl.ItemsSource = Global.GeoFilesSources; - cmbSrsFilesSourceUrl.ItemsSource = Global.SingboxRulesetSources; - cmbRoutingRulesSourceUrl.ItemsSource = Global.RoutingRulesSources; - cmbIPAPIUrl.ItemsSource = Global.IPAPIUrls; + cmbSpeedTestUrl.ItemsSource = AppConfig.SpeedTestUrls; + cmbSpeedPingTestUrl.ItemsSource = AppConfig.SpeedPingTestUrls; + cmbSubConvertUrl.ItemsSource = AppConfig.SubConvertUrls; + cmbGetFilesSourceUrl.ItemsSource = AppConfig.GeoFilesSources; + cmbSrsFilesSourceUrl.ItemsSource = AppConfig.SingboxRulesetSources; + cmbRoutingRulesSourceUrl.ItemsSource = AppConfig.RoutingRulesSources; + cmbIPAPIUrl.ItemsSource = AppConfig.IPAPIUrls; cmbMainGirdOrientation.ItemsSource = Utils.GetEnumNames(); @@ -168,7 +168,7 @@ public partial class OptionSettingWindow { files.AddRange(Directory.GetFiles(path, pattern)); } - var culture = _config.UiItem.CurrentLanguage == Global.Languages.First() ? "zh-cn" : "en-us"; + var culture = _config.UiItem.CurrentLanguage == AppConfig.Languages.First() ? "zh-cn" : "en-us"; var culture2 = "en-us"; foreach (var ttf in files) { @@ -210,10 +210,7 @@ public partial class OptionSettingWindow private void ClbdestOverride_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.destOverride = clbdestOverride.SelectedItems.Cast().ToList(); - } + ViewModel?.destOverride = clbdestOverride.SelectedItems.Cast().ToList(); } private void BtnBrowseCustomSystemProxyPacPath_Click(object sender, RoutedEventArgs e) diff --git a/v2rayN/v2rayN/Views/ProfilesSelectWindow.xaml.cs b/v2rayN/v2rayN/Views/ProfilesSelectWindow.xaml.cs index e357044c..a82d3fa8 100644 --- a/v2rayN/v2rayN/Views/ProfilesSelectWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/ProfilesSelectWindow.xaml.cs @@ -79,10 +79,7 @@ public partial class ProfilesSelectWindow private void LstProfiles_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedProfiles = lstProfiles.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedProfiles = lstProfiles.SelectedItems.Cast().ToList(); } private void LstProfiles_LoadingRow(object? sender, DataGridRowEventArgs e) @@ -97,8 +94,7 @@ public partial class ProfilesSelectWindow private void LstProfiles_ColumnHeader_Click(object sender, RoutedEventArgs e) { - var colHeader = sender as DataGridColumnHeader; - if (colHeader == null || colHeader.TabIndex < 0 || colHeader.Column == null) + if (sender is not DataGridColumnHeader colHeader || colHeader.TabIndex < 0 || colHeader.Column == null) { return; } diff --git a/v2rayN/v2rayN/Views/ProfilesView.xaml.cs b/v2rayN/v2rayN/Views/ProfilesView.xaml.cs index 58b468a4..c7843bb1 100644 --- a/v2rayN/v2rayN/Views/ProfilesView.xaml.cs +++ b/v2rayN/v2rayN/Views/ProfilesView.xaml.cs @@ -211,10 +211,7 @@ public partial class ProfilesView private void LstProfiles_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedProfiles = lstProfiles.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedProfiles = lstProfiles.SelectedItems.Cast().ToList(); } private void LstProfiles_LoadingRow(object? sender, DataGridRowEventArgs e) @@ -236,8 +233,7 @@ public partial class ProfilesView private void LstProfiles_ColumnHeader_Click(object sender, RoutedEventArgs e) { - var colHeader = sender as DataGridColumnHeader; - if (colHeader == null || colHeader.TabIndex < 0 || colHeader.Column == null) + if (sender is not DataGridColumnHeader colHeader || colHeader.TabIndex < 0 || colHeader.Column == null) { return; } @@ -365,7 +361,7 @@ public partial class ProfilesView var displayIndex = 0; foreach (var item in lvColumnItem) { - foreach (MyDGTextColumn item2 in lstProfiles.Columns) + foreach (var item2 in lstProfiles.Columns.Cast()) { if (item2.ExName == item.Name) { @@ -378,7 +374,7 @@ public partial class ProfilesView item2.Width = item.Width; item2.DisplayIndex = displayIndex++; } - if (item.Name.ToLower().StartsWith("to")) + if (item.Name.StartsWith("to", StringComparison.OrdinalIgnoreCase)) { item2.Visibility = _config.GuiItem.EnableStatistics ? Visibility.Visible : Visibility.Hidden; } @@ -409,7 +405,7 @@ public partial class ProfilesView private Point startPoint = new(); private int startIndex = -1; - private string formatData = "ProfileItemModel"; + private readonly string formatData = "ProfileItemModel"; /// /// Helper to search up the VisualTree @@ -421,9 +417,9 @@ public partial class ProfilesView { do { - if (current is T) + if (current is T t) { - return (T)current; + return t; } current = VisualTreeHelper.GetParent(current); } diff --git a/v2rayN/v2rayN/Views/RoutingRuleDetailsWindow.xaml.cs b/v2rayN/v2rayN/Views/RoutingRuleDetailsWindow.xaml.cs index e824d324..9fabadad 100644 --- a/v2rayN/v2rayN/Views/RoutingRuleDetailsWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/RoutingRuleDetailsWindow.xaml.cs @@ -13,10 +13,10 @@ public partial class RoutingRuleDetailsWindow ViewModel = new RoutingRuleDetailsViewModel(rulesItem, UpdateViewHandler); - cmbOutboundTag.ItemsSource = Global.OutboundTags; - clbProtocol.ItemsSource = Global.RuleProtocols; - clbInboundTag.ItemsSource = Global.InboundTags; - cmbNetwork.ItemsSource = Global.RuleNetworks; + cmbOutboundTag.ItemsSource = AppConfig.OutboundTags; + clbProtocol.ItemsSource = AppConfig.RuleProtocols; + clbInboundTag.ItemsSource = AppConfig.InboundTags; + cmbNetwork.ItemsSource = AppConfig.RuleNetworks; cmbRuleType.ItemsSource = Utils.GetEnumNames().AppendEmpty(); if (!rulesItem.Id.IsNullOrEmpty()) @@ -67,18 +67,12 @@ public partial class RoutingRuleDetailsWindow private void ClbProtocol_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.ProtocolItems = clbProtocol.SelectedItems.Cast().ToList(); - } + ViewModel?.ProtocolItems = clbProtocol.SelectedItems.Cast().ToList(); } private void ClbInboundTag_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.InboundTagItems = clbInboundTag.SelectedItems.Cast().ToList(); - } + ViewModel?.InboundTagItems = clbInboundTag.SelectedItems.Cast().ToList(); } private void linkRuleobjectDoc_Click(object sender, RoutedEventArgs e) diff --git a/v2rayN/v2rayN/Views/RoutingRuleSettingWindow.xaml b/v2rayN/v2rayN/Views/RoutingRuleSettingWindow.xaml index c8e679a8..2eed6500 100644 --- a/v2rayN/v2rayN/Views/RoutingRuleSettingWindow.xaml +++ b/v2rayN/v2rayN/Views/RoutingRuleSettingWindow.xaml @@ -216,7 +216,7 @@ Margin="{StaticResource Margin4}" VerticalAlignment="Center" Style="{StaticResource ToolbarTextBlock}"> - + diff --git a/v2rayN/v2rayN/Views/RoutingRuleSettingWindow.xaml.cs b/v2rayN/v2rayN/Views/RoutingRuleSettingWindow.xaml.cs index fd0cee6e..5858a59f 100644 --- a/v2rayN/v2rayN/Views/RoutingRuleSettingWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/RoutingRuleSettingWindow.xaml.cs @@ -9,16 +9,16 @@ public partial class RoutingRuleSettingWindow Owner = Application.Current.MainWindow; Loaded += Window_Loaded; PreviewKeyDown += RoutingRuleSettingWindow_PreviewKeyDown; - lstRules.SelectionChanged += lstRules_SelectionChanged; + lstRules.SelectionChanged += LstRules_SelectionChanged; lstRules.MouseDoubleClick += LstRules_MouseDoubleClick; - menuRuleSelectAll.Click += menuRuleSelectAll_Click; - btnBrowseCustomIcon.Click += btnBrowseCustomIcon_Click; - btnBrowseCustomRulesetPath4Singbox.Click += btnBrowseCustomRulesetPath4Singbox_Click; + menuRuleSelectAll.Click += MenuRuleSelectAll_Click; + btnBrowseCustomIcon.Click += BtnBrowseCustomIcon_Click; + btnBrowseCustomRulesetPath4Singbox.Click += BtnBrowseCustomRulesetPath4Singbox_Click; ViewModel = new RoutingRuleSettingViewModel(routingItem, UpdateViewHandler); - cmbdomainStrategy.ItemsSource = Global.DomainStrategies.AppendEmpty(); - cmbdomainStrategy4Singbox.ItemsSource = Global.DomainStrategies4Singbox; + cmbdomainStrategy.ItemsSource = AppConfig.DomainStrategies.AppendEmpty(); + cmbdomainStrategy4Singbox.ItemsSource = AppConfig.DomainStrategies4Singbox; this.WhenActivated(disposables => { @@ -166,12 +166,9 @@ public partial class RoutingRuleSettingWindow } } - private void lstRules_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) + private void LstRules_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedSources = lstRules.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedSources = lstRules.SelectedItems.Cast().ToList(); } private void LstRules_MouseDoubleClick(object sender, MouseButtonEventArgs e) @@ -179,12 +176,12 @@ public partial class RoutingRuleSettingWindow ViewModel?.RuleEditAsync(false); } - private void menuRuleSelectAll_Click(object sender, System.Windows.RoutedEventArgs e) + private void MenuRuleSelectAll_Click(object sender, System.Windows.RoutedEventArgs e) { lstRules.SelectAll(); } - private void btnBrowseCustomIcon_Click(object sender, System.Windows.RoutedEventArgs e) + private void BtnBrowseCustomIcon_Click(object sender, System.Windows.RoutedEventArgs e) { if (UI.OpenFileDialog(out var fileName, "PNG,ICO|*.png;*.ico") != true) @@ -195,7 +192,7 @@ public partial class RoutingRuleSettingWindow txtCustomIcon.Text = fileName; } - private void btnBrowseCustomRulesetPath4Singbox_Click(object sender, RoutedEventArgs e) + private void BtnBrowseCustomRulesetPath4Singbox_Click(object sender, RoutedEventArgs e) { if (UI.OpenFileDialog(out var fileName, "Config|*.json|All|*.*") != true) @@ -206,7 +203,7 @@ public partial class RoutingRuleSettingWindow txtCustomRulesetPath4Singbox.Text = fileName; } - private void linkCustomRulesetPath4Singbox(object sender, RoutedEventArgs e) + private void LinkCustomRulesetPath4Singbox(object sender, RoutedEventArgs e) { ProcUtils.ProcessStart("https://github.com/2dust/v2rayCustomRoutingList/blob/master/singbox_custom_ruleset_example.json"); } diff --git a/v2rayN/v2rayN/Views/RoutingSettingWindow.xaml b/v2rayN/v2rayN/Views/RoutingSettingWindow.xaml index 4e6fb8bc..38a095ba 100644 --- a/v2rayN/v2rayN/Views/RoutingSettingWindow.xaml +++ b/v2rayN/v2rayN/Views/RoutingSettingWindow.xaml @@ -88,7 +88,7 @@ Margin="{StaticResource Margin4}" VerticalAlignment="Center" Style="{StaticResource ToolbarTextBlock}"> - + @@ -107,7 +107,7 @@ Margin="{StaticResource Margin4}" VerticalAlignment="Center" Style="{StaticResource ToolbarTextBlock}"> - + diff --git a/v2rayN/v2rayN/Views/RoutingSettingWindow.xaml.cs b/v2rayN/v2rayN/Views/RoutingSettingWindow.xaml.cs index 98ccdc19..7ad480a1 100644 --- a/v2rayN/v2rayN/Views/RoutingSettingWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/RoutingSettingWindow.xaml.cs @@ -9,15 +9,15 @@ public partial class RoutingSettingWindow Owner = Application.Current.MainWindow; Closing += RoutingSettingWindow_Closing; PreviewKeyDown += RoutingSettingWindow_PreviewKeyDown; - lstRoutings.SelectionChanged += lstRoutings_SelectionChanged; + lstRoutings.SelectionChanged += LstRoutings_SelectionChanged; lstRoutings.MouseDoubleClick += LstRoutings_MouseDoubleClick; - menuRoutingAdvancedSelectAll.Click += menuRoutingAdvancedSelectAll_Click; - btnCancel.Click += btnCancel_Click; + menuRoutingAdvancedSelectAll.Click += MenuRoutingAdvancedSelectAll_Click; + btnCancel.Click += BtnCancel_Click; ViewModel = new RoutingSettingViewModel(UpdateViewHandler); - cmbdomainStrategy.ItemsSource = Global.DomainStrategies; - cmbdomainStrategy4Singbox.ItemsSource = Global.DomainStrategies4Singbox; + cmbdomainStrategy.ItemsSource = AppConfig.DomainStrategies; + cmbdomainStrategy4Singbox.ItemsSource = AppConfig.DomainStrategies4Singbox; this.WhenActivated(disposables => { @@ -102,17 +102,14 @@ public partial class RoutingSettingWindow } } - private void menuRoutingAdvancedSelectAll_Click(object sender, System.Windows.RoutedEventArgs e) + private void MenuRoutingAdvancedSelectAll_Click(object sender, RoutedEventArgs e) { lstRoutings.SelectAll(); } - private void lstRoutings_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) + private void LstRoutings_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedSources = lstRoutings.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedSources = lstRoutings.SelectedItems.Cast().ToList(); } private void LstRoutings_MouseDoubleClick(object sender, MouseButtonEventArgs e) @@ -120,17 +117,17 @@ public partial class RoutingSettingWindow ViewModel?.RoutingAdvancedEditAsync(false); } - private void linkdomainStrategy_Click(object sender, System.Windows.RoutedEventArgs e) + private void LinkdomainStrategy_Click(object sender, RoutedEventArgs e) { ProcUtils.ProcessStart("https://xtls.github.io/config/routing.html"); } - private void linkdomainStrategy4Singbox_Click(object sender, RoutedEventArgs e) + private void LinkdomainStrategy4Singbox_Click(object sender, RoutedEventArgs e) { ProcUtils.ProcessStart("https://sing-box.sagernet.org/zh/configuration/route/rule_action/#strategy"); } - private void btnCancel_Click(object sender, System.Windows.RoutedEventArgs e) + private void BtnCancel_Click(object sender, RoutedEventArgs e) { if (ViewModel?.IsModified == true) { diff --git a/v2rayN/v2rayN/Views/SubEditWindow.xaml.cs b/v2rayN/v2rayN/Views/SubEditWindow.xaml.cs index d1451a9c..e1b0da00 100644 --- a/v2rayN/v2rayN/Views/SubEditWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/SubEditWindow.xaml.cs @@ -11,7 +11,7 @@ public partial class SubEditWindow ViewModel = new SubEditViewModel(subItem, UpdateViewHandler); - cmbConvertTarget.ItemsSource = Global.SubConvertTargets; + cmbConvertTarget.ItemsSource = AppConfig.SubConvertTargets; this.WhenActivated(disposables => { diff --git a/v2rayN/v2rayN/Views/SubSettingWindow.xaml.cs b/v2rayN/v2rayN/Views/SubSettingWindow.xaml.cs index 12f8a577..d068a688 100644 --- a/v2rayN/v2rayN/Views/SubSettingWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/SubSettingWindow.xaml.cs @@ -100,10 +100,7 @@ public partial class SubSettingWindow private void LstSubscription_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { - if (ViewModel != null) - { - ViewModel.SelectedSources = lstSubscription.SelectedItems.Cast().ToList(); - } + ViewModel?.SelectedSources = lstSubscription.SelectedItems.Cast().ToList(); } private void menuClose_Click(object sender, System.Windows.RoutedEventArgs e) diff --git a/v2rayN/v2rayN/Views/ThemeSettingView.xaml.cs b/v2rayN/v2rayN/Views/ThemeSettingView.xaml.cs index 000d3fa4..06684d1d 100644 --- a/v2rayN/v2rayN/Views/ThemeSettingView.xaml.cs +++ b/v2rayN/v2rayN/Views/ThemeSettingView.xaml.cs @@ -13,8 +13,8 @@ public partial class ThemeSettingView ViewModel = new ThemeSettingViewModel(); cmbCurrentTheme.ItemsSource = Utils.GetEnumNames().Take(3).ToList(); - cmbCurrentFontSize.ItemsSource = Enumerable.Range(Global.MinFontSize, Global.MinFontSizeCount).ToList(); - cmbCurrentLanguage.ItemsSource = Global.Languages; + cmbCurrentFontSize.ItemsSource = Enumerable.Range(AppConfig.MinFontSize, AppConfig.MinFontSizeCount).ToList(); + cmbCurrentLanguage.ItemsSource = AppConfig.Languages; this.WhenActivated(disposables => { diff --git a/v2rayN/v2rayN/v2rayN.csproj b/v2rayN/v2rayN/v2rayN.csproj index 9b0220e2..768c832c 100644 --- a/v2rayN/v2rayN/v2rayN.csproj +++ b/v2rayN/v2rayN/v2rayN.csproj @@ -9,6 +9,7 @@ app.manifest PerMonitorV2 7.0 + true