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.

ActionSubstitutor.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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.actions;
  23. import com.dmdirc.ClientModule.GlobalConfig;
  24. import com.dmdirc.FrameContainer;
  25. import com.dmdirc.Precondition;
  26. import com.dmdirc.ServerState;
  27. import com.dmdirc.commandparser.CommandArguments;
  28. import com.dmdirc.interfaces.ActionController;
  29. import com.dmdirc.interfaces.CommandController;
  30. import com.dmdirc.interfaces.Connection;
  31. import com.dmdirc.interfaces.actions.ActionComponent;
  32. import com.dmdirc.interfaces.actions.ActionType;
  33. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  34. import com.dmdirc.interfaces.ui.Window;
  35. import com.dmdirc.util.annotations.factory.Factory;
  36. import com.dmdirc.util.annotations.factory.Unbound;
  37. import java.util.Arrays;
  38. import java.util.HashMap;
  39. import java.util.Map;
  40. import java.util.Set;
  41. import java.util.regex.Matcher;
  42. import java.util.regex.Pattern;
  43. /**
  44. * Handles the substitution of variables into action targets and responses.
  45. */
  46. @Factory(inject = true, providers = true, singleton = true)
  47. public class ActionSubstitutor {
  48. /** Substitution to use when a component requires a connected server. */
  49. private static final String ERR_NOT_CONNECTED = "not_connected";
  50. /** Substitution to use to replace an unknown substitution. */
  51. private static final String ERR_NOT_DEFINED = "not_defined";
  52. /** Substitution to use to replace a chain that evaluates to null. */
  53. private static final String ERR_NULL_CHAIN = "null_component";
  54. /** Substitution to use to replace subs with illegal components. */
  55. private static final String ERR_ILLEGAL_COMPONENT = "illegal_component";
  56. /** Pattern used to match braced substitutions. */
  57. private static final Pattern BRACES_PATTERN = Pattern.compile("(?<!\\\\)((?:\\\\\\\\)*)"
  58. + "(\\$\\{([^{}]*?)\\})");
  59. /** Pattern used to match all other substitutions. */
  60. private static final Pattern OTHER_PATTERN = Pattern.compile("(?<!\\\\)((?:\\\\\\\\)*)(\\$("
  61. + "[0-9]+(-([0-9]+)?)?|" // Word subs - $1, $1-, $1-2
  62. + "[0-9]+(\\.([A-Z_]+))+|" // Component subs - 2.FOO_BAR
  63. + "[a-z0-9A-Z_\\.]+" // Config/server subs
  64. + "))");
  65. /** Pattern to determine if a substitution is a word number type. */
  66. private static final Pattern NUMBER_PATTERN = Pattern.compile("([0-9]+)(-([0-9]+)?)?");
  67. /** Pattern to determine if a substitution is an argument+component type. */
  68. private static final Pattern COMP_PATTERN = Pattern.compile("([0-9]+)\\.([A-Z_]+(\\.[A-Z_]+)*)");
  69. /** Pattern to determine if a substitution is a server component type. */
  70. private static final Pattern SERVER_PATTERN = Pattern.compile("[A-Z_]+(\\.[A-Z_]+)*");
  71. /** The action controller to use to find components. */
  72. private final ActionController actionController;
  73. /** The global config to read settings from. */
  74. private final AggregateConfigProvider globalConfig;
  75. /** The command controller to use when building command arguments. */
  76. private final CommandController commandController;
  77. /** The action type this substitutor is for. */
  78. private final ActionType type;
  79. /**
  80. * Creates a new substitutor for the specified action type.
  81. *
  82. * @param actionController The action controller to use to find components.
  83. * @param commandController The command controller to use when building command arguments.
  84. * @param globalConfig The global config to read settings from.
  85. * @param type The action type this substitutor is for
  86. */
  87. public ActionSubstitutor(
  88. final ActionController actionController,
  89. final CommandController commandController,
  90. @SuppressWarnings("qualifiers") @GlobalConfig final AggregateConfigProvider globalConfig,
  91. @Unbound final ActionType type) {
  92. this.actionController = actionController;
  93. this.globalConfig = globalConfig;
  94. this.commandController = commandController;
  95. this.type = type;
  96. }
  97. /**
  98. * Retrieves a list of global config variables that will be substituted.
  99. * Note: does not include initial $.
  100. *
  101. * @return A list of global variable names that will be substituted
  102. */
  103. public Set<String> getConfigSubstitutions() {
  104. return globalConfig.getOptions("actions").keySet();
  105. }
  106. /**
  107. * Retrieves a list of substitutions derived from argument and component
  108. * combinations, along with a corresponding friendly name for them.
  109. * Note: does not include initial $.
  110. *
  111. * @return A map of component substitution names and their descriptions
  112. */
  113. public Map<String, String> getComponentSubstitutions() {
  114. final Map<String, String> res = new HashMap<>();
  115. int i = 0;
  116. for (Class<?> myClass : type.getType().getArgTypes()) {
  117. for (ActionComponent comp : actionController.findCompatibleComponents(myClass)) {
  118. final String key = "{" + i + "." + comp.toString() + "}";
  119. final String desc = type.getType().getArgNames()[i] + "'s " + comp.getName();
  120. res.put(key, desc);
  121. }
  122. i++;
  123. }
  124. return res;
  125. }
  126. /**
  127. * Retrieves a list of server substitutions, if this action type supports
  128. * them.
  129. * Note: does not include initial $.
  130. *
  131. * @return A map of server substitution names and their descriptions.
  132. */
  133. public Map<String, String> getServerSubstitutions() {
  134. final Map<String, String> res = new HashMap<>();
  135. if (hasFrameContainer()) {
  136. for (ActionComponent comp : actionController.findCompatibleComponents(Connection.class)) {
  137. final String key = "{" + comp.toString() + "}";
  138. final String desc = "The connection's " + comp.getName();
  139. res.put(key, desc);
  140. }
  141. }
  142. return res;
  143. }
  144. /**
  145. * Returns true if this action type's first argument is a frame container,
  146. * or descendent of one.
  147. *
  148. * @return True if this action type's first arg extends or is a FrameContainer
  149. */
  150. private boolean hasFrameContainer() {
  151. Class<?> target = null;
  152. if (type.getType().getArgTypes().length > 0) {
  153. target = type.getType().getArgTypes()[0];
  154. while (target != null && target != FrameContainer.class) {
  155. target = target.getSuperclass();
  156. }
  157. }
  158. return target == FrameContainer.class;
  159. }
  160. /**
  161. * Determines whether or not word substitutions will work for this action
  162. * type. Word substitutions take the form $1, $1-5, $6-, etc.
  163. *
  164. * @return True if word substitutions are supported, false otherwise.
  165. */
  166. public boolean usesWordSubstitutions() {
  167. return type.getType().getArgTypes().length > 2
  168. && (type.getType().getArgTypes()[2] == String[].class
  169. || type.getType().getArgTypes()[2] == String.class);
  170. }
  171. /**
  172. * Performs all applicable substitutions on the specified string, with the
  173. * specified arguments.
  174. *
  175. * @param target The string to be altered
  176. * @param args The arguments for the action type
  177. * @return The substituted string
  178. */
  179. @Precondition("Number of arguments given equals the number of arguments "
  180. + "required by this substitutor's type")
  181. public String doSubstitution(final String target, final Object ... args) {
  182. if (type.getType().getArity() != args.length) {
  183. throw new IllegalArgumentException("Invalid number of arguments "
  184. + "for doSubstitution: expected " + type.getType().getArity() + ", got "
  185. + args.length + ". Type: " + type.getName());
  186. }
  187. final StringBuilder res = new StringBuilder(target);
  188. Matcher bracesMatcher = BRACES_PATTERN.matcher(res);
  189. Matcher otherMatcher = OTHER_PATTERN.matcher(res);
  190. boolean first;
  191. while ((first = bracesMatcher.find()) || otherMatcher.find()) {
  192. final Matcher matcher = first ? bracesMatcher : otherMatcher;
  193. final String group = matcher.group(3);
  194. final int start = matcher.start() + matcher.group(1).length(), end = matcher.end();
  195. res.delete(start, end);
  196. res.insert(start, getSubstitution(doSubstitution(group, args), args));
  197. bracesMatcher = BRACES_PATTERN.matcher(res);
  198. otherMatcher = OTHER_PATTERN.matcher(res);
  199. }
  200. return res.toString().replaceAll("\\\\(.)", "$1");
  201. }
  202. /**
  203. * Retrieves the value which should be used for the specified substitution.
  204. *
  205. * @param substitution The substitution, without leading $
  206. * @param args The arguments for the action
  207. * @return The substitution to be used
  208. */
  209. private String getSubstitution(final String substitution, final Object ... args) {
  210. final Matcher numberMatcher = NUMBER_PATTERN.matcher(substitution);
  211. final Matcher compMatcher = COMP_PATTERN.matcher(substitution);
  212. final Matcher serverMatcher = SERVER_PATTERN.matcher(substitution);
  213. if (usesWordSubstitutions() && numberMatcher.matches()) {
  214. final CommandArguments words = args[2] instanceof String
  215. ? new CommandArguments(commandController, (String) args[2])
  216. : new CommandArguments(commandController, Arrays.asList((String[]) args[2]));
  217. int start, end;
  218. start = end = Integer.parseInt(numberMatcher.group(1)) - 1;
  219. if (numberMatcher.group(3) != null) {
  220. end = Integer.parseInt(numberMatcher.group(3)) - 1;
  221. } else if (numberMatcher.group(2) != null) {
  222. end = words.getWords().length - 1;
  223. }
  224. return words.getWordsAsString(start, end);
  225. }
  226. if (compMatcher.matches()) {
  227. final int argument = Integer.parseInt(compMatcher.group(1));
  228. try {
  229. final ActionComponentChain chain = new ActionComponentChain(
  230. type.getType().getArgTypes()[argument], compMatcher.group(2),
  231. actionController);
  232. return escape(checkConnection(chain, args, args[argument]));
  233. } catch (IllegalArgumentException ex) {
  234. return ERR_ILLEGAL_COMPONENT;
  235. }
  236. }
  237. final AggregateConfigProvider manager = getConfigManager(args);
  238. if (manager.hasOptionString("actions", substitution)) {
  239. return manager.getOption("actions", substitution);
  240. }
  241. if (hasFrameContainer() && serverMatcher.matches()) {
  242. final Connection connection = ((FrameContainer) args[0]).getConnection();
  243. if (connection != null) {
  244. try {
  245. final ActionComponentChain chain = new ActionComponentChain(
  246. Connection.class, substitution, actionController);
  247. return escape(checkConnection(chain, args, connection));
  248. } catch (IllegalArgumentException ex) {
  249. return ERR_ILLEGAL_COMPONENT;
  250. }
  251. }
  252. }
  253. return ERR_NOT_DEFINED;
  254. }
  255. /**
  256. * Checks the connection status of any server associated with the specified
  257. * arguments. If the specified component chain requires a server with an
  258. * established connection and no such server is present, this method
  259. * returns the string <code>not_connected</code> without attempting to
  260. * evaluate any components in the chain.
  261. *
  262. * @since 0.6.4
  263. * @param chain The chain to be checked
  264. * @param args The arguments for this invocation
  265. * @param argument The argument used as a base for the chain
  266. * @return The value of the evaluated chain, or <code>not_connected</code>
  267. */
  268. protected String checkConnection(final ActionComponentChain chain,
  269. final Object[] args, final Object argument) {
  270. if ((chain.requiresConnection() && args[0] instanceof FrameContainer
  271. && ((FrameContainer) args[0]).getConnection().getState()
  272. == ServerState.CONNECTED) || !chain.requiresConnection()) {
  273. final Object res = chain.get(argument);
  274. return res == null ? ERR_NULL_CHAIN : res.toString();
  275. }
  276. return ERR_NOT_CONNECTED;
  277. }
  278. /**
  279. * Tries to retrieve an appropriate configuration manager from the
  280. * specified set of arguments. If any of the arguments is an instance of
  281. * {@link FrameContainer} or {@link Window}, the config manager is
  282. * requested from them. Otherwise, the global config is returned.
  283. *
  284. * @param args The arguments to be tested
  285. * @return The best config manager to use for those arguments
  286. * @since 0.6.3m2
  287. */
  288. protected AggregateConfigProvider getConfigManager(final Object ... args) {
  289. for (Object arg : args) {
  290. if (arg instanceof FrameContainer) {
  291. return ((FrameContainer) arg).getConfigManager();
  292. } else if (arg instanceof Window) {
  293. return ((Window) arg).getContainer().getConfigManager();
  294. }
  295. }
  296. return globalConfig;
  297. }
  298. /**
  299. * Escapes all special characters in the specified input. This will result
  300. * in the input being treated as a plain string when passed through the
  301. * substitutor (i.e., no substitutions will occur).
  302. *
  303. * @param input The string to be escaped
  304. * @return An escaped version of the specified string
  305. * @since 0.6.4
  306. */
  307. protected static String escape(final String input) {
  308. return input.replace("\\", "\\\\").replace("$", "\\$");
  309. }
  310. }