Java IRC bot
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

InputHandler.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package com.md87.charliebravo;
  6. import com.dmdirc.parser.irc.ChannelClientInfo;
  7. import com.dmdirc.parser.irc.ChannelInfo;
  8. import com.dmdirc.parser.irc.ClientInfo;
  9. import com.dmdirc.parser.irc.IRCParser;
  10. import com.dmdirc.parser.irc.callbacks.interfaces.IChannelMessage;
  11. import com.dmdirc.parser.irc.callbacks.interfaces.IPrivateCTCP;
  12. import com.dmdirc.parser.irc.callbacks.interfaces.IPrivateMessage;
  13. import com.dmdirc.util.RollingList;
  14. import com.md87.charliebravo.commands.AuthenticateCommand;
  15. import com.md87.charliebravo.commands.CalcCommand;
  16. import com.md87.charliebravo.commands.DefineCommand;
  17. import com.md87.charliebravo.commands.FollowupsCommand;
  18. import com.md87.charliebravo.commands.GitCommand;
  19. import com.md87.charliebravo.commands.GoogleCommand;
  20. import com.md87.charliebravo.commands.HelpCommand;
  21. import com.md87.charliebravo.commands.IssueCommand;
  22. import com.md87.charliebravo.commands.NewzbinCommand;
  23. import com.md87.charliebravo.commands.QuitCommand;
  24. import com.md87.charliebravo.commands.ReloadCommand;
  25. import com.md87.charliebravo.commands.SetCommand;
  26. import com.md87.charliebravo.commands.SkillCommand;
  27. import com.md87.charliebravo.commands.SnippetsCommand;
  28. import com.md87.charliebravo.commands.TranslateCommand;
  29. import com.md87.charliebravo.commands.WhoisCommand;
  30. import com.md87.util.crypto.ArcFourEncrypter;
  31. import java.util.ArrayList;
  32. import java.util.HashMap;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.Random;
  36. import java.util.regex.Matcher;
  37. import net.miginfocom.Base64;
  38. /**
  39. *
  40. * @author chris
  41. */
  42. public class InputHandler implements IChannelMessage, IPrivateMessage, IPrivateCTCP {
  43. protected IRCParser parser;
  44. protected final Config config;
  45. protected final List<Command> commands = new ArrayList<Command>();
  46. protected final Map<String, Response> responses = new HashMap<String, Response>();
  47. protected final Map<String, RollingList<String>> snippets = new HashMap<String, RollingList<String>>();
  48. public InputHandler(final Config config) {
  49. this.config = config;
  50. commands.add(new GoogleCommand());
  51. commands.add(new QuitCommand());
  52. commands.add(new HelpCommand());
  53. commands.add(new FollowupsCommand());
  54. commands.add(new AuthenticateCommand());
  55. commands.add(new CalcCommand());
  56. commands.add(new WhoisCommand());
  57. commands.add(new TranslateCommand());
  58. commands.add(new IssueCommand());
  59. commands.add(new GitCommand());
  60. commands.add(new SetCommand());
  61. commands.add(new SkillCommand());
  62. commands.add(new SnippetsCommand());
  63. commands.add(new NewzbinCommand());
  64. commands.add(new ReloadCommand());
  65. commands.add(new DefineCommand());
  66. }
  67. public Config getConfig() {
  68. return config;
  69. }
  70. public List<Command> getCommands() {
  71. return new ArrayList<Command>(commands);
  72. }
  73. public Response getLastResponse(final String target) {
  74. return responses.get(target);
  75. }
  76. public RollingList<String> getSnippets(final String channel) {
  77. return snippets.get(channel);
  78. }
  79. public IRCParser getParser() {
  80. return parser;
  81. }
  82. public void setParser(final IRCParser parser) {
  83. this.parser = parser;
  84. parser.getCallbackManager().addCallback("OnChannelMessage", this);
  85. parser.getCallbackManager().addCallback("OnPrivateMessage", this);
  86. parser.getCallbackManager().addCallback("OnPrivateCTCP", this);
  87. }
  88. public void onChannelMessage(final IRCParser tParser, final ChannelInfo cChannel,
  89. final ChannelClientInfo cChannelClient, final String sMessage, final String sHost) {
  90. for (String nick : getNicknames()) {
  91. if (sMessage.matches("^(?i)" + Matcher.quoteReplacement(nick) + "[,:!] .*")) {
  92. handleInput(ClientInfo.parseHost(sHost), cChannel.getName(),
  93. sMessage.substring(nick.length() + 2));
  94. break;
  95. } else if (sMessage.matches("^(?i)" + Matcher.quoteReplacement(nick) + "\\?")
  96. && snippets.containsKey(cChannel.getName())) {
  97. final RollingList<String> snips = snippets.get(cChannel.getName());
  98. final String snippet = snips.get(snips.getList().size() - 1);
  99. handleInput(ClientInfo.parseHost(sHost), cChannel.getName(), snippet);
  100. snips.remove(snippet);
  101. break;
  102. }
  103. }
  104. for (Map.Entry<String, String> snippet : config.getConfigfile()
  105. .getKeyDomain("snippets").entrySet()) {
  106. System.out.println("Snippet test: " + snippet.getKey());
  107. if (sMessage.matches(snippet.getKey())) {
  108. if (!snippets.containsKey(cChannel.getName())) {
  109. snippets.put(cChannel.getName(), new RollingList<String>(10));
  110. }
  111. snippets.get(cChannel.getName()).add(sMessage.replaceFirst(snippet.getKey(),
  112. snippet.getValue()));
  113. System.out.println("Snippet: " + sMessage.replaceFirst(snippet.getKey(),
  114. snippet.getValue()));
  115. }
  116. }
  117. }
  118. protected String[] getNicknames() {
  119. return new String[] {
  120. parser.getMyNickname(),
  121. parser.getMyNickname().replaceAll("[a-z]", ""),
  122. parser.getMyNickname().replaceAll("[^a-zA-Z]", ""),
  123. parser.getMyNickname().replaceAll("[^A-Z]", ""),
  124. };
  125. }
  126. public void onPrivateMessage(final IRCParser tParser, final String sMessage, final String sHost) {
  127. handleInput(ClientInfo.parseHost(sHost), ClientInfo.parseHost(sHost), sMessage);
  128. }
  129. @SuppressWarnings("unchecked")
  130. public void onPrivateCTCP(IRCParser tParser, String sType, String sMessage, String sHost) {
  131. final ClientInfo client = tParser.getClientInfoOrFake(sHost);
  132. if ("COOKIE".equals(sType)) {
  133. final String status = (String) client.getMap().get("Cookie");
  134. final String key1 = (String) client.getMap().get("Key1");
  135. final String key2 = (String) client.getMap().get("Key2");
  136. final String idp = (String) client.getMap().get("OpenID-p");
  137. if ("GETKEY".equals(sMessage) && "SET".equals(status)) {
  138. parser.sendCTCP(ClientInfo.parseHost(sHost), "COOKIE", "SETKEY " + key1);
  139. client.getMap().put("Cookie", "GETKEY");
  140. } else if (sMessage.startsWith("OFFER")) {
  141. final String what = sMessage.substring(6);
  142. if (config.getConfigfile().getKeyDomain("cookies").containsKey(what)) {
  143. client.getMap().put("Key1", config.getConfigfile()
  144. .getKeyDomain("cookies").get(what));
  145. client.getMap().put("OpenID-p", config.getConfigfile()
  146. .getKeyDomain("cookie-ids").get(what));
  147. }
  148. final byte[] bytes = new byte[50];
  149. new Random().nextBytes(bytes);
  150. final String newkey2 = Base64.encodeToString(bytes, false);
  151. client.getMap().put("Cookie", "OFFER");
  152. client.getMap().put("Key2", newkey2);
  153. parser.sendCTCP(ClientInfo.parseHost(sHost), "COOKIE", "GET " + newkey2);
  154. } else if (sMessage.startsWith("SHOW") && "OFFER".equals(status)) {
  155. final String payload = sMessage.substring(5);
  156. final String info = new String(new ArcFourEncrypter(key1 + key2)
  157. .encrypt(Base64.decode(payload)));
  158. if (idp.equals(info)) {
  159. client.getMap().put("OpenID", idp);
  160. }
  161. }
  162. }
  163. }
  164. protected void handleInput(final String source, final String target, final String text) {
  165. new Thread(new Runnable() {
  166. public void run() {
  167. handleInputImpl(source, target, text);
  168. }
  169. }).start();
  170. }
  171. protected void handleInputImpl(final String source, final String target, final String text) {
  172. final Response response = new Response(parser, source, target);
  173. Command command = null;
  174. int index = 0;
  175. try {
  176. if (responses.containsKey(target)) {
  177. for (Followup followup : responses.get(target).getFollowups()) {
  178. if (followup.matches(text)) {
  179. command = followup;
  180. }
  181. }
  182. }
  183. if (command == null) {
  184. for (Command pcommand : commands) {
  185. if (text.toLowerCase().startsWith(pcommand.getClass()
  186. .getSimpleName().replace("Command", "").toLowerCase())) {
  187. command = pcommand;
  188. index = pcommand.getClass().getSimpleName().length() - 6;
  189. }
  190. }
  191. }
  192. if (command != null) {
  193. boolean cont = true;
  194. if (command.getClass().isAnnotationPresent(CommandOptions.class)) {
  195. final CommandOptions opts = command.getClass()
  196. .getAnnotation(CommandOptions.class);
  197. final String id = (String) parser.getClientInfoOrFake(source)
  198. .getMap().get("OpenID");
  199. if (opts.requireAuthorisation() && id == null) {
  200. response.sendMessage("You must be authorised to use that command", true);
  201. cont = false;
  202. } else if (opts.requireLevel() > -1 &&
  203. (!config.hasOption(id, "admin.level")
  204. || (Integer.valueOf(config.getOption(id, "admin.level"))
  205. < opts.requireLevel()))) {
  206. response.sendMessage("You have insufficient access to " +
  207. "use that command", true);
  208. response.addFollowup(new LevelErrorFollowup(response.getSource(),
  209. opts.requireLevel(),
  210. config.hasOption(id, "admin.level")
  211. ? Integer.valueOf(config.getOption(id, "admin.level")) : -1));
  212. cont = false;
  213. } else {
  214. int count = 0;
  215. final StringBuilder missing = new StringBuilder();
  216. for (String setting : opts.requiredSettings()) {
  217. if (!config.hasOption(id, setting)) {
  218. if (missing.length() > 0) {
  219. missing.append(", ");
  220. }
  221. count++;
  222. missing.append(setting);
  223. }
  224. }
  225. if (count > 0) {
  226. cont = false;
  227. response.sendRawMessage("You must have the following setting"
  228. + (count == 1 ? "" : "s")
  229. + " in order to use that command, " + response.getSource()
  230. + ": " + missing.toString()
  231. .replaceAll("^(.*), (.*?)$", "$1 and $2") + ".");
  232. }
  233. }
  234. }
  235. if (cont) {
  236. command.execute(this, response, text.substring(Math.min(text.length(), index)));
  237. }
  238. }
  239. } catch (Throwable ex) {
  240. response.sendMessage("an error has occured: " + ex.getMessage());
  241. response.addFollowup(new StacktraceFollowup(ex));
  242. }
  243. if (command != null) {
  244. if (response.isInheritFollows() && responses.containsKey(target)) {
  245. response.addFollowups(responses.get(target).getFollowups());
  246. }
  247. responses.put(target, response);
  248. }
  249. }
  250. protected static class LevelErrorFollowup implements Followup {
  251. private final String source;
  252. private final int required, desired;
  253. public LevelErrorFollowup(String source, int required, int desired) {
  254. this.source = source;
  255. this.required = required;
  256. this.desired = desired;
  257. }
  258. public boolean matches(String line) {
  259. return line.equalsIgnoreCase("details");
  260. }
  261. public void execute(InputHandler handler, Response response, String line) throws Exception {
  262. final boolean you = response.getSource().equals(source);
  263. response.sendMessage("that command requires level " + required
  264. + " access, but " + (you ? "you" : source) + " "
  265. + (desired == -1 ? "do" + (you ? "" : "es") + " not have any assigned level"
  266. : "only ha" + (you ? "ve" : "s") + " level " + desired));
  267. }
  268. }
  269. protected static class StacktraceFollowup implements Followup {
  270. private final Throwable ex;
  271. private final int index;
  272. public StacktraceFollowup(Throwable ex) {
  273. this(ex, 0);
  274. }
  275. public StacktraceFollowup(Throwable ex, int index) {
  276. this.ex = ex;
  277. this.index = index;
  278. }
  279. public boolean matches(String line) {
  280. return index == 0 ? line.equals("stacktrace") : line.equals("more");
  281. }
  282. public void execute(final InputHandler handler, Response response, String line) throws Exception {
  283. StringBuilder trace = new StringBuilder();
  284. int i;
  285. for (i = index; i < ex.getStackTrace().length; i++) {
  286. if (trace.length() > 0) {
  287. int next = ex.getStackTrace()[i].toString().length() + 2;
  288. if (trace.length() + next + 33 + (index == 0 ? 5 : 4)
  289. + String.valueOf(i - index).length() > response.getMaxLength()) {
  290. break;
  291. }
  292. trace.append("; ");
  293. }
  294. trace.append(ex.getStackTrace()[i].toString());
  295. }
  296. response.sendMessage("the " + (index == 0 ? "first" :
  297. i < ex.getStackTrace().length ? "next" : "last")
  298. + " " + (i - index) + " elements of the trace are: " + trace);
  299. if (i < ex.getStackTrace().length) {
  300. response.addFollowup(new StacktraceFollowup(ex, i));
  301. }
  302. }
  303. }
  304. }