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 javax.net.SocketFactory;
38 import net.pterodactylus.irc.event.ChannelJoined;
39 import net.pterodactylus.irc.event.ChannelNicknames;
40 import net.pterodactylus.irc.event.ChannelNotJoined;
41 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
42 import net.pterodactylus.irc.event.ChannelTopic;
43 import net.pterodactylus.irc.event.ConnectionEstablished;
44 import net.pterodactylus.irc.event.ConnectionFailed;
45 import net.pterodactylus.irc.event.MotdReceived;
46 import net.pterodactylus.irc.event.NicknameInUseReceived;
47 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
48 import net.pterodactylus.irc.event.UnknownReplyReceived;
49 import net.pterodactylus.irc.util.RandomNickname;
51 import com.beust.jcommander.internal.Maps;
52 import com.beust.jcommander.internal.Sets;
53 import com.google.common.base.Optional;
54 import com.google.common.eventbus.EventBus;
55 import com.google.common.eventbus.Subscribe;
56 import com.google.common.io.Closeables;
57 import com.google.common.util.concurrent.AbstractExecutionThreadService;
58 import com.google.common.util.concurrent.Service;
61 * A connection to an IRC server.
63 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
65 public class Connection extends AbstractExecutionThreadService implements Service {
68 private final EventBus eventBus;
70 /** The socket factory. */
71 private final SocketFactory socketFactory;
73 /** The hostname to connect to. */
74 private final String hostname;
76 /** The port to connect to. */
77 private final int port;
79 /** The nickname chooser. */
80 private NicknameChooser nicknameChooser = new NicknameChooser() {
83 public String getNickname() {
84 return RandomNickname.get();
89 private String nickname = null;
92 private Optional<String> username = Optional.absent();
95 private Optional<String> realName = Optional.absent();
97 /** The optional password for the connection. */
98 private Optional<String> password = Optional.absent();
100 /** The connection handler. */
101 private ConnectionHandler connectionHandler;
104 * Creates a new connection.
108 * @param socketFactory
111 * The hostname of the IRC server
113 * The port number of the IRC server
115 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
116 this.eventBus = eventBus;
117 this.socketFactory = socketFactory;
118 this.hostname = hostname;
127 * Returns the nickname that is currently in use by this connection. The
128 * nickname is only available once the connection has been {@link #start()}ed.
130 * @return The current nickname
132 public String nickname() {
141 * Sets the nickname chooser. The nickname chooser is only used during the
142 * creation of the connection.
144 * @param nicknameChooser
145 * The nickname chooser
146 * @return This connection
148 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
149 this.nicknameChooser = nicknameChooser;
154 * Sets the username to use.
157 * The username to use
160 public Connection username(String username) {
161 this.username = Optional.fromNullable(username);
166 * Sets the real name to use.
169 * The real name to use
170 * @return This connection
172 public Connection realName(String realName) {
173 this.realName = Optional.fromNullable(realName);
178 * Sets the optional password for the connection.
181 * The password for the connection
182 * @return This connection
184 public Connection password(String password) {
185 this.password = Optional.fromNullable(password);
194 * Joins the given channel.
197 * The channel to join
198 * @return {@code true} if the channel was joined, {@code false} otherwise
200 public boolean joinChannel(final String channel) {
201 final SynchronousQueue<Boolean> result = new SynchronousQueue<Boolean>();
202 Object eventHandler = new Object() {
205 public void channelJoined(ChannelJoined channelJoined) throws InterruptedException {
206 if (!channelJoined.channel().equalsIgnoreCase(channel)) {
209 Optional<String> nickname = channelJoined.client().nick();
210 if (!nickname.isPresent() || (nickname.isPresent() && nickname().equalsIgnoreCase(nickname.get()))) {
211 eventBus.unregister(this);
217 public void channelNotJoined(ChannelNotJoined channelNotJoined) throws InterruptedException {
218 if (!channelNotJoined.channel().equalsIgnoreCase(channel)) {
221 eventBus.unregister(this);
225 eventBus.register(eventHandler);
227 connectionHandler.sendCommand("JOIN", channel);
228 return result.take();
229 } catch (IOException ioe1) {
230 eventBus.unregister(eventHandler);
231 } catch (InterruptedException ie1) {
232 /* TODO - how to handle? */
238 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
242 protected void startUp() throws IllegalStateException {
243 checkState(username.isPresent(), "username must be set");
244 checkState(realName.isPresent(), "realName must be set");
248 protected void run() {
250 /* connect to remote socket. */
252 Socket socket = socketFactory.createSocket(hostname, port);
253 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
255 /* register connection. */
256 if (password.isPresent()) {
257 connectionHandler.sendCommand("PASSWORD", password.get());
259 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
260 nickname = nicknameChooser.getNickname();
261 connectionHandler.sendCommand("NICK", nickname);
263 } catch (IOException ioe1) {
264 eventBus.post(new ConnectionFailed(this, ioe1));
268 /* now read replies and react. */
270 /* some status variables. */
271 int oldConnectionStatus = 0;
272 int connectionStatus = 0;
273 boolean connected = true;
274 StringBuilder motd = new StringBuilder();
275 Set<Nickname> nicks = Sets.newHashSet();
278 Map<String, String> nickPrefixes = Maps.newHashMap();
281 Reply reply = connectionHandler.readReply();
282 System.err.println("<< " + reply);
283 String command = reply.command();
284 List<String> parameters = reply.parameters();
286 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
287 if (command.equals("001")) {
288 connectionStatus |= 0x01;
289 } else if (command.equals("002")) {
290 connectionStatus |= 0x02;
291 } else if (command.equals("003")) {
292 connectionStatus |= 0x04;
293 } else if (command.equals("004")) {
294 connectionStatus |= 0x08;
296 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
297 } else if (command.equals("005")) {
298 for (String parameter : parameters) {
299 if (parameter.startsWith("PREFIX=")) {
300 int openParen = parameter.indexOf('(');
301 int closeParen = parameter.indexOf(')');
302 if ((openParen != -1) && (closeParen != -1)) {
303 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
304 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
305 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
306 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
312 /* 375, 372, and 376 handle the server’s MOTD. */
313 } else if (command.equals("375")) {
315 motd.append(parameters.get(1)).append('\n');
316 } else if (command.equals("372")) {
317 motd.append(parameters.get(1)).append('\n');
318 } else if (command.equals("376")) {
319 motd.append(parameters.get(1)).append('\n');
320 eventBus.post(new MotdReceived(this, motd.toString()));
323 /* 43x replies are for nick change errors. */
324 } else if (command.equals("431")) {
325 eventBus.post(new NoNicknameGivenReceived(this, reply));
326 } else if (command.equals("433")) {
327 if (connectionStatus == 0) {
328 nickname = nicknameChooser.getNickname();
329 connectionHandler.sendCommand("NICK", nickname);
331 eventBus.post(new NicknameInUseReceived(this, reply));
335 } else if (command.equalsIgnoreCase("JOIN")) {
336 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
337 } else if (command.equals("331")) {
338 /* no topic is set. */
339 } else if (command.equals("332")) {
340 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
341 } else if (command.equals("353")) {
342 String channel = parameters.get(2);
343 for (String nickname : parameters.get(3).split(" ")) {
344 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
345 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
347 nicks.add(new Nickname(nickname, ""));
350 } else if (command.equals("366")) {
351 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
352 System.out.println("Found Nicknames: " + nicks);
355 /* common channel join errors. */
356 } else if (command.equals("474")) {
357 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
358 } else if (command.equals("473")) {
359 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
360 } else if (command.equals("475")) {
361 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
363 /* basic connection housekeeping. */
364 } else if (command.equalsIgnoreCase("PING")) {
365 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
367 /* okay, everything else. */
369 eventBus.post(new UnknownReplyReceived(this, reply));
372 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
373 /* connection succeeded! */
374 eventBus.post(new ConnectionEstablished(this));
376 oldConnectionStatus = connectionStatus;
378 } catch (IOException ioe1) {
379 ioe1.printStackTrace();
381 System.out.println("Closing Connection.");
383 Closeables.close(connectionHandler, true);
384 } catch (IOException ioe1) {
385 /* will not be thrown. */
396 * Returns an item from the list, or {@link Optional#absent()} if the list is
397 * shorter than required for the given index.
400 * The list to get an item from
402 * The index of the item
404 * The type of the list items
405 * @return This list item wrapped in an {@link Optional}, or {@link
406 * Optional#absent()} if the list is not long enough
408 private static <T> Optional<T> getOptional(List<T> list, int index) {
409 if (index < list.size()) {
410 return Optional.fromNullable(list.get(index));
412 return Optional.absent();
415 /** Handles input and output for the connection. */
416 private class ConnectionHandler implements Closeable {
418 /** The output stream of the connection. */
419 private final OutputStream outputStream;
421 /** The input stream of the connection. */
422 private final BufferedReader inputStreamReader;
425 * Creates a new connection handler for the given input stream and output
429 * The input stream of the connection
430 * @param outputStream
431 * The output stream of the connection
432 * @throws UnsupportedEncodingException
433 * if the encoding (currently “UTF-8”) is not valid
435 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
436 this.outputStream = outputStream;
437 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
445 * Sends a command with the given parameters, skipping all {@link
446 * Optional#absent()} optionals.
449 * The command to send
452 * @throws IOException
453 * if an I/O error occurs
455 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
456 List<String> setParameters = new ArrayList<String>();
457 for (Optional<String> maybeSetParameter : parameters) {
458 if (maybeSetParameter.isPresent()) {
459 setParameters.add(maybeSetParameter.get());
462 sendCommand(command, setParameters.toArray(new String[0]));
466 * Sends a command with the given parameters.
469 * The command to send
471 * The parameters of the command
472 * @throws IOException
473 * if an I/O error occurs
474 * @throws IllegalArgumentException
475 * if any parameter but that last contains a space character
477 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
478 StringBuilder commandBuilder = new StringBuilder();
480 commandBuilder.append(command);
481 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
482 String parameter = parameters[parameterIndex];
483 /* space is only allowed in the last parameter. */
484 commandBuilder.append(' ');
485 if (parameter.contains(" ")) {
486 if (parameterIndex == (parameters.length - 1)) {
487 commandBuilder.append(':');
489 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
492 commandBuilder.append(parameter);
495 System.out.println(">> " + commandBuilder.toString());
496 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
497 outputStream.flush();
501 * Reads a line of reply from the connection.
504 * @throws IOException
505 * if an I/O error occurs
506 * @throws EOFException
509 public Reply readReply() throws IOException, EOFException {
510 String line = inputStreamReader.readLine();
512 throw new EOFException();
515 return Reply.parseLine(line);
523 public void close() throws IOException {
524 Closeables.close(outputStream, true);
525 Closeables.close(inputStreamReader, true);