From 3311115bdab4fe34519f1868267ec9b5739bf94c Mon Sep 17 00:00:00 2001 From: ChsBuffer <33744752+chsbuffer@users.noreply.github.com> Date: Fri, 7 Aug 2020 02:22:45 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=B7=B2=E5=90=AF=E5=8A=A8?= =?UTF-8?q?=E6=9B=B4=E6=96=B0ACL=E4=BC=9A=E5=B0=86=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E8=AE=BE=E4=B8=BA=E7=AD=89=E5=BE=85=EF=BC=8C=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=AE=A2=E9=98=85=E3=80=81ACL=E3=80=81=E5=90=AF=E5=8A=A8?= =?UTF-8?q?=E7=AD=89=E6=9B=B4=E6=94=B9=E4=B8=BA=E5=BC=82=E6=AD=A5=E6=89=A7?= =?UTF-8?q?=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Netch/Forms/MainForm.Control.cs | 123 ++++++++++---------- Netch/Forms/MainForm.MenuStrip.cs | 179 +++++++++++++++--------------- Netch/Forms/MainForm.Profile.cs | 2 +- Netch/Forms/MainForm.Status.cs | 48 ++++---- Netch/Forms/MainForm.cs | 3 +- 5 files changed, 176 insertions(+), 179 deletions(-) diff --git a/Netch/Forms/MainForm.Control.cs b/Netch/Forms/MainForm.Control.cs index 83dd68df..82e40a7f 100644 --- a/Netch/Forms/MainForm.Control.cs +++ b/Netch/Forms/MainForm.Control.cs @@ -18,7 +18,7 @@ namespace Netch.Forms { private bool _isFirstCloseWindow = true; - private void ControlFun() + private async void ControlFun() { if (State == State.Waiting || State == State.Stopped) { @@ -35,94 +35,87 @@ namespace Netch.Forms return; } - State = State.Starting; - // 清除模式搜索框文本选择 ModeComboBox.Select(0, 0); - Task.Run(() => + State = State.Starting; + + await Task.Run(Firewall.AddNetchFwRules); + + var server = ServerComboBox.SelectedItem as Models.Server; + var mode = ModeComboBox.SelectedItem as Models.Mode; + bool result; + + try { - Task.Run(Firewall.AddNetchFwRules); + // TODO 完善控制器异常处理 + result = _mainController.Start(server, mode); + } + catch (Exception e) + { + if (e is DllNotFoundException || e is FileNotFoundException) + MessageBoxX.Show(e.Message + "\n\n" + i18N.Translate("Missing File or runtime components"), owner: this); + throw; + } - var server = ServerComboBox.SelectedItem as Models.Server; - var mode = ModeComboBox.SelectedItem as Models.Mode; - var result = false; - - try + if (result) + { + State = State.Started; + StatusTextAppend(LocalPortText(server.Type, mode.Type)); + await Task.Run(() => { Bandwidth.NetTraffic(server, mode, _mainController); }); + // 如果勾选启动后最小化 + if (Global.Settings.MinimizeWhenStarted) { - // TODO 完善控制器异常处理 - result = _mainController.Start(server, mode); - } - catch (Exception e) - { - if (e is DllNotFoundException || e is FileNotFoundException) - MessageBoxX.Show(e.Message + "\n\n" + i18N.Translate("Missing File or runtime components"), owner: this); + WindowState = FormWindowState.Minimized; - Netch.Application_OnException(this, new ThreadExceptionEventArgs(e)); - } - - if (result) - { - Task.Run(() => + if (_isFirstCloseWindow) { - State = State.Started; - StatusTextAppend(LocalPortText(server.Type, mode.Type)); - Bandwidth.NetTraffic(server, mode, _mainController); - }); - // 如果勾选启动后最小化 - if (Global.Settings.MinimizeWhenStarted) - { - WindowState = FormWindowState.Minimized; - - if (_isFirstCloseWindow) - { - // 显示提示语 - NotifyTip(i18N.Translate("Netch is now minimized to the notification bar, double click this icon to restore.")); - _isFirstCloseWindow = false; - } - - Hide(); + // 显示提示语 + NotifyTip(i18N.Translate("Netch is now minimized to the notification bar, double click this icon to restore.")); + _isFirstCloseWindow = false; } - if (Global.Settings.StartedTcping) + Hide(); + } + + if (Global.Settings.StartedTcping) + { + // 自动检测延迟 + await Task.Run(() => { - // 自动检测延迟 - Task.Run(() => + while (true) { - while (true) + if (State == State.Started) { - if (State == State.Started) - { - server.Test(); - // 重载服务器列表 - InitServer(); + server.Test(); + // 重载服务器列表 + InitServer(); - Thread.Sleep(Global.Settings.StartedTcping_Interval * 1000); - } - else - { - break; - } + Thread.Sleep(Global.Settings.StartedTcping_Interval * 1000); } - }); - } + else + { + break; + } + } + }); } - else - { - State = State.Stopped; - StatusText(i18N.Translate("Start failed")); - } - }); + } + else + { + State = State.Stopped; + StatusText(i18N.Translate("Start failed")); + } } else { State = State.Stopping; - Task.Run(() => + await Task.Run(async () => { // 停止 _mainController.Stop(); State = State.Stopped; - Task.Run(TestServer); + await Task.Run(TestServer); }); } } diff --git a/Netch/Forms/MainForm.MenuStrip.cs b/Netch/Forms/MainForm.MenuStrip.cs index b09b9443..bb0a0046 100644 --- a/Netch/Forms/MainForm.MenuStrip.cs +++ b/Netch/Forms/MainForm.MenuStrip.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Netch.Controllers; @@ -96,8 +97,13 @@ namespace Netch.Forms Hide(); } - private void UpdateServersFromSubscribeLinksToolStripMenuItem_Click(object sender, EventArgs e) + private async void UpdateServersFromSubscribeLinksToolStripMenuItem_Click(object sender, EventArgs e) { + void DisableItems(bool v) + { + MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ProfileGroupBox.Enabled = ControlButton.Enabled = v; + } + if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1) Global.Settings.UseProxyToUpdateSubscription = false; @@ -107,86 +113,80 @@ namespace Netch.Forms return; } - if (Global.Settings.SubscribeLink.Count > 0) - { - DeleteServerPictureBox.Enabled = false; - UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled = false; - - Task.Run(() => - { - if (Global.Settings.UseProxyToUpdateSubscription) - { - var mode = new Models.Mode - { - Remark = "ProxyUpdate", - Type = 5 - }; - State = State.Starting; - if (_mainController.Start(ServerComboBox.SelectedItem as Models.Server, mode)) - StatusText(i18N.Translate("Starting update subscription")); - } - else - StatusText(i18N.Translate("Starting update subscription")); - - Task.WaitAll(Global.Settings.SubscribeLink.Select(item => Task.Factory.StartNew(() => - { - try - { - var request = WebUtil.CreateRequest(item.Link); - - if (!string.IsNullOrEmpty(item.UserAgent)) request.UserAgent = item.UserAgent; - if (Global.Settings.UseProxyToUpdateSubscription) request.Proxy = new WebProxy($"http://127.0.0.1:{Global.Settings.HTTPLocalPort}"); - - var str = WebUtil.DownloadString(request); - - try - { - str = ShareLink.URLSafeBase64Decode(str); - } - catch - { - // ignored - } - - Global.Settings.Server = Global.Settings.Server.Where(server => server.Group != item.Remark).ToList(); - var result = ShareLink.Parse(str); - - if (result != null) - { - foreach (var x in result) x.Group = item.Remark; - - Global.Settings.Server.AddRange(result); - NotifyTip(i18N.TranslateFormat("Update {1} server(s) from {0}", item.Remark, result.Count)); - } - } - catch (WebException e) - { - NotifyTip($"{i18N.TranslateFormat("Update servers error from {0}", item.Remark)}\n{e.Message}", info: false); - } - })).ToArray()); - - InitServer(); - - Configuration.Save(); - NotifyTip(i18N.Translate("Subscription updated")); - - if (Global.Settings.UseProxyToUpdateSubscription) - { - _mainController.Stop(); - State = State.Stopped; - } - - State = State.Waiting; - DeleteModePictureBox.Enabled = true; - MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true; - UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled = true; - }); - - NotifyTip(i18N.Translate("Updating in the background")); - } - else + if (Global.Settings.SubscribeLink.Count <= 0) { MessageBoxX.Show(i18N.Translate("No subscription link")); + return; + } + + StatusText(i18N.Translate("Starting update subscription")); + DisableItems(false); + if (Global.Settings.UseProxyToUpdateSubscription) + { + var mode = new Models.Mode + { + Remark = "ProxyUpdate", + Type = 5 + }; + _mainController.Start(ServerComboBox.SelectedItem as Models.Server, mode); + } + + var mutex = new Mutex(); + + await Task.WhenAll(Global.Settings.SubscribeLink.Select(async item => await Task.Run(async () => + { + try + { + var request = WebUtil.CreateRequest(item.Link); + + if (!string.IsNullOrEmpty(item.UserAgent)) request.UserAgent = item.UserAgent; + if (Global.Settings.UseProxyToUpdateSubscription) + request.Proxy = new WebProxy($"http://127.0.0.1:{Global.Settings.HTTPLocalPort}"); + + var str = await WebUtil.DownloadStringAsync(request); + + try + { + str = ShareLink.URLSafeBase64Decode(str); + } + catch + { + // ignored + } + + mutex.WaitOne(); + Global.Settings.Server = Global.Settings.Server.Where(server => server.Group != item.Remark).ToList(); + mutex.ReleaseMutex(); + + + var result = ShareLink.Parse(str); + + if (result != null) + { + foreach (var x in result) x.Group = item.Remark; + + Global.Settings.Server.AddRange(result); + NotifyTip(i18N.TranslateFormat("Update {1} server(s) from {0}", item.Remark, result.Count)); + } + } + catch (WebException e) + { + NotifyTip($"{i18N.TranslateFormat("Update servers error from {0}", item.Remark)}\n{e.Message}", info: false); + } + catch (Exception e) + { + Logging.Error(e.ToString()); + } + })).ToArray()); + + Configuration.Save(); + await Task.Run(InitServer); + DisableItems(true); + StatusText(i18N.Translate("Subscription updated")); + + if (Global.Settings.UseProxyToUpdateSubscription) + { + _mainController.Stop(); } } @@ -231,17 +231,22 @@ namespace Netch.Forms UpdateACL(false, sender); } - private void UpdateACL(bool useProxy, object sender) + private async void UpdateACL(bool useProxy, object sender) { + void DisableItems(bool v) + { + ((ToolStripMenuItem) sender).Enabled = v; + } + if (useProxy && ServerComboBox.SelectedIndex == -1) { MessageBoxX.Show(i18N.Translate("Please select a server first")); return; } - ((ToolStripMenuItem) sender).Enabled = false; + DisableItems(false); - Task.Run(async () => + await Task.Run(async () => { if (useProxy) { @@ -251,10 +256,11 @@ namespace Netch.Forms Type = 5 }; State = State.Starting; - if (_mainController.Start(ServerComboBox.SelectedItem as Models.Server, mode)) - StatusText(i18N.Translate("Updating in the background")); + _mainController.Start(ServerComboBox.SelectedItem as Models.Server, mode); + // State = State.Started; } + NotifyTip(i18N.Translate("Updating in the background")); try { var req = WebUtil.CreateRequest(Global.Settings.ACL); @@ -268,19 +274,16 @@ namespace Netch.Forms { NotifyTip(i18N.Translate("ACL update failed") + "\n" + e.Message, info: false); Logging.Error("更新 ACL 失败!" + e); - if (!(e is WebException)) - throw; } finally { - ((ToolStripMenuItem) sender).Enabled = true; if (useProxy) { _mainController.Stop(); State = State.Stopped; } - State = State.Waiting; + DisableItems(true); } }); } diff --git a/Netch/Forms/MainForm.Profile.cs b/Netch/Forms/MainForm.Profile.cs index 10b76170..76a74eb5 100644 --- a/Netch/Forms/MainForm.Profile.cs +++ b/Netch/Forms/MainForm.Profile.cs @@ -173,7 +173,7 @@ namespace Netch.Forms if (MessageBoxX.Show(i18N.Translate("Remove this Profile?"), confirm: true) != DialogResult.OK) return; RemoveProfile(index); ProfileButtons[index].Text = i18N.Translate("None"); - MessageBoxX.Show(i18N.Translate("Profile Removed!")); + // MessageBoxX.Show(i18N.Translate("Profile Removed!")); return; } diff --git a/Netch/Forms/MainForm.Status.cs b/Netch/Forms/MainForm.Status.cs index 11d6cb24..23f7d2b9 100644 --- a/Netch/Forms/MainForm.Status.cs +++ b/Netch/Forms/MainForm.Status.cs @@ -22,9 +22,25 @@ namespace Netch.Forms get => _state; private set { + void StartDisableItems(bool enabled) + { + ServerComboBox.Enabled = + ModeComboBox.Enabled = + EditModePictureBox.Enabled = + EditServerPictureBox.Enabled = + DeleteModePictureBox.Enabled = + DeleteServerPictureBox.Enabled = enabled; + + // 启动需要禁用的控件 + UninstallServiceToolStripMenuItem.Enabled = + updateACLWithProxyToolStripMenuItem.Enabled = + UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled = + reinstallTapDriverToolStripMenuItem.Enabled = + ReloadModesToolStripMenuItem.Enabled = enabled; + } + _state = value; - if (IsDisposed) - return; + StatusText(i18N.Translate(StateExtension.GetStatusString(value))); switch (value) { @@ -37,19 +53,15 @@ namespace Netch.Forms ControlButton.Enabled = false; ControlButton.Text = "..."; - ConfigurationGroupBox.Enabled = false; - - MenuStripsEnabled(false); + ProfileGroupBox.Enabled = false; + StartDisableItems(false); break; case State.Started: ControlButton.Enabled = true; ControlButton.Text = i18N.Translate("Stop"); - LastUploadBandwidth = 0; - //LastDownloadBandwidth = 0; - //UploadSpeedLabel.Text = "↑: 0 KB/s"; - DownloadSpeedLabel.Text = @"↑↓: 0 KB/s"; - UsedBandwidthLabel.Text = $@"{i18N.Translate("Used", ": ")}0 KB"; + ProfileGroupBox.Enabled = true; + UsedBandwidthLabel.Visible /*= UploadSpeedLabel.Visible*/ = DownloadSpeedLabel.Visible = true; break; case State.Stopping: @@ -57,7 +69,6 @@ namespace Netch.Forms ControlButton.Text = "..."; ProfileGroupBox.Enabled = false; - UsedBandwidthLabel.Visible /*= UploadSpeedLabel.Visible*/ = DownloadSpeedLabel.Visible = false; NatTypeStatusText(); break; @@ -69,9 +80,7 @@ namespace Netch.Forms LastDownloadBandwidth = 0; ProfileGroupBox.Enabled = true; - ConfigurationGroupBox.Enabled = true; - - MenuStripsEnabled(true); + StartDisableItems(true); break; case State.Terminating: Dispose(); @@ -100,6 +109,7 @@ namespace Netch.Forms { NatTypeStatusLabel.Text = String.Format("NAT{0}{1}", i18N.Translate(": "), text); } + if (Enum.TryParse(text, false, out STUN_Client.NatType natType)) { NatTypeStatusLightLabel.Visible = true; @@ -144,7 +154,6 @@ namespace Netch.Forms NatTypeStatusLightLabel.ForeColor = c; } - /// /// 更新状态栏文本 /// @@ -158,14 +167,5 @@ namespace Netch.Forms { StatusLabel.Text += text; } - - public void MenuStripsEnabled(bool enabled) - { - // 需要禁用的菜单项 - UninstallServiceToolStripMenuItem.Enabled = - updateACLWithProxyToolStripMenuItem.Enabled = - UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled = - reinstallTapDriverToolStripMenuItem.Enabled = enabled; - } } } \ No newline at end of file diff --git a/Netch/Forms/MainForm.cs b/Netch/Forms/MainForm.cs index 57a6c24b..bacffab6 100644 --- a/Netch/Forms/MainForm.cs +++ b/Netch/Forms/MainForm.cs @@ -465,7 +465,7 @@ namespace Netch.Forms Activate(); } - private void NotifyTip(string text, int timeout = 5, bool info = true) + private void NotifyTip(string text, int timeout = 0, bool info = true) { NotifyIcon.ShowBalloonTip(timeout, UpdateChecker.Name, @@ -481,6 +481,7 @@ namespace Netch.Forms { Global.Settings.ModeComboBoxSelectedIndex = ModeComboBox.SelectedIndex; } + private void ServerComboBox_SelectedIndexChanged(object sender, EventArgs o) { Global.Settings.ServerComboBoxSelectedIndex = ServerComboBox.SelectedIndex;