Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /*
  2. * Copyright (c) 2006-2013 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.addons.scriptplugin;
  23. import com.dmdirc.FrameContainer;
  24. import com.dmdirc.commandparser.BaseCommandInfo;
  25. import com.dmdirc.commandparser.CommandArguments;
  26. import com.dmdirc.commandparser.CommandInfo;
  27. import com.dmdirc.commandparser.CommandType;
  28. import com.dmdirc.commandparser.commands.Command;
  29. import com.dmdirc.commandparser.commands.IntelligentCommand;
  30. import com.dmdirc.commandparser.commands.context.CommandContext;
  31. import com.dmdirc.config.IdentityManager;
  32. import com.dmdirc.ui.input.AdditionalTabTargets;
  33. import java.io.File;
  34. import java.io.FileWriter;
  35. import java.io.IOException;
  36. import java.lang.reflect.Method;
  37. import java.util.Arrays;
  38. import java.util.LinkedList;
  39. import java.util.List;
  40. import java.util.Map;
  41. /**
  42. * The Script Command allows controlling of the script plugin.
  43. */
  44. public final class ScriptCommand extends Command implements IntelligentCommand {
  45. /** A command info object for this command. */
  46. public static final CommandInfo INFO = new BaseCommandInfo("script",
  47. "script - Allows controlling the script plugin",
  48. CommandType.TYPE_GLOBAL);
  49. /** My Plugin. */
  50. final ScriptPlugin myPlugin;
  51. /**
  52. * Creates a new instance of ScriptCommand.
  53. *
  54. * @param plugin Parent plugin
  55. */
  56. public ScriptCommand(final ScriptPlugin plugin) {
  57. super();
  58. myPlugin = plugin;
  59. }
  60. /** {@inheritDoc} */
  61. @Override
  62. public void execute(final FrameContainer origin,
  63. final CommandArguments args, final CommandContext context) {
  64. final String[] sargs = args.getArguments();
  65. if (sargs.length > 0 && (sargs[0].equalsIgnoreCase("rehash") || sargs[0].equalsIgnoreCase("reload"))) {
  66. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "Reloading scripts");
  67. myPlugin.rehash();
  68. } else if (sargs.length > 0 && sargs[0].equalsIgnoreCase("load")) {
  69. if (sargs.length > 1) {
  70. final String filename = args.getArgumentsAsString(1);
  71. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "Loading: "+filename+" ["+myPlugin.loadScript(myPlugin.getScriptDir()+filename)+"]");
  72. } else {
  73. sendLine(origin, args.isSilent(), FORMAT_ERROR, "You must specify a script to load");
  74. }
  75. } else if (sargs.length > 0 && sargs[0].equalsIgnoreCase("unload")) {
  76. if (sargs.length > 1) {
  77. final String filename = args.getArgumentsAsString(1);
  78. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "Unloading: "+filename+" ["+myPlugin.loadScript(myPlugin.getScriptDir()+filename)+"]");
  79. } else {
  80. sendLine(origin, args.isSilent(), FORMAT_ERROR, "You must specify a script to unload");
  81. }
  82. } else if (sargs.length > 0 && sargs[0].equalsIgnoreCase("eval")) {
  83. if (sargs.length > 1) {
  84. final String script = args.getArgumentsAsString(1);
  85. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "Evaluating: "+script);
  86. try {
  87. ScriptEngineWrapper wrapper;
  88. if (IdentityManager.getIdentityManager().getGlobalConfiguration().hasOptionString(myPlugin.getDomain(), "eval.baseFile")) {
  89. final String baseFile = myPlugin.getScriptDir()+'/'+IdentityManager.getIdentityManager().getGlobalConfiguration().getOption(myPlugin.getDomain(), "eval.baseFile");
  90. if (new File(baseFile).exists()) {
  91. wrapper = new ScriptEngineWrapper(myPlugin, baseFile);
  92. } else {
  93. wrapper = new ScriptEngineWrapper(myPlugin, null);
  94. }
  95. } else {
  96. wrapper = new ScriptEngineWrapper(myPlugin, null);
  97. }
  98. wrapper.getScriptEngine().put("cmd_origin", origin);
  99. wrapper.getScriptEngine().put("cmd_isSilent", args.isSilent());
  100. wrapper.getScriptEngine().put("cmd_args", sargs);
  101. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "Result: "+wrapper.getScriptEngine().eval(script));
  102. } catch (Exception e) {
  103. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "Exception: "+e+" -> "+e.getMessage());
  104. if (IdentityManager.getIdentityManager().getGlobalConfiguration().getOptionBool(myPlugin.getDomain(), "eval.showStackTrace")) {
  105. try {
  106. final Class<?> logger = Class.forName("com.dmdirc.logger.Logger");
  107. if (logger != null) {
  108. final Method exceptionToStringArray = logger.getDeclaredMethod("exceptionToStringArray", new Class[]{Throwable.class});
  109. exceptionToStringArray.setAccessible(true);
  110. final String[] stacktrace = (String[]) exceptionToStringArray.invoke(null, e);
  111. for (String line : stacktrace) {
  112. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "Stack trace: "+line);
  113. }
  114. }
  115. } catch (Exception ex) {
  116. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "Stack trace: Exception showing stack trace: "+ex+" -> "+ex.getMessage());
  117. }
  118. }
  119. }
  120. } else {
  121. sendLine(origin, args.isSilent(), FORMAT_ERROR, "You must specify some script to eval.");
  122. }
  123. } else if (sargs.length > 0 && sargs[0].equalsIgnoreCase("savetobasefile")) {
  124. if (sargs.length > 2) {
  125. final String[] bits = sargs[1].split("/");
  126. final String functionName = bits[0];
  127. final String script = args.getArgumentsAsString(2);
  128. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "Saving as '"+functionName+"': "+script);
  129. if (IdentityManager.getIdentityManager().getGlobalConfiguration().hasOptionString(myPlugin.getDomain(), "eval.baseFile")) {
  130. try {
  131. final String baseFile = myPlugin.getScriptDir()+'/'+IdentityManager.getIdentityManager().getGlobalConfiguration().getOption(myPlugin.getDomain(), "eval.baseFile");
  132. final FileWriter writer = new FileWriter(baseFile, true);
  133. writer.write("function ");
  134. writer.write(functionName);
  135. writer.write("(");
  136. for (int i = 1; i < bits.length; i++) {
  137. writer.write(bits[i]);
  138. writer.write(" ");
  139. }
  140. writer.write(") {\n");
  141. writer.write(script);
  142. writer.write("\n}\n");
  143. writer.flush();
  144. writer.close();
  145. } catch (IOException ioe) {
  146. sendLine(origin, args.isSilent(), FORMAT_ERROR, "IOException: "+ioe.getMessage());
  147. }
  148. } else {
  149. sendLine(origin, args.isSilent(), FORMAT_ERROR, "No baseFile specified, please /set "+myPlugin.getDomain()+" eval.baseFile filename (stored in scripts dir of profile)");
  150. }
  151. } else if (sargs.length > 1) {
  152. sendLine(origin, args.isSilent(), FORMAT_ERROR, "You must specify some script to save.");
  153. } else {
  154. sendLine(origin, args.isSilent(), FORMAT_ERROR, "You must specify a function name and some script to save.");
  155. }
  156. } else if (sargs.length > 0 && sargs[0].equalsIgnoreCase("help")) {
  157. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "This command allows you to interact with the script plugin");
  158. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "-------------------");
  159. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "reload/rehash - Reload all loaded scripts");
  160. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "load <script> - load scripts/<script> (file name relative to scripts dir)");
  161. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "unload <script> - unload <script> (full file name)");
  162. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "eval <script> - evaluate the code <script> and return the result");
  163. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "savetobasefile <name> <script> - save the code <script> to the eval basefile ("+myPlugin.getDomain()+".eval.basefile)");
  164. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, " as the function <name> (name/foo/bar will save it as 'name' with foo and");
  165. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, " bar as arguments.");
  166. sendLine(origin, args.isSilent(), FORMAT_OUTPUT, "-------------------");
  167. } else {
  168. sendLine(origin, args.isSilent(), FORMAT_ERROR, "Unknown subcommand.");
  169. }
  170. }
  171. /** {@inheritDoc} */
  172. @Override
  173. public AdditionalTabTargets getSuggestions(final int arg,
  174. final IntelligentCommandContext context) {
  175. final AdditionalTabTargets res = new AdditionalTabTargets();
  176. res.excludeAll();
  177. if (arg == 0) {
  178. res.add("help");
  179. res.add("rehash");
  180. res.add("reload");
  181. res.add("load");
  182. res.add("unload");
  183. res.add("eval");
  184. res.add("savetobasefile");
  185. } else if (arg == 1) {
  186. final Map<String, ScriptEngineWrapper> scripts = myPlugin.getScripts();
  187. if (context.getPreviousArgs().get(0).equalsIgnoreCase("load")) {
  188. for (String filename : getPossibleScripts()) {
  189. res.add(filename);
  190. }
  191. } else if (context.getPreviousArgs().get(0).equalsIgnoreCase("unload")) {
  192. for (String filename : scripts.keySet()) {
  193. res.add(filename);
  194. }
  195. }
  196. }
  197. return res;
  198. }
  199. /**
  200. * Retrieves a list of all installed scripts.
  201. * Any file under the main plugin directory (~/.DMDirc/scripts or similar)
  202. * that matches *.js is deemed to be a valid script.
  203. *
  204. * @return A list of all installed scripts
  205. */
  206. private List<String> getPossibleScripts() {
  207. final List<String> res = new LinkedList<String>();
  208. final LinkedList<File> dirs = new LinkedList<File>();
  209. dirs.add(new File(myPlugin.getScriptDir()));
  210. while (!dirs.isEmpty()) {
  211. final File dir = dirs.pop();
  212. if (dir.isDirectory()) {
  213. dirs.addAll(Arrays.asList(dir.listFiles()));
  214. } else if (dir.isFile() && dir.getName().endsWith(".js")) {
  215. final String target = dir.getPath();
  216. res.add(target.substring(myPlugin.getScriptDir().length(), target.length()));
  217. }
  218. }
  219. return res;
  220. }
  221. }