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>
<OutputType>Exe</OutputType>
<NeutralLanguage>en-US</NeutralLanguage>
</PropertyGroup>
<ItemGroup>

View file

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

View file

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

View file

@ -8,7 +8,7 @@
<TargetFramework>net10.0</TargetFramework>
<TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
<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>
<ImplicitUsings>enable</ImplicitUsings>
<Authors>2dust</Authors>

View file

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

View file

@ -2,6 +2,6 @@ namespace ServiceLib.Base;
public class MyReactiveObject : ReactiveObject
{
protected static Config? _config;
protected Func<EViewAction, object?, Task<bool>>? _updateView;
protected static Config? Config { get; set; }
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)
@ -57,17 +57,26 @@ public static class Extension
public static string RemovePrefix(this string value, string prefix)
{
return value.StartsWith(prefix) ? value[prefix.Length..] : value;
return value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? value[prefix.Length..] : value;
}
public static string UpperFirstChar(this string value)
public static string UpperFirstChar(this string? value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
return char.ToUpper(value.First()) + value[1..];
if (char.IsUpper(value[0]))
{
return value;
}
return string.Create(value.Length, value, (span, oldStr) =>
{
oldStr.AsSpan().CopyTo(span);
span[0] = char.ToUpper(span[0], CultureInfo.InvariantCulture);
});
}
public static string AppendQuotes(this string value)

View file

@ -41,7 +41,7 @@ public static class FileUtils
{
FileInfo fileInfo = new(fileName);
using var originalFileStream = fileInfo.OpenRead();
using var decompressedFileStream = File.Create(toName != null ? Path.Combine(toPath, toName) : toPath);
using var decompressedFileStream = File.Create(toName is not null ? Path.Combine(toPath, toName) : toPath);
using GZipStream decompressionStream = new(originalFileStream, CompressionMode.Decompress);
decompressionStream.CopyTo(decompressedFileStream);
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -7,7 +7,7 @@ public class AnytlsFmt : BaseFmt
msg = ResUI.ConfigurationFormatIncorrect;
var parsedUrl = Utils.TryUri(str);
if (parsedUrl == null)
if (parsedUrl is null)
{
return null;
}
@ -30,7 +30,7 @@ public class AnytlsFmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
if (item == null)
if (item is null)
{
return null;
}
@ -41,7 +41,7 @@ public class AnytlsFmt : BaseFmt
}
var pw = item.Id;
var dicQuery = new Dictionary<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);
}

View file

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

View file

@ -33,58 +33,29 @@ public class FmtHandler
public static ProfileItem? ResolveConfig(string config, out string msg)
{
msg = ResUI.ConfigurationFormatIncorrect;
var span = config.AsSpan().Trim();
if (span.IsEmpty)
{
msg = ResUI.FailedReadConfiguration;
return null;
}
try
{
var str = config.TrimEx();
if (str.IsNullOrEmpty())
return span switch
{
msg = ResUI.FailedReadConfiguration;
return null;
}
if (str.StartsWith(Global.ProtocolShares[EConfigType.VMess]))
{
return VmessFmt.Resolve(str, out msg);
}
else if (str.StartsWith(Global.ProtocolShares[EConfigType.Shadowsocks]))
{
return ShadowsocksFmt.Resolve(str, out msg);
}
else if (str.StartsWith(Global.ProtocolShares[EConfigType.SOCKS]))
{
return SocksFmt.Resolve(str, out msg);
}
else if (str.StartsWith(Global.ProtocolShares[EConfigType.Trojan]))
{
return TrojanFmt.Resolve(str, out msg);
}
else if (str.StartsWith(Global.ProtocolShares[EConfigType.VLESS]))
{
return VLESSFmt.Resolve(str, out msg);
}
else if (str.StartsWith(Global.ProtocolShares[EConfigType.Hysteria2]) || str.StartsWith(Global.Hysteria2ProtocolShare))
{
return Hysteria2Fmt.Resolve(str, out msg);
}
else if (str.StartsWith(Global.ProtocolShares[EConfigType.TUIC]))
{
return TuicFmt.Resolve(str, out msg);
}
else if (str.StartsWith(Global.ProtocolShares[EConfigType.WireGuard]))
{
return WireguardFmt.Resolve(str, out msg);
}
else if (str.StartsWith(Global.ProtocolShares[EConfigType.Anytls]))
{
return AnytlsFmt.Resolve(str, out msg);
}
else
{
msg = ResUI.NonvmessOrssProtocol;
return null;
}
_ when IsProtocol(span, EConfigType.VMess) => VmessFmt.Resolve(config, out msg),
_ when IsProtocol(span, EConfigType.Shadowsocks) => ShadowsocksFmt.Resolve(config, out msg),
_ when IsProtocol(span, EConfigType.SOCKS) => SocksFmt.Resolve(config, out msg),
_ when IsProtocol(span, EConfigType.Trojan) => TrojanFmt.Resolve(config, out msg),
_ when IsProtocol(span, EConfigType.VLESS) => VLESSFmt.Resolve(config, out msg),
_ when IsProtocol(span, EConfigType.Hysteria2) || span.StartsWith(AppConfig.Hysteria2ProtocolShare,
StringComparison.OrdinalIgnoreCase) => Hysteria2Fmt.Resolve(config, out msg),
_ when IsProtocol(span, EConfigType.TUIC) => TuicFmt.Resolve(config, out msg),
_ when IsProtocol(span, EConfigType.WireGuard) => WireguardFmt.Resolve(config, out msg),
_ when IsProtocol(span, EConfigType.Anytls) => AnytlsFmt.Resolve(config, out msg),
_ => HandleUnknown(out msg)
};
}
catch (Exception ex)
{
@ -93,4 +64,16 @@ public class FmtHandler
return null;
}
}
private static bool IsProtocol(ReadOnlySpan<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);
if (url == null)
if (url is null)
{
return null;
}
@ -35,13 +35,11 @@ public class Hysteria2Fmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
if (item == null)
if (item is null)
{
return null;
}
var url = string.Empty;
var remark = string.Empty;
if (item.Remarks.IsNotEmpty())
{

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -2,7 +2,7 @@ namespace ServiceLib.Handler.SysProxy;
public static class ProxySettingLinux
{
private static readonly string _proxySetFileName = $"{Global.ProxySetLinuxShellFileName.Replace(Global.NamespaceSample, "")}.sh";
private static readonly string _proxySetFileName = $"{AppConfig.ProxySetLinuxShellFileName.Replace(AppConfig.NamespaceSample, "")}.sh";
public static async Task SetProxy(string host, int port, string exceptions)
{
@ -21,7 +21,7 @@ public static class ProxySettingLinux
var customSystemProxyScriptPath = AppManager.Instance.Config.SystemProxyItem?.CustomSystemProxyScriptPath;
var fileName = (customSystemProxyScriptPath.IsNotEmpty() && File.Exists(customSystemProxyScriptPath))
? customSystemProxyScriptPath
: await FileUtils.CreateLinuxShellFile(_proxySetFileName, EmbedUtils.GetEmbedText(Global.ProxySetLinuxShellFileName), false);
: await FileUtils.CreateLinuxShellFile(_proxySetFileName, EmbedUtils.GetEmbedText(AppConfig.ProxySetLinuxShellFileName), false);
// TODO: temporarily notify which script is being used
NoticeManager.Instance.SendMessage(fileName);

View file

@ -2,7 +2,7 @@ namespace ServiceLib.Handler.SysProxy;
public static class ProxySettingOSX
{
private static readonly string _proxySetFileName = $"{Global.ProxySetOSXShellFileName.Replace(Global.NamespaceSample, "")}.sh";
private static readonly string _proxySetFileName = $"{AppConfig.ProxySetOSXShellFileName.Replace(AppConfig.NamespaceSample, "")}.sh";
public static async Task SetProxy(string host, int port, string exceptions)
{
@ -26,7 +26,7 @@ public static class ProxySettingOSX
var customSystemProxyScriptPath = AppManager.Instance.Config.SystemProxyItem?.CustomSystemProxyScriptPath;
var fileName = (customSystemProxyScriptPath.IsNotEmpty() && File.Exists(customSystemProxyScriptPath))
? customSystemProxyScriptPath
: await FileUtils.CreateLinuxShellFile(_proxySetFileName, EmbedUtils.GetEmbedText(Global.ProxySetOSXShellFileName), false);
: await FileUtils.CreateLinuxShellFile(_proxySetFileName, EmbedUtils.GetEmbedText(AppConfig.ProxySetOSXShellFileName), false);
// TODO: temporarily notify which script is being used
NoticeManager.Instance.SendMessage(fileName);

View file

@ -2,7 +2,7 @@ using static ServiceLib.Handler.SysProxy.ProxySettingWindows.InternetConnectionO
namespace ServiceLib.Handler.SysProxy;
public static class ProxySettingWindows
public static partial class ProxySettingWindows
{
private const string _regPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
@ -121,7 +121,7 @@ public static class ProxySettingWindows
// default stuff
list.dwSize = Marshal.SizeOf(list);
if (connectionName != null)
if (connectionName is not null)
{
list.szConnection = Marshal.StringToHGlobalAuto(connectionName); // !! remember to deallocate memory 3
}
@ -201,29 +201,29 @@ public static class ProxySettingWindows
/// </summary>
/// <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>
private static IEnumerable<string> EnumerateRasEntries()
private static List<string> EnumerateRasEntries()
{
var entries = 0;
// attempt to query with 1 entry buffer
var rasEntryNames = new RASENTRYNAME[1];
var bufferSize = Marshal.SizeOf(typeof(RASENTRYNAME));
rasEntryNames[0].dwSize = Marshal.SizeOf(typeof(RASENTRYNAME));
var bufferSize = Marshal.SizeOf<RASENTRYNAME>();
rasEntryNames[0].dwSize = Marshal.SizeOf<RASENTRYNAME>();
var result = NativeMethods.RasEnumEntries(null, null, rasEntryNames, ref bufferSize, ref entries);
// increase buffer if the buffer is not large enough
if (result == (uint)ErrorCode.ERROR_BUFFER_TOO_SMALL)
{
rasEntryNames = new RASENTRYNAME[bufferSize / Marshal.SizeOf(typeof(RASENTRYNAME))];
rasEntryNames = new RASENTRYNAME[bufferSize / Marshal.SizeOf<RASENTRYNAME>()];
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);
}
if (result == 0)
{
var entryNames = new List<string>();
var entryNames = new List<string>(entries);
for (var i = 0; i < entries; i++)
{
entryNames.Add(rasEntryNames[i].szEntryName);
@ -231,7 +231,7 @@ public static class ProxySettingWindows
return entryNames;
}
throw new ApplicationException($"RasEnumEntries failed with error code: {result}");
throw new Win32Exception((int)result);
}
#region WinInet structures
@ -340,11 +340,11 @@ public static class ProxySettingWindows
#endregion WinInet enums
internal static class NativeMethods
internal static partial class NativeMethods
{
[DllImport("WinInet.dll", SetLastError = true, CharSet = CharSet.Auto)]
[LibraryImport("WinInet.dll", EntryPoint = "InternetSetOptionW", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool InternetSetOption(nint hInternet, InternetOption dwOption, nint lpBuffer, int dwBufferLength);
public static partial bool InternetSetOption(nint hInternet, InternetOption dwOption, nint lpBuffer, int dwBufferLength);
[DllImport("Rasapi32.dll", CharSet = CharSet.Auto)]
public static extern uint RasEnumEntries(

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -16,7 +16,7 @@ public partial class CoreConfigSingboxService
{
type = EInboundProtocol.mixed.ToString(),
tag = EInboundProtocol.socks.ToString(),
listen = Global.Loopback,
listen = AppConfig.Loopback,
};
singboxConfig.inbounds.Add(inbound);
@ -53,14 +53,14 @@ public partial class CoreConfigSingboxService
{
if (_config.TunModeItem.Mtu <= 0)
{
_config.TunModeItem.Mtu = Global.TunMtus.First();
_config.TunModeItem.Mtu = AppConfig.TunMtus.First();
}
if (_config.TunModeItem.Stack.IsNullOrEmpty())
{
_config.TunModeItem.Stack = Global.TunStacks.First();
_config.TunModeItem.Stack = AppConfig.TunStacks.First();
}
var tunInbound = JsonUtils.Deserialize<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.mtu = _config.TunModeItem.Mtu;
tunInbound.auto_route = _config.TunModeItem.AutoRoute;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -2,7 +2,7 @@ namespace ServiceLib.Services.CoreConfig;
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
var subjectSelectors = new List<string>();
@ -83,7 +83,7 @@ public partial class CoreConfigV2rayService
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
{
@ -93,7 +93,7 @@ public partial class CoreConfigV2rayService
EMultipleLoad.LeastLoad => "leastLoad",
_ => "roundRobin",
};
var balancerTag = $"{selector}{Global.BalancerTagSuffix}";
var balancerTag = $"{selector}{AppConfig.BalancerTagSuffix}";
var balancer = new BalancersItem4Ray
{
selector = [selector],

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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