Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Server.java 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. /*
  2. * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
  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.dmdirc;
  23. import java.net.URL;
  24. import java.util.ArrayList;
  25. import java.util.Hashtable;
  26. import java.util.List;
  27. import java.util.Locale;
  28. import java.util.Map;
  29. import java.util.Timer;
  30. import java.util.TimerTask;
  31. import javax.swing.ImageIcon;
  32. import javax.swing.JInternalFrame;
  33. import javax.swing.SwingUtilities;
  34. import com.dmdirc.actions.ActionManager;
  35. import com.dmdirc.actions.CoreActionType;
  36. import com.dmdirc.commandparser.CommandManager;
  37. import com.dmdirc.commandparser.CommandWindow;
  38. import com.dmdirc.identities.ConfigManager;
  39. import com.dmdirc.identities.ConfigSource;
  40. import com.dmdirc.logger.ErrorLevel;
  41. import com.dmdirc.logger.Logger;
  42. import com.dmdirc.parser.ChannelInfo;
  43. import com.dmdirc.parser.ClientInfo;
  44. import com.dmdirc.parser.IRCParser;
  45. import com.dmdirc.parser.MyInfo;
  46. import com.dmdirc.parser.ParserError;
  47. import com.dmdirc.parser.ServerInfo;
  48. import com.dmdirc.parser.callbacks.CallbackNotFound;
  49. import com.dmdirc.parser.callbacks.interfaces.IAwayState;
  50. import com.dmdirc.parser.callbacks.interfaces.IAwayStateOther;
  51. import com.dmdirc.parser.callbacks.interfaces.IChannelSelfJoin;
  52. import com.dmdirc.parser.callbacks.interfaces.IConnectError;
  53. import com.dmdirc.parser.callbacks.interfaces.IErrorInfo;
  54. import com.dmdirc.parser.callbacks.interfaces.IGotNetwork;
  55. import com.dmdirc.parser.callbacks.interfaces.IMOTDEnd;
  56. import com.dmdirc.parser.callbacks.interfaces.IMOTDLine;
  57. import com.dmdirc.parser.callbacks.interfaces.IMOTDStart;
  58. import com.dmdirc.parser.callbacks.interfaces.INickInUse;
  59. import com.dmdirc.parser.callbacks.interfaces.INumeric;
  60. import com.dmdirc.parser.callbacks.interfaces.IPingFailed;
  61. import com.dmdirc.parser.callbacks.interfaces.IPingSuccess;
  62. import com.dmdirc.parser.callbacks.interfaces.IPrivateAction;
  63. import com.dmdirc.parser.callbacks.interfaces.IPrivateCTCP;
  64. import com.dmdirc.parser.callbacks.interfaces.IPrivateCTCPReply;
  65. import com.dmdirc.parser.callbacks.interfaces.IPrivateMessage;
  66. import com.dmdirc.parser.callbacks.interfaces.IPrivateNotice;
  67. import com.dmdirc.parser.callbacks.interfaces.ISocketClosed;
  68. import com.dmdirc.ui.MainFrame;
  69. import com.dmdirc.ui.ServerFrame;
  70. import com.dmdirc.ui.input.TabCompleter;
  71. import com.dmdirc.ui.messages.Formatter;
  72. /**
  73. * The Server class represents the client's view of a server. It maintains
  74. * a list of all channels, queries, etc, and handles parser callbacks pertaining
  75. * to the server.
  76. * @author chris
  77. */
  78. public final class Server extends FrameContainer implements IChannelSelfJoin,
  79. IPrivateMessage, IPrivateAction, IErrorInfo, IPrivateCTCP,
  80. IPrivateCTCPReply, ISocketClosed, IPrivateNotice, IMOTDStart,
  81. IMOTDLine, IMOTDEnd, INumeric, IGotNetwork, IPingFailed, IPingSuccess,
  82. IAwayState, IConnectError, IAwayStateOther, INickInUse {
  83. /** The callbacks that should be registered for server instances. */
  84. private final static String[] callbacks = {
  85. "OnChannelSelfJoin", "OnErrorInfo", "OnPrivateMessage", "OnPingSuccess",
  86. "OnPrivateAction", "OnPrivateCTCP", "OnPrivateNotice", "OnConnectError",
  87. "OnPrivateCTCPReply", "OnSocketClosed", "OnGotNetwork", "OnNumeric",
  88. "OnMOTDStart", "OnMOTDLine", "OnMOTDEnd", "OnPingFailed", "OnAwayState",
  89. "OnAwayStateOther", "OnNickInUse"
  90. };
  91. /** Open channels that currently exist on the server. */
  92. private final Map<String, Channel> channels = new Hashtable<String, Channel>();
  93. /** Open query windows on the server. */
  94. private final Map<String, Query> queries = new Hashtable<String, Query>();
  95. /** The IRC Parser instance handling this server. */
  96. private IRCParser parser;
  97. /** The raw frame used for this server instance. */
  98. private Raw raw;
  99. /** The ServerFrame corresponding to this server. */
  100. private ServerFrame frame;
  101. /** The name of the server we're connecting to. */
  102. private String server;
  103. /** The port we're connecting to. */
  104. private int port;
  105. /** The password we're using to connect. */
  106. private String password;
  107. /** Whether we're using SSL or not. */
  108. private boolean ssl;
  109. /** The profile we're using. */
  110. private ConfigSource profile;
  111. /**
  112. * Used to indicate that this server is in the process of closing all of its
  113. * windows, and thus requests for individual ones to be closed should be
  114. * ignored.
  115. */
  116. private boolean closing;
  117. /** The tabcompleter used for this server. */
  118. private final TabCompleter tabCompleter = new TabCompleter();
  119. /** The icon being used for this server. */
  120. private ImageIcon imageIcon;
  121. /** The last activated internal frame for this server. */
  122. private FrameContainer activeFrame = this;
  123. /** The config manager for this server. */
  124. private ConfigManager configManager;
  125. /** Whether we're marked as away or not. */
  126. private boolean away;
  127. /** Our reason for being away, if any. */
  128. private String awayMessage;
  129. /** Whether we should attempt to reconnect or not. */
  130. private boolean reconnect = true;
  131. /**
  132. * Creates a new instance of Server.
  133. * @param server The hostname/ip of the server to connect to
  134. * @param port The port to connect to
  135. * @param password The server password
  136. * @param ssl Whether to use SSL or not
  137. * @param profile The profile to use
  138. */
  139. public Server(final String server, final int port, final String password,
  140. final boolean ssl, final ConfigSource profile) {
  141. this.server = server;
  142. ServerManager.getServerManager().registerServer(this);
  143. configManager = new ConfigManager("", "", server);
  144. frame = new ServerFrame(this);
  145. frame.setTitle(server + ":" + port);
  146. frame.setTabCompleter(tabCompleter);
  147. frame.addInternalFrameListener(this);
  148. MainFrame.getMainFrame().addChild(frame);
  149. frame.open();
  150. tabCompleter.addEntries(CommandManager.getServerCommandNames());
  151. tabCompleter.addEntries(CommandManager.getGlobalCommandNames());
  152. new Timer().scheduleAtFixedRate(new TimerTask() {
  153. public void run() {
  154. for (Channel channel : channels.values()) {
  155. channel.checkWho();
  156. }
  157. }
  158. }, 0, Config.getOptionInt("general", "whotime", 60000));
  159. connect(server, port, password, ssl, profile);
  160. }
  161. /**
  162. * Connects to a new server with the specified details.
  163. * @param server The hostname/ip of the server to connect to
  164. * @param port The port to connect to
  165. * @param password The server password
  166. * @param ssl Whether to use SSL or not
  167. * @param profile The profile to use
  168. */
  169. public void connect(final String server, final int port, final String password,
  170. final boolean ssl, final ConfigSource profile) {
  171. reconnect = true;
  172. if (parser != null && parser.getSocketState() == parser.STATE_OPEN) {
  173. disconnect(configManager.getOption("general", "quitmessage"));
  174. }
  175. this.server = server;
  176. this.port = port;
  177. this.password = password;
  178. this.ssl = ssl;
  179. this.profile = profile;
  180. configManager = new ConfigManager("", "", server);
  181. final ClassLoader cldr = this.getClass().getClassLoader();
  182. URL imageURL;
  183. if (ssl) {
  184. imageURL = cldr.getResource("uk/org/ownage/dmdirc/res/secure-server.png");
  185. } else {
  186. imageURL = cldr.getResource("uk/org/ownage/dmdirc/res/server.png");
  187. }
  188. imageIcon = new ImageIcon(imageURL);
  189. frame.setFrameIcon(imageIcon);
  190. addLine("serverConnecting", server, port);
  191. sendNotification();
  192. final MyInfo myInfo = new MyInfo();
  193. myInfo.setNickname(profile.getOption("profile", "nickname"));
  194. myInfo.setRealname(profile.getOption("profile", "realname"));
  195. if (profile.hasOption("profile", "ident")) {
  196. myInfo.setUsername(profile.getOption("profile", "ident"));
  197. }
  198. final ServerInfo serverInfo = new ServerInfo(server, port, password);
  199. serverInfo.setSSL(ssl);
  200. parser = new IRCParser(myInfo, serverInfo).setCreateFake(true);
  201. if (raw == null) {
  202. raw = new Raw(this);
  203. MainFrame.getMainFrame().getFrameManager().addRaw(this, raw);
  204. }
  205. try {
  206. for(String callback : callbacks) {
  207. parser.getCallbackManager().addCallback(callback, this);
  208. }
  209. parser.getCallbackManager().addCallback("OnDataIn", raw);
  210. parser.getCallbackManager().addCallback("OnDataOut", raw);
  211. } catch (CallbackNotFound ex) {
  212. Logger.error(ErrorLevel.FATAL, "Unable to register server event handlers", ex);
  213. }
  214. away = false;
  215. awayMessage = null;
  216. frame.setAway(false);
  217. try {
  218. new Thread(parser).start();
  219. } catch (IllegalThreadStateException ex) {
  220. Logger.error(ErrorLevel.FATAL, "Unable to start IRC Parser", ex);
  221. }
  222. updateIgnoreList();
  223. }
  224. /**
  225. * Reconnects to the IRC server with a specified reason
  226. * @param reason The quit reason to send
  227. */
  228. public void reconnect(final String reason) {
  229. disconnect(reason);
  230. connect(server, port, password, ssl, profile);
  231. }
  232. /** Reconnects to the IRC server. */
  233. public void reconnect() {
  234. reconnect(Config.getOption("general", "reconnectmessage"));
  235. }
  236. /**
  237. * Updates the ignore list for this server.
  238. */
  239. public void updateIgnoreList() {
  240. parser.getIgnoreList().clear();
  241. if (configManager.hasOption("network", "ignorelist")) {
  242. for (String line : configManager.getOption("network", "ignorelist").split("\n")) {
  243. parser.getIgnoreList().add(line);
  244. }
  245. }
  246. }
  247. /**
  248. * Determines whether the server knows of the specified channel.
  249. * @param channel The channel to be checked
  250. * @return True iff the channel is known, false otherwise
  251. */
  252. public boolean hasChannel(final String channel) {
  253. return channels.containsKey(channel.toLowerCase(Locale.getDefault()));
  254. }
  255. /**
  256. * Retrieves the specified channel belonging to this server.
  257. * @param channel The channel to be retrieved
  258. * @return The appropriate channel object
  259. */
  260. public Channel getChannel(final String channel) {
  261. return channels.get(channel.toLowerCase(Locale.getDefault()));
  262. }
  263. /**
  264. * Retrieves a list of channel names belonging to this server.
  265. * @return list of channel names belonging to this server
  266. */
  267. public List<String> getChannels() {
  268. final ArrayList<String> res = new ArrayList<String>();
  269. for (String channel : channels.keySet()) {
  270. res.add(channel);
  271. }
  272. return res;
  273. }
  274. /**
  275. * Determines whether the server knows of the specified query.
  276. * @param query The query to be checked
  277. * @return True iff the query is known, false otherwise
  278. */
  279. public boolean hasQuery(final String query) {
  280. return queries.containsKey(query.toLowerCase(Locale.getDefault()));
  281. }
  282. /**
  283. * Retrieves the specified query belonging to this server.
  284. * @param query The query to be retrieved
  285. * @return The appropriate query object
  286. */
  287. public Query getQuery(final String query) {
  288. return queries.get(query.toLowerCase(Locale.getDefault()));
  289. }
  290. /**
  291. * Retrieves a list of queries belonging to this server.
  292. * @return list of queries belonging to this server
  293. */
  294. public List<String> getQueries() {
  295. final ArrayList<String> res = new ArrayList<String>();
  296. for (String query : queries.keySet()) {
  297. res.add(query);
  298. }
  299. return res;
  300. }
  301. /**
  302. * Retrieves the raw window associated with this server.
  303. * @return The raw window associated with this server.
  304. */
  305. public Raw getRaw() {
  306. return raw;
  307. }
  308. /**
  309. * Retrieves the parser used for this connection.
  310. * @return IRCParser this connection's parser
  311. */
  312. public IRCParser getParser() {
  313. return parser;
  314. }
  315. /**
  316. * Retrieves the profile that's in use for this server.
  317. * @return The profile in use by this server
  318. */
  319. public ConfigSource getProfile() {
  320. return profile;
  321. }
  322. /**
  323. * Retrieves the name of this server.
  324. * @return The name of this server
  325. */
  326. public String getName() {
  327. return this.server;
  328. }
  329. /**
  330. * Retrieves the name of this server's network.
  331. * @return The name of this server's network
  332. */
  333. public String getNetwork() {
  334. return parser.getNetworkName();
  335. }
  336. /**
  337. * Retrieves the name of this server's IRCd.
  338. * @return The name of this server's IRCd
  339. */
  340. public String getIrcd() {
  341. return parser.getIRCD(true);
  342. }
  343. /**
  344. * Returns the current away status.
  345. * @return True if the client is marked as away, false otherwise
  346. */
  347. public boolean isAway() {
  348. return away;
  349. }
  350. /**
  351. * Gets the current away message.
  352. * @return Null if the client isn't away, or a textual away message if it is
  353. */
  354. public String getAwayMessage() {
  355. return awayMessage;
  356. }
  357. /**
  358. * Returns the tab completer for this connection.
  359. * @return The tab completer for this server
  360. */
  361. public TabCompleter getTabCompleter() {
  362. return tabCompleter;
  363. }
  364. /**
  365. * Returns the internal frame belonging to this object.
  366. * @return This object's internal frame
  367. */
  368. public CommandWindow getFrame() {
  369. return frame;
  370. }
  371. /** {@inheritDoc} */
  372. @Override
  373. public ConfigManager getConfigManager() {
  374. return configManager;
  375. }
  376. /**
  377. * closes this server connection and associated windows.
  378. * @param reason reason for closing
  379. */
  380. public void close(final String reason) {
  381. // Unregister parser callbacks
  382. parser.getCallbackManager().delAllCallback(this);
  383. // Unregister frame callbacks
  384. frame.removeInternalFrameListener(this);
  385. // Disconnect from the server
  386. disconnect(reason);
  387. // Close all channel windows
  388. closeChannels();
  389. // Close all query windows
  390. closeQueries();
  391. // Close the raw window
  392. if (raw != null) {
  393. raw.close();
  394. }
  395. // Unregister ourselves with the server manager
  396. ServerManager.getServerManager().unregisterServer(this);
  397. SwingUtilities.invokeLater(new Runnable() {
  398. public void run() {
  399. // Close our own window
  400. frame.setVisible(false);
  401. MainFrame.getMainFrame().delChild(frame);
  402. frame = null;
  403. }
  404. });
  405. // Ditch the parser
  406. parser = null;
  407. }
  408. /**
  409. * Closes this server connection and associated reason, with the default
  410. * quit message.
  411. */
  412. public void close() {
  413. close(configManager.getOption("general", "quitmessage"));
  414. }
  415. /**
  416. * Disconnects from the server.
  417. * @param reason disconnect reason
  418. */
  419. public void disconnect(final String reason) {
  420. reconnect = false;
  421. if (parser != null && parser.isReady()) {
  422. parser.disconnect(reason);
  423. if (configManager.getOptionBool("general", "closechannelsonquit")) {
  424. closeChannels();
  425. } else {
  426. clearChannels();
  427. }
  428. if (configManager.getOptionBool("general", "closequeriesonquit")) {
  429. closeQueries();
  430. }
  431. }
  432. }
  433. /**
  434. * closes all open channel windows associated with this server.
  435. */
  436. private void closeChannels() {
  437. closing = true;
  438. for (Channel channel : channels.values()) {
  439. channel.closeWindow();
  440. }
  441. channels.clear();
  442. closing = false;
  443. }
  444. /**
  445. * Clears the nicklist of all open channels.
  446. */
  447. private void clearChannels() {
  448. for (Channel channel : channels.values()) {
  449. channel.resetWindow();
  450. }
  451. }
  452. /**
  453. * closes all open query windows associated with this server.
  454. */
  455. private void closeQueries() {
  456. closing = true;
  457. for (Query query : queries.values()) {
  458. query.close();
  459. }
  460. queries.clear();
  461. closing = false;
  462. }
  463. /**
  464. * Removes our reference to the raw object (presumably after it has been
  465. * closed).
  466. */
  467. public void delRaw() {
  468. MainFrame.getMainFrame().getFrameManager().delRaw(this, raw);
  469. raw = null;
  470. }
  471. /**
  472. * Removes a specific channel and window from this server.
  473. * @param chan channel to remove
  474. */
  475. public void delChannel(final String chan) {
  476. tabCompleter.removeEntry(chan);
  477. MainFrame.getMainFrame().getFrameManager().delChannel(
  478. this, channels.get(chan.toLowerCase(Locale.getDefault())));
  479. if (!closing) {
  480. channels.remove(chan.toLowerCase(Locale.getDefault()));
  481. }
  482. }
  483. /**
  484. * Adds a specific channel and window to this server.
  485. * @param chan channel to add
  486. */
  487. private void addChannel(final ChannelInfo chan) {
  488. final Channel newChan = new Channel(this, chan);
  489. tabCompleter.addEntry(chan.getName());
  490. channels.put(chan.getName().toLowerCase(), newChan);
  491. MainFrame.getMainFrame().getFrameManager().addChannel(this, newChan);
  492. SwingUtilities.invokeLater(new Runnable() {
  493. public void run() {
  494. newChan.show();
  495. }
  496. });
  497. }
  498. /**
  499. * Adds a query query to this server.
  500. * @param host host of the remote client being queried
  501. */
  502. public void addQuery(final String host) {
  503. final Query newQuery = new Query(this, host);
  504. tabCompleter.addEntry(ClientInfo.parseHost(host));
  505. queries.put(ClientInfo.parseHost(host).toLowerCase(), newQuery);
  506. MainFrame.getMainFrame().getFrameManager().addQuery(this, newQuery);
  507. }
  508. /**
  509. * Deletes a query from this server.
  510. * @param host host of the remote client being queried
  511. */
  512. public void delQuery(final String host) {
  513. tabCompleter.removeEntry(ClientInfo.parseHost(host));
  514. MainFrame.getMainFrame().getFrameManager().delQuery(this, queries.get(ClientInfo.parseHost(host).toLowerCase()));
  515. if (!closing) {
  516. queries.remove(ClientInfo.parseHost(host).toLowerCase());
  517. }
  518. }
  519. /**
  520. * Determines if the specified frame is owned by this server.
  521. * @param target internalframe to be checked for ownership
  522. * @return boolean ownership status
  523. */
  524. @Override
  525. public boolean ownsFrame(final JInternalFrame target) {
  526. // Check if it's our server frame
  527. if (frame != null && frame.equals(target)) { return true; }
  528. // Check if it's the raw frame
  529. if (raw != null && raw.ownsFrame(target)) { return true; }
  530. // Check if it's a channel frame
  531. for (Channel channel : channels.values()) {
  532. if (channel.ownsFrame(target)) { return true; }
  533. }
  534. // Check if it's a query frame
  535. for (Query query : queries.values()) {
  536. if (query.ownsFrame(target)) { return true; }
  537. }
  538. return false;
  539. }
  540. /**
  541. * Sets the specified frame as the most-recently activated.
  542. * @param source The frame that was activated
  543. */
  544. public void setActiveFrame(final FrameContainer source) {
  545. activeFrame = source;
  546. }
  547. /**
  548. * Passes the arguments to the most recently activated frame for this
  549. * server. If the frame isn't know, or isn't visible, use this frame
  550. * instead.
  551. * @param messageType The type of message to send
  552. * @param args The arguments for the message
  553. */
  554. public void addLineToActive(final String messageType, final Object... args) {
  555. if (activeFrame == null || !activeFrame.getFrame().isVisible()) {
  556. activeFrame = this;
  557. }
  558. activeFrame.getFrame().addLine(messageType, args);
  559. activeFrame.sendNotification();
  560. }
  561. /**
  562. * Passes the arguments to all frames for this server.
  563. * @param messageType The type of message to send
  564. * @param args The arguments of the message
  565. */
  566. public void addLineToAll(final String messageType, final Object... args) {
  567. for (Channel channel : channels.values()) {
  568. channel.addLine(messageType, args);
  569. channel.sendNotification();
  570. }
  571. for (Query query : queries.values()) {
  572. query.addLine(messageType, args);
  573. query.sendNotification();
  574. }
  575. addLine(messageType, args);
  576. sendNotification();
  577. }
  578. /**
  579. * Handles general server notifications (i.e., ones note tied to a
  580. * specific window). The user can select where the notifications should
  581. * go in their config.
  582. * @param messageType The type of message that is being sent
  583. * @param args The arguments for the message
  584. */
  585. public void handleNotification(final String messageType, final Object... args) {
  586. String target = "server";
  587. if (configManager.hasOption("notifications", messageType)) {
  588. final String newTarget = configManager.getOption("notifications", messageType);
  589. if ("server".equals(newTarget) || "all".equals(newTarget) || "active".equals(newTarget)) {
  590. target = newTarget;
  591. }
  592. }
  593. if ("server".equals(target)) {
  594. addLine(messageType, args);
  595. sendNotification();
  596. } else if ("all".equals(target)) {
  597. addLineToAll(messageType, args);
  598. } else if ("active".equals(target)) {
  599. addLineToActive(messageType, args);
  600. }
  601. }
  602. /**
  603. * Event when client joins a channel, creates new channel object and opens
  604. * a channel window.
  605. * @param tParser parser instance triggering event
  606. * @param cChannel Channel being joined
  607. */
  608. public void onChannelSelfJoin(final IRCParser tParser, final ChannelInfo cChannel) {
  609. if (hasChannel(cChannel.getName())) {
  610. getChannel(cChannel.getName()).setChannelInfo(cChannel);
  611. getChannel(cChannel.getName()).selfJoin();
  612. } else {
  613. addChannel(cChannel);
  614. }
  615. }
  616. /**
  617. * Private message event, creates a new query object and opens a new query
  618. * window if one doesnt exist.
  619. * @param tParser parser instance triggering event
  620. * @param message private message being received
  621. * @param host host of the remote client
  622. */
  623. public void onPrivateMessage(final IRCParser tParser, final String message,
  624. final String host) {
  625. if (!queries.containsKey(ClientInfo.parseHost(host).toLowerCase())) {
  626. addQuery(host);
  627. }
  628. }
  629. /**
  630. * Private action event, creates a new query object and opens a new query
  631. * window if one doesnt exist.
  632. * @param action action text being received
  633. * @param tParser parser instance triggering event
  634. * @param host host of remote client
  635. */
  636. public void onPrivateAction(final IRCParser tParser, final String action, final String host) {
  637. if (!queries.containsKey(ClientInfo.parseHost(host).toLowerCase())) {
  638. addQuery(host);
  639. }
  640. }
  641. /**
  642. * Called when we receive a CTCP request.
  643. * @param tParser The associated IRC parser
  644. * @param sType The type of the CTCP
  645. * @param sMessage The contents of the CTCP
  646. * @param sHost The source host
  647. */
  648. public void onPrivateCTCP(final IRCParser tParser, final String sType,
  649. final String sMessage, final String sHost) {
  650. final String[] parts = ClientInfo.parseHostFull(sHost);
  651. handleNotification("privateCTCP", parts[0], parts[1], parts[2], sType, sMessage);
  652. sendCTCPReply(parts[0], sType, sMessage);
  653. }
  654. /**
  655. * Replies to an incoming CTCP message.
  656. * @param source The source of the message
  657. * @param type The CTCP type
  658. * @param args The CTCP arguments
  659. */
  660. public void sendCTCPReply(final String source, final String type, final String args) {
  661. if (type.equalsIgnoreCase("VERSION")) {
  662. parser.sendCTCPReply(source, "VERSION", "DMDirc " + Main.VERSION
  663. + " - http://www.dmdirc.com/");
  664. } else if (type.equalsIgnoreCase("PING")) {
  665. parser.sendCTCPReply(source, "PING", args);
  666. } else if (type.equalsIgnoreCase("CLIENTINFO")) {
  667. parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO");
  668. }
  669. }
  670. /**
  671. * Called when we receive a CTCP reply.
  672. * @param tParser The associated IRC parser
  673. * @param sType The type of the CTCPR
  674. * @param sMessage The contents of the CTCPR
  675. * @param sHost The source host
  676. */
  677. public void onPrivateCTCPReply(final IRCParser tParser, final String sType,
  678. final String sMessage, final String sHost) {
  679. final String[] parts = ClientInfo.parseHostFull(sHost);
  680. handleNotification("privateCTCPreply", parts[0], parts[1], parts[2], sType, sMessage);
  681. }
  682. /**
  683. * Called when we receive a notice.
  684. * @param tParser The associated IRC parser
  685. * @param sMessage The notice content
  686. * @param sHost The source of the message
  687. */
  688. public void onPrivateNotice(final IRCParser tParser, final String sMessage,
  689. final String sHost) {
  690. final String[] parts = ClientInfo.parseHostFull(sHost);
  691. handleNotification("privateNotice", parts[0], parts[1], parts[2], sMessage);
  692. }
  693. /** {@inheritDoc} */
  694. public void onNickInUse(final IRCParser tParser, final String nickName) {
  695. final String lastNick = tParser.getMyNickname();
  696. // If our last nick is still valid, ignore the in use message
  697. if (!lastNick.equalsIgnoreCase(nickName)) {
  698. return;
  699. }
  700. String newNick = null;
  701. if (profile.hasOption("profile", "altnicks")) {
  702. final String[] alts = profile.getOption("profile", "altnicks").split("\n");
  703. int offset = -1;
  704. if (!lastNick.equalsIgnoreCase(profile.getOption("profile", "nickname"))) {
  705. for (String alt : alts) {
  706. offset++;
  707. if (alt.equalsIgnoreCase(lastNick)) {
  708. break;
  709. }
  710. }
  711. }
  712. if (offset + 1 < alts.length) {
  713. newNick = alts[offset + 1];
  714. }
  715. }
  716. if (newNick == null) {
  717. newNick = lastNick + (int) (Math.random()*10);
  718. }
  719. parser.setNickname(newNick);
  720. }
  721. /**
  722. * Called when the parser has determined the network and ircd version.
  723. * @param tParser The associated IRC parser
  724. * @param networkName The name of the network
  725. * @param ircdVersion The version of the IRCd
  726. * @param ircdType The type of the IRCd
  727. */
  728. public void onGotNetwork(final IRCParser tParser, final String networkName,
  729. final String ircdVersion, final String ircdType) {
  730. configManager = new ConfigManager(ircdType, networkName, this.server);
  731. updateIgnoreList();
  732. }
  733. /**
  734. * Called when the server's MOTD is starting to be sent.
  735. * @param tParser The associated IRC parser
  736. * @param sData The message at the start of the MOTD
  737. */
  738. public void onMOTDStart(final IRCParser tParser, final String sData) {
  739. addLine("motdStart", sData);
  740. sendNotification();
  741. }
  742. /**
  743. * Called when a line of the server's MOTD has been received.
  744. * @param tParser The associated IRC parser
  745. * @param sData The line of the MOTD
  746. */
  747. public void onMOTDLine(final IRCParser tParser, final String sData) {
  748. addLine("motdLine", sData);
  749. sendNotification();
  750. }
  751. /**
  752. * Called when the server's MOTD is over.
  753. * @param tParser The associated IRC parser
  754. * @param noMOTD Indicates that there was no MOTD
  755. */
  756. public void onMOTDEnd(final IRCParser tParser, final boolean noMOTD) {
  757. addLine("motdEnd", "End of server's MOTD.");
  758. sendNotification();
  759. }
  760. /**
  761. * Called when we receive a numeric response from the server.
  762. * @param tParser The associated IRC parser
  763. * @param numeric The numeric of the message
  764. * @param line The tokenised line
  765. */
  766. public void onNumeric(final IRCParser tParser, final int numeric,
  767. final String[] line) {
  768. final String withIrcd = "numeric_" + tParser.getIRCD(true) + "_" + numeric;
  769. final String sansIrcd = "numeric_" + numeric;
  770. String target = null;
  771. if (Formatter.hasFormat(withIrcd)) {
  772. target = withIrcd;
  773. } else if (Formatter.hasFormat(sansIrcd)) {
  774. target = sansIrcd;
  775. } else if (Formatter.hasFormat("numeric_unknown")) {
  776. target = "numeric_unknown";
  777. }
  778. if (target != null) {
  779. handleNotification(target, (Object[]) line);
  780. }
  781. if (numeric == 1) {
  782. ActionManager.processEvent(CoreActionType.SERVER_CONNECTED, null, this);
  783. }
  784. ActionManager.processEvent(CoreActionType.SERVER_NUMERIC, null, this, Integer.valueOf(numeric), line);
  785. }
  786. /**
  787. * Called when our away state changes.
  788. * @param tParser The IRC parser for this server
  789. * @param currentState The current (new?) away state
  790. * @param reason The textual reason for being away, if any
  791. */
  792. public void onAwayState(final IRCParser tParser, final boolean currentState,
  793. final String reason) {
  794. if (currentState) {
  795. away = true;
  796. awayMessage = reason;
  797. ActionManager.processEvent(CoreActionType.SERVER_AWAY, null, this, awayMessage);
  798. } else {
  799. away = false;
  800. awayMessage = null;
  801. ActionManager.processEvent(CoreActionType.SERVER_BACK, null, this);
  802. }
  803. frame.setAway(away);
  804. }
  805. /**
  806. * Called when the IRC socket is closed for any reason.
  807. * @param tParser The IRC parser for this server
  808. */
  809. public void onSocketClosed(final IRCParser tParser) {
  810. handleNotification("socketClosed", this.server);
  811. if (configManager.getOptionBool("general", "closechannelsondisconnect")) {
  812. closeChannels();
  813. }
  814. if (configManager.getOptionBool("general", "closequeriesondisconnect")) {
  815. closeQueries();
  816. }
  817. if (reconnect && Config.getOptionBool("general", "reconnectondisconnect")) {
  818. reconnect();
  819. }
  820. }
  821. /**
  822. * Called when the parser encounters an error trying to connect.
  823. * @param tParser The Parser for this server
  824. * @param errorInfo Information about the error.
  825. */
  826. public void onConnectError(final IRCParser tParser, final ParserError errorInfo) {
  827. String description = "";
  828. if (errorInfo.getException() == null) {
  829. description = errorInfo.getData();
  830. } else {
  831. final Exception ex = errorInfo.getException();
  832. if (ex instanceof java.net.UnknownHostException) {
  833. description = "Unknown host (unable to resolve)";
  834. } else if (ex instanceof java.net.NoRouteToHostException) {
  835. description = "No route to host";
  836. } else if (ex instanceof java.net.SocketException) {
  837. description = ex.getMessage();
  838. } else {
  839. Logger.error(ErrorLevel.TRIVIAL, "Unknown socket error", ex);
  840. description = "Unknown error: " + ex.getMessage();
  841. }
  842. }
  843. handleNotification("connectError", server, description);
  844. if (Config.getOptionBool("general", "reconnectonconnectfailure")) {
  845. final int delay = Config.getOptionInt("general", "reconnectdelay", 5);
  846. handleNotification("connectRetry", server, delay);
  847. new Timer().schedule(new TimerTask() {
  848. public void run() {
  849. reconnect();
  850. }
  851. }, delay * 1000);
  852. }
  853. }
  854. /**
  855. * Called when the parser misses a ping reply from the server.
  856. * @param parser The IRC parser for this server
  857. */
  858. public void onPingFailed(final IRCParser parser) {
  859. MainFrame.getMainFrame().getStatusBar().setMessage("No ping reply from "
  860. + this.server + " for over "
  861. + Math.floor(parser.getPingTime(false) / 1000.0) + " seconds.", null, 10);
  862. ActionManager.processEvent(CoreActionType.SERVER_NOPING, null, this,
  863. Long.valueOf(parser.getPingTime(false)));
  864. if (parser.getPingTime(false) >= configManager.getOptionInt("server", "pingtimeout", 60000)) {
  865. handleNotification("stonedServer", server);
  866. reconnect();
  867. }
  868. }
  869. /** {@inheritDoc} */
  870. public void onPingSuccess(final IRCParser tParser) {
  871. ActionManager.processEvent(CoreActionType.SERVER_GOTPING, null, this,
  872. Long.valueOf(parser.getServerLag()));
  873. }
  874. /** {@inheritDoc} */
  875. public void onAwayStateOther(final IRCParser tParser,
  876. final ClientInfo client, final boolean state) {
  877. for (Channel chan : channels.values()) {
  878. chan.onAwayStateOther(tParser, client, state);
  879. }
  880. }
  881. /**
  882. * Parses the parser error and notifies the Logger.
  883. * @param tParser parser instance triggering event
  884. * @param errorInfo Parser error object
  885. */
  886. public void onErrorInfo(final IRCParser tParser, final ParserError errorInfo) {
  887. ErrorLevel errorLevel;
  888. if (errorInfo.isFatal()) {
  889. errorLevel = ErrorLevel.FATAL;
  890. } else if (errorInfo.isError()) {
  891. errorLevel = ErrorLevel.ERROR;
  892. } else if (errorInfo.isWarning()) {
  893. errorLevel = ErrorLevel.WARNING;
  894. } else {
  895. Logger.error(ErrorLevel.WARNING,
  896. "Unknown error level for parser error: " + errorInfo.getData());
  897. return;
  898. }
  899. if (errorInfo.isException()) {
  900. Logger.error(errorLevel, errorInfo.getData(), errorInfo.getException());
  901. } else {
  902. Logger.error(errorLevel, errorInfo.getData());
  903. }
  904. }
  905. /**
  906. * Returns this server's name.
  907. * @return A string representation of this server (i.e., its name)
  908. */
  909. public String toString() {
  910. return this.server;
  911. }
  912. /**
  913. * Returns the server instance associated with this frame.
  914. *
  915. * @return the associated server connection
  916. */
  917. public Server getServer() {
  918. return this;
  919. }
  920. }