選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Action.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /*
  2. * Copyright (c) 2006-2011 Chris Smith, Shane Mc Cormack, Gregory Holmes
  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.actions.interfaces.ActionComparison;
  24. import com.dmdirc.actions.interfaces.ActionComponent;
  25. import com.dmdirc.actions.interfaces.ActionType;
  26. import com.dmdirc.config.IdentityManager;
  27. import com.dmdirc.config.prefs.PreferencesSetting;
  28. import com.dmdirc.config.prefs.PreferencesType;
  29. import com.dmdirc.interfaces.ConfigChangeListener;
  30. import com.dmdirc.logger.ErrorLevel;
  31. import com.dmdirc.logger.Logger;
  32. import com.dmdirc.updater.Version;
  33. import com.dmdirc.util.ConfigFile;
  34. import com.dmdirc.util.InvalidConfigFileException;
  35. import java.io.File;
  36. import java.io.IOException;
  37. import java.util.ArrayList;
  38. import java.util.Arrays;
  39. import java.util.HashMap;
  40. import java.util.List;
  41. import java.util.Map;
  42. /**
  43. * Describes a single action.
  44. *
  45. * @author chris
  46. */
  47. public class Action extends ActionModel implements ConfigChangeListener {
  48. /** The domain name for condition trees. */
  49. private static final String DOMAIN_CONDITIONTREE = "conditiontree".intern();
  50. /** The domain name for format changes. */
  51. private static final String DOMAIN_FORMAT = "format".intern();
  52. /** The domain name for meta-data. */
  53. private static final String DOMAIN_METADATA = "metadata".intern();
  54. /** The domain name for response information. */
  55. private static final String DOMAIN_RESPONSE = "response".intern();
  56. /** The domain name for triggers. */
  57. private static final String DOMAIN_TRIGGERS = "triggers".intern();
  58. /** The domain name for concurrency. */
  59. private static final String DOMAIN_CONCURRENCY = "concurrency".intern();
  60. /** The domain name for misc settings. */
  61. private static final String DOMAIN_MISC = "misc".intern();
  62. /** The location of the file we're reading/saving. */
  63. private String location;
  64. /** Whether or not this action is disabled. */
  65. protected boolean disabled;
  66. /** The config file we're using. */
  67. protected ConfigFile config;
  68. /**
  69. * Creates a new instance of Action. The group and name specified must
  70. * be the group and name of a valid action already saved to disk.
  71. *
  72. * @param group The group the action belongs to
  73. * @param name The name of the action
  74. */
  75. public Action(final String group, final String name) {
  76. super(group, name);
  77. location = ActionManager.getDirectory() + group + File.separator + name;
  78. try {
  79. config = new ConfigFile(location);
  80. config.read();
  81. loadActionFromConfig();
  82. } catch (InvalidConfigFileException ex) {
  83. // This isn't a valid config file. Maybe it's a properties file?
  84. Logger.userError(ErrorLevel.MEDIUM, "Unable to parse action file: "
  85. + group + "/" + name + ": " + ex.getMessage());
  86. } catch (IOException ex) {
  87. Logger.userError(ErrorLevel.HIGH, "I/O error when loading action: "
  88. + group + "/" + name + ": " + ex.getMessage());
  89. }
  90. IdentityManager.getGlobalConfig().addChangeListener("disable_action",
  91. (group + "/" + name).replace(' ', '.'), this);
  92. checkDisabled();
  93. }
  94. /**
  95. * Creates a new instance of Action with the specified properties and saves
  96. * it to disk.
  97. *
  98. * @param group The group the action belongs to
  99. * @param name The name of the action
  100. * @param triggers The triggers to use
  101. * @param response The response to use
  102. * @param conditions The conditions to use
  103. * @param newFormat The new formatter to use
  104. */
  105. public Action(final String group, final String name,
  106. final ActionType[] triggers, final String[] response,
  107. final List<ActionCondition> conditions, final String newFormat) {
  108. this(group, name, triggers, response, conditions,
  109. ConditionTree.createConjunction(conditions.size()), newFormat);
  110. }
  111. /**
  112. * Creates a new instance of Action with the specified properties and saves
  113. * it to disk.
  114. *
  115. * @param group The group the action belongs to
  116. * @param name The name of the action
  117. * @param triggers The triggers to use
  118. * @param response The response to use
  119. * @param conditions The conditions to use
  120. * @param conditionTree The condition tree to use
  121. * @param newFormat The new formatter to use
  122. */
  123. public Action(final String group, final String name,
  124. final ActionType[] triggers, final String[] response,
  125. final List<ActionCondition> conditions,
  126. final ConditionTree conditionTree, final String newFormat) {
  127. super(group, name, triggers, response, conditions, conditionTree, newFormat);
  128. final String dir = ActionManager.getDirectory() + group + File.separator;
  129. location = dir + name.replaceAll("[^A-Za-z0-9\\-_]", "_");
  130. new File(dir).mkdirs();
  131. ActionManager.processEvent(CoreActionType.ACTION_CREATED, null, this);
  132. save();
  133. ActionManager.registerAction(this);
  134. }
  135. /**
  136. * Loads this action from the config instance.
  137. */
  138. protected void loadActionFromConfig() {
  139. if (config.isFlatDomain(DOMAIN_TRIGGERS)) {
  140. if (!loadTriggers(config.getFlatDomain(DOMAIN_TRIGGERS))) {
  141. return;
  142. }
  143. } else {
  144. error("No trigger specified");
  145. return;
  146. }
  147. if (config.isFlatDomain(DOMAIN_RESPONSE)) {
  148. response = new String[config.getFlatDomain(DOMAIN_RESPONSE).size()];
  149. int i = 0;
  150. for (String line: config.getFlatDomain(DOMAIN_RESPONSE)) {
  151. response[i++] = line;
  152. }
  153. } else {
  154. error("No response specified");
  155. return;
  156. }
  157. if (config.isFlatDomain(DOMAIN_FORMAT)) {
  158. newFormat = config.getFlatDomain(DOMAIN_FORMAT).size() == 0 ? ""
  159. : config.getFlatDomain(DOMAIN_FORMAT).get(0);
  160. }
  161. for (int cond = 0; config.isKeyDomain("condition " + cond); cond++) {
  162. if (!readCondition(config.getKeyDomain("condition " + cond))) {
  163. return;
  164. }
  165. }
  166. if (config.isFlatDomain(DOMAIN_CONDITIONTREE)
  167. && config.getFlatDomain(DOMAIN_CONDITIONTREE).size() > 0) {
  168. conditionTree = ConditionTree.parseString(
  169. config.getFlatDomain(DOMAIN_CONDITIONTREE).get(0));
  170. if (conditionTree == null) {
  171. error("Unable to parse condition tree");
  172. return;
  173. }
  174. if (conditionTree.getMaximumArgument() >= conditions.size()) {
  175. error("Condition tree references condition "
  176. + conditionTree.getMaximumArgument() + " but there are"
  177. + " only " + conditions.size() + " conditions");
  178. return;
  179. }
  180. }
  181. if (config.isKeyDomain(DOMAIN_CONCURRENCY)
  182. && config.getKeyDomain(DOMAIN_CONCURRENCY).containsKey("group")) {
  183. setConcurrencyGroup(config.getKeyDomain(DOMAIN_CONCURRENCY).get("group"));
  184. }
  185. if (config.isKeyDomain(DOMAIN_MISC)
  186. && config.getKeyDomain(DOMAIN_MISC).containsKey("stopping")) {
  187. setStopping(Boolean.parseBoolean(config.getKeyDomain(DOMAIN_MISC).get("stopping")));
  188. }
  189. ActionManager.registerAction(this);
  190. checkMetaData();
  191. }
  192. /**
  193. * Checks to see if this action contains group meta-data, and adds it to
  194. * the group as appropriate.
  195. */
  196. private void checkMetaData() {
  197. if (config.isKeyDomain(DOMAIN_METADATA)) {
  198. final ActionGroup myGroup = ActionManager.getGroup(group);
  199. final Map<String, String> data = config.getKeyDomain(DOMAIN_METADATA);
  200. if (data.containsKey("description")) {
  201. myGroup.setDescription(data.get("description"));
  202. }
  203. if (data.containsKey("author")) {
  204. myGroup.setAuthor(data.get("author"));
  205. }
  206. if (data.containsKey("version")) {
  207. myGroup.setVersion(new Version(data.get("version")));
  208. }
  209. if (data.containsKey("component")) {
  210. try {
  211. myGroup.setComponent(Integer.parseInt(data.get("component")));
  212. } catch (NumberFormatException ex) {
  213. // Do nothing
  214. }
  215. }
  216. }
  217. for (int i = 0; config.isKeyDomain("setting " + i); i++) {
  218. final ActionGroup myGroup = ActionManager.getGroup(group);
  219. final Map<String, String> data = config.getKeyDomain("setting " + i);
  220. if (data.containsKey("type") && data.containsKey("setting")
  221. && data.containsKey("title") && data.containsKey("default")
  222. && data.containsKey("tooltip")) {
  223. ActionManager.registerDefault(data.get("setting"), data.get("default"));
  224. myGroup.getSettings().put(data.get("setting"), new PreferencesSetting(
  225. PreferencesType.valueOf(data.get("type")), "actions",
  226. data.get("setting"), data.get("title"), data.get("tooltip")));
  227. }
  228. }
  229. }
  230. /**
  231. * Loads a list of triggers with the specified names.
  232. *
  233. * @param newTriggers A list of trigger names
  234. * @return True if all triggers are valid and compatible, false otherwise.
  235. */
  236. private boolean loadTriggers(final List<String> newTriggers) {
  237. triggers = new ActionType[newTriggers.size()];
  238. for (int i = 0; i < triggers.length; i++) {
  239. triggers[i] = ActionManager.getActionType(newTriggers.get(i));
  240. if (triggers[i] == null) {
  241. error("Invalid trigger specified: " + newTriggers.get(i));
  242. return false;
  243. } else if (i != 0 && !triggers[i].getType().equals(triggers[0].getType())) {
  244. error("Triggers are not compatible");
  245. return false;
  246. }
  247. }
  248. return true;
  249. }
  250. /**
  251. * Called to save the action.
  252. */
  253. public void save() {
  254. if (!isModified()) {
  255. return;
  256. }
  257. final ConfigFile newConfig = new ConfigFile(location);
  258. final List<String> triggerNames = new ArrayList<String>();
  259. final List<String> responseLines = new ArrayList<String>();
  260. for (ActionType trigger : triggers) {
  261. if (trigger == null) {
  262. Logger.appError(ErrorLevel.LOW, "ActionType was null",
  263. new IllegalArgumentException("Triggers: "
  264. + Arrays.toString(triggers)));
  265. continue;
  266. }
  267. triggerNames.add(trigger.toString());
  268. }
  269. for (String line : response) {
  270. responseLines.add(line);
  271. }
  272. newConfig.addDomain(DOMAIN_TRIGGERS, triggerNames);
  273. newConfig.addDomain(DOMAIN_RESPONSE, responseLines);
  274. if (conditionTree != null) {
  275. newConfig.addDomain(DOMAIN_CONDITIONTREE, new ArrayList<String>());
  276. newConfig.getFlatDomain(DOMAIN_CONDITIONTREE).add(conditionTree.toString());
  277. }
  278. if (newFormat != null) {
  279. newConfig.addDomain(DOMAIN_FORMAT, new ArrayList<String>());
  280. newConfig.getFlatDomain(DOMAIN_FORMAT).add(newFormat);
  281. }
  282. if (concurrencyGroup != null) {
  283. newConfig.addDomain(DOMAIN_CONCURRENCY, new HashMap<String, String>());
  284. newConfig.getKeyDomain(DOMAIN_CONCURRENCY).put("group", concurrencyGroup);
  285. }
  286. if (stop) {
  287. newConfig.addDomain(DOMAIN_MISC, new HashMap<String, String>());
  288. newConfig.getKeyDomain(DOMAIN_MISC).put("stopping", "true");
  289. }
  290. int i = 0;
  291. for (ActionCondition condition : conditions) {
  292. final Map<String, String> data = new HashMap<String, String>();
  293. data.put("argument", String.valueOf(condition.getArg()));
  294. if (condition.getArg() == -1) {
  295. data.put("starget", condition.getStarget());
  296. } else {
  297. data.put("component", condition.getComponent().toString());
  298. }
  299. data.put("comparison", condition.getComparison().toString());
  300. data.put("target", condition.getTarget());
  301. newConfig.addDomain("condition " + i, data);
  302. i++;
  303. }
  304. if (config != null) {
  305. // Preserve any meta-data
  306. if (config.isKeyDomain(DOMAIN_METADATA)) {
  307. newConfig.addDomain(DOMAIN_METADATA, config.getKeyDomain(DOMAIN_METADATA));
  308. }
  309. for (i = 0; config.isKeyDomain("setting " + i); i++) {
  310. newConfig.addDomain("setting " + i, config.getKeyDomain("setting " + i));
  311. }
  312. }
  313. try {
  314. newConfig.write();
  315. resetModified();
  316. } catch (IOException ex) {
  317. Logger.userError(ErrorLevel.HIGH, "I/O error when saving action: "
  318. + group + "/" + name + ": " + ex.getMessage());
  319. }
  320. ActionManager.processEvent(CoreActionType.ACTION_UPDATED, null, this);
  321. }
  322. /**
  323. * Reads a condition from the specified configuration section.
  324. *
  325. * @param data The relevant section of the action configuration
  326. * @return True if the condition is valid, false otherwise
  327. */
  328. private boolean readCondition(final Map<String,String> data) {
  329. int arg = 0;
  330. ActionComponent component = null;
  331. ActionComparison comparison = null;
  332. String target = "";
  333. String starget = null;
  334. // ------ Read the argument
  335. try {
  336. arg = Integer.parseInt(data.get("argument"));
  337. } catch (NumberFormatException ex) {
  338. error("Invalid argument number specified: " + data.get("argument"));
  339. return false;
  340. }
  341. if (arg < -1 || arg >= triggers[0].getType().getArity()) {
  342. error("Invalid argument number specified: " + arg);
  343. return false;
  344. }
  345. // ------ Read the component or the source
  346. if (arg == -1) {
  347. starget = data.get("starget");
  348. if (starget == null) {
  349. error("No starget specified");
  350. return false;
  351. }
  352. } else {
  353. component = readComponent(data, arg);
  354. if (component == null) {
  355. return false;
  356. }
  357. }
  358. // ------ Read the comparison
  359. comparison = ActionManager.getActionComparison(data.get("comparison"));
  360. if (comparison == null) {
  361. error("Invalid comparison specified: " + data.get("comparison"));
  362. return false;
  363. }
  364. if ((arg != -1 && !comparison.appliesTo().equals(component.getType()))
  365. || (arg == -1 && !comparison.appliesTo().equals(String.class))) {
  366. error("Comparison cannot be applied to specified component: " + data.get("comparison"));
  367. return false;
  368. }
  369. // ------ Read the target
  370. target = data.get("target");
  371. if (target == null) {
  372. error("No target specified for condition");
  373. return false;
  374. }
  375. if (arg == -1) {
  376. conditions.add(new ActionCondition(starget, comparison, target));
  377. } else {
  378. conditions.add(new ActionCondition(arg, component, comparison, target));
  379. }
  380. return true;
  381. }
  382. /**
  383. * Reads a component from the specified data section for the specified argument.
  384. *
  385. * @param data The relevant section of the action configuration
  386. * @param arg The argument number that the component should apply to
  387. * @return The corresponding ActionComponent, or null if the specified
  388. * component is invalid.
  389. */
  390. private ActionComponent readComponent(final Map<String, String> data, final int arg) {
  391. final String componentName = data.get("component");
  392. ActionComponent component;
  393. if (componentName.indexOf('.') == -1) {
  394. component = ActionManager.getActionComponent(componentName);
  395. } else {
  396. try {
  397. component = new ActionComponentChain(triggers[0].getType().getArgTypes()[arg],
  398. componentName);
  399. } catch (IllegalArgumentException iae) {
  400. error(iae.getMessage());
  401. return null;
  402. }
  403. }
  404. if (component == null) {
  405. error("Unknown component: " + componentName);
  406. return null;
  407. }
  408. if (!component.appliesTo().equals(triggers[0].getType().getArgTypes()[arg])) {
  409. error("Component cannot be applied to specified arg in condition: " + componentName);
  410. return null;
  411. }
  412. return component;
  413. }
  414. /**
  415. * Raises a trivial error, informing the user of the problem.
  416. *
  417. * @param message The message to be raised
  418. */
  419. private void error(final String message) {
  420. Logger.userError(ErrorLevel.LOW, "Error when parsing action: "
  421. + group + "/" + name + ": " + message);
  422. }
  423. /** {@inheritDoc} */
  424. @Override
  425. public void setName(final String newName) {
  426. super.setName(newName);
  427. new File(location).delete();
  428. location = ActionManager.getDirectory() + group + File.separator + newName;
  429. save();
  430. }
  431. /** {@inheritDoc} */
  432. @Override
  433. public void setGroup(final String newGroup) {
  434. super.setGroup(newGroup);
  435. new File(location).delete();
  436. final String dir = ActionManager.getDirectory() + group + File.separator;
  437. location = dir + name;
  438. new File(dir).mkdirs();
  439. save();
  440. }
  441. /**
  442. * Deletes this action.
  443. */
  444. public void delete() {
  445. ActionManager.processEvent(CoreActionType.ACTION_DELETED, null, getGroup(), getName());
  446. new File(location).delete();
  447. }
  448. /** {@inheritDoc} */
  449. @Override
  450. public String toString() {
  451. final String parent = super.toString();
  452. return parent.substring(0, parent.length() - 1)
  453. + ",location=" + location + "]";
  454. }
  455. /** {@inheritDoc} */
  456. @Override
  457. public void configChanged(final String domain, final String key) {
  458. checkDisabled();
  459. }
  460. /**
  461. * Checks if this action is disabled or not.
  462. *
  463. * @since 0.6.3
  464. */
  465. protected void checkDisabled() {
  466. disabled = IdentityManager.getGlobalConfig().hasOptionBool("disable_action",
  467. (group + "/" + name).replace(' ', '.'))
  468. && IdentityManager.getGlobalConfig().getOptionBool("disable_action",
  469. (group + "/" + name).replace(' ', '.'));
  470. }
  471. /**
  472. * Determines whether this action is enabled or not.
  473. *
  474. * @since 0.6.4
  475. * @return True if the action is enabled, false otherwise
  476. */
  477. public boolean isEnabled() {
  478. return !disabled;
  479. }
  480. /**
  481. * Sets whether this action is enabled or not.
  482. *
  483. * @param enabled true to enable, false to disable
  484. */
  485. public void setEnabled(final boolean enabled) {
  486. if (enabled && IdentityManager.getGlobalConfig().hasOptionBool(
  487. "disable_action", (group + "/" + name).replace(' ', '.'))) {
  488. IdentityManager.getConfigIdentity().unsetOption("disable_action",
  489. (group + "/" + name).replace(' ', '.'));
  490. } else {
  491. IdentityManager.getConfigIdentity().setOption("disable_action",
  492. (group + "/" + name).replace(' ', '.'), true);
  493. }
  494. }
  495. /** {@inheritDoc} */
  496. @Override
  497. public boolean trigger(final StringBuffer format, final Object... arguments) {
  498. if (!disabled) {
  499. return super.trigger(format, arguments);
  500. }
  501. return false;
  502. }
  503. }