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 17KB

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