Code optimization, function asynchrony

This commit is contained in:
2dust 2024-10-20 11:51:05 +08:00
parent 50449df08d
commit 394b657fc9
29 changed files with 467 additions and 526 deletions

View file

@ -10,7 +10,6 @@ namespace ServiceLib.Common
private string _connstr; private string _connstr;
private SQLiteConnection _db; private SQLiteConnection _db;
private SQLiteAsyncConnection _dbAsync; private SQLiteAsyncConnection _dbAsync;
private static readonly object objLock = new();
private readonly string _configDB = "guiNDB.db"; private readonly string _configDB = "guiNDB.db";
public SQLiteHelper() public SQLiteHelper()
@ -25,17 +24,9 @@ namespace ServiceLib.Common
return _db.CreateTable<T>(); return _db.CreateTable<T>();
} }
public int Insert(object model) public async Task<int> InsertAllAsync(IEnumerable models)
{ {
return _db.Insert(model); return await _dbAsync.InsertAllAsync(models);
}
public int InsertAll(IEnumerable models)
{
lock (objLock)
{
return _db.InsertAll(models);
}
} }
public async Task<int> InsertAsync(object model) public async Task<int> InsertAsync(object model)
@ -43,46 +34,19 @@ namespace ServiceLib.Common
return await _dbAsync.InsertAsync(model); return await _dbAsync.InsertAsync(model);
} }
public int Replace(object model)
{
lock (objLock)
{
return _db.InsertOrReplace(model);
}
}
public async Task<int> ReplaceAsync(object model) public async Task<int> ReplaceAsync(object model)
{ {
return await _dbAsync.InsertOrReplaceAsync(model); return await _dbAsync.InsertOrReplaceAsync(model);
} }
public int Update(object model)
{
lock (objLock)
{
return _db.Update(model);
}
}
public async Task<int> UpdateAsync(object model) public async Task<int> UpdateAsync(object model)
{ {
return await _dbAsync.UpdateAsync(model); return await _dbAsync.UpdateAsync(model);
} }
public int UpdateAll(IEnumerable models) public async Task<int> UpdateAllAsync(IEnumerable models)
{ {
lock (objLock) return await _dbAsync.UpdateAllAsync(models);
{
return _db.UpdateAll(models);
}
}
public int Delete(object model)
{
lock (objLock)
{
return _db.Delete(model);
}
} }
public async Task<int> DeleteAsync(object model) public async Task<int> DeleteAsync(object model)
@ -90,6 +54,16 @@ namespace ServiceLib.Common
return await _dbAsync.DeleteAsync(model); return await _dbAsync.DeleteAsync(model);
} }
public async Task<int> DeleteAllAsync<T>()
{
return await _dbAsync.DeleteAllAsync<T>();
}
public async Task<int> ExecuteAsync(string sql)
{
return await _dbAsync.ExecuteAsync(sql);
}
public List<T> Query<T>(string sql) where T : new() public List<T> Query<T>(string sql) where T : new()
{ {
return _db.Query<T>(sql); return _db.Query<T>(sql);
@ -100,21 +74,6 @@ namespace ServiceLib.Common
return await _dbAsync.QueryAsync<T>(sql); return await _dbAsync.QueryAsync<T>(sql);
} }
public int Execute(string sql)
{
return _db.Execute(sql);
}
public int DeleteAll<T>()
{
return _db.DeleteAll<T>();
}
public async Task<int> ExecuteAsync(string sql)
{
return await _dbAsync.ExecuteAsync(sql);
}
public TableQuery<T> Table<T>() where T : new() public TableQuery<T> Table<T>() where T : new()
{ {
return _db.Table<T>(); return _db.Table<T>();

View file

@ -46,7 +46,8 @@
public bool InitApp() public bool InitApp()
{ {
if (ConfigHandler.LoadConfig(ref _config) != 0) _config = ConfigHandler.LoadConfig();
if (_config == null)
{ {
return false; return false;
} }
@ -152,7 +153,7 @@
{ {
filter = filter.Replace("'", ""); 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<ProfileItemModel>(sql).ToList(); return SQLiteHelper.Instance.Query<ProfileItemModel>(sql).ToList();

View file

@ -10,12 +10,7 @@ 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> updateFunc) public async Task<Tuple<ClashProxies, ClashProviders>?> GetClashProxiesAsync(Config config)
{
Task.Run(() => GetClashProxiesAsync(config, updateFunc));
}
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,12 +25,13 @@ namespace ServiceLib.Handler
if (clashProxies != null || clashProviders != null) if (clashProxies != null || clashProviders != null)
{ {
_proxies = clashProxies?.proxies; _proxies = clashProxies?.proxies;
updateFunc?.Invoke(clashProxies, clashProviders); return new Tuple<ClashProxies, ClashProviders>(clashProxies, clashProviders);
return;
} }
Task.Delay(5000).Wait();
await Task.Delay(5000);
} }
updateFunc?.Invoke(null, null);
return null;
} }
public void ClashProxiesDelayTest(bool blAll, List<ClashProxyModel> lstProxy, Action<ClashProxyModel?, string> updateFunc) public void ClashProxiesDelayTest(bool blAll, List<ClashProxyModel> lstProxy, Action<ClashProxyModel?, string> updateFunc)
@ -118,7 +114,7 @@ namespace ServiceLib.Handler
} }
} }
public async void ClashSetActiveProxy(string name, string nameNode) public async Task ClashSetActiveProxy(string name, string nameNode)
{ {
try try
{ {
@ -133,9 +129,7 @@ namespace ServiceLib.Handler
} }
} }
public void ClashConfigUpdate(Dictionary<string, string> headers) public async Task ClashConfigUpdate(Dictionary<string, string> headers)
{
Task.Run(async () =>
{ {
if (_proxies == null) if (_proxies == null)
{ {
@ -145,12 +139,11 @@ namespace ServiceLib.Handler
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 try
{ {
var url = $"{GetApiUrl()}/configs?force=true"; var url = $"{GetApiUrl()}/configs?force=true";
@ -164,12 +157,7 @@ namespace ServiceLib.Handler
} }
} }
public void GetClashConnections(Config config, Action<ClashConnections> updateFunc) public async Task<ClashConnections?> GetClashConnectionsAsync(Config config)
{
Task.Run(() => GetClashConnectionsAsync(config, updateFunc));
}
private async Task GetClashConnectionsAsync(Config config, Action<ClashConnections> updateFunc)
{ {
try try
{ {
@ -177,15 +165,17 @@ 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);
updateFunc?.Invoke(clashConnections); return clashConnections;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logging.SaveLog(ex.Message, ex); Logging.SaveLog(ex.Message, ex);
} }
return null;
} }
public async void ClashConnectionClose(string id) public async Task ClashConnectionClose(string id)
{ {
try try
{ {

View file

@ -18,8 +18,9 @@ namespace ServiceLib.Handler
/// </summary> /// </summary>
/// <param name="config"></param> /// <param name="config"></param>
/// <returns></returns> /// <returns></returns>
public static int LoadConfig(ref Config? config) public static Config? LoadConfig()
{ {
Config? config = null;
var result = Utils.LoadResource(Utils.GetConfigPath(_configRes)); var result = Utils.LoadResource(Utils.GetConfigPath(_configRes));
if (Utils.IsNotEmpty(result)) if (Utils.IsNotEmpty(result))
{ {
@ -30,7 +31,7 @@ namespace ServiceLib.Handler
if (File.Exists(Utils.GetConfigPath(_configRes))) if (File.Exists(Utils.GetConfigPath(_configRes)))
{ {
Logging.SaveLog("LoadConfig Exception"); Logging.SaveLog("LoadConfig Exception");
return -1; return null;
} }
} }
@ -164,7 +165,7 @@ namespace ServiceLib.Handler
config.systemProxyItem ??= new(); config.systemProxyItem ??= new();
config.webDavItem ??= new(); config.webDavItem ??= new();
return 0; return config;
} }
/// <summary> /// <summary>
@ -172,9 +173,9 @@ namespace ServiceLib.Handler
/// </summary> /// </summary>
/// <param name="config"></param> /// <param name="config"></param>
/// <returns></returns> /// <returns></returns>
public static int SaveConfig(Config config, bool reload = true) public static async Task<int> SaveConfig(Config config, bool reload = true)
{ {
ToJsonFile(config); await ToJsonFile(config);
return 0; return 0;
} }
@ -183,7 +184,7 @@ namespace ServiceLib.Handler
/// 存储文件 /// 存储文件
/// </summary> /// </summary>
/// <param name="config"></param> /// <param name="config"></param>
private static void ToJsonFile(Config config) private static async Task ToJsonFile(Config config)
{ {
lock (_objLock) lock (_objLock)
{ {
@ -215,7 +216,7 @@ namespace ServiceLib.Handler
#region Server #region Server
public static int AddServer(Config config, ProfileItem profileItem) public static async Task<int> AddServer(Config config, ProfileItem profileItem)
{ {
var item = AppHandler.Instance.GetProfileItem(profileItem.indexId); var item = AppHandler.Instance.GetProfileItem(profileItem.indexId);
if (item is null) if (item is null)
@ -252,15 +253,15 @@ namespace ServiceLib.Handler
var ret = item.configType switch var ret = item.configType switch
{ {
EConfigType.VMess => AddVMessServer(config, item), EConfigType.VMess => await AddVMessServer(config, item),
EConfigType.Shadowsocks => AddShadowsocksServer(config, item), EConfigType.Shadowsocks => await AddShadowsocksServer(config, item),
EConfigType.SOCKS => AddSocksServer(config, item), EConfigType.SOCKS => await AddSocksServer(config, item),
EConfigType.HTTP => AddHttpServer(config, item), EConfigType.HTTP => await AddHttpServer(config, item),
EConfigType.Trojan => AddTrojanServer(config, item), EConfigType.Trojan => await AddTrojanServer(config, item),
EConfigType.VLESS => AddVlessServer(config, item), EConfigType.VLESS => await AddVlessServer(config, item),
EConfigType.Hysteria2 => AddHysteria2Server(config, item), EConfigType.Hysteria2 => await AddHysteria2Server(config, item),
EConfigType.TUIC => AddTuicServer(config, item), EConfigType.TUIC => await AddTuicServer(config, item),
EConfigType.WireGuard => AddWireguardServer(config, item), EConfigType.WireGuard => await AddWireguardServer(config, item),
_ => -1, _ => -1,
}; };
return ret; return ret;
@ -272,7 +273,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int AddVMessServer(Config config, ProfileItem profileItem, bool toFile = true) public static async Task<int> AddVMessServer(Config config, ProfileItem profileItem, bool toFile = true)
{ {
profileItem.configType = EConfigType.VMess; profileItem.configType = EConfigType.VMess;
@ -294,7 +295,7 @@ namespace ServiceLib.Handler
return -1; return -1;
} }
AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
return 0; return 0;
} }
@ -305,7 +306,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="indexes"></param> /// <param name="indexes"></param>
/// <returns></returns> /// <returns></returns>
public static int RemoveServer(Config config, List<ProfileItem> indexes) public static async Task<int> RemoveServer(Config config, List<ProfileItem> indexes)
{ {
var subid = "TempRemoveSubId"; var subid = "TempRemoveSubId";
foreach (var item in indexes) foreach (var item in indexes)
@ -313,8 +314,8 @@ namespace ServiceLib.Handler
item.subid = subid; item.subid = subid;
} }
SQLiteHelper.Instance.UpdateAll(indexes); await SQLiteHelper.Instance.UpdateAllAsync(indexes);
RemoveServerViaSubid(config, subid, false); await RemoveServerViaSubid(config, subid, false);
return 0; return 0;
} }
@ -325,7 +326,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="index"></param> /// <param name="index"></param>
/// <returns></returns> /// <returns></returns>
public static int CopyServer(Config config, List<ProfileItem> indexes) public static async Task<int> CopyServer(Config config, List<ProfileItem> indexes)
{ {
foreach (var it in indexes) foreach (var it in indexes)
{ {
@ -335,20 +336,20 @@ namespace ServiceLib.Handler
continue; continue;
} }
ProfileItem profileItem = JsonUtils.DeepCopy(item); var profileItem = JsonUtils.DeepCopy(item);
profileItem.indexId = string.Empty; profileItem.indexId = string.Empty;
profileItem.remarks = $"{item.remarks}-clone"; profileItem.remarks = $"{item.remarks}-clone";
if (profileItem.configType == EConfigType.Custom) if (profileItem.configType == EConfigType.Custom)
{ {
profileItem.address = Utils.GetConfigPath(profileItem.address); profileItem.address = Utils.GetConfigPath(profileItem.address);
if (AddCustomServer(config, profileItem, false) == 0) if (await AddCustomServer(config, profileItem, false) == 0)
{ {
} }
} }
else else
{ {
AddServerCommon(config, profileItem, true); await AddServerCommon(config, profileItem, true);
} }
} }
@ -361,7 +362,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <returns></returns> /// <returns></returns>
public static int SetDefaultServerIndex(Config config, string? indexId) public static async Task<int> SetDefaultServerIndex(Config config, string? indexId)
{ {
if (Utils.IsNullOrEmpty(indexId)) if (Utils.IsNullOrEmpty(indexId))
{ {
@ -370,12 +371,12 @@ namespace ServiceLib.Handler
config.indexId = indexId; config.indexId = indexId;
ToJsonFile(config); await ToJsonFile(config);
return 0; return 0;
} }
public static int SetDefaultServer(Config config, List<ProfileItemModel> lstProfile) public static async Task<int> SetDefaultServer(Config config, List<ProfileItemModel> lstProfile)
{ {
if (lstProfile.Exists(t => t.indexId == config.indexId)) if (lstProfile.Exists(t => t.indexId == config.indexId))
{ {
@ -387,18 +388,18 @@ namespace ServiceLib.Handler
} }
if (lstProfile.Count > 0) 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<ProfileItem>().Where(t => t.port > 0).Select(t => t.indexId).FirstOrDefault()); return await SetDefaultServerIndex(config, SQLiteHelper.Instance.Table<ProfileItem>().Where(t => t.port > 0).Select(t => t.indexId).FirstOrDefault());
} }
public static ProfileItem? GetDefaultServer(Config config) public static async Task<ProfileItem?> GetDefaultServer(Config config)
{ {
var item = AppHandler.Instance.GetProfileItem(config.indexId); var item = AppHandler.Instance.GetProfileItem(config.indexId);
if (item is null) if (item is null)
{ {
var item2 = SQLiteHelper.Instance.Table<ProfileItem>().FirstOrDefault(); var item2 = SQLiteHelper.Instance.Table<ProfileItem>().FirstOrDefault();
SetDefaultServerIndex(config, item2?.indexId); await SetDefaultServerIndex(config, item2?.indexId);
return item2; return item2;
} }
@ -413,7 +414,7 @@ namespace ServiceLib.Handler
/// <param name="index"></param> /// <param name="index"></param>
/// <param name="eMove"></param> /// <param name="eMove"></param>
/// <returns></returns> /// <returns></returns>
public static int MoveServer(Config config, ref List<ProfileItem> lstProfile, int index, EMove eMove, int pos = -1) public static async Task<int> MoveServer(Config config, List<ProfileItem> lstProfile, int index, EMove eMove, int pos = -1)
{ {
int count = lstProfile.Count; int count = lstProfile.Count;
if (index < 0 || index > lstProfile.Count - 1) if (index < 0 || index > lstProfile.Count - 1)
@ -485,7 +486,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int AddCustomServer(Config config, ProfileItem profileItem, bool blDelete) public static async Task<int> AddCustomServer(Config config, ProfileItem profileItem, bool blDelete)
{ {
var fileName = profileItem.address; var fileName = profileItem.address;
if (!File.Exists(fileName)) if (!File.Exists(fileName))
@ -517,7 +518,7 @@ namespace ServiceLib.Handler
profileItem.remarks = $"import custom@{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}"; profileItem.remarks = $"import custom@{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}";
} }
AddServerCommon(config, profileItem, true); await AddServerCommon(config, profileItem, true);
return 0; return 0;
} }
@ -528,7 +529,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int EditCustomServer(Config config, ProfileItem profileItem) public static async Task<int> EditCustomServer(Config config, ProfileItem profileItem)
{ {
var item = AppHandler.Instance.GetProfileItem(profileItem.indexId); var item = AppHandler.Instance.GetProfileItem(profileItem.indexId);
if (item is null) if (item is null)
@ -544,7 +545,7 @@ namespace ServiceLib.Handler
item.preSocksPort = profileItem.preSocksPort; item.preSocksPort = profileItem.preSocksPort;
} }
if (SQLiteHelper.Instance.Update(item) > 0) if (await SQLiteHelper.Instance.UpdateAsync(item) > 0)
{ {
return 0; return 0;
} }
@ -562,7 +563,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int AddShadowsocksServer(Config config, ProfileItem profileItem, bool toFile = true) public static async Task<int> AddShadowsocksServer(Config config, ProfileItem profileItem, bool toFile = true)
{ {
profileItem.configType = EConfigType.Shadowsocks; profileItem.configType = EConfigType.Shadowsocks;
@ -579,7 +580,7 @@ namespace ServiceLib.Handler
return -1; return -1;
} }
AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
return 0; return 0;
} }
@ -590,13 +591,13 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int AddSocksServer(Config config, ProfileItem profileItem, bool toFile = true) public static async Task<int> AddSocksServer(Config config, ProfileItem profileItem, bool toFile = true)
{ {
profileItem.configType = EConfigType.SOCKS; profileItem.configType = EConfigType.SOCKS;
profileItem.address = profileItem.address.TrimEx(); profileItem.address = profileItem.address.TrimEx();
AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
return 0; return 0;
} }
@ -607,13 +608,13 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int AddHttpServer(Config config, ProfileItem profileItem, bool toFile = true) public static async Task<int> AddHttpServer(Config config, ProfileItem profileItem, bool toFile = true)
{ {
profileItem.configType = EConfigType.HTTP; profileItem.configType = EConfigType.HTTP;
profileItem.address = profileItem.address.TrimEx(); profileItem.address = profileItem.address.TrimEx();
AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
return 0; return 0;
} }
@ -624,7 +625,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int AddTrojanServer(Config config, ProfileItem profileItem, bool toFile = true) public static async Task<int> AddTrojanServer(Config config, ProfileItem profileItem, bool toFile = true)
{ {
profileItem.configType = EConfigType.Trojan; profileItem.configType = EConfigType.Trojan;
@ -639,7 +640,7 @@ namespace ServiceLib.Handler
return -1; return -1;
} }
AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
return 0; return 0;
} }
@ -650,7 +651,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int AddHysteria2Server(Config config, ProfileItem profileItem, bool toFile = true) public static async Task<int> AddHysteria2Server(Config config, ProfileItem profileItem, bool toFile = true)
{ {
profileItem.configType = EConfigType.Hysteria2; profileItem.configType = EConfigType.Hysteria2;
profileItem.coreType = ECoreType.sing_box; profileItem.coreType = ECoreType.sing_box;
@ -669,7 +670,7 @@ namespace ServiceLib.Handler
return -1; return -1;
} }
AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
return 0; return 0;
} }
@ -680,7 +681,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int AddTuicServer(Config config, ProfileItem profileItem, bool toFile = true) public static async Task<int> AddTuicServer(Config config, ProfileItem profileItem, bool toFile = true)
{ {
profileItem.configType = EConfigType.TUIC; profileItem.configType = EConfigType.TUIC;
profileItem.coreType = ECoreType.sing_box; profileItem.coreType = ECoreType.sing_box;
@ -708,7 +709,7 @@ namespace ServiceLib.Handler
return -1; return -1;
} }
AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
return 0; return 0;
} }
@ -719,7 +720,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int AddWireguardServer(Config config, ProfileItem profileItem, bool toFile = true) public static async Task<int> AddWireguardServer(Config config, ProfileItem profileItem, bool toFile = true)
{ {
profileItem.configType = EConfigType.WireGuard; profileItem.configType = EConfigType.WireGuard;
profileItem.coreType = ECoreType.sing_box; profileItem.coreType = ECoreType.sing_box;
@ -740,12 +741,12 @@ namespace ServiceLib.Handler
return -1; return -1;
} }
AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
return 0; return 0;
} }
public static int SortServers(Config config, string subId, string colName, bool asc) public static async Task<int> SortServers(Config config, string subId, string colName, bool asc)
{ {
var lstModel = AppHandler.Instance.ProfileItems(subId, ""); var lstModel = AppHandler.Instance.ProfileItems(subId, "");
if (lstModel.Count <= 0) if (lstModel.Count <= 0)
@ -846,7 +847,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="profileItem"></param> /// <param name="profileItem"></param>
/// <returns></returns> /// <returns></returns>
public static int AddVlessServer(Config config, ProfileItem profileItem, bool toFile = true) public static async Task<int> AddVlessServer(Config config, ProfileItem profileItem, bool toFile = true)
{ {
profileItem.configType = EConfigType.VLESS; profileItem.configType = EConfigType.VLESS;
@ -872,12 +873,12 @@ namespace ServiceLib.Handler
profileItem.security = Global.None; profileItem.security = Global.None;
} }
AddServerCommon(config, profileItem, toFile); await AddServerCommon(config, profileItem, toFile);
return 0; return 0;
} }
public static Tuple<int, int> DedupServerList(Config config, string subId) public static async Task<Tuple<int, int>> DedupServerList(Config config, string subId)
{ {
var lstProfile = AppHandler.Instance.ProfileItems(subId); var lstProfile = AppHandler.Instance.ProfileItems(subId);
@ -896,12 +897,12 @@ namespace ServiceLib.Handler
lstRemove.Add(item); lstRemove.Add(item);
} }
} }
RemoveServer(config, lstRemove); await RemoveServer(config, lstRemove);
return new Tuple<int, int>(lstProfile.Count, lstKeep.Count); return new Tuple<int, int>(lstProfile.Count, lstKeep.Count);
} }
public static int AddServerCommon(Config config, ProfileItem profileItem, bool toFile = true) public static async Task<int> AddServerCommon(Config config, ProfileItem profileItem, bool toFile = true)
{ {
profileItem.configVersion = 2; profileItem.configVersion = 2;
@ -947,7 +948,7 @@ namespace ServiceLib.Handler
if (toFile) if (toFile)
{ {
SQLiteHelper.Instance.Replace(profileItem); await SQLiteHelper.Instance.ReplaceAsync(profileItem);
} }
return 0; return 0;
} }
@ -975,7 +976,7 @@ namespace ServiceLib.Handler
&& (!remarks || o.remarks == n.remarks); && (!remarks || o.remarks == n.remarks);
} }
private static int RemoveProfileItem(Config config, string indexId) private static async Task<int> RemoveProfileItem(Config config, string indexId)
{ {
try try
{ {
@ -989,7 +990,7 @@ namespace ServiceLib.Handler
File.Delete(Utils.GetConfigPath(item.address)); File.Delete(Utils.GetConfigPath(item.address));
} }
SQLiteHelper.Instance.Delete(item); await SQLiteHelper.Instance.DeleteAsync(item);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -999,19 +1000,19 @@ namespace ServiceLib.Handler
return 0; return 0;
} }
public static int AddCustomServer4Multiple(Config config, List<ProfileItem> selecteds, ECoreType coreType, out string indexId) public static async Task<Tuple<int, string>> AddCustomServer4Multiple(Config config, List<ProfileItem> selecteds, ECoreType coreType)
{ {
indexId = Utils.GetMd5(Global.CoreMultipleLoadConfigFileName); var indexId = Utils.GetMd5(Global.CoreMultipleLoadConfigFileName);
string configPath = Utils.GetConfigPath(Global.CoreMultipleLoadConfigFileName); string configPath = Utils.GetConfigPath(Global.CoreMultipleLoadConfigFileName);
if (CoreConfigHandler.GenerateClientMultipleLoadConfig(config, configPath, selecteds, coreType, out string msg) != 0) if (CoreConfigHandler.GenerateClientMultipleLoadConfig(config, configPath, selecteds, coreType, out string msg) != 0)
{ {
return -1; return new Tuple<int, string>(-1, "");
} }
var fileName = configPath; var fileName = configPath;
if (!File.Exists(fileName)) if (!File.Exists(fileName))
{ {
return -1; return new Tuple<int, string>(-1, "");
} }
var profileItem = AppHandler.Instance.GetProfileItem(indexId) ?? new(); var profileItem = AppHandler.Instance.GetProfileItem(indexId) ?? new();
@ -1021,9 +1022,9 @@ namespace ServiceLib.Handler
profileItem.configType = EConfigType.Custom; profileItem.configType = EConfigType.Custom;
profileItem.coreType = coreType; profileItem.coreType = coreType;
AddServerCommon(config, profileItem, true); await AddServerCommon(config, profileItem, true);
return 0; return new Tuple<int, string>(0, indexId);
} }
#endregion Server #endregion Server
@ -1037,7 +1038,7 @@ namespace ServiceLib.Handler
/// <param name="strData"></param> /// <param name="strData"></param>
/// <param name="subid"></param> /// <param name="subid"></param>
/// <returns>成功导入的数量</returns> /// <returns>成功导入的数量</returns>
private static int AddBatchServers(Config config, string strData, string subid, bool isSub, List<ProfileItem> lstOriSub) private static async Task<int> AddBatchServers(Config config, string strData, string subid, bool isSub, List<ProfileItem> lstOriSub)
{ {
if (Utils.IsNullOrEmpty(strData)) if (Utils.IsNullOrEmpty(strData))
{ {
@ -1048,7 +1049,7 @@ namespace ServiceLib.Handler
//remove sub items //remove sub items
if (isSub && Utils.IsNotEmpty(subid)) if (isSub && Utils.IsNotEmpty(subid))
{ {
RemoveServerViaSubid(config, subid, isSub); await RemoveServerViaSubid(config, subid, isSub);
subFilter = AppHandler.Instance.GetSubItem(subid)?.filter ?? ""; subFilter = AppHandler.Instance.GetSubItem(subid)?.filter ?? "";
} }
@ -1066,7 +1067,7 @@ namespace ServiceLib.Handler
//maybe sub //maybe sub
if (!isSub && (str.StartsWith(Global.HttpsProtocol) || str.StartsWith(Global.HttpProtocol))) if (!isSub && (str.StartsWith(Global.HttpsProtocol) || str.StartsWith(Global.HttpProtocol)))
{ {
if (AddSubItem(config, str) == 0) if (await AddSubItem(config, str) == 0)
{ {
countServers++; countServers++;
} }
@ -1114,14 +1115,14 @@ namespace ServiceLib.Handler
var addStatus = profileItem.configType switch var addStatus = profileItem.configType switch
{ {
EConfigType.VMess => AddVMessServer(config, profileItem, false), EConfigType.VMess => await AddVMessServer(config, profileItem, false),
EConfigType.Shadowsocks => AddShadowsocksServer(config, profileItem, false), EConfigType.Shadowsocks => await AddShadowsocksServer(config, profileItem, false),
EConfigType.SOCKS => AddSocksServer(config, profileItem, false), EConfigType.SOCKS => await AddSocksServer(config, profileItem, false),
EConfigType.Trojan => AddTrojanServer(config, profileItem, false), EConfigType.Trojan => await AddTrojanServer(config, profileItem, false),
EConfigType.VLESS => AddVlessServer(config, profileItem, false), EConfigType.VLESS => await AddVlessServer(config, profileItem, false),
EConfigType.Hysteria2 => AddHysteria2Server(config, profileItem, false), EConfigType.Hysteria2 => await AddHysteria2Server(config, profileItem, false),
EConfigType.TUIC => AddTuicServer(config, profileItem, false), EConfigType.TUIC => await AddTuicServer(config, profileItem, false),
EConfigType.WireGuard => AddWireguardServer(config, profileItem, false), EConfigType.WireGuard => await AddWireguardServer(config, profileItem, false),
_ => -1, _ => -1,
}; };
@ -1134,14 +1135,14 @@ namespace ServiceLib.Handler
if (lstAdd.Count > 0) if (lstAdd.Count > 0)
{ {
SQLiteHelper.Instance.InsertAll(lstAdd); await SQLiteHelper.Instance.InsertAllAsync(lstAdd);
} }
ToJsonFile(config); await ToJsonFile(config);
return countServers; return countServers;
} }
private static int AddBatchServers4Custom(Config config, string strData, string subid, bool isSub, List<ProfileItem> lstOriSub) private static async Task<int> AddBatchServers4Custom(Config config, string strData, string subid, bool isSub, List<ProfileItem> lstOriSub)
{ {
if (Utils.IsNullOrEmpty(strData)) if (Utils.IsNullOrEmpty(strData))
{ {
@ -1167,7 +1168,7 @@ namespace ServiceLib.Handler
{ {
if (isSub && Utils.IsNotEmpty(subid)) if (isSub && Utils.IsNotEmpty(subid))
{ {
RemoveServerViaSubid(config, subid, isSub); await RemoveServerViaSubid(config, subid, isSub);
} }
int count = 0; int count = 0;
foreach (var it in lstProfiles) foreach (var it in lstProfiles)
@ -1175,7 +1176,7 @@ namespace ServiceLib.Handler
it.subid = subid; it.subid = subid;
it.isSub = isSub; it.isSub = isSub;
it.preSocksPort = preSocksPort; it.preSocksPort = preSocksPort;
if (AddCustomServer(config, it, true) == 0) if (await AddCustomServer(config, it, true) == 0)
{ {
count++; count++;
} }
@ -1223,7 +1224,7 @@ namespace ServiceLib.Handler
if (isSub && Utils.IsNotEmpty(subid)) if (isSub && Utils.IsNotEmpty(subid))
{ {
RemoveServerViaSubid(config, subid, isSub); await RemoveServerViaSubid(config, subid, isSub);
} }
if (isSub && lstOriSub?.Count == 1) if (isSub && lstOriSub?.Count == 1)
{ {
@ -1232,7 +1233,7 @@ namespace ServiceLib.Handler
profileItem.subid = subid; profileItem.subid = subid;
profileItem.isSub = isSub; profileItem.isSub = isSub;
profileItem.preSocksPort = preSocksPort; profileItem.preSocksPort = preSocksPort;
if (AddCustomServer(config, profileItem, true) == 0) if (await AddCustomServer(config, profileItem, true) == 0)
{ {
return 1; return 1;
} }
@ -1242,7 +1243,7 @@ namespace ServiceLib.Handler
} }
} }
private static int AddBatchServers4SsSIP008(Config config, string strData, string subid, bool isSub, List<ProfileItem> lstOriSub) private static async Task<int> AddBatchServers4SsSIP008(Config config, string strData, string subid, bool isSub, List<ProfileItem> lstOriSub)
{ {
if (Utils.IsNullOrEmpty(strData)) if (Utils.IsNullOrEmpty(strData))
{ {
@ -1251,7 +1252,7 @@ namespace ServiceLib.Handler
if (isSub && Utils.IsNotEmpty(subid)) if (isSub && Utils.IsNotEmpty(subid))
{ {
RemoveServerViaSubid(config, subid, isSub); await RemoveServerViaSubid(config, subid, isSub);
} }
var lstSsServer = ShadowsocksFmt.ResolveSip008(strData); var lstSsServer = ShadowsocksFmt.ResolveSip008(strData);
@ -1262,19 +1263,19 @@ namespace ServiceLib.Handler
{ {
ssItem.subid = subid; ssItem.subid = subid;
ssItem.isSub = isSub; ssItem.isSub = isSub;
if (AddShadowsocksServer(config, ssItem) == 0) if (await AddShadowsocksServer(config, ssItem) == 0)
{ {
counter++; counter++;
} }
} }
ToJsonFile(config); await ToJsonFile(config);
return counter; return counter;
} }
return -1; return -1;
} }
public static int AddBatchServers(Config config, string strData, string subid, bool isSub) public static async Task<int> AddBatchServers(Config config, string strData, string subid, bool isSub)
{ {
if (Utils.IsNullOrEmpty(strData)) if (Utils.IsNullOrEmpty(strData))
{ {
@ -1289,26 +1290,26 @@ namespace ServiceLib.Handler
var counter = 0; var counter = 0;
if (Utils.IsBase64String(strData)) 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) if (counter < 1)
{ {
counter = AddBatchServers(config, strData, subid, isSub, lstOriSub); counter = await AddBatchServers(config, strData, subid, isSub, lstOriSub);
} }
if (counter < 1) 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) if (counter < 1)
{ {
counter = AddBatchServers4SsSIP008(config, strData, subid, isSub, lstOriSub); counter = await AddBatchServers4SsSIP008(config, strData, subid, isSub, lstOriSub);
} }
//maybe other sub //maybe other sub
if (counter < 1) if (counter < 1)
{ {
counter = AddBatchServers4Custom(config, strData, subid, isSub, lstOriSub); counter = await AddBatchServers4Custom(config, strData, subid, isSub, lstOriSub);
} }
return counter; return counter;
@ -1324,7 +1325,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="url"></param> /// <param name="url"></param>
/// <returns></returns> /// <returns></returns>
public static int AddSubItem(Config config, string url) public static async Task<int> AddSubItem(Config config, string url)
{ {
//already exists //already exists
if (SQLiteHelper.Instance.Table<SubItem>().Any(e => e.url == url)) if (SQLiteHelper.Instance.Table<SubItem>().Any(e => e.url == url))
@ -1348,10 +1349,10 @@ namespace ServiceLib.Handler
return 0; return 0;
} }
return AddSubItem(config, subItem); return await AddSubItem(config, subItem);
} }
public static int AddSubItem(Config config, SubItem subItem) public static async Task<int> AddSubItem(Config config, SubItem subItem)
{ {
var item = AppHandler.Instance.GetSubItem(subItem.id); var item = AppHandler.Instance.GetSubItem(subItem.id);
if (item is null) if (item is null)
@ -1389,7 +1390,7 @@ namespace ServiceLib.Handler
item.sort = maxSort + 1; item.sort = maxSort + 1;
} }
} }
if (SQLiteHelper.Instance.Replace(item) > 0) if (await SQLiteHelper.Instance.ReplaceAsync(item) > 0)
{ {
return 0; return 0;
} }
@ -1405,7 +1406,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="subid"></param> /// <param name="subid"></param>
/// <returns></returns> /// <returns></returns>
public static int RemoveServerViaSubid(Config config, string subid, bool isSub) public static async Task<int> RemoveServerViaSubid(Config config, string subid, bool isSub)
{ {
if (Utils.IsNullOrEmpty(subid)) if (Utils.IsNullOrEmpty(subid))
{ {
@ -1414,11 +1415,11 @@ namespace ServiceLib.Handler
var customProfile = SQLiteHelper.Instance.Table<ProfileItem>().Where(t => t.subid == subid && t.configType == EConfigType.Custom).ToList(); var customProfile = SQLiteHelper.Instance.Table<ProfileItem>().Where(t => t.subid == subid && t.configType == EConfigType.Custom).ToList();
if (isSub) 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 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) foreach (var item in customProfile)
{ {
@ -1428,26 +1429,26 @@ namespace ServiceLib.Handler
return 0; return 0;
} }
public static int DeleteSubItem(Config config, string id) public static async Task<int> DeleteSubItem(Config config, string id)
{ {
var item = AppHandler.Instance.GetSubItem(id); var item = AppHandler.Instance.GetSubItem(id);
if (item is null) if (item is null)
{ {
return 0; return 0;
} }
SQLiteHelper.Instance.Delete(item); await SQLiteHelper.Instance.DeleteAsync(item);
RemoveServerViaSubid(config, id, false); await RemoveServerViaSubid(config, id, false);
return 0; return 0;
} }
public static int MoveToGroup(Config config, List<ProfileItem> lstProfile, string subid) public static async Task<int> MoveToGroup(Config config, List<ProfileItem> lstProfile, string subid)
{ {
foreach (var item in lstProfile) foreach (var item in lstProfile)
{ {
item.subid = subid; item.subid = subid;
} }
SQLiteHelper.Instance.UpdateAll(lstProfile); await SQLiteHelper.Instance.UpdateAllAsync(lstProfile);
return 0; return 0;
} }
@ -1456,14 +1457,14 @@ namespace ServiceLib.Handler
#region Routing #region Routing
public static int SaveRoutingItem(Config config, RoutingItem item) public static async Task<int> SaveRoutingItem(Config config, RoutingItem item)
{ {
if (Utils.IsNullOrEmpty(item.id)) if (Utils.IsNullOrEmpty(item.id))
{ {
item.id = Utils.GetGuid(false); item.id = Utils.GetGuid(false);
} }
if (SQLiteHelper.Instance.Replace(item) > 0) if (await SQLiteHelper.Instance.ReplaceAsync(item) > 0)
{ {
return 0; return 0;
} }
@ -1479,7 +1480,7 @@ namespace ServiceLib.Handler
/// <param name="config"></param> /// <param name="config"></param>
/// <param name="strData"></param> /// <param name="strData"></param>
/// <returns></returns> /// <returns></returns>
public static int AddBatchRoutingRules(ref RoutingItem routingItem, string strData) public static async Task<int> AddBatchRoutingRules(RoutingItem routingItem, string strData)
{ {
if (Utils.IsNullOrEmpty(strData)) if (Utils.IsNullOrEmpty(strData))
{ {
@ -1504,7 +1505,7 @@ namespace ServiceLib.Handler
routingItem.id = Utils.GetGuid(false); routingItem.id = Utils.GetGuid(false);
} }
if (SQLiteHelper.Instance.Replace(routingItem) > 0) if (await SQLiteHelper.Instance.ReplaceAsync(routingItem) > 0)
{ {
return 0; return 0;
} }
@ -1521,7 +1522,7 @@ namespace ServiceLib.Handler
/// <param name="index"></param> /// <param name="index"></param>
/// <param name="eMove"></param> /// <param name="eMove"></param>
/// <returns></returns> /// <returns></returns>
public static int MoveRoutingRule(List<RulesItem> rules, int index, EMove eMove, int pos = -1) public static async Task<int> MoveRoutingRule(List<RulesItem> rules, int index, EMove eMove, int pos = -1)
{ {
int count = rules.Count; int count = rules.Count;
if (index < 0 || index > rules.Count - 1) if (index < 0 || index > rules.Count - 1)
@ -1591,55 +1592,55 @@ namespace ServiceLib.Handler
return 0; return 0;
} }
public static int SetDefaultRouting(Config config, RoutingItem routingItem) public static async Task<int> SetDefaultRouting(Config config, RoutingItem routingItem)
{ {
if (SQLiteHelper.Instance.Table<RoutingItem>().Where(t => t.id == routingItem.id).Count() > 0) if (SQLiteHelper.Instance.Table<RoutingItem>().Where(t => t.id == routingItem.id).Count() > 0)
{ {
config.routingBasicItem.routingIndexId = routingItem.id; config.routingBasicItem.routingIndexId = routingItem.id;
} }
ToJsonFile(config); await ToJsonFile(config);
return 0; return 0;
} }
public static RoutingItem GetDefaultRouting(Config config) public static async Task<RoutingItem> GetDefaultRouting(Config config)
{ {
var item = AppHandler.Instance.GetRoutingItem(config.routingBasicItem.routingIndexId); var item = AppHandler.Instance.GetRoutingItem(config.routingBasicItem.routingIndexId);
if (item is null) if (item is null)
{ {
var item2 = SQLiteHelper.Instance.Table<RoutingItem>().FirstOrDefault(t => t.locked == false); var item2 = SQLiteHelper.Instance.Table<RoutingItem>().FirstOrDefault(t => t.locked == false);
SetDefaultRouting(config, item2); await SetDefaultRouting(config, item2);
return item2; return item2;
} }
return item; return item;
} }
public static int InitRouting(Config config, bool blImportAdvancedRules = false) public static async Task<int> InitRouting(Config config, bool blImportAdvancedRules = false)
{ {
if (string.IsNullOrEmpty(config.constItem.routeRulesTemplateSourceUrl)) if (string.IsNullOrEmpty(config.constItem.routeRulesTemplateSourceUrl))
{ {
InitBuiltinRouting(config, blImportAdvancedRules); await InitBuiltinRouting(config, blImportAdvancedRules);
} }
else else
{ {
InitExternalRouting(config, blImportAdvancedRules); await InitExternalRouting(config, blImportAdvancedRules);
} }
return 0; return 0;
} }
public static int InitExternalRouting(Config config, bool blImportAdvancedRules = false) public static async Task<int> InitExternalRouting(Config config, bool blImportAdvancedRules = false)
{ {
var downloadHandle = new DownloadService(); var downloadHandle = new DownloadService();
var templateContent = Task.Run(() => downloadHandle.TryDownloadString(config.constItem.routeRulesTemplateSourceUrl, false, "")).Result; var templateContent = Task.Run(() => downloadHandle.TryDownloadString(config.constItem.routeRulesTemplateSourceUrl, false, "")).Result;
if (String.IsNullOrEmpty(templateContent)) if (string.IsNullOrEmpty(templateContent))
return InitBuiltinRouting(config, blImportAdvancedRules); // fallback return await InitBuiltinRouting(config, blImportAdvancedRules); // fallback
var template = JsonUtils.Deserialize<RoutingTemplate>(templateContent); var template = JsonUtils.Deserialize<RoutingTemplate>(templateContent);
if (template == null) if (template == null)
return InitBuiltinRouting(config, blImportAdvancedRules); // fallback return await InitBuiltinRouting(config, blImportAdvancedRules); // fallback
var items = AppHandler.Instance.RoutingItems(); var items = AppHandler.Instance.RoutingItems();
var maxSort = items.Count; var maxSort = items.Count;
@ -1651,14 +1652,14 @@ namespace ServiceLib.Handler
{ {
var item = template.routingItems[i]; var item = template.routingItems[i];
if (String.IsNullOrEmpty(item.url) && String.IsNullOrEmpty(item.ruleSet)) if (string.IsNullOrEmpty(item.url) && string.IsNullOrEmpty(item.ruleSet))
continue; continue;
var ruleSetsString = !String.IsNullOrEmpty(item.ruleSet) var ruleSetsString = !string.IsNullOrEmpty(item.ruleSet)
? item.ruleSet ? item.ruleSet
: Task.Run(() => downloadHandle.TryDownloadString(item.url, false, "")).Result; : Task.Run(() => downloadHandle.TryDownloadString(item.url, false, "")).Result;
if (String.IsNullOrEmpty(ruleSetsString)) if (string.IsNullOrEmpty(ruleSetsString))
continue; continue;
item.remarks = $"{template.version}-{item.remarks}"; item.remarks = $"{template.version}-{item.remarks}";
@ -1666,19 +1667,19 @@ namespace ServiceLib.Handler
item.sort = ++maxSort; item.sort = ++maxSort;
item.url = string.Empty; item.url = string.Empty;
AddBatchRoutingRules(ref item, ruleSetsString); await AddBatchRoutingRules(item, ruleSetsString);
//first rule as default at first startup //first rule as default at first startup
if (!blImportAdvancedRules && i == 0) if (!blImportAdvancedRules && i == 0)
{ {
SetDefaultRouting(config, item); await SetDefaultRouting(config, item);
} }
} }
return 0; return 0;
} }
public static int InitBuiltinRouting(Config config, bool blImportAdvancedRules = false) public static async Task<int> InitBuiltinRouting(Config config, bool blImportAdvancedRules = false)
{ {
var ver = "V3-"; var ver = "V3-";
var items = AppHandler.Instance.RoutingItems(); var items = AppHandler.Instance.RoutingItems();
@ -1695,7 +1696,7 @@ namespace ServiceLib.Handler
url = string.Empty, url = string.Empty,
sort = maxSort + 1, sort = maxSort + 1,
}; };
AddBatchRoutingRules(ref item2, Utils.GetEmbedText(Global.CustomRoutingFileName + "white")); await AddBatchRoutingRules(item2, Utils.GetEmbedText(Global.CustomRoutingFileName + "white"));
//Blacklist //Blacklist
var item3 = new RoutingItem() var item3 = new RoutingItem()
@ -1704,7 +1705,7 @@ namespace ServiceLib.Handler
url = string.Empty, url = string.Empty,
sort = maxSort + 2, sort = maxSort + 2,
}; };
AddBatchRoutingRules(ref item3, Utils.GetEmbedText(Global.CustomRoutingFileName + "black")); await AddBatchRoutingRules(item3, Utils.GetEmbedText(Global.CustomRoutingFileName + "black"));
//Global //Global
var item1 = new RoutingItem() var item1 = new RoutingItem()
@ -1713,11 +1714,11 @@ namespace ServiceLib.Handler
url = string.Empty, url = string.Empty,
sort = maxSort + 3, sort = maxSort + 3,
}; };
AddBatchRoutingRules(ref item1, Utils.GetEmbedText(Global.CustomRoutingFileName + "global")); await AddBatchRoutingRules(item1, Utils.GetEmbedText(Global.CustomRoutingFileName + "global"));
if (!blImportAdvancedRules) if (!blImportAdvancedRules)
{ {
SetDefaultRouting(config, item2); await SetDefaultRouting(config, item2);
} }
return 0; return 0;
} }
@ -1727,16 +1728,16 @@ namespace ServiceLib.Handler
return SQLiteHelper.Instance.Table<RoutingItem>().FirstOrDefault(it => it.locked == true); return SQLiteHelper.Instance.Table<RoutingItem>().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 #endregion Routing
#region DNS #region DNS
public static int InitBuiltinDNS(Config config) public static async Task<int> InitBuiltinDNS(Config config)
{ {
var items = AppHandler.Instance.DNSItems(); var items = AppHandler.Instance.DNSItems();
if (items.Count <= 0) if (items.Count <= 0)
@ -1746,20 +1747,20 @@ namespace ServiceLib.Handler
remarks = "V2ray", remarks = "V2ray",
coreType = ECoreType.Xray, coreType = ECoreType.Xray,
}; };
SaveDNSItems(config, item); await SaveDNSItems(config, item);
var item2 = new DNSItem() var item2 = new DNSItem()
{ {
remarks = "sing-box", remarks = "sing-box",
coreType = ECoreType.sing_box, coreType = ECoreType.sing_box,
}; };
SaveDNSItems(config, item2); await SaveDNSItems(config, item2);
} }
return 0; return 0;
} }
public static int SaveDNSItems(Config config, DNSItem item) public static async Task<int> SaveDNSItems(Config config, DNSItem item)
{ {
if (item == null) if (item == null)
{ {
@ -1771,7 +1772,7 @@ namespace ServiceLib.Handler
item.id = Utils.GetGuid(false); item.id = Utils.GetGuid(false);
} }
if (SQLiteHelper.Instance.Replace(item) > 0) if (await SQLiteHelper.Instance.ReplaceAsync(item) > 0)
{ {
return 0; return 0;
} }
@ -1787,17 +1788,17 @@ namespace ServiceLib.Handler
var downloadHandle = new DownloadService(); var downloadHandle = new DownloadService();
var templateContent = Task.Run(() => downloadHandle.TryDownloadString(url, true, "")).Result; var templateContent = Task.Run(() => downloadHandle.TryDownloadString(url, true, "")).Result;
if (String.IsNullOrEmpty(templateContent)) if (string.IsNullOrEmpty(templateContent))
return currentItem; return currentItem;
var template = JsonUtils.Deserialize<DNSItem>(templateContent); var template = JsonUtils.Deserialize<DNSItem>(templateContent);
if (template == null) if (template == null)
return currentItem; return currentItem;
if (!String.IsNullOrEmpty(template.normalDNS)) if (!string.IsNullOrEmpty(template.normalDNS))
template.normalDNS = Task.Run(() => downloadHandle.TryDownloadString(template.normalDNS, true, "")).Result; 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.tunDNS = Task.Run(() => downloadHandle.TryDownloadString(template.tunDNS, true, "")).Result;
template.id = currentItem.id; template.id = currentItem.id;
@ -1812,7 +1813,7 @@ namespace ServiceLib.Handler
#region Regional Presets #region Regional Presets
public static bool ApplyRegionalPreset(Config config, EPresetType type) public static async Task<bool> ApplyRegionalPreset(Config config, EPresetType type)
{ {
switch (type) switch (type)
{ {
@ -1821,8 +1822,8 @@ namespace ServiceLib.Handler
config.constItem.srsSourceUrl = ""; config.constItem.srsSourceUrl = "";
config.constItem.routeRulesTemplateSourceUrl = ""; config.constItem.routeRulesTemplateSourceUrl = "";
SQLiteHelper.Instance.DeleteAll<DNSItem>(); await SQLiteHelper.Instance.DeleteAllAsync<DNSItem>();
InitBuiltinDNS(config); await InitBuiltinDNS(config);
return true; return true;
@ -1831,8 +1832,8 @@ namespace ServiceLib.Handler
config.constItem.srsSourceUrl = Global.SingboxRulesetSources[1]; config.constItem.srsSourceUrl = Global.SingboxRulesetSources[1];
config.constItem.routeRulesTemplateSourceUrl = Global.RoutingRulesSources[1]; config.constItem.routeRulesTemplateSourceUrl = Global.RoutingRulesSources[1];
SaveDNSItems(config, GetExternalDNSItem(ECoreType.Xray, Global.DNSTemplateSources[1] + "v2ray.json")); await 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.sing_box, Global.DNSTemplateSources[1] + "sing_box.json"));
return true; return true;
} }

View file

@ -14,21 +14,20 @@ namespace ServiceLib.Handler
public ProfileExHandler() public ProfileExHandler()
{ {
Init();
Task.Run(async () => Task.Run(async () =>
{ {
await Init();
while (true) while (true)
{ {
SaveQueueIndexIds(); await SaveQueueIndexIds();
await Task.Delay(1000 * 600); 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<ProfileExItem>()); _lstProfileEx = new(SQLiteHelper.Instance.Table<ProfileExItem>());
} }
@ -41,7 +40,7 @@ namespace ServiceLib.Handler
} }
} }
private void SaveQueueIndexIds() private async Task SaveQueueIndexIds()
{ {
var cnt = _queIndexIds.Count; var cnt = _queIndexIds.Count;
if (cnt > 0) if (cnt > 0)
@ -72,10 +71,10 @@ namespace ServiceLib.Handler
try try
{ {
if (lstInserts.Count() > 0) if (lstInserts.Count() > 0)
SQLiteHelper.Instance.InsertAll(lstInserts); await SQLiteHelper.Instance.InsertAllAsync(lstInserts);
if (lstUpdates.Count() > 0) if (lstUpdates.Count() > 0)
SQLiteHelper.Instance.UpdateAll(lstUpdates); await SQLiteHelper.Instance.UpdateAllAsync(lstUpdates);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -97,17 +96,17 @@ namespace ServiceLib.Handler
IndexIdEnqueue(indexId); IndexIdEnqueue(indexId);
} }
public void ClearAll() public async Task ClearAll()
{ {
SQLiteHelper.Instance.Execute($"delete from ProfileExItem "); await SQLiteHelper.Instance.ExecuteAsync($"delete from ProfileExItem ");
_lstProfileEx = new(); _lstProfileEx = new();
} }
public void SaveTo() public async Task SaveTo()
{ {
try try
{ {
SaveQueueIndexIds(); await SaveQueueIndexIds();
} }
catch (Exception ex) catch (Exception ex)
{ {

View file

@ -25,8 +25,8 @@
InitData(); InitData();
_statisticsV2Ray = new StatisticsV2rayService(config, UpdateServerStat); _statisticsV2Ray = new StatisticsV2rayService(config, UpdateServerStatHandler);
_statisticsSingbox = new StatisticsSingboxService(config, UpdateServerStat); _statisticsSingbox = new StatisticsSingboxService(config, UpdateServerStatHandler);
} }
public void Close() 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; _serverStatItem = null;
_lstServerStat = new(); _lstServerStat = new();
} }
public void SaveTo() public async Task SaveTo()
{ {
try try
{ {
if (_lstServerStat != null) if (_lstServerStat != null)
{ {
SQLiteHelper.Instance.UpdateAll(_lstServerStat); await SQLiteHelper.Instance.UpdateAllAsync(_lstServerStat);
} }
} }
catch (Exception ex) 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; 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<ServerStatItem>().ToList(); _lstServerStat = SQLiteHelper.Instance.Table<ServerStatItem>().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) if (_serverStatItem is null)
{ {
@ -98,7 +103,7 @@
_updateFunc?.Invoke(server); _updateFunc?.Invoke(server);
} }
private void GetServerStatItem(string indexId) private async Task GetServerStatItem(string indexId)
{ {
long ticks = DateTime.Now.Date.Ticks; long ticks = DateTime.Now.Date.Ticks;
if (_serverStatItem != null && _serverStatItem.indexId != indexId) if (_serverStatItem != null && _serverStatItem.indexId != indexId)
@ -120,7 +125,7 @@
todayDown = 0, todayDown = 0,
dateNow = ticks dateNow = ticks
}; };
SQLiteHelper.Instance.Replace(_serverStatItem); await SQLiteHelper.Instance.ReplaceAsync(_serverStatItem);
_lstServerStat.Add(_serverStatItem); _lstServerStat.Add(_serverStatItem);
} }
} }

View file

@ -1,7 +1,4 @@
 using System.Runtime.InteropServices;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using static ServiceLib.Handler.SysProxy.ProxySettingWindows.InternetConnectionOption; using static ServiceLib.Handler.SysProxy.ProxySettingWindows.InternetConnectionOption;
namespace ServiceLib.Handler.SysProxy namespace ServiceLib.Handler.SysProxy

View file

@ -31,14 +31,14 @@
foreach (var item in lstSubs) foreach (var item in lstSubs)
{ {
updateHandle.UpdateSubscriptionProcess(config, item.id, true, (bool success, string msg) => await updateHandle.UpdateSubscriptionProcess(config, item.id, true, (bool success, string msg) =>
{ {
updateFunc?.Invoke(success, msg); updateFunc?.Invoke(success, msg);
if (success) if (success)
Logging.SaveLog("subscription" + msg); Logging.SaveLog("subscription" + msg);
}); });
item.updateTime = updateTime; item.updateTime = updateTime;
ConfigHandler.AddSubItem(config, item); await ConfigHandler.AddSubItem(config, item);
await Task.Delay(5000); await Task.Delay(5000);
} }

View file

@ -468,7 +468,7 @@ namespace ServiceLib.Services.CoreConfig
return 0; return 0;
} }
private int GenInbounds(SingboxConfig singboxConfig) private async Task<int> GenInbounds(SingboxConfig singboxConfig)
{ {
try try
{ {
@ -493,7 +493,7 @@ namespace ServiceLib.Services.CoreConfig
if (_config.routingBasicItem.enableRoutingAdvanced) if (_config.routingBasicItem.enableRoutingAdvanced)
{ {
var routing = ConfigHandler.GetDefaultRouting(_config); var routing = await ConfigHandler.GetDefaultRouting(_config);
if (Utils.IsNotEmpty(routing.domainStrategy4Singbox)) if (Utils.IsNotEmpty(routing.domainStrategy4Singbox))
{ {
inbound.domain_strategy = routing.domainStrategy4Singbox; inbound.domain_strategy = routing.domainStrategy4Singbox;
@ -899,7 +899,7 @@ namespace ServiceLib.Services.CoreConfig
return 0; return 0;
} }
private int GenRouting(SingboxConfig singboxConfig) private async Task<int> GenRouting(SingboxConfig singboxConfig)
{ {
try try
{ {
@ -952,7 +952,7 @@ namespace ServiceLib.Services.CoreConfig
if (_config.routingBasicItem.enableRoutingAdvanced) if (_config.routingBasicItem.enableRoutingAdvanced)
{ {
var routing = ConfigHandler.GetDefaultRouting(_config); var routing = await ConfigHandler.GetDefaultRouting(_config);
if (routing != null) if (routing != null)
{ {
var rules = JsonUtils.Deserialize<List<RulesItem>>(routing.ruleSet); var rules = JsonUtils.Deserialize<List<RulesItem>>(routing.ruleSet);
@ -1276,7 +1276,7 @@ namespace ServiceLib.Services.CoreConfig
return 0; return 0;
} }
private int ConvertGeo2Ruleset(SingboxConfig singboxConfig) private async Task<int> ConvertGeo2Ruleset(SingboxConfig singboxConfig)
{ {
static void AddRuleSets(List<string> ruleSets, List<string>? rule_set) static void AddRuleSets(List<string> ruleSets, List<string>? rule_set)
{ {
@ -1328,7 +1328,7 @@ namespace ServiceLib.Services.CoreConfig
List<Ruleset4Sbox> customRulesets = []; List<Ruleset4Sbox> customRulesets = [];
if (_config.routingBasicItem.enableRoutingAdvanced) if (_config.routingBasicItem.enableRoutingAdvanced)
{ {
var routing = ConfigHandler.GetDefaultRouting(_config); var routing = await ConfigHandler.GetDefaultRouting(_config);
if (Utils.IsNotEmpty(routing.customRulesetPath4Singbox)) if (Utils.IsNotEmpty(routing.customRulesetPath4Singbox))
{ {
var result = Utils.LoadResource(routing.customRulesetPath4Singbox); var result = Utils.LoadResource(routing.customRulesetPath4Singbox);

View file

@ -444,7 +444,7 @@ namespace ServiceLib.Services.CoreConfig
return inbound; return inbound;
} }
private int GenRouting(V2rayConfig v2rayConfig) private async Task<int> GenRouting(V2rayConfig v2rayConfig)
{ {
try try
{ {
@ -455,7 +455,7 @@ namespace ServiceLib.Services.CoreConfig
if (_config.routingBasicItem.enableRoutingAdvanced) if (_config.routingBasicItem.enableRoutingAdvanced)
{ {
var routing = ConfigHandler.GetDefaultRouting(_config); var routing = await ConfigHandler.GetDefaultRouting(_config);
if (routing != null) if (routing != null)
{ {
if (Utils.IsNotEmpty(routing.domainStrategy)) if (Utils.IsNotEmpty(routing.domainStrategy))

View file

@ -88,7 +88,7 @@ namespace ServiceLib.Services
UpdateFunc("", ResUI.SpeedtestingStop); UpdateFunc("", ResUI.SpeedtestingStop);
} }
private Task RunTcping() private async Task RunTcping()
{ {
try try
{ {
@ -123,13 +123,11 @@ namespace ServiceLib.Services
} }
finally finally
{ {
ProfileExHandler.Instance.SaveTo(); await ProfileExHandler.Instance.SaveTo();
}
} }
return Task.CompletedTask; private async Task RunRealPing()
}
private Task RunRealPing()
{ {
int pid = -1; int pid = -1;
try try
@ -140,7 +138,7 @@ namespace ServiceLib.Services
if (pid < 0) if (pid < 0)
{ {
UpdateFunc("", ResUI.FailedToRunCore); UpdateFunc("", ResUI.FailedToRunCore);
return Task.CompletedTask; return;
} }
DownloadService downloadHandle = new DownloadService(); DownloadService downloadHandle = new DownloadService();
@ -186,10 +184,8 @@ namespace ServiceLib.Services
{ {
CoreHandler.Instance.CoreStopPid(pid); CoreHandler.Instance.CoreStopPid(pid);
} }
ProfileExHandler.Instance.SaveTo(); await ProfileExHandler.Instance.SaveTo();
} }
return Task.CompletedTask;
} }
private async Task RunSpeedTestAsync() private async Task RunSpeedTestAsync()
@ -321,7 +317,7 @@ namespace ServiceLib.Services
CoreHandler.Instance.CoreStopPid(pid); CoreHandler.Instance.CoreStopPid(pid);
} }
UpdateFunc("", ResUI.SpeedtestingCompleted); UpdateFunc("", ResUI.SpeedtestingCompleted);
ProfileExHandler.Instance.SaveTo(); await ProfileExHandler.Instance.SaveTo();
} }
private async Task RunMixedtestAsync() private async Task RunMixedtestAsync()

View file

@ -120,7 +120,7 @@ namespace ServiceLib.Services
} }
} }
public void UpdateSubscriptionProcess(Config config, string subId, bool blProxy, Action<bool, string> updateFunc) public async Task UpdateSubscriptionProcess(Config config, string subId, bool blProxy, Action<bool, string> updateFunc)
{ {
_config = config; _config = config;
_updateFunc = updateFunc; _updateFunc = updateFunc;
@ -134,8 +134,6 @@ namespace ServiceLib.Services
return; return;
} }
Task.Run(async () =>
{
foreach (var item in subItem) foreach (var item in subItem)
{ {
string id = item.id.TrimEx(); string id = item.id.TrimEx();
@ -235,7 +233,7 @@ namespace ServiceLib.Services
_updateFunc?.Invoke(false, $"{hashCode}{result}"); _updateFunc?.Invoke(false, $"{hashCode}{result}");
} }
int ret = ConfigHandler.AddBatchServers(config, result, id, true); int ret = await ConfigHandler.AddBatchServers(config, result, id, true);
if (ret <= 0) if (ret <= 0)
{ {
Logging.SaveLog("FailedImportSubscription"); Logging.SaveLog("FailedImportSubscription");
@ -250,7 +248,6 @@ namespace ServiceLib.Services
} }
_updateFunc?.Invoke(true, $"{ResUI.MsgUpdateSubscriptionEnd}"); _updateFunc?.Invoke(true, $"{ResUI.MsgUpdateSubscriptionEnd}");
});
} }
public async Task UpdateGeoFileAll(Config config, Action<bool, string> updateFunc) public async Task UpdateGeoFileAll(Config config, Action<bool, string> updateFunc)
@ -498,12 +495,12 @@ namespace ServiceLib.Services
} }
} }
foreach(var item in geoipFiles.Distinct()) foreach (var item in geoipFiles.Distinct())
{ {
await UpdateSrsFile("geoip", item, config, updateFunc); await UpdateSrsFile("geoip", item, config, updateFunc);
} }
foreach(var item in geoSiteFiles.Distinct()) foreach (var item in geoSiteFiles.Distinct())
{ {
await UpdateSrsFile("geosite", item, config, updateFunc); await UpdateSrsFile("geosite", item, config, updateFunc);
} }

View file

@ -64,7 +64,7 @@ namespace ServiceLib.ViewModels
} }
SelectedSource.coreType = CoreType.IsNullOrEmpty() ? null : (ECoreType)Enum.Parse(typeof(ECoreType), CoreType); 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); NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); _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)) if (Utils.IsNullOrEmpty(fileName))
{ {
@ -85,7 +85,7 @@ namespace ServiceLib.ViewModels
var item = AppHandler.Instance.GetProfileItem(SelectedSource.indexId); var item = AppHandler.Instance.GetProfileItem(SelectedSource.indexId);
item ??= SelectedSource; item ??= SelectedSource;
item.address = fileName; item.address = fileName;
if (ConfigHandler.AddCustomServer(_config, item, false) == 0) if (await ConfigHandler.AddCustomServer(_config, item, false) == 0)
{ {
NoticeHandler.Instance.Enqueue(ResUI.SuccessfullyImportedCustomServer); NoticeHandler.Instance.Enqueue(ResUI.SuccessfullyImportedCustomServer);
if (Utils.IsNotEmpty(item.indexId)) if (Utils.IsNotEmpty(item.indexId))

View file

@ -84,7 +84,7 @@ namespace ServiceLib.ViewModels
} }
SelectedSource.coreType = CoreType.IsNullOrEmpty() ? null : (ECoreType)Enum.Parse(typeof(ECoreType), CoreType); 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); NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); _updateView?.Invoke(EViewAction.CloseWindow, null);

View file

@ -51,7 +51,7 @@ namespace ServiceLib.ViewModels
{ {
DisplayOperationMsg(); DisplayOperationMsg();
_config.webDavItem = SelectedSource; _config.webDavItem = SelectedSource;
ConfigHandler.SaveConfig(_config); await ConfigHandler.SaveConfig(_config);
var result = await WebDavHandler.Instance.CheckConnection(); var result = await WebDavHandler.Instance.CheckConnection();
if (result) if (result)

View file

@ -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<ConnectionItem>? connections) public void RefreshConnections(List<ConnectionItem>? connections)
@ -140,7 +138,7 @@ namespace ServiceLib.ViewModels
model.uploadTraffic = $"{Utils.HumanFy((long)item.upload)}"; model.uploadTraffic = $"{Utils.HumanFy((long)item.upload)}";
model.downloadTraffic = $"{Utils.HumanFy((long)item.download)}"; model.downloadTraffic = $"{Utils.HumanFy((long)item.download)}";
model.elapsed = sp.ToString(@"hh\:mm\:ss"); 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); lstModel.Add(model);
} }
@ -193,8 +191,8 @@ namespace ServiceLib.ViewModels
{ {
_connectionItems.Clear(); _connectionItems.Clear();
} }
ClashApiHandler.Instance.ClashConnectionClose(id); await ClashApiHandler.Instance.ClashConnectionClose(id);
GetClashConnections(); await GetClashConnections();
} }
} }
} }

View file

@ -138,18 +138,18 @@ namespace ServiceLib.ViewModels
public async Task ProxiesReload() public async Task ProxiesReload()
{ {
GetClashProxies(true); await GetClashProxies(true);
ProxiesDelayTest(); await ProxiesDelayTest();
} }
public async Task ProxiesDelayTest() public async Task ProxiesDelayTest()
{ {
ProxiesDelayTest(true); await ProxiesDelayTest(true);
} }
#region proxy function #region proxy function
private void SetRuleMode(ERuleMode mode) private async Task SetRuleMode(ERuleMode mode)
{ {
_config.clashUIItem.ruleMode = mode; _config.clashUIItem.ruleMode = mode;
@ -159,27 +159,24 @@ namespace ServiceLib.ViewModels
{ {
{ "mode", mode.ToString().ToLower() } { "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;
if (_proxies == null)
{ {
return; return;
} }
_proxies = ret.Item1.proxies;
_providers = ret?.Item2.providers;
if (refreshUI) if (refreshUI)
{ {
_updateView?.Invoke(EViewAction.DispatcherRefreshProxyGroups, null); _updateView?.Invoke(EViewAction.DispatcherRefreshProxyGroups, null);
} }
});
} }
public void RefreshProxyGroups() public void RefreshProxyGroups()
@ -365,7 +362,7 @@ namespace ServiceLib.ViewModels
return; return;
} }
ClashApiHandler.Instance.ClashSetActiveProxy(name, nameNode); await ClashApiHandler.Instance.ClashSetActiveProxy(name, nameNode);
selectedProxy.now = nameNode; selectedProxy.now = nameNode;
var group = _proxyGroups.Where(it => it.name == SelectedGroup.name).FirstOrDefault(); var group = _proxyGroups.Where(it => it.name == SelectedGroup.name).FirstOrDefault();
@ -420,7 +417,7 @@ namespace ServiceLib.ViewModels
else else
{ {
detail.delay = _delayTimeout; detail.delay = _delayTimeout;
detail.delayName = String.Empty; detail.delayName = string.Empty;
} }
_proxyDetails.Replace(detail, JsonUtils.DeepCopy(detail)); _proxyDetails.Replace(detail, JsonUtils.DeepCopy(detail));
} }
@ -435,7 +432,7 @@ namespace ServiceLib.ViewModels
var lastTime = DateTime.Now; var lastTime = DateTime.Now;
Observable.Interval(TimeSpan.FromSeconds(60)) Observable.Interval(TimeSpan.FromSeconds(60))
.Subscribe(x => .Subscribe(async x =>
{ {
if (!(AutoRefresh && _config.uiItem.showInTaskbar && _config.IsRunningCore(ECoreType.sing_box))) 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) if ((dtNow - lastTime).Minutes % _config.clashUIItem.proxiesAutoDelayTestInterval == 0)
{ {
ProxiesDelayTest(); await ProxiesDelayTest();
lastTime = dtNow; lastTime = dtNow;
} }
Task.Delay(1000).Wait(); Task.Delay(1000).Wait();

View file

@ -286,8 +286,8 @@ namespace ServiceLib.ViewModels
await SysProxyHandler.UpdateSysProxy(_config, true); await SysProxyHandler.UpdateSysProxy(_config, true);
ConfigHandler.SaveConfig(_config); ConfigHandler.SaveConfig(_config);
ProfileExHandler.Instance.SaveTo(); await ProfileExHandler.Instance.SaveTo();
StatisticsHandler.Instance.SaveTo(); await StatisticsHandler.Instance.SaveTo();
StatisticsHandler.Instance.Close(); StatisticsHandler.Instance.Close();
CoreHandler.Instance.CoreStop(); CoreHandler.Instance.CoreStop();
@ -383,7 +383,7 @@ namespace ServiceLib.ViewModels
await _updateView?.Invoke(EViewAction.AddServerViaClipboard, null); await _updateView?.Invoke(EViewAction.AddServerViaClipboard, null);
return; return;
} }
int ret = ConfigHandler.AddBatchServers(_config, clipboardData, _config.subIndexId, false); int ret = await ConfigHandler.AddBatchServers(_config, clipboardData, _config.subIndexId, false);
if (ret > 0) if (ret > 0)
{ {
RefreshSubscriptions(); RefreshSubscriptions();
@ -427,7 +427,7 @@ namespace ServiceLib.ViewModels
} }
else else
{ {
int ret = ConfigHandler.AddBatchServers(_config, result, _config.subIndexId, false); int ret = await ConfigHandler.AddBatchServers(_config, result, _config.subIndexId, false);
if (ret > 0) if (ret > 0)
{ {
RefreshSubscriptions(); RefreshSubscriptions();
@ -451,7 +451,7 @@ namespace ServiceLib.ViewModels
public async Task UpdateSubscriptionProcess(string subId, bool blProxy) 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 #endregion Subscription
@ -552,7 +552,7 @@ namespace ServiceLib.ViewModels
private async Task LoadCore() private async Task LoadCore()
{ {
await Task.Run(() => await Task.Run(async () =>
{ {
//if (_config.tunModeItem.enableTun) //if (_config.tunModeItem.enableTun)
//{ //{
@ -560,7 +560,7 @@ namespace ServiceLib.ViewModels
// WindowsUtils.RemoveTunDevice(); // WindowsUtils.RemoveTunDevice();
//} //}
var node = ConfigHandler.GetDefaultServer(_config); var node = await ConfigHandler.GetDefaultServer(_config);
CoreHandler.Instance.LoadCore(node); CoreHandler.Instance.LoadCore(node);
}); });
} }
@ -590,7 +590,7 @@ namespace ServiceLib.ViewModels
public async Task ApplyRegionalPreset(EPresetType type) public async Task ApplyRegionalPreset(EPresetType type)
{ {
ConfigHandler.ApplyRegionalPreset(_config, type); await ConfigHandler.ApplyRegionalPreset(_config, type);
ConfigHandler.InitRouting(_config); ConfigHandler.InitRouting(_config);
Locator.Current.GetService<StatusBarViewModel>()?.RefreshRoutingsMenu(); Locator.Current.GetService<StatusBarViewModel>()?.RefreshRoutingsMenu();

View file

@ -341,7 +341,7 @@ namespace ServiceLib.ViewModels
//coreType //coreType
SaveCoreType(); SaveCoreType();
if (ConfigHandler.SaveConfig(_config) == 0) if (await ConfigHandler.SaveConfig(_config) == 0)
{ {
if (needReboot) if (needReboot)
{ {

View file

@ -479,7 +479,7 @@ namespace ServiceLib.ViewModels
private async Task RemoveDuplicateServer() private async Task RemoveDuplicateServer()
{ {
var tuple = ConfigHandler.DedupServerList(_config, _config.subIndexId); var tuple = await ConfigHandler.DedupServerList(_config, _config.subIndexId);
RefreshServers(); RefreshServers();
Reload(); Reload();
NoticeHandler.Instance.Enqueue(string.Format(ResUI.RemoveDuplicateServerResult, tuple.Item1, tuple.Item2)); NoticeHandler.Instance.Enqueue(string.Format(ResUI.RemoveDuplicateServerResult, tuple.Item1, tuple.Item2));
@ -491,7 +491,7 @@ namespace ServiceLib.ViewModels
{ {
return; return;
} }
if (ConfigHandler.CopyServer(_config, lstSelecteds) == 0) if (await ConfigHandler.CopyServer(_config, lstSelecteds) == 0)
{ {
RefreshServers(); RefreshServers();
NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess);
@ -524,7 +524,7 @@ namespace ServiceLib.ViewModels
return; return;
} }
if (ConfigHandler.SetDefaultServerIndex(_config, indexId) == 0) if (await ConfigHandler.SetDefaultServerIndex(_config, indexId) == 0)
{ {
RefreshServers(); RefreshServers();
Reload(); Reload();
@ -572,19 +572,20 @@ namespace ServiceLib.ViewModels
return; 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); NoticeHandler.Instance.Enqueue(ResUI.OperationFailed);
return; return;
} }
if (indexId == _config.indexId) if (ret.Item2 == _config.indexId)
{ {
RefreshServers(); RefreshServers();
Reload(); Reload();
} }
else else
{ {
await SetDefaultServer(indexId); await SetDefaultServer(ret.Item2);
} }
} }
@ -597,7 +598,7 @@ namespace ServiceLib.ViewModels
_dicHeaderSort.TryAdd(colName, true); _dicHeaderSort.TryAdd(colName, true);
_dicHeaderSort.TryGetValue(colName, out bool asc); _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; return;
} }
@ -640,18 +641,18 @@ namespace ServiceLib.ViewModels
{ {
return; return;
} }
if (ConfigHandler.MoveServer(_config, ref _lstProfile, index, eMove) == 0) if (await ConfigHandler.MoveServer(_config, _lstProfile, index, eMove) == 0)
{ {
RefreshServers(); RefreshServers();
} }
} }
public void MoveServerTo(int startIndex, ProfileItemModel targetItem) public async Task MoveServerTo(int startIndex, ProfileItemModel targetItem)
{ {
var targetIndex = _profileItems.IndexOf(targetItem); var targetIndex = _profileItems.IndexOf(targetItem);
if (startIndex >= 0 && targetIndex >= 0 && startIndex != targetIndex) 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(); RefreshServers();
} }

View file

@ -215,7 +215,7 @@ namespace ServiceLib.ViewModels
return; return;
} }
var index = _rules.IndexOf(item); var index = _rules.IndexOf(item);
if (ConfigHandler.MoveRoutingRule(_rules, index, eMove) == 0) if (await ConfigHandler.MoveRoutingRule(_rules, index, eMove) == 0)
{ {
RefreshRulesItems(); RefreshRulesItems();
} }
@ -237,7 +237,7 @@ namespace ServiceLib.ViewModels
item.ruleNum = _rules.Count; item.ruleNum = _rules.Count;
item.ruleSet = JsonUtils.Serialize(_rules, false); item.ruleSet = JsonUtils.Serialize(_rules, false);
if (ConfigHandler.SaveRoutingItem(_config, item) == 0) if (await ConfigHandler.SaveRoutingItem(_config, item) == 0)
{ {
NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); _updateView?.Invoke(EViewAction.CloseWindow, null);

View file

@ -120,7 +120,7 @@ namespace ServiceLib.ViewModels
#region locked #region locked
private void BindingLockedData() private async Task BindingLockedData()
{ {
_lockedItem = ConfigHandler.GetLockedRoutingItem(_config); _lockedItem = ConfigHandler.GetLockedRoutingItem(_config);
if (_lockedItem == null) if (_lockedItem == null)
@ -131,7 +131,7 @@ namespace ServiceLib.ViewModels
url = string.Empty, url = string.Empty,
locked = true, locked = true,
}; };
ConfigHandler.AddBatchRoutingRules(ref _lockedItem, Utils.GetEmbedText(Global.CustomRoutingFileName + "locked")); await ConfigHandler.AddBatchRoutingRules(_lockedItem, Utils.GetEmbedText(Global.CustomRoutingFileName + "locked"));
} }
if (_lockedItem != null) if (_lockedItem != null)
@ -208,7 +208,7 @@ namespace ServiceLib.ViewModels
EndBindingLockedData(); EndBindingLockedData();
if (ConfigHandler.SaveConfig(_config) == 0) if (await ConfigHandler.SaveConfig(_config) == 0)
{ {
NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); _updateView?.Invoke(EViewAction.CloseWindow, null);
@ -288,7 +288,7 @@ namespace ServiceLib.ViewModels
return; return;
} }
if (ConfigHandler.SetDefaultRouting(_config, item) == 0) if (await ConfigHandler.SetDefaultRouting(_config, item) == 0)
{ {
RefreshRoutingItems(); RefreshRoutingItems();
IsModified = true; IsModified = true;
@ -297,7 +297,7 @@ namespace ServiceLib.ViewModels
private async Task RoutingAdvancedImportRules() private async Task RoutingAdvancedImportRules()
{ {
if (ConfigHandler.InitRouting(_config, true) == 0) if (await ConfigHandler.InitRouting(_config, true) == 0)
{ {
RefreshRoutingItems(); RefreshRoutingItems();
IsModified = true; IsModified = true;

View file

@ -220,12 +220,12 @@ namespace ServiceLib.ViewModels
if (service != null) await service.UpdateSubscriptionProcess("", blProxy); if (service != null) await service.UpdateSubscriptionProcess("", blProxy);
} }
public void RefreshServersBiz() public async Task RefreshServersBiz()
{ {
RefreshServersMenu(); RefreshServersMenu();
//display running server //display running server
var running = ConfigHandler.GetDefaultServer(_config); var running = await ConfigHandler.GetDefaultServer(_config);
if (running != null) if (running != null)
{ {
RunningServerDisplay = RunningServerDisplay =
@ -283,7 +283,7 @@ namespace ServiceLib.ViewModels
public async Task TestServerAvailability() public async Task TestServerAvailability()
{ {
var item = ConfigHandler.GetDefaultServer(_config); var item = await ConfigHandler.GetDefaultServer(_config);
if (item == null) if (item == null)
{ {
return; return;
@ -379,7 +379,7 @@ namespace ServiceLib.ViewModels
return; return;
} }
if (ConfigHandler.SetDefaultRouting(_config, item) == 0) if (await ConfigHandler.SetDefaultRouting(_config, item) == 0)
{ {
NoticeHandler.Instance.SendMessageEx(ResUI.TipChangeRouting); NoticeHandler.Instance.SendMessageEx(ResUI.TipChangeRouting);
Locator.Current.GetService<MainWindowViewModel>()?.Reload(); Locator.Current.GetService<MainWindowViewModel>()?.Reload();

View file

@ -41,7 +41,7 @@ namespace ServiceLib.ViewModels
return; return;
} }
if (ConfigHandler.AddSubItem(_config, SelectedSource) == 0) if (await ConfigHandler.AddSubItem(_config, SelectedSource) == 0)
{ {
NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null); _updateView?.Invoke(EViewAction.CloseWindow, null);

View file

@ -9,14 +9,14 @@ namespace v2rayN.Handler
private static readonly Lazy<WindowsHandler> instance = new(() => new()); private static readonly Lazy<WindowsHandler> instance = new(() => new());
public static WindowsHandler Instance => instance.Value; public static WindowsHandler Instance => instance.Value;
public Icon GetNotifyIcon(Config config) public async Task<Icon> GetNotifyIcon(Config config)
{ {
try try
{ {
int index = (int)config.systemProxyItem.sysProxyType; int index = (int)config.systemProxyItem.sysProxyType;
//Load from routing setting //Load from routing setting
var createdIcon = GetNotifyIcon4Routing(config); var createdIcon = await GetNotifyIcon4Routing(config);
if (createdIcon != null) if (createdIcon != null)
{ {
return createdIcon; return createdIcon;
@ -65,7 +65,7 @@ namespace v2rayN.Handler
return BitmapFrame.Create(new Uri($"pack://application:,,,/Resources/NotifyIcon{index}.ico", UriKind.RelativeOrAbsolute)); return BitmapFrame.Create(new Uri($"pack://application:,,,/Resources/NotifyIcon{index}.ico", UriKind.RelativeOrAbsolute));
} }
private Icon? GetNotifyIcon4Routing(Config config) private async Task<Icon?> GetNotifyIcon4Routing(Config config)
{ {
try try
{ {
@ -74,7 +74,7 @@ namespace v2rayN.Handler
return null; return null;
} }
var item = ConfigHandler.GetDefaultRouting(config); var item = await ConfigHandler.GetDefaultRouting(config);
if (item == null || Utils.IsNullOrEmpty(item.customIcon) || !File.Exists(item.customIcon)) if (item == null || Utils.IsNullOrEmpty(item.customIcon) || !File.Exists(item.customIcon))
{ {
return null; return null;

View file

@ -103,7 +103,7 @@ namespace v2rayN.Views
{ {
_config.globalHotkeys = _TextBoxKeyEventItem.Values.ToList(); _config.globalHotkeys = _TextBoxKeyEventItem.Values.ToList();
if (ConfigHandler.SaveConfig(_config, false) == 0) if ( ConfigHandler.SaveConfig(_config, false).Result == 0)
{ {
HotkeyHandler.Instance.ReLoad(); HotkeyHandler.Instance.ReLoad();
this.DialogResult = true; this.DialogResult = true;

View file

@ -90,9 +90,9 @@ namespace v2rayN.Views
break; break;
case EViewAction.DispatcherRefreshIcon: 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); Application.Current.MainWindow.Icon = WindowsHandler.Instance.GetAppIcon(_config);
}), DispatcherPriority.Normal); }), DispatcherPriority.Normal);
break; break;