Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
2dust committed Feb 8, 2024
1 parent 05e424f commit e2c8367
Show file tree
Hide file tree
Showing 11 changed files with 63 additions and 34 deletions.
6 changes: 2 additions & 4 deletions v2rayN/v2rayN/App.xaml.cs
Expand Up @@ -27,10 +27,10 @@ public App()
/// <param name="e"></param>
protected override void OnStartup(StartupEventArgs e)
{
Global.ExePathKey = Utils.GetMD5(Utils.GetExePath());
var exePathKey = Utils.GetMD5(Utils.GetExePath());

var rebootas = (e.Args ?? new string[] { }).Any(t => t == Global.RebootAs);
ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, Global.ExePathKey, out bool bCreatedNew);
ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, exePathKey, out bool bCreatedNew);
if (!rebootas && !bCreatedNew)
{
ProgramStarted.Set();
Expand All @@ -39,8 +39,6 @@ protected override void OnStartup(StartupEventArgs e)
return;
}

Global.ProcessJob = new Job();

Logging.Setup();
Init();
Logging.LoggingEnabled(_config.guiItem.enableLog);
Expand Down
22 changes: 22 additions & 0 deletions v2rayN/v2rayN/Common/Utils.cs
Expand Up @@ -576,6 +576,28 @@ public static bool PortInUse(int port)
return inUse;
}

public static int GetFreePort()
{
try
{
int defaultPort = 9090;
if (!Utils.PortInUse(defaultPort))
{
return defaultPort;
}

TcpListener l = new(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
catch
{
}
return 69090;
}

#endregion 测速

#region 杂项
Expand Down
10 changes: 1 addition & 9 deletions v2rayN/v2rayN/Global.cs
Expand Up @@ -118,6 +118,7 @@ internal class Global
@"http://cachefly.cachefly.net/100mb.test",
@"http://cachefly.cachefly.net/10mb.test"
};

public static readonly List<string> SpeedPingTestUrls = new() {
@"https://www.google.com/generate_204",
};
Expand Down Expand Up @@ -187,14 +188,5 @@ internal class Global
public static readonly List<string> TuicCongestionControls = new() { "cubic", "new_reno", "bbr" };

#endregion const

#region global variable

public static int StatePort { get; set; }
public static Job ProcessJob { get; set; }
public static bool ShowInTaskbar { get; set; }
public static string ExePathKey { get; set; }

#endregion global variable
}
}
2 changes: 1 addition & 1 deletion v2rayN/v2rayN/Handler/CoreConfigSingbox.cs
Expand Up @@ -811,7 +811,7 @@ private int GenStatistic(SingboxConfig singboxConfig)
//},
clash_api = new Clash_Api4Sbox()
{
external_controller = $"{Global.Loopback}:{Global.StatePort}",
external_controller = $"{Global.Loopback}:{LazyConfig.Instance.StatePort}",
}
};
}
Expand Down
2 changes: 1 addition & 1 deletion v2rayN/v2rayN/Handler/CoreConfigV2ray.cs
Expand Up @@ -788,7 +788,7 @@ private int GenStatistic(V2rayConfig v2rayConfig)
Inboundsettings4Ray apiInboundSettings = new();
apiInbound.tag = tag;
apiInbound.listen = Global.Loopback;
apiInbound.port = Global.StatePort;
apiInbound.port = LazyConfig.Instance.StatePort;
apiInbound.protocol = Global.InboundAPIProtocal;
apiInboundSettings.address = Global.Loopback;
apiInbound.settings = apiInboundSettings;
Expand Down
2 changes: 1 addition & 1 deletion v2rayN/v2rayN/Handler/CoreHandler.cs
Expand Up @@ -316,7 +316,7 @@ private void ShowMsg(bool updateToTrayTooltip, string msg)
throw new Exception(displayLog ? proc.StandardError.ReadToEnd() : "启动进程失败并退出 (Failed to start the process and exited)");
}

Global.ProcessJob.AddProcess(proc.Handle);
LazyConfig.Instance.AddProcess(proc.Handle);
return proc;
}
catch (Exception ex)
Expand Down
17 changes: 16 additions & 1 deletion v2rayN/v2rayN/Handler/LazyConfig.cs
Expand Up @@ -11,8 +11,14 @@ public sealed class LazyConfig

public static LazyConfig Instance => _instance.Value;

private int _statePort;
public int StatePort { get => _statePort; }
private Job _processJob = new();

public LazyConfig()
{
_statePort = Utils.GetFreePort();

SqliteHelper.Instance.CreateTable<SubItem>();
SqliteHelper.Instance.CreateTable<ProfileItem>();
SqliteHelper.Instance.CreateTable<ServerStatItem>();
Expand Down Expand Up @@ -62,6 +68,15 @@ public int GetLocalPort(string protocol)
}
return localPort;
}

public void AddProcess(IntPtr processHandle)
{
_processJob.AddProcess(processHandle);
}

#endregion Config

#region SqliteHelper

public List<SubItem> SubItems()
{
Expand Down Expand Up @@ -158,7 +173,7 @@ public DNSItem GetDNSItem(ECoreType eCoreType)
return SqliteHelper.Instance.Table<DNSItem>().FirstOrDefault(it => it.coreType == eCoreType);
}

#endregion Config
#endregion SqliteHelper

#region Core Type

Expand Down
21 changes: 11 additions & 10 deletions v2rayN/v2rayN/Handler/StatisticsHandler.cs
Expand Up @@ -28,7 +28,6 @@ public StatisticsHandler(Config config, Action<ServerSpeedItem> update)
_updateFunc = update;

Init();
Global.StatePort = GetFreePort();

_statisticsV2Ray = new StatisticsV2ray(config, UpdateServerStat);
_statisticsSingbox = new StatisticsSingbox(config, UpdateServerStat);
Expand Down Expand Up @@ -80,22 +79,24 @@ private void UpdateServerStat(ServerSpeedItem server)
{
GetServerStatItem(_config.indexId);

if (_serverStatItem is null)
{
return;
}
if (server.proxyUp != 0 || server.proxyDown != 0)
{
_serverStatItem.todayUp += server.proxyUp;
_serverStatItem.todayDown += server.proxyDown;
_serverStatItem.totalUp += server.proxyUp;
_serverStatItem.totalDown += server.proxyDown;
}
if (Global.ShowInTaskbar)
{
server.indexId = _config.indexId;
server.todayUp = _serverStatItem.todayUp;
server.todayDown = _serverStatItem.todayDown;
server.totalUp = _serverStatItem.totalUp;
server.totalDown = _serverStatItem.totalDown;
_updateFunc(server);
}

server.indexId = _config.indexId;
server.todayUp = _serverStatItem.todayUp;
server.todayDown = _serverStatItem.todayDown;
server.totalUp = _serverStatItem.totalUp;
server.totalDown = _serverStatItem.totalDown;
_updateFunc(server);
}

private void GetServerStatItem(string indexId)
Expand Down
2 changes: 1 addition & 1 deletion v2rayN/v2rayN/Handler/StatisticsSingbox.cs
Expand Up @@ -27,7 +27,7 @@ private async void Init()

try
{
url = $"ws://{Global.Loopback}:{Global.StatePort}/traffic";
url = $"ws://{Global.Loopback}:{LazyConfig.Instance.StatePort}/traffic";

if (webSocket == null)
{
Expand Down
2 changes: 1 addition & 1 deletion v2rayN/v2rayN/Handler/StatisticsV2ray.cs
Expand Up @@ -30,7 +30,7 @@ private void GrpcInit()
{
try
{
_channel = GrpcChannel.ForAddress($"{Global.HttpProtocol}{Global.Loopback}:{Global.StatePort}");
_channel = GrpcChannel.ForAddress($"{Global.HttpProtocol}{Global.Loopback}:{LazyConfig.Instance.StatePort}");
_client = new StatsService.StatsServiceClient(_channel);
}
catch (Exception ex)
Expand Down
11 changes: 6 additions & 5 deletions v2rayN/v2rayN/ViewModels/MainWindowViewModel.cs
Expand Up @@ -35,6 +35,7 @@ public class MainWindowViewModel : ReactiveObject
private readonly PaletteHelper _paletteHelper = new();
private Dictionary<string, bool> _dicHeaderSort = new();
private Action<EViewAction> _updateView;
private bool _showInTaskbar;

#endregion private prop

Expand Down Expand Up @@ -568,7 +569,7 @@ public MainWindowViewModel(ISnackbarMessageQueue snackbarMessageQueue, Action<EV

AutoHideStartup();

Global.ShowInTaskbar = true;
_showInTaskbar = true;
}

private void Init()
Expand Down Expand Up @@ -635,7 +636,7 @@ private void UpdateStatisticsHandler(ServerSpeedItem update)
{
Application.Current.Dispatcher.Invoke((Action)(() =>
{
if (!Global.ShowInTaskbar)
if (!_showInTaskbar)
{
return;
}
Expand Down Expand Up @@ -1183,7 +1184,7 @@ public void TestServerAvailability()
_noticeHandler?.SendMessage(msg, true);
Application.Current.Dispatcher.Invoke((Action)(() =>
{
if (!Global.ShowInTaskbar)
if (!_showInTaskbar)
{
return;
}
Expand Down Expand Up @@ -1658,7 +1659,7 @@ private void DoEnableTun(bool c)

public void ShowHideWindow(bool? blShow)
{
var bl = blShow ?? !Global.ShowInTaskbar;
var bl = blShow ?? !_showInTaskbar;
if (bl)
{
//Application.Current.MainWindow.ShowInTaskbar = true;
Expand All @@ -1677,7 +1678,7 @@ public void ShowHideWindow(bool? blShow)
//IntPtr windowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
//Utils.RegWriteValue(Global.MyRegPath, Utils.WindowHwndKey, Convert.ToString((long)windowHandle));
}
Global.ShowInTaskbar = bl;
_showInTaskbar = bl;
}

private void RestoreUI()
Expand Down

0 comments on commit e2c8367

Please sign in to comment.