public VerifyHash()
        {
            IsVerifyHashOpen = true;
            DiscordLauncherPresence.Status("Verify", null);
            InitializeComponent();
            SetVisuals();
            this.Closing += (x, CloseForm) =>
            {
                if (isScanning)
                {
                    if (MessageBox.Show("Do you really want to exit the VerifyHash process?", "VerifyHash", MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        CloseForm.Cancel = true;
                    }
                    else
                    {
                        DiscordLauncherPresence.Status("Settings", null);
                        IsVerifyHashOpen = false;
                        GameScanner(false);
                    }
                }
                else
                {
                    IsVerifyHashOpen = false;
                    DiscordLauncherPresence.Status("Settings", null);
                }

                GC.Collect();
            };
        }
Пример #2
0
 public RegisterScreen()
 {
     IsRegisterScreenOpen = true;
     InitializeComponent();
     SetVisuals();
     DiscordLauncherPresence.Status("Register", ServerListUpdater.ServerName("Register"));
     this.Closing += (x, y) =>
     {
         DiscordLauncherPresence.Status("Idle Ready", null);
         IsRegisterScreenOpen = false;
         GC.Collect();
     };
 }
Пример #3
0
        public UpdatePopup()
        {
            DiscordLauncherPresence.Status("Start Up", "New Version Is Available: " + LauncherUpdateCheck.LatestLauncherBuild);
            InitializeComponent();
            SetVisuals();

            if (VisualsAPIChecker.GitHubAPI)
            {
                try
                {
                    ChangelogText.Text = (EnableInsiderDeveloper.Allowed() || EnableInsiderBetaTester.Allowed()) ?
                                         JsonConvert.DeserializeObject <List <GitHubRelease> >(LauncherUpdateCheck.VersionJSON)[0].Body.Replace("\r", Environment.NewLine) :
                                         JsonConvert.DeserializeObject <GitHubRelease>(LauncherUpdateCheck.VersionJSON).Body.Replace("\r", Environment.NewLine);
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("Update Popup", null, Error, null, true);
                    ChangelogText.Text = "\n" + Error.Message;
                    ChangelogBox.Text  = "Changelog Error:";
                }
            }
            else
            {
                ChangelogText.Text = "\nUnable to Retrieve Changelog";
                ChangelogBox.Text  = "Changelog Error:";
            }

            ChangelogText.Select(0, 0);
            ChangelogText.SelectionLength = 0;
            ChangelogText.TabStop         = false;

            Bitmap bitmap1 = Bitmap.FromHicon(SystemIcons.Information.Handle);

            UpdateIcon.Image = bitmap1;

            UpdateText.Text = "An update is available. Would you like to update?\nYour version: " + Application.ProductVersion +
                              "\nUpdated version: " + LauncherUpdateCheck.LatestLauncherBuild;

            this.UpdateButton.DialogResult = DialogResult.OK;
            this.IgnoreButton.DialogResult = DialogResult.Cancel;
            this.SkipButton.DialogResult   = DialogResult.Ignore;
        }
        /// <summary>
        /// Used to Force Close Launcher when Launcher encounters an error during Startup
        /// </summary>
        /// <param name="Notes">Required: Where the Launcher is Closing From</param>
        /// <param name="Boolen">True: Restarts Launcher | False: Closes Launcher</param>
        public static void ErrorCloseLauncher(string Notes, bool Boolen)
        {
            SplashScreen.ThreadStatus("Stop");

            if (DiscordLauncherPresence.Running())
            {
                DiscordLauncherPresence.Stop("Close");
            }

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

            Log.Warning("LAUNCHER: Exiting (" + Notes + ")");
            if (!string.IsNullOrWhiteSpace(LauncherForceCloseReason))
            {
                DialogResult OpenLogFile = MessageBox.Show(null, "The GameLauncher has ecountered an Error and it must Close. " +
                                                           "Below is a Summary of the Error:" + "\n" + LauncherForceCloseReason + "\n\n" +
                                                           LogToFileAddons.OpenLogMessage, "GameLauncher",
                                                           MessageBoxButtons.YesNo, MessageBoxIcon.Information);

                if (OpenLogFile == DialogResult.Yes)
                {
                    Process.Start(Locations.LogLauncher);
                }
            }

            if (Boolen)
            {
                Application.Restart();
            }
            else
            {
                Application.Exit();
            }
        }
Пример #5
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();
            }
        }
Пример #6
0
        public static void PingAPIStatus()
        {
            Log.Checking("API: Checking Status");
            Log.Checking("API Status: WorldUnited");
            switch (UnitedSC = APIChecker.CheckStatus(URLs.Main + "/serverlist.json", 15))
            {
            case APIStatus.Online:
                UnitedSL = RetrieveJSON(URLs.Main + "/serverlist.json", "SL");
                if (UnitedSL)
                {
                    UnitedCDNL = RetrieveJSON(URLs.Main + "/cdn_list.json", "CDNL");
                }
                Log.Completed("API Status: WorldUnited");
                break;

            default:
                Log.Completed("API Status: WorldUnited");
                break;
            }

            if (!UnitedAPI())
            {
                Log.Checking("API Status: DavidCarbon");
                switch (CarbonSC = APIChecker.CheckStatus(URLs.Static + "/serverlist.json", 15))
                {
                case APIStatus.Online:
                    if (!UnitedSL)
                    {
                        CarbonSL = RetrieveJSON(URLs.Static + "/serverlist.json", "SL");
                    }
                    else
                    {
                        CarbonSL = true;
                    }
                    if (!UnitedCDNL)
                    {
                        CarbonCDNL = RetrieveJSON(URLs.Static + "/cdn_list.json", "CDNL");
                    }
                    else
                    {
                        CarbonCDNL = true;
                    }
                    Log.Completed("API Status: DavidCarbon");
                    break;

                default:
                    Log.Completed("API Status: DavidCarbon");
                    break;
                }
            }
            else
            {
                CarbonSL   = true;
                CarbonCDNL = true;
            }

            if (!CarbonAPI())
            {
                Log.Checking("API Status: DavidCarbon [Second]");
                switch (CarbonTwoSC = APIChecker.CheckStatus(URLs.Static_Alt + "/serverlist.json", 15))
                {
                case APIStatus.Online:
                    if (!CarbonSL)
                    {
                        CarbonTwoSL = RetrieveJSON(URLs.Static_Alt + "/serverlist.json", "SL");
                    }
                    else
                    {
                        CarbonTwoSL = true;
                    }
                    if (!CarbonCDNL)
                    {
                        CarbonTwoCDNL = RetrieveJSON(URLs.Static_Alt + "/cdn_list.json", "CDNL");
                    }
                    else
                    {
                        CarbonTwoCDNL = true;
                    }
                    Log.Completed("API Status: DavidCarbon [Second]");
                    break;

                default:
                    Log.Completed("API Status: DavidCarbon [Second]");
                    break;
                }
            }
            else
            {
                CarbonTwoSL   = true;
                CarbonTwoCDNL = true;
            }

            Log.Checking("API: Test #2");

            /* Check If Launcher Failed to Connect to any APIs */
            if (!CarbonAPITwo())
            {
                DiscordLauncherPresence.Status("Start Up", "Launcher Encountered API Errors");

                if (MessageBox.Show(null, Translations.Database("VisualsAPIChecker_TextBox_No_API"),
                                    Translations.Database("VisualsAPIChecker_TextBox_No_API_P2"),
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    FunctionStatus.LauncherForceClose = true;
                }
                else
                {
                    Log.Warning("PRE-CHECK: User has Bypassed 'No Internet Connection' Check and will Continue");
                    MessageBox.Show(Translations.Database("VisualsAPIChecker_TextBox_No_API_P3"),
                                    Translations.Database("VisualsAPIChecker_TextBox_No_API_P4"));
                }
            }
            Log.Completed("API: Test #2 Done");

            if (FunctionStatus.LauncherForceClose)
            {
                FunctionStatus.ErrorCloseLauncher("Closing From API Check Error", false);
            }
            else
            {
                FunctionStatus.IsVisualAPIsChecked = true;

                Log.Info("LIST CORE: Moved to Function");
                /* (Start Process) Check ServerList Status */
                ServerListUpdater.GetList();
            }
        }
Пример #7
0
        public static void GetList()
        {
            Log.Checking("LIST CORE: Creating Language List");
            DiscordLauncherPresence.Status("Start Up", "Creating Language List");

            List <LangObject> langInfos = new List <LangObject>();

            String json_language = String.Empty;

            try
            {
                json_language += "[";
                json_language += "    { \"category\": \"Official\", \"name\": \"English\",             \"xml_value\": \"EN\", \"ini_value\": \"EN\"},";
                json_language += "    { \"category\": \"Official\", \"name\": \"Deutsch\",             \"xml_value\": \"DE\", \"ini_value\": \"DE\"},";
                json_language += "    { \"category\": \"Official\", \"name\": \"Español\",             \"xml_value\": \"ES\", \"ini_value\": \"ES\"},";
                json_language += "    { \"category\": \"Official\", \"name\": \"Français\",            \"xml_value\": \"FR\", \"ini_value\": \"FR\"},";
                json_language += "    { \"category\": \"Official\", \"name\": \"Polski\",              \"xml_value\": \"PL\", \"ini_value\": \"PL\"},";
                json_language += "    { \"category\": \"Official\", \"name\": \"Русский\",             \"xml_value\": \"RU\", \"ini_value\": \"RU\"},";
                json_language += "    { \"category\": \"Official\", \"name\": \"Português (Brasil)\",  \"xml_value\": \"PT\", \"ini_value\": \"PT\"},";
                json_language += "    { \"category\": \"Official\", \"name\": \"繁體中文\",             \"xml_value\": \"TC\", \"ini_value\": \"TC\"},";
                json_language += "    { \"category\": \"Official\", \"name\": \"简体中文\",             \"xml_value\": \"SC\", \"ini_value\": \"SC\"},";
                json_language += "    { \"category\": \"Official\", \"name\": \"ภาษาไทย\",              \"xml_value\": \"TH\", \"ini_value\": \"TH\"},";
                json_language += "    { \"category\": \"Official\", \"name\": \"Türkçe\",               \"xml_value\": \"TR\", \"ini_value\": \"TR\"},";
                json_language += "    { \"category\": \"Custom\",   \"name\": \"Italiano\",             \"xml_value\": \"EN\", \"ini_value\": \"IT\"}";
                json_language += "]";
            }
            catch (Exception Error)
            {
                LogToFileAddons.OpenLog("LIST CORE", null, Error, null, true);
            }

            try
            {
                langInfos.AddRange(JsonConvert.DeserializeObject <List <LangObject> >(json_language));
            }
            catch (Exception Error)
            {
                LogToFileAddons.OpenLog("LIST CORE", null, Error, null, true);
            }

            try
            {
                foreach (LangObject NoCatList in langInfos)
                {
                    if (NoCategoryList.FindIndex(i => string.Equals(i.Name, NoCatList.Name)) == -1)
                    {
                        NoCategoryList.Add(NoCatList);
                    }
                }

                List <LangObject> RawList = new List <LangObject>();

                foreach (var langItemGroup in langInfos.GroupBy(s => s.Category))
                {
                    if (RawList.FindIndex(i => string.Equals(i.Name, $"<GROUP>{langItemGroup.Key} Mirrors")) == -1)
                    {
                        RawList.Add(new LangObject
                        {
                            Name      = $"<GROUP>{langItemGroup.Key} Languages",
                            IsSpecial = true
                        });
                    }
                    RawList.AddRange(langItemGroup.ToList());
                }

                foreach (LangObject CList in RawList)
                {
                    if (CleanList.FindIndex(i => string.Equals(i.Name, CList.Name)) == -1)
                    {
                        CleanList.Add(CList);
                    }
                }
            }
            catch (Exception Error)
            {
                LogToFileAddons.OpenLog("LIST CORE", null, Error, null, true);
            }

            Log.Checking("LIST CORE: Done");

            Log.Info("API: Moved to Function");
            /* Run the API Checks to Make Sure it Visually Displayed Correctly */
            VisualsAPIChecker.PingAPIStatus();
        }
        public static void FirstTimeRun()
        {
            if (!LauncherUpdateCheck.UpdatePopupStoppedSplashScreen)
            {
                LoadingComplete = true;
                SplashScreen.ThreadStatus("Stop");
            }

            if (!string.IsNullOrWhiteSpace(FileSettingsSave.GameInstallation))
            {
                Log.Core("LAUNCHER: Checking InstallationDirectory: " + FileSettingsSave.GameInstallation);
            }

            Log.Checking("LAUNCHER: Checking Game Installation");
            if (string.IsNullOrWhiteSpace(FileSettingsSave.GameInstallation))
            {
                DiscordLauncherPresence.Status("Start Up", "Doing First Time Run");
                Log.Core("LAUNCHER: First run!");

                try
                {
                    Form         welcome      = new WelcomeScreen();
                    DialogResult welcomereply = welcome.ShowDialog();

                    if (welcomereply != DialogResult.OK)
                    {
                        LauncherForceClose = true;
                    }
                    else
                    {
                        FileSettingsSave.CDN = SelectedCDN.CDNUrl;
                        FileSettingsSave.SaveSettings();
                    }
                }
                catch
                {
                    Log.Warning("LAUNCHER: CDN Source URL was Empty! Setting a Null Safe URL 'http://localhost'");
                    FileSettingsSave.CDN = "http://localhost";
                    Log.Core("LAUNCHER: Installation Directory was Empty! Creating and Setting Directory at " + Locations.GameFilesFailSafePath);
                    FileSettingsSave.GameInstallation = Locations.GameFilesFailSafePath;
                    FileSettingsSave.SaveSettings();
                }

                if (LauncherForceClose)
                {
                    ErrorCloseLauncher("Closing From Welcome Dialog", false);
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(FileSettingsSave.GameInstallation))
                    {
                        DiscordLauncherPresence.Status("Start Up", "User Selecting/Inputting Game Files Folder");

                        try
                        {
                            if (!UnixOS.Detected())
                            {
                                string GameFolderPath = string.Empty;

                                CommonOpenFileDialog FolderDialog = new CommonOpenFileDialog
                                {
                                    EnsurePathExists        = true,
                                    EnsureFileExists        = false,
                                    AllowNonFileSystemItems = false,
                                    Title          = "Select the location to Find or Download NFS:W",
                                    IsFolderPicker = true
                                };

                                if (FolderDialog.ShowDialog() == CommonFileDialogResult.Ok)
                                {
                                    if (!string.IsNullOrWhiteSpace(Strings.Encode(FolderDialog.FileName)))
                                    {
                                        GameFolderPath = Strings.Encode(FolderDialog.FileName);
                                    }
                                }

                                FolderDialog.Dispose();

                                if (!string.IsNullOrWhiteSpace(GameFolderPath))
                                {
                                    DiscordLauncherPresence.Status("Start Up", "Verifying Game Files Folder Location");

                                    if (!HasWriteAccessToFolder(GameFolderPath))
                                    {
                                        Log.Error("FOLDER SELECT DIALOG: Not enough permissions. Exiting.");
                                        string ErrorMessage = "You don't have enough permission to select this path as the Installation folder. " +
                                                              "Please select another directory.";
                                        MessageBox.Show(null, ErrorMessage, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        LauncherForceClose       = true;
                                        LauncherForceCloseReason = ErrorMessage;
                                    }
                                    else
                                    {
                                        if (GameFolderPath.Length == 3)
                                        {
                                            Directory.CreateDirectory("Game Files");
                                            Log.Warning("FOLDER SELECT DIALOG: Installing NFSW in root of the harddisk is not allowed.");
                                            MessageBox.Show(null, string.Format("Installing NFSW in root of the harddisk is not allowed. " +
                                                                                "Instead, we will install it on {0}.", Locations.GameFilesFailSafePath),
                                                            "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            FileSettingsSave.GameInstallation = Locations.GameFilesFailSafePath;
                                            FileSettingsSave.SaveSettings();
                                            FileGameSettings.Save("Suppress", "Language Only");
                                        }
                                        else if (GameFolderPath == Locations.LauncherFolder)
                                        {
                                            Directory.CreateDirectory("Game Files");
                                            Log.Warning("FOLDER SELECT DIALOG: Installing NFSW in same location where the GameLauncher resides is NOT allowed.");
                                            MessageBox.Show(null, string.Format("Installing NFSW in same location where the GameLauncher resides is NOT allowed.\n " +
                                                                                "Instead, we will install it on {0}.", Locations.GameFilesFailSafePath),
                                                            "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            FileSettingsSave.GameInstallation = Locations.GameFilesFailSafePath;
                                            FileSettingsSave.SaveSettings();
                                            FileGameSettings.Save("Suppress", "Language Only");
                                        }
                                        else
                                        {
                                            Log.Core("FOLDER SELECT DIALOG: Directory Set: " + GameFolderPath);
                                            FileSettingsSave.GameInstallation = GameFolderPath;
                                            FileSettingsSave.SaveSettings();
                                            FileGameSettings.Save("Suppress", "Language Only");
                                        }
                                    }
                                }
                                else
                                {
                                    LauncherForceClose = true;
                                }
                            }
                            else
                            {
                                if (string.IsNullOrWhiteSpace(FileSettingsSave.GameInstallation))
                                {
                                    try
                                    {
                                        FileSettingsSave.GameInstallation = Strings.Encode(Path.GetFullPath("GameFiles"));
                                    }
                                    catch
                                    {
                                        FileSettingsSave.GameInstallation = "GameFiles";
                                    }
                                }
                            }

                            if (!string.IsNullOrWhiteSpace(FileSettingsSave.GameInstallation))
                            {
                                if (!Directory.Exists(FileSettingsSave.GameInstallation))
                                {
                                    Log.Core("FOLDER SELECT DIALOG: Created Game Files Directory: " + FileSettingsSave.GameInstallation);
                                    Directory.CreateDirectory(FileSettingsSave.GameInstallation);
                                }
                            }

                            if (!string.IsNullOrWhiteSpace(FileSettingsSave.GameInstallation))
                            {
                                Log.Checking("CLEANLINKS: Game Path");
                                if (File.Exists(Locations.GameLinksFile))
                                {
                                    ModNetHandler.CleanLinks(Locations.GameLinksFile, FileSettingsSave.GameInstallation);
                                    Log.Completed("CLEANLINKS: Done");
                                }
                                else
                                {
                                    Log.Completed("CLEANLINKS: Not Present");
                                }
                            }
                        }
                        catch (Exception Error)
                        {
                            LauncherForceClose       = true;
                            LauncherForceCloseReason = Error.Message;
                            LogToFileAddons.OpenLog("FOLDER SELECT DIALOG", null, Error, null, true);
                        }
                    }
                }
            }
            Log.Completed("LAUNCHER: Game Installation Path Done");

            if (LauncherForceClose)
            {
                ErrorCloseLauncher("Closing From Folder Dialog", false);
            }
            else
            {
                if (!UnixOS.Detected())
                {
                    Log.Checking("LAUNCHER: Checking Game Path Location");
                    DiscordLauncherPresence.Status("Start Up", "Checking Game Files Folder Location");

                    switch (CheckFolder(FileSettingsSave.GameInstallation))
                    {
                    case FolderType.IsSameAsLauncherFolder:
                        Directory.CreateDirectory("Game Files");
                        Log.Error("LAUNCHER: Installing NFSW in same location where the GameLauncher resides is NOT allowed.");
                        MessageBox.Show(null, string.Format("Installing NFSW in same location where the GameLauncher resides is NOT allowed.\n" +
                                                            "Instead, we will install it at {0}.", Locations.GameFilesFailSafePath),
                                        "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        FileSettingsSave.GameInstallation = Locations.GameFilesFailSafePath;
                        break;

                    case FolderType.IsTempFolder:
                    case FolderType.IsUsersFolders:
                    case FolderType.IsProgramFilesFolder:
                    case FolderType.IsWindowsFolder:
                    case FolderType.IsRootFolder:
                        String constructMsg = String.Empty;
                        constructMsg += "Using this location for Game Files is not allowed.\n\n";
                        constructMsg += "The following locations are also NOT allowed:\n";
                        constructMsg += "• X:\\nfsw.exe (Root of Drive, such as C:\\ or D:\\, must be in a folder)\n";
                        constructMsg += "• C:\\Program Files\n";
                        constructMsg += "• C:\\Program Files (x86)\n";
                        constructMsg += "• C:\\Users (Includes 'Desktop', 'Documents', 'Downloads')\n";
                        constructMsg += "• C:\\Windows\n\n";
                        constructMsg += "Instead, we will install the NFSW Game at " + Locations.GameFilesFailSafePath;
                        try
                        {
                            if (!Directory.Exists(Locations.GameFilesFailSafePath))
                            {
                                Log.Core("FOLDER SELECT DIALOG: Created Game Files Directory: " + Locations.GameFilesFailSafePath);
                                Directory.CreateDirectory(Locations.GameFilesFailSafePath);
                            }
                        }
                        catch { }
                        MessageBox.Show(null, constructMsg, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Log.Error("LAUNCHER: Installing NFSW in a Restricted Location is not allowed.");
                        FileSettingsSave.GameInstallation = Locations.GameFilesFailSafePath;
                        break;
                    }
                    FileSettingsSave.SaveSettings();
                    Log.Completed("LAUNCHER: Done Checking Game Path Location");
                }

                /* Check If Launcher Failed to Connect to any APIs */
                if (!VisualsAPIChecker.CarbonAPITwo())
                {
                    DiscordLauncherPresence.Status("Start Up", "Launcher Encountered API Errors");

                    DialogResult restartAppNoApis = MessageBox.Show(null, "There is no internet connection, Launcher might crash." +
                                                                    "\n\nClick Yes to Close GameLauncher" +
                                                                    "\nor" +
                                                                    "\nClick No Continue", "GameLauncher has Stopped, Failed To Connect To API", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (restartAppNoApis == DialogResult.Yes)
                    {
                        LauncherForceClose = true;
                    }
                }

                if (LauncherForceClose)
                {
                    ErrorCloseLauncher("Closing From API Error", false);
                }
                else
                {
                    try
                    {
                        Log.Info("MAINSCREEN: Program Started");
                        Application.Run(new MainScreen());
                    }
                    catch (COMException Error)
                    {
                        LogToFileAddons.OpenLog("Main Screen [Application Run]", "Launcher Encounterd an Error.", Error, "Error", false);
                        ErrorCloseLauncher("Main Screen [Application Run]", false);
                    }
                    catch (Exception Error)
                    {
                        LogToFileAddons.OpenLog("Main Screen [Application Run]", "Launcher Encounterd an Error.", Error, "Error", false);
                        ErrorCloseLauncher("Main Screen [Application Run]", false);
                    }
                }
            }
        }
 private void Integrity()
 {
     DiscordLauncherPresence.Status("Verify Good", null);
     FileSettingsSave.GameIntegrity = "Good";
     FileSettingsSave.SaveSettings();
 }
        private void DebugScreen_Load(object sender, EventArgs e)
        {
            data.AutoGenerateColumns = true;

            string Antivirus   = String.Empty;
            string Firewall    = String.Empty;
            string AntiSpyware = String.Empty;

            if (!UnixOS.Detected())
            {
                try
                {
                    Antivirus   = (String.IsNullOrWhiteSpace(SecurityCenter("AntiVirusProduct"))) ? "---" : SecurityCenter("AntiVirusProduct");
                    Firewall    = (String.IsNullOrWhiteSpace(SecurityCenter("FirewallProduct"))) ? "Built-In" : SecurityCenter("FirewallProduct");
                    AntiSpyware = (String.IsNullOrWhiteSpace(SecurityCenter("AntiSpywareProduct"))) ? "---" : SecurityCenter("AntiSpywareProduct");
                }
                catch
                {
                    Antivirus   = "Unknown";
                    Firewall    = "Unknown";
                    AntiSpyware = "Unknown";
                }
            }

            string UpdateSkip;

            if (FileSettingsSave.IgnoreVersion == Application.ProductVersion || FileSettingsSave.IgnoreVersion == String.Empty)
            {
                UpdateSkip = "False";
            }
            else
            {
                UpdateSkip = FileSettingsSave.IgnoreVersion;
            }

            string StreamOpt;

            if (FileSettingsSave.StreamingSupport == "0")
            {
                StreamOpt = "Displaying Timer";
            }
            else
            {
                StreamOpt = "Native (Timer Removed)";
            }
            string ThemeOpt;

            if (FileSettingsSave.ThemeSupport == "0")
            {
                ThemeOpt = "Disabled";
            }
            else
            {
                ThemeOpt = "Enabled";
            }

            string InsiderOpt;

            if (FileSettingsSave.Insider == "0")
            {
                InsiderOpt = "Release Only";
            }
            else
            {
                InsiderOpt = "Insider Opt-In";
            }

            /* Used to calculate remaining Free Space on the Game Installed Drive */
            ulong lpFreeBytesAvailable = 0;

            if (!UnixOS.Detected())
            {
                try
                {
                    Kernel32.GetDiskFreeSpaceEx(FileSettingsSave.GameInstallation,
                                                out lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes);
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("Debug", null, Error, null, true);
                }
            }

            var settings = new List <ListType>
            {
                new ListType {
                    Name = "Operating System", Value = (UnixOS.Detected())? UnixOS.FullName() : Environment.OSVersion.VersionString
                },
                new ListType {
                    Name = "Environment Version", Value = Environment.OSVersion.Version.ToString()
                },
                new ListType {
                    Name = "Screen Resolution", Value = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height + " (Primary Display)"
                },
                new ListType {
                    Name = "", Value = ""
                },
                new ListType {
                    Name = "InstallationDirectory", Value = FileSettingsSave.GameInstallation
                },
                new ListType {
                    Name = "Launcher Version", Value = Application.ProductVersion
                },
                new ListType {
                    Name = "Credentials Saved", Value = (!String.IsNullOrWhiteSpace(FileAccountSave.UserHashedPassword)) ? "True" : "False"
                },
                new ListType {
                    Name = "Language", Value = FileSettingsSave.Lang
                },
                new ListType {
                    Name = "Skipping Update", Value = UpdateSkip
                },
                new ListType {
                    Name = "Proxy Enabled", Value = ServerProxy.Running().ToString()
                },
                new ListType {
                    Name = "RPC Enabled", Value = DiscordLauncherPresence.Running().ToString()
                },
                new ListType {
                    Name = "Catpure Support", Value = StreamOpt
                },
                new ListType {
                    Name = "Theme Support", Value = ThemeOpt
                },
                new ListType {
                    Name = "Insider State", Value = InsiderOpt
                },
                new ListType {
                    Name = "", Value = ""
                },
                new ListType {
                    Name = "Server Name", Value = ServerListUpdater.ServerName("Debug")
                },
                new ListType {
                    Name = "Server Address", Value = InformationCache.SelectedServerData.IPAddress
                },
                new ListType {
                    Name = "CDN Address", Value = FileSettingsSave.CDN
                },
                new ListType {
                    Name = "ProxyPort", Value = ServerProxy.ProxyPort.ToString()
                },
                new ListType {
                    Name = "Client Method", Value = FileSettingsSave.WebCallMethod
                },
                new ListType {
                    Name = "", Value = ""
                },
            };

            if (!UnixOS.Detected())
            {
                DriveInfo driveInfo = new DriveInfo(FileSettingsSave.GameInstallation);
                settings.AddRange(new[]
                {
                    new ListType {
                        Name = "Antivirus", Value = Antivirus
                    },
                    new ListType {
                        Name = "Firewall Application", Value = Firewall
                    },
                    new ListType {
                        Name = "Firewall Rule - Launcher", Value = FileSettingsSave.FirewallLauncherStatus
                    },
                    new ListType {
                        Name = "Firewall Rule - Game", Value = FileSettingsSave.FirewallGameStatus
                    },
                    new ListType {
                        Name = "AntiSpyware", Value = AntiSpyware
                    },
                    new ListType {
                        Name = "", Value = ""
                    },
                    new ListType {
                        Name = "CPU", Value = HardwareInfo.CPU.CPUName()
                    },
                    new ListType {
                        Name = "RAM", Value = HardwareInfo.RAM.SysMem() + " MB"
                    },
                    new ListType {
                        Name = "GPU", Value = HardwareInfo.GPU.CardName()
                    },
                    new ListType {
                        Name = "GPU Driver", Value = HardwareInfo.GPU.DriverVersion()
                    },
                    new ListType {
                        Name = "Disk Space Left", Value = FormatFileSize(lpFreeBytesAvailable)
                    },
                    new ListType {
                        Name = "Disk Type", Value = driveInfo.DriveFormat
                    },
                    new ListType {
                        Name = "", Value = ""
                    }
                });
            }
            settings.AddRange(new[]
            {
                new ListType {
                    Name = "HWID", Value = HardwareID.FingerPrint.Level_One_Value()
                },
            });

            data.DataSource = settings;

            DataGridViewCellStyle style = new DataGridViewCellStyle
            {
                Font = new Font(data.Font, FontStyle.Regular)
            };

            data.Columns[0].DefaultCellStyle = style;

            data.Columns[0].Width += 50;

            int size_x = 512;
            int size_y = 640;

            data.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.Size = new Size(size_x, size_y);
        }
        /* 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();
        }
Пример #12
0
        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();
        }
        /* 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();
        }
        private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            StillDownloading = false;

            if (e.Error != null && IsVerifyHashOpen && !ForceStopScan)
            {
                redownloadErrorCount++;
                LogVerify.Downloaded("File: " + CurrentDownloadingFile);
                DiscordLauncherPresence.Status("Verify Bad", redownloadedCount + redownloadErrorCount + " out of " + currentCount);

                DownloadProgressText.SafeInvokeAction(() =>
                                                      DownloadProgressText.Text = "Failed To Download File [ " +
                                                                                  redownloadedCount + redownloadErrorCount + " / " + currentCount + " ]:" + "\n" + CurrentDownloadingFile);

                DownloadProgressBar.SafeInvokeAction(() =>
                                                     DownloadProgressBar.Value = redownloadedCount + redownloadErrorCount * 100 / currentCount);

                LogVerify.Error("Download for [" + CurrentDownloadingFile + "] - " +
                                (e.Error != null ? (string.IsNullOrWhiteSpace(e.Error.Message) ? e.Error.ToString() : e.Error.Message) : "No Exception Error Provided"));

                if (redownloadedCount + redownloadErrorCount == currentCount)
                {
                    StartScanner.SafeInvokeAction(() => StartScanner.Visible = false);
                    StopScanner.SafeInvokeAction(() => StopScanner.Visible   = false);

                    DownloadProgressText.SafeInvokeAction(() =>
                                                          DownloadProgressText.Text = "\n" + redownloadedCount + " Invalid/Missing File(s) were Redownloaded");

                    VerifyHashText.SafeInvokeAction(() =>
                    {
                        VerifyHashText.ForeColor = Theming.WinFormWarningTextForeColor;
                        VerifyHashText.Text      = redownloadErrorCount + " Files Failed to Download. Check Log for Details";
                    }, this);

                    DownloadErrorEncountered = true;
                    GameScanner(false);
                }
            }
            else if (IsVerifyHashOpen && !ForceStopScan)
            {
                redownloadedCount++;

                DiscordLauncherPresence.Status("Verify Bad", redownloadedCount + " out of " + currentCount);
                LogVerify.Downloaded("File: " + CurrentDownloadingFile);

                DownloadProgressText.SafeInvokeAction(() =>
                                                      DownloadProgressText.Text = "Downloaded File [ " + redownloadedCount + " / " + currentCount + " ]:\n" + CurrentDownloadingFile);
                DownloadProgressBar.SafeInvokeAction(() =>
                                                     DownloadProgressBar.Value = redownloadedCount * 100 / currentCount);

                if (redownloadedCount == currentCount)
                {
                    Integrity();
                    Log.Info("VERIFY HASH: Re-downloaded Count: " + redownloadedCount + " Current File Count: " + currentCount);
                    DownloadProgressText.SafeInvokeAction(() =>
                                                          DownloadProgressText.Text = "\n" + redownloadedCount + " Invalid/Missing File(s) were downloaded");

                    VerifyHashText.SafeInvokeAction(() =>
                    {
                        VerifyHashText.ForeColor = Theming.WinFormWarningTextForeColor;
                        VerifyHashText.Text      = "Yay! Scanning and Downloading\n is now completed on Gamefiles";
                    }, this);

                    StartScanner.SafeInvokeAction(() => StartScanner.Visible = false);
                    StopScanner.SafeInvokeAction(() => StopScanner.Visible   = false);

                    GameScanner(false);
                }
                else if (redownloadedCount + redownloadErrorCount == currentCount)
                {
                    DownloadProgressText.SafeInvokeAction(() =>
                                                          DownloadProgressText.Text = "\n" + redownloadedCount + " Invalid/Missing File(s) were downloaded");

                    VerifyHashText.SafeInvokeAction(() =>
                    {
                        VerifyHashText.ForeColor = Theming.WinFormWarningTextForeColor;
                        VerifyHashText.Text      = redownloadErrorCount + " Files Failed to Download. Check Log for Details";
                    }, this);

                    StartScanner.SafeInvokeAction(() => StartScanner.Visible = false);
                    StopScanner.SafeInvokeAction(() => StopScanner.Visible   = false);

                    DownloadErrorEncountered = true;
                    GameScanner(false);
                }
            }
            else if (IsVerifyHashOpen && ForceStopScan)
            {
                Log.Info("VERIFY HASH: Download Process has Stopped");
                DiscordLauncherPresence.Status("Verify Bad", redownloadedCount + " out of " + currentCount);

                DownloadProgressText.SafeInvokeAction(() =>
                                                      DownloadProgressText.Text = "Download Stopped on File [ " +
                                                                                  redownloadedCount + " / " + currentCount + " ]:" + "\n" + CurrentDownloadingFile);

                DownloadProgressBar.SafeInvokeAction(() => DownloadProgressBar.Value = redownloadedCount * 100 / currentCount);

                LogVerify.Error("Download for [" + CurrentDownloadingFile + "] -  has been Cancelled");

                StartScanner.SafeInvokeAction(() => StartScanner.Visible = false);
                StopScanner.SafeInvokeAction(() => StopScanner.Visible   = false);
                VerifyHashText.SafeInvokeAction(() =>
                {
                    VerifyHashText.Text = "Verify Hash Download Process has been Terminated";
                }, this);
            }
            else if (ForceStopScan)
            {
                Log.Info("VERIFY HASH: Download Process has Stopped");
                LogVerify.Error("Download for [" + CurrentDownloadingFile + "] -  has been Cancelled");
            }
        }
        private void CorruptedFilesFound()
        {
            DiscordLauncherPresence.Status("Verify Bad", null);
            /* START Show Redownloader Progress*/
            StartScanner.SafeInvokeAction(() => StartScanner.Visible = false);
            StopScanner.SafeInvokeAction(() => StopScanner.Visible   = true);

            VerifyHashText.SafeInvokeAction(() => VerifyHashText.Text = "Currently (re)downloading files\nThis part may take awhile\ndepending on your connection.");

            if (File.Exists("invalidfiles.dat") && File.ReadAllLines("invalidfiles.dat") != null)
            {
                DownloadProgressText.SafeInvokeAction(() => DownloadProgressText.Text = "\nPreparing to Download Files");

                string[] files = File.ReadAllLines("invalidfiles.dat");

                foreach (string text in files)
                {
                    if (!ForceStopScan)
                    {
                        try
                        {
                            while (StillDownloading)
                            {
                            }

                            if (!ForceStopScan)
                            {
                                currentCount = files.Count();

                                string text2   = FileSettingsSave.GameInstallation + text;
                                string address = FinalCDNURL + "/unpacked" + text.Replace("\\", "/");
                                if (File.Exists(text2))
                                {
                                    try
                                    {
                                        LogVerify.Deleted("File: " + text2);
                                        File.Delete(text2);
                                    }
                                    catch (Exception Error)
                                    {
                                        LogVerify.Error("File: " + text2 + " Error: " + Error.Message);
                                        LogVerify.ErrorIC("File: " + text2 + " Error: " + Error.HResult);
                                        LogVerify.ErrorFR("File: " + text2 + " Error: " + Error.ToString());
                                    }
                                }

                                try
                                {
                                    if (!new FileInfo(text2).Directory.Exists)
                                    {
                                        new FileInfo(text2).Directory.Create();
                                    }
                                }
                                catch (Exception Error) { LogToFileAddons.OpenLog("VERIFY HASH File Info", null, Error, null, true); }

                                Uri URLCall = new Uri(address);
                                int Timeout = (int)TimeSpan.FromMinutes(5).TotalMilliseconds;

                                if (address.Contains("copspeechdat"))
                                {
                                    Timeout = (int)TimeSpan.FromMinutes(30).TotalMilliseconds;
                                }
                                else if (address.Contains("nfs09mx.mus"))
                                {
                                    Timeout = (int)TimeSpan.FromMinutes(15).TotalMilliseconds;
                                }

                                ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = Timeout;

                                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.DownloadProgressChanged += (Systems, RecevingData) =>
                                {
                                    if (RecevingData.TotalBytesToReceive >= 1 && !ForceStopScan)
                                    {
                                        DownloadProgressText.SafeInvokeAction(() =>
                                                                              DownloadProgressText.Text = "Downloading File [ " + redownloadedCount + " / " +
                                                                                                          currentCount + " ]:\n" + CurrentDownloadingFile + "\n" + TimeConversions.FormatFileSize(RecevingData.BytesReceived) +
                                                                                                          " of " + TimeConversions.FormatFileSize(RecevingData.TotalBytesToReceive));
                                    }
                                    else if (ForceStopScan)
                                    {
                                        Client.CancelAsync();
                                    }
                                };
                                Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);

                                try
                                {
                                    Client.DownloadFileAsync(URLCall, text2);
                                    CurrentDownloadingFile = text;
                                    StillDownloading       = true;
                                }
                                catch (Exception Error)
                                {
                                    if (!ForceStopScan)
                                    {
                                        redownloadErrorCount++;
                                    }
                                    LogToFileAddons.OpenLog("VERIFY HASH", null, Error, null, true);
                                }
                                finally
                                {
                                    if (Client != null)
                                    {
                                        Client.Dispose();
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch (Exception Error)
                        {
                            if (!ForceStopScan)
                            {
                                redownloadErrorCount++;
                            }
                            LogToFileAddons.OpenLog("VERIFY HASH", null, Error, null, true);
                        }
                        finally
                        {
                            if (IsVerifyHashOpen)
                            {
                                Application.DoEvents();
                                GC.Collect();
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
Пример #16
0
        private static void Start()
        {
            DiscordLauncherPresence.Start("Start Up", null);

            if (!UnixOS.Detected())
            {
                DiscordLauncherPresence.Status("Start Up", "Checking .NET Framework");
                try
                {
                    /* Check if User has a compatible .NET Framework Installed */
                    if (int.TryParse(RegistryCore.Read("Release", @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"), out int NetFrame_Version))
                    {
                        /* For now, allow edge case of Windows 8.0 to run .NET 4.6.1 where upgrading to 8.1 is not possible */
                        if (WindowsProductVersion.GetWindowsNumber() == 6.2 && NetFrame_Version <= 394254)
                        {
                            if (MessageBox.Show(null, Translations.Database("Program_TextBox_NetFrame_P1") +
                                                " .NETFramework, Version=v4.6.1 \n\n" + Translations.Database("Program_TextBox_NetFrame_P2"),
                                                "GameLauncher.exe - " + Translations.Database("Program_TextBox_NetFrame_P3"),
                                                MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                            {
                                Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net461");
                            }

                            FunctionStatus.LauncherForceClose = true;
                        }
                        /* Otherwise, all other OS Versions should have 4.6.2 as a Minimum Version */
                        else if (NetFrame_Version <= 394802)
                        {
                            if (MessageBox.Show(null, Translations.Database("Program_TextBox_NetFrame_P1") +
                                                " .NETFramework, Version=v4.6.2 \n\n" + Translations.Database("Program_TextBox_NetFrame_P2"),
                                                "GameLauncher.exe - " + Translations.Database("Program_TextBox_NetFrame_P3"),
                                                MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                            {
                                Process.Start("https://dotnet.microsoft.com/download/dotnet-framework");
                            }

                            FunctionStatus.LauncherForceClose = true;
                        }
                        else
                        {
                            Log.System("NET-FRAMEWORK: Supported Installed Version");
                        }
                    }
                    else
                    {
                        Log.Warning("NET-FRAMEWORK: Failed to Parse Version");
                    }
                }
                catch
                {
                    FunctionStatus.LauncherForceClose = true;
                }
            }

            if (FunctionStatus.LauncherForceClose)
            {
                FunctionStatus.ErrorCloseLauncher("Closing From .NET Framework Check", false);
            }
            else
            {
                /* Splash Screen */
                if (!Debugger.IsAttached)
                {
                    /* Starts Splash Screen */
                    SplashScreen.ThreadStatus("Start");
                }

                LogToFileAddons.RemoveLogs();
                Log.StartLogging();

                Log.Info("CURRENT DATE: " + Time.GetTime("Date"));
                Log.Checking("LAUNCHER MIGRATION: Appdata and/or Roaming Folders");
                /* Deletes Folders that will Crash the Launcher (Cleanup Migration) */
                try
                {
                    if (Directory.Exists(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "Soapbox_Race_World"))))
                    {
                        Directory.Delete(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "Soapbox_Race_World")), true);
                    }
                    if (Directory.Exists(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "Soapbox_Race_World"))))
                    {
                        Directory.Delete(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "Soapbox_Race_World")), true);
                    }
                    if (Directory.Exists(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "SoapBoxRaceWorld"))))
                    {
                        Directory.Delete(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "SoapBoxRaceWorld")), true);
                    }
                    if (Directory.Exists(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "SoapBoxRaceWorld"))))
                    {
                        Directory.Delete(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "SoapBoxRaceWorld")), true);
                    }
                    if (Directory.Exists(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "WorldUnited.gg"))))
                    {
                        Directory.Delete(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "WorldUnited.gg")), true);
                    }
                    if (Directory.Exists(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "WorldUnited.gg"))))
                    {
                        Directory.Delete(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "WorldUnited.gg")), true);
                    }
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("LAUNCHER MIGRATION", null, Error, null, true);
                }
                Log.Completed("LAUNCHER MIGRATION");

                Log.Checking("LAUNCHER XML: If File Exists or Not");
                DiscordLauncherPresence.Status("Start Up", "Checking if UserSettings XML Exists");
                /* Create Default Configuration Files (if they don't already exist) */
                if (!File.Exists(Locations.UserSettingsXML))
                {
                    try
                    {
                        if (!Directory.Exists(Locations.UserSettingsFolder))
                        {
                            Directory.CreateDirectory(Locations.UserSettingsFolder);
                        }

                        File.WriteAllBytes(Locations.UserSettingsXML, ExtractResource.AsByte("GameLauncher.Resources.UserSettings.UserSettings.xml"));
                    }
                    catch (Exception Error)
                    {
                        LogToFileAddons.OpenLog("LAUNCHER XML", null, Error, null, true);
                    }
                }
                Log.Completed("LAUNCHER XML");

                string Insider = string.Empty;
                if (EnableInsiderDeveloper.Allowed())
                {
                    Insider = "DEV TEST ";
                }
                else if (EnableInsiderBetaTester.Allowed())
                {
                    Insider = "BETA TEST ";
                }

                Log.Build(Insider + "BUILD: GameLauncher " + Application.ProductVersion + "_" + InsiderInfo.BuildNumberOnly());

                Log.Checking("OS: Detecting");
                DiscordLauncherPresence.Status("Start Up", "Checking Operating System");
                try
                {
                    if (UnixOS.Detected())
                    {
                        InformationCache.OSName = UnixOS.FullName();
                        Log.System("SYSTEM: Detected OS: " + InformationCache.OSName);
                    }
                    else
                    {
                        InformationCache.OSName = WindowsProductVersion.ConvertWindowsNumberToName();
                        Log.System("SYSTEM: Detected OS: " + InformationCache.OSName);
                        Log.System("SYSTEM: Windows Build: " + WindowsProductVersion.GetWindowsBuildNumber());
                        Log.System("SYSTEM: NT Version: " + Environment.OSVersion.VersionString);
                        Log.System("SYSTEM: Video Card: " + HardwareInfo.GPU.CardName());
                        Log.System("SYSTEM: Driver Version: " + HardwareInfo.GPU.DriverVersion());
                    }
                    Log.Completed("OS: Detected");
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("SYSTEM", null, Error, null, true);
                    FunctionStatus.LauncherForceCloseReason = "Code: 0\n" + Translations.Database("Program_TextBox_System_Detection") + "\n" + Error.Message;
                    FunctionStatus.LauncherForceClose       = true;
                }

                if (FunctionStatus.LauncherForceClose)
                {
                    FunctionStatus.ErrorCloseLauncher("Closing From Operating System Check", false);
                }
                else
                {
                    /* Set Launcher Directory */
                    Log.Checking("SETUP: Setting Launcher Folder Directory");
                    Directory.SetCurrentDirectory(Locations.LauncherFolder);
                    Log.Completed("SETUP: Current Directory now Set at -> " + Locations.LauncherFolder);

                    if (!UnixOS.Detected())
                    {
                        Log.Checking("FOLDER LOCATION: Checking Launcher Folder Directory");
                        DiscordLauncherPresence.Status("Start Up", "Checking Launcher Folder Locations");

                        switch (FunctionStatus.CheckFolder(Locations.LauncherFolder))
                        {
                        case FolderType.IsTempFolder:
                        case FolderType.IsUsersFolders:
                        case FolderType.IsProgramFilesFolder:
                        case FolderType.IsWindowsFolder:
                        case FolderType.IsRootFolder:
                            String Constructed_Msg = String.Empty;

                            Constructed_Msg += Translations.Database("Program_TextBox_Folder_Check_Launcher") + "\n\n";
                            Constructed_Msg += Translations.Database("Program_TextBox_Folder_Check_Launcher_P2") + "\n";
                            Constructed_Msg += "• X:\\GameLauncher.exe " + Translations.Database("Program_TextBox_Folder_Check_Launcher_P3") + "\n";
                            Constructed_Msg += "• C:\\Program Files\n";
                            Constructed_Msg += "• C:\\Program Files (x86)\n";
                            Constructed_Msg += "• C:\\Users " + Translations.Database("Program_TextBox_Folder_Check_Launcher_P4") + "\n";
                            Constructed_Msg += "• C:\\Windows\n\n";
                            Constructed_Msg += Translations.Database("Program_TextBox_Folder_Check_Launcher_P5") + "\n";
                            Constructed_Msg += "• 'C:\\Soapbox Race World' " + Translations.Database("Program_TextBox_Folder_Check_Launcher_P6") + " 'C:\\SBRW'\n";
                            Constructed_Msg += Translations.Database("Program_TextBox_Folder_Check_Launcher_P7") + "\n\n";

                            MessageBox.Show(null, Constructed_Msg, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            FunctionStatus.LauncherForceClose = true;
                            break;
                        }

                        Log.Completed("FOLDER LOCATION: Done");
                    }

                    if (FunctionStatus.LauncherForceClose)
                    {
                        FunctionStatus.ErrorCloseLauncher("Closing From Invalid Launcher Location", false);
                    }
                    else
                    {
                        Log.Checking("WRITE TEST: Launcher Folder Test");
                        if (!FunctionStatus.HasWriteAccessToFolder(Locations.LauncherFolder))
                        {
                            MessageBox.Show(Translations.Database("Program_TextBox_Folder_Write_Test"));
                        }
                        Log.Completed("WRITE TEST: Passed");

                        Log.Checking("INI FILES: Doing Nullsafe");
                        DiscordLauncherPresence.Status("Start Up", "Doing NullSafe ini Files");
                        FileSettingsSave.NullSafeSettings();
                        FileAccountSave.NullSafeAccount();
                        Log.Completed("INI FILES: Done");
                        /* Sets up Theming */
                        Theming.CheckIfThemeExists();

                        Log.Function("APPLICATION: Setting Language");
                        CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo(Translations.UI(Translations.Application_Language = FileSettingsSave.Lang.ToLower(), true));
                        Log.Completed("APPLICATION: Done Setting Language '" + Translations.UI(Translations.Application_Language) + "'");

                        /* Windows 7 TLS Check */
                        if (WindowsProductVersion.GetWindowsNumber() == 6.1)
                        {
                            Log.Checking("SSL/TLS: Windows 7 Detected");
                            DiscordLauncherPresence.Status("Start Up", "Checking Windows 7 SSL/TLS");

                            try
                            {
                                String MessageBoxPopupTLS = String.Empty;
                                string keyName            = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client";
                                string subKey             = "DisabledByDefault";

                                if (Registry.GetValue(keyName, subKey, null) == null)
                                {
                                    MessageBoxPopupTLS = Translations.Database("Program_TextBox_W7_TLS_P1") + "\n\n";

                                    MessageBoxPopupTLS += "- HKLM/SYSTEM/CurrentControlSet/Control/SecurityProviders\n  /SCHANNEL/Protocols/TLS 1.2/Client\n";
                                    MessageBoxPopupTLS += "- Value: DisabledByDefault -> 0\n\n";

                                    MessageBoxPopupTLS += Translations.Database("Program_TextBox_W7_TLS_P2") + "\n\n";
                                    MessageBoxPopupTLS += Translations.Database("Program_TextBox_W7_TLS_P3");

                                    /* There is only 'OK' Available because this IS Required */
                                    if (MessageBox.Show(null, MessageBoxPopupTLS, "SBRW Launcher",
                                                        MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
                                    {
                                        RegistryCore.Write("DisabledByDefault", 0x0,
                                                           @"SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client");
                                        MessageBox.Show(null, Translations.Database("Program_TextBox_W7_TLS_P4"),
                                                        "SBRW Launcher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }
                                    Log.Completed("SSL/TLS: Added Registry Key");
                                }
                                else
                                {
                                    Log.Completed("SSL/TLS: Done");
                                }
                            }
                            catch (Exception Error)
                            {
                                LogToFileAddons.OpenLog("SSL/TLS", null, Error, null, true);
                            }
                        }

                        /* Windows 7 HotFix Check */
                        if (WindowsProductVersion.GetWindowsNumber() == 6.1 && string.IsNullOrWhiteSpace(FileSettingsSave.Win7UpdatePatches))
                        {
                            Log.Checking("HotFixes: Windows 7 Detected");
                            DiscordLauncherPresence.Status("Start Up", "Checking Windows 7 HotFixes");

                            try
                            {
                                if (!ManagementSearcher.GetInstalledHotFix("KB3020369") || !ManagementSearcher.GetInstalledHotFix("KB3125574"))
                                {
                                    String MessageBoxPopupKB = String.Empty;
                                    MessageBoxPopupKB  = Translations.Database("Program_TextBox_W7_KB_P1") + "\n";
                                    MessageBoxPopupKB += Translations.Database("Program_TextBox_W7_KB_P2") + "\n\n";

                                    if (!ManagementSearcher.GetInstalledHotFix("KB3020369"))
                                    {
                                        MessageBoxPopupKB += "- " + Translations.Database("Program_TextBox_W7_KB_P3") + " KB3020369\n";
                                    }

                                    if (!ManagementSearcher.GetInstalledHotFix("KB3125574"))
                                    {
                                        MessageBoxPopupKB += "- " + Translations.Database("Program_TextBox_W7_KB_P3") + " KB3125574\n";
                                    }
                                    MessageBoxPopupKB += "\n" + Translations.Database("Program_TextBox_W7_KB_P4") + "\n";

                                    if (MessageBox.Show(null, MessageBoxPopupKB, "SBRW Launcher",
                                                        MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                                    {
                                        /* Since it's Informational we just need to know if they clicked 'OK' */
                                        FileSettingsSave.Win7UpdatePatches = "1";
                                    }
                                    else
                                    {
                                        /* or if they clicked 'Cancel' */
                                        FileSettingsSave.Win7UpdatePatches = "0";
                                    }

                                    FileSettingsSave.SaveSettings();
                                }

                                Log.Completed("HotFixes: Done");
                            }
                            catch (Exception Error)
                            {
                                LogToFileAddons.OpenLog("HotFixes", null, Error, null, true);
                            }
                        }
                    }

                    Log.Checking("JSON: Servers File");
                    try
                    {
                        if (File.Exists(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameOldServersJSON))))
                        {
                            if (File.Exists(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON))))
                            {
                                File.Delete(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)));
                            }

                            File.Move(
                                Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameOldServersJSON)),
                                Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)));
                            Log.Completed("JSON: Renaming Servers File");
                        }
                        else if (!File.Exists(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON))))
                        {
                            try
                            {
                                File.WriteAllText(
                                    Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)), "[]");
                                Log.Completed("JSON: Created Servers File");
                            }
                            catch (Exception Error)
                            {
                                LogToFileAddons.OpenLog("JSON SERVER FILE", null, Error, null, true);
                            }
                        }
                    }
                    catch (Exception Error)
                    {
                        LogToFileAddons.OpenLog("JSON SERVER FILE", null, Error, null, true);
                    }
                    Log.Checking("JSON: Done");

                    if (!string.IsNullOrWhiteSpace(FileSettingsSave.GameInstallation))
                    {
                        Log.Checking("CLEANLINKS: Game Path");
                        if (File.Exists(Locations.GameLinksFile))
                        {
                            ModNetHandler.CleanLinks(Locations.GameLinksFile, FileSettingsSave.GameInstallation);
                            Log.Completed("CLEANLINKS: Done");
                        }
                        else
                        {
                            Log.Completed("CLEANLINKS: Not Present");
                        }
                    }

                    Log.Checking("PROXY: Checking if Proxy Is Disabled from User Settings! It's value is " + FileSettingsSave.Proxy);
                    if (FileSettingsSave.Proxy == "0")
                    {
                        Log.Core("PROXY: Starting Proxy (From Startup)");
                        ServerProxy.Instance.Start("Splash Screen [Program.cs]");
                        Log.Completed("PROXY: Started");
                    }
                    else
                    {
                        Log.Completed("PROXY: Disabled");
                    }

                    Log.Info("REDISTRIBUTABLE: Moved to Function");
                    /* (Starts Function Chain) Check if Redistributable Packages are Installed */
                    Redistributable.Check();
                }
            }
        }
Пример #17
0
        public static void GetList()
        {
            Log.Checking("SERVER LIST CORE: Creating Server List");
            DiscordLauncherPresence.Status("Start Up", "Creating Server List");

            List <ServerList> serverInfos = new List <ServerList>();

            List <ServerList> CustomServerInfos = new List <ServerList>();

            try
            {
                serverInfos.AddRange(JsonConvert.DeserializeObject <List <ServerList> >(CachedJSONList));
                LoadedList = true;
            }
            catch (Exception Error)
            {
                LogToFileAddons.OpenLog("SERVER LIST CORE", null, Error, null, true);
                LoadedList = false;
            }
            finally
            {
                if (CachedJSONList != null)
                {
                    CachedJSONList = null;
                }
            }

            if (File.Exists(Locations.LauncherCustomServers))
            {
                try
                {
                    var fileItems = JsonConvert.DeserializeObject <List <ServerList> >
                                        (Strings.Encode(File.ReadAllText(Locations.LauncherCustomServers))) ?? new List <ServerList>();

                    if (fileItems.Count > 0)
                    {
                        fileItems.Select(si =>
                        {
                            si.ID        = string.IsNullOrWhiteSpace(si.ID) ? SHA.Hashes($"{si.Name}:{si.ID}:{si.IPAddress}") : si.ID;
                            si.IsSpecial = false;
                            si.Category  = string.IsNullOrWhiteSpace(si.Category) ? "CUSTOM" : si.Category;

                            return(si);
                        }).ToList().ForEach(si => CustomServerInfos.Add(si));
                        serverInfos.AddRange(CustomServerInfos);
                        LoadedList = true;
                    }
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("SERVER LIST CORE", null, Error, null, true);
                }
            }

            if (File.Exists("libOfflineServer.dll"))
            {
                serverInfos.Add(new ServerList
                {
                    Name      = "Offline Built-In Server",
                    Category  = "OFFLINE",
                    IsSpecial = false,
                    IPAddress = "http://localhost:4416/sbrw/Engine.svc",
                    ID        = "OFFLINE"
                });
            }

            if (Debugger.IsAttached)
            {
                serverInfos.Add(new ServerList
                {
                    Name      = "Local Debug Server",
                    Category  = "DEBUG",
                    IsSpecial = false,
                    IPAddress = "http://localhost:8680",
                    ID        = "DEV"
                });
            }

            try
            {
                if (serverInfos != null)
                {
                    if (serverInfos.Any())
                    {
                        /* Create Final Server List without Categories (All Servers) */
                        foreach (ServerList NoCatList in serverInfos)
                        {
                            if (NoCategoryList.FindIndex(i => string.Equals(i.Name, NoCatList.Name)) == -1)
                            {
                                NoCategoryList.Add(NoCatList);
                            }
                        }

                        if (CustomServerInfos.Count >= 1)
                        {
                            /* Create Final Server List without Categories (Custom Servers Only) */
                            foreach (ServerList NoCatList in CustomServerInfos)
                            {
                                if (NoCategoryList_CSO.FindIndex(i => string.Equals(i.Name, NoCatList.Name)) == -1)
                                {
                                    NoCategoryList_CSO.Add(NoCatList);
                                }
                            }
                        }

                        /* Create Rough Draft Server List with Categories */
                        List <ServerList> RawList = new List <ServerList>();

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

                        /* Create Final Server List with Categories */
                        foreach (ServerList CList in RawList)
                        {
                            if (CleanList.FindIndex(i => string.Equals(i.Name, CList.Name)) == -1)
                            {
                                CleanList.Add(CList);
                            }
                        }
                        Log.Completed("SERVER LIST CORE: Server List Done");
                    }
                    else
                    {
                        Log.Completed("SERVER LIST CORE: Server List has no Elements");
                    }
                }
                else
                {
                    Log.Completed("SERVER LIST CORE: Server List is NULL");
                }
            }
            catch (Exception Error)
            {
                LogToFileAddons.OpenLog("SERVER LIST CORE", null, Error, null, true);
            }

            Log.Info("CERTIFICATE STORE: Moved to Function");
            /* (Start Process) Check Up to Date Certificate Status */
            CertificateStore.Latest();
        }
        private void StartGameScanner()
        {
            DiscordLauncherPresence.Status("Verify Scan", null);
            Log.Info("VERIFY HASH: Checking and Deleting '.orig' Files and Symbolic Folders");
            ScanProgressText.SafeInvokeAction(() => ScanProgressText.Text = "Removing any '.orig' Files in Game Directory");

            /* START Show Warning Text */
            VerifyHashText.SafeInvokeAction(() =>
            {
                VerifyHashText.ForeColor = Theming.WinFormWarningTextForeColor;
                VerifyHashText.Text      = "Warning:\nIf '.orig' Files Exist\nIt will be Removed Permanently";
            });
            /* END Show Warning Text */

            try
            {
                DirectoryInfo InstallationDirectory = new DirectoryInfo(FileSettingsSave.GameInstallation);

                foreach (DirectoryInfo FoldersWeFound in InstallationDirectory.GetDirectories())
                {
                    if (!ForceStopScan)
                    {
                        foreach (FileInfo FoundFile in InstallationDirectory.EnumerateFiles("*.orig", SearchOption.AllDirectories))
                        {
                            if (!ForceStopScan)
                            {
                                try
                                {
                                    FoundFile.Delete();
                                    LogVerify.Deleted("File: " + FoundFile.Name);
                                }
                                catch (Exception Error)
                                {
                                    DeletionError++;
                                    LogVerify.Error("File: " + FoundFile.Name + " Error: " + Error.Message);
                                    LogVerify.ErrorIC("File: " + FoundFile.Name + " Error: " + Error.HResult);
                                    LogVerify.ErrorFR("File: " + FoundFile.Name + " Error: " + Error.ToString());
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        foreach (FileInfo FoundFile in FoldersWeFound.EnumerateFiles("*.orig", SearchOption.AllDirectories))
                        {
                            if (!ForceStopScan)
                            {
                                try
                                {
                                    FoundFile.Delete();
                                    LogVerify.Deleted("File: " + FoundFile.Name);
                                }
                                catch (Exception Error)
                                {
                                    DeletionError++;
                                    LogVerify.Error("File: " + FoundFile.Name + " Error: " + Error.Message);
                                    LogVerify.ErrorIC("File: " + FoundFile.Name + " Error: " + Error.HResult);
                                    LogVerify.ErrorFR("File: " + FoundFile.Name + " Error: " + Error.ToString());
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        foreach (DirectoryInfo FoundDirectory in InstallationDirectory.EnumerateDirectories())
                        {
                            if (!ForceStopScan)
                            {
                                if (ModNetHandler.IsSymbolic(FoundDirectory.FullName))
                                {
                                    if (Directory.Exists(FoundDirectory.FullName))
                                    {
                                        try
                                        {
                                            Directory.Delete(FoundDirectory.FullName, true);
                                            LogVerify.Deleted("Folder: " + FoundDirectory.Name);
                                        }
                                        catch (Exception Error)
                                        {
                                            DeletionError++;
                                            LogVerify.Error("Folder: " + FoundDirectory.Name + " Error: " + Error.Message);
                                            LogVerify.ErrorIC("Folder: " + FoundDirectory.Name + " Error: " + Error.HResult);
                                            LogVerify.ErrorFR("Folder: " + FoundDirectory.Name + " Error: " + Error.ToString());
                                        }
                                    }
                                    else if (File.Exists(FoundDirectory.FullName))
                                    {
                                        try
                                        {
                                            File.Delete(FoundDirectory.FullName);
                                            LogVerify.Deleted("File: " + FoundDirectory.Name);
                                        }
                                        catch (Exception Error)
                                        {
                                            DeletionError++;
                                            LogVerify.Error("File: " + FoundDirectory.Name + " Error: " + Error.Message);
                                            LogVerify.ErrorIC("File: " + FoundDirectory.Name + " Error: " + Error.HResult);
                                            LogVerify.ErrorFR("File: " + FoundDirectory.Name + " Error: " + Error.ToString());
                                        }
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        foreach (DirectoryInfo FoundDirectory in FoldersWeFound.EnumerateDirectories())
                        {
                            if (!ForceStopScan)
                            {
                                if (ModNetHandler.IsSymbolic(FoundDirectory.FullName))
                                {
                                    if (Directory.Exists(FoundDirectory.FullName))
                                    {
                                        try
                                        {
                                            Directory.Delete(FoundDirectory.FullName, true);
                                            LogVerify.Deleted("Folder: " + FoundDirectory.Name);
                                        }
                                        catch (Exception Error)
                                        {
                                            DeletionError++;
                                            LogVerify.Error("Folder: " + FoundDirectory.Name + " Error: " + Error.Message);
                                            LogVerify.ErrorIC("Folder: " + FoundDirectory.Name + " Error: " + Error.HResult);
                                            LogVerify.ErrorFR("Folder: " + FoundDirectory.Name + " Error: " + Error.ToString());
                                        }
                                    }
                                    else if (File.Exists(FoundDirectory.FullName))
                                    {
                                        try
                                        {
                                            File.Delete(FoundDirectory.FullName);
                                            LogVerify.Deleted("File: " + FoundDirectory.Name);
                                        }
                                        catch (Exception Error)
                                        {
                                            DeletionError++;
                                            LogVerify.Error("File: " + FoundDirectory.Name + " Error: " + Error.Message);
                                            LogVerify.ErrorIC("File: " + FoundDirectory.Name + " Error: " + Error.HResult);
                                            LogVerify.ErrorFR("File: " + FoundDirectory.Name + " Error: " + Error.ToString());
                                        }
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                if (Directory.Exists(Path.Combine(FileSettingsSave.GameInstallation, "scripts")) && !ForceStopScan)
                {
                    DirectoryInfo ScriptsFolder = new DirectoryInfo(Path.Combine(FileSettingsSave.GameInstallation, "scripts"));

                    if (ScriptsFolder.EnumerateFiles().Count() > 1)
                    {
                        if (MessageBox.Show("Verify Hash has found files in the Scripts folder.\n" +
                                            "If you have installed custom Scripts or have not installed any Scripts" +
                                            "\n\nClick Yes, to Allow Deletion of Files" +
                                            "\nClick No, to Skip Deletion of Files", "VerifyHash", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            foreach (FileInfo FoundFile in ScriptsFolder.EnumerateFiles())
                            {
                                if (FoundFile.Name != "LangPicker.ini")
                                {
                                    try
                                    {
                                        File.Delete(FoundFile.FullName);
                                        LogVerify.Deleted("File: " + FoundFile.Name);
                                    }
                                    catch (Exception Error)
                                    {
                                        DeletionError++;
                                        LogVerify.Error("File: " + FoundFile.Name + " Error: " + Error.Message);
                                        LogVerify.ErrorIC("File: " + FoundFile.Name + " Error: " + Error.HResult);
                                        LogVerify.ErrorFR("File: " + FoundFile.Name + " Error: " + Error.ToString());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception Error)
            {
                LogToFileAddons.OpenLog("VERIFY HASH", null, Error, null, true);
            }

            if (DeletionError != 0)
            {
                Log.Info("VERIFY HASH: Completed check for '.orig' Files and Symbolic Folders, BUT Encounterd a File or Folder Deletion Error. " +
                         "Check Verify.log for More Details");

                if (MessageBox.Show("Verify Hash has encountered File or Folder Deletion Errors.\n" +
                                    "Would you like to Open Verify.Log and Stop the Scanner?", "VerifyHash", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string LogFile = Strings.Encode(Locations.LogVerify);
                    if (File.Exists(LogFile))
                    {
                        Process.Start(LogFile);
                    }

                    StopScanner_Click(null, null);
                }
            }
            else
            {
                Log.Info("VERIFY HASH: Completed check for '.orig' Files and Symbolic Folders");
            }

            if (!ForceStopScan)
            {
                try
                {
                    FunctionStatus.IsVerifyHashDisabled = true;

                    String[] getFilesToCheck = { };

                    if (File.Exists("checksums.dat") && EnableInsiderDeveloper.Allowed())
                    {
                        /* Read Local checksums.dat */
                        getFilesToCheck = File.ReadAllLines("checksums.dat");
                    }
                    else
                    {
                        /* Fetch and Read Remote checksums.dat */
                        ScanProgressText.SafeInvokeAction(() => ScanProgressText.Text = "Downloading Checksums File");

                        Uri URLCall = new Uri(FinalCDNURL + "/unpacked/checksums.dat");
                        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)");
                        }

                        bool ErrorFree = true;

                        try
                        {
                            getFilesToCheck = Client.DownloadString(URLCall).Split('\n');
                        }
                        catch (Exception Error)
                        {
                            LogToFileAddons.OpenLog("VERIFY HASH CHECKSUMS", "Downloading of the Checksums File has Encountered an Error", Error, "Error", false);
                            ErrorFree = false;
                        }
                        finally
                        {
                            if (Client != null)
                            {
                                Client.Dispose();
                            }
                        }

                        if (ErrorFree)
                        {
                            File.WriteAllLines("checksums.dat", getFilesToCheck);
                        }
                        else
                        {
                            StopScanner_Click(null, null);
                        }
                    }

                    scannedHashes = new string[getFilesToCheck.Length][];
                    for (var i = 0; i < getFilesToCheck.Length; i++)
                    {
                        if (!ForceStopScan)
                        {
                            scannedHashes[i] = getFilesToCheck[i].Split(' ');
                        }
                        else
                        {
                            break;
                        }
                    }
                    filesToScan       = scannedHashes.Length;
                    totalFilesScanned = 0;

                    /* START Show Warning Text */
                    VerifyHashText.SafeInvokeAction(() =>
                    {
                        VerifyHashText.ForeColor = Theming.WinFormWarningTextForeColor;
                        VerifyHashText.Text      = "Warning:\n Stopping the Scan before it is complete\nWill result in needing to start over!";
                    });
                    /* END Show Warning Text */

                    foreach (string[] file in scannedHashes)
                    {
                        if (!ForceStopScan)
                        {
                            String FileHash       = file[0].Trim();
                            String FileName       = file[1].Trim();
                            String RealPathToFile = FileSettingsSave.GameInstallation + FileName;

                            if (!File.Exists(RealPathToFile))
                            {
                                InvalidFileList.Add(FileName);
                                LogVerify.Missing("File: " + FileName);
                            }
                            else
                            {
                                if (FileHash != SHA.Files(RealPathToFile).Trim())
                                {
                                    InvalidFileList.Add(FileName);
                                    LogVerify.Invalid("File: " + FileName);
                                }
                                else
                                {
                                    LogVerify.Valid("File: " + FileName);
                                }
                            }
                            totalFilesScanned++;
                            ScanProgressText.SafeInvokeAction(() => ScanProgressText.Text = "Scanning Files: " + (totalFilesScanned * 100 / getFilesToCheck.Length) + "%");
                            ScanProgressBar.SafeInvokeAction(() => ScanProgressBar.Value  = totalFilesScanned * 100 / getFilesToCheck.Length);
                        }
                        else
                        {
                            break;
                        }
                    }

                    Log.Info("VERIFY HASH: Scan Completed");
                    if (!InvalidFileList.Any() || ForceStopScan)
                    {
                        StartScanner.SafeInvokeAction(() => StartScanner.Visible      = false);
                        StopScanner.SafeInvokeAction(() => StopScanner.Visible        = false);
                        ScanProgressText.SafeInvokeAction(() => ScanProgressText.Text = ForceStopScan ? "User Stopped Scan." : "Scan Complete. No Files Missing or Invalid!");

                        /* Hide the DownloadProgressBar as un-needed */
                        DownloadProgressBar.SafeInvokeAction(() => DownloadProgressBar.Visible   = false);
                        DownloadProgressText.SafeInvokeAction(() => DownloadProgressText.Visible = false);
                        /* Update the player messaging that we're done */
                        VerifyHashText.SafeInvokeAction(() =>
                        {
                            if (!ForceStopScan)
                            {
                                VerifyHashText.ForeColor = Theming.WinFormSuccessTextForeColor;
                            }
                            VerifyHashText.Text = ForceStopScan ? "Verify Hash Scan Process has been Terminated" : "Excellent News! There are ZERO\nmissing or invalid Gamefiles!";
                        });

                        Integrity();
                        GameScanner(false);
                    }
                    else
                    {
                        ScanProgressText.SafeInvokeAction(() => ScanProgressText.Text = "Found Invalid or Missing Files");

                        File.WriteAllLines("invalidfiles.dat", InvalidFileList);
                        Log.Info("VERIFY HASH: Found Invalid or Missing Files and will Start File Downloader");
                        CorruptedFilesFound();
                    }
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("VERIFY HASH", null, Error, null, true);
                }
            }
        }