Refactoring Project

This commit is contained in:
2dust
2024-08-20 14:15:29 +08:00
parent 61bea05f63
commit 8d1d10b783
53 changed files with 278 additions and 249 deletions
@@ -0,0 +1,11 @@
using ReactiveUI;
namespace ServiceLib.Base
{
public class MyReactiveObject : ReactiveObject
{
protected static Config? _config;
protected Func<EViewAction, object?, bool>? _updateView;
protected NoticeHandler? _noticeHandler;
}
}
+1
View File
@@ -366,6 +366,7 @@ namespace ServiceLib.Common
public static bool IsBase64String(string plainText)
{
if(plainText.IsNullOrEmpty()) return false;
var buffer = new Span<byte>(new byte[plainText.Length]);
return Convert.TryFromBase64String(plainText, buffer, out int _);
}
+4
View File
@@ -7,6 +7,10 @@
SaveFileDialog,
AddBatchRoutingRulesYesNo,
AdjustMainLvColWidth,
UpdateSysProxy,
SetClipboardData,
AddServerViaClipboard,
ImportRulesFromClipboard,
ProfilesFocus,
ShareSub,
ShareServer,
+3
View File
@@ -0,0 +1,3 @@
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<ReactiveUI />
</Weavers>
+1
View File
@@ -71,6 +71,7 @@
public const int MaxPort = 65536;
public const string CommandClearMsg = "CommandClearMsg";
public const string CommandSendMsgView = "CommandSendMsgView";
public const string CommandSendSnackMsg = "CommandSendSnackMsg";
public const string CommandStopSpeedTest = "CommandStopSpeedTest";
public const string CommandRefreshProfiles = "CommandRefreshProfiles";
public const string DelayUnit = "";
+6 -2
View File
@@ -1,7 +1,11 @@
global using ServiceLib.Common;
global using ServiceLib.Enums;
global using ServiceLib;
global using ServiceLib.Base;
global using ServiceLib.Common;
global using ServiceLib.Handler;
global using ServiceLib.Handler.CoreConfig;
global using ServiceLib.Handler.Fmt;
global using ServiceLib.Handler.Statistics;
global using ServiceLib.Enums;
global using ServiceLib.Models;
global using ServiceLib.ViewModels;
global using ServiceLib.Resx;
@@ -1406,6 +1406,10 @@ namespace ServiceLib.Handler
public static int AddBatchServers(Config config, string strData, string subid, bool isSub)
{
if (Utils.IsNullOrEmpty(strData))
{
return -1;
}
List<ProfileItem>? lstOriSub = null;
if (isSub && !Utils.IsNullOrEmpty(subid))
{
+9 -3
View File
@@ -1,4 +1,6 @@
namespace ServiceLib.Handler
using System.Runtime.InteropServices;
namespace ServiceLib.Handler
{
public sealed class LazyConfig
{
@@ -28,7 +30,7 @@
}
}
private Job _processJob = new();
private Job? _processJob;
public LazyConfig()
{
@@ -52,7 +54,11 @@
public void AddProcess(IntPtr processHandle)
{
_processJob.AddProcess(processHandle);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_processJob ??= new();
_processJob?.AddProcess(processHandle);
}
}
#endregion Config
@@ -0,0 +1,41 @@
using ReactiveUI;
namespace ServiceLib.Handler
{
public class NoticeHandler
{
public void Enqueue(string? content)
{
if (content.IsNullOrEmpty())
{
return;
}
MessageBus.Current.SendMessage(content, Global.CommandSendSnackMsg);
}
public void SendMessage(string? content)
{
if (content.IsNullOrEmpty())
{
return;
}
MessageBus.Current.SendMessage(content, Global.CommandSendMsgView);
}
public void SendMessage(string? content, bool time)
{
if (content.IsNullOrEmpty())
{
return;
}
content = $"{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")} {content}";
SendMessage(content);
}
public void SendMessageAndEnqueue(string? msg)
{
Enqueue(msg);
SendMessage(msg);
}
}
}
+2
View File
@@ -8,6 +8,8 @@
<ItemGroup>
<PackageReference Include="Downloader" Version="3.1.2" />
<PackageReference Include="ReactiveUI" Version="20.1.1" />
<PackageReference Include="ReactiveUI.Fody" Version="19.5.41" />
<PackageReference Include="sqlite-net-pcl" Version="1.9.172" />
<PackageReference Include="Splat.NLog" Version="15.1.1" />
<PackageReference Include="YamlDotNet" Version="16.0.0" />
@@ -0,0 +1,120 @@
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
namespace ServiceLib.ViewModels
{
public class AddServer2ViewModel : MyReactiveObject
{
[Reactive]
public ProfileItem SelectedSource { get; set; }
public ReactiveCommand<Unit, Unit> BrowseServerCmd { get; }
public ReactiveCommand<Unit, Unit> EditServerCmd { get; }
public ReactiveCommand<Unit, Unit> SaveServerCmd { get; }
public bool IsModified { get; set; }
public AddServer2ViewModel(ProfileItem profileItem, Func<EViewAction, object?, bool>? updateView)
{
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_config = LazyConfig.Instance.Config;
_updateView = updateView;
if (profileItem.indexId.IsNullOrEmpty())
{
SelectedSource = profileItem;
}
else
{
SelectedSource = JsonUtils.DeepCopy(profileItem);
}
BrowseServerCmd = ReactiveCommand.Create(() =>
{
_updateView?.Invoke(EViewAction.BrowseServer, null);
});
EditServerCmd = ReactiveCommand.Create(() =>
{
EditServer();
});
SaveServerCmd = ReactiveCommand.Create(() =>
{
SaveServer();
});
}
private void SaveServer()
{
string remarks = SelectedSource.remarks;
if (Utils.IsNullOrEmpty(remarks))
{
_noticeHandler?.Enqueue(ResUI.PleaseFillRemarks);
return;
}
if (Utils.IsNullOrEmpty(SelectedSource.address))
{
_noticeHandler?.Enqueue(ResUI.FillServerAddressCustom);
return;
}
if (ConfigHandler.EditCustomServer(_config, SelectedSource) == 0)
{
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null);
}
else
{
_noticeHandler?.Enqueue(ResUI.OperationFailed);
}
}
public void BrowseServer(string fileName)
{
if (Utils.IsNullOrEmpty(fileName))
{
return;
}
var item = LazyConfig.Instance.GetProfileItem(SelectedSource.indexId);
item ??= SelectedSource;
item.address = fileName;
if (ConfigHandler.AddCustomServer(_config, item, false) == 0)
{
_noticeHandler?.Enqueue(ResUI.SuccessfullyImportedCustomServer);
if (!Utils.IsNullOrEmpty(item.indexId))
{
SelectedSource = JsonUtils.DeepCopy(item);
}
IsModified = true;
}
else
{
_noticeHandler?.Enqueue(ResUI.FailedImportedCustomServer);
}
}
private void EditServer()
{
var address = SelectedSource.address;
if (Utils.IsNullOrEmpty(address))
{
_noticeHandler?.Enqueue(ResUI.FillServerAddressCustom);
return;
}
address = Utils.GetConfigPath(address);
if (File.Exists(address))
{
Utils.ProcessStart(address);
}
else
{
_noticeHandler?.Enqueue(ResUI.FailedReadConfiguration);
}
}
}
}
@@ -0,0 +1,94 @@
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
namespace ServiceLib.ViewModels
{
public class AddServerViewModel : MyReactiveObject
{
[Reactive]
public ProfileItem SelectedSource { get; set; }
public ReactiveCommand<Unit, Unit> SaveCmd { get; }
public AddServerViewModel(ProfileItem profileItem, Func<EViewAction, object?, bool>? updateView)
{
_config = LazyConfig.Instance.Config;
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_updateView = updateView;
if (profileItem.id.IsNullOrEmpty())
{
profileItem.network = Global.DefaultNetwork;
profileItem.headerType = Global.None;
profileItem.requestHost = "";
profileItem.streamSecurity = "";
SelectedSource = profileItem;
}
else
{
SelectedSource = JsonUtils.DeepCopy(profileItem);
}
SaveCmd = ReactiveCommand.Create(() =>
{
SaveServer();
});
}
private void SaveServer()
{
if (Utils.IsNullOrEmpty(SelectedSource.remarks))
{
_noticeHandler?.Enqueue(ResUI.PleaseFillRemarks);
return;
}
if (Utils.IsNullOrEmpty(SelectedSource.address))
{
_noticeHandler?.Enqueue(ResUI.FillServerAddress);
return;
}
var port = SelectedSource.port.ToString();
if (Utils.IsNullOrEmpty(port) || !Utils.IsNumeric(port)
|| SelectedSource.port <= 0 || SelectedSource.port >= Global.MaxPort)
{
_noticeHandler?.Enqueue(ResUI.FillCorrectServerPort);
return;
}
if (SelectedSource.configType == EConfigType.Shadowsocks)
{
if (Utils.IsNullOrEmpty(SelectedSource.id))
{
_noticeHandler?.Enqueue(ResUI.FillPassword);
return;
}
if (Utils.IsNullOrEmpty(SelectedSource.security))
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectEncryption);
return;
}
}
if (SelectedSource.configType != EConfigType.Socks
&& SelectedSource.configType != EConfigType.Http)
{
if (Utils.IsNullOrEmpty(SelectedSource.id))
{
_noticeHandler?.Enqueue(ResUI.FillUUID);
return;
}
}
if (ConfigHandler.AddServer(_config, SelectedSource) == 0)
{
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null);
}
else
{
_noticeHandler?.Enqueue(ResUI.OperationFailed);
}
}
}
}
@@ -0,0 +1,191 @@
using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System.Reactive;
using System.Reactive.Linq;
namespace ServiceLib.ViewModels
{
public class ClashConnectionsViewModel : MyReactiveObject
{
private IObservableCollection<ClashConnectionModel> _connectionItems = new ObservableCollectionExtended<ClashConnectionModel>();
public IObservableCollection<ClashConnectionModel> ConnectionItems => _connectionItems;
[Reactive]
public ClashConnectionModel SelectedSource { get; set; }
public ReactiveCommand<Unit, Unit> ConnectionCloseCmd { get; }
public ReactiveCommand<Unit, Unit> ConnectionCloseAllCmd { get; }
[Reactive]
public int SortingSelected { get; set; }
[Reactive]
public bool AutoRefresh { get; set; }
public ClashConnectionsViewModel(Func<EViewAction, object?, bool>? updateView)
{
_config = LazyConfig.Instance.Config;
_updateView = updateView;
SortingSelected = _config.clashUIItem.connectionsSorting;
AutoRefresh = _config.clashUIItem.connectionsAutoRefresh;
var canEditRemove = this.WhenAnyValue(
x => x.SelectedSource,
selectedSource => selectedSource != null && !string.IsNullOrEmpty(selectedSource.id));
this.WhenAnyValue(
x => x.SortingSelected,
y => y >= 0)
.Subscribe(c => DoSortingSelected(c));
this.WhenAnyValue(
x => x.AutoRefresh,
y => y == true)
.Subscribe(c => { _config.clashUIItem.connectionsAutoRefresh = AutoRefresh; });
ConnectionCloseCmd = ReactiveCommand.Create(() =>
{
ClashConnectionClose(false);
}, canEditRemove);
ConnectionCloseAllCmd = ReactiveCommand.Create(() =>
{
ClashConnectionClose(true);
});
Init();
}
private void DoSortingSelected(bool c)
{
if (!c)
{
return;
}
if (SortingSelected != _config.clashUIItem.connectionsSorting)
{
_config.clashUIItem.connectionsSorting = SortingSelected;
}
GetClashConnections();
}
private void Init()
{
var lastTime = DateTime.Now;
Observable.Interval(TimeSpan.FromSeconds(10))
.Subscribe(x =>
{
if (!(AutoRefresh && _config.uiItem.showInTaskbar && _config.IsRunningCore(ECoreType.clash)))
{
return;
}
var dtNow = DateTime.Now;
if (_config.clashUIItem.connectionsRefreshInterval > 0)
{
if ((dtNow - lastTime).Minutes % _config.clashUIItem.connectionsRefreshInterval == 0)
{
GetClashConnections();
lastTime = dtNow;
}
Task.Delay(1000).Wait();
}
});
}
private void GetClashConnections()
{
ClashApiHandler.Instance.GetClashConnections(_config, (it) =>
{
if (it == null)
{
return;
}
_updateView?.Invoke(EViewAction.DispatcherRefreshConnections, it?.connections);
});
}
public void RefreshConnections(List<ConnectionItem>? connections)
{
_connectionItems.Clear();
var dtNow = DateTime.Now;
var lstModel = new List<ClashConnectionModel>();
foreach (var item in connections ?? [])
{
ClashConnectionModel model = new();
model.id = item.id;
model.network = item.metadata.network;
model.type = item.metadata.type;
model.host = $"{(string.IsNullOrEmpty(item.metadata.host) ? item.metadata.destinationIP : item.metadata.host)}:{item.metadata.destinationPort}";
var sp = (dtNow - item.start);
model.time = sp.TotalSeconds < 0 ? 1 : sp.TotalSeconds;
model.upload = item.upload;
model.download = item.download;
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;
lstModel.Add(model);
}
if (lstModel.Count <= 0) { return; }
//sort
switch (SortingSelected)
{
case 0:
lstModel = lstModel.OrderBy(t => t.upload / t.time).ToList();
break;
case 1:
lstModel = lstModel.OrderBy(t => t.download / t.time).ToList();
break;
case 2:
lstModel = lstModel.OrderBy(t => t.upload).ToList();
break;
case 3:
lstModel = lstModel.OrderBy(t => t.download).ToList();
break;
case 4:
lstModel = lstModel.OrderBy(t => t.time).ToList();
break;
case 5:
lstModel = lstModel.OrderBy(t => t.host).ToList();
break;
}
_connectionItems.AddRange(lstModel);
}
public void ClashConnectionClose(bool all)
{
var id = string.Empty;
if (!all)
{
var item = SelectedSource;
if (item is null)
{
return;
}
id = item.id;
}
else
{
_connectionItems.Clear();
}
ClashApiHandler.Instance.ClashConnectionClose(id);
GetClashConnections();
}
}
}
@@ -0,0 +1,461 @@
using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
using System.Reactive.Linq;
using static ServiceLib.Models.ClashProviders;
using static ServiceLib.Models.ClashProxies;
namespace ServiceLib.ViewModels
{
public class ClashProxiesViewModel : MyReactiveObject
{
private Dictionary<String, ProxiesItem>? _proxies;
private Dictionary<String, ProvidersItem>? _providers;
private int _delayTimeout = 99999999;
private IObservableCollection<ClashProxyModel> _proxyGroups = new ObservableCollectionExtended<ClashProxyModel>();
private IObservableCollection<ClashProxyModel> _proxyDetails = new ObservableCollectionExtended<ClashProxyModel>();
public IObservableCollection<ClashProxyModel> ProxyGroups => _proxyGroups;
public IObservableCollection<ClashProxyModel> ProxyDetails => _proxyDetails;
[Reactive]
public ClashProxyModel SelectedGroup { get; set; }
[Reactive]
public ClashProxyModel SelectedDetail { get; set; }
public ReactiveCommand<Unit, Unit> ProxiesReloadCmd { get; }
public ReactiveCommand<Unit, Unit> ProxiesDelaytestCmd { get; }
public ReactiveCommand<Unit, Unit> ProxiesDelaytestPartCmd { get; }
public ReactiveCommand<Unit, Unit> ProxiesSelectActivityCmd { get; }
[Reactive]
public int RuleModeSelected { get; set; }
[Reactive]
public int SortingSelected { get; set; }
[Reactive]
public bool AutoRefresh { get; set; }
public ClashProxiesViewModel(Func<EViewAction, object?, bool>? updateView)
{
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_config = LazyConfig.Instance.Config;
_updateView = updateView;
SelectedGroup = new();
SelectedDetail = new();
AutoRefresh = _config.clashUIItem.proxiesAutoRefresh;
SortingSelected = _config.clashUIItem.proxiesSorting;
RuleModeSelected = (int)_config.clashUIItem.ruleMode;
this.WhenAnyValue(
x => x.SelectedGroup,
y => y != null && !string.IsNullOrEmpty(y.name))
.Subscribe(c => RefreshProxyDetails(c));
this.WhenAnyValue(
x => x.RuleModeSelected,
y => y >= 0)
.Subscribe(c => DoRulemodeSelected(c));
this.WhenAnyValue(
x => x.SortingSelected,
y => y >= 0)
.Subscribe(c => DoSortingSelected(c));
this.WhenAnyValue(
x => x.AutoRefresh,
y => y == true)
.Subscribe(c => { _config.clashUIItem.proxiesAutoRefresh = AutoRefresh; });
ProxiesReloadCmd = ReactiveCommand.Create(() =>
{
ProxiesReload();
});
ProxiesDelaytestCmd = ReactiveCommand.Create(() =>
{
ProxiesDelayTest(true);
});
ProxiesDelaytestPartCmd = ReactiveCommand.Create(() =>
{
ProxiesDelayTest(false);
});
ProxiesSelectActivityCmd = ReactiveCommand.Create(() =>
{
SetActiveProxy();
});
ProxiesReload();
DelayTestTask();
}
private void DoRulemodeSelected(bool c)
{
if (!c)
{
return;
}
if (_config.clashUIItem.ruleMode == (ERuleMode)RuleModeSelected)
{
return;
}
SetRuleModeCheck((ERuleMode)RuleModeSelected);
}
public void SetRuleModeCheck(ERuleMode mode)
{
if (_config.clashUIItem.ruleMode == mode)
{
return;
}
SetRuleMode(mode);
}
private void DoSortingSelected(bool c)
{
if (!c)
{
return;
}
if (SortingSelected != _config.clashUIItem.proxiesSorting)
{
_config.clashUIItem.proxiesSorting = SortingSelected;
}
RefreshProxyDetails(c);
}
private void UpdateHandler(bool notify, string msg)
{
_noticeHandler?.SendMessage(msg, true);
}
public void ProxiesReload()
{
GetClashProxies(true);
ProxiesDelayTest();
}
public void ProxiesDelayTest()
{
ProxiesDelayTest(true);
}
#region proxy function
private void SetRuleMode(ERuleMode mode)
{
_config.clashUIItem.ruleMode = mode;
if (mode != ERuleMode.Unchanged)
{
Dictionary<string, string> headers = new()
{
{ "mode", mode.ToString().ToLower() }
};
ClashApiHandler.Instance.ClashConfigUpdate(headers);
}
}
private void GetClashProxies(bool refreshUI)
{
ClashApiHandler.Instance.GetClashProxies(_config, (it, it2) =>
{
//UpdateHandler(false, "Refresh Clash Proxies");
_proxies = it?.proxies;
_providers = it2?.providers;
if (_proxies == null)
{
return;
}
if (refreshUI)
{
_updateView?.Invoke(EViewAction.DispatcherRefreshProxyGroups, null);
}
});
}
public void RefreshProxyGroups()
{
var selectedName = SelectedGroup?.name;
_proxyGroups.Clear();
var proxyGroups = ClashApiHandler.Instance.GetClashProxyGroups();
if (proxyGroups != null && proxyGroups.Count > 0)
{
foreach (var it in proxyGroups)
{
if (string.IsNullOrEmpty(it.name) || !_proxies.ContainsKey(it.name))
{
continue;
}
var item = _proxies[it.name];
if (!Global.allowSelectType.Contains(item.type.ToLower()))
{
continue;
}
_proxyGroups.Add(new ClashProxyModel()
{
now = item.now,
name = item.name,
type = item.type
});
}
}
//from api
foreach (KeyValuePair<string, ProxiesItem> kv in _proxies)
{
if (!Global.allowSelectType.Contains(kv.Value.type.ToLower()))
{
continue;
}
var item = _proxyGroups.Where(t => t.name == kv.Key).FirstOrDefault();
if (item != null && !string.IsNullOrEmpty(item.name))
{
continue;
}
_proxyGroups.Add(new ClashProxyModel()
{
now = kv.Value.now,
name = kv.Key,
type = kv.Value.type
});
}
if (_proxyGroups != null && _proxyGroups.Count > 0)
{
if (selectedName != null && _proxyGroups.Any(t => t.name == selectedName))
{
SelectedGroup = _proxyGroups.FirstOrDefault(t => t.name == selectedName);
}
else
{
SelectedGroup = _proxyGroups[0];
}
}
else
{
SelectedGroup = new();
}
}
private void RefreshProxyDetails(bool c)
{
_proxyDetails.Clear();
if (!c)
{
return;
}
var name = SelectedGroup?.name;
if (string.IsNullOrEmpty(name))
{
return;
}
if (_proxies == null)
{
return;
}
_proxies.TryGetValue(name, out ProxiesItem proxy);
if (proxy == null || proxy.all == null)
{
return;
}
var lstDetails = new List<ClashProxyModel>();
foreach (var item in proxy.all)
{
var isActive = item == proxy.now;
var proxy2 = TryGetProxy(item);
if (proxy2 == null)
{
continue;
}
int delay = -1;
if (proxy2.history.Count > 0)
{
delay = proxy2.history[proxy2.history.Count - 1].delay;
}
lstDetails.Add(new ClashProxyModel()
{
isActive = isActive,
name = item,
type = proxy2.type,
delay = delay <= 0 ? _delayTimeout : delay,
delayName = delay <= 0 ? string.Empty : $"{delay}ms",
});
}
//sort
switch (SortingSelected)
{
case 0:
lstDetails = lstDetails.OrderBy(t => t.delay).ToList();
break;
case 1:
lstDetails = lstDetails.OrderBy(t => t.name).ToList();
break;
default:
break;
}
_proxyDetails.AddRange(lstDetails);
}
private ProxiesItem? TryGetProxy(string name)
{
if (_proxies is null)
return null;
_proxies.TryGetValue(name, out ProxiesItem proxy2);
if (proxy2 != null)
{
return proxy2;
}
//from providers
if (_providers != null)
{
foreach (KeyValuePair<string, ProvidersItem> kv in _providers)
{
if (Global.proxyVehicleType.Contains(kv.Value.vehicleType.ToLower()))
{
var proxy3 = kv.Value.proxies.FirstOrDefault(t => t.name == name);
if (proxy3 != null)
{
return proxy3;
}
}
}
}
return null;
}
public void SetActiveProxy()
{
if (SelectedGroup == null || string.IsNullOrEmpty(SelectedGroup.name))
{
return;
}
if (SelectedDetail == null || string.IsNullOrEmpty(SelectedDetail.name))
{
return;
}
var name = SelectedGroup.name;
if (string.IsNullOrEmpty(name))
{
return;
}
var nameNode = SelectedDetail.name;
if (string.IsNullOrEmpty(nameNode))
{
return;
}
var selectedProxy = TryGetProxy(name);
if (selectedProxy == null || selectedProxy.type != "Selector")
{
_noticeHandler?.Enqueue(ResUI.OperationFailed);
return;
}
ClashApiHandler.Instance.ClashSetActiveProxy(name, nameNode);
selectedProxy.now = nameNode;
var group = _proxyGroups.Where(it => it.name == SelectedGroup.name).FirstOrDefault();
if (group != null)
{
group.now = nameNode;
var group2 = JsonUtils.DeepCopy(group);
_proxyGroups.Replace(group, group2);
SelectedGroup = group2;
}
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
}
private void ProxiesDelayTest(bool blAll)
{
//UpdateHandler(false, "Clash Proxies Latency Test");
ClashApiHandler.Instance.ClashProxiesDelayTest(blAll, _proxyDetails.ToList(), (item, result) =>
{
if (item == null)
{
GetClashProxies(true);
return;
}
if (string.IsNullOrEmpty(result))
{
return;
}
_updateView?.Invoke(EViewAction.DispatcherProxiesDelayTest, new SpeedTestResult() { IndexId = item.name, Delay = result });
});
}
public void ProxiesDelayTestResult(SpeedTestResult result)
{
//UpdateHandler(false, $"{item.name}={result}");
var detail = _proxyDetails.Where(it => it.name == result.IndexId).FirstOrDefault();
if (detail != null)
{
var dicResult = JsonUtils.Deserialize<Dictionary<string, object>>(result.Delay);
if (dicResult != null && dicResult.ContainsKey("delay"))
{
detail.delay = Convert.ToInt32(dicResult["delay"].ToString());
detail.delayName = $"{detail.delay}ms";
}
else if (dicResult != null && dicResult.ContainsKey("message"))
{
detail.delay = _delayTimeout;
detail.delayName = $"{dicResult["message"]}";
}
else
{
detail.delay = _delayTimeout;
detail.delayName = String.Empty;
}
_proxyDetails.Replace(detail, JsonUtils.DeepCopy(detail));
}
}
#endregion proxy function
#region task
public void DelayTestTask()
{
var lastTime = DateTime.Now;
Observable.Interval(TimeSpan.FromSeconds(60))
.Subscribe(x =>
{
if (!(AutoRefresh && _config.uiItem.showInTaskbar && _config.IsRunningCore(ECoreType.clash)))
{
return;
}
var dtNow = DateTime.Now;
if (_config.clashUIItem.proxiesAutoDelayTestInterval > 0)
{
if ((dtNow - lastTime).Minutes % _config.clashUIItem.proxiesAutoDelayTestInterval == 0)
{
ProxiesDelayTest();
lastTime = dtNow;
}
Task.Delay(1000).Wait();
}
});
}
#endregion task
}
}
@@ -0,0 +1,113 @@
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
namespace ServiceLib.ViewModels
{
public class DNSSettingViewModel : MyReactiveObject
{
[Reactive] public bool useSystemHosts { get; set; }
[Reactive] public string domainStrategy4Freedom { get; set; }
[Reactive] public string domainDNSAddress { get; set; }
[Reactive] public string normalDNS { get; set; }
[Reactive] public string domainStrategy4Freedom2 { get; set; }
[Reactive] public string domainDNSAddress2 { get; set; }
[Reactive] public string normalDNS2 { get; set; }
[Reactive] public string tunDNS2 { get; set; }
public ReactiveCommand<Unit, Unit> SaveCmd { get; }
public ReactiveCommand<Unit, Unit> ImportDefConfig4V2rayCmd { get; }
public ReactiveCommand<Unit, Unit> ImportDefConfig4SingboxCmd { get; }
public DNSSettingViewModel(Func<EViewAction, object?, bool>? updateView)
{
_config = LazyConfig.Instance.Config;
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_updateView = updateView;
var item = LazyConfig.Instance.GetDNSItem(ECoreType.Xray);
useSystemHosts = item.useSystemHosts;
domainStrategy4Freedom = item?.domainStrategy4Freedom ?? string.Empty;
domainDNSAddress = item?.domainDNSAddress ?? string.Empty;
normalDNS = item?.normalDNS ?? string.Empty;
var item2 = LazyConfig.Instance.GetDNSItem(ECoreType.sing_box);
domainStrategy4Freedom2 = item2?.domainStrategy4Freedom ?? string.Empty;
domainDNSAddress2 = item2?.domainDNSAddress ?? string.Empty;
normalDNS2 = item2?.normalDNS ?? string.Empty;
tunDNS2 = item2?.tunDNS ?? string.Empty;
SaveCmd = ReactiveCommand.Create(() =>
{
SaveSetting();
});
ImportDefConfig4V2rayCmd = ReactiveCommand.Create(() =>
{
normalDNS = Utils.GetEmbedText(Global.DNSV2rayNormalFileName);
});
ImportDefConfig4SingboxCmd = ReactiveCommand.Create(() =>
{
normalDNS2 = Utils.GetEmbedText(Global.DNSSingboxNormalFileName);
tunDNS2 = Utils.GetEmbedText(Global.TunSingboxDNSFileName);
});
}
private void SaveSetting()
{
if (!Utils.IsNullOrEmpty(normalDNS))
{
var obj = JsonUtils.ParseJson(normalDNS);
if (obj != null && obj["servers"] != null)
{
}
else
{
if (normalDNS.Contains("{") || normalDNS.Contains("}"))
{
_noticeHandler?.Enqueue(ResUI.FillCorrectDNSText);
return;
}
}
}
if (!Utils.IsNullOrEmpty(normalDNS2))
{
var obj2 = JsonUtils.Deserialize<Dns4Sbox>(normalDNS2);
if (obj2 == null)
{
_noticeHandler?.Enqueue(ResUI.FillCorrectDNSText);
return;
}
}
if (!Utils.IsNullOrEmpty(tunDNS2))
{
var obj2 = JsonUtils.Deserialize<Dns4Sbox>(tunDNS2);
if (obj2 == null)
{
_noticeHandler?.Enqueue(ResUI.FillCorrectDNSText);
return;
}
}
var item = LazyConfig.Instance.GetDNSItem(ECoreType.Xray);
item.domainStrategy4Freedom = domainStrategy4Freedom;
item.domainDNSAddress = domainDNSAddress;
item.useSystemHosts = useSystemHosts;
item.normalDNS = normalDNS;
ConfigHandler.SaveDNSItems(_config, item);
var item2 = LazyConfig.Instance.GetDNSItem(ECoreType.sing_box);
item2.domainStrategy4Freedom = domainStrategy4Freedom2;
item2.domainDNSAddress = domainDNSAddress2;
item2.normalDNS = JsonUtils.Serialize(JsonUtils.ParseJson(normalDNS2));
item2.tunDNS = JsonUtils.Serialize(JsonUtils.ParseJson(tunDNS2)); ;
ConfigHandler.SaveDNSItems(_config, item2);
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,394 @@
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
namespace ServiceLib.ViewModels
{
public class OptionSettingViewModel : MyReactiveObject
{
#region Core
[Reactive] public int localPort { get; set; }
[Reactive] public bool udpEnabled { get; set; }
[Reactive] public bool sniffingEnabled { get; set; }
public IList<string> destOverride { get; set; }
[Reactive] public bool routeOnly { get; set; }
[Reactive] public bool allowLANConn { get; set; }
[Reactive] public bool newPort4LAN { get; set; }
[Reactive] public string user { get; set; }
[Reactive] public string pass { get; set; }
[Reactive] public bool muxEnabled { get; set; }
[Reactive] public bool logEnabled { get; set; }
[Reactive] public string loglevel { get; set; }
[Reactive] public bool defAllowInsecure { get; set; }
[Reactive] public string defFingerprint { get; set; }
[Reactive] public string defUserAgent { get; set; }
[Reactive] public string mux4SboxProtocol { get; set; }
[Reactive] public bool enableCacheFile4Sbox { get; set; }
[Reactive] public int hyUpMbps { get; set; }
[Reactive] public int hyDownMbps { get; set; }
[Reactive] public bool enableFragment { get; set; }
#endregion Core
#region Core KCP
//[Reactive] public int Kcpmtu { get; set; }
//[Reactive] public int Kcptti { get; set; }
//[Reactive] public int KcpuplinkCapacity { get; set; }
//[Reactive] public int KcpdownlinkCapacity { get; set; }
//[Reactive] public int KcpreadBufferSize { get; set; }
//[Reactive] public int KcpwriteBufferSize { get; set; }
//[Reactive] public bool Kcpcongestion { get; set; }
#endregion Core KCP
#region UI
[Reactive] public bool AutoRun { get; set; }
[Reactive] public bool EnableStatistics { get; set; }
[Reactive] public bool KeepOlderDedupl { get; set; }
[Reactive] public bool IgnoreGeoUpdateCore { get; set; }
[Reactive] public bool EnableAutoAdjustMainLvColWidth { get; set; }
[Reactive] public bool EnableUpdateSubOnlyRemarksExist { get; set; }
[Reactive] public bool EnableSecurityProtocolTls13 { get; set; }
[Reactive] public bool AutoHideStartup { get; set; }
[Reactive] public bool EnableCheckPreReleaseUpdate { get; set; }
[Reactive] public bool EnableDragDropSort { get; set; }
[Reactive] public bool DoubleClick2Activate { get; set; }
[Reactive] public int AutoUpdateInterval { get; set; }
[Reactive] public int TrayMenuServersLimit { get; set; }
[Reactive] public string CurrentFontFamily { get; set; }
[Reactive] public int SpeedTestTimeout { get; set; }
[Reactive] public string SpeedTestUrl { get; set; }
[Reactive] public string SpeedPingTestUrl { get; set; }
[Reactive] public bool EnableHWA { get; set; }
[Reactive] public string SubConvertUrl { get; set; }
[Reactive] public int MainGirdOrientation { get; set; }
#endregion UI
#region System proxy
[Reactive] public bool notProxyLocalAddress { get; set; }
[Reactive] public string systemProxyAdvancedProtocol { get; set; }
[Reactive] public string systemProxyExceptions { get; set; }
#endregion System proxy
#region Tun mode
[Reactive] public bool TunStrictRoute { get; set; }
[Reactive] public string TunStack { get; set; }
[Reactive] public int TunMtu { get; set; }
[Reactive] public bool TunEnableExInbound { get; set; }
[Reactive] public bool TunEnableIPv6Address { get; set; }
#endregion Tun mode
#region CoreType
[Reactive] public string CoreType1 { get; set; }
[Reactive] public string CoreType2 { get; set; }
[Reactive] public string CoreType3 { get; set; }
[Reactive] public string CoreType4 { get; set; }
[Reactive] public string CoreType5 { get; set; }
[Reactive] public string CoreType6 { get; set; }
#endregion CoreType
public ReactiveCommand<Unit, Unit> SaveCmd { get; }
public OptionSettingViewModel(Func<EViewAction, object?, bool>? updateView)
{
_config = LazyConfig.Instance.Config;
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_updateView = updateView;
#region Core
var inbound = _config.inbound[0];
localPort = inbound.localPort;
udpEnabled = inbound.udpEnabled;
sniffingEnabled = inbound.sniffingEnabled;
routeOnly = inbound.routeOnly;
allowLANConn = inbound.allowLANConn;
newPort4LAN = inbound.newPort4LAN;
user = inbound.user;
pass = inbound.pass;
muxEnabled = _config.coreBasicItem.muxEnabled;
logEnabled = _config.coreBasicItem.logEnabled;
loglevel = _config.coreBasicItem.loglevel;
defAllowInsecure = _config.coreBasicItem.defAllowInsecure;
defFingerprint = _config.coreBasicItem.defFingerprint;
defUserAgent = _config.coreBasicItem.defUserAgent;
mux4SboxProtocol = _config.mux4SboxItem.protocol;
enableCacheFile4Sbox = _config.coreBasicItem.enableCacheFile4Sbox;
hyUpMbps = _config.hysteriaItem.up_mbps;
hyDownMbps = _config.hysteriaItem.down_mbps;
enableFragment = _config.coreBasicItem.enableFragment;
#endregion Core
#region Core KCP
//Kcpmtu = _config.kcpItem.mtu;
//Kcptti = _config.kcpItem.tti;
//KcpuplinkCapacity = _config.kcpItem.uplinkCapacity;
//KcpdownlinkCapacity = _config.kcpItem.downlinkCapacity;
//KcpreadBufferSize = _config.kcpItem.readBufferSize;
//KcpwriteBufferSize = _config.kcpItem.writeBufferSize;
//Kcpcongestion = _config.kcpItem.congestion;
#endregion Core KCP
#region UI
AutoRun = _config.guiItem.autoRun;
EnableStatistics = _config.guiItem.enableStatistics;
KeepOlderDedupl = _config.guiItem.keepOlderDedupl;
IgnoreGeoUpdateCore = _config.guiItem.ignoreGeoUpdateCore;
EnableAutoAdjustMainLvColWidth = _config.uiItem.enableAutoAdjustMainLvColWidth;
EnableUpdateSubOnlyRemarksExist = _config.uiItem.enableUpdateSubOnlyRemarksExist;
EnableSecurityProtocolTls13 = _config.guiItem.enableSecurityProtocolTls13;
AutoHideStartup = _config.uiItem.autoHideStartup;
EnableCheckPreReleaseUpdate = _config.guiItem.checkPreReleaseUpdate;
EnableDragDropSort = _config.uiItem.enableDragDropSort;
DoubleClick2Activate = _config.uiItem.doubleClick2Activate;
AutoUpdateInterval = _config.guiItem.autoUpdateInterval;
TrayMenuServersLimit = _config.guiItem.trayMenuServersLimit;
CurrentFontFamily = _config.uiItem.currentFontFamily;
SpeedTestTimeout = _config.speedTestItem.speedTestTimeout;
SpeedTestUrl = _config.speedTestItem.speedTestUrl;
SpeedPingTestUrl = _config.speedTestItem.speedPingTestUrl;
EnableHWA = _config.guiItem.enableHWA;
SubConvertUrl = _config.constItem.subConvertUrl;
MainGirdOrientation = (int)_config.uiItem.mainGirdOrientation;
#endregion UI
#region System proxy
notProxyLocalAddress = _config.systemProxyItem.notProxyLocalAddress;
systemProxyAdvancedProtocol = _config.systemProxyItem.systemProxyAdvancedProtocol;
systemProxyExceptions = _config.systemProxyItem.systemProxyExceptions;
#endregion System proxy
#region Tun mode
TunStrictRoute = _config.tunModeItem.strictRoute;
TunStack = _config.tunModeItem.stack;
TunMtu = _config.tunModeItem.mtu;
TunEnableExInbound = _config.tunModeItem.enableExInbound;
TunEnableIPv6Address = _config.tunModeItem.enableIPv6Address;
#endregion Tun mode
InitCoreType();
SaveCmd = ReactiveCommand.Create(() =>
{
SaveSetting();
});
}
private void InitCoreType()
{
if (_config.coreTypeItem == null)
{
_config.coreTypeItem = new List<CoreTypeItem>();
}
foreach (EConfigType it in Enum.GetValues(typeof(EConfigType)))
{
if (_config.coreTypeItem.FindIndex(t => t.configType == it) >= 0)
{
continue;
}
_config.coreTypeItem.Add(new CoreTypeItem()
{
configType = it,
coreType = ECoreType.Xray
});
}
_config.coreTypeItem.ForEach(it =>
{
var type = it.coreType.ToString();
switch ((int)it.configType)
{
case 1:
CoreType1 = type;
break;
case 2:
CoreType2 = type;
break;
case 3:
CoreType3 = type;
break;
case 4:
CoreType4 = type;
break;
case 5:
CoreType5 = type;
break;
case 6:
CoreType6 = type;
break;
}
});
}
private void SaveSetting()
{
if (Utils.IsNullOrEmpty(localPort.ToString()) || !Utils.IsNumeric(localPort.ToString())
|| localPort <= 0 || localPort >= Global.MaxPort)
{
_noticeHandler?.Enqueue(ResUI.FillLocalListeningPort);
return;
}
var needReboot = (EnableStatistics != _config.guiItem.enableStatistics
|| EnableDragDropSort != _config.uiItem.enableDragDropSort
|| EnableHWA != _config.guiItem.enableHWA
|| CurrentFontFamily != _config.uiItem.currentFontFamily
|| MainGirdOrientation != (int)_config.uiItem.mainGirdOrientation);
//if (Utile.IsNullOrEmpty(Kcpmtu.ToString()) || !Utile.IsNumeric(Kcpmtu.ToString())
// || Utile.IsNullOrEmpty(Kcptti.ToString()) || !Utile.IsNumeric(Kcptti.ToString())
// || Utile.IsNullOrEmpty(KcpuplinkCapacity.ToString()) || !Utile.IsNumeric(KcpuplinkCapacity.ToString())
// || Utile.IsNullOrEmpty(KcpdownlinkCapacity.ToString()) || !Utile.IsNumeric(KcpdownlinkCapacity.ToString())
// || Utile.IsNullOrEmpty(KcpreadBufferSize.ToString()) || !Utile.IsNumeric(KcpreadBufferSize.ToString())
// || Utile.IsNullOrEmpty(KcpwriteBufferSize.ToString()) || !Utile.IsNumeric(KcpwriteBufferSize.ToString()))
//{
// _noticeHandler?.Enqueue(ResUI.FillKcpParameters);
// return;
//}
//Core
_config.inbound[0].localPort = localPort;
_config.inbound[0].udpEnabled = udpEnabled;
_config.inbound[0].sniffingEnabled = sniffingEnabled;
_config.inbound[0].destOverride = destOverride?.ToList();
_config.inbound[0].routeOnly = routeOnly;
_config.inbound[0].allowLANConn = allowLANConn;
_config.inbound[0].newPort4LAN = newPort4LAN;
_config.inbound[0].user = user;
_config.inbound[0].pass = pass;
if (_config.inbound.Count > 1)
{
_config.inbound.RemoveAt(1);
}
_config.coreBasicItem.logEnabled = logEnabled;
_config.coreBasicItem.loglevel = loglevel;
_config.coreBasicItem.muxEnabled = muxEnabled;
_config.coreBasicItem.defAllowInsecure = defAllowInsecure;
_config.coreBasicItem.defFingerprint = defFingerprint;
_config.coreBasicItem.defUserAgent = defUserAgent;
_config.mux4SboxItem.protocol = mux4SboxProtocol;
_config.coreBasicItem.enableCacheFile4Sbox = enableCacheFile4Sbox;
_config.hysteriaItem.up_mbps = hyUpMbps;
_config.hysteriaItem.down_mbps = hyDownMbps;
_config.coreBasicItem.enableFragment = enableFragment;
_config.guiItem.autoRun = AutoRun;
_config.guiItem.enableStatistics = EnableStatistics;
_config.guiItem.keepOlderDedupl = KeepOlderDedupl;
_config.guiItem.ignoreGeoUpdateCore = IgnoreGeoUpdateCore;
_config.uiItem.enableAutoAdjustMainLvColWidth = EnableAutoAdjustMainLvColWidth;
_config.uiItem.enableUpdateSubOnlyRemarksExist = EnableUpdateSubOnlyRemarksExist;
_config.guiItem.enableSecurityProtocolTls13 = EnableSecurityProtocolTls13;
_config.uiItem.autoHideStartup = AutoHideStartup;
_config.guiItem.autoUpdateInterval = AutoUpdateInterval;
_config.guiItem.checkPreReleaseUpdate = EnableCheckPreReleaseUpdate;
_config.uiItem.enableDragDropSort = EnableDragDropSort;
_config.uiItem.doubleClick2Activate = DoubleClick2Activate;
_config.guiItem.trayMenuServersLimit = TrayMenuServersLimit;
_config.uiItem.currentFontFamily = CurrentFontFamily;
_config.speedTestItem.speedTestTimeout = SpeedTestTimeout;
_config.speedTestItem.speedTestUrl = SpeedTestUrl;
_config.speedTestItem.speedPingTestUrl = SpeedPingTestUrl;
_config.guiItem.enableHWA = EnableHWA;
_config.constItem.subConvertUrl = SubConvertUrl;
_config.uiItem.mainGirdOrientation = (EGirdOrientation)MainGirdOrientation;
//systemProxy
_config.systemProxyItem.systemProxyExceptions = systemProxyExceptions;
_config.systemProxyItem.notProxyLocalAddress = notProxyLocalAddress;
_config.systemProxyItem.systemProxyAdvancedProtocol = systemProxyAdvancedProtocol;
//tun mode
_config.tunModeItem.strictRoute = TunStrictRoute;
_config.tunModeItem.stack = TunStack;
_config.tunModeItem.mtu = TunMtu;
_config.tunModeItem.enableExInbound = TunEnableExInbound;
_config.tunModeItem.enableIPv6Address = TunEnableIPv6Address;
//coreType
SaveCoreType();
if (ConfigHandler.SaveConfig(_config) == 0)
{
if (needReboot)
{
_noticeHandler?.Enqueue(ResUI.NeedRebootTips);
}
else
{
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
}
_updateView?.Invoke(EViewAction.CloseWindow, null);
}
else
{
_noticeHandler?.Enqueue(ResUI.OperationFailed);
}
}
private int SaveCoreType()
{
for (int k = 1; k <= _config.coreTypeItem.Count; k++)
{
var item = _config.coreTypeItem[k - 1];
var type = string.Empty;
switch ((int)item.configType)
{
case 1:
type = CoreType1;
break;
case 2:
type = CoreType2;
break;
case 3:
type = CoreType3;
break;
case 4:
type = CoreType4;
break;
case 5:
type = CoreType5;
break;
case 6:
type = CoreType6;
break;
default:
continue;
}
item.coreType = (ECoreType)Enum.Parse(typeof(ECoreType), type);
}
return 0;
}
}
}
@@ -0,0 +1,785 @@
using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
using System.Reactive.Linq;
using System.Text;
namespace ServiceLib.ViewModels
{
public class ProfilesViewModel : MyReactiveObject
{
#region private prop
private List<ProfileItem> _lstProfile;
private string _serverFilter = string.Empty;
private Dictionary<string, bool> _dicHeaderSort = new();
private SpeedtestHandler? _speedtestHandler;
#endregion private prop
#region ObservableCollection
private IObservableCollection<ProfileItemModel> _profileItems = new ObservableCollectionExtended<ProfileItemModel>();
public IObservableCollection<ProfileItemModel> ProfileItems => _profileItems;
private IObservableCollection<SubItem> _subItems = new ObservableCollectionExtended<SubItem>();
public IObservableCollection<SubItem> SubItems => _subItems;
private IObservableCollection<ComboItem> _servers = new ObservableCollectionExtended<ComboItem>();
[Reactive]
public ProfileItemModel SelectedProfile { get; set; }
public IList<ProfileItemModel> SelectedProfiles { get; set; }
[Reactive]
public SubItem SelectedSub { get; set; }
[Reactive]
public SubItem SelectedMoveToGroup { get; set; }
[Reactive]
public ComboItem SelectedServer { get; set; }
[Reactive]
public string ServerFilter { get; set; }
[Reactive]
public bool BlServers { get; set; }
#endregion ObservableCollection
#region Menu
//servers delete
public ReactiveCommand<Unit, Unit> EditServerCmd { get; }
public ReactiveCommand<Unit, Unit> RemoveServerCmd { get; }
public ReactiveCommand<Unit, Unit> RemoveDuplicateServerCmd { get; }
public ReactiveCommand<Unit, Unit> CopyServerCmd { get; }
public ReactiveCommand<Unit, Unit> SetDefaultServerCmd { get; }
public ReactiveCommand<Unit, Unit> ShareServerCmd { get; }
public ReactiveCommand<Unit, Unit> SetDefaultMultipleServerCmd { get; }
public ReactiveCommand<Unit, Unit> SetDefaultLoadBalanceServerCmd { get; }
//servers move
public ReactiveCommand<Unit, Unit> MoveTopCmd { get; }
public ReactiveCommand<Unit, Unit> MoveUpCmd { get; }
public ReactiveCommand<Unit, Unit> MoveDownCmd { get; }
public ReactiveCommand<Unit, Unit> MoveBottomCmd { get; }
//servers ping
public ReactiveCommand<Unit, Unit> MixedTestServerCmd { get; }
public ReactiveCommand<Unit, Unit> TcpingServerCmd { get; }
public ReactiveCommand<Unit, Unit> RealPingServerCmd { get; }
public ReactiveCommand<Unit, Unit> SpeedServerCmd { get; }
public ReactiveCommand<Unit, Unit> SortServerResultCmd { get; }
//servers export
public ReactiveCommand<Unit, Unit> Export2ClientConfigCmd { get; }
public ReactiveCommand<Unit, Unit> Export2ClientConfigClipboardCmd { get; }
public ReactiveCommand<Unit, Unit> Export2ShareUrlCmd { get; }
public ReactiveCommand<Unit, Unit> Export2ShareUrlBase64Cmd { get; }
public ReactiveCommand<Unit, Unit> AddSubCmd { get; }
public ReactiveCommand<Unit, Unit> EditSubCmd { get; }
#endregion Menu
#region Init
public ProfilesViewModel(Func<EViewAction, object?, bool>? updateView)
{
_config = LazyConfig.Instance.Config;
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_updateView = updateView;
MessageBus.Current.Listen<string>(Global.CommandRefreshProfiles).Subscribe(x => _updateView?.Invoke(EViewAction.DispatcherRefreshServersBiz, null));
SelectedProfile = new();
SelectedSub = new();
SelectedMoveToGroup = new();
SelectedServer = new();
RefreshSubscriptions();
RefreshServers();
#region WhenAnyValue && ReactiveCommand
var canEditRemove = this.WhenAnyValue(
x => x.SelectedProfile,
selectedSource => selectedSource != null && !selectedSource.indexId.IsNullOrEmpty());
this.WhenAnyValue(
x => x.SelectedSub,
y => y != null && !y.remarks.IsNullOrEmpty() && _config.subIndexId != y.id)
.Subscribe(c => SubSelectedChanged(c));
this.WhenAnyValue(
x => x.SelectedMoveToGroup,
y => y != null && !y.remarks.IsNullOrEmpty())
.Subscribe(c => MoveToGroup(c));
this.WhenAnyValue(
x => x.SelectedServer,
y => y != null && !y.Text.IsNullOrEmpty())
.Subscribe(c => ServerSelectedChanged(c));
this.WhenAnyValue(
x => x.ServerFilter,
y => y != null && _serverFilter != y)
.Subscribe(c => ServerFilterChanged(c));
//servers delete
EditServerCmd = ReactiveCommand.Create(() =>
{
EditServer(EConfigType.Custom);
}, canEditRemove);
RemoveServerCmd = ReactiveCommand.Create(() =>
{
RemoveServer();
}, canEditRemove);
RemoveDuplicateServerCmd = ReactiveCommand.Create(() =>
{
RemoveDuplicateServer();
});
CopyServerCmd = ReactiveCommand.Create(() =>
{
CopyServer();
}, canEditRemove);
SetDefaultServerCmd = ReactiveCommand.Create(() =>
{
SetDefaultServer();
}, canEditRemove);
ShareServerCmd = ReactiveCommand.Create(() =>
{
ShareServer();
}, canEditRemove);
SetDefaultMultipleServerCmd = ReactiveCommand.Create(() =>
{
SetDefaultMultipleServer(ECoreType.sing_box);
}, canEditRemove);
SetDefaultLoadBalanceServerCmd = ReactiveCommand.Create(() =>
{
SetDefaultMultipleServer(ECoreType.Xray);
}, canEditRemove);
//servers move
MoveTopCmd = ReactiveCommand.Create(() =>
{
MoveServer(EMove.Top);
}, canEditRemove);
MoveUpCmd = ReactiveCommand.Create(() =>
{
MoveServer(EMove.Up);
}, canEditRemove);
MoveDownCmd = ReactiveCommand.Create(() =>
{
MoveServer(EMove.Down);
}, canEditRemove);
MoveBottomCmd = ReactiveCommand.Create(() =>
{
MoveServer(EMove.Bottom);
}, canEditRemove);
//servers ping
MixedTestServerCmd = ReactiveCommand.Create(() =>
{
ServerSpeedtest(ESpeedActionType.Mixedtest);
});
TcpingServerCmd = ReactiveCommand.Create(() =>
{
ServerSpeedtest(ESpeedActionType.Tcping);
}, canEditRemove);
RealPingServerCmd = ReactiveCommand.Create(() =>
{
ServerSpeedtest(ESpeedActionType.Realping);
}, canEditRemove);
SpeedServerCmd = ReactiveCommand.Create(() =>
{
ServerSpeedtest(ESpeedActionType.Speedtest);
}, canEditRemove);
SortServerResultCmd = ReactiveCommand.Create(() =>
{
SortServer(EServerColName.delayVal.ToString());
});
//servers export
Export2ClientConfigCmd = ReactiveCommand.Create(() =>
{
Export2ClientConfig(false);
}, canEditRemove);
Export2ClientConfigClipboardCmd = ReactiveCommand.Create(() =>
{
Export2ClientConfig(true);
}, canEditRemove);
Export2ShareUrlCmd = ReactiveCommand.Create(() =>
{
Export2ShareUrl(false);
}, canEditRemove);
Export2ShareUrlBase64Cmd = ReactiveCommand.Create(() =>
{
Export2ShareUrl(true);
}, canEditRemove);
//Subscription
AddSubCmd = ReactiveCommand.Create(() =>
{
EditSub(true);
});
EditSubCmd = ReactiveCommand.Create(() =>
{
EditSub(false);
});
#endregion WhenAnyValue && ReactiveCommand
}
#endregion Init
#region Actions
private void Reload()
{
Locator.Current.GetService<MainWindowViewModel>()?.Reload();
}
private void UpdateSpeedtestHandler(SpeedTestResult result)
{
_updateView?.Invoke(EViewAction.DispatcherSpeedTest, result);
}
public void SetSpeedTestResult(SpeedTestResult result)
{
if (Utils.IsNullOrEmpty(result.IndexId))
{
_noticeHandler?.SendMessage(result.Delay, true);
_noticeHandler?.Enqueue(result.Delay);
return;
}
var item = _profileItems.Where(it => it.indexId == result.IndexId).FirstOrDefault();
if (item != null)
{
if (!Utils.IsNullOrEmpty(result.Delay))
{
int.TryParse(result.Delay, out int temp);
item.delay = temp;
item.delayVal = $"{result.Delay} {Global.DelayUnit}";
}
if (!Utils.IsNullOrEmpty(result.Speed))
{
item.speedVal = $"{result.Speed} {Global.SpeedUnit}";
}
_profileItems.Replace(item, JsonUtils.DeepCopy(item));
}
}
public void UpdateStatistics(ServerSpeedItem update)
{
try
{
var item = _profileItems.Where(it => it.indexId == update.indexId).FirstOrDefault();
if (item != null)
{
item.todayDown = Utils.HumanFy(update.todayDown);
item.todayUp = Utils.HumanFy(update.todayUp);
item.totalDown = Utils.HumanFy(update.totalDown);
item.totalUp = Utils.HumanFy(update.totalUp);
if (SelectedProfile?.indexId == item.indexId)
{
var temp = JsonUtils.DeepCopy(item);
_profileItems.Replace(item, temp);
SelectedProfile = temp;
}
else
{
_profileItems.Replace(item, JsonUtils.DeepCopy(item));
}
}
}
catch
{
}
}
public void AutofitColumnWidth()
{
_updateView?.Invoke(EViewAction.AdjustMainLvColWidth, null);
}
#endregion Actions
#region Servers && Groups
private void SubSelectedChanged(bool c)
{
if (!c)
{
return;
}
_config.subIndexId = SelectedSub?.id;
RefreshServers();
_updateView?.Invoke(EViewAction.ProfilesFocus, null);
}
private void ServerFilterChanged(bool c)
{
if (!c)
{
return;
}
_serverFilter = ServerFilter;
if (Utils.IsNullOrEmpty(_serverFilter))
{
RefreshServers();
}
}
public void RefreshServers()
{
MessageBus.Current.SendMessage("", Global.CommandRefreshProfiles);
}
public void RefreshServersBiz()
{
var lstModel = LazyConfig.Instance.ProfileItemsEx(_config.subIndexId, _serverFilter);
_lstProfile = JsonUtils.Deserialize<List<ProfileItem>>(JsonUtils.Serialize(lstModel)) ?? [];
_profileItems.Clear();
_profileItems.AddRange(lstModel);
if (lstModel.Count > 0)
{
var selected = lstModel.FirstOrDefault(t => t.indexId == _config.indexId);
if (selected != null)
{
SelectedProfile = selected;
}
else
{
SelectedProfile = lstModel[0];
}
}
}
public void RefreshSubscriptions()
{
_subItems.Clear();
_subItems.Add(new SubItem { remarks = ResUI.AllGroupServers });
foreach (var item in LazyConfig.Instance.SubItems().OrderBy(t => t.sort))
{
_subItems.Add(item);
}
if (_config.subIndexId != null && _subItems.FirstOrDefault(t => t.id == _config.subIndexId) != null)
{
SelectedSub = _subItems.FirstOrDefault(t => t.id == _config.subIndexId);
}
else
{
SelectedSub = _subItems[0];
}
}
#endregion Servers && Groups
#region Add Servers
private int GetProfileItems(out List<ProfileItem> lstSelecteds, bool latest)
{
lstSelecteds = new List<ProfileItem>();
if (SelectedProfiles == null || SelectedProfiles.Count <= 0)
{
return -1;
}
var orderProfiles = SelectedProfiles?.OrderBy(t => t.sort);
if (latest)
{
foreach (var profile in orderProfiles)
{
var item = LazyConfig.Instance.GetProfileItem(profile.indexId);
if (item is not null)
{
lstSelecteds.Add(item);
}
}
}
else
{
lstSelecteds = JsonUtils.Deserialize<List<ProfileItem>>(JsonUtils.Serialize(orderProfiles));
}
return 0;
}
public void EditServer(EConfigType eConfigType)
{
if (Utils.IsNullOrEmpty(SelectedProfile?.indexId))
{
return;
}
var item = LazyConfig.Instance.GetProfileItem(SelectedProfile.indexId);
if (item is null)
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectServer);
return;
}
eConfigType = item.configType;
bool? ret = false;
if (eConfigType == EConfigType.Custom)
{
ret = _updateView?.Invoke(EViewAction.AddServer2Window, item);
}
else
{
ret = _updateView?.Invoke(EViewAction.AddServerWindow, item);
}
if (ret == true)
{
RefreshServers();
if (item.indexId == _config.indexId)
{
Reload();
}
}
}
public void RemoveServer()
{
if (GetProfileItems(out List<ProfileItem> lstSelecteds, true) < 0)
{
return;
}
if (_updateView?.Invoke(EViewAction.ShowYesNo, null) == false)
{
return;
}
var exists = lstSelecteds.Exists(t => t.indexId == _config.indexId);
ConfigHandler.RemoveServer(_config, lstSelecteds);
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
RefreshServers();
if (exists)
{
Reload();
}
}
private void RemoveDuplicateServer()
{
var tuple = ConfigHandler.DedupServerList(_config, _config.subIndexId);
RefreshServers();
Reload();
_noticeHandler?.Enqueue(string.Format(ResUI.RemoveDuplicateServerResult, tuple.Item1, tuple.Item2));
}
private void CopyServer()
{
if (GetProfileItems(out List<ProfileItem> lstSelecteds, false) < 0)
{
return;
}
if (ConfigHandler.CopyServer(_config, lstSelecteds) == 0)
{
RefreshServers();
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
}
}
public void SetDefaultServer()
{
if (Utils.IsNullOrEmpty(SelectedProfile?.indexId))
{
return;
}
SetDefaultServer(SelectedProfile.indexId);
}
private void SetDefaultServer(string indexId)
{
if (Utils.IsNullOrEmpty(indexId))
{
return;
}
if (indexId == _config.indexId)
{
return;
}
var item = LazyConfig.Instance.GetProfileItem(indexId);
if (item is null)
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectServer);
return;
}
if (ConfigHandler.SetDefaultServerIndex(_config, indexId) == 0)
{
RefreshServers();
Reload();
}
}
private void ServerSelectedChanged(bool c)
{
if (!c)
{
return;
}
if (SelectedServer == null)
{
return;
}
if (Utils.IsNullOrEmpty(SelectedServer.ID))
{
return;
}
SetDefaultServer(SelectedServer.ID);
}
public void ShareServer()
{
var item = LazyConfig.Instance.GetProfileItem(SelectedProfile.indexId);
if (item is null)
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectServer);
return;
}
var url = FmtHandler.GetShareUri(item);
if (Utils.IsNullOrEmpty(url))
{
return;
}
_updateView?.Invoke(EViewAction.ShareServer, url);
}
private void SetDefaultMultipleServer(ECoreType coreType)
{
if (GetProfileItems(out List<ProfileItem> lstSelecteds, true) < 0)
{
return;
}
if (ConfigHandler.AddCustomServer4Multiple(_config, lstSelecteds, coreType, out string indexId) != 0)
{
_noticeHandler?.Enqueue(ResUI.OperationFailed);
return;
}
if (indexId == _config.indexId)
{
RefreshServers();
Reload();
}
else
{
SetDefaultServer(indexId);
}
}
public void SortServer(string colName)
{
if (Utils.IsNullOrEmpty(colName))
{
return;
}
_dicHeaderSort.TryAdd(colName, true);
_dicHeaderSort.TryGetValue(colName, out bool asc);
if (ConfigHandler.SortServers(_config, _config.subIndexId, colName, asc) != 0)
{
return;
}
_dicHeaderSort[colName] = !asc;
RefreshServers();
}
//move server
private void MoveToGroup(bool c)
{
if (!c)
{
return;
}
if (GetProfileItems(out List<ProfileItem> lstSelecteds, true) < 0)
{
return;
}
ConfigHandler.MoveToGroup(_config, lstSelecteds, SelectedMoveToGroup.id);
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
RefreshServers();
SelectedMoveToGroup = new();
//Reload();
}
public void MoveServer(EMove eMove)
{
var item = _lstProfile.FirstOrDefault(t => t.indexId == SelectedProfile.indexId);
if (item is null)
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectServer);
return;
}
int index = _lstProfile.IndexOf(item);
if (index < 0)
{
return;
}
if (ConfigHandler.MoveServer(_config, ref _lstProfile, index, eMove) == 0)
{
RefreshServers();
}
}
public void 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)
{
RefreshServers();
}
}
}
public void ServerSpeedtest(ESpeedActionType actionType)
{
if (actionType == ESpeedActionType.Mixedtest)
{
SelectedProfiles = _profileItems;
}
if (GetProfileItems(out List<ProfileItem> lstSelecteds, false) < 0)
{
return;
}
//ClearTestResult();
var coreHandler = Locator.Current.GetService<CoreHandler>();
if (coreHandler != null)
{
_speedtestHandler = new SpeedtestHandler(_config, coreHandler, lstSelecteds, actionType, UpdateSpeedtestHandler);
}
}
public void ServerSpeedtestStop()
{
_speedtestHandler?.ExitLoop();
}
private void Export2ClientConfig(bool blClipboard)
{
var item = LazyConfig.Instance.GetProfileItem(SelectedProfile.indexId);
if (item is null)
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectServer);
return;
}
if (blClipboard)
{
if (CoreConfigHandler.GenerateClientConfig(item, null, out string msg, out string content) != 0)
{
Locator.Current.GetService<NoticeHandler>()?.Enqueue(msg);
}
else
{
_updateView?.Invoke(EViewAction.SetClipboardData, content);
_noticeHandler?.SendMessage(ResUI.OperationSuccess);
}
}
else
{
_updateView?.Invoke(EViewAction.SaveFileDialog, item);
}
}
public void Export2ClientConfigResult(string fileName, ProfileItem item)
{
if (Utils.IsNullOrEmpty(fileName))
{
return;
}
if (CoreConfigHandler.GenerateClientConfig(item, fileName, out string msg, out string content) != 0)
{
Locator.Current.GetService<NoticeHandler>()?.Enqueue(msg);
}
else
{
msg = string.Format(ResUI.SaveClientConfigurationIn, fileName);
Locator.Current.GetService<NoticeHandler>()?.SendMessageAndEnqueue(msg);
}
}
public void Export2ShareUrl(bool blEncode)
{
if (GetProfileItems(out List<ProfileItem> lstSelecteds, true) < 0)
{
return;
}
StringBuilder sb = new();
foreach (var it in lstSelecteds)
{
var url = FmtHandler.GetShareUri(it);
if (Utils.IsNullOrEmpty(url))
{
continue;
}
sb.Append(url);
sb.AppendLine();
}
if (sb.Length > 0)
{
if (blEncode)
{
_updateView?.Invoke(EViewAction.SetClipboardData, Utils.Base64Encode(sb.ToString()));
}
else
{
_updateView?.Invoke(EViewAction.SetClipboardData, sb.ToString());
}
_noticeHandler?.SendMessage(ResUI.BatchExportURLSuccessfully);
}
}
#endregion Add Servers
#region Subscription
private void EditSub(bool blNew)
{
SubItem item;
if (blNew)
{
item = new();
}
else
{
item = LazyConfig.Instance.GetSubItem(_config.subIndexId);
if (item is null)
{
return;
}
}
if (_updateView?.Invoke(EViewAction.SubEditWindow, item) == true)
{
RefreshSubscriptions();
SubSelectedChanged(true);
}
}
#endregion Subscription
}
}
@@ -0,0 +1,94 @@
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
namespace ServiceLib.ViewModels
{
public class RoutingRuleDetailsViewModel : MyReactiveObject
{
public IList<string> ProtocolItems { get; set; }
public IList<string> InboundTagItems { get; set; }
[Reactive]
public RulesItem SelectedSource { get; set; }
[Reactive]
public string Domain { get; set; }
[Reactive]
public string IP { get; set; }
[Reactive]
public string Process { get; set; }
[Reactive]
public bool AutoSort { get; set; }
public ReactiveCommand<Unit, Unit> SaveCmd { get; }
public RoutingRuleDetailsViewModel(RulesItem rulesItem, Func<EViewAction, object?, bool>? updateView)
{
_config = LazyConfig.Instance.Config;
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_updateView = updateView;
if (rulesItem.id.IsNullOrEmpty())
{
rulesItem.id = Utils.GetGUID(false);
rulesItem.outboundTag = Global.ProxyTag;
rulesItem.enabled = true;
SelectedSource = rulesItem;
}
else
{
SelectedSource = rulesItem;
}
Domain = Utils.List2String(SelectedSource.domain, true);
IP = Utils.List2String(SelectedSource.ip, true);
Process = Utils.List2String(SelectedSource.process, true);
SaveCmd = ReactiveCommand.Create(() =>
{
SaveRules();
});
}
private void SaveRules()
{
Domain = Utils.Convert2Comma(Domain);
IP = Utils.Convert2Comma(IP);
Process = Utils.Convert2Comma(Process);
if (AutoSort)
{
SelectedSource.domain = Utils.String2ListSorted(Domain);
SelectedSource.ip = Utils.String2ListSorted(IP);
SelectedSource.process = Utils.String2ListSorted(Process);
}
else
{
SelectedSource.domain = Utils.String2List(Domain);
SelectedSource.ip = Utils.String2List(IP);
SelectedSource.process = Utils.String2List(Process);
}
SelectedSource.protocol = ProtocolItems?.ToList();
SelectedSource.inboundTag = InboundTagItems?.ToList();
bool hasRule = SelectedSource.domain?.Count > 0
|| SelectedSource.ip?.Count > 0
|| SelectedSource.protocol?.Count > 0
|| SelectedSource.process?.Count > 0
|| !Utils.IsNullOrEmpty(SelectedSource.port);
if (!hasRule)
{
_noticeHandler?.Enqueue(string.Format(ResUI.RoutingRuleDetailRequiredTips, "Port/Protocol/Domain/IP/Process"));
return;
}
//_noticeHandler?.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null);
}
}
}
@@ -0,0 +1,339 @@
using DynamicData.Binding;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
namespace ServiceLib.ViewModels
{
public class RoutingRuleSettingViewModel : MyReactiveObject
{
private List<RulesItem> _rules;
[Reactive]
public RoutingItem SelectedRouting { get; set; }
private IObservableCollection<RulesItemModel> _rulesItems = new ObservableCollectionExtended<RulesItemModel>();
public IObservableCollection<RulesItemModel> RulesItems => _rulesItems;
[Reactive]
public RulesItemModel SelectedSource { get; set; }
public IList<RulesItemModel> SelectedSources { get; set; }
public ReactiveCommand<Unit, Unit> RuleAddCmd { get; }
public ReactiveCommand<Unit, Unit> ImportRulesFromFileCmd { get; }
public ReactiveCommand<Unit, Unit> ImportRulesFromClipboardCmd { get; }
public ReactiveCommand<Unit, Unit> ImportRulesFromUrlCmd { get; }
public ReactiveCommand<Unit, Unit> RuleRemoveCmd { get; }
public ReactiveCommand<Unit, Unit> RuleExportSelectedCmd { get; }
public ReactiveCommand<Unit, Unit> MoveTopCmd { get; }
public ReactiveCommand<Unit, Unit> MoveUpCmd { get; }
public ReactiveCommand<Unit, Unit> MoveDownCmd { get; }
public ReactiveCommand<Unit, Unit> MoveBottomCmd { get; }
public ReactiveCommand<Unit, Unit> SaveCmd { get; }
public RoutingRuleSettingViewModel(RoutingItem routingItem, Func<EViewAction, object?, bool>? updateView)
{
_config = LazyConfig.Instance.Config;
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_updateView = updateView;
SelectedSource = new();
if (routingItem.id.IsNullOrEmpty())
{
SelectedRouting = routingItem;
_rules = new();
}
else
{
SelectedRouting = routingItem;
_rules = JsonUtils.Deserialize<List<RulesItem>>(SelectedRouting.ruleSet);
}
RefreshRulesItems();
var canEditRemove = this.WhenAnyValue(
x => x.SelectedSource,
selectedSource => selectedSource != null && !selectedSource.outboundTag.IsNullOrEmpty());
RuleAddCmd = ReactiveCommand.Create(() =>
{
RuleEdit(true);
});
ImportRulesFromFileCmd = ReactiveCommand.Create(() =>
{
_updateView?.Invoke(EViewAction.ImportRulesFromFile, null);
});
ImportRulesFromClipboardCmd = ReactiveCommand.Create(() =>
{
ImportRulesFromClipboard(null);
});
ImportRulesFromUrlCmd = ReactiveCommand.Create(() =>
{
ImportRulesFromUrl();
});
RuleRemoveCmd = ReactiveCommand.Create(() =>
{
RuleRemove();
}, canEditRemove);
RuleExportSelectedCmd = ReactiveCommand.Create(() =>
{
RuleExportSelected();
}, canEditRemove);
MoveTopCmd = ReactiveCommand.Create(() =>
{
MoveRule(EMove.Top);
}, canEditRemove);
MoveUpCmd = ReactiveCommand.Create(() =>
{
MoveRule(EMove.Up);
}, canEditRemove);
MoveDownCmd = ReactiveCommand.Create(() =>
{
MoveRule(EMove.Down);
}, canEditRemove);
MoveBottomCmd = ReactiveCommand.Create(() =>
{
MoveRule(EMove.Bottom);
}, canEditRemove);
SaveCmd = ReactiveCommand.Create(() =>
{
SaveRouting();
});
}
public void RefreshRulesItems()
{
_rulesItems.Clear();
foreach (var item in _rules)
{
var it = new RulesItemModel()
{
id = item.id,
outboundTag = item.outboundTag,
port = item.port,
network = item.network,
protocols = Utils.List2String(item.protocol),
inboundTags = Utils.List2String(item.inboundTag),
domains = Utils.List2String(item.domain),
ips = Utils.List2String(item.ip),
enabled = item.enabled,
};
_rulesItems.Add(it);
}
}
public void RuleEdit(bool blNew)
{
RulesItem? item;
if (blNew)
{
item = new();
}
else
{
item = _rules.FirstOrDefault(t => t.id == SelectedSource?.id);
if (item is null)
{
return;
}
}
if (_updateView?.Invoke(EViewAction.RoutingRuleDetailsWindow, item) == true)
{
if (blNew)
{
_rules.Add(item);
}
RefreshRulesItems();
}
}
public void RuleRemove()
{
if (SelectedSource is null || SelectedSource.outboundTag.IsNullOrEmpty())
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectRules);
return;
}
if (_updateView?.Invoke(EViewAction.ShowYesNo, null) == false)
{
return;
}
foreach (var it in SelectedSources)
{
var item = _rules.FirstOrDefault(t => t.id == it?.id);
if (item != null)
{
_rules.Remove(item);
}
}
RefreshRulesItems();
}
public void RuleExportSelected()
{
if (SelectedSource is null || SelectedSource.outboundTag.IsNullOrEmpty())
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectRules);
return;
}
var lst = new List<RulesItem4Ray>();
foreach (var it in SelectedSources)
{
var item = _rules.FirstOrDefault(t => t.id == it?.id);
if (item != null)
{
var item2 = JsonUtils.Deserialize<RulesItem4Ray>(JsonUtils.Serialize(item));
lst.Add(item2 ?? new());
}
}
if (lst.Count > 0)
{
_updateView?.Invoke(EViewAction.SetClipboardData, JsonUtils.Serialize(lst));
}
}
public void MoveRule(EMove eMove)
{
if (SelectedSource is null || SelectedSource.outboundTag.IsNullOrEmpty())
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectRules);
return;
}
var item = _rules.FirstOrDefault(t => t.id == SelectedSource?.id);
if (item == null)
{
return;
}
var index = _rules.IndexOf(item);
if (ConfigHandler.MoveRoutingRule(_rules, index, eMove) == 0)
{
RefreshRulesItems();
}
}
private void SaveRouting()
{
string remarks = SelectedRouting.remarks;
if (Utils.IsNullOrEmpty(remarks))
{
_noticeHandler?.Enqueue(ResUI.PleaseFillRemarks);
return;
}
var item = SelectedRouting;
foreach (var it in _rules)
{
it.id = Utils.GetGUID(false);
}
item.ruleNum = _rules.Count;
item.ruleSet = JsonUtils.Serialize(_rules, false);
if (ConfigHandler.SaveRoutingItem(_config, item) == 0)
{
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null);
}
else
{
_noticeHandler?.Enqueue(ResUI.OperationFailed);
}
}
#region Import rules
public void ImportRulesFromFile(string fileName)
{
if (Utils.IsNullOrEmpty(fileName))
{
return;
}
string result = Utils.LoadResource(fileName);
if (Utils.IsNullOrEmpty(result))
{
return;
}
if (AddBatchRoutingRules(SelectedRouting, result) == 0)
{
RefreshRulesItems();
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
}
}
public void ImportRulesFromClipboard(string? clipboardData)
{
if (clipboardData == null)
{
_updateView?.Invoke(EViewAction.ImportRulesFromClipboard, null);
return;
}
if (AddBatchRoutingRules(SelectedRouting, clipboardData) == 0)
{
RefreshRulesItems();
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
}
}
private void ImportRulesFromUrl()
{
var url = SelectedRouting.url;
if (Utils.IsNullOrEmpty(url))
{
_noticeHandler?.Enqueue(ResUI.MsgNeedUrl);
return;
}
DownloadHandler downloadHandle = new DownloadHandler();
var result = downloadHandle.TryDownloadString(url, true, "").Result;
if (AddBatchRoutingRules(SelectedRouting, result) == 0)
{
RefreshRulesItems();
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
}
}
private int AddBatchRoutingRules(RoutingItem routingItem, string? clipboardData)
{
bool blReplace = false;
if (_updateView?.Invoke(EViewAction.AddBatchRoutingRulesYesNo, null) == false)
{
blReplace = true;
}
if (Utils.IsNullOrEmpty(clipboardData))
{
return -1;
}
var lstRules = JsonUtils.Deserialize<List<RulesItem>>(clipboardData);
if (lstRules == null)
{
return -1;
}
foreach (var rule in lstRules)
{
rule.id = Utils.GetGUID(false);
}
if (blReplace)
{
_rules = lstRules;
}
else
{
_rules.AddRange(lstRules);
}
return 0;
}
#endregion Import rules
}
}
@@ -0,0 +1,297 @@
using DynamicData.Binding;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
namespace ServiceLib.ViewModels
{
public class RoutingSettingViewModel : MyReactiveObject
{
private RoutingItem _lockedItem;
private List<RulesItem> _lockedRules;
#region Reactive
private IObservableCollection<RoutingItemModel> _routingItems = new ObservableCollectionExtended<RoutingItemModel>();
public IObservableCollection<RoutingItemModel> RoutingItems => _routingItems;
[Reactive]
public RoutingItemModel SelectedSource { get; set; }
public IList<RoutingItemModel> SelectedSources { get; set; }
[Reactive]
public bool enableRoutingAdvanced { get; set; }
[Reactive]
public bool enableRoutingBasic { get; set; }
[Reactive]
public string domainStrategy { get; set; }
[Reactive]
public string domainMatcher { get; set; }
[Reactive]
public string domainStrategy4Singbox { get; set; }
[Reactive]
public string ProxyDomain { get; set; }
[Reactive]
public string ProxyIP { get; set; }
[Reactive]
public string DirectDomain { get; set; }
[Reactive]
public string DirectIP { get; set; }
[Reactive]
public string BlockDomain { get; set; }
[Reactive]
public string BlockIP { get; set; }
public ReactiveCommand<Unit, Unit> RoutingBasicImportRulesCmd { get; }
public ReactiveCommand<Unit, Unit> RoutingAdvancedAddCmd { get; }
public ReactiveCommand<Unit, Unit> RoutingAdvancedRemoveCmd { get; }
public ReactiveCommand<Unit, Unit> RoutingAdvancedSetDefaultCmd { get; }
public ReactiveCommand<Unit, Unit> RoutingAdvancedImportRulesCmd { get; }
public ReactiveCommand<Unit, Unit> SaveCmd { get; }
public bool IsModified { get; set; }
#endregion Reactive
public RoutingSettingViewModel(Func<EViewAction, object?, bool>? updateView)
{
_config = LazyConfig.Instance.Config;
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_updateView = updateView;
SelectedSource = new();
ConfigHandler.InitBuiltinRouting(_config);
enableRoutingAdvanced = _config.routingBasicItem.enableRoutingAdvanced;
domainStrategy = _config.routingBasicItem.domainStrategy;
domainMatcher = _config.routingBasicItem.domainMatcher;
domainStrategy4Singbox = _config.routingBasicItem.domainStrategy4Singbox;
RefreshRoutingItems();
BindingLockedData();
var canEditRemove = this.WhenAnyValue(
x => x.SelectedSource,
selectedSource => selectedSource != null && !selectedSource.remarks.IsNullOrEmpty());
this.WhenAnyValue(
x => x.enableRoutingAdvanced)
.Subscribe(c => enableRoutingBasic = !enableRoutingAdvanced);
RoutingBasicImportRulesCmd = ReactiveCommand.Create(() =>
{
RoutingBasicImportRules();
});
RoutingAdvancedAddCmd = ReactiveCommand.Create(() =>
{
RoutingAdvancedEdit(true);
});
RoutingAdvancedRemoveCmd = ReactiveCommand.Create(() =>
{
RoutingAdvancedRemove();
}, canEditRemove);
RoutingAdvancedSetDefaultCmd = ReactiveCommand.Create(() =>
{
RoutingAdvancedSetDefault();
}, canEditRemove);
RoutingAdvancedImportRulesCmd = ReactiveCommand.Create(() =>
{
RoutingAdvancedImportRules();
});
SaveCmd = ReactiveCommand.Create(() =>
{
SaveRouting();
});
}
#region locked
private void BindingLockedData()
{
_lockedItem = ConfigHandler.GetLockedRoutingItem(_config);
if (_lockedItem != null)
{
_lockedRules = JsonUtils.Deserialize<List<RulesItem>>(_lockedItem.ruleSet);
ProxyDomain = Utils.List2String(_lockedRules[0].domain, true);
ProxyIP = Utils.List2String(_lockedRules[0].ip, true);
DirectDomain = Utils.List2String(_lockedRules[1].domain, true);
DirectIP = Utils.List2String(_lockedRules[1].ip, true);
BlockDomain = Utils.List2String(_lockedRules[2].domain, true);
BlockIP = Utils.List2String(_lockedRules[2].ip, true);
}
}
private void EndBindingLockedData()
{
if (_lockedItem != null)
{
_lockedRules[0].domain = Utils.String2List(Utils.Convert2Comma(ProxyDomain.TrimEx()));
_lockedRules[0].ip = Utils.String2List(Utils.Convert2Comma(ProxyIP.TrimEx()));
_lockedRules[1].domain = Utils.String2List(Utils.Convert2Comma(DirectDomain.TrimEx()));
_lockedRules[1].ip = Utils.String2List(Utils.Convert2Comma(DirectIP.TrimEx()));
_lockedRules[2].domain = Utils.String2List(Utils.Convert2Comma(BlockDomain.TrimEx()));
_lockedRules[2].ip = Utils.String2List(Utils.Convert2Comma(BlockIP.TrimEx()));
_lockedItem.ruleSet = JsonUtils.Serialize(_lockedRules, false);
ConfigHandler.SaveRoutingItem(_config, _lockedItem);
}
}
#endregion locked
#region Refresh Save
public void RefreshRoutingItems()
{
_routingItems.Clear();
var routings = LazyConfig.Instance.RoutingItems();
foreach (var item in routings)
{
bool def = false;
if (item.id == _config.routingBasicItem.routingIndexId)
{
def = true;
}
var it = new RoutingItemModel()
{
isActive = def,
ruleNum = item.ruleNum,
id = item.id,
remarks = item.remarks,
url = item.url,
customIcon = item.customIcon,
customRulesetPath4Singbox = item.customRulesetPath4Singbox,
sort = item.sort,
};
_routingItems.Add(it);
}
}
private void SaveRouting()
{
_config.routingBasicItem.domainStrategy = domainStrategy;
_config.routingBasicItem.enableRoutingAdvanced = enableRoutingAdvanced;
_config.routingBasicItem.domainMatcher = domainMatcher;
_config.routingBasicItem.domainStrategy4Singbox = domainStrategy4Singbox;
EndBindingLockedData();
if (ConfigHandler.SaveConfig(_config) == 0)
{
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null);
}
else
{
_noticeHandler?.Enqueue(ResUI.OperationFailed);
}
}
#endregion Refresh Save
private void RoutingBasicImportRules()
{
//Extra to bypass the mainland
ProxyDomain = "geosite:google";
DirectDomain = "geosite:cn";
DirectIP = "geoip:private,geoip:cn";
BlockDomain = "geosite:category-ads-all";
//_noticeHandler?.Enqueue(ResUI.OperationSuccess);
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
}
public void RoutingAdvancedEdit(bool blNew)
{
RoutingItem item;
if (blNew)
{
item = new();
}
else
{
item = LazyConfig.Instance.GetRoutingItem(SelectedSource?.id);
if (item is null)
{
return;
}
}
if (_updateView?.Invoke(EViewAction.RoutingRuleSettingWindow, item) == true)
{
RefreshRoutingItems();
IsModified = true;
}
}
public void RoutingAdvancedRemove()
{
if (SelectedSource is null || SelectedSource.remarks.IsNullOrEmpty())
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectRules);
return;
}
if (_updateView?.Invoke(EViewAction.ShowYesNo, null) == false)
{
return;
}
foreach (var it in SelectedSources)
{
var item = LazyConfig.Instance.GetRoutingItem(it?.id);
if (item != null)
{
ConfigHandler.RemoveRoutingItem(item);
}
}
RefreshRoutingItems();
IsModified = true;
}
public void RoutingAdvancedSetDefault()
{
var item = LazyConfig.Instance.GetRoutingItem(SelectedSource?.id);
if (item is null)
{
_noticeHandler?.Enqueue(ResUI.PleaseSelectRules);
return;
}
if (ConfigHandler.SetDefaultRouting(_config, item) == 0)
{
RefreshRoutingItems();
IsModified = true;
}
}
private void RoutingAdvancedImportRules()
{
if (ConfigHandler.InitBuiltinRouting(_config, true) == 0)
{
RefreshRoutingItems();
IsModified = true;
}
}
}
}
@@ -0,0 +1,56 @@
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
namespace ServiceLib.ViewModels
{
public class SubEditViewModel : MyReactiveObject
{
[Reactive]
public SubItem SelectedSource { get; set; }
public ReactiveCommand<Unit, Unit> SaveCmd { get; }
public SubEditViewModel(SubItem subItem, Func<EViewAction, object?, bool>? updateView)
{
_config = LazyConfig.Instance.Config;
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_updateView = updateView;
if (subItem.id.IsNullOrEmpty())
{
SelectedSource = subItem;
}
else
{
SelectedSource = JsonUtils.DeepCopy(subItem);
}
SaveCmd = ReactiveCommand.Create(() =>
{
SaveSub();
});
}
private void SaveSub()
{
string remarks = SelectedSource.remarks;
if (Utils.IsNullOrEmpty(remarks))
{
_noticeHandler?.Enqueue(ResUI.PleaseFillRemarks);
return;
}
if (ConfigHandler.AddSubItem(_config, SelectedSource) == 0)
{
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
_updateView?.Invoke(EViewAction.CloseWindow, null);
}
else
{
_noticeHandler?.Enqueue(ResUI.OperationFailed);
}
}
}
}
@@ -0,0 +1,102 @@
using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System.Reactive;
namespace ServiceLib.ViewModels
{
public class SubSettingViewModel : MyReactiveObject
{
private IObservableCollection<SubItem> _subItems = new ObservableCollectionExtended<SubItem>();
public IObservableCollection<SubItem> SubItems => _subItems;
[Reactive]
public SubItem SelectedSource { get; set; }
public IList<SubItem> SelectedSources { get; set; }
public ReactiveCommand<Unit, Unit> SubAddCmd { get; }
public ReactiveCommand<Unit, Unit> SubDeleteCmd { get; }
public ReactiveCommand<Unit, Unit> SubEditCmd { get; }
public ReactiveCommand<Unit, Unit> SubShareCmd { get; }
public bool IsModified { get; set; }
public SubSettingViewModel(Func<EViewAction, object?, bool>? updateView)
{
_config = LazyConfig.Instance.Config;
_noticeHandler = Locator.Current.GetService<NoticeHandler>();
_updateView = updateView;
SelectedSource = new();
RefreshSubItems();
var canEditRemove = this.WhenAnyValue(
x => x.SelectedSource,
selectedSource => selectedSource != null && !selectedSource.id.IsNullOrEmpty());
SubAddCmd = ReactiveCommand.Create(() =>
{
EditSub(true);
});
SubDeleteCmd = ReactiveCommand.Create(() =>
{
DeleteSub();
}, canEditRemove);
SubEditCmd = ReactiveCommand.Create(() =>
{
EditSub(false);
}, canEditRemove);
SubShareCmd = ReactiveCommand.Create(() =>
{
_updateView?.Invoke(EViewAction.ShareSub, SelectedSource?.url);
}, canEditRemove);
}
public void RefreshSubItems()
{
_subItems.Clear();
_subItems.AddRange(LazyConfig.Instance.SubItems().OrderBy(t => t.sort));
}
public void EditSub(bool blNew)
{
SubItem item;
if (blNew)
{
item = new();
}
else
{
item = LazyConfig.Instance.GetSubItem(SelectedSource?.id);
if (item is null)
{
return;
}
}
if (_updateView?.Invoke(EViewAction.SubEditWindow, item) == true)
{
RefreshSubItems();
IsModified = true;
}
}
private void DeleteSub()
{
if (_updateView?.Invoke(EViewAction.ShowYesNo, null) == false)
{
return;
}
foreach (var it in SelectedSources)
{
ConfigHandler.DeleteSubItem(_config, it.id);
}
RefreshSubItems();
_noticeHandler?.Enqueue(ResUI.OperationSuccess);
IsModified = true;
}
}
}