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.

CommandParser.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 CommandParser implements Serializable {
  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 CommandParser(
  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. /**
  85. * Registers the specified command with this parser.
  86. *
  87. * @since 0.6.3m1
  88. * @param command Command to be registered
  89. * @param info The information the command should be registered with
  90. */
  91. public final void registerCommand(final Command command, final CommandInfo info) {
  92. commands.put(info.getName().toLowerCase(), new CommandInfoPair(info, command));
  93. }
  94. /**
  95. * Unregisters the specified command with this parser.
  96. *
  97. * @param info Command information to be unregistered
  98. *
  99. * @since 0.6.3m1
  100. */
  101. public final void unregisterCommand(final CommandInfo info) {
  102. commands.remove(info.getName().toLowerCase());
  103. }
  104. /**
  105. * Retrieves a map of commands known by this command parser.
  106. *
  107. * @since 0.6.3m1
  108. * @return A map of commands known to this parser
  109. */
  110. public Map<String, CommandInfoPair> getCommands() {
  111. return new HashMap<>(commands);
  112. }
  113. /**
  114. * Parses the specified string as a command.
  115. *
  116. * @param origin The container which received the command
  117. * @param line The line to be parsed
  118. * @param parseChannel Whether or not to try and parse the first argument as a channel name
  119. *
  120. * @since 0.6.4
  121. */
  122. public final void parseCommand(@Nonnull final WindowModel origin, final String line,
  123. final boolean parseChannel) {
  124. checkNotNull(origin);
  125. final CommandArguments args = new CommandArguments(commandManager, line);
  126. if (args.isCommand()) {
  127. if (handleChannelCommand(origin, args, parseChannel)) {
  128. return;
  129. }
  130. if (commands.containsKey(args.getCommandName().toLowerCase())) {
  131. final CommandInfoPair pair = commands.get(args.getCommandName().toLowerCase());
  132. addHistory(args.getStrippedLine());
  133. executeCommand(origin, pair.getCommandInfo(), pair.getCommand(), args,
  134. getCommandContext(origin, pair.getCommandInfo(), pair.getCommand(), args));
  135. } else {
  136. handleInvalidCommand(origin, args);
  137. }
  138. } else {
  139. handleNonCommand(origin, line);
  140. }
  141. }
  142. /**
  143. * Checks to see whether the inputted command is a channel or external command, and if it is
  144. * whether one or more channels have been specified for its execution. If it is a channel or
  145. * external command, and channels are specified, this method invoke the appropriate command
  146. * parser methods to handle the command, and will return true. If the command is not handled,
  147. * the method returns false.
  148. *
  149. * @param origin The container which received the command
  150. * @param args The command and its arguments
  151. * @param parseChannel Whether or not to try parsing channel names
  152. *
  153. * @return True iff the command was handled, false otherwise
  154. */
  155. protected boolean handleChannelCommand(@Nonnull final WindowModel origin,
  156. final CommandArguments args, final boolean parseChannel) {
  157. final boolean silent = args.isSilent();
  158. final String command = args.getCommandName();
  159. final String[] cargs = args.getArguments();
  160. final Optional<Connection> connection = origin.getConnection();
  161. if (cargs.length == 0
  162. || !parseChannel
  163. || !connection.isPresent()
  164. || !commandManager.isChannelCommand(command)) {
  165. return false;
  166. }
  167. final Connection server = connection.get();
  168. final String[] parts = cargs[0].split(",");
  169. boolean someValid = false;
  170. for (String part : parts) {
  171. someValid |= server.getGroupChatManager().isValidChannelName(part);
  172. }
  173. if (someValid) {
  174. for (String channelName : parts) {
  175. if (!server.getGroupChatManager().isValidChannelName(channelName)) {
  176. origin.getEventBus().publishAsync(new CommandErrorEvent(origin,
  177. "Invalid channel name: " + channelName));
  178. continue;
  179. }
  180. final String newCommandString = commandManager.getCommandChar()
  181. + (silent ? String.valueOf(commandManager.getSilenceChar()) : "")
  182. + args.getCommandName()
  183. + (cargs.length > 1 ? ' ' + args.getArgumentsAsString(1) : "");
  184. final Optional<GroupChat> channel = server.getGroupChatManager()
  185. .getChannel(channelName);
  186. if (channel.isPresent()) {
  187. channel.get().getWindowModel().getInputModel().map(InputModel::getCommandParser)
  188. .ifPresent(cp -> cp.parseCommand(origin, newCommandString, false));
  189. } else {
  190. final Map.Entry<CommandInfo, Command> actCommand = commandManager.getCommand(
  191. CommandType.TYPE_CHANNEL, command);
  192. if (actCommand != null && actCommand.getValue() instanceof ExternalCommand) {
  193. ((ExternalCommand) actCommand.getValue()).execute(
  194. origin, server, channelName, silent,
  195. new CommandArguments(commandManager, newCommandString));
  196. }
  197. }
  198. }
  199. return true;
  200. }
  201. return false;
  202. }
  203. /**
  204. * Adds a command to this parser's history.
  205. *
  206. * @param command The command name and arguments that were used
  207. */
  208. private void addHistory(final String command) {
  209. synchronized (history) {
  210. final PreviousCommand pc = new PreviousCommand(command);
  211. history.remove(pc);
  212. history.add(pc);
  213. }
  214. }
  215. /**
  216. * Retrieves the most recent time that the specified command was used. Commands should not
  217. * include command or silence chars.
  218. *
  219. * @param command The command to search for
  220. *
  221. * @return The timestamp that the command was used, or 0 if it wasn't
  222. */
  223. public long getCommandTime(final String command) {
  224. long res = 0;
  225. synchronized (history) {
  226. for (PreviousCommand pc : history.getList()) {
  227. if (pc.getLine().matches("(?i)" + command)) {
  228. res = Math.max(res, pc.getTime());
  229. }
  230. }
  231. }
  232. return res;
  233. }
  234. /**
  235. * Parses the specified string as a command.
  236. *
  237. * @param origin The container which received the command
  238. * @param line The line to be parsed
  239. *
  240. * @since 0.6.4
  241. */
  242. public void parseCommand(@Nonnull final WindowModel origin, final String line) {
  243. parseCommand(origin, line, true);
  244. }
  245. /**
  246. * Handles the specified string as a non-command.
  247. *
  248. * @param origin The window in which the command was typed
  249. * @param line The line to be parsed
  250. */
  251. public void parseCommandCtrl(final WindowModel origin, final String line) {
  252. handleNonCommand(origin, line);
  253. }
  254. /**
  255. * Gets the command with the given name that was previously registered with this parser.
  256. *
  257. * @param commandName The name of the command to retrieve.
  258. * @return The command info pair, or {@code null} if the command does not exist.
  259. */
  260. @Nullable
  261. public CommandInfoPair getCommand(final String commandName) {
  262. return commands.get(commandName);
  263. }
  264. /**
  265. * Gets the context that the command will execute with.
  266. *
  267. * @param origin The container which received the command
  268. * @param commandInfo The command information object matched by the command
  269. * @param command The command to be executed
  270. * @param args The arguments to the command
  271. *
  272. * @return The context for the command.
  273. */
  274. protected abstract CommandContext getCommandContext(
  275. final WindowModel origin,
  276. final CommandInfo commandInfo,
  277. final Command command,
  278. final CommandArguments args);
  279. /**
  280. * Executes the specified command with the given arguments.
  281. *
  282. * @param origin The container which received the command
  283. * @param commandInfo The command information object matched by the command
  284. * @param command The command to be executed
  285. * @param args The arguments to the command
  286. * @param context The context to use when executing the command
  287. */
  288. protected abstract void executeCommand(
  289. @Nonnull final WindowModel origin,
  290. final CommandInfo commandInfo, final Command command,
  291. final CommandArguments args, final CommandContext context);
  292. /**
  293. * Called when the user attempted to issue a command (i.e., used the command character) that
  294. * wasn't found. It could be that the command has a different arity, or that it plain doesn't
  295. * exist.
  296. *
  297. * @param origin The window in which the command was typed
  298. * @param args The arguments passed to the command
  299. *
  300. * @since 0.6.3m1
  301. */
  302. protected void handleInvalidCommand(final WindowModel origin,
  303. final CommandArguments args) {
  304. eventBus.publishAsync(new UnknownCommandEvent(origin, args.getCommandName(),
  305. args.getArguments()));
  306. }
  307. /**
  308. * Called when the input was a line of text that was not a command. This normally means it is
  309. * sent to the server/channel/user as-is, with no further processing.
  310. *
  311. * @param origin The window in which the command was typed
  312. * @param line The line input by the user
  313. */
  314. protected abstract void handleNonCommand(final WindowModel origin,
  315. final String line);
  316. /**
  317. * Determines if the specified command has defined any command options.
  318. *
  319. * @param command The command to investigate
  320. *
  321. * @return True if the command defines options, false otherwise
  322. */
  323. protected boolean hasCommandOptions(final Command command) {
  324. return command.getClass().isAnnotationPresent(CommandOptions.class);
  325. }
  326. /**
  327. * Retrieves the command options for the specified command. If the command does not define
  328. * options, this method will return null.
  329. *
  330. * @param command The command whose options should be retrieved
  331. *
  332. * @return The command's options, or null if not available
  333. */
  334. protected CommandOptions getCommandOptions(final Command command) {
  335. return command.getClass().getAnnotation(CommandOptions.class);
  336. }
  337. }