public static bool OpenYS_Command_Moderation_ReloadSettings_Method(Client ThisClient, CommandReader Command)
 {
     Console.Locked = true;
     SettingsHandler.LoadAll();
     Console.Locked = false;
     Console.WriteLine("&aReloaded Settings.");
     return(true);
 }
예제 #2
0
            private static void Run(string[] args)
            {
                //Initialisation
                #region Initialisation
                Thread.CurrentThread.Name = "OpenYS Client Core";
                Threads.List.Add(Thread.CurrentThread);

                Console._LogOutput    = Log.ConsoleOutput;
                Console._Process      = CommandManager.ProcessConsole;
                Console.ConsolePrompt = "&cOpenYS&f->&f";
                Console.Locked        = true;

                if (Console.console_present)
                {
                    System.Console.CursorVisible = false;
                    System.Console.Clear();
                    System.Console.Title = "OpenYS - YSFlight Open Source Client";
                }

                #region OYS_Console
                OpenYS.OpenYSConsole.SetConsole();
                OpenYS.OpenYSConsole.SetFakeClient();
                OpenYS.OpenYSConsole.Username = Settings.Options.ConsoleName;
                OpenYS.OpenYSConsole.OP();
                #endregion
                #region OYS_BackgroundHandler
                OpenYS.OpenYSBackGround.SetController();
                OpenYS.OpenYSBackGround.SetFakeClient();
                OpenYS.OpenYSBackGround.Username = Settings.Options.SchedulerName;
                OpenYS.OpenYSBackGround.OP();
                #endregion


                Sequencers.Process = CommandManager.ProcessScheduler;
                Schedulers.Process = CommandManager.ProcessScheduler;

                OpenYS.BuildType          = OpenYS._BuildType.Client;
                Environment.EntryAssembly = Assembly.GetExecutingAssembly();
                #endregion

                //Begin Program.
                #region TRY:
#if RELEASE
                try {
#endif
                #endregion
                #region MAIN LOOP
                //Loading
                #region Loading
                #region ? Argument
                if (args.Length > 0)
                {
                    if (args[0] == "/?" | args[0] == "?")
                    {
                        if (Console.console_present)
                        {
                            System.Console.WriteLine("OpenYS Open Source Server Project. (C) OfficerFlake 2015");
                            System.Console.WriteLine("    ");
                            System.Console.WriteLine("    Usage: OpenYS_Client.exe [HostAddress] [HostPort] [ListenerPortNumber]");
                            System.Console.WriteLine("    ");
                            System.Console.WriteLine("Thanks for using OpenYS!");
                            System.Environment.Exit(0);
                        }
                    }
                }
                #endregion
                #region Clear Logs
                Files.FileDelete("./Logs/Client_Debug.Log");
                Files.FileDelete("./Logs/Console.Log");
                #endregion
                #region Introduction
                Console.WriteLine(ConsoleColor.Red, "Welcome to OpenYS Client!");
                Console.WriteLine();
                Console.WriteLine(ConsoleColor.DarkYellow, "This client allows your YSF Client to use the extended features of OpenYS!");
                Console.WriteLine();
                #endregion
                #region Version Number
                Console.WriteLine(ConsoleColor.Red, "You are using version:&e " + Environment.GetCompilationDate());
                Console.WriteLine();
                #endregion
                #region LoadSettings
                SettingsHandler.LoadAll();
                SettingsHandler.Monitor();
                #endregion
                #region InitialSettings
                OpenYS.OpenYSConsole.Username    = Settings.Options.ConsoleName;
                OpenYS.OpenYSBackGround.Username = Settings.Options.SchedulerName;
                OpenYS.Field = new Packets.Packet_04_FieldName(Settings.Loading.FieldName);
                #endregion
                #region Check Arguments
                CheckArguments(args);
                #endregion
                #region Load Commands
                Commands.LoadAll();
                #endregion
                #endregion

                //Connection Handling Services.
                #region Start Server
                Server.Listener.Start();
                OpenYS.YSFListener.ServerStarted.WaitOne();
                #endregion

                //Timing Services.
                #region Lock/Unlock Console Input
                Console.Locked = true;
                Console.WriteLine("\r");     //effectively refreshes the prompt...
                #endregion
                //Sequencers.LoadAll();
                //Schedulers.LoadAll();

                Thread.Sleep(Timeout.Infinite);
                Console.TerminateConsole("End Of Program");
                return;

                #endregion
                #region CATCH
#if RELEASE
            }

            catch (Exception e)
            {
                if (e is ThreadAbortException)
                {
                    return;
                }
                Log.Error(e);
                #region TRY:
#if RELEASE
                try
                {
#endif
                #endregion
                #region Terminate
                Console.Locked = true;
                Console.WriteLine(ConsoleColor.Red, "OpenYS Has been terminated with error:");
                Console.WriteLine();
                Console.WriteLine(Debug.GetStackTrace(e));
                Emailing.SendCrashReportEmail(e);
                Thread.Sleep(5000);
                //RemovePDB();
                System.Environment.Exit(0);
                Console.WriteLine();
                Console.Terminate.Set();
                Console.Reader.Abort();
                for (int i = 10 - 1; i > 0; i--)
                {
                    Console.WriteLine(String.Format("\r&cOpenYS Will Restart In &f{0}&c Seconds.   ", i + 1));
                    Thread.Sleep(1000);
                }
                Console.WriteLine(String.Format("\r&cOpenYS Will Restart In &f1&c Second.   "));
                Thread.Sleep(1000);
                for (int i = 3; i > 0; i--)
                {
                    Console.WriteLine("\r&c!!!&f OpenYS Restarting &c!!!                            ");
                    Thread.Sleep(500);
                    Console.WriteLine("\r                                                  ");
                    Thread.Sleep(500);
                }
                Environment.RestartNow();
                #endregion
                #region CATCH
#if RELEASE
            }
            catch (Exception e2)
            {
                Console.WriteLine("Safe Restart Failed... Sorry!");
                Console.WriteLine(e2.Message);
                Log.Error(e2);
                Thread.Sleep(Timeout.Infinite);
                Console.TerminateConsole("End Of Program");
                return;
            }
#endif
                #endregion
            }
#endif
                #endregion
            }
        protected override void OnLoad(EventArgs e)
        {
            Visible       = false; // Hide form window.
            ShowInTaskbar = false; // Remove from taskbar.

            base.OnLoad(e);
            SettingsHandler.LoadAll();
            Username_TextBox.Text     = Settings.YSFHQ.Username;
            Password_TextBox.Text     = Settings.YSFHQ.EncryptedPassword;
            Instructions_Label_1.Text = "Connect your YSFlight client to 127.0.0.1:" + Settings.Server.ListenerPort.ToString();
            Instructions_Label_2.Text = "To begin!";
            PasswordIsEncrypted       = true;
            if (Username_TextBox.Text == "" | Password_TextBox.Text == "")
            {
                Password_TextBox.Text = "";
                PasswordIsEncrypted   = false;
            }
            Application.DoEvents();

            if (Username_TextBox.Text != "" & Password_TextBox.Text != "")
            {
                Authenticate();
            }
            Application.DoEvents();


            //////////////////////////////////////////////
            // DO CLIENTSIDE STUFF
            //////////////////////////////////////////////

            //Initialisation
            #region Initialisation
            Thread.CurrentThread.Name = "OpenYS Client Core";
            Threads.List.Add(Thread.CurrentThread);

            Console._LogOutput    = Log.ConsoleOutput;
            Console._Process      = CommandManager.ProcessConsole;
            Console.ConsolePrompt = "&cOpenYS&f->&f";
            Console.Locked        = true;

            if (Console.console_present)
            {
                System.Console.CursorVisible = false;
                System.Console.Clear();
                System.Console.Title = "OpenYS - YSFlight Open Source Client";
            }

            #region OYS_Console
            OpenYS.OpenYSConsole.SetConsole();
            OpenYS.OpenYSConsole.SetFakeClient();
            OpenYS.OpenYSConsole.Username = Settings.Options.ConsoleName;
            OpenYS.OpenYSConsole.OP();
            #endregion
            #region OYS_BackgroundHandler
            OpenYS.OpenYSBackGround.SetController();
            OpenYS.OpenYSBackGround.SetFakeClient();
            OpenYS.OpenYSBackGround.Username = Settings.Options.SchedulerName;
            OpenYS.OpenYSBackGround.OP();
            #endregion


            Sequencers.Process = CommandManager.ProcessScheduler;
            Schedulers.Process = CommandManager.ProcessScheduler;

            OpenYS.BuildType          = OpenYS._BuildType.Client;
            Environment.EntryAssembly = Assembly.GetExecutingAssembly();
            #endregion

            Server.Listener.Start();
            OpenYS.YSFListener.ServerStarted.WaitOne();
            while (true)
            {
                Application.DoEvents();
            }

            //Try and start a proxy service!
        }
        private void Authenticate()
        {
            //Disable all inputs!
            Username_TextBox.Enabled             = false;
            Password_TextBox.Enabled             = false;
            Authentication_Button.Enabled        = false;
            ShowPassword_CheckBox.Enabled        = false;
            AuthenticationStatus_Label.Text      = "AUTHENTICATING...";
            AuthenticationStatus_Label.ForeColor = Color.FromArgb(240, 200, 0);
            AuthenticationStatus_Label.BackColor = Color.Transparent;
            OpenYS_Link.Stats._id = 0;
            Application.DoEvents();

            using (var client = new WebClient())
            {
                var values = new NameValueCollection();
                values["username"] = Username_TextBox.Text;

                if (PasswordIsEncrypted)
                {
                    values["password"] = OYS_Cryptography.DecryptPassword(Password_TextBox.Text);
                }
                else
                {
                    values["password"] = Password_TextBox.Text;
                }
                try
                {
                    //Key Verification:
                    //https://forum.ysfhq.com/api-check.php?apikey=

                    string APIKey = Environment.GetAPIKey();

                    if (APIKey == "MISSINGNO." | APIKey == "")
                    {
                        MessageBox.Show("APIKey not supplied for this custom build of OYS!\n\nTo get your own API Key, contact YSFHQ Webmasters, then place that key inside APIKey.txt, inside OpenYS-Library/Utilities!", "API Key Not Found!");
                        Username_TextBox.Enabled             = false;
                        Password_TextBox.Enabled             = false;
                        ShowPassword_CheckBox.Enabled        = false;
                        Authentication_Button.Enabled        = false; //leave this false, unable to authenticate without reloading!
                        AuthenticationStatus_Label.Text      = "API KEY MISSING";
                        AuthenticationStatus_Label.ForeColor = Color.FromArgb(128, 0, 0);
                        AuthenticationStatus_Label.BackColor = Color.FromArgb(240, 200, 0);
                        OpenYS_Link.Stats._id = 0;
                        Application.DoEvents();
                        return;
                    }

                    var response       = client.UploadValues("https://forum.ysfhq.com/api-login.php?apikey=" + APIKey, values);
                    var responseString = Encoding.Default.GetString(response);
                    System.Console.WriteLine(responseString);
                    bool Failed = !Int32.TryParse(responseString.Replace("\"", ""), out OpenYS_Link.Stats._id);

                    if (Failed | OpenYS_Link.Stats._id <= 0)
                    {
                        //NO GOOD!
                        Username_TextBox.Enabled             = true;
                        Password_TextBox.Enabled             = true;
                        ShowPassword_CheckBox.Enabled        = true;
                        Authentication_Button.Enabled        = true;
                        AuthenticationStatus_Label.Text      = "AUTHENTICATION FAIL!";
                        AuthenticationStatus_Label.ForeColor = Color.FromArgb(240, 0, 0);
                        AuthenticationStatus_Label.BackColor = Color.Transparent;
                        Application.DoEvents();
                        return;
                    }
                    else
                    {
                        //ALL GOOD!
                        if (!PasswordIsEncrypted)
                        {
                            //Only update if the password has been modified!

                            SettingsHandler.LoadAll();
                            Settings.YSFHQ.Username          = Username_TextBox.Text;
                            Settings.YSFHQ.EncryptedPassword = OYS_Cryptography.EncryptPassword(Password_TextBox.Text);
                            SettingsHandler.SaveAll();
                        }
                        Username_TextBox.Enabled             = true;
                        Password_TextBox.Enabled             = true;
                        ShowPassword_CheckBox.Enabled        = true;
                        Authentication_Button.Enabled        = true;
                        AuthenticationStatus_Label.Text      = "AUTHENTICATED";
                        AuthenticationStatus_Label.ForeColor = Color.FromArgb(0, 128, 0);
                        AuthenticationStatus_Label.BackColor = Color.Transparent;
                        Application.DoEvents();

                        OpenYS_Link.GetAllStats();

                        //OpenYS_Link.OYS_Link_Response Response = OpenYS_Link.Get(YSFHQ_ID, "/stats_total_flight_seconds");
                        //MessageBox.Show(Response.Response, Response.Reason);

                        //^^ WORKING!
                        return;
                    }
                }
                catch (System.Net.WebException WebError)
                {
                    HttpStatusCode ErrorCode = ((HttpWebResponse)WebError.Response).StatusCode;

                    if (ErrorCode == HttpStatusCode.BadRequest) //400
                    {
                        //Missing Username / Password
                        Username_TextBox.Enabled             = true;
                        Password_TextBox.Enabled             = true;
                        ShowPassword_CheckBox.Enabled        = true;
                        Authentication_Button.Enabled        = true;
                        AuthenticationStatus_Label.Text      = "NO USER OR PASS?";
                        AuthenticationStatus_Label.ForeColor = Color.FromArgb(240, 0, 0);
                        AuthenticationStatus_Label.BackColor = Color.Transparent;
                        Application.DoEvents();
                        return;
                    }
                    if (ErrorCode == HttpStatusCode.Unauthorized) //401
                    {
                        //Bad API Key
                        MessageBox.Show("APIKey not accepted for this release of OYS!\n\nPlease confirm your API Key with YSFHQ Webmasters, then update OpenYS-Library/Utilities/APIKey.txt!", "API Key Rejected!");
                        Username_TextBox.Enabled             = false;
                        Password_TextBox.Enabled             = false;
                        ShowPassword_CheckBox.Enabled        = false;
                        Authentication_Button.Enabled        = false; //leave this false, unable to authenticate without reloading!
                        AuthenticationStatus_Label.Text      = "API KEY REJECTED";
                        AuthenticationStatus_Label.ForeColor = Color.FromArgb(128, 0, 0);
                        AuthenticationStatus_Label.BackColor = Color.FromArgb(240, 200, 0);
                        Application.DoEvents();
                        return;
                    }
                    if (ErrorCode == HttpStatusCode.Forbidden) //403
                    {
                        //Bad Username / Password
                        Username_TextBox.Enabled             = true;
                        Password_TextBox.Enabled             = true;
                        ShowPassword_CheckBox.Enabled        = true;
                        Authentication_Button.Enabled        = true;
                        AuthenticationStatus_Label.Text      = "AUTHENTICATION FAIL!";
                        AuthenticationStatus_Label.ForeColor = Color.FromArgb(240, 0, 0);
                        AuthenticationStatus_Label.BackColor = Color.Transparent;
                        Application.DoEvents();
                        return;
                    }
                    //Generic Error?
                    MessageBox.Show("Generic Error Occured:\n\n" + WebError.Message, "Genereric Error!");
                    Username_TextBox.Enabled             = true;
                    Password_TextBox.Enabled             = true;
                    ShowPassword_CheckBox.Enabled        = true;
                    Authentication_Button.Enabled        = true;
                    AuthenticationStatus_Label.Text      = "GENERIC ERROR!";
                    AuthenticationStatus_Label.ForeColor = Color.FromArgb(240, 0, 0);
                    AuthenticationStatus_Label.BackColor = Color.Transparent;
                    Application.DoEvents();
                    return;
                    //System.Console.WriteLine(WebError);
                }
            }
        }
            private static void Run(string[] args)
            {
                //Initialisation
                #region Initialisation
                Thread.CurrentThread.Name = "OpenYS Server Core";
                Threads.List.Add(Thread.CurrentThread);

                Console._LogOutput    = Log.ConsoleOutput;
                Console._Process      = CommandManager.ProcessConsole;
                Console.ConsolePrompt = "&3OpenYS&f->&f";
                Console.Locked        = true;

                System.Console.CursorVisible = false;
                System.Console.Title         = "OpenYS - YSFlight Open Source Server";
                System.Console.Clear();

                #region OYS_Console
                OpenYS.OpenYSConsole.SetConsole();
                OpenYS.OpenYSConsole.SetFakeClient();
                OpenYS.OpenYSConsole.Username = Settings.Options.ConsoleName;
                OpenYS.OpenYSConsole.OP();
                OpenYS.OpenYSConsole.YSFClient.ConnectionContext = ClientIO.ConnectionContexts.Connectionless;
                #endregion
                #region OYS_BackgroundHandler
                OpenYS.OpenYSBackGround.SetController();
                OpenYS.OpenYSBackGround.SetFakeClient();
                OpenYS.OpenYSBackGround.Username = Settings.Options.SchedulerName;
                OpenYS.OpenYSBackGround.OP();
                OpenYS.OpenYSBackGround.YSFClient.ConnectionContext = ClientIO.ConnectionContexts.Connectionless;
                #endregion

                Sequencers.Process = CommandManager.ProcessScheduler;
                Schedulers.Process = CommandManager.ProcessScheduler;

                OpenYS.BuildType          = OpenYS._BuildType.Server;
                Environment.EntryAssembly = Assembly.GetExecutingAssembly();
                #endregion

                //Begin Program.
                #region TRY:
#if RELEASE
                try
                {
#endif
                #endregion
                #region MAIN LOOP
                while (!Environment.TerminateSignal.WaitOne(0))
                {
                    //Loading
                    #region Loading
                    #region ? Argument
                    if (args.Length > 0)
                    {
                        if (args[0] == "/?" | args[0] == "?")
                        {
                            System.Console.WriteLine("OpenYS Open Source Server Project. (C) OfficerFlake 2015");
                            System.Console.WriteLine("    ");
                            System.Console.WriteLine("    Usage: OpenYS_Client.exe [HostAddress] [HostPort] [ListenerPortNumber]");
                            System.Console.WriteLine("    ");
                            System.Console.WriteLine("Thanks for using OpenYS!");
                            System.Environment.Exit(0);
                        }
                    }
                    #endregion
                    #region Clear Logs
                    Files.FileDelete("./Logs/Client_Debug.Log");
                    Files.FileDelete("./Logs/Console.Log");
                    #endregion
                    #region Introduction
                    Console.WriteLine(ConsoleColor.Cyan, "Welcome to OpenYS Client!");
                    Console.WriteLine();
                    #endregion
                    #region Version Number
                    Console.WriteLine(ConsoleColor.DarkCyan, "You are using version:&e " + Environment.GetCompilationDate());
                    Console.WriteLine();
                    #endregion
                    #region LoadSettings
                    SettingsHandler.LoadAll();
                    SettingsHandler.Monitor();
                    #endregion
                    #region InitialSettings
                    OpenYS.OpenYSConsole.Username    = Settings.Options.ConsoleName;
                    OpenYS.OpenYSBackGround.Username = Settings.Options.SchedulerName;
                    Environment.OwnerName            = Settings.Options.OwnerName;
                    Environment.OwnerEmail           = Settings.Options.OwnerEmail;
                    Environment.ServerName           = Settings.Options.ServerName;
                    OpenYS.Field = new Packets.Packet_04_FieldName(Settings.Loading.FieldName);
                    #endregion
                    #region Check Arguments
                    CheckArguments(args);
                    #endregion
                    #region Load Commands
                    Commands.LoadAll();
                    #endregion
                    #region Load YSF
                    FormatYSFDirectory();
                    if (!Directories.DirectoryExists(Settings.Loading.YSFlightDirectory))
                    {
                        Console.TerminateConsole("YSFlight Directory Not Found.");
                    }
                    LoadAllMetaData();
                    if (!World.Load(OpenYS.Field.FieldName))
                    {
                        Console.TerminateConsole("FLD Name not found.");
                    }
                    #endregion
                    #region Load Games
                    Games.Racing.Initialise();
                    //Console.WriteLine();
                    #endregion
                    #region Loading Complete!
                    Console.WriteLine("");
                    Console.WriteLine(ConsoleColor.DarkYellow, "Loading Complete!");
                    Console.WriteLine("");
                    #endregion
                    #endregion

                    //Connection Handling Services.
                    #region Start Server
                    Server.Listener.Start();
                    OpenYS.YSFListener.ServerStarted.WaitOne();
                    #endregion

                    #region External IP & IRC
                    Threads.Add(() =>
                    {
                        #region IRC
                        IRC.Init();
                        IRC.Start();
                        #endregion
                        #region External IP
                        //Console.WriteLine();
                        //Console.WriteLine("&6Fetching External IP...");
                        //Console.WriteLine();
                        var ExternalIP = Environment.ExternalIP;
                        //Console.WriteLine("&6External IP: " + Environment.ExternalIP.ToString());
                        #endregion
                    }, "IRC/External IP Loading...");
                    //Console.WriteLine();
                    #endregion

                    //Timing Services.
                    #region Restart Timer
                    OpenYS.StartResetTimer();
                    #endregion
                    #region Lock/Unlock Console Input
                    Console.Locked = false;
                    Console.WriteLine("\r");     //effectively refreshes the prompt...
                    #endregion
                    #region SetServerTime
                    OpenYS.SetServerTimeTicks(Settings.Weather.Time * 10);
                    #endregion
                    int SeqLoaded = Sequencers.LoadAll();
                    int SchLoaded = Schedulers.LoadAll();

                    Thread.Sleep(10);
                    int LoopsPassed = 0;

                    while (!OpenYS.Signal_ResetServer.WaitOne(0))
                    {
                        #region Start Tick Update!
                        DateTime StartUpdate = DateTime.Now;
                        #endregion

                        OpenYS.PollResetTimer();
                        //OpenYS.MicroTick();
                        //OpenYS.MacroTick();
                        //OpenYS.UpdateTimeOfDay();
                        //Schedulers.Poll();
                        //Sequencers.Poll();
                        //YSFlightReplays.ServerReplay.SendUpdate();

                        #region End Tick Update!
                        DateTime EndUpdate = DateTime.Now;
                        #endregion
                        #region MicroTick Delay
                        OpenYS.Time_LastMicroTick = DateTime.Now;
                        int ThisUpdateTotalTime = (int)Math.Ceiling(((TimeSpan)(EndUpdate - StartUpdate)).TotalMilliseconds);
                        if (ThisUpdateTotalTime < 100)
                        {
                            Thread.Sleep(100 - ThisUpdateTotalTime);     //Micro Tick Delay.
                        }
                        //No Delay, resume immediately! - The update took over 100m/s!
                        #endregion
                        LoopsPassed++;
                    }
                    //We should reset now.
                    //OpenYS.TickUpdaterThread.Abort();
                    Schedulers.StopAll();
                    Sequencers.StopAll();
                    Server.Listener.Stop();
                    Console.Clear();
                    args = Environment.CommandLineArguments;
                    //Utilities.Restart();
                }
                #endregion
                #region CATCH
#if RELEASE
            }

            catch (Exception e)
            {
                if (e is ThreadAbortException)
                {
                    return;
                }
                Log.Error(e);
                #region TRY:
#if RELEASE
                try
                {
#endif
                #endregion
                #region Terminate
                Console.Locked = true;
                Console.WriteLine(ConsoleColor.Red, "OpenYS Has been terminated with error:");
                Console.WriteLine();
                Console.WriteLine(Debug.GetStackTrace(e));
                Emailing.SendCrashReportEmail(e);
                Thread.Sleep(5000);
                //RemovePDB();
                System.Environment.Exit(0);
                Console.WriteLine();
                Console.Terminate.Set();
                Console.Reader.Abort();
                for (int i = 10 - 1; i > 0; i--)
                {
                    Console.WriteLine(String.Format("\r&cOpenYS Will Restart In &f{0}&c Seconds.   ", i + 1));
                    Thread.Sleep(1000);
                }
                Console.WriteLine(String.Format("\r&cOpenYS Will Restart In &f1&c Second.   "));
                Thread.Sleep(1000);
                for (int i = 3; i > 0; i--)
                {
                    Console.WriteLine("\r&c!!!&f OpenYS Restarting &c!!!                            ");
                    Thread.Sleep(500);
                    Console.WriteLine("\r                                                  ");
                    Thread.Sleep(500);
                }
                Environment.RestartNow();
                #endregion
                #region CATCH
#if RELEASE
            }
            catch (Exception e2)
            {
                Console.WriteLine("Safe Restart Failed... Sorry!");
                Console.WriteLine(e2.Message);
                Log.Error(e2);
                Thread.Sleep(Timeout.Infinite);
                Console.TerminateConsole("End Of Program");
                return;
            }
#endif
                #endregion
            }
#endif
                #endregion
            }