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();
279 Set<Character> channelTypes = Sets.newHashSet();
282 Reply reply = connectionHandler.readReply();
283 System.err.println("<< " + reply);
284 String command = reply.command();
285 List<String> parameters = reply.parameters();
287 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
288 if (command.equals("001")) {
289 connectionStatus |= 0x01;
290 } else if (command.equals("002")) {
291 connectionStatus |= 0x02;
292 } else if (command.equals("003")) {
293 connectionStatus |= 0x04;
294 } else if (command.equals("004")) {
295 connectionStatus |= 0x08;
297 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
298 } else if (command.equals("005")) {
299 for (String parameter : parameters) {
300 if (parameter.startsWith("PREFIX=")) {
301 int openParen = parameter.indexOf('(');
302 int closeParen = parameter.indexOf(')');
303 if ((openParen != -1) && (closeParen != -1)) {
304 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
305 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
306 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
307 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
310 } else if (parameter.startsWith("CHANTYPES=")) {
311 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
312 channelTypes.add(parameter.charAt(typeIndex));
317 /* 375, 372, and 376 handle the server’s MOTD. */
318 } else if (command.equals("375")) {
320 motd.append(parameters.get(1)).append('\n');
321 } else if (command.equals("372")) {
322 motd.append(parameters.get(1)).append('\n');
323 } else if (command.equals("376")) {
324 motd.append(parameters.get(1)).append('\n');
325 eventBus.post(new MotdReceived(this, motd.toString()));
328 /* 43x replies are for nick change errors. */
329 } else if (command.equals("431")) {
330 eventBus.post(new NoNicknameGivenReceived(this, reply));
331 } else if (command.equals("433")) {
332 if (connectionStatus == 0) {
333 nickname = nicknameChooser.getNickname();
334 connectionHandler.sendCommand("NICK", nickname);
336 eventBus.post(new NicknameInUseReceived(this, reply));
340 } else if (command.equalsIgnoreCase("JOIN")) {
341 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
342 } else if (command.equals("331")) {
343 /* no topic is set. */
344 } else if (command.equals("332")) {
345 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
346 } else if (command.equals("353")) {
347 String channel = parameters.get(2);
348 for (String nickname : parameters.get(3).split(" ")) {
349 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
350 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
352 nicks.add(new Nickname(nickname, ""));
355 } else if (command.equals("366")) {
356 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
357 System.out.println("Found Nicknames: " + nicks);
360 /* common channel join errors. */
361 } else if (command.equals("474")) {
362 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
363 } else if (command.equals("473")) {
364 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
365 } else if (command.equals("475")) {
366 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
368 /* basic connection housekeeping. */
369 } else if (command.equalsIgnoreCase("PING")) {
370 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
372 /* okay, everything else. */
374 eventBus.post(new UnknownReplyReceived(this, reply));
377 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
378 /* connection succeeded! */
379 eventBus.post(new ConnectionEstablished(this));
381 oldConnectionStatus = connectionStatus;
383 } catch (IOException ioe1) {
384 ioe1.printStackTrace();
386 System.out.println("Closing Connection.");
388 Closeables.close(connectionHandler, true);
389 } catch (IOException ioe1) {
390 /* will not be thrown. */
401 * Returns an item from the list, or {@link Optional#absent()} if the list is
402 * shorter than required for the given index.
405 * The list to get an item from
407 * The index of the item
409 * The type of the list items
410 * @return This list item wrapped in an {@link Optional}, or {@link
411 * Optional#absent()} if the list is not long enough
413 private static <T> Optional<T> getOptional(List<T> list, int index) {
414 if (index < list.size()) {
415 return Optional.fromNullable(list.get(index));
417 return Optional.absent();
420 /** Handles input and output for the connection. */
421 private class ConnectionHandler implements Closeable {
423 /** The output stream of the connection. */
424 private final OutputStream outputStream;
426 /** The input stream of the connection. */
427 private final BufferedReader inputStreamReader;
430 * Creates a new connection handler for the given input stream and output
434 * The input stream of the connection
435 * @param outputStream
436 * The output stream of the connection
437 * @throws UnsupportedEncodingException
438 * if the encoding (currently “UTF-8”) is not valid
440 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
441 this.outputStream = outputStream;
442 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
450 * Sends a command with the given parameters, skipping all {@link
451 * Optional#absent()} optionals.
454 * The command to send
457 * @throws IOException
458 * if an I/O error occurs
460 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
461 List<String> setParameters = new ArrayList<String>();
462 for (Optional<String> maybeSetParameter : parameters) {
463 if (maybeSetParameter.isPresent()) {
464 setParameters.add(maybeSetParameter.get());
467 sendCommand(command, setParameters.toArray(new String[0]));
471 * Sends a command with the given parameters.
474 * The command to send
476 * The parameters of the command
477 * @throws IOException
478 * if an I/O error occurs
479 * @throws IllegalArgumentException
480 * if any parameter but that last contains a space character
482 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
483 StringBuilder commandBuilder = new StringBuilder();
485 commandBuilder.append(command);
486 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
487 String parameter = parameters[parameterIndex];
488 /* space is only allowed in the last parameter. */
489 commandBuilder.append(' ');
490 if (parameter.contains(" ")) {
491 if (parameterIndex == (parameters.length - 1)) {
492 commandBuilder.append(':');
494 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
497 commandBuilder.append(parameter);
500 System.out.println(">> " + commandBuilder.toString());
501 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
502 outputStream.flush();
506 * Reads a line of reply from the connection.
509 * @throws IOException
510 * if an I/O error occurs
511 * @throws EOFException
514 public Reply readReply() throws IOException, EOFException {
515 String line = inputStreamReader.readLine();
517 throw new EOFException();
520 return Reply.parseLine(line);
528 public void close() throws IOException {
529 Closeables.close(outputStream, true);
530 Closeables.close(inputStreamReader, true);