Пример #1
0
        public static bool OpenYS_Command_Weather_Turbulemce_Method(Client ThisClient, CommandReader Command)
        {
            if (Command._CmdArguments.Count() < 1)
            {
                if (OpenYS.AdvancedWeatherOptions._Turbulence > 0)
                {
                    ThisClient.SendMessage("&eServer turbulence is " + OpenYS.AdvancedWeatherOptions._Turbulence + ".");
                }
                else
                {
                    ThisClient.SendMessage("&eServer disables turbulence.");
                }
                return(false);
            }
            uint ID = 0;

            if (!UInt32.TryParse(Command._CmdArguments[0], out ID))
            {
                ThisClient.SendMessage("&eFormat incorrect: Be sure you are using an integer value!");
                return(false);
            }
            if (ID > 0)
            {
                OpenYS.AdvancedWeatherOptions._Turbulence = (int)ID;
                ThisClient.SendMessage("&aServer turbulence set to &a" + ID + "&a percent.");
                Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set turbulence to &a" + ID + "&a percent.");
                SettingsHandler.SaveAll();
                return(true);
            }
            else
            {
                OpenYS.AdvancedWeatherOptions._Turbulence = 0;
                ThisClient.SendMessage("&aServer turbulence set to &cOFF&a.");
                Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set turbulence to &cOFF&a.");
                SettingsHandler.SaveAll();
                return(true);
            }
        }
Пример #2
0
 public static bool OpenYS_Command_Options_Field_Method(Client ThisClient, CommandReader Command)
 {
     if (Command._CmdArguments.Count() < 1)
     {
         if (OpenYS.Field != null)
         {
             ThisClient.SendMessage("&eCurrent Field: &a" + OpenYS.Field.FieldName + "&e.");
         }
         else
         {
             ThisClient.SendMessage("&cERROR: Server Field handler not found.");
         }
         return(false);
     }
     if (Command._CmdRawArguments.Contains(' '))
     {
         Command._CmdRawArguments = '"' + Command._CmdRawArguments + '"';
     }
     if (MetaData._Scenery.List.Where(x => x.Identify.ToUpperInvariant().StartsWith(Command._CmdRawArguments.ToUpperInvariant())).Count() <= 0)
     {
         ThisClient.SendMessage("&eTarget Field not found: " + Command._CmdRawArguments + "&e.");
         return(false);
     }
     if (Environment.CommandLineArguments.Length == 0)
     {
         Environment.CommandLineArguments = new string[] { Settings.Loading.YSFlightDirectory, MetaData._Scenery.List.Where(x => x.Identify.ToUpperInvariant().StartsWith(Command._CmdRawArguments.ToUpperInvariant())).ToArray()[0].Identify, Settings.Server.ListenerPort.ToString() };
     }
     else if (Environment.CommandLineArguments.Length > 1)
     {
         Environment.CommandLineArguments[1] = MetaData._Scenery.List.Where(x => x.Identify.ToUpperInvariant().StartsWith(Command._CmdRawArguments.ToUpperInvariant())).ToArray()[0].Identify;
     }
     Settings.Loading.FieldName = Environment.CommandLineArguments[1];
     SettingsHandler.SaveAll();
     ThisClient.SendMessage("&cTarget Server Field changed to &e" + Environment.CommandLineArguments[1] + "&c.");
     ThisClient.SendMessage("&cTO CHANGE THE Field NOW, RESTART THE SERVER!");
     //Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set the server name to: &2" + OpenYS.OpenYSConsole.Info.Username + "&a.");
     return(true);
 }
Пример #3
0
 public static bool OpenYS_Command_Weather_Time_Method(Client ThisClient, CommandReader Command)
 {
     if (Command._CmdArguments.Count() < 1)
     {
         ThisClient.SendMessage("&eServer time is currently " + OpenYS.GetServerTimeString() + "J.");
         return(false);
     }
     if (Command._CmdArguments[0].ToUpperInvariant() == "DAY")
     {
         OpenYS.Weather = new Packets.Packet_33_Weather(OpenYS._Weather)
         {
             Lighting = 0
         };
         int      incrementticks = (int)(12 * 1000) + (int)Math.Round(0 * 1000d / 60d);
         TimeSpan Adjustment     = new TimeSpan(0, 0, 0, 0, (int)(incrementticks / 24000d * OpenYS.AdvancedWeatherOptions._DayNightCycleLength * 60 * 1000d));
         OpenYS.AdvancedWeatherOptions._LastDayNightCycleRestart = DateTime.Now - Adjustment;
         Clients.AllClients.SendPacket(OpenYS.Weather);
         ThisClient.SendMessage("&aServer time set to 1200J.");
         Settings.Weather.Time = 1200;
         SettingsHandler.SaveAll();
         Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set the time to 1200J.");
         return(true);
     }
     if (Command._CmdArguments[0].ToUpperInvariant() == "NIGHT")
     {
         OpenYS.Weather = new Packets.Packet_33_Weather(OpenYS._Weather)
         {
             Lighting = 65537
         };
         int      incrementticks = (int)(0 * 1000) + (int)Math.Round(0 * 1000d / 60d);
         TimeSpan Adjustment     = new TimeSpan(0, 0, 0, 0, (int)(incrementticks / 24000d * OpenYS.AdvancedWeatherOptions._DayNightCycleLength * 60 * 1000d));
         OpenYS.AdvancedWeatherOptions._LastDayNightCycleRestart = DateTime.Now - Adjustment;
         Clients.AllClients.SendPacket(OpenYS.Weather);
         ThisClient.SendMessage("&aServer time set to 0000J.");
         Settings.Weather.Time = 0000;
         SettingsHandler.SaveAll();
         Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set the time to 0000J.");
         return(true);
     }
     if (Command._CmdArguments[0].ToUpperInvariant() == "DAWN")
     {
         OpenYS.Weather = new Packets.Packet_33_Weather(OpenYS._Weather)
         {
             Lighting = 0
         };
         int      incrementticks = (int)(6 * 1000) + (int)Math.Round(0 * 1000d / 60d);
         TimeSpan Adjustment     = new TimeSpan(0, 0, 0, 0, (int)(incrementticks / 24000d * OpenYS.AdvancedWeatherOptions._DayNightCycleLength * 60 * 1000d));
         OpenYS.AdvancedWeatherOptions._LastDayNightCycleRestart = DateTime.Now - Adjustment;
         Clients.AllClients.SendPacket(OpenYS.Weather);
         ThisClient.SendMessage("&aServer time set to 0600J.");
         Settings.Weather.Time = 0600;
         SettingsHandler.SaveAll();
         Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set the time to 0600J.");
         return(true);
     }
     if (Command._CmdArguments[0].ToUpperInvariant() == "DUSK")
     {
         OpenYS.Weather = new Packets.Packet_33_Weather(OpenYS._Weather)
         {
             Lighting = 65537
         };
         Clients.AllClients.SendPacket(OpenYS.Weather);
         SettingsHandler.SaveAll();
         OpenYS.AdvancedWeatherOptions._LastDayNightCycleRestart = DateTime.Now;
         int      incrementticks = (int)(18 * 1000) + (int)Math.Round(0 * 1000d / 60d);
         TimeSpan Adjustment     = new TimeSpan(0, 0, 0, 0, (int)(incrementticks / 24000d * OpenYS.AdvancedWeatherOptions._DayNightCycleLength * 60 * 1000d));
         OpenYS.AdvancedWeatherOptions._LastDayNightCycleRestart = DateTime.Now - Adjustment;
         ThisClient.SendMessage("&aServer time set to 1800J.");
         Settings.Weather.Time = 1800;
         SettingsHandler.SaveAll();
         Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set the time to 1800J.");
         return(true);
     }
     try
     {
         String Input = Command._CmdArguments[0];
         if (Input.Length == 5 && Input.ToUpperInvariant().EndsWith("J"))
         {
             Input = Input.Substring(0, Input.Length - 1);
         }
         if (Input.Length != 4)
         {
             ThisClient.SendMessage("&eTime must be in 24 Hour Format!");
             return(false);
         }
         uint hours   = UInt32.Parse(Input.ToUpperInvariant().Substring(0, 2));
         uint minutes = UInt32.Parse(Input.ToUpperInvariant().Substring(2, 2));
         if (hours >= 24)
         {
             ThisClient.SendMessage("&aServer Time Invalid! Must be between 0000 and 2359!");
         }
         if (minutes >= 60)
         {
             ThisClient.SendMessage("&aServer Time Invalid! Minutes >= 60???");
         }
         uint incrementticks = (hours * 1000) + (uint)Math.Round(minutes * 1000d / 60d);
         OpenYS.SetServerTimeTicks(incrementticks);
         Settings.Weather.Time = OpenYS.GetServerTimeUint();
         SettingsHandler.SaveAll();
         ThisClient.SendMessage("&aServer time set to " + OpenYS.GetServerTimeString() + "J.");
         Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set the time to " + OpenYS.GetServerTimeString() + "J.");
         return(true);
     }
     catch
     {
     }
     ThisClient.SendMessage("&eUnrecognised time - \"" + Command._CmdArguments[0] + "\".");
     return(false);
 }
        public static bool OpenYS_Command_Weather_DNCycle_Method(Client ThisClient, CommandReader Command)
        {
            if (Command._CmdArguments.Count() < 1)
            {
                if (OpenYS.AdvancedWeatherOptions._DayNightCycleLength > 0)
                {
                    ThisClient.SendMessage("&eServer enables its day/night cycle (" + OpenYS.AdvancedWeatherOptions._DayNightCycleLength + ").");
                }
                else
                {
                    ThisClient.SendMessage("&eServer disables its day/night cycle.");
                }
                return(false);
            }
            uint ID = 0;

            if (!UInt32.TryParse(Command._CmdArguments[0], out ID))
            {
                ThisClient.SendMessage("&eFormat incorrect: Be sure you are using an integer value!");
                return(false);
            }
            if (ID > 0)
            {
                uint CurrentTick = OpenYS.GetServerTimeTicks();
                OpenYS.AdvancedWeatherOptions._DayNightCycleLength = (int)ID;
                OpenYS.SetServerTimeTicks((uint)CurrentTick);
                Random ThisRandom = new Random();
                ThisClient.SendMessage("&aServer day/night cycle set to &a" + ID + "&a Minutes.");
                Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set day/night cycle to &a" + ID + "&a Minutes.");
                if (OpenYS.GetServerTimeTicks() > 7000 && OpenYS.GetServerTimeTicks() < 19000)
                {
                    if (ThisRandom.Next(1, 100) == 99)
                    {
                        Clients.AllClients.SendMessage("&6Dawn of the first day. (Lol, YSZelda.)");
                    }
                    else
                    {
                        Clients.AllClients.SendMessage("&6The sun rises... (Day/Night Sequencer Started!)");
                    }
                }
                else
                {
                    if (ThisRandom.Next(1, 100) == 99)
                    {
                        Clients.AllClients.SendMessage("&5The Dark (k)Night rises. (Lol, YSBatman.)");
                    }
                    else
                    {
                        Clients.AllClients.SendMessage("&5The sun sets... (Day/Night Sequencer Started!)");
                    }
                }
                if (OpenYS.GetServerTimeTicks() > 7000 && OpenYS.GetServerTimeTicks() < 19000)
                {
                    OpenYS._Weather.Lighting = 0;
                }
                else
                {
                    OpenYS._Weather.Lighting = 65537;
                }
                OpenYS.UpdateWeather();
                SettingsHandler.SaveAll();
                return(true);
            }
            else
            {
                uint CurrentTick = OpenYS.GetServerTimeTicks();
                OpenYS.AdvancedWeatherOptions._DayNightCycleLength = 0;
                OpenYS.SetServerTimeTicks((uint)CurrentTick);
                ThisClient.SendMessage("&aServer day/night cycle set to &cOFF&a.");
                Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set day/night cycle to &cOFF&a.");
                SettingsHandler.SaveAll();
                return(true);
            }
        }
Пример #5
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);
                }
            }
        }
Пример #8
0
        public static bool SaveAll()
        {
            SettingsFileWatcher.EnableRaisingEvents = false;
            FileInfo File = new FileInfo("./Settings.xlsx");

            //This framework is a real pain in the ARSE!
            //It uses non zero based indexes!
            using (ExcelPackage xlPackage = new ExcelPackage(File))
            {
                // get the first worksheet in the workbook
                ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];
                for (int i = 4; i < 1024; i++)
                {
                    object _Key = worksheet.Cells[i, 1].Value;
                    string Key  = _Key == null ? "" : _Key.ToString();
                    if (Key == "")
                    {
                        continue;
                    }
                    object _Val   = worksheet.Cells[i, 2].Value;
                    string Val    = _Val == null ? "" : _Val.ToString();
                    object NewVal = SettingsHandler._GetDirect(Key);
                    if (NewVal == null)
                    {
                        Log.Warning(("&3Save Fail: " + Key).Resize(System.Console.WindowWidth));
                        NewVal = Val;
                    }
                    if (NewVal.GetType() == typeof(IPAddress))
                    {
                        IPAddress   _IP      = (IPAddress)NewVal;
                        IPAddress[] _Matches = new IPAddress[0];
                        bool        NetIsUp  = false;
                        try
                        {
                            Ping ping = new Ping();

                            //ping googles dns server to determine if the net connection is available!
                            PingReply pingStatus = ping.Send(IPAddress.Parse("8.8.8.8"));

                            if (pingStatus.Status == IPStatus.Success)
                            {
                                NetIsUp = true;
                            }
                        }
                        catch
                        {
                        }

                        try
                        {
                            if (NetIsUp)
                            {
                                _Matches = Dns.GetHostAddresses(Val);
                            }
                        }
                        catch
                        {
                            //No net connection, can't resolve...
                        }
                        if (!NetIsUp)
                        {
                            continue;           //can't verify the IP Address, let's leave it the way it is for now...
                        }
                        if (_Matches.Select(x => x.ToString()).Contains(_IP.ToString()))
                        {
                            continue;                                                              //no change required!
                        }
                        else
                        {
                            worksheet.Cells[i, 2].Value = NewVal;
                        }
                        continue;
                    }
                    if (NewVal.ToString() == Val)
                    {
                        continue;
                    }
                    worksheet.Cells[i, 2].Value = NewVal;
                }
                xlPackage.Save();
            } // the using statement calls Dispose() which closes the package.
            try
            {
                SettingsFileWatcher.EnableRaisingEvents = true;
            }
            catch
            {
                //Path not of legal form? Stop watching...
            }
            return(true);
        }
Пример #9
0
        public static bool OpenYS_Command_Weather_Wind_Method(Client ThisClient, CommandReader Command)
        {
            int Angle;
            int Speed;

            string _Angle;
            string _Speed;
            string TAF;

            if (Command._CmdArguments.Count() < 1)
            {
                Angle = 90 - (int)(Math.Atan2(OpenYS.Weather.WindZ, OpenYS.Weather.WindX) / Math.PI * 180) + 180;
                while (Angle < 0)
                {
                    Angle += 360;
                }
                while (Angle >= 360)
                {
                    Angle -= 360;
                }

                Speed = (int)(Math.Sqrt(Math.Pow(OpenYS.Weather.WindZ, 2) + Math.Pow(OpenYS.Weather.WindX, 2)) * 1.943844492440605);
                //ThisClient.SendMessage("&eServer Wind Angle is currently " + Angle + "deg.");
                //ThisClient.SendMessage("&eServer Wind Speed is currently " + Speed + "kt.");

                if (Speed <= 0)
                {
                    Angle = 0;
                }
                _Angle = Angle.ToString();
                if (_Angle.Length > 3)
                {
                    _Angle = "XXX";
                }
                while (_Angle.Length < 3)
                {
                    _Angle = "0" + _Angle;
                }
                _Speed = Speed.ToString();
                if (_Speed.Length > 2)
                {
                    _Speed = "99";
                }
                while (_Speed.Length < 2)
                {
                    _Speed = "0" + _Speed;
                }

                TAF = _Angle + _Speed + "KT";
                if (TAF == "00000KT")
                {
                    TAF = "calm";
                }
                ThisClient.SendMessage("&eServer Wind is currently " + TAF + ".");
                return(true);
            }
            TAF = Command._CmdArguments[0].ToLowerInvariant();
            if (TAF == "calm")
            {
                TAF = "00000KT";
            }
            uint output = 0;

            if (!UInt32.TryParse(TAF.Substring(0, 3), out output))
            {
                ThisClient.SendMessage("&eUnrecognised value - \"" + Command._CmdArguments[0] + "\".");
                return(false);
            }
            Angle = 90 - (int)output;
            while (Angle < 0)
            {
                Angle += 360;
            }
            while (Angle >= 360)
            {
                Angle -= 360;
            }
            output = 0;
            if (!UInt32.TryParse(TAF.Substring(3, 2), out output))
            {
                ThisClient.SendMessage("&eUnrecognised value - \"" + Command._CmdArguments[0] + "\".");
                return(false);
            }
            Speed          = (int)output;
            OpenYS.Weather = new Packets.Packet_33_Weather(OpenYS._Weather)
            {
                WindZ = (float)((Math.Sin((double)Angle / 180 * Math.PI)) * Speed * 0.5144444444444444),
                WindX = (float)((Math.Cos((double)Angle / 180 * Math.PI)) * Speed * 0.5144444444444444)
            };


            TAF = Command._CmdArguments[0].ToUpperInvariant();
            if (TAF == "CALM")
            {
                TAF = "calm";
            }
            else if (TAF.Substring(3, 2) == "00")
            {
                TAF = "calm";
            }
            Clients.AllClients.SendPacket(OpenYS.Weather);
            SettingsHandler.SaveAll();
            ThisClient.SendMessage("&eServer Wind set to " + TAF + ".");
            Clients.AllClients.Exclude(ThisClient).SendMessage("&a" + ThisClient.Username + " set the Wind to " + TAF + ".");
            return(true);
        }
            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
            }