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.ChannelMessageReceived;
40 import net.pterodactylus.irc.event.ChannelNicknames;
41 import net.pterodactylus.irc.event.ChannelNotJoined;
42 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
43 import net.pterodactylus.irc.event.ChannelTopic;
44 import net.pterodactylus.irc.event.ConnectionEstablished;
45 import net.pterodactylus.irc.event.ConnectionFailed;
46 import net.pterodactylus.irc.event.MotdReceived;
47 import net.pterodactylus.irc.event.NicknameInUseReceived;
48 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
49 import net.pterodactylus.irc.event.PrivateMessageReceived;
50 import net.pterodactylus.irc.event.UnknownReplyReceived;
51 import net.pterodactylus.irc.util.RandomNickname;
53 import com.beust.jcommander.internal.Maps;
54 import com.beust.jcommander.internal.Sets;
55 import com.google.common.base.Optional;
56 import com.google.common.eventbus.EventBus;
57 import com.google.common.eventbus.Subscribe;
58 import com.google.common.io.Closeables;
59 import com.google.common.util.concurrent.AbstractExecutionThreadService;
60 import com.google.common.util.concurrent.Service;
63 * A connection to an IRC server.
65 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
67 public class Connection extends AbstractExecutionThreadService implements Service {
70 private final EventBus eventBus;
72 /** The socket factory. */
73 private final SocketFactory socketFactory;
75 /** The hostname to connect to. */
76 private final String hostname;
78 /** The port to connect to. */
79 private final int port;
81 /** The nickname chooser. */
82 private NicknameChooser nicknameChooser = new NicknameChooser() {
85 public String getNickname() {
86 return RandomNickname.get();
91 private String nickname = null;
94 private Optional<String> username = Optional.absent();
97 private Optional<String> realName = Optional.absent();
99 /** The optional password for the connection. */
100 private Optional<String> password = Optional.absent();
102 /** The connection handler. */
103 private ConnectionHandler connectionHandler;
106 * Creates a new connection.
110 * @param socketFactory
113 * The hostname of the IRC server
115 * The port number of the IRC server
117 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
118 this.eventBus = eventBus;
119 this.socketFactory = socketFactory;
120 this.hostname = hostname;
129 * Returns the nickname that is currently in use by this connection. The
130 * nickname is only available once the connection has been {@link #start()}ed.
132 * @return The current nickname
134 public String nickname() {
143 * Sets the nickname chooser. The nickname chooser is only used during the
144 * creation of the connection.
146 * @param nicknameChooser
147 * The nickname chooser
148 * @return This connection
150 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
151 this.nicknameChooser = nicknameChooser;
156 * Sets the username to use.
159 * The username to use
162 public Connection username(String username) {
163 this.username = Optional.fromNullable(username);
168 * Sets the real name to use.
171 * The real name to use
172 * @return This connection
174 public Connection realName(String realName) {
175 this.realName = Optional.fromNullable(realName);
180 * Sets the optional password for the connection.
183 * The password for the connection
184 * @return This connection
186 public Connection password(String password) {
187 this.password = Optional.fromNullable(password);
196 * Joins the given channel.
199 * The channel to join
200 * @return {@code true} if the channel was joined, {@code false} otherwise
202 public boolean joinChannel(final String channel) {
203 final SynchronousQueue<Boolean> result = new SynchronousQueue<Boolean>();
204 Object eventHandler = new Object() {
207 public void channelJoined(ChannelJoined channelJoined) throws InterruptedException {
208 if (!channelJoined.channel().equalsIgnoreCase(channel)) {
211 Optional<String> nickname = channelJoined.client().nick();
212 if (!nickname.isPresent() || (nickname.isPresent() && nickname().equalsIgnoreCase(nickname.get()))) {
213 eventBus.unregister(this);
219 public void channelNotJoined(ChannelNotJoined channelNotJoined) throws InterruptedException {
220 if (!channelNotJoined.channel().equalsIgnoreCase(channel)) {
223 eventBus.unregister(this);
227 eventBus.register(eventHandler);
229 connectionHandler.sendCommand("JOIN", channel);
230 return result.take();
231 } catch (IOException ioe1) {
232 eventBus.unregister(eventHandler);
233 } catch (InterruptedException ie1) {
234 /* TODO - how to handle? */
240 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
244 protected void startUp() throws IllegalStateException {
245 checkState(username.isPresent(), "username must be set");
246 checkState(realName.isPresent(), "realName must be set");
250 protected void run() {
252 /* connect to remote socket. */
254 Socket socket = socketFactory.createSocket(hostname, port);
255 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
257 /* register connection. */
258 if (password.isPresent()) {
259 connectionHandler.sendCommand("PASSWORD", password.get());
261 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
262 nickname = nicknameChooser.getNickname();
263 connectionHandler.sendCommand("NICK", nickname);
265 } catch (IOException ioe1) {
266 eventBus.post(new ConnectionFailed(this, ioe1));
270 /* now read replies and react. */
272 /* some status variables. */
273 int oldConnectionStatus = 0;
274 int connectionStatus = 0;
275 boolean connected = true;
276 StringBuilder motd = new StringBuilder();
277 Set<Nickname> nicks = Sets.newHashSet();
280 Map<String, String> nickPrefixes = Maps.newHashMap();
281 Set<Character> channelTypes = Sets.newHashSet();
284 Reply reply = connectionHandler.readReply();
285 System.err.println("<< " + reply);
286 String command = reply.command();
287 List<String> parameters = reply.parameters();
289 /* most common events. */
290 if (command.equalsIgnoreCase("PRIVMSG")) {
291 String recipient = parameters.get(0);
292 if (!channelTypes.contains(recipient.charAt(0))) {
293 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), parameters.get(1)));
295 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), parameters.get(1)));
298 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
299 } else if (command.equals("001")) {
300 connectionStatus |= 0x01;
301 } else if (command.equals("002")) {
302 connectionStatus |= 0x02;
303 } else if (command.equals("003")) {
304 connectionStatus |= 0x04;
305 } else if (command.equals("004")) {
306 connectionStatus |= 0x08;
308 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
309 } else if (command.equals("005")) {
310 for (String parameter : parameters) {
311 if (parameter.startsWith("PREFIX=")) {
312 int openParen = parameter.indexOf('(');
313 int closeParen = parameter.indexOf(')');
314 if ((openParen != -1) && (closeParen != -1)) {
315 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
316 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
317 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
318 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
321 } else if (parameter.startsWith("CHANTYPES=")) {
322 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
323 channelTypes.add(parameter.charAt(typeIndex));
328 /* 375, 372, and 376 handle the server’s MOTD. */
329 } else if (command.equals("375")) {
331 motd.append(parameters.get(1)).append('\n');
332 } else if (command.equals("372")) {
333 motd.append(parameters.get(1)).append('\n');
334 } else if (command.equals("376")) {
335 motd.append(parameters.get(1)).append('\n');
336 eventBus.post(new MotdReceived(this, motd.toString()));
339 /* 43x replies are for nick change errors. */
340 } else if (command.equals("431")) {
341 eventBus.post(new NoNicknameGivenReceived(this, reply));
342 } else if (command.equals("433")) {
343 if (connectionStatus == 0) {
344 nickname = nicknameChooser.getNickname();
345 connectionHandler.sendCommand("NICK", nickname);
347 eventBus.post(new NicknameInUseReceived(this, reply));
351 } else if (command.equalsIgnoreCase("JOIN")) {
352 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
353 } else if (command.equals("331")) {
354 /* no topic is set. */
355 } else if (command.equals("332")) {
356 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
357 } else if (command.equals("353")) {
358 String channel = parameters.get(2);
359 for (String nickname : parameters.get(3).split(" ")) {
360 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
361 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
363 nicks.add(new Nickname(nickname, ""));
366 } else if (command.equals("366")) {
367 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
368 System.out.println("Found Nicknames: " + nicks);
371 /* common channel join errors. */
372 } else if (command.equals("474")) {
373 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
374 } else if (command.equals("473")) {
375 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
376 } else if (command.equals("475")) {
377 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
379 /* basic connection housekeeping. */
380 } else if (command.equalsIgnoreCase("PING")) {
381 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
383 /* okay, everything else. */
385 eventBus.post(new UnknownReplyReceived(this, reply));
388 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
389 /* connection succeeded! */
390 eventBus.post(new ConnectionEstablished(this));
392 oldConnectionStatus = connectionStatus;
394 } catch (IOException ioe1) {
395 ioe1.printStackTrace();
397 System.out.println("Closing Connection.");
399 Closeables.close(connectionHandler, true);
400 } catch (IOException ioe1) {
401 /* will not be thrown. */
412 * Returns an item from the list, or {@link Optional#absent()} if the list is
413 * shorter than required for the given index.
416 * The list to get an item from
418 * The index of the item
420 * The type of the list items
421 * @return This list item wrapped in an {@link Optional}, or {@link
422 * Optional#absent()} if the list is not long enough
424 private static <T> Optional<T> getOptional(List<T> list, int index) {
425 if (index < list.size()) {
426 return Optional.fromNullable(list.get(index));
428 return Optional.absent();
431 /** Handles input and output for the connection. */
432 private class ConnectionHandler implements Closeable {
434 /** The output stream of the connection. */
435 private final OutputStream outputStream;
437 /** The input stream of the connection. */
438 private final BufferedReader inputStreamReader;
441 * Creates a new connection handler for the given input stream and output
445 * The input stream of the connection
446 * @param outputStream
447 * The output stream of the connection
448 * @throws UnsupportedEncodingException
449 * if the encoding (currently “UTF-8”) is not valid
451 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
452 this.outputStream = outputStream;
453 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
461 * Sends a command with the given parameters, skipping all {@link
462 * Optional#absent()} optionals.
465 * The command to send
468 * @throws IOException
469 * if an I/O error occurs
471 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
472 List<String> setParameters = new ArrayList<String>();
473 for (Optional<String> maybeSetParameter : parameters) {
474 if (maybeSetParameter.isPresent()) {
475 setParameters.add(maybeSetParameter.get());
478 sendCommand(command, setParameters.toArray(new String[0]));
482 * Sends a command with the given parameters.
485 * The command to send
487 * The parameters of the command
488 * @throws IOException
489 * if an I/O error occurs
490 * @throws IllegalArgumentException
491 * if any parameter but that last contains a space character
493 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
494 StringBuilder commandBuilder = new StringBuilder();
496 commandBuilder.append(command);
497 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
498 String parameter = parameters[parameterIndex];
499 /* space is only allowed in the last parameter. */
500 commandBuilder.append(' ');
501 if (parameter.contains(" ")) {
502 if (parameterIndex == (parameters.length - 1)) {
503 commandBuilder.append(':');
505 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
508 commandBuilder.append(parameter);
511 System.out.println(">> " + commandBuilder.toString());
512 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
513 outputStream.flush();
517 * Reads a line of reply from the connection.
520 * @throws IOException
521 * if an I/O error occurs
522 * @throws EOFException
525 public Reply readReply() throws IOException, EOFException {
526 String line = inputStreamReader.readLine();
528 throw new EOFException();
531 return Reply.parseLine(line);
539 public void close() throws IOException {
540 Closeables.close(outputStream, true);
541 Closeables.close(inputStreamReader, true);