2 * XdccDownloader - Connection.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.irc;
20 import static com.google.common.base.Preconditions.checkState;
22 import java.io.BufferedReader;
23 import java.io.Closeable;
24 import java.io.EOFException;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.OutputStream;
29 import java.io.UnsupportedEncodingException;
30 import java.net.Socket;
31 import java.util.ArrayList;
32 import java.util.List;
35 import java.util.concurrent.SynchronousQueue;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38 import javax.net.SocketFactory;
40 import net.pterodactylus.irc.event.ChannelJoined;
41 import net.pterodactylus.irc.event.ChannelMessageReceived;
42 import net.pterodactylus.irc.event.ChannelNicknames;
43 import net.pterodactylus.irc.event.ChannelNotJoined;
44 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
45 import net.pterodactylus.irc.event.ChannelTopic;
46 import net.pterodactylus.irc.event.ConnectionEstablished;
47 import net.pterodactylus.irc.event.ConnectionFailed;
48 import net.pterodactylus.irc.event.MotdReceived;
49 import net.pterodactylus.irc.event.NicknameInUseReceived;
50 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
51 import net.pterodactylus.irc.event.PrivateMessageReceived;
52 import net.pterodactylus.irc.event.UnknownReplyReceived;
53 import net.pterodactylus.irc.util.RandomNickname;
55 import com.beust.jcommander.internal.Maps;
56 import com.beust.jcommander.internal.Sets;
57 import com.google.common.base.Optional;
58 import com.google.common.eventbus.EventBus;
59 import com.google.common.eventbus.Subscribe;
60 import com.google.common.io.Closeables;
61 import com.google.common.util.concurrent.AbstractExecutionThreadService;
62 import com.google.common.util.concurrent.Service;
65 * A connection to an IRC server.
67 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69 public class Connection extends AbstractExecutionThreadService implements Service {
72 private static final Logger logger = Logger.getLogger(Connection.class.getName());
75 private final EventBus eventBus;
77 /** The socket factory. */
78 private final SocketFactory socketFactory;
80 /** The hostname to connect to. */
81 private final String hostname;
83 /** The port to connect to. */
84 private final int port;
86 /** The nickname chooser. */
87 private NicknameChooser nicknameChooser = new NicknameChooser() {
90 public String getNickname() {
91 return RandomNickname.get();
96 private String nickname = null;
99 private Optional<String> username = Optional.absent();
101 /** The real name. */
102 private Optional<String> realName = Optional.absent();
104 /** The optional password for the connection. */
105 private Optional<String> password = Optional.absent();
107 /** The connection handler. */
108 private ConnectionHandler connectionHandler;
111 * Creates a new connection.
115 * @param socketFactory
118 * The hostname of the IRC server
120 * The port number of the IRC server
122 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
123 this.eventBus = eventBus;
124 this.socketFactory = socketFactory;
125 this.hostname = hostname;
134 * Returns the nickname that is currently in use by this connection. The
135 * nickname is only available once the connection has been {@link #start()}ed.
137 * @return The current nickname
139 public String nickname() {
148 * Sets the nickname chooser. The nickname chooser is only used during the
149 * creation of the connection.
151 * @param nicknameChooser
152 * The nickname chooser
153 * @return This connection
155 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
156 this.nicknameChooser = nicknameChooser;
161 * Sets the username to use.
164 * The username to use
167 public Connection username(String username) {
168 this.username = Optional.fromNullable(username);
173 * Sets the real name to use.
176 * The real name to use
177 * @return This connection
179 public Connection realName(String realName) {
180 this.realName = Optional.fromNullable(realName);
185 * Sets the optional password for the connection.
188 * The password for the connection
189 * @return This connection
191 public Connection password(String password) {
192 this.password = Optional.fromNullable(password);
201 * Joins the given channel.
204 * The channel to join
205 * @return {@code true} if the channel was joined, {@code false} otherwise
207 public boolean joinChannel(final String channel) {
208 final SynchronousQueue<Boolean> result = new SynchronousQueue<Boolean>();
209 Object eventHandler = new Object() {
212 public void channelJoined(ChannelJoined channelJoined) throws InterruptedException {
213 if (!channelJoined.channel().equalsIgnoreCase(channel)) {
216 Optional<String> nickname = channelJoined.client().nick();
217 if (!nickname.isPresent() || (nickname.isPresent() && nickname().equalsIgnoreCase(nickname.get()))) {
218 eventBus.unregister(this);
224 public void channelNotJoined(ChannelNotJoined channelNotJoined) throws InterruptedException {
225 if (!channelNotJoined.channel().equalsIgnoreCase(channel)) {
228 eventBus.unregister(this);
232 eventBus.register(eventHandler);
234 connectionHandler.sendCommand("JOIN", channel);
235 return result.take();
236 } catch (IOException ioe1) {
237 eventBus.unregister(eventHandler);
238 } catch (InterruptedException ie1) {
239 /* TODO - how to handle? */
245 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
249 protected void startUp() throws IllegalStateException {
250 checkState(username.isPresent(), "username must be set");
251 checkState(realName.isPresent(), "realName must be set");
255 protected void run() {
257 /* connect to remote socket. */
259 Socket socket = socketFactory.createSocket(hostname, port);
260 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
262 /* register connection. */
263 if (password.isPresent()) {
264 connectionHandler.sendCommand("PASSWORD", password.get());
266 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
267 nickname = nicknameChooser.getNickname();
268 connectionHandler.sendCommand("NICK", nickname);
270 } catch (IOException ioe1) {
271 eventBus.post(new ConnectionFailed(this, ioe1));
275 /* now read replies and react. */
277 /* some status variables. */
278 int oldConnectionStatus = 0;
279 int connectionStatus = 0;
280 boolean connected = true;
281 StringBuilder motd = new StringBuilder();
282 Set<Nickname> nicks = Sets.newHashSet();
285 Map<String, String> nickPrefixes = Maps.newHashMap();
286 Set<Character> channelTypes = Sets.newHashSet();
289 Reply reply = connectionHandler.readReply();
290 logger.finest(String.format("<< %s", reply));
291 String command = reply.command();
292 List<String> parameters = reply.parameters();
294 /* most common events. */
295 if (command.equalsIgnoreCase("PRIVMSG")) {
296 String recipient = parameters.get(0);
297 if (!channelTypes.contains(recipient.charAt(0))) {
298 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), parameters.get(1)));
300 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), parameters.get(1)));
303 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
304 } else if (command.equals("001")) {
305 connectionStatus |= 0x01;
306 } else if (command.equals("002")) {
307 connectionStatus |= 0x02;
308 } else if (command.equals("003")) {
309 connectionStatus |= 0x04;
310 } else if (command.equals("004")) {
311 connectionStatus |= 0x08;
313 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
314 } else if (command.equals("005")) {
315 for (String parameter : parameters) {
316 if (parameter.startsWith("PREFIX=")) {
317 int openParen = parameter.indexOf('(');
318 int closeParen = parameter.indexOf(')');
319 if ((openParen != -1) && (closeParen != -1)) {
320 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
321 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
322 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
323 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
325 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
327 } else if (parameter.startsWith("CHANTYPES=")) {
328 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
329 channelTypes.add(parameter.charAt(typeIndex));
331 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
335 /* 375, 372, and 376 handle the server’s MOTD. */
336 } else if (command.equals("375")) {
338 motd.append(parameters.get(1)).append('\n');
339 } else if (command.equals("372")) {
340 motd.append(parameters.get(1)).append('\n');
341 } else if (command.equals("376")) {
342 motd.append(parameters.get(1)).append('\n');
343 eventBus.post(new MotdReceived(this, motd.toString()));
346 /* 43x replies are for nick change errors. */
347 } else if (command.equals("431")) {
348 eventBus.post(new NoNicknameGivenReceived(this, reply));
349 } else if (command.equals("433")) {
350 if (connectionStatus == 0) {
351 nickname = nicknameChooser.getNickname();
352 connectionHandler.sendCommand("NICK", nickname);
354 eventBus.post(new NicknameInUseReceived(this, reply));
358 } else if (command.equalsIgnoreCase("JOIN")) {
359 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
360 } else if (command.equals("331")) {
361 /* no topic is set. */
362 } else if (command.equals("332")) {
363 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
364 } else if (command.equals("353")) {
365 String channel = parameters.get(2);
366 for (String nickname : parameters.get(3).split(" ")) {
367 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
368 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
370 nicks.add(new Nickname(nickname, ""));
373 } else if (command.equals("366")) {
374 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
377 /* common channel join errors. */
378 } else if (command.equals("474")) {
379 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
380 } else if (command.equals("473")) {
381 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
382 } else if (command.equals("475")) {
383 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
385 /* basic connection housekeeping. */
386 } else if (command.equalsIgnoreCase("PING")) {
387 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
389 /* okay, everything else. */
391 eventBus.post(new UnknownReplyReceived(this, reply));
394 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
395 /* connection succeeded! */
396 eventBus.post(new ConnectionEstablished(this));
398 oldConnectionStatus = connectionStatus;
400 } catch (IOException ioe1) {
401 logger.log(Level.WARNING, "I/O error", ioe1);
403 logger.info("Closing Connection.");
405 Closeables.close(connectionHandler, true);
406 } catch (IOException ioe1) {
407 /* will not be thrown. */
418 * Returns an item from the list, or {@link Optional#absent()} if the list is
419 * shorter than required for the given index.
422 * The list to get an item from
424 * The index of the item
426 * The type of the list items
427 * @return This list item wrapped in an {@link Optional}, or {@link
428 * Optional#absent()} if the list is not long enough
430 private static <T> Optional<T> getOptional(List<T> list, int index) {
431 if (index < list.size()) {
432 return Optional.fromNullable(list.get(index));
434 return Optional.absent();
437 /** Handles input and output for the connection. */
438 private class ConnectionHandler implements Closeable {
440 /** The output stream of the connection. */
441 private final OutputStream outputStream;
443 /** The input stream of the connection. */
444 private final BufferedReader inputStreamReader;
447 * Creates a new connection handler for the given input stream and output
451 * The input stream of the connection
452 * @param outputStream
453 * The output stream of the connection
454 * @throws UnsupportedEncodingException
455 * if the encoding (currently “UTF-8”) is not valid
457 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
458 this.outputStream = outputStream;
459 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
467 * Sends a command with the given parameters, skipping all {@link
468 * Optional#absent()} optionals.
471 * The command to send
474 * @throws IOException
475 * if an I/O error occurs
477 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
478 List<String> setParameters = new ArrayList<String>();
479 for (Optional<String> maybeSetParameter : parameters) {
480 if (maybeSetParameter.isPresent()) {
481 setParameters.add(maybeSetParameter.get());
484 sendCommand(command, setParameters.toArray(new String[0]));
488 * Sends a command with the given parameters.
491 * The command to send
493 * The parameters of the command
494 * @throws IOException
495 * if an I/O error occurs
496 * @throws IllegalArgumentException
497 * if any parameter but that last contains a space character
499 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
500 StringBuilder commandBuilder = new StringBuilder();
502 commandBuilder.append(command);
503 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
504 String parameter = parameters[parameterIndex];
505 /* space is only allowed in the last parameter. */
506 commandBuilder.append(' ');
507 if (parameter.contains(" ")) {
508 if (parameterIndex == (parameters.length - 1)) {
509 commandBuilder.append(':');
511 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
514 commandBuilder.append(parameter);
517 logger.finest(String.format(">> %s", commandBuilder));
518 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
519 outputStream.flush();
523 * Reads a line of reply from the connection.
526 * @throws IOException
527 * if an I/O error occurs
528 * @throws EOFException
531 public Reply readReply() throws IOException, EOFException {
532 String line = inputStreamReader.readLine();
534 throw new EOFException();
537 return Reply.parseLine(line);
545 public void close() throws IOException {
546 Closeables.close(outputStream, true);
547 Closeables.close(inputStreamReader, true);