Example #1
0
        public async Task UpdateServersFromSubscribe()
        {
            void DisableItems(bool v)
            {
                MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ProfileGroupBox.Enabled = ControlButton.Enabled = v;
            }

            if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1)
            {
                Global.Settings.UseProxyToUpdateSubscription = false;
            }

            if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1)
            {
                MessageBoxX.Show(i18N.Translate("Please select a server first"));
                return;
            }

            if (Global.Settings.SubscribeLink.Count <= 0)
            {
                MessageBoxX.Show(i18N.Translate("No subscription link"));
                return;
            }

            StatusText(i18N.Translate("Starting update subscription"));
            DisableItems(false);
            try
            {
                if (Global.Settings.UseProxyToUpdateSubscription)
                {
                    var mode = new Models.Mode
                    {
                        Remark = "ProxyUpdate",
                        Type   = 5
                    };
                    await MainController.Start(ServerComboBox.SelectedItem as Server, mode);
                }

                await Task.WhenAll(Global.Settings.SubscribeLink.Select(async item => await Task.Run(() =>
                {
                    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}");
                        }

                        List <Server> servers;

                        var result = WebUtil.DownloadString(request, out var rep);
                        if (rep.StatusCode == HttpStatusCode.OK)
                        {
                            servers = ShareLink.ParseText(result);
                        }
                        else
                        {
                            throw new Exception($"{item.Remark} Response Status Code: {rep.StatusCode}");
                        }

                        foreach (var server in servers)
                        {
                            server.Group = item.Remark;
                        }

                        lock (_serverLock)
                        {
                            Global.Settings.Server.RemoveAll(server => server.Group.Equals(item.Remark));
                            Global.Settings.Server.AddRange(servers);
                        }


                        NotifyTip(i18N.TranslateFormat("Update {1} server(s) from {0}", item.Remark, servers.Count));
                    }
                    catch (Exception e)
                    {
                        NotifyTip($"{i18N.TranslateFormat("Update servers error from {0}", item.Remark)}\n{e.Message}", info: false);
                        Logging.Error(e.ToString());
                    }
                })).ToArray());

                InitServer();
                Configuration.Save();
                StatusText(i18N.Translate("Subscription updated"));
            }
            catch (Exception)
            {
                // ignored
            }
            finally
            {
                if (Global.Settings.UseProxyToUpdateSubscription)
                {
                    await MainController.Stop();
                }

                DisableItems(true);
            }
        }
Example #2
0
        private void ControlButton_Click(object sender, EventArgs e)
        {
            Global.Settings.ExitWhenClosed         = ExitWhenClosedCheckBox.Checked;
            Global.Settings.StopWhenExited         = StopWhenExitedCheckBox.Checked;
            Global.Settings.StartWhenOpened        = StartWhenOpenedCheckBox.Checked;
            Global.Settings.CheckUpdateWhenOpened  = CheckUpdateWhenOpenedCheckBox.Checked;
            Global.Settings.MinimizeWhenStarted    = MinimizeWhenStartedCheckBox.Checked;
            Global.Settings.RunAtStartup           = RunAtStartup.Checked;
            Global.Settings.BootShadowsocksFromDLL = BootShadowsocksFromDLLCheckBox.Checked;
            Global.Settings.Language = LanguageComboBox.SelectedItem.ToString();

            // 开机自启判断
            var scheduler = new TaskSchedulerClass();

            scheduler.Connect();
            var folder       = scheduler.GetFolder("\\");
            var taskIsExists = false;

            try
            {
                folder.GetTask("Netch Startup");
                taskIsExists = true;
            }
            catch (Exception) { }

            if (RunAtStartup.Checked)
            {
                if (taskIsExists)
                {
                    folder.DeleteTask("Netch Startup", 0);
                }

                var task = scheduler.NewTask(0);
                task.RegistrationInfo.Author      = "Netch";
                task.RegistrationInfo.Description = "Netch run at startup.";
                task.Principal.RunLevel           = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;

                task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);
                var action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = Application.ExecutablePath;


                task.Settings.ExecutionTimeLimit         = "PT0S";
                task.Settings.DisallowStartIfOnBatteries = false;
                task.Settings.RunOnlyIfIdle = false;

                folder.RegisterTaskDefinition("Netch Startup", task, (int)_TASK_CREATION.TASK_CREATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");
            }
            else
            {
                if (taskIsExists)
                {
                    folder.DeleteTask("Netch Startup", 0);
                }
            }

            try
            {
                var Socks5Port = int.Parse(Socks5PortTextBox.Text);

                if (Socks5Port > 0 && Socks5Port < 65536)
                {
                    Global.Settings.Socks5LocalPort = Socks5Port;
                }
                else
                {
                    throw new FormatException();
                }
            }
            catch (FormatException)
            {
                Socks5PortTextBox.Text = Global.Settings.Socks5LocalPort.ToString();
                MessageBoxX.Show(i18N.Translate("Port value illegal. Try again."));

                return;
            }

            try
            {
                var HTTPPort = int.Parse(HTTPPortTextBox.Text);

                if (HTTPPort > 0 && HTTPPort < 65536)
                {
                    Global.Settings.HTTPLocalPort = HTTPPort;
                }
                else
                {
                    throw new FormatException();
                }
            }
            catch (FormatException)
            {
                HTTPPortTextBox.Text = Global.Settings.HTTPLocalPort.ToString();
                MessageBoxX.Show(i18N.Translate("Port value illegal. Try again."));

                return;
            }

            try
            {
                var RedirectorPort = int.Parse(RedirectorTextBox.Text);

                if (RedirectorPort > 0 && RedirectorPort < 65536)
                {
                    Global.Settings.RedirectorTCPPort = RedirectorPort;
                }
                else
                {
                    throw new FormatException();
                }
            }
            catch (FormatException)
            {
                RedirectorTextBox.Text = Global.Settings.RedirectorTCPPort.ToString();
                MessageBoxX.Show(i18N.Translate("Port value illegal. Try again."));

                return;
            }

            if (AllowDevicesCheckBox.Checked)
            {
                Global.Settings.LocalAddress = "0.0.0.0";
            }
            else
            {
                Global.Settings.LocalAddress = "127.0.0.1";
            }

            try
            {
                var Address = IPAddress.Parse(TUNTAPAddressTextBox.Text);
                var Netmask = IPAddress.Parse(TUNTAPNetmaskTextBox.Text);
                var Gateway = IPAddress.Parse(TUNTAPGatewayTextBox.Text);

                var DNS = new List <IPAddress>();
                foreach (var ip in TUNTAPDNSTextBox.Text.Split(','))
                {
                    DNS.Add(IPAddress.Parse(ip));
                }
            }
            catch (FormatException)
            {
                MessageBoxX.Show(i18N.Translate("IP address format illegal. Try again."));

                TUNTAPAddressTextBox.Text = Global.Settings.TUNTAP.Address;
                TUNTAPNetmaskTextBox.Text = Global.Settings.TUNTAP.Netmask;
                TUNTAPGatewayTextBox.Text = Global.Settings.TUNTAP.Gateway;

                var DNS = "";
                foreach (var ip in Global.Settings.TUNTAP.DNS)
                {
                    DNS += ip;
                    DNS += ',';
                }
                DNS = DNS.Trim();
                TUNTAPDNSTextBox.Text        = DNS.Substring(0, DNS.Length - 1);
                UseCustomDNSCheckBox.Checked = Global.Settings.TUNTAP.UseCustomDNS;

                return;
            }
            try
            {
                var ProfileCount = int.Parse(ProfileCount_TextBox.Text);

                if (ProfileCount > -1)
                {
                    Global.Settings.ProfileCount = ProfileCount;
                }
                else
                {
                    throw new FormatException();
                }
            }
            catch (FormatException)
            {
                ProfileCount_TextBox.Text = Global.Settings.ProfileCount.ToString();
                MessageBoxX.Show(i18N.Translate("ProfileCount value illegal. Try again."));

                return;
            }
            try
            {
                var STUN_Server = STUN_ServerTextBox.Text;
                Global.Settings.STUN_Server = STUN_Server;

                var STUN_ServerPort = int.Parse(STUN_ServerPortTextBox.Text);

                if (STUN_ServerPort > 0)
                {
                    Global.Settings.STUN_Server_Port = STUN_ServerPort;
                }
                else
                {
                    throw new FormatException();
                }
            }
            catch (FormatException)
            {
                ProfileCount_TextBox.Text = Global.Settings.ProfileCount.ToString();
                MessageBoxX.Show(i18N.Translate("STUN_ServerPort value illegal. Try again."));

                return;
            }
            try
            {
                Global.Settings.StartedTcping = EnableStartedTcping_CheckBox.Checked;

                var DetectionInterval = int.Parse(DetectionInterval_TextBox.Text);

                if (DetectionInterval > 0)
                {
                    Global.Settings.StartedTcping_Interval = DetectionInterval;
                }
                else
                {
                    throw new FormatException();
                }
            }
            catch (FormatException)
            {
                ProfileCount_TextBox.Text = Global.Settings.ProfileCount.ToString();
                MessageBoxX.Show(i18N.Translate("Detection interval value illegal. Try again."));

                return;
            }

            Global.Settings.ACL = AclAddr.Text;

            Global.Settings.TUNTAP.Address = TUNTAPAddressTextBox.Text;
            Global.Settings.TUNTAP.Netmask = TUNTAPNetmaskTextBox.Text;
            Global.Settings.TUNTAP.Gateway = TUNTAPGatewayTextBox.Text;

            Global.Settings.TUNTAP.DNS.Clear();
            foreach (var ip in TUNTAPDNSTextBox.Text.Split(','))
            {
                Global.Settings.TUNTAP.DNS.Add(ip);
            }

            Global.Settings.TUNTAP.UseCustomDNS = UseCustomDNSCheckBox.Checked;
            Global.Settings.TUNTAP.ProxyDNS     = ProxyDNSCheckBox.Checked;
            Global.Settings.TUNTAP.UseFakeDNS   = UseFakeDNSCheckBox.Checked;

            Configuration.Save();
            MessageBoxX.Show(i18N.Translate("Saved"));
            Close();
        }
Example #3
0
        private void AddButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(RemarkTextBox.Text))
            {
                MessageBoxX.Show(i18N.Translate("Remark can not be empty"));
                return;
            }

            if (string.IsNullOrWhiteSpace(LinkTextBox.Text))
            {
                MessageBoxX.Show(i18N.Translate("Link can not be empty"));
                return;
            }

            if (!LinkTextBox.Text.StartsWith("HTTP://", StringComparison.OrdinalIgnoreCase) && !LinkTextBox.Text.StartsWith("HTTPS://", StringComparison.OrdinalIgnoreCase))
            {
                MessageBoxX.Show(i18N.Translate("Links must start with http:// or https://"));
                return;
            }

            // 备注重复的订阅项
            var duplicateRemarkItems = Global.Settings.SubscribeLink.Where(link => link.Remark.Equals(RemarkLabel.Text));

            // 链接重复的订阅项
            SubscribeLink duplicateLinkItem = null;

            try
            {
                duplicateLinkItem = Global.Settings.SubscribeLink.First(link => link.Link.Equals(LinkTextBox.Text));
            }
            catch
            {
                // ignored
            }

            if (duplicateRemarkItems.Any())
            {
                MessageBoxX.Show("Remark Name Duplicate!");
                return;
            }

            if (duplicateLinkItem != null)
            {
                if (duplicateLinkItem.Remark != RemarkTextBox.Text)
                {
                    RenameServersGroup(duplicateLinkItem.Remark, RemarkTextBox.Text);
                }

                duplicateLinkItem.Remark    = RemarkTextBox.Text;
                duplicateLinkItem.UserAgent = UserAgentTextBox.Text;
            }
            else if (_editingIndex != -1)
            {
                // 只修改备注/未修改被上面处理
                var target = Global.Settings.SubscribeLink[_editingIndex];
                if (MessageBox.Show(i18N.Translate("Delete the corresponding group of items in the server list?"), i18N.Translate("Confirm"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    DeleteServersInGroup(target.Remark);
                }
                else
                {
                    RenameServersGroup(target.Remark, RemarkTextBox.Text);
                }

                target.Link      = LinkTextBox.Text;
                target.Remark    = RemarkTextBox.Text;
                target.UserAgent = UserAgentTextBox.Text;
            }
            else
            {
                Global.Settings.SubscribeLink.Add(new SubscribeLink
                {
                    Remark    = RemarkTextBox.Text,
                    Link      = LinkTextBox.Text,
                    UserAgent = UserAgentTextBox.Text
                });
            }

            Configuration.Save();
            Global.Settings.UseProxyToUpdateSubscription = UseSelectedServerCheckBox.Checked;
            // MessageBoxX.Show(i18N.Translate("Saved"));

            ResetEditingGroup();

            InitSubscribeLink();
        }
Example #4
0
        private void UpdateServersFromSubscribeLinksToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var bak_State     = State;
            var bak_StateText = StatusLabel.Text;

            if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1)
            {
                Global.Settings.UseProxyToUpdateSubscription = false;
            }

            if (Global.Settings.UseProxyToUpdateSubscription)
            {
                // 当前 ServerComboBox 中至少有一项
                if (ServerComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a server first"));
                    return;
                }

                MenuStrip.Enabled  = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false;
                ControlButton.Text = "...";
            }

            if (Global.Settings.SubscribeLink.Count > 0)
            {
                StatusText(i18N.Translate("Starting update subscription"));
                DeleteServerPictureBox.Enabled = false;

                UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled = false;
                Task.Run(() =>
                {
                    if (Global.Settings.UseProxyToUpdateSubscription)
                    {
                        var mode = new Models.Mode
                        {
                            Remark = "ProxyUpdate",
                            Type   = 5
                        };
                        _mainController = new MainController();
                        _mainController.Start(ServerComboBox.SelectedItem as Models.Server, mode);
                    }

                    foreach (var item in Global.Settings.SubscribeLink)
                    {
                        using var client = new WebClient();
                        try
                        {
                            if (!string.IsNullOrEmpty(item.UserAgent))
                            {
                                client.Headers.Add("User-Agent", item.UserAgent);
                            }
                            else
                            {
                                client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36");
                            }

                            if (Global.Settings.UseProxyToUpdateSubscription)
                            {
                                client.Proxy = new WebProxy($"http://127.0.0.1:{Global.Settings.HTTPLocalPort}");
                            }

                            var response = client.DownloadString(item.Link);

                            try
                            {
                                response = ShareLink.URLSafeBase64Decode(response);
                            }
                            catch (Exception)
                            {
                                // ignored
                            }

                            Global.Settings.Server = Global.Settings.Server.Where(server => server.Group != item.Remark).ToList();
                            var result             = ShareLink.Parse(response);

                            if (result != null)
                            {
                                foreach (var x in result)
                                {
                                    x.Group = item.Remark;
                                }

                                Global.Settings.Server.AddRange(result);
                                NotifyIcon.ShowBalloonTip(5,
                                                          UpdateChecker.Name,
                                                          string.Format(i18N.Translate("Update {1} server(s) from {0}"), item.Remark, result.Count),
                                                          ToolTipIcon.Info);
                            }
                            else
                            {
                                NotifyIcon.ShowBalloonTip(5,
                                                          UpdateChecker.Name,
                                                          string.Format(i18N.Translate("Update servers error from {0}"), item.Remark),
                                                          ToolTipIcon.Error);
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }

                    InitServer();
                    DeleteServerPictureBox.Enabled = true;
                    if (Global.Settings.UseProxyToUpdateSubscription)
                    {
                        MenuStrip.Enabled  = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true;
                        ControlButton.Text = i18N.Translate("Start");
                        _mainController.Stop();
                        NatTypeStatusLabel.Text = "";
                    }

                    Configuration.Save();
                    StatusText(i18N.Translate("Subscription updated"));

                    MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true;
                    State             = bak_State;
                    StatusLabel.Text  = bak_StateText;
                }).ContinueWith(task => { BeginInvoke(new Action(() => { UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled = true; })); });

                NotifyIcon.ShowBalloonTip(5,
                                          UpdateChecker.Name,
                                          i18N.Translate("Updating in the background"),
                                          ToolTipIcon.Info);
            }
            else
            {
                MessageBoxX.Show(i18N.Translate("No subscription link"));
            }
        }
Example #5
0
        private async void ProfileButton_Click(object sender, EventArgs e)
        {
            var index = ProfileButtons.IndexOf((Button)sender);

            if (ModifierKeys == Keys.Control)
            {
                if (ServerComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a server first"));
                }
                else if (ModeComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a mode first"));
                }
                else if (ProfileNameText.Text == "")
                {
                    MessageBoxX.Show(i18N.Translate("Please enter a profile name first"));
                }
                else
                {
                    SaveProfile(index);
                    ProfileButtons[index].Text = ProfileNameText.Text;
                }

                return;
            }

            if (Global.Settings.Profiles[index].IsDummy)
            {
                MessageBoxX.Show(
                    i18N.Translate("No saved profile here. Save a profile first by Ctrl+Click on the button"));
                return;
            }

            if (ModifierKeys == Keys.Shift)
            {
                if (MessageBoxX.Show(i18N.Translate("Remove this Profile?"), confirm: true) != DialogResult.OK)
                {
                    return;
                }
                RemoveProfile(index);
                ProfileButtons[index].Text = i18N.Translate("None");
                return;
            }

            try
            {
                LoadProfile(index);
            }
            catch (Exception exception)
            {
                MessageBoxX.Show(exception.Message, LogLevel.ERROR);
                return;
            }

            // start the profile
            ControlFun();
            if (State == State.Stopping || State == State.Stopped)
            {
                while (State != State.Stopped)
                {
                    await Task.Delay(250);
                }

                ControlFun();
            }
        }
Example #6
0
        public async Task UpdateServersFromSubscribe()
        {
            void DisableItems(bool v)
            {
                MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ProfileGroupBox.Enabled = ControlButton.Enabled = v;
            }

            if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1)
            {
                Global.Settings.UseProxyToUpdateSubscription = false;
            }

            if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1)
            {
                MessageBoxX.Show(i18N.Translate("Please select a server first"));
                return;
            }

            if (Global.Settings.SubscribeLink.Count <= 0)
            {
                MessageBoxX.Show(i18N.Translate("No subscription link"));
                return;
            }

            StatusText(i18N.Translate("Starting update subscription"));
            DisableItems(false);
            try
            {
                if (Global.Settings.UseProxyToUpdateSubscription)
                {
                    var mode = new Models.Mode
                    {
                        Remark = "ProxyUpdate",
                        Type   = 5
                    };
                    await MainController.Start(ServerComboBox.SelectedItem as Models.Server, mode);
                }

                var serverLock = new object();

                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
                        }

                        lock (serverLock)
                        {
                            Global.Settings.Server.RemoveAll(server => server.Group == item.Remark);

                            var result = ShareLink.Parse(str);
                            if (result != null)
                            {
                                foreach (var server in result)
                                {
                                    server.Group = item.Remark;
                                    Global.Settings.Server.Add(server);
                                }
                            }

                            NotifyTip(i18N.TranslateFormat("Update {1} server(s) from {0}", item.Remark, result?.Count ?? 0));
                        }
                    }
                    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());

                InitServer();
                Configuration.Save();
                StatusText(i18N.Translate("Subscription updated"));
            }
            catch (Exception)
            {
                // ignored
            }
            finally
            {
                if (Global.Settings.UseProxyToUpdateSubscription)
                {
                    await MainController.Stop();
                }

                DisableItems(true);
            }
        }
Example #7
0
        private async void ControlFun()
        {
            if (State == State.Waiting || State == State.Stopped)
            {
                // 服务器、模式 需选择
                if (ServerComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a server first"));
                    return;
                }

                if (ModeComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a mode first"));
                    return;
                }

                // 清除模式搜索框文本选择
                ModeComboBox.Select(0, 0);

                State = State.Starting;

                await Task.Run(Firewall.AddNetchFwRules);

                var server = ServerComboBox.SelectedItem as Models.Server;
                var mode   = ModeComboBox.SelectedItem as Models.Mode;
                var result = false;

                await Task.Run(() =>
                {
                    try
                    {
                        // 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: Global.MainForm);
                        }
                        Netch.Application_OnException(null, new ThreadExceptionEventArgs(e));
                    }
                });

                if (result)
                {
                    State = State.Started;
                    _     = Task.Run(() => { 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();
                    }

                    if (Global.Settings.StartedTcping)
                    {
                        // 自动检测延迟
                        await Task.Run(() =>
                        {
                            while (State == State.Started)
                            {
                                server.Test();
                                // 重载服务器列表
                                InitServer();

                                Thread.Sleep(Global.Settings.StartedTcping_Interval * 1000);
                            }
                        });
                    }
                }
                else
                {
                    State = State.Stopped;
                    StatusText(i18N.Translate("Start failed"));
                }
            }
            else
            {
                // 停止
                State = State.Stopping;
                _mainController.Stop();
                State = State.Stopped;
                _     = Task.Run(TestServer);
            }
        }
        private void ProfileButton_Click(object sender, EventArgs e)
        {
            var index = ProfileButtons.IndexOf((Button)sender);

            if (ModifierKeys == Keys.Control)
            {
                if (ServerComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a server first"));
                }
                else if (ModeComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select an mode first"));
                }
                else if (ProfileNameText.Text == "")
                {
                    MessageBoxX.Show(i18N.Translate("Please enter a profile name first"));
                }
                else
                {
                    SaveProfile(index);
                    ProfileButtons[index].Text = ProfileNameText.Text;
                }
            }
            else if (ModifierKeys == Keys.Shift)
            {
                if (MessageBoxX.Show(i18N.Translate("Remove this Profile?"), confirm: true) == DialogResult.OK)
                {
                    RemoveProfile(index);
                    ProfileButtons[index].Text = i18N.Translate("None");
                    MessageBoxX.Show(i18N.Translate("Profile Removed!"));
                }
            }
            else
            {
                if (Global.Settings.Profiles[index].IsDummy)
                {
                    MessageBoxX.Show(i18N.Translate("No saved profile here. Save a profile first by Ctrl+Click on the button"));
                    return;
                }

                try
                {
                    ProfileNameText.Text = LoadProfile(index);

                    // start the profile
                    ControlFun();
                    if (State == State.Stopping || State == State.Stopped)
                    {
                        Task.Run(() =>
                        {
                            while (State != State.Stopped)
                            {
                                Thread.Sleep(250);
                            }

                            ControlButton.PerformClick();
                        });
                    }
                }
                catch (Exception ee)
                {
                    Task.Run(() =>
                    {
                        Logging.Info(ee.ToString());
                        ProfileButtons[index].Text = i18N.Translate("Error");
                        Thread.Sleep(1200);
                        ProfileButtons[index].Text = i18N.Translate("None");
                    });
                }
            }
        }
Example #9
0
        private async void ControlFun()
        {
            Configuration.Save();
            if (State == State.Waiting || State == State.Stopped)
            {
                // 服务器、模式 需选择
                if (ServerComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a server first"));
                    return;
                }

                if (ModeComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a mode first"));
                    return;
                }

                // 清除模式搜索框文本选择
                ModeComboBox.Select(0, 0);

                State = State.Starting;

                var server = ServerComboBox.SelectedItem as Models.Server;
                var mode   = ModeComboBox.SelectedItem as Models.Mode;

                if (await _mainController.Start(server, mode))
                {
                    State = State.Started;
                    _     = Task.Run(() => { Bandwidth.NetTraffic(server, mode, ref _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();
                    }

                    if (Global.Settings.StartedTcping)
                    {
                        // 自动检测延迟
                        _ = Task.Run(() =>
                        {
                            while (State == State.Started)
                            {
                                server.Test();
                                // 重绘 ServerComboBox
                                ServerComboBox.Invalidate();

                                Thread.Sleep(Global.Settings.StartedTcping_Interval * 1000);
                            }
                        });
                    }
                }
                else
                {
                    State = State.Stopped;
                    StatusText(i18N.Translate("Start failed"));
                }
            }
            else
            {
                // 停止
                State = State.Stopping;
                await _mainController.Stop();

                State = State.Stopped;
                _     = Task.Run(TestServer);
            }
        }
Example #10
0
        private void AddButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(RemarkTextBox.Text))
            {
                MessageBoxX.Show(i18N.Translate("Remark can not be empty"));
                return;
            }

            if (string.IsNullOrWhiteSpace(LinkTextBox.Text))
            {
                MessageBoxX.Show(i18N.Translate("Link can not be empty"));
                return;
            }

            if (!LinkTextBox.Text.StartsWith("HTTP://", StringComparison.OrdinalIgnoreCase) && !LinkTextBox.Text.StartsWith("HTTPS://", StringComparison.OrdinalIgnoreCase))
            {
                MessageBoxX.Show(i18N.Translate("Link must start with http:// or https://"));
                return;
            }

            if (_editingIndex == -1)
            {
                if (Global.Settings.SubscribeLink.Any(link => link.Remark.Equals(RemarkTextBox.Text)))
                {
                    MessageBoxX.Show("Remark Name Duplicate!");
                    return;
                }

                Global.Settings.SubscribeLink.Add(new SubscribeLink
                {
                    Enable    = true,
                    Remark    = RemarkTextBox.Text,
                    Link      = LinkTextBox.Text,
                    UserAgent = UserAgentTextBox.Text
                });
            }
            else
            {
                var target = Global.Settings.SubscribeLink[_editingIndex];

                /*if (MessageBox.Show(i18N.Translate("Delete the corresponding group of items in the server list?"), i18N.Translate("Confirm"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                 * {
                 *  DeleteServersInGroup(target.Remark);
                 * }
                 * else
                 * {
                 *  RenameServersGroup(target.Remark, RemarkTextBox.Text);
                 * }*/
                ListViewItem listViewItem = SubscribeLinkListView.Items[_editingIndex];

                target.Enable    = listViewItem.Checked;
                target.Link      = LinkTextBox.Text;
                target.Remark    = RemarkTextBox.Text;
                target.UserAgent = UserAgentTextBox.Text;
            }

            MessageBoxX.Show(i18N.Translate("Saved"));
            Configuration.Save();
            Global.Settings.UseProxyToUpdateSubscription = UseSelectedServerCheckBox.Checked;

            ResetEditingGroup();
            InitSubscribeLink();
        }
Example #11
0
        public void ControlFun()
        {
            SaveConfigs();
            if (State == State.Waiting || State == State.Stopped)
            {
                // 服务器、模式 需选择
                if (ServerComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a server first"));
                    return;
                }

                if (ModeComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select an mode first"));
                    return;
                }

                //MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false;

                UpdateStatus(State.Starting);

                Firewall.AddNetchFwRules();

                Task.Run(() =>
                {
                    var server = ServerComboBox.SelectedItem as Models.Server;
                    var mode   = ModeComboBox.SelectedItem as Models.Mode;

                    MainController = new MainController();

                    var startResult = MainController.Start(server, mode);

                    if (startResult)
                    {
                        Task.Run(() =>
                        {
                            LastUploadBandwidth = 0;
                            //LastDownloadBandwidth = 0;
                            //UploadSpeedLabel.Text = "↑: 0 KB/s";
                            DownloadSpeedLabel.Text    = "↑↓: 0 KB/s";
                            UsedBandwidthLabel.Text    = $"{i18N.Translate("Used",": ")}0 KB";
                            UsedBandwidthLabel.Visible = UploadSpeedLabel.Visible = DownloadSpeedLabel.Visible = true;


                            UploadSpeedLabel.Visible = false;
                            Bandwidth.NetTraffic(server, mode, MainController);
                        });
                        //MainController.pNFController.OnBandwidthUpdated += OnBandwidthUpdated;

                        // 如果勾选启动后最小化
                        if (Global.Settings.MinimizeWhenStarted)
                        {
                            WindowState        = FormWindowState.Minimized;
                            NotifyIcon.Visible = true;

                            if (IsFirstOpened)
                            {
                                // 显示提示语
                                NotifyIcon.ShowBalloonTip(5,
                                                          UpdateChecker.Name,
                                                          i18N.Translate(
                                                              "Netch is now minimized to the notification bar, double click this icon to restore."),
                                                          ToolTipIcon.Info);

                                IsFirstOpened = false;
                            }

                            Hide();
                        }

                        // TODO 是否需要移到一个函数中
                        var text = new StringBuilder(" (");
                        text.Append(Global.Settings.LocalAddress == "0.0.0.0"
                            ? i18N.Translate("Allow other Devices to connect") + " "
                            : "");
                        if (server.Type == "Socks5")
                        {
                            // 不可控Socks5
                            if (mode.Type == 3 && mode.Type == 5)
                            {
                                // 可控HTTP
                                text.Append(
                                    $"HTTP {i18N.Translate("Local Port", ": ")}{Global.Settings.HTTPLocalPort}");
                            }
                            else
                            {
                                // 不可控HTTP
                                text.Clear();
                            }
                        }
                        else
                        {
                            // 可控Socks5
                            text.Append(
                                $"Socks5 {i18N.Translate("Local Port", ": ")}{Global.Settings.Socks5LocalPort}");
                            if (mode.Type == 3 || mode.Type == 5)
                            {
                                //有HTTP
                                text.Append(
                                    $" | HTTP {i18N.Translate("Local Port", ": ")}{Global.Settings.HTTPLocalPort}");
                            }
                        }
                        if (text.Length > 0)
                        {
                            text.Append(")");
                        }
                        UpdateStatus(State.Started);
                        StatusText(i18N.Translate(StateExtension.GetStatusString(State)) + text);

                        if (Global.Settings.StartedTcping)
                        {
                            // 自动检测延迟
                            Task.Run(() =>
                            {
                                while (true)
                                {
                                    if (State == State.Started)
                                    {
                                        server.Test();
                                        // 重载服务器列表
                                        InitServer();

                                        Thread.Sleep(Global.Settings.StartedTcping_Interval * 1000);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            });
                        }
                    }
                    else
                    {
                        UpdateStatus(State.Stopped);
                        StatusText(i18N.Translate("Start Failed"));
                    }
                });
            }
            else
            {
                // 停止
                UpdateStatus(State.Stopping);

                Task.Run(() =>
                {
                    var server = ServerComboBox.SelectedItem as Models.Server;
                    var mode   = ModeComboBox.SelectedItem as Models.Mode;

                    MainController.Stop();

                    UpdateStatus(State.Stopped);

                    TestServer();
                });
            }
        }
Example #12
0
        private void ControlFun()
        {
            //防止模式选择框变成蓝色:D
            ModeComboBox.Select(0, 0);

            if (State == State.Waiting || State == State.Stopped)
            {
                // 服务器、模式 需选择
                if (ServerComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a server first"));
                    return;
                }

                if (ModeComboBox.SelectedIndex == -1)
                {
                    MessageBoxX.Show(i18N.Translate("Please select a mode first"));
                    return;
                }

                UpdateStatus(State.Starting);

                Task.Run(() =>
                {
                    Task.Run(Firewall.AddNetchFwRules);

                    var server = ServerComboBox.SelectedItem as Models.Server;
                    var mode   = ModeComboBox.SelectedItem as Models.Mode;

                    if (_mainController.Start(server, mode))
                    {
                        Task.Run(() =>
                        {
                            UpdateStatus(State.Started,
                                         i18N.Translate(StateExtension.GetStatusString(State.Started)) + LocalPortText(server.Type, mode.Type));
                            Bandwidth.NetTraffic(server, mode, _mainController);
                        });
                        // 如果勾选启动后最小化
                        if (Global.Settings.MinimizeWhenStarted)
                        {
                            WindowState        = FormWindowState.Minimized;
                            NotifyIcon.Visible = true;

                            if (_isFirstCloseWindow)
                            {
                                // 显示提示语
                                NotifyIcon.ShowBalloonTip(5,
                                                          UpdateChecker.Name,
                                                          i18N.Translate(
                                                              "Netch is now minimized to the notification bar, double click this icon to restore."),
                                                          ToolTipIcon.Info);

                                _isFirstCloseWindow = false;
                            }

                            Hide();
                        }

                        if (Global.Settings.StartedTcping)
                        {
                            // 自动检测延迟
                            Task.Run(() =>
                            {
                                while (true)
                                {
                                    if (State == State.Started)
                                    {
                                        server.Test();
                                        // 重载服务器列表
                                        InitServer();

                                        Thread.Sleep(Global.Settings.StartedTcping_Interval * 1000);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            });
                        }
                    }
                    else
                    {
                        UpdateStatus(State.Stopped, i18N.Translate("Start failed"));
                    }
                });
            }
            else
            {
                // 停止
                UpdateStatus(State.Stopping);
                _mainController.Stop();
                UpdateStatus(State.Stopped);
                Task.Run(TestServer);
            }
        }