public static void RegisterText_LinkClicked(object sender, EventArgs e)
 {
     if (FunctionStatus.AllowRegistration)
     {
         if (!string.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.webSignupUrl))
         {
             Process.Start(InformationCache.SelectedServerJSON.webSignupUrl);
             MessageBox.Show(null, "A browser window has been opened to complete registration on " +
                             ServerListUpdater.ServerName("Register"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         else if (InformationCache.SelectedServerData.Name.ToUpper() == "WORLDUNITED OFFICIAL")
         {
             Process.Start("https://signup.worldunited.gg/" + ((!string.IsNullOrWhiteSpace(DiscordLauncherPresence.UserID) &&
                                                                DiscordLauncherPresence.UserID != "0") ? "?discordid=" + DiscordLauncherPresence.UserID : string.Empty));
             MessageBox.Show(null, "A browser window has been opened to complete registration on " +
                             InformationCache.SelectedServerData.Name, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         else
         {
             RegisterScreen.OpenScreen();
         }
     }
     else
     {
         MessageBox.Show(null, "Server seems to be Offline.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
 private void PreloadServerList()
 {
     if (FunctionStatus.ServerListStatus != "Loaded")
     {
         ServerListUpdater.GetList();
     }
 }
Beispiel #3
0
 /// <summary>
 /// Starts the UI updater threads/tasks.
 /// </summary>
 public static void StartUIUpdaters()
 {
     ConnectionStatusUpdater.StartThread();
     ServerListUpdater.StartThread();
     AccountInfoUpdater.StartTask();
     VersionUpdater.StartTask();
     ToastManager.StartThread();
     PingManager.StartThread();
 }
Beispiel #4
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();
     };
 }
        private void SplashScreen_Load(object sender, EventArgs e)
        {
            if (MainForm.Instance.Visible)
                StartPosition = FormStartPosition.CenterParent;
            else
                StartPosition = FormStartPosition.CenterScreen;

            Activate();
            BringToFront();
            Focus();

            _updater = new ServerListUpdater(this);
            _updater.Update();
        }
Beispiel #6
0
        public SelectServer()
        {
            InitializeComponent();
            SetVisuals();

            Version.Text = "Version: v" + Application.ProductVersion;

            //And one for keeping data about server, IP tbh
            ServerListRenderer.View          = View.Details;
            ServerListRenderer.FullRowSelect = true;

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

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

            ServerListRenderer.Columns.Add("Country");
            ServerListRenderer.Columns[2].Width     = 100;
            ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Center;

            ServerListRenderer.Columns.Add("Online");
            ServerListRenderer.Columns[3].Width     = 75;
            ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Center;

            ServerListRenderer.Columns.Add("Registered");
            ServerListRenderer.Columns[4].Width     = 85;
            ServerListRenderer.Columns[4].TextAlign = HorizontalAlignment.Center;

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

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

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

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

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

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

                        try
                        {
                            WebClient getdata            = new WebClient();
                            GetServerInformation content = JsonConvert.DeserializeObject <GetServerInformation>(getdata.DownloadString(serverurl));

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

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

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

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

                        Application.DoEvents();
                    }
                });
            })
            {
                IsBackground = true
            };

            newList.Start();

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

            ServerListRenderer.DoubleClick += new EventHandler((handler, args) =>
            {
                SelectedGameServerToRemember();
            });
        }
Beispiel #7
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();
            }
        }
        private void SetVisuals()
        {
            /*******************************/

            /* Set Font                     /
            *  /*******************************/

            FontFamily DejaVuSans     = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf");
            FontFamily DejaVuSansBold = FontWrapper.Instance.GetFontFamily("DejaVuSans-Bold.ttf");

            var MainFontSize = 9f * 96f / CreateGraphics().DpiY;

            if (UnixOS.Detected())
            {
                MainFontSize = 9f;
            }

            Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            ServerListRenderer.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            Loading.Font            = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            BtnAddServer.Font       = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            BtnRemoveServer.Font    = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            BtnSelectServer.Font    = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            BtnClose.Font           = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            Version.Font            = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);

            /********************************/

            /* Set Theme Colors & Images     /
            *  /********************************/

            ForeColor = Theming.WinFormTextForeColor;
            BackColor = Theming.WinFormTBGForeColor;

            Loading.ForeColor = Theming.WinFormWarningTextForeColor;
            Version.ForeColor = Theming.WinFormTextForeColor;

            ServerListRenderer.ForeColor = Theming.WinFormSecondaryTextForeColor;

            BtnAddServer.ForeColor = Theming.BlueForeColorButton;
            BtnAddServer.BackColor = Theming.BlueBackColorButton;
            BtnAddServer.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            BtnAddServer.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;

            BtnRemoveServer.ForeColor = CustomServersOnly ? Theming.BlueForeColorButton : Theming.GrayForeColorButton;
            BtnRemoveServer.BackColor = CustomServersOnly ? Theming.BlueBackColorButton : Theming.GrayBackColorButton;
            BtnRemoveServer.FlatAppearance.BorderColor        = CustomServersOnly ? Theming.BlueBorderColorButton : Theming.GrayBorderColorButton;
            BtnRemoveServer.FlatAppearance.MouseOverBackColor = CustomServersOnly ? Theming.BlueMouseOverBackColorButton : Theming.GrayMouseOverBackColorButton;

            BtnSelectServer.ForeColor = !CustomServersOnly ? Theming.BlueForeColorButton : Theming.GrayForeColorButton;
            BtnSelectServer.BackColor = !CustomServersOnly ? Theming.BlueBackColorButton : Theming.GrayBackColorButton;
            BtnSelectServer.FlatAppearance.BorderColor        = !CustomServersOnly ? Theming.BlueBorderColorButton : Theming.GrayBorderColorButton;
            BtnSelectServer.FlatAppearance.MouseOverBackColor = !CustomServersOnly ? Theming.BlueMouseOverBackColorButton : Theming.GrayMouseOverBackColorButton;

            BtnClose.ForeColor = Theming.BlueForeColorButton;
            BtnClose.BackColor = Theming.BlueBackColorButton;
            BtnClose.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            BtnClose.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;

            /********************************/

            /* Functions                     /
            *  /********************************/

            Name = (CustomServersOnly ? "Saved Custom Servers" : "Please Select a Server") + " - SBRW Launcher";
            ServerListRenderer.AllowColumnReorder   = false;
            ServerListRenderer.ColumnWidthChanging += (handler, args) =>
            {
                args.Cancel   = true;
                args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width;
            };
            ServerListRenderer.DoubleClick += new EventHandler((handler, args) =>
            {
                if (!CustomServersOnly)
                {
                    SelectedGameServerToRemember();
                }
            });
            BtnSelectServer.Click += new EventHandler(BtnSelectServer_Click);
            BtnRemoveServer.Click += new EventHandler(BtnRemoveServer_Click);

            Version.Text = "Version: v" + Application.ProductVersion;

            /* And one for keeping data about server, IP tbh */
            ServerListRenderer.View          = View.Details;
            ServerListRenderer.FullRowSelect = true;

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

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

            ServerListRenderer.Columns.Add("Country");
            ServerListRenderer.Columns[2].Width     = 100;
            ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Center;

            ServerListRenderer.Columns.Add("Online");
            ServerListRenderer.Columns[3].Width     = 75;
            ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Center;

            ServerListRenderer.Columns.Add("Registered");
            ServerListRenderer.Columns[4].Width     = 85;
            ServerListRenderer.Columns[4].TextAlign = HorizontalAlignment.Center;

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

            foreach (ServerList substring in CustomServersOnly ? ServerListUpdater.NoCategoryList_CSO : ServerListUpdater.NoCategoryList)
            {
                try
                {
                    ServersToPing.Enqueue(ID + "_|||_" + substring.IPAddress + "_|||_" + substring.Name);

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

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

            Shown += (x, y) =>
            {
                Application.OpenForms[this.Name].Activate();
                this.BringToFront();

                new Thread(() =>
                {
                    while (ServersToPing.Count != 0)
                    {
                        string QueueContent    = ServersToPing.Dequeue();
                        string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None);

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

                        try
                        {
                            try
                            {
                                Uri URLCall = new Uri(serverurl);
                                ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
                                var Client = new WebClient
                                {
                                    Encoding = Encoding.UTF8
                                };

                                if (!WebCalls.Alternative())
                                {
                                    Client = new WebClientWithTimeout {
                                        Encoding = Encoding.UTF8
                                    };
                                }
                                else
                                {
                                    Client.Headers.Add("user-agent", "SBRW Launcher " +
                                                       Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                                }

                                try
                                {
                                    ServerJson = Client.DownloadString(serverurl);
                                }
                                catch { }
                                finally
                                {
                                    if (Client != null)
                                    {
                                        Client.Dispose();
                                    }
                                }
                            }
                            catch { }

                            if (string.IsNullOrWhiteSpace(ServerJson))
                            {
                                ServerListRenderer.SafeInvokeAction(() =>
                                {
                                    ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName;
                                    ServerListRenderer.Items[serverid].SubItems[2].Text = "---";
                                    ServerListRenderer.Items[serverid].SubItems[3].Text = "---";
                                    ServerListRenderer.Items[serverid].SubItems[4].Text = "---";
                                    ServerListRenderer.Items[serverid].SubItems[5].Text = "---";
                                }, this);
                            }
                            else if (!IsJSONValid.ValidJson(ServerJson))
                            {
                                ServerListRenderer.SafeInvokeAction(() =>
                                {
                                    ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName;
                                    ServerListRenderer.Items[serverid].SubItems[2].Text = "-?-";
                                    ServerListRenderer.Items[serverid].SubItems[3].Text = "-?-";
                                    ServerListRenderer.Items[serverid].SubItems[4].Text = "-?-";
                                    ServerListRenderer.Items[serverid].SubItems[5].Text = "-?-";
                                }, this);
                            }
                            else
                            {
                                ServerJsonData = JsonConvert.DeserializeObject <GetServerInformation>(ServerJson);

                                ServerListRenderer.SafeInvokeAction(() =>
                                {
                                    ServerListRenderer.Items[serverid].SubItems[1].Text = (!string.IsNullOrWhiteSpace(ServerJsonData.serverName)) ?
                                                                                          ServerJsonData.serverName : ServerName;
                                    ServerListRenderer.Items[serverid].SubItems[2].Text = ServerListUpdater.CountryName(ServerJsonData.country.ToString());
                                    ServerListRenderer.Items[serverid].SubItems[3].Text = ServerJsonData.onlineNumber.ToString();
                                    ServerListRenderer.Items[serverid].SubItems[4].Text = ServerJsonData.numberOfRegistered.ToString();
                                }, this);

                                Ping CheckMate = null;

                                try
                                {
                                    Uri StringToUri = new Uri(serverurl);
                                    ServicePointManager.FindServicePoint(StringToUri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
                                    CheckMate = new Ping();
                                    CheckMate.PingCompleted += (sender3, e3) =>
                                    {
                                        if (e3.Reply != null)
                                        {
                                            if (e3.Reply.Status == IPStatus.Success && ServerName != "Offline Built-In Server")
                                            {
                                                ServerListRenderer.SafeInvokeAction(() =>
                                                {
                                                    ServerListRenderer.Items[serverid].SubItems[5].Text = e3.Reply.RoundtripTime + "ms";
                                                }, this);
                                            }
                                            else
                                            {
                                                ServerListRenderer.SafeInvokeAction(() =>
                                                {
                                                    ServerListRenderer.Items[serverid].SubItems[5].Text = "!?";
                                                }, this);
                                            }
                                        }
                                        else
                                        {
                                            ServerListRenderer.SafeInvokeAction(() =>
                                            {
                                                ServerListRenderer.Items[serverid].SubItems[5].Text = "N/A";
                                            }, this);
                                        }

                                        ((AutoResetEvent)e3.UserState).Set();
                                    };
                                    CheckMate.SendAsync(StringToUri.Host, 5000, new byte[1], new PingOptions(30, true), new AutoResetEvent(false));
                                }
                                catch
                                {
                                    ServerListRenderer.SafeInvokeAction(() =>
                                    {
                                        ServerListRenderer.Items[serverid].SubItems[5].Text = "?";
                                    }, this);
                                }
                                finally
                                {
                                    if (CheckMate != null)
                                    {
                                        CheckMate.Dispose();
                                    }
                                }
                            }
                        }
                        catch
                        {
                            ServerListRenderer.SafeInvokeAction(() =>
                            {
                                ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName;
                                ServerListRenderer.Items[serverid].SubItems[2].Text = "---";
                                ServerListRenderer.Items[serverid].SubItems[3].Text = "---";
                                ServerListRenderer.Items[serverid].SubItems[4].Text = "---";
                                ServerListRenderer.Items[serverid].SubItems[5].Text = "---";
                            }, this);
                        }
                        finally
                        {
                            if (ServerJson != null)
                            {
                                ServerJson = null;
                            }
                            if (ServerJsonData != null)
                            {
                                ServerJsonData = null;
                            }
                            if (ServerName != null)
                            {
                                ServerName = null;
                            }

                            GC.Collect();
                        }

                        Application.DoEvents();
                    }

                    Loading.SafeInvokeAction(() =>
                    {
                        Loading.Text = string.Empty;
                    }, this);
                }).Start();
            };
        }
Beispiel #9
0
        /// <summary>
        /// Sets the current Status of the Launcher's State
        /// </summary>
        /// <remarks>RPC Status</remarks>
        /// <param name="State">Which RPC Status Text to Set</param>
        /// <param name="Status">Additional RPC Status Details to Display</param>
        public static void Status(string State, string Status)
        {
            try
            {
                ButtonsList.Clear();
                ButtonsList.Add(new DiscordButton()
                {
                    Label = "Project Site",
                    Url   = "https://soapboxrace.world"
                });
                ButtonsList.Add(new DiscordButton()
                {
                    Label = "Launcher Patch Notes",
                    Url   = "https://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases/tag/" + Theming.PrivacyRPCBuild
                });
                Presence.Buttons = ButtonsList.ToArray();

                if (State == "Start Up")
                {
                    Presence.State   = Status;
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw"
                    };
                }
                else if (State == "Unpack Game Files")
                {
                    Download         = true;
                    Presence.State   = Status;
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw",
                        SmallImageText = string.Empty,
                        SmallImageKey  = "files_success"
                    };
                    Presence.Buttons = ButtonsList.ToArray();
                }
                else if (State == "Download Game Files")
                {
                    Download         = true;
                    Presence.State   = Status;
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw",
                        SmallImageText = string.Empty,
                        SmallImageKey  = "files"
                    };
                    Presence.Buttons = ButtonsList.ToArray();
                }
                else if (State == "Download Game Files Error")
                {
                    Download         = true;
                    Presence.State   = "Game Download Error";
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw",
                        SmallImageText = string.Empty,
                        SmallImageKey  = "files_error"
                    };
                    Presence.Buttons = ButtonsList.ToArray();
                }
                else if (State == "Idle Ready")
                {
                    Presence.State   = "Ready To Race";
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw",
                        SmallImageText = string.Empty,
                        SmallImageKey  = !string.IsNullOrWhiteSpace(CertificateStore.LauncherSerial) ? "official" : "unofficial"
                    };
                    Presence.Buttons = ButtonsList.ToArray();
                }
                else if (State == "Checking ModNet")
                {
                    Presence.State   = "Checking ModNet";
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw",
                        SmallImageText = string.Empty,
                        SmallImageKey  = "files_alert"
                    };
                    Presence.Buttons = ButtonsList.ToArray();
                }
                else if (State == "ModNet File Check Passed")
                {
                    Presence.State   = "Has ModNet File: " + Status;
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw",
                        SmallImageText = string.Empty,
                        SmallImageKey  = "files_success"
                    };
                    Presence.Buttons = ButtonsList.ToArray();
                }
                else if (State == "Download ModNet")
                {
                    Presence.State   = "Downloading ModNet Files";
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw",
                        SmallImageText = string.Empty,
                        SmallImageKey  = "files"
                    };
                    Presence.Buttons = ButtonsList.ToArray();
                }
                else if (State == "Download ModNet Error")
                {
                    Presence.State   = "ModNet Encounterd an Error";
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw",
                        SmallImageText = string.Empty,
                        SmallImageKey  = "files_error"
                    };
                    Presence.Buttons = ButtonsList.ToArray();
                }
                else if (State == "Download Server Mods")
                {
                    Presence.State   = "Downloading Server Mods";
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw",
                        SmallImageText = string.Empty,
                        SmallImageKey  = "files"
                    };
                    Presence.Buttons = ButtonsList.ToArray();
                }
                else if (State == "Download Server Mods Error")
                {
                    Presence.State   = "Server Mod Download Error";
                    Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                    Presence.Assets  = new Assets
                    {
                        LargeImageText = "Launcher",
                        LargeImageKey  = "nfsw",
                        SmallImageText = string.Empty,
                        SmallImageKey  = "files_error"
                    };
                    Presence.Buttons = ButtonsList.ToArray();
                }

                if (Download == false)
                {
                    if (State == "Security Center")
                    {
                        Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                        Presence.State   = "On Security Center Screen";
                        Presence.Assets  = new Assets
                        {
                            LargeImageText = "Launcher",
                            LargeImageKey  = "nfsw",
                            SmallImageText = SecurityCenter.SecurityCenterRPC(1),
                            SmallImageKey  = SecurityCenter.SecurityCenterRPC(0)
                        };
                    }
                    else if (State == "Register")
                    {
                        Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                        Presence.State   = "On Registration Screen";
                        Presence.Assets  = new Assets
                        {
                            LargeImageText = "Launcher",
                            LargeImageKey  = "nfsw",
                            SmallImageText = string.Empty,
                            SmallImageKey  = "screen_register"
                        };
                    }
                    else if (State == "Settings")
                    {
                        Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                        Presence.State   = "On Settings Screen";
                        Presence.Assets  = new Assets
                        {
                            LargeImageText = "Launcher",
                            LargeImageKey  = "nfsw",
                            SmallImageText = string.Empty,
                            SmallImageKey  = "screen_settings"
                        };
                    }
                    else if (State == "User XML Editor")
                    {
                        Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                        Presence.State   = "On User XML Editor Screen";
                        Presence.Assets  = new Assets
                        {
                            LargeImageText = "Launcher",
                            LargeImageKey  = "nfsw",
                            SmallImageText = string.Empty,
                            SmallImageKey  = "screen_uxe"
                        };
                    }
                    else if (State == "Verify")
                    {
                        Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                        Presence.State   = "On Verify Game Files Screen";
                        Presence.Assets  = new Assets
                        {
                            LargeImageText = "Launcher",
                            LargeImageKey  = "nfsw",
                            SmallImageText = string.Empty,
                            SmallImageKey  = "screen_verify"
                        };
                    }
                    else if (State == "Verify Scan")
                    {
                        Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                        Presence.State   = "Verifying Game Files";
                        Presence.Assets  = new Assets
                        {
                            LargeImageText = "Launcher",
                            LargeImageKey  = "nfsw",
                            SmallImageText = string.Empty,
                            SmallImageKey  = "verify_files_scan"
                        };
                    }
                    else if (State == "Verify Bad")
                    {
                        Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                        Presence.State   = "Downloaded " + Status + " Missing Game Files";
                        Presence.Assets  = new Assets
                        {
                            LargeImageText = "Launcher",
                            LargeImageKey  = "nfsw",
                            SmallImageText = string.Empty,
                            SmallImageKey  = "verify_files_bad"
                        };
                    }
                    else if (State == "Verify Good")
                    {
                        Presence.Details = "In-Launcher: " + Theming.PrivacyRPCBuild;
                        Presence.State   = "Finished Validating Game Files";
                        Presence.Assets  = new Assets
                        {
                            LargeImageText = "Launcher",
                            LargeImageKey  = "nfsw",
                            SmallImageText = string.Empty,
                            SmallImageKey  = "verify_files_good"
                        };
                    }
                    else if (State == "In-Game")
                    {
                        Presence.State   = ServerListUpdater.ServerName("RPC");
                        Presence.Details = "In-Game";
                        Presence.Assets  = new Assets
                        {
                            LargeImageText = "Need for Speed: World",
                            LargeImageKey  = "nfsw",
                            SmallImageText = string.Empty,
                            SmallImageKey  = "ingame"
                        };

                        if (!String.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.homePageUrl) ||
                            !String.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.discordUrl) ||
                            !String.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.webPanelUrl))
                        {
                            ButtonsList.Clear();

                            if (!String.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.webPanelUrl))
                            {
                                /* Let's format it now, if possible */
                                ButtonsList.Add(new DiscordButton()
                                {
                                    Label = "View Panel",
                                    Url   = InformationCache.SelectedServerJSON.webPanelUrl.Split(new string[] { "{sep}" }, StringSplitOptions.None)[0]
                                });
                            }
                            else if (!String.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.homePageUrl) &&
                                     InformationCache.SelectedServerJSON.homePageUrl != InformationCache.SelectedServerJSON.discordUrl)
                            {
                                ButtonsList.Add(new DiscordButton()
                                {
                                    Label = "Website",
                                    Url   = InformationCache.SelectedServerJSON.homePageUrl
                                });
                            }

                            if (!String.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.discordUrl))
                            {
                                ButtonsList.Add(new DiscordButton()
                                {
                                    Label = "Discord",
                                    Url   = InformationCache.SelectedServerJSON.discordUrl
                                });
                            }
                        }

                        Presence.Buttons = ButtonsList.ToArray();
                    }
                }

                if (Running() && InformationCache.SelectedServerCategory != "DEV")
                {
                    Client.SetPresence(Presence);
                }
            }
            catch (Exception Error)
            {
                LogToFileAddons.OpenLog("DISCORD", null, Error, null, true);
            }
        }
Beispiel #10
0
 /// <summary>
 /// Terminates UI updater threads/tasks on FxA account logout.
 /// </summary>
 public static void TerminateUIUpdaters()
 {
     ConnectionStatusUpdater.StopThread();
     ServerListUpdater.StopThread();
     AccountInfoUpdater.StopTask();
 }
Beispiel #11
0
        private void RegisterButton_Click(object sender, EventArgs e)
        {
            Refresh();

            List <string> registerErrors = new List <string>();

            if (string.IsNullOrWhiteSpace(RegisterEmail.Text))
            {
                registerErrors.Add("Please enter your e-mail.");
                RegisterEmailBorder.Image = Theming.BorderEmailError;
            }
            else if (!IsEmailValid.Validate(RegisterEmail.Text))
            {
                registerErrors.Add("Please enter a valid e-mail address.");
                RegisterEmailBorder.Image = Theming.BorderEmailError;
            }

            if (string.IsNullOrWhiteSpace(RegisterTicket.Text) && _ticketRequired)
            {
                registerErrors.Add("Please enter your ticket.");
                RegisterTicketBorder.Image = Theming.BorderTicketError;
            }

            if (string.IsNullOrWhiteSpace(RegisterPassword.Text))
            {
                registerErrors.Add("Please enter your password.");
                RegisterPasswordBorder.Image = Theming.BorderPasswordError;
            }

            if (string.IsNullOrWhiteSpace(RegisterConfirmPassword.Text))
            {
                registerErrors.Add("Please confirm your password.");
                RegisterConfirmPasswordBorder.Image = Theming.BorderPasswordError;
            }

            if (RegisterConfirmPassword.Text != RegisterPassword.Text)
            {
                registerErrors.Add("Passwords don't match.");
                RegisterConfirmPasswordBorder.Image = Theming.BorderPasswordError;
            }

            if (!RegisterAgree.Checked)
            {
                registerErrors.Add("You have not agreed to the Terms of Service.");
                RegisterAgree.ForeColor = Theming.Error;
            }

            if (registerErrors.Count == 0)
            {
                bool allowReg = false;

                String Email;
                String Password;

                switch (Authentication.HashType(InformationCache.SelectedServerJSON.authHash ?? string.Empty))
                {
                case AuthHash.H10:
                    Email    = RegisterEmail.Text.ToString();
                    Password = RegisterPassword.Text.ToString();
                    break;

                case AuthHash.H11:
                    Email    = RegisterEmail.Text.ToString();
                    Password = MDFive.Hashes(RegisterPassword.Text.ToString()).ToLower();
                    break;

                case AuthHash.H12:
                    Email    = RegisterEmail.Text.ToString();
                    Password = SHA.Hashes(RegisterPassword.Text.ToString()).ToLower();
                    break;

                case AuthHash.H13:
                    Email    = RegisterEmail.Text.ToString();
                    Password = SHATwoFiveSix.Hashes(RegisterPassword.Text.ToString()).ToLower();
                    break;

                case AuthHash.H20:
                    Email    = MDFive.Hashes(RegisterEmail.Text.ToString()).ToLower();
                    Password = MDFive.Hashes(RegisterPassword.Text.ToString()).ToLower();
                    break;

                case AuthHash.H21:
                    Email    = SHA.Hashes(RegisterEmail.Text.ToString()).ToLower();
                    Password = SHA.Hashes(RegisterPassword.Text.ToString()).ToLower();
                    break;

                case AuthHash.H22:
                    Email    = SHATwoFiveSix.Hashes(RegisterEmail.Text.ToString()).ToLower();
                    Password = SHATwoFiveSix.Hashes(RegisterPassword.Text.ToString()).ToLower();
                    break;

                default:
                    Log.Error("HASH TYPE: Unknown Hash Standard was Provided");
                    return;
                }

                try
                {
                    string[] regex = new Regex(@"([0-9A-Z]{5})([0-9A-Z]{35})").Split(Password.ToUpper());

                    Uri URLCall = new Uri("https://api.pwnedpasswords.com/range/" + regex[1]);
                    ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
                    var Client = new WebClient
                    {
                        Encoding = Encoding.UTF8
                    };
                    if (!WebCalls.Alternative())
                    {
                        Client = new WebClientWithTimeout {
                            Encoding = Encoding.UTF8
                        };
                    }
                    else
                    {
                        Client.Headers.Add("user-agent", "SBRW Launcher " +
                                           Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                    }

                    String serverReply = null;
                    try
                    {
                        serverReply = Client.DownloadString(URLCall);
                    }
                    catch (WebException Error)
                    {
                        APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped),
                                               Error, (HttpWebResponse)Error.Response);
                    }
                    catch (Exception Error)
                    {
                        LogToFileAddons.OpenLog("Register", null, Error, null, true);
                    }
                    finally
                    {
                        if (Client != null)
                        {
                            Client.Dispose();
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(serverReply))
                    {
                        String verify = regex[2];

                        string[] hashes = serverReply.Split('\n');
                        foreach (string hash in hashes)
                        {
                            var splitChecks = hash.Split(':');
                            if (splitChecks[0] == verify)
                            {
                                var passwordCheckReply = MessageBox.Show(null, "Password used for registration has been breached " + Convert.ToInt32(splitChecks[1]) +
                                                                         " times, you should consider using a different one.\n\nAlternatively you can use the unsafe password anyway." +
                                                                         "\nWould you like to continue to use it?", "GameLauncher", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                                if (passwordCheckReply == DialogResult.Yes)
                                {
                                    allowReg = true;
                                }
                                else
                                {
                                    allowReg = false;
                                }
                            }
                            else
                            {
                                allowReg = true;
                            }
                        }
                    }
                    else
                    {
                        allowReg = true;
                    }
                }
                catch
                {
                    allowReg = true;
                }

                if (allowReg)
                {
                    Tokens.Clear();

                    Tokens.IPAddress  = InformationCache.SelectedServerData.IPAddress;
                    Tokens.ServerName = ServerListUpdater.ServerName("Register");

                    Authentication.Client("Register", InformationCache.SelectedServerJSON.modernAuthSupport, Email, Password, _ticketRequired ? RegisterTicket.Text : null);

                    if (!String.IsNullOrWhiteSpace(Tokens.Success))
                    {
                        DialogResult Success = MessageBox.Show(null, Tokens.Success, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        if (Success == DialogResult.OK)
                        {
                            Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show(null, Tokens.Error, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    var message = "There were some errors while registering. Please fix them:\n\n";

                    foreach (var error in registerErrors)
                    {
                        message += "• " + error + "\n";
                    }

                    MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #12
0
        private void SetVisuals()
        {
            /*******************************/

            /* Set Window Name              /
            *  /*******************************/

            Text = "Register - SBRW Launcher: v" + Application.ProductVersion;

            /*******************************/

            /* Set Initial position & Icon  /
            *  /*******************************/

            FunctionStatus.CenterParent(this);

            /*******************************/

            /* Set Font                     /
            *  /*******************************/

            FontFamily DejaVuSans     = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf");
            FontFamily DejaVuSansBold = FontWrapper.Instance.GetFontFamily("DejaVuSans-Bold.ttf");

            float MainFontSize      = UnixOS.Detected() ? 9f : 9f * 96f / CreateGraphics().DpiY;
            float SecondaryFontSize = UnixOS.Detected() ? 8f : 8f * 96f / CreateGraphics().DpiY;

            Font = new Font(DejaVuSans, SecondaryFontSize, FontStyle.Regular);

            /* Registering Panel */
            RegisterEmail.Font           = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            RegisterPassword.Font        = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            RegisterConfirmPassword.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            RegisterTicket.Font          = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            RegisterAgree.Font           = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            RegisterButton.Font          = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            RegisterCancel.Font          = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            CurrentWindowInfo.Font       = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);

            /********************************/

            /* Set Theme Colors & Images     /
            *  /********************************/

            /* Set Background with Transparent Key */
            BackgroundImage = Theming.RegisterScreen;
            TransparencyKey = Theming.RegisterScreenTransparencyKey;

            CurrentWindowInfo.ForeColor = Theming.FivithTextForeColor;

            RegisterEmail.BackColor   = Theming.Input;
            RegisterEmail.ForeColor   = Theming.FivithTextForeColor;
            RegisterEmailBorder.Image = Theming.BorderEmail;

            RegisterPasswordBorder.Image = Theming.BorderPassword;
            RegisterPassword.BackColor   = Theming.Input;
            RegisterPassword.ForeColor   = Theming.FivithTextForeColor;

            RegisterConfirmPasswordBorder.Image = Theming.BorderPassword;
            RegisterConfirmPassword.BackColor   = Theming.Input;
            RegisterConfirmPassword.ForeColor   = Theming.FivithTextForeColor;

            RegisterTicketBorder.Image = Theming.BorderTicket;
            RegisterTicket.BackColor   = Theming.Input;
            RegisterTicket.ForeColor   = Theming.FivithTextForeColor;

            RegisterAgree.ForeColor = Theming.WinFormWarningTextForeColor;

            RegisterButton.BackgroundImage = Theming.GreenButton;
            RegisterButton.ForeColor       = Theming.SeventhTextForeColor;

            RegisterCancel.BackgroundImage = Theming.GrayButton;
            RegisterCancel.ForeColor       = Theming.FivithTextForeColor;

            /********************************/

            /* Events                        /
            *  /********************************/

            RegisterEmail.TextChanged           += new EventHandler(RegisterEmail_TextChanged);
            RegisterPassword.TextChanged        += new EventHandler(RegisterPassword_TextChanged);
            RegisterConfirmPassword.TextChanged += new EventHandler(RegisterConfirmPassword_TextChanged);
            RegisterTicket.TextChanged          += new EventHandler(RegisterTicket_TextChanged);
            RegisterAgree.CheckedChanged        += new EventHandler(RegisterAgree_CheckedChanged);

            RegisterButton.MouseEnter += Greenbutton_hover_MouseEnter;
            RegisterButton.MouseLeave += Greenbutton_MouseLeave;
            RegisterButton.MouseUp    += Greenbutton_hover_MouseUp;
            RegisterButton.MouseDown  += Greenbutton_click_MouseDown;
            RegisterButton.Click      += RegisterButton_Click;

            RegisterCancel.MouseEnter += new EventHandler(Graybutton_hover_MouseEnter);
            RegisterCancel.MouseLeave += new EventHandler(Graybutton_MouseLeave);
            RegisterCancel.MouseUp    += new MouseEventHandler(Graybutton_hover_MouseUp);
            RegisterCancel.MouseDown  += new MouseEventHandler(Graybutton_click_MouseDown);
            RegisterCancel.Click      += new EventHandler(RegisterCancel_Click);

            /********************************/

            /* Functions                     /
            *  /********************************/

            CurrentWindowInfo.Text = "REGISTER ON \n" + ServerListUpdater.ServerName("Register").ToUpper();

            try
            {
                if (InformationCache.SelectedServerJSON.requireTicket != null && !string.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.requireTicket))
                {
                    _ticketRequired = InformationCache.SelectedServerJSON.requireTicket.ToLower() == "true";
                }
                else
                {
                    _ticketRequired = false;
                }
            }
            catch { }

            /* Show Ticket Box if its Required  */
            RegisterTicket.Visible       = _ticketRequired;
            RegisterTicketBorder.Visible = _ticketRequired;
        }
Beispiel #13
0
        private static void ShowMainScreen()
        {
            if (VisualsAPIChecker.WOPLAPI == false)
            {
                DialogResult restartAppNoApis = MessageBox.Show(null, "There's no internet connection, Launcher might crash \n \nClick Yes to Close Launcher \nor \nClick No Continue", "GameLauncher has Stopped, Failed To Connect To API", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (restartAppNoApis == DialogResult.No)
                {
                    MessageBox.Show("Good Luck... \n No Really \n ...Good Luck", "GameLauncher Will Continue, When It Failed To Connect To API");
                    Log.Warning("PRE-CHECK: User has Bypassed 'No Internet Connection' Check and Will Continue");
                }

                if (restartAppNoApis == DialogResult.Yes)
                {
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }
            }

            ServerListUpdater.GetList();
            CDNListUpdater.GetList();
            LauncherUpdateCheck.CheckAvailability();

            if (!DetectLinux.LinuxDetected())
            {
                //Install Custom Root Certificate
                CertificateStore.Check();

                if (!File.Exists("GameLauncherUpdater.exe"))
                {
                    Log.Info("LAUNCHER UPDATER: Starting GameLauncherUpdater downloader");
                    try
                    {
                        using (WebClient wc = new WebClient())
                        {
                            wc.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
                            {
                                if (new FileInfo("GameLauncherUpdater.exe").Length == 0)
                                {
                                    File.Delete("GameLauncherUpdater.exe");
                                }
                            };
                            wc.DownloadFile(new Uri("https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("LAUCHER UPDATER: Failed to download updater. " + ex.Message);
                    }
                }
                else if (File.Exists("GameLauncherUpdater.exe"))
                {
                    String GameLauncherUpdaterLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameLauncherUpdater.exe");
                    var    LauncherUpdaterBuild        = FileVersionInfo.GetVersionInfo(GameLauncherUpdaterLocation);
                    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 GameLauncherUpdater.exe");
                        File.Delete("GameLauncherUpdater.exe");

                        try
                        {
                            using (WebClient wc = new WebClient())
                            {
                                wc.DownloadFile(new Uri("https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe");
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error("LAUNCHER UPDATER: Failed to download new updater. " + ex.Message);
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(FileSettingsSave.GameInstallation))
            {
                var linksPath = Path.Combine(FileSettingsSave.GameInstallation + "\\.links");
                ModNetLinksCleanup.CleanLinks(linksPath);
            }

            Log.Info("PROXY: Starting Proxy");
            ServerProxy.Instance.Start();

            Log.Visuals("CORE: Starting MainScreen");
            Application.Run(new MainScreen());
        }
Beispiel #14
0
        private static void DoRunChecks(Arguments args)
        {
            /* Splash Screen */
            if (!Debugger.IsAttached && !DetectLinux.LinuxDetected())
            {
                _SplashScreen = new Thread(new ThreadStart(SplashScreen));
                _SplashScreen.Start();
            }

            File.Delete("communication.log");
            File.Delete("launcher.log");
            Log.StartLogging();

            if (!DetectLinux.LinuxDetected())
            {
                //Check if User has .NETFramework 4.6.2 or later Installed
                const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";

                using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
                {
                    if (ndpKey != null && ndpKey.GetValue("Release") != null && (int)ndpKey.GetValue("Release") >= 394802)
                    {
                        /* Check Up to Date Certificate Status */
                        try
                        {
                            WebClient update_data = new WebClient();
                            update_data.CancelAsync();
                            update_data.Headers.Add("user-agent", "GameLauncher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                            update_data.DownloadStringAsync(new Uri("http://crl.carboncrew.org/RCA-Info.json"));
                            update_data.DownloadStringCompleted += (sender, e) => {
                                JsonRootCA API = JsonConvert.DeserializeObject <JsonRootCA>(e.Result);

                                if (API.CN != null)
                                {
                                    Log.Info("CERTIFICATE STORE: Setting Common Name -> " + API.CN);
                                    CertificateStore.RootCACommonName = API.CN;
                                }

                                if (API.Subject != null)
                                {
                                    Log.Info("CERTIFICATE STORE: Setting Subject Name -> " + API.Subject);
                                    CertificateStore.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);
                                            CertificateStore.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);
                                            CertificateStore.RootCAFileName = entries.Name;
                                        }

                                        if (entries.Cer != null)
                                        {
                                            Log.Info("CERTIFICATE STORE: Setting Root CA File URL -> " + entries.Cer);
                                            CertificateStore.RootCAFileURL = entries.Cer;
                                        }
                                    }
                                }
                            };
                        }
                        catch
                        {
                            Log.Error("CERTIFICATE STORE: Unable to Retrive Latest Certificate Information");
                        }
                    }
                    else
                    {
                        DialogResult frameworkError = MessageBox.Show(null, "This application requires one of the following versions of the .NET Framework:\n" +
                                                                      " .NETFramework, Version=v4.6.2 \n\nDo you want to install this .NET Framework version now?", "GameLauncher.exe - This application could not be started.", MessageBoxButtons.YesNo, MessageBoxIcon.Error);

                        if (frameworkError == DialogResult.Yes)
                        {
                            Process.Start("https://dotnet.microsoft.com/download/dotnet-framework");
                        }

                        /* Close Splash Screen (Just in Case) */
                        if (IsSplashScreenLive == true)
                        {
                            _SplashScreen.Abort();
                        }

                        Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                    }
                }
            }

            FileSettingsSave.NullSafeSettings();
            FileAccountSave.NullSafeAccount();

            FunctionStatus.CurrentLanguage        = CultureInfo.CurrentCulture.Name.Split('-')[0].ToUpper();
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture("en-US");
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");

            if (UriScheme.IsCommandLineArgumentsInstalled())
            {
                UriScheme.InstallCommandLineArguments(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), AppDomain.CurrentDomain.FriendlyName));
                if (args.Parse != null)
                {
                    new UriScheme(args.Parse);
                }
            }

            if (EnableInsider.ShouldIBeAnInsider() == true)
            {
                Log.Build("INSIDER: GameLauncher " + Application.ProductVersion + "_" + EnableInsider.BuildNumber());
            }
            else
            {
                Log.Build("BUILD: GameLauncher " + Application.ProductVersion);
            }

            if (Properties.Settings.Default.IsRestarting)
            {
                Properties.Settings.Default.IsRestarting = false;
                Properties.Settings.Default.Save();
                Thread.Sleep(3000);
            }

            if (!DetectLinux.LinuxDetected())
            {
                //Windows Firewall Runner
                if (!string.IsNullOrEmpty(FileSettingsSave.FirewallStatus))
                {
                    if (FirewallManager.IsServiceRunning == true && FirewallHelper.FirewallStatus() == true)
                    {
                        string nameOfLauncher  = "SBRW - Game Launcher";
                        string localOfLauncher = Assembly.GetEntryAssembly().Location;

                        string nameOfUpdater  = "SBRW - Game Launcher Updater";
                        string localOfUpdater = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "GameLauncherUpdater.exe");

                        string groupKeyLauncher    = "Game Launcher for Windows";
                        string descriptionLauncher = "Soapbox Race World";

                        bool removeFirewallRule = false;
                        bool firstTimeRun       = false;

                        if (FileSettingsSave.FirewallStatus == "Not Excluded" || FileSettingsSave.FirewallStatus == "Turned Off" || FileSettingsSave.FirewallStatus == "Service Stopped" || FileSettingsSave.FirewallStatus == "Unknown")
                        {
                            firstTimeRun = true;
                            FileSettingsSave.FirewallStatus = "Excluded";
                        }
                        else if (FileSettingsSave.FirewallStatus == "Reset")
                        {
                            removeFirewallRule = true;
                            FileSettingsSave.FirewallStatus = "Not Excluded";
                        }

                        //Inbound & Outbound
                        FirewallHelper.DoesRulesExist(removeFirewallRule, firstTimeRun, nameOfLauncher, localOfLauncher, groupKeyLauncher, descriptionLauncher, FirewallProtocol.Any);
                        FirewallHelper.DoesRulesExist(removeFirewallRule, firstTimeRun, nameOfUpdater, localOfUpdater, groupKeyLauncher, descriptionLauncher, FirewallProtocol.Any);

                        //This Removes the Game File Exe From Firewall
                        //To Find the one that Adds the Exe To Firewall -> Search for `OnDownloadFinished()`
                        string CurrentGameFilesExePath = Path.Combine(FileSettingsSave.GameInstallation + "\\nfsw.exe");

                        if (File.Exists(CurrentGameFilesExePath) && removeFirewallRule == true)
                        {
                            string nameOfGame  = "SBRW - Game";
                            string localOfGame = CurrentGameFilesExePath;

                            string groupKeyGame    = "Need for Speed: World";
                            string descriptionGame = groupKeyGame;

                            //Inbound & Outbound
                            FirewallHelper.DoesRulesExist(removeFirewallRule, firstTimeRun, nameOfGame, localOfGame, groupKeyGame, descriptionGame, FirewallProtocol.Any);
                        }
                    }
                    else if (FirewallManager.IsServiceRunning == true && FirewallHelper.FirewallStatus() == false)
                    {
                        FileSettingsSave.FirewallStatus = "Turned Off";
                    }
                    else
                    {
                        FileSettingsSave.FirewallStatus = "Service Stopped";
                    }

                    FileSettingsSave.SaveSettings();
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);

            /* Set Launcher Directory */
            Log.Info("CORE: Setting up current directory: " + Path.GetDirectoryName(Application.ExecutablePath));
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            if (!DetectLinux.LinuxDetected())
            {
                Log.Info("CORE: Checking current directory");

                switch (FunctionStatus.CheckFolder(Directory.GetCurrentDirectory()))
                {
                case FolderType.IsTempFolder:
                case FolderType.IsUsersFolders:
                case FolderType.IsProgramFilesFolder:
                case FolderType.IsWindowsFolder:
                case FolderType.IsRootFolder:
                    String constructMsg = String.Empty;

                    constructMsg += "Bu Dizinde NFS World Dosyaları Yok.\nLütfen Bu Başlatıcı Dosyalarını oyunun Dosyalarının Olduğu dizine atın NOT:\n\n";
                    constructMsg += "• X:\\ (Anadizin, veya C:\\ ve D:\\)\n";
                    constructMsg += "• C:\\Program Files\n";
                    constructMsg += "• C:\\Program Files (x86)\n";
                    constructMsg += "• C:\\Kullanıcı ('Masaüstü' veya 'Belgeler')\n";
                    constructMsg += "• C:\\Windows\n\n";
                    constructMsg += "Dizinlerine Kurmayınız!";
                    MessageBox.Show(null, constructMsg, "NFSTR.Com Başlatıcı", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    Environment.Exit(0);
                    break;
                }

                if (!FunctionStatus.HasWriteAccessToFolder(Path.GetDirectoryName(Application.ExecutablePath)))
                {
                    MessageBox.Show("Bu Uygulama Admin Yetkileri Gerektirir");
                }

                //Update this text file if a new GameLauncherUpdater.exe has been delployed - DavidCarbon
                try
                {
                    try
                    {
                        switch (APIStatusChecker.CheckStatus("http://api.github.com/repos/SoapboxRaceWorld/GameLauncherUpdater/releases/latest"))
                        {
                        case APIStatus.Online:
                            WebClient update_data = new WebClient();
                            update_data.CancelAsync();
                            update_data.Headers.Add("user-agent", "GameLauncher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                            update_data.DownloadStringAsync(new Uri("http://api.github.com/repos/SoapboxRaceWorld/GameLauncherUpdater/releases/latest"));
                            update_data.DownloadStringCompleted += (sender, e) => {
                                GitHubRelease GHAPI = JsonConvert.DeserializeObject <GitHubRelease>(e.Result);

                                if (GHAPI.TagName != null)
                                {
                                    Log.Info("LAUNCHER UPDATER: Setting Latest Version -> " + GHAPI.TagName);
                                    LatestUpdaterBuildVersion = GHAPI.TagName;
                                }
                                Log.Info("LAUNCHER UPDATER: Latest Version -> " + LatestUpdaterBuildVersion);
                            };
                            break;

                        default:
                            Log.Error("LAUNCHER UPDATER: Failed to Retrive Latest Updater Information from GitHub");
                            break;
                        }
                    }
                    catch
                    {
                        var GetLatestUpdaterBuildVersion = new WebClient().DownloadString(URLs.secondstaticapiserver + "/Version.txt");
                        if (!string.IsNullOrEmpty(GetLatestUpdaterBuildVersion))
                        {
                            Log.Info("LAUNCHER UPDATER: Setting Latest Version -> " + GetLatestUpdaterBuildVersion);
                            LatestUpdaterBuildVersion = GetLatestUpdaterBuildVersion;
                        }
                    }
                    Log.Info("LAUNCHER UPDATER: Fail Safe Latest Version -> " + LatestUpdaterBuildVersion);
                }
                catch (Exception ex)
                {
                    Log.Error("LAUNCHER UPDATER: Failed to get new version file: " + ex.Message);
                }
            }

            if (!DetectLinux.LinuxDetected())
            {
                //Windows 7 Fix
                if (WindowsProductVersion.GetWindowsNumber() == 6.1 && (string.IsNullOrEmpty(FileSettingsSave.Win7UpdatePatches)))
                {
                    if (ManagementSearcher.GetInstalledHotFix("KB3020369") == false || ManagementSearcher.GetInstalledHotFix("KB3125574") == false)
                    {
                        String messageBoxPopupKB = String.Empty;
                        messageBoxPopupKB  = "Hey Windows 7 User, we've detected a potential issue of some missing Updates that are required.\n";
                        messageBoxPopupKB += "We found that these Windows Update packages are showing as not installed:\n\n";

                        if (ManagementSearcher.GetInstalledHotFix("KB3020369") == false)
                        {
                            messageBoxPopupKB += "- Update KB3020369\n";
                        }
                        if (ManagementSearcher.GetInstalledHotFix("KB3125574") == false)
                        {
                            messageBoxPopupKB += "- Update KB3125574\n";
                        }

                        messageBoxPopupKB += "\nAditionally, we must add a value to the registry:\n";

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

                        messageBoxPopupKB += "Would you like to add those values?";
                        DialogResult replyPatchWin7 = MessageBox.Show(null, messageBoxPopupKB, "SBRW Launcher", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                        if (replyPatchWin7 == DialogResult.Yes)
                        {
                            RegistryKey key = Registry.LocalMachine.CreateSubKey(@"SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client");
                            key.SetValue("DisabledByDefault", 0x0);

                            MessageBox.Show(null, "Registry option set, Remember that the changes may require a system reboot to take effect", "SBRW Launcher", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            FileSettingsSave.Win7UpdatePatches = "1";
                        }
                        else
                        {
                            MessageBox.Show(null, "Roger that, There may be some issues connecting to the servers.", "SBRW Launcher", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            FileSettingsSave.Win7UpdatePatches = "0";
                        }

                        FileSettingsSave.SaveSettings();
                    }
                }

                if (!RedistributablePackage.IsInstalled(RedistributablePackageVersion.VC2015to2019x86))
                {
                    var result = MessageBox.Show(
                        "You do not have the 32-bit 2015-2019 VC++ Redistributable Package installed.\n \nThis will install in the Background\n \nThis may restart your computer. \n \nClick OK to install it.",
                        "Compatibility",
                        MessageBoxButtons.OKCancel,
                        MessageBoxIcon.Warning);

                    if (result != DialogResult.OK)
                    {
                        MessageBox.Show("The game will not be started.", "Compatibility", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return;
                    }

                    var wc = new WebClient();
                    wc.DownloadFile("https://aka.ms/vs/16/release/VC_redist.x86.exe", "VC_redist.x86.exe");
                    var proc = Process.Start(new ProcessStartInfo
                    {
                        Verb      = "runas",
                        Arguments = "/quiet",
                        FileName  = "VC_redist.x86.exe"
                    });

                    if (proc == null)
                    {
                        MessageBox.Show("Failed to run package installer. The game will not be started.", "Compatibility", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return;
                    }
                }

                if (Environment.Is64BitOperatingSystem == true)
                {
                    if (!RedistributablePackage.IsInstalled(RedistributablePackageVersion.VC2015to2019x64))
                    {
                        var result = MessageBox.Show(
                            "You do not have the 64-bit 2015-2019 VC++ Redistributable Package installed.\n \nThis will install in the Background\n \nThis may restart your computer. \n \nClick OK to install it.",
                            "Compatibility",
                            MessageBoxButtons.OKCancel,
                            MessageBoxIcon.Warning);

                        if (result != DialogResult.OK)
                        {
                            MessageBox.Show("The game will not be started.", "Compatibility", MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                            return;
                        }

                        var wc = new WebClient();
                        wc.DownloadFile("https://aka.ms/vs/16/release/VC_redist.x64.exe", "VC_redist.x64.exe");
                        var proc = Process.Start(new ProcessStartInfo
                        {
                            Verb      = "runas",
                            Arguments = "/quiet",
                            FileName  = "VC_redist.x64.exe"
                        });

                        if (proc == null)
                        {
                            MessageBox.Show("Failed to run package installer. The game will not be started.", "Compatibility", MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                            return;
                        }
                    }
                }
            }

            Console.WriteLine("Application path: " + Path.GetDirectoryName(Application.ExecutablePath));

            if (!string.IsNullOrEmpty(FileSettingsSave.GameInstallation))
            {
                if (!FunctionStatus.HasWriteAccessToFolder(FileSettingsSave.GameInstallation))
                {
                    MessageBox.Show("This application requires admin priviledge. Restarting...");
                }
            }

            //StaticConfiguration.DisableErrorTraces = false;

            if (!File.Exists("servers.json"))
            {
                try
                {
                    File.WriteAllText("servers.json", "[]");
                }
                catch { /* ignored */ }
            }

            if (Properties.Settings.Default.IsRestarting)
            {
                Properties.Settings.Default.IsRestarting = false;
                Properties.Settings.Default.Save();
                Thread.Sleep(3000);
            }

            Theming.CheckIfThemeExists();

            /* Check If Launcher Failed to Connect to any APIs */
            if (VisualsAPIChecker.WOPLAPI == false)
            {
                DialogResult restartAppNoApis = MessageBox.Show(null, "There's no internet connection, Launcher might crash \n \nClick Yes to Close Launcher \nor \nClick No Continue", "GameLauncher has Stopped, Failed To Connect To API", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (restartAppNoApis == DialogResult.No)
                {
                    MessageBox.Show("Good Luck... \n No Really \n ...Good Luck", "GameLauncher Will Continue, When It Failed To Connect To API");
                    Log.Warning("PRE-CHECK: User has Bypassed 'No Internet Connection' Check and Will Continue");
                }

                if (restartAppNoApis == DialogResult.Yes)
                {
                    /* Close Splash Screen (Just in Case) */
                    if (IsSplashScreenLive == true)
                    {
                        _SplashScreen.Abort();
                    }

                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }
            }

            LanguageListUpdater.GetList();
            LauncherUpdateCheck.CheckAvailability();

            if (!DetectLinux.LinuxDetected())
            {
                //Install Custom Root Certificate
                CertificateStore.Check();

                if (!File.Exists("GameLauncherUpdater.exe"))
                {
                    Log.Info("LAUNCHER UPDATER: Starting GameLauncherUpdater downloader");
                    try
                    {
                        using (WebClient wc = new WebClient())
                        {
                            wc.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
                            {
                                if (new FileInfo("GameLauncherUpdater.exe").Length == 0)
                                {
                                    File.Delete("GameLauncherUpdater.exe");
                                }
                            };
                            wc.DownloadFile(new Uri("https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("LAUCHER UPDATER: Failed to download updater. " + ex.Message);
                    }
                }
                else if (File.Exists("GameLauncherUpdater.exe"))
                {
                    String GameLauncherUpdaterLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameLauncherUpdater.exe");
                    var    LauncherUpdaterBuild        = FileVersionInfo.GetVersionInfo(GameLauncherUpdaterLocation);
                    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 GameLauncherUpdater.exe");
                        File.Delete("GameLauncherUpdater.exe");

                        try
                        {
                            using (WebClient wc = new WebClient())
                            {
                                wc.DownloadFile(new Uri("https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe");
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error("LAUNCHER UPDATER: Failed to download new updater. " + ex.Message);
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(FileSettingsSave.GameInstallation))
            {
                var linksPath = Path.Combine(FileSettingsSave.GameInstallation + "\\.links");
                ModNetLinksCleanup.CleanLinks(linksPath);
            }

            /* Check Permission for Launcher Folder and File it Self */
            FileORFolderPermissions.CheckLauncherPerms("Folder", Path.Combine(AppDomain.CurrentDomain.BaseDirectory));

            Log.Info("PROXY: Starting Proxy");
            ServerProxy.Instance.Start();

            /* Check ServerList Status */

            if (FunctionStatus.ServerListStatus != "Loaded")
            {
                ServerListUpdater.GetList();
            }

            /* Close Splash Screen */
            if (IsSplashScreenLive == true)
            {
                _SplashScreen.Abort();
            }

            Log.Visuals("CORE: Starting MainScreen");
            Application.Run(new MainScreen());
        }
        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);
        }
Beispiel #16
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (NFSW.IsNFSWRunning())
            {
                if (NFSW.DetectGameProcess())
                {
                    MessageBox.Show(null, "An instance of Need for Speed: World is already running", UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    MessageBox.Show(null, "An instance of SBRW Launcher is already running.", UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
            }
            else
            {
                var mutex = new Mutex(false, UserAgent.AgentName);
                try
                {
                    if (mutex.WaitOne(0, false))
                    {
                        if (!File.Exists("nfsw.exe"))
                        {
                            MessageBox.Show("nfsw.exe not found! Please put this launcher in the game directory. " +
                                            "If you don't have the game installed, Use the Vanilla Launcher to install it (visit https://soapboxrace.world/)",
                                            UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Error);

                            Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                        }
                        else
                        {
                            if (!canAccesGameData())
                            {
                                MessageBox.Show("This application requires admin priviledge. Restarting...");
                                runAsAdmin();
                                return;
                            }

                            if (SHA.HashFile("nfsw.exe") != "7C0D6EE08EB1EDA67D5E5087DDA3762182CDE4AC")
                            {
                                MessageBox.Show("Invalid file was detected, please restore original nfsw.exe", UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                if (File.Exists(".links"))
                                {
                                    var linksPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\.links");
                                    ModNetLinksCleanup.CleanLinks(linksPath);
                                }

                                ServicePointManager.Expect100Continue = true;
                                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                                ServerListUpdater.GetList();

                                Application.Run(new Form1());
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(null, "An instance of Launcher is already running.", UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                finally
                {
                    mutex.Close();
                }
            }
        }