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.

Action.java 21KB

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