コード例 #1
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            string loginData = @"oauth=
username="******"fourtf");

            //IrcManager.MessageReceived += (s, e) =>
            //{
            //    lock (messages)
            //    {
            //        messages.Add(e.Message);
            //        e.Message.CalculateBounds(null, 1000);
            //    }
            //};
        }
コード例 #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Irc"/> class.
 /// </summary>
 /// <param name="sst">The main class.</param>
 public Irc(SynServerTool sst)
 {
     IsIrcAccessAllowed = false;
     _sst           = sst;
     _configHandler = new ConfigHandler();
     _irc           = new IrcManager(_sst);
     LoadConfig();
 }
コード例 #3
0
ファイル: WelcomeForm.cs プロジェクト: vileelf/botterino
        private void button2_Click(object sender, EventArgs e)
        {
            using (var loginForm = new LoginForm())
            {
                loginForm.ShowDialog();

                if (loginForm.Account != null)
                {
                    AccountManager.AddAccount(loginForm.Account);

                    IrcManager.Account = loginForm.Account;
                    IrcManager.Connect();
                }
            }
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: vileelf/botterino
        static void Main(string[] args)
        {
            Application.Init();

            AppSettings.SavePath = Path.Combine(Util.GetUserDataPath(), "Settings.ini");

            GuiEngine.Initialize(new GtkGuiEngine());

            Cache.Load();
            AppSettings.Load();

            IrcManager.Connect();

            var window = new MainWindow();

            window.ShowAll();
            window.Hidden += (s, e) => { Application.Quit(); };

            Application.Run();

            AppSettings.Save();
        }
コード例 #5
0
        static void Main()
        {
            ServerStarted = DateTime.Now;

            if (File.Exists("MOTD.txt"))
            {
                MOTD = Encoding.Default.GetBytes($"<pre>\n{File.ReadAllText("MOTD.txt").InsertHrefInUrls()}\n</pre>");
            }

            Console.Write("Initializing Bancho");
            if (IsDebug)
            {
                Console.Write(" in debug mode");
            }
            Console.WriteLine("..");

            Process.GetCurrentProcess().PriorityBoostEnabled = true;
            Process.GetCurrentProcess().PriorityClass        = ProcessPriorityClass.RealTime;
            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            Console.CursorVisible = false;
            Console.Title         = (IsDebug?"[DEBUG] ":"") + "osu!Bancho";

            GeoUtil.Initialize();

            if (!File.Exists("config.ini"))
            {
                File.WriteAllText("config.ini", IniFile.DefaultIni);
            }

            IniFile ini = new IniFile("config.ini");

            Bancho.IsRestricted = ini.GetValue("Bancho", "Restricted", false);

            CultureInfo = CultureInfo.CreateSpecificCulture("en-GB");

            Console.WriteLine("Initializing Database..");

            var connectionString = new MySqlConnectionStringBuilder
            {
                ConnectionTimeout     = ini.GetValue("DatabaseConnection", "ConnectionTimeout", 10u),
                Database              = ini.GetValue("DatabaseConnection", "Database", "osu!"),
                DefaultCommandTimeout = ini.GetValue("DatabaseConnection", "CommandTimeout", 30u),
                Logging             = false,
                MaximumPoolSize     = ini.GetValue("DatabaseConnection", "MaximumPoolSize", 250u),
                MinimumPoolSize     = ini.GetValue("DatabaseConnection", "MinimumPoolSize", 10u),
                Password            = ini.GetValue("DatabaseConnection", "Password", ""),
                Pooling             = true,
                Port                = ini.GetValue("DatabaseConnection", "Port", 3306u),
                Server              = ini.GetValue("DatabaseConnection", "Server", "127.0.0.1"),
                UserID              = ini.GetValue("DatabaseConnection", "User", "root"),
                AllowZeroDateTime   = true,
                ConvertZeroDateTime = true,
            };

            _databaseManager = new DatabaseManager(connectionString.ToString());
            if (!_databaseManager.IsConnected())
            {
                Console.Error.WriteLine("Failed to connect to the specified MySQL server.");
                Console.ReadKey(true);
                Environment.Exit(1);
            }

            workerTimer = new Timer(
                (state) =>
            {
                foreach (Player player in PlayerManager.Players
                         .Where(player => (Environment.TickCount - player.LastPacketTime) >= 80000))
                {
                    PlayerManager.DisconnectPlayer(player, DisconnectReason.Timeout);
                }
                try
                {
                    UpdateOnlineNow();
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Can't update onlines_now: " + e.Message);
                }
            },
                null, 0, 15000);

#if DEBUG
            Debug.Listeners.Add(new ConsoleTraceListener());
#endif

            Console.WriteLine("Initializing IRC..");

            irc = new IrcManager();
            irc.Start();

            var port = ini.GetValue("Bancho", "Port", 80);
            Console.WriteLine($"Initializing HTTP in port {port.ToString()}..");

            HttpAsyncHost http = new HttpAsyncHost(IsDebug? 1 : 120);
            http.Run("http://+:" + port.ToString() + "/");

            Console.ReadLine();
        }
コード例 #6
0
ファイル: SettingsDialog.cs プロジェクト: lyx0/chatterino
        //private Button btnResetCurrent;
        //private Button btnResetAll;

        //CTOR
        public SettingsDialog()
        {
            InitializeComponent();

            TopMost = AppSettings.WindowTopMost;

            AppSettings.WindowTopMostChanged += (s, e) =>
            {
                TopMost = AppSettings.WindowTopMost;
            };

            Icon = App.Icon;

            try
            {
                //this.Icon = Program.AppIcon;
            }
            catch { }

            tabs.SelectedIndex = 0;
            tabs.PageSelected += tabs_PageSelected;
            tabs_PageSelected(this, EventArgs.Empty);

            // Accounts
            #region Accounts
            var originalAccounts = AccountManager.Accounts.ToArray();

            foreach (var account in originalAccounts)
            {
                dataGridViewAccounts.Rows.Add(account.Username);
            }

            dataGridViewAccounts.Sort(dataGridViewAccounts.Columns[0], ListSortDirection.Descending);

            LoginForm loginForm = null;

            buttonAccountAdd.Click += delegate
            {
                if (loginForm == null)
                {
                    loginForm = new LoginForm();

                    loginForm.FormClosed += (s, e) =>
                    {
                        if (loginForm.Account != null)
                        {
                            AccountManager.AddAccount(loginForm.Account);

                            IrcManager.Account = loginForm.Account;
                            IrcManager.Connect();

                            var username = loginForm.Account.Username.ToLowerInvariant();

                            var addGridViewItem = true;

                            foreach (DataGridViewRow row in dataGridViewAccounts.Rows)
                            {
                                if (((string)row.Cells[0].Value).ToLowerInvariant() == username)
                                {
                                    addGridViewItem = false;
                                    break;
                                }
                            }

                            if (addGridViewItem)
                            {
                                dataGridViewAccounts.Rows.Add(loginForm.Account.Username);
                                dataGridViewAccounts.Sort(dataGridViewAccounts.Columns[0], ListSortDirection.Ascending);
                            }
                        }
                        loginForm = null;
                    };

                    loginForm.Show();
                }
                else
                {
                    loginForm.BringToFront();
                }
            };

            Closed += delegate
            {
                AccountManager.SaveToJson(Path.Combine(Util.GetUserDataPath(), "Login.json"));

                loginForm?.Close();
            };

            buttonAccountRemove.Click += (s, e) =>
            {
                if (dataGridViewAccounts.SelectedCells.Count != 1)
                {
                    return;
                }

                var username = (string)dataGridViewAccounts.SelectedCells[0].Value;

                AccountManager.RemoveAccount(username);

                buttonAccountRemove.Enabled = dataGridViewAccounts.RowCount != 0;
            };

            buttonAccountRemove.Enabled = dataGridViewAccounts.RowCount != 0;
            #endregion

            // Appearance
            #region Appearance

            Action setNightThemeVisibility = () =>
            {
                comboThemeNight.Visible           = labelNightDesc.Visible = comboThemeNight.Visible =
                    labelThemeNight.Visible       = labelThemeNightFrom.Visible = labelNightThemeUntil.Visible =
                        numThemeNightFrom.Visible = numThemeNightUntil.Visible =
                            checkBoxDifferentThemeAtNight.Checked;
            };

            var originalTheme           = comboTheme.Text = AppSettings.Theme;
            var originalThemeNight      = comboThemeNight.Text = AppSettings.NightTheme;
            var originalThemeHue        = AppSettings.ThemeHue;
            var originalThemeNightStart = AppSettings.NightThemeStart;
            var originalThemeNightEnd   = AppSettings.NightThemeEnd;
            var originalQuality         = comboQuality.Text = AppSettings.Quality;
            var originalPath            = AppSettings.StreamlinkPath;

            BindCheckBox(checkBoxDifferentThemeAtNight, "EnableNightTheme");

            checkBoxDifferentThemeAtNight.CheckedChanged += (s, e) =>
            {
                AppSettings.UpdateCurrentTheme();
                setNightThemeVisibility();
            };

            comboTheme.SelectedValueChanged += (s, e) =>
            {
                AppSettings.Theme = comboTheme.Text;
            };

            comboThemeNight.SelectedValueChanged += (s, e) =>
            {
                AppSettings.NightTheme = comboThemeNight.Text;
            };

            comboQuality.SelectedValueChanged += (s, e) =>
            {
                AppSettings.Quality = comboQuality.Text;
            };

            numThemeNightFrom.Value = Math.Max(1, Math.Min(24, AppSettings.NightThemeStart));

            numThemeNightFrom.ValueChanged += (s, e) =>
            {
                AppSettings.NightThemeStart = (int)numThemeNightFrom.Value;
            };

            numThemeNightUntil.Value = Math.Max(1, Math.Min(24, AppSettings.NightThemeEnd));

            numThemeNightUntil.ValueChanged += (s, e) =>
            {
                AppSettings.NightThemeEnd = (int)numThemeNightUntil.Value;
            };

            setNightThemeVisibility();

            onCancel += (s, e) =>
            {
                AppSettings.Theme           = originalTheme;
                AppSettings.NightTheme      = originalThemeNight;
                AppSettings.ThemeHue        = originalThemeHue;
                AppSettings.NightThemeStart = originalThemeNightStart;
                AppSettings.NightThemeEnd   = originalThemeNightEnd;
                AppSettings.Quality         = originalQuality;
                App.MainForm.Refresh();
            };


            trackBar1.Value = Math.Max(Math.Min((int)Math.Round(originalThemeHue * 360), 360), 0);

            trackBar1.ValueChanged += (s, e) =>
            {
                AppSettings.ThemeHue = trackBar1.Value / 360.0;
                App.MainForm.Refresh();
            };

            var defaultScrollSpeed = AppSettings.ScrollMultiplyer;

            trackBar2.Value = Math.Min(400, Math.Max(100, (int)(AppSettings.ScrollMultiplyer * 200)));

            onCancel += (s, e) =>
            {
                AppSettings.ScrollMultiplyer = defaultScrollSpeed;
            };

            lblScrollSpeed.Text = (int)(AppSettings.ScrollMultiplyer * 100) + "%";

            trackBar2.ValueChanged += (s, e) =>
            {
                AppSettings.ScrollMultiplyer = (double)trackBar2.Value / 200;

                lblScrollSpeed.Text = (int)(AppSettings.ScrollMultiplyer * 100) + "%";
            };

            btnSelectFont.Click += (s, e) =>
            {
                using (var dialog = new CustomFontDialog.FontDialog())
                {
                    if (dialog.ShowDialog(this) == DialogResult.OK)
                    {
                        AppSettings.SetFont(dialog.Font.Name, dialog.Font.Size);
                    }
                }

                updateFontName();
            };

            BindCheckBox(chkTimestamps, "ChatShowTimestamps");
            BindCheckBox(chkTimestampSeconds, "ChatShowTimestampSeconds");
            BindCheckBox(chkTimestampAmPm, "TimestampsAmPm");
            BindCheckBox(chkAllowSameMessages, "ChatAllowSameMessage");
            BindCheckBox(chkDoubleClickLinks, "ChatLinksDoubleClickOnly");
            BindCheckBox(chkHideInput, "ChatHideInputIfEmpty");
            BindCheckBox(chkMessageSeperators, "ChatSeperateMessages");
            BindCheckBox(chkRainbow, "Rainbow");
            BindCheckBox(chkStreamlinkPath, "EnableStreamlinkPath");
            BindCheckBox(chkPrefereEmotes, "PrefereEmotesOverUsernames");

            chkMessageSeperators.CheckedChanged += (s, e) =>
            {
                App.MainForm.Refresh();
            };

            BindTextBox(txtMsgLimit, "ChatMessageLimit");

            BindCheckBox(chkHighlight, "ChatEnableHighlight");
            BindCheckBox(chkPings, "ChatEnableHighlightSound");
            BindCheckBox(chkFlashTaskbar, "ChatEnableHighlightTaskbar");
            BindCheckBox(chkCustomPingSound, "ChatCustomHighlightSound");

            BindCheckBox(chkInputShowMessageLength, "ChatInputShowMessageLength");

            BindCheckBox(chkMentionUserWithAt, "ChatMentionUsersWithAt");

            BindCheckBox(chkTabLocalizedNames, "ChatTabLocalizedNames");
            BindCheckBox(chkTopMost, "WindowTopMost");

            BindCheckBox(chkLastReadMessageIndicator, "ChatShowLastReadMessageIndicator");
            chkLastReadMessageIndicator.CheckedChanged += (s, e) =>
            {
                App.MainForm.Refresh();
            };

            txtStreamlinkCustomArguments.Text = AppSettings.CustomStreamlinkArguments;

            txtStreamlinkCustomArguments.TextChanged += (s, e) =>
            {
                AppSettings.CustomStreamlinkArguments = txtStreamlinkCustomArguments.Text;
            };

            var originalCustomStreamlinkArguments = AppSettings.CustomStreamlinkArguments;

            onCancel += (s, e) =>
            {
                AppSettings.CustomStreamlinkArguments = originalCustomStreamlinkArguments;
            };
            #endregion

            // Commands
            #region Commands
            lock (Commands.CustomCommandsLock)
            {
                foreach (var c in Commands.CustomCommands)
                {
                    dgvCommands.Rows.Add(c.Raw);
                }
            }

            //ChatAllowCommandsAtEnd
            var defaultAllowCommandAtEnd = AppSettings.ChatAllowCommandsAtEnd;

            chkAllowCommandAtEnd.Checked = AppSettings.ChatAllowCommandsAtEnd;

            chkAllowCommandAtEnd.CheckedChanged += (s, e) =>
            {
                AppSettings.ChatAllowCommandsAtEnd = chkAllowCommandAtEnd.Checked;
            };

            onCancel += (s, e) =>
            {
                AppSettings.ChatAllowCommandsAtEnd = defaultAllowCommandAtEnd;
            };

            dgvCommands.MultiSelect      = false;
            dgvCommands.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            dgvCommands.Columns[0].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            dgvCommands.KeyDown += (s, e) =>
            {
                if (e.KeyData == (Keys.Control | Keys.Back))
                {
                    e.Handled = true;
                }
            };

            btnCommandAdd.Click += (s, e) =>
            {
                dgvCommands.Rows.Add();
                dgvCommands.Rows[dgvCommands.Rows.Count - 1].Selected = true;
            };

            Action updateCustomCommands = () =>
            {
                lock (Commands.CustomCommandsLock)
                {
                    Commands.CustomCommands.Clear();

                    foreach (DataGridViewRow row in dgvCommands.Rows)
                    {
                        Commands.CustomCommands.Add(new Command((string)row.Cells[0].Value));
                    }
                }
            };

            btnCommandRemove.Click += (s, e) =>
            {
                if (dgvCommands.SelectedCells.Count != 0)
                {
                    dgvCommands.Rows.RemoveAt(dgvCommands.SelectedCells[0].RowIndex);
                }

                updateCustomCommands();
            };

            var originalCustomCommand = Commands.CustomCommands;

            lock (Commands.CustomCommandsLock)
            {
                Commands.CustomCommands = new List <Command>(Commands.CustomCommands);
            }

            dgvCommands.CellValueChanged += (s, e) =>
            {
                updateCustomCommands();
            };

            onCancel += (s, e) =>
            {
                lock (Commands.CustomCommandsLock)
                {
                    Commands.CustomCommands = originalCustomCommand;
                }
            };
            #endregion

            // Emotes
            #region emotes
            BindCheckBox(chkTwitchEmotes, "ChatEnableTwitchEmotes");
            BindCheckBox(chkBttvEmotes, "ChatEnableBttvEmotes");
            BindCheckBox(chkFFzEmotes, "ChatEnableFfzEmotes");
            BindCheckBox(chkEmojis, "ChatEnableEmojis");
            BindCheckBox(chkGifEmotes, "ChatEnableGifAnimations");

            var originalIgnoredEmotes = rtbIngoredEmotes.Text = string.Join(Environment.NewLine, AppSettings.ChatIgnoredEmotes.Keys);

            rtbIngoredEmotes.LostFocus += (s, e) =>
            {
                AppSettings.ChatIgnoredEmotes.Clear();
                var    reader = new StringReader(rtbIngoredEmotes.Text);
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    AppSettings.ChatIgnoredEmotes[line.Trim()] = null;
                }
            };

            onCancel += (s, e) =>
            {
                AppSettings.ChatIgnoredEmotes.Clear();
                var    reader = new StringReader(originalIgnoredEmotes);
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    AppSettings.ChatIgnoredEmotes[line.Trim()] = null;
                }
            };

            BindCheckBox(checkBoxEmoteSizeBasedOnTextHeight, "EmoteScaleByLineHeight");

            var originialEmoteScale = AppSettings.EmoteScale;

            onCancel += (s, e) =>
            {
                AppSettings.EmoteScale = originialEmoteScale;
                App.TriggerEmoteLoaded();
            };

            checkBoxEmoteSizeBasedOnTextHeight.CheckedChanged += (s, e) =>
            {
                labelEmoteScale.Text = $"Emote scale: {AppSettings.EmoteScale:0.##}x";

                App.TriggerEmoteLoaded();
            };

            trackBarEmoteScale.Value = Math.Min(trackBarEmoteScale.Maximum,
                                                Math.Max(trackBarEmoteScale.Minimum, (int)Math.Round((AppSettings.EmoteScale - 0.5) * 10)));

            trackBarEmoteScale.ValueChanged += (s, e) =>
            {
                AppSettings.EmoteScale = trackBarEmoteScale.Value / 10.0 + 0.5;
                labelEmoteScale.Text   = $"Emote scale: {AppSettings.EmoteScale:0.##}x";

                App.TriggerEmoteLoaded();
            };

            labelEmoteScale.Text = $"Emote scale: {AppSettings.EmoteScale:0.##}x";
            #endregion

            // Ignored Users
            #region ignored users
            //BindCheckBox(chkTwitchIgnores, "EnableTwitchUserIgnores");

            foreach (var user in IrcManager.IgnoredUsers)
            {
                dgvIgnoredUsers.Rows.Add(user);
            }

            switch (AppSettings.ChatShowIgnoredUsersMessages)
            {
            case 1:
                comboShowIgnoredUsersMessagesIf.Text = "You are moderator";
                break;

            case 2:
                comboShowIgnoredUsersMessagesIf.Text = "You are broadcaster";
                break;

            default:
                comboShowIgnoredUsersMessagesIf.Text = "Never";
                break;
            }

            comboShowIgnoredUsersMessagesIf.SelectedIndexChanged += (s, e) =>
            {
                if (comboShowIgnoredUsersMessagesIf.Text.Contains("moderator"))
                {
                    AppSettings.ChatShowIgnoredUsersMessages = 1;
                }
                else if (comboShowIgnoredUsersMessagesIf.Text.Contains("broadcaster"))
                {
                    AppSettings.ChatShowIgnoredUsersMessages = 2;
                }
                else
                {
                    AppSettings.ChatShowIgnoredUsersMessages = 0;
                }
            };

            dgvIgnoredUsers.MultiSelect      = false;
            dgvIgnoredUsers.ReadOnly         = true;
            dgvIgnoredUsers.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            dgvIgnoredUsers.Columns[0].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            btnIgnoredUserAdd.Click += (s, e) =>
            {
                using (var dialog = new InputDialogForm("Input Username"))
                {
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        string message;

                        if (IrcManager.TryAddIgnoredUser(dialog.Value.Trim(), out message))
                        {
                            dgvIgnoredUsers.Rows.Add(dialog.Value.Trim());
                        }
                        else
                        {
                            MessageBox.Show(message, "Error while ignoring user");
                        }
                    }
                }
            };

            btnIgnoredUserRemove.Click += (s, e) =>
            {
                if (dgvIgnoredUsers.SelectedCells.Count != 0)
                {
                    string message;
                    var    username = (string)dgvIgnoredUsers.SelectedCells[0].Value;

                    if (IrcManager.TryRemoveIgnoredUser(username, out message))
                    {
                        dgvIgnoredUsers.Rows.RemoveAt(dgvIgnoredUsers.SelectedCells[0].RowIndex);
                    }
                    else
                    {
                        MessageBox.Show(message, "Error while unignoring user");
                    }
                }
            };
            #endregion

            // Ignored Messages
            #region ignored messages
            var ignoreKeywordsOriginal = rtbIgnoreKeywords.Text = string.Join(Environment.NewLine, AppSettings.ChatIgnoredKeywords);

            rtbIgnoreKeywords.LostFocus += (s, e) =>
            {
                var    list   = new List <string>();
                var    reader = new StringReader(rtbIgnoreKeywords.Text);
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    list.Add(line.Trim());
                }
                AppSettings.ChatIgnoredKeywords = list.ToArray();
            };

            onCancel += (s, e) =>
            {
                // highlight keywords
                {
                    var    list   = new List <string>();
                    var    reader = new StringReader(ignoreKeywordsOriginal);
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        list.Add(line.Trim());
                    }
                    AppSettings.ChatIgnoredKeywords = list.ToArray();
                }
            };
            #endregion

            // Links

            //RegistryKey browserKeys;
            ////on 64bit the browsers are in a different location
            //browserKeys = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Clients\StartMenuInternet");
            //if (browserKeys == null)
            //    browserKeys = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Clients\StartMenuInternet");
            //string[] browserNames = browserKeys.GetSubKeyNames();

            // Proxy
            BindCheckBox(chkProxyEnabled, "ProxyEnable");
            BindTextBox(textBox1, "ProxyHost");
            BindTextBox(textBox4, "ProxyPort");
            BindTextBox(textBox2, "ProxyUsername");
            BindTextBox(textBox3, "ProxyPassword");

            // Highlights
            #region highlights
            var customHighlightsOriginal      = rtbHighlights.Text = string.Join(Environment.NewLine, AppSettings.ChatCustomHighlights);
            var highlightIgnoredUsersOriginal = rtbUserBlacklist.Text = string.Join(Environment.NewLine, AppSettings.HighlightIgnoredUsers.Keys);

            rtbHighlights.LostFocus += (s, e) =>
            {
                var    list   = new List <string>();
                var    reader = new StringReader(rtbHighlights.Text);
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    list.Add(line.Trim());
                }
                AppSettings.ChatCustomHighlights = list.ToArray();
            };

            rtbUserBlacklist.LostFocus += (s, e) =>
            {
                AppSettings.HighlightIgnoredUsers.Clear();
                var    reader = new StringReader(rtbUserBlacklist.Text);
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    AppSettings.HighlightIgnoredUsers[line.Trim().ToLower()] = null;
                }
            };

            onCancel += (s, e) =>
            {
                // highlight keywords
                {
                    var    list   = new List <string>();
                    var    reader = new StringReader(customHighlightsOriginal);
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        list.Add(line.Trim());
                    }
                    AppSettings.ChatCustomHighlights = list.ToArray();
                }

                // user blacklist
                {
                    AppSettings.HighlightIgnoredUsers.Clear();
                    var    reader = new StringReader(highlightIgnoredUsersOriginal);
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        AppSettings.HighlightIgnoredUsers[line.Trim().ToLower()] = null;
                    }
                }
            };

            updateFontName();

            btnCustomHighlightOpenFile.Click += (s, e) =>
            {
                using (var dialog = new OpenFileDialog())
                {
                    dialog.Filter = "wave sound file|*.wav";

                    if (dialog.ShowDialog(this) == DialogResult.OK)
                    {
                        try
                        {
                            (GuiEngine.Current as WinformsGuiEngine).HighlightSound?.Dispose();

                            if (!Directory.Exists(Path.Combine(Util.GetUserDataPath(), "Custom")))
                            {
                                Directory.CreateDirectory(Path.Combine(Util.GetUserDataPath(), "Custom"));
                            }

                            File.Copy(dialog.FileName, Path.Combine(Util.GetUserDataPath(), "Custom", "Ping.wav"), true);
                        }
                        catch (Exception exc)
                        {
                            MessageBox.Show(exc.Message, "Error copying the highlight sound");
                        }
                    }
                }
            };
            #endregion

            // Moderation
            BindCheckBox(chkBanButton, "EnableBanButton");
            BindCheckBox(chkTimeoutButton, "EnableTimeoutButton");

            var originalTimeoutButtons = new List <int>(AppSettings.TimeoutButtons);

            Action updateTimeoutButtons = () =>
            {
                List <int> values = new List <int>();
                foreach (var control in listView1.Controls)
                {
                    values.Add((control as TimespanSelectControl).GetValue());
                }
                AppSettings.TimeoutButtons = values;
            };

            foreach (var i in AppSettings.TimeoutButtons)
            {
                var c = new TimespanSelectControl(i);
                c.ValueChanged += (s, e) => updateTimeoutButtons();
                listView1.Controls.Add(c);
            }

            onCancel += (s, e) =>
            {
                AppSettings.TimeoutButtons = originalTimeoutButtons;
            };

            listView1.ControlRemoved += (s, e) => updateTimeoutButtons();
            listView1.ControlAdded   += (s, e) => updateTimeoutButtons();

            btnAddTimeout.Click += (s, e) =>
            {
                listView1.Controls.Add(new TimespanSelectControl());
            };

            // Whispers
            BindCheckBox(chkEnableInlineWhispers, "ChatEnableInlineWhispers");

            //Buttons
            var x = 0;

            ///Cancel
            btnCancel           = new Button();
            btnCancel.AutoSize  = true;
            btnCancel.Text      = "Cancel";
            btnCancel.Location  = new Point(tabs.Panel.Width - 12 - btnCancel.Width - x, tabs.Panel.Height - 12 - btnCancel.Height);
            btnCancel.Anchor    = (AnchorStyles.Right | AnchorStyles.Bottom);
            btnCancel.BackColor = Color.FromArgb(0);
            btnCancel.Click    += new EventHandler(btnCancel_Click);
            tabs.Panel.Controls.Add(btnCancel);
            x += 12 + btnCancel.Width;

            ///OK
            BtnOK           = new Button();
            BtnOK.AutoSize  = true;
            BtnOK.Text      = "Apply";
            BtnOK.Location  = new Point(tabs.Panel.Width - 12 - BtnOK.Width - x, tabs.Panel.Height - 12 - btnCancel.Height);
            BtnOK.Anchor    = (AnchorStyles.Right | AnchorStyles.Bottom);
            BtnOK.BackColor = Color.FromArgb(0);
            BtnOK.Click    += new EventHandler(btnOK_Click);
            tabs.Panel.Controls.Add(BtnOK);
            x += 12 + BtnOK.Width;

            /////ResetCurrent
            //btnResetCurrent = new Button();
            //btnResetCurrent.AutoSize = true;
            //btnResetCurrent.Text = "Reset Current Page";
            //btnResetCurrent.Location = new Point(tabs.Panel.Width - 12 - btnResetCurrent.Width - x, tabs.Panel.Height - 12 - btnOK.Height);
            //btnResetCurrent.Anchor = (AnchorStyles.Right | AnchorStyles.Bottom);
            //btnResetCurrent.BackColor = Color.FromArgb(0);
            //btnResetCurrent.Click += new EventHandler(btnResetCurrent_Click);
            //tabs.Panel.Controls.Add(btnResetCurrent);
            //x += 12 + btnResetCurrent.Width;

            /////ResetAll
            //btnResetAll = new Button();
            //btnResetAll.AutoSize = true;
            //btnResetAll.Text = "Reset All";
            //btnResetAll.Location = new Point(tabs.Panel.Width - 12 - btnResetAll.Width - x, tabs.Panel.Height - 12 - btnOK.Height);
            //btnResetAll.Anchor = (AnchorStyles.Right | AnchorStyles.Bottom);
            //btnResetAll.BackColor = Color.FromArgb(0);
            //btnResetAll.Click += new EventHandler(btnResetAll_Click);
            //tabs.Panel.Controls.Add(btnResetAll);
            //x += 12 + btnResetAll.Width;

            Closed += (s, e) =>
            {
                AppSettings.Save();
            };
        }
コード例 #7
0
        static void Main()
        {
            CurrentVersion = VersionNumber.Parse(
                AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().Location).Version.ToString());

            if (!File.Exists("./removeupdatenew") && Directory.Exists("./Updater.new"))
            {
                UpdaterPath = Path.Combine(new FileInfo(Assembly.GetEntryAssembly().Location).Directory.FullName,
                                           "Updater.new", "Chatterino.Updater.exe");
            }
            else
            {
                if (File.Exists("./update2"))
                {
                    UpdaterPath = Path.Combine(new FileInfo(Assembly.GetEntryAssembly().Location).Directory.FullName,
                                               "Updater2", "Chatterino.Updater.exe");
                }
            }

            Directory.SetCurrentDirectory(new FileInfo(Assembly.GetEntryAssembly().Location).Directory.FullName);

            GuiEngine.Initialize(new WinformsGuiEngine());

            ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
            ServicePointManager.DefaultConnectionLimit = int.MaxValue;
            //ServicePointManager.UseNagleAlgorithm = false;
            //ServicePointManager.MaxServicePoints = 10000;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //SetProcessDpiAwareness(_Process_DPI_Awareness.Process_Per_Monitor_DPI_Aware);

            Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);

            // Fonts
            if (Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1)
            {
                UseDirectX = true;
            }

            // Exceptions
            Application.ThreadException += (s, e) =>
            {
                e.Exception.Log("exception", "{0}\n");
            };
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                (e.ExceptionObject as Exception).Log("exception", "{0}\n");
            };
            EmoteCache.init();
            // Update gif emotes
            int offset = 0;

            new System.Windows.Forms.Timer {
                Interval = 30, Enabled = true
            }.Tick += (s, e) =>
            {
                if (AppSettings.ChatEnableGifAnimations)
                {
                    lock (GuiEngine.Current.GifEmotesLock)
                    {
                        offset += 3;
                        if (offset < 0)
                        {
                            offset = 0;
                        }
                        try {
                            if (EmoteList != null && EmoteList.GetGifEmotes() != null)
                            {
                                GuiEngine.Current.GifEmotesOnScreen.UnionWith(EmoteList.GetGifEmotes());
                            }
                            foreach (LazyLoadedImage emote in GuiEngine.Current.GifEmotesOnScreen)
                            {
                                if (emote.HandleAnimation != null)
                                {
                                    emote.HandleAnimation(offset);
                                }
                            }
                            if (ToolTip != null && ToolTip.Visible && ToolTip.Image != null && ToolTip.Image.HandleAnimation != null)
                            {
                                ToolTip.Image.HandleAnimation(offset);
                                lock (ToolTip) {
                                    ToolTip.redraw();
                                }
                            }
                        } catch (Exception err) {
                            GuiEngine.Current.log("error updating gifs " + err.ToString());
                        }
                    }
                    GifEmoteFramesUpdated?.Invoke(null, EventArgs.Empty);
                }
            };

            // Settings/Colors
            try
            {
                if (!Directory.Exists(Util.GetUserDataPath()))
                {
                    Directory.CreateDirectory(Util.GetUserDataPath());
                }

                if (!Directory.Exists(Path.Combine(Util.GetUserDataPath(), "Custom")))
                {
                    Directory.CreateDirectory(Path.Combine(Util.GetUserDataPath(), "Custom"));
                }
            }
            catch
            {
            }

            AppSettings.SavePath = Path.Combine(Util.GetUserDataPath(), "Settings.ini");

            var showWelcomeForm = false;

            try
            {
                if (!File.Exists(AppSettings.SavePath))
                {
                    CanShowChangelogs = false;

                    showWelcomeForm = true;

                    if (File.Exists("./Settings.ini") && !File.Exists(AppSettings.SavePath))
                    {
                        File.Move("./Settings.ini", AppSettings.SavePath);

                        try

                        {
                            File.Delete("./Settings.ini");
                        }
                        catch { }
                    }

                    if (File.Exists("./Custom/Commands.txt") &&
                        !File.Exists(Path.Combine(Util.GetUserDataPath(), "Custom", "Commands.txt")))
                    {
                        File.Move("./Custom/Commands.txt", Path.Combine(Util.GetUserDataPath(), "Custom", "Commands.txt"));

                        try
                        {
                            File.Delete("./Custom/Commands.txt");
                        }
                        catch { }
                    }

                    if (File.Exists("./Custom/Ping.wav") &&
                        !File.Exists(Path.Combine(Util.GetUserDataPath(), "Custom", "Ping.wav")))
                    {
                        File.Move("./Custom/Ping.wav", Path.Combine(Util.GetUserDataPath(), "Custom", "Ping.wav"));

                        try
                        {
                            File.Delete("./Custom/Ping.wav");
                        }
                        catch { }
                    }

                    if (File.Exists("./Layout.xml") &&
                        !File.Exists(Path.Combine(Util.GetUserDataPath(), "Layout.xml")))
                    {
                        File.Move("./Layout.xml", Path.Combine(Util.GetUserDataPath(), "Layout.xml"));

                        try
                        {
                            File.Delete("./Layout.xml");
                        }
                        catch { }
                    }
                }
            }
            catch
            {
            }

            AppSettings.Load();

            AccountManager.LoadFromJson(Path.Combine(Util.GetUserDataPath(), "Login.json"));

            IrcManager.Account = AccountManager.FromUsername(AppSettings.SelectedUser) ?? Account.AnonAccount;
            IrcManager.Connect();

            Commands.LoadOrDefault(Path.Combine(Util.GetUserDataPath(), "Custom", "Commands.txt"));
            Cache.Load();

            _updateTheme();

            AppSettings.ThemeChanged += (s, e) => _updateTheme();

            // Check for updates
            //try
            //{
            //    string updaterPath = "./Updater";
            //    string newUpdaterPath = "./Updater.new";

            //    if (Directory.Exists(newUpdaterPath))
            //    {
            //        if (Directory.Exists(updaterPath))
            //            Directory.Delete(updaterPath, true);

            //        Directory.Move(newUpdaterPath, updaterPath);
            //    }
            //}
            //catch { }

            Updates.UpdateFound += (s, e) =>
            {
                try
                {
                    using (var dialog = new UpdateDialog())
                    {
                        if (File.Exists(UpdaterPath))
                        {
                            var result = dialog.ShowDialog();

                            // OK -> install now
                            // Yes -> install on exit
                            if (result == DialogResult.OK || result == DialogResult.Yes)
                            {
                                using (var client = new WebClient())
                                {
                                    client.DownloadFile(e.Url, Path.Combine(Util.GetUserDataPath(), "update.zip"));
                                }

                                installUpdatesOnExit = true;

                                if (result == DialogResult.OK)
                                {
                                    restartAfterUpdates = true;
                                    MainForm?.Close();
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("An update is available but the update executable could not be found. If you want to update chatterino you will have to reinstall it.");
                        }
                    }
                }
                catch { }
            };

#if DEBUG
            Updates.CheckForUpdate("win-dev", CurrentVersion);
#else
            Updates.CheckForUpdate("win-release", CurrentVersion);
#endif

            // Start irc
            Emotes.LoadGlobalEmotes();
            Badges.LoadGlobalBadges();
            GuiEngine.Current.LoadBadges();
            Net.StartHttpServer();

            // Show form
            MainForm = new MainForm();

            MainForm.Show();

            if (showWelcomeForm)
            {
                new WelcomeForm().Show();
            }

            MainForm.FormClosed += (s, e) =>
            {
                Application.Exit();

                // Save settings
                AppSettings.Save();

                Cache.Save();

                EmoteCache.SaveEmoteList();

                Commands.Save(Path.Combine(Util.GetUserDataPath(), "Custom", "Commands.txt"));
            };

            Application.Run();
            Environment.Exit(0);
        }
コード例 #8
0
ファイル: UserSwitchPopup.cs プロジェクト: vileelf/botterino
        public UserSwitchPopup()
        {
            FormBorderStyle = FormBorderStyle.None;

            KeyPreview = true;

            TopMost = AppSettings.WindowTopMost;

            AppSettings.WindowTopMostChanged += (s, e) =>
            {
                TopMost = AppSettings.WindowTopMost;
            };

            // listview
            var listView = new ListView()
            {
                Font = new Font("Segoe UI", 14f),
                View = View.List,
                Size = new Size(Width, Height - 32)
            };

            Controls.Add(listView);

            listView.Items.Add("anonymous user");

            var accounts = AccountManager.Accounts.ToList();

            accounts.Sort((acc1, acc2) => string.Compare(acc1.Username, acc2.Username, StringComparison.Ordinal));

            foreach (var account in accounts)
            {
                listView.Items.Add(account.Username);
            }

            listView.ItemActivate += (s, e) =>
            {
                IrcManager.Account = AccountManager.FromUsername(listView.FocusedItem.Text) ?? Account.AnonAccount;
                IrcManager.Connect();

                Close();
            };

            // button
            var manageAccountsButton = new Button()
            {
                AutoSize = true,
                Text     = "Manage Accounts",
            };

            manageAccountsButton.Location = new Point(8, Height - (manageAccountsButton.Height + 32) / 2);

            manageAccountsButton.Click += (s, e) =>
            {
                Close();

                App.ShowSettings();
                App.SettingsDialog.Show("Accounts");
            };

            Controls.Add(manageAccountsButton);

            // hotkey
            var label = new Label
            {
                Text     = "Hotkey: Ctrl+U",
                AutoSize = true,
            };

            label.Location = new Point(Width - label.Width, manageAccountsButton.Location.Y + 5);

            Controls.Add(label);
        }
コード例 #9
0
ファイル: ChatCommands.cs プロジェクト: vileelf/chatterino
        public static void addChatCommands()
        {
            Commands.ChatCommands.TryAdd("user", (s, channel, execute) =>
            {
                if (execute)
                {
                    var S = s.SplitWords();
                    if (S.Length > 0 && S[0].Length > 0)
                    {
                        Common.UserInfoData data = new Common.UserInfoData();
                        data.UserName            = S[0];
                        data.Channel             = channel;
                        if ((data.UserId = IrcManager.LoadUserIDFromTwitch(data.UserName)) != null)
                        {
                            var popup = new UserInfoPopup(data)
                            {
                                StartPosition = FormStartPosition.Manual,
                                Location      = Cursor.Position
                            };

                            popup.Show();

                            var screen = Screen.FromPoint(Cursor.Position);

                            int x = popup.Location.X, y = popup.Location.Y;

                            if (popup.Location.X < screen.WorkingArea.X)
                            {
                                x = screen.WorkingArea.X;
                            }
                            else if (popup.Location.X + popup.Width > screen.WorkingArea.Right)
                            {
                                x = screen.WorkingArea.Right - popup.Width;
                            }

                            if (popup.Location.Y < screen.WorkingArea.Y)
                            {
                                y = screen.WorkingArea.Y;
                            }
                            else if (popup.Location.Y + popup.Height > screen.WorkingArea.Bottom)
                            {
                                y = screen.WorkingArea.Bottom - popup.Height;
                            }

                            popup.Location = new Point(x, y);
                        }
                        else
                        {
                            channel.AddMessage(new Chatterino.Common.Message($"This user could not be found (/user {data.UserName})"));
                        }
                    }
                }
                return(null);
            });

            // Chat Commands
            Commands.ChatCommands.TryAdd("w", (s, channel, execute) =>
            {
                if (execute)
                {
                    var S = s.SplitWords();

                    if (S.Length > 1)
                    {
                        var name = S[0];

                        IrcMessage message;
                        IrcMessage.TryParse($":{name}!{name}@{name}.tmi.twitch.tv PRIVMSG #whispers :" + s.SubstringFromWordIndex(1), out message);

                        TwitchChannel.WhisperChannel.AddMessage(new Chatterino.Common.Message(message, TwitchChannel.WhisperChannel, isSentWhisper: true));

                        if (AppSettings.ChatEnableInlineWhispers)
                        {
                            var inlineMessage = new Chatterino.Common.Message(message, TwitchChannel.WhisperChannel, true, false, isSentWhisper: true)
                            {
                                HighlightTab = false
                            };

                            inlineMessage.HighlightType = HighlightType.Whisper;

                            foreach (var c in TwitchChannel.Channels)
                            {
                                c.AddMessage(inlineMessage);
                            }
                        }
                    }
                }

                return("/w " + s);
            });

            Commands.ChatCommands.TryAdd("ignore", (s, channel, execute) =>
            {
                if (execute)
                {
                    var S = s.SplitWords();
                    if (S.Length > 0)
                    {
                        IrcManager.AddIgnoredUser(S[0], null);
                    }
                }
                return(null);
            });
            Commands.ChatCommands.TryAdd("rejoin", (s, channel, execute) =>
            {
                if (execute)
                {
                    Task.Run(() =>
                    {
                        channel.Rejoin();
                    });
                }
                return(null);
            });
            Commands.ChatCommands.TryAdd("unignore", (s, channel, execute) =>
            {
                if (execute)
                {
                    var S = s.SplitWords();
                    if (S.Length > 0)
                    {
                        IrcManager.RemoveIgnoredUser(S[0], null);
                    }
                }
                return(null);
            });

            Commands.ChatCommands.TryAdd("uptime", (s, channel, execute) =>
            {
                if (execute && channel != null)
                {
                    try
                    {
                        var request =
                            WebRequest.Create(
                                $"https://api.twitch.tv/helix/streams?user_login={channel.Name}");
                        if (AppSettings.IgnoreSystemProxy)
                        {
                            request.Proxy = null;
                        }
                        request.Headers["Authorization"] = $"Bearer {IrcManager.Account.OauthToken}";
                        request.Headers["Client-ID"]     = $"{IrcManager.DefaultClientID}";
                        using (var resp = request.GetResponse())
                            using (var stream = resp.GetResponseStream())
                            {
                                var parser = new JsonParser();

                                dynamic json = parser.Parse(stream);
                                dynamic data = json["data"];
                                if (data != null && data.Count > 0 && data[0]["type"] != "")
                                {
                                    dynamic root = data[0];

                                    string createdAt = root["started_at"];

                                    var streamStart = DateTime.Parse(createdAt);

                                    var uptime = DateTime.Now - streamStart;

                                    var text = "Stream uptime: ";

                                    if (uptime.TotalDays > 1)
                                    {
                                        text += (int)uptime.TotalDays + " days, " + uptime.ToString("hh\\h\\ mm\\m\\ ss\\s");
                                    }
                                    else
                                    {
                                        text += uptime.ToString("hh\\h\\ mm\\m\\ ss\\s");
                                    }

                                    channel.AddMessage(new Chatterino.Common.Message(text));
                                }
                            }
                    }
                    catch { }
                }

                return(null);
            });
        }