BigScreenBot.java 26 KB

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