public void Invoke(string[] args) { var options = new OptionSet(); options.Add( "?|help", "Show help information.", x => HelpUtility.WriteHelpInformation(this, options) ); bool matchFound = false; if (args != null) { try { var extra = options.Parse(args); matchFound = args.Length != extra.Count; } catch (OptionException ex) { CommandResult.WriteLine(ex.Message); } } if (!matchFound) { if (args.IsNullOrEmpty()) { CommandResult.WriteLine("You must supply a username."); } else if (args.Length == 1) { var username = args[0]; if (!_dataBucket.UserRepository.CheckUserExists(username)) { var random = new Random(); string code = random.Next(1 << 16).ToString("X4") + random.Next(1 << 16).ToString("X4") + random.Next(1 << 16).ToString("X4") + random.Next(1 << 16).ToString("X4"); var inviteCode = new InviteCode { Code = code, Username = username }; _dataBucket.InviteCodeRepository.AddInviteCode(inviteCode); _dataBucket.SaveChanges(); CommandResult.WriteLine("Invite Code: {0}", code); } else { CommandResult.WriteLine("That username already exists."); } } } }
public void Invoke(string[] args) { var options = new OptionSet(); options.Add( "?|help", "Show help information.", x => HelpUtility.WriteHelpInformation(this, options) ); bool matchFound = false; if (args != null) { try { var extra = options.Parse(args); matchFound = args.Length != extra.Count; } catch (OptionException ex) { CommandResult.WriteLine(ex.Message); } } if (!matchFound) { if (args.IsNullOrEmpty()) { CommandResult.CurrentUser.LastLogin = DateTime.UtcNow.AddMinutes(-10); _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); _dataBucket.SaveChanges(); CommandResult.WriteLine("You have been logged out."); CommandResult.CurrentUser = null; } } }
public void Invoke(string[] args) { bool showHelp = false; string newAlias = null; string deleteAlias = null; var options = new OptionSet(); options.Add( "?|help", "Show help information.", x => showHelp = x != null ); options.Add( "n|new=", "Create a new {alias}.", x => newAlias = x ); options.Add( "d|delete=", "Delete an existing {alias}.", x => deleteAlias = x ); if (args == null) { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } else { try { var parsedArgs = options.Parse(args).ToArray(); if (parsedArgs.Length == args.Length) { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } else { if (showHelp) { HelpUtility.WriteHelpInformation(this, options); } else if (newAlias != null) { if (!newAlias.Is("HELP") && !AvailableCommands.Any(x => x.Name.Is(newAlias))) { var alias = _dataBucket.AliasRepository.GetAlias(CommandResult.CurrentUser.Username, newAlias); if (alias == null) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Type the value that should be sent to the terminal when you use your new alias."); CommandResult.SetPrompt(Name, args, string.Format("{0} VALUE", newAlias.ToUpper())); } else if (CommandResult.CommandContext.PromptData.Length == 1) { _dataBucket.AliasRepository.AddAlias(new Alias { Username = CommandResult.CurrentUser.Username, Shortcut = newAlias, Command = CommandResult.CommandContext.PromptData[0] }); _dataBucket.SaveChanges(); CommandResult.WriteLine("Alias '{0}' was successfully defined.", newAlias.ToUpper()); CommandResult.RestoreContext(); } } else { CommandResult.WriteLine("You have already defined an alias named '{0}'.", newAlias.ToUpper()); } } else { CommandResult.WriteLine("'{0}' is an existing command. You cannot create aliases with the same name as existing commands.", newAlias.ToUpper()); } } else if (deleteAlias != null) { var alias = _dataBucket.AliasRepository.GetAlias(CommandResult.CurrentUser.Username, deleteAlias); if (alias != null) { _dataBucket.AliasRepository.DeleteAlias(alias); _dataBucket.SaveChanges(); CommandResult.WriteLine("Alias '{0}' was successfully deleted.", deleteAlias.ToUpper()); } else { CommandResult.WriteLine("You have not defined an alias named '{0}'.", deleteAlias.ToUpper()); } } } } catch (OptionException ex) { CommandResult.WriteLine(ex.Message); } } }
/// <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; _dataBucket.UserRepository.UpdateUser(_currentUser); _dataBucket.SaveChanges(); } // Check for alias. Replace command name with alias. if ((_commandContext.Status & ContextStatus.Forced) == 0) { var alias = defaultAliases.SingleOrDefault(x => x.Shortcut.Is(commandName)); if (_currentUser != null) { alias = _dataBucket.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(TerminalEvents) { Command = commandName.ToUpper(), CurrentUser = _currentUser, CommandContext = _commandContext, IPAddress = _ipAddress, }; // 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 { _dataBucket.UserRepository.UnbanUser(_currentUser.Username); _dataBucket.UserRepository.UpdateUser(_currentUser); _dataBucket.SaveChanges(); } } // 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")) { commandResult.DeactivateContext(); } // Perform different behaviors based on the current command context. switch (_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(_commandContext.Command)); if (command != null) { args = commandString.Contains(' ') ? commandString.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries) : new string[] { commandString }; var newArgs = new List <string>(); if (_commandContext.Args != null) { newArgs.AddRange(_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(_commandContext.Command)); if (command != null) { command.CommandResult.Command = command.Name; if (_commandContext.Prompt) { var newStrings = new List <string>(); if (_commandContext.PromptData != null) { newStrings.AddRange(_commandContext.PromptData); } newStrings.Add(commandString); _commandContext.PromptData = newStrings.ToArray(); command.Invoke(_commandContext.Args); } else { args = commandString.Contains(' ') ? commandString.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries) : new string[] { commandString }; var newArgs = new List <string>(); if (_commandContext.Args != null) { newArgs.AddRange(_commandContext.Args); } newArgs.AddRange(args); args = newArgs.ToArray(); command.Invoke(args); } } } else { commandResult.RestoreContext(); 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 { _dataBucket.UserRepository.UnbanUser(_currentUser.Username); _dataBucket.UserRepository.UpdateUser(_currentUser); _dataBucket.SaveChanges(); } } // Temporarily notify of messages on each command execution. if (_currentUser != null) { var unreadMessageCount = _dataBucket.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); }
public void Invoke(string[] args) { var options = new OptionSet(); options.Add( "?|help", "Show help information.", x => HelpUtility.WriteHelpInformation(this, options) ); List <string> parsedArgs = null; if (args != null) { try { parsedArgs = options.Parse(args); } catch (OptionException ex) { CommandResult.WriteLine(ex.Message); } } var registrationStatus = _dataBucket.VariableRepository.GetVariable("Registration"); if (registrationStatus.Equals("Open", StringComparison.InvariantCultureIgnoreCase) || CommandResult.CommandContext.PromptData != null) { CommandResult.CommandContext.Prompt = false; InviteCode inviteCode = null; if (CommandResult.CommandContext.PromptData != null) { inviteCode = _dataBucket.InviteCodeRepository.GetInviteCode(CommandResult.CommandContext.PromptData[0]); } if (CommandResult.CommandContext.PromptData == null || inviteCode != null) { if (inviteCode != null) { if (parsedArgs == null) { parsedArgs = new List <string> { inviteCode.Username } } ; else { parsedArgs.Insert(0, inviteCode.Username); } } if ((parsedArgs == null || parsedArgs.Count == 0)) { CommandResult.WriteLine("Enter your desired username. (no spaces. sorry.)"); CommandResult.SetContext(ContextStatus.Forced, Name, args, "Username"); } else if (parsedArgs.Count == 1) { if (parsedArgs[0].Length >= 3 && parsedArgs[0].Length <= 30) { if (!_dataBucket.UserRepository.CheckUserExists(parsedArgs[0])) { CommandResult.WriteLine("Enter your desired password."); CommandResult.PasswordField = true; CommandResult.SetContext(ContextStatus.Forced, Name, args, "Password"); } else { CommandResult.WriteLine("Username already exists."); CommandResult.WriteLine("Enter a different username."); CommandResult.SetContext(ContextStatus.Forced, Name, null, "Username"); } } else { CommandResult.WriteLine("Username must be between 3 and 15 characters."); CommandResult.WriteLine("Enter a different username."); CommandResult.SetContext(ContextStatus.Forced, Name, null, "Username"); } } else if (parsedArgs.Count == 2) { if (parsedArgs[0].Length >= 3 && parsedArgs[0].Length <= 15) { if (!_dataBucket.UserRepository.CheckUserExists(parsedArgs[0])) { CommandResult.WriteLine("Re-enter your desired password."); CommandResult.PasswordField = true; CommandResult.SetContext(ContextStatus.Forced, Name, args, "Confirm Password"); } else { CommandResult.WriteLine("Username already exists."); CommandResult.WriteLine("Enter your desired username."); CommandResult.SetContext(ContextStatus.Forced, Name, null, "Username"); } } else { CommandResult.WriteLine("Username must be between 3 and 15 characters."); CommandResult.WriteLine("Enter a different username."); CommandResult.SetContext(ContextStatus.Forced, Name, null, "Username"); } } else if (parsedArgs.Count == 3) { if (parsedArgs[0].Length >= 3 && parsedArgs[0].Length <= 15) { var user = _dataBucket.UserRepository.GetUser(parsedArgs[0]); if (user == null) { if (parsedArgs[1] == parsedArgs[2]) { user = new User { Username = parsedArgs[0], Password = parsedArgs[1], JoinDate = DateTime.UtcNow, LastLogin = DateTime.UtcNow, TimeZone = "UTC", Sound = true, }; var role = _dataBucket.UserRepository.GetRole("User"); user.Roles = new List <Role> { role }; if (inviteCode != null) { _dataBucket.InviteCodeRepository.DeleteInviteCode(inviteCode); } _dataBucket.UserRepository.AddUser(user); _dataBucket.SaveChanges(); var defaultAliases = new List <Alias> { new Alias { Username = user.Username, Shortcut = "lb", Command = "BOARDS" }, new Alias { Username = user.Username, Shortcut = "b", Command = "BOARD" }, new Alias { Username = user.Username, Shortcut = "t", Command = "TOPIC" }, new Alias { Username = user.Username, Shortcut = "lm", Command = "MESSAGES" }, new Alias { Username = user.Username, Shortcut = "m", Command = "MESSAGE" } }; defaultAliases.ForEach(x => _dataBucket.AliasRepository.AddAlias(x)); _dataBucket.SaveChanges(); CommandResult.CurrentUser = user; CommandResult.WriteLine("Thank you for registering."); //CommandResult.WriteLine(); //var STATS = AvailableCommands.SingleOrDefault(x => x.Name.Is("STATS")); //STATS.Invoke(new string[] { "-users" }); CommandResult.WriteLine(); CommandResult.WriteLine("You are now logged in as {0}.", CommandResult.CurrentUser.Username); CommandResult.DeactivateContext(); } else { CommandResult.WriteLine("Passwords did not match."); CommandResult.WriteLine("Enter your desired password."); CommandResult.PasswordField = true; CommandResult.SetContext(ContextStatus.Forced, Name, new string[] { parsedArgs[0] }, "Password"); } } else { CommandResult.WriteLine("Username already exists."); CommandResult.WriteLine("Enter your desired username."); CommandResult.SetContext(ContextStatus.Forced, Name, null, "Username"); } } else { CommandResult.WriteLine("Username must be between 3 and 15 characters."); CommandResult.WriteLine("Enter a different username."); CommandResult.SetContext(ContextStatus.Forced, Name, null, "Username"); } } } else { CommandResult.WriteLine("You did not supply a valid invite code."); CommandResult.DeactivateContext(); } } else if (registrationStatus.Equals("Invite-Only", StringComparison.InvariantCultureIgnoreCase)) { CommandResult.WriteLine("Enter your invite code."); CommandResult.SetPrompt(Name, args, "Invite Code"); } else if (registrationStatus.Equals("Closed", StringComparison.InvariantCultureIgnoreCase)) { CommandResult.WriteLine("Registration is currently closed."); } }
public void Invoke(string[] args) { bool showHelp = false; bool? ignore = null; bool warn = false; bool? ban = null; bool history = false; string addRole = null; string removeRole = null; string giveCredits = null; string giveInvites = null; var options = new OptionSet(); options.Add( "?|help", "Show help information.", x => showHelp = x != null ); options.Add( "i|ignore", "Ignore the specified user.", x => ignore = x != null ); if (CommandResult.CurrentUser.IsModerator || CommandResult.CurrentUser.IsAdministrator) { options.Add( "h|history", "Show warning & ban history for the user.", x => history = x != null ); options.Add( "w|warn", "Warn the user about an offense.", x => warn = x != null ); options.Add( "b|ban", "Ban the user for a specified amount of time.", x => ban = x != null ); } if (CommandResult.CurrentUser.IsAdministrator) { options.Add( "addRole=", "Add the specified role to the user.", x => addRole = x ); options.Add( "removeRole=", "Remove the specified role from the user.", x => removeRole = x ); } if (args == null) { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } else { try { var parsedArgs = options.Parse(args).ToArray(); if (parsedArgs.Length == args.Length) { if (parsedArgs.Length == 1) { var user = _dataBucket.UserRepository.GetUser(parsedArgs[0]); if (user != null) { // display user profile. } else { CommandResult.WriteLine("There is no user with the username '{0}'.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must specify a username."); } } else { if (showHelp) { HelpUtility.WriteHelpInformation(this, options); } else if (warn) { if (parsedArgs.Length == 1) { var user = _dataBucket.UserRepository.GetUser(parsedArgs[0]); if (user != null) { if ((!user.IsModerator && !user.IsAdministrator) || CommandResult.CurrentUser.IsAdministrator) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Type the details of your warning to '{0}'.", user.Username); CommandResult.SetPrompt(Name, args, string.Format("{0} WARNING", user.Username)); } else if (CommandResult.CommandContext.PromptData.Length == 1) { user.UserActivityLog.Add(new UserActivityLogItem { Type = "Warning", Date = DateTime.UtcNow, Information = string.Format( "Warning given by '{0}'\n\nDetails: {1}", CommandResult.CurrentUser.Username, CommandResult.CommandContext.PromptData[0] ) }); user.ReceivedMessages.Add(new Message { Sender = CommandResult.CurrentUser.Username, SentDate = DateTime.UtcNow, Subject = string.Format( "{0} has given you a warning.", CommandResult.CurrentUser.Username ), Body = string.Format( "You have been given a warning by '{0}'.\n\n{1}", CommandResult.CurrentUser.Username, CommandResult.CommandContext.PromptData[0] ) }); _dataBucket.UserRepository.UpdateUser(user); _dataBucket.SaveChanges(); CommandResult.RestoreContext(); CommandResult.WriteLine("Warning successfully issued to '{0}'.", user.Username); } } else { CommandResult.WriteLine("You are not authorized to give warnings to user '{0}'.", user.Username); } } else { CommandResult.WriteLine("There is no user with the username '{0}'.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must specify a username."); } } else if (ban != null) { if (parsedArgs.Length == 1) { var user = _dataBucket.UserRepository.GetUser(parsedArgs[0]); if (user != null) { if ((!user.IsModerator && !user.IsAdministrator) || CommandResult.CurrentUser.IsAdministrator) { if ((bool)ban) { if (user.BanInfo == null) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("How severe should the ban be?"); CommandResult.WriteLine(); CommandResult.WriteLine("1 = One Hour"); CommandResult.WriteLine("2 = Three Hours"); CommandResult.WriteLine("3 = One Day"); CommandResult.WriteLine("4 = One Week"); CommandResult.WriteLine("5 = One Month"); CommandResult.WriteLine("6 = One Year"); CommandResult.WriteLine("7 = 42 Years"); CommandResult.SetPrompt(Name, args, string.Format("{0} BAN SEVERITY", user.Username)); } else if (CommandResult.CommandContext.PromptData.Length == 1) { string promptData = CommandResult.CommandContext.PromptData[0]; if (promptData.IsShort()) { var banType = promptData.ToShort(); if (banType >= 1 && banType <= 7) { CommandResult.WriteLine("Type a reason for this ban."); CommandResult.SetPrompt(Name, args, string.Format("{0} BAN REASON", user.Username)); } else { CommandResult.WriteLine("'{0}' is not a valid ban type.", banType); } } else { CommandResult.WriteLine("'{0}' is not a valid ban type.", promptData); } } else if (CommandResult.CommandContext.PromptData.Length == 2) { string promptData = CommandResult.CommandContext.PromptData[0]; if (promptData.IsShort()) { var banType = promptData.ToShort(); if (banType >= 1 && banType <= 7) { DateTime expirationDate = DateTime.UtcNow; switch (banType) { case 1: expirationDate = DateTime.UtcNow.AddHours(1); break; case 2: expirationDate = DateTime.UtcNow.AddHours(3); break; case 3: expirationDate = DateTime.UtcNow.AddDays(1); break; case 4: expirationDate = DateTime.UtcNow.AddDays(7); break; case 5: expirationDate = DateTime.UtcNow.AddMonths(1); break; case 6: expirationDate = DateTime.UtcNow.AddYears(1); break; case 7: expirationDate = DateTime.UtcNow.AddYears(42); break; } user.UserActivityLog.Add(new UserActivityLogItem { Type = "Ban", Date = DateTime.UtcNow, Information = string.Format( "Ban given by '{0}'\n\nExpiration: {1}\n\nDetails: {2}", CommandResult.CurrentUser.Username, expirationDate.TimeUntil(), CommandResult.CommandContext.PromptData[1] ) }); CommandResult.CurrentUser.BannedUsers.Add(new Ban { StartDate = DateTime.UtcNow, EndDate = expirationDate, Username = user.Username, Reason = CommandResult.CommandContext.PromptData[1] }); _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); _dataBucket.SaveChanges(); CommandResult.RestoreContext(); CommandResult.WriteLine("'{0}' banned successfully.", user.Username); } else { CommandResult.WriteLine("'{0}' is not a valid ban type.", banType); } } else { CommandResult.WriteLine("'{0}' is not a valid ban type.", promptData); } } } else { CommandResult.WriteLine("User '{0}' is already banned.", user.Username); } } else { if (user.BanInfo != null) { _dataBucket.UserRepository.UnbanUser(user.Username); _dataBucket.UserRepository.UpdateUser(user); _dataBucket.SaveChanges(); CommandResult.WriteLine("User '{0}' successfully unbanned.", user.Username); } else { CommandResult.WriteLine("User '{0}' is not banned.", user.Username); } } } else { CommandResult.WriteLine("You are not authorized to ban user '{0}'.", user.Username); } } else { CommandResult.WriteLine("There is no user with the username '{0}'.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must specify a username."); } } else { if (history) { if (parsedArgs.Length == 1) { var user = _dataBucket.UserRepository.GetUser(parsedArgs[0]); if (user != null) { var offenseLog = _dataBucket.UserRepository.GetOffenseHistory(user.Username); CommandResult.WriteLine(DisplayMode.Dim | DisplayMode.DontType, new string('-', AppSettings.DividerLength)); foreach (var logItem in offenseLog) { CommandResult.WriteLine(); if (logItem.Type.Is("Ban")) { CommandResult.WriteLine(DisplayMode.DontType, "'{0}' was banned {1}.", user.Username, logItem.Date.TimePassed()); } else if (logItem.Type.Is("Warning")) { CommandResult.WriteLine(DisplayMode.DontType, "'{0}' was warned {1}.", user.Username, logItem.Date.TimePassed()); } CommandResult.WriteLine(); CommandResult.WriteLine(DisplayMode.DontType, logItem.Information); CommandResult.WriteLine(); CommandResult.WriteLine(DisplayMode.Dim | DisplayMode.DontType, new string('-', AppSettings.DividerLength)); } if (offenseLog.Count() == 0) { CommandResult.WriteLine(); CommandResult.WriteLine("User '{0}' does not have any offenses.", user.Username); } } else { CommandResult.WriteLine("There is no user with the username '{0}'.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must specify a username."); } } if (ignore != null) { if (parsedArgs.Length == 1) { var user = _dataBucket.UserRepository.GetUser(parsedArgs[0]); if (user != null) { var ignoreItem = CommandResult.CurrentUser.Ignores .SingleOrDefault(x => x.IgnoredUser.Equals(user.Username)); if ((bool)ignore) { if (ignoreItem == null) { _dataBucket.UserRepository.IgnoreUser(CommandResult.CurrentUser.Username, user.Username); _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); _dataBucket.SaveChanges(); CommandResult.WriteLine("'{0}' successfully ignored.", user.Username); } else { CommandResult.WriteLine("You have already ignored '{0}'.", user.Username); } } else if (!(bool)ignore) { if (ignoreItem != null) { _dataBucket.UserRepository.UnignoreUser(CommandResult.CurrentUser.Username, user.Username); _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); _dataBucket.SaveChanges(); CommandResult.WriteLine("'{0}' successfully unignored.", user.Username); } else { CommandResult.WriteLine("You have not ignored any users with the username '{0}'.", user.Username); } } } else { CommandResult.WriteLine("There is no user with the username '{0}'.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must specify a username."); } } if (addRole != null) { if (parsedArgs.Length == 1) { var user = _dataBucket.UserRepository.GetUser(parsedArgs[0]); if (user != null) { var role = _dataBucket.UserRepository.GetRole(addRole); if (role != null) { user.Roles.Add(role); _dataBucket.UserRepository.UpdateUser(user); _dataBucket.SaveChanges(); CommandResult.WriteLine("Role '{0}' added to '{1}' successfully.", role.Name, user.Username); } else { CommandResult.WriteLine("There is no role '{0}'.", addRole); } } else { CommandResult.WriteLine("There is no user with the username '{0}'.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must specify a username."); } } if (removeRole != null) { if (parsedArgs.Length == 1) { var user = _dataBucket.UserRepository.GetUser(parsedArgs[0]); if (user != null) { var role = _dataBucket.UserRepository.GetRole(removeRole); if (role != null) { user.Roles.Remove(role); _dataBucket.UserRepository.UpdateUser(user); _dataBucket.SaveChanges(); CommandResult.WriteLine("Role '{0}' removed from '{1}' successfully.", role.Name, user.Username); } else { CommandResult.WriteLine("There is no role '{0}'.", addRole); } } else { CommandResult.WriteLine("There is no user with the username '{0}'.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must specify a username."); } } } } } catch (OptionException ex) { CommandResult.WriteLine(ex.Message); } } }
public void Invoke(string[] args) { bool showHelp = false; bool newTopic = false; bool modTopic = false; bool refresh = false; bool?lockBoard = null; var options = new OptionSet(); options.Add( "?|help", "Show help information.", x => showHelp = x != null ); options.Add( "R|refresh", "Refresh the current board.", x => refresh = x != null ); if (CommandResult.IsUserLoggedIn) { options.Add( "nt|newTopic", "Create new topic on the specified board.", x => newTopic = x != null ); } if (CommandResult.UserLoggedAndModOrAdmin()) { options.Add( "mt|modTopic", "Create a topic that only moderators can see.", x => { newTopic = x != null; modTopic = x != null; } ); } if (CommandResult.UserLoggedAndAdmin()) { options.Add( "l|lock", "Lock the board to prevent creation of topics.", x => lockBoard = x != null ); } if (args == null) { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } else { try { var parsedArgs = options.Parse(args).ToArray(); if (parsedArgs.Length == args.Length) { if (parsedArgs.Length == 1) { if (parsedArgs[0].IsShort()) { var boardId = parsedArgs[0].ToShort(); var page = 1; WriteTopics(boardId, page); } else { CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]); } } else if (parsedArgs.Length == 2) { if (parsedArgs[0].IsShort()) { var boardId = parsedArgs[0].ToShort(); if (parsedArgs[1].IsInt()) { var page = parsedArgs[1].ToInt(); WriteTopics(boardId, page); } else if (PagingUtility.Shortcuts.Any(x => parsedArgs[1].Is(x))) { var page = PagingUtility.TranslateShortcut(parsedArgs[1], CommandResult.CommandContext.CurrentPage); WriteTopics(boardId, page); if (parsedArgs[1].Is("last") || parsedArgs[1].Is("prev")) { CommandResult.ScrollToBottom = false; } } else { CommandResult.WriteLine("'{0}' is not a valid page number.", parsedArgs[1]); } } else { CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]); } } else { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } } else { if (showHelp) { HelpUtility.WriteHelpInformation(this, options); } else if (newTopic) { if (parsedArgs.Length >= 1) { if (parsedArgs[0].IsShort()) { var boardId = parsedArgs[0].ToShort(); var board = _dataBucket.BoardRepository.GetBoard(boardId); if (board != null) { if (!board.Locked || CommandResult.CurrentUser.IsModeratorOrAdministrator()) { if (!board.ModsOnly || CommandResult.CurrentUser.IsModeratorOrAdministrator()) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Create a title for your topic."); CommandResult.SetPrompt(Name, args, string.Format("{0} NEW TOPIC Title", boardId)); } else if (CommandResult.CommandContext.PromptData.Length == 1) { CommandResult.WriteLine("Create the body for your topic."); CommandResult.SetPrompt(Name, args, string.Format("{0} NEW TOPIC Body", boardId)); } else if (CommandResult.CommandContext.PromptData.Length == 2) { var topic = new Topic { BoardID = boardId, Title = CommandResult.CommandContext.PromptData[0], Body = BBCodeUtility.SimplifyComplexTags( CommandResult.CommandContext.PromptData[1], _dataBucket.ReplyRepository, CommandResult.CurrentUser.IsModeratorOrAdministrator() ), Username = CommandResult.CurrentUser.Username, PostedDate = DateTime.UtcNow, LastEdit = DateTime.UtcNow, ModsOnly = modTopic && !board.ModsOnly }; _dataBucket.TopicRepository.AddTopic(topic); _dataBucket.SaveChanges(); CommandResult.RestoreContext(); var TOPIC = AvailableCommands.SingleOrDefault(x => x.Name.Is("TOPIC")); TOPIC.Invoke(new string[] { topic.TopicID.ToString() }); CommandResult.WriteLine("New topic succesfully posted."); } } else { CommandResult.WriteLine("Board '{0}' is for moderators only.", boardId); } } else { CommandResult.WriteLine("Board '{0}' is locked. You cannot create topics on this board.", boardId); } } else { CommandResult.WriteLine("There is no board with ID '{0}'.", boardId); } } else { CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a board ID."); } } else { if (lockBoard != null) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsShort()) { var boardId = parsedArgs[0].ToShort(); var board = _dataBucket.BoardRepository.GetBoard(boardId); if (board != null) { board.Locked = (bool)lockBoard; _dataBucket.BoardRepository.UpdateBoard(board); _dataBucket.SaveChanges(); string status = (bool)lockBoard ? "locked" : "unlocked"; CommandResult.WriteLine("Board '{0}' was successfully {1}.", boardId, status); } else { CommandResult.WriteLine("There is no board with ID '{0}'.", boardId); } } else { CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a board ID."); } } if (refresh) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsShort()) { var boardId = parsedArgs[0].ToShort(); WriteTopics(boardId, CommandResult.CommandContext.CurrentPage); } else { CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a board ID."); } } } } } catch (OptionException ex) { CommandResult.WriteLine(ex.Message); } } }
public void Invoke(string[] args) { bool showHelp = false; bool replyToTopic = false; bool refresh = false; bool edit = false; bool delete = false; bool report = false; bool modReply = false; bool? lockTopic = null; bool? stickyTopic = null; bool? globalStickyTopic = null; long? replyId = null; short?moveToBoard = null; var options = new OptionSet(); options.Add( "?|help", "Show help information.", x => showHelp = x != null ); options.Add( "R|refresh", "Refresh the current topic.", x => refresh = x != null ); if (CommandResult.IsUserLoggedIn) { options.Add( "r|reply:", "Reply to the topic. Optionally quotes a reply if a {ReplyID} is specified.", x => { replyToTopic = true; if (x.IsLong()) { replyId = x.ToLong(); } } ); options.Add( "e|edit:", "Edits the topic or a reply if a {ReplyID} is specified.", x => { edit = true; if (x.IsLong()) { replyId = x.ToLong(); } } ); options.Add( "d|delete:", "Deletes the topic or a reply if a {ReplyID} is specified.", x => { delete = true; if (x.IsLong()) { replyId = x.ToLong(); } } ); options.Add( "report:", "Report abuse for the topic or a reply if a {ReplyID} is specified.", x => { report = true; if (x.IsLong()) { replyId = x.ToLong(); } } ); } if (CommandResult.UserLoggedAndModOrAdmin()) { options.Add( "mr|modReply", "A reply only moderators can see.", x => { modReply = x != null; replyToTopic = x != null; } ); options.Add( "l|lock", "Locks the topic preventing further replies except modreplies.", x => lockTopic = x != null ); options.Add( "s|sticky", "Sticky's the topic keeping it at the top of the board regardless of last reply date.", x => stickyTopic = x != null ); options.Add( "g|globalSticky", "Sticky's the topic keeping it at the top of \"All Activity Board\".", x => globalStickyTopic = x != null ); options.Add( "m|move=", "Moves the topic to the board with the specified {BoardID}.", x => moveToBoard = x.ToShort() ); } try { if (args == null) { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } else { var parsedArgs = options.Parse(args).ToArray(); if (parsedArgs.Length == args.Length) { if (parsedArgs.Length == 1) { if (parsedArgs[0].IsLong()) { var topicId = parsedArgs[0].ToLong(); var page = 1; WriteTopic(topicId, page); } else { CommandResult.WriteLine("'{0}' is not a valid topic ID.", parsedArgs[0]); } } else if (parsedArgs.Length == 2) { if (parsedArgs[0].IsInt()) { var topicId = parsedArgs[0].ToLong(); if (parsedArgs[1].IsInt()) { var page = parsedArgs[1].ToInt(); WriteTopic(topicId, page); } else if (PagingUtility.Shortcuts.Any(x => parsedArgs[1].Is(x))) { var page = PagingUtility.TranslateShortcut(parsedArgs[1], CommandResult.CommandContext.CurrentPage); WriteTopic(topicId, page); if (parsedArgs[1].Is("last") || parsedArgs[1].Is("prev")) { CommandResult.ScrollToBottom = true; } } else { CommandResult.WriteLine("'{0}' is not a valid page number.", parsedArgs[1]); } } else { CommandResult.WriteLine("'{0}' is not a valid topic ID.", parsedArgs[0]); } } else { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } } else { if (showHelp) { HelpUtility.WriteHelpInformation(this, options); } else if (replyToTopic) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var topicId = parsedArgs[0].ToLong(); var topic = _dataBucket.TopicRepository.GetTopic(topicId); if (topic != null) { if (!topic.Locked || (!topic.IsModsOnly() && modReply && CommandResult.CurrentUser.IsModerator) || CommandResult.CurrentUser.IsAdministrator) { if (!topic.IsModsOnly() || CommandResult.CurrentUser.IsModeratorOrAdministrator()) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Type your reply."); if (replyId != null) { CommandResult.EditText = string.Format("[quote]{0}[/quote]\r\n\r\n", replyId); } CommandResult.SetPrompt(Name, args, string.Format("{0} REPLY", topicId)); } else { _dataBucket.ReplyRepository.AddReply(new Reply { Username = CommandResult.CurrentUser.Username, PostedDate = DateTime.UtcNow, LastEdit = DateTime.UtcNow, TopicID = topicId, Body = BBCodeUtility.SimplifyComplexTags( CommandResult.CommandContext.PromptData[0], _dataBucket.ReplyRepository, CommandResult.CurrentUser.IsModeratorOrAdministrator() ), ModsOnly = modReply && !topic.IsModsOnly() }); _dataBucket.SaveChanges(); CommandResult.CommandContext.PromptData = null; //var TOPIC = AvailableCommands.SingleOrDefault(x => x.Name.Is("TOPIC")); //TOPIC.Invoke(new string[] { topicId.ToString(), "last" }); CommandResult.RestoreContext(); CommandResult.WriteLine("Reply successfully posted."); } } else { CommandResult.WriteLine("Topic '{0}' is for moderators only.", topicId); } } else { CommandResult.WriteLine("Topic '{0}' is locked.", topicId); } } else { CommandResult.WriteLine("There is no topic with ID '{0}'.", topicId); } } else { CommandResult.WriteLine("'{0}' is not a valid topic ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a topic ID."); } } else if (edit) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var topicId = parsedArgs[0].ToLong(); if (replyId == null) { var topic = _dataBucket.TopicRepository.GetTopic(topicId); if (topic != null) { if (!topic.Locked || CommandResult.CurrentUser.IsAdministrator) { if (topic.Username.Is(CommandResult.CurrentUser.Username) || (CommandResult.CurrentUser.IsModerator && !topic.IsModsOnly() && !topic.User.IsModerator && !topic.User.IsAdministrator) || CommandResult.CurrentUser.IsAdministrator) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Edit the topic title."); CommandResult.EditText = topic.Title; CommandResult.SetPrompt(Name, args, string.Format("{0} EDIT Title", topicId)); } else if (CommandResult.CommandContext.PromptData.Length == 1) { CommandResult.WriteLine("Edit the topic body."); CommandResult.EditText = topic.Body; CommandResult.SetPrompt(Name, args, string.Format("{0} EDIT Body", topicId)); } else if (CommandResult.CommandContext.PromptData.Length == 2) { topic.Title = CommandResult.CommandContext.PromptData[0]; topic.Body = BBCodeUtility.SimplifyComplexTags( CommandResult.CommandContext.PromptData[1], _dataBucket.ReplyRepository, CommandResult.CurrentUser.IsModeratorOrAdministrator() ); topic.LastEdit = DateTime.UtcNow; topic.EditedBy = CommandResult.CurrentUser.Username; _dataBucket.TopicRepository.UpdateTopic(topic); _dataBucket.SaveChanges(); CommandResult.CommandContext.PromptData = null; CommandResult.WriteLine("Topic '{0}' was edited successfully.", topicId); CommandResult.RestoreContext(); } } else { CommandResult.WriteLine("Topic '{0}' does not belong to you. You are not authorized to edit it.", topicId); } } else { CommandResult.WriteLine("Topic '{0}' is locked.", topicId); } } else { CommandResult.WriteLine("There is no topic with ID '{0}'.", topicId); } } else { var reply = _dataBucket.ReplyRepository.GetReply((long)replyId); if (reply != null) { if (reply.TopicID == topicId) { if (!reply.Topic.Locked || (reply.ModsOnly && !reply.Topic.IsModsOnly()) || CommandResult.CurrentUser.IsAdministrator) { if (reply.Username.Is(CommandResult.CurrentUser.Username) || (CommandResult.CurrentUser.IsModerator && !reply.IsModsOnly() && !reply.User.IsModeratorOrAdministrator()) || CommandResult.CurrentUser.IsAdministrator) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Edit the reply body."); CommandResult.EditText = reply.Body; CommandResult.SetPrompt(Name, args, string.Format("{0} EDIT Reply {1}", topicId, replyId)); } else if (CommandResult.CommandContext.PromptData.Length == 1) { reply.Body = BBCodeUtility.SimplifyComplexTags( CommandResult.CommandContext.PromptData[0], _dataBucket.ReplyRepository, CommandResult.CurrentUser.IsModeratorOrAdministrator() ); reply.LastEdit = DateTime.UtcNow; reply.EditedBy = CommandResult.CurrentUser.Username; _dataBucket.ReplyRepository.UpdateReply(reply); _dataBucket.SaveChanges(); CommandResult.CommandContext.PromptData = null; CommandResult.WriteLine("Reply '{0}' was edited successfully.", replyId); CommandResult.RestoreContext(); } } else { CommandResult.WriteLine("Reply '{0}' does not belong to you. You are not authorized to edit it.", replyId); } } else { CommandResult.WriteLine("Topic '{0}' is locked.", topicId); } } else { CommandResult.WriteLine("Topic '{0}' does not contain a reply with ID '{1}'.", topicId, replyId); } } else { CommandResult.WriteLine("Reply '{0}' does not exist.", replyId); } } } else { CommandResult.WriteLine("'{0}' is not a valid topic ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a topic ID."); } } else if (delete) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var topicId = parsedArgs[0].ToLong(); if (replyId == null) { var topic = _dataBucket.TopicRepository.GetTopic(topicId); if (topic != null) { if (!topic.Locked || CommandResult.CurrentUser.IsAdministrator) { if (CommandResult.CurrentUser.IsAdministrator) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Are you sure you want to delete the topic titled \"{0}\"? (Y/N)", topic.Title); CommandResult.SetPrompt(Name, args, string.Format("{0} DELETE CONFIRM", topicId)); } else if (CommandResult.CommandContext.PromptData.Length == 1) { if (CommandResult.CommandContext.PromptData[0].Is("Y")) { _dataBucket.TopicRepository.DeleteTopic(topic); _dataBucket.SaveChanges(); CommandResult.WriteLine("Topic '{0}' was deleted successfully.", topicId); CommandResult.CommandContext.PromptData = null; if (CommandResult.CommandContext.PreviousContext != null && CommandResult.CommandContext.PreviousContext.Command.Is("TOPIC") && CommandResult.CommandContext.PreviousContext.Args.Contains(topicId.ToString()) && CommandResult.CommandContext.PreviousContext.Status == ContextStatus.Passive) { CommandResult.ClearScreen = true; CommandResult.DeactivateContext(); } else { CommandResult.RestoreContext(); } } else { CommandResult.WriteLine("Topic '{0}' was not deleted.", topicId); CommandResult.CommandContext.PromptData = null; CommandResult.RestoreContext(); } } } else { CommandResult.WriteLine("You are not an administrator. You are not authorized to delete topics."); } } else { CommandResult.WriteLine("Topic '{0}' is locked.", topicId); } } else { CommandResult.WriteLine("There is no topic with ID {0}.", topicId); } } else { var reply = _dataBucket.ReplyRepository.GetReply((long)replyId); if (reply != null) { if (reply.TopicID == topicId) { if (!reply.Topic.Locked || (reply.ModsOnly && !reply.Topic.IsModsOnly()) || CommandResult.CurrentUser.IsAdministrator) { if (reply.Username.Is(CommandResult.CurrentUser.Username) || (CommandResult.CurrentUser.IsModerator && !reply.IsModsOnly() && !reply.User.IsModeratorOrAdministrator()) || CommandResult.CurrentUser.IsAdministrator) { _dataBucket.ReplyRepository.DeleteReply(reply); _dataBucket.SaveChanges(); CommandResult.WriteLine("Reply '{0}' was deleted successfully.", replyId); } else { CommandResult.WriteLine("Reply '{0}' does not belong to you. You are not authorized to delete it.", replyId); } } else { CommandResult.WriteLine("Topic '{0}' is locked.", topicId); } } else { CommandResult.WriteLine("Topic '{0}' does not contain a reply with ID '{1}'.", topicId, replyId); } } else { CommandResult.WriteLine("Reply '{0}' does not exist.", replyId); } } } else { CommandResult.WriteLine("'{0}' is not a valid topic ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a topic ID."); } } else if (report) { // allow user to report abuse. } else { if (lockTopic != null) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var topicId = parsedArgs[0].ToLong(); var topic = _dataBucket.TopicRepository.GetTopic(topicId); if (topic != null) { if (!topic.IsModsOnly() || CommandResult.CurrentUser.IsAdministrator) { if ((bool)lockTopic || (!(bool)lockTopic && CommandResult.CurrentUser.IsAdministrator)) { topic.Locked = (bool)lockTopic; _dataBucket.TopicRepository.UpdateTopic(topic); _dataBucket.SaveChanges(); string status = (bool)lockTopic ? "locked" : "unlocked"; CommandResult.WriteLine("Topic '{0}' was successfully {1}.", topicId, status); } else { CommandResult.WriteLine("Only administrators can unlock topics."); } } else { CommandResult.WriteLine("You are not authorized to lock moderator topics."); } } else { CommandResult.WriteLine("There is no topic with ID {0}.", topicId); } } else { CommandResult.WriteLine("'{0}' is not a valid topic ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a topic ID."); } } if (stickyTopic != null) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var topicId = parsedArgs[0].ToLong(); var topic = _dataBucket.TopicRepository.GetTopic(topicId); if (topic != null) { if (!topic.IsModsOnly() || CommandResult.CurrentUser.IsAdministrator) { topic.Stickied = (bool)stickyTopic; _dataBucket.TopicRepository.UpdateTopic(topic); _dataBucket.SaveChanges(); string status = (bool)stickyTopic ? "stickied" : "unstickied"; CommandResult.WriteLine("Topic '{0}' was successfully {1}.", topicId, status); } else { CommandResult.WriteLine("You are not authorized to sticky/unsticky moderator topics."); } } else { CommandResult.WriteLine("There is no topic with ID '{0}'.", topicId); } } else { CommandResult.WriteLine("'{0}' is not a valid topic ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a topic ID."); } } if (globalStickyTopic != null) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var topicId = parsedArgs[0].ToLong(); var topic = _dataBucket.TopicRepository.GetTopic(topicId); if (topic != null) { if (!topic.IsModsOnly() || CommandResult.CurrentUser.IsAdministrator) { topic.GlobalSticky = (bool)globalStickyTopic; _dataBucket.TopicRepository.UpdateTopic(topic); _dataBucket.SaveChanges(); string status = (bool)globalStickyTopic ? "stickied" : "unstickied"; CommandResult.WriteLine("Topic '{0}' was successfully globally {1}.", topicId, status); } else { CommandResult.WriteLine("You are not authorized to globally sticky/unsticky moderator topics."); } } else { CommandResult.WriteLine("There is no topic with ID '{0}'.", topicId); } } else { CommandResult.WriteLine("'{0}' is not a valid topic ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a topic ID."); } } if (moveToBoard != null) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var topicId = parsedArgs[0].ToLong(); var topic = _dataBucket.TopicRepository.GetTopic(topicId); if (topic != null) { var board = _dataBucket.BoardRepository.GetBoard((short)moveToBoard); if (board != null) { if (!board.Locked || CommandResult.CurrentUser.IsAdministrator) { if (!topic.IsModsOnly() || CommandResult.CurrentUser.IsAdministrator) { if (!board.ModsOnly || CommandResult.CurrentUser.IsAdministrator) { topic.BoardID = (short)moveToBoard; _dataBucket.TopicRepository.UpdateTopic(topic); _dataBucket.SaveChanges(); CommandResult.WriteLine("Topic '{0}' was successfully moved to board '{1}'.", topicId, moveToBoard); } else { CommandResult.WriteLine("You are not authorized to move topics onto moderator boards."); } } else { CommandResult.WriteLine("You are not authorized to move moderator topics."); } } else { CommandResult.WriteLine("Board '{0}' is locked.", moveToBoard); } } else { CommandResult.WriteLine("There is no board with ID '{0}'.", moveToBoard); } } else { CommandResult.WriteLine("There is no topic with ID '{0}'.", topicId); } } else { CommandResult.WriteLine("'{0}' is not a valid topic ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a board ID."); } } if (refresh) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var topicId = parsedArgs[0].ToLong(); WriteTopic(topicId, CommandResult.CommandContext.CurrentPage); } else { CommandResult.WriteLine("'{0}' is not a valid topic ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a topic ID."); } } } } } } catch (OptionException ex) { CommandResult.WriteLine(ex.Message); } }
public void Invoke(string[] args) { bool showHelp = false; bool? mute = null; bool changePassword = false; bool setTimeZone = false; bool? timeStamps = null; bool? autoFollow = null; bool? replyNotify = null; bool? messageNotify = null; string registration = null; var options = new OptionSet(); options.Add( "?|help", "Show help information.", x => showHelp = x != null ); options.Add( "m|mute", "Mute/unmute the terminal typing sound.", x => mute = x != null ); options.Add( "changePassword", "Change your current password.", x => changePassword = x != null ); options.Add( "setTimeZone", "Set your current time zone.", x => setTimeZone = x != null ); options.Add( "timeStamps", "Turn timestamps on/off.", x => timeStamps = x != null ); options.Add( "autoFollow", "Auto-follow topics you create or reply to.", x => autoFollow = x != null ); options.Add( "replyNotify", "Display notifications about replies to your followed topics.", x => replyNotify = x != null ); options.Add( "msgNotify", "Display notifications for unread messages in your inbox.", x => messageNotify = x != null ); if (CommandResult.CurrentUser.IsAdministrator) { options.Add( "reg|registration=", "1=OPEN, 2=INVITE-ONLY, 3=CLOSED", x => registration = x ); } if (args == null) { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } else { try { var parsedArgs = options.Parse(args).ToArray(); if (parsedArgs.Length == args.Length) { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } else { if (showHelp) { HelpUtility.WriteHelpInformation(this, options); } else if (changePassword) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Type your new password."); CommandResult.PasswordField = true; CommandResult.SetPrompt(Name, args, "NEW PASSWORD"); } else if (CommandResult.CommandContext.PromptData.Length == 1) { CommandResult.WriteLine("Confirm your new password."); CommandResult.PasswordField = true; CommandResult.SetPrompt(Name, args, "CONFIRM PASSWORD"); } else if (CommandResult.CommandContext.PromptData.Length == 2) { string password = CommandResult.CommandContext.PromptData[0]; string confirmPassword = CommandResult.CommandContext.PromptData[1]; if (password == confirmPassword) { CommandResult.CurrentUser.Password = password; _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); _dataBucket.SaveChanges(); CommandResult.WriteLine("Password changed successfully."); } else { CommandResult.WriteLine("Passwords did not match."); } CommandResult.RestoreContext(); } } else if (setTimeZone) { var timeZones = TimeZoneInfo.GetSystemTimeZones(); if (CommandResult.CommandContext.PromptData == null) { for (int index = 0; index < timeZones.Count; index++) { var timeZone = timeZones[index]; CommandResult.WriteLine(DisplayMode.DontType, "{{{0}}} {1}", index, timeZone.DisplayName); } CommandResult.WriteLine(); CommandResult.WriteLine("Enter time zone ID."); CommandResult.SetPrompt(Name, args, "CHANGE TIME ZONE"); } else if (CommandResult.CommandContext.PromptData.Length == 1) { string promptData = CommandResult.CommandContext.PromptData[0]; if (promptData.IsInt()) { int timeZoneId = promptData.ToInt(); if (timeZoneId >= 0 && timeZoneId < timeZones.Count) { var timeZone = timeZones[timeZoneId]; CommandResult.CurrentUser.TimeZone = timeZone.Id; _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); _dataBucket.SaveChanges(); CommandResult.WriteLine("'{0}' successfully set as your current time zone.", timeZone.Id); CommandResult.RestoreContext(); } else { CommandResult.WriteLine("'{0}' does not match any available time zone ID.", timeZoneId); CommandResult.RestoreContext(); CommandResult.WriteLine("Enter time zone ID."); CommandResult.SetPrompt(Name, args, "CHANGE TIME ZONE"); } } else { CommandResult.WriteLine("'{0}' is not a valid time zone ID.", promptData); CommandResult.RestoreContext(); CommandResult.WriteLine("Enter time zone ID."); CommandResult.SetPrompt(Name, args, "CHANGE TIME ZONE"); } } } else { if (mute != null) { CommandResult.CurrentUser.Sound = !(bool)mute; _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); CommandResult.WriteLine("Sound successfully {0}.", (bool)mute ? "muted" : "unmuted"); } if (timeStamps != null) { CommandResult.CurrentUser.ShowTimestamps = (bool)timeStamps; _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); CommandResult.WriteLine("Timestamps were successfully {0}.", (bool)timeStamps ? "enabled" : "disabled"); } if (autoFollow != null) { CommandResult.CurrentUser.AutoFollow = (bool)autoFollow; _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); CommandResult.WriteLine("Auto-follow {0}.", (bool)autoFollow ? "activated" : "deactivated"); } if (replyNotify != null) { CommandResult.CurrentUser.NotifyReplies = (bool)replyNotify; _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); CommandResult.WriteLine("Reply notifications were successfully turned {0}.", (bool)replyNotify ? "on" : "off"); } if (messageNotify != null) { CommandResult.CurrentUser.NotifyMessages = (bool)messageNotify; _dataBucket.UserRepository.UpdateUser(CommandResult.CurrentUser); CommandResult.WriteLine("Message notifications were successfully turned {0}.", (bool)messageNotify ? "on" : "off"); } if (registration != null) { var registrationStatus = _dataBucket.VariableRepository.GetVariable("Registration"); if (registration == "1") { registrationStatus = "Open"; CommandResult.WriteLine("Registration opened successfully."); } else if (registration == "2") { registrationStatus = "Invite-Only"; CommandResult.WriteLine("Registration set to invite only."); } else if (registration == "3") { registrationStatus = "Closed"; CommandResult.WriteLine("Registration closed successfully."); } _dataBucket.VariableRepository.ModifyVariable("Registration", registrationStatus); } _dataBucket.SaveChanges(); } } } catch (OptionException ex) { CommandResult.WriteLine(ex.Message); } } }
public void Invoke(string[] args) { bool showHelp = false; bool sent = false; bool refresh = false; bool deleteAll = false; string username = CommandResult.CurrentUser.Username; var options = new OptionSet(); options.Add( "?|help", "Show help information.", x => showHelp = x != null ); options.Add( "R|refresh", "Refresh the current list of messages.", x => refresh = x != null ); options.Add( "s|sent", "Display sent messages.", x => sent = x != null ); options.Add( "i|inbox", "Display received messages.", x => sent = x == null ); options.Add( "da|deleteAll", "Delete all messages, excluding locked messages.", x => deleteAll = x != null ); if (CommandResult.CurrentUser.IsAdministrator) { options.Add( "u|user="******"Get messages for a specified {Username}.", x => username = x ); } if (args == null) { WriteMessages(username, 1, false); } else { try { var parsedArgs = options.Parse(args).ToArray(); if (parsedArgs.Length == args.Length) { if (parsedArgs.Length == 1) { if (parsedArgs[0].IsInt()) { var page = parsedArgs[0].ToInt(); WriteMessages(username, page, false); } else if (PagingUtility.Shortcuts.Any(x => parsedArgs[0].Is(x))) { var page = PagingUtility.TranslateShortcut(parsedArgs[0], CommandResult.CommandContext.CurrentPage); WriteMessages(username, page, false); if (parsedArgs[0].Is("last") || parsedArgs[0].Is("prev")) { CommandResult.ScrollToBottom = false; } } else { CommandResult.WriteLine("'{0}' is not a valid page number.", parsedArgs[0]); } } else { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } } else { if (showHelp) { HelpUtility.WriteHelpInformation(this, options); } else if (deleteAll) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Are you sure you want to delete all {0} messages? (Y/N)", sent ? "sent" : "received"); CommandResult.SetPrompt(Name, args, string.Format("DELETE {0} CONFIRM", sent ? "SENT" : "RECEIVED")); } else if (CommandResult.CommandContext.PromptData.Length == 1) { if (CommandResult.CommandContext.PromptData[0].Is("Y")) { var messages = _dataBucket.MessageRepository.GetAllMessages(username, sent) .Where(x => sent ? !x.SenderLocked : !x.RecipientLocked).ToList(); foreach (var message in messages) { if (sent) { message.SenderDeleted = true; } else { message.RecipientDeleted = true; } _dataBucket.MessageRepository.UpdateMessage(message); _dataBucket.SaveChanges(); } CommandResult.WriteLine("All {0} messages for '{1}' have been deleted.", sent ? "sent" : "received", username); CommandResult.CommandContext.PromptData = null; CommandResult.RestoreContext(); } else { CommandResult.WriteLine("{0} messages were not deleted.", sent ? "Sent" : "Received"); CommandResult.CommandContext.PromptData = null; CommandResult.RestoreContext(); } } } else if (refresh) { WriteMessages(username, CommandResult.CommandContext.CurrentPage, sent); } else if (parsedArgs.Length >= 1) { if (parsedArgs[0].IsInt()) { var page = parsedArgs[0].ToInt(); WriteMessages(username, page, sent); } else if (PagingUtility.Shortcuts.Any(x => parsedArgs[0].Is(x))) { var page = PagingUtility.TranslateShortcut(parsedArgs[0], CommandResult.CommandContext.CurrentPage); WriteMessages(username, page, sent); if (parsedArgs[1].Is("last") || parsedArgs[1].Is("prev")) { CommandResult.ScrollToBottom = false; } } else { CommandResult.WriteLine("'{0}' is not a valid page number.", parsedArgs[0]); } } else { WriteMessages(username, 1, sent); } } } catch (OptionException ex) { CommandResult.WriteLine(ex.Message); } } }
public void Invoke(string[] args) { bool showHelp = false; bool delete = false; bool?lockMessage = null; bool reply = false; bool newMessage = false; var options = new OptionSet(); options.Add( "?|help", "Show help information.", x => showHelp = x != null ); options.Add( "r|reply", "Reply to the specified message.", x => reply = x != null ); options.Add( "d|delete", "Deletes the specified message.", x => delete = x != null ); options.Add( "l|lock", "Locks the message to prevent accidental deltion.", x => lockMessage = x != null ); options.Add( "nm|newMessage", "Send a new message to a specific user.", x => newMessage = x != null ); if (args == null) { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } else { try { var parsedArgs = options.Parse(args).ToArray(); if (parsedArgs.Length == args.Length) { if (parsedArgs.Length == 1) { if (parsedArgs[0].IsLong()) { var messageId = parsedArgs[0].ToLong(); WriteMessage(messageId); } else { CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]); } } else { CommandResult.WriteLine(DisplayTemplates.InvalidArguments); } } else { if (showHelp) { HelpUtility.WriteHelpInformation(this, options); } else if (reply) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var messageId = parsedArgs[0].ToLong(); var message = _dataBucket.MessageRepository.GetMessage(messageId); if (message != null) { if (message.Recipient.Is(CommandResult.CurrentUser.Username)) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Write the body of your message."); CommandResult.SetPrompt(Name, args, string.Format("{0} REPLY Body", messageId)); } else if (CommandResult.CommandContext.PromptData.Length == 1) { _dataBucket.MessageRepository.AddMessage(new Message { Body = CommandResult.CommandContext.PromptData[0], RecipientLocked = false, SenderLocked = false, MessageRead = false, Recipient = message.Sender, Sender = CommandResult.CurrentUser.Username, RecipientDeleted = false, SenderDeleted = false, Subject = string.Format("Re: {0}", message.Subject), SentDate = DateTime.UtcNow }); _dataBucket.SaveChanges(); CommandResult.WriteLine("Reply sent succesfully."); CommandResult.RestoreContext(); } } else { CommandResult.WriteLine("Message '{0}' was not sent to you.", messageId); } } else { CommandResult.WriteLine("There is no message with ID '{0}'.", messageId); } } else { CommandResult.WriteLine("'{0}' is not a valid message ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a message ID."); } } else if (delete) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var messageId = parsedArgs[0].ToLong(); var message = _dataBucket.MessageRepository.GetMessage(messageId); if (message != null) { if (message.Recipient.Is(CommandResult.CurrentUser.Username)) { if (!message.RecipientLocked) { message.RecipientDeleted = true; _dataBucket.MessageRepository.UpdateMessage(message); _dataBucket.SaveChanges(); CommandResult.WriteLine("Message '{0}' deleted successfully.", messageId); } else { CommandResult.WriteLine("You have locked message '{0}' and cannot delete it.", messageId); } } else if (message.Sender.Is(CommandResult.CurrentUser.Username)) { if (!message.SenderLocked) { message.SenderDeleted = true; _dataBucket.MessageRepository.UpdateMessage(message); _dataBucket.SaveChanges(); CommandResult.WriteLine("Message '{0}' deleted successfully.", messageId); } else { CommandResult.WriteLine("You have locked message '{0}' and cannot delete it.", messageId); } } else { CommandResult.WriteLine("Message '{0}' does not belong to you.", messageId); } } else { CommandResult.WriteLine("There is no message with ID '{0}'.", messageId); } } else { CommandResult.WriteLine("'{0}' is not a valid message ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a message ID."); } } else if (newMessage) { if (CommandResult.CommandContext.PromptData == null) { CommandResult.WriteLine("Type the name of the recipient."); CommandResult.SetPrompt(Name, args, "USERNAME"); } else if (CommandResult.CommandContext.PromptData.Length == 1) { var user = _dataBucket.UserRepository.GetUser(CommandResult.CommandContext.PromptData[0]); if (user != null) { CommandResult.WriteLine("Type the subject of your message."); CommandResult.SetPrompt(Name, args, "SUBJECT"); } else { CommandResult.WriteLine("'{0}' is not a valid username.", CommandResult.CommandContext.PromptData[0]); CommandResult.WriteLine("Re-type the name of the recipient."); CommandResult.CommandContext.PromptData = null; CommandResult.SetPrompt(Name, args, "USERNAME"); } } else if (CommandResult.CommandContext.PromptData.Length == 2) { CommandResult.WriteLine("Type the body of your message."); CommandResult.SetPrompt(Name, args, "BODY"); } else if (CommandResult.CommandContext.PromptData.Length == 3) { _dataBucket.MessageRepository.AddMessage(new Message { Sender = CommandResult.CurrentUser.Username, Recipient = CommandResult.CommandContext.PromptData[0], Subject = CommandResult.CommandContext.PromptData[1], Body = CommandResult.CommandContext.PromptData[2], SentDate = DateTime.UtcNow }); _dataBucket.SaveChanges(); CommandResult.WriteLine("Message sent succesfully."); CommandResult.RestoreContext(); } } else if (lockMessage != null) { if (parsedArgs.Length > 0) { if (parsedArgs[0].IsLong()) { var messageId = parsedArgs[0].ToLong(); var message = _dataBucket.MessageRepository.GetMessage(messageId); if (message != null) { if (message.Recipient.Is(CommandResult.CurrentUser.Username)) { message.RecipientLocked = (bool)lockMessage; _dataBucket.MessageRepository.UpdateMessage(message); _dataBucket.SaveChanges(); CommandResult.WriteLine("Message '{0}' {1} successfully.", messageId, (bool)lockMessage ? "locked" : "unlocked"); } else if (message.Sender.Is(CommandResult.CurrentUser.Username)) { message.SenderLocked = (bool)lockMessage; _dataBucket.MessageRepository.UpdateMessage(message); _dataBucket.SaveChanges(); CommandResult.WriteLine("Message '{0}' {1} successfully.", messageId, (bool)lockMessage ? "locked" : "unlocked"); } else { CommandResult.WriteLine("Message '{0}' does not belong to you.", messageId); } } else { CommandResult.WriteLine("There is no message with ID '{0}'.", messageId); } } else { CommandResult.WriteLine("'{0}' is not a valid message ID.", parsedArgs[0]); } } else { CommandResult.WriteLine("You must supply a message ID."); } } } } catch (OptionException ex) { CommandResult.WriteLine(ex.Message); } } }