// 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; }
private void check_updates() { String current_ver = btn_update.Text; btn_update.Refresh(); new System.Threading.Thread(() => { System.Threading.Thread.CurrentThread.IsBackground = true; try { WebClient client = new WebClientWithTimeout(); String lang_check_update = ""; if (language == "es") { lang_check_update = "https://raw.githubusercontent.com/ging/AARS/main/current_plato_saga_es.txt"; } if (language == "en") { lang_check_update = "https://raw.githubusercontent.com/ging/AARS/main/current_plato_saga_en.txt"; } Stream stream = client.OpenRead(lang_check_update); StreamReader reader = new StreamReader(stream); String content = reader.ReadToEnd(); content1 = content; } catch (Exception excpt) { try { this.Invoke(new MethodInvoker(delegate { this.Enabled = false; })); } catch { } if (language == "es") { MessageBox.Show("Hubo un error al conectar al servidor de actualizaciones." + Environment.NewLine + Environment.NewLine + excpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (language == "en") { MessageBox.Show("An error occurred conecting to update service." + Environment.NewLine + Environment.NewLine + excpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } btn_update.Invoke(new MethodInvoker(delegate { btn_update.Text = current_ver; })); this.Invoke(new MethodInvoker(delegate { this.Enabled = true; this.Activate(); })); return; } try { if (Convert.ToInt16(content1.Replace(".", String.Empty).Substring(0, 3)) > Convert.ToInt16(Application.ProductVersion.Replace(".", String.Empty))) { DialogResult a = DialogResult.None; this.Invoke(new MethodInvoker(delegate { this.Enabled = false; })); if (language == "es") { a = MessageBox.Show("Una nueva versión está disponible: " + content1.Substring(0, 5) + Environment.NewLine + content1.Substring(6, content1.Length - 6) + Environment.NewLine + Environment.NewLine + "¿Desea descargarla?", "Nueva versión disponible", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } if (language == "en") { a = MessageBox.Show("A new version was found : " + content1.Substring(0, 5) + Environment.NewLine + content1.Substring(6, content1.Length - 6) + Environment.NewLine + Environment.NewLine + "Do you want to download it?", "New version found", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } if (a == DialogResult.Yes) { update_now = true; this.Invoke(new MethodInvoker(delegate { this.Enabled = true; this.Close(); })); } else { this.Invoke(new MethodInvoker(delegate { this.Enabled = true; })); } } else { if (language == "es") { MessageBox.Show("Está usando la versión más reciente."); } if (language == "en") { MessageBox.Show("You are using the latest version."); } } } catch { if (language == "es") { MessageBox.Show("Ocurrió un error al buscar actualizaciones.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (language == "en") { MessageBox.Show("An error ocurred while obtaining updates.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } this.Invoke(new MethodInvoker(delegate { this.Enabled = true; this.Activate(); })); } }).Start(); }
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 void checkAvailability() { text.Text = "Launcher Status - Checking..."; description.Text = "Version : v" + Application.ProductVersion; status.Image = Properties.Resources.ac_unknown; text.ForeColor = Color.FromArgb(0x848484); try { WebClientWithTimeout update_data = new WebClientWithTimeout(); update_data.CancelAsync(); update_data.DownloadStringAsync(new Uri(Self.mainserver + "/update.php?version=" + Application.ProductVersion)); update_data.DownloadStringCompleted += (sender, e) => { if (description.InvokeRequired == true) { description.Invoke(new Action(delegate() { description.Visible = true; })); } else { description.Visible = true; } if (e.Cancelled) { text.Text = "Launcher Status - Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Event cancelled."; } else if (e.Error != null) { text.Text = "Launcher Status"; status.Image = Properties.Resources.ac_success; text.ForeColor = Color.FromArgb(0x9fc120); description.Text = "Version : v" + Application.ProductVersion; } else { UpdateCheckResponse updater = JsonConvert.DeserializeObject <UpdateCheckResponse>(e.Result); try { if (updater.Code == 0) { if (updater.Payload.UpdateExists == false) { if (updater.Payload.LatestVersion.CompareTo(updater.Payload.ClientVersion) >= 0) { text.Text = "Launcher Status - Updated"; status.Image = Properties.Resources.ac_success; text.ForeColor = Color.FromArgb(0x9fc120); } else { text.Text = "Launcher Status - Prerelease"; status.Image = Properties.Resources.ac_warning; text.ForeColor = Color.Yellow; } description.Text = "Version : v" + Application.ProductVersion; } else { text.Text = "Launcher Status - Available"; status.Image = Properties.Resources.ac_warning; text.ForeColor = Color.Yellow; description.Text = "New Version : " + updater.Payload.LatestVersion; Application.DoEvents(); Thread.Sleep(3000); DialogResult updateConfirm = new UpdatePopup(updater).ShowDialog(); if (updateConfirm == DialogResult.OK) { progress.Text = "DOWNLOADING GAMELAUNCHERUPDATER.EXE"; new WebClientWithTimeout().DownloadFile(new Uri(Self.fileserver + "/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe"); Process.Start(@"GameLauncherUpdater.exe", Process.GetCurrentProcess().Id.ToString()); //Let's fetch new downloader /*Properties.Settings.Default.IsRestarting = false; * Properties.Settings.Default.Save(); * * WebClientWithTimeout updateDownload = new WebClientWithTimeout(); * updateDownload.DownloadFileAsync(new Uri(updater.Payload.Update.DownloadUrl), "update.sbrw"); * updateDownload.DownloadProgressChanged += (x, y) => { * progress.Text = "DOWNLOADING UPDATE: " + y.ProgressPercentage + "%"; * }; * * updateDownload.DownloadFileCompleted += (x, y) => { * progress.Text = "READY!"; * * if (File.Exists("Update.exe")) { * Process.Start(@"Update.exe"); * } else { * Process.Start(@"https://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases/latest"); * } * * Process.GetProcessById(Process.GetCurrentProcess().Id).Kill(); * };*/ } ; } } else { text.Text = "Launcher Status - GitHub Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Version : v" + Application.ProductVersion; } } catch (Exception ex) { MessageBox.Show(ex.Message); if (text.InvokeRequired == true) //checks skip, because we only need to know if we can access ui from actual thread { text.Invoke(new Action(delegate() { text.Text = "Launcher Status - Backend Error"; text.ForeColor = Color.FromArgb(254, 0, 0); })); status.Invoke(new Action(delegate() { status.Image = Properties.Resources.ac_error; })); description.Invoke(new Action(delegate() { description.Text = "Version : v" + Application.ProductVersion; })); } else { text.Text = "Launcher Status - Backend Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Version : v" + Application.ProductVersion; } } } }; } catch { text.Text = "Launcher Status - Internal Error"; status.Image = Properties.Resources.ac_error; text.ForeColor = Color.FromArgb(254, 0, 0); description.Text = "Version : v" + Application.ProductVersion; } }
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) { 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 { 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(); } }); }
/// <param name="result">第一个元素表示是否成功;第二个元素为结果</param> private static IEnumerable GetProgramVersionByUrl(String url, ReturnTuple<Boolean, String> result) { WebClientWithTimeout webClient = new WebClientWithTimeout(); webClient.Timeout = 30 * 1000; DownloadState downloadState = new DownloadState(); webClient.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs arg) => { if (arg.Cancelled) { downloadState.cancel = true; } else if (arg.Error != null) //error occurs { downloadState.exception = arg.Error; } else { downloadState.result = arg.Result; } downloadState.done = true; }; webClient.DownloadDataAsync(new Uri(PatcherSpace.Utility.AddRandomParamToUrl(url))); while (!downloadState.done) { yield return null; } if (!downloadState.cancel && downloadState.exception == null) //success { result.value_0 = true; result.value_1 = Encoding.UTF8.GetString(downloadState.result); } else { UnityEngine.Debug.LogWarning("Failed to download version file: " + url); if (downloadState.exception != null) { UnityEngine.Debug.LogWarning(downloadState.exception.ToString()); } } }
private void RegisterButton_Click(object sender, EventArgs e) { Refresh(); List <string> registerErrors = new List <string>(); if (string.IsNullOrWhiteSpace(RegisterEmail.Text)) { registerErrors.Add("Please enter your e-mail."); RegisterEmailBorder.Image = Theming.BorderEmailError; } else if (!IsEmailValid.Validate(RegisterEmail.Text)) { registerErrors.Add("Please enter a valid e-mail address."); RegisterEmailBorder.Image = Theming.BorderEmailError; } if (string.IsNullOrWhiteSpace(RegisterTicket.Text) && _ticketRequired) { registerErrors.Add("Please enter your ticket."); RegisterTicketBorder.Image = Theming.BorderTicketError; } if (string.IsNullOrWhiteSpace(RegisterPassword.Text)) { registerErrors.Add("Please enter your password."); RegisterPasswordBorder.Image = Theming.BorderPasswordError; } if (string.IsNullOrWhiteSpace(RegisterConfirmPassword.Text)) { registerErrors.Add("Please confirm your password."); RegisterConfirmPasswordBorder.Image = Theming.BorderPasswordError; } if (RegisterConfirmPassword.Text != RegisterPassword.Text) { registerErrors.Add("Passwords don't match."); RegisterConfirmPasswordBorder.Image = Theming.BorderPasswordError; } if (!RegisterAgree.Checked) { registerErrors.Add("You have not agreed to the Terms of Service."); RegisterAgree.ForeColor = Theming.Error; } if (registerErrors.Count == 0) { bool allowReg = false; String Email; String Password; switch (Authentication.HashType(InformationCache.SelectedServerJSON.authHash ?? string.Empty)) { case AuthHash.H10: Email = RegisterEmail.Text.ToString(); Password = RegisterPassword.Text.ToString(); break; case AuthHash.H11: Email = RegisterEmail.Text.ToString(); Password = MDFive.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; case AuthHash.H12: Email = RegisterEmail.Text.ToString(); Password = SHA.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; case AuthHash.H13: Email = RegisterEmail.Text.ToString(); Password = SHATwoFiveSix.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; case AuthHash.H20: Email = MDFive.Hashes(RegisterEmail.Text.ToString()).ToLower(); Password = MDFive.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; case AuthHash.H21: Email = SHA.Hashes(RegisterEmail.Text.ToString()).ToLower(); Password = SHA.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; case AuthHash.H22: Email = SHATwoFiveSix.Hashes(RegisterEmail.Text.ToString()).ToLower(); Password = SHATwoFiveSix.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; default: Log.Error("HASH TYPE: Unknown Hash Standard was Provided"); return; } try { string[] regex = new Regex(@"([0-9A-Z]{5})([0-9A-Z]{35})").Split(Password.ToUpper()); Uri URLCall = new Uri("https://api.pwnedpasswords.com/range/" + regex[1]); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } String serverReply = null; try { serverReply = Client.DownloadString(URLCall); } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("Register", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } if (!string.IsNullOrWhiteSpace(serverReply)) { String verify = regex[2]; string[] hashes = serverReply.Split('\n'); foreach (string hash in hashes) { var splitChecks = hash.Split(':'); if (splitChecks[0] == verify) { var passwordCheckReply = MessageBox.Show(null, "Password used for registration has been breached " + Convert.ToInt32(splitChecks[1]) + " times, you should consider using a different one.\n\nAlternatively you can use the unsafe password anyway." + "\nWould you like to continue to use it?", "GameLauncher", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (passwordCheckReply == DialogResult.Yes) { allowReg = true; } else { allowReg = false; } } else { allowReg = true; } } } else { allowReg = true; } } catch { allowReg = true; } if (allowReg) { Tokens.Clear(); Tokens.IPAddress = InformationCache.SelectedServerData.IPAddress; Tokens.ServerName = ServerListUpdater.ServerName("Register"); Authentication.Client("Register", InformationCache.SelectedServerJSON.modernAuthSupport, Email, Password, _ticketRequired ? RegisterTicket.Text : null); if (!String.IsNullOrWhiteSpace(Tokens.Success)) { DialogResult Success = MessageBox.Show(null, Tokens.Success, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Warning); if (Success == DialogResult.OK) { Close(); } } else { MessageBox.Show(null, Tokens.Error, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { var message = "There were some errors while registering. Please fix them:\n\n"; foreach (var error in registerErrors) { message += "• " + error + "\n"; } MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
/* Check If Updater Exists or Requires an Update */ public static void Check() { Log.Checking("LAUNCHER UPDATER: Is Version Up to Date or not"); DiscordLauncherPresence.Status("Start Up", "Checking Launcher and Updater Release Information"); /* Update this text file if a new GameLauncherUpdater.exe has been delployed - DavidCarbon */ try { bool IsGithubOnline = false; Uri URLCall = new Uri(URLs.GitHub_Updater); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { VersionJSON = Client.DownloadString(URLCall); IsGithubOnline = true; } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } bool IsJsonValid = false; try { if (IsJSONValid.ValidJson(VersionJSON) && IsGithubOnline) { GitHubRelease GHAPI = JsonConvert.DeserializeObject <GitHubRelease>(VersionJSON); if (GHAPI.TagName != null) { Log.Info("LAUNCHER UPDATER: Setting Latest Version -> " + GHAPI.TagName); LatestUpdaterBuildVersion = GHAPI.TagName; IsJsonValid = true; } Log.Info("LAUNCHER UPDATER: Latest Version -> " + LatestUpdaterBuildVersion); if (GHAPI != null) { GHAPI = null; } } else { Log.Warning("LAUNCHER UPDATER: Received Invalid JSON Data"); } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER", null, Error, null, true); } if (!IsGithubOnline || !IsJsonValid) { Log.Info("LAUNCHER UPDATER: Fail Safe Latest Version -> " + LatestUpdaterBuildVersion); } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER", null, Error, null, true); } finally { if (VersionJSON != null) { VersionJSON = null; } } /* Check if File needs to be Downloaded or Require an Update */ string UpdaterPath = Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameUpdater)); if (!File.Exists(UpdaterPath)) { Log.Info("LAUNCHER UPDATER: Starting GameLauncherUpdater downloader"); try { Uri URLCall = new Uri("https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } Client.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { if (File.Exists(UpdaterPath)) { try { if (new FileInfo(UpdaterPath).Length == 0) { File.Delete(UpdaterPath); } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [EXE Error #1]", null, Error, null, true); } } }; try { Client.DownloadFile(URLCall, UpdaterPath); } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [EXE DL #1]", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [!FileExists]", null, Error, null, true); } } else if (File.Exists(UpdaterPath)) { try { var LauncherUpdaterBuild = FileVersionInfo.GetVersionInfo(UpdaterPath); var LauncherUpdaterBuildNumber = LauncherUpdaterBuild.FileVersion; var UpdaterBuildNumberResult = LauncherUpdaterBuildNumber.CompareTo(LatestUpdaterBuildVersion); Log.Build("LAUNCHER UPDATER BUILD: GameLauncherUpdater " + LauncherUpdaterBuildNumber); if (UpdaterBuildNumberResult < 0) { Log.Info("LAUNCHER UPDATER: " + UpdaterBuildNumberResult + " Builds behind latest Updater!"); } else { Log.Info("LAUNCHER UPDATER: Latest GameLauncherUpdater!"); } if (UpdaterBuildNumberResult < 0) { Log.Info("LAUNCHER UPDATER: Downloading New " + Locations.NameUpdater); File.Delete(Locations.NameUpdater); Uri URLCall = new Uri("https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } Client.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { if (File.Exists(UpdaterPath)) { try { if (new FileInfo(UpdaterPath).Length == 0) { File.Delete(UpdaterPath); } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [EXE Error #2]", null, Error, null, true); } } }; try { Client.DownloadFile(URLCall, Locations.NameUpdater); } catch (WebException Error) { APIChecker.StatusCodes( "https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe", Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [EXE DL #2]", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [FileExists]", null, Error, null, true); } } Log.Completed("LAUNCHER UPDATER: Done"); Log.Info("LAUNCHER UPDATE: Moved to Function"); /* (Start Process) Check Latest Launcher Version */ LauncherUpdateCheck.Latest(); }
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); } }
/// <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)))); }
/// <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")))); }
/// <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")))); }
public static void Check() { if (!UnixOS.Detected()) { Log.Checking("REDISTRIBUTABLE: Is Installed or Not"); DiscordLauncherPresence.Status("Start Up", "Checking Redistributable Package Visual Code 2015 to 2019"); if (!RedistributablePackage.IsInstalled(RedistributablePackageVersion.VC2015to2019x86)) { if (MessageBox.Show(Translations.Database("Redistributable_VC_32") + "\n\n" + Translations.Database("Redistributable_VC_P2") + "\n\n" + Translations.Database("Redistributable_VC_P3") + "\n\n" + Translations.Database("Redistributable_VC_P4"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { try { Uri URLCall = new Uri("https://aka.ms/vs/16/release/VC_redist.x86.exe"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient(); if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout(); } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { Client.DownloadFile(URLCall, "VC_redist.x86.exe"); } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE", null, Error, null, true); } if (File.Exists("VC_redist.x86.exe")) { try { var proc = Process.Start(new ProcessStartInfo { Verb = "runas", Arguments = "/quiet", FileName = "VC_redist.x86.exe" }); proc.WaitForExit((int)TimeSpan.FromMinutes(10).TotalMilliseconds); if (proc == null) { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P6"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (proc != null) { if (!proc.HasExited) { if (proc.Responding) { proc.CloseMainWindow(); } else { proc.Kill(); ErrorFree = false; } } if (proc.ExitCode != 0) { ErrorFree = false; Log.Error("REDISTRIBUTABLE INSTALLER [EXIT CODE]: " + proc.ExitCode.ToString() + " HEX: (0x" + proc.ExitCode.ToString("X") + ")"); MessageBox.Show(Translations.Database("Redistributable_VC_P7") + " " + proc.ExitCode.ToString() + " (0x" + proc.ExitCode.ToString("X") + ")" + "\n" + Translations.Database("Redistributable_VC_P8"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } proc.Close(); } } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE x86 Process", null, Error, null, true); ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P9"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P10"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P8"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { Log.Info("REDISTRIBUTABLE: 32-bit 2015-2019 VC++ Redistributable Package is Installed"); } if (Environment.Is64BitOperatingSystem) { if (!RedistributablePackage.IsInstalled(RedistributablePackageVersion.VC2015to2019x64)) { if (MessageBox.Show(Translations.Database("Redistributable_VC_64") + "\n\n" + Translations.Database("Redistributable_VC_P2") + "\n\n" + Translations.Database("Redistributable_VC_P3") + "\n\n" + Translations.Database("Redistributable_VC_P4"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { try { Uri URLCall = new Uri("https://aka.ms/vs/16/release/VC_redist.x64.exe"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient(); if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout(); } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { Client.DownloadFile(URLCall, "VC_redist.x64.exe"); } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE x64", null, Error, null, true); } if (File.Exists("VC_redist.x64.exe")) { try { var proc = Process.Start(new ProcessStartInfo { Verb = "runas", Arguments = "/quiet", FileName = "VC_redist.x64.exe" }); proc.WaitForExit((int)TimeSpan.FromMinutes(10).TotalMilliseconds); if (proc == null) { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P6"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (proc != null) { if (!proc.HasExited) { if (proc.Responding) { proc.CloseMainWindow(); } else { proc.Kill(); ErrorFree = false; } } if (proc.ExitCode != 0) { ErrorFree = false; Log.Error("REDISTRIBUTABLE INSTALLER [EXIT CODE]: " + proc.ExitCode.ToString() + " HEX: (0x" + proc.ExitCode.ToString("X") + ")"); MessageBox.Show(Translations.Database("Redistributable_VC_P7") + " " + proc.ExitCode.ToString() + " (0x" + proc.ExitCode.ToString("X") + ")" + "\n" + Translations.Database("Redistributable_VC_P8"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } proc.Close(); } } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE x64 Process", null, Error, null, true); ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P9"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P10"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P8"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { Log.Info("REDISTRIBUTABLE: 64-bit 2015-2019 VC++ Redistributable Package is Installed"); } } Log.Completed("REDISTRIBUTABLE: Done"); } Log.Info("ID: Moved to Function"); /* (Start Process) */ HardwareID.FingerPrint.Get(); }
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; } }
public string PostRequest(string url, string requestBody, Dictionary<string, string> requestHeaders) { WebClientWithTimeout client = new WebClientWithTimeout(); client.Timeout = Timeout; if (requestHeaders != null) { foreach (KeyValuePair<string, string> keys in requestHeaders) client.Headers.Add(keys.Key, keys.Value); } if (url.StartsWith("https://")) { //Sending secure, ignore any SSL errors ServicePointManager.ServerCertificateValidationCallback = (obj, certificate, chain, errors) => true; } string response; //for integration tests if (url.Contains("fakesuccess")) { string successXML = "<RESULT><CODE>1</CODE><MESSAGE>Application Processed</MESSAGE><URL><![CDATA[http://whatever.com/ApplyLead?lala=TEST]]></URL></RESULT>"; response = successXML; return response; } if(url.Contains("fakerejected")) { string successXML = "<RESULT><CODE>0</CODE><MESSAGE>Rejected - no partners accepted this lead</MESSAGE><URL></URL></RESULT>"; response = successXML; return response; } response = client.UploadString(url, requestBody); return response; }
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(); }
/* Retrieve CA Information */ /// <summary> /// Retrieves the Root CA JSON file with the latest details of the Certificate /// </summary> /// <remarks>Sets the Certificate Details For Launcher Comparison</remarks> public static void Latest() { if (!UnixOS.Detected()) { Log.Checking("CERTIFICATE STORE: Is Installed or Not"); DiscordLauncherPresence.Status("Start Up", "Checking Root Certificate Authority"); try { Uri URLCall = new Uri("http://crl.carboncrew.org/RCA-Info.json"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { /* Download Up to Date Certificate Status */ RootCAJson = Client.DownloadString(URLCall); } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } if (IsJSONValid.ValidJson(RootCAJson)) { JsonRootCA API = JsonConvert.DeserializeObject <JsonRootCA>(RootCAJson); if (API.CN != null) { Log.Info("CERTIFICATE STORE: Setting Common Name -> " + API.CN); RootCACommonName = API.CN; } if (API.Subject != null) { Log.Info("CERTIFICATE STORE: Setting Subject Name -> " + API.Subject); RootCASubjectName = API.Subject; } if (API.Ids != null) { foreach (IdsModel entries in API.Ids) { if (entries.Serial != null) { Log.Info("CERTIFICATE STORE: Setting Serial Number -> " + entries.Serial); RootCASerial = entries.Serial; } } } if (API.File != null) { foreach (FileModel entries in API.File) { if (entries.Name != null) { Log.Info("CERTIFICATE STORE: Setting Root CA File Name -> " + entries.Name); RootCAFileName = entries.Name; } if (entries.Cer != null) { Log.Info("CERTIFICATE STORE: Setting Root CA File URL -> " + entries.Cer); RootCAFileURL = entries.Cer; } } } if (API != null) { API = null; } } else { Log.Warning("CERTIFICATE STORE: Received Invalid JSON Data"); } } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } finally { if (RootCAJson != null) { RootCAJson = null; } } /* Install Custom Root Certificate (If Default Values aren't used) */ if (RootCASerial != "7449A8EB07C997A6") { try { X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); var certificatesThumbPrint = store.Certificates.Find(X509FindType.FindByThumbprint, RootCASerial, false); for (int i = 0; i < store.Certificates.Count; i++) { if (store.Certificates[i].SerialNumber == RootCASerial) { Log.Info("CERTIFICATE STORE: Found Root CA [" + store.Certificates[i].Subject + "]"); Log.Info("CERTIFICATE STORE: Serial Number [" + store.Certificates[i].SerialNumber + "]"); IsROOTCAInstalled = true; } else if (store.Certificates[i].SerialNumber != RootCASerial && store.Certificates[i].Subject == RootCASubjectName) { Log.Info("CERTIFICATE STORE: Removing OLD Root CA [" + store.Certificates[i].Subject + "]"); Log.Info("CERTIFICATE STORE: Serial Number [" + store.Certificates[i].SerialNumber + "]"); store.Remove(store.Certificates[i]); } } store.Close(); store.Dispose(); } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } string CertSaveLocation = Strings.Encode(Path.Combine(Locations.LauncherFolder, RootCAFileName + ".cer")); try { if (!IsROOTCAInstalled) { Uri URLCall = new Uri(RootCAFileURL); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { /* Download Up to Date Certificate Status */ Client.DownloadFile(URLCall, CertSaveLocation); } catch (WebException Error) { APIChecker.StatusCodes(RootCAFileURL, Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } if (File.Exists(CertSaveLocation)) { X509Store Store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); Store.Open(OpenFlags.ReadWrite); X509Certificate2Collection collection = new X509Certificate2Collection(); X509Certificate2 cert = new X509Certificate2(CertSaveLocation); byte[] encodedCert = cert.GetRawCertData(); Log.Info("CERTIFICATE STORE: We are now installing [" + RootCACommonName + "] certificate into the Trusted Root Certificate store ..."); Store.Add(cert); Log.Info("CERTIFICATE STORE: Done! [" + RootCACommonName + "] certificate was installed successfully."); Store.Close(); Store.Dispose(); } } } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } try { if (File.Exists(CertSaveLocation)) { Log.Info("CERTIFICATE STORE: Removed [" + RootCACommonName + "] certificate from launcher folder."); File.Delete(CertSaveLocation); } } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } } else { Log.Warning("CERTIFICATE STORE: Default Information was detected. Not running additional Function Calls"); } Log.Completed("CERTIFICATE STORE: Done"); } Log.Checking("CERTIFICATE CHECK: Is Signed or Not"); try { X509Certificate certificate = null; try { Assembly assembly = Assembly.LoadFrom(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameLauncher))); Module module = assembly.GetModules().First(); certificate = module.GetSignerCertificate(); if (certificate != null) { LauncherSerial = certificate.GetSerialNumberString(); } } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE CHECK", null, Error, null, true); } finally { if (certificate != null) { certificate.Dispose(); } } } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE CHECK", null, Error, null, true); } Log.Completed("CERTIFICATE CHECK: Done"); Log.Info("VERIFIED: Moved to Function"); /* (Start Process) Check if Launcher Is Signed or Not */ IsExeVerified.Check(); }
public string GetRequest(Uri uri, int timeoutMilliseconds) { using (var client = new WebClientWithTimeout(timeoutMilliseconds)) { return client.DownloadString(uri); } }
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(); } }); }
public void BeginUpdate() { _webClient = new WebClientWithTimeout(); _webClient.DownloadStringCompleted += _DownloadStringCompletedHandler; _webClient.DownloadStringAsync(_updateInfoUri); }
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); }
private void OkButton_Click(object sender, EventArgs e) { try { if (File.Exists(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameOldServersJSON)))) { File.Move( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameOldServersJSON)), Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON))); } else if (!File.Exists( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)))) { try { File.WriteAllText( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)), "[]"); } catch (Exception Error) { LogToFileAddons.OpenLog("JSON SERVER FILE", null, Error, null, true); } } } catch (Exception Error) { LogToFileAddons.OpenLog("JSON SERVER FILE", null, Error, null, true); } Error.Visible = false; this.Refresh(); if (IsNullOrWhiteSpace(ServerAddress.Text) || IsNullOrWhiteSpace(Strings.Encode(ServerName.Text))) { if (IsNullOrWhiteSpace(ServerAddress.Text)) { Error.Text = "Fix Empty IP"; DrawErrorAroundTextBox(ServerAddress); } else { Error.Text = "Fix Empty Name"; DrawErrorAroundTextBox(ServerName); } Error.Visible = true; return; } if (Error.Visible) { Error.Visible = false; } bool CorrectFormat = Uri.TryCreate(ServerAddress.Text, UriKind.Absolute, out Uri Result) && (Result.Scheme == Uri.UriSchemeHttp || Result.Scheme == Uri.UriSchemeHttps); string FormattedURL; if (!CorrectFormat) { DrawErrorAroundTextBox(ServerAddress); return; } else { FormattedURL = Result.ToString(); } ButtonControls(false); try { string ServerInfomationJSON = Empty; try { Uri StringToUri = new Uri(FormattedURL + "/GetServerInformation"); ServicePointManager.FindServicePoint(StringToUri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { ServerInfomationJSON = Client.DownloadString(StringToUri); } catch (Exception Error) { string LogMessage = "Add Server Check Encountered an Error:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); } finally { if (Client != null) { Client.Dispose(); } } } catch (Exception Error) { string LogMessage = "Add Server Check Encountered an Error:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); } if (IsNullOrWhiteSpace(ServerInfomationJSON)) { ButtonControls(true); return; } else if (!IsJSONValid.ValidJson(ServerInfomationJSON)) { Error.Text = "Unstable Connection"; DrawErrorAroundTextBox(ServerAddress); Error.Visible = true; ButtonControls(true); ServerInfomationJSON = null; return; } else { GetServerInformation ServerInformationData = null; try { ServerInformationData = JsonConvert.DeserializeObject <GetServerInformation>(ServerInfomationJSON); } catch (Exception Error) { string LogMessage = "Add Server Get Information Encountered an Error:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); } if (ServerInformationData == null) { ButtonControls(true); ServerInfomationJSON = null; return; } else { string ServerID = Empty; Uri newModNetUri = new Uri(FormattedURL + "/Modding/GetModInfo"); ServicePointManager.FindServicePoint(newModNetUri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { GetModInfo ServerGetInfo = JsonConvert.DeserializeObject <GetModInfo>(Client.DownloadString(newModNetUri)); ServerID = IsNullOrWhiteSpace(ServerGetInfo.serverID) ? Result.Host : ServerGetInfo.serverID; } catch (Exception Error) { LogToFileAddons.OpenLog("Add Server", null, Error, null, true); ServerID = Result.Host; } finally { if (Client != null) { Client.Dispose(); } } try { StreamReader sr = new StreamReader(Locations.LauncherCustomServers); String oldcontent = sr.ReadToEnd(); sr.Close(); if (IsNullOrWhiteSpace(oldcontent)) { oldcontent = "[]"; } var Servers = JsonConvert.DeserializeObject <List <ServerList> >(oldcontent); Servers.Add(new ServerList { Name = Strings.Encode(ServerName.Text), IPAddress = FormattedURL, IsSpecial = false, ID = ServerID, Category = IsNullOrWhiteSpace(Strings.Encode(ServerCategory.Text)) ? "Custom" : Strings.Encode(ServerCategory.Text) }); File.WriteAllText(Locations.LauncherCustomServers, JsonConvert.SerializeObject(Servers)); MessageBox.Show(null, "The New server will be added on the next start of the Launcher.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception Error) { string LogMessage = "Failed to Add New Server:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); ButtonControls(true); return; } finally { if (ServerID != null) { ServerID = null; } if (ServerInfomationJSON != null) { ServerInfomationJSON = null; } } CancelButton_Click(sender, e); } } } catch { DrawErrorAroundTextBox(ServerAddress); ButtonControls(true); } }
private static void ValidateUrl(string url, string title, string genre) { Console.WriteLine("Trying url: {0}", url); try { Uri uri = new Uri(url); string hostName = uri.DnsSafeHost; //if (!QueryDnsWithTimeout(hostName, 300)) //{ // Console.WriteLine("\t -> Url: {0} is not valid (DNS error)", url); // return; //} List<String> urlsToCkeck = new List<string>(); if (IsPlaylist(url)) { string fileName = Path.GetFileName(uri.LocalPath); string tempFile = @"c:\temp.pls"; using (WebClientWithTimeout wc = new WebClientWithTimeout()) { wc.Timeout = 500; wc.Proxy = AppSettings.GetWebProxy(); wc.DownloadFile(uri, tempFile); } if (File.Exists(tempFile)) { Playlist p = new Playlist(); p.LoadPlaylist(tempFile); File.Delete(tempFile); foreach (PlaylistItem item in p.AllItems) { urlsToCkeck.Add(item.Path); } } } else { urlsToCkeck.Add(url); } foreach(string url2 in urlsToCkeck) { //if (!QueryDnsWithTimeout(url2, 300)) // continue; ShoutcastStream ss = new ShoutcastStream(url2, 500); if (ss.Connected) { RadioStation rs = new RadioStation { Genre = genre, Title = title, Url = url2 }; data.RadioStations.Add(rs); Console.WriteLine("\t -> Added radio station: {0}", url2); ss.Close(); ss.Dispose(); ss = null; } } } catch(Exception ex) { Console.WriteLine("\t ->" + ex.Message); } Console.WriteLine("\t -> Url: {0} is not valid", url); }
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; }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: EdcbSchUploader <user> <pass> [epgurl] [slot] [upload_url]"); Environment.Exit(2); } // サービス名としょぼかる放送局名の対応ファイル"SyoboiCh.txt"があれば読み込む var chMap = new Dictionary <string, string>(); try { string[] chList = File.ReadAllText( Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "SyoboiCh.txt"), Encoding.GetEncoding(932) ).Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string ch in chList) { string[] chSplit = ch.Split(new char[] { '\t' }); if (chSplit.Length >= 2 && chSplit[0].StartsWith(";") == false) { chMap[chSplit[0]] = chSplit[1]; } } } catch { } // EpgTimerSrvから予約情報を取得 var cmd = new CtrlCmdUtil(); var rl = new List <ReserveData>(); var tl = new List <TunerReserveInfo>(); if (cmd.SendEnumReserve(ref rl) != ErrCode.CMD_SUCCESS || cmd.SendEnumTunerReserve(ref tl) != ErrCode.CMD_SUCCESS) { Console.WriteLine("Failed to communicate with EpgTimerSrv."); Environment.Exit(1); } string data = ""; int dataCount = 0; foreach (ReserveData r in rl) { string tuner = null; foreach (TunerReserveInfo tr in tl) { if (tr.reserveList.Contains(r.ReserveID)) { // T+{BonDriver番号(上2桁)}+{チューナ番号(下2桁)},チューナ不足はT9999 tuner = "T" + ("" + (10000 + Math.Min(tr.tunerID / 65536, 99) * 100 + Math.Min(tr.tunerID % 65536, 99))).Substring(1); break; } } if (tuner != null && r.RecSetting.RecMode <= 3 && r.RecSetting.Priority >= UPLOAD_REC_PRIORITY) { // "最大200行" if (dataCount++ >= 200) { break; } else { // "開始時間 終了時間 デバイス名 番組名 放送局名 サブタイトル オフセット XID" string title = r.Title.Replace("\t", "").Replace("\r", "").Replace("\n", ""); data += "" + (r.StartTime.ToUniversalTime() - (new DateTime(1970, 1, 1))).TotalSeconds + "\t" + (r.StartTime.ToUniversalTime().AddSeconds(r.DurationSecond) - (new DateTime(1970, 1, 1))).TotalSeconds + "\t" + tuner + "\t" + (title.Length > UPLOAD_TITLE_MAXLEN ? title.Substring(0, UPLOAD_TITLE_MAXLEN - 1) + "…" : title) + "\t" + (chMap.ContainsKey(r.StationName) ? chMap[r.StationName] : r.StationName) + "\t\t0\t" + r.ReserveID + "\n"; } } } // 以前の内容と同じなら送信しない string lastPath = Path.ChangeExtension(Assembly.GetEntryAssembly().Location, "last"); try { if (File.ReadAllText(lastPath) == data.Replace("\n", "\r\n")) { Console.WriteLine("Not modified, nothing to do."); Environment.Exit(0); } } catch { } // しょぼかるのPOSTは"Expect: 100-Continue"に対応してないっぽい ServicePointManager.Expect100Continue = false; // 予約情報をサーバに送信 using (var wc = new WebClientWithTimeout()) { // WebClientはデフォルトでIEのプロキシ設定に従う(wc.Proxy = WebRequest.DefaultWebProxy) // 認証プロキシなど必要であればwc.Proxyをここで設定すること wc.Timeout = TIMEOUT; wc.Encoding = Encoding.UTF8; wc.Credentials = new NetworkCredential(Uri.EscapeDataString(args[0]), Uri.EscapeDataString(args[1])); wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; wc.Headers[HttpRequestHeader.UserAgent] = USER_AGENT; var body = new System.Collections.Specialized.NameValueCollection(); body["slot"] = args.Length < 4 ? "0" : args[3]; body["devcolors"] = DEV_COLORS; body["epgurl"] = args.Length < 3 ? "" : args[2]; body["data"] = data; try { wc.UploadValues(args.Length < 5 ? UPLOAD_URL : args[4], body); File.WriteAllText(lastPath, data.Replace("\n", "\r\n"), Encoding.UTF8); } catch (Exception ex) { Console.WriteLine(ex.GetType().ToString() + " : " + ex.Message); Environment.Exit(1); } } Console.WriteLine("Done."); Environment.Exit(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; } } }
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs args) { try { if (WebCalls.Alternative()) { using (WebClient webClient = new WebClient()) { webClient.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.DownloadManager_DownloadDataCompleted); webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); while (true) { if (this._freeChunks <= 0) { Thread.Sleep(100); } else { lock (this._downloadQueue) { if (this._downloadQueue.Count == 0) { lock (this._workers) { this._workers.Remove((BackgroundWorker)sender); } DownloaderHandler._workerCount--; break; } } string value = null; lock (this._downloadQueue) { value = this._downloadQueue.Last.Value; this._downloadQueue.RemoveLast(); lock (this._freeChunksLock) { this._freeChunks--; } } lock (this._downloadList[value]) { if (this._downloadList[value].Status != DownloaderHandler.DownloadStatus.Canceled) { this._downloadList[value].Status = DownloaderHandler.DownloadStatus.Downloading; } } while (webClient.IsBusy) { Thread.Sleep(100); } webClient.DownloadDataAsync(new Uri(value), value); DownloaderHandler.DownloadStatus status = DownloaderHandler.DownloadStatus.Downloading; while (status == DownloaderHandler.DownloadStatus.Downloading) { status = this._downloadList[value].Status; if (status == DownloaderHandler.DownloadStatus.Canceled) { break; } Thread.Sleep(100); } if (status == DownloaderHandler.DownloadStatus.Canceled) { webClient.CancelAsync(); } lock (this._workers) { if (DownloaderHandler._workerCount > this._maxWorkers || !this._managerRunning) { this._workers.Remove((BackgroundWorker)sender); DownloaderHandler._workerCount--; break; } } } } } } else { using (WebClientWithTimeout webClient = new WebClientWithTimeout()) { webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.DownloadManager_DownloadDataCompleted); webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); while (true) { if (this._freeChunks <= 0) { Thread.Sleep(100); } else { lock (this._downloadQueue) { if (this._downloadQueue.Count == 0) { lock (this._workers) { this._workers.Remove((BackgroundWorker)sender); } DownloaderHandler._workerCount--; break; } } string value = null; lock (this._downloadQueue) { value = this._downloadQueue.Last.Value; this._downloadQueue.RemoveLast(); lock (this._freeChunksLock) { this._freeChunks--; } } lock (this._downloadList[value]) { if (this._downloadList[value].Status != DownloaderHandler.DownloadStatus.Canceled) { this._downloadList[value].Status = DownloaderHandler.DownloadStatus.Downloading; } } while (webClient.IsBusy) { Thread.Sleep(100); } webClient.DownloadDataAsync(new Uri(value), value); DownloaderHandler.DownloadStatus status = DownloaderHandler.DownloadStatus.Downloading; while (status == DownloaderHandler.DownloadStatus.Downloading) { status = this._downloadList[value].Status; if (status == DownloaderHandler.DownloadStatus.Canceled) { break; } Thread.Sleep(100); } if (status == DownloaderHandler.DownloadStatus.Canceled) { webClient.CancelAsync(); } lock (this._workers) { if (DownloaderHandler._workerCount > this._maxWorkers || !this._managerRunning) { this._workers.Remove((BackgroundWorker)sender); DownloaderHandler._workerCount--; break; } } } } } } } catch (Exception Error) { LogToFileAddons.OpenLog("CDN DOWNLOADER [Background Work DH]", null, Error, null, true); Exception exception = Error; lock (this._workers) { this._workers.Remove((BackgroundWorker)sender); DownloaderHandler._workerCount--; } } }
private void trySettings() { if (!m_SettingsDone && m_SettingsAggregator != null) { m_SettingsDone = true; m_Logger.Log(@"settings applied to Shell Window", Category.Debug, Priority.Medium); bool clickOnce = ApplicationDeployment.IsNetworkDeployed; if (!clickOnce && Settings.Default.EnableVersionChecking) { string thisVersion = ApplicationConstants.GetVersion(); string url = "http://data.daisy.org/projects/tobi/install/net-4/Tobi_NET4.application"; var webClient = new WebClientWithTimeout { UseDefaultCredentials = true, Timeout = 5 * 1000 }; // 5 seconds StreamReader streamReader = null; try { streamReader = new StreamReader(webClient.OpenRead(url), Encoding.UTF8); string xmlStr = streamReader.ReadToEnd(); //m_Logger.Log(str, Category.Info, Priority.High); if (!string.IsNullOrEmpty(xmlStr)) { int i = xmlStr.IndexOf(" version=", 20); if (i > 0) { int k = i + 10; int j = xmlStr.IndexOf("\"", k); if (j > 0 && j > i) { string latestVersion = xmlStr.Substring(k, j - k); int lastestVersionNumber = parseVersionNumber(latestVersion); int thisVersionNumber = parseVersionNumber(thisVersion); if (lastestVersionNumber > thisVersionNumber && Settings.Default.UpdateRejected != latestVersion) { bool update = askUserAppUpdate(thisVersion, latestVersion); if (update) { ExecuteShellProcess("http://daisy.org/tobi"); } else { Settings.Default.UpdateRejected = latestVersion; } } } } } } catch (Exception ex) { m_Logger.Log(@"Problem checking Tobi latest version? " + ex.Message, Category.Exception, Priority.High); //ExceptionHandler.LogException(ex); #if DEBUG Debugger.Break(); #endif // DEBUG } finally { if (streamReader != null) { streamReader.Close(); } } } } }
internal static void CheckForUpdate(object sender, EventArgs e) { try { var client = new WebClientWithTimeout(); var uri = new Uri(Self.mainserver + "/launcher/update?version=" + Application.ProductVersion); client.CancelAsync(); client.DownloadStringAsync(uri); client.DownloadStringCompleted += (sender2, e2) => { try { var json = JsonConvert.DeserializeObject <UpdateCheckResponse>(e2.Result); if (json.Code != 0) { MessageBox.Show("Launchpad update service returned an error: " + json.Code); return; } if (json.Payload.UpdateExists) { var settingFile = new IniFile("Settings.ini"); if (settingFile.Read("IgnoreUpdateVersion") != json.Payload.LatestVersion) { var dia = new TaskDialog { Caption = "Update", InstructionText = "An update is available!", DetailsExpanded = true, Icon = TaskDialogStandardIcon.Information, DetailsCollapsedLabel = "Show Changelog", Text = "An update is available. Do you want to download it?\nYour version: " + Application.ProductVersion + "\nUpdated version: " + json.Payload.LatestVersion, DetailsExpandedText = new WebClientWithTimeout().DownloadString(Self.mainserver + "/launcher/changelog"), ExpansionMode = TaskDialogExpandedDetailsLocation.ExpandFooter }; var update = new TaskDialogCommandLink("update", "Yes", "Launcher will be updated to " + json.Payload.LatestVersion + "."); var cancel = new TaskDialogCommandLink("cancel", "No", "Launcher will ask you to update on the next launch."); var skipupdate = new TaskDialogCommandLink("skipupdate", "Ignore", "This update will be skipped. A new prompt will apear as soon as a newer update is available."); update.UseElevationIcon = true; skipupdate.Click += (sender3, e3) => { settingFile.Write("IgnoreUpdateVersion", json.Payload.LatestVersion); dia.Close(); }; cancel.Click += (sender3, e3) => { dia.Close(); }; update.Click += (sender3, e3) => { if (File.Exists("GameLauncherUpdater.exe")) { Process.Start(@"GameLauncherUpdater.exe", Process.GetCurrentProcess().Id.ToString()); } else { Process.Start(@"https://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases/latest"); } dia.Close(); }; dia.Controls.Add(update); dia.Controls.Add(cancel); dia.Controls.Add(skipupdate); dia.Show(); //new UpdatePopup(json.github_build).Show(); } } else { try { if (((Form)sender).Name == "mainScreen") { } } catch { MessageBox.Show("Your launcher is up-to-date"); } } } catch { try { if (((Form)sender).Name == "mainScreen") { } } catch { MessageBox.Show("Failed to check for update!"); } } }; } catch { MessageBox.Show("Failed to check for update!"); } }
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 (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.json"); String oldcontent = sr.ReadToEnd(); sr.Close(); if (string.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) }); //String addString = serverName.Text + ";" + wellFormattedURL + "\r\n"; //File.WriteAllText("servers.txt", oldcontent + addString); 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; } }
public void usageReport(IShellView shellView) { string uid = ""; if (!Tobi.Settings.Default.EnableAnonymousUsageReport_UserConfirm) { Tobi.Settings.Default.EnableAnonymousUsageReport = false; // reset Tobi.Settings.Default.EnableAnonymousUsageReport_UserConfirm = true; string defaultSettingValue = (string)Settings.Default.Properties["UserId"].DefaultValue; string settingValue = Tobi.Settings.Default.UserId; if (!String.IsNullOrEmpty(settingValue)) { settingValue = settingValue.Trim(); if (settingValue.Equals(defaultSettingValue, StringComparison.OrdinalIgnoreCase)) { settingValue = ""; // can be null also } } // NEED USER CONFIRM (explicit consent, opt-in) if (true) // String.IsNullOrEmpty(settingValue) || settingValue.Equals(defaultSettingValue)) { // Settings.Default.UserId_DoNotAskAgain ? "" : String userid = askUserId(shellView, Tobi_Lang.UserId_title, Tobi_Lang.UserId_message, Tobi_Lang.UserId_details, Tobi_Lang.UserId_consent, settingValue); if (!String.IsNullOrEmpty(userid)) { userid = userid.Trim(); } if (String.IsNullOrEmpty(userid)) { Tobi.Settings.Default.UserId = defaultSettingValue; uid = ""; } else { Tobi.Settings.Default.UserId = userid; uid = userid; if (userid.Equals(defaultSettingValue, StringComparison.OrdinalIgnoreCase)) { uid = ""; } } } } //http://blogs.msdn.com/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx string url = ApplicationConstants.TOBI_ANON_USAGE_URI; url += "?version=" + Uri.EscapeDataString(ApplicationConstants.APP_VERSION); url += "&clickonce=" + (ApplicationDeployment.IsNetworkDeployed ? "true" : (Debugger.IsAttached ? "VS" : "false")); url += "&datetime=" + Uri.EscapeDataString(DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss_K", CultureInfo.InvariantCulture)); url += "&datetimeutc=" + Uri.EscapeDataString(DateTime.UtcNow.ToString("yyyy-MM-dd_HH:mm:ss_K", CultureInfo.InvariantCulture)); url += "&os=" + Uri.EscapeDataString(ApplicationConstants.OS_INFORMATION); url += "&lang=" + Thread.CurrentThread.CurrentUICulture; url += "&userid=" + Uri.EscapeDataString(uid); // THIS BREAKS PRIVACY, so we don't //string ipAddress = ""; //IPHostEntry ipHostEntry = Dns.GetHostEntry(Dns.GetHostName()); //IPAddress[] ipAddresses = ipHostEntry.AddressList; //for (int i = 0; i < ipAddresses.Length; i++) //{ // if (ipAddresses[i].AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6) // { // if (!IPAddress.IsLoopback(ipAddresses[i])) // { // ipAddress += string.Format("_{0}", ipAddresses[i]); // } // } // else // { // ipAddress += string.Format("__{0}", ipAddresses[i]); // } //} //if (!string.IsNullOrEmpty(ipAddress)) //{ // url += "&localip=" + Uri.EscapeDataString(ipAddress); //} if (Settings.Default.EnableAnonymousUsageReport && Settings.Default.EnableAnonymousUsageReport_UserConfirm) { var webClient = new WebClientWithTimeout { UseDefaultCredentials = true, Timeout = 5 * 1000 }; // 5 seconds StreamReader streamReader = null; try { streamReader = new StreamReader(webClient.OpenRead(url), Encoding.UTF8); string str = streamReader.ReadToEnd(); m_Logger.Log(str, Category.Info, Priority.High); } catch (Exception ex) { m_Logger.Log(@"Can't query Tobi anonymous usage logger !", Category.Exception, Priority.High); ExceptionHandler.LogException(ex); //#if DEBUG // Debugger.Break(); //#endif // DEBUG } finally { if (streamReader != null) { streamReader.Close(); } } } else { m_Logger.Log(@"Tobi anonymous usage logger has been DISABLED by user.", Category.Warn, Priority.High); } }
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()); } }
/// <summary> /// Form Url or Post Request to the Server for Login and Registration /// </summary> /// <remarks>Non Secure: Uses regualar URL Request. Secure: Uses Post Request</remarks> /// <returns>Receives UserId and Auth Key for Login. Sends Email and Password to Server</returns> /// <param name="ConnectionProtocol">Connection Protocol: Check AuthProtocol</param> /// <param name="Method">Form Type: "Login" or "Register"</param> public static void Client(string Method, bool Modern_Auth, String Email, String Password, String Token) { try { if (!Modern_Auth) { Uri URLCall = new Uri((Method == "Login") ? Tokens.IPAddress + "/User/authenticateUser?email=" + Email + "&password="******"/User/createUser?email=" + Email + "&password="******"&inviteTicket=" + Token : "")); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); Client.Headers["X-HWID"] = HardwareID.FingerPrint.Value(); Client.Headers["X-HiddenHWID"] = HardwareID.FingerPrint.ValueAlt(); Client.Headers["X-UserAgent"] = "GameLauncherReborn " + Application.ProductVersion + " WinForms (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"; Client.Headers["X-GameLauncherHash"] = WebHelpers.Value(); Client.Headers["X-GameLauncherCertificate"] = CertificateStore.LauncherSerial; Client.Headers["X-DiscordID"] = DiscordLauncherPresence.UserID; } try { if (Method == "Login") { LoginResponse = Client.DownloadString(URLCall); } else { LoginResponse = Client.DownloadString(URLCall); } } catch { throw; } finally { if (Client != null) { Client.Dispose(); } } } else { string ServerUrl = Tokens.IPAddress + "/User/modernAuth"; if (Method == "Register") { ServerUrl = Tokens.IPAddress + "/User/modernRegister"; } Uri SendRequest = new Uri(ServerUrl); ServicePointManager.FindServicePoint(SendRequest).ConnectionLeaseTimeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(SendRequest); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; httpWebRequest.Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { String JSON; if (Method == "Login") { JSON = new JavaScriptSerializer().Serialize(new { Email, Password, upgrade = true }); } else { JSON = new JavaScriptSerializer().Serialize(new { Email, Password, Ticket = Token }); } streamWriter.Write(JSON); } ServerResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var sr = new StreamReader(ServerResponse.GetResponseStream())) { ServerErrorCode = (int)ServerResponse.StatusCode; LoginResponse = sr.ReadToEnd(); } } } catch (WebException Error) { LogToFileAddons.OpenLog("CLIENT [LOGIN/REGISTER]", null, Error, null, true); ServerResponse = (HttpWebResponse)Error.Response; if (ServerResponse == null) { ServerErrorCode = 500; LoginResponse = Modern_Auth ? "{\"error\":\"Failed to get reply from server. Please retry.\"}" : "<LoginStatusVO><UserId>0</UserId><Description>Failed to get reply from server. Please retry.</Description></LoginStatusVO>"; } else { using (var sr = new StreamReader(ServerResponse.GetResponseStream())) { ServerErrorCode = (int)ServerResponse.StatusCode; ServerErrorResponse = Modern_Auth ? "{\"error\":\"" + ServerResponse.StatusDescription + "\"}" : null; LoginResponse = sr.ReadToEnd(); } } } if (!Modern_Auth) { if (string.IsNullOrWhiteSpace(LoginResponse)) { Tokens.Error = "Server Seems to be Offline."; } else { XmlDocument sbrwXml = new XmlDocument(); var msgBoxInfo = string.Empty; bool XMLIsErrorFree = true; try { if (EnableInsiderDeveloper.Allowed()) { Log.Info("Authentication: Received XML -> " + LoginResponse); } sbrwXml.LoadXml(LoginResponse); if (EnableInsiderDeveloper.Allowed()) { Log.Info("Authentication: Loaded XML -> " + sbrwXml.OuterXml); } } catch (Exception Error) { LogToFileAddons.OpenLog("XML LOGIN", null, Error, null, true); XMLIsErrorFree = false; msgBoxInfo = "An error occured: " + Error.Message; } if (XMLIsErrorFree == true) { if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO", "NodeOnly") == "VAILD NODE - LAUNCHER") { if (XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Ban", "InnerText") != "EMPTY VALUE - LAUNCHER") { if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO/Description", "NodeOnly") == "VAILD NODE - LAUNCHER") { msgBoxInfo += XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Description", "InnerText"); } else { msgBoxInfo = string.Format("You got banned on {0}.", Tokens.ServerName) + "\n"; if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO/Ban/Reason", "NodeOnly") != "INVALID NODE - LAUNCHER") { msgBoxInfo += "Reason: " + XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Ban/Reason", "InnerText") + "\n"; } else { msgBoxInfo += "Reason: Unknown \n"; } if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO/Ban/Expires", "NodeOnly") != "INVALID NODE - LAUNCHER") { msgBoxInfo += "Ban Expires: " + XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Ban/Expires", "InnerText"); } else { msgBoxInfo += "Banned Forever"; } } } else if (XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/UserId", "InnerText") == "0") { if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO/Description", "NodeOnly") != "ERROR NODE - LAUNCHER" && XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Description", "InnerText") != "EMPTY VALUE - LAUNCHER") { if (XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Description", "InnerText") == "LOGIN ERROR") { msgBoxInfo += "Invalid E-mail or Password"; } else { msgBoxInfo += XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Description", "InnerText"); } } else { msgBoxInfo += "ERROR " + ServerErrorCode + ": " + XMLServerCore.NodeReader(sbrwXml, "InnerText", "html/body", "InnerText"); } } if (string.IsNullOrWhiteSpace(msgBoxInfo) || msgBoxInfo == "SERVER FULL") { if (Method == "Login" && string.IsNullOrWhiteSpace(msgBoxInfo)) { Tokens.UserId = XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/UserId", "InnerText"); Tokens.LoginToken = XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/LoginToken", "InnerText"); if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO/Warning", null) == "VAILD NODE - LAUNCHER") { Tokens.Warning = XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Warning", "InnerText"); } } else if (Method == "Register") { string MessageSuccess; string MessageServerWelcome = string.Empty; if (!string.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.messageSrv)) { if (InformationCache.SelectedServerJSON.messageSrv.ToLower().Contains("welcome")) { MessageServerWelcome = InformationCache.SelectedServerJSON.messageSrv + "\n"; } else { MessageServerWelcome = "Welcome: " + InformationCache.SelectedServerJSON.messageSrv + "\n"; } } if (msgBoxInfo == "SERVER FULL") { MessageSuccess = string.Format(MessageServerWelcome + "Successfully registered on {0}. However, server is actually full, " + "therefore you cannot play it right now.", Tokens.ServerName); } else { MessageSuccess = string.Format(MessageServerWelcome + "Successfully registered on {0}. You can log in now.", Tokens.ServerName); } Tokens.Success = MessageSuccess; } else { Tokens.Error = msgBoxInfo; } } else { Tokens.Error = msgBoxInfo; } } else { Log.Error("Authentication: Unable to Read XML File Due to the Node 'LoginStatusVO' having an Error"); Tokens.Error = "Unable to Read XML File Due to the Node 'LoginStatusVO' having an Error\nERROR NODE - LAUNCHER"; } } else { Log.Error("Authentication: Unable to Read XML File -> " + msgBoxInfo); Tokens.Error = msgBoxInfo; } } } else { if (String.IsNullOrWhiteSpace(LoginResponse)) { Tokens.Error = "Server seems to be offline."; } else { ModernAuthObject ServerObjectResponse; try { ServerObjectResponse = JsonConvert.DeserializeObject <ModernAuthObject>(LoginResponse); } catch { ServerObjectResponse = JsonConvert.DeserializeObject <ModernAuthObject>(ServerErrorResponse); } if (String.IsNullOrWhiteSpace(ServerObjectResponse.Error) || ServerObjectResponse.Error == "SERVER FULL") { if (Method == "Login") { Tokens.UserId = ServerObjectResponse.UserId; Tokens.LoginToken = ServerObjectResponse.Token; if (!String.IsNullOrWhiteSpace(ServerObjectResponse.Warning)) { Tokens.Warning = ServerObjectResponse.Warning; } } else if (Method == "Register") { string MessageSuccess; string MessageServerWelcome = string.Empty; if (!string.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.messageSrv)) { if (InformationCache.SelectedServerJSON.messageSrv.ToLower().Contains("welcome")) { MessageServerWelcome = InformationCache.SelectedServerJSON.messageSrv + "\n"; } else { MessageServerWelcome = "Welcome: " + InformationCache.SelectedServerJSON.messageSrv + "\n"; } } if (ServerObjectResponse.Error == "SERVER FULL") { MessageSuccess = string.Format(MessageServerWelcome + "Successfully registered on {0}. However, server is actually full, " + "therefore you cannot play it right now.", Tokens.ServerName); } else { MessageSuccess = string.Format(MessageServerWelcome + "Successfully registered on {0}. You can log in now.", Tokens.ServerName); } Tokens.Success = MessageSuccess; } } else { Tokens.Error = ServerObjectResponse.Error; } } } }
private void SetVisuals() { /*******************************/ /* Set Font / * /*******************************/ FontFamily DejaVuSans = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf"); FontFamily DejaVuSansBold = FontWrapper.Instance.GetFontFamily("DejaVuSans-Bold.ttf"); var MainFontSize = 9f * 96f / CreateGraphics().DpiY; if (UnixOS.Detected()) { MainFontSize = 9f; } Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); ServerListRenderer.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); Loading.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); BtnAddServer.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); BtnRemoveServer.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); BtnSelectServer.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); BtnClose.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); Version.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); /********************************/ /* Set Theme Colors & Images / * /********************************/ ForeColor = Theming.WinFormTextForeColor; BackColor = Theming.WinFormTBGForeColor; Loading.ForeColor = Theming.WinFormWarningTextForeColor; Version.ForeColor = Theming.WinFormTextForeColor; ServerListRenderer.ForeColor = Theming.WinFormSecondaryTextForeColor; BtnAddServer.ForeColor = Theming.BlueForeColorButton; BtnAddServer.BackColor = Theming.BlueBackColorButton; BtnAddServer.FlatAppearance.BorderColor = Theming.BlueBorderColorButton; BtnAddServer.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton; BtnRemoveServer.ForeColor = CustomServersOnly ? Theming.BlueForeColorButton : Theming.GrayForeColorButton; BtnRemoveServer.BackColor = CustomServersOnly ? Theming.BlueBackColorButton : Theming.GrayBackColorButton; BtnRemoveServer.FlatAppearance.BorderColor = CustomServersOnly ? Theming.BlueBorderColorButton : Theming.GrayBorderColorButton; BtnRemoveServer.FlatAppearance.MouseOverBackColor = CustomServersOnly ? Theming.BlueMouseOverBackColorButton : Theming.GrayMouseOverBackColorButton; BtnSelectServer.ForeColor = !CustomServersOnly ? Theming.BlueForeColorButton : Theming.GrayForeColorButton; BtnSelectServer.BackColor = !CustomServersOnly ? Theming.BlueBackColorButton : Theming.GrayBackColorButton; BtnSelectServer.FlatAppearance.BorderColor = !CustomServersOnly ? Theming.BlueBorderColorButton : Theming.GrayBorderColorButton; BtnSelectServer.FlatAppearance.MouseOverBackColor = !CustomServersOnly ? Theming.BlueMouseOverBackColorButton : Theming.GrayMouseOverBackColorButton; BtnClose.ForeColor = Theming.BlueForeColorButton; BtnClose.BackColor = Theming.BlueBackColorButton; BtnClose.FlatAppearance.BorderColor = Theming.BlueBorderColorButton; BtnClose.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton; /********************************/ /* Functions / * /********************************/ Name = (CustomServersOnly ? "Saved Custom Servers" : "Please Select a Server") + " - SBRW Launcher"; ServerListRenderer.AllowColumnReorder = false; ServerListRenderer.ColumnWidthChanging += (handler, args) => { args.Cancel = true; args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width; }; ServerListRenderer.DoubleClick += new EventHandler((handler, args) => { if (!CustomServersOnly) { SelectedGameServerToRemember(); } }); BtnSelectServer.Click += new EventHandler(BtnSelectServer_Click); BtnRemoveServer.Click += new EventHandler(BtnRemoveServer_Click); Version.Text = "Version: v" + Application.ProductVersion; /* And one for keeping data about server, IP tbh */ ServerListRenderer.View = View.Details; ServerListRenderer.FullRowSelect = true; ServerListRenderer.Columns.Add(""); ServerListRenderer.Columns[0].Width = 1; ServerListRenderer.Columns.Add("Name"); ServerListRenderer.Columns[1].Width = 210; ServerListRenderer.Columns.Add("Country"); ServerListRenderer.Columns[2].Width = 100; ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Online"); ServerListRenderer.Columns[3].Width = 75; ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Registered"); ServerListRenderer.Columns[4].Width = 85; ServerListRenderer.Columns[4].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Ping"); ServerListRenderer.Columns[5].Width = 60; ServerListRenderer.Columns[5].TextAlign = HorizontalAlignment.Center; foreach (ServerList substring in CustomServersOnly ? ServerListUpdater.NoCategoryList_CSO : ServerListUpdater.NoCategoryList) { try { ServersToPing.Enqueue(ID + "_|||_" + substring.IPAddress + "_|||_" + substring.Name); ServerListRenderer.Items.Add(new ListViewItem( new[] { ID.ToString(), substring.Name, "", "", "", "", "" } )); ServerListBook.Add(ID, substring); ID++; } catch { } } Shown += (x, y) => { Application.OpenForms[this.Name].Activate(); this.BringToFront(); new Thread(() => { while (ServersToPing.Count != 0) { string QueueContent = ServersToPing.Dequeue(); string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None); int serverid = Convert.ToInt32(QueueContent2[0]) - 1; string serverurl = QueueContent2[1] + "/GetServerInformation"; ServerName = QueueContent2[2]; string ServerJson = null; try { try { Uri URLCall = new Uri(serverurl); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { ServerJson = Client.DownloadString(serverurl); } catch { } finally { if (Client != null) { Client.Dispose(); } } } catch { } if (string.IsNullOrWhiteSpace(ServerJson)) { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = "---"; ServerListRenderer.Items[serverid].SubItems[3].Text = "---"; ServerListRenderer.Items[serverid].SubItems[4].Text = "---"; ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; }, this); } else if (!IsJSONValid.ValidJson(ServerJson)) { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = "-?-"; ServerListRenderer.Items[serverid].SubItems[3].Text = "-?-"; ServerListRenderer.Items[serverid].SubItems[4].Text = "-?-"; ServerListRenderer.Items[serverid].SubItems[5].Text = "-?-"; }, this); } else { ServerJsonData = JsonConvert.DeserializeObject <GetServerInformation>(ServerJson); ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = (!string.IsNullOrWhiteSpace(ServerJsonData.serverName)) ? ServerJsonData.serverName : ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = ServerListUpdater.CountryName(ServerJsonData.country.ToString()); ServerListRenderer.Items[serverid].SubItems[3].Text = ServerJsonData.onlineNumber.ToString(); ServerListRenderer.Items[serverid].SubItems[4].Text = ServerJsonData.numberOfRegistered.ToString(); }, this); Ping CheckMate = null; try { Uri StringToUri = new Uri(serverurl); ServicePointManager.FindServicePoint(StringToUri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; CheckMate = new Ping(); CheckMate.PingCompleted += (sender3, e3) => { if (e3.Reply != null) { if (e3.Reply.Status == IPStatus.Success && ServerName != "Offline Built-In Server") { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = e3.Reply.RoundtripTime + "ms"; }, this); } else { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = "!?"; }, this); } } else { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = "N/A"; }, this); } ((AutoResetEvent)e3.UserState).Set(); }; CheckMate.SendAsync(StringToUri.Host, 5000, new byte[1], new PingOptions(30, true), new AutoResetEvent(false)); } catch { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = "?"; }, this); } finally { if (CheckMate != null) { CheckMate.Dispose(); } } } } catch { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = "---"; ServerListRenderer.Items[serverid].SubItems[3].Text = "---"; ServerListRenderer.Items[serverid].SubItems[4].Text = "---"; ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; }, this); } finally { if (ServerJson != null) { ServerJson = null; } if (ServerJsonData != null) { ServerJsonData = null; } if (ServerName != null) { ServerName = null; } GC.Collect(); } Application.DoEvents(); } Loading.SafeInvokeAction(() => { Loading.Text = string.Empty; }, this); }).Start(); }; }
private void Verify(object parameters) { string[] array = (string[])parameters; string str = array[0].Trim(); string text = array[1].Trim(); if (!string.IsNullOrWhiteSpace(text)) { str = str + "/" + text; } string text2 = array[2].Trim(); bool flag = bool.Parse(array[3]); bool flag2 = bool.Parse(array[4]); bool flag3 = bool.Parse(array[5]); bool flag4 = false; try { XmlDocument indexFile = this.GetIndexFile(str + "/index.xml", false); if (indexFile == null) { ISynchronizeInvoke arg_B9_0 = this.mFE; Delegate arg_B9_1 = this.mDownloadFailed; object[] args = new object[1]; arg_B9_0.BeginInvoke(arg_B9_1, args); } else { long num = long.Parse(indexFile.SelectSingleNode("/index/header/length").InnerText); var Client = new WebClient(); if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout(); } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } Client.Headers.Add("Accept", "text/html,text/xml,application/xhtml+xml,application/xml,application/*,*/*;q=0.9,*/*;q=0.8"); Client.Headers.Add("Accept-Language", "en-us,en;q=0.5"); Client.Headers.Add("Accept-Encoding", "gzip,deflate"); Client.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); XmlNodeList xmlNodeList = indexFile.SelectNodes("/index/fileinfo"); DownloaderHashReader.Instance.Clear(); DownloaderHashReader.Instance.Start(indexFile, text2, text + ".hsh", this.mHashThreads); long num2 = 0L; ulong num3 = 0uL; ulong num4 = 0uL; foreach (XmlNode xmlNode in xmlNodeList) { string text3 = xmlNode.SelectSingleNode("path").InnerText; string innerText = xmlNode.SelectSingleNode("file").InnerText; if (!string.IsNullOrWhiteSpace(text2)) { int num5 = text3.IndexOf("/"); if (num5 >= 0) { text3 = text3.Replace(text3.Substring(0, num5), text2); } else { text3 = text2; } } string text4 = text3 + "/" + innerText; int num6 = int.Parse(xmlNode.SelectSingleNode("length").InnerText); if (xmlNode.SelectSingleNode("hash") != null) { if (!DownloaderHashReader.Instance.HashesMatch(text4)) { num3 += ulong.Parse(xmlNode.SelectSingleNode("length").InnerText); ulong num7; if (xmlNode.SelectSingleNode("compressed") != null) { num7 = ulong.Parse(xmlNode.SelectSingleNode("compressed").InnerText); } else { num7 = ulong.Parse(xmlNode.SelectSingleNode("length").InnerText); } num4 += num7; if (flag) { this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { }); return; } flag4 = true; } } else { if (flag) { throw new DownloaderException("Without hash in the metadata I cannot verify the download"); } flag4 = true; } if (Downloader.mStopFlag) { ISynchronizeInvoke arg_367_0 = this.mFE; Delegate arg_367_1 = this.mDownloadFailed; object[] args2 = new object[1]; arg_367_0.BeginInvoke(arg_367_1, args2); return; } num2 += (long)num6; object[] args3 = new object[] { num, num2, 0, innerText, 0 }; this.mFE.BeginInvoke(this.mProgressUpdated, args3); } if (flag3) { DownloaderHashReader.Instance.WriteHashCache(text + ".hsh", true); } if (flag4) { this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { }); } else { this.mFE.BeginInvoke(this.mDownloadFinished, null); } } } catch (DownloaderException Error) { LogToFileAddons.OpenLog("CDN DOWNLOADER", null, Error, null, true); this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { Error }); } catch (Exception Error) { LogToFileAddons.OpenLog("CDN DOWNLOADER", null, Error, null, true); this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { Error }); } finally { if (flag2) { DownloaderHashReader.Instance.Clear(); } GC.Collect(); } }