refactor: code modernization

- Resolve static analysis warnings (CAxxxx) and optimize performance.

- Refactor UI bindings to eliminate async void and race conditions.

- Migrate Win32 API to LibraryImport for AOT compatibility.
This commit is contained in:
romeoahmed 2026-01-17 21:08:19 +08:00
parent fd7847557b
commit 84a6b12838
No known key found for this signature in database
GPG key ID: 8C5095EF11EA485A
148 changed files with 1770 additions and 1892 deletions

View file

@ -2,6 +2,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<NeutralLanguage>en-US</NeutralLanguage>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View file

@ -4,7 +4,7 @@ using System.Text;
namespace AmazTool; namespace AmazTool;
internal class UpgradeApp internal static class UpgradeApp
{ {
public static void Upgrade(string fileName) public static void Upgrade(string fileName)
{ {
@ -25,7 +25,7 @@ internal class UpgradeApp
foreach (var pp in existing) foreach (var pp in existing)
{ {
var path = pp.MainModule?.FileName ?? ""; var path = pp.MainModule?.FileName ?? "";
if (path.StartsWith(Utils.GetPath(Utils.V2rayN))) if (path.StartsWith(Utils.GetPath(Utils.V2rayN), StringComparison.OrdinalIgnoreCase))
{ {
pp?.Kill(); pp?.Kill();
pp?.WaitForExit(1000); pp?.WaitForExit(1000);
@ -74,7 +74,7 @@ internal class UpgradeApp
var entryOutputPath = Utils.GetPath(fullName); var entryOutputPath = Utils.GetPath(fullName);
Directory.CreateDirectory(Path.GetDirectoryName(entryOutputPath)!); Directory.CreateDirectory(Path.GetDirectoryName(entryOutputPath)!);
//In the bin folder, if the file already exists, it will be skipped //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; continue;
} }

View file

@ -2,7 +2,7 @@ using System.Diagnostics;
namespace AmazTool; namespace AmazTool;
internal class Utils internal static class Utils
{ {
public static string GetExePath() public static string GetExePath()
{ {

View file

@ -8,7 +8,7 @@
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<TargetLatestRuntimePatch>true</TargetLatestRuntimePatch> <TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
<NoWarn>CA1031;CS1591;NU1507;CA1416;IDE0058;IDE0053;IDE0200;NETSDK1206</NoWarn> <NoWarn>CA1031;CS1591;NU1507;CA1416;IDE0058;IDE0053;IDE0200;IDE0022;NETSDK1206</NoWarn>
<Nullable>annotations</Nullable> <Nullable>annotations</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Authors>2dust</Authors> <Authors>2dust</Authors>

View file

@ -1,6 +1,6 @@
namespace ServiceLib; namespace ServiceLib;
public class Global public class AppConfig
{ {
#region const #region const

View file

@ -2,6 +2,6 @@ namespace ServiceLib.Base;
public class MyReactiveObject : ReactiveObject public class MyReactiveObject : ReactiveObject
{ {
protected static Config? _config; protected static Config? Config { get; set; }
protected Func<EViewAction, object?, Task<bool>>? _updateView; protected Func<EViewAction, object?, Task<bool>>? UpdateView { get; set; }
} }

View file

@ -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) 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) 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)) if (string.IsNullOrEmpty(value))
{ {
return string.Empty; 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) public static string AppendQuotes(this string value)

View file

@ -41,7 +41,7 @@ public static class FileUtils
{ {
FileInfo fileInfo = new(fileName); FileInfo fileInfo = new(fileName);
using var originalFileStream = fileInfo.OpenRead(); 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); using GZipStream decompressionStream = new(originalFileStream, CompressionMode.Decompress);
decompressionStream.CopyTo(decompressedFileStream); decompressionStream.CopyTo(decompressedFileStream);
} }

View file

@ -100,7 +100,7 @@ public class JsonUtils
var result = string.Empty; var result = string.Empty;
try try
{ {
if (obj == null) if (obj is null)
{ {
return result; return result;
} }
@ -125,7 +125,7 @@ public class JsonUtils
var result = string.Empty; var result = string.Empty;
try try
{ {
if (obj == null) if (obj is null)
{ {
return result; return result;
} }

View file

@ -47,7 +47,7 @@ public class Logging
_logger2.Debug($"{strTitle},{ex.Message}"); _logger2.Debug($"{strTitle},{ex.Message}");
_logger2.Debug(ex.StackTrace); _logger2.Debug(ex.StackTrace);
if (ex?.InnerException != null) if (ex?.InnerException is not null)
{ {
_logger2.Error(ex.InnerException); _logger2.Error(ex.InnerException);
} }

View file

@ -53,7 +53,7 @@ public static class ProcUtils
ProcessStartInfo startInfo = new() ProcessStartInfo startInfo = new()
{ {
UseShellExecute = true, UseShellExecute = true,
Arguments = Global.RebootAs, Arguments = AppConfig.RebootAs,
WorkingDirectory = Utils.StartupPath(), WorkingDirectory = Utils.StartupPath(),
FileName = Utils.GetExePath().AppendQuotes(), FileName = Utils.GetExePath().AppendQuotes(),
Verb = blAdmin ? "runas" : null, Verb = blAdmin ? "runas" : null,

View file

@ -42,7 +42,7 @@ public class QRCodeUtils
} }
} }
if (lastDtle != null) if (lastDtle is not null)
{ {
throw lastDtle; throw lastDtle;
} }
@ -52,7 +52,7 @@ public class QRCodeUtils
public static string? ParseBarcode(string? fileName) public static string? ParseBarcode(string? fileName)
{ {
if (fileName == null || !File.Exists(fileName)) if (fileName is null || !File.Exists(fileName))
{ {
return null; return null;
} }
@ -96,7 +96,7 @@ public class QRCodeUtils
var reader = new BarcodeReader(); var reader = new BarcodeReader();
var result = reader.Decode(bitmap); var result = reader.Decode(bitmap);
if (result != null && result.Text.IsNotEmpty()) if (result is not null && result.Text.IsNotEmpty())
{ {
return result.Text; return result.Text;
} }

View file

@ -9,6 +9,9 @@ public class Utils
{ {
private static readonly string _tag = "Utils"; private static readonly string _tag = "Utils";
private static readonly char[] LineSeparators = { '\r', '\n' };
private static readonly char[] FieldSeparators = { ' ', '\t' };
#region Conversion Functions #region Conversion Functions
/// <summary> /// <summary>
@ -19,7 +22,7 @@ public class Utils
/// <returns></returns> /// <returns></returns>
public static string List2String(List<string>? lst, bool wrap = false) public static string List2String(List<string>? lst, bool wrap = false)
{ {
if (lst == null || lst.Count == 0) if (lst is null || lst.Count == 0)
{ {
return string.Empty; return string.Empty;
} }
@ -141,7 +144,7 @@ public class Utils
{ {
try try
{ {
return Convert.ToBoolean(obj); return Convert.ToBoolean(obj, CultureInfo.InvariantCulture);
} }
catch catch
{ {
@ -232,13 +235,8 @@ public class Utils
{ {
var byteOld = Encoding.UTF8.GetBytes(str); var byteOld = Encoding.UTF8.GetBytes(str);
var byteNew = MD5.HashData(byteOld); 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) catch (Exception ex)
{ {
@ -264,7 +262,7 @@ public class Utils
using var md5 = MD5.Create(); using var md5 = MD5.Create();
using var stream = File.OpenRead(filePath); using var stream = File.OpenRead(filePath);
var hash = md5.ComputeHash(stream); var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); return Convert.ToHexStringLower(hash);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -335,24 +333,24 @@ public class Utils
public static Dictionary<string, List<string>> ParseHostsToDictionary(string hostsContent) public static Dictionary<string, List<string>> ParseHostsToDictionary(string hostsContent)
{ {
var userHostsMap = hostsContent var userHostsMap = hostsContent
.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Split(LineSeparators, StringSplitOptions.RemoveEmptyEntries)
.Select(line => line.Trim()) .Select(line => line.Trim())
// skip full-line comments // skip full-line comments
.Where(line => !string.IsNullOrWhiteSpace(line) && !line.StartsWith("#")) .Where(line => !string.IsNullOrWhiteSpace(line) && !line.StartsWith('#'))
// strip inline comments (truncate at '#') // strip inline comments (truncate at '#')
.Select(line => .Select(line =>
{ {
var index = line.IndexOf('#'); 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 // ensure line still contains valid parts
.Where(line => !string.IsNullOrWhiteSpace(line) && line.Contains(' ')) .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) .Where(parts => parts.Length >= 2)
.GroupBy(parts => parts[0]) .GroupBy(parts => parts[0], StringComparer.OrdinalIgnoreCase)
.ToDictionary( .ToDictionary(
group => group.Key, group => group.Key,
group => group.SelectMany(parts => parts.Skip(1)).ToList() group => group.SelectMany(parts => parts.Skip(1)).Distinct(StringComparer.OrdinalIgnoreCase).ToList()
); );
return userHostsMap; return userHostsMap;
@ -660,15 +658,15 @@ public class Utils
try try
{ {
return blFull return blFull
? $"{Global.AppName} - V{GetVersionInfo()} - {RuntimeInformation.ProcessArchitecture}" ? $"{AppConfig.AppName} - V{GetVersionInfo()} - {RuntimeInformation.ProcessArchitecture}"
: $"{Global.AppName}/{GetVersionInfo()}"; : $"{AppConfig.AppName}/{GetVersionInfo()}";
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.SaveLog(_tag, ex); Logging.SaveLog(_tag, ex);
} }
return Global.AppName; return AppConfig.AppName;
} }
public static string GetVersionInfo() public static string GetVersionInfo()
@ -695,23 +693,16 @@ public class Utils
/// <returns></returns> /// <returns></returns>
public static string GetGuid(bool full = true) public static string GetGuid(bool full = true)
{ {
try var guid = Guid.NewGuid();
if (full)
{ {
if (full) return guid.ToString("D");
{
return Guid.NewGuid().ToString("D");
}
else
{
return BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0).ToString();
}
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
} }
return string.Empty; Span<byte> buffer = stackalloc byte[16];
guid.TryWriteBytes(buffer);
return BitConverter.ToInt64(buffer).ToString(CultureInfo.InvariantCulture);
} }
public static bool IsGuidByParse(string strSrc) public static bool IsGuidByParse(string strSrc)
@ -722,22 +713,22 @@ public class Utils
public static Dictionary<string, string> GetSystemHosts() public static Dictionary<string, string> GetSystemHosts()
{ {
var systemHosts = new Dictionary<string, string>(); var systemHosts = new Dictionary<string, string>();
var hostFile = @"C:\Windows\System32\drivers\etc\hosts"; var hostFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts");
try try
{ {
if (File.Exists(hostFile)) if (File.Exists(hostFile))
{ {
var hosts = File.ReadAllText(hostFile).Replace("\r", ""); var hostsList = File.ReadAllText(hostFile)
var hostsList = hosts.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); .Split(LineSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (var host in hostsList) foreach (var host in hostsList)
{ {
if (host.StartsWith("#")) if (host.StartsWith('#'))
{ {
continue; continue;
} }
var hostItem = host.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); var hostItem = host.Split(FieldSeparators, StringSplitOptions.RemoveEmptyEntries);
if (hostItem.Length < 2) if (hostItem.Length < 2)
{ {
continue; continue;
@ -757,7 +748,7 @@ public class Utils
public static async Task<string?> GetCliWrapOutput(string filePath, string? arg) public static async Task<string?> GetCliWrapOutput(string filePath, string? arg)
{ {
return await GetCliWrapOutput(filePath, arg != null ? new List<string>() { arg } : null); return await GetCliWrapOutput(filePath, arg is not null ? new List<string>() { arg } : null);
} }
public static async Task<string?> GetCliWrapOutput(string filePath, IEnumerable<string>? args) public static async Task<string?> GetCliWrapOutput(string filePath, IEnumerable<string>? args)
@ -765,7 +756,7 @@ public class Utils
try try
{ {
var cmd = Cli.Wrap(filePath); var cmd = Cli.Wrap(filePath);
if (args != null) if (args is not null)
{ {
if (args.Count() == 1) if (args.Count() == 1)
{ {
@ -854,7 +845,7 @@ public class Utils
public static string StartupPath() 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"); return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "v2rayN");
} }
@ -917,9 +908,9 @@ public class Utils
Directory.CreateDirectory(tempPath); 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)) if (!Directory.Exists(tempPath))
{ {
Directory.CreateDirectory(tempPath); Directory.CreateDirectory(tempPath);
@ -1058,7 +1049,7 @@ public class Utils
private static async Task<string?> GetLinuxUserId() private static async Task<string?> GetLinuxUserId()
{ {
var arg = new List<string>() { "-c", "id -u" }; var arg = new List<string>() { "-c", "id -u" };
return await GetCliWrapOutput(Global.LinuxBash, arg); return await GetCliWrapOutput(AppConfig.LinuxBash, arg);
} }
public static async Task<string?> SetLinuxChmod(string? fileName) public static async Task<string?> SetLinuxChmod(string? fileName)
@ -1078,7 +1069,7 @@ public class Utils
fileName = fileName.AppendQuotes(); fileName = fileName.AppendQuotes();
} }
var arg = new List<string>() { "-c", $"chmod +x {fileName}" }; var arg = new List<string>() { "-c", $"chmod +x {fileName}" };
return await GetCliWrapOutput(Global.LinuxBash, arg); return await GetCliWrapOutput(AppConfig.LinuxBash, arg);
} }
public static bool SetUnixFileMode(string? fileName) public static bool SetUnixFileMode(string? fileName)
@ -1104,11 +1095,11 @@ public class Utils
return false; return false;
} }
public static async Task<string?> GetLinuxFontFamily(string lang) public static async Task<string?> GetLinuxFontFamily()
{ {
// var arg = new List<string>() { "-c", $"fc-list :lang={lang} family" }; // var arg = new List<string>() { "-c", $"fc-list :lang={lang} family" };
var arg = new List<string>() { "-c", $"fc-list : family" }; var arg = new List<string>() { "-c", $"fc-list : family" };
return await GetCliWrapOutput(Global.LinuxBash, arg); return await GetCliWrapOutput(AppConfig.LinuxBash, arg);
} }
public static string? GetHomePath() public static string? GetHomePath()

View file

@ -41,7 +41,7 @@ public class YamlUtils
public static string ToYaml(object? obj) public static string ToYaml(object? obj)
{ {
var result = string.Empty; var result = string.Empty;
if (obj == null) if (obj is null)
{ {
return result; return result;
} }

View file

@ -1,5 +1,7 @@
global using System.Collections.Concurrent; global using System.Collections.Concurrent;
global using System.ComponentModel;
global using System.Diagnostics; global using System.Diagnostics;
global using System.Globalization;
global using System.Net; global using System.Net;
global using System.Net.NetworkInformation; global using System.Net.NetworkInformation;
global using System.Net.Sockets; global using System.Net.Sockets;

View file

@ -44,7 +44,7 @@ public static class AutoStartupHandler
private static async Task ClearTaskWindows() private static async Task ClearTaskWindows()
{ {
var autoRunName = GetAutoRunNameWindows(); var autoRunName = GetAutoRunNameWindows();
WindowsUtils.RegWriteValue(Global.AutoRunRegPath, autoRunName, ""); WindowsUtils.RegWriteValue(AppConfig.AutoRunRegPath, autoRunName, "");
if (Utils.IsAdministrator()) if (Utils.IsAdministrator())
{ {
AutoStartTaskService(autoRunName, "", ""); AutoStartTaskService(autoRunName, "", "");
@ -65,7 +65,7 @@ public static class AutoStartupHandler
} }
else else
{ {
WindowsUtils.RegWriteValue(Global.AutoRunRegPath, autoRunName, exePath.AppendQuotes()); WindowsUtils.RegWriteValue(AppConfig.AutoRunRegPath, autoRunName, exePath.AppendQuotes());
} }
} }
catch (Exception ex) catch (Exception ex)
@ -117,7 +117,7 @@ public static class AutoStartupHandler
private static string GetAutoRunNameWindows() private static string GetAutoRunNameWindows()
{ {
return $"{Global.AutoRunName}_{Utils.GetMd5(Utils.StartupPath())}"; return $"{AppConfig.AutoRunName}_{Utils.GetMd5(Utils.StartupPath())}";
} }
#endregion Windows #endregion Windows
@ -141,7 +141,7 @@ public static class AutoStartupHandler
{ {
try try
{ {
var linuxConfig = EmbedUtils.GetEmbedText(Global.LinuxAutostartConfig); var linuxConfig = EmbedUtils.GetEmbedText(AppConfig.LinuxAutostartConfig);
if (linuxConfig.IsNotEmpty()) if (linuxConfig.IsNotEmpty())
{ {
linuxConfig = linuxConfig.Replace("$ExecPath$", Utils.GetExePath()); linuxConfig = linuxConfig.Replace("$ExecPath$", Utils.GetExePath());
@ -159,7 +159,7 @@ public static class AutoStartupHandler
private static string GetHomePathLinux() 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)); Directory.CreateDirectory(Path.GetDirectoryName(homePath));
return homePath; return homePath;
} }
@ -176,7 +176,7 @@ public static class AutoStartupHandler
if (File.Exists(launchAgentPath)) if (File.Exists(launchAgentPath))
{ {
var args = new[] { "-c", $"launchctl unload -w \"{launchAgentPath}\"" }; var args = new[] { "-c", $"launchctl unload -w \"{launchAgentPath}\"" };
await Utils.GetCliWrapOutput(Global.LinuxBash, args); await Utils.GetCliWrapOutput(AppConfig.LinuxBash, args);
File.Delete(launchAgentPath); File.Delete(launchAgentPath);
} }
@ -196,7 +196,7 @@ public static class AutoStartupHandler
await File.WriteAllTextAsync(launchAgentPath, plistContent); await File.WriteAllTextAsync(launchAgentPath, plistContent);
var args = new[] { "-c", $"launchctl load -w \"{launchAgentPath}\"" }; var args = new[] { "-c", $"launchctl load -w \"{launchAgentPath}\"" };
await Utils.GetCliWrapOutput(Global.LinuxBash, args); await Utils.GetCliWrapOutput(AppConfig.LinuxBash, args);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -207,7 +207,7 @@ public static class AutoStartupHandler
private static string GetLaunchAgentPathMacOS() private static string GetLaunchAgentPathMacOS()
{ {
var homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); 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)); Directory.CreateDirectory(Path.GetDirectoryName(launchAgentPath));
return launchAgentPath; return launchAgentPath;
} }
@ -221,7 +221,7 @@ public static class AutoStartupHandler
<plist version=""1.0""> <plist version=""1.0"">
<dict> <dict>
<key>Label</key> <key>Label</key>
<string>{Global.AppName}-LaunchAgent</string> <string>{AppConfig.AppName}-LaunchAgent</string>
<key>ProgramArguments</key> <key>ProgramArguments</key>
<array> <array>
<string>/bin/sh</string> <string>/bin/sh</string>

View file

@ -4,7 +4,7 @@ namespace ServiceLib.Handler;
public static class ConfigHandler public static class ConfigHandler
{ {
private static readonly string _configRes = Global.ConfigFileName; private static readonly string _configRes = AppConfig.ConfigFileName;
private static readonly string _tag = "ConfigHandler"; private static readonly string _tag = "ConfigHandler";
#region ConfigHandler #region ConfigHandler
@ -42,7 +42,7 @@ public static class ConfigHandler
MuxEnabled = false, MuxEnabled = false,
}; };
if (config.Inbound == null) if (config.Inbound is null)
{ {
config.Inbound = new List<InItem>(); config.Inbound = new List<InItem>();
InItem inItem = new() InItem inItem = new()
@ -67,7 +67,7 @@ public static class ConfigHandler
config.RoutingBasicItem ??= new(); config.RoutingBasicItem ??= new();
if (config.RoutingBasicItem.DomainStrategy.IsNullOrEmpty()) if (config.RoutingBasicItem.DomainStrategy.IsNullOrEmpty())
{ {
config.RoutingBasicItem.DomainStrategy = Global.DomainStrategies.First(); config.RoutingBasicItem.DomainStrategy = AppConfig.DomainStrategies.First();
} }
config.KcpItem ??= new KcpItem config.KcpItem ??= new KcpItem
@ -104,16 +104,17 @@ public static class ConfigHandler
if (config.UiItem.CurrentLanguage.IsNullOrEmpty()) if (config.UiItem.CurrentLanguage.IsNullOrEmpty())
{ {
config.UiItem.CurrentLanguage = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.Equals("zh", StringComparison.CurrentCultureIgnoreCase) config.UiItem.CurrentLanguage = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName
? Global.Languages.First() .Equals("zh", StringComparison.OrdinalIgnoreCase)
: Global.Languages[2]; ? AppConfig.Languages.First()
: AppConfig.Languages[2];
} }
config.ConstItem ??= new ConstItem(); config.ConstItem ??= new ConstItem();
config.SimpleDNSItem ??= InitBuiltinSimpleDNS(); config.SimpleDNSItem ??= InitBuiltinSimpleDNS();
config.SimpleDNSItem.GlobalFakeIp ??= true; config.SimpleDNSItem.GlobalFakeIp ??= true;
config.SimpleDNSItem.BootstrapDNS ??= Global.DomainPureIPDNSAddress.FirstOrDefault(); config.SimpleDNSItem.BootstrapDNS ??= AppConfig.DomainPureIPDNSAddress.FirstOrDefault();
config.SpeedTestItem ??= new(); config.SpeedTestItem ??= new();
if (config.SpeedTestItem.SpeedTestTimeout < 10) if (config.SpeedTestItem.SpeedTestTimeout < 10)
@ -122,11 +123,11 @@ public static class ConfigHandler
} }
if (config.SpeedTestItem.SpeedTestUrl.IsNullOrEmpty()) if (config.SpeedTestItem.SpeedTestUrl.IsNullOrEmpty())
{ {
config.SpeedTestItem.SpeedTestUrl = Global.SpeedTestUrls.First(); config.SpeedTestItem.SpeedTestUrl = AppConfig.SpeedTestUrls.First();
} }
if (config.SpeedTestItem.SpeedPingTestUrl.IsNullOrEmpty()) if (config.SpeedTestItem.SpeedPingTestUrl.IsNullOrEmpty())
{ {
config.SpeedTestItem.SpeedPingTestUrl = Global.SpeedPingTestUrls.First(); config.SpeedTestItem.SpeedPingTestUrl = AppConfig.SpeedPingTestUrls.First();
} }
if (config.SpeedTestItem.MixedConcurrencyCount < 1) if (config.SpeedTestItem.MixedConcurrencyCount < 1)
{ {
@ -142,7 +143,7 @@ public static class ConfigHandler
config.Mux4SboxItem ??= new() config.Mux4SboxItem ??= new()
{ {
Protocol = Global.SingboxMuxs.First(), Protocol = AppConfig.SingboxMuxs.First(),
MaxConnections = 8 MaxConnections = 8
}; };
@ -165,7 +166,7 @@ public static class ConfigHandler
if (config.SystemProxyItem.SystemProxyExceptions.IsNullOrEmpty()) 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; return config;
@ -287,16 +288,16 @@ public static class ConfigHandler
{ {
profileItem.ConfigType = EConfigType.VMess; profileItem.ConfigType = EConfigType.VMess;
profileItem.Address = profileItem.Address.TrimEx(); profileItem.Address = profileItem.Address.TrimSafe();
profileItem.Id = profileItem.Id.TrimEx(); profileItem.Id = profileItem.Id.TrimSafe();
profileItem.Security = profileItem.Security.TrimEx(); profileItem.Security = profileItem.Security.TrimSafe();
profileItem.Network = profileItem.Network.TrimEx(); profileItem.Network = profileItem.Network.TrimSafe();
profileItem.HeaderType = profileItem.HeaderType.TrimEx(); profileItem.HeaderType = profileItem.HeaderType.TrimSafe();
profileItem.RequestHost = profileItem.RequestHost.TrimEx(); profileItem.RequestHost = profileItem.RequestHost.TrimSafe();
profileItem.Path = profileItem.Path.TrimEx(); profileItem.Path = profileItem.Path.TrimSafe();
profileItem.StreamSecurity = profileItem.StreamSecurity.TrimEx(); profileItem.StreamSecurity = profileItem.StreamSecurity.TrimSafe();
if (!Global.VmessSecurities.Contains(profileItem.Security)) if (!AppConfig.VmessSecurities.Contains(profileItem.Security))
{ {
return -1; return -1;
} }
@ -361,7 +362,7 @@ public static class ConfigHandler
else if (profileItem.ConfigType.IsGroupType()) else if (profileItem.ConfigType.IsGroupType())
{ {
var profileGroupItem = await AppManager.Instance.GetProfileGroupItem(it.IndexId); var profileGroupItem = await AppManager.Instance.GetProfileGroupItem(it.IndexId);
await AddGroupServerCommon(config, profileItem, profileGroupItem, true); await AddGroupServerCommon(profileItem, profileGroupItem, true);
} }
else else
{ {
@ -407,7 +408,7 @@ public static class ConfigHandler
return 0; return 0;
} }
if (await SQLiteHelper.Instance.TableAsync<ProfileItem>().FirstOrDefaultAsync(t => t.IndexId == config.IndexId) != null) if (await SQLiteHelper.Instance.TableAsync<ProfileItem>().FirstOrDefaultAsync(t => t.IndexId == config.IndexId) is not null)
{ {
return 0; return 0;
} }
@ -443,76 +444,42 @@ public static class ConfigHandler
/// Move a server in the list to a different position /// Move a server in the list to a different position
/// Supports moving to top, up, down, bottom or specific position /// Supports moving to top, up, down, bottom or specific position
/// </summary> /// </summary>
/// <param name="config">Current configuration</param>
/// <param name="lstProfile">List of server profiles</param> /// <param name="lstProfile">List of server profiles</param>
/// <param name="index">Index of the server to move</param> /// <param name="index">Index of the server to move</param>
/// <param name="eMove">Direction to move the server</param> /// <param name="eMove">Direction to move the server</param>
/// <param name="pos">Target position when using EMove.Position</param> /// <param name="pos">Target position when using EMove.Position</param>
/// <returns>0 if successful, -1 if failed</returns> /// <returns>0 if successful, -1 if failed</returns>
public static async Task<int> MoveServer(Config config, List<ProfileItem> lstProfile, int index, EMove eMove, int pos = -1) public static Task<int> MoveServer(List<ProfileItem> lstProfile, int index, EMove eMove, int pos = -1)
{ {
var count = lstProfile.Count; 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); ProfileExManager.Instance.SetSort(lstProfile[i].IndexId, (i + 1) * 10);
} }
var sort = 0; var sort = eMove switch
switch (eMove)
{ {
case EMove.Top: EMove.Top => ProfileExManager.Instance.GetSort(lstProfile[0].IndexId) - 1,
{ EMove.Up => ProfileExManager.Instance.GetSort(lstProfile[index - 1].IndexId) - 1,
if (index == 0) EMove.Down => ProfileExManager.Instance.GetSort(lstProfile[index + 1].IndexId) + 1,
{ EMove.Bottom => ProfileExManager.Instance.GetSort(lstProfile[^1].IndexId) + 1,
return 0; EMove.Position => (pos * 10) + 1,
} _ => 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;
}
ProfileExManager.Instance.SetSort(lstProfile[index].IndexId, sort); ProfileExManager.Instance.SetSort(lstProfile[index].IndexId, sort);
return await Task.FromResult(0); return Task.FromResult(0);
} }
/// <summary> /// <summary>
@ -552,7 +519,7 @@ public static class ConfigHandler
profileItem.ConfigType = EConfigType.Custom; profileItem.ConfigType = EConfigType.Custom;
if (profileItem.Remarks.IsNullOrEmpty()) 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); await AddServerCommon(config, profileItem, true);
@ -564,17 +531,13 @@ public static class ConfigHandler
/// Edit an existing custom server configuration /// Edit an existing custom server configuration
/// Updates the server's properties without changing the file /// Updates the server's properties without changing the file
/// </summary> /// </summary>
/// <param name="config">Current configuration</param>
/// <param name="profileItem">Profile item with updated properties</param> /// <param name="profileItem">Profile item with updated properties</param>
/// <returns>0 if successful, -1 if failed</returns> /// <returns>0 if successful, -1 if failed</returns>
public static async Task<int> EditCustomServer(Config config, ProfileItem profileItem) public static async Task<int> EditCustomServer(ProfileItem profileItem)
{ {
var item = await AppManager.Instance.GetProfileItem(profileItem.IndexId); var item = await AppManager.Instance.GetProfileItem(profileItem.IndexId);
if (item is null)
{ if (item is not null)
item = profileItem;
}
else
{ {
item.Remarks = profileItem.Remarks; item.Remarks = profileItem.Remarks;
item.Address = profileItem.Address; item.Address = profileItem.Address;
@ -583,14 +546,9 @@ public static class ConfigHandler
item.PreSocksPort = profileItem.PreSocksPort; item.PreSocksPort = profileItem.PreSocksPort;
} }
if (await SQLiteHelper.Instance.UpdateAsync(item) > 0) item ??= profileItem;
{
return 0; return await SQLiteHelper.Instance.UpdateAsync(item) > 0 ? 0 : -1;
}
else
{
return -1;
}
//ToJsonFile(config); //ToJsonFile(config);
} }
@ -607,9 +565,9 @@ public static class ConfigHandler
{ {
profileItem.ConfigType = EConfigType.Shadowsocks; profileItem.ConfigType = EConfigType.Shadowsocks;
profileItem.Address = profileItem.Address.TrimEx(); profileItem.Address = profileItem.Address.TrimSafe();
profileItem.Id = profileItem.Id.TrimEx(); profileItem.Id = profileItem.Id.TrimSafe();
profileItem.Security = profileItem.Security.TrimEx(); profileItem.Security = profileItem.Security.TrimSafe();
if (!AppManager.Instance.GetShadowsocksSecurities(profileItem).Contains(profileItem.Security)) if (!AppManager.Instance.GetShadowsocksSecurities(profileItem).Contains(profileItem.Security))
{ {
@ -637,7 +595,7 @@ public static class ConfigHandler
{ {
profileItem.ConfigType = EConfigType.SOCKS; profileItem.ConfigType = EConfigType.SOCKS;
profileItem.Address = profileItem.Address.TrimEx(); profileItem.Address = profileItem.Address.TrimSafe();
await AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
@ -656,7 +614,7 @@ public static class ConfigHandler
{ {
profileItem.ConfigType = EConfigType.HTTP; profileItem.ConfigType = EConfigType.HTTP;
profileItem.Address = profileItem.Address.TrimEx(); profileItem.Address = profileItem.Address.TrimSafe();
await AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
@ -675,11 +633,11 @@ public static class ConfigHandler
{ {
profileItem.ConfigType = EConfigType.Trojan; profileItem.ConfigType = EConfigType.Trojan;
profileItem.Address = profileItem.Address.TrimEx(); profileItem.Address = profileItem.Address.TrimSafe();
profileItem.Id = profileItem.Id.TrimEx(); profileItem.Id = profileItem.Id.TrimSafe();
if (profileItem.StreamSecurity.IsNullOrEmpty()) if (profileItem.StreamSecurity.IsNullOrEmpty())
{ {
profileItem.StreamSecurity = Global.StreamSecurity; profileItem.StreamSecurity = AppConfig.StreamSecurity;
} }
if (profileItem.Id.IsNullOrEmpty()) if (profileItem.Id.IsNullOrEmpty())
{ {
@ -705,14 +663,14 @@ public static class ConfigHandler
profileItem.ConfigType = EConfigType.Hysteria2; profileItem.ConfigType = EConfigType.Hysteria2;
//profileItem.CoreType = ECoreType.sing_box; //profileItem.CoreType = ECoreType.sing_box;
profileItem.Address = profileItem.Address.TrimEx(); profileItem.Address = profileItem.Address.TrimSafe();
profileItem.Id = profileItem.Id.TrimEx(); profileItem.Id = profileItem.Id.TrimSafe();
profileItem.Path = profileItem.Path.TrimEx(); profileItem.Path = profileItem.Path.TrimSafe();
profileItem.Network = string.Empty; profileItem.Network = string.Empty;
if (profileItem.StreamSecurity.IsNullOrEmpty()) if (profileItem.StreamSecurity.IsNullOrEmpty())
{ {
profileItem.StreamSecurity = Global.StreamSecurity; profileItem.StreamSecurity = AppConfig.StreamSecurity;
} }
if (profileItem.Id.IsNullOrEmpty()) if (profileItem.Id.IsNullOrEmpty())
{ {
@ -738,19 +696,19 @@ public static class ConfigHandler
profileItem.ConfigType = EConfigType.TUIC; profileItem.ConfigType = EConfigType.TUIC;
profileItem.CoreType = ECoreType.sing_box; profileItem.CoreType = ECoreType.sing_box;
profileItem.Address = profileItem.Address.TrimEx(); profileItem.Address = profileItem.Address.TrimSafe();
profileItem.Id = profileItem.Id.TrimEx(); profileItem.Id = profileItem.Id.TrimSafe();
profileItem.Security = profileItem.Security.TrimEx(); profileItem.Security = profileItem.Security.TrimSafe();
profileItem.Network = string.Empty; 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()) if (profileItem.StreamSecurity.IsNullOrEmpty())
{ {
profileItem.StreamSecurity = Global.StreamSecurity; profileItem.StreamSecurity = AppConfig.StreamSecurity;
} }
if (profileItem.Alpn.IsNullOrEmpty()) if (profileItem.Alpn.IsNullOrEmpty())
{ {
@ -778,15 +736,15 @@ public static class ConfigHandler
{ {
profileItem.ConfigType = EConfigType.WireGuard; profileItem.ConfigType = EConfigType.WireGuard;
profileItem.Address = profileItem.Address.TrimEx(); profileItem.Address = profileItem.Address.TrimSafe();
profileItem.Id = profileItem.Id.TrimEx(); profileItem.Id = profileItem.Id.TrimSafe();
profileItem.PublicKey = profileItem.PublicKey.TrimEx(); profileItem.PublicKey = profileItem.PublicKey.TrimSafe();
profileItem.Path = profileItem.Path.TrimEx(); profileItem.Path = profileItem.Path.TrimSafe();
profileItem.RequestHost = profileItem.RequestHost.TrimEx(); profileItem.RequestHost = profileItem.RequestHost.TrimSafe();
profileItem.Network = string.Empty; profileItem.Network = string.Empty;
if (profileItem.ShortId.IsNullOrEmpty()) if (profileItem.ShortId.IsNullOrEmpty())
{ {
profileItem.ShortId = Global.TunMtus.First().ToString(); profileItem.ShortId = AppConfig.TunMtus[0].ToString(CultureInfo.InvariantCulture);
} }
if (profileItem.Id.IsNullOrEmpty()) if (profileItem.Id.IsNullOrEmpty())
@ -812,13 +770,13 @@ public static class ConfigHandler
profileItem.ConfigType = EConfigType.Anytls; profileItem.ConfigType = EConfigType.Anytls;
profileItem.CoreType = ECoreType.sing_box; profileItem.CoreType = ECoreType.sing_box;
profileItem.Address = profileItem.Address.TrimEx(); profileItem.Address = profileItem.Address.TrimSafe();
profileItem.Id = profileItem.Id.TrimEx(); profileItem.Id = profileItem.Id.TrimSafe();
profileItem.Security = profileItem.Security.TrimEx(); profileItem.Security = profileItem.Security.TrimSafe();
profileItem.Network = string.Empty; profileItem.Network = string.Empty;
if (profileItem.StreamSecurity.IsNullOrEmpty()) if (profileItem.StreamSecurity.IsNullOrEmpty())
{ {
profileItem.StreamSecurity = Global.StreamSecurity; profileItem.StreamSecurity = AppConfig.StreamSecurity;
} }
if (profileItem.Id.IsNullOrEmpty()) if (profileItem.Id.IsNullOrEmpty())
{ {
@ -864,10 +822,10 @@ public static class ConfigHandler
Delay = t33?.Delay ?? 0, Delay = t33?.Delay ?? 0,
Speed = t33?.Speed ?? 0, Speed = t33?.Speed ?? 0,
Sort = t33?.Sort ?? 0, Sort = t33?.Sort ?? 0,
TodayDown = (t22?.TodayDown ?? 0).ToString("D16"), TodayDown = (t22?.TodayDown ?? 0).ToString("D16", CultureInfo.InvariantCulture),
TodayUp = (t22?.TodayUp ?? 0).ToString("D16"), TodayUp = (t22?.TodayUp ?? 0).ToString("D16", CultureInfo.InvariantCulture),
TotalDown = (t22?.TotalDown ?? 0).ToString("D16"), TotalDown = (t22?.TotalDown ?? 0).ToString("D16", CultureInfo.InvariantCulture),
TotalUp = (t22?.TotalUp ?? 0).ToString("D16"), TotalUp = (t22?.TotalUp ?? 0).ToString("D16", CultureInfo.InvariantCulture),
}).ToList(); }).ToList();
Enum.TryParse(colName, true, out EServerColName name); Enum.TryParse(colName, true, out EServerColName name);
@ -956,18 +914,18 @@ public static class ConfigHandler
{ {
profileItem.ConfigType = EConfigType.VLESS; profileItem.ConfigType = EConfigType.VLESS;
profileItem.Address = profileItem.Address.TrimEx(); profileItem.Address = profileItem.Address.TrimSafe();
profileItem.Id = profileItem.Id.TrimEx(); profileItem.Id = profileItem.Id.TrimSafe();
profileItem.Security = profileItem.Security.TrimEx(); profileItem.Security = profileItem.Security.TrimSafe();
profileItem.Network = profileItem.Network.TrimEx(); profileItem.Network = profileItem.Network.TrimSafe();
profileItem.HeaderType = profileItem.HeaderType.TrimEx(); profileItem.HeaderType = profileItem.HeaderType.TrimSafe();
profileItem.RequestHost = profileItem.RequestHost.TrimEx(); profileItem.RequestHost = profileItem.RequestHost.TrimSafe();
profileItem.Path = profileItem.Path.TrimEx(); profileItem.Path = profileItem.Path.TrimSafe();
profileItem.StreamSecurity = profileItem.StreamSecurity.TrimEx(); 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()) if (profileItem.Id.IsNullOrEmpty())
{ {
@ -975,7 +933,7 @@ public static class ConfigHandler
} }
if (profileItem.Security.IsNullOrEmpty()) if (profileItem.Security.IsNullOrEmpty())
{ {
profileItem.Security = Global.None; profileItem.Security = AppConfig.None;
} }
await AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
@ -993,7 +951,7 @@ public static class ConfigHandler
public static async Task<Tuple<int, int>> DedupServerList(Config config, string subId) public static async Task<Tuple<int, int>> DedupServerList(Config config, string subId)
{ {
var lstProfile = await AppManager.Instance.ProfileItems(subId); var lstProfile = await AppManager.Instance.ProfileItems(subId);
if (lstProfile == null) if (lstProfile is null)
{ {
return new Tuple<int, int>(0, 0); return new Tuple<int, int>(0, 0);
} }
@ -1035,8 +993,8 @@ public static class ConfigHandler
if (profileItem.StreamSecurity.IsNotEmpty()) if (profileItem.StreamSecurity.IsNotEmpty())
{ {
if (profileItem.StreamSecurity != Global.StreamSecurity if (profileItem.StreamSecurity is not AppConfig.StreamSecurity
&& profileItem.StreamSecurity != Global.StreamSecurityReality) and not AppConfig.StreamSecurityReality)
{ {
profileItem.StreamSecurity = string.Empty; profileItem.StreamSecurity = string.Empty;
} }
@ -1044,18 +1002,20 @@ public static class ConfigHandler
{ {
if (profileItem.AllowInsecure.IsNullOrEmpty()) 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; 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; var maxSort = -1;
@ -1080,7 +1040,7 @@ public static class ConfigHandler
return 0; return 0;
} }
public static async Task<int> AddGroupServerCommon(Config config, ProfileItem profileItem, ProfileGroupItem profileGroupItem, bool toFile = true) public static async Task<int> AddGroupServerCommon(ProfileItem profileItem, ProfileGroupItem profileGroupItem, bool toFile = true)
{ {
var maxSort = -1; var maxSort = -1;
if (profileItem.IndexId.IsNullOrEmpty()) if (profileItem.IndexId.IsNullOrEmpty())
@ -1097,7 +1057,7 @@ public static class ConfigHandler
if (toFile) if (toFile)
{ {
await SQLiteHelper.Instance.ReplaceAsync(profileItem); await SQLiteHelper.Instance.ReplaceAsync(profileItem);
if (profileGroupItem != null) if (profileGroupItem is not null)
{ {
profileGroupItem.IndexId = profileItem.IndexId; profileGroupItem.IndexId = profileItem.IndexId;
await ProfileGroupItemManager.Instance.SaveItemAsync(profileGroupItem); await ProfileGroupItemManager.Instance.SaveItemAsync(profileGroupItem);
@ -1121,7 +1081,7 @@ public static class ConfigHandler
/// <returns>True if the profiles match, false otherwise</returns> /// <returns>True if the profiles match, false otherwise</returns>
private static bool CompareProfileItem(ProfileItem? o, ProfileItem? n, bool remarks) private static bool CompareProfileItem(ProfileItem? o, ProfileItem? n, bool remarks)
{ {
if (o == null || n == null) if (o is null || n is null)
{ {
return false; return false;
} }
@ -1142,11 +1102,11 @@ public static class ConfigHandler
&& AreEqual(o.Fingerprint, n.Fingerprint) && AreEqual(o.Fingerprint, n.Fingerprint)
&& AreEqual(o.PublicKey, n.PublicKey) && AreEqual(o.PublicKey, n.PublicKey)
&& AreEqual(o.ShortId, n.ShortId) && 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) 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 /// Remove a single server profile by its index ID
/// Deletes the configuration file if it's a custom config /// Deletes the configuration file if it's a custom config
/// </summary> /// </summary>
/// <param name="config">Current configuration</param>
/// <param name="indexId">Index ID of the profile to remove</param> /// <param name="indexId">Index ID of the profile to remove</param>
/// <returns>0 if successful</returns> /// <returns>0 if successful</returns>
private static async Task<int> RemoveProfileItem(Config config, string indexId) private static async Task<int> RemoveProfileItem(string indexId)
{ {
try try
{ {
var item = await AppManager.Instance.GetProfileItem(indexId); var item = await AppManager.Instance.GetProfileItem(indexId);
if (item == null) if (item is null)
{ {
return 0; return 0;
} }
@ -1185,12 +1144,11 @@ public static class ConfigHandler
/// Create a group server that combines multiple servers for load balancing /// Create a group server that combines multiple servers for load balancing
/// Generates a configuration file that references multiple servers /// Generates a configuration file that references multiple servers
/// </summary> /// </summary>
/// <param name="config">Current configuration</param>
/// <param name="selecteds">Selected servers to combine</param> /// <param name="selecteds">Selected servers to combine</param>
/// <param name="coreType">Core type to use (Xray or sing_box)</param> /// <param name="coreType">Core type to use (Xray or sing_box)</param>
/// <param name="multipleLoad">Load balancing algorithm</param> /// <param name="multipleLoad">Load balancing algorithm</param>
/// <returns>Result object with success state and data</returns> /// <returns>Result object with success state and data</returns>
public static async Task<RetResult> AddGroupServer4Multiple(Config config, List<ProfileItem> selecteds, ECoreType coreType, EMultipleLoad multipleLoad, string? subId) public static async Task<RetResult> AddGroupServer4Multiple(List<ProfileItem> selecteds, ECoreType coreType, EMultipleLoad multipleLoad, string? subId)
{ {
var result = new RetResult(); var result = new RetResult();
@ -1237,7 +1195,7 @@ public static class ConfigHandler
MultipleLoad = multipleLoad, MultipleLoad = multipleLoad,
IndexId = indexId, IndexId = indexId,
}; };
var ret = await AddGroupServerCommon(config, profile, profileGroup, true); var ret = await AddGroupServerCommon(profile, profileGroup, true);
result.Success = ret == 0; result.Success = ret == 0;
result.Data = indexId; result.Data = indexId;
return result; return result;
@ -1269,7 +1227,7 @@ public static class ConfigHandler
{ {
CoreType = ECoreType.sing_box, CoreType = ECoreType.sing_box,
ConfigType = EConfigType.SOCKS, ConfigType = EConfigType.SOCKS,
Address = Global.Loopback, Address = AppConfig.Loopback,
SpiderX = tun2SocksAddress, // Tun2SocksAddress SpiderX = tun2SocksAddress, // Tun2SocksAddress
Port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks) Port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks)
}; };
@ -1281,7 +1239,7 @@ public static class ConfigHandler
{ {
CoreType = preCoreType, CoreType = preCoreType,
ConfigType = EConfigType.SOCKS, ConfigType = EConfigType.SOCKS,
Address = Global.Loopback, Address = AppConfig.Loopback,
Port = node.PreSocksPort.Value, Port = node.PreSocksPort.Value,
}; };
} }
@ -1352,7 +1310,10 @@ public static class ConfigHandler
foreach (var str in arrData) foreach (var str in arrData)
{ {
//maybe sub //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) if (await AddSubItem(config, str) == 0)
{ {
@ -1438,7 +1399,7 @@ public static class ConfigHandler
{ {
lstProfiles = V2rayFmt.ResolveFullArray(strData, subRemarks); lstProfiles = V2rayFmt.ResolveFullArray(strData, subRemarks);
} }
if (lstProfiles != null && lstProfiles.Count > 0) if (lstProfiles is not null && lstProfiles.Count > 0)
{ {
if (isSub && subid.IsNotEmpty()) if (isSub && subid.IsNotEmpty())
{ {
@ -1462,31 +1423,30 @@ public static class ConfigHandler
} }
ProfileItem? profileItem = null; 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 //Is Html Page
if (profileItem is null && HtmlPageFmt.IsHtmlPage(strData)) if (profileItem is null && HtmlPageFmt.IsHtmlPage(strData))
{ {
return -1; return -1;
} }
//Is Clash configuration
if (profileItem is null) var resolvers = new Func<string, string?, ProfileItem?>[]
{ {
profileItem = ClashFmt.ResolveFull(strData, subRemarks); SingboxFmt.ResolveFull,
} V2rayFmt.ResolveFull,
//Is hysteria configuration ClashFmt.ResolveFull,
if (profileItem is null) 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()) if (profileItem is null || profileItem.Address.IsNullOrEmpty())
{ {
return -1; return -1;
@ -1600,24 +1560,24 @@ public static class ConfigHandler
} }
//Select active node //Select active node
if (activeProfile != null) if (activeProfile is not null)
{ {
var lstSub = await AppManager.Instance.ProfileItems(subid); var lstSub = await AppManager.Instance.ProfileItems(subid);
var existItem = lstSub?.FirstOrDefault(t => config.UiItem.EnableUpdateSubOnlyRemarksExist ? t.Remarks == activeProfile.Remarks : CompareProfileItem(t, activeProfile, true)); 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); await ConfigHandler.SetDefaultServerIndex(config, existItem.IndexId);
} }
} }
//Keep the last traffic statistics //Keep the last traffic statistics
if (lstOriSub != null) if (lstOriSub is not null)
{ {
var lstSub = await AppManager.Instance.ProfileItems(subid); var lstSub = await AppManager.Instance.ProfileItems(subid);
foreach (var item in lstSub) foreach (var item in lstSub)
{ {
var existItem = lstOriSub?.FirstOrDefault(t => config.UiItem.EnableUpdateSubOnlyRemarksExist ? t.Remarks == item.Remarks : CompareProfileItem(t, item, true)); 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); await StatisticsManager.Instance.CloneServerStatItem(existItem.IndexId, item.IndexId);
} }
@ -1653,12 +1613,12 @@ public static class ConfigHandler
}; };
var uri = Utils.TryUri(url); var uri = Utils.TryUri(url);
if (uri == null) if (uri is null)
{ {
return -1; return -1;
} }
//Do not allow http protocol //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 //TODO Temporary reminder to be removed later
NoticeManager.Instance.Enqueue(ResUI.InsecureUrlProtocol); NoticeManager.Instance.Enqueue(ResUI.InsecureUrlProtocol);
@ -1835,7 +1795,7 @@ public static class ConfigHandler
} }
var lstRules = JsonUtils.Deserialize<List<RulesItem>>(strData); var lstRules = JsonUtils.Deserialize<List<RulesItem>>(strData);
if (lstRules == null) if (lstRules is null)
{ {
return -1; return -1;
} }
@ -2028,14 +1988,14 @@ public static class ConfigHandler
} }
var template = JsonUtils.Deserialize<RoutingTemplate>(templateContent); var template = JsonUtils.Deserialize<RoutingTemplate>(templateContent);
if (template == null) if (template is null)
{ {
return await InitBuiltinRouting(config, blImportAdvancedRules); // fallback return await InitBuiltinRouting(config, blImportAdvancedRules); // fallback
} }
var items = await AppManager.Instance.RoutingItems(); var items = await AppManager.Instance.RoutingItems();
var maxSort = items.Count; 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; return 0;
} }
@ -2088,20 +2048,20 @@ public static class ConfigHandler
//TODO Temporary code to be removed later //TODO Temporary code to be removed later
var lockItem = items?.FirstOrDefault(t => t.Locked == true); var lockItem = items?.FirstOrDefault(t => t.Locked == true);
if (lockItem != null) if (lockItem is not null)
{ {
await ConfigHandler.RemoveRoutingItem(lockItem); await ConfigHandler.RemoveRoutingItem(lockItem);
items = await AppManager.Instance.RoutingItems(); 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 //migrate
//TODO Temporary code to be removed later //TODO Temporary code to be removed later
if (config.RoutingBasicItem.RoutingIndexId.IsNotEmpty()) if (config.RoutingBasicItem.RoutingIndexId.IsNotEmpty())
{ {
var item = items.FirstOrDefault(t => t.Id == config.RoutingBasicItem.RoutingIndexId); var item = items.FirstOrDefault(t => t.Id == config.RoutingBasicItem.RoutingIndexId);
if (item != null) if (item is not null)
{ {
await SetDefaultRouting(config, item); await SetDefaultRouting(config, item);
} }
@ -2119,7 +2079,7 @@ public static class ConfigHandler
Url = string.Empty, Url = string.Empty,
Sort = maxSort + 1, Sort = maxSort + 1,
}; };
await AddBatchRoutingRules(item2, EmbedUtils.GetEmbedText(Global.CustomRoutingFileName + "white")); await AddBatchRoutingRules(item2, EmbedUtils.GetEmbedText(AppConfig.CustomRoutingFileName + "white"));
//Blacklist //Blacklist
var item3 = new RoutingItem() var item3 = new RoutingItem()
@ -2128,7 +2088,7 @@ public static class ConfigHandler
Url = string.Empty, Url = string.Empty,
Sort = maxSort + 2, Sort = maxSort + 2,
}; };
await AddBatchRoutingRules(item3, EmbedUtils.GetEmbedText(Global.CustomRoutingFileName + "black")); await AddBatchRoutingRules(item3, EmbedUtils.GetEmbedText(AppConfig.CustomRoutingFileName + "black"));
//Global //Global
var item1 = new RoutingItem() var item1 = new RoutingItem()
@ -2137,7 +2097,7 @@ public static class ConfigHandler
Url = string.Empty, Url = string.Empty,
Sort = maxSort + 3, Sort = maxSort + 3,
}; };
await AddBatchRoutingRules(item1, EmbedUtils.GetEmbedText(Global.CustomRoutingFileName + "global")); await AddBatchRoutingRules(item1, EmbedUtils.GetEmbedText(AppConfig.CustomRoutingFileName + "global"));
if (!blImportAdvancedRules) if (!blImportAdvancedRules)
{ {
@ -2217,7 +2177,7 @@ public static class ConfigHandler
/// <returns>0 if successful, -1 if failed</returns> /// <returns>0 if successful, -1 if failed</returns>
public static async Task<int> SaveDNSItems(Config config, DNSItem item) public static async Task<int> SaveDNSItems(Config config, DNSItem item)
{ {
if (item == null) if (item is null)
{ {
return -1; return -1;
} }
@ -2256,7 +2216,7 @@ public static class ConfigHandler
} }
var template = JsonUtils.Deserialize<DNSItem>(templateContent); var template = JsonUtils.Deserialize<DNSItem>(templateContent);
if (template == null) if (template is null)
{ {
return currentItem; return currentItem;
} }
@ -2292,9 +2252,9 @@ public static class ConfigHandler
FakeIP = false, FakeIP = false,
GlobalFakeIp = true, GlobalFakeIp = true,
BlockBindingQuery = true, BlockBindingQuery = true,
DirectDNS = Global.DomainDirectDNSAddress.FirstOrDefault(), DirectDNS = AppConfig.DomainDirectDNSAddress.FirstOrDefault(),
RemoteDNS = Global.DomainRemoteDNSAddress.FirstOrDefault(), RemoteDNS = AppConfig.DomainRemoteDNSAddress.FirstOrDefault(),
BootstrapDNS = Global.DomainPureIPDNSAddress.FirstOrDefault(), BootstrapDNS = AppConfig.DomainPureIPDNSAddress.FirstOrDefault(),
}; };
} }
@ -2308,7 +2268,7 @@ public static class ConfigHandler
} }
var template = JsonUtils.Deserialize<SimpleDNSItem>(templateContent); var template = JsonUtils.Deserialize<SimpleDNSItem>(templateContent);
if (template == null) if (template is null)
{ {
return null; return null;
} }
@ -2345,7 +2305,7 @@ public static class ConfigHandler
public static async Task<int> SaveFullConfigTemplate(Config config, FullConfigTemplateItem item) public static async Task<int> SaveFullConfigTemplate(Config config, FullConfigTemplateItem item)
{ {
if (item == null) if (item is null)
{ {
return -1; return -1;
} }
@ -2392,15 +2352,15 @@ public static class ConfigHandler
break; break;
case EPresetType.Russia: case EPresetType.Russia:
config.ConstItem.GeoSourceUrl = Global.GeoFilesSources[1]; config.ConstItem.GeoSourceUrl = AppConfig.GeoFilesSources[1];
config.ConstItem.SrsSourceUrl = Global.SingboxRulesetSources[1]; config.ConstItem.SrsSourceUrl = AppConfig.SingboxRulesetSources[1];
config.ConstItem.RouteRulesTemplateSourceUrl = Global.RoutingRulesSources[1]; config.ConstItem.RouteRulesTemplateSourceUrl = AppConfig.RoutingRulesSources[1];
var xrayDnsRussia = await GetExternalDNSItem(ECoreType.Xray, Global.DNSTemplateSources[1] + "v2ray.json"); var xrayDnsRussia = await GetExternalDNSItem(ECoreType.Xray, AppConfig.DNSTemplateSources[1] + "v2ray.json");
var singboxDnsRussia = await GetExternalDNSItem(ECoreType.sing_box, Global.DNSTemplateSources[1] + "sing_box.json"); var singboxDnsRussia = await GetExternalDNSItem(ECoreType.sing_box, AppConfig.DNSTemplateSources[1] + "sing_box.json");
var simpleDnsRussia = await GetExternalSimpleDNSItem(Global.DNSTemplateSources[1] + "simple_dns.json"); var simpleDnsRussia = await GetExternalSimpleDNSItem(AppConfig.DNSTemplateSources[1] + "simple_dns.json");
if (simpleDnsRussia == null) if (simpleDnsRussia is null)
{ {
xrayDnsRussia.Enabled = true; xrayDnsRussia.Enabled = true;
singboxDnsRussia.Enabled = true; singboxDnsRussia.Enabled = true;
@ -2415,15 +2375,15 @@ public static class ConfigHandler
break; break;
case EPresetType.Iran: case EPresetType.Iran:
config.ConstItem.GeoSourceUrl = Global.GeoFilesSources[2]; config.ConstItem.GeoSourceUrl = AppConfig.GeoFilesSources[2];
config.ConstItem.SrsSourceUrl = Global.SingboxRulesetSources[2]; config.ConstItem.SrsSourceUrl = AppConfig.SingboxRulesetSources[2];
config.ConstItem.RouteRulesTemplateSourceUrl = Global.RoutingRulesSources[2]; config.ConstItem.RouteRulesTemplateSourceUrl = AppConfig.RoutingRulesSources[2];
var xrayDnsIran = await GetExternalDNSItem(ECoreType.Xray, Global.DNSTemplateSources[2] + "v2ray.json"); var xrayDnsIran = await GetExternalDNSItem(ECoreType.Xray, AppConfig.DNSTemplateSources[2] + "v2ray.json");
var singboxDnsIran = await GetExternalDNSItem(ECoreType.sing_box, Global.DNSTemplateSources[2] + "sing_box.json"); var singboxDnsIran = await GetExternalDNSItem(ECoreType.sing_box, AppConfig.DNSTemplateSources[2] + "sing_box.json");
var simpleDnsIran = await GetExternalSimpleDNSItem(Global.DNSTemplateSources[2] + "simple_dns.json"); var simpleDnsIran = await GetExternalSimpleDNSItem(AppConfig.DNSTemplateSources[2] + "simple_dns.json");
if (simpleDnsIran == null) if (simpleDnsIran is null)
{ {
xrayDnsIran.Enabled = true; xrayDnsIran.Enabled = true;
singboxDnsIran.Enabled = true; singboxDnsIran.Enabled = true;
@ -2448,7 +2408,7 @@ public static class ConfigHandler
public static WindowSizeItem? GetWindowSizeItem(Config config, string typeName) public static WindowSizeItem? GetWindowSizeItem(Config config, string typeName)
{ {
var sizeItem = config?.UiItem?.WindowSizeItem?.FirstOrDefault(t => t.TypeName == 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; return null;
} }
@ -2459,7 +2419,7 @@ public static class ConfigHandler
public static int SaveWindowSizeItem(Config config, string typeName, double width, double height) public static int SaveWindowSizeItem(Config config, string typeName, double width, double height)
{ {
var sizeItem = config?.UiItem?.WindowSizeItem?.FirstOrDefault(t => t.TypeName == typeName); var sizeItem = config?.UiItem?.WindowSizeItem?.FirstOrDefault(t => t.TypeName == typeName);
if (sizeItem == null) if (sizeItem is null)
{ {
sizeItem = new WindowSizeItem { TypeName = typeName }; sizeItem = new WindowSizeItem { TypeName = typeName };
config.UiItem.WindowSizeItem.Add(sizeItem); config.UiItem.WindowSizeItem.Add(sizeItem);

View file

@ -7,7 +7,7 @@ public static class ConnectionHandler
public static async Task<string> RunAvailabilityCheck() public static async Task<string> RunAvailabilityCheck()
{ {
var time = await GetRealPingTimeInfo(); 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); return string.Format(ResUI.TestMeOutput, time, ip);
} }
@ -22,13 +22,13 @@ public static class ConnectionHandler
var downloadHandle = new DownloadService(); var downloadHandle = new DownloadService();
var result = await downloadHandle.TryDownloadString(url, true, ""); var result = await downloadHandle.TryDownloadString(url, true, "");
if (result == null) if (result is null)
{ {
return null; return null;
} }
var ipInfo = JsonUtils.Deserialize<IPAPIInfo>(result); var ipInfo = JsonUtils.Deserialize<IPAPIInfo>(result);
if (ipInfo == null) if (ipInfo is null)
{ {
return null; return null;
} }
@ -45,7 +45,7 @@ public static class ConnectionHandler
try try
{ {
var port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks); 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; var url = AppManager.Instance.Config.SpeedTestItem.SpeedPingTestUrl;
for (var i = 0; i < 2; i++) for (var i = 0; i < 2; i++)
@ -76,7 +76,7 @@ public static class ConnectionHandler
using var client = new HttpClient(new SocketsHttpHandler() using var client = new HttpClient(new SocketsHttpHandler()
{ {
Proxy = webProxy, Proxy = webProxy,
UseProxy = webProxy != null UseProxy = webProxy is not null
}); });
List<int> oneTime = new(); List<int> oneTime = new();

View file

@ -7,10 +7,13 @@ public static class CoreConfigHandler
{ {
private static readonly string _tag = "CoreConfigHandler"; private static readonly string _tag = "CoreConfigHandler";
private static readonly CompositeFormat _successfulConfigFormat =
CompositeFormat.Parse(ResUI.SuccessfulConfiguration);
public static async Task<RetResult> GenerateClientConfig(ProfileItem node, string? fileName) public static async Task<RetResult> GenerateClientConfig(ProfileItem node, string? fileName)
{ {
var config = AppManager.Instance.Config; var config = AppManager.Instance.Config;
var result = new RetResult(); RetResult result;
if (node.ConfigType == EConfigType.Custom) if (node.ConfigType == EConfigType.Custom)
{ {
@ -33,7 +36,7 @@ public static class CoreConfigHandler
{ {
return result; return result;
} }
if (fileName.IsNotEmpty() && result.Data != null) if (fileName.IsNotEmpty() && result.Data is not null)
{ {
await File.WriteAllTextAsync(fileName, result.Data.ToString()); await File.WriteAllTextAsync(fileName, result.Data.ToString());
} }
@ -46,7 +49,7 @@ public static class CoreConfigHandler
var ret = new RetResult(); var ret = new RetResult();
try try
{ {
if (node == null || fileName is null) if (node is null || fileName is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -78,7 +81,7 @@ public static class CoreConfigHandler
return ret; return ret;
} }
ret.Msg = string.Format(ResUI.SuccessfulConfiguration, ""); ret.Msg = string.Format(CultureInfo.CurrentCulture, _successfulConfigFormat, "");
ret.Success = true; ret.Success = true;
return await Task.FromResult(ret); return await Task.FromResult(ret);
} }
@ -111,7 +114,7 @@ public static class CoreConfigHandler
public static async Task<RetResult> GenerateClientSpeedtestConfig(Config config, ProfileItem node, ServerTestItem testItem, string fileName) public static async Task<RetResult> GenerateClientSpeedtestConfig(Config config, ProfileItem node, ServerTestItem testItem, string fileName)
{ {
var result = new RetResult(); RetResult result;
var initPort = AppManager.Instance.GetLocalPort(EInboundProtocol.speedtest); var initPort = AppManager.Instance.GetLocalPort(EInboundProtocol.speedtest);
var port = Utils.GetFreePort(initPort + testItem.QueueNum); var port = Utils.GetFreePort(initPort + testItem.QueueNum);
testItem.Port = port; testItem.Port = port;

View file

@ -7,7 +7,7 @@ public class AnytlsFmt : BaseFmt
msg = ResUI.ConfigurationFormatIncorrect; msg = ResUI.ConfigurationFormatIncorrect;
var parsedUrl = Utils.TryUri(str); var parsedUrl = Utils.TryUri(str);
if (parsedUrl == null) if (parsedUrl is null)
{ {
return null; return null;
} }
@ -30,7 +30,7 @@ public class AnytlsFmt : BaseFmt
public static string? ToUri(ProfileItem? item) public static string? ToUri(ProfileItem? item)
{ {
if (item == null) if (item is null)
{ {
return null; return null;
} }
@ -41,7 +41,7 @@ public class AnytlsFmt : BaseFmt
} }
var pw = item.Id; var pw = item.Id;
var dicQuery = new Dictionary<string, string>(); var dicQuery = new Dictionary<string, string>();
ToUriQuery(item, Global.None, ref dicQuery); ToUriQuery(item, AppConfig.None, ref dicQuery);
return ToUri(EConfigType.Anytls, item.Address, item.Port, pw, dicQuery, remark); return ToUri(EConfigType.Anytls, item.Address, item.Port, pw, dicQuery, remark);
} }

View file

@ -32,7 +32,7 @@ public class BaseFmt
} }
else else
{ {
if (securityDef != null) if (securityDef is not null)
{ {
dicQuery.Add("security", securityDef); dicQuery.Add("security", securityDef);
} }
@ -62,7 +62,7 @@ public class BaseFmt
dicQuery.Add("pqv", Utils.UrlEncode(item.Mldsa65Verify)); 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()) if (item.Alpn.IsNotEmpty())
{ {
@ -84,7 +84,7 @@ public class BaseFmt
switch (item.Network) switch (item.Network)
{ {
case nameof(ETransport.tcp): 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()) if (item.RequestHost.IsNotEmpty())
{ {
dicQuery.Add("host", Utils.UrlEncode(item.RequestHost)); dicQuery.Add("host", Utils.UrlEncode(item.RequestHost));
@ -92,7 +92,7 @@ public class BaseFmt
break; break;
case nameof(ETransport.kcp): 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()) if (item.Path.IsNotEmpty())
{ {
dicQuery.Add("seed", Utils.UrlEncode(item.Path)); dicQuery.Add("seed", Utils.UrlEncode(item.Path));
@ -120,14 +120,14 @@ public class BaseFmt
{ {
dicQuery.Add("path", Utils.UrlEncode(item.Path)); 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)); dicQuery.Add("mode", Utils.UrlEncode(item.HeaderType));
} }
if (item.Extra.IsNotEmpty()) if (item.Extra.IsNotEmpty())
{ {
var node = JsonUtils.ParseJson(item.Extra); var node = JsonUtils.ParseJson(item.Extra);
var extra = node != null var extra = node is not null
? JsonUtils.Serialize(node, new JsonSerializerOptions ? JsonUtils.Serialize(node, new JsonSerializerOptions
{ {
WriteIndented = false, WriteIndented = false,
@ -153,7 +153,7 @@ public class BaseFmt
break; break;
case nameof(ETransport.quic): 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("quicSecurity", Utils.UrlEncode(item.RequestHost));
dicQuery.Add("key", Utils.UrlEncode(item.Path)); dicQuery.Add("key", Utils.UrlEncode(item.Path));
break; break;
@ -163,7 +163,7 @@ public class BaseFmt
{ {
dicQuery.Add("authority", Utils.UrlEncode(item.RequestHost)); dicQuery.Add("authority", Utils.UrlEncode(item.RequestHost));
dicQuery.Add("serviceName", Utils.UrlEncode(item.Path)); 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)); dicQuery.Add("mode", Utils.UrlEncode(item.HeaderType));
} }
@ -191,7 +191,7 @@ public class BaseFmt
private static int ToUriQueryAllowInsecure(ProfileItem item, ref Dictionary<string, string> dicQuery) private static int ToUriQueryAllowInsecure(ProfileItem item, ref Dictionary<string, string> dicQuery)
{ {
if (item.AllowInsecure.Equals(Global.AllowInsecure.First())) if (item.AllowInsecure.Equals(AppConfig.AllowInsecure.First(), StringComparison.OrdinalIgnoreCase))
{ {
// Add two for compatibility // Add two for compatibility
dicQuery.Add("insecure", "1"); dicQuery.Add("insecure", "1");
@ -222,11 +222,11 @@ public class BaseFmt
if (_allowInsecureArray.Any(k => GetQueryDecoded(query, k) == "1")) 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")) else if (_allowInsecureArray.Any(k => GetQueryDecoded(query, k) == "0"))
{ {
item.AllowInsecure = Global.AllowInsecure.Skip(1).First(); item.AllowInsecure = AppConfig.AllowInsecure.Skip(1).First();
} }
else else
{ {
@ -237,12 +237,12 @@ public class BaseFmt
switch (item.Network) switch (item.Network)
{ {
case nameof(ETransport.tcp): case nameof(ETransport.tcp):
item.HeaderType = GetQueryValue(query, "headerType", Global.None); item.HeaderType = GetQueryValue(query, "headerType", AppConfig.None);
item.RequestHost = GetQueryDecoded(query, "host"); item.RequestHost = GetQueryDecoded(query, "host");
break; break;
case nameof(ETransport.kcp): case nameof(ETransport.kcp):
item.HeaderType = GetQueryValue(query, "headerType", Global.None); item.HeaderType = GetQueryValue(query, "headerType", AppConfig.None);
item.Path = GetQueryDecoded(query, "seed"); item.Path = GetQueryDecoded(query, "seed");
break; break;
@ -260,7 +260,7 @@ public class BaseFmt
if (extraDecoded.IsNotEmpty()) if (extraDecoded.IsNotEmpty())
{ {
var node = JsonUtils.ParseJson(extraDecoded); var node = JsonUtils.ParseJson(extraDecoded);
if (node != null) if (node is not null)
{ {
extraDecoded = JsonUtils.Serialize(node, new JsonSerializerOptions extraDecoded = JsonUtils.Serialize(node, new JsonSerializerOptions
{ {
@ -281,15 +281,15 @@ public class BaseFmt
break; break;
case nameof(ETransport.quic): case nameof(ETransport.quic):
item.HeaderType = GetQueryValue(query, "headerType", Global.None); item.HeaderType = GetQueryValue(query, "headerType", AppConfig.None);
item.RequestHost = GetQueryValue(query, "quicSecurity", Global.None); item.RequestHost = GetQueryValue(query, "quicSecurity", AppConfig.None);
item.Path = GetQueryDecoded(query, "key"); item.Path = GetQueryDecoded(query, "key");
break; break;
case nameof(ETransport.grpc): case nameof(ETransport.grpc):
item.RequestHost = GetQueryDecoded(query, "authority"); item.RequestHost = GetQueryDecoded(query, "authority");
item.Path = GetQueryDecoded(query, "serviceName"); item.Path = GetQueryDecoded(query, "serviceName");
item.HeaderType = GetQueryDecoded(query, "mode", Global.GrpcGunMode); item.HeaderType = GetQueryDecoded(query, "mode", AppConfig.GrpcGunMode);
break; break;
default: default:
@ -300,7 +300,7 @@ public class BaseFmt
protected static bool Contains(string str, params string[] s) 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") 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<string, string>? dicQuery, string? remark) protected static string ToUri(EConfigType eConfigType, string address, object port, string userInfo, Dictionary<string, string>? dicQuery, string? remark)
{ {
var query = dicQuery != null var query = dicQuery is not null
? ("?" + string.Join("&", dicQuery.Select(x => x.Key + "=" + x.Value).ToArray())) ? ("?" + string.Join("&", dicQuery.Select(x => x.Key + "=" + x.Value).ToArray()))
: string.Empty; : string.Empty;
var url = $"{Utils.UrlEncode(userInfo)}@{GetIpv6(address)}:{port}"; 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 = "") protected static string GetQueryValue(NameValueCollection query, string key, string defaultValue = "")

View file

@ -33,58 +33,29 @@ public class FmtHandler
public static ProfileItem? ResolveConfig(string config, out string msg) 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 try
{ {
var str = config.TrimEx(); return span switch
if (str.IsNullOrEmpty())
{ {
msg = ResUI.FailedReadConfiguration; _ when IsProtocol(span, EConfigType.VMess) => VmessFmt.Resolve(config, out msg),
return null; _ 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),
if (str.StartsWith(Global.ProtocolShares[EConfigType.VMess])) _ when IsProtocol(span, EConfigType.VLESS) => VLESSFmt.Resolve(config, out msg),
{ _ when IsProtocol(span, EConfigType.Hysteria2) || span.StartsWith(AppConfig.Hysteria2ProtocolShare,
return VmessFmt.Resolve(str, out msg); StringComparison.OrdinalIgnoreCase) => Hysteria2Fmt.Resolve(config, out msg),
} _ when IsProtocol(span, EConfigType.TUIC) => TuicFmt.Resolve(config, out msg),
else if (str.StartsWith(Global.ProtocolShares[EConfigType.Shadowsocks])) _ when IsProtocol(span, EConfigType.WireGuard) => WireguardFmt.Resolve(config, out msg),
{ _ when IsProtocol(span, EConfigType.Anytls) => AnytlsFmt.Resolve(config, out msg),
return ShadowsocksFmt.Resolve(str, out msg); _ => HandleUnknown(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;
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -93,4 +64,16 @@ public class FmtHandler
return null; return null;
} }
} }
private static bool IsProtocol(ReadOnlySpan<char> 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;
}
} }

View file

@ -11,7 +11,7 @@ public class Hysteria2Fmt : BaseFmt
}; };
var url = Utils.TryUri(str); var url = Utils.TryUri(str);
if (url == null) if (url is null)
{ {
return null; return null;
} }
@ -35,13 +35,11 @@ public class Hysteria2Fmt : BaseFmt
public static string? ToUri(ProfileItem? item) public static string? ToUri(ProfileItem? item)
{ {
if (item == null) if (item is null)
{ {
return null; return null;
} }
var url = string.Empty;
var remark = string.Empty; var remark = string.Empty;
if (item.Remarks.IsNotEmpty()) if (item.Remarks.IsNotEmpty())
{ {

View file

@ -8,7 +8,7 @@ public class ShadowsocksFmt : BaseFmt
ProfileItem? item; ProfileItem? item;
item = ResolveSSLegacy(str) ?? ResolveSip002(str); item = ResolveSSLegacy(str) ?? ResolveSip002(str);
if (item == null) if (item is null)
{ {
return null; return null;
} }
@ -24,7 +24,7 @@ public class ShadowsocksFmt : BaseFmt
public static string? ToUri(ProfileItem? item) public static string? ToUri(ProfileItem? item)
{ {
if (item == null) if (item is null)
{ {
return null; return null;
} }
@ -46,7 +46,7 @@ public class ShadowsocksFmt : BaseFmt
var plugin = string.Empty; var plugin = string.Empty;
var pluginArgs = 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"; plugin = "obfs-local";
pluginArgs = $"obfs=http;obfs-host={item.RequestHost};"; pluginArgs = $"obfs=http;obfs-host={item.RequestHost};";
@ -66,7 +66,7 @@ public class ShadowsocksFmt : BaseFmt
{ {
pluginArgs += "mode=quic;"; pluginArgs += "mode=quic;";
} }
if (item.StreamSecurity == Global.StreamSecurity) if (item.StreamSecurity == AppConfig.StreamSecurity)
{ {
pluginArgs += "tls;"; pluginArgs += "tls;";
var certs = CertPemManager.ParsePemChain(item.Cert); var certs = CertPemManager.ParsePemChain(item.Cert);
@ -146,7 +146,7 @@ public class ShadowsocksFmt : BaseFmt
private static ProfileItem? ResolveSip002(string result) private static ProfileItem? ResolveSip002(string result)
{ {
var parsedUrl = Utils.TryUri(result); var parsedUrl = Utils.TryUri(result);
if (parsedUrl == null) if (parsedUrl is null)
{ {
return null; return null;
} }
@ -183,7 +183,7 @@ public class ShadowsocksFmt : BaseFmt
} }
var queryParameters = Utils.ParseQueryString(parsedUrl.Query); var queryParameters = Utils.ParseQueryString(parsedUrl.Query);
if (queryParameters["plugin"] != null) if (queryParameters["plugin"] is not null)
{ {
var pluginStr = queryParameters["plugin"]; var pluginStr = queryParameters["plugin"];
var pluginParts = pluginStr.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var pluginParts = pluginStr.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
@ -211,8 +211,8 @@ public class ShadowsocksFmt : BaseFmt
if ((!obfsMode.IsNullOrEmpty()) && obfsMode.Contains("obfs=http") && obfsHost.IsNotEmpty()) if ((!obfsMode.IsNullOrEmpty()) && obfsMode.Contains("obfs=http") && obfsHost.IsNotEmpty())
{ {
obfsHost = obfsHost.Replace("obfs-host=", ""); obfsHost = obfsHost.Replace("obfs-host=", "");
item.Network = Global.DefaultNetwork; item.Network = AppConfig.DefaultNetwork;
item.HeaderType = Global.TcpHeaderHttp; item.HeaderType = AppConfig.TcpHeaderHttp;
item.RequestHost = obfsHost; item.RequestHost = obfsHost;
} }
} }
@ -249,7 +249,7 @@ public class ShadowsocksFmt : BaseFmt
if (hasTls) if (hasTls)
{ {
item.StreamSecurity = Global.StreamSecurity; item.StreamSecurity = AppConfig.StreamSecurity;
if (!certRaw.IsNullOrEmpty()) if (!certRaw.IsNullOrEmpty())
{ {

View file

@ -15,7 +15,7 @@ public class SingboxFmt : BaseFmt
{ {
var objectString = JsonUtils.Serialize(configObject); var objectString = JsonUtils.Serialize(configObject);
var profileIt = ResolveFull(objectString, subRemarks); var profileIt = ResolveFull(objectString, subRemarks);
if (profileIt != null) if (profileIt is not null)
{ {
lstResult.Add(profileIt); lstResult.Add(profileIt);
} }
@ -26,10 +26,10 @@ public class SingboxFmt : BaseFmt
public static ProfileItem? ResolveFull(string strData, string? subRemarks) public static ProfileItem? ResolveFull(string strData, string? subRemarks)
{ {
var config = JsonUtils.ParseJson(strData); var config = JsonUtils.ParseJson(strData);
if (config?["inbounds"] == null if (config?["inbounds"] is null
|| config["outbounds"] == null || config["outbounds"] is null
|| config["route"] == null || config["route"] is null
|| config["dns"] == null) || config["dns"] is null)
{ {
return null; return null;
} }

View file

@ -7,7 +7,7 @@ public class SocksFmt : BaseFmt
msg = ResUI.ConfigurationFormatIncorrect; msg = ResUI.ConfigurationFormatIncorrect;
var item = ResolveSocksNew(str) ?? ResolveSocks(str); var item = ResolveSocksNew(str) ?? ResolveSocks(str);
if (item == null) if (item is null)
{ {
return null; return null;
} }
@ -23,7 +23,7 @@ public class SocksFmt : BaseFmt
public static string? ToUri(ProfileItem? item) public static string? ToUri(ProfileItem? item)
{ {
if (item == null) if (item is null)
{ {
return null; return null;
} }
@ -43,7 +43,7 @@ public class SocksFmt : BaseFmt
{ {
ConfigType = EConfigType.SOCKS ConfigType = EConfigType.SOCKS
}; };
result = result[Global.ProtocolShares[EConfigType.SOCKS].Length..]; result = result[AppConfig.ProtocolShares[EConfigType.SOCKS].Length..];
//remark //remark
var indexRemark = result.IndexOf('#'); var indexRemark = result.IndexOf('#');
if (indexRemark > 0) if (indexRemark > 0)
@ -87,7 +87,7 @@ public class SocksFmt : BaseFmt
private static ProfileItem? ResolveSocksNew(string result) private static ProfileItem? ResolveSocksNew(string result)
{ {
var parsedUrl = Utils.TryUri(result); var parsedUrl = Utils.TryUri(result);
if (parsedUrl == null) if (parsedUrl is null)
{ {
return null; return null;
} }

View file

@ -12,7 +12,7 @@ public class TrojanFmt : BaseFmt
}; };
var url = Utils.TryUri(str); var url = Utils.TryUri(str);
if (url == null) if (url is null)
{ {
return null; return null;
} }
@ -30,7 +30,7 @@ public class TrojanFmt : BaseFmt
public static string? ToUri(ProfileItem? item) public static string? ToUri(ProfileItem? item)
{ {
if (item == null) if (item is null)
{ {
return null; return null;
} }

View file

@ -12,7 +12,7 @@ public class TuicFmt : BaseFmt
}; };
var url = Utils.TryUri(str); var url = Utils.TryUri(str);
if (url == null) if (url is null)
{ {
return null; return null;
} }
@ -21,7 +21,7 @@ public class TuicFmt : BaseFmt
item.Port = url.Port; item.Port = url.Port;
item.Remarks = url.GetComponents(UriComponents.Fragment, UriFormat.Unescaped); item.Remarks = url.GetComponents(UriComponents.Fragment, UriFormat.Unescaped);
var rawUserInfo = Utils.UrlDecode(url.UserInfo); var rawUserInfo = Utils.UrlDecode(url.UserInfo);
var userInfoParts = rawUserInfo.Split(new[] { ':' }, 2); var userInfoParts = rawUserInfo.Split(':', 2);
if (userInfoParts.Length == 2) if (userInfoParts.Length == 2)
{ {
item.Id = userInfoParts.First(); item.Id = userInfoParts.First();
@ -37,7 +37,7 @@ public class TuicFmt : BaseFmt
public static string? ToUri(ProfileItem? item) public static string? ToUri(ProfileItem? item)
{ {
if (item == null) if (item is null)
{ {
return null; return null;
} }

View file

@ -15,7 +15,7 @@ public class V2rayFmt : BaseFmt
{ {
var objectString = JsonUtils.Serialize(configObject); var objectString = JsonUtils.Serialize(configObject);
var profileIt = ResolveFull(objectString, subRemarks); var profileIt = ResolveFull(objectString, subRemarks);
if (profileIt != null) if (profileIt is not null)
{ {
lstResult.Add(profileIt); lstResult.Add(profileIt);
} }
@ -27,9 +27,9 @@ public class V2rayFmt : BaseFmt
public static ProfileItem? ResolveFull(string strData, string? subRemarks) public static ProfileItem? ResolveFull(string strData, string? subRemarks)
{ {
var config = JsonUtils.ParseJson(strData); var config = JsonUtils.ParseJson(strData);
if (config?["inbounds"] == null if (config?["inbounds"] is null
|| config["outbounds"] == null || config["outbounds"] is null
|| config["routing"] == null) || config["routing"] is null)
{ {
return null; return null;
} }

View file

@ -9,11 +9,11 @@ public class VLESSFmt : BaseFmt
ProfileItem item = new() ProfileItem item = new()
{ {
ConfigType = EConfigType.VLESS, ConfigType = EConfigType.VLESS,
Security = Global.None Security = AppConfig.None
}; };
var url = Utils.TryUri(str); var url = Utils.TryUri(str);
if (url == null) if (url is null)
{ {
return null; return null;
} }
@ -24,7 +24,7 @@ public class VLESSFmt : BaseFmt
item.Id = Utils.UrlDecode(url.UserInfo); item.Id = Utils.UrlDecode(url.UserInfo);
var query = Utils.ParseQueryString(url.Query); 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"); item.StreamSecurity = GetQueryValue(query, "security");
ResolveUriQuery(query, ref item); ResolveUriQuery(query, ref item);
@ -33,7 +33,7 @@ public class VLESSFmt : BaseFmt
public static string? ToUri(ProfileItem? item) public static string? ToUri(ProfileItem? item)
{ {
if (item == null) if (item is null)
{ {
return null; return null;
} }
@ -50,9 +50,9 @@ public class VLESSFmt : BaseFmt
} }
else 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); return ToUri(EConfigType.VLESS, item.Address, item.Port, item.Id, dicQuery, remark);
} }

View file

@ -19,14 +19,14 @@ public class VmessFmt : BaseFmt
public static string? ToUri(ProfileItem? item) public static string? ToUri(ProfileItem? item)
{ {
if (item == null) if (item is null)
{ {
return null; return null;
} }
var vmessQRCode = new VmessQRCode var vmessQRCode = new VmessQRCode
{ {
v = item.ConfigVersion, v = item.ConfigVersion,
ps = item.Remarks.TrimEx(), ps = item.Remarks.TrimSafe(),
add = item.Address, add = item.Address,
port = item.Port, port = item.Port,
id = item.Id, id = item.Id,
@ -40,12 +40,12 @@ public class VmessFmt : BaseFmt
sni = item.Sni, sni = item.Sni,
alpn = item.Alpn, alpn = item.Alpn,
fp = item.Fingerprint, 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); var url = JsonUtils.Serialize(vmessQRCode);
url = Utils.Base64Encode(url); url = Utils.Base64Encode(url);
url = $"{Global.ProtocolShares[EConfigType.VMess]}{url}"; url = $"{AppConfig.ProtocolShares[EConfigType.VMess]}{url}";
return url; return url;
} }
@ -58,18 +58,18 @@ public class VmessFmt : BaseFmt
ConfigType = EConfigType.VMess ConfigType = EConfigType.VMess
}; };
result = result[Global.ProtocolShares[EConfigType.VMess].Length..]; result = result[AppConfig.ProtocolShares[EConfigType.VMess].Length..];
result = Utils.Base64Decode(result); result = Utils.Base64Decode(result);
var vmessQRCode = JsonUtils.Deserialize<VmessQRCode>(result); var vmessQRCode = JsonUtils.Deserialize<VmessQRCode>(result);
if (vmessQRCode == null) if (vmessQRCode is null)
{ {
msg = ResUI.FailedConversionConfiguration; msg = ResUI.FailedConversionConfiguration;
return null; return null;
} }
item.Network = Global.DefaultNetwork; item.Network = AppConfig.DefaultNetwork;
item.HeaderType = Global.None; item.HeaderType = AppConfig.None;
item.ConfigVersion = vmessQRCode.v; item.ConfigVersion = vmessQRCode.v;
item.Remarks = Utils.ToString(vmessQRCode.ps); item.Remarks = Utils.ToString(vmessQRCode.ps);
@ -79,7 +79,7 @@ public class VmessFmt : BaseFmt
item.AlterId = vmessQRCode.aid; item.AlterId = vmessQRCode.aid;
item.Security = Utils.ToString(vmessQRCode.scy); 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()) if (vmessQRCode.net.IsNotEmpty())
{ {
item.Network = vmessQRCode.net; item.Network = vmessQRCode.net;
@ -95,7 +95,7 @@ public class VmessFmt : BaseFmt
item.Sni = Utils.ToString(vmessQRCode.sni); item.Sni = Utils.ToString(vmessQRCode.sni);
item.Alpn = Utils.ToString(vmessQRCode.alpn); item.Alpn = Utils.ToString(vmessQRCode.alpn);
item.Fingerprint = Utils.ToString(vmessQRCode.fp); 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; return item;
} }
@ -109,7 +109,7 @@ public class VmessFmt : BaseFmt
}; };
var url = Utils.TryUri(str); var url = Utils.TryUri(str);
if (url == null) if (url is null)
{ {
return null; return null;
} }

View file

@ -12,7 +12,7 @@ public class WireguardFmt : BaseFmt
}; };
var url = Utils.TryUri(str); var url = Utils.TryUri(str);
if (url == null) if (url is null)
{ {
return null; return null;
} }
@ -34,7 +34,7 @@ public class WireguardFmt : BaseFmt
public static string? ToUri(ProfileItem? item) public static string? ToUri(ProfileItem? item)
{ {
if (item == null) if (item is null)
{ {
return null; return null;
} }

View file

@ -59,8 +59,8 @@ public static class SubscriptionHandler
private static bool IsValidSubscription(SubItem item, string subId) private static bool IsValidSubscription(SubItem item, string subId)
{ {
var id = item.Id.TrimEx(); var id = item.Id.TrimSafe();
var url = item.Url.TrimEx(); var url = item.Url.TrimSafe();
if (id.IsNullOrEmpty() || url.IsNullOrEmpty()) if (id.IsNullOrEmpty() || url.IsNullOrEmpty())
{ {
@ -72,7 +72,7 @@ public static class SubscriptionHandler
return false; return false;
} }
if (!url.StartsWith(Global.HttpsProtocol) && !url.StartsWith(Global.HttpProtocol)) if (!url.StartsWith(AppConfig.HttpsProtocol) && !url.StartsWith(AppConfig.HttpProtocol))
{ {
return false; return false;
} }
@ -109,7 +109,7 @@ public static class SubscriptionHandler
var result = await DownloadMainSubscription(config, item, blProxy, downloadHandle); var result = await DownloadMainSubscription(config, item, blProxy, downloadHandle);
// Process additional subscription links (if any) // 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); result = await DownloadAdditionalSubscriptions(item, result, blProxy, downloadHandle);
} }
@ -120,13 +120,13 @@ public static class SubscriptionHandler
private static async Task<string> DownloadMainSubscription(Config config, SubItem item, bool blProxy, DownloadService downloadHandle) private static async Task<string> DownloadMainSubscription(Config config, SubItem item, bool blProxy, DownloadService downloadHandle)
{ {
// Prepare subscription URL and download directly // 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 conversion is needed
if (item.ConvertTarget.IsNotEmpty()) if (item.ConvertTarget.IsNotEmpty())
{ {
var subConvertUrl = config.ConstItem.SubConvertUrl.IsNullOrEmpty() var subConvertUrl = config.ConstItem.SubConvertUrl.IsNullOrEmpty()
? Global.SubConvertUrls.FirstOrDefault() ? AppConfig.SubConvertUrls.FirstOrDefault()
: config.ConstItem.SubConvertUrl; : config.ConstItem.SubConvertUrl;
url = string.Format(subConvertUrl!, Utils.UrlEncode(url)); url = string.Format(subConvertUrl!, Utils.UrlEncode(url));
@ -138,7 +138,7 @@ public static class SubscriptionHandler
if (!url.Contains("config=")) 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 // Process additional URL list
var lstUrl = item.MoreUrl.TrimEx().Split(",") ?? []; var lstUrl = item.MoreUrl.TrimSafe().Split(",") ?? [];
foreach (var it in lstUrl) foreach (var it in lstUrl)
{ {
var url2 = Utils.GetPunycode(it); var url2 = Utils.GetPunycode(it);

View file

@ -2,7 +2,7 @@ namespace ServiceLib.Handler.SysProxy;
public static class ProxySettingLinux 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) 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 customSystemProxyScriptPath = AppManager.Instance.Config.SystemProxyItem?.CustomSystemProxyScriptPath;
var fileName = (customSystemProxyScriptPath.IsNotEmpty() && File.Exists(customSystemProxyScriptPath)) var fileName = (customSystemProxyScriptPath.IsNotEmpty() && File.Exists(customSystemProxyScriptPath))
? 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 // TODO: temporarily notify which script is being used
NoticeManager.Instance.SendMessage(fileName); NoticeManager.Instance.SendMessage(fileName);

View file

@ -2,7 +2,7 @@ namespace ServiceLib.Handler.SysProxy;
public static class ProxySettingOSX 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) 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 customSystemProxyScriptPath = AppManager.Instance.Config.SystemProxyItem?.CustomSystemProxyScriptPath;
var fileName = (customSystemProxyScriptPath.IsNotEmpty() && File.Exists(customSystemProxyScriptPath)) var fileName = (customSystemProxyScriptPath.IsNotEmpty() && File.Exists(customSystemProxyScriptPath))
? 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 // TODO: temporarily notify which script is being used
NoticeManager.Instance.SendMessage(fileName); NoticeManager.Instance.SendMessage(fileName);

View file

@ -2,7 +2,7 @@ using static ServiceLib.Handler.SysProxy.ProxySettingWindows.InternetConnectionO
namespace ServiceLib.Handler.SysProxy; namespace ServiceLib.Handler.SysProxy;
public static class ProxySettingWindows public static partial class ProxySettingWindows
{ {
private const string _regPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings"; private const string _regPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
@ -121,7 +121,7 @@ public static class ProxySettingWindows
// default stuff // default stuff
list.dwSize = Marshal.SizeOf(list); list.dwSize = Marshal.SizeOf(list);
if (connectionName != null) if (connectionName is not null)
{ {
list.szConnection = Marshal.StringToHGlobalAuto(connectionName); // !! remember to deallocate memory 3 list.szConnection = Marshal.StringToHGlobalAuto(connectionName); // !! remember to deallocate memory 3
} }
@ -201,29 +201,29 @@ public static class ProxySettingWindows
/// </summary> /// </summary>
/// <returns>A list of RAS connection names. May be empty list if no dial up connection.</returns> /// <returns>A list of RAS connection names. May be empty list if no dial up connection.</returns>
/// <exception cref="ApplicationException">Error message with win32 error code</exception> /// <exception cref="ApplicationException">Error message with win32 error code</exception>
private static IEnumerable<string> EnumerateRasEntries() private static List<string> EnumerateRasEntries()
{ {
var entries = 0; var entries = 0;
// attempt to query with 1 entry buffer // attempt to query with 1 entry buffer
var rasEntryNames = new RASENTRYNAME[1]; var rasEntryNames = new RASENTRYNAME[1];
var bufferSize = Marshal.SizeOf(typeof(RASENTRYNAME)); var bufferSize = Marshal.SizeOf<RASENTRYNAME>();
rasEntryNames[0].dwSize = Marshal.SizeOf(typeof(RASENTRYNAME)); rasEntryNames[0].dwSize = Marshal.SizeOf<RASENTRYNAME>();
var result = NativeMethods.RasEnumEntries(null, null, rasEntryNames, ref bufferSize, ref entries); var result = NativeMethods.RasEnumEntries(null, null, rasEntryNames, ref bufferSize, ref entries);
// increase buffer if the buffer is not large enough // increase buffer if the buffer is not large enough
if (result == (uint)ErrorCode.ERROR_BUFFER_TOO_SMALL) if (result == (uint)ErrorCode.ERROR_BUFFER_TOO_SMALL)
{ {
rasEntryNames = new RASENTRYNAME[bufferSize / Marshal.SizeOf(typeof(RASENTRYNAME))]; rasEntryNames = new RASENTRYNAME[bufferSize / Marshal.SizeOf<RASENTRYNAME>()];
for (var i = 0; i < rasEntryNames.Length; i++) for (var i = 0; i < rasEntryNames.Length; i++)
{ {
rasEntryNames[i].dwSize = Marshal.SizeOf(typeof(RASENTRYNAME)); rasEntryNames[i].dwSize = Marshal.SizeOf<RASENTRYNAME>();
} }
result = NativeMethods.RasEnumEntries(null, null, rasEntryNames, ref bufferSize, ref entries); result = NativeMethods.RasEnumEntries(null, null, rasEntryNames, ref bufferSize, ref entries);
} }
if (result == 0) if (result == 0)
{ {
var entryNames = new List<string>(); var entryNames = new List<string>(entries);
for (var i = 0; i < entries; i++) for (var i = 0; i < entries; i++)
{ {
entryNames.Add(rasEntryNames[i].szEntryName); entryNames.Add(rasEntryNames[i].szEntryName);
@ -231,7 +231,7 @@ public static class ProxySettingWindows
return entryNames; return entryNames;
} }
throw new ApplicationException($"RasEnumEntries failed with error code: {result}"); throw new Win32Exception((int)result);
} }
#region WinInet structures #region WinInet structures
@ -340,11 +340,11 @@ public static class ProxySettingWindows
#endregion WinInet enums #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)] [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)] [DllImport("Rasapi32.dll", CharSet = CharSet.Auto)]
public static extern uint RasEnumEntries( public static extern uint RasEnumEntries(

View file

@ -30,11 +30,11 @@ public static class SysProxyHandler
break; break;
} }
case ESysProxyType.ForcedChange when Utils.IsLinux(): case ESysProxyType.ForcedChange when Utils.IsLinux():
await ProxySettingLinux.SetProxy(Global.Loopback, port, exceptions); await ProxySettingLinux.SetProxy(AppConfig.Loopback, port, exceptions);
break; break;
case ESysProxyType.ForcedChange when Utils.IsMacOS(): case ESysProxyType.ForcedChange when Utils.IsMacOS():
await ProxySettingOSX.SetProxy(Global.Loopback, port, exceptions); await ProxySettingOSX.SetProxy(AppConfig.Loopback, port, exceptions);
break; break;
case ESysProxyType.ForcedClear when Utils.IsWindows(): case ESysProxyType.ForcedClear when Utils.IsWindows():
@ -74,15 +74,14 @@ public static class SysProxyHandler
strExceptions = $"<local>;{strExceptions}"; strExceptions = $"<local>;{strExceptions}";
} }
strProxy = string.Empty;
if (config.SystemProxyItem.SystemProxyAdvancedProtocol.IsNullOrEmpty()) if (config.SystemProxyItem.SystemProxyAdvancedProtocol.IsNullOrEmpty())
{ {
strProxy = $"{Global.Loopback}:{port}"; strProxy = $"{AppConfig.Loopback}:{port}";
} }
else else
{ {
strProxy = config.SystemProxyItem.SystemProxyAdvancedProtocol strProxy = config.SystemProxyItem.SystemProxyAdvancedProtocol
.Replace("{ip}", Global.Loopback) .Replace("{ip}", AppConfig.Loopback)
.Replace("{http_port}", port.ToString()) .Replace("{http_port}", port.ToString())
.Replace("{socks_port}", port.ToString()); .Replace("{socks_port}", port.ToString());
} }
@ -92,7 +91,7 @@ public static class SysProxyHandler
{ {
var portPac = AppManager.Instance.GetLocalPort(EInboundProtocol.pac); var portPac = AppManager.Instance.GetLocalPort(EInboundProtocol.pac);
await PacManager.Instance.StartAsync(port, portPac); 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); ProxySettingWindows.SetProxy(strProxy, "", 4);
} }
} }

View file

@ -2,12 +2,9 @@ using Downloader;
namespace ServiceLib.Helper; namespace ServiceLib.Helper;
public class DownloaderHelper public static class DownloaderHelper
{ {
private static readonly Lazy<DownloaderHelper> _instance = new(() => new()); public static async Task<string?> DownloadStringAsync(IWebProxy? webProxy, string url, string? userAgent, int timeout)
public static DownloaderHelper Instance => _instance.Value;
public async Task<string?> DownloadStringAsync(IWebProxy? webProxy, string url, string? userAgent, int timeout)
{ {
if (url.IsNullOrEmpty()) if (url.IsNullOrEmpty())
{ {
@ -38,7 +35,7 @@ public class DownloaderHelper
await using var downloader = new Downloader.DownloadService(downloadOpt); await using var downloader = new Downloader.DownloadService(downloadOpt);
downloader.DownloadFileCompleted += (sender, value) => downloader.DownloadFileCompleted += (sender, value) =>
{ {
if (value.Error != null) if (value.Error is not null)
{ {
throw value.Error; throw value.Error;
} }
@ -53,7 +50,7 @@ public class DownloaderHelper
return await reader.ReadToEndAsync(cts.Token); return await reader.ReadToEndAsync(cts.Token);
} }
public async Task DownloadDataAsync4Speed(IWebProxy webProxy, string url, IProgress<string> progress, int timeout) public static async Task DownloadDataAsync4Speed(IWebProxy webProxy, string url, IProgress<string> progress, int timeout)
{ {
if (url.IsNullOrEmpty()) if (url.IsNullOrEmpty())
{ {
@ -78,14 +75,14 @@ public class DownloaderHelper
downloader.DownloadProgressChanged += (sender, value) => downloader.DownloadProgressChanged += (sender, value) =>
{ {
if (progress != null && value.BytesPerSecondSpeed > 0) if (progress is not null && value.BytesPerSecondSpeed > 0)
{ {
hasValue = true; hasValue = true;
if (value.BytesPerSecondSpeed > maxSpeed) if (value.BytesPerSecondSpeed > maxSpeed)
{ {
maxSpeed = value.BytesPerSecondSpeed; maxSpeed = value.BytesPerSecondSpeed;
} }
var ts = DateTime.Now - lastUpdateTime; var ts = DateTime.Now - lastUpdateTime;
if (ts.TotalMilliseconds >= 1000) if (ts.TotalMilliseconds >= 1000)
{ {
@ -97,14 +94,14 @@ public class DownloaderHelper
}; };
downloader.DownloadFileCompleted += (sender, value) => downloader.DownloadFileCompleted += (sender, value) =>
{ {
if (progress != null) if (progress is not null)
{ {
if (hasValue && maxSpeed > 0) if (hasValue && maxSpeed > 0)
{ {
var finalSpeed = (maxSpeed / 1000 / 1000).ToString("#0.0"); var finalSpeed = (maxSpeed / 1000 / 1000).ToString("#0.0");
progress.Report(finalSpeed); progress.Report(finalSpeed);
} }
else if (value.Error != null) else if (value.Error is not null)
{ {
progress.Report(value.Error?.Message); progress.Report(value.Error?.Message);
} }
@ -122,7 +119,7 @@ public class DownloaderHelper
downloadOpt = null; downloadOpt = null;
} }
public async Task DownloadFileAsync(IWebProxy? webProxy, string url, string fileName, IProgress<double> progress, int timeout) public static async Task DownloadFileAsync(IWebProxy? webProxy, string url, string fileName, IProgress<double> progress, int timeout)
{ {
if (url.IsNullOrEmpty()) if (url.IsNullOrEmpty())
{ {
@ -164,13 +161,13 @@ public class DownloaderHelper
}; };
downloader.DownloadFileCompleted += (sender, value) => 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); progress.Report(101);
} }
else if (value.Error != null) else if (value.Error is not null)
{ {
throw value.Error; throw value.Error;
} }

View file

@ -107,12 +107,12 @@ public class ActionPrecheckManager
if (coreType == ECoreType.sing_box) if (coreType == ECoreType.sing_box)
{ {
var transportError = ValidateSingboxTransport(item.ConfigType, net); var transportError = ValidateSingboxTransport(item.ConfigType, net);
if (transportError != null) if (transportError is not null)
{ {
errors.Add(transportError); errors.Add(transportError);
} }
if (!Global.SingboxSupportConfigType.Contains(item.ConfigType)) if (!AppConfig.SingboxSupportConfigType.Contains(item.ConfigType))
{ {
errors.Add(string.Format(ResUI.CoreNotSupportProtocol, errors.Add(string.Format(ResUI.CoreNotSupportProtocol,
nameof(ECoreType.sing_box), item.ConfigType.ToString())); nameof(ECoreType.sing_box), item.ConfigType.ToString()));
@ -121,7 +121,7 @@ public class ActionPrecheckManager
else if (coreType is ECoreType.Xray) else if (coreType is ECoreType.Xray)
{ {
// Xray core does not support these protocols // 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, errors.Add(string.Format(ResUI.CoreNotSupportProtocol,
nameof(ECoreType.Xray), item.ConfigType.ToString())); nameof(ECoreType.Xray), item.ConfigType.ToString()));
@ -144,7 +144,7 @@ public class ActionPrecheckManager
errors.Add(string.Format(ResUI.InvalidProperty, "Id")); 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")); errors.Add(string.Format(ResUI.InvalidProperty, "Flow"));
} }
@ -157,7 +157,7 @@ public class ActionPrecheckManager
errors.Add(string.Format(ResUI.InvalidProperty, "Id")); 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")); errors.Add(string.Format(ResUI.InvalidProperty, "Security"));
} }
@ -165,7 +165,7 @@ public class ActionPrecheckManager
break; break;
} }
if (item.StreamSecurity == Global.StreamSecurity) if (item.StreamSecurity == AppConfig.StreamSecurity)
{ {
// check certificate validity // check certificate validity
if (!item.Cert.IsNullOrEmpty() 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()) if (item.PublicKey.IsNullOrEmpty())
{ {
@ -330,7 +330,7 @@ public class ActionPrecheckManager
var coreType = AppManager.Instance.GetCoreType(item, item.ConfigType); var coreType = AppManager.Instance.GetCoreType(item, item.ConfigType);
var routing = await ConfigHandler.GetDefaultRouting(AppManager.Instance.Config); var routing = await ConfigHandler.GetDefaultRouting(AppManager.Instance.Config);
if (routing == null) if (routing is null)
{ {
return errors; return errors;
} }
@ -344,7 +344,7 @@ public class ActionPrecheckManager
} }
var outboundTag = ruleItem.OutboundTag; var outboundTag = ruleItem.OutboundTag;
if (outboundTag.IsNullOrEmpty() || Global.OutboundTags.Contains(outboundTag)) if (outboundTag.IsNullOrEmpty() || AppConfig.OutboundTags.Contains(outboundTag))
{ {
continue; continue;
} }

View file

@ -5,11 +5,10 @@ public sealed class AppManager
#region Property #region Property
private static readonly Lazy<AppManager> _instance = new(() => new()); private static readonly Lazy<AppManager> _instance = new(() => new());
private Config _config;
private int? _statePort; private int? _statePort;
private int? _statePort2; private int? _statePort2;
public static AppManager Instance => _instance.Value; public static AppManager Instance => _instance.Value;
public Config Config => _config; public Config Config { get; private set; }
public int StatePort public int StatePort
{ {
@ -25,7 +24,7 @@ public sealed class AppManager
get get
{ {
_statePort2 ??= Utils.GetFreePort(GetLocalPort(EInboundProtocol.api2)); _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) if (Utils.HasWritePermission() == false)
{ {
Environment.SetEnvironmentVariable(Global.LocalAppData, "1", EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable(AppConfig.LocalAppData, "1", EnvironmentVariableTarget.Process);
} }
Logging.Setup(); Logging.Setup();
var config = ConfigHandler.LoadConfig(); var config = ConfigHandler.LoadConfig();
if (config == null) if (config is null)
{ {
return false; return false;
} }
_config = config; Config = config;
Thread.CurrentThread.CurrentUICulture = new(_config.UiItem.CurrentLanguage); Thread.CurrentThread.CurrentUICulture = new(Config.UiItem.CurrentLanguage);
//Under Win10 //Under Win10
if (Utils.IsWindows() && Environment.OSVersion.Version.Major < 10) if (Utils.IsWindows() && Environment.OSVersion.Version.Major < 10)
@ -88,7 +87,7 @@ public sealed class AppManager
public bool InitComponents() public bool InitComponents()
{ {
Logging.SaveLog($"v2rayN start up | {Utils.GetRuntimeInfo()}"); Logging.SaveLog($"v2rayN start up | {Utils.GetRuntimeInfo()}");
Logging.LoggingEnabled(_config.GuiItem.EnableLog); Logging.LoggingEnabled(Config.GuiItem.EnableLog);
//First determine the port value //First determine the port value
_ = StatePort; _ = StatePort;
@ -110,11 +109,11 @@ public sealed class AppManager
{ {
Logging.SaveLog("AppExitAsync Begin"); Logging.SaveLog("AppExitAsync Begin");
await SysProxyHandler.UpdateSysProxy(_config, true); await SysProxyHandler.UpdateSysProxy(Config, true);
AppEvents.AppExitRequested.Publish(); AppEvents.AppExitRequested.Publish();
await Task.Delay(50); //Wait for AppExitRequested to be processed await Task.Delay(50); //Wait for AppExitRequested to be processed
await ConfigHandler.SaveConfig(_config); await ConfigHandler.SaveConfig(Config);
await ProfileExManager.Instance.SaveTo(); await ProfileExManager.Instance.SaveTo();
await StatisticsManager.Instance.SaveTo(); await StatisticsManager.Instance.SaveTo();
await CoreManager.Instance.CoreStop(); await CoreManager.Instance.CoreStop();
@ -149,7 +148,7 @@ public sealed class AppManager
public int GetLocalPort(EInboundProtocol protocol) 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; return localPort + (int)protocol;
} }
@ -274,25 +273,25 @@ public sealed class AppManager
switch (coreType) switch (coreType)
{ {
case ECoreType.v2fly: case ECoreType.v2fly:
return Global.SsSecurities; return AppConfig.SsSecurities;
case ECoreType.Xray: case ECoreType.Xray:
return Global.SsSecuritiesInXray; return AppConfig.SsSecuritiesInXray;
case ECoreType.sing_box: case ECoreType.sing_box:
return Global.SsSecuritiesInSingbox; return AppConfig.SsSecuritiesInSingbox;
} }
return Global.SsSecuritiesInSingbox; return AppConfig.SsSecuritiesInSingbox;
} }
public ECoreType GetCoreType(ProfileItem profileItem, EConfigType eConfigType) public ECoreType GetCoreType(ProfileItem profileItem, EConfigType eConfigType)
{ {
if (profileItem?.CoreType != null) if (profileItem?.CoreType is not null)
{ {
return (ECoreType)profileItem.CoreType; 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; return item?.CoreType ?? ECoreType.Xray;
} }

View file

@ -225,7 +225,7 @@ public class CertPemManager
await ssl.AuthenticateAsClientAsync(sslOptions, cts.Token); await ssl.AuthenticateAsClientAsync(sslOptions, cts.Token);
var remote = ssl.RemoteCertificate; var remote = ssl.RemoteCertificate;
if (remote == null) if (remote is null)
{ {
return (null, null); return (null, null);
} }
@ -308,7 +308,7 @@ public class CertPemManager
X509Chain? chain, X509Chain? chain,
SslPolicyErrors sslPolicyErrors) SslPolicyErrors sslPolicyErrors)
{ {
if (certificate == null) if (certificate is null)
{ {
return false; return false;
} }
@ -409,7 +409,7 @@ public class CertPemManager
/// <returns>Concatenated PEM certificates string</returns> /// <returns>Concatenated PEM certificates string</returns>
public static string ConcatenatePemChain(IEnumerable<string> pemList) public static string ConcatenatePemChain(IEnumerable<string> pemList)
{ {
if (pemList == null) if (pemList is null)
{ {
return string.Empty; return string.Empty;
} }

View file

@ -23,7 +23,7 @@ public sealed class ClashApiManager
var result2 = await HttpClientHelper.Instance.TryGetAsync(url2); var result2 = await HttpClientHelper.Instance.TryGetAsync(url2);
var clashProviders = JsonUtils.Deserialize<ClashProviders>(result2); var clashProviders = JsonUtils.Deserialize<ClashProviders>(result2);
if (clashProxies != null || clashProviders != null) if (clashProxies is not null || clashProviders is not null)
{ {
_proxies = clashProxies?.proxies; _proxies = clashProxies?.proxies;
return new Tuple<ClashProxies, ClashProviders>(clashProxies, clashProviders); return new Tuple<ClashProxies, ClashProviders>(clashProxies, clashProviders);
@ -41,14 +41,14 @@ public sealed class ClashApiManager
{ {
if (blAll) if (blAll)
{ {
if (_proxies == null) if (_proxies is null)
{ {
await GetClashProxiesAsync(); await GetClashProxiesAsync();
} }
lstProxy = new List<ClashProxyModel>(); lstProxy = new List<ClashProxyModel>();
foreach (var kv in _proxies ?? []) foreach (var kv in _proxies ?? [])
{ {
if (Global.notAllowTestType.Contains(kv.Value.type?.ToLower())) if (AppConfig.notAllowTestType.Contains(kv.Value.type?.ToLower()))
{ {
continue; continue;
} }
@ -70,7 +70,7 @@ public sealed class ClashApiManager
var tasks = new List<Task>(); var tasks = new List<Task>();
foreach (var it in lstProxy) foreach (var it in lstProxy)
{ {
if (Global.notAllowTestType.Contains(it.Type.ToLower())) if (AppConfig.notAllowTestType.Contains(it.Type.ToLower()))
{ {
continue; continue;
} }
@ -123,7 +123,7 @@ public sealed class ClashApiManager
public async Task ClashConfigUpdate(Dictionary<string, string> headers) public async Task ClashConfigUpdate(Dictionary<string, string> headers)
{ {
if (_proxies == null) if (_proxies is null)
{ {
return; return;
} }
@ -182,6 +182,6 @@ public sealed class ClashApiManager
private string GetApiUrl() private string GetApiUrl()
{ {
return $"{Global.HttpProtocol}{Global.Loopback}:{AppManager.Instance.StatePort2}"; return $"{AppConfig.HttpProtocol}{AppConfig.Loopback}:{AppManager.Instance.StatePort2}";
} }
} }

View file

@ -14,7 +14,7 @@ public class CoreAdminManager
public async Task Init(Config config, Func<bool, string, Task> updateFunc) public async Task Init(Config config, Func<bool, string, Task> updateFunc)
{ {
if (_config != null) if (_config is not null)
{ {
return; return;
} }
@ -67,14 +67,14 @@ public class CoreAdminManager
try 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); var shFilePath = await FileUtils.CreateLinuxShellFile("kill_as_sudo.sh", EmbedUtils.GetEmbedText(shellFileName), true);
if (shFilePath.Contains(' ')) if (shFilePath.Contains(' '))
{ {
shFilePath = shFilePath.AppendQuotes(); shFilePath = shFilePath.AppendQuotes();
} }
var arg = new List<string>() { "-c", $"sudo -S {shFilePath} {_linuxSudoPid}" }; var arg = new List<string>() { "-c", $"sudo -S {shFilePath} {_linuxSudoPid}" };
var result = await Cli.Wrap(Global.LinuxBash) var result = await Cli.Wrap(AppConfig.LinuxBash)
.WithArguments(arg) .WithArguments(arg)
.WithStandardInputPipe(PipeSource.FromString(AppManager.Instance.LinuxSudoPwd)) .WithStandardInputPipe(PipeSource.FromString(AppManager.Instance.LinuxSudoPwd))
.ExecuteBufferedAsync(); .ExecuteBufferedAsync();

View file

@ -13,7 +13,7 @@ public sealed class CoreInfoManager
public CoreInfo? GetCoreInfo(ECoreType coreType) public CoreInfo? GetCoreInfo(ECoreType coreType)
{ {
if (_coreInfo == null) if (_coreInfo is null)
{ {
InitCoreInfo(); InitCoreInfo();
} }
@ -22,7 +22,7 @@ public sealed class CoreInfoManager
public List<CoreInfo> GetCoreInfo() public List<CoreInfo> GetCoreInfo()
{ {
if (_coreInfo == null) if (_coreInfo is null)
{ {
InitCoreInfo(); InitCoreInfo();
} }
@ -63,7 +63,7 @@ public sealed class CoreInfoManager
{ {
CoreType = ECoreType.v2rayN, CoreType = ECoreType.v2rayN,
Url = GetCoreUrl(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", DownloadUrlWin64 = urlN + "/download/{0}/v2rayN-windows-64.zip",
DownloadUrlWinArm64 = urlN + "/download/{0}/v2rayN-windows-arm64.zip", DownloadUrlWinArm64 = urlN + "/download/{0}/v2rayN-windows-arm64.zip",
DownloadUrlLinux64 = urlN + "/download/{0}/v2rayN-linux-64.zip", DownloadUrlLinux64 = urlN + "/download/{0}/v2rayN-linux-64.zip",
@ -82,7 +82,7 @@ public sealed class CoreInfoManager
VersionArg = "-version", VersionArg = "-version",
Environment = new Dictionary<string, string?>() Environment = new Dictionary<string, string?>()
{ {
{ Global.V2RayLocalAsset, Utils.GetBinPath("") }, { AppConfig.V2RayLocalAsset, Utils.GetBinPath("") },
}, },
}, },
@ -96,7 +96,7 @@ public sealed class CoreInfoManager
VersionArg = "version", VersionArg = "version",
Environment = new Dictionary<string, string?>() Environment = new Dictionary<string, string?>()
{ {
{ Global.V2RayLocalAsset, Utils.GetBinPath("") }, { AppConfig.V2RayLocalAsset, Utils.GetBinPath("") },
}, },
}, },
@ -106,7 +106,7 @@ public sealed class CoreInfoManager
CoreExes = ["xray"], CoreExes = ["xray"],
Arguments = "run -c {0}", Arguments = "run -c {0}",
Url = GetCoreUrl(ECoreType.Xray), 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", DownloadUrlWin64 = urlXray + "/download/{0}/Xray-windows-64.zip",
DownloadUrlWinArm64 = urlXray + "/download/{0}/Xray-windows-arm64-v8a.zip", DownloadUrlWinArm64 = urlXray + "/download/{0}/Xray-windows-arm64-v8a.zip",
DownloadUrlLinux64 = urlXray + "/download/{0}/Xray-linux-64.zip", DownloadUrlLinux64 = urlXray + "/download/{0}/Xray-linux-64.zip",
@ -117,8 +117,8 @@ public sealed class CoreInfoManager
VersionArg = "-version", VersionArg = "-version",
Environment = new Dictionary<string, string?>() Environment = new Dictionary<string, string?>()
{ {
{ Global.XrayLocalAsset, Utils.GetBinPath("") }, { AppConfig.XrayLocalAsset, Utils.GetBinPath("") },
{ Global.XrayLocalCert, Utils.GetBinPath("") }, { AppConfig.XrayLocalCert, Utils.GetBinPath("") },
}, },
}, },
@ -128,7 +128,7 @@ public sealed class CoreInfoManager
CoreExes = GetMihomoCoreExes(), CoreExes = GetMihomoCoreExes(),
Arguments = "-f {0}" + PortableMode(), Arguments = "-f {0}" + PortableMode(),
Url = GetCoreUrl(ECoreType.mihomo), 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", DownloadUrlWin64 = urlMihomo + "/download/{0}/mihomo-windows-amd64-v1-{0}.zip",
DownloadUrlWinArm64 = urlMihomo + "/download/{0}/mihomo-windows-arm64-{0}.zip", DownloadUrlWinArm64 = urlMihomo + "/download/{0}/mihomo-windows-arm64-{0}.zip",
DownloadUrlLinux64 = urlMihomo + "/download/{0}/mihomo-linux-amd64-v1-{0}.gz", DownloadUrlLinux64 = urlMihomo + "/download/{0}/mihomo-linux-amd64-v1-{0}.gz",
@ -170,7 +170,7 @@ public sealed class CoreInfoManager
Arguments = "run -c {0} --disable-color", Arguments = "run -c {0} --disable-color",
Url = GetCoreUrl(ECoreType.sing_box), 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", DownloadUrlWin64 = urlSingbox + "/download/{0}/sing-box-{1}-windows-amd64.zip",
DownloadUrlWinArm64 = urlSingbox + "/download/{0}/sing-box-{1}-windows-arm64.zip", DownloadUrlWinArm64 = urlSingbox + "/download/{0}/sing-box-{1}-windows-arm64.zip",
DownloadUrlLinux64 = urlSingbox + "/download/{0}/sing-box-{1}-linux-amd64.tar.gz", 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) private static string GetCoreUrl(ECoreType eCoreType)
{ {
return $"{Global.GithubUrl}/{Global.CoreUrls[eCoreType]}/releases"; return $"{AppConfig.GithubUrl}/{AppConfig.CoreUrls[eCoreType]}/releases";
} }
private static List<string>? GetMihomoCoreExes() private static List<string>? GetMihomoCoreExes()

View file

@ -11,7 +11,7 @@ public class CoreManager
private WindowsJobService? _processJob; private WindowsJobService? _processJob;
private ProcessService? _processService; private ProcessService? _processService;
private ProcessService? _processPreService; private ProcessService? _processPreService;
private bool _linuxSudo = false; private bool _linuxSudo;
private Func<bool, string, Task>? _updateFunc; private Func<bool, string, Task>? _updateFunc;
private const string _tag = "CoreHandler"; private const string _tag = "CoreHandler";
@ -21,7 +21,7 @@ public class CoreManager
_updateFunc = updateFunc; _updateFunc = updateFunc;
//Copy the bin folder to the storage location (for init) //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 fromPath = Utils.GetBaseDirectory("bin");
var toPath = Utils.GetBinPath(""); var toPath = Utils.GetBinPath("");
@ -59,13 +59,13 @@ public class CoreManager
public async Task LoadCore(ProfileItem? node) public async Task LoadCore(ProfileItem? node)
{ {
if (node == null) if (node is null)
{ {
await UpdateFunc(false, ResUI.CheckServerSettings); await UpdateFunc(false, ResUI.CheckServerSettings);
return; return;
} }
var fileName = Utils.GetBinConfigPath(Global.CoreConfigFileName); var fileName = Utils.GetBinConfigPath(AppConfig.CoreConfigFileName);
var result = await CoreConfigHandler.GenerateClientConfig(node, fileName); var result = await CoreConfigHandler.GenerateClientConfig(node, fileName);
if (result.Success != true) if (result.Success != true)
{ {
@ -87,7 +87,7 @@ public class CoreManager
await CoreStart(node); await CoreStart(node);
await CoreStartPreService(node); await CoreStartPreService(node);
if (_processService != null) if (_processService is not null)
{ {
await UpdateFunc(true, $"{node.GetSummary()}"); await UpdateFunc(true, $"{node.GetSummary()}");
} }
@ -95,8 +95,8 @@ public class CoreManager
public async Task<ProcessService?> LoadCoreConfigSpeedtest(List<ServerTestItem> selecteds) public async Task<ProcessService?> LoadCoreConfigSpeedtest(List<ServerTestItem> selecteds)
{ {
var coreType = selecteds.Any(t => Global.SingboxOnlyConfigType.Contains(t.ConfigType)) ? ECoreType.sing_box : ECoreType.Xray; var coreType = selecteds.Any(t => AppConfig.SingboxOnlyConfigType.Contains(t.ConfigType)) ? ECoreType.sing_box : ECoreType.Xray;
var fileName = string.Format(Global.CoreSpeedtestConfigFileName, Utils.GetGuid(false)); var fileName = string.Format(AppConfig.CoreSpeedtestConfigFileName, Utils.GetGuid(false));
var configPath = Utils.GetBinConfigPath(fileName); var configPath = Utils.GetBinConfigPath(fileName);
var result = await CoreConfigHandler.GenerateClientSpeedtestConfig(_config, configPath, selecteds, coreType); var result = await CoreConfigHandler.GenerateClientSpeedtestConfig(_config, configPath, selecteds, coreType);
await UpdateFunc(false, result.Msg); await UpdateFunc(false, result.Msg);
@ -120,7 +120,7 @@ public class CoreManager
return null; 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 configPath = Utils.GetBinConfigPath(fileName);
var result = await CoreConfigHandler.GenerateClientSpeedtestConfig(_config, node, testItem, configPath); var result = await CoreConfigHandler.GenerateClientSpeedtestConfig(_config, node, testItem, configPath);
if (result.Success != true) if (result.Success != true)
@ -143,14 +143,14 @@ public class CoreManager
_linuxSudo = false; _linuxSudo = false;
} }
if (_processService != null) if (_processService is not null)
{ {
await _processService.StopAsync(); await _processService.StopAsync();
_processService.Dispose(); _processService.Dispose();
_processService = null; _processService = null;
} }
if (_processPreService != null) if (_processPreService is not null)
{ {
await _processPreService.StopAsync(); await _processPreService.StopAsync();
_processPreService.Dispose(); _processPreService.Dispose();
@ -171,7 +171,7 @@ public class CoreManager
var coreInfo = CoreInfoManager.Instance.GetCoreInfo(coreType); var coreInfo = CoreInfoManager.Instance.GetCoreInfo(coreType);
var displayLog = node.ConfigType != EConfigType.Custom || node.DisplayLog; 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) if (proc is null)
{ {
return; return;
@ -181,19 +181,19 @@ public class CoreManager
private async Task CoreStartPreService(ProfileItem node) 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 coreType = AppManager.Instance.GetCoreType(node, node.ConfigType);
var itemSocks = await ConfigHandler.GetPreSocksItem(_config, node, coreType); var itemSocks = await ConfigHandler.GetPreSocksItem(_config, node, coreType);
if (itemSocks != null) if (itemSocks is not null)
{ {
var preCoreType = itemSocks.CoreType ?? ECoreType.sing_box; 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); var result = await CoreConfigHandler.GenerateClientConfig(itemSocks, fileName);
if (result.Success) if (result.Success)
{ {
var coreInfo = CoreInfoManager.Instance.GetCoreInfo(preCoreType); 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) if (proc is null)
{ {
return; return;

View file

@ -40,7 +40,7 @@ public class PacManager
if (!File.Exists(fileName)) if (!File.Exists(fileName))
{ {
var pac = EmbedUtils.GetEmbedText(Global.PacFileName); var pac = EmbedUtils.GetEmbedText(AppConfig.PacFileName);
await File.AppendAllTextAsync(fileName, pac); await File.AppendAllTextAsync(fileName, pac);
} }
@ -94,7 +94,7 @@ public class PacManager
public void Stop() public void Stop()
{ {
if (_tcpListener == null) if (_tcpListener is null)
{ {
return; return;
} }

View file

@ -161,7 +161,7 @@ public class ProfileExManager
public int GetSort(string indexId) public int GetSort(string indexId)
{ {
var profileEx = _lstProfileEx.FirstOrDefault(t => t.IndexId == indexId); var profileEx = _lstProfileEx.FirstOrDefault(t => t.IndexId == indexId);
if (profileEx == null) if (profileEx is null)
{ {
return 0; return 0;
} }
@ -174,6 +174,6 @@ public class ProfileExManager
{ {
return 0; return 0;
} }
return _lstProfileEx.Max(t => t == null ? 0 : t.Sort); return _lstProfileEx.Max(t => t is null ? 0 : t.Sort);
} }
} }

View file

@ -148,7 +148,7 @@ public class ProfileGroupItemManager
try try
{ {
var lst = await SQLiteHelper.Instance.TableAsync<ProfileGroupItem>().Where(t => t.IndexId == item.IndexId).ToListAsync(); var lst = await SQLiteHelper.Instance.TableAsync<ProfileGroupItem>().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<ProfileGroupItem> { item }); await SQLiteHelper.Instance.UpdateAllAsync(new List<ProfileGroupItem> { item });
} }
@ -194,7 +194,7 @@ public class ProfileGroupItemManager
{ {
Instance.TryGet(indexId, out var groupItem); Instance.TryGet(indexId, out var groupItem);
if (groupItem == null || groupItem.ChildItems.IsNullOrEmpty()) if (groupItem is null || groupItem.ChildItems.IsNullOrEmpty())
{ {
return false; return false;
} }
@ -202,7 +202,7 @@ public class ProfileGroupItemManager
var childIds = Utils.String2List(groupItem.ChildItems) var childIds = Utils.String2List(groupItem.ChildItems)
.Where(p => !string.IsNullOrEmpty(p)) .Where(p => !string.IsNullOrEmpty(p))
.ToList(); .ToList();
if (childIds == null) if (childIds is null)
{ {
return false; return false;
} }
@ -226,7 +226,7 @@ public class ProfileGroupItemManager
public static async Task<(List<ProfileItem> Items, ProfileGroupItem? Group)> GetChildProfileItems(string? indexId) public static async Task<(List<ProfileItem> Items, ProfileGroupItem? Group)> GetChildProfileItems(string? indexId)
{ {
Instance.TryGet(indexId, out var profileGroupItem); Instance.TryGet(indexId, out var profileGroupItem);
if (profileGroupItem == null || profileGroupItem.NotHasChild()) if (profileGroupItem is null || profileGroupItem.NotHasChild())
{ {
return (new List<ProfileItem>(), profileGroupItem); return (new List<ProfileItem>(), profileGroupItem);
} }
@ -240,7 +240,7 @@ public class ProfileGroupItemManager
public static async Task<List<ProfileItem>> GetChildProfileItems(ProfileGroupItem? group) public static async Task<List<ProfileItem>> GetChildProfileItems(ProfileGroupItem? group)
{ {
if (group == null || group.ChildItems.IsNullOrEmpty()) if (group is null || group.ChildItems.IsNullOrEmpty())
{ {
return new(); return new();
} }
@ -250,7 +250,7 @@ public class ProfileGroupItemManager
.Select(AppManager.Instance.GetProfileItem) .Select(AppManager.Instance.GetProfileItem)
)) ))
.Where(p => .Where(p =>
p != null && p is not null &&
p.IsValid() && p.IsValid() &&
p.ConfigType != EConfigType.Custom p.ConfigType != EConfigType.Custom
) )
@ -260,14 +260,14 @@ public class ProfileGroupItemManager
public static async Task<List<ProfileItem>> GetSubChildProfileItems(ProfileGroupItem? group) public static async Task<List<ProfileItem>> GetSubChildProfileItems(ProfileGroupItem? group)
{ {
if (group == null || group.SubChildItems.IsNullOrEmpty()) if (group is null || group.SubChildItems.IsNullOrEmpty())
{ {
return new(); return new();
} }
var childProfiles = await AppManager.Instance.ProfileItems(group.SubChildItems); var childProfiles = await AppManager.Instance.ProfileItems(group.SubChildItems);
return childProfiles.Where(p => return childProfiles.Where(p =>
p != null && p is not null &&
p.IsValid() && p.IsValid() &&
!p.ConfigType.IsComplexType() && !p.ConfigType.IsComplexType() &&
(group.Filter.IsNullOrEmpty() || Regex.IsMatch(p.Remarks, group.Filter)) (group.Filter.IsNullOrEmpty() || Regex.IsMatch(p.Remarks, group.Filter))
@ -279,7 +279,7 @@ public class ProfileGroupItemManager
{ {
// include grand children // include grand children
var childAddresses = new HashSet<string>(); var childAddresses = new HashSet<string>();
if (!Instance.TryGet(indexId, out var groupItem) || groupItem == null) if (!Instance.TryGet(indexId, out var groupItem) || groupItem is null)
{ {
return childAddresses; return childAddresses;
} }
@ -295,7 +295,7 @@ public class ProfileGroupItemManager
foreach (var childId in childIds) foreach (var childId in childIds)
{ {
var childNode = await AppManager.Instance.GetProfileItem(childId); var childNode = await AppManager.Instance.GetProfileItem(childId);
if (childNode == null) if (childNode is null)
{ {
continue; continue;
} }
@ -321,7 +321,7 @@ public class ProfileGroupItemManager
{ {
// include grand children // include grand children
var childAddresses = new HashSet<string>(); var childAddresses = new HashSet<string>();
if (!Instance.TryGet(indexId, out var groupItem) || groupItem == null) if (!Instance.TryGet(indexId, out var groupItem) || groupItem is null)
{ {
return childAddresses; return childAddresses;
} }
@ -335,7 +335,7 @@ public class ProfileGroupItemManager
{ {
continue; continue;
} }
if (childNode.StreamSecurity == Global.StreamSecurity if (childNode.StreamSecurity == AppConfig.StreamSecurity
&& childNode.EchConfigList?.Contains("://") == true) && childNode.EchConfigList?.Contains("://") == true)
{ {
var idx = childNode.EchConfigList.IndexOf('+'); var idx = childNode.EchConfigList.IndexOf('+');
@ -353,14 +353,14 @@ public class ProfileGroupItemManager
foreach (var childId in childIds) foreach (var childId in childIds)
{ {
var childNode = await AppManager.Instance.GetProfileItem(childId); var childNode = await AppManager.Instance.GetProfileItem(childId);
if (childNode == null) if (childNode is null)
{ {
continue; continue;
} }
if (!childNode.IsComplex() && !childNode.EchConfigList.IsNullOrEmpty()) if (!childNode.IsComplex() && !childNode.EchConfigList.IsNullOrEmpty())
{ {
if (childNode.StreamSecurity == Global.StreamSecurity if (childNode.StreamSecurity == AppConfig.StreamSecurity
&& childNode.EchConfigList?.Contains("://") == true) && childNode.EchConfigList?.Contains("://") == true)
{ {
var idx = childNode.EchConfigList.IndexOf('+'); var idx = childNode.EchConfigList.IndexOf('+');

View file

@ -7,13 +7,12 @@ public class StatisticsManager
private Config _config; private Config _config;
private ServerStatItem? _serverStatItem; private ServerStatItem? _serverStatItem;
private List<ServerStatItem> _lstServerStat;
private Func<ServerSpeedItem, Task>? _updateFunc; private Func<ServerSpeedItem, Task>? _updateFunc;
private StatisticsXrayService? _statisticsXray; private StatisticsXrayService? _statisticsXray;
private StatisticsSingboxService? _statisticsSingbox; private StatisticsSingboxService? _statisticsSingbox;
private static readonly string _tag = "StatisticsHandler"; private static readonly string _tag = "StatisticsHandler";
public List<ServerStatItem> ServerStat => _lstServerStat; public List<ServerStatItem> ServerStat { get; private set; }
public async Task Init(Config config, Func<ServerSpeedItem, Task> updateFunc) public async Task Init(Config config, Func<ServerSpeedItem, Task> updateFunc)
{ {
@ -45,16 +44,16 @@ public class StatisticsManager
{ {
await SQLiteHelper.Instance.ExecuteAsync($"delete from ServerStatItem "); await SQLiteHelper.Instance.ExecuteAsync($"delete from ServerStatItem ");
_serverStatItem = null; _serverStatItem = null;
_lstServerStat = new(); ServerStat = new();
} }
public async Task SaveTo() public async Task SaveTo()
{ {
try try
{ {
if (_lstServerStat != null) if (ServerStat is not null)
{ {
await SQLiteHelper.Instance.UpdateAllAsync(_lstServerStat); await SQLiteHelper.Instance.UpdateAllAsync(ServerStat);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -65,7 +64,7 @@ public class StatisticsManager
public async Task CloneServerStatItem(string indexId, string toIndexId) public async Task CloneServerStatItem(string indexId, string toIndexId)
{ {
if (_lstServerStat == null) if (ServerStat is null)
{ {
return; return;
} }
@ -75,8 +74,8 @@ public class StatisticsManager
return; return;
} }
var stat = _lstServerStat.FirstOrDefault(t => t.IndexId == indexId); var stat = ServerStat.FirstOrDefault(t => t.IndexId == indexId);
if (stat == null) if (stat is null)
{ {
return; return;
} }
@ -84,7 +83,7 @@ public class StatisticsManager
var toStat = JsonUtils.DeepCopy(stat); var toStat = JsonUtils.DeepCopy(stat);
toStat.IndexId = toIndexId; toStat.IndexId = toIndexId;
await SQLiteHelper.Instance.ReplaceAsync(toStat); await SQLiteHelper.Instance.ReplaceAsync(toStat);
_lstServerStat.Add(toStat); ServerStat.Add(toStat);
} }
private async Task InitData() private async Task InitData()
@ -94,7 +93,7 @@ public class StatisticsManager
var ticks = DateTime.Now.Date.Ticks; var ticks = DateTime.Now.Date.Ticks;
await SQLiteHelper.Instance.ExecuteAsync($"update ServerStatItem set todayUp = 0,todayDown=0,dateNow={ticks} where dateNow<>{ticks}"); await SQLiteHelper.Instance.ExecuteAsync($"update ServerStatItem set todayUp = 0,todayDown=0,dateNow={ticks} where dateNow<>{ticks}");
_lstServerStat = await SQLiteHelper.Instance.TableAsync<ServerStatItem>().ToListAsync(); ServerStat = await SQLiteHelper.Instance.TableAsync<ServerStatItem>().ToListAsync();
} }
private async Task UpdateServerStatHandler(ServerSpeedItem server) private async Task UpdateServerStatHandler(ServerSpeedItem server)
@ -129,15 +128,15 @@ public class StatisticsManager
private async Task GetServerStatItem(string indexId) private async Task GetServerStatItem(string indexId)
{ {
var ticks = DateTime.Now.Date.Ticks; var ticks = DateTime.Now.Date.Ticks;
if (_serverStatItem != null && _serverStatItem.IndexId != indexId) if (_serverStatItem is not null && _serverStatItem.IndexId != indexId)
{ {
_serverStatItem = null; _serverStatItem = null;
} }
if (_serverStatItem == null) if (_serverStatItem is null)
{ {
_serverStatItem = _lstServerStat.FirstOrDefault(t => t.IndexId == indexId); _serverStatItem = ServerStat.FirstOrDefault(t => t.IndexId == indexId);
if (_serverStatItem == null) if (_serverStatItem is null)
{ {
_serverStatItem = new ServerStatItem _serverStatItem = new ServerStatItem
{ {
@ -149,7 +148,7 @@ public class StatisticsManager
DateNow = ticks DateNow = ticks
}; };
await SQLiteHelper.Instance.ReplaceAsync(_serverStatItem); await SQLiteHelper.Instance.ReplaceAsync(_serverStatItem);
_lstServerStat.Add(_serverStatItem); ServerStat.Add(_serverStatItem);
} }
} }

View file

@ -10,7 +10,7 @@ public sealed class WebDavManager
private readonly Config? _config; private readonly Config? _config;
private WebDavClient? _client; private WebDavClient? _client;
private string? _lastDescription; private string? _lastDescription;
private string _webDir = Global.AppName + "_backup"; private string _webDir = AppConfig.AppName + "_backup";
private readonly string _webFileName = "backup.zip"; private readonly string _webFileName = "backup.zip";
private readonly string _tag = "WebDav--"; private readonly string _tag = "WebDav--";
@ -29,18 +29,18 @@ public sealed class WebDavManager
{ {
throw new ArgumentException("webdav parameter error or null"); throw new ArgumentException("webdav parameter error or null");
} }
if (_client != null) if (_client is not null)
{ {
_client?.Dispose(); _client?.Dispose();
_client = null; _client = null;
} }
if (_config.WebDavItem.DirName.IsNullOrEmpty()) if (_config.WebDavItem.DirName.IsNullOrEmpty())
{ {
_webDir = Global.AppName + "_backup"; _webDir = AppConfig.AppName + "_backup";
} }
else else
{ {
_webDir = _config.WebDavItem.DirName.TrimEx(); _webDir = _config.WebDavItem.DirName.TrimSafe();
} }
// Ensure BaseAddress URL ends with a trailing slash // Ensure BaseAddress URL ends with a trailing slash

View file

@ -72,7 +72,7 @@ public class GUIItem
public bool KeepOlderDedupl { get; set; } public bool KeepOlderDedupl { get; set; }
public int AutoUpdateInterval { get; set; } public int AutoUpdateInterval { get; set; }
public int TrayMenuServersLimit { get; set; } = 20; public int TrayMenuServersLimit { get; set; } = 20;
public bool EnableHWA { get; set; } = false; public bool EnableHWA { get; set; }
public bool EnableLog { get; set; } = true; public bool EnableLog { get; set; } = true;
} }
@ -99,7 +99,7 @@ public class UIItem
public bool EnableDragDropSort { get; set; } public bool EnableDragDropSort { get; set; }
public bool DoubleClick2Activate { get; set; } public bool DoubleClick2Activate { get; set; }
public bool AutoHideStartup { get; set; } public bool AutoHideStartup { get; set; }
public bool Hide2TrayWhenClose { get; set; } public bool Hide2TrayWhenClose { get; set; }
public bool MacOSShowInDock { get; set; } public bool MacOSShowInDock { get; set; }
public List<ColumnItem> MainColumnItem { get; set; } public List<ColumnItem> MainColumnItem { get; set; }
public List<WindowSizeItem> WindowSizeItem { get; set; } public List<WindowSizeItem> WindowSizeItem { get; set; }

View file

@ -28,10 +28,10 @@ public class ProfileItem : ReactiveObject
public string GetSummary() public string GetSummary()
{ {
var summary = $"[{ConfigType.ToString()}] "; var summary = $"[{ConfigType}] ";
if (IsComplex()) if (IsComplex())
{ {
summary += $"[{CoreType.ToString()}]{Remarks}"; summary += $"[{CoreType}]{Remarks}";
} }
else else
{ {
@ -54,11 +54,11 @@ public class ProfileItem : ReactiveObject
public string GetNetwork() 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() public bool IsComplex()
@ -94,7 +94,7 @@ public class ProfileItem : ReactiveObject
return false; return false;
} }
if (!Global.Flows.Contains(Flow)) if (!AppConfig.Flows.Contains(Flow))
{ {
return false; return false;
} }
@ -107,7 +107,7 @@ public class ProfileItem : ReactiveObject
return false; return false;
} }
if (string.IsNullOrEmpty(Security) || !Global.SsSecuritiesInSingbox.Contains(Security)) if (string.IsNullOrEmpty(Security) || !AppConfig.SsSecuritiesInSingbox.Contains(Security))
{ {
return false; return false;
} }
@ -116,7 +116,7 @@ public class ProfileItem : ReactiveObject
} }
if ((ConfigType is EConfigType.VLESS or EConfigType.Trojan) if ((ConfigType is EConfigType.VLESS or EConfigType.Trojan)
&& StreamSecurity == Global.StreamSecurityReality && StreamSecurity == AppConfig.StreamSecurityReality
&& PublicKey.IsNullOrEmpty()) && PublicKey.IsNullOrEmpty())
{ {
return false; return false;

View file

@ -82,7 +82,7 @@ public class SemanticVersion
public string ToVersionString(string? prefix = null) public string ToVersionString(string? prefix = null)
{ {
if (prefix == null) if (prefix is null)
{ {
return version; return version;
} }

View file

@ -128,7 +128,7 @@ public class Outboundsettings4Ray
public string? secretKey { get; set; } public string? secretKey { get; set; }
public Object? address { get; set; } public object? address { get; set; }
public int? port { get; set; } public int? port { get; set; }
public List<WireguardPeer4Ray>? peers { get; set; } public List<WireguardPeer4Ray>? peers { get; set; }

View file

@ -2,6 +2,8 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<NeutralLanguage>en-US</NeutralLanguage>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View file

@ -3,20 +3,15 @@ namespace ServiceLib.Services.CoreConfig;
/// <summary> /// <summary>
/// Core configuration file processing class /// Core configuration file processing class
/// </summary> /// </summary>
public class CoreConfigClashService public class CoreConfigClashService(Config config)
{ {
private Config _config; private readonly Config _config = config;
private static readonly string _tag = "CoreConfigClashService"; private static readonly string _tag = "CoreConfigClashService";
public CoreConfigClashService(Config config)
{
_config = config;
}
public async Task<RetResult> GenerateClientCustomConfig(ProfileItem node, string? fileName) public async Task<RetResult> GenerateClientCustomConfig(ProfileItem node, string? fileName)
{ {
var ret = new RetResult(); var ret = new RetResult();
if (node == null || fileName is null) if (node is null || fileName is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -26,7 +21,7 @@ public class CoreConfigClashService
try try
{ {
if (node == null) if (node is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -66,7 +61,7 @@ public class CoreConfigClashService
} }
var fileContent = YamlUtils.FromYaml<Dictionary<string, object>>(txtFile); var fileContent = YamlUtils.FromYaml<Dictionary<string, object>>(txtFile);
if (fileContent == null) if (fileContent is null)
{ {
ret.Msg = ResUI.FailedConversionConfiguration; ret.Msg = ResUI.FailedConversionConfiguration;
return ret; return ret;
@ -78,7 +73,7 @@ public class CoreConfigClashService
fileContent["log-level"] = GetLogLevel(_config.CoreBasicItem.Loglevel); fileContent["log-level"] = GetLogLevel(_config.CoreBasicItem.Loglevel);
//external-controller //external-controller
fileContent["external-controller"] = $"{Global.Loopback}:{AppManager.Instance.StatePort2}"; fileContent["external-controller"] = $"{AppConfig.Loopback}:{AppManager.Instance.StatePort2}";
fileContent.Remove("secret"); fileContent.Remove("secret");
//allow-lan //allow-lan
if (_config.Inbound.First().AllowLANConn) if (_config.Inbound.First().AllowLANConn)
@ -110,11 +105,11 @@ public class CoreConfigClashService
//enable tun mode //enable tun mode
if (_config.TunModeItem.EnableTun) if (_config.TunModeItem.EnableTun)
{ {
var tun = EmbedUtils.GetEmbedText(Global.ClashTunYaml); var tun = EmbedUtils.GetEmbedText(AppConfig.ClashTunYaml);
if (tun.IsNotEmpty()) if (tun.IsNotEmpty())
{ {
var tunContent = YamlUtils.FromYaml<Dictionary<string, object>>(tun); var tunContent = YamlUtils.FromYaml<Dictionary<string, object>>(tun);
if (tunContent != null) if (tunContent is not null)
{ {
fileContent["tun"] = tunContent["tun"]; fileContent["tun"] = tunContent["tun"];
} }
@ -161,17 +156,17 @@ public class CoreConfigClashService
return; return;
} }
var path = Utils.GetConfigPath(Global.ClashMixinConfigFileName); var path = Utils.GetConfigPath(AppConfig.ClashMixinConfigFileName);
if (!File.Exists(path)) if (!File.Exists(path))
{ {
var mixin = EmbedUtils.GetEmbedText(Global.ClashMixinYaml); var mixin = EmbedUtils.GetEmbedText(AppConfig.ClashMixinYaml);
await File.AppendAllTextAsync(path, mixin); 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<Dictionary<string, object>>(txtFile); var mixinContent = YamlUtils.FromYaml<Dictionary<string, object>>(txtFile);
if (mixinContent == null) if (mixinContent is null)
{ {
return; return;
} }

View file

@ -12,7 +12,7 @@ public partial class CoreConfigSingboxService(Config config)
var ret = new RetResult(); var ret = new RetResult();
try try
{ {
if (node == null if (node is null
|| !node.IsValid()) || !node.IsValid())
{ {
ret.Msg = ResUI.CheckServerSettings; 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()) if (result.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -46,7 +46,7 @@ public partial class CoreConfigSingboxService(Config config)
} }
var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result); var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result);
if (singboxConfig == null) if (singboxConfig is null)
{ {
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
@ -61,7 +61,7 @@ public partial class CoreConfigSingboxService(Config config)
singboxConfig.outbounds.RemoveAt(0); singboxConfig.outbounds.RemoveAt(0);
var endpoints = new Endpoints4Sbox(); var endpoints = new Endpoints4Sbox();
await GenEndpoint(node, endpoints); await GenEndpoint(node, endpoints);
endpoints.tag = Global.ProxyTag; endpoints.tag = AppConfig.ProxyTag;
singboxConfig.endpoints = new() { endpoints }; singboxConfig.endpoints = new() { endpoints };
} }
else else
@ -98,7 +98,7 @@ public partial class CoreConfigSingboxService(Config config)
var ret = new RetResult(); var ret = new RetResult();
try try
{ {
if (_config == null) if (_config is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -106,8 +106,8 @@ public partial class CoreConfigSingboxService(Config config)
ret.Msg = ResUI.InitialConfiguration; ret.Msg = ResUI.InitialConfiguration;
var result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient); var result = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleClient);
var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty()) if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -115,7 +115,7 @@ public partial class CoreConfigSingboxService(Config config)
} }
var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result); var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result);
if (singboxConfig == null) if (singboxConfig is null)
{ {
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
@ -142,7 +142,7 @@ public partial class CoreConfigSingboxService(Config config)
foreach (var it in selecteds) foreach (var it in selecteds)
{ {
if (!Global.SingboxSupportConfigType.Contains(it.ConfigType)) if (!AppConfig.SingboxSupportConfigType.Contains(it.ConfigType))
{ {
continue; continue;
} }
@ -158,7 +158,7 @@ public partial class CoreConfigSingboxService(Config config)
//find unused port //find unused port
var port = initPort; 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) if (lstIpEndPoints?.FindIndex(_it => _it.Port == k) >= 0)
{ {
@ -185,7 +185,7 @@ public partial class CoreConfigSingboxService(Config config)
//inbound //inbound
Inbound4Sbox inbound = new() Inbound4Sbox inbound = new()
{ {
listen = Global.Loopback, listen = AppConfig.Loopback,
listen_port = port, listen_port = port,
type = EInboundProtocol.mixed.ToString(), type = EInboundProtocol.mixed.ToString(),
}; };
@ -199,7 +199,7 @@ public partial class CoreConfigSingboxService(Config config)
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
} }
var tag = Global.ProxyTag + inbound.listen_port.ToString(); var tag = AppConfig.ProxyTag + inbound.listen_port.ToString();
server.tag = tag; server.tag = tag;
if (server is Endpoints4Sbox endpoint) if (server is Endpoints4Sbox endpoint)
{ {
@ -221,7 +221,7 @@ public partial class CoreConfigSingboxService(Config config)
} }
var rawDNSItem = await AppManager.Instance.GetDNSItem(ECoreType.sing_box); 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); await GenDnsDomainsCompatible(singboxConfig, rawDNSItem);
} }
@ -231,7 +231,7 @@ public partial class CoreConfigSingboxService(Config config)
} }
singboxConfig.route.default_domain_resolver = new() singboxConfig.route.default_domain_resolver = new()
{ {
server = Global.SingboxLocalDNSTag, server = AppConfig.SingboxLocalDNSTag,
}; };
ret.Success = true; ret.Success = true;
@ -251,7 +251,7 @@ public partial class CoreConfigSingboxService(Config config)
var ret = new RetResult(); var ret = new RetResult();
try try
{ {
if (node == null if (node is null
|| !node.IsValid()) || !node.IsValid())
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
@ -265,7 +265,7 @@ public partial class CoreConfigSingboxService(Config config)
ret.Msg = ResUI.InitialConfiguration; ret.Msg = ResUI.InitialConfiguration;
var result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient); var result = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleClient);
if (result.IsNullOrEmpty()) if (result.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -273,7 +273,7 @@ public partial class CoreConfigSingboxService(Config config)
} }
var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result); var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result);
if (singboxConfig == null) if (singboxConfig is null)
{ {
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
@ -285,7 +285,7 @@ public partial class CoreConfigSingboxService(Config config)
singboxConfig.outbounds.RemoveAt(0); singboxConfig.outbounds.RemoveAt(0);
var endpoints = new Endpoints4Sbox(); var endpoints = new Endpoints4Sbox();
await GenEndpoint(node, endpoints); await GenEndpoint(node, endpoints);
endpoints.tag = Global.ProxyTag; endpoints.tag = AppConfig.ProxyTag;
singboxConfig.endpoints = new() { endpoints }; singboxConfig.endpoints = new() { endpoints };
} }
else else
@ -294,7 +294,7 @@ public partial class CoreConfigSingboxService(Config config)
} }
await GenMoreOutbounds(node, singboxConfig); await GenMoreOutbounds(node, singboxConfig);
var item = await AppManager.Instance.GetDNSItem(ECoreType.sing_box); 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); await GenDnsDomainsCompatible(singboxConfig, item);
} }
@ -304,7 +304,7 @@ public partial class CoreConfigSingboxService(Config config)
} }
singboxConfig.route.default_domain_resolver = new() singboxConfig.route.default_domain_resolver = new()
{ {
server = Global.SingboxLocalDNSTag, server = AppConfig.SingboxLocalDNSTag,
}; };
singboxConfig.route.rules.Clear(); singboxConfig.route.rules.Clear();
@ -312,7 +312,7 @@ public partial class CoreConfigSingboxService(Config config)
singboxConfig.inbounds.Add(new() singboxConfig.inbounds.Add(new()
{ {
tag = $"{EInboundProtocol.mixed}{port}", tag = $"{EInboundProtocol.mixed}{port}",
listen = Global.Loopback, listen = AppConfig.Loopback,
listen_port = port, listen_port = port,
type = EInboundProtocol.mixed.ToString(), type = EInboundProtocol.mixed.ToString(),
}); });
@ -335,7 +335,7 @@ public partial class CoreConfigSingboxService(Config config)
var ret = new RetResult(); var ret = new RetResult();
try try
{ {
if (_config == null) if (_config is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -343,8 +343,8 @@ public partial class CoreConfigSingboxService(Config config)
ret.Msg = ResUI.InitialConfiguration; ret.Msg = ResUI.InitialConfiguration;
var result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient); var result = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleClient);
var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty()) if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -352,7 +352,7 @@ public partial class CoreConfigSingboxService(Config config)
} }
var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result); var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result);
if (singboxConfig == null) if (singboxConfig is null)
{ {
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
@ -392,7 +392,7 @@ public partial class CoreConfigSingboxService(Config config)
var ret = new RetResult(); var ret = new RetResult();
try try
{ {
if (_config == null) if (_config is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -400,8 +400,8 @@ public partial class CoreConfigSingboxService(Config config)
ret.Msg = ResUI.InitialConfiguration; ret.Msg = ResUI.InitialConfiguration;
var result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient); var result = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleClient);
var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty()) if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -409,7 +409,7 @@ public partial class CoreConfigSingboxService(Config config)
} }
var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result); var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result);
if (singboxConfig == null) if (singboxConfig is null)
{ {
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
@ -447,7 +447,7 @@ public partial class CoreConfigSingboxService(Config config)
public async Task<RetResult> GenerateClientCustomConfig(ProfileItem node, string? fileName) public async Task<RetResult> GenerateClientCustomConfig(ProfileItem node, string? fileName)
{ {
var ret = new RetResult(); var ret = new RetResult();
if (node == null || fileName is null) if (node is null || fileName is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -457,7 +457,7 @@ public partial class CoreConfigSingboxService(Config config)
try try
{ {
if (node == null) if (node is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -484,11 +484,11 @@ public partial class CoreConfigSingboxService(Config config)
return ret; return ret;
} }
if (node.Address == Global.CoreMultipleLoadConfigFileName) if (node.Address == AppConfig.CoreMultipleLoadConfigFileName)
{ {
var txtFile = File.ReadAllText(addressFileName); var txtFile = File.ReadAllText(addressFileName);
var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(txtFile); var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(txtFile);
if (singboxConfig == null) if (singboxConfig is null)
{ {
File.Copy(addressFileName, fileName); File.Copy(addressFileName, fileName);
} }

View file

@ -5,7 +5,7 @@ public partial class CoreConfigSingboxService
private async Task<string> ApplyFullConfigTemplate(SingboxConfig singboxConfig) private async Task<string> ApplyFullConfigTemplate(SingboxConfig singboxConfig)
{ {
var fullConfigTemplate = await AppManager.Instance.GetFullConfigTemplateItem(ECoreType.sing_box); var fullConfigTemplate = await AppManager.Instance.GetFullConfigTemplateItem(ECoreType.sing_box);
if (fullConfigTemplate == null || !fullConfigTemplate.Enabled) if (fullConfigTemplate is null || !fullConfigTemplate.Enabled)
{ {
return JsonUtils.Serialize(singboxConfig); return JsonUtils.Serialize(singboxConfig);
} }
@ -17,7 +17,7 @@ public partial class CoreConfigSingboxService
} }
var fullConfigTemplateNode = JsonNode.Parse(fullConfigTemplateItem); var fullConfigTemplateNode = JsonNode.Parse(fullConfigTemplateItem);
if (fullConfigTemplateNode == null) if (fullConfigTemplateNode is null)
{ {
return JsonUtils.Serialize(singboxConfig); return JsonUtils.Serialize(singboxConfig);
} }
@ -42,7 +42,7 @@ public partial class CoreConfigSingboxService
fullConfigTemplateNode["outbounds"] = customOutboundsNode; fullConfigTemplateNode["outbounds"] = customOutboundsNode;
// Process endpoints // 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(); var customEndpointsNode = fullConfigTemplateNode["endpoints"] is JsonArray endpoints ? endpoints : new JsonArray();
foreach (var endpoint in singboxConfig.endpoints) foreach (var endpoint in singboxConfig.endpoints)

View file

@ -7,7 +7,7 @@ public partial class CoreConfigSingboxService
try try
{ {
var item = await AppManager.Instance.GetDNSItem(ECoreType.sing_box); 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); return await GenDnsCompatible(node, singboxConfig);
} }
@ -22,22 +22,22 @@ public partial class CoreConfigSingboxService
// final dns // final dns
var routing = await ConfigHandler.GetDefaultRouting(_config); var routing = await ConfigHandler.GetDefaultRouting(_config);
var useDirectDns = false; var useDirectDns = false;
if (routing != null) if (routing is not null)
{ {
var rules = JsonUtils.Deserialize<List<RulesItem>>(routing.RuleSet) ?? []; var rules = JsonUtils.Deserialize<List<RulesItem>>(routing.RuleSet) ?? [];
useDirectDns = rules?.LastOrDefault() is { } lastRule && useDirectDns = rules?.LastOrDefault() is { } lastRule &&
lastRule.OutboundTag == Global.DirectTag && lastRule.OutboundTag == AppConfig.DirectTag &&
(lastRule.Port == "0-65535" || (lastRule.Port == "0-65535" ||
lastRule.Network == "tcp,udp" || lastRule.Network == "tcp,udp" ||
lastRule.Ip?.Contains("0.0.0.0/0") == true); 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) if ((!useDirectDns) && simpleDNSItem.FakeIP == true && simpleDNSItem.GlobalFakeIp == false)
{ {
singboxConfig.dns.rules.Add(new() singboxConfig.dns.rules.Add(new()
{ {
server = Global.SingboxFakeDNSTag, server = AppConfig.SingboxFakeDNSTag,
query_type = new List<int> { 1, 28 }, // A and AAAA query_type = new List<int> { 1, 28 }, // A and AAAA
rewrite_ttl = 1, rewrite_ttl = 1,
}); });
@ -57,29 +57,29 @@ public partial class CoreConfigSingboxService
var finalDns = await GenDnsDomains(singboxConfig, simpleDNSItem); var finalDns = await GenDnsDomains(singboxConfig, simpleDNSItem);
var directDns = ParseDnsAddress(simpleDNSItem.DirectDNS); var directDns = ParseDnsAddress(simpleDNSItem.DirectDNS);
directDns.tag = Global.SingboxDirectDNSTag; directDns.tag = AppConfig.SingboxDirectDNSTag;
directDns.domain_resolver = Global.SingboxLocalDNSTag; directDns.domain_resolver = AppConfig.SingboxLocalDNSTag;
var remoteDns = ParseDnsAddress(simpleDNSItem.RemoteDNS); var remoteDns = ParseDnsAddress(simpleDNSItem.RemoteDNS);
remoteDns.tag = Global.SingboxRemoteDNSTag; remoteDns.tag = AppConfig.SingboxRemoteDNSTag;
remoteDns.detour = Global.ProxyTag; remoteDns.detour = AppConfig.ProxyTag;
remoteDns.domain_resolver = Global.SingboxLocalDNSTag; remoteDns.domain_resolver = AppConfig.SingboxLocalDNSTag;
var hostsDns = new Server4Sbox var hostsDns = new Server4Sbox
{ {
tag = Global.SingboxHostsDNSTag, tag = AppConfig.SingboxHostsDNSTag,
type = "hosts", type = "hosts",
predefined = new(), predefined = new(),
}; };
if (simpleDNSItem.AddCommonHosts == true) if (simpleDNSItem.AddCommonHosts == true)
{ {
hostsDns.predefined = Global.PredefinedHosts; hostsDns.predefined = AppConfig.PredefinedHosts;
} }
if (simpleDNSItem.UseSystemHosts == true) if (simpleDNSItem.UseSystemHosts == true)
{ {
var systemHosts = Utils.GetSystemHosts(); var systemHosts = Utils.GetSystemHosts();
if (systemHosts != null && systemHosts.Count > 0) if (systemHosts is not null && systemHosts.Count > 0)
{ {
foreach (var host in systemHosts) foreach (var host in systemHosts)
{ {
@ -102,15 +102,15 @@ public partial class CoreConfigSingboxService
{ {
if (finalDns.server == host.Key) if (finalDns.server == host.Key)
{ {
finalDns.domain_resolver = Global.SingboxHostsDNSTag; finalDns.domain_resolver = AppConfig.SingboxHostsDNSTag;
} }
if (remoteDns.server == host.Key) if (remoteDns.server == host.Key)
{ {
remoteDns.domain_resolver = Global.SingboxHostsDNSTag; remoteDns.domain_resolver = AppConfig.SingboxHostsDNSTag;
} }
if (directDns.server == host.Key) 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 var fakeip = new Server4Sbox
{ {
tag = Global.SingboxFakeDNSTag, tag = AppConfig.SingboxFakeDNSTag,
type = "fakeip", type = "fakeip",
inet4_range = "198.18.0.0/15", inet4_range = "198.18.0.0/15",
inet6_range = "fc00::/18", inet6_range = "fc00::/18",
@ -137,22 +137,22 @@ public partial class CoreConfigSingboxService
var (_, dnsServer) = ParseEchParam(node?.EchConfigList); var (_, dnsServer) = ParseEchParam(node?.EchConfigList);
if (dnsServer is not null) if (dnsServer is not null)
{ {
dnsServer.tag = Global.SingboxEchDNSTag; dnsServer.tag = AppConfig.SingboxEchDNSTag;
if (dnsServer.server is not null if (dnsServer.server is not null
&& hostsDns.predefined.ContainsKey(dnsServer.server)) && hostsDns.predefined.ContainsKey(dnsServer.server))
{ {
dnsServer.domain_resolver = Global.SingboxHostsDNSTag; dnsServer.domain_resolver = AppConfig.SingboxHostsDNSTag;
} }
else else
{ {
dnsServer.domain_resolver = Global.SingboxLocalDNSTag; dnsServer.domain_resolver = AppConfig.SingboxLocalDNSTag;
} }
singboxConfig.dns.servers.Add(dnsServer); singboxConfig.dns.servers.Add(dnsServer);
} }
else if (node?.ConfigType.IsGroupType() == true) else if (node?.ConfigType.IsGroupType() == true)
{ {
var echDnsObject = JsonUtils.DeepCopy(directDns); var echDnsObject = JsonUtils.DeepCopy(directDns);
echDnsObject.tag = Global.SingboxEchDNSTag; echDnsObject.tag = AppConfig.SingboxEchDNSTag;
singboxConfig.dns.servers.Add(echDnsObject); singboxConfig.dns.servers.Add(echDnsObject);
} }
@ -162,7 +162,7 @@ public partial class CoreConfigSingboxService
private async Task<Server4Sbox> GenDnsDomains(SingboxConfig singboxConfig, SimpleDNSItem? simpleDNSItem) private async Task<Server4Sbox> GenDnsDomains(SingboxConfig singboxConfig, SimpleDNSItem? simpleDNSItem)
{ {
var finalDns = ParseDnsAddress(simpleDNSItem.BootstrapDNS); var finalDns = ParseDnsAddress(simpleDNSItem.BootstrapDNS);
finalDns.tag = Global.SingboxLocalDNSTag; finalDns.tag = AppConfig.SingboxLocalDNSTag;
singboxConfig.dns ??= new Dns4Sbox(); singboxConfig.dns ??= new Dns4Sbox();
singboxConfig.dns.servers ??= new List<Server4Sbox>(); singboxConfig.dns.servers ??= new List<Server4Sbox>();
singboxConfig.dns.servers.Add(finalDns); singboxConfig.dns.servers.Add(finalDns);
@ -176,16 +176,16 @@ public partial class CoreConfigSingboxService
singboxConfig.dns.rules.AddRange(new[] 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 new Rule4Sbox
{ {
server = Global.SingboxRemoteDNSTag, server = AppConfig.SingboxRemoteDNSTag,
strategy = simpleDNSItem.SingboxStrategy4Proxy.NullIfEmpty(), strategy = simpleDNSItem.SingboxStrategy4Proxy.NullIfEmpty(),
clash_mode = ERuleMode.Global.ToString() clash_mode = ERuleMode.Global.ToString()
}, },
new Rule4Sbox new Rule4Sbox
{ {
server = Global.SingboxDirectDNSTag, server = AppConfig.SingboxDirectDNSTag,
strategy = simpleDNSItem.SingboxStrategy4Direct.NullIfEmpty(), strategy = simpleDNSItem.SingboxStrategy4Direct.NullIfEmpty(),
clash_mode = ERuleMode.Direct.ToString() clash_mode = ERuleMode.Direct.ToString()
} }
@ -198,7 +198,7 @@ public partial class CoreConfigSingboxService
singboxConfig.dns.rules.Add(new() singboxConfig.dns.rules.Add(new()
{ {
query_type = new List<int> { 64, 65 }, query_type = new List<int> { 64, 65 },
server = Global.SingboxEchDNSTag, server = AppConfig.SingboxEchDNSTag,
domain = echDomain is not null ? new List<string> { echDomain } : null, domain = echDomain is not null ? new List<string> { echDomain } : null,
}); });
} }
@ -210,7 +210,7 @@ public partial class CoreConfigSingboxService
singboxConfig.dns.rules.Add(new() singboxConfig.dns.rules.Add(new()
{ {
query_type = new List<int> { 64, 65 }, query_type = new List<int> { 64, 65 },
server = Global.SingboxEchDNSTag, server = AppConfig.SingboxEchDNSTag,
domain = queryServerNames, domain = queryServerNames,
}); });
} }
@ -228,11 +228,11 @@ public partial class CoreConfigSingboxService
if (simpleDNSItem.FakeIP == true && simpleDNSItem.GlobalFakeIp == true) if (simpleDNSItem.FakeIP == true && simpleDNSItem.GlobalFakeIp == true)
{ {
var fakeipFilterRule = JsonUtils.Deserialize<Rule4Sbox>(EmbedUtils.GetEmbedText(Global.SingboxFakeIPFilterFileName)); var fakeipFilterRule = JsonUtils.Deserialize<Rule4Sbox>(EmbedUtils.GetEmbedText(AppConfig.SingboxFakeIPFilterFileName));
fakeipFilterRule.invert = true; fakeipFilterRule.invert = true;
var rule4Fake = new Rule4Sbox var rule4Fake = new Rule4Sbox
{ {
server = Global.SingboxFakeDNSTag, server = AppConfig.SingboxFakeDNSTag,
type = "logical", type = "logical",
mode = "and", mode = "and",
rewrite_ttl = 1, rewrite_ttl = 1,
@ -249,7 +249,7 @@ public partial class CoreConfigSingboxService
} }
var routing = await ConfigHandler.GetDefaultRouting(_config); var routing = await ConfigHandler.GetDefaultRouting(_config);
if (routing == null) if (routing is null)
{ {
return 0; return 0;
} }
@ -306,9 +306,9 @@ public partial class CoreConfigSingboxService
continue; 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; rule.strategy = string.IsNullOrEmpty(simpleDNSItem.SingboxStrategy4Direct) ? null : simpleDNSItem.SingboxStrategy4Direct;
if (expectedIPsRegions.Count > 0 && rule.geosite?.Count > 0) 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.action = "predefined";
rule.rcode = "NXDOMAIN"; rule.rcode = "NXDOMAIN";
@ -337,12 +337,12 @@ public partial class CoreConfigSingboxService
if (simpleDNSItem.FakeIP == true && simpleDNSItem.GlobalFakeIp == false) if (simpleDNSItem.FakeIP == true && simpleDNSItem.GlobalFakeIp == false)
{ {
var rule4Fake = JsonUtils.DeepCopy(rule); var rule4Fake = JsonUtils.DeepCopy(rule);
rule4Fake.server = Global.SingboxFakeDNSTag; rule4Fake.server = AppConfig.SingboxFakeDNSTag;
rule4Fake.query_type = new List<int> { 1, 28 }; // A and AAAA rule4Fake.query_type = new List<int> { 1, 28 }; // A and AAAA
rule4Fake.rewrite_ttl = 1; rule4Fake.rewrite_ttl = 1;
singboxConfig.dns.rules.Add(rule4Fake); singboxConfig.dns.rules.Add(rule4Fake);
} }
rule.server = Global.SingboxRemoteDNSTag; rule.server = AppConfig.SingboxRemoteDNSTag;
rule.strategy = string.IsNullOrEmpty(simpleDNSItem.SingboxStrategy4Proxy) ? null : simpleDNSItem.SingboxStrategy4Proxy; rule.strategy = string.IsNullOrEmpty(simpleDNSItem.SingboxStrategy4Proxy) ? null : simpleDNSItem.SingboxStrategy4Proxy;
} }
@ -360,11 +360,11 @@ public partial class CoreConfigSingboxService
var strDNS = string.Empty; var strDNS = string.Empty;
if (_config.TunModeItem.EnableTun) 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 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<Dns4Sbox>(strDNS); var dns4Sbox = JsonUtils.Deserialize<Dns4Sbox>(strDNS);
@ -374,7 +374,7 @@ public partial class CoreConfigSingboxService
} }
singboxConfig.dns = dns4Sbox; 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); await GenDnsDomainsCompatible(singboxConfig, item);
} }
@ -398,9 +398,9 @@ public partial class CoreConfigSingboxService
dns4Sbox.servers ??= []; dns4Sbox.servers ??= [];
dns4Sbox.rules ??= []; 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); var localDnsServer = ParseDnsAddress(finalDnsAddress);
localDnsServer.tag = tag; localDnsServer.tag = tag;
@ -417,12 +417,12 @@ public partial class CoreConfigSingboxService
dns4Sbox.servers ??= []; dns4Sbox.servers ??= [];
dns4Sbox.rules ??= []; dns4Sbox.rules ??= [];
var tag = Global.SingboxLocalDNSTag; var tag = AppConfig.SingboxLocalDNSTag;
dns4Sbox.servers.Add(new() dns4Sbox.servers.Add(new()
{ {
tag = tag, tag = tag,
address = string.IsNullOrEmpty(dnsItem?.DomainDNSAddress) ? Global.DomainPureIPDNSAddress.FirstOrDefault() : dnsItem?.DomainDNSAddress, address = string.IsNullOrEmpty(dnsItem?.DomainDNSAddress) ? AppConfig.DomainPureIPDNSAddress.FirstOrDefault() : dnsItem?.DomainDNSAddress,
detour = Global.DirectTag, detour = AppConfig.DirectTag,
strategy = string.IsNullOrEmpty(dnsItem?.DomainStrategy4Freedom) ? null : dnsItem?.DomainStrategy4Freedom, strategy = string.IsNullOrEmpty(dnsItem?.DomainStrategy4Freedom) ? null : dnsItem?.DomainStrategy4Freedom,
}); });
dns4Sbox.rules.Insert(0, new() dns4Sbox.rules.Insert(0, new()
@ -432,7 +432,7 @@ public partial class CoreConfigSingboxService
}); });
dns4Sbox.rules.Insert(0, new() 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() clash_mode = ERuleMode.Global.ToString()
}); });
@ -441,7 +441,7 @@ public partial class CoreConfigSingboxService
.Select(t => t.server) .Select(t => t.server)
.Distinct() .Distinct()
.ToList(); .ToList();
if (lstDomain != null && lstDomain.Count > 0) if (lstDomain is not null && lstDomain.Count > 0)
{ {
dns4Sbox.rules.Insert(0, new() dns4Sbox.rules.Insert(0, new()
{ {
@ -456,7 +456,7 @@ public partial class CoreConfigSingboxService
private async Task<int> GenOutboundDnsRule(ProfileItem? node, SingboxConfig singboxConfig) private async Task<int> GenOutboundDnsRule(ProfileItem? node, SingboxConfig singboxConfig)
{ {
if (node == null) if (node is null)
{ {
return 0; return 0;
} }
@ -466,7 +466,7 @@ public partial class CoreConfigSingboxService
{ {
domain.Add(node.Address); 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) domain.AddRange(Utils.String2List(node.SpiderX)
.Where(Utils.IsDomain) .Where(Utils.IsDomain)
@ -481,7 +481,7 @@ public partial class CoreConfigSingboxService
singboxConfig.dns.rules ??= new List<Rule4Sbox>(); singboxConfig.dns.rules ??= new List<Rule4Sbox>();
singboxConfig.dns.rules.Insert(0, new Rule4Sbox singboxConfig.dns.rules.Insert(0, new Rule4Sbox
{ {
server = Global.SingboxLocalDNSTag, server = AppConfig.SingboxLocalDNSTag,
domain = domain, domain = domain,
}); });

View file

@ -16,7 +16,7 @@ public partial class CoreConfigSingboxService
{ {
type = EInboundProtocol.mixed.ToString(), type = EInboundProtocol.mixed.ToString(),
tag = EInboundProtocol.socks.ToString(), tag = EInboundProtocol.socks.ToString(),
listen = Global.Loopback, listen = AppConfig.Loopback,
}; };
singboxConfig.inbounds.Add(inbound); singboxConfig.inbounds.Add(inbound);
@ -53,14 +53,14 @@ public partial class CoreConfigSingboxService
{ {
if (_config.TunModeItem.Mtu <= 0) if (_config.TunModeItem.Mtu <= 0)
{ {
_config.TunModeItem.Mtu = Global.TunMtus.First(); _config.TunModeItem.Mtu = AppConfig.TunMtus.First();
} }
if (_config.TunModeItem.Stack.IsNullOrEmpty()) if (_config.TunModeItem.Stack.IsNullOrEmpty())
{ {
_config.TunModeItem.Stack = Global.TunStacks.First(); _config.TunModeItem.Stack = AppConfig.TunStacks.First();
} }
var tunInbound = JsonUtils.Deserialize<Inbound4Sbox>(EmbedUtils.GetEmbedText(Global.TunSingboxInboundFileName)) ?? new Inbound4Sbox { }; var tunInbound = JsonUtils.Deserialize<Inbound4Sbox>(EmbedUtils.GetEmbedText(AppConfig.TunSingboxInboundFileName)) ?? new Inbound4Sbox { };
tunInbound.interface_name = Utils.IsMacOS() ? $"utun{new Random().Next(99)}" : "singbox_tun"; tunInbound.interface_name = Utils.IsMacOS() ? $"utun{new Random().Next(99)}" : "singbox_tun";
tunInbound.mtu = _config.TunModeItem.Mtu; tunInbound.mtu = _config.TunModeItem.Mtu;
tunInbound.auto_route = _config.TunModeItem.AutoRoute; tunInbound.auto_route = _config.TunModeItem.AutoRoute;

View file

@ -21,7 +21,7 @@ public partial class CoreConfigSingboxService
default: default:
break; break;
} }
if (_config.CoreBasicItem.Loglevel == Global.None) if (_config.CoreBasicItem.Loglevel == AppConfig.None)
{ {
singboxConfig.log.disabled = true; singboxConfig.log.disabled = true;
} }

View file

@ -8,7 +8,7 @@ public partial class CoreConfigSingboxService
{ {
outbound.server = node.Address; outbound.server = node.Address;
outbound.server_port = node.Port; outbound.server_port = node.Port;
outbound.type = Global.ProtocolTypes[node.ConfigType]; outbound.type = AppConfig.ProtocolTypes[node.ConfigType];
switch (node.ConfigType) switch (node.ConfigType)
{ {
@ -16,13 +16,13 @@ public partial class CoreConfigSingboxService
{ {
outbound.uuid = node.Id; outbound.uuid = node.Id;
outbound.alter_id = node.AlterId; outbound.alter_id = node.AlterId;
if (Global.VmessSecurities.Contains(node.Security)) if (AppConfig.VmessSecurities.Contains(node.Security))
{ {
outbound.security = node.Security; outbound.security = node.Security;
} }
else else
{ {
outbound.security = Global.DefaultSecurity; outbound.security = AppConfig.DefaultSecurity;
} }
await GenOutboundMux(node, outbound); await GenOutboundMux(node, outbound);
@ -31,10 +31,10 @@ public partial class CoreConfigSingboxService
} }
case EConfigType.Shadowsocks: 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; 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 = "obfs-local";
outbound.plugin_opts = $"obfs=http;obfs-host={node.RequestHost};"; outbound.plugin_opts = $"obfs=http;obfs-host={node.RequestHost};";
@ -55,7 +55,7 @@ public partial class CoreConfigSingboxService
{ {
pluginArgs += "mode=quic;"; pluginArgs += "mode=quic;";
} }
if (node.StreamSecurity == Global.StreamSecurity) if (node.StreamSecurity == AppConfig.StreamSecurity)
{ {
pluginArgs += "tls;"; pluginArgs += "tls;";
var certs = CertPemManager.ParsePemChain(node.Cert); var certs = CertPemManager.ParsePemChain(node.Cert);
@ -141,7 +141,7 @@ public partial class CoreConfigSingboxService
outbound.obfs = new() outbound.obfs = new()
{ {
type = "salamander", type = "salamander",
password = node.Path.TrimEx(), password = node.Path.TrimSafe(),
}; };
} }
@ -192,7 +192,7 @@ public partial class CoreConfigSingboxService
try try
{ {
endpoint.address = Utils.String2List(node.RequestHost); endpoint.address = Utils.String2List(node.RequestHost);
endpoint.type = Global.ProtocolTypes[node.ConfigType]; endpoint.type = AppConfig.ProtocolTypes[node.ConfigType];
switch (node.ConfigType) switch (node.ConfigType)
{ {
@ -208,7 +208,7 @@ public partial class CoreConfigSingboxService
allowed_ips = new() { "0.0.0.0/0", "::/0" }, allowed_ips = new() { "0.0.0.0/0", "::/0" },
}; };
endpoint.private_key = node.Id; 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 }; endpoint.peers = new() { peer };
break; break;
} }
@ -225,7 +225,7 @@ public partial class CoreConfigSingboxService
{ {
try try
{ {
var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (node.ConfigType == EConfigType.WireGuard) if (node.ConfigType == EConfigType.WireGuard)
{ {
var endpoint = JsonUtils.Deserialize<Endpoints4Sbox>(txtOutbound); var endpoint = JsonUtils.Deserialize<Endpoints4Sbox>(txtOutbound);
@ -282,7 +282,7 @@ public partial class CoreConfigSingboxService
{ {
try 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); return await Task.FromResult(0);
} }
@ -315,7 +315,7 @@ public partial class CoreConfigSingboxService
fingerprint = node.Fingerprint.IsNullOrEmpty() ? _config.CoreBasicItem.DefFingerprint : node.Fingerprint 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); var certs = CertPemManager.ParsePemChain(node.Cert);
if (certs.Count > 0) if (certs.Count > 0)
@ -324,7 +324,7 @@ public partial class CoreConfigSingboxService
tls.insecure = false; tls.insecure = false;
} }
} }
else if (node.StreamSecurity == Global.StreamSecurityReality) else if (node.StreamSecurity == AppConfig.StreamSecurityReality)
{ {
tls.reality = new Reality4Sbox() tls.reality = new Reality4Sbox()
{ {
@ -363,7 +363,7 @@ public partial class CoreConfigSingboxService
break; break;
case nameof(ETransport.tcp): //http case nameof(ETransport.tcp): //http
if (node.HeaderType == Global.TcpHeaderHttp) if (node.HeaderType == AppConfig.TcpHeaderHttp)
{ {
transport.type = nameof(ETransport.http); transport.type = nameof(ETransport.http);
transport.host = node.RequestHost.IsNullOrEmpty() ? null : Utils.String2List(node.RequestHost); transport.host = node.RequestHost.IsNullOrEmpty() ? null : Utils.String2List(node.RequestHost);
@ -433,7 +433,7 @@ public partial class CoreConfigSingboxService
default: default:
break; break;
} }
if (transport.type != null) if (transport.type is not null)
{ {
outbound.transport = transport; outbound.transport = transport;
} }
@ -445,7 +445,7 @@ public partial class CoreConfigSingboxService
return await Task.FromResult(0); return await Task.FromResult(0);
} }
private async Task<int> GenGroupOutbound(ProfileItem node, SingboxConfig singboxConfig, string baseTagName = Global.ProxyTag, bool ignoreOriginChain = false) private async Task<int> GenGroupOutbound(ProfileItem node, SingboxConfig singboxConfig, string baseTagName = AppConfig.ProxyTag, bool ignoreOriginChain = false)
{ {
try try
{ {
@ -508,18 +508,18 @@ public partial class CoreConfigSingboxService
} }
//current proxy //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(); outbound ??= singboxConfig.outbounds.First();
var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
//Previous proxy //Previous proxy
var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile); var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
string? prevOutboundTag = null; string? prevOutboundTag = null;
if (prevNode is not 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); var prevServer = await GenServer(prevNode);
prevServer.tag = prevOutboundTag; prevServer.tag = prevOutboundTag;
if (prevServer is Endpoints4Sbox endpoint) if (prevServer is Endpoints4Sbox endpoint)
@ -555,12 +555,12 @@ public partial class CoreConfigSingboxService
return 0; return 0;
} }
private async Task<int> GenOutboundsListWithChain(List<ProfileItem> nodes, SingboxConfig singboxConfig, EMultipleLoad multipleLoad, string baseTagName = Global.ProxyTag) private async Task<int> GenOutboundsListWithChain(List<ProfileItem> nodes, SingboxConfig singboxConfig, EMultipleLoad multipleLoad, string baseTagName = AppConfig.ProxyTag)
{ {
try try
{ {
// Get outbound template and initialize lists // Get outbound template and initialize lists
var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (txtOutbound.IsNullOrEmpty()) if (txtOutbound.IsNullOrEmpty())
{ {
return 0; return 0;
@ -610,7 +610,7 @@ public partial class CoreConfigSingboxService
string? prevTag = null; string? prevTag = null;
var currentServer = await GenServer(node); var currentServer = await GenServer(node);
var nextServer = nextProxyCache.GetValueOrDefault(node.Subid, null); var nextServer = nextProxyCache.GetValueOrDefault(node.Subid, null);
if (nextServer != null) if (nextServer is not null)
{ {
nextServer = JsonUtils.DeepCopy(nextServer); nextServer = JsonUtils.DeepCopy(nextServer);
} }
@ -631,7 +631,7 @@ public partial class CoreConfigSingboxService
{ {
var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile); var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
if (prevNode is not null if (prevNode is not null
&& Global.SingboxSupportConfigType.Contains(prevNode.ConfigType)) && AppConfig.SingboxSupportConfigType.Contains(prevNode.ConfigType))
{ {
var prevOutbound = JsonUtils.Deserialize<Outbound4Sbox>(txtOutbound); var prevOutbound = JsonUtils.Deserialize<Outbound4Sbox>(txtOutbound);
await GenOutbound(prevNode, prevOutbound); await GenOutbound(prevNode, prevOutbound);
@ -707,7 +707,7 @@ public partial class CoreConfigSingboxService
.Concat(resultOutbounds) .Concat(resultOutbounds)
.Concat(resultEndpoints) .Concat(resultEndpoints)
.ToList(); .ToList();
await AddRangeOutbounds(serverList, singboxConfig, baseTagName == Global.ProxyTag); await AddRangeOutbounds(serverList, singboxConfig, baseTagName == AppConfig.ProxyTag);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -721,7 +721,7 @@ public partial class CoreConfigSingboxService
{ {
try try
{ {
var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.SingboxSampleOutbound);
if (!prevOutboundTag.IsNullOrEmpty()) if (!prevOutboundTag.IsNullOrEmpty())
{ {
@ -731,7 +731,7 @@ public partial class CoreConfigSingboxService
// Next proxy // Next proxy
var nextNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.NextProfile); var nextNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.NextProfile);
if (nextNode is not null if (nextNode is not null
&& Global.SingboxSupportConfigType.Contains(nextNode.ConfigType)) && AppConfig.SingboxSupportConfigType.Contains(nextNode.ConfigType))
{ {
nextOutbound ??= await GenServer(nextNode); nextOutbound ??= await GenServer(nextNode);
nextOutbound.tag = outbound.tag; nextOutbound.tag = outbound.tag;
@ -748,7 +748,7 @@ public partial class CoreConfigSingboxService
return null; return null;
} }
private async Task<int> GenOutboundsList(List<ProfileItem> nodes, SingboxConfig singboxConfig, EMultipleLoad multipleLoad, string baseTagName = Global.ProxyTag) private async Task<int> GenOutboundsList(List<ProfileItem> nodes, SingboxConfig singboxConfig, EMultipleLoad multipleLoad, string baseTagName = AppConfig.ProxyTag)
{ {
var resultOutbounds = new List<Outbound4Sbox>(); var resultOutbounds = new List<Outbound4Sbox>();
var resultEndpoints = new List<Endpoints4Sbox>(); // For endpoints var resultEndpoints = new List<Endpoints4Sbox>(); // For endpoints
@ -756,7 +756,7 @@ public partial class CoreConfigSingboxService
for (var i = 0; i < nodes.Count; i++) for (var i = 0; i < nodes.Count; i++)
{ {
var node = nodes[i]; var node = nodes[i];
if (node == null) if (node is null)
{ {
continue; continue;
} }
@ -830,11 +830,11 @@ public partial class CoreConfigSingboxService
serverList = serverList.Concat(resultOutbounds) serverList = serverList.Concat(resultOutbounds)
.Concat(resultEndpoints) .Concat(resultEndpoints)
.ToList(); .ToList();
await AddRangeOutbounds(serverList, singboxConfig, baseTagName == Global.ProxyTag); await AddRangeOutbounds(serverList, singboxConfig, baseTagName == AppConfig.ProxyTag);
return await Task.FromResult(0); return await Task.FromResult(0);
} }
private async Task<int> GenChainOutboundsList(List<ProfileItem> nodes, SingboxConfig singboxConfig, string baseTagName = Global.ProxyTag) private async Task<int> GenChainOutboundsList(List<ProfileItem> nodes, SingboxConfig singboxConfig, string baseTagName = AppConfig.ProxyTag)
{ {
// Based on actual network flow instead of data packets // Based on actual network flow instead of data packets
var nodesReverse = nodes.AsEnumerable().Reverse().ToList(); var nodesReverse = nodes.AsEnumerable().Reverse().ToList();
@ -877,7 +877,7 @@ public partial class CoreConfigSingboxService
serverList = serverList.Concat(resultOutbounds) serverList = serverList.Concat(resultOutbounds)
.Concat(resultEndpoints) .Concat(resultEndpoints)
.ToList(); .ToList();
await AddRangeOutbounds(serverList, singboxConfig, baseTagName == Global.ProxyTag); await AddRangeOutbounds(serverList, singboxConfig, baseTagName == AppConfig.ProxyTag);
return await Task.FromResult(0); return await Task.FromResult(0);
} }

View file

@ -6,17 +6,17 @@ public partial class CoreConfigSingboxService
{ {
try try
{ {
singboxConfig.route.final = Global.ProxyTag; singboxConfig.route.final = AppConfig.ProxyTag;
var item = _config.SimpleDNSItem; var item = _config.SimpleDNSItem;
var defaultDomainResolverTag = Global.SingboxDirectDNSTag; var defaultDomainResolverTag = AppConfig.SingboxDirectDNSTag;
var directDNSStrategy = item.SingboxStrategy4Direct.IsNullOrEmpty() ? Global.SingboxDomainStrategy4Out.FirstOrDefault() : item.SingboxStrategy4Direct; var directDNSStrategy = item.SingboxStrategy4Direct.IsNullOrEmpty() ? AppConfig.SingboxDomainStrategy4Out.FirstOrDefault() : item.SingboxStrategy4Direct;
var rawDNSItem = await AppManager.Instance.GetDNSItem(ECoreType.sing_box); 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; defaultDomainResolverTag = AppConfig.SingboxLocalDNSTag;
directDNSStrategy = rawDNSItem.DomainStrategy4Freedom.IsNullOrEmpty() ? Global.SingboxDomainStrategy4Out.FirstOrDefault() : rawDNSItem.DomainStrategy4Freedom; directDNSStrategy = rawDNSItem.DomainStrategy4Freedom.IsNullOrEmpty() ? AppConfig.SingboxDomainStrategy4Out.FirstOrDefault() : rawDNSItem.DomainStrategy4Freedom;
} }
singboxConfig.route.default_domain_resolver = new() singboxConfig.route.default_domain_resolver = new()
{ {
@ -28,8 +28,8 @@ public partial class CoreConfigSingboxService
{ {
singboxConfig.route.auto_detect_interface = true; singboxConfig.route.auto_detect_interface = true;
var tunRules = JsonUtils.Deserialize<List<Rule4Sbox>>(EmbedUtils.GetEmbedText(Global.TunSingboxRulesFileName)); var tunRules = JsonUtils.Deserialize<List<Rule4Sbox>>(EmbedUtils.GetEmbedText(AppConfig.TunSingboxRulesFileName));
if (tunRules != null) if (tunRules is not null)
{ {
singboxConfig.route.rules.AddRange(tunRules); singboxConfig.route.rules.AddRange(tunRules);
} }
@ -44,7 +44,7 @@ public partial class CoreConfigSingboxService
singboxConfig.route.rules.Add(new() singboxConfig.route.rules.Add(new()
{ {
outbound = Global.DirectTag, outbound = AppConfig.DirectTag,
process_name = lstDirectExe process_name = lstDirectExe
}); });
} }
@ -73,7 +73,7 @@ public partial class CoreConfigSingboxService
var hostsDomains = new List<string>(); var hostsDomains = new List<string>();
var dnsItem = await AppManager.Instance.GetDNSItem(ECoreType.sing_box); 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; var simpleDNSItem = _config.SimpleDNSItem;
if (!simpleDNSItem.Hosts.IsNullOrEmpty()) if (!simpleDNSItem.Hosts.IsNullOrEmpty())
@ -104,12 +104,12 @@ public partial class CoreConfigSingboxService
singboxConfig.route.rules.Add(new() singboxConfig.route.rules.Add(new()
{ {
outbound = Global.DirectTag, outbound = AppConfig.DirectTag,
clash_mode = ERuleMode.Direct.ToString() clash_mode = ERuleMode.Direct.ToString()
}); });
singboxConfig.route.rules.Add(new() singboxConfig.route.rules.Add(new()
{ {
outbound = Global.ProxyTag, outbound = AppConfig.ProxyTag,
clash_mode = ERuleMode.Global.ToString() clash_mode = ERuleMode.Global.ToString()
}); });
@ -124,14 +124,14 @@ public partial class CoreConfigSingboxService
action = "resolve", action = "resolve",
strategy = domainStrategy strategy = domainStrategy
}; };
if (_config.RoutingBasicItem.DomainStrategy == Global.IPOnDemand) if (_config.RoutingBasicItem.DomainStrategy == AppConfig.IPOnDemand)
{ {
singboxConfig.route.rules.Add(resolveRule); singboxConfig.route.rules.Add(resolveRule);
} }
var routing = await ConfigHandler.GetDefaultRouting(_config); var routing = await ConfigHandler.GetDefaultRouting(_config);
var ipRules = new List<RulesItem>(); var ipRules = new List<RulesItem>();
if (routing != null) if (routing is not null)
{ {
var rules = JsonUtils.Deserialize<List<RulesItem>>(routing.RuleSet); var rules = JsonUtils.Deserialize<List<RulesItem>>(routing.RuleSet);
foreach (var item1 in rules ?? []) 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); singboxConfig.route.rules.Add(resolveRule);
foreach (var item2 in ipRules) foreach (var item2 in ipRules)
@ -202,7 +202,7 @@ public partial class CoreConfigSingboxService
{ {
try try
{ {
if (item == null) if (item is null)
{ {
return 0; return 0;
} }
@ -326,7 +326,7 @@ public partial class CoreConfigSingboxService
} }
if (!hasDomainIp 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); rules.Add(rule);
} }
@ -352,7 +352,7 @@ public partial class CoreConfigSingboxService
else if (domain.StartsWith("regexp:")) else if (domain.StartsWith("regexp:"))
{ {
rule.domain_regex ??= []; 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:")) else if (domain.StartsWith("domain:"))
{ {
@ -412,23 +412,23 @@ public partial class CoreConfigSingboxService
private async Task<string?> GenRoutingUserRuleOutbound(string outboundTag, SingboxConfig singboxConfig) private async Task<string?> GenRoutingUserRuleOutbound(string outboundTag, SingboxConfig singboxConfig)
{ {
if (Global.OutboundTags.Contains(outboundTag)) if (AppConfig.OutboundTags.Contains(outboundTag))
{ {
return outboundTag; return outboundTag;
} }
var node = await AppManager.Instance.GetProfileItemViaRemarks(outboundTag); var node = await AppManager.Instance.GetProfileItemViaRemarks(outboundTag);
if (node == null if (node is null
|| (!Global.SingboxSupportConfigType.Contains(node.ConfigType) || (!AppConfig.SingboxSupportConfigType.Contains(node.ConfigType)
&& !node.ConfigType.IsGroupType())) && !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) 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; return tag;
} }
@ -440,13 +440,13 @@ public partial class CoreConfigSingboxService
{ {
return tag; return tag;
} }
return Global.ProxyTag; return AppConfig.ProxyTag;
} }
var server = await GenServer(node); var server = await GenServer(node);
if (server is null) if (server is null)
{ {
return Global.ProxyTag; return AppConfig.ProxyTag;
} }
server.tag = tag; server.tag = tag;

View file

@ -6,7 +6,7 @@ public partial class CoreConfigSingboxService
{ {
static void AddRuleSets(List<string> ruleSets, List<string>? rule_set) static void AddRuleSets(List<string> ruleSets, List<string>? rule_set)
{ {
if (rule_set != null) if (rule_set is not null)
{ {
ruleSets.AddRange(rule_set); ruleSets.AddRange(rule_set);
} }
@ -67,9 +67,9 @@ public partial class CoreConfigSingboxService
if (result.IsNotEmpty()) if (result.IsNotEmpty())
{ {
customRulesets = (JsonUtils.Deserialize<List<Ruleset4Sbox>>(result) ?? []) customRulesets = (JsonUtils.Deserialize<List<Ruleset4Sbox>>(result) ?? [])
.Where(t => t.tag != null) .Where(t => t.tag is not null)
.Where(t => t.type != null) .Where(t => t.type is not null)
.Where(t => t.format != null) .Where(t => t.format is not null)
.ToList(); .ToList();
} }
} }
@ -82,8 +82,10 @@ public partial class CoreConfigSingboxService
foreach (var item in new HashSet<string>(ruleSets)) foreach (var item in new HashSet<string>(ruleSets))
{ {
if (item.IsNullOrEmpty()) 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) if (customRuleset is null)
{ {
var pathSrs = Path.Combine(localSrss, $"{item}.srs"); var pathSrs = Path.Combine(localSrss, $"{item}.srs");
@ -100,7 +102,7 @@ public partial class CoreConfigSingboxService
else else
{ {
var srsUrl = string.IsNullOrEmpty(_config.ConstItem.SrsSourceUrl) var srsUrl = string.IsNullOrEmpty(_config.ConstItem.SrsSourceUrl)
? Global.SingboxRulesetUrl ? AppConfig.SingboxRulesetUrl
: _config.ConstItem.SrsSourceUrl; : _config.ConstItem.SrsSourceUrl;
customRuleset = new() customRuleset = new()
@ -109,7 +111,7 @@ public partial class CoreConfigSingboxService
format = "binary", format = "binary",
tag = item, tag = item,
url = string.Format(srsUrl, item.StartsWith(geosite) ? geosite : geoip, item), url = string.Format(srsUrl, item.StartsWith(geosite) ? geosite : geoip, item),
download_detour = Global.ProxyTag download_detour = AppConfig.ProxyTag
}; };
} }
} }

View file

@ -4,12 +4,12 @@ public partial class CoreConfigSingboxService
{ {
private async Task<int> GenExperimental(SingboxConfig singboxConfig) private async Task<int> GenExperimental(SingboxConfig singboxConfig)
{ {
//if (_config.guiItem.enableStatistics) //if (Config.guiItem.enableStatistics)
{ {
singboxConfig.experimental ??= new Experimental4Sbox(); singboxConfig.experimental ??= new Experimental4Sbox();
singboxConfig.experimental.clash_api = new Clash_Api4Sbox() singboxConfig.experimental.clash_api = new Clash_Api4Sbox()
{ {
external_controller = $"{Global.Loopback}:{AppManager.Instance.StatePort2}", external_controller = $"{AppConfig.Loopback}:{AppManager.Instance.StatePort2}",
}; };
} }

View file

@ -12,7 +12,7 @@ public partial class CoreConfigV2rayService(Config config)
var ret = new RetResult(); var ret = new RetResult();
try try
{ {
if (node == null if (node is null
|| !node.IsValid()) || !node.IsValid())
{ {
ret.Msg = ResUI.CheckServerSettings; 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()) if (result.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -47,7 +47,7 @@ public partial class CoreConfigV2rayService(Config config)
} }
var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result); var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result);
if (v2rayConfig == null) if (v2rayConfig is null)
{ {
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
@ -86,7 +86,7 @@ public partial class CoreConfigV2rayService(Config config)
try try
{ {
if (_config == null) if (_config is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -94,8 +94,8 @@ public partial class CoreConfigV2rayService(Config config)
ret.Msg = ResUI.InitialConfiguration; ret.Msg = ResUI.InitialConfiguration;
var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient); var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleClient);
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty()) if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -103,7 +103,7 @@ public partial class CoreConfigV2rayService(Config config)
} }
var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result); var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result);
if (v2rayConfig == null) if (v2rayConfig is null)
{ {
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
@ -124,7 +124,7 @@ public partial class CoreConfigV2rayService(Config config)
await GenDns(null, v2rayConfig); await GenDns(null, v2rayConfig);
await GenStatistic(v2rayConfig); await GenStatistic(v2rayConfig);
var defaultBalancerTag = $"{Global.ProxyTag}{Global.BalancerTagSuffix}"; var defaultBalancerTag = $"{AppConfig.ProxyTag}{AppConfig.BalancerTagSuffix}";
//add rule //add rule
var rules = v2rayConfig.routing.rules; var rules = v2rayConfig.routing.rules;
@ -136,7 +136,7 @@ public partial class CoreConfigV2rayService(Config config)
foreach (var rule in rules) foreach (var rule in rules)
{ {
if (rule.outboundTag == null) if (rule.outboundTag is null)
{ {
continue; continue;
} }
@ -148,7 +148,7 @@ public partial class CoreConfigV2rayService(Config config)
continue; continue;
} }
var outboundWithSuffix = rule.outboundTag + Global.BalancerTagSuffix; var outboundWithSuffix = rule.outboundTag + AppConfig.BalancerTagSuffix;
if (balancerTagSet.Contains(outboundWithSuffix)) if (balancerTagSet.Contains(outboundWithSuffix))
{ {
rule.balancerTag = 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() v2rayConfig.routing.rules.Add(new()
{ {
@ -194,7 +194,7 @@ public partial class CoreConfigV2rayService(Config config)
try try
{ {
if (_config == null) if (_config is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -202,8 +202,8 @@ public partial class CoreConfigV2rayService(Config config)
ret.Msg = ResUI.InitialConfiguration; ret.Msg = ResUI.InitialConfiguration;
var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient); var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleClient);
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty()) if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -211,7 +211,7 @@ public partial class CoreConfigV2rayService(Config config)
} }
var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result); var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result);
if (v2rayConfig == null) if (v2rayConfig is null)
{ {
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
@ -250,7 +250,7 @@ public partial class CoreConfigV2rayService(Config config)
var ret = new RetResult(); var ret = new RetResult();
try try
{ {
if (_config == null) if (_config is null)
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
return ret; return ret;
@ -258,8 +258,8 @@ public partial class CoreConfigV2rayService(Config config)
ret.Msg = ResUI.InitialConfiguration; ret.Msg = ResUI.InitialConfiguration;
var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient); var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleClient);
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty()) if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -267,7 +267,7 @@ public partial class CoreConfigV2rayService(Config config)
} }
var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result); var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result);
if (v2rayConfig == null) if (v2rayConfig is null)
{ {
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
@ -294,7 +294,7 @@ public partial class CoreConfigV2rayService(Config config)
foreach (var it in selecteds) foreach (var it in selecteds)
{ {
if (!Global.XraySupportConfigType.Contains(it.ConfigType)) if (!AppConfig.XraySupportConfigType.Contains(it.ConfigType))
{ {
continue; continue;
} }
@ -310,7 +310,7 @@ public partial class CoreConfigV2rayService(Config config)
//find unused port //find unused port
var port = initPort; 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) if (lstIpEndPoints?.FindIndex(_it => _it.Port == k) >= 0)
{ {
@ -337,7 +337,7 @@ public partial class CoreConfigV2rayService(Config config)
//inbound //inbound
Inbounds4Ray inbound = new() Inbounds4Ray inbound = new()
{ {
listen = Global.Loopback, listen = AppConfig.Loopback,
port = port, port = port,
protocol = EInboundProtocol.mixed.ToString(), protocol = EInboundProtocol.mixed.ToString(),
}; };
@ -347,7 +347,7 @@ public partial class CoreConfigV2rayService(Config config)
//outbound //outbound
var outbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound); var outbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound);
await GenOutbound(item, outbound); await GenOutbound(item, outbound);
outbound.tag = Global.ProxyTag + inbound.port.ToString(); outbound.tag = AppConfig.ProxyTag + inbound.port.ToString();
v2rayConfig.outbounds.Add(outbound); v2rayConfig.outbounds.Add(outbound);
//rule //rule
@ -378,7 +378,7 @@ public partial class CoreConfigV2rayService(Config config)
var ret = new RetResult(); var ret = new RetResult();
try try
{ {
if (node == null if (node is null
|| !node.IsValid()) || !node.IsValid())
{ {
ret.Msg = ResUI.CheckServerSettings; ret.Msg = ResUI.CheckServerSettings;
@ -391,7 +391,7 @@ public partial class CoreConfigV2rayService(Config config)
return ret; return ret;
} }
var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient); var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleClient);
if (result.IsNullOrEmpty()) if (result.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -399,7 +399,7 @@ public partial class CoreConfigV2rayService(Config config)
} }
var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result); var v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result);
if (v2rayConfig == null) if (v2rayConfig is null)
{ {
ret.Msg = ResUI.FailedGenDefaultConfiguration; ret.Msg = ResUI.FailedGenDefaultConfiguration;
return ret; return ret;
@ -414,7 +414,7 @@ public partial class CoreConfigV2rayService(Config config)
v2rayConfig.inbounds.Add(new() v2rayConfig.inbounds.Add(new()
{ {
tag = $"{EInboundProtocol.socks}{port}", tag = $"{EInboundProtocol.socks}{port}",
listen = Global.Loopback, listen = AppConfig.Loopback,
port = port, port = port,
protocol = EInboundProtocol.mixed.ToString(), protocol = EInboundProtocol.mixed.ToString(),
}); });

View file

@ -2,7 +2,7 @@ namespace ServiceLib.Services.CoreConfig;
public partial class CoreConfigV2rayService public partial class CoreConfigV2rayService
{ {
private async Task<int> GenObservatory(V2rayConfig v2rayConfig, EMultipleLoad multipleLoad, string baseTagName = Global.ProxyTag) private async Task<int> GenObservatory(V2rayConfig v2rayConfig, EMultipleLoad multipleLoad, string baseTagName = AppConfig.ProxyTag)
{ {
// Collect all existing subject selectors from both observatories // Collect all existing subject selectors from both observatories
var subjectSelectors = new List<string>(); var subjectSelectors = new List<string>();
@ -83,7 +83,7 @@ public partial class CoreConfigV2rayService
return await Task.FromResult(0); return await Task.FromResult(0);
} }
private async Task<string> GenBalancer(V2rayConfig v2rayConfig, EMultipleLoad multipleLoad, string selector = Global.ProxyTag) private async Task<string> GenBalancer(V2rayConfig v2rayConfig, EMultipleLoad multipleLoad, string selector = AppConfig.ProxyTag)
{ {
var strategyType = multipleLoad switch var strategyType = multipleLoad switch
{ {
@ -93,7 +93,7 @@ public partial class CoreConfigV2rayService
EMultipleLoad.LeastLoad => "leastLoad", EMultipleLoad.LeastLoad => "leastLoad",
_ => "roundRobin", _ => "roundRobin",
}; };
var balancerTag = $"{selector}{Global.BalancerTagSuffix}"; var balancerTag = $"{selector}{AppConfig.BalancerTagSuffix}";
var balancer = new BalancersItem4Ray var balancer = new BalancersItem4Ray
{ {
selector = [selector], selector = [selector],

View file

@ -5,13 +5,13 @@ public partial class CoreConfigV2rayService
private async Task<string> ApplyFullConfigTemplate(V2rayConfig v2rayConfig) private async Task<string> ApplyFullConfigTemplate(V2rayConfig v2rayConfig)
{ {
var fullConfigTemplate = await AppManager.Instance.GetFullConfigTemplateItem(ECoreType.Xray); 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); return JsonUtils.Serialize(v2rayConfig);
} }
var fullConfigTemplateNode = JsonNode.Parse(fullConfigTemplate.Config); var fullConfigTemplateNode = JsonNode.Parse(fullConfigTemplate.Config);
if (fullConfigTemplateNode == null) if (fullConfigTemplateNode is null)
{ {
return JsonUtils.Serialize(v2rayConfig); return JsonUtils.Serialize(v2rayConfig);
} }
@ -23,11 +23,11 @@ public partial class CoreConfigV2rayService
// Modify existing rules in custom config // Modify existing rules in custom config
var rulesNode = fullConfigTemplateNode["routing"]?["rules"]; var rulesNode = fullConfigTemplateNode["routing"]?["rules"];
if (rulesNode != null) if (rulesNode is not null)
{ {
foreach (var rule in rulesNode.AsArray()) foreach (var rule in rulesNode.AsArray())
{ {
if (rule["outboundTag"]?.GetValue<string>() == Global.ProxyTag) if (rule["outboundTag"]?.GetValue<string>() == AppConfig.ProxyTag)
{ {
rule.AsObject().Remove("outboundTag"); rule.AsObject().Remove("outboundTag");
rule["balancerTag"] = balancer.tag; rule["balancerTag"] = balancer.tag;
@ -36,7 +36,7 @@ public partial class CoreConfigV2rayService
} }
// Ensure routing node exists // Ensure routing node exists
if (fullConfigTemplateNode["routing"] == null) if (fullConfigTemplateNode["routing"] is null)
{ {
fullConfigTemplateNode["routing"] = new JsonObject(); 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)); 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)); fullConfigTemplateNode["burstObservatory"] = JsonNode.Parse(JsonUtils.Serialize(v2rayConfig.burstObservatory));
} }

View file

@ -7,19 +7,19 @@ public partial class CoreConfigV2rayService
try try
{ {
var item = await AppManager.Instance.GetDNSItem(ECoreType.Xray); 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); var result = await GenDnsCompatible(node, v2rayConfig);
if (v2rayConfig.routing.domainStrategy == Global.IPIfNonMatch) if (v2rayConfig.routing.domainStrategy == AppConfig.IPIfNonMatch)
{ {
// DNS routing // DNS routing
v2rayConfig.dns.tag = Global.DnsTag; v2rayConfig.dns.tag = AppConfig.DnsTag;
v2rayConfig.routing.rules.Add(new RulesItem4Ray v2rayConfig.routing.rules.Add(new RulesItem4Ray
{ {
type = "field", type = "field",
inboundTag = new List<string> { Global.DnsTag }, inboundTag = new List<string> { AppConfig.DnsTag },
outboundTag = Global.ProxyTag, outboundTag = AppConfig.ProxyTag,
}); });
} }
@ -31,29 +31,26 @@ public partial class CoreConfigV2rayService
//Outbound Freedom domainStrategy //Outbound Freedom domainStrategy
if (domainStrategy4Freedom.IsNotEmpty()) if (domainStrategy4Freedom.IsNotEmpty())
{ {
var outbound = v2rayConfig.outbounds.FirstOrDefault(t => t is { protocol: "freedom", tag: Global.DirectTag }); var outbound = v2rayConfig.outbounds.FirstOrDefault(t => t is { protocol: "freedom", tag: AppConfig.DirectTag });
if (outbound != null) outbound?.settings = new()
{ {
outbound.settings = new() domainStrategy = domainStrategy4Freedom,
{ userLevel = 0
domainStrategy = domainStrategy4Freedom, };
userLevel = 0
};
}
} }
await GenDnsServers(node, v2rayConfig, simpleDNSItem); await GenDnsServers(node, v2rayConfig, simpleDNSItem);
await GenDnsHosts(v2rayConfig, simpleDNSItem); await GenDnsHosts(v2rayConfig, simpleDNSItem);
if (v2rayConfig.routing.domainStrategy == Global.IPIfNonMatch) if (v2rayConfig.routing.domainStrategy == AppConfig.IPIfNonMatch)
{ {
// DNS routing // DNS routing
v2rayConfig.dns.tag = Global.DnsTag; v2rayConfig.dns.tag = AppConfig.DnsTag;
v2rayConfig.routing.rules.Add(new RulesItem4Ray v2rayConfig.routing.rules.Add(new RulesItem4Ray
{ {
type = "field", type = "field",
inboundTag = new List<string> { Global.DnsTag }, inboundTag = new List<string> { AppConfig.DnsTag },
outboundTag = Global.ProxyTag, outboundTag = AppConfig.ProxyTag,
}); });
} }
} }
@ -106,8 +103,8 @@ public partial class CoreConfigV2rayService
}); });
} }
var directDNSAddress = ParseDnsAddresses(simpleDNSItem?.DirectDNS, Global.DomainDirectDNSAddress.FirstOrDefault()); var directDNSAddress = ParseDnsAddresses(simpleDNSItem?.DirectDNS, AppConfig.DomainDirectDNSAddress.FirstOrDefault());
var remoteDNSAddress = ParseDnsAddresses(simpleDNSItem?.RemoteDNS, Global.DomainRemoteDNSAddress.FirstOrDefault()); var remoteDNSAddress = ParseDnsAddresses(simpleDNSItem?.RemoteDNS, AppConfig.DomainRemoteDNSAddress.FirstOrDefault());
var directDomainList = new List<string>(); var directDomainList = new List<string>();
var directGeositeList = new List<string>(); var directGeositeList = new List<string>();
@ -117,7 +114,7 @@ public partial class CoreConfigV2rayService
var expectedIPs = new List<string>(); var expectedIPs = new List<string>();
var regionNames = new HashSet<string>(); var regionNames = new HashSet<string>();
var bootstrapDNSAddress = ParseDnsAddresses(simpleDNSItem?.BootstrapDNS, Global.DomainPureIPDNSAddress.FirstOrDefault()); var bootstrapDNSAddress = ParseDnsAddresses(simpleDNSItem?.BootstrapDNS, AppConfig.DomainPureIPDNSAddress.FirstOrDefault());
var dnsServerDomains = new List<string>(); var dnsServerDomains = new List<string>();
foreach (var dns in directDNSAddress) foreach (var dns in directDNSAddress)
@ -171,7 +168,7 @@ public partial class CoreConfigV2rayService
var routing = await ConfigHandler.GetDefaultRouting(_config); var routing = await ConfigHandler.GetDefaultRouting(_config);
List<RulesItem>? rules = null; List<RulesItem>? rules = null;
if (routing != null) if (routing is not null)
{ {
rules = JsonUtils.Deserialize<List<RulesItem>>(routing.RuleSet) ?? []; rules = JsonUtils.Deserialize<List<RulesItem>>(routing.RuleSet) ?? [];
foreach (var item in rules) foreach (var item in rules)
@ -193,9 +190,9 @@ public partial class CoreConfigV2rayService
continue; 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:")) if (normalizedDomain.StartsWith("geosite:") || normalizedDomain.StartsWith("ext:"))
{ {
@ -206,7 +203,7 @@ public partial class CoreConfigV2rayService
directDomainList.Add(normalizedDomain); directDomainList.Add(normalizedDomain);
} }
} }
else if (item.OutboundTag != Global.BlockTag) else if (item.OutboundTag != AppConfig.BlockTag)
{ {
if (normalizedDomain.StartsWith("geosite:") || normalizedDomain.StartsWith("ext:")) if (normalizedDomain.StartsWith("geosite:") || normalizedDomain.StartsWith("ext:"))
{ {
@ -235,7 +232,7 @@ public partial class CoreConfigV2rayService
{ {
var profileNode = await AppManager.Instance.GetProfileItemViaRemarks(profile); var profileNode = await AppManager.Instance.GetProfileItemViaRemarks(profile);
if (profileNode is not null if (profileNode is not null
&& Global.XraySupportConfigType.Contains(profileNode.ConfigType) && AppConfig.XraySupportConfigType.Contains(profileNode.ConfigType)
&& Utils.IsDomain(profileNode.Address)) && Utils.IsDomain(profileNode.Address))
{ {
directDomainList.Add(profileNode.Address); directDomainList.Add(profileNode.Address);
@ -269,7 +266,7 @@ public partial class CoreConfigV2rayService
} }
var useDirectDns = rules?.LastOrDefault() is { } lastRule var useDirectDns = rules?.LastOrDefault() is { } lastRule
&& lastRule.OutboundTag == Global.DirectTag && lastRule.OutboundTag == AppConfig.DirectTag
&& (lastRule.Port == "0-65535" && (lastRule.Port == "0-65535"
|| lastRule.Network == "tcp,udp" || lastRule.Network == "tcp,udp"
|| lastRule.Ip?.Contains("0.0.0.0/0") == true); || lastRule.Ip?.Contains("0.0.0.0/0") == true);
@ -280,7 +277,7 @@ public partial class CoreConfigV2rayService
return 0; return 0;
} }
private async Task<int> GenDnsHosts(V2rayConfig v2rayConfig, SimpleDNSItem simpleDNSItem) private static async Task<int> GenDnsHosts(V2rayConfig v2rayConfig, SimpleDNSItem simpleDNSItem)
{ {
if (simpleDNSItem.AddCommonHosts == false && simpleDNSItem.UseSystemHosts == false && simpleDNSItem.Hosts.IsNullOrEmpty()) if (simpleDNSItem.AddCommonHosts == false && simpleDNSItem.UseSystemHosts == false && simpleDNSItem.Hosts.IsNullOrEmpty())
{ {
@ -290,7 +287,7 @@ public partial class CoreConfigV2rayService
v2rayConfig.dns.hosts ??= new Dictionary<string, object>(); v2rayConfig.dns.hosts ??= new Dictionary<string, object>();
if (simpleDNSItem.AddCommonHosts == true) if (simpleDNSItem.AddCommonHosts == true)
{ {
v2rayConfig.dns.hosts = Global.PredefinedHosts.ToDictionary( v2rayConfig.dns.hosts = AppConfig.PredefinedHosts.ToDictionary(
kvp => kvp.Key, kvp => kvp.Key,
kvp => (object)kvp.Value kvp => (object)kvp.Value
); );
@ -301,7 +298,7 @@ public partial class CoreConfigV2rayService
var systemHosts = Utils.GetSystemHosts(); var systemHosts = Utils.GetSystemHosts();
var normalHost = v2rayConfig?.dns?.hosts; var normalHost = v2rayConfig?.dns?.hosts;
if (normalHost != null && systemHosts?.Count > 0) if (normalHost is not null && systemHosts?.Count > 0)
{ {
foreach (var host in systemHosts) foreach (var host in systemHosts)
{ {
@ -331,19 +328,18 @@ public partial class CoreConfigV2rayService
var domainStrategy4Freedom = item?.DomainStrategy4Freedom; var domainStrategy4Freedom = item?.DomainStrategy4Freedom;
if (normalDNS.IsNullOrEmpty()) if (normalDNS.IsNullOrEmpty())
{ {
normalDNS = EmbedUtils.GetEmbedText(Global.DNSV2rayNormalFileName); normalDNS = EmbedUtils.GetEmbedText(AppConfig.DNSV2rayNormalFileName);
} }
//Outbound Freedom domainStrategy //Outbound Freedom domainStrategy
if (domainStrategy4Freedom.IsNotEmpty()) if (domainStrategy4Freedom.IsNotEmpty())
{ {
var outbound = v2rayConfig.outbounds.FirstOrDefault(t => t is { protocol: "freedom", tag: Global.DirectTag }); var outbound = v2rayConfig.outbounds.FirstOrDefault(t => t is { protocol: "freedom", tag: AppConfig.DirectTag });
if (outbound != null) outbound?.settings = new()
{ {
outbound.settings = new(); domainStrategy = domainStrategy4Freedom,
outbound.settings.domainStrategy = domainStrategy4Freedom; userLevel = 0
outbound.settings.userLevel = 0; };
}
} }
var obj = JsonUtils.ParseJson(normalDNS); var obj = JsonUtils.ParseJson(normalDNS);
@ -366,11 +362,11 @@ public partial class CoreConfigV2rayService
if (systemHosts.Count > 0) if (systemHosts.Count > 0)
{ {
var normalHost1 = obj["hosts"]; var normalHost1 = obj["hosts"];
if (normalHost1 != null) if (normalHost1 is not null)
{ {
foreach (var host in systemHosts) foreach (var host in systemHosts)
{ {
if (normalHost1[host.Key] != null) if (normalHost1[host.Key] is not null)
{ {
continue; continue;
} }
@ -381,7 +377,7 @@ public partial class CoreConfigV2rayService
} }
} }
var normalHost = obj["hosts"]; var normalHost = obj["hosts"];
if (normalHost != null) if (normalHost is not null)
{ {
foreach (var hostProp in normalHost.AsObject().ToList()) foreach (var hostProp in normalHost.AsObject().ToList())
{ {
@ -403,14 +399,14 @@ public partial class CoreConfigV2rayService
return 0; return 0;
} }
private async Task<int> GenDnsDomainsCompatible(ProfileItem? node, JsonNode dns, DNSItem? dnsItem) private static async Task<int> GenDnsDomainsCompatible(ProfileItem? node, JsonNode dns, DNSItem? dnsItem)
{ {
if (node == null) if (node is null)
{ {
return 0; return 0;
} }
var servers = dns["servers"]; var servers = dns["servers"];
if (servers != null) if (servers is not null)
{ {
var domainList = new List<string>(); var domainList = new List<string>();
if (Utils.IsDomain(node.Address)) if (Utils.IsDomain(node.Address))
@ -423,7 +419,7 @@ public partial class CoreConfigV2rayService
// Previous proxy // Previous proxy
var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile); var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
if (prevNode is not null if (prevNode is not null
&& Global.SingboxSupportConfigType.Contains(prevNode.ConfigType) && AppConfig.SingboxSupportConfigType.Contains(prevNode.ConfigType)
&& Utils.IsDomain(prevNode.Address)) && Utils.IsDomain(prevNode.Address))
{ {
domainList.Add(prevNode.Address); domainList.Add(prevNode.Address);
@ -432,7 +428,7 @@ public partial class CoreConfigV2rayService
// Next proxy // Next proxy
var nextNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.NextProfile); var nextNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.NextProfile);
if (nextNode is not null if (nextNode is not null
&& Global.SingboxSupportConfigType.Contains(nextNode.ConfigType) && AppConfig.SingboxSupportConfigType.Contains(nextNode.ConfigType)
&& Utils.IsDomain(nextNode.Address)) && Utils.IsDomain(nextNode.Address))
{ {
domainList.Add(nextNode.Address); domainList.Add(nextNode.Address);
@ -442,7 +438,7 @@ public partial class CoreConfigV2rayService
{ {
var dnsServer = new DnsServer4Ray() 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, skipFallback = true,
domains = domainList domains = domainList
}; };

View file

@ -30,7 +30,7 @@ public partial class CoreConfigV2rayService
if (_config.Inbound.First().User.IsNotEmpty() && _config.Inbound.First().Pass.IsNotEmpty()) if (_config.Inbound.First().User.IsNotEmpty() && _config.Inbound.First().Pass.IsNotEmpty())
{ {
inbound3.settings.auth = "password"; inbound3.settings.auth = "password";
inbound3.settings.accounts = new List<AccountsItem4Ray> { new AccountsItem4Ray() { user = _config.Inbound.First().User, pass = _config.Inbound.First().Pass } }; inbound3.settings.accounts = new List<AccountsItem4Ray> { new() { user = _config.Inbound.First().User, pass = _config.Inbound.First().Pass } };
} }
} }
else else
@ -48,14 +48,14 @@ public partial class CoreConfigV2rayService
private Inbounds4Ray GetInbound(InItem inItem, EInboundProtocol protocol, bool bSocks) private Inbounds4Ray GetInbound(InItem inItem, EInboundProtocol protocol, bool bSocks)
{ {
var result = EmbedUtils.GetEmbedText(Global.V2raySampleInbound); var result = EmbedUtils.GetEmbedText(AppConfig.V2raySampleInbound);
if (result.IsNullOrEmpty()) if (result.IsNullOrEmpty())
{ {
return new(); return new();
} }
var inbound = JsonUtils.Deserialize<Inbounds4Ray>(result); var inbound = JsonUtils.Deserialize<Inbounds4Ray>(result);
if (inbound == null) if (inbound is null)
{ {
return new(); return new();
} }

View file

@ -37,14 +37,14 @@ public partial class CoreConfigV2rayService
usersItem.id = node.Id; usersItem.id = node.Id;
usersItem.alterId = node.AlterId; usersItem.alterId = node.AlterId;
usersItem.email = Global.UserEMail; usersItem.email = AppConfig.UserEMail;
if (Global.VmessSecurities.Contains(node.Security)) if (AppConfig.VmessSecurities.Contains(node.Security))
{ {
usersItem.security = node.Security; usersItem.security = node.Security;
} }
else else
{ {
usersItem.security = Global.DefaultSecurity; usersItem.security = AppConfig.DefaultSecurity;
} }
await GenOutboundMux(node, outbound, muxEnabled, muxEnabled); await GenOutboundMux(node, outbound, muxEnabled, muxEnabled);
@ -139,7 +139,7 @@ public partial class CoreConfigV2rayService
usersItem = vnextItem.users.First(); usersItem = vnextItem.users.First();
} }
usersItem.id = node.Id; usersItem.id = node.Id;
usersItem.email = Global.UserEMail; usersItem.email = AppConfig.UserEMail;
usersItem.encryption = node.Security; usersItem.encryption = node.Security;
if (node.Flow.IsNullOrEmpty()) if (node.Flow.IsNullOrEmpty())
@ -185,9 +185,9 @@ public partial class CoreConfigV2rayService
version = 2, version = 2,
address = node.Address, address = node.Address,
port = node.Port, port = node.Port,
vnext = null,
servers = null
}; };
outbound.settings.vnext = null;
outbound.settings.servers = null;
break; break;
} }
case EConfigType.WireGuard: case EConfigType.WireGuard:
@ -207,7 +207,7 @@ public partial class CoreConfigV2rayService
address = Utils.String2List(node.RequestHost), address = Utils.String2List(node.RequestHost),
secretKey = node.Id, secretKey = node.Id,
reserved = Utils.String2List(node.Path)?.Select(int.Parse).ToList(), 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<WireguardPeer4Ray> { peer } peers = new List<WireguardPeer4Ray> { peer }
}; };
outbound.settings = setting; 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) if (node.ConfigType == EConfigType.Hysteria2)
{ {
outbound.protocol = "hysteria"; outbound.protocol = "hysteria";
@ -268,15 +268,15 @@ public partial class CoreConfigV2rayService
network = "hysteria"; network = "hysteria";
} }
streamSettings.network = network; streamSettings.network = network;
var host = node.RequestHost.TrimEx(); var host = node.RequestHost.TrimSafe();
var path = node.Path.TrimEx(); var path = node.Path.TrimSafe();
var sni = node.Sni.TrimEx(); var sni = node.Sni.TrimSafe();
var useragent = ""; var useragent = "";
if (!_config.CoreBasicItem.DefUserAgent.IsNullOrEmpty()) if (!_config.CoreBasicItem.DefUserAgent.IsNullOrEmpty())
{ {
try try
{ {
useragent = Global.UserAgentTexts[_config.CoreBasicItem.DefUserAgent]; useragent = AppConfig.UserAgentTexts[_config.CoreBasicItem.DefUserAgent];
} }
catch (KeyNotFoundException) catch (KeyNotFoundException)
{ {
@ -285,7 +285,7 @@ public partial class CoreConfigV2rayService
} }
//if tls //if tls
if (node.StreamSecurity == Global.StreamSecurity) if (node.StreamSecurity == AppConfig.StreamSecurity)
{ {
streamSettings.security = node.StreamSecurity; streamSettings.security = node.StreamSecurity;
@ -330,7 +330,7 @@ public partial class CoreConfigV2rayService
} }
//if Reality //if Reality
if (node.StreamSecurity == Global.StreamSecurityReality) if (node.StreamSecurity == AppConfig.StreamSecurityReality)
{ {
streamSettings.security = node.StreamSecurity; streamSettings.security = node.StreamSecurity;
@ -355,19 +355,18 @@ public partial class CoreConfigV2rayService
KcpSettings4Ray kcpSettings = new() KcpSettings4Ray kcpSettings = new()
{ {
mtu = _config.KcpItem.Mtu, 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; congestion = _config.KcpItem.Congestion,
kcpSettings.downlinkCapacity = _config.KcpItem.DownlinkCapacity; readBufferSize = _config.KcpItem.ReadBufferSize,
writeBufferSize = _config.KcpItem.WriteBufferSize,
kcpSettings.congestion = _config.KcpItem.Congestion; header = new Header4Ray
kcpSettings.readBufferSize = _config.KcpItem.ReadBufferSize; {
kcpSettings.writeBufferSize = _config.KcpItem.WriteBufferSize; type = node.HeaderType,
kcpSettings.header = new Header4Ray domain = host.NullIfEmpty()
{ }
type = node.HeaderType,
domain = host.NullIfEmpty()
}; };
if (path.IsNotEmpty()) if (path.IsNotEmpty())
{ {
@ -377,8 +376,10 @@ public partial class CoreConfigV2rayService
break; break;
//ws //ws
case nameof(ETransport.ws): case nameof(ETransport.ws):
WsSettings4Ray wsSettings = new(); WsSettings4Ray wsSettings = new()
wsSettings.headers = new Headers4Ray(); {
headers = new Headers4Ray()
};
if (host.IsNotEmpty()) if (host.IsNotEmpty())
{ {
@ -423,7 +424,7 @@ public partial class CoreConfigV2rayService
{ {
xhttpSettings.host = host; 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; xhttpSettings.mode = node.HeaderType;
} }
@ -461,7 +462,7 @@ public partial class CoreConfigV2rayService
} }
}; };
streamSettings.quicSettings = quicsettings; streamSettings.quicSettings = quicsettings;
if (node.StreamSecurity == Global.StreamSecurity) if (node.StreamSecurity == AppConfig.StreamSecurity)
{ {
if (sni.IsNotEmpty()) if (sni.IsNotEmpty())
{ {
@ -479,7 +480,7 @@ public partial class CoreConfigV2rayService
{ {
authority = host.NullIfEmpty(), authority = host.NullIfEmpty(),
serviceName = path, serviceName = path,
multiMode = node.HeaderType == Global.GrpcMultiMode, multiMode = node.HeaderType == AppConfig.GrpcMultiMode,
idle_timeout = _config.GrpcItem.IdleTimeout, idle_timeout = _config.GrpcItem.IdleTimeout,
health_check_timeout = _config.GrpcItem.HealthCheckTimeout, health_check_timeout = _config.GrpcItem.HealthCheckTimeout,
permit_without_stream = _config.GrpcItem.PermitWithoutStream, permit_without_stream = _config.GrpcItem.PermitWithoutStream,
@ -513,13 +514,13 @@ public partial class CoreConfigV2rayService
if (node.Path.IsNotEmpty()) if (node.Path.IsNotEmpty())
{ {
streamSettings.udpmasks = streamSettings.udpmasks =
[new() { type = "salamander", settings = new() { password = node.Path.TrimEx(), } }]; [new() { type = "salamander", settings = new() { password = node.Path.TrimSafe(), } }];
} }
break; break;
default: default:
//tcp //tcp
if (node.HeaderType == Global.TcpHeaderHttp) if (node.HeaderType == AppConfig.TcpHeaderHttp)
{ {
TcpSettings4Ray tcpSettings = new() TcpSettings4Ray tcpSettings = new()
{ {
@ -530,7 +531,7 @@ public partial class CoreConfigV2rayService
}; };
//request Host //request Host
var request = EmbedUtils.GetEmbedText(Global.V2raySampleHttpRequestFileName); var request = EmbedUtils.GetEmbedText(AppConfig.V2raySampleHttpRequestFileName);
var arrHost = host.Split(','); var arrHost = host.Split(',');
var host2 = string.Join(",".AppendQuotes(), arrHost); var host2 = string.Join(",".AppendQuotes(), arrHost);
request = request.Replace("$requestHost$", $"{host2.AppendQuotes()}"); request = request.Replace("$requestHost$", $"{host2.AppendQuotes()}");
@ -557,7 +558,7 @@ public partial class CoreConfigV2rayService
return 0; return 0;
} }
private async Task<int> GenGroupOutbound(ProfileItem node, V2rayConfig v2rayConfig, string baseTagName = Global.ProxyTag, bool ignoreOriginChain = false) private async Task<int> GenGroupOutbound(ProfileItem node, V2rayConfig v2rayConfig, string baseTagName = AppConfig.ProxyTag, bool ignoreOriginChain = false)
{ {
try try
{ {
@ -620,7 +621,7 @@ public partial class CoreConfigV2rayService
var fragmentOutbound = new Outbounds4Ray var fragmentOutbound = new Outbounds4Ray
{ {
protocol = "freedom", protocol = "freedom",
tag = $"frag-{Global.ProxyTag}", tag = $"frag-{AppConfig.ProxyTag}",
settings = new() settings = new()
{ {
fragment = new() fragment = new()
@ -654,17 +655,17 @@ public partial class CoreConfigV2rayService
//current proxy //current proxy
var outbound = v2rayConfig.outbounds.First(); var outbound = v2rayConfig.outbounds.First();
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
//Previous proxy //Previous proxy
var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile); var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
string? prevOutboundTag = null; string? prevOutboundTag = null;
if (prevNode is not null if (prevNode is not null
&& Global.XraySupportConfigType.Contains(prevNode.ConfigType)) && AppConfig.XraySupportConfigType.Contains(prevNode.ConfigType))
{ {
var prevOutbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound); var prevOutbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound);
await GenOutbound(prevNode, prevOutbound); await GenOutbound(prevNode, prevOutbound);
prevOutboundTag = $"prev-{Global.ProxyTag}"; prevOutboundTag = $"prev-{AppConfig.ProxyTag}";
prevOutbound.tag = prevOutboundTag; prevOutbound.tag = prevOutboundTag;
v2rayConfig.outbounds.Add(prevOutbound); v2rayConfig.outbounds.Add(prevOutbound);
} }
@ -683,12 +684,12 @@ public partial class CoreConfigV2rayService
return 0; return 0;
} }
private async Task<int> GenOutboundsListWithChain(List<ProfileItem> nodes, V2rayConfig v2rayConfig, string baseTagName = Global.ProxyTag) private async Task<int> GenOutboundsListWithChain(List<ProfileItem> nodes, V2rayConfig v2rayConfig, string baseTagName = AppConfig.ProxyTag)
{ {
try try
{ {
// Get template and initialize list // Get template and initialize list
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (txtOutbound.IsNullOrEmpty()) if (txtOutbound.IsNullOrEmpty())
{ {
return 0; return 0;
@ -731,7 +732,7 @@ public partial class CoreConfigV2rayService
string? prevTag = null; string? prevTag = null;
var currentOutbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound); var currentOutbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound);
var nextOutbound = nextProxyCache.GetValueOrDefault(node.Subid, null); var nextOutbound = nextProxyCache.GetValueOrDefault(node.Subid, null);
if (nextOutbound != null) if (nextOutbound is not null)
{ {
nextOutbound = JsonUtils.DeepCopy(nextOutbound); nextOutbound = JsonUtils.DeepCopy(nextOutbound);
} }
@ -752,7 +753,7 @@ public partial class CoreConfigV2rayService
{ {
var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile); var prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
if (prevNode is not null if (prevNode is not null
&& Global.XraySupportConfigType.Contains(prevNode.ConfigType)) && AppConfig.XraySupportConfigType.Contains(prevNode.ConfigType))
{ {
var prevOutbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound); var prevOutbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound);
await GenOutbound(prevNode, prevOutbound); 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 // 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(prevOutbounds);
resultOutbounds.AddRange(v2rayConfig.outbounds); resultOutbounds.AddRange(v2rayConfig.outbounds);
@ -814,7 +815,7 @@ public partial class CoreConfigV2rayService
{ {
try try
{ {
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (!prevOutboundTag.IsNullOrEmpty()) if (!prevOutboundTag.IsNullOrEmpty())
{ {
@ -827,9 +828,9 @@ public partial class CoreConfigV2rayService
// Next proxy // Next proxy
var nextNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.NextProfile); var nextNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.NextProfile);
if (nextNode is not null 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<Outbounds4Ray>(txtOutbound); nextOutbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound);
await GenOutbound(nextNode, nextOutbound); await GenOutbound(nextNode, nextOutbound);
@ -851,13 +852,13 @@ public partial class CoreConfigV2rayService
return null; return null;
} }
private async Task<int> GenOutboundsList(List<ProfileItem> nodes, V2rayConfig v2rayConfig, string baseTagName = Global.ProxyTag) private async Task<int> GenOutboundsList(List<ProfileItem> nodes, V2rayConfig v2rayConfig, string baseTagName = AppConfig.ProxyTag)
{ {
var resultOutbounds = new List<Outbounds4Ray>(); var resultOutbounds = new List<Outbounds4Ray>();
for (var i = 0; i < nodes.Count; i++) for (var i = 0; i < nodes.Count; i++)
{ {
var node = nodes[i]; var node = nodes[i];
if (node == null) if (node is null)
{ {
continue; continue;
} }
@ -880,7 +881,7 @@ public partial class CoreConfigV2rayService
}; };
continue; continue;
} }
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (txtOutbound.IsNullOrEmpty()) if (txtOutbound.IsNullOrEmpty())
{ {
break; break;
@ -894,7 +895,7 @@ public partial class CoreConfigV2rayService
outbound.tag = baseTagName + (i + 1).ToString(); outbound.tag = baseTagName + (i + 1).ToString();
resultOutbounds.Add(outbound); resultOutbounds.Add(outbound);
} }
if (baseTagName == Global.ProxyTag) if (baseTagName == AppConfig.ProxyTag)
{ {
resultOutbounds.AddRange(v2rayConfig.outbounds); resultOutbounds.AddRange(v2rayConfig.outbounds);
v2rayConfig.outbounds = resultOutbounds; v2rayConfig.outbounds = resultOutbounds;
@ -906,7 +907,7 @@ public partial class CoreConfigV2rayService
return await Task.FromResult(0); return await Task.FromResult(0);
} }
private async Task<int> GenChainOutboundsList(List<ProfileItem> nodes, V2rayConfig v2rayConfig, string baseTagName = Global.ProxyTag) private async Task<int> GenChainOutboundsList(List<ProfileItem> nodes, V2rayConfig v2rayConfig, string baseTagName = AppConfig.ProxyTag)
{ {
// Based on actual network flow instead of data packets // Based on actual network flow instead of data packets
var nodesReverse = nodes.AsEnumerable().Reverse().ToList(); var nodesReverse = nodes.AsEnumerable().Reverse().ToList();
@ -914,7 +915,7 @@ public partial class CoreConfigV2rayService
for (var i = 0; i < nodesReverse.Count; i++) for (var i = 0; i < nodesReverse.Count; i++)
{ {
var node = nodesReverse[i]; var node = nodesReverse[i];
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
if (txtOutbound.IsNullOrEmpty()) if (txtOutbound.IsNullOrEmpty())
{ {
break; break;
@ -947,7 +948,7 @@ public partial class CoreConfigV2rayService
resultOutbounds.Add(outbound); resultOutbounds.Add(outbound);
} }
if (baseTagName == Global.ProxyTag) if (baseTagName == AppConfig.ProxyTag)
{ {
resultOutbounds.AddRange(v2rayConfig.outbounds); resultOutbounds.AddRange(v2rayConfig.outbounds);
v2rayConfig.outbounds = resultOutbounds; v2rayConfig.outbounds = resultOutbounds;

View file

@ -6,12 +6,12 @@ public partial class CoreConfigV2rayService
{ {
try try
{ {
if (v2rayConfig.routing?.rules != null) if (v2rayConfig.routing?.rules is not null)
{ {
v2rayConfig.routing.domainStrategy = _config.RoutingBasicItem.DomainStrategy; v2rayConfig.routing.domainStrategy = _config.RoutingBasicItem.DomainStrategy;
var routing = await ConfigHandler.GetDefaultRouting(_config); var routing = await ConfigHandler.GetDefaultRouting(_config);
if (routing != null) if (routing is not null)
{ {
if (routing.DomainStrategy.IsNotEmpty()) if (routing.DomainStrategy.IsNotEmpty())
{ {
@ -47,7 +47,7 @@ public partial class CoreConfigV2rayService
{ {
try try
{ {
if (rule == null) if (rule is null)
{ {
return 0; return 0;
} }
@ -95,7 +95,7 @@ public partial class CoreConfigV2rayService
{ {
it.domain.RemoveAt(k); 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); v2rayConfig.routing.rules.Add(it);
hasDomainIp = true; hasDomainIp = true;
@ -123,7 +123,7 @@ public partial class CoreConfigV2rayService
if (rule.port.IsNotEmpty() if (rule.port.IsNotEmpty()
|| rule.protocol?.Count > 0 || rule.protocol?.Count > 0
|| rule.inboundTag?.Count > 0 || rule.inboundTag?.Count > 0
|| rule.network != null || rule.network is not null
) )
{ {
var it = JsonUtils.DeepCopy(rule); var it = JsonUtils.DeepCopy(rule);
@ -141,21 +141,21 @@ public partial class CoreConfigV2rayService
private async Task<string?> GenRoutingUserRuleOutbound(string outboundTag, V2rayConfig v2rayConfig) private async Task<string?> GenRoutingUserRuleOutbound(string outboundTag, V2rayConfig v2rayConfig)
{ {
if (Global.OutboundTags.Contains(outboundTag)) if (AppConfig.OutboundTags.Contains(outboundTag))
{ {
return outboundTag; return outboundTag;
} }
var node = await AppManager.Instance.GetProfileItemViaRemarks(outboundTag); var node = await AppManager.Instance.GetProfileItemViaRemarks(outboundTag);
if (node == null if (node is null
|| (!Global.XraySupportConfigType.Contains(node.ConfigType) || (!AppConfig.XraySupportConfigType.Contains(node.ConfigType)
&& !node.ConfigType.IsGroupType())) && !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)) if (v2rayConfig.outbounds.Any(p => p.tag == tag))
{ {
return tag; return tag;
@ -168,10 +168,10 @@ public partial class CoreConfigV2rayService
{ {
return tag; return tag;
} }
return Global.ProxyTag; return AppConfig.ProxyTag;
} }
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(AppConfig.V2raySampleOutbound);
var outbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound); var outbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound);
await GenOutbound(node, outbound); await GenOutbound(node, outbound);
outbound.tag = tag; outbound.tag = tag;

View file

@ -26,10 +26,10 @@ public partial class CoreConfigV2rayService
Inbounds4Ray apiInbound = new(); Inbounds4Ray apiInbound = new();
Inboundsettings4Ray apiInboundSettings = new(); Inboundsettings4Ray apiInboundSettings = new();
apiInbound.tag = tag; apiInbound.tag = tag;
apiInbound.listen = Global.Loopback; apiInbound.listen = AppConfig.Loopback;
apiInbound.port = AppManager.Instance.StatePort; apiInbound.port = AppManager.Instance.StatePort;
apiInbound.protocol = Global.InboundAPIProtocol; apiInbound.protocol = AppConfig.InboundAPIProtocol;
apiInboundSettings.address = Global.Loopback; apiInboundSettings.address = AppConfig.Loopback;
apiInbound.settings = apiInboundSettings; apiInbound.settings = apiInboundSettings;
v2rayConfig.inbounds.Add(apiInbound); v2rayConfig.inbounds.Add(apiInbound);
} }

View file

@ -13,14 +13,14 @@ public class DownloadService
private static readonly string _tag = "DownloadService"; private static readonly string _tag = "DownloadService";
public async Task<int> DownloadDataAsync(string url, WebProxy webProxy, int downloadTimeout, Func<bool, string, Task> updateFunc) public static async Task<int> DownloadDataAsync(string url, WebProxy webProxy, int downloadTimeout, Func<bool, string, Task> updateFunc)
{ {
try try
{ {
var progress = new Progress<string>(); var progress = new Progress<string>();
progress.ProgressChanged += (sender, value) => updateFunc?.Invoke(false, $"{value}"); progress.ProgressChanged += (sender, value) => updateFunc?.Invoke(false, $"{value}");
await DownloaderHelper.Instance.DownloadDataAsync4Speed(webProxy, await DownloaderHelper.DownloadDataAsync4Speed(webProxy,
url, url,
progress, progress,
downloadTimeout); downloadTimeout);
@ -28,7 +28,7 @@ public class DownloadService
catch (Exception ex) catch (Exception ex)
{ {
await updateFunc?.Invoke(false, ex.Message); await updateFunc?.Invoke(false, ex.Message);
if (ex.InnerException != null) if (ex.InnerException is not null)
{ {
await updateFunc?.Invoke(false, ex.InnerException.Message); 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}%")); progress.ProgressChanged += (sender, value) => UpdateCompleted?.Invoke(this, new UpdateResult(value > 100, $"...{value}%"));
var webProxy = await GetWebProxy(blProxy); var webProxy = await GetWebProxy(blProxy);
await DownloaderHelper.Instance.DownloadFileAsync(webProxy, await DownloaderHelper.DownloadFileAsync(webProxy,
url, url,
fileName, fileName,
progress, progress,
@ -57,7 +57,7 @@ public class DownloadService
Logging.SaveLog(_tag, ex); Logging.SaveLog(_tag, ex);
Error?.Invoke(this, new ErrorEventArgs(ex)); Error?.Invoke(this, new ErrorEventArgs(ex));
if (ex.InnerException != null) if (ex.InnerException is not null)
{ {
Error?.Invoke(this, new ErrorEventArgs(ex.InnerException)); Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
} }
@ -66,22 +66,22 @@ public class DownloadService
public async Task<string?> UrlRedirectAsync(string url, bool blProxy) public async Task<string?> UrlRedirectAsync(string url, bool blProxy)
{ {
var webRequestHandler = new SocketsHttpHandler using var webRequestHandler = new SocketsHttpHandler
{ {
AllowAutoRedirect = false, AllowAutoRedirect = false,
Proxy = await GetWebProxy(blProxy) 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) if (response.StatusCode == HttpStatusCode.Redirect && response.Headers.Location is not null)
{ {
return response.Headers.Location.ToString(); return response.Headers.Location.ToString();
} }
else else
{ {
Error?.Invoke(this, new ErrorEventArgs(new Exception("StatusCode error: " + response.StatusCode))); Error?.Invoke(this, new ErrorEventArgs(new HttpRequestException($"StatusCode error: {response.StatusCode}", null, response.StatusCode)));
Logging.SaveLog("StatusCode error: " + url); Logging.SaveLog($"StatusCode error: {url}");
return null; return null;
} }
} }
@ -100,7 +100,7 @@ public class DownloadService
{ {
Logging.SaveLog(_tag, ex); Logging.SaveLog(_tag, ex);
Error?.Invoke(this, new ErrorEventArgs(ex)); Error?.Invoke(this, new ErrorEventArgs(ex));
if (ex.InnerException != null) if (ex.InnerException is not null)
{ {
Error?.Invoke(this, new ErrorEventArgs(ex.InnerException)); Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
} }
@ -118,7 +118,7 @@ public class DownloadService
{ {
Logging.SaveLog(_tag, ex); Logging.SaveLog(_tag, ex);
Error?.Invoke(this, new ErrorEventArgs(ex)); Error?.Invoke(this, new ErrorEventArgs(ex));
if (ex.InnerException != null) if (ex.InnerException is not null)
{ {
Error?.Invoke(this, new ErrorEventArgs(ex.InnerException)); Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
} }
@ -139,7 +139,7 @@ public class DownloadService
var client = new HttpClient(new SocketsHttpHandler() var client = new HttpClient(new SocketsHttpHandler()
{ {
Proxy = webProxy, Proxy = webProxy,
UseProxy = webProxy != null UseProxy = webProxy is not null
}); });
if (userAgent.IsNullOrEmpty()) if (userAgent.IsNullOrEmpty())
@ -163,7 +163,7 @@ public class DownloadService
{ {
Logging.SaveLog(_tag, ex); Logging.SaveLog(_tag, ex);
Error?.Invoke(this, new ErrorEventArgs(ex)); Error?.Invoke(this, new ErrorEventArgs(ex));
if (ex.InnerException != null) if (ex.InnerException is not null)
{ {
Error?.Invoke(this, new ErrorEventArgs(ex.InnerException)); Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
} }
@ -185,14 +185,14 @@ public class DownloadService
{ {
userAgent = Utils.GetVersion(false); 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; return result;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.SaveLog(_tag, ex); Logging.SaveLog(_tag, ex);
Error?.Invoke(this, new ErrorEventArgs(ex)); Error?.Invoke(this, new ErrorEventArgs(ex));
if (ex.InnerException != null) if (ex.InnerException is not null)
{ {
Error?.Invoke(this, new ErrorEventArgs(ex.InnerException)); Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
} }
@ -200,22 +200,22 @@ public class DownloadService
return null; return null;
} }
private async Task<WebProxy?> GetWebProxy(bool blProxy) private static async Task<WebProxy?> GetWebProxy(bool blProxy)
{ {
if (!blProxy) if (!blProxy)
{ {
return null; return null;
} }
var port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks); var port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks);
if (await SocketCheck(Global.Loopback, port) == false) if (await SocketCheck(AppConfig.Loopback, port) == false)
{ {
return null; return null;
} }
return new WebProxy($"socks5://{Global.Loopback}:{port}"); return new WebProxy($"socks5://{AppConfig.Loopback}:{port}");
} }
private async Task<bool> SocketCheck(string ip, int port) private static async Task<bool> SocketCheck(string ip, int port)
{ {
try try
{ {

View file

@ -39,7 +39,7 @@ public class ProcessService : IDisposable
EnableRaisingEvents = true EnableRaisingEvents = true
}; };
if (environmentVars != null) if (environmentVars is not null)
{ {
foreach (var kv in environmentVars) foreach (var kv in environmentVars)
{ {

View file

@ -7,6 +7,9 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
private readonly Func<SpeedTestResult, Task>? _updateFunc = updateFunc; private readonly Func<SpeedTestResult, Task>? _updateFunc = updateFunc;
private static readonly ConcurrentBag<string> _lstExitLoop = new(); private static readonly ConcurrentBag<string> _lstExitLoop = new();
private static readonly CompositeFormat _speedtestingTestFailedPart =
CompositeFormat.Parse(ResUI.SpeedtestingTestFailedPart);
public void RunLoop(ESpeedActionType actionType, List<ProfileItem> selecteds) public void RunLoop(ESpeedActionType actionType, List<ProfileItem> selecteds)
{ {
Task.Run(async () => Task.Run(async () =>
@ -128,7 +131,7 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
var responseTime = await GetTcpingTime(it.Address, it.Port); var responseTime = await GetTcpingTime(it.Address, it.Port);
ProfileExManager.Instance.SetTestDelay(it.IndexId, responseTime); ProfileExManager.Instance.SetTestDelay(it.IndexId, responseTime);
await UpdateFunc(it.IndexId, responseTime.ToString()); await UpdateFunc(it.IndexId, responseTime.ToString(CultureInfo.InvariantCulture));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -143,7 +146,7 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
{ {
if (pageSize <= 0) 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); var lstTest = GetTestBatchItem(lstSelected, pageSize);
@ -168,7 +171,7 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
return; return;
} }
await UpdateFunc("", string.Format(ResUI.SpeedtestingTestFailedPart, lstFailed.Count)); await UpdateFunc("", string.Format(CultureInfo.InvariantCulture, _speedtestingTestFailedPart, lstFailed.Count));
if (pageSizeNext > _config.SpeedTestItem.MixedConcurrencyCount) if (pageSizeNext > _config.SpeedTestItem.MixedConcurrencyCount)
{ {
@ -220,7 +223,7 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
} }
finally finally
{ {
if (processService != null) if (processService is not null)
{ {
await processService?.StopAsync(); await processService?.StopAsync();
} }
@ -231,7 +234,6 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
private async Task RunMixedTestAsync(List<ServerTestItem> selecteds, int concurrencyCount, bool blSpeedTest, string exitLoopKey) private async Task RunMixedTestAsync(List<ServerTestItem> selecteds, int concurrencyCount, bool blSpeedTest, string exitLoopKey)
{ {
using var concurrencySemaphore = new SemaphoreSlim(concurrencyCount); using var concurrencySemaphore = new SemaphoreSlim(concurrencyCount);
var downloadHandle = new DownloadService();
List<Task> tasks = new(); List<Task> tasks = new();
foreach (var it in selecteds) foreach (var it in selecteds)
{ {
@ -267,7 +269,7 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
if (delay > 0) if (delay > 0)
{ {
await DoSpeedTest(downloadHandle, it); await DoSpeedTest(it);
} }
else else
{ {
@ -281,7 +283,7 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
} }
finally finally
{ {
if (processService != null) if (processService is not null)
{ {
await processService?.StopAsync(); await processService?.StopAsync();
} }
@ -294,25 +296,24 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
private async Task<int> DoRealPing(ServerTestItem it) private async Task<int> 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); var responseTime = await ConnectionHandler.GetRealPingTime(_config.SpeedTestItem.SpeedPingTestUrl, webProxy, 10);
ProfileExManager.Instance.SetTestDelay(it.IndexId, responseTime); ProfileExManager.Instance.SetTestDelay(it.IndexId, responseTime);
await UpdateFunc(it.IndexId, responseTime.ToString()); await UpdateFunc(it.IndexId, responseTime.ToString(CultureInfo.InvariantCulture));
return responseTime; return responseTime;
} }
private async Task DoSpeedTest(DownloadService downloadHandle, ServerTestItem it) private async Task DoSpeedTest(ServerTestItem it)
{ {
await UpdateFunc(it.IndexId, "", ResUI.Speedtesting); 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 url = _config.SpeedTestItem.SpeedTestUrl;
var timeout = _config.SpeedTestItem.SpeedTestTimeout; 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 (decimal.TryParse(msg, out var dec) && dec > 0)
if (dec > 0)
{ {
ProfileExManager.Instance.SetTestSpeed(it.IndexId, dec); ProfileExManager.Instance.SetTestSpeed(it.IndexId, dec);
} }
@ -320,7 +321,7 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
}); });
} }
private async Task<int> GetTcpingTime(string url, int port) private static async Task<int> GetTcpingTime(string url, int port)
{ {
var responseTime = -1; var responseTime = -1;
@ -350,11 +351,11 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
return responseTime; return responseTime;
} }
private List<List<ServerTestItem>> GetTestBatchItem(List<ServerTestItem> lstSelected, int pageSize) private static List<List<ServerTestItem>> GetTestBatchItem(List<ServerTestItem> lstSelected, int pageSize)
{ {
List<List<ServerTestItem>> lstTest = new(); List<List<ServerTestItem>> lstTest = new();
var lst1 = lstSelected.Where(t => Global.XraySupportConfigType.Contains(t.ConfigType)).ToList(); var lst1 = lstSelected.Where(t => AppConfig.XraySupportConfigType.Contains(t.ConfigType)).ToList();
var lst2 = lstSelected.Where(t => Global.SingboxOnlyConfigType.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++) for (var num = 0; num < (int)Math.Ceiling(lst1.Count * 1.0 / pageSize); num++)
{ {

View file

@ -8,7 +8,7 @@ public class StatisticsSingboxService
private bool _exitFlag; private bool _exitFlag;
private ClientWebSocket? webSocket; private ClientWebSocket? webSocket;
private readonly Func<ServerSpeedItem, Task>? _updateFunc; private readonly Func<ServerSpeedItem, Task>? _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"; private static readonly string _tag = "StatisticsSingboxService";
public StatisticsSingboxService(Config config, Func<ServerSpeedItem, Task> updateFunc) public StatisticsSingboxService(Config config, Func<ServerSpeedItem, Task> updateFunc)
@ -26,7 +26,7 @@ public class StatisticsSingboxService
try try
{ {
if (webSocket == null) if (webSocket is null)
{ {
webSocket = new ClientWebSocket(); webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(Url), CancellationToken.None); await webSocket.ConnectAsync(new Uri(Url), CancellationToken.None);
@ -40,11 +40,8 @@ public class StatisticsSingboxService
try try
{ {
_exitFlag = true; _exitFlag = true;
if (webSocket != null) webSocket?.Abort();
{ webSocket = null;
webSocket.Abort();
webSocket = null;
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -65,7 +62,7 @@ public class StatisticsSingboxService
{ {
continue; continue;
} }
if (webSocket != null) if (webSocket is not null)
{ {
if (webSocket.State is WebSocketState.Aborted or WebSocketState.Closed) if (webSocket.State is WebSocketState.Aborted or WebSocketState.Closed)
{ {
@ -112,7 +109,7 @@ public class StatisticsSingboxService
try try
{ {
var trafficItem = JsonUtils.Deserialize<TrafficItem>(source); var trafficItem = JsonUtils.Deserialize<TrafficItem>(source);
if (trafficItem != null) if (trafficItem is not null)
{ {
up = trafficItem.Up; up = trafficItem.Up;
down = trafficItem.Down; down = trafficItem.Down;

View file

@ -7,7 +7,7 @@ public class StatisticsXrayService
private readonly Config _config; private readonly Config _config;
private bool _exitFlag; private bool _exitFlag;
private readonly Func<ServerSpeedItem, Task>? _updateFunc; private readonly Func<ServerSpeedItem, Task>? _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<ServerSpeedItem, Task> updateFunc) public StatisticsXrayService(Config config, Func<ServerSpeedItem, Task> updateFunc)
{ {
@ -36,7 +36,7 @@ public class StatisticsXrayService
} }
var result = await HttpClientHelper.Instance.TryGetAsync(Url); var result = await HttpClientHelper.Instance.TryGetAsync(Url);
if (result != null) if (result is not null)
{ {
var server = ParseOutput(result) ?? new ServerSpeedItem(); var server = ParseOutput(result) ?? new ServerSpeedItem();
await _updateFunc?.Invoke(server); await _updateFunc?.Invoke(server);
@ -54,7 +54,7 @@ public class StatisticsXrayService
try try
{ {
var source = JsonUtils.Deserialize<V2rayMetricsVars>(result); var source = JsonUtils.Deserialize<V2rayMetricsVars>(result);
if (source?.stats?.outbound == null) if (source?.stats?.outbound is null)
{ {
return null; return null;
} }
@ -63,18 +63,18 @@ public class StatisticsXrayService
foreach (var key in source.stats.outbound.Keys.Cast<string>()) foreach (var key in source.stats.outbound.Keys.Cast<string>())
{ {
var value = source.stats.outbound[key]; var value = source.stats.outbound[key];
if (value == null) if (value is null)
{ {
continue; continue;
} }
var state = JsonUtils.Deserialize<V2rayMetricsVarsLink>(value.ToString()); var state = JsonUtils.Deserialize<V2rayMetricsVarsLink>(value.ToString());
if (key.StartsWith(Global.ProxyTag)) if (key.StartsWith(AppConfig.ProxyTag))
{ {
server.ProxyUp += state.uplink / linkBase; server.ProxyUp += state.uplink / linkBase;
server.ProxyDown += state.downlink / linkBase; server.ProxyDown += state.downlink / linkBase;
} }
else if (key == Global.DirectTag) else if (key == AppConfig.DirectTag)
{ {
server.DirectUp = state.uplink / linkBase; server.DirectUp = state.uplink / linkBase;
server.DirectDown = state.downlink / linkBase; server.DirectDown = state.downlink / linkBase;

View file

@ -136,7 +136,7 @@ public class UpdateService(Config config, Func<bool, string, Task> updateFunc)
if (preRelease) if (preRelease)
{ {
var url = coreInfo?.ReleaseApiUrl; 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()) if (result.IsNullOrEmpty())
{ {
return new UpdateResult(false, ""); return new UpdateResult(false, "");
@ -151,7 +151,7 @@ public class UpdateService(Config config, Func<bool, string, Task> updateFunc)
{ {
var url = Path.Combine(coreInfo.Url, "latest"); var url = Path.Combine(coreInfo.Url, "latest");
var lastUrl = await downloadHandle.UrlRedirectAsync(url, true); var lastUrl = await downloadHandle.UrlRedirectAsync(url, true);
if (lastUrl == null) if (lastUrl is null)
{ {
return new UpdateResult(false, ""); return new UpdateResult(false, "");
} }
@ -327,7 +327,7 @@ public class UpdateService(Config config, Func<bool, string, Task> updateFunc)
private async Task UpdateGeoFiles() private async Task UpdateGeoFiles()
{ {
var geoUrl = string.IsNullOrEmpty(_config?.ConstItem.GeoSourceUrl) var geoUrl = string.IsNullOrEmpty(_config?.ConstItem.GeoSourceUrl)
? Global.GeoUrl ? AppConfig.GeoUrl
: _config.ConstItem.GeoSourceUrl; : _config.ConstItem.GeoSourceUrl;
List<string> files = ["geosite", "geoip"]; List<string> files = ["geosite", "geoip"];
@ -349,7 +349,7 @@ public class UpdateService(Config config, Func<bool, string, Task> updateFunc)
return; return;
} }
foreach (var url in Global.OtherGeoUrls) foreach (var url in AppConfig.OtherGeoUrls)
{ {
var fileName = Path.GetFileName(url); var fileName = Path.GetFileName(url);
var targetPath = Utils.GetBinPath($"{fileName}"); var targetPath = Utils.GetBinPath($"{fileName}");
@ -415,7 +415,7 @@ public class UpdateService(Config config, Func<bool, string, Task> updateFunc)
private async Task UpdateSrsFile(string type, string srsName) private async Task UpdateSrsFile(string type, string srsName)
{ {
var srsUrl = string.IsNullOrEmpty(_config.ConstItem.SrsSourceUrl) var srsUrl = string.IsNullOrEmpty(_config.ConstItem.SrsSourceUrl)
? Global.SingboxRulesetUrl ? AppConfig.SingboxRulesetUrl
: _config.ConstItem.SrsSourceUrl; : _config.ConstItem.SrsSourceUrl;
var fileName = $"{type}-{srsName}.srs"; var fileName = $"{type}-{srsName}.srs";

View file

@ -3,7 +3,7 @@ namespace ServiceLib.Services;
/// <summary> /// <summary>
/// http://stackoverflow.com/questions/6266820/working-example-of-createjobobject-setinformationjobobject-pinvoke-in-net /// http://stackoverflow.com/questions/6266820/working-example-of-createjobobject-setinformationjobobject-pinvoke-in-net
/// </summary> /// </summary>
public sealed class WindowsJobService : IDisposable public sealed partial class WindowsJobService : IDisposable
{ {
private nint handle = nint.Zero; private nint handle = nint.Zero;
@ -99,18 +99,20 @@ public sealed class WindowsJobService : IDisposable
#region Interop #region Interop
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] [LibraryImport("kernel32.dll", EntryPoint = "CreateJobObjectW", StringMarshalling = StringMarshalling.Utf16)]
private static extern nint CreateJobObject(nint a, string? lpName); private static partial nint CreateJobObject(nint a, string? lpName);
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("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)]
[return: MarshalAs(UnmanagedType.Bool)] [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 #endregion Interop
} }

View file

@ -39,12 +39,12 @@ public class AddGroupServerViewModel : MyReactiveObject
public AddGroupServerViewModel(ProfileItem profileItem, Func<EViewAction, object?, Task<bool>>? updateView) public AddGroupServerViewModel(ProfileItem profileItem, Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
var canEditRemove = this.WhenAnyValue( var canEditRemove = this.WhenAnyValue(
x => x.SelectedChild, x => x.SelectedChild,
SelectedChild => SelectedChild != null && !SelectedChild.Remarks.IsNullOrEmpty()); SelectedChild => SelectedChild is not null && !SelectedChild.Remarks.IsNullOrEmpty());
RemoveCmd = ReactiveCommand.CreateFromTask(async () => RemoveCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -97,13 +97,13 @@ public class AddGroupServerViewModel : MyReactiveObject
Filter = profileGroup?.Filter; Filter = profileGroup?.Filter;
var childItemMulti = ProfileGroupItemManager.Instance.GetOrCreateAndMarkDirty(SelectedSource?.IndexId); var childItemMulti = ProfileGroupItemManager.Instance.GetOrCreateAndMarkDirty(SelectedSource?.IndexId);
if (childItemMulti != null) if (childItemMulti is not null)
{ {
var childIndexIds = Utils.String2List(childItemMulti.ChildItems) ?? []; var childIndexIds = Utils.String2List(childItemMulti.ChildItems) ?? [];
foreach (var item in childIndexIds) foreach (var item in childIndexIds)
{ {
var child = await AppManager.Instance.GetProfileItem(item); var child = await AppManager.Instance.GetProfileItem(item);
if (child == null) if (child is null)
{ {
continue; continue;
} }
@ -114,14 +114,14 @@ public class AddGroupServerViewModel : MyReactiveObject
public async Task ChildRemoveAsync() public async Task ChildRemoveAsync()
{ {
if (SelectedChild == null || SelectedChild.IndexId.IsNullOrEmpty()) if (SelectedChild is null || SelectedChild.IndexId.IsNullOrEmpty())
{ {
NoticeManager.Instance.Enqueue(ResUI.PleaseSelectServer); NoticeManager.Instance.Enqueue(ResUI.PleaseSelectServer);
return; return;
} }
foreach (var it in SelectedChildren ?? [SelectedChild]) foreach (var it in SelectedChildren ?? [SelectedChild])
{ {
if (it != null) if (it is not null)
{ {
ChildItemsObs.Remove(it); ChildItemsObs.Remove(it);
} }
@ -131,7 +131,7 @@ public class AddGroupServerViewModel : MyReactiveObject
public async Task MoveServer(EMove eMove) public async Task MoveServer(EMove eMove)
{ {
if (SelectedChild == null || SelectedChild.IndexId.IsNullOrEmpty()) if (SelectedChild is null || SelectedChild.IndexId.IsNullOrEmpty())
{ {
NoticeManager.Instance.Enqueue(ResUI.PleaseSelectServer); NoticeManager.Instance.Enqueue(ResUI.PleaseSelectServer);
return; return;
@ -236,10 +236,10 @@ public class AddGroupServerViewModel : MyReactiveObject
return; return;
} }
if (await ConfigHandler.AddGroupServerCommon(_config, SelectedSource, profileGroup, true) == 0) if (await ConfigHandler.AddGroupServerCommon(SelectedSource, profileGroup, true) == 0)
{ {
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); UpdateView?.Invoke(EViewAction.CloseWindow, null);
} }
else else
{ {

View file

@ -15,12 +15,12 @@ public class AddServer2ViewModel : MyReactiveObject
public AddServer2ViewModel(ProfileItem profileItem, Func<EViewAction, object?, Task<bool>>? updateView) public AddServer2ViewModel(ProfileItem profileItem, Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
BrowseServerCmd = ReactiveCommand.CreateFromTask(async () => BrowseServerCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
_updateView?.Invoke(EViewAction.BrowseServer, null); UpdateView?.Invoke(EViewAction.BrowseServer, null);
await Task.CompletedTask; await Task.CompletedTask;
}); });
EditServerCmd = ReactiveCommand.CreateFromTask(async () => EditServerCmd = ReactiveCommand.CreateFromTask(async () =>
@ -52,10 +52,10 @@ public class AddServer2ViewModel : MyReactiveObject
} }
SelectedSource.CoreType = CoreType.IsNullOrEmpty() ? null : (ECoreType)Enum.Parse(typeof(ECoreType), CoreType); 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); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); UpdateView?.Invoke(EViewAction.CloseWindow, null);
} }
else else
{ {
@ -73,7 +73,7 @@ public class AddServer2ViewModel : MyReactiveObject
var item = await AppManager.Instance.GetProfileItem(SelectedSource.IndexId); var item = await AppManager.Instance.GetProfileItem(SelectedSource.IndexId);
item ??= SelectedSource; item ??= SelectedSource;
item.Address = fileName; item.Address = fileName;
if (await ConfigHandler.AddCustomServer(_config, item, false) == 0) if (await ConfigHandler.AddCustomServer(Config, item, false) == 0)
{ {
NoticeManager.Instance.Enqueue(ResUI.SuccessfullyImportedCustomServer); NoticeManager.Instance.Enqueue(ResUI.SuccessfullyImportedCustomServer);
if (item.IndexId.IsNotEmpty()) if (item.IndexId.IsNotEmpty())

View file

@ -23,8 +23,8 @@ public class AddServerViewModel : MyReactiveObject
public AddServerViewModel(ProfileItem profileItem, Func<EViewAction, object?, Task<bool>>? updateView) public AddServerViewModel(ProfileItem profileItem, Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
FetchCertCmd = ReactiveCommand.CreateFromTask(async () => FetchCertCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -50,8 +50,8 @@ public class AddServerViewModel : MyReactiveObject
if (profileItem.IndexId.IsNullOrEmpty()) if (profileItem.IndexId.IsNullOrEmpty())
{ {
profileItem.Network = Global.DefaultNetwork; profileItem.Network = AppConfig.DefaultNetwork;
profileItem.HeaderType = Global.None; profileItem.HeaderType = AppConfig.None;
profileItem.RequestHost = ""; profileItem.RequestHost = "";
profileItem.StreamSecurity = ""; profileItem.StreamSecurity = "";
SelectedSource = profileItem; SelectedSource = profileItem;
@ -80,7 +80,7 @@ public class AddServerViewModel : MyReactiveObject
} }
var port = SelectedSource.Port.ToString(); var port = SelectedSource.Port.ToString();
if (port.IsNullOrEmpty() || !Utils.IsNumeric(port) 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); NoticeManager.Instance.Enqueue(ResUI.FillCorrectServerPort);
return; return;
@ -110,10 +110,10 @@ public class AddServerViewModel : MyReactiveObject
SelectedSource.Cert = Cert.IsNullOrEmpty() ? string.Empty : Cert; SelectedSource.Cert = Cert.IsNullOrEmpty() ? string.Empty : Cert;
SelectedSource.CertSha = CertSha.IsNullOrEmpty() ? string.Empty : CertSha; 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); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); UpdateView?.Invoke(EViewAction.CloseWindow, null);
} }
else else
{ {
@ -156,7 +156,7 @@ public class AddServerViewModel : MyReactiveObject
private async Task FetchCert() private async Task FetchCert()
{ {
if (SelectedSource.StreamSecurity != Global.StreamSecurity) if (SelectedSource.StreamSecurity != AppConfig.StreamSecurity)
{ {
return; return;
} }
@ -186,7 +186,7 @@ public class AddServerViewModel : MyReactiveObject
private async Task FetchCertChain() private async Task FetchCertChain()
{ {
if (SelectedSource.StreamSecurity != Global.StreamSecurity) if (SelectedSource.StreamSecurity != AppConfig.StreamSecurity)
{ {
return; return;
} }

View file

@ -17,8 +17,8 @@ public class BackupAndRestoreViewModel : MyReactiveObject
public BackupAndRestoreViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public BackupAndRestoreViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
WebDavCheckCmd = ReactiveCommand.CreateFromTask(async () => WebDavCheckCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -33,7 +33,7 @@ public class BackupAndRestoreViewModel : MyReactiveObject
await RemoteRestore(); await RemoteRestore();
}); });
SelectedSource = JsonUtils.DeepCopy(_config.WebDavItem); SelectedSource = JsonUtils.DeepCopy(Config.WebDavItem);
} }
private void DisplayOperationMsg(string msg = "") private void DisplayOperationMsg(string msg = "")
@ -44,8 +44,8 @@ public class BackupAndRestoreViewModel : MyReactiveObject
private async Task WebDavCheck() private async Task WebDavCheck()
{ {
DisplayOperationMsg(); DisplayOperationMsg();
_config.WebDavItem = SelectedSource; Config.WebDavItem = SelectedSource;
_ = await ConfigHandler.SaveConfig(_config); _ = await ConfigHandler.SaveConfig(Config);
var result = await WebDavManager.Instance.CheckConnection(); var result = await WebDavManager.Instance.CheckConnection();
if (result) if (result)
@ -145,7 +145,7 @@ public class BackupAndRestoreViewModel : MyReactiveObject
{ {
if (Utils.UpgradeAppExists(out var upgradeFileName)) if (Utils.UpgradeAppExists(out var upgradeFileName))
{ {
_ = ProcUtils.ProcessStart(upgradeFileName, Global.RebootAs, Utils.StartupPath()); _ = ProcUtils.ProcessStart(upgradeFileName, AppConfig.RebootAs, Utils.StartupPath());
} }
} }
AppManager.Instance.Shutdown(true); AppManager.Instance.Shutdown(true);

View file

@ -13,22 +13,22 @@ public class CheckUpdateViewModel : MyReactiveObject
public CheckUpdateViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public CheckUpdateViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; base.UpdateView = updateView;
CheckUpdateCmd = ReactiveCommand.CreateFromTask(CheckUpdate); CheckUpdateCmd = ReactiveCommand.CreateFromTask(CheckUpdate);
CheckUpdateCmd.ThrownExceptions.Subscribe(ex => CheckUpdateCmd.ThrownExceptions.Subscribe(ex =>
{ {
Logging.SaveLog(_tag, ex); Logging.SaveLog(_tag, ex);
_ = UpdateView(_v2rayN, ex.Message); _ = UpdateViewAsync(_v2rayN, ex.Message);
}); });
EnableCheckPreReleaseUpdate = _config.CheckUpdateItem.CheckPreReleaseUpdate; EnableCheckPreReleaseUpdate = Config.CheckUpdateItem.CheckPreReleaseUpdate;
this.WhenAnyValue( this.WhenAnyValue(
x => x.EnableCheckPreReleaseUpdate, x => x.EnableCheckPreReleaseUpdate,
y => y == true) y => y == true)
.Subscribe(c => _config.CheckUpdateItem.CheckPreReleaseUpdate = EnableCheckPreReleaseUpdate); .Subscribe(c => Config.CheckUpdateItem.CheckPreReleaseUpdate = EnableCheckPreReleaseUpdate);
RefreshCheckUpdateItems(); RefreshCheckUpdateItems();
} }
@ -65,7 +65,7 @@ public class CheckUpdateViewModel : MyReactiveObject
return new() return new()
{ {
IsSelected = _config.CheckUpdateItem.SelectedCoreTypes?.Contains(coreType) ?? true, IsSelected = Config.CheckUpdateItem.SelectedCoreTypes?.Contains(coreType) ?? true,
CoreType = coreType, CoreType = coreType,
Remarks = ResUI.menuCheckUpdate, Remarks = ResUI.menuCheckUpdate,
}; };
@ -73,8 +73,8 @@ public class CheckUpdateViewModel : MyReactiveObject
private async Task SaveSelectedCoreTypes() private async Task SaveSelectedCoreTypes()
{ {
_config.CheckUpdateItem.SelectedCoreTypes = CheckUpdateModels.Where(t => t.IsSelected == true).Select(t => t.CoreType ?? "").ToList(); Config.CheckUpdateItem.SelectedCoreTypes = CheckUpdateModels.Where(t => t.IsSelected == true).Select(t => t.CoreType ?? "").ToList();
await ConfigHandler.SaveConfig(_config); await ConfigHandler.SaveConfig(Config);
} }
private async Task CheckUpdate() private async Task CheckUpdate()
@ -97,7 +97,7 @@ public class CheckUpdateViewModel : MyReactiveObject
continue; continue;
} }
await UpdateView(item.CoreType, "..."); await UpdateViewAsync(item.CoreType, "...");
if (item.CoreType == _geo) if (item.CoreType == _geo)
{ {
await CheckUpdateGeo(); await CheckUpdateGeo();
@ -106,7 +106,7 @@ public class CheckUpdateViewModel : MyReactiveObject
{ {
if (Utils.IsPackagedInstall()) if (Utils.IsPackagedInstall())
{ {
await UpdateView(_v2rayN, "Not Support"); await UpdateViewAsync(_v2rayN, "Not Support");
continue; continue;
} }
await CheckUpdateN(EnableCheckPreReleaseUpdate); await CheckUpdateN(EnableCheckPreReleaseUpdate);
@ -127,7 +127,7 @@ public class CheckUpdateViewModel : MyReactiveObject
private void UpdatedPlusPlus(string coreType, string fileName) private void UpdatedPlusPlus(string coreType, string fileName)
{ {
var item = _lstUpdated.FirstOrDefault(x => x.CoreType == coreType); var item = _lstUpdated.FirstOrDefault(x => x.CoreType == coreType);
if (item == null) if (item is null)
{ {
return; return;
} }
@ -142,13 +142,13 @@ public class CheckUpdateViewModel : MyReactiveObject
{ {
async Task _updateUI(bool success, string msg) async Task _updateUI(bool success, string msg)
{ {
await UpdateView(_geo, msg); await UpdateViewAsync(_geo, msg);
if (success) if (success)
{ {
UpdatedPlusPlus(_geo, ""); UpdatedPlusPlus(_geo, "");
} }
} }
await new UpdateService(_config, _updateUI).UpdateGeoFileAll() await new UpdateService(Config, _updateUI).UpdateGeoFileAll()
.ContinueWith(t => UpdatedPlusPlus(_geo, "")); .ContinueWith(t => UpdatedPlusPlus(_geo, ""));
} }
@ -156,14 +156,14 @@ public class CheckUpdateViewModel : MyReactiveObject
{ {
async Task _updateUI(bool success, string msg) async Task _updateUI(bool success, string msg)
{ {
await UpdateView(_v2rayN, msg); await UpdateViewAsync(_v2rayN, msg);
if (success) if (success)
{ {
await UpdateView(_v2rayN, ResUI.OperationSuccess); await UpdateViewAsync(_v2rayN, ResUI.OperationSuccess);
UpdatedPlusPlus(_v2rayN, msg); UpdatedPlusPlus(_v2rayN, msg);
} }
} }
await new UpdateService(_config, _updateUI).CheckUpdateGuiN(preRelease) await new UpdateService(Config, _updateUI).CheckUpdateGuiN(preRelease)
.ContinueWith(t => UpdatedPlusPlus(_v2rayN, "")); .ContinueWith(t => UpdatedPlusPlus(_v2rayN, ""));
} }
@ -171,16 +171,16 @@ public class CheckUpdateViewModel : MyReactiveObject
{ {
async Task _updateUI(bool success, string msg) async Task _updateUI(bool success, string msg)
{ {
await UpdateView(model.CoreType, msg); await UpdateViewAsync(model.CoreType, msg);
if (success) if (success)
{ {
await UpdateView(model.CoreType, ResUI.MsgUpdateV2rayCoreSuccessfullyMore); await UpdateViewAsync(model.CoreType, ResUI.MsgUpdateV2rayCoreSuccessfullyMore);
UpdatedPlusPlus(model.CoreType, msg); UpdatedPlusPlus(model.CoreType, msg);
} }
} }
var type = (ECoreType)Enum.Parse(typeof(ECoreType), model.CoreType); 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, "")); .ContinueWith(t => UpdatedPlusPlus(model.CoreType, ""));
} }
@ -235,7 +235,7 @@ public class CheckUpdateViewModel : MyReactiveObject
} }
if (!Utils.UpgradeAppExists(out var upgradeFileName)) if (!Utils.UpgradeAppExists(out var upgradeFileName))
{ {
await UpdateView(_v2rayN, ResUI.UpgradeAppNotExistTip); await UpdateViewAsync(_v2rayN, ResUI.UpgradeAppNotExistTip);
NoticeManager.Instance.SendMessageAndEnqueue(ResUI.UpgradeAppNotExistTip); NoticeManager.Instance.SendMessageAndEnqueue(ResUI.UpgradeAppNotExistTip);
Logging.SaveLog("UpgradeApp does not exist"); Logging.SaveLog("UpgradeApp does not exist");
return; return;
@ -249,7 +249,7 @@ public class CheckUpdateViewModel : MyReactiveObject
} }
catch (Exception ex) 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)) 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() var item = new CheckUpdateModel()
{ {
@ -328,7 +328,7 @@ public class CheckUpdateViewModel : MyReactiveObject
public async Task UpdateViewResult(CheckUpdateModel model) public async Task UpdateViewResult(CheckUpdateModel model)
{ {
var found = CheckUpdateModels.FirstOrDefault(t => t.CoreType == model.CoreType); var found = CheckUpdateModels.FirstOrDefault(t => t.CoreType == model.CoreType);
if (found == null) if (found is null)
{ {
return; return;
} }

View file

@ -18,18 +18,18 @@ public class ClashConnectionsViewModel : MyReactiveObject
public ClashConnectionsViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public ClashConnectionsViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
AutoRefresh = _config.ClashUIItem.ConnectionsAutoRefresh; AutoRefresh = Config.ClashUIItem.ConnectionsAutoRefresh;
var canEditRemove = this.WhenAnyValue( var canEditRemove = this.WhenAnyValue(
x => x.SelectedSource, x => x.SelectedSource,
selectedSource => selectedSource != null && selectedSource.Id.IsNotEmpty()); selectedSource => selectedSource is not null && selectedSource.Id.IsNotEmpty());
this.WhenAnyValue( this.WhenAnyValue(
x => x.AutoRefresh, x => x.AutoRefresh,
y => y == true) y => y == true)
.Subscribe(c => { _config.ClashUIItem.ConnectionsAutoRefresh = AutoRefresh; }); .Subscribe(c => { Config.ClashUIItem.ConnectionsAutoRefresh = AutoRefresh; });
ConnectionCloseCmd = ReactiveCommand.CreateFromTask(async () => ConnectionCloseCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
await ClashConnectionClose(false); await ClashConnectionClose(false);
@ -51,7 +51,7 @@ public class ClashConnectionsViewModel : MyReactiveObject
private async Task GetClashConnections() private async Task GetClashConnections()
{ {
var ret = await ClashApiManager.Instance.GetClashConnectionsAsync(); var ret = await ClashApiManager.Instance.GetClashConnectionsAsync();
if (ret == null) if (ret is null)
{ {
return; return;
} }
@ -133,12 +133,12 @@ public class ClashConnectionsViewModel : MyReactiveObject
continue; continue;
} }
if (_config.ClashUIItem.ConnectionsRefreshInterval <= 0) if (Config.ClashUIItem.ConnectionsRefreshInterval <= 0)
{ {
continue; continue;
} }
if (numOfExecuted % _config.ClashUIItem.ConnectionsRefreshInterval != 0) if (numOfExecuted % Config.ClashUIItem.ConnectionsRefreshInterval != 0)
{ {
continue; continue;
} }

View file

@ -35,8 +35,8 @@ public class ClashProxiesViewModel : MyReactiveObject
public ClashProxiesViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public ClashProxiesViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
ProxiesReloadCmd = ReactiveCommand.CreateFromTask(async () => ProxiesReloadCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -58,15 +58,15 @@ public class ClashProxiesViewModel : MyReactiveObject
SelectedGroup = new(); SelectedGroup = new();
SelectedDetail = new(); SelectedDetail = new();
AutoRefresh = _config.ClashUIItem.ProxiesAutoRefresh; AutoRefresh = Config.ClashUIItem.ProxiesAutoRefresh;
SortingSelected = _config.ClashUIItem.ProxiesSorting; SortingSelected = Config.ClashUIItem.ProxiesSorting;
RuleModeSelected = (int)_config.ClashUIItem.RuleMode; RuleModeSelected = (int)Config.ClashUIItem.RuleMode;
#region WhenAnyValue && ReactiveCommand #region WhenAnyValue && ReactiveCommand
this.WhenAnyValue( this.WhenAnyValue(
x => x.SelectedGroup, x => x.SelectedGroup,
y => y != null && y.Name.IsNotEmpty()) y => y is not null && y.Name.IsNotEmpty())
.Subscribe(c => RefreshProxyDetails(c)); .Subscribe(c => RefreshProxyDetails(c));
this.WhenAnyValue( this.WhenAnyValue(
@ -82,7 +82,7 @@ public class ClashProxiesViewModel : MyReactiveObject
this.WhenAnyValue( this.WhenAnyValue(
x => x.AutoRefresh, x => x.AutoRefresh,
y => y == true) y => y == true)
.Subscribe(c => { _config.ClashUIItem.ProxiesAutoRefresh = AutoRefresh; }); .Subscribe(c => { Config.ClashUIItem.ProxiesAutoRefresh = AutoRefresh; });
#endregion WhenAnyValue && ReactiveCommand #endregion WhenAnyValue && ReactiveCommand
@ -109,7 +109,7 @@ public class ClashProxiesViewModel : MyReactiveObject
{ {
return; return;
} }
if (_config.ClashUIItem.RuleMode == (ERuleMode)RuleModeSelected) if (Config.ClashUIItem.RuleMode == (ERuleMode)RuleModeSelected)
{ {
return; return;
} }
@ -118,7 +118,7 @@ public class ClashProxiesViewModel : MyReactiveObject
public async Task SetRuleModeCheck(ERuleMode mode) public async Task SetRuleModeCheck(ERuleMode mode)
{ {
if (_config.ClashUIItem.RuleMode == mode) if (Config.ClashUIItem.RuleMode == mode)
{ {
return; return;
} }
@ -131,9 +131,9 @@ public class ClashProxiesViewModel : MyReactiveObject
{ {
return; return;
} }
if (SortingSelected != _config.ClashUIItem.ProxiesSorting) if (SortingSelected != Config.ClashUIItem.ProxiesSorting)
{ {
_config.ClashUIItem.ProxiesSorting = SortingSelected; Config.ClashUIItem.ProxiesSorting = SortingSelected;
} }
RefreshProxyDetails(c); RefreshProxyDetails(c);
@ -149,7 +149,7 @@ public class ClashProxiesViewModel : MyReactiveObject
private async Task SetRuleMode(ERuleMode mode) private async Task SetRuleMode(ERuleMode mode)
{ {
_config.ClashUIItem.RuleMode = mode; Config.ClashUIItem.RuleMode = mode;
if (mode != ERuleMode.Unchanged) if (mode != ERuleMode.Unchanged)
{ {
@ -164,7 +164,7 @@ public class ClashProxiesViewModel : MyReactiveObject
private async Task GetClashProxies(bool refreshUI) private async Task GetClashProxies(bool refreshUI)
{ {
var ret = await ClashApiManager.Instance.GetClashProxiesAsync(); var ret = await ClashApiManager.Instance.GetClashProxiesAsync();
if (ret?.Item1 == null || ret.Item2 == null) if (ret?.Item1 is null || ret.Item2 is null)
{ {
return; return;
} }
@ -179,7 +179,7 @@ public class ClashProxiesViewModel : MyReactiveObject
public async Task RefreshProxyGroups() public async Task RefreshProxyGroups()
{ {
if (_proxies == null) if (_proxies is null)
{ {
return; return;
} }
@ -188,7 +188,7 @@ public class ClashProxiesViewModel : MyReactiveObject
ProxyGroups.Clear(); ProxyGroups.Clear();
var proxyGroups = ClashApiManager.Instance.GetClashProxyGroups(); var proxyGroups = ClashApiManager.Instance.GetClashProxyGroups();
if (proxyGroups != null && proxyGroups.Count > 0) if (proxyGroups is not null && proxyGroups.Count > 0)
{ {
foreach (var it in proxyGroups) foreach (var it in proxyGroups)
{ {
@ -197,7 +197,7 @@ public class ClashProxiesViewModel : MyReactiveObject
continue; continue;
} }
var item = _proxies[it.name]; var item = _proxies[it.name];
if (!Global.allowSelectType.Contains(item.type.ToLower())) if (!AppConfig.allowSelectType.Contains(item.type.ToLower()))
{ {
continue; continue;
} }
@ -213,12 +213,12 @@ public class ClashProxiesViewModel : MyReactiveObject
//from api //from api
foreach (var kv in _proxies) foreach (var kv in _proxies)
{ {
if (!Global.allowSelectType.Contains(kv.Value.type.ToLower())) if (!AppConfig.allowSelectType.Contains(kv.Value.type.ToLower()))
{ {
continue; continue;
} }
var item = ProxyGroups.FirstOrDefault(t => t.Name == kv.Key); var item = ProxyGroups.FirstOrDefault(t => t.Name == kv.Key);
if (item != null && item.Name.IsNotEmpty()) if (item is not null && item.Name.IsNotEmpty())
{ {
continue; 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); SelectedGroup = ProxyGroups.FirstOrDefault(t => t.Name == selectedName);
} }
@ -260,13 +260,13 @@ public class ClashProxiesViewModel : MyReactiveObject
{ {
return; return;
} }
if (_proxies == null) if (_proxies is null)
{ {
return; return;
} }
_proxies.TryGetValue(name, out var proxy); _proxies.TryGetValue(name, out var proxy);
if (proxy?.all == null) if (proxy?.all is null)
{ {
return; return;
} }
@ -274,7 +274,7 @@ public class ClashProxiesViewModel : MyReactiveObject
foreach (var item in proxy.all) foreach (var item in proxy.all)
{ {
var proxy2 = TryGetProxy(item); var proxy2 = TryGetProxy(item);
if (proxy2 == null) if (proxy2 is null)
{ {
continue; continue;
} }
@ -308,24 +308,24 @@ public class ClashProxiesViewModel : MyReactiveObject
private ProxiesItem? TryGetProxy(string name) private ProxiesItem? TryGetProxy(string name)
{ {
if (_proxies == null) if (_proxies is null)
{ {
return null; return null;
} }
_proxies.TryGetValue(name, out var proxy2); _proxies.TryGetValue(name, out var proxy2);
if (proxy2 != null) if (proxy2 is not null)
{ {
return proxy2; return proxy2;
} }
//from providers //from providers
if (_providers != null) if (_providers is not null)
{ {
foreach (var kv in _providers) 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); var proxy3 = kv.Value.proxies.FirstOrDefault(t => t.name == name);
if (proxy3 != null) if (proxy3 is not null)
{ {
return proxy3; return proxy3;
} }
@ -337,11 +337,11 @@ public class ClashProxiesViewModel : MyReactiveObject
public async Task SetActiveProxy() public async Task SetActiveProxy()
{ {
if (SelectedGroup == null || SelectedGroup.Name.IsNullOrEmpty()) if (SelectedGroup is null || SelectedGroup.Name.IsNullOrEmpty())
{ {
return; return;
} }
if (SelectedDetail == null || SelectedDetail.Name.IsNullOrEmpty()) if (SelectedDetail is null || SelectedDetail.Name.IsNullOrEmpty())
{ {
return; return;
} }
@ -356,7 +356,7 @@ public class ClashProxiesViewModel : MyReactiveObject
return; return;
} }
var selectedProxy = TryGetProxy(name); var selectedProxy = TryGetProxy(name);
if (selectedProxy == null || selectedProxy.type != "Selector") if (selectedProxy is null || selectedProxy.type != "Selector")
{ {
NoticeManager.Instance.Enqueue(ResUI.OperationFailed); NoticeManager.Instance.Enqueue(ResUI.OperationFailed);
return; return;
@ -366,7 +366,7 @@ public class ClashProxiesViewModel : MyReactiveObject
selectedProxy.now = nameNode; selectedProxy.now = nameNode;
var group = ProxyGroups.FirstOrDefault(it => it.Name == SelectedGroup.Name); var group = ProxyGroups.FirstOrDefault(it => it.Name == SelectedGroup.Name);
if (group != null) if (group is not null)
{ {
group.Now = nameNode; group.Now = nameNode;
var group2 = JsonUtils.DeepCopy(group); var group2 = JsonUtils.DeepCopy(group);
@ -381,7 +381,7 @@ public class ClashProxiesViewModel : MyReactiveObject
{ {
ClashApiManager.Instance.ClashProxiesDelayTest(blAll, ProxyDetails.ToList(), async (item, result) => ClashApiManager.Instance.ClashProxiesDelayTest(blAll, ProxyDetails.ToList(), async (item, result) =>
{ {
if (item == null || result.IsNullOrEmpty()) if (item is null || result.IsNullOrEmpty())
{ {
return; return;
} }
@ -400,18 +400,18 @@ public class ClashProxiesViewModel : MyReactiveObject
public async Task ProxiesDelayTestResult(SpeedTestResult result) public async Task ProxiesDelayTestResult(SpeedTestResult result)
{ {
var detail = ProxyDetails.FirstOrDefault(it => it.Name == result.IndexId); var detail = ProxyDetails.FirstOrDefault(it => it.Name == result.IndexId);
if (detail == null) if (detail is null)
{ {
return; return;
} }
var dicResult = JsonUtils.Deserialize<Dictionary<string, object>>(result.Delay); var dicResult = JsonUtils.Deserialize<Dictionary<string, object>>(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.Delay = Convert.ToInt32(value.ToString());
detail.DelayName = $"{detail.Delay}ms"; 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.Delay = _delayTimeout;
detail.DelayName = $"{value1}"; detail.DelayName = $"{value1}";
@ -441,11 +441,11 @@ public class ClashProxiesViewModel : MyReactiveObject
{ {
continue; continue;
} }
if (_config.ClashUIItem.ProxiesAutoDelayTestInterval <= 0) if (Config.ClashUIItem.ProxiesAutoDelayTestInterval <= 0)
{ {
continue; continue;
} }
if (numOfExecuted % _config.ClashUIItem.ProxiesAutoDelayTestInterval != 0) if (numOfExecuted % Config.ClashUIItem.ProxiesAutoDelayTestInterval != 0)
{ {
continue; continue;
} }

View file

@ -35,20 +35,20 @@ public class DNSSettingViewModel : MyReactiveObject
public DNSSettingViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public DNSSettingViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
SaveCmd = ReactiveCommand.CreateFromTask(SaveSettingAsync); SaveCmd = ReactiveCommand.CreateFromTask(SaveSettingAsync);
ImportDefConfig4V2rayCompatibleCmd = ReactiveCommand.CreateFromTask(async () => ImportDefConfig4V2rayCompatibleCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
NormalDNSCompatible = EmbedUtils.GetEmbedText(Global.DNSV2rayNormalFileName); NormalDNSCompatible = EmbedUtils.GetEmbedText(AppConfig.DNSV2rayNormalFileName);
await Task.CompletedTask; await Task.CompletedTask;
}); });
ImportDefConfig4SingboxCompatibleCmd = ReactiveCommand.CreateFromTask(async () => ImportDefConfig4SingboxCompatibleCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
NormalDNS2Compatible = EmbedUtils.GetEmbedText(Global.DNSSingboxNormalFileName); NormalDNS2Compatible = EmbedUtils.GetEmbedText(AppConfig.DNSSingboxNormalFileName);
TunDNS2Compatible = EmbedUtils.GetEmbedText(Global.TunSingboxDNSFileName); TunDNS2Compatible = EmbedUtils.GetEmbedText(AppConfig.TunSingboxDNSFileName);
await Task.CompletedTask; await Task.CompletedTask;
}); });
@ -61,8 +61,8 @@ public class DNSSettingViewModel : MyReactiveObject
private async Task Init() private async Task Init()
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
var item = _config.SimpleDNSItem; var item = Config.SimpleDNSItem;
UseSystemHosts = item.UseSystemHosts; UseSystemHosts = item.UseSystemHosts;
AddCommonHosts = item.AddCommonHosts; AddCommonHosts = item.AddCommonHosts;
FakeIP = item.FakeIP; FakeIP = item.FakeIP;
@ -93,23 +93,23 @@ public class DNSSettingViewModel : MyReactiveObject
private async Task SaveSettingAsync() private async Task SaveSettingAsync()
{ {
_config.SimpleDNSItem.UseSystemHosts = UseSystemHosts; Config.SimpleDNSItem.UseSystemHosts = UseSystemHosts;
_config.SimpleDNSItem.AddCommonHosts = AddCommonHosts; Config.SimpleDNSItem.AddCommonHosts = AddCommonHosts;
_config.SimpleDNSItem.FakeIP = FakeIP; Config.SimpleDNSItem.FakeIP = FakeIP;
_config.SimpleDNSItem.BlockBindingQuery = BlockBindingQuery; Config.SimpleDNSItem.BlockBindingQuery = BlockBindingQuery;
_config.SimpleDNSItem.DirectDNS = DirectDNS; Config.SimpleDNSItem.DirectDNS = DirectDNS;
_config.SimpleDNSItem.RemoteDNS = RemoteDNS; Config.SimpleDNSItem.RemoteDNS = RemoteDNS;
_config.SimpleDNSItem.BootstrapDNS = BootstrapDNS; Config.SimpleDNSItem.BootstrapDNS = BootstrapDNS;
_config.SimpleDNSItem.RayStrategy4Freedom = RayStrategy4Freedom; Config.SimpleDNSItem.RayStrategy4Freedom = RayStrategy4Freedom;
_config.SimpleDNSItem.SingboxStrategy4Direct = SingboxStrategy4Direct; Config.SimpleDNSItem.SingboxStrategy4Direct = SingboxStrategy4Direct;
_config.SimpleDNSItem.SingboxStrategy4Proxy = SingboxStrategy4Proxy; Config.SimpleDNSItem.SingboxStrategy4Proxy = SingboxStrategy4Proxy;
_config.SimpleDNSItem.Hosts = Hosts; Config.SimpleDNSItem.Hosts = Hosts;
_config.SimpleDNSItem.DirectExpectedIPs = DirectExpectedIPs; Config.SimpleDNSItem.DirectExpectedIPs = DirectExpectedIPs;
if (NormalDNSCompatible.IsNotEmpty()) if (NormalDNSCompatible.IsNotEmpty())
{ {
var obj = JsonUtils.ParseJson(NormalDNSCompatible); var obj = JsonUtils.ParseJson(NormalDNSCompatible);
if (obj != null && obj["servers"] != null) if (obj is not null && obj["servers"] is not null)
{ {
} }
else else
@ -124,7 +124,7 @@ public class DNSSettingViewModel : MyReactiveObject
if (NormalDNS2Compatible.IsNotEmpty()) if (NormalDNS2Compatible.IsNotEmpty())
{ {
var obj2 = JsonUtils.Deserialize<Dns4Sbox>(NormalDNS2Compatible); var obj2 = JsonUtils.Deserialize<Dns4Sbox>(NormalDNS2Compatible);
if (obj2 == null) if (obj2 is null)
{ {
NoticeManager.Instance.Enqueue(ResUI.FillCorrectDNSText); NoticeManager.Instance.Enqueue(ResUI.FillCorrectDNSText);
return; return;
@ -133,7 +133,7 @@ public class DNSSettingViewModel : MyReactiveObject
if (TunDNS2Compatible.IsNotEmpty()) if (TunDNS2Compatible.IsNotEmpty())
{ {
var obj2 = JsonUtils.Deserialize<Dns4Sbox>(TunDNS2Compatible); var obj2 = JsonUtils.Deserialize<Dns4Sbox>(TunDNS2Compatible);
if (obj2 == null) if (obj2 is null)
{ {
NoticeManager.Instance.Enqueue(ResUI.FillCorrectDNSText); NoticeManager.Instance.Enqueue(ResUI.FillCorrectDNSText);
return; return;
@ -146,7 +146,7 @@ public class DNSSettingViewModel : MyReactiveObject
item1.DomainDNSAddress = DomainDNSAddressCompatible; item1.DomainDNSAddress = DomainDNSAddressCompatible;
item1.UseSystemHosts = UseSystemHostsCompatible; item1.UseSystemHosts = UseSystemHostsCompatible;
item1.NormalDNS = NormalDNSCompatible; item1.NormalDNS = NormalDNSCompatible;
await ConfigHandler.SaveDNSItems(_config, item1); await ConfigHandler.SaveDNSItems(Config, item1);
var item2 = await AppManager.Instance.GetDNSItem(ECoreType.sing_box); var item2 = await AppManager.Instance.GetDNSItem(ECoreType.sing_box);
item2.Enabled = SBCustomDNSEnableCompatible; item2.Enabled = SBCustomDNSEnableCompatible;
@ -154,12 +154,12 @@ public class DNSSettingViewModel : MyReactiveObject
item2.DomainDNSAddress = DomainDNSAddress2Compatible; item2.DomainDNSAddress = DomainDNSAddress2Compatible;
item2.NormalDNS = JsonUtils.Serialize(JsonUtils.ParseJson(NormalDNS2Compatible)); item2.NormalDNS = JsonUtils.Serialize(JsonUtils.ParseJson(NormalDNS2Compatible));
item2.TunDNS = JsonUtils.Serialize(JsonUtils.ParseJson(TunDNS2Compatible)); item2.TunDNS = JsonUtils.Serialize(JsonUtils.ParseJson(TunDNS2Compatible));
await ConfigHandler.SaveDNSItems(_config, item2); await ConfigHandler.SaveDNSItems(Config, item2);
await ConfigHandler.SaveConfig(_config); await ConfigHandler.SaveConfig(Config);
if (_updateView != null) if (UpdateView is not null)
{ {
await _updateView(EViewAction.CloseWindow, null); await UpdateView(EViewAction.CloseWindow, null);
} }
} }
} }

View file

@ -37,8 +37,8 @@ public class FullConfigTemplateViewModel : MyReactiveObject
public FullConfigTemplateViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public FullConfigTemplateViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
SaveCmd = ReactiveCommand.CreateFromTask(async () => SaveCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
await SaveSettingAsync(); await SaveSettingAsync();
@ -76,7 +76,7 @@ public class FullConfigTemplateViewModel : MyReactiveObject
} }
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
_ = _updateView?.Invoke(EViewAction.CloseWindow, null); _ = UpdateView?.Invoke(EViewAction.CloseWindow, null);
} }
private async Task<bool> SaveXrayConfigAsync() private async Task<bool> SaveXrayConfigAsync()
@ -90,7 +90,7 @@ public class FullConfigTemplateViewModel : MyReactiveObject
item.AddProxyOnly = AddProxyOnly4Ray; item.AddProxyOnly = AddProxyOnly4Ray;
item.ProxyDetour = ProxyDetour4Ray; item.ProxyDetour = ProxyDetour4Ray;
await ConfigHandler.SaveFullConfigTemplate(_config, item); await ConfigHandler.SaveFullConfigTemplate(Config, item);
return true; return true;
} }
@ -107,7 +107,7 @@ public class FullConfigTemplateViewModel : MyReactiveObject
item.AddProxyOnly = AddProxyOnly4Singbox; item.AddProxyOnly = AddProxyOnly4Singbox;
item.ProxyDetour = ProxyDetour4Singbox; item.ProxyDetour = ProxyDetour4Singbox;
await ConfigHandler.SaveFullConfigTemplate(_config, item); await ConfigHandler.SaveFullConfigTemplate(Config, item);
return true; return true;
} }
} }

View file

@ -8,10 +8,10 @@ public class GlobalHotkeySettingViewModel : MyReactiveObject
public GlobalHotkeySettingViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public GlobalHotkeySettingViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
_globalHotkeys = JsonUtils.DeepCopy(_config.GlobalHotkeys); _globalHotkeys = JsonUtils.DeepCopy(Config.GlobalHotkeys);
SaveCmd = ReactiveCommand.CreateFromTask(async () => SaveCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -22,7 +22,7 @@ public class GlobalHotkeySettingViewModel : MyReactiveObject
public KeyEventItem GetKeyEventItem(EGlobalHotkey eg) public KeyEventItem GetKeyEventItem(EGlobalHotkey eg)
{ {
var item = _globalHotkeys.FirstOrDefault((it) => it.EGlobalHotkey == eg); var item = _globalHotkeys.FirstOrDefault((it) => it.EGlobalHotkey == eg);
if (item != null) if (item is not null)
{ {
return item; return item;
} }
@ -47,11 +47,11 @@ public class GlobalHotkeySettingViewModel : MyReactiveObject
private async Task SaveSettingAsync() 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 else
{ {

View file

@ -70,8 +70,8 @@ public class MainWindowViewModel : MyReactiveObject
public MainWindowViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public MainWindowViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
BlIsWindows = Utils.IsWindows(); BlIsWindows = Utils.IsWindows();
#region WhenAnyValue && ReactiveCommand #region WhenAnyValue && ReactiveCommand
@ -158,11 +158,11 @@ public class MainWindowViewModel : MyReactiveObject
}); });
SubGroupUpdateCmd = ReactiveCommand.CreateFromTask(async () => SubGroupUpdateCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
await UpdateSubscriptionProcess(_config.SubIndexId, false); await UpdateSubscriptionProcess(Config.SubIndexId, false);
}); });
SubGroupUpdateViaProxyCmd = ReactiveCommand.CreateFromTask(async () => SubGroupUpdateViaProxyCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
await UpdateSubscriptionProcess(_config.SubIndexId, true); await UpdateSubscriptionProcess(Config.SubIndexId, true);
}); });
//Setting //Setting
@ -184,7 +184,7 @@ public class MainWindowViewModel : MyReactiveObject
}); });
GlobalHotkeySettingCmd = ReactiveCommand.CreateFromTask(async () => 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); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
} }
@ -255,17 +255,17 @@ public class MainWindowViewModel : MyReactiveObject
{ {
AppManager.Instance.ShowInTaskbar = true; AppManager.Instance.ShowInTaskbar = true;
//await ConfigHandler.InitBuiltinRouting(_config); //await ConfigHandler.InitBuiltinRouting(Config);
await ConfigHandler.InitBuiltinDNS(_config); await ConfigHandler.InitBuiltinDNS(Config);
await ConfigHandler.InitBuiltinFullConfigTemplate(_config); await ConfigHandler.InitBuiltinFullConfigTemplate(Config);
await ProfileExManager.Instance.Init(); await ProfileExManager.Instance.Init();
await ProfileGroupItemManager.Instance.Init(); await ProfileGroupItemManager.Instance.Init();
await CoreManager.Instance.Init(_config, UpdateHandler); await CoreManager.Instance.Init(Config, UpdateHandler);
TaskManager.Instance.RegUpdateTask(_config, UpdateTaskHandler); 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(); await RefreshServers();
@ -291,13 +291,13 @@ public class MainWindowViewModel : MyReactiveObject
NoticeManager.Instance.SendMessageEx(msg); NoticeManager.Instance.SendMessageEx(msg);
if (success) if (success)
{ {
var indexIdOld = _config.IndexId; var indexIdOld = Config.IndexId;
await RefreshServers(); await RefreshServers();
if (indexIdOld != _config.IndexId) if (indexIdOld != Config.IndexId)
{ {
await Reload(); await Reload();
} }
if (_config.UiItem.EnableAutoAdjustMainLvColWidth) if (Config.UiItem.EnableAutoAdjustMainLvColWidth)
{ {
AppEvents.AdjustMainLvColWidthRequested.Publish(); AppEvents.AdjustMainLvColWidthRequested.Publish();
} }
@ -338,7 +338,7 @@ public class MainWindowViewModel : MyReactiveObject
{ {
ProfileItem item = new() ProfileItem item = new()
{ {
Subid = _config.SubIndexId, Subid = Config.SubIndexId,
ConfigType = eConfigType, ConfigType = eConfigType,
IsSub = false, IsSub = false,
}; };
@ -346,20 +346,20 @@ public class MainWindowViewModel : MyReactiveObject
bool? ret = false; bool? ret = false;
if (eConfigType == EConfigType.Custom) if (eConfigType == EConfigType.Custom)
{ {
ret = await _updateView?.Invoke(EViewAction.AddServer2Window, item); ret = await UpdateView?.Invoke(EViewAction.AddServer2Window, item);
} }
else if (eConfigType.IsGroupType()) else if (eConfigType.IsGroupType())
{ {
ret = await _updateView?.Invoke(EViewAction.AddGroupServerWindow, item); ret = await UpdateView?.Invoke(EViewAction.AddGroupServerWindow, item);
} }
else else
{ {
ret = await _updateView?.Invoke(EViewAction.AddServerWindow, item); ret = await UpdateView?.Invoke(EViewAction.AddServerWindow, item);
} }
if (ret == true) if (ret == true)
{ {
await RefreshServers(); await RefreshServers();
if (item.IndexId == _config.IndexId) if (item.IndexId == Config.IndexId)
{ {
await Reload(); await Reload();
} }
@ -368,12 +368,12 @@ public class MainWindowViewModel : MyReactiveObject
public async Task AddServerViaClipboardAsync(string? clipboardData) 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; return;
} }
var ret = await ConfigHandler.AddBatchServers(_config, clipboardData, _config.SubIndexId, false); var ret = await ConfigHandler.AddBatchServers(Config, clipboardData, Config.SubIndexId, false);
if (ret > 0) if (ret > 0)
{ {
RefreshSubscriptions(); RefreshSubscriptions();
@ -388,7 +388,7 @@ public class MainWindowViewModel : MyReactiveObject
public async Task AddServerViaScanAsync() public async Task AddServerViaScanAsync()
{ {
_updateView?.Invoke(EViewAction.ScanScreenTask, null); UpdateView?.Invoke(EViewAction.ScanScreenTask, null);
await Task.CompletedTask; await Task.CompletedTask;
} }
@ -400,7 +400,7 @@ public class MainWindowViewModel : MyReactiveObject
public async Task AddServerViaImageAsync() public async Task AddServerViaImageAsync()
{ {
_updateView?.Invoke(EViewAction.ScanImageTask, null); UpdateView?.Invoke(EViewAction.ScanImageTask, null);
await Task.CompletedTask; await Task.CompletedTask;
} }
@ -423,7 +423,7 @@ public class MainWindowViewModel : MyReactiveObject
} }
else else
{ {
var ret = await ConfigHandler.AddBatchServers(_config, result, _config.SubIndexId, false); var ret = await ConfigHandler.AddBatchServers(Config, result, Config.SubIndexId, false);
if (ret > 0) if (ret > 0)
{ {
RefreshSubscriptions(); RefreshSubscriptions();
@ -443,7 +443,7 @@ public class MainWindowViewModel : MyReactiveObject
private async Task SubSettingAsync() private async Task SubSettingAsync()
{ {
if (await _updateView?.Invoke(EViewAction.SubSettingWindow, null) == true) if (await UpdateView?.Invoke(EViewAction.SubSettingWindow, null) == true)
{ {
RefreshSubscriptions(); RefreshSubscriptions();
} }
@ -451,7 +451,7 @@ public class MainWindowViewModel : MyReactiveObject
public async Task UpdateSubscriptionProcess(string subId, bool blProxy) 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 #endregion Subscription
@ -460,7 +460,7 @@ public class MainWindowViewModel : MyReactiveObject
private async Task OptionSettingAsync() private async Task OptionSettingAsync()
{ {
var ret = await _updateView?.Invoke(EViewAction.OptionSettingWindow, null); var ret = await UpdateView?.Invoke(EViewAction.OptionSettingWindow, null);
if (ret == true) if (ret == true)
{ {
AppEvents.InboundDisplayRequested.Publish(); AppEvents.InboundDisplayRequested.Publish();
@ -470,10 +470,10 @@ public class MainWindowViewModel : MyReactiveObject
private async Task RoutingSettingAsync() private async Task RoutingSettingAsync()
{ {
var ret = await _updateView?.Invoke(EViewAction.RoutingSettingWindow, null); var ret = await UpdateView?.Invoke(EViewAction.RoutingSettingWindow, null);
if (ret == true) if (ret == true)
{ {
await ConfigHandler.InitBuiltinRouting(_config); await ConfigHandler.InitBuiltinRouting(Config);
AppEvents.RoutingsMenuRefreshRequested.Publish(); AppEvents.RoutingsMenuRefreshRequested.Publish();
await Reload(); await Reload();
} }
@ -481,7 +481,7 @@ public class MainWindowViewModel : MyReactiveObject
private async Task DNSSettingAsync() private async Task DNSSettingAsync()
{ {
var ret = await _updateView?.Invoke(EViewAction.DNSSettingWindow, null); var ret = await UpdateView?.Invoke(EViewAction.DNSSettingWindow, null);
if (ret == true) if (ret == true)
{ {
await Reload(); await Reload();
@ -490,7 +490,7 @@ public class MainWindowViewModel : MyReactiveObject
private async Task FullConfigTemplateAsync() private async Task FullConfigTemplateAsync()
{ {
var ret = await _updateView?.Invoke(EViewAction.FullConfigTemplateWindow, null); var ret = await UpdateView?.Invoke(EViewAction.FullConfigTemplateWindow, null);
if (ret == true) if (ret == true)
{ {
await Reload(); await Reload();
@ -541,7 +541,7 @@ public class MainWindowViewModel : MyReactiveObject
{ {
SetReloadEnabled(false); SetReloadEnabled(false);
var msgs = await ActionPrecheckManager.Instance.Check(_config.IndexId); var msgs = await ActionPrecheckManager.Instance.Check(Config.IndexId);
if (msgs.Count > 0) if (msgs.Count > 0)
{ {
foreach (var msg in msgs) foreach (var msg in msgs)
@ -555,7 +555,7 @@ public class MainWindowViewModel : MyReactiveObject
await Task.Run(async () => await Task.Run(async () =>
{ {
await LoadCore(); await LoadCore();
await SysProxyHandler.UpdateSysProxy(_config, false); await SysProxyHandler.UpdateSysProxy(Config, false);
await Task.Delay(1000); await Task.Delay(1000);
}); });
AppEvents.TestServerRequested.Publish(); AppEvents.TestServerRequested.Publish();
@ -597,7 +597,7 @@ public class MainWindowViewModel : MyReactiveObject
private async Task LoadCore() private async Task LoadCore()
{ {
var node = await ConfigHandler.GetDefaultServer(_config); var node = await ConfigHandler.GetDefaultServer(Config);
await CoreManager.Instance.LoadCore(node); await CoreManager.Instance.LoadCore(node);
} }
@ -607,12 +607,12 @@ public class MainWindowViewModel : MyReactiveObject
public async Task ApplyRegionalPreset(EPresetType type) public async Task ApplyRegionalPreset(EPresetType type)
{ {
await ConfigHandler.ApplyRegionalPreset(_config, type); await ConfigHandler.ApplyRegionalPreset(Config, type);
await ConfigHandler.InitRouting(_config); await ConfigHandler.InitRouting(Config);
AppEvents.RoutingsMenuRefreshRequested.Publish(); AppEvents.RoutingsMenuRefreshRequested.Publish();
await ConfigHandler.SaveConfig(_config); await ConfigHandler.SaveConfig(Config);
await new UpdateService(_config, UpdateTaskHandler).UpdateGeoFileAll(); await new UpdateService(Config, UpdateTaskHandler).UpdateGeoFileAll();
await Reload(); await Reload();
} }

View file

@ -15,10 +15,10 @@ public class MsgViewModel : MyReactiveObject
public MsgViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public MsgViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
MsgFilter = _config.MsgUIItem.MainMsgFilter ?? string.Empty; MsgFilter = Config.MsgUIItem.MainMsgFilter ?? string.Empty;
AutoRefresh = _config.MsgUIItem.AutoRefresh ?? true; AutoRefresh = Config.MsgUIItem.AutoRefresh ?? true;
this.WhenAnyValue( this.WhenAnyValue(
x => x.MsgFilter) x => x.MsgFilter)
@ -27,7 +27,7 @@ public class MsgViewModel : MyReactiveObject
this.WhenAnyValue( this.WhenAnyValue(
x => x.AutoRefresh, x => x.AutoRefresh,
y => y == true) y => y == true)
.Subscribe(c => _config.MsgUIItem.AutoRefresh = AutoRefresh); .Subscribe(c => Config.MsgUIItem.AutoRefresh = AutoRefresh);
AppEvents.SendMsgViewRequested AppEvents.SendMsgViewRequested
.AsObservable() .AsObservable()
@ -64,7 +64,7 @@ public class MsgViewModel : MyReactiveObject
sb.Append(line); sb.Append(line);
} }
await _updateView?.Invoke(EViewAction.DispatcherShowMsg, sb.ToString()); await UpdateView?.Invoke(EViewAction.DispatcherShowMsg, sb.ToString());
} }
finally finally
{ {
@ -105,7 +105,7 @@ public class MsgViewModel : MyReactiveObject
private void DoMsgFilter() private void DoMsgFilter()
{ {
_config.MsgUIItem.MainMsgFilter = MsgFilter; Config.MsgUIItem.MainMsgFilter = MsgFilter;
_lastMsgFilterNotAvailable = false; _lastMsgFilterNotAvailable = false;
} }
} }

View file

@ -117,8 +117,8 @@ public class OptionSettingViewModel : MyReactiveObject
public OptionSettingViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public OptionSettingViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
BlIsWindows = Utils.IsWindows(); BlIsWindows = Utils.IsWindows();
BlIsLinux = Utils.IsLinux(); BlIsLinux = Utils.IsLinux();
BlIsIsMacOS = Utils.IsMacOS(); BlIsIsMacOS = Utils.IsMacOS();
@ -134,11 +134,11 @@ public class OptionSettingViewModel : MyReactiveObject
private async Task Init() private async Task Init()
{ {
await _updateView?.Invoke(EViewAction.InitSettingFont, null); await UpdateView?.Invoke(EViewAction.InitSettingFont, null);
#region Core #region Core
var inbound = _config.Inbound.First(); var inbound = Config.Inbound.First();
localPort = inbound.LocalPort; localPort = inbound.LocalPort;
SecondLocalPortEnabled = inbound.SecondLocalPortEnabled; SecondLocalPortEnabled = inbound.SecondLocalPortEnabled;
udpEnabled = inbound.UdpEnabled; udpEnabled = inbound.UdpEnabled;
@ -148,80 +148,80 @@ public class OptionSettingViewModel : MyReactiveObject
newPort4LAN = inbound.NewPort4LAN; newPort4LAN = inbound.NewPort4LAN;
user = inbound.User; user = inbound.User;
pass = inbound.Pass; pass = inbound.Pass;
muxEnabled = _config.CoreBasicItem.MuxEnabled; muxEnabled = Config.CoreBasicItem.MuxEnabled;
logEnabled = _config.CoreBasicItem.LogEnabled; logEnabled = Config.CoreBasicItem.LogEnabled;
loglevel = _config.CoreBasicItem.Loglevel; loglevel = Config.CoreBasicItem.Loglevel;
defAllowInsecure = _config.CoreBasicItem.DefAllowInsecure; defAllowInsecure = Config.CoreBasicItem.DefAllowInsecure;
defFingerprint = _config.CoreBasicItem.DefFingerprint; defFingerprint = Config.CoreBasicItem.DefFingerprint;
defUserAgent = _config.CoreBasicItem.DefUserAgent; defUserAgent = Config.CoreBasicItem.DefUserAgent;
mux4SboxProtocol = _config.Mux4SboxItem.Protocol; mux4SboxProtocol = Config.Mux4SboxItem.Protocol;
enableCacheFile4Sbox = _config.CoreBasicItem.EnableCacheFile4Sbox; enableCacheFile4Sbox = Config.CoreBasicItem.EnableCacheFile4Sbox;
hyUpMbps = _config.HysteriaItem.UpMbps; hyUpMbps = Config.HysteriaItem.UpMbps;
hyDownMbps = _config.HysteriaItem.DownMbps; hyDownMbps = Config.HysteriaItem.DownMbps;
enableFragment = _config.CoreBasicItem.EnableFragment; enableFragment = Config.CoreBasicItem.EnableFragment;
#endregion Core #endregion Core
#region Core KCP #region Core KCP
//Kcpmtu = _config.kcpItem.mtu; //Kcpmtu = Config.kcpItem.mtu;
//Kcptti = _config.kcpItem.tti; //Kcptti = Config.kcpItem.tti;
//KcpuplinkCapacity = _config.kcpItem.uplinkCapacity; //KcpuplinkCapacity = Config.kcpItem.uplinkCapacity;
//KcpdownlinkCapacity = _config.kcpItem.downlinkCapacity; //KcpdownlinkCapacity = Config.kcpItem.downlinkCapacity;
//KcpreadBufferSize = _config.kcpItem.readBufferSize; //KcpreadBufferSize = Config.kcpItem.readBufferSize;
//KcpwriteBufferSize = _config.kcpItem.writeBufferSize; //KcpwriteBufferSize = Config.kcpItem.writeBufferSize;
//Kcpcongestion = _config.kcpItem.congestion; //Kcpcongestion = Config.kcpItem.congestion;
#endregion Core KCP #endregion Core KCP
#region UI #region UI
AutoRun = _config.GuiItem.AutoRun; AutoRun = Config.GuiItem.AutoRun;
EnableStatistics = _config.GuiItem.EnableStatistics; EnableStatistics = Config.GuiItem.EnableStatistics;
DisplayRealTimeSpeed = _config.GuiItem.DisplayRealTimeSpeed; DisplayRealTimeSpeed = Config.GuiItem.DisplayRealTimeSpeed;
KeepOlderDedupl = _config.GuiItem.KeepOlderDedupl; KeepOlderDedupl = Config.GuiItem.KeepOlderDedupl;
EnableAutoAdjustMainLvColWidth = _config.UiItem.EnableAutoAdjustMainLvColWidth; EnableAutoAdjustMainLvColWidth = Config.UiItem.EnableAutoAdjustMainLvColWidth;
EnableUpdateSubOnlyRemarksExist = _config.UiItem.EnableUpdateSubOnlyRemarksExist; EnableUpdateSubOnlyRemarksExist = Config.UiItem.EnableUpdateSubOnlyRemarksExist;
AutoHideStartup = _config.UiItem.AutoHideStartup; AutoHideStartup = Config.UiItem.AutoHideStartup;
Hide2TrayWhenClose = _config.UiItem.Hide2TrayWhenClose; Hide2TrayWhenClose = Config.UiItem.Hide2TrayWhenClose;
MacOSShowInDock = _config.UiItem.MacOSShowInDock; MacOSShowInDock = Config.UiItem.MacOSShowInDock;
EnableDragDropSort = _config.UiItem.EnableDragDropSort; EnableDragDropSort = Config.UiItem.EnableDragDropSort;
DoubleClick2Activate = _config.UiItem.DoubleClick2Activate; DoubleClick2Activate = Config.UiItem.DoubleClick2Activate;
AutoUpdateInterval = _config.GuiItem.AutoUpdateInterval; AutoUpdateInterval = Config.GuiItem.AutoUpdateInterval;
TrayMenuServersLimit = _config.GuiItem.TrayMenuServersLimit; TrayMenuServersLimit = Config.GuiItem.TrayMenuServersLimit;
CurrentFontFamily = _config.UiItem.CurrentFontFamily; CurrentFontFamily = Config.UiItem.CurrentFontFamily;
SpeedTestTimeout = _config.SpeedTestItem.SpeedTestTimeout; SpeedTestTimeout = Config.SpeedTestItem.SpeedTestTimeout;
SpeedTestUrl = _config.SpeedTestItem.SpeedTestUrl; SpeedTestUrl = Config.SpeedTestItem.SpeedTestUrl;
MixedConcurrencyCount = _config.SpeedTestItem.MixedConcurrencyCount; MixedConcurrencyCount = Config.SpeedTestItem.MixedConcurrencyCount;
SpeedPingTestUrl = _config.SpeedTestItem.SpeedPingTestUrl; SpeedPingTestUrl = Config.SpeedTestItem.SpeedPingTestUrl;
EnableHWA = _config.GuiItem.EnableHWA; EnableHWA = Config.GuiItem.EnableHWA;
SubConvertUrl = _config.ConstItem.SubConvertUrl; SubConvertUrl = Config.ConstItem.SubConvertUrl;
MainGirdOrientation = (int)_config.UiItem.MainGirdOrientation; MainGirdOrientation = (int)Config.UiItem.MainGirdOrientation;
GeoFileSourceUrl = _config.ConstItem.GeoSourceUrl; GeoFileSourceUrl = Config.ConstItem.GeoSourceUrl;
SrsFileSourceUrl = _config.ConstItem.SrsSourceUrl; SrsFileSourceUrl = Config.ConstItem.SrsSourceUrl;
RoutingRulesSourceUrl = _config.ConstItem.RouteRulesTemplateSourceUrl; RoutingRulesSourceUrl = Config.ConstItem.RouteRulesTemplateSourceUrl;
IPAPIUrl = _config.SpeedTestItem.IPAPIUrl; IPAPIUrl = Config.SpeedTestItem.IPAPIUrl;
#endregion UI #endregion UI
#region System proxy #region System proxy
notProxyLocalAddress = _config.SystemProxyItem.NotProxyLocalAddress; notProxyLocalAddress = Config.SystemProxyItem.NotProxyLocalAddress;
systemProxyAdvancedProtocol = _config.SystemProxyItem.SystemProxyAdvancedProtocol; systemProxyAdvancedProtocol = Config.SystemProxyItem.SystemProxyAdvancedProtocol;
systemProxyExceptions = _config.SystemProxyItem.SystemProxyExceptions; systemProxyExceptions = Config.SystemProxyItem.SystemProxyExceptions;
CustomSystemProxyPacPath = _config.SystemProxyItem.CustomSystemProxyPacPath; CustomSystemProxyPacPath = Config.SystemProxyItem.CustomSystemProxyPacPath;
CustomSystemProxyScriptPath = _config.SystemProxyItem.CustomSystemProxyScriptPath; CustomSystemProxyScriptPath = Config.SystemProxyItem.CustomSystemProxyScriptPath;
#endregion System proxy #endregion System proxy
#region Tun mode #region Tun mode
TunAutoRoute = _config.TunModeItem.AutoRoute; TunAutoRoute = Config.TunModeItem.AutoRoute;
TunStrictRoute = _config.TunModeItem.StrictRoute; TunStrictRoute = Config.TunModeItem.StrictRoute;
TunStack = _config.TunModeItem.Stack; TunStack = Config.TunModeItem.Stack;
TunMtu = _config.TunModeItem.Mtu; TunMtu = Config.TunModeItem.Mtu;
TunEnableExInbound = _config.TunModeItem.EnableExInbound; TunEnableExInbound = Config.TunModeItem.EnableExInbound;
TunEnableIPv6Address = _config.TunModeItem.EnableIPv6Address; TunEnableIPv6Address = Config.TunModeItem.EnableIPv6Address;
#endregion Tun mode #endregion Tun mode
@ -230,25 +230,25 @@ public class OptionSettingViewModel : MyReactiveObject
private async Task InitCoreType() private async Task InitCoreType()
{ {
if (_config.CoreTypeItem == null) if (Config.CoreTypeItem is null)
{ {
_config.CoreTypeItem = new List<CoreTypeItem>(); Config.CoreTypeItem = new List<CoreTypeItem>();
} }
foreach (EConfigType it in Enum.GetValues(typeof(EConfigType))) foreach (var it in Enum.GetValues<EConfigType>().Select(v => v))
{ {
if (_config.CoreTypeItem.FindIndex(t => t.ConfigType == it) >= 0) if (Config.CoreTypeItem.FindIndex(t => t.ConfigType == it) >= 0)
{ {
continue; continue;
} }
_config.CoreTypeItem.Add(new CoreTypeItem() Config.CoreTypeItem.Add(new CoreTypeItem()
{ {
ConfigType = it, ConfigType = it,
CoreType = ECoreType.Xray CoreType = ECoreType.Xray
}); });
} }
_config.CoreTypeItem.ForEach(it => Config.CoreTypeItem.ForEach(it =>
{ {
var type = it.CoreType.ToString(); var type = it.CoreType.ToString();
switch ((int)it.ConfigType) switch ((int)it.ConfigType)
@ -292,17 +292,17 @@ public class OptionSettingViewModel : MyReactiveObject
private async Task SaveSettingAsync() private async Task SaveSettingAsync()
{ {
if (localPort.ToString().IsNullOrEmpty() || !Utils.IsNumeric(localPort.ToString()) if (localPort.ToString().IsNullOrEmpty() || !Utils.IsNumeric(localPort.ToString())
|| localPort <= 0 || localPort >= Global.MaxPort) || localPort <= 0 || localPort >= AppConfig.MaxPort)
{ {
NoticeManager.Instance.Enqueue(ResUI.FillLocalListeningPort); NoticeManager.Instance.Enqueue(ResUI.FillLocalListeningPort);
return; return;
} }
var needReboot = EnableStatistics != _config.GuiItem.EnableStatistics var needReboot = EnableStatistics != Config.GuiItem.EnableStatistics
|| DisplayRealTimeSpeed != _config.GuiItem.DisplayRealTimeSpeed || DisplayRealTimeSpeed != Config.GuiItem.DisplayRealTimeSpeed
|| EnableDragDropSort != _config.UiItem.EnableDragDropSort || EnableDragDropSort != Config.UiItem.EnableDragDropSort
|| EnableHWA != _config.GuiItem.EnableHWA || EnableHWA != Config.GuiItem.EnableHWA
|| CurrentFontFamily != _config.UiItem.CurrentFontFamily || CurrentFontFamily != Config.UiItem.CurrentFontFamily
|| MainGirdOrientation != (int)_config.UiItem.MainGirdOrientation; || MainGirdOrientation != (int)Config.UiItem.MainGirdOrientation;
//if (Utile.IsNullOrEmpty(Kcpmtu.ToString()) || !Utile.IsNumeric(Kcpmtu.ToString()) //if (Utile.IsNullOrEmpty(Kcpmtu.ToString()) || !Utile.IsNumeric(Kcpmtu.ToString())
// || Utile.IsNullOrEmpty(Kcptti.ToString()) || !Utile.IsNumeric(Kcptti.ToString()) // || Utile.IsNullOrEmpty(Kcptti.ToString()) || !Utile.IsNumeric(Kcptti.ToString())
@ -316,83 +316,83 @@ public class OptionSettingViewModel : MyReactiveObject
//} //}
//Core //Core
_config.Inbound.First().LocalPort = localPort; Config.Inbound.First().LocalPort = localPort;
_config.Inbound.First().SecondLocalPortEnabled = SecondLocalPortEnabled; Config.Inbound.First().SecondLocalPortEnabled = SecondLocalPortEnabled;
_config.Inbound.First().UdpEnabled = udpEnabled; Config.Inbound.First().UdpEnabled = udpEnabled;
_config.Inbound.First().SniffingEnabled = sniffingEnabled; Config.Inbound.First().SniffingEnabled = sniffingEnabled;
_config.Inbound.First().DestOverride = destOverride?.ToList(); Config.Inbound.First().DestOverride = destOverride?.ToList();
_config.Inbound.First().RouteOnly = routeOnly; Config.Inbound.First().RouteOnly = routeOnly;
_config.Inbound.First().AllowLANConn = allowLANConn; Config.Inbound.First().AllowLANConn = allowLANConn;
_config.Inbound.First().NewPort4LAN = newPort4LAN; Config.Inbound.First().NewPort4LAN = newPort4LAN;
_config.Inbound.First().User = user; Config.Inbound.First().User = user;
_config.Inbound.First().Pass = pass; Config.Inbound.First().Pass = pass;
if (_config.Inbound.Count > 1) if (Config.Inbound.Count > 1)
{ {
_config.Inbound.RemoveAt(1); Config.Inbound.RemoveAt(1);
} }
_config.CoreBasicItem.LogEnabled = logEnabled; Config.CoreBasicItem.LogEnabled = logEnabled;
_config.CoreBasicItem.Loglevel = loglevel; Config.CoreBasicItem.Loglevel = loglevel;
_config.CoreBasicItem.MuxEnabled = muxEnabled; Config.CoreBasicItem.MuxEnabled = muxEnabled;
_config.CoreBasicItem.DefAllowInsecure = defAllowInsecure; Config.CoreBasicItem.DefAllowInsecure = defAllowInsecure;
_config.CoreBasicItem.DefFingerprint = defFingerprint; Config.CoreBasicItem.DefFingerprint = defFingerprint;
_config.CoreBasicItem.DefUserAgent = defUserAgent; Config.CoreBasicItem.DefUserAgent = defUserAgent;
_config.Mux4SboxItem.Protocol = mux4SboxProtocol; Config.Mux4SboxItem.Protocol = mux4SboxProtocol;
_config.CoreBasicItem.EnableCacheFile4Sbox = enableCacheFile4Sbox; Config.CoreBasicItem.EnableCacheFile4Sbox = enableCacheFile4Sbox;
_config.HysteriaItem.UpMbps = hyUpMbps; Config.HysteriaItem.UpMbps = hyUpMbps;
_config.HysteriaItem.DownMbps = hyDownMbps; Config.HysteriaItem.DownMbps = hyDownMbps;
_config.CoreBasicItem.EnableFragment = enableFragment; Config.CoreBasicItem.EnableFragment = enableFragment;
_config.GuiItem.AutoRun = AutoRun; Config.GuiItem.AutoRun = AutoRun;
_config.GuiItem.EnableStatistics = EnableStatistics; Config.GuiItem.EnableStatistics = EnableStatistics;
_config.GuiItem.DisplayRealTimeSpeed = DisplayRealTimeSpeed; Config.GuiItem.DisplayRealTimeSpeed = DisplayRealTimeSpeed;
_config.GuiItem.KeepOlderDedupl = KeepOlderDedupl; Config.GuiItem.KeepOlderDedupl = KeepOlderDedupl;
_config.UiItem.EnableAutoAdjustMainLvColWidth = EnableAutoAdjustMainLvColWidth; Config.UiItem.EnableAutoAdjustMainLvColWidth = EnableAutoAdjustMainLvColWidth;
_config.UiItem.EnableUpdateSubOnlyRemarksExist = EnableUpdateSubOnlyRemarksExist; Config.UiItem.EnableUpdateSubOnlyRemarksExist = EnableUpdateSubOnlyRemarksExist;
_config.UiItem.AutoHideStartup = AutoHideStartup; Config.UiItem.AutoHideStartup = AutoHideStartup;
_config.UiItem.Hide2TrayWhenClose = Hide2TrayWhenClose; Config.UiItem.Hide2TrayWhenClose = Hide2TrayWhenClose;
_config.UiItem.MacOSShowInDock = MacOSShowInDock; Config.UiItem.MacOSShowInDock = MacOSShowInDock;
_config.GuiItem.AutoUpdateInterval = AutoUpdateInterval; Config.GuiItem.AutoUpdateInterval = AutoUpdateInterval;
_config.UiItem.EnableDragDropSort = EnableDragDropSort; Config.UiItem.EnableDragDropSort = EnableDragDropSort;
_config.UiItem.DoubleClick2Activate = DoubleClick2Activate; Config.UiItem.DoubleClick2Activate = DoubleClick2Activate;
_config.GuiItem.TrayMenuServersLimit = TrayMenuServersLimit; Config.GuiItem.TrayMenuServersLimit = TrayMenuServersLimit;
_config.UiItem.CurrentFontFamily = CurrentFontFamily; Config.UiItem.CurrentFontFamily = CurrentFontFamily;
_config.SpeedTestItem.SpeedTestTimeout = SpeedTestTimeout; Config.SpeedTestItem.SpeedTestTimeout = SpeedTestTimeout;
_config.SpeedTestItem.MixedConcurrencyCount = MixedConcurrencyCount; Config.SpeedTestItem.MixedConcurrencyCount = MixedConcurrencyCount;
_config.SpeedTestItem.SpeedTestUrl = SpeedTestUrl; Config.SpeedTestItem.SpeedTestUrl = SpeedTestUrl;
_config.SpeedTestItem.SpeedPingTestUrl = SpeedPingTestUrl; Config.SpeedTestItem.SpeedPingTestUrl = SpeedPingTestUrl;
_config.GuiItem.EnableHWA = EnableHWA; Config.GuiItem.EnableHWA = EnableHWA;
_config.ConstItem.SubConvertUrl = SubConvertUrl; Config.ConstItem.SubConvertUrl = SubConvertUrl;
_config.UiItem.MainGirdOrientation = (EGirdOrientation)MainGirdOrientation; Config.UiItem.MainGirdOrientation = (EGirdOrientation)MainGirdOrientation;
_config.ConstItem.GeoSourceUrl = GeoFileSourceUrl; Config.ConstItem.GeoSourceUrl = GeoFileSourceUrl;
_config.ConstItem.SrsSourceUrl = SrsFileSourceUrl; Config.ConstItem.SrsSourceUrl = SrsFileSourceUrl;
_config.ConstItem.RouteRulesTemplateSourceUrl = RoutingRulesSourceUrl; Config.ConstItem.RouteRulesTemplateSourceUrl = RoutingRulesSourceUrl;
_config.SpeedTestItem.IPAPIUrl = IPAPIUrl; Config.SpeedTestItem.IPAPIUrl = IPAPIUrl;
//systemProxy //systemProxy
_config.SystemProxyItem.SystemProxyExceptions = systemProxyExceptions; Config.SystemProxyItem.SystemProxyExceptions = systemProxyExceptions;
_config.SystemProxyItem.NotProxyLocalAddress = notProxyLocalAddress; Config.SystemProxyItem.NotProxyLocalAddress = notProxyLocalAddress;
_config.SystemProxyItem.SystemProxyAdvancedProtocol = systemProxyAdvancedProtocol; Config.SystemProxyItem.SystemProxyAdvancedProtocol = systemProxyAdvancedProtocol;
_config.SystemProxyItem.CustomSystemProxyPacPath = CustomSystemProxyPacPath; Config.SystemProxyItem.CustomSystemProxyPacPath = CustomSystemProxyPacPath;
_config.SystemProxyItem.CustomSystemProxyScriptPath = CustomSystemProxyScriptPath; Config.SystemProxyItem.CustomSystemProxyScriptPath = CustomSystemProxyScriptPath;
//tun mode //tun mode
_config.TunModeItem.AutoRoute = TunAutoRoute; Config.TunModeItem.AutoRoute = TunAutoRoute;
_config.TunModeItem.StrictRoute = TunStrictRoute; Config.TunModeItem.StrictRoute = TunStrictRoute;
_config.TunModeItem.Stack = TunStack; Config.TunModeItem.Stack = TunStack;
_config.TunModeItem.Mtu = TunMtu; Config.TunModeItem.Mtu = TunMtu;
_config.TunModeItem.EnableExInbound = TunEnableExInbound; Config.TunModeItem.EnableExInbound = TunEnableExInbound;
_config.TunModeItem.EnableIPv6Address = TunEnableIPv6Address; Config.TunModeItem.EnableIPv6Address = TunEnableIPv6Address;
//coreType //coreType
await SaveCoreType(); 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(); AppManager.Instance.Reset();
NoticeManager.Instance.Enqueue(needReboot ? ResUI.NeedRebootTips : ResUI.OperationSuccess); NoticeManager.Instance.Enqueue(needReboot ? ResUI.NeedRebootTips : ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); UpdateView?.Invoke(EViewAction.CloseWindow, null);
} }
else else
{ {
@ -402,10 +402,10 @@ public class OptionSettingViewModel : MyReactiveObject
private async Task SaveCoreType() 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 item = Config.CoreTypeItem[k - 1];
var type = string.Empty; string type;
switch ((int)item.ConfigType) switch ((int)item.ConfigType)
{ {
case 1: case 1:

View file

@ -5,14 +5,9 @@ public class ProfilesSelectViewModel : MyReactiveObject
#region private prop #region private prop
private string _serverFilter = string.Empty; private string _serverFilter = string.Empty;
private Dictionary<string, bool> _dicHeaderSort = new(); private readonly Dictionary<string, bool> _dicHeaderSort = new();
private string _subIndexId = string.Empty; private string _subIndexId = string.Empty;
// ConfigType filter state: default include-mode with all types selected
private List<EConfigType> _filterConfigTypes = new();
private bool _filterExclude = false;
#endregion private prop #endregion private prop
#region ObservableCollection #region ObservableCollection
@ -35,16 +30,16 @@ public class ProfilesSelectViewModel : MyReactiveObject
// Include/Exclude filter for ConfigType // Include/Exclude filter for ConfigType
public List<EConfigType> FilterConfigTypes public List<EConfigType> FilterConfigTypes
{ {
get => _filterConfigTypes; get;
set => this.RaiseAndSetIfChanged(ref _filterConfigTypes, value); set => this.RaiseAndSetIfChanged(ref field, value);
} } = new();
[Reactive] [Reactive]
public bool FilterExclude public bool FilterExclude
{ {
get => _filterExclude; get;
set => this.RaiseAndSetIfChanged(ref _filterExclude, value); set => this.RaiseAndSetIfChanged(ref field, value);
} } = false;
#endregion ObservableCollection #endregion ObservableCollection
@ -52,20 +47,20 @@ public class ProfilesSelectViewModel : MyReactiveObject
public ProfilesSelectViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public ProfilesSelectViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
_subIndexId = _config.SubIndexId ?? string.Empty; _subIndexId = Config.SubIndexId ?? string.Empty;
#region WhenAnyValue && ReactiveCommand #region WhenAnyValue && ReactiveCommand
this.WhenAnyValue( this.WhenAnyValue(
x => x.SelectedSub, 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)); .Subscribe(async c => await SubSelectedChangedAsync(c));
this.WhenAnyValue( this.WhenAnyValue(
x => x.ServerFilter, x => x.ServerFilter,
y => y != null && _serverFilter != y) y => y is not null && _serverFilter != y)
.Subscribe(async c => await ServerFilterChanged(c)); .Subscribe(async c => await ServerFilterChanged(c));
// React to ConfigType filter changes // React to ConfigType filter changes
@ -108,7 +103,7 @@ public class ProfilesSelectViewModel : MyReactiveObject
public bool CanOk() public bool CanOk()
{ {
return SelectedProfile != null && !SelectedProfile.IndexId.IsNullOrEmpty(); return SelectedProfile is not null && !SelectedProfile.IndexId.IsNullOrEmpty();
} }
public bool SelectFinish() public bool SelectFinish()
@ -117,7 +112,7 @@ public class ProfilesSelectViewModel : MyReactiveObject
{ {
return false; return false;
} }
_updateView?.Invoke(EViewAction.CloseWindow, null); UpdateView?.Invoke(EViewAction.CloseWindow, null);
return true; return true;
} }
@ -135,7 +130,7 @@ public class ProfilesSelectViewModel : MyReactiveObject
await RefreshServers(); await RefreshServers();
await _updateView?.Invoke(EViewAction.ProfilesFocus, null); await UpdateView?.Invoke(EViewAction.ProfilesFocus, null);
} }
private async Task ServerFilterChanged(bool c) private async Task ServerFilterChanged(bool c)
@ -158,14 +153,14 @@ public class ProfilesSelectViewModel : MyReactiveObject
private async Task RefreshServersBiz() private async Task RefreshServersBiz()
{ {
var lstModel = await GetProfileItemsEx(_subIndexId, _serverFilter); var lstModel = await GetProfileItemsEx(_serverFilter);
ProfileItems.Clear(); ProfileItems.Clear();
ProfileItems.AddRange(lstModel); ProfileItems.AddRange(lstModel);
if (lstModel.Count > 0) if (lstModel.Count > 0)
{ {
var selected = lstModel.FirstOrDefault(t => t.IndexId == _config.IndexId); var selected = lstModel.FirstOrDefault(t => t.IndexId == Config.IndexId);
if (selected != null) if (selected is not null)
{ {
SelectedProfile = selected; 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() public async Task RefreshSubscriptions()
@ -188,7 +183,7 @@ public class ProfilesSelectViewModel : MyReactiveObject
{ {
SubItems.Add(item); 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); SelectedSub = SubItems.FirstOrDefault(t => t.Id == _subIndexId);
} }
@ -198,7 +193,7 @@ public class ProfilesSelectViewModel : MyReactiveObject
} }
} }
private async Task<List<ProfileItemModel>?> GetProfileItemsEx(string subid, string filter) private async Task<List<ProfileItemModel>?> GetProfileItemsEx(string filter)
{ {
var lstModel = await AppManager.Instance.ProfileItems(_subIndexId, filter); var lstModel = await AppManager.Instance.ProfileItems(_subIndexId, filter);
lstModel = (from t in lstModel lstModel = (from t in lstModel
@ -214,11 +209,11 @@ public class ProfilesSelectViewModel : MyReactiveObject
StreamSecurity = t.StreamSecurity, StreamSecurity = t.StreamSecurity,
Subid = t.Subid, Subid = t.Subid,
SubRemarks = t.SubRemarks, SubRemarks = t.SubRemarks,
IsActive = t.IndexId == _config.IndexId, IsActive = t.IndexId == Config.IndexId,
}).OrderBy(t => t.Sort).ToList(); }).OrderBy(t => t.Sort).ToList();
// Apply ConfigType filter (include or exclude) // Apply ConfigType filter (include or exclude)
if (FilterConfigTypes != null && FilterConfigTypes.Count > 0) if (FilterConfigTypes is not null && FilterConfigTypes.Count > 0)
{ {
if (FilterExclude) if (FilterExclude)
{ {
@ -251,7 +246,7 @@ public class ProfilesSelectViewModel : MyReactiveObject
public async Task<List<ProfileItem>?> GetProfileItems() public async Task<List<ProfileItem>?> GetProfileItems()
{ {
if (SelectedProfiles == null || SelectedProfiles.Count == 0) if (SelectedProfiles is null || SelectedProfiles.Count == 0)
{ {
return null; return null;
} }
@ -263,7 +258,7 @@ public class ProfilesSelectViewModel : MyReactiveObject
continue; continue;
} }
var item = await AppManager.Instance.GetProfileItem(sp.IndexId); var item = await AppManager.Instance.GetProfileItem(sp.IndexId);
if (item != null) if (item is not null)
{ {
lst.Add(item); lst.Add(item);
} }
@ -284,13 +279,12 @@ public class ProfilesSelectViewModel : MyReactiveObject
} }
var prop = typeof(ProfileItemModel).GetProperty(colName); var prop = typeof(ProfileItemModel).GetProperty(colName);
if (prop == null) if (prop is null)
{ {
return; return;
} }
;
_dicHeaderSort.TryAdd(colName, true); var asc = _dicHeaderSort.GetValueOrDefault(colName, true);
var asc = _dicHeaderSort[colName];
var comparer = Comparer<object?>.Create((a, b) => var comparer = Comparer<object?>.Create((a, b) =>
{ {

View file

@ -6,7 +6,7 @@ public class ProfilesViewModel : MyReactiveObject
private List<ProfileItem> _lstProfile; private List<ProfileItem> _lstProfile;
private string _serverFilter = string.Empty; private string _serverFilter = string.Empty;
private Dictionary<string, bool> _dicHeaderSort = new(); private readonly Dictionary<string, bool> _dicHeaderSort = new();
private SpeedtestService? _speedtestService; private SpeedtestService? _speedtestService;
#endregion private prop #endregion private prop
@ -56,7 +56,7 @@ public class ProfilesViewModel : MyReactiveObject
public ReactiveCommand<Unit, Unit> MoveUpCmd { get; } public ReactiveCommand<Unit, Unit> MoveUpCmd { get; }
public ReactiveCommand<Unit, Unit> MoveDownCmd { get; } public ReactiveCommand<Unit, Unit> MoveDownCmd { get; }
public ReactiveCommand<Unit, Unit> MoveBottomCmd { get; } public ReactiveCommand<Unit, Unit> MoveBottomCmd { get; }
public ReactiveCommand<SubItem, Unit> MoveToGroupCmd { get; } public ReactiveCommand<SubItem, Unit> MoveToGroupCmd { get; }
//servers ping //servers ping
@ -86,27 +86,27 @@ public class ProfilesViewModel : MyReactiveObject
public ProfilesViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public ProfilesViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
#region WhenAnyValue && ReactiveCommand #region WhenAnyValue && ReactiveCommand
var canEditRemove = this.WhenAnyValue( var canEditRemove = this.WhenAnyValue(
x => x.SelectedProfile, x => x.SelectedProfile,
selectedSource => selectedSource != null && !selectedSource.IndexId.IsNullOrEmpty()); selectedSource => selectedSource is not null && !selectedSource.IndexId.IsNullOrEmpty());
this.WhenAnyValue( this.WhenAnyValue(
x => x.SelectedSub, 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)); .Subscribe(async c => await SubSelectedChangedAsync(c));
this.WhenAnyValue( this.WhenAnyValue(
x => x.SelectedMoveToGroup, x => x.SelectedMoveToGroup,
y => y != null && !y.Remarks.IsNullOrEmpty()) y => y is not null && !y.Remarks.IsNullOrEmpty())
.Subscribe(async c => await MoveToGroup(c)); .Subscribe(async c => await MoveToGroup(c));
this.WhenAnyValue( this.WhenAnyValue(
x => x.ServerFilter, x => x.ServerFilter,
y => y != null && _serverFilter != y) y => y is not null && _serverFilter != y)
.Subscribe(async c => await ServerFilterChanged(c)); .Subscribe(async c => await ServerFilterChanged(c));
//servers delete //servers delete
@ -303,7 +303,7 @@ public class ProfilesViewModel : MyReactiveObject
return; return;
} }
var item = ProfileItems.FirstOrDefault(it => it.IndexId == result.IndexId); var item = ProfileItems.FirstOrDefault(it => it.IndexId == result.IndexId);
if (item == null) if (item is null)
{ {
return; return;
} }
@ -322,7 +322,7 @@ public class ProfilesViewModel : MyReactiveObject
public async Task UpdateStatistics(ServerSpeedItem update) public async Task UpdateStatistics(ServerSpeedItem update)
{ {
if (!_config.GuiItem.EnableStatistics if (!Config.GuiItem.EnableStatistics
|| (update.ProxyUp + update.ProxyDown) <= 0 || (update.ProxyUp + update.ProxyDown) <= 0
|| DateTime.Now.Second % 3 != 0) || DateTime.Now.Second % 3 != 0)
{ {
@ -332,7 +332,7 @@ public class ProfilesViewModel : MyReactiveObject
try try
{ {
var item = ProfileItems.FirstOrDefault(it => it.IndexId == update.IndexId); var item = ProfileItems.FirstOrDefault(it => it.IndexId == update.IndexId);
if (item != null) if (item is not null)
{ {
item.TodayDown = Utils.HumanFy(update.TodayDown); item.TodayDown = Utils.HumanFy(update.TodayDown);
item.TodayUp = Utils.HumanFy(update.TodayUp); item.TodayUp = Utils.HumanFy(update.TodayUp);
@ -356,11 +356,11 @@ public class ProfilesViewModel : MyReactiveObject
{ {
return; return;
} }
_config.SubIndexId = SelectedSub?.Id; Config.SubIndexId = SelectedSub?.Id;
await RefreshServers(); await RefreshServers();
await _updateView?.Invoke(EViewAction.ProfilesFocus, null); await UpdateView?.Invoke(EViewAction.ProfilesFocus, null);
} }
private async Task ServerFilterChanged(bool c) private async Task ServerFilterChanged(bool c)
@ -385,15 +385,15 @@ public class ProfilesViewModel : MyReactiveObject
private async Task RefreshServersBiz() private async Task RefreshServersBiz()
{ {
var lstModel = await GetProfileItemsEx(_config.SubIndexId, _serverFilter); var lstModel = await GetProfileItemsEx(Config.SubIndexId, _serverFilter);
_lstProfile = JsonUtils.Deserialize<List<ProfileItem>>(JsonUtils.Serialize(lstModel)) ?? []; _lstProfile = JsonUtils.Deserialize<List<ProfileItem>>(JsonUtils.Serialize(lstModel)) ?? [];
ProfileItems.Clear(); ProfileItems.Clear();
ProfileItems.AddRange(lstModel); ProfileItems.AddRange(lstModel);
if (lstModel.Count > 0) if (lstModel.Count > 0)
{ {
var selected = lstModel.FirstOrDefault(t => t.IndexId == _config.IndexId); var selected = lstModel.FirstOrDefault(t => t.IndexId == Config.IndexId);
if (selected != null) if (selected is not null)
{ {
SelectedProfile = selected; 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() private async Task RefreshSubscriptions()
@ -416,9 +416,9 @@ public class ProfilesViewModel : MyReactiveObject
{ {
SubItems.Add(item); 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 else
{ {
@ -428,11 +428,11 @@ public class ProfilesViewModel : MyReactiveObject
private async Task<List<ProfileItemModel>?> GetProfileItemsEx(string subid, string filter) private async Task<List<ProfileItemModel>?> 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(); var lstProfileExs = await ProfileExManager.Instance.GetProfileExs();
lstModel = (from t in lstModel lstModel = (from t in lstModel
join t2 in lstServerStat on t.IndexId equals t2.IndexId into t2b join t2 in lstServerStat on t.IndexId equals t2.IndexId into t2b
@ -451,16 +451,16 @@ public class ProfilesViewModel : MyReactiveObject
StreamSecurity = t.StreamSecurity, StreamSecurity = t.StreamSecurity,
Subid = t.Subid, Subid = t.Subid,
SubRemarks = t.SubRemarks, SubRemarks = t.SubRemarks,
IsActive = t.IndexId == _config.IndexId, IsActive = t.IndexId == Config.IndexId,
Sort = t33?.Sort ?? 0, Sort = t33?.Sort ?? 0,
Delay = t33?.Delay ?? 0, Delay = t33?.Delay ?? 0,
Speed = t33?.Speed ?? 0, Speed = t33?.Speed ?? 0,
DelayVal = t33?.Delay != 0 ? $"{t33?.Delay}" : string.Empty, DelayVal = t33?.Delay != 0 ? $"{t33?.Delay}" : string.Empty,
SpeedVal = t33?.Speed > 0 ? $"{t33?.Speed}" : t33?.Message ?? string.Empty, SpeedVal = t33?.Speed > 0 ? $"{t33?.Speed}" : t33?.Message ?? string.Empty,
TodayDown = t22 == null ? "" : Utils.HumanFy(t22.TodayDown), TodayDown = t22 is null ? "" : Utils.HumanFy(t22.TodayDown),
TodayUp = t22 == null ? "" : Utils.HumanFy(t22.TodayUp), TodayUp = t22 is null ? "" : Utils.HumanFy(t22.TodayUp),
TotalDown = t22 == null ? "" : Utils.HumanFy(t22.TotalDown), TotalDown = t22 is null ? "" : Utils.HumanFy(t22.TotalDown),
TotalUp = t22 == null ? "" : Utils.HumanFy(t22.TotalUp) TotalUp = t22 is null ? "" : Utils.HumanFy(t22.TotalUp)
}).OrderBy(t => t.Sort).ToList(); }).OrderBy(t => t.Sort).ToList();
return lstModel; return lstModel;
@ -473,7 +473,7 @@ public class ProfilesViewModel : MyReactiveObject
private async Task<List<ProfileItem>?> GetProfileItems(bool latest) private async Task<List<ProfileItem>?> GetProfileItems(bool latest)
{ {
var lstSelected = new List<ProfileItem>(); var lstSelected = new List<ProfileItem>();
if (SelectedProfiles == null || SelectedProfiles.Count <= 0) if (SelectedProfiles is null || SelectedProfiles.Count <= 0)
{ {
return null; return null;
} }
@ -515,20 +515,20 @@ public class ProfilesViewModel : MyReactiveObject
bool? ret = false; bool? ret = false;
if (eConfigType == EConfigType.Custom) if (eConfigType == EConfigType.Custom)
{ {
ret = await _updateView?.Invoke(EViewAction.AddServer2Window, item); ret = await UpdateView?.Invoke(EViewAction.AddServer2Window, item);
} }
else if (eConfigType.IsGroupType()) else if (eConfigType.IsGroupType())
{ {
ret = await _updateView?.Invoke(EViewAction.AddGroupServerWindow, item); ret = await UpdateView?.Invoke(EViewAction.AddGroupServerWindow, item);
} }
else else
{ {
ret = await _updateView?.Invoke(EViewAction.AddServerWindow, item); ret = await UpdateView?.Invoke(EViewAction.AddServerWindow, item);
} }
if (ret == true) if (ret == true)
{ {
await RefreshServers(); await RefreshServers();
if (item.IndexId == _config.IndexId) if (item.IndexId == Config.IndexId)
{ {
Reload(); Reload();
} }
@ -538,17 +538,17 @@ public class ProfilesViewModel : MyReactiveObject
public async Task RemoveServerAsync() public async Task RemoveServerAsync()
{ {
var lstSelected = await GetProfileItems(true); var lstSelected = await GetProfileItems(true);
if (lstSelected == null) if (lstSelected is null)
{ {
return; return;
} }
if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false)
{ {
return; 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); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
if (lstSelected.Count == ProfileItems.Count) if (lstSelected.Count == ProfileItems.Count)
{ {
@ -563,12 +563,12 @@ public class ProfilesViewModel : MyReactiveObject
private async Task RemoveDuplicateServer() private async Task RemoveDuplicateServer()
{ {
if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false)
{ {
return; return;
} }
var tuple = await ConfigHandler.DedupServerList(_config, _config.SubIndexId); var tuple = await ConfigHandler.DedupServerList(Config, Config.SubIndexId);
if (tuple.Item1 > 0 || tuple.Item2 > 0) if (tuple.Item1 > 0 || tuple.Item2 > 0)
{ {
await RefreshServers(); await RefreshServers();
@ -580,11 +580,11 @@ public class ProfilesViewModel : MyReactiveObject
private async Task CopyServer() private async Task CopyServer()
{ {
var lstSelected = await GetProfileItems(false); var lstSelected = await GetProfileItems(false);
if (lstSelected == null) if (lstSelected is null)
{ {
return; return;
} }
if (await ConfigHandler.CopyServer(_config, lstSelected) == 0) if (await ConfigHandler.CopyServer(Config, lstSelected) == 0)
{ {
await RefreshServers(); await RefreshServers();
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
@ -606,7 +606,7 @@ public class ProfilesViewModel : MyReactiveObject
{ {
return; return;
} }
if (indexId == _config.IndexId) if (indexId == Config.IndexId)
{ {
return; return;
} }
@ -617,7 +617,7 @@ public class ProfilesViewModel : MyReactiveObject
return; return;
} }
if (await ConfigHandler.SetDefaultServerIndex(_config, indexId) == 0) if (await ConfigHandler.SetDefaultServerIndex(Config, indexId) == 0)
{ {
await RefreshServers(); await RefreshServers();
Reload(); Reload();
@ -638,24 +638,24 @@ public class ProfilesViewModel : MyReactiveObject
return; return;
} }
await _updateView?.Invoke(EViewAction.ShareServer, url); await UpdateView?.Invoke(EViewAction.ShareServer, url);
} }
private async Task GenGroupMultipleServer(ECoreType coreType, EMultipleLoad multipleLoad) private async Task GenGroupMultipleServer(ECoreType coreType, EMultipleLoad multipleLoad)
{ {
var lstSelected = await GetProfileItems(true); var lstSelected = await GetProfileItems(true);
if (lstSelected == null) if (lstSelected is null)
{ {
return; 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) if (ret.Success != true)
{ {
NoticeManager.Instance.Enqueue(ResUI.OperationFailed); NoticeManager.Instance.Enqueue(ResUI.OperationFailed);
return; return;
} }
if (ret?.Data?.ToString() == _config.IndexId) if (ret?.Data?.ToString() == Config.IndexId)
{ {
await RefreshServers(); await RefreshServers();
Reload(); Reload();
@ -675,7 +675,7 @@ public class ProfilesViewModel : MyReactiveObject
_dicHeaderSort.TryAdd(colName, true); _dicHeaderSort.TryAdd(colName, true);
_dicHeaderSort.TryGetValue(colName, out var asc); _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; return;
} }
@ -685,7 +685,7 @@ public class ProfilesViewModel : MyReactiveObject
public async Task RemoveInvalidServerResult() public async Task RemoveInvalidServerResult()
{ {
var count = await ConfigHandler.RemoveInvalidServerResult(_config, _config.SubIndexId); var count = await ConfigHandler.RemoveInvalidServerResult(Config, Config.SubIndexId);
await RefreshServers(); await RefreshServers();
NoticeManager.Instance.Enqueue(string.Format(ResUI.RemoveInvalidServerResultTip, count)); NoticeManager.Instance.Enqueue(string.Format(ResUI.RemoveInvalidServerResultTip, count));
} }
@ -699,12 +699,12 @@ public class ProfilesViewModel : MyReactiveObject
} }
var lstSelected = await GetProfileItems(true); var lstSelected = await GetProfileItems(true);
if (lstSelected == null) if (lstSelected is null)
{ {
return; return;
} }
await ConfigHandler.MoveToGroup(_config, lstSelected, SelectedMoveToGroup.Id); await ConfigHandler.MoveToGroup(Config, lstSelected, SelectedMoveToGroup.Id);
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
await RefreshServers(); await RefreshServers();
@ -726,7 +726,7 @@ public class ProfilesViewModel : MyReactiveObject
{ {
return; return;
} }
if (await ConfigHandler.MoveServer(_config, _lstProfile, index, eMove) == 0) if (await ConfigHandler.MoveServer(_lstProfile, index, eMove) == 0)
{ {
await RefreshServers(); await RefreshServers();
} }
@ -737,7 +737,7 @@ public class ProfilesViewModel : MyReactiveObject
var targetIndex = ProfileItems.IndexOf(targetItem); var targetIndex = ProfileItems.IndexOf(targetItem);
if (startIndex >= 0 && targetIndex >= 0 && startIndex != targetIndex) 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(); await RefreshServers();
} }
@ -757,12 +757,12 @@ public class ProfilesViewModel : MyReactiveObject
} }
var lstSelected = await GetProfileItems(false); var lstSelected = await GetProfileItems(false);
if (lstSelected == null) if (lstSelected is null)
{ {
return; return;
} }
_speedtestService ??= new SpeedtestService(_config, async (SpeedTestResult result) => _speedtestService ??= new SpeedtestService(Config, async (SpeedTestResult result) =>
{ {
RxApp.MainThreadScheduler.Schedule(result, (scheduler, result) => RxApp.MainThreadScheduler.Schedule(result, (scheduler, result) =>
{ {
@ -808,13 +808,13 @@ public class ProfilesViewModel : MyReactiveObject
} }
else else
{ {
await _updateView?.Invoke(EViewAction.SetClipboardData, result.Data); await UpdateView?.Invoke(EViewAction.SetClipboardData, result.Data);
NoticeManager.Instance.SendMessage(ResUI.OperationSuccess); NoticeManager.Instance.SendMessage(ResUI.OperationSuccess);
} }
} }
else 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) public async Task Export2ShareUrlAsync(bool blEncode)
{ {
var lstSelected = await GetProfileItems(true); var lstSelected = await GetProfileItems(true);
if (lstSelected == null) if (lstSelected is null)
{ {
return; return;
} }
@ -858,11 +858,11 @@ public class ProfilesViewModel : MyReactiveObject
{ {
if (blEncode) if (blEncode)
{ {
await _updateView?.Invoke(EViewAction.SetClipboardData, Utils.Base64Encode(sb.ToString())); await UpdateView?.Invoke(EViewAction.SetClipboardData, Utils.Base64Encode(sb.ToString()));
} }
else else
{ {
await _updateView?.Invoke(EViewAction.SetClipboardData, sb.ToString()); await UpdateView?.Invoke(EViewAction.SetClipboardData, sb.ToString());
} }
NoticeManager.Instance.SendMessage(ResUI.BatchExportURLSuccessfully); NoticeManager.Instance.SendMessage(ResUI.BatchExportURLSuccessfully);
} }
@ -881,13 +881,13 @@ public class ProfilesViewModel : MyReactiveObject
} }
else else
{ {
item = await AppManager.Instance.GetSubItem(_config.SubIndexId); item = await AppManager.Instance.GetSubItem(Config.SubIndexId);
if (item is null) if (item is null)
{ {
return; return;
} }
} }
if (await _updateView?.Invoke(EViewAction.SubEditWindow, item) == true) if (await UpdateView?.Invoke(EViewAction.SubEditWindow, item) == true)
{ {
await RefreshSubscriptions(); await RefreshSubscriptions();
await SubSelectedChangedAsync(true); await SubSelectedChangedAsync(true);
@ -896,17 +896,17 @@ public class ProfilesViewModel : MyReactiveObject
private async Task DeleteSubAsync() private async Task DeleteSubAsync()
{ {
var item = await AppManager.Instance.GetSubItem(_config.SubIndexId); var item = await AppManager.Instance.GetSubItem(Config.SubIndexId);
if (item is null) if (item is null)
{ {
return; return;
} }
if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false)
{ {
return; return;
} }
await ConfigHandler.DeleteSubItem(_config, item.Id); await ConfigHandler.DeleteSubItem(Config, item.Id);
await RefreshSubscriptions(); await RefreshSubscriptions();
await SubSelectedChangedAsync(true); await SubSelectedChangedAsync(true);

View file

@ -27,8 +27,8 @@ public class RoutingRuleDetailsViewModel : MyReactiveObject
public RoutingRuleDetailsViewModel(RulesItem rulesItem, Func<EViewAction, object?, Task<bool>>? updateView) public RoutingRuleDetailsViewModel(RulesItem rulesItem, Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
SaveCmd = ReactiveCommand.CreateFromTask(async () => SaveCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -38,7 +38,7 @@ public class RoutingRuleDetailsViewModel : MyReactiveObject
if (rulesItem.Id.IsNullOrEmpty()) if (rulesItem.Id.IsNullOrEmpty())
{ {
rulesItem.Id = Utils.GetGuid(false); rulesItem.Id = Utils.GetGuid(false);
rulesItem.OutboundTag = Global.ProxyTag; rulesItem.OutboundTag = AppConfig.ProxyTag;
rulesItem.Enabled = true; rulesItem.Enabled = true;
SelectedSource = rulesItem; SelectedSource = rulesItem;
} }
@ -73,7 +73,7 @@ public class RoutingRuleDetailsViewModel : MyReactiveObject
} }
SelectedSource.Protocol = ProtocolItems?.ToList(); SelectedSource.Protocol = ProtocolItems?.ToList();
SelectedSource.InboundTag = InboundTagItems?.ToList(); SelectedSource.InboundTag = InboundTagItems?.ToList();
SelectedSource.RuleType = RuleType.IsNullOrEmpty() ? null : (ERuleType)Enum.Parse(typeof(ERuleType), RuleType); SelectedSource.RuleType = RuleType.IsNullOrEmpty() ? null : Enum.Parse<ERuleType>(RuleType);
var hasRule = SelectedSource.Domain?.Count > 0 var hasRule = SelectedSource.Domain?.Count > 0
|| SelectedSource.Ip?.Count > 0 || SelectedSource.Ip?.Count > 0
@ -88,6 +88,6 @@ public class RoutingRuleDetailsViewModel : MyReactiveObject
return; return;
} }
//NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); //NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess);
await _updateView?.Invoke(EViewAction.CloseWindow, null); await UpdateView?.Invoke(EViewAction.CloseWindow, null);
} }
} }

View file

@ -29,12 +29,12 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
public RoutingRuleSettingViewModel(RoutingItem routingItem, Func<EViewAction, object?, Task<bool>>? updateView) public RoutingRuleSettingViewModel(RoutingItem routingItem, Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
var canEditRemove = this.WhenAnyValue( var canEditRemove = this.WhenAnyValue(
x => x.SelectedSource, x => x.SelectedSource,
selectedSource => selectedSource != null && !selectedSource.OutboundTag.IsNullOrEmpty()); selectedSource => selectedSource is not null && !selectedSource.OutboundTag.IsNullOrEmpty());
RuleAddCmd = ReactiveCommand.CreateFromTask(async () => RuleAddCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -42,7 +42,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
}); });
ImportRulesFromFileCmd = ReactiveCommand.CreateFromTask(async () => ImportRulesFromFileCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
await _updateView?.Invoke(EViewAction.ImportRulesFromFile, null); await UpdateView?.Invoke(EViewAction.ImportRulesFromFile, null);
}); });
ImportRulesFromClipboardCmd = ReactiveCommand.CreateFromTask(async () => ImportRulesFromClipboardCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -129,7 +129,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
return; return;
} }
} }
if (await _updateView?.Invoke(EViewAction.RoutingRuleDetailsWindow, item) == true) if (await UpdateView?.Invoke(EViewAction.RoutingRuleDetailsWindow, item) == true)
{ {
if (blNew) if (blNew)
{ {
@ -146,14 +146,14 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
NoticeManager.Instance.Enqueue(ResUI.PleaseSelectRules); NoticeManager.Instance.Enqueue(ResUI.PleaseSelectRules);
return; return;
} }
if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false)
{ {
return; return;
} }
foreach (var it in SelectedSources ?? [SelectedSource]) foreach (var it in SelectedSources ?? [SelectedSource])
{ {
var item = _rules.FirstOrDefault(t => t.Id == it?.Id); var item = _rules.FirstOrDefault(t => t.Id == it?.Id);
if (item != null) if (item is not null)
{ {
_rules.Remove(item); _rules.Remove(item);
} }
@ -189,7 +189,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, 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); var item = _rules.FirstOrDefault(t => t.Id == SelectedSource?.Id);
if (item == null) if (item is null)
{ {
return; return;
} }
@ -229,10 +229,10 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
item.RuleNum = _rules.Count; item.RuleNum = _rules.Count;
item.RuleSet = JsonUtils.Serialize(_rules, false); 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); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); UpdateView?.Invoke(EViewAction.CloseWindow, null);
} }
else else
{ {
@ -264,9 +264,9 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
public async Task ImportRulesFromClipboardAsync(string? clipboardData) 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; return;
} }
var ret = await AddBatchRoutingRulesAsync(SelectedRouting, clipboardData); var ret = await AddBatchRoutingRulesAsync(SelectedRouting, clipboardData);
@ -299,7 +299,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
private async Task<int> AddBatchRoutingRulesAsync(RoutingItem routingItem, string? clipboardData) private async Task<int> AddBatchRoutingRulesAsync(RoutingItem routingItem, string? clipboardData)
{ {
var blReplace = false; var blReplace = false;
if (await _updateView?.Invoke(EViewAction.AddBatchRoutingRulesYesNo, null) == false) if (await UpdateView?.Invoke(EViewAction.AddBatchRoutingRulesYesNo, null) == false)
{ {
blReplace = true; blReplace = true;
} }
@ -308,7 +308,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
return -1; return -1;
} }
var lstRules = JsonUtils.Deserialize<List<RulesItem>>(clipboardData); var lstRules = JsonUtils.Deserialize<List<RulesItem>>(clipboardData);
if (lstRules == null) if (lstRules is null)
{ {
return -1; return -1;
} }

View file

@ -29,12 +29,12 @@ public class RoutingSettingViewModel : MyReactiveObject
public RoutingSettingViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public RoutingSettingViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
var canEditRemove = this.WhenAnyValue( var canEditRemove = this.WhenAnyValue(
x => x.SelectedSource, x => x.SelectedSource,
selectedSource => selectedSource != null && !selectedSource.Remarks.IsNullOrEmpty()); selectedSource => selectedSource is not null && !selectedSource.Remarks.IsNullOrEmpty());
RoutingAdvancedAddCmd = ReactiveCommand.CreateFromTask(async () => RoutingAdvancedAddCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -65,10 +65,10 @@ public class RoutingSettingViewModel : MyReactiveObject
{ {
SelectedSource = new(); SelectedSource = new();
DomainStrategy = _config.RoutingBasicItem.DomainStrategy; DomainStrategy = Config.RoutingBasicItem.DomainStrategy;
DomainStrategy4Singbox = _config.RoutingBasicItem.DomainStrategy4Singbox; DomainStrategy4Singbox = Config.RoutingBasicItem.DomainStrategy4Singbox;
await ConfigHandler.InitBuiltinRouting(_config); await ConfigHandler.InitBuiltinRouting(Config);
await RefreshRoutingItems(); await RefreshRoutingItems();
} }
@ -98,13 +98,13 @@ public class RoutingSettingViewModel : MyReactiveObject
private async Task SaveRoutingAsync() private async Task SaveRoutingAsync()
{ {
_config.RoutingBasicItem.DomainStrategy = DomainStrategy; Config.RoutingBasicItem.DomainStrategy = DomainStrategy;
_config.RoutingBasicItem.DomainStrategy4Singbox = DomainStrategy4Singbox; Config.RoutingBasicItem.DomainStrategy4Singbox = DomainStrategy4Singbox;
if (await ConfigHandler.SaveConfig(_config) == 0) if (await ConfigHandler.SaveConfig(Config) == 0)
{ {
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); UpdateView?.Invoke(EViewAction.CloseWindow, null);
} }
else else
{ {
@ -129,7 +129,7 @@ public class RoutingSettingViewModel : MyReactiveObject
return; return;
} }
} }
if (await _updateView?.Invoke(EViewAction.RoutingRuleSettingWindow, item) == true) if (await UpdateView?.Invoke(EViewAction.RoutingRuleSettingWindow, item) == true)
{ {
await RefreshRoutingItems(); await RefreshRoutingItems();
IsModified = true; IsModified = true;
@ -143,14 +143,14 @@ public class RoutingSettingViewModel : MyReactiveObject
NoticeManager.Instance.Enqueue(ResUI.PleaseSelectRules); NoticeManager.Instance.Enqueue(ResUI.PleaseSelectRules);
return; return;
} }
if (await _updateView?.Invoke(EViewAction.ShowYesNo, null) == false) if (await UpdateView?.Invoke(EViewAction.ShowYesNo, null) == false)
{ {
return; return;
} }
foreach (var it in SelectedSources ?? [SelectedSource]) foreach (var it in SelectedSources ?? [SelectedSource])
{ {
var item = await AppManager.Instance.GetRoutingItem(it?.Id); var item = await AppManager.Instance.GetRoutingItem(it?.Id);
if (item != null) if (item is not null)
{ {
await ConfigHandler.RemoveRoutingItem(item); await ConfigHandler.RemoveRoutingItem(item);
} }
@ -169,7 +169,7 @@ public class RoutingSettingViewModel : MyReactiveObject
return; return;
} }
if (await ConfigHandler.SetDefaultRouting(_config, item) == 0) if (await ConfigHandler.SetDefaultRouting(Config, item) == 0)
{ {
await RefreshRoutingItems(); await RefreshRoutingItems();
IsModified = true; IsModified = true;
@ -178,7 +178,7 @@ public class RoutingSettingViewModel : MyReactiveObject
private async Task RoutingAdvancedImportRules() private async Task RoutingAdvancedImportRules()
{ {
if (await ConfigHandler.InitRouting(_config, true) == 0) if (await ConfigHandler.InitRouting(Config, true) == 0)
{ {
await RefreshRoutingItems(); await RefreshRoutingItems();
IsModified = true; IsModified = true;

View file

@ -3,6 +3,9 @@ namespace ServiceLib.ViewModels;
public class StatusBarViewModel : MyReactiveObject public class StatusBarViewModel : MyReactiveObject
{ {
private static readonly Lazy<StatusBarViewModel> _instance = new(() => new(null)); private static readonly Lazy<StatusBarViewModel> _instance = new(() => new(null));
private static readonly CompositeFormat _speedDisplayFormat = CompositeFormat.Parse(ResUI.SpeedDisplayText);
public static StatusBarViewModel Instance => _instance.Value; public static StatusBarViewModel Instance => _instance.Value;
#region ObservableCollection #region ObservableCollection
@ -94,35 +97,35 @@ public class StatusBarViewModel : MyReactiveObject
public StatusBarViewModel(Func<EViewAction, object?, Task<bool>>? updateView) public StatusBarViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
SelectedRouting = new(); SelectedRouting = new();
SelectedServer = new(); SelectedServer = new();
RunningServerToolTipText = "-"; RunningServerToolTipText = "-";
BlSystemProxyPacVisible = Utils.IsWindows(); BlSystemProxyPacVisible = Utils.IsWindows();
BlIsNonWindows = Utils.IsNonWindows(); BlIsNonWindows = Utils.IsNonWindows();
if (_config.TunModeItem.EnableTun && AllowEnableTun()) if (Config.TunModeItem.EnableTun && AllowEnableTun())
{ {
EnableTun = true; EnableTun = true;
} }
else else
{ {
_config.TunModeItem.EnableTun = EnableTun = false; Config.TunModeItem.EnableTun = EnableTun = false;
} }
#region WhenAnyValue && ReactiveCommand #region WhenAnyValue && ReactiveCommand
this.WhenAnyValue( this.WhenAnyValue(
x => x.SelectedRouting, x => x.SelectedRouting,
y => y != null && !y.Remarks.IsNullOrEmpty()) y => y is not null && !y.Remarks.IsNullOrEmpty())
.Subscribe(async c => await RoutingSelectedChangedAsync(c)); .Subscribe(async c => await RoutingSelectedChangedAsync(c));
this.WhenAnyValue( this.WhenAnyValue(
x => x.SelectedServer, x => x.SelectedServer,
y => y != null && !y.Text.IsNullOrEmpty()) y => y is not null && !y.Text.IsNullOrEmpty())
.Subscribe(ServerSelectedChanged); .Subscribe(ServerSelectedChanged);
SystemProxySelected = (int)_config.SystemProxyItem.SysProxyType; SystemProxySelected = (int)Config.SystemProxyItem.SysProxyType;
this.WhenAnyValue( this.WhenAnyValue(
x => x.SystemProxySelected, x => x.SystemProxySelected,
y => y >= 0) y => y >= 0)
@ -131,7 +134,7 @@ public class StatusBarViewModel : MyReactiveObject
this.WhenAnyValue( this.WhenAnyValue(
x => x.EnableTun, x => x.EnableTun,
y => y == true) y => y == true)
.Subscribe(async c => await DoEnableTun(c)); .Subscribe(async c => await DoEnableTun());
CopyProxyCmdToClipboardCmd = ReactiveCommand.CreateFromTask(async () => CopyProxyCmdToClipboardCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -193,7 +196,7 @@ public class StatusBarViewModel : MyReactiveObject
#region AppEvents #region AppEvents
if (updateView != null) if (updateView is not null)
{ {
InitUpdateView(updateView); InitUpdateView(updateView);
} }
@ -230,16 +233,16 @@ public class StatusBarViewModel : MyReactiveObject
private async Task Init() private async Task Init()
{ {
await ConfigHandler.InitBuiltinRouting(_config); await ConfigHandler.InitBuiltinRouting(Config);
await RefreshRoutingsMenu(); await RefreshRoutingsMenu();
await InboundDisplayStatus(); await InboundDisplayStatus();
await ChangeSystemProxyAsync(_config.SystemProxyItem.SysProxyType, true); await ChangeSystemProxyAsync(Config.SystemProxyItem.SysProxyType, true);
} }
public void InitUpdateView(Func<EViewAction, object?, Task<bool>>? updateView) public void InitUpdateView(Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_updateView = updateView; UpdateView = updateView;
if (_updateView != null) if (UpdateView is not null)
{ {
AppEvents.ProfilesRefreshRequested AppEvents.ProfilesRefreshRequested
.AsObservable() .AsObservable()
@ -251,33 +254,33 @@ public class StatusBarViewModel : MyReactiveObject
private async Task CopyProxyCmdToClipboard() private async Task CopyProxyCmdToClipboard()
{ {
var cmd = Utils.IsWindows() ? "set" : "export"; 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(); var sb = new StringBuilder();
sb.AppendLine($"{cmd} http_proxy={Global.HttpProtocol}{address}"); sb.AppendLine($"{cmd} http_proxy={AppConfig.HttpProtocol}{address}");
sb.AppendLine($"{cmd} https_proxy={Global.HttpProtocol}{address}"); sb.AppendLine($"{cmd} https_proxy={AppConfig.HttpProtocol}{address}");
sb.AppendLine($"{cmd} all_proxy={Global.Socks5Protocol}{address}"); sb.AppendLine($"{cmd} all_proxy={AppConfig.Socks5Protocol}{address}");
sb.AppendLine(""); sb.AppendLine("");
sb.AppendLine($"{cmd} HTTP_PROXY={Global.HttpProtocol}{address}"); sb.AppendLine($"{cmd} HTTP_PROXY={AppConfig.HttpProtocol}{address}");
sb.AppendLine($"{cmd} HTTPS_PROXY={Global.HttpProtocol}{address}"); sb.AppendLine($"{cmd} HTTPS_PROXY={AppConfig.HttpProtocol}{address}");
sb.AppendLine($"{cmd} ALL_PROXY={Global.Socks5Protocol}{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(); AppEvents.AddServerViaClipboardRequested.Publish();
await Task.Delay(1000); await Task.Delay(1000);
} }
private async Task AddServerViaScan() private static async Task AddServerViaScan()
{ {
AppEvents.AddServerViaScanRequested.Publish(); AppEvents.AddServerViaScanRequested.Publish();
await Task.Delay(1000); await Task.Delay(1000);
} }
private async Task UpdateSubscriptionProcess(bool blProxy) private static async Task UpdateSubscriptionProcess(bool blProxy)
{ {
AppEvents.SubscriptionsUpdateRequested.Publish(blProxy); AppEvents.SubscriptionsUpdateRequested.Publish(blProxy);
await Task.Delay(1000); await Task.Delay(1000);
@ -288,8 +291,8 @@ public class StatusBarViewModel : MyReactiveObject
await RefreshServersMenu(); await RefreshServersMenu();
//display running server //display running server
var running = await ConfigHandler.GetDefaultServer(_config); var running = await ConfigHandler.GetDefaultServer(Config);
if (running != null) if (running is not null)
{ {
RunningServerDisplay = RunningServerDisplay =
RunningServerToolTipText = running.GetSummary(); RunningServerToolTipText = running.GetSummary();
@ -303,10 +306,10 @@ public class StatusBarViewModel : MyReactiveObject
private async Task RefreshServersMenu() private async Task RefreshServersMenu()
{ {
var lstModel = await AppManager.Instance.ProfileItems(_config.SubIndexId, ""); var lstModel = await AppManager.Instance.ProfileItems(Config.SubIndexId, "");
Servers.Clear(); Servers.Clear();
if (lstModel.Count > _config.GuiItem.TrayMenuServersLimit) if (lstModel.Count > Config.GuiItem.TrayMenuServersLimit)
{ {
BlServers = false; BlServers = false;
return; return;
@ -320,7 +323,7 @@ public class StatusBarViewModel : MyReactiveObject
var item = new ComboItem() { ID = it.IndexId, Text = name }; var item = new ComboItem() { ID = it.IndexId, Text = name };
Servers.Add(item); Servers.Add(item);
if (_config.IndexId == it.IndexId) if (Config.IndexId == it.IndexId)
{ {
SelectedServer = item; SelectedServer = item;
} }
@ -333,7 +336,7 @@ public class StatusBarViewModel : MyReactiveObject
{ {
return; return;
} }
if (SelectedServer == null) if (SelectedServer is null)
{ {
return; return;
} }
@ -346,8 +349,8 @@ public class StatusBarViewModel : MyReactiveObject
public async Task TestServerAvailability() public async Task TestServerAvailability()
{ {
var item = await ConfigHandler.GetDefaultServer(_config); var item = await ConfigHandler.GetDefaultServer(Config);
if (item == null) if (item is null)
{ {
return; return;
} }
@ -380,21 +383,21 @@ public class StatusBarViewModel : MyReactiveObject
private async Task SetListenerType(ESysProxyType type) private async Task SetListenerType(ESysProxyType type)
{ {
if (_config.SystemProxyItem.SysProxyType == type) if (Config.SystemProxyItem.SysProxyType == type)
{ {
return; return;
} }
_config.SystemProxyItem.SysProxyType = type; Config.SystemProxyItem.SysProxyType = type;
await ChangeSystemProxyAsync(type, true); 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; SystemProxySelected = (int)Config.SystemProxyItem.SysProxyType;
await ConfigHandler.SaveConfig(_config); await ConfigHandler.SaveConfig(Config);
} }
public async Task ChangeSystemProxyAsync(ESysProxyType type, bool blChange) public async Task ChangeSystemProxyAsync(ESysProxyType type, bool blChange)
{ {
await SysProxyHandler.UpdateSysProxy(_config, false); await SysProxyHandler.UpdateSysProxy(Config, false);
BlSystemProxyClear = type == ESysProxyType.ForcedClear; BlSystemProxyClear = type == ESysProxyType.ForcedClear;
BlSystemProxySet = type == ESysProxyType.ForcedChange; BlSystemProxySet = type == ESysProxyType.ForcedChange;
@ -403,7 +406,7 @@ public class StatusBarViewModel : MyReactiveObject
if (blChange) if (blChange)
{ {
_updateView?.Invoke(EViewAction.DispatcherRefreshIcon, null); UpdateView?.Invoke(EViewAction.DispatcherRefreshIcon, null);
} }
} }
@ -430,7 +433,7 @@ public class StatusBarViewModel : MyReactiveObject
return; return;
} }
if (SelectedRouting == null) if (SelectedRouting is null)
{ {
return; return;
} }
@ -441,11 +444,11 @@ public class StatusBarViewModel : MyReactiveObject
return; return;
} }
if (await ConfigHandler.SetDefaultRouting(_config, item) == 0) if (await ConfigHandler.SetDefaultRouting(Config, item) == 0)
{ {
NoticeManager.Instance.SendMessageEx(ResUI.TipChangeRouting); NoticeManager.Instance.SendMessageEx(ResUI.TipChangeRouting);
AppEvents.ReloadRequested.Publish(); AppEvents.ReloadRequested.Publish();
_updateView?.Invoke(EViewAction.DispatcherRefreshIcon, null); UpdateView?.Invoke(EViewAction.DispatcherRefreshIcon, null);
} }
} }
@ -455,46 +458,46 @@ public class StatusBarViewModel : MyReactiveObject
{ {
return; return;
} }
if (_config.SystemProxyItem.SysProxyType == (ESysProxyType)SystemProxySelected) if (Config.SystemProxyItem.SysProxyType == (ESysProxyType)SystemProxySelected)
{ {
return; return;
} }
await SetListenerType((ESysProxyType)SystemProxySelected); 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; return;
} }
_config.TunModeItem.EnableTun = EnableTun; Config.TunModeItem.EnableTun = EnableTun;
if (EnableTun && AllowEnableTun() == false) if (EnableTun && AllowEnableTun() == false)
{ {
// When running as a non-administrator, reboot to administrator mode // When running as a non-administrator, reboot to administrator mode
if (Utils.IsWindows()) if (Utils.IsWindows())
{ {
_config.TunModeItem.EnableTun = false; Config.TunModeItem.EnableTun = false;
await AppManager.Instance.RebootAsAdmin(); await AppManager.Instance.RebootAsAdmin();
return; return;
} }
else else
{ {
bool? passwordResult = await _updateView?.Invoke(EViewAction.PasswordInput, null); bool? passwordResult = await UpdateView?.Invoke(EViewAction.PasswordInput, null);
if (passwordResult == false) if (passwordResult == false)
{ {
_config.TunModeItem.EnableTun = false; Config.TunModeItem.EnableTun = false;
return; return;
} }
} }
} }
await ConfigHandler.SaveConfig(_config); await ConfigHandler.SaveConfig(Config);
AppEvents.ReloadRequested.Publish(); AppEvents.ReloadRequested.Publish();
} }
private bool AllowEnableTun() private static bool AllowEnableTun()
{ {
if (Utils.IsWindows()) if (Utils.IsWindows())
{ {
@ -519,30 +522,30 @@ public class StatusBarViewModel : MyReactiveObject
{ {
StringBuilder sb = new(); StringBuilder sb = new();
sb.Append($"[{EInboundProtocol.mixed}:{AppManager.Instance.GetLocalPort(EInboundProtocol.socks)}"); 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($",{AppManager.Instance.GetLocalPort(EInboundProtocol.socks2)}");
} }
sb.Append(']'); sb.Append(']');
InboundDisplay = $"{ResUI.LabLocal}:{sb}"; 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.socks3)}]"
: $"[{EInboundProtocol.mixed}:{AppManager.Instance.GetLocalPort(EInboundProtocol.socks)}]"; : $"[{EInboundProtocol.mixed}:{AppManager.Instance.GetLocalPort(EInboundProtocol.socks)}]";
InboundLanDisplay = $"{ResUI.LabLAN}:{lan}"; InboundLanDisplay = $"{ResUI.LabLAN}:{lan}";
} }
else else
{ {
InboundLanDisplay = $"{ResUI.LabLAN}:{Global.None}"; InboundLanDisplay = $"{ResUI.LabLAN}:{AppConfig.None}";
} }
await Task.CompletedTask; await Task.CompletedTask;
} }
public async Task UpdateStatistics(ServerSpeedItem update) public async Task UpdateStatistics(ServerSpeedItem update)
{ {
if (!_config.GuiItem.DisplayRealTimeSpeed) if (!Config.GuiItem.DisplayRealTimeSpeed)
{ {
return; return;
} }
@ -551,13 +554,13 @@ public class StatusBarViewModel : MyReactiveObject
{ {
if (AppManager.Instance.IsRunningCore(ECoreType.sing_box)) 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; SpeedDirectDisplay = string.Empty;
} }
else else
{ {
SpeedProxyDisplay = string.Format(ResUI.SpeedDisplayText, Global.ProxyTag, Utils.HumanFy(update.ProxyUp), Utils.HumanFy(update.ProxyDown)); SpeedProxyDisplay = string.Format(CultureInfo.CurrentCulture, _speedDisplayFormat, AppConfig.ProxyTag, Utils.HumanFy(update.ProxyUp), Utils.HumanFy(update.ProxyDown));
SpeedDirectDisplay = string.Format(ResUI.SpeedDisplayText, Global.DirectTag, Utils.HumanFy(update.DirectUp), Utils.HumanFy(update.DirectDown)); SpeedDirectDisplay = string.Format(CultureInfo.CurrentCulture, _speedDisplayFormat, AppConfig.DirectTag, Utils.HumanFy(update.DirectUp), Utils.HumanFy(update.DirectDown));
} }
} }
catch catch

View file

@ -9,8 +9,8 @@ public class SubEditViewModel : MyReactiveObject
public SubEditViewModel(SubItem subItem, Func<EViewAction, object?, Task<bool>>? updateView) public SubEditViewModel(SubItem subItem, Func<EViewAction, object?, Task<bool>>? updateView)
{ {
_config = AppManager.Instance.Config; Config = AppManager.Instance.Config;
_updateView = updateView; UpdateView = updateView;
SaveCmd = ReactiveCommand.CreateFromTask(async () => SaveCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
@ -33,23 +33,23 @@ public class SubEditViewModel : MyReactiveObject
if (url.IsNotEmpty()) if (url.IsNotEmpty())
{ {
var uri = Utils.TryUri(url); var uri = Utils.TryUri(url);
if (uri == null) if (uri is null)
{ {
NoticeManager.Instance.Enqueue(ResUI.InvalidUrlTip); NoticeManager.Instance.Enqueue(ResUI.InvalidUrlTip);
return; return;
} }
//Do not allow http protocol //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); NoticeManager.Instance.Enqueue(ResUI.InsecureUrlProtocol);
//return; //return;
} }
} }
if (await ConfigHandler.AddSubItem(_config, SelectedSource) == 0) if (await ConfigHandler.AddSubItem(Config, SelectedSource) == 0)
{ {
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess); NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); UpdateView?.Invoke(EViewAction.CloseWindow, null);
} }
else else
{ {

Some files were not shown because too many files have changed in this diff Show more