Пример #1
0
        public void Invoke(string[] args)
        {
            var options = new OptionSet();
            options.Add(
                "?|help",
                "Show help information.",
                x =>
                {
                    HelpUtility.WriteHelpInformation(
                        this.CommandResult,
                        this.Name,
                        this.Parameters,
                        this.Description,
                        options
                    );
                }
            );

            bool matchFound = false;

            if (args != null)
            {
                try
                {
                    var extra = options.Parse(args);
                    matchFound = args.Length != extra.Count;
                }
                catch (OptionException ex)
                {
                    this.CommandResult.WriteLine(ex.Message);
                }
            }

            if (!matchFound)
            {
                var registrationStatus = _variableRepository.GetVariable("Registration");
                if (registrationStatus.Value.Equals("Open", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (args.IsNullOrEmpty())
                    {
                        this.CommandResult.WriteLine("Enter your desired username.");
                        this.CommandResult.CommandContext.Set(ContextStatus.Forced, this.Name, args, "Username");
                    }
                    else if (args.Length == 1)
                    {
                        if (args[0].Length > 3)
                        {
                            if (!_userRepository.CheckUserExists(args[0]))
                            {
                                this.CommandResult.WriteLine("Enter your desired password.");
                                this.CommandResult.PasswordField = true;
                                this.CommandResult.CommandContext.Set(ContextStatus.Forced, this.Name, args, "Password");
                            }
                            else
                            {
                                this.CommandResult.WriteLine("Username already exists.");
                                this.CommandResult.WriteLine("Enter a different username.");
                                this.CommandResult.CommandContext.Set(ContextStatus.Forced, this.Name, null, "Username");
                            }
                        }
                        else
                        {
                            this.CommandResult.WriteLine("Username must be at least four characters long.");
                            this.CommandResult.WriteLine("Enter a different username.");
                            this.CommandResult.CommandContext.Set(ContextStatus.Forced, this.Name, null, "Username");
                        }
                    }
                    else if (args.Length == 2)
                    {
                        if (args[0].Length > 3)
                        {
                            if (!_userRepository.CheckUserExists(args[0]))
                            {
                                this.CommandResult.WriteLine("Re-enter your desired password.");
                                this.CommandResult.PasswordField = true;
                                this.CommandResult.CommandContext.Set(ContextStatus.Forced, this.Name, args, "Confirm Password");
                            }
                            else
                            {
                                this.CommandResult.WriteLine("Username already exists.");
                                this.CommandResult.WriteLine("Enter your desired username.");
                                this.CommandResult.CommandContext.Set(ContextStatus.Forced, this.Name, null, "Username");
                            }
                        }
                        else
                        {
                            this.CommandResult.WriteLine("Username must be at least four characters long.");
                            this.CommandResult.WriteLine("Enter a different username.");
                            this.CommandResult.CommandContext.Set(ContextStatus.Forced, this.Name, null, "Username");
                        }
                    }
                    else if (args.Length == 3)
                    {
                        if (args[0].Length > 3)
                        {
                            var user = this._userRepository.GetUser(args[0]);
                            if (user == null)
                            {
                                if (args[1] == args[2])
                                {
                                    user = new User
                                    {
                                        Username = args[0],
                                        Password = args[1],
                                        JoinDate = DateTime.UtcNow,
                                        LastLogin = DateTime.UtcNow,
                                        TimeZone = "UTC",
                                        Sound = true
                                    };
                                    _userRepository.AddRoleToUser(user, "User");
                                    _userRepository.AddUser(user);

                                    this.CommandResult.CurrentUser = user;
                                    this.CommandResult.WriteLine("Thank you for registering.");
                                    this.CommandResult.WriteLine();
                                    var STATS = this.AvailableCommands.SingleOrDefault(x => x.Name.Is("STATS"));
                                    STATS.Invoke(new string[] { "-users" });
                                    this.CommandResult.WriteLine();
                                    this.CommandResult.WriteLine("You are now logged in as {0}.", this.CommandResult.CurrentUser.Username);
                                    this.CommandResult.CommandContext.Deactivate();
                                }
                                else
                                {
                                    this.CommandResult.WriteLine("Passwords did not match.");
                                    this.CommandResult.WriteLine("Enter your desired password.");
                                    this.CommandResult.PasswordField = true;
                                    this.CommandResult.CommandContext.Set(ContextStatus.Forced, this.Name, new string[] { args[0] }, "Password");
                                }
                            }
                            else
                            {
                                this.CommandResult.WriteLine("Username already exists.");
                                this.CommandResult.WriteLine("Enter your desired username.");
                                this.CommandResult.CommandContext.Set(ContextStatus.Forced, this.Name, null, "Username");
                            }
                        }
                        else
                        {
                            this.CommandResult.WriteLine("Username must be at least four characters long.");
                            this.CommandResult.WriteLine("Enter a different username.");
                            this.CommandResult.CommandContext.Set(ContextStatus.Forced, this.Name, null, "Username");
                        }
                    }
                }
                else
                    this.CommandResult.WriteLine("Registration is currently closed.");
            }
        }
Пример #2
0
 /// <summary>
 /// Deletes a user from the data context.
 /// </summary>
 /// <param name="user">The user to be deleted.</param>
 public void DeleteUser(User user)
 {
     _entityContainer.Users.Remove(user);
 }
Пример #3
0
 /// <summary>
 /// Adds a user to the data context.
 /// </summary>
 /// <param name="user">The user to be added.</param>
 public void AddUser(User user)
 {
     _entityContainer.Users.Add(user);
     _entityContainer.SaveChanges();
 }
Пример #4
0
 /// <summary>
 /// Associate a role with the user.
 /// </summary>
 /// <param name="roleName">The name of the role to associate.</param>
 public void AddRoleToUser(User user, string roleName)
 {
     var role = _entityContainer.Roles.Single(x => x.Name.Equals(roleName, StringComparison.InvariantCultureIgnoreCase));
     user.Roles.Add(role);
 }
Пример #5
0
 /// <summary>
 /// Updates an existing user in the data context.
 /// </summary>
 /// <param name="user">The user to be updated.</param>
 public void UpdateUser(User user)
 {
     _entityContainer.SaveChanges();
 }
Пример #6
0
        /// <summary>
        /// Accepts a command string and handles the parsing and execution of the command and the included arguments.
        /// </summary>
        /// <param name="commandString">The command string. Usually a string passed in from a command line interface by the user.</param>
        /// <returns>A CommandResult option containing properties relevant to how data should be processed by the UI.</returns>
        public CommandResult ExecuteCommand(string commandString)
        {
            if (commandString == null) commandString = string.Empty;
            var hasSpace = commandString.Contains(' ');
            var spaceIndex = 0;
            if (hasSpace)
                spaceIndex = commandString.IndexOf(' ');

            // Parse command string to find the command name.
            string commandName = hasSpace ? commandString.Remove(spaceIndex) : commandString;

            if (_currentUser != null)
            {
                _currentUser.LastLogin = DateTime.UtcNow;
                _userRepository.UpdateUser(_currentUser);

                // Check for alias. Replace command name with alias.
                if ((_commandContext.Status & ContextStatus.Forced) == 0)
                {
                    var alias = _aliasRepository.GetAlias(_currentUser.Username, commandName);
                    if (alias != null)
                    {
                        commandString = hasSpace ? alias.Command + commandString.Remove(0, spaceIndex) : alias.Command;
                        hasSpace = commandString.Contains(' ');
                        spaceIndex = 0;
                        if (hasSpace)
                            spaceIndex = commandString.IndexOf(' ');
                        commandName = hasSpace ? commandString.Remove(spaceIndex) : commandString;
                    }
                }
            }

            // Parse command string and divide up arguments into a string array.
            var args = hasSpace ?
                commandString.Remove(0, spaceIndex)
                .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) : null;

            // Obtain all roles the current user is a part of.
            var availableRoles = _currentUser != null ? _currentUser.Roles.Select(x => x.Name).ToArray() : new string[] { "Visitor" };

            // Create command result.
            var commandResult = new CommandResult
            {
                Command = commandName.ToUpper(),
                CurrentUser = _currentUser,
                CommandContext = this._commandContext
            };

            // Obtain all commands for the roles the user is a part of.
            var commands = _commands
                .Where(x => x.Roles.Any(y => availableRoles.Any(z => z.Is(y))))
                .ToList();

            foreach (var cmd in commands)
            {
                cmd.CommandResult = commandResult;
                cmd.AvailableCommands = commands;
            }

            if (_currentUser != null && _currentUser.BanInfo != null)
                if (DateTime.UtcNow < _currentUser.BanInfo.EndDate)
                    return BanMessage(commandResult);
                else
                {
                    _userRepository.UnbanUser(_currentUser.Username);
                    _userRepository.UpdateUser(_currentUser);
                }

            // Obtain the command the user intends to execute from the list of available commands.
            var command = commands.SingleOrDefault(x => x.Name.Is(commandName));

            if (commandName.Is("INITIALIZE"))
                this._commandContext.Deactivate();

            // Perform different behaviors based on the current command context.
            switch (this._commandContext.Status)
            {
                // Perform normal command execution.
                case ContextStatus.Disabled:
                    if (command != null)
                    {
                        command.CommandResult.Command = command.Name;
                        command.Invoke(args);
                    }
                    break;

                // Perform normal command execution.
                // If command does not exist, attempt to use command context instead.
                case ContextStatus.Passive:
                    if (command != null)
                    {
                        command.CommandResult.Command = command.Name;
                        command.Invoke(args);
                    }
                    else if (!commandName.Is("HELP"))
                    {
                        command = commands.SingleOrDefault(x => x.Name.Is(this._commandContext.Command));
                        if (command != null)
                        {
                            args = commandString.Contains(' ') ? commandString.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries) : new string[] { commandString };
                            var newArgs = new List<string>();
                            if (this._commandContext.Args != null) newArgs.AddRange(this._commandContext.Args);
                            newArgs.AddRange(args);
                            command.CommandResult.Command = command.Name;
                            command.Invoke(newArgs.ToArray());
                        }
                    }
                    break;

                // Perform command execution using command context.
                // Reset command context if "CANCEL" is supplied.
                case ContextStatus.Forced:
                    if (!commandName.Is("CANCEL"))
                    {
                        command = commands.SingleOrDefault(x => x.Name.Is(this._commandContext.Command));
                        if (command != null)
                        {
                            command.CommandResult.Command = command.Name;
                            if (this._commandContext.Prompt)
                            {
                                var newStrings = new List<string>();
                                if (this._commandContext.PromptData != null)
                                    newStrings.AddRange(this._commandContext.PromptData);
                                newStrings.Add(commandString);
                                this._commandContext.PromptData = newStrings.ToArray();
                                command.Invoke(this._commandContext.Args);
                            }
                            else
                            {
                                args = commandString.Contains(' ') ? commandString.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries) : new string[] { commandString };
                                var newArgs = new List<string>();
                                if (this._commandContext.Args != null) newArgs.AddRange(this._commandContext.Args);
                                newArgs.AddRange(args);
                                args = newArgs.ToArray();
                                command.Invoke(args);
                            }
                        }
                    }
                    else
                    {
                        commandResult.CommandContext.Restore();
                        commandResult.WriteLine("Action canceled.");
                    }
                    break;
            }

            // If command does not exist, check if the command was "HELP".
            // If so, call the ShowHelp method to show help information for all available commands.
            if (command == null)
            {
                if (commandName.Is("HELP"))
                    commandResult = DisplayHelp(commands, args, commandResult);
                else if (!commandName.Is("CANCEL"))
                    if (commandName.IsNullOrWhiteSpace())
                        commandResult.WriteLine("You must supply a command.");
                    else
                        commandResult.WriteLine("'{0}' is not a recognized command or is not available in the current context.", commandName);
            }

            _currentUser = commandResult.CurrentUser;
            if (_currentUser != null && _currentUser.BanInfo != null)
                if (DateTime.UtcNow < _currentUser.BanInfo.EndDate)
                    return BanMessage(commandResult);
                else
                {
                    _userRepository.UnbanUser(_currentUser.Username);
                    _userRepository.UpdateUser(_currentUser);
                }

            // Temporarily notify of messages on each command execution.
            if (_currentUser != null)
            {
                var unreadMessageCount = _messageRepository.UnreadMessages(_currentUser.Username);
                if (unreadMessageCount > 0)
                {
                    commandResult.WriteLine();
                    commandResult.WriteLine("You have {0} unread message(s).", unreadMessageCount);
                }
            }

            commandResult.TerminalTitle = string.Format("Terminal - {0}", _currentUser != null ? _currentUser.Username : "******");

            FinalParsing(commandResult);

            return commandResult;
        }