Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

BaseCommandParser.java 13KB

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