You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BaseCommandParser.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. * Copyright (c) 2006-2015 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.commandparser.parsers;
  23. import com.dmdirc.commandparser.CommandArguments;
  24. import com.dmdirc.commandparser.CommandInfo;
  25. import com.dmdirc.commandparser.CommandInfoPair;
  26. import com.dmdirc.commandparser.CommandType;
  27. import com.dmdirc.commandparser.commands.Command;
  28. import com.dmdirc.commandparser.commands.CommandOptions;
  29. import com.dmdirc.commandparser.commands.ExternalCommand;
  30. import com.dmdirc.commandparser.commands.PreviousCommand;
  31. import com.dmdirc.commandparser.commands.context.CommandContext;
  32. import com.dmdirc.events.CommandErrorEvent;
  33. import com.dmdirc.events.UnknownCommandEvent;
  34. import com.dmdirc.interfaces.CommandController;
  35. import com.dmdirc.interfaces.Connection;
  36. import com.dmdirc.interfaces.EventBus;
  37. import com.dmdirc.interfaces.GroupChat;
  38. import com.dmdirc.interfaces.InputModel;
  39. import com.dmdirc.interfaces.WindowModel;
  40. import com.dmdirc.interfaces.config.ReadOnlyConfigProvider;
  41. import com.dmdirc.util.collections.RollingList;
  42. import java.io.Serializable;
  43. import java.util.HashMap;
  44. import java.util.Map;
  45. import java.util.Optional;
  46. import javax.annotation.Nonnull;
  47. import javax.annotation.Nullable;
  48. import static com.google.common.base.Preconditions.checkNotNull;
  49. /**
  50. * Represents a generic command parser. A command parser takes a line of input from the user,
  51. * determines if it is an attempt at executing a command (based on the character at the start of the
  52. * string), and handles it appropriately.
  53. */
  54. public abstract class BaseCommandParser implements Serializable, CommandParser {
  55. /** A version number for this class. */
  56. private static final long serialVersionUID = 1;
  57. /** Commands that are associated with this parser. */
  58. private final Map<String, CommandInfoPair> commands;
  59. /** A history of commands that have been entered into this parser. */
  60. private final RollingList<PreviousCommand> history;
  61. /** Command manager to use. */
  62. protected final CommandController commandManager;
  63. /** Event bus to post events to. */
  64. private final EventBus eventBus;
  65. /**
  66. * Creates a new instance of CommandParser.
  67. *
  68. * @param configManager Config manager to read settings
  69. * @param commandManager Command manager to load plugins from
  70. * @param eventBus The event bus to post events to.
  71. */
  72. protected BaseCommandParser(
  73. final ReadOnlyConfigProvider configManager,
  74. final CommandController commandManager,
  75. final EventBus eventBus) {
  76. this.eventBus = eventBus;
  77. commands = new HashMap<>();
  78. history = new RollingList<>(configManager.getOptionInt("general", "commandhistory"));
  79. this.commandManager = commandManager;
  80. loadCommands();
  81. }
  82. /** Loads the relevant commands into the parser. */
  83. protected abstract void loadCommands();
  84. @Override
  85. public final void registerCommand(final Command command, final CommandInfo info) {
  86. commands.put(info.getName().toLowerCase(), new CommandInfoPair(info, command));
  87. }
  88. @Override
  89. public final void unregisterCommand(final CommandInfo info) {
  90. commands.remove(info.getName().toLowerCase());
  91. }
  92. @Override
  93. public Map<String, CommandInfoPair> getCommands() {
  94. return new HashMap<>(commands);
  95. }
  96. @Override
  97. public final void parseCommand(@Nonnull final WindowModel origin, final String line,
  98. final boolean parseChannel) {
  99. checkNotNull(origin);
  100. final CommandArguments args = new CommandArguments(commandManager, line);
  101. if (args.isCommand()) {
  102. if (handleChannelCommand(origin, args, parseChannel)) {
  103. return;
  104. }
  105. if (commands.containsKey(args.getCommandName().toLowerCase())) {
  106. final CommandInfoPair pair = commands.get(args.getCommandName().toLowerCase());
  107. addHistory(args.getStrippedLine());
  108. executeCommand(origin, pair.getCommandInfo(), pair.getCommand(), args,
  109. getCommandContext(origin, pair.getCommandInfo(), pair.getCommand(), args));
  110. } else {
  111. handleInvalidCommand(origin, args);
  112. }
  113. } else {
  114. handleNonCommand(origin, line);
  115. }
  116. }
  117. /**
  118. * Checks to see whether the inputted command is a channel or external command, and if it is
  119. * whether one or more channels have been specified for its execution. If it is a channel or
  120. * external command, and channels are specified, this method invoke the appropriate command
  121. * parser methods to handle the command, and will return true. If the command is not handled,
  122. * the method returns false.
  123. *
  124. * @param origin The container which received the command
  125. * @param args The command and its arguments
  126. * @param parseChannel Whether or not to try parsing channel names
  127. *
  128. * @return True iff the command was handled, false otherwise
  129. */
  130. protected boolean handleChannelCommand(@Nonnull final WindowModel origin,
  131. final CommandArguments args, final boolean parseChannel) {
  132. final boolean silent = args.isSilent();
  133. final String command = args.getCommandName();
  134. final String[] cargs = args.getArguments();
  135. final Optional<Connection> connection = origin.getConnection();
  136. if (cargs.length == 0
  137. || !parseChannel
  138. || !connection.isPresent()
  139. || !commandManager.isChannelCommand(command)) {
  140. return false;
  141. }
  142. final Connection server = connection.get();
  143. final String[] parts = cargs[0].split(",");
  144. boolean someValid = false;
  145. for (String part : parts) {
  146. someValid |= server.getGroupChatManager().isValidChannelName(part);
  147. }
  148. if (someValid) {
  149. for (String channelName : parts) {
  150. if (!server.getGroupChatManager().isValidChannelName(channelName)) {
  151. origin.getEventBus().publishAsync(new CommandErrorEvent(origin,
  152. "Invalid channel name: " + channelName));
  153. continue;
  154. }
  155. final String newCommandString = commandManager.getCommandChar()
  156. + (silent ? String.valueOf(commandManager.getSilenceChar()) : "")
  157. + args.getCommandName()
  158. + (cargs.length > 1 ? ' ' + args.getArgumentsAsString(1) : "");
  159. final Optional<GroupChat> channel = server.getGroupChatManager()
  160. .getChannel(channelName);
  161. if (channel.isPresent()) {
  162. channel.get().getWindowModel().getInputModel().map(InputModel::getCommandParser)
  163. .ifPresent(cp -> cp.parseCommand(origin, newCommandString, false));
  164. } else {
  165. final Map.Entry<CommandInfo, Command> actCommand = commandManager.getCommand(
  166. CommandType.TYPE_CHANNEL, command);
  167. if (actCommand != null && actCommand.getValue() instanceof ExternalCommand) {
  168. ((ExternalCommand) actCommand.getValue()).execute(
  169. origin, server, channelName, silent,
  170. new CommandArguments(commandManager, newCommandString));
  171. }
  172. }
  173. }
  174. return true;
  175. }
  176. return false;
  177. }
  178. /**
  179. * Adds a command to this parser's history.
  180. *
  181. * @param command The command name and arguments that were used
  182. */
  183. private void addHistory(final String command) {
  184. synchronized (history) {
  185. final PreviousCommand pc = new PreviousCommand(command);
  186. history.remove(pc);
  187. history.add(pc);
  188. }
  189. }
  190. /**
  191. * Retrieves the most recent time that the specified command was used. Commands should not
  192. * include command or silence chars.
  193. *
  194. * @param command The command to search for
  195. *
  196. * @return The timestamp that the command was used, or 0 if it wasn't
  197. */
  198. public long getCommandTime(final String command) {
  199. long res = 0;
  200. synchronized (history) {
  201. for (PreviousCommand pc : history.getList()) {
  202. if (pc.getLine().matches("(?i)" + command)) {
  203. res = Math.max(res, pc.getTime());
  204. }
  205. }
  206. }
  207. return res;
  208. }
  209. @Override
  210. public void parseCommand(@Nonnull final WindowModel origin, final String line) {
  211. parseCommand(origin, line, true);
  212. }
  213. @Override
  214. public void parseCommandCtrl(final WindowModel origin, final String line) {
  215. handleNonCommand(origin, line);
  216. }
  217. @Override
  218. @Nullable
  219. public CommandInfoPair getCommand(final String commandName) {
  220. return commands.get(commandName);
  221. }
  222. /**
  223. * Gets the context that the command will execute with.
  224. *
  225. * @param origin The container which received the command
  226. * @param commandInfo The command information object matched by the command
  227. * @param command The command to be executed
  228. * @param args The arguments to the command
  229. *
  230. * @return The context for the command.
  231. */
  232. protected abstract CommandContext getCommandContext(
  233. final WindowModel origin,
  234. final CommandInfo commandInfo,
  235. final Command command,
  236. final CommandArguments args);
  237. /**
  238. * Executes the specified command with the given arguments.
  239. *
  240. * @param origin The container which received the command
  241. * @param commandInfo The command information object matched by the command
  242. * @param command The command to be executed
  243. * @param args The arguments to the command
  244. * @param context The context to use when executing the command
  245. */
  246. protected abstract void executeCommand(
  247. @Nonnull final WindowModel origin,
  248. final CommandInfo commandInfo, final Command command,
  249. final CommandArguments args, final CommandContext context);
  250. /**
  251. * Called when the user attempted to issue a command (i.e., used the command character) that
  252. * wasn't found. It could be that the command has a different arity, or that it plain doesn't
  253. * exist.
  254. *
  255. * @param origin The window in which the command was typed
  256. * @param args The arguments passed to the command
  257. *
  258. * @since 0.6.3m1
  259. */
  260. protected void handleInvalidCommand(final WindowModel origin,
  261. final CommandArguments args) {
  262. eventBus.publishAsync(new UnknownCommandEvent(origin, args.getCommandName(),
  263. args.getArguments()));
  264. }
  265. /**
  266. * Called when the input was a line of text that was not a command. This normally means it is
  267. * sent to the server/channel/user as-is, with no further processing.
  268. *
  269. * @param origin The window in which the command was typed
  270. * @param line The line input by the user
  271. */
  272. protected abstract void handleNonCommand(final WindowModel origin,
  273. final String line);
  274. /**
  275. * Determines if the specified command has defined any command options.
  276. *
  277. * @param command The command to investigate
  278. *
  279. * @return True if the command defines options, false otherwise
  280. */
  281. protected boolean hasCommandOptions(final Command command) {
  282. return command.getClass().isAnnotationPresent(CommandOptions.class);
  283. }
  284. /**
  285. * Retrieves the command options for the specified command. If the command does not define
  286. * options, this method will return null.
  287. *
  288. * @param command The command whose options should be retrieved
  289. *
  290. * @return The command's options, or null if not available
  291. */
  292. protected CommandOptions getCommandOptions(final Command command) {
  293. return command.getClass().getAnnotation(CommandOptions.class);
  294. }
  295. }