Skip to content

Commit

Permalink
Refactor code to decouple view and viewmodel
Browse files Browse the repository at this point in the history
  • Loading branch information
2dust committed Aug 17, 2024
1 parent a986041 commit 7faabdc
Show file tree
Hide file tree
Showing 14 changed files with 304 additions and 299 deletions.
1 change: 1 addition & 0 deletions v2rayN/v2rayN/Enums/EViewAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ public enum EViewAction
{
CloseWindow,
ShowYesNo,
SaveFileDialog,
AddBatchRoutingRulesYesNo,
AdjustMainLvColWidth,
ProfilesFocus,
Expand Down
101 changes: 93 additions & 8 deletions v2rayN/v2rayN/Handler/ConfigHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -355,13 +355,64 @@ private static void ToJsonFile(Config config)

#region Server

public static int AddServer(Config config, ProfileItem profileItem)
{
var item = LazyConfig.Instance.GetProfileItem(profileItem.indexId);
if (item is null)
{
item = profileItem;
}
else
{
item.coreType = profileItem.coreType;
item.remarks = profileItem.remarks;
item.address = profileItem.address;
item.port = profileItem.port;

item.id = profileItem.id;
item.alterId = profileItem.alterId;
item.security = profileItem.security;
item.flow = profileItem.flow;

item.network = profileItem.network;
item.headerType = profileItem.headerType;
item.requestHost = profileItem.requestHost;
item.path = profileItem.path;

item.streamSecurity = profileItem.streamSecurity;
item.sni = profileItem.sni;
item.allowInsecure = profileItem.allowInsecure;
item.fingerprint = profileItem.fingerprint;
item.alpn = profileItem.alpn;

item.publicKey = profileItem.publicKey;
item.shortId = profileItem.shortId;
item.spiderX = profileItem.spiderX;
}

var ret = item.configType switch
{
EConfigType.VMess => AddVMessServer(config, item),
EConfigType.Shadowsocks => AddShadowsocksServer(config, item),
EConfigType.Socks => AddSocksServer(config, item),
EConfigType.Http => AddHttpServer(config, item),
EConfigType.Trojan => AddTrojanServer(config, item),
EConfigType.VLESS => AddVlessServer(config, item),
EConfigType.Hysteria2 => AddHysteria2Server(config, item),
EConfigType.Tuic => AddTuicServer(config, item),
EConfigType.Wireguard => AddWireguardServer(config, item),
_ => -1,
};
return ret;
}

/// <summary>
/// Add or edit server
/// </summary>
/// <param name="config"></param>
/// <param name="profileItem"></param>
/// <returns></returns>
public static int AddServer(Config config, ProfileItem profileItem, bool toFile = true)
public static int AddVMessServer(Config config, ProfileItem profileItem, bool toFile = true)
{
profileItem.configType = EConfigType.VMess;

Expand Down Expand Up @@ -619,7 +670,21 @@ public static int AddCustomServer(Config config, ProfileItem profileItem, bool b
/// <returns></returns>
public static int EditCustomServer(Config config, ProfileItem profileItem)
{
if (SQLiteHelper.Instance.Update(profileItem) > 0)
var item = LazyConfig.Instance.GetProfileItem(profileItem.indexId);
if (item is null)
{
item = profileItem;
}
else
{
item.remarks = profileItem.remarks;
item.address = profileItem.address;
item.coreType = profileItem.coreType;
item.displayLog = profileItem.displayLog;
item.preSocksPort = profileItem.preSocksPort;
}

if (SQLiteHelper.Instance.Update(item) > 0)
{
return 0;
}
Expand Down Expand Up @@ -1189,7 +1254,7 @@ private static int AddBatchServers(Config config, string strData, string subid,

var addStatus = profileItem.configType switch
{
EConfigType.VMess => AddServer(config, profileItem, false),
EConfigType.VMess => AddVMessServer(config, profileItem, false),
EConfigType.Shadowsocks => AddShadowsocksServer(config, profileItem, false),
EConfigType.Socks => AddSocksServer(config, profileItem, false),
EConfigType.Trojan => AddTrojanServer(config, profileItem, false),
Expand Down Expand Up @@ -1419,21 +1484,41 @@ public static int AddSubItem(Config config, string url)

public static int AddSubItem(Config config, SubItem subItem)
{
if (Utils.IsNullOrEmpty(subItem.id))
var item = LazyConfig.Instance.GetSubItem(subItem.id);
if (item is null)
{
item = subItem;
}
else
{
subItem.id = Utils.GetGUID(false);
item.remarks = subItem.remarks;
item.url = subItem.url;
item.moreUrl = subItem.moreUrl;
item.enabled = subItem.enabled;
item.autoUpdateInterval = subItem.autoUpdateInterval;
item.userAgent = subItem.userAgent;
item.sort = subItem.sort;
item.filter = subItem.filter;
item.convertTarget = subItem.convertTarget;
item.prevProfile = subItem.prevProfile;
item.nextProfile = subItem.nextProfile;
}

if (Utils.IsNullOrEmpty(item.id))
{
item.id = Utils.GetGUID(false);

if (subItem.sort <= 0)
if (item.sort <= 0)
{
var maxSort = 0;
if (SQLiteHelper.Instance.Table<SubItem>().Count() > 0)
{
maxSort = SQLiteHelper.Instance.Table<SubItem>().Max(t => t == null ? 0 : t.sort);
}
subItem.sort = maxSort + 1;
item.sort = maxSort + 1;
}
}
if (SQLiteHelper.Instance.Replace(subItem) > 0)
if (SQLiteHelper.Instance.Replace(item) > 0)
{
return 0;
}
Expand Down
40 changes: 40 additions & 0 deletions v2rayN/v2rayN/Handler/LazyConfig.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using v2rayN.Enums;
using v2rayN.Handler.Statistics;
using v2rayN.Models;

namespace v2rayN.Handler
Expand Down Expand Up @@ -119,6 +120,45 @@ from ProfileItem a
return SQLiteHelper.Instance.Query<ProfileItemModel>(sql).ToList();
}

public List<ProfileItemModel> ProfileItemsEx(string subid, string filter)
{
var lstModel = ProfileItems(_config.subIndexId, filter);

ConfigHandler.SetDefaultServer(_config, lstModel);

var lstServerStat = (_config.guiItem.enableStatistics ? StatisticsHandler.Instance.ServerStat : null) ?? [];
var lstProfileExs = ProfileExHandler.Instance.ProfileExs;
lstModel = (from t in lstModel
join t2 in lstServerStat on t.indexId equals t2.indexId into t2b
from t22 in t2b.DefaultIfEmpty()
join t3 in lstProfileExs on t.indexId equals t3.indexId into t3b
from t33 in t3b.DefaultIfEmpty()
select new ProfileItemModel
{
indexId = t.indexId,
configType = t.configType,
remarks = t.remarks,
address = t.address,
port = t.port,
security = t.security,
network = t.network,
streamSecurity = t.streamSecurity,
subid = t.subid,
subRemarks = t.subRemarks,
isActive = t.indexId == _config.indexId,
sort = t33 == null ? 0 : t33.sort,
delay = t33 == null ? 0 : t33.delay,
delayVal = t33?.delay != 0 ? $"{t33?.delay} {Global.DelayUnit}" : string.Empty,
speedVal = t33?.speed != 0 ? $"{t33?.speed} {Global.SpeedUnit}" : string.Empty,
todayDown = t22 == null ? "" : Utils.HumanFy(t22.todayDown),
todayUp = t22 == null ? "" : Utils.HumanFy(t22.todayUp),
totalDown = t22 == null ? "" : Utils.HumanFy(t22.totalDown),
totalUp = t22 == null ? "" : Utils.HumanFy(t22.totalUp)
}).OrderBy(t => t.sort).ToList();

return lstModel;
}

public ProfileItem? GetProfileItem(string indexId)
{
if (Utils.IsNullOrEmpty(indexId))
Expand Down
78 changes: 78 additions & 0 deletions v2rayN/v2rayN/Handler/TaskHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using v2rayN.Models;

namespace v2rayN.Handler
{
internal class TaskHandler
{
private static readonly Lazy<TaskHandler> _instance = new(() => new());
public static TaskHandler Instance => _instance.Value;

public TaskHandler()
{
}

public void RegUpdateTask(Config config, Action<bool, string> update)
{
Task.Run(() => UpdateTaskRunSubscription(config, update));
Task.Run(() => UpdateTaskRunGeo(config, update));
}

private async Task UpdateTaskRunSubscription(Config config, Action<bool, string> update)
{
await Task.Delay(60000);
Logging.SaveLog("UpdateTaskRunSubscription");

var updateHandle = new UpdateHandler();
while (true)
{
var updateTime = ((DateTimeOffset)DateTime.Now).ToUnixTimeSeconds();
var lstSubs = LazyConfig.Instance.SubItems()
.Where(t => t.autoUpdateInterval > 0)
.Where(t => updateTime - t.updateTime >= t.autoUpdateInterval * 60)
.ToList();

foreach (var item in lstSubs)
{
updateHandle.UpdateSubscriptionProcess(config, item.id, true, (bool success, string msg) =>
{
update(success, msg);
if (success)
Logging.SaveLog("subscription" + msg);
});
item.updateTime = updateTime;
ConfigHandler.AddSubItem(config, item);

await Task.Delay(5000);
}
await Task.Delay(60000);
}
}

private async Task UpdateTaskRunGeo(Config config, Action<bool, string> update)
{
var autoUpdateGeoTime = DateTime.Now;

await Task.Delay(1000 * 120);
Logging.SaveLog("UpdateTaskRunGeo");

var updateHandle = new UpdateHandler();
while (true)
{
var dtNow = DateTime.Now;
if (config.guiItem.autoUpdateInterval > 0)
{
if ((dtNow - autoUpdateGeoTime).Hours % config.guiItem.autoUpdateInterval == 0)
{
updateHandle.UpdateGeoFileAll(config, (bool success, string msg) =>
{
update(false, msg);
});
autoUpdateGeoTime = dtNow;
}
}

await Task.Delay(1000 * 3600);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,15 @@
using Microsoft.Win32;
using Splat;
using System.Drawing;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using v2rayN.Enums;
using v2rayN.Handler.CoreConfig;
using v2rayN.Models;
using v2rayN.Resx;

namespace v2rayN.Handler
{
public sealed class MainFormHandler
public sealed class WindowsHandler
{
private static readonly Lazy<MainFormHandler> instance = new(() => new());
public static MainFormHandler Instance => instance.Value;
private static readonly Lazy<WindowsHandler> instance = new(() => new());
public static WindowsHandler Instance => instance.Value;

public Icon GetNotifyIcon(Config config)
{
Expand Down Expand Up @@ -123,66 +116,11 @@ public System.Windows.Media.ImageSource GetAppIcon(Config config)
}
}

public void Export2ClientConfig(ProfileItem item, Config config)
{
if (item == null)
{
return;
}

SaveFileDialog fileDialog = new()
{
Filter = "Config|*.json",
FilterIndex = 2,
RestoreDirectory = true
};
if (fileDialog.ShowDialog() != true)
{
return;
}
string fileName = fileDialog.FileName;
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 RegisterGlobalHotkey(Config config, Action<EGlobalHotkey> handler, Action<bool, string>? update)
{
HotkeyHandler.Instance.UpdateViewEvent += update;
HotkeyHandler.Instance.HotkeyTriggerEvent += handler;
HotkeyHandler.Instance.Load();
}

public void RegisterSystemColorSet(Config config, Window window, Action<bool> update)
{
var helper = new WindowInteropHelper(window);
var hwndSource = HwndSource.FromHwnd(helper.EnsureHandle());
hwndSource.AddHook((IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) =>
{
if (config.uiItem.followSystemTheme)
{
const int WM_SETTINGCHANGE = 0x001A;
if (msg == WM_SETTINGCHANGE)
{
if (wParam == IntPtr.Zero && Marshal.PtrToStringUni(lParam) == "ImmersiveColorSet")
{
update(!WindowsUtils.IsLightTheme());
}
}
}
return IntPtr.Zero;
});
}
}
}
Loading

0 comments on commit 7faabdc

Please sign in to comment.