Exemplo n.º 1
0
        public void Should_Not_Handle_If_ParsedCommand_Is_Not_Successful()
        {
            _parser.ParseCommand(Arg.Any <IMessage>()).Returns(ParsedCommand.Unsuccessful());

            ICommandHandler commandHandler = Substitute.For <ICommandHandler>();

            commandHandler.CommandName.Returns("test");

            _discloseClient.Register(commandHandler);

            _discordClient.OnMessageReceived += Raise.EventWith(new object(), new MessageEventArgs(_message));

            commandHandler.Received(0).Handle(Arg.Any <DiscloseMessage>(), Arg.Any <string>());
        }
Exemplo n.º 2
0
        public void Execute(string command)
        {
            var commands = _commandParser.ParseCommand(command);

            _commandInvoker.SetCommands(commands);
            _commandInvoker.InvokeAll();
        }
Exemplo n.º 3
0
        public void Start()
        {
            var initialCommand = new HelpCommand();
            var helpMessage    = initialCommand.Execute();

            _printer.Print(helpMessage.CommandOutput);

            do
            {
                var userInput      = _inputParser.Parse();
                var currentCommand = _commandParser.ParseCommand(userInput);
                currentCommand.CancellationRequested += CancellationRequested;

                if (CanScheduleTask)
                {
                    currentCommand.SortFinished += SortFinished;
                }

                var commandData = currentCommand.Execute(CanScheduleTask);

                _printer.Print(commandData.CommandOutput);
                _isRunning = commandData.ContinueExecution;

                if (commandData.Token.HasValue)
                {
                    _cancellationToken = commandData.Token;
                }
            } while (_isRunning);
        }
Exemplo n.º 4
0
        private async Task ProcessMessage(BotEventArgs e)
        {
            using var scope = _serviceProvider.CreateScope();
            var commandHandler = new CommandHandler(scope.ServiceProvider);

            CommandContainer commandContainer = _commandParser.ParseCommand(e);

            if (!commandContainer.StartsWithPrefix(_prefix))
            {
                return;
            }

            commandContainer.RemovePrefix(_prefix);

            Result checkResult = commandHandler.CheckArgsCount(commandContainer);

            if (!checkResult.IsSuccess)
            {
                throw new CommandArgumentsException(checkResult.Message);
            }

            checkResult = commandHandler.CanCommandBeExecuted(commandContainer);
            if (!checkResult.IsSuccess)
            {
                throw new CommandCantBeExecutedException(checkResult.Message);
            }

            IBotMessage message = await commandHandler.ExecuteCommand(commandContainer);

            await message.SendAsync(_apiProvider, e.SenderInfo);
        }
Exemplo n.º 5
0
        private async void OnMessageReceived(object sender, MessageEventArgs e)
        {
            IMessage message = e.Message;

            if (message.User.Id == _discordClient.ClientId)
            {
                return;
            }

            ParsedCommand parsedCommand = _parser.ParseCommand(message);

            if (!parsedCommand.Success)
            {
                return;
            }

            bool commandExists = _commandHandlers.TryGetValue(parsedCommand.Command, out ICommandHandler commandHandler);

            if (!commandExists)
            {
                return;
            }

            if (commandHandler.ChannelFilter != null && !commandHandler.ChannelFilter(new DiscloseChannel(message.Channel)))
            {
                return;
            }

            DiscloseUser discloseUser;

            if (message.Channel.IsPrivateMessage)
            {
                //User objects in Direct Messages don't have roles because there is no server context. So find the user on the server and use that user to have the user's roles available
                IEnumerable <DiscloseUser> serverUsers = await _server.GetUsersAsync();

                discloseUser = serverUsers.FirstOrDefault(su => su.Id == message.User.Id);

                if (discloseUser == null)
                {
                    return;
                }
            }
            else
            {
                discloseUser = new DiscloseUser((IServerUser)message.User, _server);
            }

            DiscloseMessage discloseMessage = new DiscloseMessage(message, discloseUser);

            if (commandHandler.UserFilter != null && !commandHandler.UserFilter(discloseMessage.User))
            {
                return;
            }

            await commandHandler.Handle(discloseMessage, parsedCommand.Argument);
        }
Exemplo n.º 6
0
        public object ExecuteCommand(string commandText)
        {
            if (string.IsNullOrEmpty(commandText))
            {
                return(null);
            }

            (string command, string[] args) = commandParser.ParseCommand(commandText);
            return(ExecuteCommand(command, args));
        }
        public string ProcessCommand(string commandAsString)
        {
            Guard.WhenArgument(commandAsString, "command").IsNullOrWhiteSpace().Throw();

            var command    = parser.ParseCommand(commandAsString);
            var parameters = parser.ParseParameters(commandAsString);

            var executionResult = command.Execute(parameters);

            return(executionResult);
        }
Exemplo n.º 8
0
    public void Run()
    {
        while (true)
        {
            string input = this.reader.ReadLine();

            ICommand command = commandParser.ParseCommand(input);

            commandExecutor.Execute(command);
        }
    }
Exemplo n.º 9
0
        public string DispatchCommand(string[] commandParameters)
        {
            command = parser.ParseCommand(commandParameters);

            if (commandParameters.Length < command.GetParameters)
            {
                throw new InvalidOperationException($"Command {commandParameters[0]} is not valid");
            }

            return(command.Execute());
        }
Exemplo n.º 10
0
        public override StringCommandInfo FindCommandInfo(IAppSession session, byte[] readBuffer, int offset, int length, bool isReusableBuffer, out int left)
        {
            NextCommandReader = this;

            string command;

            if (!FindCommandInfoDirectly(readBuffer, offset, length, isReusableBuffer, out command, out left))
            {
                return(null);
            }

            return(m_CommandParser.ParseCommand(command));
        }
Exemplo n.º 11
0
        public string ProcessCommand(string inputLine)
        {
            //processes the command (parses the parrameters and gives it to the command)
            //command format: cmdname - <arg1> : <arg2> : <arg3> : ...
            var      cmdArguments = inputLine.Split('-').Select(arg => arg.Trim()).ToList();
            ICommand command      = parser.ParseCommand(cmdArguments.First().Replace(" ", ""));

            if (cmdArguments.Count < 2)
            {
                return("Thats a nice potential command, but please, put '-' after it");
            }
            var parameters = cmdArguments[1].Split(':').Select(arg => arg.Trim()).ToList();

            return(command.Run(parameters));
        }
        protected override string OnGetAuthenticatedCommandRequest(Session session, string request, out bool isCommand)
        {
            isCommand = false;

            ICommand command;

            if ((command = commandParser
                           .ParseCommand(CultureInfo.InvariantCulture, request, out var processedInput)) != null &&
                !string.IsNullOrEmpty(processedInput))
            {
                isCommand = true;
                request   = processedInput;
            }

            return(request);
        }
Exemplo n.º 13
0
        public string ExecuteCommand(string input)
        {
            var command = commandParser.ParseCommand(input.ToLower());

            if (command.CommandId == Command.Quit)
            {
                return(null);
            }
            else if (command.CommandId == Command.Help)
            {
                return(help);
            }
            else if (command.CommandId == Command.InvalidCommand)
            {
                return(invalidCommand);
            }

            return(ExecuteParsedCommand(command));
        }
Exemplo n.º 14
0
        private void AddButtonClicked(object sender, RoutedEventArgs e)
        {
            var officeName        = this.officeName.Text;
            var email             = this.usernameReg.Text;
            var password          = this.passwordReg.Password;
            var confirmedPassword = this.confirmedPassword.Password;

            var command = commandParser.ParseCommand(new[] { "Register", officeName, email, password, confirmedPassword });

            try
            {
                command.Execute();
                Switcher.Switch(new ClientsPage());
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
Exemplo n.º 15
0
        private void StartCommandParsing()
        {
            Console.WriteLine("Enter connection you want to set. Syntax: <port1> <port2> [up|down]");
            while (true)
            {
                Console.Write("> ");
                string input = Console.ReadLine();

                try
                {
                    (string, string, bool)connection = _commandParser.ParseCommand(input);
                    _cableCloudManager.SetConnectionAlive(connection);
                }
                catch (ParserException e)
                {
                    LOG.Warn(e.ExceptionMessage);
                }
            }
        }
Exemplo n.º 16
0
        private void ProcessMessage(BotEventArgs e)
        {
            Result <CommandArgumentContainer> commandResult = _commandParser.ParseCommand(e);

            if (commandResult.IsFailed)
            {
                return;
            }

            if (!commandResult.Value.EnsureStartWithPrefix(_prefix))
            {
                return;
            }

            commandResult = _commandHandler.IsCorrectArgumentCount(commandResult.Value.ApplySettings(_prefix));
            if (commandResult.IsFailed)
            {
                HandlerError(commandResult, e);
                return;
            }

            commandResult = _commandHandler.IsCommandCanBeExecuted(commandResult.Value);
            if (commandResult.IsFailed)
            {
                HandlerError(commandResult, e);
                return;
            }

            Result <IBotMessage> executionResult = _commandHandler.ExecuteCommand(commandResult.Value);

            if (executionResult.IsFailed)
            {
                HandlerError(commandResult, e);
                return;
            }

            IBotMessage message = executionResult.Value;
            SenderInfo  sender  = commandResult.Value.Sender;

            //_apiProvider.WriteMessage(new BotEventArgs(executionResult.Value, commandResult.Value));
            message.Send(_apiProvider, sender);
        }
Exemplo n.º 17
0
        private void StartCommandParsing()
        {
            Console.WriteLine("Enter MPLS out label to direct packet to specific remote host and message you want to send.\n" +
                              "Input format: <<mpls_out_label>> [space] <<message>>");
            while (true)
            {
                Console.Write("> ");
                string input = Console.ReadLine();

                try
                {
                    (string mplsOutLabel, string message) = _commandParser.ParseCommand(input);
                    _clientNodeManager.Send(mplsOutLabel, message, _commandParser.CheckMplsOutLabel(mplsOutLabel));
                }
                catch (ParserException e)
                {
                    LOG.Warn(e.ExceptionMessage);
                }
            }
        }
Exemplo n.º 18
0
        void HandleClient(object obj)
        {
            Socket client = obj as Socket;

            while (IsServerWork)
            {
                try
                {
                    byte[] buffer = new byte[6500];
                    client.Receive(buffer); // Принимаем данные

                    Guid id = Guid.NewGuid();

                    ActAbstract command = commandParser.ParseCommand(buffer, client);

                    if (sender.ExistUser(client))
                    {
                        NewRequest?.Invoke(DateTime.Now, command.ToString().Split('.').Last(), id, sender.GetUserID(client));                          // Событие нового сообщения
                    }
                    else
                    {
                        NewRequest?.Invoke(DateTime.Now, command.ToString().Split('.').Last(), id, Guid.Empty);  // Событие нового сообщения
                    }
                    command.Execute();
                    NewResponse?.Invoke(DateTime.Now, id);
                }
                catch (SocketException)
                {
                    break; // Выходим из цикла
                }
            }

            // Заканчиваем подключение
            sender.RemoveUser(client);
            CliendDisconnect.Invoke();
            client.Shutdown(SocketShutdown.Both);
            client.Disconnect(false);
            client.Dispose();
        }
Exemplo n.º 19
0
        public static void Start(IReader reader, IWriter writer, ICommandParser parser)
        {
            Setup(reader, writer, parser);

            var command = reader.ReadLine();

            while (command != GlobalConstants.EndExecutionCommand)
            {
                try
                {
                    var result = commandParser.ParseCommand(command);

                    writer.WriteLine(result);
                }
                catch (Exception e)
                {
                    writer.WriteLine(e.Message);
                }

                command = reader.ReadLine();
            }
        }
Exemplo n.º 20
0
        public int Run(string[] args)
        {
            if (args.Length > 0 && args[0] == "--help")
            {
                var help = _helpGenerator.Build();
                Console.WriteLine(help);
                return(0);
            }

            var parsedVerb = _commandParser.ParseCommand(args);
            var verbType   = _verbTypeFinder.FindByName(parsedVerb.VerbName !);

            if (verbType == null)
            {
                throw new InvalidOperationException(
                          "Cannot find any verb class that can handle verbs. If your application does not have verbs, add a verb with the name default!");
            }

            var options = _optionsParser.CreatePopulatedOptionsObject(verbType !, parsedVerb);

            // The reason why we are registering and resolving it is because to inject the dependencies
            // the verb type might have.
            _serviceProvider.Register(verbType, verbType);
            var verbObject = (IVerbRunner)_serviceProvider.Resolve(verbType);

            if (options != null)
            {
                var optionsPropertyInfo = verbType !.GetProperty("Options");
                optionsPropertyInfo !.SetValue(verbObject, options);
            }

            VerbViewBase view = verbObject.Run();

            // Running the view to render the result to the console (stdout).
            // This could be a good extension point for various redirections.
            view.RenderResponse();
            return(Environment.ExitCode);
        }
Exemplo n.º 21
0
 private void SendCommand(object sender, MessageSentEventArgs e)
 {
     _commandParser.ParseCommand(e.Message);
 }
Exemplo n.º 22
0
 public int Run(string[] args)
 {
     return(_parser.ParseCommand(args));
 }
Exemplo n.º 23
0
        internal static Task Client_MessageReceived(SocketMessage arg)
        {
            SocketUserMessage userMessage = arg as SocketUserMessage;

            if (userMessage != null)
            {
                SocketTextChannel guildChannel = userMessage.Channel as SocketTextChannel;
                bool isGuildContext            = guildChannel != null;

                bool ispotentialCommand;
                if (isGuildContext)
                {
                    ispotentialCommand = CommandParser.IsPotentialCommand(userMessage.Content, guildChannel.Guild.Id);
                }
                else
                {
                    ispotentialCommand = CommandParser.IsPotentialCommand(userMessage.Content);
                }

                if (ispotentialCommand)
                {
                    IMessageContext      messageContext;
                    IGuildMessageContext guildMessageContext;
                    IDMCommandContext    commandContext;
                    IGuildCommandContext guildCommandContext;
                    if (isGuildContext)
                    {
                        guildMessageContext = new GuildMessageContext(userMessage, guildChannel.Guild);
                        messageContext      = guildMessageContext;
                    }
                    else
                    {
                        messageContext      = new MessageContext(userMessage);
                        guildMessageContext = null;
                    }

                    if (messageContext.IsDefined)
                    {
                        if (isGuildContext)
                        {
                            guildCommandContext = new GuildCommandContext(guildMessageContext, CommandParser.ParseCommand(guildMessageContext));
                            commandContext      = guildCommandContext;
                        }
                        else
                        {
                            commandContext      = new DMCommandContext(messageContext, CommandParser.ParseCommand(messageContext));
                            guildCommandContext = null;
                        }

                        if (isGuildContext)
                        {
                            if (!guildCommandContext.ChannelMeta.CheckChannelMeta(guildCommandContext.UserInfo, guildCommandContext.InterpretedCommand, out string error))
                            {
                                return(messageContext.Channel.SendEmbedAsync(error, true));
                            }
                        }

                        switch (commandContext.CommandSearch)
                        {
                        case CommandSearchResult.NoMatch:
                            return(messageContext.Message.AddReactionAsync(UnicodeEmoteService.Question));

                        case CommandSearchResult.PerfectMatch:
                            return(commandContext.InterpretedCommand.HandleCommandAsync(commandContext, guildCommandContext));

                        case CommandSearchResult.TooFewArguments:
                            return(messageContext.Channel.SendEmbedAsync($"The command `{commandContext.InterpretedCommand}` requires a minimum of {commandContext.InterpretedCommand.MinimumArgumentCount} arguments!", true));

                        case CommandSearchResult.TooManyArguments:
                            return(commandContext.InterpretedCommand.HandleCommandAsync(commandContext, guildCommandContext));
                        }
                    }
                }
            }
            return(Task.CompletedTask);
        }
        private Result FlushTextBuffer(Session session)
        {
            bool isCommand = false;
            var  input     = string.Join(string.Empty, session.Data.ToArray());

            try
            {
                if (session.SignedIn)
                {
                    ICommand command;
                    if ((command = commandParser
                                   .ParseCommand(CultureInfo.InvariantCulture, input, out var processedInput)) != null &&
                        !string.IsNullOrEmpty(processedInput))
                    {
                        isCommand = true;
                        input     = processedInput;
                    }
                }

                // do not send empty character arrays to the input simulator it throws an argument null exception
                if (!string.IsNullOrWhiteSpace(input))
                {
                    input = input.Trim();

                    if (input.Equals(":quit"))
                    {
                        return(Result.Success(true));
                    }

                    if (input.StartsWith(setUserNamePrecursor))
                    {
                        session.UserName = input
                                           .Replace(setUserNamePrecursor, string.Empty);
                        WriteText(session.DataStream, $"User name has been set to {session.UserName}, this will be reset on session termination.", Encoding.ASCII);

                        return(Result.Success());
                    }

                    if (input.StartsWith(getUserNamePrecursor))
                    {
                        if (string.IsNullOrWhiteSpace(session.UserName))
                        {
                            WriteText(
                                session.DataStream,
                                $"User name has not been set, you can set the user name at any time with {setUserNamePrecursor}",
                                Encoding.ASCII);

                            return(Result.Success());
                        }

                        WriteText(session.DataStream, $"User name has been set to {session.UserName}", Encoding.ASCII);
                        return(Result.Success());
                    }

                    if (input.StartsWith(loginPrecursor))
                    {
                        WriteText(session.DataStream, "Please wait...", Encoding.ASCII);
                        Task.Delay(1000);
                        session.SignedIn = input
                                           .Replace(loginPrecursor, string.Empty)
                                           .Equals(applicationSettings.Security.Password);

                        WriteText(session.DataStream, "Done! If the password was valid you should have access to all areas.", Encoding.ASCII);
                        if (session.SignedIn)
                        {
                            logger.LogInformation("Remote utility sign-in successful");
                        }
                        else
                        {
                            logger.LogWarning("Remote utility sign-in unsuccessful");
                        }

                        return(Result.Success());
                    }

                    if (session.SignedIn)
                    {
                        return(ProcessWhenSignedIn(session, input, isCommand));
                    }
                }
            }
            finally
            {
                session.Data.Clear();
            }

            return(Result.Failed());
        }