Beispiel #1
0
        private void TaskMonitor()
        {
            var messagePointer = 0;

            while (!_workerTerminateSignal)
            {
                var next = _intervals[messagePointer];

                messagePointer++;
                var ts = next - DateTime.Now;
                if (ts.TotalSeconds > 0)
                {
                    _waitHandle.WaitOne(ts);
                    if (_workerTerminateSignal)
                    {
                        break;
                    }
                }
                var restart = _runtime - DateTime.Now;
                var message = String.Format(_message, restart.Humanize(2));
                for (var i = 1; i <= _repeat; i++)
                {
                    AppConsole.Log(String.Format("Sending Message: {0}", message), ConsoleColor.DarkMagenta);
                    if (!_debug)
                    {
                        _api.SendCommand(new Command(String.Format("say -1 {0}", message)));
                    }
                }
            }
        }
Beispiel #2
0
        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var message = _ini.GetSetting("Messages", _messages[_messagePointer]);

            _messagePointer++;
            if (String.IsNullOrWhiteSpace(message))
            {
                return;
            }
            message = String.Format("{0} {1}", _prefix, message);
            AppConsole.Log(String.Format("{0}: {1}", Name, message), ConsoleColor.Magenta);

            var cmd = new Command()
            {
                Type       = Command.CmdType.Say,
                Parameters = String.Format("-1 {0}", message)
            };

            _api.SendCommand(cmd);

            if (_messagePointer >= _messages.Length)
            {
                if (_repeat)
                {
                    _messagePointer = 0;
                }
                else
                {
                    Kill();
                }
            }
        }
Beispiel #3
0
        private static void Initialize(string[] args)
        {
            string invokedVerb         = null;
            object invokedVerbInstance = null;

            var opts = new CmdArgs();

            if (args.Length == 0 || CommandLine.Parser.Default.ParseArguments(
                    args,
                    opts,
                    (verb, subOptions) =>
            {
                // if parsing succeeds the verb name and correct instance
                // will be passed to onVerbCommand delegate (string,object)
                invokedVerb = verb;
                invokedVerbInstance = subOptions;
            }))
            {
                if (invokedVerbInstance is CmdArgs.BatchSubOptions)
                {
                }
                else
                {
                    App.Main();
                }
            }
            else
            {
                AppConsole.Show();
                Console.WriteLine(opts.GetUsage(invokedVerb));
                AppConsole.Hide();
            }
        }
Beispiel #4
0
 private void TaskMonitor()
 {
     while (!_workerTerminateSignal)
     {
         Task t;
         lock (Task.Tasks)
         {
             t = Task.Next;
         }
         _waitHandle.WaitOne(t.TimeSpan);
         if (_workerTerminateSignal)
         {
             break;
         }
         if (_debug)
         {
             AppConsole.Log(String.Format("Running Task: {0} {1}", t.Command.Type, t.Command.Parameters), ConsoleColor.DarkMagenta);
         }
         else
         {
             _api.SendCommand(t.Command);
         }
         lock (Task.Tasks)
         {
             t.Increment();
         }
     }
 }
Beispiel #5
0
        public void Connect()
        {
            for (var tries = 1; tries <= _maxtries; tries++)
            {
                try
                {
                    _beclient.Connect();
                    if (!_beclient.Connected)
                    {
                        throw new CoreException();
                    }
                    break;
                }
                catch
                {
                    AppConsole.Log(String.Format("Failed to connect to server. Attempt {0}/{1}", tries, _maxtries), ConsoleColor.Red);
                }
                Thread.Sleep(1000);
            }

            if (!_beclient.Connected)
            {
                throw new CoreException("Failed to connect to server.");
            }
            _connected = true;
        }
Beispiel #6
0
        public static void Main(string[] args)
        {
            // Go to http://aka.ms/dotnet-get-started-console to continue learning how to build a console app!
            if (args.Length == 0 || (args.Length >= 1 && HelpRequired(args[0])))
            {
                // if displaying help.
                AppConsole.DisplayHelp();
            }
            else
            {
                // if running the code.
                string phpDir    = "";
                string apacheDir = "";
                if (args.Length >= 2)
                {
                    // if php versions folder was specified.
                    // set php folder path.
                    phpDir = args[1];
                }
                if (args.Length >= 3)
                {
                    // if apache folder was specified.
                    // set apache folder path.
                    apacheDir = args[2];
                }
                FileSystem Fs = new FileSystem(args[0], phpDir, apacheDir);

                // check that this is running as admin.
                if (IsRunAsAdmin() == false)
                {
                    // if not run as admin.
                    try
                    {
                        RelaunchAsAdmin();
                    } catch
                    {
                        AppConsole.ErrorMessage("Please run this command as administrator privilege.");
                        System.Threading.Thread.Sleep(5000);
                        Environment.Exit(1);
                    }
                }
                // end check if running as admin.

                // validate required folders.
                FileSystem.ValidateRequiredPath();

                // stop web server service.
                Service.StopWebServerService();

                // copy files (also remove running version before copy).
                FileSystem.StartCopyFiles();

                // start web server service again.
                Service.StartWebServerService();

                // success message and exit.
                AppConsole.SuccessExit();
            }
        }
Beispiel #7
0
        public PluginManager(string pluginPath)
        {
            AppConsole.Log("Loading Plugins...");
            var dirs       = Directory.GetDirectories(pluginPath, "*", SearchOption.TopDirectoryOnly);
            var pluginType = typeof(IPlugin);

            foreach (var dir in dirs)
            {
                var name = Path.GetFileName(dir);
                var dll  = Path.Combine(dir, String.Format("{0}.dll", name));

                try
                {
                    if (!File.Exists(dll))
                    {
                        throw new CoreException(String.Format("The dll \"{0}\" was not found.", dll));
                    }

                    var an       = AssemblyName.GetAssemblyName(dll);
                    var assembly = Assembly.Load(an);

                    if (assembly == null)
                    {
                        continue;
                    }
                    var types = assembly.GetTypes();
                    foreach (var type in types)
                    {
                        if (type.IsInterface || type.IsAbstract)
                        {
                            continue;
                        }

                        if (type.GetInterface(pluginType.FullName) == null)
                        {
                            continue;
                        }

                        var pluginInstance = (IPlugin)Activator.CreateInstance(type);

                        var plugin = new Plugin()
                        {
                            Instance = pluginInstance,
                            DllPath  = dir
                        };
                        _pluginCollection.Add(plugin);
                    }
                }
                catch (Exception ex)
                {
                    AppConsole.Log(String.Format("Error loading plugin {0}: {1} - {2}", name, ex.Message, ex), ConsoleColor.Red);
                }
            }
        }
Beispiel #8
0
        public void Init(IApi api, string dllpath)
        {
            _api     = api;
            _dllpath = dllpath;
            try
            {
                _ini = new IniParser(_configPath);
            }
            catch (Exception ex)
            {
                throw new WebRconException(String.Format("Error loading config: {0}", ex.Message));
            }

            _enabled = _ini.GetBoolSetting(Name, "Enabled");
            if (!_enabled)
            {
                throw new WebRconException(String.Format("{0} has been disabled", Name));
            }

            var port = _ini.GetSetting(Name, "Port");

            try
            {
                _port = Convert.ToInt32(port);
            }
            catch (Exception ex)
            {
                throw new WebRconException(String.Format("Invalid port: {0}", ex.Message));
            }

            _password = _ini.GetSetting(Name, "Password");
            if (_password == "")
            {
                _password = Utils.GetRandomString();
            }

#if DEBUG
            _serverurl = String.Format("http://localhost:{0}/", _port);
#else
            _serverurl = String.Format("http://*:{0}/", _port);
#endif
            _webServer = new WebServer(HttpRequest, _serverurl);
            _webServer.Run();
            AppConsole.Log(String.Format("Started HTTP server at {0}. Password: {1}", _serverurl, _password), ConsoleColor.Cyan);

            _port++;
            _socketServer = new WebSocketServer(_port);
            _socketServer.AddWebSocketService("/rcon", () => new SocketBehavior(_api, _password));
            _socketServer.Start();

            LoadHtdocsFiles();
        }
Beispiel #9
0
        private void FilterMonitor()
        {
            _modified = new Dictionary <string, DateTime>();
            foreach (var f in _filters)
            {
                var file = Path.Combine(_api.Settings.BePath, f);
                if (!File.Exists(file))
                {
                    AppConsole.Log(String.Format("Could not find BEFilter: {0}", f));
                    continue;
                }
                var info = new FileInfo(file);
                _modified.Add(file, info.LastWriteTime);
            }

            while (!_workerTerminateSignal)
            {
                _waitHandle.WaitOne(_interval);
                if (_workerTerminateSignal)
                {
                    break;
                }

                foreach (var key in new List <string>(_modified.Keys))
                {
                    var info = new FileInfo(key);
                    if (info.LastWriteTime > _modified[key])
                    {
                        _modified[key] = info.LastWriteTime;

                        AppConsole.Log(String.Format("Filter {0} has been updated.", info.Name));
                        Command command;
                        if (info.Name == "scripts")
                        {
                            command = new Command()
                            {
                                Type = Command.CmdType.LoadScripts
                            };
                        }
                        else
                        {
                            command = new Command()
                            {
                                Type = Command.CmdType.loadEvents
                            };
                        }
                        _api.SendCommand(command);
                    }
                }
            }
        }
Beispiel #10
0
 public void Kill()
 {
     if (_worker != null)
     {
         _workerTerminateSignal = true;
         _waitHandle.Set();
         if (!_worker.Join(TimeSpan.FromMinutes(1)))
         {
             AppConsole.Log("Worker busy, aborting the thread.", ConsoleColor.Red);
             _worker.Abort();
         }
         _worker = null;
     }
 }
Beispiel #11
0
 internal void Kill()
 {
     AppConsole.Log("Unloading MBCon");
     try
     {
         _pluginManager.Kill();
         _beclient.Disconnect();
         _api.Dispose();
     }
     catch
     {
         // ignored
     }
 }
Beispiel #12
0
 internal void Init(IApi _api)
 {
     foreach (var t in _pluginCollection.ToArray())
     {
         try
         {
             t.Instance.Init(_api, t.DllPath);
         }
         catch (Exception ex)
         {
             AppConsole.Log(String.Format("Plugin {0} loading failed: {1}", t.Instance.Name, ex.Message), ConsoleColor.Yellow);
             _pluginCollection.Remove(t);
         }
     }
 }
Beispiel #13
0
    protected void Awake()
    {
        Instance = this;
        foreach (Transform child in textbox)
        {
            Destroy(child.gameObject);
        }

        for (int i = 0; i < maxMessages; i++)
        {
            TextMeshProUGUI consoleText = Instantiate(consoleTextPrefab);
            consoleText.transform.SetParent(textbox, false);
            consoleText.text = string.Empty;
        }
    }
Beispiel #14
0
        void _be_MessageEventHandler(Message message)
        {
            var color = ConsoleColor.DarkGray;

            switch (message.Type)
            {
            case Message.MessageType.ConnectGUID:
            case Message.MessageType.ConnectIP:
            case Message.MessageType.ConnectLegacyGUID:
                color = ConsoleColor.Blue;
                break;

            case Message.MessageType.Disconnect:
                color = ConsoleColor.DarkBlue;
                break;

            case Message.MessageType.Kick:
                color = ConsoleColor.Red;
                break;

            case Message.MessageType.Chat:
                color = ConsoleColor.White;
                if (message.Content.StartsWith("(Side)"))
                {
                    color = ConsoleColor.Cyan;
                }
                if (message.Content.StartsWith("(Vehicle)"))
                {
                    color = ConsoleColor.Yellow;
                }
                if (message.Content.StartsWith("(Direct)"))
                {
                    color = ConsoleColor.White;
                }
                if (message.Content.StartsWith("(Group)"))
                {
                    color = ConsoleColor.Green;
                }
                if (message.Content.StartsWith("(Global)"))
                {
                    color = ConsoleColor.Gray;
                }

                break;
            }

            AppConsole.Log(message.Content, color);
        }
Beispiel #15
0
        void onBEMessageReceivedEvent(Message message)
        {
            if (!(
                    message.Type == Message.MessageType.ConnectLegacyGUID ||
                    message.Type == Message.MessageType.ConnectGUID ||
                    (_checkip && message.Type == Message.MessageType.ConnectIP)
                    ))
            {
                return;
            }
            Player player;

            try
            {
                player = new Player(message);
            }
            catch (Exception ex)
            {
                AppConsole.Log(String.Format("Error paring be message: {0}", ex.Message), ConsoleColor.Red);
                return;
            }

            bool check;

            try
            {
                check = _driver.CheckPlayer(player);
            }
            catch (Exception ex)
            {
                AppConsole.Log(String.Format("Error checking player: {0}", ex.Message), ConsoleColor.Red);
                Console.WriteLine(ex.StackTrace);
                return;
            }

            var kick = (check && _mode == Mode.Blacklist) || (!check && _mode == Mode.Whitelist);

            if (kick)
            {
                var cmd = new Command()
                {
                    Type       = Command.CmdType.Kick,
                    Parameters = String.Format("{0} {1}", player.Id, _kickMessage)
                };
                AppConsole.Log(String.Format("Kicking {0}", player.Name));
                _api.SendCommand(cmd);
            }
        }
Beispiel #16
0
 internal void Kill()
 {
     AppConsole.Log("Unloading Plugins");
     foreach (var t in _pluginCollection)
     {
         try
         {
             AppConsole.Log(String.Format("Unloading {0}", t.Instance.Name));
             t.Instance.Kill();
         }
         catch
         {
             // ignored
         }
     }
 }
Beispiel #17
0
 private void BattlEyeConnected(BattlEyeConnectEventArgs args)
 {
     if (args.ConnectionResult == BattlEyeConnectionResult.Success)
     {
         AppConsole.Log(String.Format("Connected to {0}:{1}", _settings.Address, _settings.Port));
     }
     else
     {
         AppConsole.Log(String.Format("Connection to {0}:{1} failed: {2}", _settings.Address, _settings.Port, args.Message), ConsoleColor.Red);
         if (_connected)
         {
             Thread.Sleep(2000);
             Environment.Exit(0);
         }
     }
 }
Beispiel #18
0
        public ActionResult Console()
        {
            // TODO: Align RiskWeb and ORE folders on local machines!

            // Test python
            //string strTest = Test("/home/anders/developer/git/RiskWeb");
            //string strTest = Test("/app");

            // TODO: Unable to read from launchSettings.json file when Docker is included.
            // With Docker enabled hosting environment path defaults to C:\ and environment to "Development"

            ProcessStartInfo start = new ProcessStartInfo();
            // Linux
            //string root = "/home/anders/developer/git/ore/Engine";
            //string root = "/home/anders/developer/git/RiskWeb/Resources";
            //string root = "/app/Resources/";

            string root = _config.Value.OreWindowsRoot;

            string runFile = string.Format("{0}/{1}", root, "Examples/Example_1/run.py");
            string wd      = string.Format("{0}/{1}", root, "Examples/Example_1");

            start.WorkingDirectory       = wd;
            start.FileName               = "python"; // Assumes path to python.exe in PATH-variable
            start.Arguments              = string.Format("{0} {1}", runFile, "");
            start.UseShellExecute        = false;
            start.RedirectStandardOutput = true;

            // Console output
            AppConsole    console = new AppConsole();
            StringBuilder sb      = new StringBuilder();
            string        str     = "";

            using (Process process = Process.Start(start))
            {
                string line;
                while ((line = process.StandardOutput.ReadLine()) != null)
                {
                    sb.AppendFormat(line, Environment.NewLine);
                    str += line + Environment.NewLine;
                }
            }

            console.Text = str;

            return(View(console));
        }
Beispiel #19
0
 private void ProcessLogin(LoginRequest req)
 {
     if (req.password == _password)
     {
         SendLoginResult(true);
         SendToken();
         _authed = true;
         _api.OnBeMessageReceivedEvent += onBEMessageReceivedEvent;
         SendPlayerList(_api.Players);
         _api.OnPlayerListUpdatedEvent += onPlayerListUpdatedEvent;
     }
     else
     {
         AppConsole.Log("User tried tried to login with the wrong password.");
         SendLoginResult(false);
     }
 }
Beispiel #20
0
 private void SendLog(Job job)
 {
     try
     {
         using (var client = new WebClient())
         {
             var reqparm = new NameValueCollection {
                 { "message", job.message }, { "type", job.type }
             };
             client.UploadValues(_uri, "POST", reqparm);
         }
     }
     catch (Exception ex)
     {
         AppConsole.Log(String.Format("Error posting log: {0}", ex.Message), ConsoleColor.Red);
     }
 }
Beispiel #21
0
        /**
         * <summary>Validate required folders. Exit the program if not found.</summary>
         */
        public static void ValidateRequiredPath()
        {
            if (Fs.IsApacheFolderExists() == false)
            {
                AppConsole.ErrorMessage("Error! The Apache config folder or required folders, file for Apache configuration is not exists. (" + Fs.ApacheDir + ")");
                System.Threading.Thread.Sleep(5000);
                Environment.Exit(1);
                return;
            }

            if (Fs.IsApacheConfigFileExists(Apache.phpVersion) == false)
            {
                AppConsole.ErrorMessage("Error! The Apache config file for specific PHP version is not exists. (conf/extra/httpd-php-" + Apache.phpVersion + ".conf)");
                System.Threading.Thread.Sleep(5000);
                Environment.Exit(1);
                return;
            }
        }
Beispiel #22
0
        private BattlEyeClient BEClient()
        {
            AppConsole.Log("Loading BEClient...");
            var login = new BattlEyeLoginCredentials
            {
                Host     = _settings.Address,
                Port     = _settings.Port,
                Password = _settings.RconPass
            };

            var beclient = new BattlEyeClient(login)
            {
                ReconnectOnPacketLoss = true
            };

            beclient.BattlEyeConnected    += BattlEyeConnected;
            beclient.BattlEyeDisconnected += BattlEyeDisconnected;
            return(beclient);
        }
Beispiel #23
0
        public WSBanListPacket(string[] bansfile)
            : base(4)
        {
            var i = 0;

            foreach (var line in bansfile)
            {
                var ban = line.Trim();
                try
                {
                    var row = new Dictionary <string, string>();
                    if (rx.IsMatch(ban))
                    {
                        var match = rx.Match(ban);
                        row.Add("data", match.Groups["data"].Value);
                        row.Add("time", match.Groups["time"].Value);
                        try
                        {
                            row.Add("reason", match.Groups["reason"].Value);
                        }
                        catch
                        {
                            row.Add("reason", "");
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Input string is not valid");
                    }

                    row.Add("id", i.ToString());
                    bans.Add(row);
                }
                catch (Exception ex)
                {
                    AppConsole.Log(String.Format("Error parsing line '{0}'. {1}", ban, ex.Message), ConsoleColor.Red);
                }

                i++;
            }
        }
Beispiel #24
0
        new public void SetConfig(DriverSettings settings)
        {
            base.SetConfig(settings);
            var f = settings.Ini.GetSetting("File", "Path");

            if (!Path.IsPathRooted(f))
            {
                f = Path.Combine(settings.PluginPath, f);
            }
            if (!System.IO.File.Exists(f))
            {
                throw new DriverException(String.Format("Could not load player list {0}", f));
            }
            var    file = new StreamReader(f);
            string line;

            while ((line = file.ReadLine()) != null)
            {
                _list.Add(line.Trim());
            }
            AppConsole.Log(String.Format("PlayerCheck: Loaded {0} GUIDs into list.", _list.Count));
            file.Close();
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            Console.CancelKeyPress += delegate
            {
                core.Kill();
            };
            handler = ConsoleEventCallback;
            SetConsoleCtrlHandler(handler, true);

            Console.Title          = "MBCon - Connected";
            Console.OutputEncoding = Encoding.UTF8;
            core = new Core();
            try
            {
                core.Run(args);
            }
            catch (CoreException ex)
            {
                core.Kill();
                AppConsole.Log(String.Format("ERROR: {0}", ex.Message), ConsoleColor.Red);
                Thread.Sleep(5000);
            }
        }
Beispiel #26
0
        public Dashboard()
        {
            InitializeComponent();

            AppConsole.RegisterTextbox(appConsole);
            AppConsole.RedirectConsoleOutput();

            _centralClock = new CentralClock <TResponseData>(this);

            _centralClock.FrameGenerated += CentralClockOnFrameGenerated;
            _centralClock.StateGenerated += CentralClockOnStateGenerated;
            _centralClock.DataGenerated  += CentralClockOnDataGenerated;

            ApplicationConfig.ConfigUpdated += (config) =>
            {
                auxVideoStream.MJPEGUrl  = config.AuxVideoUrl;
                mainVideoStream.MJPEGUrl = config.MainVideoUrl;
            };

            auxVideoStream.MJPEGUrl  = ApplicationConfig.Shared.AuxVideoUrl;
            mainVideoStream.MJPEGUrl = ApplicationConfig.Shared.MainVideoUrl;

            LogicMapper <TResponseData> .InputProcessor.ButtonPress += InputProcessorOnButtonPress;
        }
 public MsBuildProjectLoader(AppConsole console)
 {
     this.console = console;
 }
Beispiel #28
0
 private void ClientOnRoverCommInitiation(RoverClientInitializationEventArgs eventArgs)
 {
     AppConsole.WriteLine("Rover Client is connected", EventLevel.Logging);
 }
Beispiel #29
0
 private void ClientOnRoverPacketReceived(RoverPacketReceivedEventArgs eventArgs)
 {
     LatestData = eventArgs.ResponseData;
     AppConsole.WriteLine("Recieved data. Timestamp: " + eventArgs.ResponseData.MessageTime.ToString("G"), EventLevel.Debugging);
 }
 public LatestVersionProvider(AppConsole console)
 {
     this.console = console;
 }