Code clean

This commit is contained in:
2dust 2025-10-31 20:25:45 +08:00
parent 67494108ad
commit 18ea6fdc00
20 changed files with 51 additions and 54 deletions

View file

@ -424,7 +424,7 @@ public class Utils
// Handle IPv6 addresses, e.g., "[2001:db8::1]:443" // Handle IPv6 addresses, e.g., "[2001:db8::1]:443"
if (authority.StartsWith("[") && authority.Contains("]")) if (authority.StartsWith("[") && authority.Contains("]"))
{ {
int closingBracketIndex = authority.LastIndexOf(']'); var closingBracketIndex = authority.LastIndexOf(']');
if (closingBracketIndex < authority.Length - 1 && authority[closingBracketIndex + 1] == ':') if (closingBracketIndex < authority.Length - 1 && authority[closingBracketIndex + 1] == ':')
{ {
// Port exists // Port exists

View file

@ -1,6 +1,3 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ServiceLib.Common; namespace ServiceLib.Common;
/* /*
* See: * See:

View file

@ -447,13 +447,13 @@ public static class ConfigHandler
/// <returns>0 if successful, -1 if failed</returns> /// <returns>0 if successful, -1 if failed</returns>
public static async Task<int> MoveServer(Config config, List<ProfileItem> lstProfile, int index, EMove eMove, int pos = -1) public static async Task<int> MoveServer(Config config, List<ProfileItem> lstProfile, int index, EMove eMove, int pos = -1)
{ {
int count = lstProfile.Count; var count = lstProfile.Count;
if (index < 0 || index > lstProfile.Count - 1) if (index < 0 || index > lstProfile.Count - 1)
{ {
return -1; return -1;
} }
for (int i = 0; i < lstProfile.Count; i++) for (var i = 0; i < lstProfile.Count; i++)
{ {
ProfileExManager.Instance.SetSort(lstProfile[i].IndexId, (i + 1) * 10); ProfileExManager.Instance.SetSort(lstProfile[i].IndexId, (i + 1) * 10);
} }
@ -527,7 +527,7 @@ public static class ConfigHandler
return -1; return -1;
} }
var ext = Path.GetExtension(fileName); var ext = Path.GetExtension(fileName);
string newFileName = $"{Utils.GetGuid()}{ext}"; var newFileName = $"{Utils.GetGuid()}{ext}";
//newFileName = Path.Combine(Utile.GetTempPath(), newFileName); //newFileName = Path.Combine(Utile.GetTempPath(), newFileName);
try try
@ -1356,7 +1356,7 @@ public static class ConfigHandler
} }
continue; continue;
} }
var profileItem = FmtHandler.ResolveConfig(str, out string msg); var profileItem = FmtHandler.ResolveConfig(str, out var msg);
if (profileItem is null) if (profileItem is null)
{ {
continue; continue;
@ -1440,7 +1440,7 @@ public static class ConfigHandler
{ {
await RemoveServersViaSubid(config, subid, isSub); await RemoveServersViaSubid(config, subid, isSub);
} }
int count = 0; var count = 0;
foreach (var it in lstProfiles) foreach (var it in lstProfiles)
{ {
it.Subid = subid; it.Subid = subid;
@ -1530,7 +1530,7 @@ public static class ConfigHandler
var lstSsServer = ShadowsocksFmt.ResolveSip008(strData); var lstSsServer = ShadowsocksFmt.ResolveSip008(strData);
if (lstSsServer?.Count > 0) if (lstSsServer?.Count > 0)
{ {
int counter = 0; var counter = 0;
foreach (var ssItem in lstSsServer) foreach (var ssItem in lstSsServer)
{ {
ssItem.Subid = subid; ssItem.Subid = subid;
@ -1705,7 +1705,7 @@ public static class ConfigHandler
var maxSort = 0; var maxSort = 0;
if (await SQLiteHelper.Instance.TableAsync<SubItem>().CountAsync() > 0) if (await SQLiteHelper.Instance.TableAsync<SubItem>().CountAsync() > 0)
{ {
var lstSubs = (await AppManager.Instance.SubItems()); var lstSubs = await AppManager.Instance.SubItems();
maxSort = lstSubs.LastOrDefault()?.Sort ?? 0; maxSort = lstSubs.LastOrDefault()?.Sort ?? 0;
} }
item.Sort = maxSort + 1; item.Sort = maxSort + 1;
@ -1867,7 +1867,7 @@ public static class ConfigHandler
/// <returns>0 if successful, -1 if failed</returns> /// <returns>0 if successful, -1 if failed</returns>
public static async Task<int> MoveRoutingRule(List<RulesItem> rules, int index, EMove eMove, int pos = -1) public static async Task<int> MoveRoutingRule(List<RulesItem> rules, int index, EMove eMove, int pos = -1)
{ {
int count = rules.Count; var count = rules.Count;
if (index < 0 || index > rules.Count - 1) if (index < 0 || index > rules.Count - 1)
{ {
return -1; return -1;

View file

@ -58,7 +58,7 @@ public static class CoreConfigHandler
File.Delete(fileName); File.Delete(fileName);
} }
string addressFileName = node.Address; var addressFileName = node.Address;
if (!File.Exists(addressFileName)) if (!File.Exists(addressFileName))
{ {
addressFileName = Utils.GetConfigPath(addressFileName); addressFileName = Utils.GetConfigPath(addressFileName);

View file

@ -37,7 +37,7 @@ public class FmtHandler
try try
{ {
string str = config.TrimEx(); var str = config.TrimEx();
if (str.IsNullOrEmpty()) if (str.IsNullOrEmpty())
{ {
msg = ResUI.FailedReadConfiguration; msg = ResUI.FailedReadConfiguration;

View file

@ -33,9 +33,9 @@ public class Hysteria2Fmt : BaseFmt
{ {
if (item == null) if (item == null)
return null; return null;
string url = string.Empty; var url = string.Empty;
string remark = string.Empty; var remark = string.Empty;
if (item.Remarks.IsNotEmpty()) if (item.Remarks.IsNotEmpty())
{ {
remark = "#" + Utils.UrlEncode(item.Remarks); remark = "#" + Utils.UrlEncode(item.Remarks);

View file

@ -85,7 +85,7 @@ public class ActionPrecheckManager(Config config)
break; break;
case EConfigType.VLESS: case EConfigType.VLESS:
if (item.Id.IsNullOrEmpty() || !Utils.IsGuidByParse(item.Id) && item.Id.Length > 30) if (item.Id.IsNullOrEmpty() || (!Utils.IsGuidByParse(item.Id) && item.Id.Length > 30))
errors.Add(string.Format(ResUI.InvalidProperty, "Id")); errors.Add(string.Format(ResUI.InvalidProperty, "Id"));
if (!Global.Flows.Contains(item.Flow)) if (!Global.Flows.Contains(item.Flow))
errors.Add(string.Format(ResUI.InvalidProperty, "Flow")); errors.Add(string.Format(ResUI.InvalidProperty, "Flow"));

View file

@ -28,7 +28,7 @@ public class ProfileItem : ReactiveObject
public string GetSummary() public string GetSummary()
{ {
var summary = $"[{(ConfigType).ToString()}] "; var summary = $"[{ConfigType.ToString()}] ";
if (IsComplex()) if (IsComplex())
{ {
summary += $"[{CoreType.ToString()}]{Remarks}"; summary += $"[{CoreType.ToString()}]{Remarks}";

View file

@ -94,8 +94,8 @@ public partial class CoreConfigV2rayService(Config config)
ret.Msg = ResUI.InitialConfiguration; ret.Msg = ResUI.InitialConfiguration;
string result = EmbedUtils.GetEmbedText(Global.V2raySampleClient); var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
string txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty()) if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;
@ -200,8 +200,8 @@ public partial class CoreConfigV2rayService(Config config)
ret.Msg = ResUI.InitialConfiguration; ret.Msg = ResUI.InitialConfiguration;
string result = EmbedUtils.GetEmbedText(Global.V2raySampleClient); var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
string txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound); var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty()) if (result.IsNullOrEmpty() || txtOutbound.IsNullOrEmpty())
{ {
ret.Msg = ResUI.FailedGetDefaultConfiguration; ret.Msg = ResUI.FailedGetDefaultConfiguration;

View file

@ -87,7 +87,7 @@ public partial class CoreConfigV2rayService
} }
var customOutboundsNode = new JsonArray(); var customOutboundsNode = new JsonArray();
foreach (var outbound in v2rayConfig.outbounds) foreach (var outbound in v2rayConfig.outbounds)
{ {
if (outbound.protocol.ToLower() is "blackhole" or "dns" or "freedom") if (outbound.protocol.ToLower() is "blackhole" or "dns" or "freedom")
@ -112,7 +112,7 @@ public partial class CoreConfigV2rayService
} }
customOutboundsNode.Add(JsonUtils.DeepCopy(outbound)); customOutboundsNode.Add(JsonUtils.DeepCopy(outbound));
} }
if (fullConfigTemplateNode["outbounds"] is JsonArray templateOutbounds) if (fullConfigTemplateNode["outbounds"] is JsonArray templateOutbounds)
{ {
foreach (var outbound in templateOutbounds) foreach (var outbound in templateOutbounds)
@ -120,7 +120,7 @@ public partial class CoreConfigV2rayService
customOutboundsNode.Add(outbound?.DeepClone()); customOutboundsNode.Add(outbound?.DeepClone());
} }
} }
fullConfigTemplateNode["outbounds"] = customOutboundsNode; fullConfigTemplateNode["outbounds"] = customOutboundsNode;
return await Task.FromResult(JsonUtils.Serialize(fullConfigTemplateNode)); return await Task.FromResult(JsonUtils.Serialize(fullConfigTemplateNode));

View file

@ -347,8 +347,8 @@ public partial class CoreConfigV2rayService
if (obj is null) if (obj is null)
{ {
List<string> servers = []; List<string> servers = [];
string[] arrDNS = normalDNS.Split(','); var arrDNS = normalDNS.Split(',');
foreach (string str in arrDNS) foreach (var str in arrDNS)
{ {
servers.Add(str); servers.Add(str);
} }

View file

@ -48,7 +48,7 @@ public partial class CoreConfigV2rayService
private Inbounds4Ray GetInbound(InItem inItem, EInboundProtocol protocol, bool bSocks) private Inbounds4Ray GetInbound(InItem inItem, EInboundProtocol protocol, bool bSocks)
{ {
string result = EmbedUtils.GetEmbedText(Global.V2raySampleInbound); var result = EmbedUtils.GetEmbedText(Global.V2raySampleInbound);
if (result.IsNullOrEmpty()) if (result.IsNullOrEmpty())
{ {
return new(); return new();

View file

@ -453,16 +453,16 @@ public partial class CoreConfigV2rayService
}; };
//request Host //request Host
string request = EmbedUtils.GetEmbedText(Global.V2raySampleHttpRequestFileName); var request = EmbedUtils.GetEmbedText(Global.V2raySampleHttpRequestFileName);
string[] arrHost = host.Split(','); var arrHost = host.Split(',');
string host2 = string.Join(",".AppendQuotes(), arrHost); var host2 = string.Join(",".AppendQuotes(), arrHost);
request = request.Replace("$requestHost$", $"{host2.AppendQuotes()}"); request = request.Replace("$requestHost$", $"{host2.AppendQuotes()}");
request = request.Replace("$requestUserAgent$", $"{useragent.AppendQuotes()}"); request = request.Replace("$requestUserAgent$", $"{useragent.AppendQuotes()}");
//Path //Path
string pathHttp = @"/"; var pathHttp = @"/";
if (path.IsNotEmpty()) if (path.IsNotEmpty())
{ {
string[] arrPath = path.Split(','); var arrPath = path.Split(',');
pathHttp = string.Join(",".AppendQuotes(), arrPath); pathHttp = string.Join(",".AppendQuotes(), arrPath);
} }
request = request.Replace("$requestPath$", $"{pathHttp.AppendQuotes()}"); request = request.Replace("$requestPath$", $"{pathHttp.AppendQuotes()}");
@ -623,10 +623,10 @@ public partial class CoreConfigV2rayService
// Cache for chain proxies to avoid duplicate generation // Cache for chain proxies to avoid duplicate generation
var nextProxyCache = new Dictionary<string, Outbounds4Ray?>(); var nextProxyCache = new Dictionary<string, Outbounds4Ray?>();
var prevProxyTags = new Dictionary<string, string?>(); // Map from profile name to tag var prevProxyTags = new Dictionary<string, string?>(); // Map from profile name to tag
int prevIndex = 0; // Index for prev outbounds var prevIndex = 0; // Index for prev outbounds
// Process nodes // Process nodes
int index = 0; var index = 0;
foreach (var node in nodes) foreach (var node in nodes)
{ {
index++; index++;

View file

@ -6,7 +6,7 @@ public partial class CoreConfigV2rayService
{ {
if (_config.GuiItem.EnableStatistics || _config.GuiItem.DisplayRealTimeSpeed) if (_config.GuiItem.EnableStatistics || _config.GuiItem.DisplayRealTimeSpeed)
{ {
string tag = EInboundProtocol.api.ToString(); var tag = EInboundProtocol.api.ToString();
Metrics4Ray apiObj = new(); Metrics4Ray apiObj = new();
Policy4Ray policyObj = new(); Policy4Ray policyObj = new();
SystemPolicy4Ray policySystemSetting = new(); SystemPolicy4Ray policySystemSetting = new();

View file

@ -167,7 +167,7 @@ public class UpdateService
try try
{ {
var coreInfo = CoreInfoManager.Instance.GetCoreInfo(type); var coreInfo = CoreInfoManager.Instance.GetCoreInfo(type);
string filePath = string.Empty; var filePath = string.Empty;
foreach (var name in coreInfo.CoreExes) foreach (var name in coreInfo.CoreExes)
{ {
var vName = Utils.GetBinPath(Utils.GetExeName(name), coreInfo.CoreType.ToString()); var vName = Utils.GetBinPath(Utils.GetExeName(name), coreInfo.CoreType.ToString());
@ -180,14 +180,14 @@ public class UpdateService
if (!File.Exists(filePath)) if (!File.Exists(filePath))
{ {
string msg = string.Format(ResUI.NotFoundCore, @"", "", ""); var msg = string.Format(ResUI.NotFoundCore, @"", "", "");
//ShowMsg(true, msg); //ShowMsg(true, msg);
return new SemanticVersion(""); return new SemanticVersion("");
} }
var result = await Utils.GetCliWrapOutput(filePath, coreInfo.VersionArg); var result = await Utils.GetCliWrapOutput(filePath, coreInfo.VersionArg);
var echo = result ?? ""; var echo = result ?? "";
string version = string.Empty; var version = string.Empty;
switch (type) switch (type)
{ {
case ECoreType.v2fly: case ECoreType.v2fly:

View file

@ -211,7 +211,7 @@ public class ClashProxiesViewModel : MyReactiveObject
} }
//from api //from api
foreach (KeyValuePair<string, ProxiesItem> kv in _proxies) foreach (var kv in _proxies)
{ {
if (!Global.allowSelectType.Contains(kv.Value.type.ToLower())) if (!Global.allowSelectType.Contains(kv.Value.type.ToLower()))
{ {
@ -319,7 +319,7 @@ public class ClashProxiesViewModel : MyReactiveObject
//from providers //from providers
if (_providers != null) if (_providers != null)
{ {
foreach (KeyValuePair<string, ProvidersItem> kv in _providers) foreach (var kv in _providers)
{ {
if (Global.proxyVehicleType.Contains(kv.Value.vehicleType.ToLower())) if (Global.proxyVehicleType.Contains(kv.Value.vehicleType.ToLower()))
{ {

View file

@ -273,12 +273,12 @@ public class OptionSettingViewModel : MyReactiveObject
NoticeManager.Instance.Enqueue(ResUI.FillLocalListeningPort); NoticeManager.Instance.Enqueue(ResUI.FillLocalListeningPort);
return; return;
} }
var needReboot = (EnableStatistics != _config.GuiItem.EnableStatistics var needReboot = EnableStatistics != _config.GuiItem.EnableStatistics
|| DisplayRealTimeSpeed != _config.GuiItem.DisplayRealTimeSpeed || DisplayRealTimeSpeed != _config.GuiItem.DisplayRealTimeSpeed
|| EnableDragDropSort != _config.UiItem.EnableDragDropSort || EnableDragDropSort != _config.UiItem.EnableDragDropSort
|| EnableHWA != _config.GuiItem.EnableHWA || EnableHWA != _config.GuiItem.EnableHWA
|| CurrentFontFamily != _config.UiItem.CurrentFontFamily || CurrentFontFamily != _config.UiItem.CurrentFontFamily
|| MainGirdOrientation != (int)_config.UiItem.MainGirdOrientation); || MainGirdOrientation != (int)_config.UiItem.MainGirdOrientation;
//if (Utile.IsNullOrEmpty(Kcpmtu.ToString()) || !Utile.IsNumeric(Kcpmtu.ToString()) //if (Utile.IsNullOrEmpty(Kcpmtu.ToString()) || !Utile.IsNumeric(Kcpmtu.ToString())
// || Utile.IsNullOrEmpty(Kcptti.ToString()) || !Utile.IsNumeric(Kcptti.ToString()) // || Utile.IsNullOrEmpty(Kcptti.ToString()) || !Utile.IsNumeric(Kcptti.ToString())
@ -375,7 +375,7 @@ public class OptionSettingViewModel : MyReactiveObject
private async Task SaveCoreType() private async Task SaveCoreType()
{ {
for (int k = 1; k <= _config.CoreTypeItem.Count; k++) for (var k = 1; k <= _config.CoreTypeItem.Count; k++)
{ {
var item = _config.CoreTypeItem[k - 1]; var item = _config.CoreTypeItem[k - 1];
var type = string.Empty; var type = string.Empty;

View file

@ -658,7 +658,7 @@ public class ProfilesViewModel : MyReactiveObject
} }
_dicHeaderSort.TryAdd(colName, true); _dicHeaderSort.TryAdd(colName, true);
_dicHeaderSort.TryGetValue(colName, out bool asc); _dicHeaderSort.TryGetValue(colName, out var asc);
if (await ConfigHandler.SortServers(_config, _config.SubIndexId, colName, asc) != 0) if (await ConfigHandler.SortServers(_config, _config.SubIndexId, colName, asc) != 0)
{ {
return; return;

View file

@ -215,7 +215,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
private async Task SaveRoutingAsync() private async Task SaveRoutingAsync()
{ {
string remarks = SelectedRouting.Remarks; var remarks = SelectedRouting.Remarks;
if (remarks.IsNullOrEmpty()) if (remarks.IsNullOrEmpty())
{ {
NoticeManager.Instance.Enqueue(ResUI.PleaseFillRemarks); NoticeManager.Instance.Enqueue(ResUI.PleaseFillRemarks);
@ -286,7 +286,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
return; return;
} }
DownloadService downloadHandle = new DownloadService(); var downloadHandle = new DownloadService();
var result = await downloadHandle.TryDownloadString(url, true, ""); var result = await downloadHandle.TryDownloadString(url, true, "");
var ret = await AddBatchRoutingRulesAsync(SelectedRouting, result); var ret = await AddBatchRoutingRulesAsync(SelectedRouting, result);
if (ret == 0) if (ret == 0)
@ -298,7 +298,7 @@ public class RoutingRuleSettingViewModel : MyReactiveObject
private async Task<int> AddBatchRoutingRulesAsync(RoutingItem routingItem, string? clipboardData) private async Task<int> AddBatchRoutingRulesAsync(RoutingItem routingItem, string? clipboardData)
{ {
bool blReplace = false; var blReplace = false;
if (await _updateView?.Invoke(EViewAction.AddBatchRoutingRulesYesNo, null) == false) if (await _updateView?.Invoke(EViewAction.AddBatchRoutingRulesYesNo, null) == false)
{ {
blReplace = true; blReplace = true;

View file

@ -313,10 +313,10 @@ public class StatusBarViewModel : MyReactiveObject
} }
BlServers = true; BlServers = true;
for (int k = 0; k < lstModel.Count; k++) for (var k = 0; k < lstModel.Count; k++)
{ {
ProfileItem it = lstModel[k]; ProfileItem it = lstModel[k];
string name = it.GetSummary(); var name = it.GetSummary();
var item = new ComboItem() { ID = it.IndexId, Text = name }; var item = new ComboItem() { ID = it.IndexId, Text = name };
Servers.Add(item); Servers.Add(item);
@ -394,10 +394,10 @@ public class StatusBarViewModel : MyReactiveObject
{ {
await SysProxyHandler.UpdateSysProxy(_config, false); await SysProxyHandler.UpdateSysProxy(_config, false);
BlSystemProxyClear = (type == ESysProxyType.ForcedClear); BlSystemProxyClear = type == ESysProxyType.ForcedClear;
BlSystemProxySet = (type == ESysProxyType.ForcedChange); BlSystemProxySet = type == ESysProxyType.ForcedChange;
BlSystemProxyNothing = (type == ESysProxyType.Unchanged); BlSystemProxyNothing = type == ESysProxyType.Unchanged;
BlSystemProxyPac = (type == ESysProxyType.Pac); BlSystemProxyPac = type == ESysProxyType.Pac;
if (blChange) if (blChange)
{ {