diff --git a/v2rayN/ServiceLib/Common/SqliteHelper.cs b/v2rayN/ServiceLib/Common/SqliteHelper.cs index 36447e9a..8c9a151b 100644 --- a/v2rayN/ServiceLib/Common/SqliteHelper.cs +++ b/v2rayN/ServiceLib/Common/SqliteHelper.cs @@ -10,7 +10,6 @@ namespace ServiceLib.Common private string _connstr; private SQLiteConnection _db; private SQLiteAsyncConnection _dbAsync; - private static readonly object objLock = new(); private readonly string _configDB = "guiNDB.db"; public SQLiteHelper() @@ -25,17 +24,9 @@ namespace ServiceLib.Common return _db.CreateTable(); } - public int Insert(object model) + public async Task InsertAllAsync(IEnumerable models) { - return _db.Insert(model); - } - - public int InsertAll(IEnumerable models) - { - lock (objLock) - { - return _db.InsertAll(models); - } + return await _dbAsync.InsertAllAsync(models); } public async Task InsertAsync(object model) @@ -43,46 +34,19 @@ namespace ServiceLib.Common return await _dbAsync.InsertAsync(model); } - public int Replace(object model) - { - lock (objLock) - { - return _db.InsertOrReplace(model); - } - } - public async Task ReplaceAsync(object model) { return await _dbAsync.InsertOrReplaceAsync(model); } - public int Update(object model) - { - lock (objLock) - { - return _db.Update(model); - } - } - public async Task UpdateAsync(object model) { return await _dbAsync.UpdateAsync(model); } - public int UpdateAll(IEnumerable models) + public async Task UpdateAllAsync(IEnumerable models) { - lock (objLock) - { - return _db.UpdateAll(models); - } - } - - public int Delete(object model) - { - lock (objLock) - { - return _db.Delete(model); - } + return await _dbAsync.UpdateAllAsync(models); } public async Task DeleteAsync(object model) @@ -90,6 +54,16 @@ namespace ServiceLib.Common return await _dbAsync.DeleteAsync(model); } + public async Task DeleteAllAsync() + { + return await _dbAsync.DeleteAllAsync(); + } + + public async Task ExecuteAsync(string sql) + { + return await _dbAsync.ExecuteAsync(sql); + } + public List Query(string sql) where T : new() { return _db.Query(sql); @@ -100,21 +74,6 @@ namespace ServiceLib.Common return await _dbAsync.QueryAsync(sql); } - public int Execute(string sql) - { - return _db.Execute(sql); - } - - public int DeleteAll() - { - return _db.DeleteAll(); - } - - public async Task ExecuteAsync(string sql) - { - return await _dbAsync.ExecuteAsync(sql); - } - public TableQuery Table() where T : new() { return _db.Table(); diff --git a/v2rayN/ServiceLib/Enums/EPresetType.cs b/v2rayN/ServiceLib/Enums/EPresetType.cs index 57a1984f..ffd89c11 100644 --- a/v2rayN/ServiceLib/Enums/EPresetType.cs +++ b/v2rayN/ServiceLib/Enums/EPresetType.cs @@ -5,4 +5,4 @@ Default = 0, Russia = 1, } -} +} \ No newline at end of file diff --git a/v2rayN/ServiceLib/Handler/AppHandler.cs b/v2rayN/ServiceLib/Handler/AppHandler.cs index b04870ad..3ef7eaf4 100644 --- a/v2rayN/ServiceLib/Handler/AppHandler.cs +++ b/v2rayN/ServiceLib/Handler/AppHandler.cs @@ -46,7 +46,8 @@ public bool InitApp() { - if (ConfigHandler.LoadConfig(ref _config) != 0) + _config = ConfigHandler.LoadConfig(); + if (_config == null) { return false; } @@ -152,7 +153,7 @@ { filter = filter.Replace("'", ""); } - sql += String.Format(" and (a.remarks like '%{0}%' or a.address like '%{0}%') ", filter); + sql += string.Format(" and (a.remarks like '%{0}%' or a.address like '%{0}%') ", filter); } return SQLiteHelper.Instance.Query(sql).ToList(); diff --git a/v2rayN/ServiceLib/Handler/ClashApiHandler.cs b/v2rayN/ServiceLib/Handler/ClashApiHandler.cs index c27dda9e..90897503 100644 --- a/v2rayN/ServiceLib/Handler/ClashApiHandler.cs +++ b/v2rayN/ServiceLib/Handler/ClashApiHandler.cs @@ -10,12 +10,7 @@ namespace ServiceLib.Handler private Dictionary? _proxies; public Dictionary ProfileContent { get; set; } - public void GetClashProxies(Config config, Action updateFunc) - { - Task.Run(() => GetClashProxiesAsync(config, updateFunc)); - } - - private async Task GetClashProxiesAsync(Config config, Action updateFunc) + public async Task?> GetClashProxiesAsync(Config config) { for (var i = 0; i < 5; i++) { @@ -30,74 +25,75 @@ namespace ServiceLib.Handler if (clashProxies != null || clashProviders != null) { _proxies = clashProxies?.proxies; - updateFunc?.Invoke(clashProxies, clashProviders); - return; + return new Tuple(clashProxies, clashProviders); } - Task.Delay(5000).Wait(); + + await Task.Delay(5000); } - updateFunc?.Invoke(null, null); + + return null; } public void ClashProxiesDelayTest(bool blAll, List lstProxy, Action updateFunc) { Task.Run(() => + { + if (blAll) { - if (blAll) + for (int i = 0; i < 5; i++) { - for (int i = 0; i < 5; i++) + if (_proxies != null) { - if (_proxies != null) - { - break; - } - Task.Delay(5000).Wait(); - } - if (_proxies == null) - { - return; - } - lstProxy = new List(); - foreach (KeyValuePair kv in _proxies) - { - if (Global.notAllowTestType.Contains(kv.Value.type.ToLower())) - { - continue; - } - lstProxy.Add(new ClashProxyModel() - { - name = kv.Value.name, - type = kv.Value.type.ToLower(), - }); + break; } + Task.Delay(5000).Wait(); } - - if (lstProxy == null) + if (_proxies == null) { return; } - var urlBase = $"{GetApiUrl()}/proxies"; - urlBase += @"/{0}/delay?timeout=10000&url=" + AppHandler.Instance.Config.speedTestItem.speedPingTestUrl; - - List tasks = new List(); - foreach (var it in lstProxy) + lstProxy = new List(); + foreach (KeyValuePair kv in _proxies) { - if (Global.notAllowTestType.Contains(it.type.ToLower())) + if (Global.notAllowTestType.Contains(kv.Value.type.ToLower())) { continue; } - var name = it.name; - var url = string.Format(urlBase, name); - tasks.Add(Task.Run(async () => + lstProxy.Add(new ClashProxyModel() { - var result = await HttpClientHelper.Instance.TryGetAsync(url); - updateFunc?.Invoke(it, result); - })); + name = kv.Value.name, + type = kv.Value.type.ToLower(), + }); } - Task.WaitAll(tasks.ToArray()); + } - Task.Delay(1000).Wait(); - updateFunc?.Invoke(null, ""); - }); + if (lstProxy == null) + { + return; + } + var urlBase = $"{GetApiUrl()}/proxies"; + urlBase += @"/{0}/delay?timeout=10000&url=" + AppHandler.Instance.Config.speedTestItem.speedPingTestUrl; + + List tasks = new List(); + foreach (var it in lstProxy) + { + if (Global.notAllowTestType.Contains(it.type.ToLower())) + { + continue; + } + var name = it.name; + var url = string.Format(urlBase, name); + tasks.Add(Task.Run(async () => + { + var result = await HttpClientHelper.Instance.TryGetAsync(url); + updateFunc?.Invoke(it, result); + })); + } + Task.WaitAll(tasks.ToArray()); + + Task.Delay(1000).Wait(); + updateFunc?.Invoke(null, ""); + }); } public List? GetClashProxyGroups() @@ -118,7 +114,7 @@ namespace ServiceLib.Handler } } - public async void ClashSetActiveProxy(string name, string nameNode) + public async Task ClashSetActiveProxy(string name, string nameNode) { try { @@ -133,24 +129,21 @@ namespace ServiceLib.Handler } } - public void ClashConfigUpdate(Dictionary headers) + public async Task ClashConfigUpdate(Dictionary headers) { - Task.Run(async () => + if (_proxies == null) { - if (_proxies == null) - { - return; - } + return; + } - var urlBase = $"{GetApiUrl()}/configs"; + var urlBase = $"{GetApiUrl()}/configs"; - await HttpClientHelper.Instance.PatchAsync(urlBase, headers); - }); + await HttpClientHelper.Instance.PatchAsync(urlBase, headers); } - public async void ClashConfigReload(string filePath) + public async Task ClashConfigReload(string filePath) { - ClashConnectionClose(""); + await ClashConnectionClose(""); try { var url = $"{GetApiUrl()}/configs?force=true"; @@ -164,12 +157,7 @@ namespace ServiceLib.Handler } } - public void GetClashConnections(Config config, Action updateFunc) - { - Task.Run(() => GetClashConnectionsAsync(config, updateFunc)); - } - - private async Task GetClashConnectionsAsync(Config config, Action updateFunc) + public async Task GetClashConnectionsAsync(Config config) { try { @@ -177,15 +165,17 @@ namespace ServiceLib.Handler var result = await HttpClientHelper.Instance.TryGetAsync(url); var clashConnections = JsonUtils.Deserialize(result); - updateFunc?.Invoke(clashConnections); + return clashConnections; } catch (Exception ex) { Logging.SaveLog(ex.Message, ex); } + + return null; } - public async void ClashConnectionClose(string id) + public async Task ClashConnectionClose(string id) { try { diff --git a/v2rayN/ServiceLib/Handler/ConfigHandler.cs b/v2rayN/ServiceLib/Handler/ConfigHandler.cs index c227b942..cf92d615 100644 --- a/v2rayN/ServiceLib/Handler/ConfigHandler.cs +++ b/v2rayN/ServiceLib/Handler/ConfigHandler.cs @@ -18,8 +18,9 @@ namespace ServiceLib.Handler /// /// /// - public static int LoadConfig(ref Config? config) + public static Config? LoadConfig() { + Config? config = null; var result = Utils.LoadResource(Utils.GetConfigPath(_configRes)); if (Utils.IsNotEmpty(result)) { @@ -30,7 +31,7 @@ namespace ServiceLib.Handler if (File.Exists(Utils.GetConfigPath(_configRes))) { Logging.SaveLog("LoadConfig Exception"); - return -1; + return null; } } @@ -164,7 +165,7 @@ namespace ServiceLib.Handler config.systemProxyItem ??= new(); config.webDavItem ??= new(); - return 0; + return config; } /// @@ -172,9 +173,9 @@ namespace ServiceLib.Handler /// /// /// - public static int SaveConfig(Config config, bool reload = true) + public static async Task SaveConfig(Config config, bool reload = true) { - ToJsonFile(config); + await ToJsonFile(config); return 0; } @@ -183,7 +184,7 @@ namespace ServiceLib.Handler /// 存储文件 /// /// - private static void ToJsonFile(Config config) + private static async Task ToJsonFile(Config config) { lock (_objLock) { @@ -215,7 +216,7 @@ namespace ServiceLib.Handler #region Server - public static int AddServer(Config config, ProfileItem profileItem) + public static async Task AddServer(Config config, ProfileItem profileItem) { var item = AppHandler.Instance.GetProfileItem(profileItem.indexId); if (item is null) @@ -252,15 +253,15 @@ namespace ServiceLib.Handler var ret = item.configType switch { - EConfigType.VMess => AddVMessServer(config, item), - EConfigType.Shadowsocks => AddShadowsocksServer(config, item), - EConfigType.SOCKS => AddSocksServer(config, item), - EConfigType.HTTP => AddHttpServer(config, item), - EConfigType.Trojan => AddTrojanServer(config, item), - EConfigType.VLESS => AddVlessServer(config, item), - EConfigType.Hysteria2 => AddHysteria2Server(config, item), - EConfigType.TUIC => AddTuicServer(config, item), - EConfigType.WireGuard => AddWireguardServer(config, item), + EConfigType.VMess => await AddVMessServer(config, item), + EConfigType.Shadowsocks => await AddShadowsocksServer(config, item), + EConfigType.SOCKS => await AddSocksServer(config, item), + EConfigType.HTTP => await AddHttpServer(config, item), + EConfigType.Trojan => await AddTrojanServer(config, item), + EConfigType.VLESS => await AddVlessServer(config, item), + EConfigType.Hysteria2 => await AddHysteria2Server(config, item), + EConfigType.TUIC => await AddTuicServer(config, item), + EConfigType.WireGuard => await AddWireguardServer(config, item), _ => -1, }; return ret; @@ -272,7 +273,7 @@ namespace ServiceLib.Handler /// /// /// - public static int AddVMessServer(Config config, ProfileItem profileItem, bool toFile = true) + public static async Task AddVMessServer(Config config, ProfileItem profileItem, bool toFile = true) { profileItem.configType = EConfigType.VMess; @@ -294,7 +295,7 @@ namespace ServiceLib.Handler return -1; } - AddServerCommon(config, profileItem, toFile); + await AddServerCommon(config, profileItem, toFile); return 0; } @@ -305,7 +306,7 @@ namespace ServiceLib.Handler /// /// /// - public static int RemoveServer(Config config, List indexes) + public static async Task RemoveServer(Config config, List indexes) { var subid = "TempRemoveSubId"; foreach (var item in indexes) @@ -313,8 +314,8 @@ namespace ServiceLib.Handler item.subid = subid; } - SQLiteHelper.Instance.UpdateAll(indexes); - RemoveServerViaSubid(config, subid, false); + await SQLiteHelper.Instance.UpdateAllAsync(indexes); + await RemoveServerViaSubid(config, subid, false); return 0; } @@ -325,7 +326,7 @@ namespace ServiceLib.Handler /// /// /// - public static int CopyServer(Config config, List indexes) + public static async Task CopyServer(Config config, List indexes) { foreach (var it in indexes) { @@ -335,20 +336,20 @@ namespace ServiceLib.Handler continue; } - ProfileItem profileItem = JsonUtils.DeepCopy(item); + var profileItem = JsonUtils.DeepCopy(item); profileItem.indexId = string.Empty; profileItem.remarks = $"{item.remarks}-clone"; if (profileItem.configType == EConfigType.Custom) { profileItem.address = Utils.GetConfigPath(profileItem.address); - if (AddCustomServer(config, profileItem, false) == 0) + if (await AddCustomServer(config, profileItem, false) == 0) { } } else { - AddServerCommon(config, profileItem, true); + await AddServerCommon(config, profileItem, true); } } @@ -361,7 +362,7 @@ namespace ServiceLib.Handler /// /// /// - public static int SetDefaultServerIndex(Config config, string? indexId) + public static async Task SetDefaultServerIndex(Config config, string? indexId) { if (Utils.IsNullOrEmpty(indexId)) { @@ -370,12 +371,12 @@ namespace ServiceLib.Handler config.indexId = indexId; - ToJsonFile(config); + await ToJsonFile(config); return 0; } - public static int SetDefaultServer(Config config, List lstProfile) + public static async Task SetDefaultServer(Config config, List lstProfile) { if (lstProfile.Exists(t => t.indexId == config.indexId)) { @@ -387,18 +388,18 @@ namespace ServiceLib.Handler } if (lstProfile.Count > 0) { - return SetDefaultServerIndex(config, lstProfile.Where(t => t.port > 0).FirstOrDefault()?.indexId); + return await SetDefaultServerIndex(config, lstProfile.Where(t => t.port > 0).FirstOrDefault()?.indexId); } - return SetDefaultServerIndex(config, SQLiteHelper.Instance.Table().Where(t => t.port > 0).Select(t => t.indexId).FirstOrDefault()); + return await SetDefaultServerIndex(config, SQLiteHelper.Instance.Table().Where(t => t.port > 0).Select(t => t.indexId).FirstOrDefault()); } - public static ProfileItem? GetDefaultServer(Config config) + public static async Task GetDefaultServer(Config config) { var item = AppHandler.Instance.GetProfileItem(config.indexId); if (item is null) { var item2 = SQLiteHelper.Instance.Table().FirstOrDefault(); - SetDefaultServerIndex(config, item2?.indexId); + await SetDefaultServerIndex(config, item2?.indexId); return item2; } @@ -413,7 +414,7 @@ namespace ServiceLib.Handler /// /// /// - public static int MoveServer(Config config, ref List lstProfile, int index, EMove eMove, int pos = -1) + public static async Task MoveServer(Config config, List lstProfile, int index, EMove eMove, int pos = -1) { int count = lstProfile.Count; if (index < 0 || index > lstProfile.Count - 1) @@ -485,7 +486,7 @@ namespace ServiceLib.Handler /// /// /// - public static int AddCustomServer(Config config, ProfileItem profileItem, bool blDelete) + public static async Task AddCustomServer(Config config, ProfileItem profileItem, bool blDelete) { var fileName = profileItem.address; if (!File.Exists(fileName)) @@ -517,7 +518,7 @@ namespace ServiceLib.Handler profileItem.remarks = $"import custom@{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}"; } - AddServerCommon(config, profileItem, true); + await AddServerCommon(config, profileItem, true); return 0; } @@ -528,7 +529,7 @@ namespace ServiceLib.Handler /// /// /// - public static int EditCustomServer(Config config, ProfileItem profileItem) + public static async Task EditCustomServer(Config config, ProfileItem profileItem) { var item = AppHandler.Instance.GetProfileItem(profileItem.indexId); if (item is null) @@ -544,7 +545,7 @@ namespace ServiceLib.Handler item.preSocksPort = profileItem.preSocksPort; } - if (SQLiteHelper.Instance.Update(item) > 0) + if (await SQLiteHelper.Instance.UpdateAsync(item) > 0) { return 0; } @@ -562,7 +563,7 @@ namespace ServiceLib.Handler /// /// /// - public static int AddShadowsocksServer(Config config, ProfileItem profileItem, bool toFile = true) + public static async Task AddShadowsocksServer(Config config, ProfileItem profileItem, bool toFile = true) { profileItem.configType = EConfigType.Shadowsocks; @@ -579,7 +580,7 @@ namespace ServiceLib.Handler return -1; } - AddServerCommon(config, profileItem, toFile); + await AddServerCommon(config, profileItem, toFile); return 0; } @@ -590,13 +591,13 @@ namespace ServiceLib.Handler /// /// /// - public static int AddSocksServer(Config config, ProfileItem profileItem, bool toFile = true) + public static async Task AddSocksServer(Config config, ProfileItem profileItem, bool toFile = true) { profileItem.configType = EConfigType.SOCKS; profileItem.address = profileItem.address.TrimEx(); - AddServerCommon(config, profileItem, toFile); + await AddServerCommon(config, profileItem, toFile); return 0; } @@ -607,13 +608,13 @@ namespace ServiceLib.Handler /// /// /// - public static int AddHttpServer(Config config, ProfileItem profileItem, bool toFile = true) + public static async Task AddHttpServer(Config config, ProfileItem profileItem, bool toFile = true) { profileItem.configType = EConfigType.HTTP; profileItem.address = profileItem.address.TrimEx(); - AddServerCommon(config, profileItem, toFile); + await AddServerCommon(config, profileItem, toFile); return 0; } @@ -624,7 +625,7 @@ namespace ServiceLib.Handler /// /// /// - public static int AddTrojanServer(Config config, ProfileItem profileItem, bool toFile = true) + public static async Task AddTrojanServer(Config config, ProfileItem profileItem, bool toFile = true) { profileItem.configType = EConfigType.Trojan; @@ -639,7 +640,7 @@ namespace ServiceLib.Handler return -1; } - AddServerCommon(config, profileItem, toFile); + await AddServerCommon(config, profileItem, toFile); return 0; } @@ -650,7 +651,7 @@ namespace ServiceLib.Handler /// /// /// - public static int AddHysteria2Server(Config config, ProfileItem profileItem, bool toFile = true) + public static async Task AddHysteria2Server(Config config, ProfileItem profileItem, bool toFile = true) { profileItem.configType = EConfigType.Hysteria2; profileItem.coreType = ECoreType.sing_box; @@ -669,7 +670,7 @@ namespace ServiceLib.Handler return -1; } - AddServerCommon(config, profileItem, toFile); + await AddServerCommon(config, profileItem, toFile); return 0; } @@ -680,7 +681,7 @@ namespace ServiceLib.Handler /// /// /// - public static int AddTuicServer(Config config, ProfileItem profileItem, bool toFile = true) + public static async Task AddTuicServer(Config config, ProfileItem profileItem, bool toFile = true) { profileItem.configType = EConfigType.TUIC; profileItem.coreType = ECoreType.sing_box; @@ -708,7 +709,7 @@ namespace ServiceLib.Handler return -1; } - AddServerCommon(config, profileItem, toFile); + await AddServerCommon(config, profileItem, toFile); return 0; } @@ -719,7 +720,7 @@ namespace ServiceLib.Handler /// /// /// - public static int AddWireguardServer(Config config, ProfileItem profileItem, bool toFile = true) + public static async Task AddWireguardServer(Config config, ProfileItem profileItem, bool toFile = true) { profileItem.configType = EConfigType.WireGuard; profileItem.coreType = ECoreType.sing_box; @@ -740,12 +741,12 @@ namespace ServiceLib.Handler return -1; } - AddServerCommon(config, profileItem, toFile); + await AddServerCommon(config, profileItem, toFile); return 0; } - public static int SortServers(Config config, string subId, string colName, bool asc) + public static async Task SortServers(Config config, string subId, string colName, bool asc) { var lstModel = AppHandler.Instance.ProfileItems(subId, ""); if (lstModel.Count <= 0) @@ -846,7 +847,7 @@ namespace ServiceLib.Handler /// /// /// - public static int AddVlessServer(Config config, ProfileItem profileItem, bool toFile = true) + public static async Task AddVlessServer(Config config, ProfileItem profileItem, bool toFile = true) { profileItem.configType = EConfigType.VLESS; @@ -872,12 +873,12 @@ namespace ServiceLib.Handler profileItem.security = Global.None; } - AddServerCommon(config, profileItem, toFile); + await AddServerCommon(config, profileItem, toFile); return 0; } - public static Tuple DedupServerList(Config config, string subId) + public static async Task> DedupServerList(Config config, string subId) { var lstProfile = AppHandler.Instance.ProfileItems(subId); @@ -896,12 +897,12 @@ namespace ServiceLib.Handler lstRemove.Add(item); } } - RemoveServer(config, lstRemove); + await RemoveServer(config, lstRemove); return new Tuple(lstProfile.Count, lstKeep.Count); } - public static int AddServerCommon(Config config, ProfileItem profileItem, bool toFile = true) + public static async Task AddServerCommon(Config config, ProfileItem profileItem, bool toFile = true) { profileItem.configVersion = 2; @@ -947,7 +948,7 @@ namespace ServiceLib.Handler if (toFile) { - SQLiteHelper.Instance.Replace(profileItem); + await SQLiteHelper.Instance.ReplaceAsync(profileItem); } return 0; } @@ -975,7 +976,7 @@ namespace ServiceLib.Handler && (!remarks || o.remarks == n.remarks); } - private static int RemoveProfileItem(Config config, string indexId) + private static async Task RemoveProfileItem(Config config, string indexId) { try { @@ -989,7 +990,7 @@ namespace ServiceLib.Handler File.Delete(Utils.GetConfigPath(item.address)); } - SQLiteHelper.Instance.Delete(item); + await SQLiteHelper.Instance.DeleteAsync(item); } catch (Exception ex) { @@ -999,19 +1000,19 @@ namespace ServiceLib.Handler return 0; } - public static int AddCustomServer4Multiple(Config config, List selecteds, ECoreType coreType, out string indexId) + public static async Task> AddCustomServer4Multiple(Config config, List selecteds, ECoreType coreType) { - indexId = Utils.GetMd5(Global.CoreMultipleLoadConfigFileName); + var indexId = Utils.GetMd5(Global.CoreMultipleLoadConfigFileName); string configPath = Utils.GetConfigPath(Global.CoreMultipleLoadConfigFileName); if (CoreConfigHandler.GenerateClientMultipleLoadConfig(config, configPath, selecteds, coreType, out string msg) != 0) { - return -1; + return new Tuple(-1, ""); } var fileName = configPath; if (!File.Exists(fileName)) { - return -1; + return new Tuple(-1, ""); } var profileItem = AppHandler.Instance.GetProfileItem(indexId) ?? new(); @@ -1021,9 +1022,9 @@ namespace ServiceLib.Handler profileItem.configType = EConfigType.Custom; profileItem.coreType = coreType; - AddServerCommon(config, profileItem, true); + await AddServerCommon(config, profileItem, true); - return 0; + return new Tuple(0, indexId); } #endregion Server @@ -1037,7 +1038,7 @@ namespace ServiceLib.Handler /// /// /// 成功导入的数量 - private static int AddBatchServers(Config config, string strData, string subid, bool isSub, List lstOriSub) + private static async Task AddBatchServers(Config config, string strData, string subid, bool isSub, List lstOriSub) { if (Utils.IsNullOrEmpty(strData)) { @@ -1048,7 +1049,7 @@ namespace ServiceLib.Handler //remove sub items if (isSub && Utils.IsNotEmpty(subid)) { - RemoveServerViaSubid(config, subid, isSub); + await RemoveServerViaSubid(config, subid, isSub); subFilter = AppHandler.Instance.GetSubItem(subid)?.filter ?? ""; } @@ -1066,7 +1067,7 @@ namespace ServiceLib.Handler //maybe sub if (!isSub && (str.StartsWith(Global.HttpsProtocol) || str.StartsWith(Global.HttpProtocol))) { - if (AddSubItem(config, str) == 0) + if (await AddSubItem(config, str) == 0) { countServers++; } @@ -1114,14 +1115,14 @@ namespace ServiceLib.Handler var addStatus = profileItem.configType switch { - EConfigType.VMess => AddVMessServer(config, profileItem, false), - EConfigType.Shadowsocks => AddShadowsocksServer(config, profileItem, false), - EConfigType.SOCKS => AddSocksServer(config, profileItem, false), - EConfigType.Trojan => AddTrojanServer(config, profileItem, false), - EConfigType.VLESS => AddVlessServer(config, profileItem, false), - EConfigType.Hysteria2 => AddHysteria2Server(config, profileItem, false), - EConfigType.TUIC => AddTuicServer(config, profileItem, false), - EConfigType.WireGuard => AddWireguardServer(config, profileItem, false), + EConfigType.VMess => await AddVMessServer(config, profileItem, false), + EConfigType.Shadowsocks => await AddShadowsocksServer(config, profileItem, false), + EConfigType.SOCKS => await AddSocksServer(config, profileItem, false), + EConfigType.Trojan => await AddTrojanServer(config, profileItem, false), + EConfigType.VLESS => await AddVlessServer(config, profileItem, false), + EConfigType.Hysteria2 => await AddHysteria2Server(config, profileItem, false), + EConfigType.TUIC => await AddTuicServer(config, profileItem, false), + EConfigType.WireGuard => await AddWireguardServer(config, profileItem, false), _ => -1, }; @@ -1134,14 +1135,14 @@ namespace ServiceLib.Handler if (lstAdd.Count > 0) { - SQLiteHelper.Instance.InsertAll(lstAdd); + await SQLiteHelper.Instance.InsertAllAsync(lstAdd); } - ToJsonFile(config); + await ToJsonFile(config); return countServers; } - private static int AddBatchServers4Custom(Config config, string strData, string subid, bool isSub, List lstOriSub) + private static async Task AddBatchServers4Custom(Config config, string strData, string subid, bool isSub, List lstOriSub) { if (Utils.IsNullOrEmpty(strData)) { @@ -1167,7 +1168,7 @@ namespace ServiceLib.Handler { if (isSub && Utils.IsNotEmpty(subid)) { - RemoveServerViaSubid(config, subid, isSub); + await RemoveServerViaSubid(config, subid, isSub); } int count = 0; foreach (var it in lstProfiles) @@ -1175,7 +1176,7 @@ namespace ServiceLib.Handler it.subid = subid; it.isSub = isSub; it.preSocksPort = preSocksPort; - if (AddCustomServer(config, it, true) == 0) + if (await AddCustomServer(config, it, true) == 0) { count++; } @@ -1223,7 +1224,7 @@ namespace ServiceLib.Handler if (isSub && Utils.IsNotEmpty(subid)) { - RemoveServerViaSubid(config, subid, isSub); + await RemoveServerViaSubid(config, subid, isSub); } if (isSub && lstOriSub?.Count == 1) { @@ -1232,7 +1233,7 @@ namespace ServiceLib.Handler profileItem.subid = subid; profileItem.isSub = isSub; profileItem.preSocksPort = preSocksPort; - if (AddCustomServer(config, profileItem, true) == 0) + if (await AddCustomServer(config, profileItem, true) == 0) { return 1; } @@ -1242,7 +1243,7 @@ namespace ServiceLib.Handler } } - private static int AddBatchServers4SsSIP008(Config config, string strData, string subid, bool isSub, List lstOriSub) + private static async Task AddBatchServers4SsSIP008(Config config, string strData, string subid, bool isSub, List lstOriSub) { if (Utils.IsNullOrEmpty(strData)) { @@ -1251,7 +1252,7 @@ namespace ServiceLib.Handler if (isSub && Utils.IsNotEmpty(subid)) { - RemoveServerViaSubid(config, subid, isSub); + await RemoveServerViaSubid(config, subid, isSub); } var lstSsServer = ShadowsocksFmt.ResolveSip008(strData); @@ -1262,19 +1263,19 @@ namespace ServiceLib.Handler { ssItem.subid = subid; ssItem.isSub = isSub; - if (AddShadowsocksServer(config, ssItem) == 0) + if (await AddShadowsocksServer(config, ssItem) == 0) { counter++; } } - ToJsonFile(config); + await ToJsonFile(config); return counter; } return -1; } - public static int AddBatchServers(Config config, string strData, string subid, bool isSub) + public static async Task AddBatchServers(Config config, string strData, string subid, bool isSub) { if (Utils.IsNullOrEmpty(strData)) { @@ -1289,26 +1290,26 @@ namespace ServiceLib.Handler var counter = 0; if (Utils.IsBase64String(strData)) { - counter = AddBatchServers(config, Utils.Base64Decode(strData), subid, isSub, lstOriSub); + counter = await AddBatchServers(config, Utils.Base64Decode(strData), subid, isSub, lstOriSub); } if (counter < 1) { - counter = AddBatchServers(config, strData, subid, isSub, lstOriSub); + counter = await AddBatchServers(config, strData, subid, isSub, lstOriSub); } if (counter < 1) { - counter = AddBatchServers(config, Utils.Base64Decode(strData), subid, isSub, lstOriSub); + counter = await AddBatchServers(config, Utils.Base64Decode(strData), subid, isSub, lstOriSub); } if (counter < 1) { - counter = AddBatchServers4SsSIP008(config, strData, subid, isSub, lstOriSub); + counter = await AddBatchServers4SsSIP008(config, strData, subid, isSub, lstOriSub); } //maybe other sub if (counter < 1) { - counter = AddBatchServers4Custom(config, strData, subid, isSub, lstOriSub); + counter = await AddBatchServers4Custom(config, strData, subid, isSub, lstOriSub); } return counter; @@ -1324,7 +1325,7 @@ namespace ServiceLib.Handler /// /// /// - public static int AddSubItem(Config config, string url) + public static async Task AddSubItem(Config config, string url) { //already exists if (SQLiteHelper.Instance.Table().Any(e => e.url == url)) @@ -1348,10 +1349,10 @@ namespace ServiceLib.Handler return 0; } - return AddSubItem(config, subItem); + return await AddSubItem(config, subItem); } - public static int AddSubItem(Config config, SubItem subItem) + public static async Task AddSubItem(Config config, SubItem subItem) { var item = AppHandler.Instance.GetSubItem(subItem.id); if (item is null) @@ -1389,7 +1390,7 @@ namespace ServiceLib.Handler item.sort = maxSort + 1; } } - if (SQLiteHelper.Instance.Replace(item) > 0) + if (await SQLiteHelper.Instance.ReplaceAsync(item) > 0) { return 0; } @@ -1405,7 +1406,7 @@ namespace ServiceLib.Handler /// /// /// - public static int RemoveServerViaSubid(Config config, string subid, bool isSub) + public static async Task RemoveServerViaSubid(Config config, string subid, bool isSub) { if (Utils.IsNullOrEmpty(subid)) { @@ -1414,11 +1415,11 @@ namespace ServiceLib.Handler var customProfile = SQLiteHelper.Instance.Table().Where(t => t.subid == subid && t.configType == EConfigType.Custom).ToList(); if (isSub) { - SQLiteHelper.Instance.Execute($"delete from ProfileItem where isSub = 1 and subid = '{subid}'"); + await SQLiteHelper.Instance.ExecuteAsync($"delete from ProfileItem where isSub = 1 and subid = '{subid}'"); } else { - SQLiteHelper.Instance.Execute($"delete from ProfileItem where subid = '{subid}'"); + await SQLiteHelper.Instance.ExecuteAsync($"delete from ProfileItem where subid = '{subid}'"); } foreach (var item in customProfile) { @@ -1428,26 +1429,26 @@ namespace ServiceLib.Handler return 0; } - public static int DeleteSubItem(Config config, string id) + public static async Task DeleteSubItem(Config config, string id) { var item = AppHandler.Instance.GetSubItem(id); if (item is null) { return 0; } - SQLiteHelper.Instance.Delete(item); - RemoveServerViaSubid(config, id, false); + await SQLiteHelper.Instance.DeleteAsync(item); + await RemoveServerViaSubid(config, id, false); return 0; } - public static int MoveToGroup(Config config, List lstProfile, string subid) + public static async Task MoveToGroup(Config config, List lstProfile, string subid) { foreach (var item in lstProfile) { item.subid = subid; } - SQLiteHelper.Instance.UpdateAll(lstProfile); + await SQLiteHelper.Instance.UpdateAllAsync(lstProfile); return 0; } @@ -1456,14 +1457,14 @@ namespace ServiceLib.Handler #region Routing - public static int SaveRoutingItem(Config config, RoutingItem item) + public static async Task SaveRoutingItem(Config config, RoutingItem item) { if (Utils.IsNullOrEmpty(item.id)) { item.id = Utils.GetGuid(false); } - if (SQLiteHelper.Instance.Replace(item) > 0) + if (await SQLiteHelper.Instance.ReplaceAsync(item) > 0) { return 0; } @@ -1479,7 +1480,7 @@ namespace ServiceLib.Handler /// /// /// - public static int AddBatchRoutingRules(ref RoutingItem routingItem, string strData) + public static async Task AddBatchRoutingRules(RoutingItem routingItem, string strData) { if (Utils.IsNullOrEmpty(strData)) { @@ -1504,7 +1505,7 @@ namespace ServiceLib.Handler routingItem.id = Utils.GetGuid(false); } - if (SQLiteHelper.Instance.Replace(routingItem) > 0) + if (await SQLiteHelper.Instance.ReplaceAsync(routingItem) > 0) { return 0; } @@ -1521,7 +1522,7 @@ namespace ServiceLib.Handler /// /// /// - public static int MoveRoutingRule(List rules, int index, EMove eMove, int pos = -1) + public static async Task MoveRoutingRule(List rules, int index, EMove eMove, int pos = -1) { int count = rules.Count; if (index < 0 || index > rules.Count - 1) @@ -1591,55 +1592,55 @@ namespace ServiceLib.Handler return 0; } - public static int SetDefaultRouting(Config config, RoutingItem routingItem) + public static async Task SetDefaultRouting(Config config, RoutingItem routingItem) { if (SQLiteHelper.Instance.Table().Where(t => t.id == routingItem.id).Count() > 0) { config.routingBasicItem.routingIndexId = routingItem.id; } - ToJsonFile(config); + await ToJsonFile(config); return 0; } - public static RoutingItem GetDefaultRouting(Config config) + public static async Task GetDefaultRouting(Config config) { var item = AppHandler.Instance.GetRoutingItem(config.routingBasicItem.routingIndexId); if (item is null) { var item2 = SQLiteHelper.Instance.Table().FirstOrDefault(t => t.locked == false); - SetDefaultRouting(config, item2); + await SetDefaultRouting(config, item2); return item2; } return item; } - public static int InitRouting(Config config, bool blImportAdvancedRules = false) + public static async Task InitRouting(Config config, bool blImportAdvancedRules = false) { if (string.IsNullOrEmpty(config.constItem.routeRulesTemplateSourceUrl)) { - InitBuiltinRouting(config, blImportAdvancedRules); + await InitBuiltinRouting(config, blImportAdvancedRules); } else { - InitExternalRouting(config, blImportAdvancedRules); + await InitExternalRouting(config, blImportAdvancedRules); } return 0; } - public static int InitExternalRouting(Config config, bool blImportAdvancedRules = false) + public static async Task InitExternalRouting(Config config, bool blImportAdvancedRules = false) { var downloadHandle = new DownloadService(); var templateContent = Task.Run(() => downloadHandle.TryDownloadString(config.constItem.routeRulesTemplateSourceUrl, false, "")).Result; - if (String.IsNullOrEmpty(templateContent)) - return InitBuiltinRouting(config, blImportAdvancedRules); // fallback + if (string.IsNullOrEmpty(templateContent)) + return await InitBuiltinRouting(config, blImportAdvancedRules); // fallback var template = JsonUtils.Deserialize(templateContent); if (template == null) - return InitBuiltinRouting(config, blImportAdvancedRules); // fallback + return await InitBuiltinRouting(config, blImportAdvancedRules); // fallback var items = AppHandler.Instance.RoutingItems(); var maxSort = items.Count; @@ -1651,14 +1652,14 @@ namespace ServiceLib.Handler { var item = template.routingItems[i]; - if (String.IsNullOrEmpty(item.url) && String.IsNullOrEmpty(item.ruleSet)) + if (string.IsNullOrEmpty(item.url) && string.IsNullOrEmpty(item.ruleSet)) continue; - var ruleSetsString = !String.IsNullOrEmpty(item.ruleSet) + var ruleSetsString = !string.IsNullOrEmpty(item.ruleSet) ? item.ruleSet : Task.Run(() => downloadHandle.TryDownloadString(item.url, false, "")).Result; - if (String.IsNullOrEmpty(ruleSetsString)) + if (string.IsNullOrEmpty(ruleSetsString)) continue; item.remarks = $"{template.version}-{item.remarks}"; @@ -1666,19 +1667,19 @@ namespace ServiceLib.Handler item.sort = ++maxSort; item.url = string.Empty; - AddBatchRoutingRules(ref item, ruleSetsString); + await AddBatchRoutingRules(item, ruleSetsString); //first rule as default at first startup if (!blImportAdvancedRules && i == 0) { - SetDefaultRouting(config, item); + await SetDefaultRouting(config, item); } } return 0; } - public static int InitBuiltinRouting(Config config, bool blImportAdvancedRules = false) + public static async Task InitBuiltinRouting(Config config, bool blImportAdvancedRules = false) { var ver = "V3-"; var items = AppHandler.Instance.RoutingItems(); @@ -1695,7 +1696,7 @@ namespace ServiceLib.Handler url = string.Empty, sort = maxSort + 1, }; - AddBatchRoutingRules(ref item2, Utils.GetEmbedText(Global.CustomRoutingFileName + "white")); + await AddBatchRoutingRules(item2, Utils.GetEmbedText(Global.CustomRoutingFileName + "white")); //Blacklist var item3 = new RoutingItem() @@ -1704,7 +1705,7 @@ namespace ServiceLib.Handler url = string.Empty, sort = maxSort + 2, }; - AddBatchRoutingRules(ref item3, Utils.GetEmbedText(Global.CustomRoutingFileName + "black")); + await AddBatchRoutingRules(item3, Utils.GetEmbedText(Global.CustomRoutingFileName + "black")); //Global var item1 = new RoutingItem() @@ -1713,11 +1714,11 @@ namespace ServiceLib.Handler url = string.Empty, sort = maxSort + 3, }; - AddBatchRoutingRules(ref item1, Utils.GetEmbedText(Global.CustomRoutingFileName + "global")); + await AddBatchRoutingRules(item1, Utils.GetEmbedText(Global.CustomRoutingFileName + "global")); if (!blImportAdvancedRules) { - SetDefaultRouting(config, item2); + await SetDefaultRouting(config, item2); } return 0; } @@ -1727,16 +1728,16 @@ namespace ServiceLib.Handler return SQLiteHelper.Instance.Table().FirstOrDefault(it => it.locked == true); } - public static void RemoveRoutingItem(RoutingItem routingItem) + public static async Task RemoveRoutingItem(RoutingItem routingItem) { - SQLiteHelper.Instance.Delete(routingItem); + await SQLiteHelper.Instance.DeleteAsync(routingItem); } #endregion Routing #region DNS - public static int InitBuiltinDNS(Config config) + public static async Task InitBuiltinDNS(Config config) { var items = AppHandler.Instance.DNSItems(); if (items.Count <= 0) @@ -1746,20 +1747,20 @@ namespace ServiceLib.Handler remarks = "V2ray", coreType = ECoreType.Xray, }; - SaveDNSItems(config, item); + await SaveDNSItems(config, item); var item2 = new DNSItem() { remarks = "sing-box", coreType = ECoreType.sing_box, }; - SaveDNSItems(config, item2); + await SaveDNSItems(config, item2); } return 0; } - public static int SaveDNSItems(Config config, DNSItem item) + public static async Task SaveDNSItems(Config config, DNSItem item) { if (item == null) { @@ -1771,7 +1772,7 @@ namespace ServiceLib.Handler item.id = Utils.GetGuid(false); } - if (SQLiteHelper.Instance.Replace(item) > 0) + if (await SQLiteHelper.Instance.ReplaceAsync(item) > 0) { return 0; } @@ -1787,17 +1788,17 @@ namespace ServiceLib.Handler var downloadHandle = new DownloadService(); var templateContent = Task.Run(() => downloadHandle.TryDownloadString(url, true, "")).Result; - if (String.IsNullOrEmpty(templateContent)) + if (string.IsNullOrEmpty(templateContent)) return currentItem; var template = JsonUtils.Deserialize(templateContent); if (template == null) return currentItem; - if (!String.IsNullOrEmpty(template.normalDNS)) + if (!string.IsNullOrEmpty(template.normalDNS)) template.normalDNS = Task.Run(() => downloadHandle.TryDownloadString(template.normalDNS, true, "")).Result; - if (!String.IsNullOrEmpty(template.tunDNS)) + if (!string.IsNullOrEmpty(template.tunDNS)) template.tunDNS = Task.Run(() => downloadHandle.TryDownloadString(template.tunDNS, true, "")).Result; template.id = currentItem.id; @@ -1812,7 +1813,7 @@ namespace ServiceLib.Handler #region Regional Presets - public static bool ApplyRegionalPreset(Config config, EPresetType type) + public static async Task ApplyRegionalPreset(Config config, EPresetType type) { switch (type) { @@ -1821,8 +1822,8 @@ namespace ServiceLib.Handler config.constItem.srsSourceUrl = ""; config.constItem.routeRulesTemplateSourceUrl = ""; - SQLiteHelper.Instance.DeleteAll(); - InitBuiltinDNS(config); + await SQLiteHelper.Instance.DeleteAllAsync(); + await InitBuiltinDNS(config); return true; @@ -1831,8 +1832,8 @@ namespace ServiceLib.Handler config.constItem.srsSourceUrl = Global.SingboxRulesetSources[1]; config.constItem.routeRulesTemplateSourceUrl = Global.RoutingRulesSources[1]; - SaveDNSItems(config, GetExternalDNSItem(ECoreType.Xray, Global.DNSTemplateSources[1] + "v2ray.json")); - SaveDNSItems(config, GetExternalDNSItem(ECoreType.sing_box, Global.DNSTemplateSources[1] + "sing_box.json")); + await SaveDNSItems(config, GetExternalDNSItem(ECoreType.Xray, Global.DNSTemplateSources[1] + "v2ray.json")); + await SaveDNSItems(config, GetExternalDNSItem(ECoreType.sing_box, Global.DNSTemplateSources[1] + "sing_box.json")); return true; } diff --git a/v2rayN/ServiceLib/Handler/ProfileExHandler.cs b/v2rayN/ServiceLib/Handler/ProfileExHandler.cs index adc4e3d4..4cf59768 100644 --- a/v2rayN/ServiceLib/Handler/ProfileExHandler.cs +++ b/v2rayN/ServiceLib/Handler/ProfileExHandler.cs @@ -14,21 +14,20 @@ namespace ServiceLib.Handler public ProfileExHandler() { - Init(); - Task.Run(async () => { + await Init(); while (true) { - SaveQueueIndexIds(); + await SaveQueueIndexIds(); await Task.Delay(1000 * 600); } }); } - private void Init() + private async Task Init() { - SQLiteHelper.Instance.Execute($"delete from ProfileExItem where indexId not in ( select indexId from ProfileItem )"); + await SQLiteHelper.Instance.ExecuteAsync($"delete from ProfileExItem where indexId not in ( select indexId from ProfileItem )"); _lstProfileEx = new(SQLiteHelper.Instance.Table()); } @@ -41,7 +40,7 @@ namespace ServiceLib.Handler } } - private void SaveQueueIndexIds() + private async Task SaveQueueIndexIds() { var cnt = _queIndexIds.Count; if (cnt > 0) @@ -72,10 +71,10 @@ namespace ServiceLib.Handler try { if (lstInserts.Count() > 0) - SQLiteHelper.Instance.InsertAll(lstInserts); + await SQLiteHelper.Instance.InsertAllAsync(lstInserts); if (lstUpdates.Count() > 0) - SQLiteHelper.Instance.UpdateAll(lstUpdates); + await SQLiteHelper.Instance.UpdateAllAsync(lstUpdates); } catch (Exception ex) { @@ -97,17 +96,17 @@ namespace ServiceLib.Handler IndexIdEnqueue(indexId); } - public void ClearAll() + public async Task ClearAll() { - SQLiteHelper.Instance.Execute($"delete from ProfileExItem "); + await SQLiteHelper.Instance.ExecuteAsync($"delete from ProfileExItem "); _lstProfileEx = new(); } - public void SaveTo() + public async Task SaveTo() { try { - SaveQueueIndexIds(); + await SaveQueueIndexIds(); } catch (Exception ex) { diff --git a/v2rayN/ServiceLib/Handler/StatisticsHandler.cs b/v2rayN/ServiceLib/Handler/StatisticsHandler.cs index 9ce5150a..b0335e8f 100644 --- a/v2rayN/ServiceLib/Handler/StatisticsHandler.cs +++ b/v2rayN/ServiceLib/Handler/StatisticsHandler.cs @@ -25,8 +25,8 @@ InitData(); - _statisticsV2Ray = new StatisticsV2rayService(config, UpdateServerStat); - _statisticsSingbox = new StatisticsSingboxService(config, UpdateServerStat); + _statisticsV2Ray = new StatisticsV2rayService(config, UpdateServerStatHandler); + _statisticsSingbox = new StatisticsSingboxService(config, UpdateServerStatHandler); } public void Close() @@ -42,20 +42,20 @@ } } - public void ClearAllServerStatistics() + public async Task ClearAllServerStatistics() { - SQLiteHelper.Instance.Execute($"delete from ServerStatItem "); + await SQLiteHelper.Instance.ExecuteAsync($"delete from ServerStatItem "); _serverStatItem = null; _lstServerStat = new(); } - public void SaveTo() + public async Task SaveTo() { try { if (_lstServerStat != null) { - SQLiteHelper.Instance.UpdateAll(_lstServerStat); + await SQLiteHelper.Instance.UpdateAllAsync(_lstServerStat); } } catch (Exception ex) @@ -64,19 +64,24 @@ } } - private void InitData() + private async Task InitData() { - SQLiteHelper.Instance.Execute($"delete from ServerStatItem where indexId not in ( select indexId from ProfileItem )"); + await SQLiteHelper.Instance.ExecuteAsync($"delete from ServerStatItem where indexId not in ( select indexId from ProfileItem )"); long ticks = DateTime.Now.Date.Ticks; - SQLiteHelper.Instance.Execute($"update ServerStatItem set todayUp = 0,todayDown=0,dateNow={ticks} where dateNow<>{ticks}"); + await SQLiteHelper.Instance.ExecuteAsync($"update ServerStatItem set todayUp = 0,todayDown=0,dateNow={ticks} where dateNow<>{ticks}"); _lstServerStat = SQLiteHelper.Instance.Table().ToList(); } - private void UpdateServerStat(ServerSpeedItem server) + private void UpdateServerStatHandler(ServerSpeedItem server) { - GetServerStatItem(_config.indexId); + UpdateServerStat(server); + } + + private async Task UpdateServerStat(ServerSpeedItem server) + { + await GetServerStatItem(_config.indexId); if (_serverStatItem is null) { @@ -98,7 +103,7 @@ _updateFunc?.Invoke(server); } - private void GetServerStatItem(string indexId) + private async Task GetServerStatItem(string indexId) { long ticks = DateTime.Now.Date.Ticks; if (_serverStatItem != null && _serverStatItem.indexId != indexId) @@ -120,7 +125,7 @@ todayDown = 0, dateNow = ticks }; - SQLiteHelper.Instance.Replace(_serverStatItem); + await SQLiteHelper.Instance.ReplaceAsync(_serverStatItem); _lstServerStat.Add(_serverStatItem); } } diff --git a/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingWindows.cs b/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingWindows.cs index 112e759c..dbeeedb6 100644 --- a/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingWindows.cs +++ b/v2rayN/ServiceLib/Handler/SysProxy/ProxySettingWindows.cs @@ -1,7 +1,4 @@ - -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; using static ServiceLib.Handler.SysProxy.ProxySettingWindows.InternetConnectionOption; namespace ServiceLib.Handler.SysProxy diff --git a/v2rayN/ServiceLib/Handler/TaskHandler.cs b/v2rayN/ServiceLib/Handler/TaskHandler.cs index a75470c2..b75426ef 100644 --- a/v2rayN/ServiceLib/Handler/TaskHandler.cs +++ b/v2rayN/ServiceLib/Handler/TaskHandler.cs @@ -31,14 +31,14 @@ foreach (var item in lstSubs) { - updateHandle.UpdateSubscriptionProcess(config, item.id, true, (bool success, string msg) => - { - updateFunc?.Invoke(success, msg); - if (success) - Logging.SaveLog("subscription" + msg); - }); + await updateHandle.UpdateSubscriptionProcess(config, item.id, true, (bool success, string msg) => + { + updateFunc?.Invoke(success, msg); + if (success) + Logging.SaveLog("subscription" + msg); + }); item.updateTime = updateTime; - ConfigHandler.AddSubItem(config, item); + await ConfigHandler.AddSubItem(config, item); await Task.Delay(5000); } diff --git a/v2rayN/ServiceLib/Models/RoutingTemplate.cs b/v2rayN/ServiceLib/Models/RoutingTemplate.cs index 1eb9c1d0..3c0a4e59 100644 --- a/v2rayN/ServiceLib/Models/RoutingTemplate.cs +++ b/v2rayN/ServiceLib/Models/RoutingTemplate.cs @@ -6,4 +6,4 @@ public string version { get; set; } public RoutingItem[] routingItems { get; set; } } -} +} \ No newline at end of file diff --git a/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigSingboxService.cs b/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigSingboxService.cs index b0fbf800..7b978794 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigSingboxService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigSingboxService.cs @@ -468,7 +468,7 @@ namespace ServiceLib.Services.CoreConfig return 0; } - private int GenInbounds(SingboxConfig singboxConfig) + private async Task GenInbounds(SingboxConfig singboxConfig) { try { @@ -493,7 +493,7 @@ namespace ServiceLib.Services.CoreConfig if (_config.routingBasicItem.enableRoutingAdvanced) { - var routing = ConfigHandler.GetDefaultRouting(_config); + var routing = await ConfigHandler.GetDefaultRouting(_config); if (Utils.IsNotEmpty(routing.domainStrategy4Singbox)) { inbound.domain_strategy = routing.domainStrategy4Singbox; @@ -899,7 +899,7 @@ namespace ServiceLib.Services.CoreConfig return 0; } - private int GenRouting(SingboxConfig singboxConfig) + private async Task GenRouting(SingboxConfig singboxConfig) { try { @@ -952,7 +952,7 @@ namespace ServiceLib.Services.CoreConfig if (_config.routingBasicItem.enableRoutingAdvanced) { - var routing = ConfigHandler.GetDefaultRouting(_config); + var routing = await ConfigHandler.GetDefaultRouting(_config); if (routing != null) { var rules = JsonUtils.Deserialize>(routing.ruleSet); @@ -1276,7 +1276,7 @@ namespace ServiceLib.Services.CoreConfig return 0; } - private int ConvertGeo2Ruleset(SingboxConfig singboxConfig) + private async Task ConvertGeo2Ruleset(SingboxConfig singboxConfig) { static void AddRuleSets(List ruleSets, List? rule_set) { @@ -1328,7 +1328,7 @@ namespace ServiceLib.Services.CoreConfig List customRulesets = []; if (_config.routingBasicItem.enableRoutingAdvanced) { - var routing = ConfigHandler.GetDefaultRouting(_config); + var routing = await ConfigHandler.GetDefaultRouting(_config); if (Utils.IsNotEmpty(routing.customRulesetPath4Singbox)) { var result = Utils.LoadResource(routing.customRulesetPath4Singbox); diff --git a/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigV2rayService.cs b/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigV2rayService.cs index 97d951be..b32e8ed0 100644 --- a/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigV2rayService.cs +++ b/v2rayN/ServiceLib/Services/CoreConfig/CoreConfigV2rayService.cs @@ -444,7 +444,7 @@ namespace ServiceLib.Services.CoreConfig return inbound; } - private int GenRouting(V2rayConfig v2rayConfig) + private async Task GenRouting(V2rayConfig v2rayConfig) { try { @@ -455,7 +455,7 @@ namespace ServiceLib.Services.CoreConfig if (_config.routingBasicItem.enableRoutingAdvanced) { - var routing = ConfigHandler.GetDefaultRouting(_config); + var routing = await ConfigHandler.GetDefaultRouting(_config); if (routing != null) { if (Utils.IsNotEmpty(routing.domainStrategy)) diff --git a/v2rayN/ServiceLib/Services/SpeedtestService.cs b/v2rayN/ServiceLib/Services/SpeedtestService.cs index 588e2eef..52330266 100644 --- a/v2rayN/ServiceLib/Services/SpeedtestService.cs +++ b/v2rayN/ServiceLib/Services/SpeedtestService.cs @@ -88,7 +88,7 @@ namespace ServiceLib.Services UpdateFunc("", ResUI.SpeedtestingStop); } - private Task RunTcping() + private async Task RunTcping() { try { @@ -123,13 +123,11 @@ namespace ServiceLib.Services } finally { - ProfileExHandler.Instance.SaveTo(); + await ProfileExHandler.Instance.SaveTo(); } - - return Task.CompletedTask; } - private Task RunRealPing() + private async Task RunRealPing() { int pid = -1; try @@ -140,7 +138,7 @@ namespace ServiceLib.Services if (pid < 0) { UpdateFunc("", ResUI.FailedToRunCore); - return Task.CompletedTask; + return; } DownloadService downloadHandle = new DownloadService(); @@ -186,10 +184,8 @@ namespace ServiceLib.Services { CoreHandler.Instance.CoreStopPid(pid); } - ProfileExHandler.Instance.SaveTo(); + await ProfileExHandler.Instance.SaveTo(); } - - return Task.CompletedTask; } private async Task RunSpeedTestAsync() @@ -321,7 +317,7 @@ namespace ServiceLib.Services CoreHandler.Instance.CoreStopPid(pid); } UpdateFunc("", ResUI.SpeedtestingCompleted); - ProfileExHandler.Instance.SaveTo(); + await ProfileExHandler.Instance.SaveTo(); } private async Task RunMixedtestAsync() diff --git a/v2rayN/ServiceLib/Services/UpdateService.cs b/v2rayN/ServiceLib/Services/UpdateService.cs index 4303d1fc..d4f1e6f0 100644 --- a/v2rayN/ServiceLib/Services/UpdateService.cs +++ b/v2rayN/ServiceLib/Services/UpdateService.cs @@ -120,7 +120,7 @@ namespace ServiceLib.Services } } - public void UpdateSubscriptionProcess(Config config, string subId, bool blProxy, Action updateFunc) + public async Task UpdateSubscriptionProcess(Config config, string subId, bool blProxy, Action updateFunc) { _config = config; _updateFunc = updateFunc; @@ -134,123 +134,120 @@ namespace ServiceLib.Services return; } - Task.Run(async () => + foreach (var item in subItem) { - foreach (var item in subItem) + string id = item.id.TrimEx(); + string url = item.url.TrimEx(); + string userAgent = item.userAgent.TrimEx(); + string hashCode = $"{item.remarks}->"; + if (Utils.IsNullOrEmpty(id) || Utils.IsNullOrEmpty(url) || Utils.IsNotEmpty(subId) && item.id != subId) { - string id = item.id.TrimEx(); - string url = item.url.TrimEx(); - string userAgent = item.userAgent.TrimEx(); - string hashCode = $"{item.remarks}->"; - if (Utils.IsNullOrEmpty(id) || Utils.IsNullOrEmpty(url) || Utils.IsNotEmpty(subId) && item.id != subId) - { - //_updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgNoValidSubscription}"); - continue; - } - if (!url.StartsWith(Global.HttpsProtocol) && !url.StartsWith(Global.HttpProtocol)) - { - continue; - } - if (item.enabled == false) - { - _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgSkipSubscriptionUpdate}"); - continue; - } - - var downloadHandle = new DownloadService(); - downloadHandle.Error += (sender2, args) => - { - _updateFunc?.Invoke(false, $"{hashCode}{args.GetException().Message}"); - }; - - _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgStartGettingSubscriptions}"); - - //one url - url = Utils.GetPunycode(url); - //convert - if (Utils.IsNotEmpty(item.convertTarget)) - { - var subConvertUrl = Utils.IsNullOrEmpty(config.constItem.subConvertUrl) ? Global.SubConvertUrls.FirstOrDefault() : config.constItem.subConvertUrl; - url = string.Format(subConvertUrl!, Utils.UrlEncode(url)); - if (!url.Contains("target=")) - { - url += string.Format("&target={0}", item.convertTarget); - } - if (!url.Contains("config=")) - { - url += string.Format("&config={0}", Global.SubConvertConfig.FirstOrDefault()); - } - } - var result = await downloadHandle.TryDownloadString(url, blProxy, userAgent); - if (blProxy && Utils.IsNullOrEmpty(result)) - { - result = await downloadHandle.TryDownloadString(url, false, userAgent); - } - - //more url - if (Utils.IsNullOrEmpty(item.convertTarget) && Utils.IsNotEmpty(item.moreUrl.TrimEx())) - { - if (Utils.IsNotEmpty(result) && Utils.IsBase64String(result)) - { - result = Utils.Base64Decode(result); - } - - var lstUrl = item.moreUrl.TrimEx().Split(",") ?? []; - foreach (var it in lstUrl) - { - var url2 = Utils.GetPunycode(it); - if (Utils.IsNullOrEmpty(url2)) - { - continue; - } - - var result2 = await downloadHandle.TryDownloadString(url2, blProxy, userAgent); - if (blProxy && Utils.IsNullOrEmpty(result2)) - { - result2 = await downloadHandle.TryDownloadString(url2, false, userAgent); - } - if (Utils.IsNotEmpty(result2)) - { - if (Utils.IsBase64String(result2)) - { - result += Utils.Base64Decode(result2); - } - else - { - result += result2; - } - } - } - } - - if (Utils.IsNullOrEmpty(result)) - { - _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgSubscriptionDecodingFailed}"); - } - else - { - _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgGetSubscriptionSuccessfully}"); - if (result?.Length < 99) - { - _updateFunc?.Invoke(false, $"{hashCode}{result}"); - } - - int ret = ConfigHandler.AddBatchServers(config, result, id, true); - if (ret <= 0) - { - Logging.SaveLog("FailedImportSubscription"); - Logging.SaveLog(result); - } - _updateFunc?.Invoke(false, - ret > 0 - ? $"{hashCode}{ResUI.MsgUpdateSubscriptionEnd}" - : $"{hashCode}{ResUI.MsgFailedImportSubscription}"); - } - _updateFunc?.Invoke(false, "-------------------------------------------------------"); + //_updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgNoValidSubscription}"); + continue; + } + if (!url.StartsWith(Global.HttpsProtocol) && !url.StartsWith(Global.HttpProtocol)) + { + continue; + } + if (item.enabled == false) + { + _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgSkipSubscriptionUpdate}"); + continue; } - _updateFunc?.Invoke(true, $"{ResUI.MsgUpdateSubscriptionEnd}"); - }); + var downloadHandle = new DownloadService(); + downloadHandle.Error += (sender2, args) => + { + _updateFunc?.Invoke(false, $"{hashCode}{args.GetException().Message}"); + }; + + _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgStartGettingSubscriptions}"); + + //one url + url = Utils.GetPunycode(url); + //convert + if (Utils.IsNotEmpty(item.convertTarget)) + { + var subConvertUrl = Utils.IsNullOrEmpty(config.constItem.subConvertUrl) ? Global.SubConvertUrls.FirstOrDefault() : config.constItem.subConvertUrl; + url = string.Format(subConvertUrl!, Utils.UrlEncode(url)); + if (!url.Contains("target=")) + { + url += string.Format("&target={0}", item.convertTarget); + } + if (!url.Contains("config=")) + { + url += string.Format("&config={0}", Global.SubConvertConfig.FirstOrDefault()); + } + } + var result = await downloadHandle.TryDownloadString(url, blProxy, userAgent); + if (blProxy && Utils.IsNullOrEmpty(result)) + { + result = await downloadHandle.TryDownloadString(url, false, userAgent); + } + + //more url + if (Utils.IsNullOrEmpty(item.convertTarget) && Utils.IsNotEmpty(item.moreUrl.TrimEx())) + { + if (Utils.IsNotEmpty(result) && Utils.IsBase64String(result)) + { + result = Utils.Base64Decode(result); + } + + var lstUrl = item.moreUrl.TrimEx().Split(",") ?? []; + foreach (var it in lstUrl) + { + var url2 = Utils.GetPunycode(it); + if (Utils.IsNullOrEmpty(url2)) + { + continue; + } + + var result2 = await downloadHandle.TryDownloadString(url2, blProxy, userAgent); + if (blProxy && Utils.IsNullOrEmpty(result2)) + { + result2 = await downloadHandle.TryDownloadString(url2, false, userAgent); + } + if (Utils.IsNotEmpty(result2)) + { + if (Utils.IsBase64String(result2)) + { + result += Utils.Base64Decode(result2); + } + else + { + result += result2; + } + } + } + } + + if (Utils.IsNullOrEmpty(result)) + { + _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgSubscriptionDecodingFailed}"); + } + else + { + _updateFunc?.Invoke(false, $"{hashCode}{ResUI.MsgGetSubscriptionSuccessfully}"); + if (result?.Length < 99) + { + _updateFunc?.Invoke(false, $"{hashCode}{result}"); + } + + int ret = await ConfigHandler.AddBatchServers(config, result, id, true); + if (ret <= 0) + { + Logging.SaveLog("FailedImportSubscription"); + Logging.SaveLog(result); + } + _updateFunc?.Invoke(false, + ret > 0 + ? $"{hashCode}{ResUI.MsgUpdateSubscriptionEnd}" + : $"{hashCode}{ResUI.MsgFailedImportSubscription}"); + } + _updateFunc?.Invoke(false, "-------------------------------------------------------"); + } + + _updateFunc?.Invoke(true, $"{ResUI.MsgUpdateSubscriptionEnd}"); } public async Task UpdateGeoFileAll(Config config, Action updateFunc) @@ -498,15 +495,15 @@ namespace ServiceLib.Services } } - foreach(var item in geoipFiles.Distinct()) + foreach (var item in geoipFiles.Distinct()) { await UpdateSrsFile("geoip", item, config, updateFunc); } - foreach(var item in geoSiteFiles.Distinct()) + foreach (var item in geoSiteFiles.Distinct()) { await UpdateSrsFile("geosite", item, config, updateFunc); - } + } } private async Task UpdateSrsFile(string type, string srsName, Config config, Action updateFunc) diff --git a/v2rayN/ServiceLib/ViewModels/AddServer2ViewModel.cs b/v2rayN/ServiceLib/ViewModels/AddServer2ViewModel.cs index f781492d..30a336d8 100644 --- a/v2rayN/ServiceLib/ViewModels/AddServer2ViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/AddServer2ViewModel.cs @@ -64,7 +64,7 @@ namespace ServiceLib.ViewModels } SelectedSource.coreType = CoreType.IsNullOrEmpty() ? null : (ECoreType)Enum.Parse(typeof(ECoreType), CoreType); - if (ConfigHandler.EditCustomServer(_config, SelectedSource) == 0) + if (await ConfigHandler.EditCustomServer(_config, SelectedSource) == 0) { NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); _updateView?.Invoke(EViewAction.CloseWindow, null); @@ -75,7 +75,7 @@ namespace ServiceLib.ViewModels } } - public void BrowseServer(string fileName) + public async Task BrowseServer(string fileName) { if (Utils.IsNullOrEmpty(fileName)) { @@ -85,7 +85,7 @@ namespace ServiceLib.ViewModels var item = AppHandler.Instance.GetProfileItem(SelectedSource.indexId); item ??= SelectedSource; item.address = fileName; - if (ConfigHandler.AddCustomServer(_config, item, false) == 0) + if (await ConfigHandler.AddCustomServer(_config, item, false) == 0) { NoticeHandler.Instance.Enqueue(ResUI.SuccessfullyImportedCustomServer); if (Utils.IsNotEmpty(item.indexId)) diff --git a/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs b/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs index 5769d821..5bff42fe 100644 --- a/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/AddServerViewModel.cs @@ -84,7 +84,7 @@ namespace ServiceLib.ViewModels } SelectedSource.coreType = CoreType.IsNullOrEmpty() ? null : (ECoreType)Enum.Parse(typeof(ECoreType), CoreType); - if (ConfigHandler.AddServer(_config, SelectedSource) == 0) + if (await ConfigHandler.AddServer(_config, SelectedSource) == 0) { NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); _updateView?.Invoke(EViewAction.CloseWindow, null); diff --git a/v2rayN/ServiceLib/ViewModels/BackupAndRestoreViewModel.cs b/v2rayN/ServiceLib/ViewModels/BackupAndRestoreViewModel.cs index 7deececd..2712cb3d 100644 --- a/v2rayN/ServiceLib/ViewModels/BackupAndRestoreViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/BackupAndRestoreViewModel.cs @@ -51,7 +51,7 @@ namespace ServiceLib.ViewModels { DisplayOperationMsg(); _config.webDavItem = SelectedSource; - ConfigHandler.SaveConfig(_config); + await ConfigHandler.SaveConfig(_config); var result = await WebDavHandler.Instance.CheckConnection(); if (result) diff --git a/v2rayN/ServiceLib/ViewModels/ClashConnectionsViewModel.cs b/v2rayN/ServiceLib/ViewModels/ClashConnectionsViewModel.cs index a5f6a250..325871f5 100644 --- a/v2rayN/ServiceLib/ViewModels/ClashConnectionsViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/ClashConnectionsViewModel.cs @@ -100,17 +100,15 @@ namespace ServiceLib.ViewModels }); } - private void GetClashConnections() + private async Task GetClashConnections() { - ClashApiHandler.Instance.GetClashConnections(_config, async (it) => + var ret = await ClashApiHandler.Instance.GetClashConnectionsAsync(_config); + if (ret == null) { - if (it == null) - { - return; - } + return; + } - _updateView?.Invoke(EViewAction.DispatcherRefreshConnections, it?.connections); - }); + _updateView?.Invoke(EViewAction.DispatcherRefreshConnections, ret?.connections); } public void RefreshConnections(List? connections) @@ -140,7 +138,7 @@ namespace ServiceLib.ViewModels model.uploadTraffic = $"{Utils.HumanFy((long)item.upload)}"; model.downloadTraffic = $"{Utils.HumanFy((long)item.download)}"; model.elapsed = sp.ToString(@"hh\:mm\:ss"); - model.chain = item.chains?.Count > 0 ? item.chains[0] : String.Empty; + model.chain = item.chains?.Count > 0 ? item.chains[0] : string.Empty; lstModel.Add(model); } @@ -193,8 +191,8 @@ namespace ServiceLib.ViewModels { _connectionItems.Clear(); } - ClashApiHandler.Instance.ClashConnectionClose(id); - GetClashConnections(); + await ClashApiHandler.Instance.ClashConnectionClose(id); + await GetClashConnections(); } } } \ No newline at end of file diff --git a/v2rayN/ServiceLib/ViewModels/ClashProxiesViewModel.cs b/v2rayN/ServiceLib/ViewModels/ClashProxiesViewModel.cs index f19e7b77..74e51257 100644 --- a/v2rayN/ServiceLib/ViewModels/ClashProxiesViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/ClashProxiesViewModel.cs @@ -138,18 +138,18 @@ namespace ServiceLib.ViewModels public async Task ProxiesReload() { - GetClashProxies(true); - ProxiesDelayTest(); + await GetClashProxies(true); + await ProxiesDelayTest(); } public async Task ProxiesDelayTest() { - ProxiesDelayTest(true); + await ProxiesDelayTest(true); } #region proxy function - private void SetRuleMode(ERuleMode mode) + private async Task SetRuleMode(ERuleMode mode) { _config.clashUIItem.ruleMode = mode; @@ -159,27 +159,24 @@ namespace ServiceLib.ViewModels { { "mode", mode.ToString().ToLower() } }; - ClashApiHandler.Instance.ClashConfigUpdate(headers); + await ClashApiHandler.Instance.ClashConfigUpdate(headers); } } - private void GetClashProxies(bool refreshUI) + private async Task GetClashProxies(bool refreshUI) { - ClashApiHandler.Instance.GetClashProxies(_config, async (it, it2) => + var ret = await ClashApiHandler.Instance.GetClashProxiesAsync(_config); + if (ret?.Item1 == null || ret.Item2 == null) { - //UpdateHandler(false, "Refresh Clash Proxies"); - _proxies = it?.proxies; - _providers = it2?.providers; + return; + } + _proxies = ret.Item1.proxies; + _providers = ret?.Item2.providers; - if (_proxies == null) - { - return; - } - if (refreshUI) - { - _updateView?.Invoke(EViewAction.DispatcherRefreshProxyGroups, null); - } - }); + if (refreshUI) + { + _updateView?.Invoke(EViewAction.DispatcherRefreshProxyGroups, null); + } } public void RefreshProxyGroups() @@ -365,7 +362,7 @@ namespace ServiceLib.ViewModels return; } - ClashApiHandler.Instance.ClashSetActiveProxy(name, nameNode); + await ClashApiHandler.Instance.ClashSetActiveProxy(name, nameNode); selectedProxy.now = nameNode; var group = _proxyGroups.Where(it => it.name == SelectedGroup.name).FirstOrDefault(); @@ -420,7 +417,7 @@ namespace ServiceLib.ViewModels else { detail.delay = _delayTimeout; - detail.delayName = String.Empty; + detail.delayName = string.Empty; } _proxyDetails.Replace(detail, JsonUtils.DeepCopy(detail)); } @@ -435,7 +432,7 @@ namespace ServiceLib.ViewModels var lastTime = DateTime.Now; Observable.Interval(TimeSpan.FromSeconds(60)) - .Subscribe(x => + .Subscribe(async x => { if (!(AutoRefresh && _config.uiItem.showInTaskbar && _config.IsRunningCore(ECoreType.sing_box))) { @@ -446,7 +443,7 @@ namespace ServiceLib.ViewModels { if ((dtNow - lastTime).Minutes % _config.clashUIItem.proxiesAutoDelayTestInterval == 0) { - ProxiesDelayTest(); + await ProxiesDelayTest(); lastTime = dtNow; } Task.Delay(1000).Wait(); diff --git a/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs b/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs index 68c75d17..016297e6 100644 --- a/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs @@ -286,8 +286,8 @@ namespace ServiceLib.ViewModels await SysProxyHandler.UpdateSysProxy(_config, true); ConfigHandler.SaveConfig(_config); - ProfileExHandler.Instance.SaveTo(); - StatisticsHandler.Instance.SaveTo(); + await ProfileExHandler.Instance.SaveTo(); + await StatisticsHandler.Instance.SaveTo(); StatisticsHandler.Instance.Close(); CoreHandler.Instance.CoreStop(); @@ -383,7 +383,7 @@ namespace ServiceLib.ViewModels await _updateView?.Invoke(EViewAction.AddServerViaClipboard, null); return; } - int ret = ConfigHandler.AddBatchServers(_config, clipboardData, _config.subIndexId, false); + int ret = await ConfigHandler.AddBatchServers(_config, clipboardData, _config.subIndexId, false); if (ret > 0) { RefreshSubscriptions(); @@ -427,7 +427,7 @@ namespace ServiceLib.ViewModels } else { - int ret = ConfigHandler.AddBatchServers(_config, result, _config.subIndexId, false); + int ret = await ConfigHandler.AddBatchServers(_config, result, _config.subIndexId, false); if (ret > 0) { RefreshSubscriptions(); @@ -451,7 +451,7 @@ namespace ServiceLib.ViewModels public async Task UpdateSubscriptionProcess(string subId, bool blProxy) { - (new UpdateService()).UpdateSubscriptionProcess(_config, subId, blProxy, UpdateTaskHandler); + await (new UpdateService()).UpdateSubscriptionProcess(_config, subId, blProxy, UpdateTaskHandler); } #endregion Subscription @@ -552,7 +552,7 @@ namespace ServiceLib.ViewModels private async Task LoadCore() { - await Task.Run(() => + await Task.Run(async () => { //if (_config.tunModeItem.enableTun) //{ @@ -560,7 +560,7 @@ namespace ServiceLib.ViewModels // WindowsUtils.RemoveTunDevice(); //} - var node = ConfigHandler.GetDefaultServer(_config); + var node = await ConfigHandler.GetDefaultServer(_config); CoreHandler.Instance.LoadCore(node); }); } @@ -590,7 +590,7 @@ namespace ServiceLib.ViewModels public async Task ApplyRegionalPreset(EPresetType type) { - ConfigHandler.ApplyRegionalPreset(_config, type); + await ConfigHandler.ApplyRegionalPreset(_config, type); ConfigHandler.InitRouting(_config); Locator.Current.GetService()?.RefreshRoutingsMenu(); diff --git a/v2rayN/ServiceLib/ViewModels/OptionSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/OptionSettingViewModel.cs index 7b0d200d..d00d797d 100644 --- a/v2rayN/ServiceLib/ViewModels/OptionSettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/OptionSettingViewModel.cs @@ -341,7 +341,7 @@ namespace ServiceLib.ViewModels //coreType SaveCoreType(); - if (ConfigHandler.SaveConfig(_config) == 0) + if (await ConfigHandler.SaveConfig(_config) == 0) { if (needReboot) { diff --git a/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs b/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs index ce9c899c..e3d7a2af 100644 --- a/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/ProfilesViewModel.cs @@ -479,7 +479,7 @@ namespace ServiceLib.ViewModels private async Task RemoveDuplicateServer() { - var tuple = ConfigHandler.DedupServerList(_config, _config.subIndexId); + var tuple = await ConfigHandler.DedupServerList(_config, _config.subIndexId); RefreshServers(); Reload(); NoticeHandler.Instance.Enqueue(string.Format(ResUI.RemoveDuplicateServerResult, tuple.Item1, tuple.Item2)); @@ -491,7 +491,7 @@ namespace ServiceLib.ViewModels { return; } - if (ConfigHandler.CopyServer(_config, lstSelecteds) == 0) + if (await ConfigHandler.CopyServer(_config, lstSelecteds) == 0) { RefreshServers(); NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); @@ -524,7 +524,7 @@ namespace ServiceLib.ViewModels return; } - if (ConfigHandler.SetDefaultServerIndex(_config, indexId) == 0) + if (await ConfigHandler.SetDefaultServerIndex(_config, indexId) == 0) { RefreshServers(); Reload(); @@ -572,19 +572,20 @@ namespace ServiceLib.ViewModels return; } - if (ConfigHandler.AddCustomServer4Multiple(_config, lstSelecteds, coreType, out string indexId) != 0) + var ret = await ConfigHandler.AddCustomServer4Multiple(_config, lstSelecteds, coreType); + if (ret.Item1 != 0) { NoticeHandler.Instance.Enqueue(ResUI.OperationFailed); return; } - if (indexId == _config.indexId) + if (ret.Item2 == _config.indexId) { RefreshServers(); Reload(); } else { - await SetDefaultServer(indexId); + await SetDefaultServer(ret.Item2); } } @@ -597,7 +598,7 @@ namespace ServiceLib.ViewModels _dicHeaderSort.TryAdd(colName, true); _dicHeaderSort.TryGetValue(colName, out bool asc); - if (ConfigHandler.SortServers(_config, _config.subIndexId, colName, asc) != 0) + if (await ConfigHandler.SortServers(_config, _config.subIndexId, colName, asc) != 0) { return; } @@ -640,18 +641,18 @@ namespace ServiceLib.ViewModels { return; } - if (ConfigHandler.MoveServer(_config, ref _lstProfile, index, eMove) == 0) + if (await ConfigHandler.MoveServer(_config, _lstProfile, index, eMove) == 0) { RefreshServers(); } } - public void MoveServerTo(int startIndex, ProfileItemModel targetItem) + public async Task MoveServerTo(int startIndex, ProfileItemModel targetItem) { var targetIndex = _profileItems.IndexOf(targetItem); if (startIndex >= 0 && targetIndex >= 0 && startIndex != targetIndex) { - if (ConfigHandler.MoveServer(_config, ref _lstProfile, startIndex, EMove.Position, targetIndex) == 0) + if (await ConfigHandler.MoveServer(_config, _lstProfile, startIndex, EMove.Position, targetIndex) == 0) { RefreshServers(); } diff --git a/v2rayN/ServiceLib/ViewModels/RoutingRuleSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/RoutingRuleSettingViewModel.cs index 57692d9c..5e22091c 100644 --- a/v2rayN/ServiceLib/ViewModels/RoutingRuleSettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/RoutingRuleSettingViewModel.cs @@ -215,7 +215,7 @@ namespace ServiceLib.ViewModels return; } var index = _rules.IndexOf(item); - if (ConfigHandler.MoveRoutingRule(_rules, index, eMove) == 0) + if (await ConfigHandler.MoveRoutingRule(_rules, index, eMove) == 0) { RefreshRulesItems(); } @@ -237,7 +237,7 @@ namespace ServiceLib.ViewModels item.ruleNum = _rules.Count; item.ruleSet = JsonUtils.Serialize(_rules, false); - if (ConfigHandler.SaveRoutingItem(_config, item) == 0) + if (await ConfigHandler.SaveRoutingItem(_config, item) == 0) { NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); _updateView?.Invoke(EViewAction.CloseWindow, null); diff --git a/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs b/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs index a4c4092b..1bee71c8 100644 --- a/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/RoutingSettingViewModel.cs @@ -120,7 +120,7 @@ namespace ServiceLib.ViewModels #region locked - private void BindingLockedData() + private async Task BindingLockedData() { _lockedItem = ConfigHandler.GetLockedRoutingItem(_config); if (_lockedItem == null) @@ -131,7 +131,7 @@ namespace ServiceLib.ViewModels url = string.Empty, locked = true, }; - ConfigHandler.AddBatchRoutingRules(ref _lockedItem, Utils.GetEmbedText(Global.CustomRoutingFileName + "locked")); + await ConfigHandler.AddBatchRoutingRules(_lockedItem, Utils.GetEmbedText(Global.CustomRoutingFileName + "locked")); } if (_lockedItem != null) @@ -208,7 +208,7 @@ namespace ServiceLib.ViewModels EndBindingLockedData(); - if (ConfigHandler.SaveConfig(_config) == 0) + if (await ConfigHandler.SaveConfig(_config) == 0) { NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); _updateView?.Invoke(EViewAction.CloseWindow, null); @@ -288,7 +288,7 @@ namespace ServiceLib.ViewModels return; } - if (ConfigHandler.SetDefaultRouting(_config, item) == 0) + if (await ConfigHandler.SetDefaultRouting(_config, item) == 0) { RefreshRoutingItems(); IsModified = true; @@ -297,7 +297,7 @@ namespace ServiceLib.ViewModels private async Task RoutingAdvancedImportRules() { - if (ConfigHandler.InitRouting(_config, true) == 0) + if (await ConfigHandler.InitRouting(_config, true) == 0) { RefreshRoutingItems(); IsModified = true; diff --git a/v2rayN/ServiceLib/ViewModels/StatusBarViewModel.cs b/v2rayN/ServiceLib/ViewModels/StatusBarViewModel.cs index 74701048..011e7bcf 100644 --- a/v2rayN/ServiceLib/ViewModels/StatusBarViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/StatusBarViewModel.cs @@ -220,12 +220,12 @@ namespace ServiceLib.ViewModels if (service != null) await service.UpdateSubscriptionProcess("", blProxy); } - public void RefreshServersBiz() + public async Task RefreshServersBiz() { RefreshServersMenu(); //display running server - var running = ConfigHandler.GetDefaultServer(_config); + var running = await ConfigHandler.GetDefaultServer(_config); if (running != null) { RunningServerDisplay = @@ -283,7 +283,7 @@ namespace ServiceLib.ViewModels public async Task TestServerAvailability() { - var item = ConfigHandler.GetDefaultServer(_config); + var item = await ConfigHandler.GetDefaultServer(_config); if (item == null) { return; @@ -379,7 +379,7 @@ namespace ServiceLib.ViewModels return; } - if (ConfigHandler.SetDefaultRouting(_config, item) == 0) + if (await ConfigHandler.SetDefaultRouting(_config, item) == 0) { NoticeHandler.Instance.SendMessageEx(ResUI.TipChangeRouting); Locator.Current.GetService()?.Reload(); diff --git a/v2rayN/ServiceLib/ViewModels/SubEditViewModel.cs b/v2rayN/ServiceLib/ViewModels/SubEditViewModel.cs index 494e43d7..d58dd257 100644 --- a/v2rayN/ServiceLib/ViewModels/SubEditViewModel.cs +++ b/v2rayN/ServiceLib/ViewModels/SubEditViewModel.cs @@ -41,7 +41,7 @@ namespace ServiceLib.ViewModels return; } - if (ConfigHandler.AddSubItem(_config, SelectedSource) == 0) + if (await ConfigHandler.AddSubItem(_config, SelectedSource) == 0) { NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); _updateView?.Invoke(EViewAction.CloseWindow, null); diff --git a/v2rayN/v2rayN/Handler/WindowsHandler.cs b/v2rayN/v2rayN/Handler/WindowsHandler.cs index 736b8892..df2f2661 100644 --- a/v2rayN/v2rayN/Handler/WindowsHandler.cs +++ b/v2rayN/v2rayN/Handler/WindowsHandler.cs @@ -9,14 +9,14 @@ namespace v2rayN.Handler private static readonly Lazy instance = new(() => new()); public static WindowsHandler Instance => instance.Value; - public Icon GetNotifyIcon(Config config) + public async Task GetNotifyIcon(Config config) { try { int index = (int)config.systemProxyItem.sysProxyType; //Load from routing setting - var createdIcon = GetNotifyIcon4Routing(config); + var createdIcon = await GetNotifyIcon4Routing(config); if (createdIcon != null) { return createdIcon; @@ -65,7 +65,7 @@ namespace v2rayN.Handler return BitmapFrame.Create(new Uri($"pack://application:,,,/Resources/NotifyIcon{index}.ico", UriKind.RelativeOrAbsolute)); } - private Icon? GetNotifyIcon4Routing(Config config) + private async Task GetNotifyIcon4Routing(Config config) { try { @@ -74,7 +74,7 @@ namespace v2rayN.Handler return null; } - var item = ConfigHandler.GetDefaultRouting(config); + var item = await ConfigHandler.GetDefaultRouting(config); if (item == null || Utils.IsNullOrEmpty(item.customIcon) || !File.Exists(item.customIcon)) { return null; diff --git a/v2rayN/v2rayN/Views/GlobalHotkeySettingWindow.xaml.cs b/v2rayN/v2rayN/Views/GlobalHotkeySettingWindow.xaml.cs index cb168658..487edd0b 100644 --- a/v2rayN/v2rayN/Views/GlobalHotkeySettingWindow.xaml.cs +++ b/v2rayN/v2rayN/Views/GlobalHotkeySettingWindow.xaml.cs @@ -103,7 +103,7 @@ namespace v2rayN.Views { _config.globalHotkeys = _TextBoxKeyEventItem.Values.ToList(); - if (ConfigHandler.SaveConfig(_config, false) == 0) + if ( ConfigHandler.SaveConfig(_config, false).Result == 0) { HotkeyHandler.Instance.ReLoad(); this.DialogResult = true; diff --git a/v2rayN/v2rayN/Views/StatusBarView.xaml.cs b/v2rayN/v2rayN/Views/StatusBarView.xaml.cs index ea53a556..d1234ff7 100644 --- a/v2rayN/v2rayN/Views/StatusBarView.xaml.cs +++ b/v2rayN/v2rayN/Views/StatusBarView.xaml.cs @@ -90,9 +90,9 @@ namespace v2rayN.Views break; case EViewAction.DispatcherRefreshIcon: - Application.Current?.Dispatcher.Invoke((() => + Application.Current?.Dispatcher.Invoke((async () => { - tbNotify.Icon = WindowsHandler.Instance.GetNotifyIcon(_config); + tbNotify.Icon = await WindowsHandler.Instance.GetNotifyIcon(_config); Application.Current.MainWindow.Icon = WindowsHandler.Instance.GetAppIcon(_config); }), DispatcherPriority.Normal); break;