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 Runnable()
  298. {
  299. @Override
  300. public void run()
  301. {
  302. sendMessage(channel, sender, String.format("enter the code from the device (\"%1$s\") to finish pairing", arguments[0]));
  303. }
  304. }))
  305. sendMessage(channel, sender, String.format("pairing with device (\"%1$s\") succeeded", arguments[0]));
  306. else
  307. sendMessage(channel, sender, String.format("pairing with device (\"%1$s\") failed", arguments[0]));
  308. }
  309. catch (MalformedURLException exception)
  310. {
  311. sendMessage(channel, sender, String.format("invalid device name (\"%1$s\")", arguments[0]));
  312. }
  313. catch (UnknownHostException exception)
  314. {
  315. sendMessage(channel, sender, String.format("could not find device (\"%1$s\")", arguments[0]));
  316. }
  317. catch (IOException exception)
  318. {
  319. error(channel, sender, exception);
  320. }
  321. catch (PoloException exception)
  322. {
  323. error(channel, sender, exception);
  324. }
  325. catch (GeneralSecurityException exception)
  326. {
  327. error(channel, sender, exception);
  328. }
  329. }
  330. }.start();
  331. break;
  332. default:
  333. sendMessage(channel, sender, String.format("finishing pairing with device (\"%1$s\")...", arguments[0]));
  334. new Thread()
  335. {
  336. @Override
  337. public void run()
  338. {
  339. try
  340. {
  341. if (!remote.finishPairDevice(arguments[0], arguments[1]))
  342. sendMessage(channel, sender, String.format("have not started pairing with device (\"%1$s\")", arguments[0]));
  343. }
  344. catch (MalformedURLException exception)
  345. {
  346. sendMessage(channel, sender, String.format("invalid device name (\"%1$s\")", arguments[0]));
  347. }
  348. }
  349. }.start();
  350. }
  351. }
  352. });
  353. commands.put("part", new Command(true, PRIVATE, "channel [message]", "part from a channel")
  354. {
  355. @Override
  356. public void execute(String channel, String sender, boolean admin, String argument)
  357. {
  358. String[] arguments = StringUtils.split(argument, null, 2);
  359. if (arguments.length == 0)
  360. {
  361. help(channel, sender, admin, "part");
  362. return;
  363. }
  364. if (arguments.length == 2)
  365. partChannel(arguments[0], arguments[1]);
  366. else
  367. partChannel(arguments[0]);
  368. synchronized (channels)
  369. {
  370. channels.remove(arguments[0]);
  371. storeChannels(channel, sender);
  372. }
  373. sendMessage(channel, sender, String.format("parted channel (\"%1$s\")", arguments[0]));
  374. }
  375. });
  376. commands.put("quit", new Command(true, PRIVATE, "[message]", "quit and do not come back")
  377. {
  378. @Override
  379. public void execute(String channel, String sender, boolean admin, String argument)
  380. {
  381. synchronized (action)
  382. {
  383. action = Action.QUIT;
  384. }
  385. quitServer(!argument.isEmpty() ? argument : "oh no!");
  386. }
  387. });
  388. commands.put("restart", new Command(true, PRIVATE, "", "quit and join running more up to date code")
  389. {
  390. @Override
  391. public void execute(String channel, String sender, boolean admin, String argument)
  392. {
  393. synchronized (action)
  394. {
  395. action = Action.RESTART;
  396. }
  397. quitServer("restarting");
  398. }
  399. });
  400. commands.put("say", new Command(true, PRIVATE, "nick|channel message", "say message to nick or channel")
  401. {
  402. @Override
  403. public void execute(String channel, String sender, boolean admin, String argument)
  404. {
  405. String[] arguments = StringUtils.split(argument, null, 2);
  406. if (arguments.length != 2)
  407. {
  408. help(channel, sender, admin, "say");
  409. return;
  410. }
  411. if (arguments[0].equalsIgnoreCase(getNick()))
  412. {
  413. sendMessage(channel, sender, "nice try");
  414. return;
  415. }
  416. sendMessage(arguments[0], arguments[1]);
  417. sendMessage(channel, sender, String.format("successfully sent message (\"%1$s\") to nick/channel (\"%2$s\")", arguments[1], arguments[0]));
  418. }
  419. });
  420. commands.put("unban", new Command(true, PRIVATE, "[mask...]", "allow blocked nick masks to use commands again")
  421. {
  422. @Override
  423. public void execute(String channel, String sender, boolean admin, String argument)
  424. {
  425. String[] arguments = StringUtils.split(argument);
  426. if (arguments.length == 0)
  427. {
  428. listBans(channel, sender);
  429. return;
  430. }
  431. synchronized (bans)
  432. {
  433. for (String ban : arguments)
  434. if (bans.remove(ban) != null)
  435. sendMessage(channel, sender, String.format("unbanned nick mask (\"%1$s\")", ban));
  436. else
  437. sendMessage(channel, sender, String.format("nick mask (\"%1$s\") already unbanned", ban));
  438. storeBans(channel, sender);
  439. }
  440. }
  441. });
  442. try
  443. {
  444. connect(settings.getProperty("server"), settings.getIntegerProperty("port", 6667));
  445. }
  446. catch (IOException exception)
  447. {
  448. error(exception, 1);
  449. }
  450. catch (IrcException exception)
  451. {
  452. error(exception, 1);
  453. }
  454. }
  455. @Override
  456. public void dispose()
  457. {
  458. super.dispose();
  459. try
  460. {
  461. remote.close();
  462. }
  463. catch (IOException exception)
  464. {
  465. error(exception);
  466. }
  467. }
  468. public void sendMessage(String channel, String sender, String message)
  469. {
  470. sendMessage(channel != null ? channel : sender, message);
  471. }
  472. @Override
  473. protected void onConnect()
  474. {
  475. synchronized (channels)
  476. {
  477. for (String channel : channels)
  478. joinChannel(channel);
  479. }
  480. }
  481. @Override
  482. protected void onDisconnect()
  483. {
  484. synchronized (action)
  485. {
  486. switch (action)
  487. {
  488. case RESTART:
  489. dispose();
  490. System.exit(2);
  491. case QUIT:
  492. dispose();
  493. break;
  494. default:
  495. while (true)
  496. {
  497. try
  498. {
  499. reconnect();
  500. }
  501. catch (IOException exception)
  502. {
  503. continue;
  504. }
  505. catch (IrcException exception)
  506. {
  507. error(exception, 1);
  508. }
  509. break;
  510. }
  511. }
  512. }
  513. }
  514. @Override
  515. protected void onMessage(String channel, String sender, String login, String hostname, String message)
  516. {
  517. doCommandFromMessage(channel, sender, login, hostname, message);
  518. }
  519. @Override
  520. protected void onPrivateMessage(String sender, String login, String hostname, String message)
  521. {
  522. doCommandFromMessage(null, sender, login, hostname, message);
  523. }
  524. private void doCommandFromMessage(String channel, String sender, String login, String hostname, String message)
  525. {
  526. boolean admin = matchNickMasks(sender, login, hostname, admins);
  527. synchronized (bans)
  528. {
  529. if (!admin && (matchNickMasks(sender, login, hostname, bans.values()) || !isNickInChannels(sender)))
  530. return;
  531. }
  532. message = Colors.removeFormattingAndColors(message);
  533. String[] arguments = StringUtils.split(message, null, 2);
  534. String argument = "";
  535. Command command = null;
  536. if (arguments.length != 0)
  537. {
  538. if (channel == null)
  539. {
  540. if (isValidURL(arguments[0]))
  541. {
  542. fling(channel, sender, admin, arguments);
  543. return;
  544. }
  545. }
  546. 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]))
  547. {
  548. fling(channel, sender, admin, Arrays.copyOfRange(arguments, 1, arguments.length));
  549. return;
  550. }
  551. argument = arguments[0].toLowerCase();
  552. if (argument.startsWith("!"))
  553. argument = argument.substring(1);
  554. command = commands.get(argument);
  555. }
  556. if (channel != null)
  557. {
  558. if (command == null)
  559. return;
  560. if (!admin && command.isAdmin())
  561. return;
  562. if (!command.isChannel())
  563. return;
  564. }
  565. else
  566. {
  567. if (command == null)
  568. {
  569. sendMessage(channel, sender, String.format("unknown command (\"%1$s\"); try \"help\"", argument));
  570. return;
  571. }
  572. if (!admin && command.isAdmin())
  573. {
  574. sendMessage(channel, sender, String.format("unauthorized command (\"%1$s\")", argument));
  575. return;
  576. }
  577. if (!command.isPrivate())
  578. {
  579. sendMessage(channel, sender, String.format("inappropriate command (\"%1$s\")", argument));
  580. return;
  581. }
  582. }
  583. command.execute(channel, sender, admin, arguments.length == 2 ? arguments[1] : "");
  584. }
  585. private void error(Exception exception)
  586. {
  587. if (verbose)
  588. exception.printStackTrace();
  589. else
  590. System.err.println("bigscreenbot: " + exception.getMessage());
  591. }
  592. private void error(Exception exception, int code)
  593. {
  594. error(exception);
  595. System.exit(code);
  596. }
  597. private void error(String channel, String sender, Exception exception)
  598. {
  599. error(exception);
  600. sendMessage(channel, sender, "an error occurred: " + exception.getMessage());
  601. }
  602. private void fling(String channel, String sender, boolean admin, String... arguments)
  603. {
  604. commands.get("googletv").execute(channel, sender, admin, StringUtils.join(arguments, ' '));
  605. }
  606. private void help(String channel, String sender, boolean admin, String command)
  607. {
  608. commands.get("help").execute(channel, sender, admin, command);
  609. }
  610. private boolean isValidURL(String url)
  611. {
  612. try
  613. {
  614. return SCHEMES.matcher(new URL(url).getProtocol()).matches();
  615. }
  616. catch (MalformedURLException exception)
  617. {
  618. return false;
  619. }
  620. }
  621. private void listBans(String channel, String sender)
  622. {
  623. synchronized (bans)
  624. {
  625. if (bans.isEmpty())
  626. {
  627. sendMessage(channel, sender, "there are no bans");
  628. return;
  629. }
  630. sendMessage(channel, sender, Colors.BOLD + "ban" + Colors.NORMAL);
  631. for (String ban : bans.keySet())
  632. sendMessage(channel, sender, ban);
  633. }
  634. }
  635. private void storeBans(String channel, String sender)
  636. {
  637. synchronized (bans)
  638. {
  639. synchronized (settings)
  640. {
  641. settings.setListProperty("bans", bans.keySet());
  642. try
  643. {
  644. settings.store();
  645. }
  646. catch (IOException exception)
  647. {
  648. error(channel, sender, exception);
  649. }
  650. }
  651. }
  652. }
  653. private void storeChannels(String channel, String sender)
  654. {
  655. synchronized (channels)
  656. {
  657. synchronized (settings)
  658. {
  659. settings.setListProperty("channels", channels);
  660. try
  661. {
  662. settings.store();
  663. }
  664. catch (IOException exception)
  665. {
  666. error(channel, sender, exception);
  667. }
  668. }
  669. }
  670. }
  671. public static void main(String[] args)
  672. {
  673. Options options = new Options();
  674. options.addOption("h", "help", false, "show this help message and exit");
  675. options.addOption("v", "verbose", false, "");
  676. CommandLine line = null;
  677. try
  678. {
  679. line = new GnuParser().parse(options, args);
  680. }
  681. catch (ParseException exception)
  682. {
  683. System.err.println("bigscreenbot: " + exception.getMessage());
  684. }
  685. if (line.hasOption('h'))
  686. {
  687. new HelpFormatter().printHelp("bigscreenbot", options, true);
  688. return;
  689. }
  690. new BigScreenBot(line.hasOption('v'));
  691. }
  692. }
  693. // vim: expandtab