Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ActionManager.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. /*
  2. * Copyright (c) 2006-2015 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.DMDircMBassador;
  24. import com.dmdirc.Precondition;
  25. import com.dmdirc.ui.messages.WhoisNumericFormatter;
  26. import com.dmdirc.commandline.CommandLineOptionsModule.Directory;
  27. import com.dmdirc.commandline.CommandLineOptionsModule.DirectoryType;
  28. import com.dmdirc.config.ConfigBinding;
  29. import com.dmdirc.events.AppErrorEvent;
  30. import com.dmdirc.events.ClientClosedEvent;
  31. import com.dmdirc.events.DMDircEvent;
  32. import com.dmdirc.events.DisplayableEvent;
  33. import com.dmdirc.events.UserErrorEvent;
  34. import com.dmdirc.interfaces.ActionController;
  35. import com.dmdirc.interfaces.actions.ActionComparison;
  36. import com.dmdirc.interfaces.actions.ActionComponent;
  37. import com.dmdirc.interfaces.actions.ActionType;
  38. import com.dmdirc.interfaces.config.IdentityController;
  39. import com.dmdirc.logger.ErrorLevel;
  40. import com.dmdirc.updater.components.ActionGroupComponent;
  41. import com.dmdirc.updater.manager.UpdateManager;
  42. import com.dmdirc.util.collections.MapList;
  43. import com.dmdirc.util.io.FileUtils;
  44. import java.io.File;
  45. import java.io.IOException;
  46. import java.lang.reflect.Method;
  47. import java.nio.file.Files;
  48. import java.nio.file.Path;
  49. import java.nio.file.Paths;
  50. import java.util.ArrayList;
  51. import java.util.Collection;
  52. import java.util.Collections;
  53. import java.util.HashMap;
  54. import java.util.List;
  55. import java.util.Map;
  56. import java.util.stream.Collectors;
  57. import javax.inject.Inject;
  58. import javax.inject.Provider;
  59. import javax.inject.Singleton;
  60. import org.slf4j.Logger;
  61. import org.slf4j.LoggerFactory;
  62. import net.engio.mbassy.listener.Handler;
  63. import static com.google.common.base.Preconditions.checkArgument;
  64. import static com.google.common.base.Preconditions.checkNotNull;
  65. /**
  66. * Manages all actions for the client.
  67. */
  68. @Singleton
  69. public class ActionManager implements ActionController {
  70. private static final Logger LOG = LoggerFactory.getLogger(ActionManager.class);
  71. /** The identity manager to load configuration from. */
  72. private final IdentityController identityManager;
  73. /** The factory to use to create actions. */
  74. private final ActionFactory factory;
  75. /** Provider of an update manager. */
  76. private final Provider<UpdateManager> updateManagerProvider;
  77. /** A list of registered action types. */
  78. private final Collection<ActionType> types = new ArrayList<>();
  79. /** A list of registered action components. */
  80. private final Collection<ActionComponent> components = new ArrayList<>();
  81. /** A list of registered action comparisons. */
  82. private final Collection<ActionComparison> comparisons = new ArrayList<>();
  83. /** A map linking types and a list of actions that're registered for them. */
  84. private final MapList<ActionType, Action> actions = new MapList<>();
  85. /** A map linking groups and a list of actions that're in them. */
  86. private final Map<String, ActionGroup> groups = new HashMap<>();
  87. /** A map of objects to synchronise on for concurrency groups. */
  88. private final Map<String, Object> locks = new HashMap<>();
  89. /** A map of the action type groups to the action types within. */
  90. private final MapList<String, ActionType> typeGroups = new MapList<>();
  91. /** The global event bus to monitor. */
  92. private final DMDircMBassador eventBus;
  93. /** The directory to load and save actions in. */
  94. private final String directory;
  95. /** Indicates whether or not user actions should be killed (not processed). */
  96. @ConfigBinding(domain = "actions", key = "killswitch")
  97. private boolean killSwitch;
  98. /**
  99. * Creates a new instance of ActionManager.
  100. *
  101. * @param identityManager The IdentityManager to load configuration from.
  102. * @param factory The factory to use to create new actions.
  103. * @param updateManagerProvider Provider of an update manager, to register components.
  104. * @param eventBus The global event bus to monitor.
  105. * @param directory The directory to load and save actions in.
  106. */
  107. @Inject
  108. public ActionManager(
  109. final IdentityController identityManager,
  110. final ActionFactory factory,
  111. final Provider<UpdateManager> updateManagerProvider,
  112. final DMDircMBassador eventBus,
  113. @Directory(DirectoryType.ACTIONS) final String directory) {
  114. this.identityManager = identityManager;
  115. this.factory = factory;
  116. this.updateManagerProvider = updateManagerProvider;
  117. this.eventBus = eventBus;
  118. this.directory = directory;
  119. }
  120. /**
  121. * Initialiases the actions manager.
  122. *
  123. * @param colourComparisons The colour comparisons to use.
  124. */
  125. // TODO: Refactor to take a list of comparisons/sources.
  126. public void initialise(final ColourActionComparison colourComparisons) {
  127. LOG.info("Initialising the actions manager");
  128. identityManager.getGlobalConfiguration().getBinder().bind(this, ActionManager.class);
  129. registerTypes(CoreActionType.values());
  130. registerComparisons(CoreActionComparison.values());
  131. registerComparisons(colourComparisons.getComparisons());
  132. registerComponents(CoreActionComponent.values());
  133. new WhoisNumericFormatter(identityManager.getAddonSettings(), eventBus).register();
  134. eventBus.subscribe(this);
  135. }
  136. @Override
  137. public void saveAllActions() {
  138. for (ActionGroup group : groups.values()) {
  139. for (Action action : group) {
  140. action.save();
  141. }
  142. }
  143. }
  144. /**
  145. * Saves all actions when the client is being closed.
  146. *
  147. * @param event The event that was raised.
  148. */
  149. @Handler
  150. public void handleClientClosed(final ClientClosedEvent event) {
  151. LOG.debug("Client closed - saving all actions");
  152. saveAllActions();
  153. }
  154. @Override
  155. public void registerSetting(final String name, final String value) {
  156. LOG.debug("Registering new action setting: {} = {}", name, value);
  157. identityManager.getAddonSettings().setOption("actions", name, value);
  158. }
  159. @Override
  160. public void addGroup(final ActionGroup group) {
  161. groups.put(group.getName(), group);
  162. }
  163. @Override
  164. public void registerTypes(final ActionType[] newTypes) {
  165. for (ActionType type : newTypes) {
  166. checkNotNull(type);
  167. if (!types.contains(type)) {
  168. LOG.debug("Registering action type: {}", type);
  169. types.add(type);
  170. typeGroups.add(type.getType().getGroup(), type);
  171. }
  172. }
  173. }
  174. @Override
  175. public void registerComponents(final ActionComponent[] comps) {
  176. for (ActionComponent comp : comps) {
  177. checkNotNull(comp);
  178. LOG.debug("Registering action component: {}", comp);
  179. components.add(comp);
  180. }
  181. }
  182. @Override
  183. public void registerComparisons(final ActionComparison[] comps) {
  184. for (ActionComparison comp : comps) {
  185. checkNotNull(comp);
  186. LOG.debug("Registering action comparison: {}", comp);
  187. comparisons.add(comp);
  188. }
  189. }
  190. @Override
  191. public Map<String, ActionGroup> getGroupsMap() {
  192. return Collections.unmodifiableMap(groups);
  193. }
  194. @Override
  195. public MapList<String, ActionType> getGroupedTypes() {
  196. return new MapList<>(typeGroups);
  197. }
  198. @Override
  199. public void loadUserActions() {
  200. actions.clear();
  201. groups.values().forEach(ActionGroup::clear);
  202. final File dir = new File(directory);
  203. if (!dir.exists()) {
  204. try {
  205. dir.mkdirs();
  206. dir.createNewFile();
  207. } catch (IOException ex) {
  208. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.HIGH, null,
  209. "I/O error when creating actions directory: " + ex.getMessage(), ""));
  210. }
  211. }
  212. if (dir.listFiles() == null) {
  213. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.MEDIUM, null,
  214. "Unable to load user action files", ""));
  215. } else {
  216. for (File file : dir.listFiles()) {
  217. if (file.isDirectory()) {
  218. loadActions(file);
  219. }
  220. }
  221. }
  222. registerComponents(updateManagerProvider.get());
  223. }
  224. /**
  225. * Creates new ActionGroupComponents for each action group.
  226. *
  227. * @param updateManager The update manager to register components with
  228. */
  229. private void registerComponents(final UpdateManager updateManager) {
  230. groups.values().stream()
  231. .filter(group -> group.getComponent() != -1 && group.getVersion() != null)
  232. .forEach(group -> updateManager.addComponent(
  233. new ActionGroupComponent(this, group)));
  234. }
  235. /**
  236. * Loads action files from a specified group directory.
  237. *
  238. * @param dir The directory to scan.
  239. */
  240. @Precondition("The specified File is not null and represents a directory")
  241. private void loadActions(final File dir) {
  242. checkNotNull(dir);
  243. checkArgument(dir.isDirectory());
  244. LOG.debug("Loading actions from directory: {}", dir.getAbsolutePath());
  245. if (!groups.containsKey(dir.getName())) {
  246. groups.put(dir.getName(), new ActionGroup(this, dir.getName()));
  247. }
  248. for (File file : dir.listFiles()) {
  249. factory.getAction(dir.getName(), file.getName());
  250. }
  251. }
  252. @Override
  253. public void addAction(final Action action) {
  254. checkNotNull(action);
  255. LOG.debug("Registering action: {}/{} (status: {})", action.getGroup(), action.getName(),
  256. action.getStatus());
  257. if (action.getStatus() != ActionStatus.FAILED) {
  258. for (ActionType trigger : action.getTriggers()) {
  259. LOG.trace("Action has trigger {}", trigger);
  260. actions.add(trigger, action);
  261. }
  262. }
  263. getOrCreateGroup(action.getGroup()).add(action);
  264. }
  265. @Override
  266. public ActionGroup getOrCreateGroup(final String name) {
  267. if (!groups.containsKey(name)) {
  268. groups.put(name, new ActionGroup(this, name));
  269. }
  270. return groups.get(name);
  271. }
  272. @Override
  273. public void removeAction(final Action action) {
  274. checkNotNull(action);
  275. actions.removeFromAll(action);
  276. getOrCreateGroup(action.getGroup()).remove(action);
  277. }
  278. @Override
  279. public void reregisterAction(final Action action) {
  280. removeAction(action);
  281. addAction(action);
  282. }
  283. @Override
  284. public boolean triggerEvent(final ActionType type,
  285. final StringBuffer format, final Object... arguments) {
  286. checkNotNull(type);
  287. checkNotNull(type.getType());
  288. checkArgument(type.getType().getArity() == arguments.length);
  289. LOG.trace("Calling listeners for event of type {}", type);
  290. return killSwitch || !triggerActions(type, format, arguments);
  291. }
  292. /**
  293. * Triggers actions that respond to the specified type.
  294. *
  295. * @param type The type of the event to process
  296. * @param format The format of the message that's going to be displayed for the event.
  297. * Actions may change this format.
  298. * @param arguments The arguments for the event
  299. *
  300. * @return True if the event should be skipped, or false if it can continue
  301. */
  302. @Precondition("The specified ActionType is not null")
  303. private boolean triggerActions(final ActionType type,
  304. final StringBuffer format, final Object... arguments) {
  305. checkNotNull(type);
  306. LOG.trace("Executing actions for event of type {}", type);
  307. boolean res = false;
  308. if (actions.containsKey(type)) {
  309. for (Action action : new ArrayList<>(actions.get(type))) {
  310. try {
  311. if (action.getConcurrencyGroup() == null) {
  312. res |= action.trigger(format, arguments);
  313. } else {
  314. synchronized (locks) {
  315. if (!locks.containsKey(action.getConcurrencyGroup())) {
  316. locks.put(action.getConcurrencyGroup(), new Object());
  317. }
  318. }
  319. synchronized (locks.get(action.getConcurrencyGroup())) {
  320. res |= action.trigger(format, arguments);
  321. }
  322. }
  323. } catch (LinkageError | Exception e) {
  324. eventBus.publishAsync(new AppErrorEvent(ErrorLevel.MEDIUM, e,
  325. "Error processing action: " + e.getMessage(), ""));
  326. }
  327. }
  328. }
  329. return res;
  330. }
  331. /**
  332. * Processes an event from the event bus.
  333. *
  334. * @param event The event that was raised.
  335. */
  336. @Handler
  337. public void processEvent(final DMDircEvent event) {
  338. final ActionType type = getType(getLegacyActionTypeName(event));
  339. if (type == null) {
  340. LOG.warn("Unable to locate legacy type for event {}", event.getClass().getName());
  341. return;
  342. }
  343. final Class<?>[] argTypes = type.getType().getArgTypes();
  344. final Object[] arguments = getLegacyArguments(event, argTypes);
  345. if (event instanceof DisplayableEvent) {
  346. final DisplayableEvent displayable = (DisplayableEvent) event;
  347. final StringBuffer buffer = new StringBuffer(displayable.getDisplayFormat());
  348. triggerEvent(type, buffer, arguments);
  349. displayable.setDisplayFormat(buffer.toString());
  350. } else {
  351. triggerEvent(type, null, arguments);
  352. }
  353. }
  354. /**
  355. * Gets the name of the legacy {@link ActionType} to which the given event corresponds.
  356. *
  357. * @param event The event to obtain the name of.
  358. *
  359. * @return The legacy action type name.
  360. */
  361. private static String getLegacyActionTypeName(final DMDircEvent event) {
  362. return event.getClass().getSimpleName()
  363. .replaceAll("Event$", "")
  364. .replaceAll("(.)([A-Z])", "$1_$2")
  365. .toUpperCase();
  366. }
  367. /**
  368. * Attempts to obtain a legacy arguments array from the given event. Arguments will be matched
  369. * based on their expected classes. Where an event provides multiple getters of the same type,
  370. * the one closest in index to the argument index will be used.
  371. *
  372. * @param event The event to get legacy arguments for.
  373. * @param argTypes The type of arguments expected for the action type.
  374. *
  375. * @return An array of objects containing the legacy arguments.
  376. */
  377. private static Object[] getLegacyArguments(final DMDircEvent event, final Class<?>[] argTypes) {
  378. final Object[] arguments = new Object[argTypes.length];
  379. final Method[] methods = event.getClass().getMethods();
  380. for (int i = 0; i < argTypes.length; i++) {
  381. final Class<?> target = argTypes[i];
  382. Method best = null;
  383. int bestDistance = Integer.MAX_VALUE;
  384. for (int j = 0; j < methods.length; j++) {
  385. final Method method = methods[j];
  386. if (method.getParameterTypes().length == 0
  387. && method.getName().startsWith("get")
  388. && !"getDisplayFormat".equals(method.getName())
  389. && method.getReturnType().equals(target)
  390. && Math.abs(j - i) < bestDistance) {
  391. bestDistance = Math.abs(j - i);
  392. best = method;
  393. }
  394. }
  395. if (best == null) {
  396. LOG.error("Unable to find method on event {} to satisfy argument #{} of class {}",
  397. event.getClass().getName(), i, target.getName());
  398. arguments[i] = null;
  399. } else {
  400. try {
  401. arguments[i] = best.invoke(event);
  402. } catch (ReflectiveOperationException ex) {
  403. LOG.error("Unable to invoke method {} on {} to get action argument",
  404. best.getName(), event.getClass().getName(), ex);
  405. }
  406. }
  407. }
  408. return arguments;
  409. }
  410. @Override
  411. public ActionGroup createGroup(final String group) {
  412. checkNotNull(group);
  413. checkArgument(!group.isEmpty());
  414. checkArgument(!groups.containsKey(group));
  415. final File file = new File(directory + group);
  416. if (file.isDirectory() || file.mkdir()) {
  417. final ActionGroup actionGroup = new ActionGroup(this, group);
  418. groups.put(group, actionGroup);
  419. return actionGroup;
  420. } else {
  421. throw new IllegalArgumentException("Unable to create action group directory"
  422. + "\n\nDir: " + directory + group);
  423. }
  424. }
  425. @Override
  426. public void deleteGroup(final String group) {
  427. checkNotNull(group);
  428. checkArgument(!group.isEmpty());
  429. checkArgument(groups.containsKey(group));
  430. groups.get(group).getActions().forEach(this::removeAction);
  431. final File dir = new File(directory + group);
  432. if (dir.isDirectory()) {
  433. for (File file : dir.listFiles()) {
  434. if (!file.delete()) {
  435. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.MEDIUM, null,
  436. "Unable to remove file: " + file.getAbsolutePath(), ""));
  437. return;
  438. }
  439. }
  440. }
  441. if (!dir.delete()) {
  442. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.MEDIUM, null,
  443. "Unable to remove directory: " + dir.getAbsolutePath(), ""));
  444. return;
  445. }
  446. groups.remove(group);
  447. }
  448. @Override
  449. public void changeGroupName(final String oldName, final String newName) {
  450. checkNotNull(oldName);
  451. checkArgument(!oldName.isEmpty());
  452. checkNotNull(newName);
  453. checkArgument(!newName.isEmpty());
  454. checkArgument(groups.containsKey(oldName));
  455. checkArgument(!groups.containsKey(newName));
  456. checkArgument(!newName.equals(oldName));
  457. createGroup(newName);
  458. for (Action action : groups.get(oldName).getActions()) {
  459. action.setGroup(newName);
  460. getOrCreateGroup(oldName).remove(action);
  461. getOrCreateGroup(newName).add(action);
  462. }
  463. deleteGroup(oldName);
  464. }
  465. @Override
  466. public ActionType getType(final String type) {
  467. if (type == null || type.isEmpty()) {
  468. return null;
  469. }
  470. for (ActionType target : types) {
  471. if (target.name().equals(type)) {
  472. return target;
  473. }
  474. }
  475. return null;
  476. }
  477. @Override
  478. public List<ActionType> findCompatibleTypes(final ActionType type) {
  479. checkNotNull(type);
  480. final List<ActionType> res = types.stream()
  481. .filter(target -> !target.equals(type) && target.getType().equals(type.getType()))
  482. .collect(Collectors.toList());
  483. return res;
  484. }
  485. @Override
  486. public List<ActionComponent> findCompatibleComponents(final Class<?> target) {
  487. checkNotNull(target);
  488. final List<ActionComponent> res =
  489. components.stream().filter(subject -> subject.appliesTo().equals(target))
  490. .collect(Collectors.toList());
  491. return res;
  492. }
  493. @Override
  494. public List<ActionComparison> findCompatibleComparisons(final Class<?> target) {
  495. checkNotNull(target);
  496. final List<ActionComparison> res =
  497. comparisons.stream().filter(subject -> subject.appliesTo().equals(target))
  498. .collect(Collectors.toList());
  499. return res;
  500. }
  501. @Override
  502. public ActionComponent getComponent(final String type) {
  503. checkNotNull(type);
  504. checkArgument(!type.isEmpty());
  505. for (ActionComponent target : components) {
  506. if (target.name().equals(type)) {
  507. return target;
  508. }
  509. }
  510. return null;
  511. }
  512. @Override
  513. public ActionComparison getComparison(final String type) {
  514. checkNotNull(type);
  515. checkArgument(!type.isEmpty());
  516. for (ActionComparison target : comparisons) {
  517. if (target.name().equals(type)) {
  518. return target;
  519. }
  520. }
  521. return null;
  522. }
  523. /**
  524. * Installs an action pack located at the specified path.
  525. *
  526. * @param path The full path of the action pack .zip.
  527. *
  528. * @throws IOException If the zip cannot be extracted
  529. */
  530. public void installActionPack(final Path path) throws IOException {
  531. FileUtils.copyRecursively(path, Paths.get(directory));
  532. loadUserActions();
  533. Files.delete(path);
  534. }
  535. }