public VersionBetweenAttribute(VersionState minVersionState, String minVersionString, VersionState maxVersionState, String maxVersionString)
        {
            this.minVersion = new DroneFirmwareVersion(minVersionString);
            this.minVersionState = minVersionState;

            this.maxVersion = new DroneFirmwareVersion(maxVersionString);
            this.maxVersionState = maxVersionState;
        }
        public VersionBetweenAttribute(VersionState minVersionState, String minVersionString, VersionState maxVersionState, String maxVersionString)
        {
            this.minVersion      = new DroneFirmwareVersion(minVersionString);
            this.minVersionState = minVersionState;

            this.maxVersion      = new DroneFirmwareVersion(maxVersionString);
            this.maxVersionState = maxVersionState;
        }
Ejemplo n.º 3
0
            private void FixState(char current)
            {
                if (char.IsDigit(current))
                {
                    versionObject.Fix = (int)char.GetNumericValue(current);

                    currentState   = VersionState.Done;
                    currentPointer = null;
                }
            }
Ejemplo n.º 4
0
            private void MinorState(char current)
            {
                if (char.IsDigit(current))
                {
                    versionObject.VersionMinor = (int)char.GetNumericValue(current);

                    currentState   = VersionState.SettingFix;
                    currentPointer = FixState;
                }
            }
Ejemplo n.º 5
0
        // Helper function to read the response from a Url and return a version state machine
        internal static async Task <VersionState> GetVersionFromSource(string pageSource)
        {
            // Create an instance of an HtmlAgilityPack Html document that we can load the Url response into
            HtmlDocument updateDoc = new HtmlDocument();

            // Create a default state machine of there being no new update
            VersionState state = new VersionState()
            {
                IsNewVersion = false, Url = String.Empty, Version = string.Empty
            };

            //Load the page source into the HtmlAgilityPack document so that we can parse the DOM effectively
            updateDoc.LoadHtml(pageSource);

            // Find any 'H3' elements in the document
            var pageH3s = updateDoc.DocumentNode.Descendants("h3");

            if (pageH3s != null)
            {
                // The first one that has a 'Zip' file as its source, is our upgrade file
                var firstZipLink = pageH3s.Select(h3 => h3.Descendants("a").FirstOrDefault(a => a.Attributes["href"] != null && a.Attributes["href"].Value != null && a.Attributes["href"].Value.ToLower().Contains(".zip"))).FirstOrDefault(item => item != null);

                if (firstZipLink != null)
                {
                    var linkVersion = firstZipLink.Attributes["data-version"];

                    //List<string> linkText = firstZipLink.InnerText.Split(' ').ToList();
                    if (linkVersion?.Value != null)
                    {
                        // Use the link text to get the version number
                        string webVersionInfo = linkVersion.Value;

                        // Get the current version number (note the process DOESN'T take into account revisions...)
                        string appVersionInfo = ApplicationUtility.BuildVersion();

                        // Create an appropriate state machine for this versions
                        ApplicationUtility.VersionState currentState = ApplicationUtility.CompareVersions(appVersionInfo, webVersionInfo);

                        // Alter the state machine based on whether the remote version is newer
                        if (currentState == ApplicationUtility.VersionState.WebIsNewer)
                        {
                            state.IsNewVersion = true;
                            state.Version      = webVersionInfo;
                            state.Url          = firstZipLink.Attributes["href"].Value;
                        }
                    }
                }
            }

            // Clear up and close the HtmlAgilityPack document
            updateDoc = null;

            return(state);
        }
Ejemplo n.º 6
0
        public void CreateVersionState_DesiredGreaterLessThanZero_SetsToLast()
        {
            using (_mocks.Record())
            {
                SetupResult.For(_configuration.DesiredVersion).Return((long)-1);
                SetupResult.For(_schemaStateManager.GetAppliedMigrationVersions(null)).Return(new long[] { 1, 2, 3 });
            }
            VersionState actual = _target.CreateVersionState(_migrations)[string.Empty];

            Assert.AreEqual(4, actual.Desired);
        }
Ejemplo n.º 7
0
        public void CreateVersionState_PassAlongScopeFromConfiguration()
        {
            using (_mocks.Record())
            {
                SetupResult.For(_configuration.Scope).Return("core");
                SetupResult.For(_schemaStateManager.GetAppliedMigrationVersions("core")).Return(new long[] { 1, 2, 3 });
            }
            VersionState actual = _target.CreateVersionState(_migrations)[string.Empty];

            Assert.AreEqual(0, actual.Desired);
        }
Ejemplo n.º 8
0
        public void CreateVersionState_Always_SetsApplied()
        {
            using (_mocks.Record())
            {
                SetupResult.For(_configuration.DesiredVersion).Return((long)2);
                SetupResult.For(_schemaStateManager.GetAppliedMigrationVersions(null)).Return(new long[] { 1, 2, 3 });
            }
            VersionState actual = _target.CreateVersionState(_migrations)[string.Empty];

            CollectionAssert.AreEqual(new long[] { 1, 2, 3 }, new List <long>(actual.Applied));
        }
Ejemplo n.º 9
0
        // Asynchronous method for checking the specified Url for any new version numbers
        public static async Task <VersionState> CheckVersion(string versionURL)
        {
            // Load the Url, and read the response as an array of bytes
            byte[] versionPageBytes = await LoadPage(versionURL).ConfigureAwait(false);

            // Convert the bytes into UTF-8 formatted text
            string versionPageSource = Encoding.UTF8.GetString(versionPageBytes);

            // Scrape the response string, and get an appropriate version state from it
            VersionState versionFromSource = await GetVersionFromSource(versionPageSource).ConfigureAwait(false);

            return(versionFromSource);
        }
Ejemplo n.º 10
0
 public int getVersion(VersionState partOfVersion)
 {
     switch (partOfVersion)
     {
         case VersionState.Build:
             return Build;
         case VersionState.Debug:
             return Debug;
         case VersionState.mainVersion:
             return mainVersion;
         case VersionState.subVersion:
             return subVersion;
         default:
             return -1;
     }
 }
Ejemplo n.º 11
0
 public void Count(VersionState Version)
 {
     switch (Version)
     {
         case VersionState.Build:
             Build += 1;
             break;
         case VersionState.Debug:
             Debug+= 1;
             break;
         case VersionState.mainVersion:
             mainVersion+= 1;
             break;
         case VersionState.subVersion:
             subVersion+= 1;
             break;
         default:
             //nothing
             break;
     }
 }
Ejemplo n.º 12
0
        public AppVersion(string version, VersionState state = VersionState.Stable)
        {
            Match m;

            if ((m = rtmPattern.Match(version)).Success)
            {
                SetVersion(m);
                State = state;
            }
            else if ((m = prvPattern.Match(version)).Success)
            {
                PreviewDate = new DateTime(int.Parse("20" + m.Groups[1].Value), int.Parse(m.Groups[2].Value), int.Parse(m.Groups[3].Value));
                if (m.Groups[4].Success)
                {
                    Revision = int.Parse(m.Groups[4].Value);
                }
                State = VersionState.PreAlpha;
            }
            else
            {
                throw new ArgumentException("正しい文字列表現ではありません.", nameof(version));
            }
        }
Ejemplo n.º 13
0
        private async void MainForm_Load(object sender, EventArgs e)
        {
            // Wait till program shows up
            await Task.Delay(1);

#warning application do events

            // Minimize the form to the system tray if the switcher was launched in silent mode
            if (m_silent)
            {
                Hide();
                notifyIcon.Visible = true;
            }

            // Fix bug that the icon in the taskbar would be the one from the latest created shortcut that points to this program
            // e.g. when creating a shortcut for bancho the icon of this program in the taskbar would be the bancho icon
            Icon = Icon.FromHandle(Icon.Handle);
#warning not working

            // Check the state of the current version
            VersionState vs = await VersionChecker.GetCurrentState();

            if (vs == VersionState.BLACKLISTED)
            {
                // If the current version is blacklisted, prevent the user from using it.
                MessageBox.Show($"Your current version ({VersionChecker.CurrentVersion}) is blacklisted.\r\n\r\nThis can happen when the version contains security flaws or other things that could interrupt a good user experience.\r\n\r\nPlease download the newest version of the switcher from our GitHub page.\r\n(github.com/minisbett/ultimate-osu-server-switcher/releases)", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(0);
                return;
            }
            else if (vs == VersionState.MAINTENANCE)
            {
                // If the switcher is in maintenance, also prevent the user from using it.
                MessageBox.Show("The switcher is currently hold in maintenance mode which means that the switcher is currently not available.\r\n\r\nJoin our discord server for more informations.\r\nThe Discord server and be found on our GitHub page.", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(0);
                return;
            }
            else if (vs == VersionState.OUTDATED)
            {
                // Show the user a message that a new version is available if the current switcher is outdated.
                MessageBox.Show($"Your switcher version ({VersionChecker.CurrentVersion}) is outdated.\r\nA newer version ({await VersionChecker.GetNewestVersion()}) is available.\r\n\r\nWe recommend to download the newest version of the switcher from our GitHub page.\r\n(github.com/minisbett/ultimate-osu-server-switcher/releases)", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }


            lblInfo.Text = "Fetching mirrors...";
            Application.DoEvents();

            // Try to load online data and verify servers
            List <Mirror> mirrors = null;
            try
            {
                // Download the mirror data from github and deserialize it into a mirror list
                mirrors = JsonConvert.DeserializeObject <List <Mirror> >(await WebUtils.DownloadStringAsync(Urls.Mirrors));
            }
            catch
            {
                // If it was not successful, github may cannot currently be reached or I made a mistake in the json data.
                MessageBox.Show("Error whilst parsing the server mirrors from GitHub!\r\nPlease make sure you can connect to www.github.com in your browser.\r\n\r\nIf this issue persists, please visit our Discord server.", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
                return;
            }

            // set the maximum to the amount of mirrors + amount of static servers that need to be loaded
            imgLoadingBar.Maximum = mirrors.Count + Server.StaticServers.Length;

            // Parse every server from their mirror
            foreach (Mirror mirror in mirrors)
            {
                lblInfo.Text = $"Loading mirror {mirror.Url}";
                Application.DoEvents();

                Server server = null;
                // Try to serialize the mirror into a server
                try
                {
                    // Download the data from the mirror and try to parse it into a server object.
                    server = JsonConvert.DeserializeObject <Server>(await WebUtils.DownloadStringAsync(mirror.Url));
                }
                catch
                {
                    // If the cast was not successful (invalid json) or the mirror could not be reached, skip the mirror
                    imgLoadingBar.Value++;
                    continue;
                }

                // Forward mirror variables to the server
                server.IsFeatured = mirror.Featured;
                server.UID        = mirror.UID;

                // add the server
                await Switcher.AddServer(server);

                imgLoadingBar.Value++;
                Application.DoEvents();
            }

            // Load the static servers
            foreach (Server server in Server.StaticServers)
            {
                lblInfo.Text = $"Loading {server.ServerName}";
                Application.DoEvents();

                // add the server directly because hardcoded servers dont need the validation checks (or would even fail there)
                await Switcher.AddServerNoCheck(server);

                imgLoadingBar.Value++;
                Application.DoEvents();
            }

            // Remove all saved accounts from servers that may no longer exist
            List <Account> accounts = JsonConvert.DeserializeObject <List <Account> >(m_accounts["accounts"]);
            accounts.RemoveAll(a => !Switcher.Servers.Any(x => x.UID == a.ServerUID));
            m_accounts["accounts"] = JsonConvert.SerializeObject(accounts);

            // Remove all history entries from servers that may no longer exist
            List <HistoryElement> history = JsonConvert.DeserializeObject <HistoryElement[]>(m_history["history"]).ToList();
            history.RemoveAll(a => !Switcher.Servers.Any(x => x.UID == a.FromUID) || !Switcher.Servers.Any(x => x.UID == a.ToUID));
            m_history["history"] = JsonConvert.SerializeObject(history.ToArray());

            // Enable/Disable the timer depending on if useDiscordRichPresence is true or false
            // Set here because the timer needs to have the servers loaded
            richPresenceUpdateTimer.Enabled = m_settings["useDiscordRichPresence"] == "true";

            // Initialize the current selected server variable
            m_currentSelectedServer = Switcher.GetCurrentServer();
            // If current connected server is unidentified, show/select bancho
            if (m_currentSelectedServer.IsUnidentified)
            {
                m_currentSelectedServer = Switcher.Servers.First(x => x.UID == "bancho");
            }

            // Hide loading button and loading bar after all mirrors are loaded
            pctrLoading.Visible   = false;
            imgLoadingBar.Visible = false;

            // Show the account manager button, the Create A Shortcut linklabel and the history button because all servers are loaded now
            btnAccountManager.Visible    = true;
            lnklblCreateShortcut.Visible = true;
            btnHistory.Visible           = true;

            // Update the UI
            UpdateUI();
        }
Ejemplo n.º 14
0
        private async void MainForm_Load(object sender, EventArgs e)
        {
            // Hide the connect button, show the loading button to make the user clear that the servers are being fetched
            btnConnect.Visible  = false;
            pctrLoading.Visible = true;
            Application.DoEvents();

            await Task.Delay(1);

            // Check the state of the current version
            VersionState vs = await VersionChecker.GetCurrentState();

            if (vs == VersionState.BLACKLISTED)
            {
                // If the current version is blacklisted, prevent the user from using it.
                MessageBox.Show($"Your current version ({VersionChecker.CurrentVersion}) is blacklisted.\r\n\r\nThis can happen when the version contains security flaws or other things that could interrupt a good user experience.\r\n\r\nPlease download the newest version of the switcher from its website. (github.com/minisbett/ultimate-osu-server-switcher/releases).", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(0);
                return;
            }
            else if (vs == VersionState.MAINTENANCE)
            {
                // If the switcher is in maintenance, also prevent the user from using it.
                MessageBox.Show("The switcher is currently hold in maintenance mode which means that the switcher is currently not available.\r\n\r\nJoin our discord server for more informations.\r\nThe discord server and be found on our github page.", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(0);
                return;
            }
            else if (vs == VersionState.OUTDATED)
            {
                // Show the user a message that a new version is available if the current switcher is outdated.
                MessageBox.Show($"Your switcher version ({VersionChecker.CurrentVersion}) is outdated.\r\nA newer version ({await VersionChecker.GetNewestVersion()}) is available.\r\n\r\nYou can download it from our github page.", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }


            lblInfo.Text = "Fetching mirrors...";
            Application.DoEvents();

            // Try to load online data and verify servers
            List <Mirror> mirrors = null;

            try
            {
                // Download the mirror data from github and deserialize it into a mirror list
                mirrors = JsonConvert.DeserializeObject <List <Mirror> >(await WebHelper.DownloadStringAsync(Urls.Mirrors));
            }
            catch
            {
                // If it was not successful, github may cannot currently be reached or I made a mistake in the json data.
                MessageBox.Show("Error whilst parsing the server mirrors from GitHub!\r\nPlease make sure you can connect to www.github.com in your browser.\r\n\r\nIf this issue persists, please visit our discord. You can find the invite link on our GitHub Page (minisbett/ultimate-osu-server-switcher)", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
                return;
            }

            imgLoadingBar.Maximum = mirrors.Count;
            // Try to load all servers
            List <Server> servers = new List <Server>();

            foreach (Mirror mirror in mirrors)
            {
                lblInfo.Text = $"Parsing mirror {mirror.Url}";
                Application.DoEvents();
                Server server = null;
                // Try to serialize the mirror into a server
                try
                {
                    // Download the data from the mirror and try to parse it into a server object.
                    server = JsonConvert.DeserializeObject <Server>(await WebHelper.DownloadStringAsync(mirror.Url));
                }
                catch
                {
                    // If the cast was not successful (invalid json) or the mirror could not be reached, skip the mirror
                    continue;
                }
                // Forward mirror variables to the server
                server.IsFeatured = mirror.Featured;
                server.UID        = mirror.UID;
                lblInfo.Text      = $"Parsing mirror {mirror.Url} ({server.ServerName})";
                Application.DoEvents();

                // Check if UID is 6 letters long (If not I made a mistake)
                if (server.UID.Length != 6)
                {
                    continue;
                }

                // Check if the UID is really unique (I may accidentally put the same uid for two servers)
                if (servers.Any(x => x.UID == server.UID))
                {
                    continue;
                }

                // Check if everything is set
                if (server.ServerName == null ||
                    server.IP == null ||
                    server.IconUrl == null ||
                    server.CertificateUrl == null ||
                    server.DiscordUrl == null)
                {
                    continue;
                }

                // Check if server name length is valid (between 3 and 24)
                if (server.ServerName.Replace(" ", "").Length < 3 || server.ServerName.Length > 24)
                {
                    continue;
                }
                // Check if it neither start with a space, nor end
                if (server.ServerName.StartsWith(" "))
                {
                    continue;
                }
                if (server.ServerName.EndsWith(" "))
                {
                    continue;
                }
                // // Only a-zA-Z0-9 ! is allowed
                if (!Regex.Match(server.ServerName.Replace("!", "").Replace(" ", ""), "^\\w+$").Success)
                {
                    continue;
                }
                // Double spaces are invalid because its hard to tell how many spaces there are
                // (One server could be named test 123 and the other test  123)
                if (server.ServerName.Replace("  ", "") != server.ServerName)
                {
                    continue;
                }
                // Check if the server fakes a hardcoded server
                if (Server.StaticServers.Any(x => x.ServerName == server.ServerName))
                {
                    continue;
                }

                // Check if the server ip is formatted correctly
                if (!Regex.IsMatch(server.IP, @"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"))
                {
                    continue;
                }

                // Check if that server name already exists (if so, prioritize the first one)
                if (servers.Any(x => x.ServerName.ToLower().Replace(" ", "") == server.ServerName.ToLower().Replace(" ", "")))
                {
                    continue;
                }

                // Check if its a real discord invite url
                if (!server.DiscordUrl.Replace("https", "").Replace("http", "").Replace("://", "").StartsWith("discord.gg"))
                {
                    continue;
                }

                // Initialize variables like Certificate and Icon that are downloaded from their urls when
                // all checks are done (IconUrl, CertificateUrl)

                try
                {
                    // Try to parse the certificate from the given url
                    server.Certificate = await WebHelper.DownloadBytesAsync(server.CertificateUrl);

                    server.CertificateThumbprint = new X509Certificate2(server.Certificate).Thumbprint;
                }
                catch // Cerfiticate url not valid or certificate type is not cer (base64 encoded)
                {
                    continue;
                }

                // Check if icon is valid
                try
                {
                    // Download the icon and check if its at least 256x256
                    Image icon = await WebHelper.DownloadImageAsync(server.IconUrl);

                    if (icon.Width < 256 || icon.Height < 256)
                    {
                        continue;
                    }

                    // Scale the image to 256x256
                    server.Icon = new Bitmap(icon, new Size(256, 256));

                    // Add the server to the servers that were successfully parsed and checked
                    servers.Add(server);
                }
                catch // Image could not be downloaded or loaded
                {
                    continue;
                }

                imgLoadingBar.Value++;
            }

            // Load bancho and localhost
            try
            {
                // Download the icon and check if its at least 256x256
                Image icon = await WebHelper.DownloadImageAsync(Server.BanchoServer.IconUrl);

                if (icon.Width >= 256 && icon.Height >= 256)
                {
                    // Add the bancho server
                    Server s = Server.BanchoServer;
                    // Scale the image to 256x256
                    s.Icon = new Bitmap(icon, new Size(256, 256));
                    servers.Add(s);
                }
            }
            catch // Image could not be downloaded or loaded
            {
            }

            try
            {
                // Download the icon and check if its at least 256x256
                Image icon = await WebHelper.DownloadImageAsync(Server.LocalhostServer.IconUrl);

                if (icon.Width >= 256 && icon.Height >= 256)
                {
                    // Add the localhost server
                    Server s = Server.LocalhostServer;
                    // Scale the image to 256x256
                    s.Icon = new Bitmap(icon, new Size(256, 256));
                    servers.Add(s);
                }
            }
            catch // Image could not be downloaded or loaded
            {
            }

            // Sort the servers by priority (first bancho, then featured, then normal, then localhost)
            servers = servers.OrderByDescending(x => x.Priority).ToList();

            // Create .ico files for shortcuts
            foreach (Server server in servers)
            {
                using (FileStream fs = File.OpenWrite(Paths.IconCacheFolder + $@"\{server.UID}.ico"))
                    using (MemoryStream ms = new MemoryStream((byte[])new ImageConverter().ConvertTo(server.Icon, typeof(byte[]))))
                        ImagingHelper.ConvertToIcon(ms, fs, server.Icon.Width, true);
            }

            Switcher.Servers = servers;

            // Enable/Disable the timer depending on if useDiscordRichPresence is true or false
            // Set here because the timer needs to have the servers loaded
            richPresenceUpdateTimer.Enabled = m_settings["useDiscordRichPresence"] == "true";

            // Initialize the current selected server variable
            m_currentSelectedServer = Switcher.GetCurrentServer();
            if (m_currentSelectedServer.IsUnidentified)
            {
                m_currentSelectedServer = Switcher.Servers.First(x => x.UID == "bancho");
            }

            // Hide loading button and loading bar after all mirrors are loaded
            pctrLoading.Visible   = false;
            imgLoadingBar.Visible = false;

            // Show the account manager button because all servers are loaded now
            btnAccountManager.Visible = true;

            // Update the UI
            UpdateUI();
        }
 void RenderVersionText(Rect versionRect, string content, GUIStyle style, VersionState state)
 {
     //TODO - VersionState에 맞는 색깔 넣어주기
     GUI.Label(versionRect, content, style);
 }
 public VersionStateChangeInfo(VersionState versionState)
 {
     _versionState = versionState;
 }
Ejemplo n.º 17
0
 // mainVersion.subVersion.Build.Debug
 public bool Count(VersionState Version)
 {
     projectVersion.Count(Version);
     return true;
 }
Ejemplo n.º 18
0
 public UnityVersionParser(UnityVersion versionObject)
 {
     this.versionObject  = versionObject;
     this.currentState   = VersionState.SettingMajor;
     this.currentPointer = MajorState;
 }