Improved Action Invoke

This commit is contained in:
2dust 2024-10-08 13:47:13 +08:00
parent 3e74bb65bd
commit 53e19ecb1d
16 changed files with 113 additions and 126 deletions

View file

@ -110,7 +110,7 @@ namespace ServiceLib.Common
catch (Exception ex) catch (Exception ex)
{ {
Logging.SaveLog(ex.Message, ex); Logging.SaveLog(ex.Message, ex);
return new List<string>(); return [];
} }
} }
@ -131,7 +131,7 @@ namespace ServiceLib.Common
catch (Exception ex) catch (Exception ex)
{ {
Logging.SaveLog(ex.Message, ex); Logging.SaveLog(ex.Message, ex);
return new List<string>(); return [];
} }
} }
@ -640,29 +640,16 @@ namespace ServiceLib.Common
return fileName; return fileName;
} }
public static IPAddress? GetDefaultGateway()
{
return NetworkInterface
.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up)
.Where(n => n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.SelectMany(n => n.GetIPProperties()?.GatewayAddresses)
.Select(g => g?.Address)
.Where(a => a != null)
// .Where(a => a.AddressFamily == AddressFamily.InterNetwork)
// .Where(a => Array.FindIndex(a.GetAddressBytes(), b => b != 0) >= 0)
.FirstOrDefault();
}
public static bool IsGuidByParse(string strSrc) public static bool IsGuidByParse(string strSrc)
{ {
return Guid.TryParse(strSrc, out Guid g); return Guid.TryParse(strSrc, out _);
} }
public static void ProcessStart(string fileName, string arguments = "") public static void ProcessStart(string? fileName, string arguments = "")
{ {
try try
{ {
if (fileName.IsNullOrEmpty()) { return; }
Process.Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = true }); Process.Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = true });
} }
catch (Exception ex) catch (Exception ex)

View file

@ -10,12 +10,12 @@ namespace ServiceLib.Handler
private Dictionary<String, ProxiesItem>? _proxies; private Dictionary<String, ProxiesItem>? _proxies;
public Dictionary<string, object> ProfileContent { get; set; } public Dictionary<string, object> ProfileContent { get; set; }
public void GetClashProxies(Config config, Action<ClashProxies, ClashProviders> update) public void GetClashProxies(Config config, Action<ClashProxies, ClashProviders> updateFunc)
{ {
Task.Run(() => GetClashProxiesAsync(config, update)); Task.Run(() => GetClashProxiesAsync(config, updateFunc));
} }
private async Task GetClashProxiesAsync(Config config, Action<ClashProxies, ClashProviders> update) private async Task GetClashProxiesAsync(Config config, Action<ClashProxies, ClashProviders> updateFunc)
{ {
for (var i = 0; i < 5; i++) for (var i = 0; i < 5; i++)
{ {
@ -30,15 +30,15 @@ namespace ServiceLib.Handler
if (clashProxies != null || clashProviders != null) if (clashProxies != null || clashProviders != null)
{ {
_proxies = clashProxies?.proxies; _proxies = clashProxies?.proxies;
update(clashProxies, clashProviders); updateFunc?.Invoke(clashProxies, clashProviders);
return; return;
} }
Task.Delay(5000).Wait(); Task.Delay(5000).Wait();
} }
update(null, null); updateFunc?.Invoke(null, null);
} }
public void ClashProxiesDelayTest(bool blAll, List<ClashProxyModel> lstProxy, Action<ClashProxyModel?, string> update) public void ClashProxiesDelayTest(bool blAll, List<ClashProxyModel> lstProxy, Action<ClashProxyModel?, string> updateFunc)
{ {
Task.Run(() => Task.Run(() =>
{ {
@ -90,13 +90,13 @@ namespace ServiceLib.Handler
tasks.Add(Task.Run(async () => tasks.Add(Task.Run(async () =>
{ {
var result = await HttpClientHelper.Instance.TryGetAsync(url); var result = await HttpClientHelper.Instance.TryGetAsync(url);
update(it, result); updateFunc?.Invoke(it, result);
})); }));
} }
Task.WaitAll(tasks.ToArray()); Task.WaitAll(tasks.ToArray());
Task.Delay(1000).Wait(); Task.Delay(1000).Wait();
update(null, ""); updateFunc?.Invoke(null, "");
}); });
} }
@ -164,12 +164,12 @@ namespace ServiceLib.Handler
} }
} }
public void GetClashConnections(Config config, Action<ClashConnections> update) public void GetClashConnections(Config config, Action<ClashConnections> updateFunc)
{ {
Task.Run(() => GetClashConnectionsAsync(config, update)); Task.Run(() => GetClashConnectionsAsync(config, updateFunc));
} }
private async Task GetClashConnectionsAsync(Config config, Action<ClashConnections> update) private async Task GetClashConnectionsAsync(Config config, Action<ClashConnections> updateFunc)
{ {
try try
{ {
@ -177,7 +177,7 @@ namespace ServiceLib.Handler
var result = await HttpClientHelper.Instance.TryGetAsync(url); var result = await HttpClientHelper.Instance.TryGetAsync(url);
var clashConnections = JsonUtils.Deserialize<ClashConnections>(result); var clashConnections = JsonUtils.Deserialize<ClashConnections>(result);
update(clashConnections); updateFunc?.Invoke(clashConnections);
} }
catch (Exception ex) catch (Exception ex)
{ {

View file

@ -13,12 +13,12 @@ namespace ServiceLib.Handler
private Config _config; private Config _config;
private Process? _process; private Process? _process;
private Process? _processPre; private Process? _processPre;
private Action<bool, string> _updateFunc; private Action<bool, string>? _updateFunc;
public void Init(Config config, Action<bool, string> update) public void Init(Config config, Action<bool, string> updateFunc)
{ {
_config = config; _config = config;
_updateFunc = update; _updateFunc = updateFunc;
Environment.SetEnvironmentVariable("v2ray.location.asset", Utils.GetBinPath(""), EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable("v2ray.location.asset", Utils.GetBinPath(""), EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("xray.location.asset", Utils.GetBinPath(""), EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable("xray.location.asset", Utils.GetBinPath(""), EnvironmentVariableTarget.Process);
@ -267,7 +267,7 @@ namespace ServiceLib.Handler
private void ShowMsg(bool notify, string msg) private void ShowMsg(bool notify, string msg)
{ {
_updateFunc(notify, msg); _updateFunc?.Invoke(notify, msg);
} }
#endregion Private #endregion Private

View file

@ -8,16 +8,16 @@
private Config _config; private Config _config;
private ServerStatItem? _serverStatItem; private ServerStatItem? _serverStatItem;
private List<ServerStatItem> _lstServerStat; private List<ServerStatItem> _lstServerStat;
private Action<ServerSpeedItem> _updateFunc; private Action<ServerSpeedItem>? _updateFunc;
private StatisticsV2rayService? _statisticsV2Ray; private StatisticsV2rayService? _statisticsV2Ray;
private StatisticsSingboxService? _statisticsSingbox; private StatisticsSingboxService? _statisticsSingbox;
public List<ServerStatItem> ServerStat => _lstServerStat; public List<ServerStatItem> ServerStat => _lstServerStat;
public void Init(Config config, Action<ServerSpeedItem> update) public void Init(Config config, Action<ServerSpeedItem> updateFunc)
{ {
_config = config; _config = config;
_updateFunc = update; _updateFunc = updateFunc;
if (!config.guiItem.enableStatistics) if (!config.guiItem.enableStatistics)
{ {
return; return;
@ -95,7 +95,7 @@
server.todayDown = _serverStatItem.todayDown; server.todayDown = _serverStatItem.todayDown;
server.totalUp = _serverStatItem.totalUp; server.totalUp = _serverStatItem.totalUp;
server.totalDown = _serverStatItem.totalDown; server.totalDown = _serverStatItem.totalDown;
_updateFunc(server); _updateFunc?.Invoke(server);
} }
private void GetServerStatItem(string indexId) private void GetServerStatItem(string indexId)

View file

@ -9,13 +9,13 @@
{ {
} }
public void RegUpdateTask(Config config, Action<bool, string> update) public void RegUpdateTask(Config config, Action<bool, string> updateFunc)
{ {
Task.Run(() => UpdateTaskRunSubscription(config, update)); Task.Run(() => UpdateTaskRunSubscription(config, updateFunc));
Task.Run(() => UpdateTaskRunGeo(config, update)); Task.Run(() => UpdateTaskRunGeo(config, updateFunc));
} }
private async Task UpdateTaskRunSubscription(Config config, Action<bool, string> update) private async Task UpdateTaskRunSubscription(Config config, Action<bool, string> updateFunc)
{ {
await Task.Delay(60000); await Task.Delay(60000);
Logging.SaveLog("UpdateTaskRunSubscription"); Logging.SaveLog("UpdateTaskRunSubscription");
@ -33,7 +33,7 @@
{ {
updateHandle.UpdateSubscriptionProcess(config, item.id, true, (bool success, string msg) => updateHandle.UpdateSubscriptionProcess(config, item.id, true, (bool success, string msg) =>
{ {
update(success, msg); updateFunc?.Invoke(success, msg);
if (success) if (success)
Logging.SaveLog("subscription" + msg); Logging.SaveLog("subscription" + msg);
}); });
@ -46,7 +46,7 @@
} }
} }
private async Task UpdateTaskRunGeo(Config config, Action<bool, string> update) private async Task UpdateTaskRunGeo(Config config, Action<bool, string> updateFunc)
{ {
var autoUpdateGeoTime = DateTime.Now; var autoUpdateGeoTime = DateTime.Now;
@ -65,7 +65,7 @@
{ {
await updateHandle.UpdateGeoFileAll(config, (bool success, string msg) => await updateHandle.UpdateGeoFileAll(config, (bool success, string msg) =>
{ {
update(false, msg); updateFunc?.Invoke(false, msg);
}); });
autoUpdateGeoTime = dtNow; autoUpdateGeoTime = dtNow;
} }

View file

@ -8,14 +8,14 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Downloader" Version="3.2.0" /> <PackageReference Include="Downloader" Version="3.2.1" />
<PackageReference Include="Mono.Posix.NETStandard" Version="1.0.0" /> <PackageReference Include="Mono.Posix.NETStandard" Version="1.0.0" />
<PackageReference Include="ReactiveUI" Version="20.1.63" /> <PackageReference Include="ReactiveUI" Version="20.1.63" />
<PackageReference Include="ReactiveUI.Fody" Version="19.5.41" /> <PackageReference Include="ReactiveUI.Fody" Version="19.5.41" />
<PackageReference Include="sqlite-net-pcl" Version="1.9.172" /> <PackageReference Include="sqlite-net-pcl" Version="1.9.172" />
<PackageReference Include="Splat.NLog" Version="15.2.22" /> <PackageReference Include="Splat.NLog" Version="15.2.22" />
<PackageReference Include="WebDav.Client" Version="2.8.0" /> <PackageReference Include="WebDav.Client" Version="2.8.0" />
<PackageReference Include="YamlDotNet" Version="16.1.2" /> <PackageReference Include="YamlDotNet" Version="16.1.3" />
<PackageReference Include="QRCoder" Version="1.6.0" /> <PackageReference Include="QRCoder" Version="1.6.0" />
<PackageReference Include="CliWrap" Version="3.6.6" /> <PackageReference Include="CliWrap" Version="3.6.6" />
</ItemGroup> </ItemGroup>

View file

@ -26,7 +26,7 @@ namespace ServiceLib.Services
} }
} }
public async Task<int> DownloadDataAsync(string url, WebProxy webProxy, int downloadTimeout, Action<bool, string> update) public async Task<int> DownloadDataAsync(string url, WebProxy webProxy, int downloadTimeout, Action<bool, string> updateFunc)
{ {
try try
{ {
@ -35,10 +35,10 @@ namespace ServiceLib.Services
var progress = new Progress<string>(); var progress = new Progress<string>();
progress.ProgressChanged += (sender, value) => progress.ProgressChanged += (sender, value) =>
{ {
if (update != null) if (updateFunc != null)
{ {
string msg = $"{value}"; string msg = $"{value}";
update(false, msg); updateFunc?.Invoke(false, msg);
} }
}; };
@ -49,10 +49,10 @@ namespace ServiceLib.Services
} }
catch (Exception ex) catch (Exception ex)
{ {
update(false, ex.Message); updateFunc?.Invoke(false, ex.Message);
if (ex.InnerException != null) if (ex.InnerException != null)
{ {
update(false, ex.InnerException.Message); updateFunc?.Invoke(false, ex.InnerException.Message);
} }
} }
return 0; return 0;

View file

@ -9,15 +9,15 @@ namespace ServiceLib.Services
private Config? _config; private Config? _config;
private List<ServerTestItem> _selecteds; private List<ServerTestItem> _selecteds;
private ESpeedActionType _actionType; private ESpeedActionType _actionType;
private Action<SpeedTestResult> _updateFunc; private Action<SpeedTestResult>? _updateFunc;
private bool _exitLoop = false; private bool _exitLoop = false;
public SpeedtestService(Config config, List<ProfileItem> selecteds, ESpeedActionType actionType, Action<SpeedTestResult> update) public SpeedtestService(Config config, List<ProfileItem> selecteds, ESpeedActionType actionType, Action<SpeedTestResult> updateFunc)
{ {
_config = config; _config = config;
_actionType = actionType; _actionType = actionType;
_updateFunc = update; _updateFunc = updateFunc;
_selecteds = new List<ServerTestItem>(); _selecteds = new List<ServerTestItem>();
foreach (var it in selecteds) foreach (var it in selecteds)
@ -383,7 +383,7 @@ namespace ServiceLib.Services
private void UpdateFunc(string indexId, string delay, string speed = "") private void UpdateFunc(string indexId, string delay, string speed = "")
{ {
_updateFunc(new() { IndexId = indexId, Delay = delay, Speed = speed }); _updateFunc?.Invoke(new() { IndexId = indexId, Delay = delay, Speed = speed });
} }
} }
} }

View file

@ -9,12 +9,12 @@ namespace ServiceLib.Services.Statistics
private bool _exitFlag; private bool _exitFlag;
private ClientWebSocket? webSocket; private ClientWebSocket? webSocket;
private string url = string.Empty; private string url = string.Empty;
private Action<ServerSpeedItem> _updateFunc; private Action<ServerSpeedItem>? _updateFunc;
public StatisticsSingboxService(Config config, Action<ServerSpeedItem> update) public StatisticsSingboxService(Config config, Action<ServerSpeedItem> updateFunc)
{ {
_config = config; _config = config;
_updateFunc = update; _updateFunc = updateFunc;
_exitFlag = false; _exitFlag = false;
Task.Run(() => Run()); Task.Run(() => Run());
@ -92,7 +92,7 @@ namespace ServiceLib.Services.Statistics
{ {
ParseOutput(result, out ulong up, out ulong down); ParseOutput(result, out ulong up, out ulong down);
_updateFunc(new ServerSpeedItem() _updateFunc?.Invoke(new ServerSpeedItem()
{ {
proxyUp = (long)(up / 1000), proxyUp = (long)(up / 1000),
proxyDown = (long)(down / 1000) proxyDown = (long)(down / 1000)

View file

@ -10,12 +10,12 @@ namespace ServiceLib.Services.Statistics
private GrpcChannel? _channel; private GrpcChannel? _channel;
private StatsService.StatsServiceClient? _client; private StatsService.StatsServiceClient? _client;
private bool _exitFlag; private bool _exitFlag;
private Action<ServerSpeedItem> _updateFunc; private Action<ServerSpeedItem>? _updateFunc;
public StatisticsV2rayService(Models.Config config, Action<ServerSpeedItem> update) public StatisticsV2rayService(Models.Config config, Action<ServerSpeedItem> updateFunc)
{ {
_config = config; _config = config;
_updateFunc = update; _updateFunc = updateFunc;
_exitFlag = false; _exitFlag = false;
GrpcInit(); GrpcInit();
@ -70,7 +70,7 @@ namespace ServiceLib.Services.Statistics
if (res != null) if (res != null)
{ {
ParseOutput(res.Stat, out ServerSpeedItem server); ParseOutput(res.Stat, out ServerSpeedItem server);
_updateFunc(server); _updateFunc?.Invoke(server);
} }
} }
if (_channel != null) if (_channel != null)

View file

@ -7,7 +7,7 @@ namespace ServiceLib.Services
{ {
public class UpdateService public class UpdateService
{ {
private Action<bool, string> _updateFunc; private Action<bool, string>? _updateFunc;
private Config _config; private Config _config;
private int _timeout = 30; private int _timeout = 30;
@ -25,10 +25,10 @@ namespace ServiceLib.Services
} }
} }
public async Task CheckUpdateGuiN(Config config, Action<bool, string> update, bool preRelease) public async Task CheckUpdateGuiN(Config config, Action<bool, string> updateFunc, bool preRelease)
{ {
_config = config; _config = config;
_updateFunc = update; _updateFunc = updateFunc;
var url = string.Empty; var url = string.Empty;
var fileName = string.Empty; var fileName = string.Empty;
@ -37,25 +37,25 @@ namespace ServiceLib.Services
{ {
if (args.Success) if (args.Success)
{ {
_updateFunc(false, ResUI.MsgDownloadV2rayCoreSuccessfully); _updateFunc?.Invoke(false, ResUI.MsgDownloadV2rayCoreSuccessfully);
_updateFunc(true, Utils.UrlEncode(fileName)); _updateFunc?.Invoke(true, Utils.UrlEncode(fileName));
} }
else else
{ {
_updateFunc(false, args.Msg); _updateFunc?.Invoke(false, args.Msg);
} }
}; };
downloadHandle.Error += (sender2, args) => downloadHandle.Error += (sender2, args) =>
{ {
_updateFunc(false, args.GetException().Message); _updateFunc?.Invoke(false, args.GetException().Message);
}; };
_updateFunc(false, string.Format(ResUI.MsgStartUpdating, ECoreType.v2rayN)); _updateFunc?.Invoke(false, string.Format(ResUI.MsgStartUpdating, ECoreType.v2rayN));
var args = await CheckUpdateAsync(downloadHandle, ECoreType.v2rayN, preRelease); var args = await CheckUpdateAsync(downloadHandle, ECoreType.v2rayN, preRelease);
if (args.Success) if (args.Success)
{ {
_updateFunc(false, string.Format(ResUI.MsgParsingSuccessfully, ECoreType.v2rayN)); _updateFunc?.Invoke(false, string.Format(ResUI.MsgParsingSuccessfully, ECoreType.v2rayN));
_updateFunc(false, args.Msg); _updateFunc?.Invoke(false, args.Msg);
url = args.Url; url = args.Url;
fileName = Utils.GetTempPath(Utils.GetGUID()); fileName = Utils.GetTempPath(Utils.GetGUID());
@ -63,14 +63,14 @@ namespace ServiceLib.Services
} }
else else
{ {
_updateFunc(false, args.Msg); _updateFunc?.Invoke(false, args.Msg);
} }
} }
public async Task CheckUpdateCore(ECoreType type, Config config, Action<bool, string> update, bool preRelease) public async Task CheckUpdateCore(ECoreType type, Config config, Action<bool, string> updateFunc, bool preRelease)
{ {
_config = config; _config = config;
_updateFunc = update; _updateFunc = updateFunc;
var url = string.Empty; var url = string.Empty;
var fileName = string.Empty; var fileName = string.Empty;
@ -79,34 +79,34 @@ namespace ServiceLib.Services
{ {
if (args.Success) if (args.Success)
{ {
_updateFunc(false, ResUI.MsgDownloadV2rayCoreSuccessfully); _updateFunc?.Invoke(false, ResUI.MsgDownloadV2rayCoreSuccessfully);
_updateFunc(false, ResUI.MsgUnpacking); _updateFunc?.Invoke(false, ResUI.MsgUnpacking);
try try
{ {
_updateFunc(true, fileName); _updateFunc?.Invoke(true, fileName);
} }
catch (Exception ex) catch (Exception ex)
{ {
_updateFunc(false, ex.Message); _updateFunc?.Invoke(false, ex.Message);
} }
} }
else else
{ {
_updateFunc(false, args.Msg); _updateFunc?.Invoke(false, args.Msg);
} }
}; };
downloadHandle.Error += (sender2, args) => downloadHandle.Error += (sender2, args) =>
{ {
_updateFunc(false, args.GetException().Message); _updateFunc?.Invoke(false, args.GetException().Message);
}; };
_updateFunc(false, string.Format(ResUI.MsgStartUpdating, type)); _updateFunc?.Invoke(false, string.Format(ResUI.MsgStartUpdating, type));
var args = await CheckUpdateAsync(downloadHandle, type, preRelease); var args = await CheckUpdateAsync(downloadHandle, type, preRelease);
if (args.Success) if (args.Success)
{ {
_updateFunc(false, string.Format(ResUI.MsgParsingSuccessfully, type)); _updateFunc?.Invoke(false, string.Format(ResUI.MsgParsingSuccessfully, type));
_updateFunc(false, args.Msg); _updateFunc?.Invoke(false, args.Msg);
url = args.Url; url = args.Url;
var ext = Path.GetExtension(url); var ext = Path.GetExtension(url);
@ -117,22 +117,22 @@ namespace ServiceLib.Services
{ {
if (!args.Msg.IsNullOrEmpty()) if (!args.Msg.IsNullOrEmpty())
{ {
_updateFunc(false, args.Msg); _updateFunc?.Invoke(false, args.Msg);
} }
} }
} }
public void UpdateSubscriptionProcess(Config config, string subId, bool blProxy, Action<bool, string> update) public void UpdateSubscriptionProcess(Config config, string subId, bool blProxy, Action<bool, string> updateFunc)
{ {
_config = config; _config = config;
_updateFunc = update; _updateFunc = updateFunc;
_updateFunc(false, ResUI.MsgUpdateSubscriptionStart); _updateFunc?.Invoke(false, ResUI.MsgUpdateSubscriptionStart);
var subItem = AppHandler.Instance.SubItems().OrderBy(t => t.sort).ToList(); var subItem = AppHandler.Instance.SubItems().OrderBy(t => t.sort).ToList();
if (subItem == null || subItem.Count <= 0) if (subItem == null || subItem.Count <= 0)
{ {
_updateFunc(false, ResUI.MsgNoValidSubscription); _updateFunc?.Invoke(false, ResUI.MsgNoValidSubscription);
return; return;
} }
@ -146,7 +146,7 @@ namespace ServiceLib.Services
string hashCode = $"{item.remarks}->"; string hashCode = $"{item.remarks}->";
if (Utils.IsNullOrEmpty(id) || Utils.IsNullOrEmpty(url) || Utils.IsNotEmpty(subId) && item.id != subId) if (Utils.IsNullOrEmpty(id) || Utils.IsNullOrEmpty(url) || Utils.IsNotEmpty(subId) && item.id != subId)
{ {
//_updateFunc(false, $"{hashCode}{ResUI.MsgNoValidSubscription}"); //_updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgNoValidSubscription}");
continue; continue;
} }
if (!url.StartsWith(Global.HttpsProtocol) && !url.StartsWith(Global.HttpProtocol)) if (!url.StartsWith(Global.HttpsProtocol) && !url.StartsWith(Global.HttpProtocol))
@ -155,17 +155,17 @@ namespace ServiceLib.Services
} }
if (item.enabled == false) if (item.enabled == false)
{ {
_updateFunc(false, $"{hashCode}{ResUI.MsgSkipSubscriptionUpdate}"); _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgSkipSubscriptionUpdate}");
continue; continue;
} }
var downloadHandle = new DownloadService(); var downloadHandle = new DownloadService();
downloadHandle.Error += (sender2, args) => downloadHandle.Error += (sender2, args) =>
{ {
_updateFunc(false, $"{hashCode}{args.GetException().Message}"); _updateFunc?.Invoke(false, $"{hashCode}{args.GetException().Message}");
}; };
_updateFunc(false, $"{hashCode}{ResUI.MsgStartGettingSubscriptions}"); _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgStartGettingSubscriptions}");
//one url //one url
url = Utils.GetPunycode(url); url = Utils.GetPunycode(url);
@ -227,14 +227,14 @@ namespace ServiceLib.Services
if (Utils.IsNullOrEmpty(result)) if (Utils.IsNullOrEmpty(result))
{ {
_updateFunc(false, $"{hashCode}{ResUI.MsgSubscriptionDecodingFailed}"); _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgSubscriptionDecodingFailed}");
} }
else else
{ {
_updateFunc(false, $"{hashCode}{ResUI.MsgGetSubscriptionSuccessfully}"); _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgGetSubscriptionSuccessfully}");
if (result?.Length < 99) if (result?.Length < 99)
{ {
_updateFunc(false, $"{hashCode}{result}"); _updateFunc?.Invoke(false, $"{hashCode}{result}");
} }
int ret = ConfigHandler.AddBatchServers(config, result, id, true); int ret = ConfigHandler.AddBatchServers(config, result, id, true);
@ -243,29 +243,29 @@ namespace ServiceLib.Services
Logging.SaveLog("FailedImportSubscription"); Logging.SaveLog("FailedImportSubscription");
Logging.SaveLog(result); Logging.SaveLog(result);
} }
_updateFunc(false, _updateFunc?.Invoke(false,
ret > 0 ret > 0
? $"{hashCode}{ResUI.MsgUpdateSubscriptionEnd}" ? $"{hashCode}{ResUI.MsgUpdateSubscriptionEnd}"
: $"{hashCode}{ResUI.MsgFailedImportSubscription}"); : $"{hashCode}{ResUI.MsgFailedImportSubscription}");
} }
_updateFunc(false, "-------------------------------------------------------"); _updateFunc?.Invoke(false, "-------------------------------------------------------");
} }
_updateFunc(true, $"{ResUI.MsgUpdateSubscriptionEnd}"); _updateFunc?.Invoke(true, $"{ResUI.MsgUpdateSubscriptionEnd}");
}); });
} }
public async Task UpdateGeoFileAll(Config config, Action<bool, string> update) public async Task UpdateGeoFileAll(Config config, Action<bool, string> updateFunc)
{ {
await UpdateGeoFile("geosite", _config, update); await UpdateGeoFile("geosite", _config, updateFunc);
await UpdateGeoFile("geoip", _config, update); await UpdateGeoFile("geoip", _config, updateFunc);
_updateFunc(true, string.Format(ResUI.MsgDownloadGeoFileSuccessfully, "geo")); _updateFunc?.Invoke(true, string.Format(ResUI.MsgDownloadGeoFileSuccessfully, "geo"));
} }
public async Task RunAvailabilityCheck(Action<bool, string> update) public async Task RunAvailabilityCheck(Action<bool, string> updateFunc)
{ {
var time = await new DownloadService().RunAvailabilityCheck(null); var time = await new DownloadService().RunAvailabilityCheck(null);
update(false, string.Format(ResUI.TestMeOutput, time)); updateFunc?.Invoke(false, string.Format(ResUI.TestMeOutput, time));
} }
#region private #region private
@ -290,7 +290,7 @@ namespace ServiceLib.Services
catch (Exception ex) catch (Exception ex)
{ {
Logging.SaveLog(ex.Message, ex); Logging.SaveLog(ex.Message, ex);
_updateFunc(false, ex.Message); _updateFunc?.Invoke(false, ex.Message);
return new ResultEventArgs(false, ex.Message); return new ResultEventArgs(false, ex.Message);
} }
} }
@ -355,7 +355,7 @@ namespace ServiceLib.Services
catch (Exception ex) catch (Exception ex)
{ {
Logging.SaveLog(ex.Message, ex); Logging.SaveLog(ex.Message, ex);
_updateFunc(false, ex.Message); _updateFunc?.Invoke(false, ex.Message);
return new SemanticVersion(""); return new SemanticVersion("");
} }
} }
@ -419,7 +419,7 @@ namespace ServiceLib.Services
catch (Exception ex) catch (Exception ex)
{ {
Logging.SaveLog(ex.Message, ex); Logging.SaveLog(ex.Message, ex);
_updateFunc(false, ex.Message); _updateFunc?.Invoke(false, ex.Message);
return new ResultEventArgs(false, ex.Message); return new ResultEventArgs(false, ex.Message);
} }
} }
@ -457,10 +457,10 @@ namespace ServiceLib.Services
return null; return null;
} }
private async Task UpdateGeoFile(string geoName, Config config, Action<bool, string> update) private async Task UpdateGeoFile(string geoName, Config config, Action<bool, string> updateFunc)
{ {
_config = config; _config = config;
_updateFunc = update; _updateFunc = updateFunc;
var url = string.Format(Global.GeoUrl, geoName); var url = string.Format(Global.GeoUrl, geoName);
var fileName = Utils.GetTempPath(Utils.GetGUID()); var fileName = Utils.GetTempPath(Utils.GetGUID());
@ -469,7 +469,7 @@ namespace ServiceLib.Services
{ {
if (args.Success) if (args.Success)
{ {
_updateFunc(false, string.Format(ResUI.MsgDownloadGeoFileSuccessfully, geoName)); _updateFunc?.Invoke(false, string.Format(ResUI.MsgDownloadGeoFileSuccessfully, geoName));
try try
{ {
@ -479,22 +479,22 @@ namespace ServiceLib.Services
File.Copy(fileName, targetPath, true); File.Copy(fileName, targetPath, true);
File.Delete(fileName); File.Delete(fileName);
//_updateFunc(true, ""); //_updateFunc?.Invoke(true, "");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_updateFunc(false, ex.Message); _updateFunc?.Invoke(false, ex.Message);
} }
} }
else else
{ {
_updateFunc(false, args.Msg); _updateFunc?.Invoke(false, args.Msg);
} }
}; };
downloadHandle.Error += (sender2, args) => downloadHandle.Error += (sender2, args) =>
{ {
_updateFunc(false, args.GetException().Message); _updateFunc?.Invoke(false, args.GetException().Message);
}; };
await downloadHandle.DownloadFileAsync(url, fileName, true, _timeout); await downloadHandle.DownloadFileAsync(url, fileName, true, _timeout);

View file

@ -32,7 +32,7 @@ namespace ServiceLib.ViewModels
await CheckUpdate() await CheckUpdate()
.ContinueWith(t => .ContinueWith(t =>
{ {
UpdateFinished(); _ = UpdateFinished();
}); });
}); });
EnableCheckPreReleaseUpdate = _config.guiItem.checkPreReleaseUpdate; EnableCheckPreReleaseUpdate = _config.guiItem.checkPreReleaseUpdate;

View file

@ -38,9 +38,9 @@ namespace ServiceLib.ViewModels
normalDNS2 = item2?.normalDNS ?? string.Empty; normalDNS2 = item2?.normalDNS ?? string.Empty;
tunDNS2 = item2?.tunDNS ?? string.Empty; tunDNS2 = item2?.tunDNS ?? string.Empty;
SaveCmd = ReactiveCommand.Create(() => SaveCmd = ReactiveCommand.CreateFromTask(async () =>
{ {
SaveSettingAsync(); await SaveSettingAsync();
}); });
ImportDefConfig4V2rayCmd = ReactiveCommand.Create(() => ImportDefConfig4V2rayCmd = ReactiveCommand.Create(() =>
@ -65,7 +65,7 @@ namespace ServiceLib.ViewModels
} }
else else
{ {
if (normalDNS.Contains("{") || normalDNS.Contains("}")) if (normalDNS.Contains('{') || normalDNS.Contains('}'))
{ {
NoticeHandler.Instance.Enqueue(ResUI.FillCorrectDNSText); NoticeHandler.Instance.Enqueue(ResUI.FillCorrectDNSText);
return; return;

View file

@ -453,7 +453,7 @@ namespace v2rayN.Desktop.Views
{ {
var item = new MenuItem() var item = new MenuItem()
{ {
Tag = it.Url.Replace(@"/releases", ""), Tag = it.Url?.Replace(@"/releases", ""),
Header = string.Format(ResUI.menuWebsiteItem, it.CoreType.ToString().Replace("_", " ")).UpperFirstChar() Header = string.Format(ResUI.menuWebsiteItem, it.CoreType.ToString().Replace("_", " ")).UpperFirstChar()
}; };
item.Click += MenuItem_Click; item.Click += MenuItem_Click;
@ -465,7 +465,7 @@ namespace v2rayN.Desktop.Views
{ {
if (sender is MenuItem item) if (sender is MenuItem item)
{ {
Utils.ProcessStart(item.Tag.ToString()); Utils.ProcessStart(item.Tag?.ToString());
} }
} }

View file

@ -25,7 +25,7 @@
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.1.3" /> <PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.1.3" />
<PackageReference Include="Avalonia.ReactiveUI" Version="11.1.3" /> <PackageReference Include="Avalonia.ReactiveUI" Version="11.1.3" />
<PackageReference Include="DialogHost.Avalonia" Version="0.8.1" /> <PackageReference Include="DialogHost.Avalonia" Version="0.8.1" />
<PackageReference Include="MessageBox.Avalonia" Version="3.1.6" /> <PackageReference Include="MessageBox.Avalonia" Version="3.1.6.13" />
<PackageReference Include="Semi.Avalonia" Version="11.1.0.4" /> <PackageReference Include="Semi.Avalonia" Version="11.1.0.4" />
<PackageReference Include="Semi.Avalonia.DataGrid" Version="11.1.0.4" /> <PackageReference Include="Semi.Avalonia.DataGrid" Version="11.1.0.4" />
<PackageReference Include="ReactiveUI" Version="20.1.63" /> <PackageReference Include="ReactiveUI" Version="20.1.63" />

View file

@ -185,7 +185,7 @@ namespace v2rayN.ViewModels
_paletteHelper.SetTheme(theme); _paletteHelper.SetTheme(theme);
} }
public void RegisterSystemColorSet(Config config, Window window, Action<bool> update) public void RegisterSystemColorSet(Config config, Window window, Action<bool> updateFunc)
{ {
var helper = new WindowInteropHelper(window); var helper = new WindowInteropHelper(window);
var hwndSource = HwndSource.FromHwnd(helper.EnsureHandle()); var hwndSource = HwndSource.FromHwnd(helper.EnsureHandle());
@ -198,7 +198,7 @@ namespace v2rayN.ViewModels
{ {
if (wParam == IntPtr.Zero && Marshal.PtrToStringUni(lParam) == "ImmersiveColorSet") if (wParam == IntPtr.Zero && Marshal.PtrToStringUni(lParam) == "ImmersiveColorSet")
{ {
update(!WindowsUtils.IsLightTheme()); updateFunc?.Invoke(!WindowsUtils.IsLightTheme());
} }
} }
} }