Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

CommandParser.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /*
  2. * Copyright (c) 2006-2014 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.DMDircMBassador;
  24. import com.dmdirc.FrameContainer;
  25. import com.dmdirc.Server;
  26. import com.dmdirc.commandparser.CommandArguments;
  27. import com.dmdirc.commandparser.CommandInfo;
  28. import com.dmdirc.commandparser.CommandInfoPair;
  29. import com.dmdirc.commandparser.CommandType;
  30. import com.dmdirc.commandparser.commands.Command;
  31. import com.dmdirc.commandparser.commands.CommandOptions;
  32. import com.dmdirc.commandparser.commands.ExternalCommand;
  33. import com.dmdirc.commandparser.commands.PreviousCommand;
  34. import com.dmdirc.commandparser.commands.context.CommandContext;
  35. import com.dmdirc.events.EventUtils;
  36. import com.dmdirc.events.UnknownCommandEvent;
  37. import com.dmdirc.interfaces.CommandController;
  38. import com.dmdirc.interfaces.Connection;
  39. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  40. import com.dmdirc.util.collections.RollingList;
  41. import java.io.Serializable;
  42. import java.util.HashMap;
  43. import java.util.Map;
  44. import javax.annotation.Nonnull;
  45. import static com.google.common.base.Preconditions.checkNotNull;
  46. /**
  47. * Represents a generic command parser. A command parser takes a line of input from the user,
  48. * determines if it is an attempt at executing a command (based on the character at the start of the
  49. * string), and handles it appropriately.
  50. */
  51. public abstract class CommandParser implements Serializable {
  52. /** A version number for this class. */
  53. private static final long serialVersionUID = 1;
  54. /** Commands that are associated with this parser. */
  55. private final Map<String, CommandInfoPair> commands;
  56. /** A history of commands that have been entered into this parser. */
  57. private final RollingList<PreviousCommand> history;
  58. /** Command manager to use. */
  59. protected final CommandController commandManager;
  60. /** Event bus to post events to. */
  61. private final DMDircMBassador eventBus;
  62. /**
  63. * Creates a new instance of CommandParser.
  64. *
  65. * @param configManager Config manager to read settings
  66. * @param commandManager Command manager to load plugins from
  67. * @param eventBus The event bus to post events to.
  68. */
  69. protected CommandParser(final AggregateConfigProvider configManager,
  70. final CommandController commandManager,
  71. final DMDircMBassador eventBus) {
  72. this.eventBus = eventBus;
  73. commands = new HashMap<>();
  74. history = new RollingList<>(configManager.getOptionInt("general", "commandhistory"));
  75. this.commandManager = commandManager;
  76. loadCommands();
  77. }
  78. /**
  79. * @deprecated Callers should obtain their own instance of command controller.
  80. *
  81. * @return The command manager for this parser.
  82. */
  83. @Deprecated
  84. public CommandController getCommandManager() {
  85. return commandManager;
  86. }
  87. /**
  88. * Sets the owner of this command parser.
  89. *
  90. * @param owner The container which owns this parser
  91. *
  92. * @since 0.6.4
  93. */
  94. public abstract void setOwner(final FrameContainer owner);
  95. /** Loads the relevant commands into the parser. */
  96. protected abstract void loadCommands();
  97. /**
  98. * Registers the specified command with this parser.
  99. *
  100. * @since 0.6.3m1
  101. * @param command Command to be registered
  102. * @param info The information the command should be registered with
  103. */
  104. public final void registerCommand(final Command command, final CommandInfo info) {
  105. commands.put(info.getName().toLowerCase(), new CommandInfoPair(info, command));
  106. }
  107. /**
  108. * Unregisters the specified command with this parser.
  109. *
  110. * @param info Command information to be unregistered
  111. *
  112. * @since 0.6.3m1
  113. */
  114. public final void unregisterCommand(final CommandInfo info) {
  115. commands.remove(info.getName().toLowerCase());
  116. }
  117. /**
  118. * Retrieves a map of commands known by this command parser.
  119. *
  120. * @since 0.6.3m1
  121. * @return A map of commands known to this parser
  122. */
  123. public Map<String, CommandInfoPair> getCommands() {
  124. return new HashMap<>(commands);
  125. }
  126. /**
  127. * Parses the specified string as a command.
  128. *
  129. * @param origin The container which received the command
  130. * @param line The line to be parsed
  131. * @param parseChannel Whether or not to try and parse the first argument as a channel name
  132. *
  133. * @since 0.6.4
  134. */
  135. public final void parseCommand(@Nonnull final FrameContainer origin, final String line,
  136. final boolean parseChannel) {
  137. checkNotNull(origin);
  138. final CommandArguments args = new CommandArguments(commandManager, line);
  139. if (args.isCommand()) {
  140. if (handleChannelCommand(origin, args, parseChannel)) {
  141. return;
  142. }
  143. if (commands.containsKey(args.getCommandName().toLowerCase())) {
  144. final CommandInfoPair pair = commands.get(args.getCommandName().toLowerCase());
  145. addHistory(args.getStrippedLine());
  146. executeCommand(origin, pair.getCommandInfo(), pair.getCommand(), args,
  147. getCommandContext(origin, pair.getCommandInfo(), pair.getCommand(), args));
  148. } else {
  149. handleInvalidCommand(origin, args);
  150. }
  151. } else {
  152. handleNonCommand(origin, line);
  153. }
  154. }
  155. /**
  156. * Checks to see whether the inputted command is a channel or external command, and if it is
  157. * whether one or more channels have been specified for its execution. If it is a channel or
  158. * external command, and channels are specified, this method invoke the appropriate command
  159. * parser methods to handle the command, and will return true. If the command is not handled,
  160. * the method returns false.
  161. *
  162. * @param origin The container which received the command
  163. * @param args The command and its arguments
  164. * @param parseChannel Whether or not to try parsing channel names
  165. *
  166. * @return True iff the command was handled, false otherwise
  167. */
  168. protected boolean handleChannelCommand(@Nonnull final FrameContainer origin,
  169. final CommandArguments args, final boolean parseChannel) {
  170. final boolean silent = args.isSilent();
  171. final String command = args.getCommandName();
  172. final String[] cargs = args.getArguments();
  173. if (cargs.length == 0 || !parseChannel
  174. || origin.getConnection() == null
  175. || !commandManager.isChannelCommand(command)) {
  176. return false;
  177. }
  178. final Connection server = origin.getConnection();
  179. final String[] parts = cargs[0].split(",");
  180. boolean someValid = false;
  181. for (String part : parts) {
  182. someValid |= server.isValidChannelName(part);
  183. }
  184. if (someValid) {
  185. for (String channel : parts) {
  186. if (!server.isValidChannelName(channel)) {
  187. origin.addLine("commandError", "Invalid channel name: " + channel);
  188. continue;
  189. }
  190. final String newCommandString = commandManager.getCommandChar()
  191. + (silent ? String.valueOf(commandManager.getSilenceChar()) : "")
  192. + args.getCommandName()
  193. + (cargs.length > 1 ? " " + args.getArgumentsAsString(1) : "");
  194. if (server.hasChannel(channel)) {
  195. server.getChannel(channel).getCommandParser().parseCommand(origin,
  196. newCommandString, false);
  197. } else {
  198. final Map.Entry<CommandInfo, Command> actCommand = commandManager.getCommand(
  199. CommandType.TYPE_CHANNEL, command);
  200. if (actCommand != null && actCommand.getValue() instanceof ExternalCommand) {
  201. ((ExternalCommand) actCommand.getValue()).execute(
  202. origin, (Server) server, channel, silent,
  203. new CommandArguments(commandManager, newCommandString));
  204. }
  205. }
  206. }
  207. return true;
  208. }
  209. return false;
  210. }
  211. /**
  212. * Adds a command to this parser's history.
  213. *
  214. * @param command The command name and arguments that were used
  215. */
  216. private void addHistory(final String command) {
  217. synchronized (history) {
  218. final PreviousCommand pc = new PreviousCommand(command);
  219. history.remove(pc);
  220. history.add(pc);
  221. }
  222. }
  223. /**
  224. * Retrieves the most recent time that the specified command was used. Commands should not
  225. * include command or silence chars.
  226. *
  227. * @param command The command to search for
  228. *
  229. * @return The timestamp that the command was used, or 0 if it wasn't
  230. */
  231. public long getCommandTime(final String command) {
  232. long res = 0;
  233. synchronized (history) {
  234. for (PreviousCommand pc : history.getList()) {
  235. if (pc.getLine().matches("(?i)" + command)) {
  236. res = Math.max(res, pc.getTime());
  237. }
  238. }
  239. }
  240. return res;
  241. }
  242. /**
  243. * Parses the specified string as a command.
  244. *
  245. * @param origin The container which received the command
  246. * @param line The line to be parsed
  247. *
  248. * @since 0.6.4
  249. */
  250. public void parseCommand(@Nonnull final FrameContainer origin, final String line) {
  251. parseCommand(origin, line, true);
  252. }
  253. /**
  254. * Handles the specified string as a non-command.
  255. *
  256. * @param origin The window in which the command was typed
  257. * @param line The line to be parsed
  258. */
  259. public void parseCommandCtrl(final FrameContainer origin, final String line) {
  260. handleNonCommand(origin, line);
  261. }
  262. /**
  263. * Gets the context that the command will execute with.
  264. *
  265. * @param origin The container which received the command
  266. * @param commandInfo The command information object matched by the command
  267. * @param command The command to be executed
  268. * @param args The arguments to the command
  269. *
  270. * @return The context for the command.
  271. */
  272. protected abstract CommandContext getCommandContext(
  273. final FrameContainer origin,
  274. final CommandInfo commandInfo,
  275. final Command command,
  276. final CommandArguments args);
  277. /**
  278. * Executes the specified command with the given arguments.
  279. *
  280. * @param origin The container which received the command
  281. * @param commandInfo The command information object matched by the command
  282. * @param command The command to be executed
  283. * @param args The arguments to the command
  284. * @param context The context to use when executing the command
  285. */
  286. protected abstract void executeCommand(
  287. @Nonnull final FrameContainer origin,
  288. final CommandInfo commandInfo, final Command command,
  289. final CommandArguments args, final CommandContext context);
  290. /**
  291. * Called when the user attempted to issue a command (i.e., used the command character) that
  292. * wasn't found. It could be that the command has a different arity, or that it plain doesn't
  293. * exist.
  294. *
  295. * @param origin The window in which the command was typed
  296. * @param args The arguments passed to the command
  297. *
  298. * @since 0.6.3m1
  299. */
  300. protected void handleInvalidCommand(final FrameContainer origin,
  301. final CommandArguments args) {
  302. if (origin == null) {
  303. eventBus.publish(new UnknownCommandEvent(null, args.getCommandName(), args.getArguments()));
  304. } else {
  305. final UnknownCommandEvent event = new UnknownCommandEvent(origin, args.getCommandName(),
  306. args.getArguments());
  307. final String format = EventUtils.postDisplayable(eventBus, event, "unknownCommand");
  308. origin.addLine(format, args.getCommandName());
  309. }
  310. }
  311. /**
  312. * Called when the input was a line of text that was not a command. This normally means it is
  313. * sent to the server/channel/user as-is, with no further processing.
  314. *
  315. * @param origin The window in which the command was typed
  316. * @param line The line input by the user
  317. */
  318. protected abstract void handleNonCommand(final FrameContainer origin,
  319. final String line);
  320. /**
  321. * Determines if the specified command has defined any command options.
  322. *
  323. * @param command The command to investigate
  324. *
  325. * @return True if the command defines options, false otherwise
  326. */
  327. protected boolean hasCommandOptions(final Command command) {
  328. return command.getClass().isAnnotationPresent(CommandOptions.class);
  329. }
  330. /**
  331. * Retrieves the command options for the specified command. If the command does not define
  332. * options, this method will return null.
  333. *
  334. * @param command The command whose options should be retrieved
  335. *
  336. * @return The command's options, or null if not available
  337. */
  338. protected CommandOptions getCommandOptions(final Command command) {
  339. return command.getClass().getAnnotation(CommandOptions.class);
  340. }
  341. }