Code clean

This commit is contained in:
2dust
2025-11-02 15:25:41 +08:00
parent b218f0b501
commit ab6a6b879e
45 changed files with 326 additions and 52 deletions
+31
View File
@@ -306,7 +306,10 @@ public class Utils
public static bool IsBase64String(string? plainText)
{
if (plainText.IsNullOrEmpty())
{
return false;
}
var buffer = new Span<byte>(new byte[plainText.Length]);
return Convert.TryFromBase64String(plainText, buffer, out var _);
}
@@ -520,40 +523,62 @@ public class Utils
{
// Loopback address check (127.0.0.1 for IPv4, ::1 for IPv6)
if (IPAddress.IsLoopback(address))
{
return true;
}
var ipBytes = address.GetAddressBytes();
if (address.AddressFamily == AddressFamily.InterNetwork)
{
// IPv4 private address check
if (ipBytes[0] == 10)
{
return true;
}
if (ipBytes[0] == 172 && ipBytes[1] >= 16 && ipBytes[1] <= 31)
{
return true;
}
if (ipBytes[0] == 192 && ipBytes[1] == 168)
{
return true;
}
}
else if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
// IPv6 private address check
// Link-local address fe80::/10
if (ipBytes[0] == 0xfe && (ipBytes[1] & 0xc0) == 0x80)
{
return true;
}
// Unique local address fc00::/7 (typically fd00::/8)
if ((ipBytes[0] & 0xfe) == 0xfc)
{
return true;
}
// Private portion in IPv4-mapped addresses ::ffff:0:0/96
if (address.IsIPv4MappedToIPv6)
{
var ipv4Bytes = ipBytes.Skip(12).ToArray();
if (ipv4Bytes[0] == 10)
{
return true;
}
if (ipv4Bytes[0] == 172 && ipv4Bytes[1] >= 16 && ipv4Bytes[1] <= 31)
{
return true;
}
if (ipv4Bytes[0] == 192 && ipv4Bytes[1] == 168)
{
return true;
}
}
}
}
@@ -708,10 +733,16 @@ public class Utils
foreach (var host in hostsList)
{
if (host.StartsWith("#"))
{
continue;
}
var hostItem = host.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (hostItem.Length < 2)
{
continue;
}
systemHosts.Add(hostItem[1], hostItem[0]);
}
}
@@ -1651,7 +1651,9 @@ public static class ConfigHandler
var uri = Utils.TryUri(url);
if (uri == null)
{
return -1;
}
//Do not allow http protocol
if (url.StartsWith(Global.HttpProtocol) && !Utils.IsPrivateNetwork(uri.IdnHost))
{
@@ -2018,11 +2020,15 @@ public static class ConfigHandler
var downloadHandle = new DownloadService();
var templateContent = await downloadHandle.TryDownloadString(config.ConstItem.RouteRulesTemplateSourceUrl, true, "");
if (templateContent.IsNullOrEmpty())
{
return await InitBuiltinRouting(config, blImportAdvancedRules); // fallback
}
var template = JsonUtils.Deserialize<RoutingTemplate>(templateContent);
if (template == null)
{
return await InitBuiltinRouting(config, blImportAdvancedRules); // fallback
}
var items = await AppManager.Instance.RoutingItems();
var maxSort = items.Count;
@@ -2035,14 +2041,18 @@ public static class ConfigHandler
var item = template.RoutingItems[i];
if (item.Url.IsNullOrEmpty() && item.RuleSet.IsNullOrEmpty())
{
continue;
}
var ruleSetsString = !item.RuleSet.IsNullOrEmpty()
? item.RuleSet
: await downloadHandle.TryDownloadString(item.Url, true, "");
if (ruleSetsString.IsNullOrEmpty())
{
continue;
}
item.Remarks = $"{template.Version}-{item.Remarks}";
item.Enabled = true;
@@ -2238,17 +2248,25 @@ public static class ConfigHandler
var downloadHandle = new DownloadService();
var templateContent = await downloadHandle.TryDownloadString(url, true, "");
if (templateContent.IsNullOrEmpty())
{
return currentItem;
}
var template = JsonUtils.Deserialize<DNSItem>(templateContent);
if (template == null)
{
return currentItem;
}
if (!template.NormalDNS.IsNullOrEmpty())
{
template.NormalDNS = await downloadHandle.TryDownloadString(template.NormalDNS, true, "");
}
if (!template.TunDNS.IsNullOrEmpty())
{
template.TunDNS = await downloadHandle.TryDownloadString(template.TunDNS, true, "");
}
template.Id = currentItem.Id;
template.Enabled = currentItem.Enabled;
@@ -2282,10 +2300,16 @@ public static class ConfigHandler
var downloadHandle = new DownloadService();
var templateContent = await downloadHandle.TryDownloadString(url, true, "");
if (templateContent.IsNullOrEmpty())
{
return null;
}
var template = JsonUtils.Deserialize<SimpleDNSItem>(templateContent);
if (template == null)
{
return null;
}
return template;
}
@@ -12,7 +12,9 @@ public class Hysteria2Fmt : BaseFmt
var url = Utils.TryUri(str);
if (url == null)
{
return null;
}
item.Address = url.IdnHost;
item.Port = url.Port;
@@ -32,7 +34,10 @@ public class Hysteria2Fmt : BaseFmt
public static string? ToUri(ProfileItem? item)
{
if (item == null)
{
return null;
}
var url = string.Empty;
var remark = string.Empty;
@@ -81,21 +81,36 @@ public class ActionPrecheckManager(Config config)
{
case EConfigType.VMess:
if (item.Id.IsNullOrEmpty() || !Utils.IsGuidByParse(item.Id))
{
errors.Add(string.Format(ResUI.InvalidProperty, "Id"));
}
break;
case EConfigType.VLESS:
if (item.Id.IsNullOrEmpty() || (!Utils.IsGuidByParse(item.Id) && item.Id.Length > 30))
{
errors.Add(string.Format(ResUI.InvalidProperty, "Id"));
}
if (!Global.Flows.Contains(item.Flow))
{
errors.Add(string.Format(ResUI.InvalidProperty, "Flow"));
}
break;
case EConfigType.Shadowsocks:
if (item.Id.IsNullOrEmpty())
{
errors.Add(string.Format(ResUI.InvalidProperty, "Id"));
}
if (string.IsNullOrEmpty(item.Security) || !Global.SsSecuritiesInSingbox.Contains(item.Security))
{
errors.Add(string.Format(ResUI.InvalidProperty, "Security"));
}
break;
}
@@ -173,13 +173,19 @@ public class ProfileGroupItemManager
public static bool HasCycle(string? indexId, HashSet<string> visited, HashSet<string> stack)
{
if (indexId.IsNullOrEmpty())
{
return false;
}
if (stack.Contains(indexId))
{
return true;
}
if (visited.Contains(indexId))
{
return false;
}
visited.Add(indexId);
stack.Add(indexId);
@@ -289,7 +295,9 @@ public class ProfileGroupItemManager
{
var childNode = await AppManager.Instance.GetProfileItem(childId);
if (childNode == null)
{
continue;
}
if (!childNode.IsComplex())
{
+19
View File
@@ -69,30 +69,49 @@ public class ProfileItem : ReactiveObject
public bool IsValid()
{
if (IsComplex())
{
return true;
}
if (Address.IsNullOrEmpty() || Port is <= 0 or >= 65536)
{
return false;
}
switch (ConfigType)
{
case EConfigType.VMess:
if (Id.IsNullOrEmpty() || !Utils.IsGuidByParse(Id))
{
return false;
}
break;
case EConfigType.VLESS:
if (Id.IsNullOrEmpty() || (!Utils.IsGuidByParse(Id) && Id.Length > 30))
{
return false;
}
if (!Global.Flows.Contains(Flow))
{
return false;
}
break;
case EConfigType.Shadowsocks:
if (Id.IsNullOrEmpty())
{
return false;
}
if (string.IsNullOrEmpty(Security) || !Global.SsSecuritiesInSingbox.Contains(Security))
{
return false;
}
break;
}
@@ -202,7 +202,9 @@ public partial class CoreConfigSingboxService
var routing = await ConfigHandler.GetDefaultRouting(_config);
if (routing == null)
{
return 0;
}
var rules = JsonUtils.Deserialize<List<RulesItem>>(routing.RuleSet) ?? [];
var expectedIPCidr = new List<string>();
@@ -679,7 +679,10 @@ public partial class CoreConfigSingboxService
{
var node = nodes[i];
if (node == null)
{
continue;
}
if (node.ConfigType.IsGroupType())
{
var (childProfiles, profileGroupItem) = await ProfileGroupItemManager.GetChildProfileItems(node.IndexId);
@@ -250,7 +250,9 @@ public partial class CoreConfigSingboxService
foreach (var it in item.Domain)
{
if (ParseV2Domain(it, rule1))
{
countDomain++;
}
}
if (countDomain > 0)
{
@@ -265,7 +267,9 @@ public partial class CoreConfigSingboxService
foreach (var it in item.Ip)
{
if (ParseV2Address(it, rule2))
{
countIp++;
}
}
if (countIp > 0)
{
@@ -7,7 +7,9 @@ public partial class CoreConfigSingboxService
static void AddRuleSets(List<string> ruleSets, List<string>? rule_set)
{
if (rule_set != null)
{
ruleSets.AddRange(rule_set);
}
}
var geosite = "geosite";
var geoip = "geoip";
@@ -137,7 +137,9 @@ public partial class CoreConfigV2rayService(Config config)
foreach (var rule in rules)
{
if (rule.outboundTag == null)
{
continue;
}
if (balancerTagSet.Contains(rule.outboundTag))
{
@@ -11,7 +11,9 @@ public partial class CoreConfigV2rayService
// Case 1: exact match already exists -> nothing to do
if (subjectSelectors.Any(baseTagName.StartsWith))
{
return await Task.FromResult(0);
}
// Case 2: prefix match exists -> reuse it and move to the first position
var matched = subjectSelectors.FirstOrDefault(s => s.StartsWith(baseTagName));
@@ -189,7 +189,10 @@ public partial class CoreConfigV2rayService
foreach (var domain in item.Domain)
{
if (domain.StartsWith('#'))
{
continue;
}
var normalizedDomain = domain.Replace(Global.RoutingRuleComma, ",");
if (item.OutboundTag == Global.DirectTag)
@@ -368,7 +371,10 @@ public partial class CoreConfigV2rayService
foreach (var host in systemHosts)
{
if (normalHost1[host.Key] != null)
{
continue;
}
normalHost1[host.Key] = host.Value;
}
}
@@ -803,7 +803,10 @@ public partial class CoreConfigV2rayService
{
var node = nodes[i];
if (node == null)
{
continue;
}
if (node.ConfigType.IsGroupType())
{
var (childProfiles, _) = await ProfileGroupItemManager.GetChildProfileItems(node.IndexId);
@@ -21,7 +21,7 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
{
if (_lstExitLoop.Count > 0)
{
UpdateFunc("", ResUI.SpeedtestingStop);
_ = UpdateFunc("", ResUI.SpeedtestingStop);
_lstExitLoop.Clear();
}
@@ -209,6 +209,7 @@ public class CheckUpdateViewModel : MyReactiveObject
_ = UpdateFinishedResult(blReload);
return Disposable.Empty;
});
await Task.CompletedTask;
}
public async Task UpdateFinishedResult(bool blReload)
@@ -321,6 +322,7 @@ public class CheckUpdateViewModel : MyReactiveObject
_ = UpdateViewResult(model);
return Disposable.Empty;
});
await Task.CompletedTask;
}
public async Task UpdateViewResult(CheckUpdateModel model)
@@ -331,5 +333,6 @@ public class CheckUpdateViewModel : MyReactiveObject
return;
}
found.Remarks = model.Remarks;
await Task.CompletedTask;
}
}
@@ -96,6 +96,7 @@ public class ClashConnectionsViewModel : MyReactiveObject
}
ConnectionItems.AddRange(lstModel);
await Task.CompletedTask;
}
public async Task ClashConnectionClose(bool all)
@@ -245,6 +245,7 @@ public class ClashProxiesViewModel : MyReactiveObject
{
SelectedGroup = new();
}
await Task.CompletedTask;
}
private void RefreshProxyDetails(bool c)
@@ -391,6 +392,7 @@ public class ClashProxiesViewModel : MyReactiveObject
_ = ProxiesDelayTestResult(model);
return Disposable.Empty;
});
await Task.CompletedTask;
});
await Task.CompletedTask;
}
@@ -419,6 +421,7 @@ public class ClashProxiesViewModel : MyReactiveObject
detail.Delay = _delayTimeout;
detail.DelayName = string.Empty;
}
await Task.CompletedTask;
}
#endregion proxy function
@@ -66,10 +66,14 @@ public class FullConfigTemplateViewModel : MyReactiveObject
private async Task SaveSettingAsync()
{
if (!await SaveXrayConfigAsync())
{
return;
}
if (!await SaveSingboxConfigAsync())
{
return;
}
NoticeManager.Instance.Enqueue(ResUI.OperationSuccess);
_ = _updateView?.Invoke(EViewAction.CloseWindow, null);
@@ -78,55 +78,55 @@ public class MainWindowViewModel : MyReactiveObject
//servers
AddVmessServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.VMess);
await AddServerAsync(EConfigType.VMess);
});
AddVlessServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.VLESS);
await AddServerAsync(EConfigType.VLESS);
});
AddShadowsocksServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.Shadowsocks);
await AddServerAsync(EConfigType.Shadowsocks);
});
AddSocksServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.SOCKS);
await AddServerAsync(EConfigType.SOCKS);
});
AddHttpServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.HTTP);
await AddServerAsync(EConfigType.HTTP);
});
AddTrojanServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.Trojan);
await AddServerAsync(EConfigType.Trojan);
});
AddHysteria2ServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.Hysteria2);
await AddServerAsync(EConfigType.Hysteria2);
});
AddTuicServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.TUIC);
await AddServerAsync(EConfigType.TUIC);
});
AddWireguardServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.WireGuard);
await AddServerAsync(EConfigType.WireGuard);
});
AddAnytlsServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.Anytls);
await AddServerAsync(EConfigType.Anytls);
});
AddCustomServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.Custom);
await AddServerAsync(EConfigType.Custom);
});
AddPolicyGroupServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.PolicyGroup);
await AddServerAsync(EConfigType.PolicyGroup);
});
AddProxyChainServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await AddServerAsync(true, EConfigType.ProxyChain);
await AddServerAsync(EConfigType.ProxyChain);
});
AddServerViaClipboardCmd = ReactiveCommand.CreateFromTask(async () =>
{
@@ -283,6 +283,7 @@ public class MainWindowViewModel : MyReactiveObject
{
NoticeManager.Instance.Enqueue(msg);
}
await Task.CompletedTask;
}
private async Task UpdateTaskHandler(bool success, string msg)
@@ -310,6 +311,7 @@ public class MainWindowViewModel : MyReactiveObject
return;
}
AppEvents.DispatcherStatisticsRequested.Publish(update);
await Task.CompletedTask;
}
#endregion Actions
@@ -332,7 +334,7 @@ public class MainWindowViewModel : MyReactiveObject
#region Add Servers
public async Task AddServerAsync(bool blNew, EConfigType eConfigType)
public async Task AddServerAsync(EConfigType eConfigType)
{
ProfileItem item = new()
{
@@ -110,7 +110,7 @@ public class ProfilesViewModel : MyReactiveObject
//servers delete
EditServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
await EditServerAsync(EConfigType.Custom);
await EditServerAsync();
}, canEditRemove);
RemoveServerCmd = ReactiveCommand.CreateFromTask(async () =>
{
@@ -300,14 +300,14 @@ public class ProfilesViewModel : MyReactiveObject
if (result.Delay.IsNotEmpty())
{
int.TryParse(result.Delay, out var temp);
item.Delay = temp;
item.Delay = result.Delay.ToInt();
item.DelayVal = result.Delay ?? string.Empty;
}
if (result.Speed.IsNotEmpty())
{
item.SpeedVal = result.Speed ?? string.Empty;
}
await Task.CompletedTask;
}
public async Task UpdateStatistics(ServerSpeedItem update)
@@ -333,6 +333,7 @@ public class ProfilesViewModel : MyReactiveObject
catch
{
}
await Task.CompletedTask;
}
#endregion Actions
@@ -487,7 +488,7 @@ public class ProfilesViewModel : MyReactiveObject
return lstSelected;
}
public async Task EditServerAsync(EConfigType eConfigType)
public async Task EditServerAsync()
{
if (string.IsNullOrEmpty(SelectedProfile?.IndexId))
{
@@ -499,7 +500,7 @@ public class ProfilesViewModel : MyReactiveObject
NoticeManager.Instance.Enqueue(ResUI.PleaseSelectServer);
return;
}
eConfigType = item.ConfigType;
var eConfigType = item.ConfigType;
bool? ret = false;
if (eConfigType == EConfigType.Custom)
@@ -753,6 +754,7 @@ public class ProfilesViewModel : MyReactiveObject
_ = SetSpeedTestResult(result);
return Disposable.Empty;
});
await Task.CompletedTask;
});
_speedtestService?.RunLoop(actionType, lstSelected);
}
@@ -120,7 +120,7 @@ public class StatusBarViewModel : MyReactiveObject
this.WhenAnyValue(
x => x.SelectedServer,
y => y != null && !y.Text.IsNullOrEmpty())
.Subscribe(c => ServerSelectedChanged(c));
.Subscribe(ServerSelectedChanged);
SystemProxySelected = (int)_config.SystemProxyItem.SysProxyType;
this.WhenAnyValue(
@@ -367,11 +367,13 @@ public class StatusBarViewModel : MyReactiveObject
_ = TestServerAvailabilityResult(msg);
return Disposable.Empty;
});
await Task.CompletedTask;
}
public async Task TestServerAvailabilityResult(string msg)
{
RunningInfoDisplay = msg;
await Task.CompletedTask;
}
#region System proxy and Routings
@@ -384,7 +386,7 @@ public class StatusBarViewModel : MyReactiveObject
}
_config.SystemProxyItem.SysProxyType = type;
await ChangeSystemProxyAsync(type, true);
NoticeManager.Instance.SendMessageEx($"{ResUI.TipChangeSystemProxy} - {_config.SystemProxyItem.SysProxyType.ToString()}");
NoticeManager.Instance.SendMessageEx($"{ResUI.TipChangeSystemProxy} - {_config.SystemProxyItem.SysProxyType}");
SystemProxySelected = (int)_config.SystemProxyItem.SysProxyType;
await ConfigHandler.SaveConfig(_config);
@@ -561,6 +563,7 @@ public class StatusBarViewModel : MyReactiveObject
catch
{
}
await Task.CompletedTask;
}
#endregion UI