private void CalculateMyOperation()
        {
            try
            {
                using (WebClient webClient = new WebClientWithTimeout())
                {
                    webClient.Headers.Add("User-Agent: Other");
                    var page = webClient.DownloadString(FindElement.Settings.DefaultServer ?? AppVariable.DefaultServer2);
                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(page);
                    var query = doc.DocumentNode.SelectNodes("//table[@class='table table-striped table-hover']/tbody/tr")
                                .Select(r =>
                    {
                        var linkNode = r.Descendants("a").Select(node => node.Attributes["href"].Value).ToArray();
                        return(new DelegationLink()
                        {
                            Row = r.SelectSingleNode(".//td").InnerText,
                            link = FindElement.Settings.DefaultServer + linkNode.FirstOrDefault(),
                            Category = r.SelectSingleNode(".//td[2]").InnerText,
                            Title = r.SelectSingleNode(".//td[3]").InnerText,
                            Date = r.SelectSingleNode(".//td[4]").InnerText,
                            Type = r.SelectSingleNode(".//td[5]").InnerText,
                            SubType = r.SelectSingleNode(".//td[6]").InnerText
                        });
                    }
                                        ).ToList();
                    var parsedValues = query.Take(Limited ? 20 : query.Count).ToList();
                    myClass = parsedValues;
                    int currentIndex = 0;
                    Dispatcher.Invoke(() =>
                    {
                        lst.Items.Clear();
                        btnStart.IsEnabled    = false;
                        prgLoading.Visibility = Visibility.Hidden;
                        prgUpdate.Visibility  = Visibility.Visible;
                    });
                    foreach (var i in parsedValues)
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            currentIndex += 1;
                            lst.Items.Add(i);

                            prgUpdate.Value = (Convert.ToDouble(((double)currentIndex / (double)parsedValues.Count).ToString("N2")) * 100);
                        }), DispatcherPriority.Background);
                    }
                }
            }
            catch (ArgumentNullException) { }
            catch (WebException)
            {
                Dispatcher.BeginInvoke(new Action(() => { MainWindow.main.showGrowlNotification(AppVariable.Recived_Circular_KEY, false); }), DispatcherPriority.Background);
            }
        }
        /// <summary>
        /// Attempts to download a string from a remote URL. Throws WebException if anything goes awry/the request times out.
        /// </summary>
        /// <param name="Url">The URL to download the string from.</param>
        /// <param name="TimeOut">After this specified amount of time in seconds, the request will timeout.</param>
        /// <returns>The downloaded string, or null if it failed to download.</returns>
        public static string DownloadStringTimeout(string Url, int TimeOut)
        {
            string downloadResult = null;

            WebClientWithTimeout webClient = new WebClientWithTimeout(TimeOut);

            webClient.Headers["user-agent"] = "WebUtils Parsing";

            downloadResult = webClient.DownloadString(Url);

            return(downloadResult);
        }
Exemple #3
0
        private static string GetLatestReleaseJson()
        {
            // .NET 3.5 Framework workaround for TLS 1.2, though still assumes
            // that the Windows system executing this code has the necessary
            // updates installed. Remove upon upgrade past .NET 3.5.
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)(SslProtocols)0x00000C00;

            var client = new WebClientWithTimeout(TimeSpan.FromSeconds(2));

            client.Headers.Add("User-Agent", "twopointzero/TJAPlayer3");

            return(client.DownloadString(
                       "https://api.github.com/repos/twopointzero/tjaplayer3/releases/latest"));
        }
        private void Settings_Load(object sender, EventArgs e)
        {
            //Serverlist
            var response = "";

            try {
                WebClient wc        = new WebClientWithTimeout();
                string    serverurl = "http://launcher.soapboxrace.world/serverlist.txt";
                response = wc.DownloadString(serverurl);
            } catch (Exception) { }

            serverText.DisplayMember = "Text";
            serverText.ValueMember   = "Value";

            List <Object> items = new List <Object>();

            String[] substrings = response.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
            foreach (var substring in substrings)
            {
                if (!String.IsNullOrEmpty(substring))
                {
                    String[] substrings22 = substring.Split(new string[] { ";" }, StringSplitOptions.None);
                    items.Add(new { Text = substrings22[0], Value = substrings22[1] });
                }
            }

            serverText.DataSource    = items;
            serverText.SelectedIndex = 0;

            //Executable
            var executables = Directory.GetFiles(".", "*.exe");

            executableText.DisplayMember = "Text";
            executableText.ValueMember   = "Value";

            List <Object> items2 = new List <Object>();

            foreach (var substring2 in executables)
            {
                var dummy = substring2.Replace(".\\", "");
                if (dummy != AppDomain.CurrentDomain.FriendlyName)
                {
                    items2.Add(dummy);
                }
            }

            executableText.DataSource = items2;
        }
        /// <summary>
        /// Initialize the mock server and confirm it is available..
        /// </summary>
        public StubServer()
        {
            const string homePageResponse = "Hello from the mock security api";
            var          uri = $"{ConfigurationHelper.MockPaymentDetailsApiHost()}:{ConfigurationHelper.MockPaymentDetailsApiPort()}";

            _stubHttp = HttpMockRepository.At(uri);
            _stubHttp.Stub(x => x.Get(""))
            .Return(homePageResponse)
            .OK();

            var webClient = new WebClientWithTimeout {
                Timeout = 2 * 1000
            };
            string result = webClient.DownloadString(uri);

            Assert.AreEqual(homePageResponse, result);
        }
        private string GetRemoteRepositoryHash()
        {
            try
            {
                using (var webClient = new WebClientWithTimeout(WebRequestTimeout))
                {
                    var remoteRepositoryHash = webClient.DownloadString(storeRemoteProductHash).Trim();
                    return(remoteRepositoryHash);
                }
            }
            catch (Exception e)
            {
                LogProvider.Log.Error(this, "Remote hash of product app store has not been obtained.", e);
            }

            return(null);
        }
Exemple #7
0
        public void RefreshCurrencyRates()
        {
            var currencyUrl = CommonResourceManager.Instance.GetResourceString("SystemSettings_CurrencyRates");

            Task.Run(() =>
            {
                try
                {
                    using (var webClient = new WebClientWithTimeout())
                    {
                        var currencyRatesDataBase64 = webClient.DownloadString(currencyUrl).Trim();

                        var currencyRates = GetCurrencyRates(currencyRatesDataBase64);

                        if (currencyRates == null)
                        {
                            LogProvider.Log.Warn(this, "Failed to obtain currency rates from server.");
                            return;
                        }

                        var settingsService = ServiceLocator.Current.GetInstance <ISettingsService>();
                        var settingsModel   = settingsService.GetSettings();
                        var generalSettings = settingsModel?.GeneralSettings;

                        if (generalSettings == null)
                        {
                            LogProvider.Log.Warn(this, "Failed to find general settings.");
                            return;
                        }

                        if (generalSettings.CRates.Equals(currencyRatesDataBase64, StringComparison.Ordinal))
                        {
                            return;
                        }

                        generalSettings.CRates = currencyRatesDataBase64;
                        settingsService.SaveSettings(settingsModel);
                    }
                }
                catch (Exception e)
                {
                    LogProvider.Log.Error(this, "Failed to refresh currency rates.", e);
                }
            });
        }
Exemple #8
0
#pragma warning disable S1541 // Methods and properties should not be too complex
        public string ExecuteRequest(int timeoutMilliseconds, string method, string url, string data, List <Tuple <string, string> > headers, Action <string> asyncCallback)
#pragma warning restore S1541 // Methods and properties should not be too complex
        {
            using (var webClient = new WebClientWithTimeout(timeoutMilliseconds))
            {
                webClient.Credentials = CredentialCache.DefaultCredentials;

                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        webClient.Headers.Add(header.Item1, header.Item2);
                    }
                }

                var uri = new Uri(url.Contains("http://") || url.Contains("https://") ? url : "http://" + url);

                switch (method)
                {
                case "GET":
                    if (asyncCallback == null)
                    {
                        return(webClient.DownloadString(uri));
                    }
                    webClient.DownloadStringCompleted += (sender, args) => asyncCallback?.Invoke(args.Result);
                    webClient.DownloadStringAsync(uri, null);
                    break;

                case "POST":
                    if (asyncCallback == null)
                    {
                        return(webClient.UploadString(uri, data));
                    }
                    webClient.UploadStringCompleted += (sender, args) => asyncCallback?.Invoke(args.Result);
                    webClient.UploadStringAsync(uri, data);
                    break;

                default:
                    return(string.Empty);
                }
            }
            return(string.Empty);
        }
Exemple #9
0
        /// <summary>
        /// Retrieves a JSON structure describing all existing versions of Minecraft.
        /// </summary>
        /// <returns>A <see cref="Task"/> object that that represents the current state of the download operation.</returns>
        /// <exception cref="WebException">
        /// Thrown if the web API request times out.
        /// </exception>
        public static async Task <VersionInformationTag> GetAllJavaVersionInformation()
        {
            WebClientWithTimeout mojangRequest = new WebClientWithTimeout(1000);

            return(await Task.Run(() => JsonConvert.DeserializeObject <VersionInformationTag>(mojangRequest.DownloadString("https://launchermeta.mojang.com/mc/game/version_manifest.json"))));
        }
Exemple #10
0
        /// <summary>
        /// Retrieves information about the latest version of the Minecraft: Bedrock Edition server.
        /// </summary>
        /// <returns>A <see cref="Task"/> object that that represents the current state of the download operation.</returns>
        /// <exception cref="WebException">
        /// Thrown if the web API request times out.
        /// </exception>
        public static async Task <ServerVersionInformation> GetCurrentBedrockServerVersionInformation()
        {
            WebClientWithTimeout mojangRequest = new WebClientWithTimeout(1000);

            return(await Task.Run(() => new RoyalXmlSerializer().Deserialize <ServerVersionInformation>(mojangRequest.DownloadString("http://raw.githubusercontent.com/DouglasDwyer/IntegratedMinecraftServer/master/IMS-Distribution/bedrock-version.xml"))));
        }
Exemple #11
0
        // TODO: factor out the guts of this and the default timout method above with a private method taking a WebClient object
        public string ExecuteRequest(int timeoutMilliseconds, string method, string url, string data, List<Tuple<string, string>> headers = null, Action<string> asyncCallback = null)
        {
            using (var webClient = new WebClientWithTimeout(timeoutMilliseconds))
            {
                webClient.Credentials = CredentialCache.DefaultCredentials;

                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        webClient.Headers.Add(header.Item1, header.Item2);
                    }
                }

                var uri = new Uri(url.Contains("http://") || url.Contains("https://") ? url : "http://" + url);

                switch (method)
                {
                    case "GET":
                        if (asyncCallback == null)
                        {
                            return webClient.DownloadString(uri);
                        }
                        webClient.DownloadStringCompleted += (sender, args) => asyncCallback(args.Result);
                        webClient.DownloadStringAsync(uri, null);
                        break;
                    case "POST":
                        if (asyncCallback == null)
                        {
                            return webClient.UploadString(uri, data);
                        }
                        webClient.UploadStringCompleted += (sender, args) => asyncCallback(args.Result);
                        webClient.UploadStringAsync(uri, data);
                        break;
                }
            }
            return string.Empty;
        }
        public SelectServer()
        {
            InitializeComponent();

            //And one for keeping data about server, IP tbh
            Dictionary <int, ServerInfo> data = new Dictionary <int, ServerInfo>();

            ServerListRenderer.View          = View.Details;
            ServerListRenderer.FullRowSelect = true;

            ServerListRenderer.Columns.Add("ID");
            ServerListRenderer.Columns[0].Width = 25;

            ServerListRenderer.Columns.Add("Name");
            ServerListRenderer.Columns[1].Width = 320;

            ServerListRenderer.Columns.Add("Players Online");
            ServerListRenderer.Columns[2].Width     = 80;
            ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Right;

            ServerListRenderer.Columns.Add("Registered Players");
            ServerListRenderer.Columns[3].Width     = 100;
            ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Right;

            //Actually accept JSON instead of old format//
            List <ServerInfo> serverInfos = new List <ServerInfo>();

            foreach (var serverListURL in Self.serverlisturl)
            {
                try {
                    var wc       = new WebClientWithTimeout();
                    var response = wc.DownloadString(serverListURL);

                    try {
                        serverInfos.AddRange(JsonConvert.DeserializeObject <List <ServerInfo> >(response));
                    } catch (Exception error) {
                        //throw new Exception("Error occurred while deserializing server list from [" + serverListURL + "]: " + error.Message, error);
                    }
                } catch (Exception error) {
                    //throw new Exception("Error occurred while loading server list from [" + serverListURL + "]: " + error.Message, error);
                }
            }

            foreach (var substring in serverInfos)
            {
                try {
                    GetServerInformation content = JsonConvert.DeserializeObject <GetServerInformation>(new WebClientWithTimeout().DownloadString(substring.IpAddress + "/GetServerInformation"));

                    Console.Write(content);

                    if (content != null)
                    {
                        ServerListRenderer.Items.Add(new ListViewItem(
                                                         new[] {
                            ID.ToString(),
                            substring.Name,
                            content.onlineNumber.ToString(),
                            content.numberOfRegistered.ToString(),
                        }
                                                         ));

                        data.Add(ID, substring);
                    }

                    rememberServerInformationID.Add(ID, content);
                    ID++;
                } catch {
                }
            }

            ServerListRenderer.AllowColumnReorder   = false;
            ServerListRenderer.ColumnWidthChanging += (handler, args) => {
                args.Cancel   = true;
                args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width;
            };

            ServerListRenderer.DoubleClick += new EventHandler((handler, args) => {
                if (ServerListRenderer.SelectedItems.Count == 1)
                {
                    rememberServerInformationID.TryGetValue(ServerListRenderer.SelectedIndices[0], out ServerInfo);

                    MainScreen.ServerName = data[ServerListRenderer.SelectedIndices[0] + 1];

                    this.Close();
                }
            });
        }
Exemple #13
0
        public static void Register(String email, String password, String token = null)
        {
            try
            {
                WebClientWithTimeout wc = new WebClientWithTimeout();
                String buildUrl         = Tokens.IPAddress + "/User/createUser?email=" + email + "&password="******"&inviteTicket=" + token : "");
                serverLoginResponse = wc.DownloadString(buildUrl);
            }
            catch (WebException ex)
            {
                var serverReply = (HttpWebResponse)ex.Response;
                if (serverReply == null)
                {
                    _errorcode          = 500;
                    serverLoginResponse = "<LoginStatusVO><UserId/><LoginToken/><Description>Failed to get reply from server. Please retry.</Description></LoginStatusVO>";
                }
                else
                {
                    using (var sr = new StreamReader(serverReply.GetResponseStream()))
                    {
                        _errorcode          = (int)serverReply.StatusCode;
                        serverLoginResponse = sr.ReadToEnd();
                    }
                }
            }

            try
            {
                var sbrwXml = new XmlDocument();
                sbrwXml.LoadXml(serverLoginResponse);

                XmlNode extraNode;
                XmlNode loginTokenNode;
                XmlNode userIdNode;
                var     msgBoxInfo = "";

                loginTokenNode = sbrwXml.SelectSingleNode("LoginStatusVO/LoginToken");
                userIdNode     = sbrwXml.SelectSingleNode("LoginStatusVO/UserId");

                if (sbrwXml.SelectSingleNode("LoginStatusVO/Ban") == null)
                {
                    if (sbrwXml.SelectSingleNode("LoginStatusVO/Description") == null)
                    {
                        extraNode = sbrwXml.SelectSingleNode("html/body");
                    }
                    else
                    {
                        extraNode = sbrwXml.SelectSingleNode("LoginStatusVO/Description");
                    }
                }
                else
                {
                    extraNode = sbrwXml.SelectSingleNode("LoginStatusVO/Ban");
                }

                if (string.IsNullOrEmpty(extraNode.InnerText) || extraNode.InnerText == "SERVER FULL")
                {
                    Tokens.UserId     = userIdNode.InnerText;
                    Tokens.LoginToken = loginTokenNode.InnerText;

                    if (extraNode.InnerText == "SERVER FULL")
                    {
                        Tokens.Success = string.Format("Successfully registered on {0}. However, server is actually full, therefore you cannot play it right now.", Tokens.ServerName);
                    }
                    else
                    {
                        Tokens.Success = string.Format("Successfully registered on {0}. You can log in now.", Tokens.ServerName);
                    }
                }
                else
                {
                    if (extraNode.SelectSingleNode("Reason") != null)
                    {
                        msgBoxInfo  = string.Format("You got banned on {0}.", Tokens.ServerName) + "\n";
                        msgBoxInfo += string.Format("Reason: {0}", extraNode.SelectSingleNode("Reason").InnerText);

                        if (extraNode.SelectSingleNode("Expires") != null)
                        {
                            msgBoxInfo += "\n" + string.Format("Ban expires {0}", extraNode.SelectSingleNode("Expires").InnerText);
                        }
                        else
                        {
                            msgBoxInfo += "\n" + "Banned forever.";
                        }
                    }
                    else
                    {
                        if (extraNode.InnerText == "Please use MeTonaTOR's launcher. Or, are you tampering?")
                        {
                            msgBoxInfo = "Launcher tampering detected. Please use original build.";
                        }
                        else
                        {
                            if (sbrwXml.SelectSingleNode("html/body") == null)
                            {
                                if (extraNode.InnerText == "LOGIN ERROR")
                                {
                                    msgBoxInfo = "Invalid e-mail or password.";
                                }
                                else
                                {
                                    msgBoxInfo = extraNode.InnerText;
                                }
                            }
                            else
                            {
                                msgBoxInfo = "ERROR " + _errorcode + ": " + extraNode.InnerText;
                            }
                        }
                    }

                    Tokens.Error = msgBoxInfo;
                }
            }
            catch (Exception ex)
            {
                Tokens.Error = "An error occured: " + ex.Message;
            }
        }
        public static void UpdateList()
        {
            thread = new Thread(new ThreadStart(() =>
            {
                List <Task> tasks = new List <Task>();
                ConcurrentBag <ServerInfo> serverInfos = new ConcurrentBag <ServerInfo>();

                foreach (string serverurl in Self.serverlisturl)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        string response = null;
                        try
                        {
                            Log.Debug("Loading serverlist from: " + serverurl);
                            WebClientWithTimeout wc = new WebClientWithTimeout();

                            response = wc.DownloadString(serverurl);
                        }
                        catch (Exception error)
                        {
                            Log.Error(error.Message);
                        }
                        if (response != null)
                        {
                            Log.Debug("Loaded serverlist from: " + serverurl);

                            foreach (ServerInfo si in JsonConvert.DeserializeObject <List <ServerInfo> >(response))
                            {
                                serverInfos.Add(si);
                            }
                        }
                    }));
                }

                if (File.Exists("servers.json"))
                {
                    var fileItems = JsonConvert.DeserializeObject <List <ServerInfo> >(File.ReadAllText("servers.json")) ?? new List <ServerInfo>();

                    if (fileItems.Count > 0)
                    {
                        serverInfos.Add(new ServerInfo
                        {
                            Id        = "__category-CUSTOMCUSTOM__",
                            Name      = "<GROUP>Custom Servers",
                            IsSpecial = true
                        });

                        fileItems.Select(si =>
                        {
                            si.DistributionUrl    = "";
                            si.DiscordPresenceKey = "";
                            si.Id        = SHA.HashPassword($"{si.Name}:{si.Id}:{si.IpAddress}");
                            si.IsSpecial = false;
                            si.Category  = "CUSTOMCUSTOM";

                            return(si);
                        }).ToList().ForEach(si => serverInfos.Add(si));
                    }
                }

                if (File.Exists("libOfflineServer.dll"))
                {
                    serverInfos.Add(new ServerInfo
                    {
                        Id        = "__category-OFFLINEOFFLINE__",
                        Name      = "<GROUP>Offline Server",
                        IsSpecial = true
                    });

                    serverInfos.Add(new ServerInfo
                    {
                        Name               = "Offline Built-In Server",
                        Category           = "OFFLINEOFFLINE",
                        DiscordPresenceKey = "",
                        IsSpecial          = false,
                        DistributionUrl    = "",
                        IpAddress          = "http://localhost:4416/sbrw/Engine.svc",
                        Id = "OFFLINE"
                    });
                }

                //Somewhere here i have to remove duplicates...

                foreach (Task task in tasks)
                {
                    task.Wait();
                }

                foreach (var serverItemGroup in serverInfos.Reverse().GroupBy(s => s.Category))
                {
                    if (finalItems.FindIndex(i => string.Equals(i.Name, $"<GROUP>{serverItemGroup.Key} Servers")) == -1)
                    {
                        finalItems.Add(new ServerInfo
                        {
                            Id        = $"__category-{serverItemGroup.Key}__",
                            Name      = $"<GROUP>{serverItemGroup.Key} Servers",
                            IsSpecial = true
                        });
                    }
                    finalItems.AddRange(serverItemGroup.ToList());
                }
            }));

            thread.IsBackground = true;
            thread.Start();
        }
Exemple #15
0
        private void Press_Regist(object sender, RoutedEventArgs e)
        {
            if (emailForRegist.Text.ToString() == "" || password0.Password.ToString() == "" || password1.Password.ToString() == "")
            {
                MessageBox.Show(getStrFromResource("questToFillAccInfForReg"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (password0.Password.ToString() != password1.Password.ToString())
            {
                password0.Password = "";
                password1.Password = "";
                MessageBox.Show(getStrFromResource("questErrorAccInfForReg"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            string serverLoginResponse;

            try
            {
                WebClient wcr = new WebClientWithTimeout();
                wcr.Headers.Add("user-agent", "GameLauncher (+https://github.com/XFaost/World-Evolved-Launcher)");

                string BuildURL = serverIP + "/User/createUser?email=" + emailForRegist.Text.ToString() + "&password="******"<LoginStatusVO><UserId/><LoginToken/><Description>Failed to get reply from server. Please retry.</Description></LoginStatusVO>";
                }
                else
                {
                    using (var sr = new StreamReader(serverReply.GetResponseStream()))
                    {
                        serverLoginResponse = sr.ReadToEnd();
                    }
                }
            }

            XmlDocument SBRW_XML = new XmlDocument();

            SBRW_XML.LoadXml(serverLoginResponse);
            var nodes = SBRW_XML.SelectNodes("LoginStatusVO");

            try
            {
                foreach (XmlNode childrenNode in nodes)
                {
                    string Description = childrenNode["Description"].InnerText;

                    if (Description == "Registration Error: Email already exists!")
                    {
                        MessageBox.Show(getStrFromResource("alreadyEmail"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    else if (Description != "")
                    {
                        MessageBox.Show(Description);
                    }
                    if (childrenNode["UserId"].InnerText != "" && childrenNode["LoginToken"].InnerText != "")
                    {
                        MessageBox.Show(getStrFromResource("succReg"), getStrFromResource("WE"), MessageBoxButton.OK);
                        backFunk();
                        return;
                    }
                }
                ;
            }
            catch
            {
                MessageBox.Show(getStrFromResource("unknownError"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }
Exemple #16
0
        static void Main()
        {
            String  Username, Password, ServerAddress, serverLoginResponse, encryptedPassword, LoginToken, UserId, Executable;
            String  ConfigFile = AppDomain.CurrentDomain.FriendlyName.Replace(".exe", "") + ".ini";
            IniFile Config     = new IniFile(ConfigFile);


            if (!File.Exists(Directory.GetCurrentDirectory() + "/lightfx.dll"))
            {
                File.WriteAllBytes(Directory.GetCurrentDirectory() + "/lightfx.dll", ExtractResource.AsByte("InstantGameLauncher.SoapBoxModules.lightfx.dll"));
                Directory.CreateDirectory(Directory.GetCurrentDirectory() + "/modules");
                File.WriteAllText(Directory.GetCurrentDirectory() + "/modules/udpcrc.soapbox.module", ExtractResource.AsString("InstantGameLauncher.SoapBoxModules.udpcrc.soapbox.module"));
                File.WriteAllText(Directory.GetCurrentDirectory() + "/modules/udpcrypt1.soapbox.module", ExtractResource.AsString("InstantGameLauncher.SoapBoxModules.udpcrypt1.soapbox.module"));
                File.WriteAllText(Directory.GetCurrentDirectory() + "/modules/udpcrypt2.soapbox.module", ExtractResource.AsString("InstantGameLauncher.SoapBoxModules.udpcrypt2.soapbox.module"));
                File.WriteAllText(Directory.GetCurrentDirectory() + "/modules/xmppsubject.soapbox.module", ExtractResource.AsString("InstantGameLauncher.SoapBoxModules.xmppsubject.soapbox.module"));
            }

            if (!File.Exists(ConfigFile))
            {
                DialogResult InstallerAsk = MessageBox.Show(null, "There's no " + ConfigFile + " file. Do you wanna run Settings page?", "InstantGameLauncher", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (InstallerAsk == DialogResult.Yes)
                {
                    //Let's show form
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Settings());
                }

                Environment.Exit(Environment.ExitCode);
            }

            Uri Server_Address = new Uri(Config.Read("ServerAddress", "Configuration"));

            if (Server_Address.Port == 80)
            {
                ServerAddress = Server_Address.Scheme + "://" + Server_Address.Host + "/soapbox-race-core/Engine.svc";
            }
            else
            {
                ServerAddress = Server_Address.Scheme + "://" + Server_Address.Host + ":" + Server_Address.Port + "/soapbox-race-core/Engine.svc";
            }

            Username = Config.Read("Username", "Configuration");
            Password = Config.Read("Password", "Configuration");

            HashAlgorithm algorithm = SHA1.Create();
            StringBuilder sb        = new StringBuilder();

            foreach (byte b in algorithm.ComputeHash(Encoding.UTF8.GetBytes(Password)))
            {
                sb.Append(b.ToString("X2"));
            }

            encryptedPassword   = sb.ToString();
            serverLoginResponse = "";

            try {
                WebClient wc = new WebClientWithTimeout();
                Server_Address = new Uri(ServerAddress);
                string BuildURL = ServerAddress + "/User/authenticateUser?email=" + Username + "&password="******"Failed to connect to the server. " + ex.Message);
                    //    Environment.Exit(Environment.ExitCode);
                    //}
                }
                else
                {
                    MessageBox.Show(null, "Failed to connect to the server. " + ex.Message, "InstantGameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Environment.Exit(Environment.ExitCode);
                }
            }

            try {
                XmlDocument SBRW_XML = new XmlDocument();
                SBRW_XML.LoadXml(serverLoginResponse);

                XmlNode DescriptionNode, LoginTokenNode, UserIdNode;

                DescriptionNode = SBRW_XML.SelectSingleNode("LoginStatusVO/Description");
                LoginTokenNode  = SBRW_XML.SelectSingleNode("LoginStatusVO/LoginToken");
                UserIdNode      = SBRW_XML.SelectSingleNode("LoginStatusVO/UserId");

                if (String.IsNullOrEmpty(DescriptionNode.InnerText))
                {
                    UserId     = UserIdNode.InnerText;
                    LoginToken = LoginTokenNode.InnerText;

                    if (Config.KeyExists("UseExecutable", "Configuration"))
                    {
                        Executable = Config.Read("UseExecutable", "Configuration");
                    }
                    else
                    {
                        Executable = "nfsw.exe";
                    }

                    if (!File.Exists(Executable))
                    {
                        MessageBox.Show(null, "Failed to launch " + Executable + ". File not found.", "InstantGameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Environment.Exit(Environment.ExitCode);
                    }

                    string filename = Directory.GetCurrentDirectory() + "\\" + Executable;
                    String cParams  = "US " + ServerAddress + " " + LoginToken + " " + UserId;
                    Process.Start(filename, cParams);
                }
                else
                {
                    MessageBox.Show(null, DescriptionNode.InnerText, "InstantGameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            } catch {
                MessageBox.Show(null, "Server is offline.", "InstantGameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #17
0
        /// <summary>
        /// Retrieves a JSON structure describing data about a single version of Minecraft.
        /// </summary>
        /// <param name="version">The version to download additional information about.</param>
        /// <returns>A <see cref="Task"/> object that represents the current state of the download operation.</returns>
        /// <exception cref="WebException">
        /// Thrown if the web API request times out.
        /// </exception>
        public static async Task <VersionDataTag> GetVersionInformation(VersionMetadataTag version)
        {
            WebClientWithTimeout mojangRequest = new WebClientWithTimeout(1000);

            return(await Task.Run(() => JsonConvert.DeserializeObject <VersionDataTag>(mojangRequest.DownloadString(version.url))));
        }
Exemple #18
0
 /// <summary>
 /// Gets the username of a Minecraft: Java Edition player from their UUID.
 /// </summary>
 /// <param name="uuid">The UUID of the player to get information about.</param>
 /// <returns>A string representing the player's username.</returns>
 public static string GetUsernameFromUUID(string uuid)
 {
     try
     {
         WebClientWithTimeout mojangRequest = new WebClientWithTimeout(1000);
         NameTimelineTag[]    tag           = JsonConvert.DeserializeObject <NameTimelineTag[]>(mojangRequest.DownloadString("https://api.mojang.com/user/profiles/" + uuid.Replace("-", "") + "/names"));
         return(tag.Last().name);
     }
     catch
     {
         Logger.WriteWarning("Could not get player " + uuid + "'s username from Mojang servers!");
         return(null);
     }
 }
Exemple #19
0
 /// <summary>
 /// Gets the UUID of a Minecraft: Java Edition player from their username.
 /// </summary>
 /// <param name="username">The username of the player to get information about.</param>
 /// <returns>A string that represents the player's UUID.</returns>
 public static string GetUUIDFromUsername(string username)
 {
     try
     {
         WebClientWithTimeout mojangRequest = new WebClientWithTimeout(1000);
         PlayerIDPairTag      tag           = JsonConvert.DeserializeObject <PlayerIDPairTag>(mojangRequest.DownloadString("https://api.mojang.com/users/profiles/minecraft/" + username));
         return(tag.id);
     }
     catch
     {
         Logger.WriteWarning("Could not get player " + username + "'s UUID from Mojang servers!");
         return(null);
     }
 }
        public static void UpdateList()
        {
            List <ServerInfo> serverInfos = new List <ServerInfo>();

            foreach (var serverListURL in Self.serverlisturl)
            {
                try {
                    Log.Debug("Loading serverlist from: " + serverListURL);
                    var wc       = new WebClientWithTimeout();
                    var response = wc.DownloadString(serverListURL);
                    Log.Debug("Loaded serverlist from: " + serverListURL);

                    try {
                        serverInfos.AddRange(
                            JsonConvert.DeserializeObject <List <ServerInfo> >(response));
                    } catch (Exception error) {
                        Log.Error("Error occurred while deserializing server list from [" + serverListURL + "]: " + error.Message);
                    }
                } catch (Exception error) {
                    Log.Error("Error occurred while loading server list from [" + serverListURL + "]: " + error.Message);
                }
            }

            if (File.Exists("servers.json"))
            {
                var fileItems = JsonConvert.DeserializeObject <List <ServerInfo> >(File.ReadAllText("servers.json")) ?? new List <ServerInfo>();

                if (fileItems.Count > 0)
                {
                    serverInfos.Add(new ServerInfo
                    {
                        Id        = "__category-CUSTOM__",
                        Name      = "<GROUP>Custom Servers",
                        IsSpecial = true
                    });

                    fileItems.Select(si =>
                    {
                        si.DistributionUrl    = "";
                        si.DiscordPresenceKey = "";
                        si.Id        = SHA.HashPassword($"{si.Name}:{si.Id}:{si.IpAddress}");
                        si.IsSpecial = false;
                        si.Category  = "CUSTOM";

                        return(si);
                    }).ToList().ForEach(si => serverInfos.Add(si));
                }
            }

            if (File.Exists("libOfflineServer.dll"))
            {
                serverInfos.Add(new ServerInfo
                {
                    Id        = "__category-OFFLINE__",
                    Name      = "<GROUP>Offline Server",
                    IsSpecial = true
                });

                serverInfos.Add(new ServerInfo
                {
                    Name               = "Offline Built-In Server",
                    Category           = "OFFLINE",
                    DiscordPresenceKey = "",
                    IsSpecial          = false,
                    DistributionUrl    = "",
                    IpAddress          = "http://localhost:4416/sbrw/Engine.svc",
                    Id = "OFFLINE"
                });
            }

            foreach (var serverItemGroup in serverInfos.GroupBy(s => s.Category))
            {
                if (finalItems.FindIndex(i => string.Equals(i.Name, $"<GROUP>{serverItemGroup.Key} Servers")) == -1)
                {
                    finalItems.Add(new ServerInfo
                    {
                        Id        = $"__category-{serverItemGroup.Key}__",
                        Name      = $"<GROUP>{serverItemGroup.Key} Servers",
                        IsSpecial = true
                    });
                }
                finalItems.AddRange(serverItemGroup.ToList());
            }
        }
        public SelectServer(String windowName = "")
        {
            InitializeComponent();

            if (windowName != "")
            {
                this.Text = windowName;
            }

            //And one for keeping data about server, IP tbh
            Dictionary <int, ServerInfo> data = new Dictionary <int, ServerInfo>();

            ServerListRenderer.View          = View.Details;
            ServerListRenderer.FullRowSelect = true;

            ServerListRenderer.Columns.Add("");
            ServerListRenderer.Columns[0].Width = 1;

            ServerListRenderer.Columns.Add("Name");
            ServerListRenderer.Columns[1].Width = 220;

            ServerListRenderer.Columns.Add("Country");
            ServerListRenderer.Columns[2].Width = 80;

            ServerListRenderer.Columns.Add("Players Online");
            ServerListRenderer.Columns[3].Width     = 80;
            ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Right;

            ServerListRenderer.Columns.Add("Registered Players");
            ServerListRenderer.Columns[4].Width     = 100;
            ServerListRenderer.Columns[4].TextAlign = HorizontalAlignment.Right;

            ServerListRenderer.Columns.Add("Ping");
            ServerListRenderer.Columns[5].Width     = 55;
            ServerListRenderer.Columns[5].TextAlign = HorizontalAlignment.Right;

            //Actually accept JSON instead of old format//
            List <ServerInfo> serverInfos = new List <ServerInfo>();

            //foreach (var serverListURL in Self.serverlisturl) {
            try {
                var wc       = new WebClientWithTimeout();
                var response = wc.DownloadString(Self.serverlisturl[0]);

                try {
                    serverInfos.AddRange(JsonConvert.DeserializeObject <List <ServerInfo> >(response));
                } catch (Exception error) {
                    Log.Error("Error occurred while deserializing server list from [" + Self.serverlisturl[0] + "]: " + error.Message);
                }
            } catch (Exception error) {
                Log.Error("Error occurred while loading server list from [" + Self.serverlisturl[0] + "]: " + error.Message);
            }
            //}

            if (File.Exists("servers.json"))
            {
                var fileItems = JsonConvert.DeserializeObject <List <ServerInfo> >(File.ReadAllText("servers.json"));

                if (fileItems.Count > 0)
                {
                    fileItems.Select(si => {
                        si.DistributionUrl    = "";
                        si.DiscordPresenceKey = "";
                        si.Id        = SHA.HashPassword($"{si.Name}:{si.Id}:{si.IpAddress}");
                        si.IsSpecial = false;
                        si.Category  = "CUSTOM";

                        return(si);
                    }).ToList().ForEach(si => serverInfos.Add(si));
                }
            }

            List <ServerInfo> newFinalItems = new List <ServerInfo>();

            foreach (ServerInfo xServ in serverInfos)
            {
                if (newFinalItems.FindIndex(i => string.Equals(i.Name, xServ.Name)) == -1)
                {
                    newFinalItems.Add(xServ);
                }
            }


            foreach (var substring in newFinalItems)
            {
                try {
                    servers.Enqueue(ID + "_|||_" + substring.IpAddress + "_|||_" + substring.Name);

                    ServerListRenderer.Items.Add(new ListViewItem(
                                                     new[] {
                        ID.ToString(), substring.Name, "", "", "", "", ""
                    }
                                                     ));

                    data.Add(ID, substring);
                    ID++;
                } catch {
                }
            }

            Thread newList = new Thread(() => {
                Thread.Sleep(200);
                this.BeginInvoke((MethodInvoker) delegate {
                    while (servers.Count != 0)
                    {
                        string QueueContent    = servers.Dequeue();
                        string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None);

                        int serverid      = Convert.ToInt32(QueueContent2[0]) - 1;
                        string serverurl  = QueueContent2[1] + "/GetServerInformation";
                        string servername = QueueContent2[2];

                        try {
                            WebClientWithTimeout getdata = new WebClientWithTimeout();
                            getdata.Timeout(1000);

                            GetServerInformation content = JsonConvert.DeserializeObject <GetServerInformation>(getdata.DownloadString(serverurl));

                            if (content == null)
                            {
                                ServerListRenderer.Items[serverid].SubItems[1].Text = servername;
                                ServerListRenderer.Items[serverid].SubItems[2].Text = "N/A";
                                ServerListRenderer.Items[serverid].SubItems[3].Text = "N/A";
                                ServerListRenderer.Items[serverid].SubItems[4].Text = "---";
                            }
                            else
                            {
                                ServerListRenderer.Items[serverid].SubItems[1].Text = servername;
                                ServerListRenderer.Items[serverid].SubItems[2].Text = Self.CountryName(content.country.ToString());
                                ServerListRenderer.Items[serverid].SubItems[3].Text = content.onlineNumber.ToString();
                                ServerListRenderer.Items[serverid].SubItems[4].Text = content.numberOfRegistered.ToString();

                                //PING
                                if (!DetectLinux.LinuxDetected())
                                {
                                    Ping pingSender = new Ping();
                                    Uri StringToUri = new Uri(serverurl);
                                    pingSender.SendAsync(StringToUri.Host, 1000, new byte[1], new PingOptions(64, true), new AutoResetEvent(false));
                                    pingSender.PingCompleted += (sender3, e3) => {
                                        PingReply reply = e3.Reply;

                                        if (reply.Status == IPStatus.Success && servername != "Offline Built-In Server")
                                        {
                                            ServerListRenderer.Items[serverid].SubItems[5].Text = reply.RoundtripTime + "ms";
                                        }
                                        else
                                        {
                                            ServerListRenderer.Items[serverid].SubItems[5].Text = "---";
                                        }
                                    };
                                }
                                else
                                {
                                    ServerListRenderer.Items[serverid].SubItems[5].Text = "---";
                                }
                            }
                        } catch {
                            ServerListRenderer.Items[serverid].SubItems[1].Text = servername;
                            ServerListRenderer.Items[serverid].SubItems[3].Text = "N/A";
                            ServerListRenderer.Items[serverid].SubItems[4].Text = "N/A";
                            ServerListRenderer.Items[serverid].SubItems[5].Text = "---";
                        }


                        if (servers.Count == 0)
                        {
                            loading.Text = "";
                        }

                        Application.DoEvents();
                    }
                });
            });

            newList.IsBackground = true;
            newList.Start();

            ServerListRenderer.AllowColumnReorder   = false;
            ServerListRenderer.ColumnWidthChanging += (handler, args) => {
                args.Cancel   = true;
                args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width;
            };

            ServerListRenderer.DoubleClick += new EventHandler((handler, args) => {
                if (ServerListRenderer.SelectedItems.Count == 1)
                {
                    rememberServerInformationID.TryGetValue(ServerListRenderer.SelectedIndices[0], out ServerInfo);

                    MainScreen.ServerName = data[ServerListRenderer.SelectedIndices[0] + 1];

                    this.Close();
                }
            });
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            
            Dispatcher.Invoke<Task>(async () =>
        {
            waterfallFlow.Children.Clear();
            MaterialCircular _addUser;
            Control _currentUser;
            try
            {
                using (WebClient webClient = new WebClientWithTimeout())
                {
                    webClient.Headers.Add("User-Agent: Other");
                    var page = webClient.DownloadString(FindElement.Settings.DefaultServer ?? AppVariable.DefaultServer2);
                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(page);
                    var query = doc.DocumentNode.SelectNodes("//table[@class='table table-striped table-hover']/tbody/tr")
                .Select(r =>
                {
                    var linkNode = r.Descendants("a").Select(node => node.Attributes["href"].Value).ToArray();
                    var linkNode2 = r.SelectSingleNode("th|td");
                    return new DelegationLink()
                    {
                        Row = r.SelectSingleNode(".//td").InnerText,
                        link = FindElement.Settings.DefaultServer + linkNode.FirstOrDefault(),
                        Category = r.SelectSingleNode(".//td[2]").InnerText,
                        Title = r.SelectSingleNode(".//td[3]").InnerText,
                        Date = r.SelectSingleNode(".//td[4]").InnerText,
                        Type = r.SelectSingleNode(".//td[5]").InnerText,
                        SubType = r.SelectSingleNode(".//td[6]").InnerText
                    };
                }
                ).ToList();
                    var parsedValues = query.Take(Limited ? 20 : query.Count).ToList();
                    myClass = parsedValues;
                    prgUpdate.Maximum = parsedValues.Count;

                    foreach (var item in parsedValues)
                    {
                        if (!Permission)
                            return;

                        await Task.Delay(10);
                        prgUpdate.Value += 1;
                        prgUpdate.Hint = string.Format("{0}%", ((prgUpdate.Value * 100) / parsedValues.Count).ToString("0"));
                        _addUser = new MaterialCircular(item.Row, item.Title, item.Category, item.Type, item.SubType, item.Date, item.link);
                        _currentUser = _addUser;
                        waterfallFlow.Children.Add(_currentUser);
                        waterfallFlow.Refresh();
                    }
                    if (prgUpdate.Hint == "100%")
                    {
                        Permission = false;
                        txtStop.Text = "دریافت";
                        Style style = this.FindResource("WorkButtonGreen") as Style;
                        btnStop.Style = style;
                        img.Source = new BitmapImage(new Uri("pack://application:,,,/MoalemYar;component/Resources/start.png", UriKind.Absolute));
                        txtSearch.IsEnabled = true;
                    }
                }
            }
            catch (WebException)
            {
                MainWindow.main.ShowRecivedCircularNotification(false);
            }
        }, DispatcherPriority.ContextIdle);
        }
        XmlNodeList getInfAboutAcc(string login, string encryptPass)
        {
            string serverLoginResponse = "";

            try
            {
                WebClient wc = new WebClientWithTimeout();
                wc.Headers.Add("user-agent", "World Evolved Launcher");
                serverLoginResponse = wc.DownloadString(serverIP + "/User/authenticateUser?email=" + login + "&password="******"error5"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Error); break;

                    case 6: MessageBox.Show(getStrFromResource("error6"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Error); break;

                    case 7: MessageBox.Show(getStrFromResource("error7"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Error); break;

                    case 10: MessageBox.Show(getStrFromResource("error10"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Error); break;

                    case 13: MessageBox.Show(getStrFromResource("error13"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Error); break;

                    case 410: MessageBox.Show(getStrFromResource("error500"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Error); break;

                    case 500:       //MessageBox.Show("Внутренняя ошибка сервера");
                        using (StreamReader sr = new StreamReader(serverReply.GetResponseStream()))
                        {
                            serverLoginResponse = sr.ReadToEnd();
                        }
                        break;

                    default: MessageBox.Show(getStrFromResource("anotherError") + (int)serverReply.StatusCode, getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Error); break;
                    }
                }
                else
                {
                    serverLoginResponse = ex.Message;
                }
            }
            if (string.IsNullOrEmpty(serverLoginResponse))
            {
                MessageBox.Show(getStrFromResource("offline"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Warning);
                Process.GetCurrentProcess().Kill();
            }

            XmlDocument SBRW_XML = new XmlDocument();

            try
            {
                SBRW_XML.LoadXml(serverLoginResponse);
            }
            catch
            {
                MessageBox.Show(getStrFromResource("offlineOrErrorInternet"), getStrFromResource("WE"), MessageBoxButton.OK, MessageBoxImage.Warning);
                Process.GetCurrentProcess().Kill();
            }

            var nodes = SBRW_XML.SelectNodes("LoginStatusVO");

            return(nodes);
        }
Exemple #24
0
        public static void Login(String email, String password)
        {
            try
            {
                WebClientWithTimeout wc = new WebClientWithTimeout();
                var buildUrl            = Tokens.IPAddress + "/User/authenticateUser?email=" + email + "&password="******"<LoginStatusVO><UserId/><LoginToken/><Description>Failed to get reply from server. Please retry.</Description></LoginStatusVO>";
                }
                else
                {
                    using (var sr = new StreamReader(serverReply.GetResponseStream()))
                    {
                        _errorcode          = (int)serverReply.StatusCode;
                        serverLoginResponse = sr.ReadToEnd();
                    }
                }
            }

            if (string.IsNullOrEmpty(serverLoginResponse))
            {
                Tokens.Error = "Server seems to be offline.";
            }
            else
            {
                try
                {
                    var sbrwXml = new XmlDocument();
                    sbrwXml.LoadXml(serverLoginResponse);

                    XmlNode extraNode;
                    XmlNode loginTokenNode;
                    XmlNode userIdNode;
                    var     msgBoxInfo = "";

                    loginTokenNode = sbrwXml.SelectSingleNode("LoginStatusVO/LoginToken");
                    userIdNode     = sbrwXml.SelectSingleNode("LoginStatusVO/UserId");

                    if (sbrwXml.SelectSingleNode("LoginStatusVO/Ban") == null)
                    {
                        if (sbrwXml.SelectSingleNode("LoginStatusVO/Description") == null)
                        {
                            extraNode = sbrwXml.SelectSingleNode("html/body");
                        }
                        else
                        {
                            extraNode = sbrwXml.SelectSingleNode("LoginStatusVO/Description");
                        }
                    }
                    else
                    {
                        extraNode = sbrwXml.SelectSingleNode("LoginStatusVO/Ban");
                    }

                    if (!string.IsNullOrEmpty(extraNode.InnerText))
                    {
                        if (extraNode.SelectSingleNode("Expires") != null || extraNode.SelectSingleNode("Reason") != null)
                        {
                            msgBoxInfo = string.Format("You got banned on {0}.", Tokens.ServerName) + "\n";

                            if (extraNode.SelectSingleNode("Reason") != null)
                            {
                                msgBoxInfo += string.Format("Reason: {0}", extraNode.SelectSingleNode("Reason").InnerText);
                            }
                            else
                            {
                                msgBoxInfo += "Reason: unknown";
                            }

                            if (extraNode.SelectSingleNode("Expires") != null)
                            {
                                msgBoxInfo += "\n" + string.Format("Ban expires: {0}", extraNode.SelectSingleNode("Expires").InnerText);
                            }
                            else
                            {
                                msgBoxInfo += "\n" + "Banned forever.";
                            }
                        }
                        else
                        {
                            if (extraNode.InnerText == "Please use MeTonaTOR's launcher. Or, are you tampering?")
                            {
                                msgBoxInfo = "Launcher tampering detected. Please use original build.";
                            }
                            else
                            {
                                if (sbrwXml.SelectSingleNode("html/body") == null)
                                {
                                    if (extraNode.InnerText == "LOGIN ERROR")
                                    {
                                        msgBoxInfo = "Invalid e-mail or password.";
                                    }
                                    else if (string.IsNullOrEmpty(msgBoxInfo))
                                    {
                                        msgBoxInfo = extraNode.InnerText;
                                    }
                                }
                                else
                                {
                                    msgBoxInfo = "ERROR " + _errorcode + ": " + extraNode.InnerText;
                                }
                            }
                        }

                        Tokens.Error = msgBoxInfo;
                    }
                    else
                    {
                        Tokens.UserId     = userIdNode.InnerText;
                        Tokens.LoginToken = loginTokenNode.InnerText;

                        if (sbrwXml.SelectSingleNode("LoginStatusVO/Warning") != null)
                        {
                            Tokens.Warning = sbrwXml.SelectSingleNode("LoginStatusVO/Warning").InnerText;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Tokens.Error = "An error occured: " + ex.Message;
                }
            }
        }
 public string GetRequest(Uri uri, int timeoutMilliseconds)
 {
     using (var client = new WebClientWithTimeout(timeoutMilliseconds))
     {
         return client.DownloadString(uri);
     }
 }
        private void okButton_Click(object sender, EventArgs e)
        {
            bool success = true;

            error.Visible = false;
            this.Refresh();

            String wellFormattedURL = "";

            if (String.IsNullOrEmpty(serverAddress.Text))
            {
                drawErrorAroundTextBox(serverAddress);
                success = false;
            }

            if (String.IsNullOrEmpty(serverName.Text))
            {
                drawErrorAroundTextBox(serverName);
                success = false;
            }

            Uri  uriResult;
            bool result = Uri.TryCreate(serverAddress.Text, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

            if (!result)
            {
                drawErrorAroundTextBox(serverAddress);
                success = false;
            }
            else
            {
                Uri      parsedServerAddress = new Uri(serverAddress.Text);
                string[] splitted            = parsedServerAddress.AbsolutePath.Split('/');
                if (splitted.Length == 3 || splitted.Length == 4)
                {
                    if (String.IsNullOrEmpty(splitted[1]))
                    {
                        splitted[1] = "soapbox-race-core";
                    }

                    if (String.IsNullOrEmpty(splitted[2]))
                    {
                        splitted[2] = "Engine.svc";
                    }

                    if (parsedServerAddress.Port == 80)
                    {
                        wellFormattedURL = parsedServerAddress.Scheme + "://" + parsedServerAddress.Host + "/" + splitted[1] + "/" + splitted[2];
                    }
                    else
                    {
                        wellFormattedURL = parsedServerAddress.Scheme + "://" + parsedServerAddress.Host + ":" + parsedServerAddress.Port + "/" + splitted[1] + "/" + splitted[2];
                    }
                }
                else
                {
                    if (parsedServerAddress.Port == 80)
                    {
                        wellFormattedURL = parsedServerAddress.Scheme + "://" + parsedServerAddress.Host + "/soapbox-race-core/Engine.svc";
                    }
                    else
                    {
                        wellFormattedURL = parsedServerAddress.Scheme + "://" + parsedServerAddress.Host + ":" + parsedServerAddress.Port + "/soapbox-race-core/Engine.svc";
                    }
                }
            }

            cancelButton.Enabled  = false;
            okButton.Enabled      = false;
            serverAddress.Enabled = false;
            serverName.Enabled    = false;

            try {
                var    client              = new WebClientWithTimeout();
                Uri    StringToUri         = new Uri(wellFormattedURL + "/GetServerInformation");
                String serverLoginResponse = client.DownloadString(StringToUri);

                GetServerInformation json = JsonConvert.DeserializeObject <GetServerInformation>(serverLoginResponse);

                if (String.IsNullOrEmpty(json.serverName))
                {
                    drawErrorAroundTextBox(serverAddress);
                    success = false;
                }
            } catch {
                drawErrorAroundTextBox(serverAddress);
                success = false;
            }

            cancelButton.Enabled  = true;
            okButton.Enabled      = true;
            serverAddress.Enabled = true;
            serverName.Enabled    = true;

            if (success == true)
            {
                try {
                    StreamReader sr         = new StreamReader("servers.txt");
                    String       oldcontent = sr.ReadToEnd();
                    sr.Close();

                    String addString = serverName.Text + ";" + wellFormattedURL + "\r\n";
                    File.WriteAllText("servers.txt", oldcontent + addString);
                    MessageBox.Show(null, "New server will be added on next start of launcher.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                } catch (Exception ex) {
                    MessageBox.Show(null, "Failed to add new server. " + ex.Message, "GameLauncher", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                }

                cancelButton_Click(sender, e);
            }
            else
            {
                error.Visible = true;
            }
        }
Exemple #27
0
        private void serverPick_SelectedIndexChanged(object sender, EventArgs e)
        {
            Tokens.Clear();
            actionText.Text = "Loading info...";

            try
            {
                ButtonLogin.Enabled    = true;
                ButtonRegister.Enabled = true;

                SelectedServerName  = ServerDropDownList.Text.ToString().ToUpper();
                SelectedServerIP    = new Uri(ServerDropDownList.SelectedValue.ToString()).Host;
                SelectedServerIPRaw = ServerDropDownList.SelectedValue.ToString();

                WebClientWithTimeout serverval = new WebClientWithTimeout();
                var    stringToUri             = new Uri(ServerDropDownList.SelectedValue.ToString() + "/GetServerInformation");
                String serverdata = serverval.DownloadString(stringToUri);

                result = JSON.Parse(serverdata);

                actionText.Text = "Players on server: " + result["onlineNumber"];

                try
                {
                    if (string.IsNullOrEmpty(result["modernAuthSupport"]))
                    {
                        _modernAuthSupport = false;
                    }
                    else if (result["modernAuthSupport"])
                    {
                        if (stringToUri.Scheme == "https")
                        {
                            _modernAuthSupport = true;
                        }
                        else
                        {
                            _modernAuthSupport = false;
                        }
                    }
                    else
                    {
                        _modernAuthSupport = false;
                    }
                }
                catch
                {
                    _modernAuthSupport = false;
                }

                try
                {
                    _ticketRequired = (bool)result["requireTicket"];
                }
                catch
                {
                    _ticketRequired = true; //lets assume yes, we gonna check later if ticket is empty or not.
                }
            }
            catch
            {
                ButtonLogin.Enabled    = false;
                ButtonRegister.Enabled = false;

                SelectedServerName = "Offline";
                SelectedServerIP   = "http://localhost";

                actionText.Text = "Server is offline.";
            }

            ticketBox.Enabled = _ticketRequired;
        }
Exemple #28
0
        public SelectServer(String windowName = "")
        {
            InitializeComponent();

            if (windowName != "")
            {
                this.Text = windowName;
            }

            //And one for keeping data about server, IP tbh
            Dictionary <int, ServerInfo> data = new Dictionary <int, ServerInfo>();

            ServerListRenderer.View          = View.Details;
            ServerListRenderer.FullRowSelect = true;

            ServerListRenderer.Columns.Add("Name");
            ServerListRenderer.Columns[0].Width = 285;

            ServerListRenderer.Columns.Add("Country");
            ServerListRenderer.Columns[1].Width = 80;

            ServerListRenderer.Columns.Add("Players Online");
            ServerListRenderer.Columns[2].Width     = 80;
            ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Right;

            ServerListRenderer.Columns.Add("Registered Players");
            ServerListRenderer.Columns[3].Width     = 100;
            ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Right;

            //Actually accept JSON instead of old format//
            List <ServerInfo> serverInfos = new List <ServerInfo>();

            foreach (var serverListURL in Self.serverlisturl)
            {
                try {
                    var wc       = new WebClientWithTimeout();
                    var response = wc.DownloadString(serverListURL);

                    try {
                        serverInfos.AddRange(JsonConvert.DeserializeObject <List <ServerInfo> >(response));
                    } catch (Exception error) {
                        Log.Error("Error occurred while deserializing server list from [" + serverListURL + "]: " + error.Message);
                    }
                } catch (Exception error) {
                    Log.Error("Error occurred while loading server list from [" + serverListURL + "]: " + error.Message);
                }
            }

            List <ServerInfo> newFinalItems = new List <ServerInfo>();

            foreach (ServerInfo xServ in serverInfos)
            {
                if (newFinalItems.FindIndex(i => string.Equals(i.Name, xServ.Name)) == -1)
                {
                    newFinalItems.Add(xServ);
                }
            }

            foreach (var substring in newFinalItems)
            {
                try {
                    servers.Enqueue(ID + "_|||_" + substring.IpAddress + "_|||_" + substring.Name);

                    ServerListRenderer.Items.Add(new ListViewItem(
                                                     new[] {
                        "", "", "", "", ""
                    }
                                                     ));

                    data.Add(ID, substring);
                    ID++;
                } catch {
                }
            }

            Thread newList = new Thread(() => {
                Thread.Sleep(200);
                this.BeginInvoke((MethodInvoker) delegate {
                    while (servers.Count != 0)
                    {
                        string QueueContent    = servers.Dequeue();
                        string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None);

                        int serverid      = Convert.ToInt32(QueueContent2[0]) - 1;
                        string serverurl  = QueueContent2[1] + "/GetServerInformation";
                        string servername = QueueContent2[2];

                        try {
                            WebClientWithTimeout getdata = new WebClientWithTimeout();
                            getdata.Timeout(1000);

                            GetServerInformation content = JsonConvert.DeserializeObject <GetServerInformation>(getdata.DownloadString(serverurl));

                            if (content == null)
                            {
                                ServerListRenderer.Items[serverid].SubItems[0].Text = servername;
                                ServerListRenderer.Items[serverid].SubItems[2].Text = "N/A";
                                ServerListRenderer.Items[serverid].SubItems[3].Text = "N/A";
                            }
                            else
                            {
                                ServerListRenderer.Items[serverid].SubItems[0].Text = servername;
                                ServerListRenderer.Items[serverid].SubItems[1].Text = Self.CountryName(content.country.ToString());
                                ServerListRenderer.Items[serverid].SubItems[2].Text = content.onlineNumber.ToString();
                                ServerListRenderer.Items[serverid].SubItems[3].Text = content.numberOfRegistered.ToString();
                            }
                        } catch {
                            ServerListRenderer.Items[serverid].SubItems[0].Text = servername;
                            ServerListRenderer.Items[serverid].SubItems[2].Text = "N/A";
                            ServerListRenderer.Items[serverid].SubItems[3].Text = "N/A";
                        }


                        if (servers.Count == 0)
                        {
                            loading.Text = "";
                        }

                        Application.DoEvents();
                    }
                });
            });

            newList.IsBackground = true;
            newList.Start();

            ServerListRenderer.AllowColumnReorder   = false;
            ServerListRenderer.ColumnWidthChanging += (handler, args) => {
                args.Cancel   = true;
                args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width;
            };

            ServerListRenderer.DoubleClick += new EventHandler((handler, args) => {
                if (ServerListRenderer.SelectedItems.Count == 1)
                {
                    rememberServerInformationID.TryGetValue(ServerListRenderer.SelectedIndices[0], out ServerInfo);

                    MainScreen.ServerName = data[ServerListRenderer.SelectedIndices[0] + 1];

                    this.Close();
                }
            });
        }
        private void okButton_Click(object sender, EventArgs e)
        {
            if (!File.Exists("servers.json"))
            {
                File.Create("servers.json");
            }

            bool success = true;

            error.Visible = false;
            this.Refresh();

            String wellFormattedURL = "";

            if (IsNullOrEmpty(serverAddress.Text))
            {
                drawErrorAroundTextBox(serverAddress);
                success = false;
            }

            if (IsNullOrEmpty(serverName.Text))
            {
                drawErrorAroundTextBox(serverName);
                success = false;
            }

            Uri  uriResult;
            bool result = Uri.TryCreate(serverAddress.Text, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

            if (!result)
            {
                drawErrorAroundTextBox(serverAddress);
                success = false;
            }
            else
            {
                wellFormattedURL = uriResult.ToString();
            }

            cancelButton.Enabled  = false;
            okButton.Enabled      = false;
            serverAddress.Enabled = false;
            serverName.Enabled    = false;

            try {
                var client              = new WebClientWithTimeout();
                Uri StringToUri         = new Uri(wellFormattedURL + "/GetServerInformation");
                var serverLoginResponse = client.DownloadString(StringToUri);

                GetServerInformation json = JsonConvert.DeserializeObject <GetServerInformation>(serverLoginResponse);

                if (IsNullOrEmpty(json.serverName))
                {
                    drawErrorAroundTextBox(serverAddress);
                    success = false;
                }
            } catch {
                drawErrorAroundTextBox(serverAddress);
                success = false;
            }

            cancelButton.Enabled  = true;
            okButton.Enabled      = true;
            serverAddress.Enabled = true;
            serverName.Enabled    = true;

            if (success == true)
            {
                try {
                    StreamReader sr         = new StreamReader("servers.json");
                    String       oldcontent = sr.ReadToEnd();
                    sr.Close();

                    if (IsNullOrWhiteSpace(oldcontent))
                    {
                        oldcontent = "[]";
                    }

                    var servers = JsonConvert.DeserializeObject <List <ServerInfo> >(oldcontent);

                    servers.Add(new ServerInfo
                    {
                        Name      = serverName.Text,
                        IpAddress = wellFormattedURL,
                        IsSpecial = false,
                        Id        = SHA.HashPassword(uriResult.Host)
                    });

                    File.WriteAllText("servers.json", JsonConvert.SerializeObject(servers));

                    MessageBox.Show(null, "New server will be added on next start of launcher.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex) {
                    MessageBox.Show(null, "Failed to add new server. " + ex.Message, "GameLauncher", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                }

                cancelButton_Click(sender, e);
            }
            else
            {
                error.Visible = true;
            }
        }