BigScreenBot.java 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. // Big Screen Bot
  2. //
  3. // Douglas Thrift
  4. //
  5. // BigScreenBot.java
  6. /* Copyright 2011 Douglas Thrift
  7. *
  8. * This file is part of Big Screen Bot.
  9. *
  10. * Big Screen Bot is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation, either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * Big Screen Bot is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with Big Screen Bot. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. package net.douglasthrift.bigscreenbot;
  24. import java.io.IOException;
  25. import java.net.MalformedURLException;
  26. import java.net.UnknownHostException;
  27. import java.net.URL;
  28. import java.security.GeneralSecurityException;
  29. import java.util.ArrayList;
  30. import java.util.HashSet;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.TreeMap;
  34. import java.util.Set;
  35. import java.util.regex.Pattern;
  36. import javax.net.ssl.SSLSocketFactory;
  37. import com.google.polo.exception.PoloException;
  38. import com.google.polo.ssl.DummySSLSocketFactory;
  39. import org.apache.commons.cli.CommandLine;
  40. import org.apache.commons.cli.GnuParser;
  41. import org.apache.commons.cli.HelpFormatter;
  42. import org.apache.commons.cli.Options;
  43. import org.apache.commons.cli.ParseException;
  44. import org.apache.commons.lang3.StringUtils;
  45. import org.jibble.pircbot.Colors;
  46. import org.jibble.pircbot.IrcException;
  47. public class BigScreenBot extends Bot
  48. {
  49. private static final int CHANNEL = 0x1;
  50. private static final int PRIVATE = 0x2;
  51. private static final int BOTH = 0x3;
  52. private static enum Action { RECONNECT, RESTART, QUIT }
  53. private abstract class Command
  54. {
  55. private boolean admin;
  56. private int access;
  57. private String arguments, description;
  58. protected Command(boolean admin, int access, String arguments, String description)
  59. {
  60. this.admin = admin;
  61. this.access = access;
  62. this.arguments = arguments;
  63. this.description = description;
  64. }
  65. public abstract void execute(String channel, String sender, boolean admin, String argument);
  66. public int getAccess()
  67. {
  68. return access;
  69. }
  70. public String getArguments()
  71. {
  72. return arguments;
  73. }
  74. public String getDescription()
  75. {
  76. return description;
  77. }
  78. public boolean isAdmin()
  79. {
  80. return admin;
  81. }
  82. public boolean isChannel()
  83. {
  84. return (access & CHANNEL) != 0;
  85. }
  86. public boolean isPrivate()
  87. {
  88. return (access & PRIVATE) != 0;
  89. }
  90. }
  91. private boolean verbose;
  92. private Remote remote;
  93. private Settings settings = new Settings();
  94. private Set<String> channels;
  95. private List<Pattern> admins = new ArrayList<Pattern>();
  96. private Map<String, Pattern> bans = new TreeMap<String, Pattern>();
  97. private Map<String, Command> commands = new TreeMap<String, Command>();
  98. private Action action = Action.RECONNECT;
  99. private BigScreenBot(boolean verbose)
  100. {
  101. super();
  102. this.verbose = verbose;
  103. try
  104. {
  105. settings.load();
  106. remote = new Remote(verbose, settings);
  107. }
  108. catch (IOException exception)
  109. {
  110. error(exception, 1);
  111. }
  112. catch (GeneralSecurityException exception)
  113. {
  114. error(exception, 1);
  115. }
  116. setAutoNickChange(true);
  117. setFinger("Big Screen Bot");
  118. setMessageDelay(0);
  119. setVersion(String.format("Big Screen Bot (%1$s)", System.getProperty("os.name")));
  120. if (settings.getBooleanProperty("ssl", false))
  121. if (settings.getBooleanProperty("verify", true))
  122. setSocketFactory(SSLSocketFactory.getDefault());
  123. else
  124. try
  125. {
  126. setSocketFactory(DummySSLSocketFactory.fromKeyManagers(null));
  127. }
  128. catch (GeneralSecurityException exception)
  129. {
  130. error(exception, 1);
  131. }
  132. setLogin(System.getProperty("user.name"));
  133. setName(settings.getProperty("nick", "bigscreenbot"));
  134. setVerbose(verbose);
  135. channels = new HashSet<String>(settings.getListProperty("channels", new ArrayList<String>()));
  136. for (String admin : settings.getListProperty("admins"))
  137. admins.add(compileNickMask(admin));
  138. for (String ban : settings.getListProperty("bans", new ArrayList<String>()))
  139. bans.put(ban, compileNickMask(ban));
  140. commands.put("ban", new Command(true, PRIVATE, "[mask...]", "block nick masks from using commands")
  141. {
  142. @Override
  143. public void execute(String channel, String sender, boolean admin, String argument)
  144. {
  145. String[] arguments = StringUtils.split(argument);
  146. if (arguments.length == 0)
  147. {
  148. listBans(channel, sender);
  149. return;
  150. }
  151. synchronized (bans)
  152. {
  153. for (String ban : arguments)
  154. if (bans.put(ban, compileNickMask(ban)) == null)
  155. sendMessage(channel, sender, String.format("banned nick mask (\"%1$s\")", ban));
  156. else
  157. sendMessage(channel, sender, String.format("nick mask (\"%1$s\") already banned", ban));
  158. storeBans(channel, sender);
  159. }
  160. }
  161. });
  162. commands.put("googletv", new Command(false, BOTH, "url [device]", "fling url to a Google TV device")
  163. {
  164. @Override
  165. public void execute(final String channel, final String sender, boolean admin, String argument)
  166. {
  167. final String[] arguments = StringUtils.split(argument, null, 2);
  168. if (arguments.length == 0)
  169. {
  170. help(channel, sender, admin, "googletv");
  171. return;
  172. }
  173. try
  174. {
  175. if (!new URL(arguments[0]).getProtocol().matches("^https?$"))
  176. {
  177. invalidURL(channel, sender, arguments[0]);
  178. return;
  179. }
  180. }
  181. catch (MalformedURLException exception)
  182. {
  183. invalidURL(channel, sender, arguments[0]);
  184. return;
  185. }
  186. if (arguments.length == 2)
  187. sendMessage(channel, sender, String.format("flinging URL (\"%1$s\") to device (\"%2$s\")...", arguments[0], arguments[1]));
  188. else
  189. sendMessage(channel, sender, String.format("flinging URL (\"%1$s\") to device(s)...", arguments[0]));
  190. new Thread()
  191. {
  192. @Override
  193. public void run()
  194. {
  195. if (arguments.length == 2)
  196. remote.fling(arguments[1], arguments[0]);
  197. else
  198. remote.fling(arguments[0]);
  199. sendMessage(channel, sender, String.format("flung URL (\"%1$s\") to device(s)", arguments[0]));
  200. }
  201. }.start();
  202. }
  203. private void invalidURL(String channel, String sender, String url)
  204. {
  205. sendMessage(channel, sender, String.format("invalid URL (\"%1$s\")", url));
  206. }
  207. });
  208. commands.put("help", new Command(false, PRIVATE, "[command]", "show this help message")
  209. {
  210. @Override
  211. public void execute(String channel, String sender, boolean admin, String arguments)
  212. {
  213. String argument = null;
  214. Command command = null;
  215. try
  216. {
  217. argument = StringUtils.split(arguments, null, 2)[0].toLowerCase();
  218. if (argument.startsWith("!"))
  219. argument = argument.substring(1);
  220. command = commands.get(argument);
  221. }
  222. catch (ArrayIndexOutOfBoundsException exception) {}
  223. sendMessage(channel, sender, Colors.BOLD + String.format("%1$-11s %2$-23s %3$-15s %4$s", "command", "arguments", "access", "description") + Colors.NORMAL);
  224. if (command != null)
  225. help(channel, sender, admin, argument, command);
  226. else
  227. for (Map.Entry<String, Command> nameCommand : commands.entrySet())
  228. help(channel, sender, admin, nameCommand.getKey(), nameCommand.getValue());
  229. }
  230. private void help(String channel, String sender, boolean admin, String name, Command command)
  231. {
  232. boolean unavailable = command.isAdmin() && !admin;
  233. String access;
  234. switch (command.getAccess())
  235. {
  236. case CHANNEL:
  237. access = "channel"; break;
  238. case PRIVATE:
  239. access = "private"; break;
  240. case BOTH: default:
  241. access = "channel/private"; break;
  242. }
  243. sendMessage(channel, sender, (unavailable ? Colors.UNDERLINE : "") + String.format("%1$-11s %2$-23s %3$-15s %4$s", name, command.getArguments(), access, command.getDescription()) + (unavailable ? Colors.NORMAL : ""));
  244. }
  245. });
  246. commands.put("join", new Command(true, PRIVATE, "channel", "join a channel")
  247. {
  248. @Override
  249. public void execute(String channel, String sender, boolean admin, String arguments)
  250. {
  251. String argument;
  252. try
  253. {
  254. argument = StringUtils.split(arguments, null, 2)[0];
  255. }
  256. catch (ArrayIndexOutOfBoundsException exception)
  257. {
  258. help(channel, sender, admin, "join");
  259. return;
  260. }
  261. joinChannel(argument);
  262. synchronized (channels)
  263. {
  264. channels.add(argument);
  265. storeChannels(channel, sender);
  266. }
  267. sendMessage(channel, sender, String.format("joined channel (\"%1$s\")", argument));
  268. }
  269. });
  270. commands.put("pair", new Command(true, PRIVATE, "[device [code]]", "pair with a Google TV device")
  271. {
  272. @Override
  273. public void execute(final String channel, final String sender, boolean admin, String argument)
  274. {
  275. final String[] arguments = StringUtils.split(argument, null, 2);
  276. switch (arguments.length)
  277. {
  278. case 0:
  279. sendMessage(channel, sender, "searching for devices to pair with...");
  280. new Thread()
  281. {
  282. @Override
  283. public void run()
  284. {
  285. List<String> devices;
  286. devices = remote.listDevices();
  287. if (devices.isEmpty())
  288. {
  289. sendMessage(channel, sender, "there are no devices to pair with");
  290. return;
  291. }
  292. sendMessage(channel, sender, Colors.BOLD + "devices" + Colors.NORMAL);
  293. for (String device : devices)
  294. sendMessage(channel, sender, device);
  295. }
  296. }.start();
  297. break;
  298. case 1:
  299. sendMessage(channel, sender, String.format("starting to pair with device (\"%1$s\")...", arguments[0]));
  300. new Thread()
  301. {
  302. @Override
  303. public void run()
  304. {
  305. try
  306. {
  307. if (remote.startPairDevice(arguments[0], new Remote.Pairing()
  308. {
  309. @Override
  310. public void prompt()
  311. {
  312. sendMessage(channel, sender, String.format("enter the code from the device (\"%1$s\") to finish pairing", arguments[0]));
  313. }
  314. @Override
  315. public void interrupted(InterruptedException exception)
  316. {
  317. sendMessage(channel, sender, String.format("pairing with device (\"%1$s\") interrupted", arguments[0]));
  318. }
  319. }))
  320. sendMessage(channel, sender, String.format("paired with device (\"%1$s\")", arguments[0]));
  321. }
  322. catch (MalformedURLException exception)
  323. {
  324. sendMessage(channel, sender, String.format("invalid device name (\"%1$s\")", arguments[0]));
  325. }
  326. catch (UnknownHostException exception)
  327. {
  328. sendMessage(channel, sender, String.format("could not find device (\"%1$s\")", arguments[0]));
  329. }
  330. catch (IOException exception)
  331. {
  332. error(channel, sender, exception);
  333. }
  334. catch (PoloException exception)
  335. {
  336. error(channel, sender, exception);
  337. }
  338. }
  339. }.start();
  340. break;
  341. default:
  342. sendMessage(channel, sender, String.format("finishing pairing with device (\"%1$s\")...", arguments[0]));
  343. new Thread()
  344. {
  345. @Override
  346. public void run()
  347. {
  348. try
  349. {
  350. if (!remote.finishPairDevice(arguments[0], arguments[1]))
  351. sendMessage(channel, sender, String.format("have not started pairing with device (\"%1$s\")", arguments[0]));
  352. }
  353. catch (MalformedURLException exception)
  354. {
  355. sendMessage(channel, sender, String.format("invalid device name (\"%1$s\")", arguments[0]));
  356. }
  357. }
  358. }.start();
  359. }
  360. }
  361. });
  362. commands.put("part", new Command(true, PRIVATE, "channel [message]", "part from a channel")
  363. {
  364. @Override
  365. public void execute(String channel, String sender, boolean admin, String argument)
  366. {
  367. String[] arguments = StringUtils.split(argument, null, 2);
  368. if (arguments.length == 0)
  369. {
  370. help(channel, sender, admin, "part");
  371. return;
  372. }
  373. if (arguments.length == 2)
  374. partChannel(arguments[0], arguments[1]);
  375. else
  376. partChannel(arguments[0]);
  377. synchronized (channels)
  378. {
  379. channels.remove(arguments[0]);
  380. storeChannels(channel, sender);
  381. }
  382. sendMessage(channel, sender, String.format("parted channel (\"%1$s\")", arguments[0]));
  383. }
  384. });
  385. commands.put("quit", new Command(true, PRIVATE, "[message]", "quit and do not come back")
  386. {
  387. @Override
  388. public void execute(String channel, String sender, boolean admin, String argument)
  389. {
  390. synchronized (action)
  391. {
  392. action = Action.QUIT;
  393. }
  394. quitServer(!argument.isEmpty() ? argument : "oh no!");
  395. }
  396. });
  397. commands.put("restart", new Command(true, PRIVATE, "", "quit and join running more up to date code")
  398. {
  399. @Override
  400. public void execute(String channel, String sender, boolean admin, String argument)
  401. {
  402. synchronized (action)
  403. {
  404. action = Action.RESTART;
  405. }
  406. quitServer("restarting");
  407. }
  408. });
  409. commands.put("say", new Command(true, PRIVATE, "nick|channel message", "say message to nick or channel")
  410. {
  411. @Override
  412. public void execute(String channel, String sender, boolean admin, String argument)
  413. {
  414. String[] arguments = StringUtils.split(argument, null, 2);
  415. if (arguments.length != 2)
  416. {
  417. help(channel, sender, admin, "say");
  418. return;
  419. }
  420. if (arguments[0].equalsIgnoreCase(getNick()))
  421. {
  422. sendMessage(channel, sender, "nice try");
  423. return;
  424. }
  425. sendMessage(arguments[0], arguments[1]);
  426. sendMessage(channel, sender, String.format("successfully sent message (\"%1$s\") to nick/channel (\"%2$s\")", arguments[1], arguments[0]));
  427. }
  428. });
  429. commands.put("unban", new Command(true, PRIVATE, "[mask...]", "allow blocked nick masks to use commands again")
  430. {
  431. @Override
  432. public void execute(String channel, String sender, boolean admin, String argument)
  433. {
  434. String[] arguments = StringUtils.split(argument);
  435. if (arguments.length == 0)
  436. {
  437. listBans(channel, sender);
  438. return;
  439. }
  440. synchronized (bans)
  441. {
  442. for (String ban : arguments)
  443. if (bans.remove(ban) != null)
  444. sendMessage(channel, sender, String.format("unbanned nick mask (\"%1$s\")", ban));
  445. else
  446. sendMessage(channel, sender, String.format("nick mask (\"%1$s\") already unbanned", ban));
  447. storeBans(channel, sender);
  448. }
  449. }
  450. });
  451. try
  452. {
  453. connect(settings.getProperty("server"), settings.getIntegerProperty("port", 6667));
  454. }
  455. catch (IOException exception)
  456. {
  457. error(exception, 1);
  458. }
  459. catch (IrcException exception)
  460. {
  461. error(exception, 1);
  462. }
  463. }
  464. @Override
  465. public void dispose()
  466. {
  467. super.dispose();
  468. try
  469. {
  470. remote.close();
  471. }
  472. catch (IOException exception)
  473. {
  474. error(exception);
  475. }
  476. }
  477. public void sendMessage(String channel, String sender, String message)
  478. {
  479. sendMessage(channel != null ? channel : sender, message);
  480. }
  481. @Override
  482. protected void onConnect()
  483. {
  484. synchronized (channels)
  485. {
  486. for (String channel : channels)
  487. joinChannel(channel);
  488. }
  489. }
  490. @Override
  491. protected void onDisconnect()
  492. {
  493. synchronized (action)
  494. {
  495. switch (action)
  496. {
  497. case RESTART:
  498. dispose();
  499. System.exit(2);
  500. case QUIT:
  501. dispose();
  502. break;
  503. default:
  504. while (true)
  505. {
  506. try
  507. {
  508. reconnect();
  509. }
  510. catch (IOException exception)
  511. {
  512. continue;
  513. }
  514. catch (IrcException exception)
  515. {
  516. error(exception, 1);
  517. }
  518. break;
  519. }
  520. }
  521. }
  522. }
  523. @Override
  524. protected void onMessage(String channel, String sender, String login, String hostname, String message)
  525. {
  526. doCommandFromMessage(channel, sender, login, hostname, message);
  527. }
  528. @Override
  529. protected void onPrivateMessage(String sender, String login, String hostname, String message)
  530. {
  531. doCommandFromMessage(null, sender, login, hostname, message);
  532. }
  533. private void doCommandFromMessage(String channel, String sender, String login, String hostname, String message)
  534. {
  535. boolean admin = matchNickMasks(sender, login, hostname, admins);
  536. synchronized (bans)
  537. {
  538. if (!admin && (matchNickMasks(sender, login, hostname, bans.values()) || !isNickInChannels(sender)))
  539. return;
  540. }
  541. message = Colors.removeFormattingAndColors(message);
  542. String[] arguments = StringUtils.split(message, null, 2);
  543. String argument = "";
  544. Command command = null;
  545. if (arguments.length != 0)
  546. {
  547. if (channel == null)
  548. try
  549. {
  550. if (new URL(arguments[0]).getProtocol().matches("^https?$"))
  551. {
  552. commands.get("googletv").execute(channel, sender, admin, StringUtils.join(arguments, ' '));
  553. return;
  554. }
  555. }
  556. catch (MalformedURLException exception) {}
  557. argument = arguments[0].toLowerCase();
  558. if (argument.startsWith("!"))
  559. argument = argument.substring(1);
  560. command = commands.get(argument);
  561. }
  562. if (channel != null)
  563. {
  564. if (command == null)
  565. return;
  566. if (!admin && command.isAdmin())
  567. return;
  568. if (!command.isChannel())
  569. return;
  570. }
  571. else
  572. {
  573. if (command == null)
  574. {
  575. sendMessage(channel, sender, String.format("unknown command (\"%1$s\"); try \"help\"", argument));
  576. return;
  577. }
  578. if (!admin && command.isAdmin())
  579. {
  580. sendMessage(channel, sender, String.format("unauthorized command (\"%1$s\")", argument));
  581. return;
  582. }
  583. if (!command.isPrivate())
  584. {
  585. sendMessage(channel, sender, String.format("inappropriate command (\"%1$s\")", argument));
  586. return;
  587. }
  588. }
  589. command.execute(channel, sender, admin, arguments.length == 2 ? arguments[1] : "");
  590. }
  591. private void error(Exception exception)
  592. {
  593. if (verbose)
  594. exception.printStackTrace();
  595. else
  596. System.err.println("bigscreenbot: " + exception.getMessage());
  597. }
  598. private void error(Exception exception, int code)
  599. {
  600. error(exception);
  601. System.exit(code);
  602. }
  603. private void error(String channel, String sender, Exception exception)
  604. {
  605. error(exception);
  606. sendMessage(channel, sender, "an error occurred: " + exception.getMessage());
  607. }
  608. private void help(String channel, String sender, boolean admin, String command)
  609. {
  610. commands.get("help").execute(channel, sender, admin, command);
  611. }
  612. private void listBans(String channel, String sender)
  613. {
  614. synchronized (bans)
  615. {
  616. if (bans.isEmpty())
  617. {
  618. sendMessage(channel, sender, "there are no bans");
  619. return;
  620. }
  621. sendMessage(channel, sender, Colors.BOLD + "ban" + Colors.NORMAL);
  622. for (String ban : bans.keySet())
  623. sendMessage(channel, sender, ban);
  624. }
  625. }
  626. private void storeBans(String channel, String sender)
  627. {
  628. synchronized (bans)
  629. {
  630. synchronized (settings)
  631. {
  632. settings.setListProperty("bans", bans.keySet());
  633. try
  634. {
  635. settings.store();
  636. }
  637. catch (IOException exception)
  638. {
  639. error(channel, sender, exception);
  640. }
  641. }
  642. }
  643. }
  644. private void storeChannels(String channel, String sender)
  645. {
  646. synchronized (channels)
  647. {
  648. synchronized (settings)
  649. {
  650. settings.setListProperty("channels", channels);
  651. try
  652. {
  653. settings.store();
  654. }
  655. catch (IOException exception)
  656. {
  657. error(channel, sender, exception);
  658. }
  659. }
  660. }
  661. }
  662. public static void main(String[] args)
  663. {
  664. Options options = new Options();
  665. options.addOption("h", "help", false, "show this help message and exit");
  666. options.addOption("v", "verbose", false, "");
  667. CommandLine line = null;
  668. try
  669. {
  670. line = new GnuParser().parse(options, args);
  671. }
  672. catch (ParseException exception)
  673. {
  674. System.err.println("bigscreenbot: " + exception.getMessage());
  675. }
  676. if (line.hasOption('h'))
  677. {
  678. new HelpFormatter().printHelp("bigscreenbot", options, true);
  679. return;
  680. }
  681. new BigScreenBot(line.hasOption('v'));
  682. }
  683. }
  684. // vim: expandtab