Java IRC bot
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.

InputHandler.java 15KB

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