Java IRC bot
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

InputHandler.java 16KB

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