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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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.interfaces.actions.ActionComparison;
  24. import com.dmdirc.interfaces.actions.ActionComponent;
  25. import com.dmdirc.interfaces.actions.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.io.ConfigFile;
  34. import com.dmdirc.util.io.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.getIdentityManager().getGlobalConfiguration().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.getIdentityManager().getGlobalConfiguration().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. IdentityManager.getIdentityManager().getGlobalConfiguration(),
  232. IdentityManager.getConfigIdentity()));
  233. }
  234. }
  235. }
  236. /**
  237. * Loads a list of triggers with the specified names.
  238. *
  239. * @param newTriggers A list of trigger names
  240. * @return True if all triggers are valid and compatible, false otherwise.
  241. */
  242. private boolean loadTriggers(final List<String> newTriggers) {
  243. triggers = new ActionType[newTriggers.size()];
  244. for (int i = 0; i < triggers.length; i++) {
  245. triggers[i] = ActionManager.getActionManager().getType(newTriggers.get(i));
  246. if (triggers[i] == null) {
  247. error(ActionErrorType.TRIGGERS, "Invalid trigger specified: " + newTriggers.get(i));
  248. return false;
  249. } else if (i != 0 && !triggers[i].getType().equals(triggers[0].getType())) {
  250. error(ActionErrorType.TRIGGERS, "Triggers are not compatible");
  251. return false;
  252. }
  253. }
  254. return true;
  255. }
  256. /**
  257. * Called to save the action.
  258. */
  259. public void save() {
  260. if (!isModified()) {
  261. return;
  262. }
  263. final ConfigFile newConfig = new ConfigFile(location);
  264. final List<String> triggerNames = new ArrayList<String>();
  265. final List<String> responseLines = new ArrayList<String>();
  266. responseLines.addAll(Arrays.asList(response));
  267. for (ActionType trigger : triggers) {
  268. if (trigger == null) {
  269. Logger.appError(ErrorLevel.LOW, "ActionType was null",
  270. new IllegalArgumentException("Triggers: "
  271. + Arrays.toString(triggers)));
  272. continue;
  273. }
  274. triggerNames.add(trigger.toString());
  275. }
  276. newConfig.addDomain(DOMAIN_TRIGGERS, triggerNames);
  277. newConfig.addDomain(DOMAIN_RESPONSE, responseLines);
  278. if (conditionTree != null) {
  279. newConfig.addDomain(DOMAIN_CONDITIONTREE, new ArrayList<String>());
  280. newConfig.getFlatDomain(DOMAIN_CONDITIONTREE).add(conditionTree.toString());
  281. }
  282. if (newFormat != null) {
  283. newConfig.addDomain(DOMAIN_FORMAT, new ArrayList<String>());
  284. newConfig.getFlatDomain(DOMAIN_FORMAT).add(newFormat);
  285. }
  286. if (concurrencyGroup != null) {
  287. newConfig.addDomain(DOMAIN_CONCURRENCY, new HashMap<String, String>());
  288. newConfig.getKeyDomain(DOMAIN_CONCURRENCY).put("group", concurrencyGroup);
  289. }
  290. if (stop) {
  291. newConfig.addDomain(DOMAIN_MISC, new HashMap<String, String>());
  292. newConfig.getKeyDomain(DOMAIN_MISC).put("stopping", "true");
  293. }
  294. int i = 0;
  295. for (ActionCondition condition : conditions) {
  296. final Map<String, String> data = new HashMap<String, String>();
  297. data.put("argument", String.valueOf(condition.getArg()));
  298. if (condition.getArg() == -1) {
  299. data.put("starget", condition.getStarget());
  300. } else {
  301. data.put("component", condition.getComponent().toString());
  302. }
  303. data.put("comparison", condition.getComparison().toString());
  304. data.put("target", condition.getTarget());
  305. newConfig.addDomain("condition " + i, data);
  306. i++;
  307. }
  308. if (config != null) {
  309. // Preserve any meta-data
  310. if (config.isKeyDomain(DOMAIN_METADATA)) {
  311. newConfig.addDomain(DOMAIN_METADATA, config.getKeyDomain(DOMAIN_METADATA));
  312. }
  313. for (i = 0; config.isKeyDomain("setting " + i); i++) {
  314. newConfig.addDomain("setting " + i, config.getKeyDomain("setting " + i));
  315. }
  316. }
  317. try {
  318. newConfig.write();
  319. resetModified();
  320. } catch (IOException ex) {
  321. Logger.userError(ErrorLevel.HIGH, "I/O error when saving action: "
  322. + group + "/" + name + ": " + ex.getMessage());
  323. }
  324. ActionManager.getActionManager().triggerEvent(
  325. CoreActionType.ACTION_UPDATED, null, this);
  326. }
  327. /**
  328. * Reads a condition from the specified configuration section.
  329. *
  330. * @param data The relevant section of the action configuration
  331. * @return True if the condition is valid, false otherwise
  332. */
  333. private boolean readCondition(final Map<String, String> data) {
  334. int arg = 0;
  335. ActionComponent component = null;
  336. ActionComparison comparison = null;
  337. String target = "";
  338. String starget = null;
  339. // ------ Read the argument
  340. try {
  341. arg = Integer.parseInt(data.get("argument"));
  342. } catch (NumberFormatException ex) {
  343. error(ActionErrorType.CONDITIONS,
  344. "Invalid argument number specified: " + data.get("argument"));
  345. return false;
  346. }
  347. if (arg < -1 || arg >= triggers[0].getType().getArity()) {
  348. error(ActionErrorType.CONDITIONS, "Invalid argument number specified: " + arg);
  349. return false;
  350. }
  351. // ------ Read the component or the source
  352. if (arg == -1) {
  353. starget = data.get("starget");
  354. if (starget == null) {
  355. error(ActionErrorType.CONDITIONS, "No starget specified");
  356. return false;
  357. }
  358. } else {
  359. component = readComponent(data, arg);
  360. if (component == null) {
  361. return false;
  362. }
  363. }
  364. // ------ Read the comparison
  365. comparison = ActionManager.getActionManager().getComparison(data.get("comparison"));
  366. if (comparison == null) {
  367. error(ActionErrorType.CONDITIONS, "Invalid comparison specified: "
  368. + data.get("comparison"));
  369. return false;
  370. }
  371. if ((arg != -1 && !comparison.appliesTo().equals(component.getType()))
  372. || (arg == -1 && !comparison.appliesTo().equals(String.class))) {
  373. error(ActionErrorType.CONDITIONS,
  374. "Comparison cannot be applied to specified component: " + data.get("comparison"));
  375. return false;
  376. }
  377. // ------ Read the target
  378. target = data.get("target");
  379. if (target == null) {
  380. error(ActionErrorType.CONDITIONS, "No target specified for condition");
  381. return false;
  382. }
  383. if (arg == -1) {
  384. conditions.add(new ActionCondition(starget, comparison, target));
  385. } else {
  386. conditions.add(new ActionCondition(arg, component, comparison, target));
  387. }
  388. return true;
  389. }
  390. /**
  391. * Reads a component from the specified data section for the specified argument.
  392. *
  393. * @param data The relevant section of the action configuration
  394. * @param arg The argument number that the component should apply to
  395. * @return The corresponding ActionComponent, or null if the specified
  396. * component is invalid.
  397. */
  398. private ActionComponent readComponent(final Map<String, String> data, final int arg) {
  399. final String componentName = data.get("component");
  400. ActionComponent component;
  401. if (componentName.indexOf('.') == -1) {
  402. component = ActionManager.getActionManager().getComponent(componentName);
  403. } else {
  404. try {
  405. component = new ActionComponentChain(triggers[0].getType().getArgTypes()[arg],
  406. componentName);
  407. } catch (IllegalArgumentException iae) {
  408. error(ActionErrorType.CONDITIONS, iae.getMessage());
  409. return null;
  410. }
  411. }
  412. if (component == null) {
  413. error(ActionErrorType.CONDITIONS, "Unknown component: " + componentName);
  414. return null;
  415. }
  416. if (!component.appliesTo().equals(triggers[0].getType().getArgTypes()[arg])) {
  417. error(ActionErrorType.CONDITIONS,
  418. "Component cannot be applied to specified arg in condition: " + componentName);
  419. return null;
  420. }
  421. return component;
  422. }
  423. /**
  424. * Raises a trivial error, informing the user of the problem.
  425. *
  426. * @param message The message to be raised
  427. */
  428. private void error(final ActionErrorType type, final String message) {
  429. this.error = message;
  430. this.errorType = type;
  431. this.status = ActionStatus.FAILED;
  432. Logger.userError(ErrorLevel.LOW, "Error when parsing action: "
  433. + group + "/" + name + ": " + message);
  434. }
  435. /** {@inheritDoc} */
  436. @Override
  437. public void setName(final String newName) {
  438. super.setName(newName);
  439. new File(location).delete();
  440. location = ActionManager.getDirectory() + group + File.separator + newName;
  441. save();
  442. }
  443. /** {@inheritDoc} */
  444. @Override
  445. public void setGroup(final String newGroup) {
  446. super.setGroup(newGroup);
  447. new File(location).delete();
  448. final String dir = ActionManager.getDirectory() + group + File.separator;
  449. location = dir + name;
  450. new File(dir).mkdirs();
  451. save();
  452. }
  453. /**
  454. * Deletes this action.
  455. */
  456. public void delete() {
  457. ActionManager.getActionManager().triggerEvent(
  458. CoreActionType.ACTION_DELETED, null, getGroup(), getName());
  459. new File(location).delete();
  460. }
  461. /** {@inheritDoc} */
  462. @Override
  463. public String toString() {
  464. final String parent = super.toString();
  465. return parent.substring(0, parent.length() - 1)
  466. + ",location=" + location + "]";
  467. }
  468. /** {@inheritDoc} */
  469. @Override
  470. public void configChanged(final String domain, final String key) {
  471. checkDisabled();
  472. }
  473. /**
  474. * Checks if this action is disabled or not.
  475. *
  476. * @since 0.6.3
  477. */
  478. protected void checkDisabled() {
  479. final String key = (group + "/" + name).replace(' ', '.');
  480. final boolean disabled = IdentityManager.getIdentityManager()
  481. .getGlobalConfiguration().hasOptionBool("disable_action", key)
  482. && IdentityManager.getIdentityManager().getGlobalConfiguration()
  483. .getOptionBool("disable_action", key);
  484. if (disabled && status == ActionStatus.ACTIVE) {
  485. status = ActionStatus.DISABLED;
  486. } else if (!disabled && status == ActionStatus.DISABLED) {
  487. status = ActionStatus.ACTIVE;
  488. }
  489. }
  490. /**
  491. * Sets whether this action is enabled or not.
  492. *
  493. * @param enabled true to enable, false to disable
  494. */
  495. public void setEnabled(final boolean enabled) {
  496. if (enabled) {
  497. IdentityManager.getConfigIdentity().unsetOption("disable_action",
  498. (group + "/" + name).replace(' ', '.'));
  499. } else {
  500. IdentityManager.getConfigIdentity().setOption("disable_action",
  501. (group + "/" + name).replace(' ', '.'), true);
  502. }
  503. }
  504. }