Ejemplo n.º 1
0
        private static bool RetrieveJSON(string JSONUrl, string Function)
        {
            Log.Checking("JSON LIST: Retriving " + JSONUrl);
            try
            {
                Uri URLCall = new Uri(JSONUrl);
                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
                {
                    OnlineListJson = Client.DownloadString(URLCall);

                    if (URLCall.OriginalString.Contains(URLs.Main))
                    {
                        UnitedSC = APIStatus.Online;
                    }
                    else if (URLCall.OriginalString.Contains(URLs.Static))
                    {
                        CarbonSC = APIStatus.Online;
                    }
                    else if (URLCall.OriginalString.Contains(URLs.Static_Alt))
                    {
                        CarbonTwoSC = APIStatus.Online;
                    }

                    Log.UrlCall("JSON LIST: Retrieved " + JSONUrl);
                }
                catch (WebException Error)
                {
                    APIStatus API_Status = APIChecker.StatusCodes(JSONUrl, Error, (HttpWebResponse)Error.Response);

                    if (URLCall.OriginalString.Contains(URLs.Main))
                    {
                        UnitedSC = API_Status;
                    }
                    else if (URLCall.OriginalString.Contains(URLs.Static))
                    {
                        CarbonSC = API_Status;
                    }
                    else if (URLCall.OriginalString.Contains(URLs.Static_Alt))
                    {
                        CarbonTwoSC = API_Status;
                    }

                    return(false);
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("JSON LIST", null, Error, null, true);

                    if (URLCall.OriginalString.Contains(URLs.Main))
                    {
                        UnitedSC = APIStatus.Unknown;
                    }
                    else if (URLCall.OriginalString.Contains(URLs.Static))
                    {
                        CarbonSC = APIStatus.Unknown;
                    }
                    else if (URLCall.OriginalString.Contains(URLs.Static_Alt))
                    {
                        CarbonTwoSC = APIStatus.Unknown;
                    }

                    return(false);
                }
                finally
                {
                    if (Client != null)
                    {
                        Client.Dispose();
                    }
                }

                if (IsJSONValid.ValidJson(OnlineListJson))
                {
                    switch (Function)
                    {
                    case "SL":
                        ServerListUpdater.CachedJSONList = OnlineListJson;
                        break;

                    case "CDNL":
                        CDNListUpdater.CachedJSONList = OnlineListJson;
                        break;

                    default:
                        break;
                    }
                    Log.Completed("JSON LIST: Valid " + JSONUrl);

                    return(true);
                }
                else
                {
                    Log.Completed("JSON LIST: Invalid " + JSONUrl);
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
            finally
            {
                if (OnlineListJson != null)
                {
                    OnlineListJson = null;
                }
            }
        }
Ejemplo n.º 2
0
        public static void Latest()
        {
            Log.Checking("LAUNCHER UPDATE: Is Version Up to Date or not");
            DiscordLauncherPresence.Status("Start Up", "Checking Latest Launcher Release Information");
            try
            {
                Uri URLCall = new Uri((EnableInsiderBetaTester.Allowed() || EnableInsiderDeveloper.Allowed()) ?
                                      URLs.GitHub_Launcher_Beta : URLs.GitHub_Launcher_Stable);
                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);
                    VisualsAPIChecker.GitHubAPI = true;
                }
                catch (WebException Error)
                {
                    APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped),
                                           Error, (HttpWebResponse)Error.Response);
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("LAUNCHER UPDATE [GITHUB]", null, Error, null, true);
                }
                finally
                {
                    if (Client != null)
                    {
                        Client.Dispose();
                    }
                }

                if (IsJSONValid.ValidJson(VersionJSON) && VisualsAPIChecker.GitHubAPI)
                {
                    LatestLauncherBuild = (EnableInsiderDeveloper.Allowed() || EnableInsiderBetaTester.Allowed()) ?
                                          JsonConvert.DeserializeObject <List <GitHubRelease> >(VersionJSON)[0].TagName :
                                          JsonConvert.DeserializeObject <GitHubRelease>(VersionJSON).TagName;
                    Log.Info("LAUNCHER UPDATE: GitHub Latest Version -> " + LatestLauncherBuild);
                    ValidJSONDownload = true;
                }
                else
                {
                    Log.Error("LAUNCHER UPDATE: Failed to retrieve Latest Build information from GitHub");
                    ValidJSONDownload = false;
                }
            }
            catch (Exception Error)
            {
                LogToFileAddons.OpenLog("LAUNCHER UPDATE [GITHUB]", null, Error, null, true);
            }

            Log.Completed("LAUNCHER UPDATE: Done");

            if (!UpdateStatusResult())
            {
                Log.Info("FIRST TIME RUN: Moved to Function");
                /* Do First Time Run Checks */
                FunctionStatus.FirstTimeRun();
            }
            else
            {
                if (DiscordLauncherPresence.Running())
                {
                    DiscordLauncherPresence.Stop("Close");
                }

                if (ServerProxy.Running())
                {
                    ServerProxy.Instance.Stop("Force Close");
                }

                Application.Exit();
            }
        }
        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();
            };
        }
Ejemplo n.º 4
0
        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);
            }
        }
        /* 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();
        }
        /* 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();
        }
Ejemplo n.º 7
0
        public void DoUpdate()
        {
            string[] args = Environment.GetCommandLineArgs();

            if (args.Length == 2)
            {
                bool Launcher_Process_ID_Terminated = false;
                try
                {
                    Process Launcher_Process_ID = Process.GetProcessById(Convert.ToInt32(args[1]));
                    if (!Launcher_Process_ID.HasExited)
                    {
                        Launcher_Process_ID_Terminated = Launcher_Process_ID.CloseMainWindow();

                        if (!Launcher_Process_ID_Terminated)
                        {
                            Launcher_Process_ID.Kill();
                        }
                    }
                }
                catch
                {
                    try
                    {
                        if (!Launcher_Process_ID_Terminated)
                        {
                            Process.GetProcessById(Convert.ToInt32(args[1])).Kill();
                        }
                    }
                    catch { }
                }
            }

            if (args.Length == 3)
            {
                if (args[2].ToString() == "Preview")
                {
                    BranchStatus.Text = "Preview Branch";
                    UsingPreview      = true;
                }
            }

            if (File.Exists("GameLauncher.exe"))
            {
                var versionInfo = FileVersionInfo.GetVersionInfo("GameLauncher.exe");
                Version = versionInfo.ProductVersion;
            }
            else
            {
                Version = "0.0.0.0";
            }

            try
            {
                WebClient client      = new WebClient();
                Uri       StringToUri = new Uri(UsingPreview ? GitHub_Launcher_Beta : GitHub_Launcher_Stable);
                client.Headers.Add("user-agent", "GameLauncherUpdater " + Application.ProductVersion +
                                   " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                client.CancelAsync();
                client.DownloadStringAsync(StringToUri);
                client.DownloadStringCompleted += (sender3, e3) =>
                {
                    string JSONFile = e3.Result;

                    if (IsJSONValid.ValidJson(JSONFile))
                    {
                        try
                        {
                            if (UnixOS.Detected() && !Directory.Exists(LauncherUpdaterFolder))
                            {
                                Directory.CreateDirectory(LauncherUpdaterFolder);
                            }

                            GitHubReleaseSchema LatestLauncherBuild = (UsingPreview) ?
                                                                      new JavaScriptSerializer().Deserialize <List <GitHubReleaseSchema> >(JSONFile)[0] :
                                                                      new JavaScriptSerializer().Deserialize <GitHubReleaseSchema>(JSONFile);

                            if (Version != LatestLauncherBuild.tag_name)
                            {
                                WebClient client2 = new WebClient();
                                client2.Headers.Add("user-agent", "GameLauncherUpdater " + Application.ProductVersion +
                                                    " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                                client2.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
                                client2.DownloadFileCompleted   += new AsyncCompletedEventHandler(Launcher_Client_DownloadFileCompleted);
                                client2.DownloadFileAsync(new Uri("http://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases/download/" +
                                                                  LatestLauncherBuild.tag_name + "/Release_" + LatestLauncherBuild.tag_name + ".zip"), TempLauncherNameZip);
                            }
                            else
                            {
                                Process.Start(@"GameLauncher.exe");
                                DisplayError("Up To Date. Starting SBRW Launcher", 2);
                            }
                        }
                        catch (Exception Error)
                        {
                            DisplayError("Failed to Update.\n" + Error.Message, 10);
                        }
                    }
                    else
                    {
                        DisplayError("Failed to Update.\nRetrived Invalid JSON", 10);
                    }
                };
            }
            catch (Exception Error)
            {
                DisplayError(Error.Message, 10);
            }
        }