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.logging.Level;
36 import java.util.logging.Logger;
37 import javax.net.SocketFactory;
39 import net.pterodactylus.irc.event.ChannelJoined;
40 import net.pterodactylus.irc.event.ChannelMessageReceived;
41 import net.pterodactylus.irc.event.ChannelNicknames;
42 import net.pterodactylus.irc.event.ChannelNotJoined;
43 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
44 import net.pterodactylus.irc.event.ChannelTopic;
45 import net.pterodactylus.irc.event.ConnectionEstablished;
46 import net.pterodactylus.irc.event.ConnectionFailed;
47 import net.pterodactylus.irc.event.MotdReceived;
48 import net.pterodactylus.irc.event.NicknameInUseReceived;
49 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
50 import net.pterodactylus.irc.event.PrivateMessageReceived;
51 import net.pterodactylus.irc.event.UnknownReplyReceived;
52 import net.pterodactylus.irc.util.RandomNickname;
54 import com.beust.jcommander.internal.Maps;
55 import com.beust.jcommander.internal.Sets;
56 import com.google.common.base.Optional;
57 import com.google.common.eventbus.EventBus;
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 static final Logger logger = Logger.getLogger(Connection.class.getName());
73 private final EventBus eventBus;
75 /** The socket factory. */
76 private final SocketFactory socketFactory;
78 /** The hostname to connect to. */
79 private final String hostname;
81 /** The port to connect to. */
82 private final int port;
84 /** The nickname chooser. */
85 private NicknameChooser nicknameChooser = new NicknameChooser() {
88 public String getNickname() {
89 return RandomNickname.get();
94 private String nickname = null;
97 private Optional<String> username = Optional.absent();
100 private Optional<String> realName = Optional.absent();
102 /** The optional password for the connection. */
103 private Optional<String> password = Optional.absent();
105 /** The connection handler. */
106 private ConnectionHandler connectionHandler;
109 * Creates a new connection.
113 * @param socketFactory
116 * The hostname of the IRC server
118 * The port number of the IRC server
120 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
121 this.eventBus = eventBus;
122 this.socketFactory = socketFactory;
123 this.hostname = hostname;
132 * Returns the nickname that is currently in use by this connection. The
133 * nickname is only available once the connection has been {@link #start()}ed.
135 * @return The current nickname
137 public String nickname() {
146 * Sets the nickname chooser. The nickname chooser is only used during the
147 * creation of the connection.
149 * @param nicknameChooser
150 * The nickname chooser
151 * @return This connection
153 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
154 this.nicknameChooser = nicknameChooser;
159 * Sets the username to use.
162 * The username to use
163 * @return This connection
165 public Connection username(String username) {
166 this.username = Optional.fromNullable(username);
171 * Sets the real name to use.
174 * The real name to use
175 * @return This connection
177 public Connection realName(String realName) {
178 this.realName = Optional.fromNullable(realName);
183 * Sets the optional password for the connection.
186 * The password for the connection
187 * @return This connection
189 public Connection password(String password) {
190 this.password = Optional.fromNullable(password);
199 * Joins the given channel.
202 * The channel to join
203 * @throws IOException
204 * if an I/O error occurs
206 public void joinChannel(final String channel) throws IOException {
207 connectionHandler.sendCommand("JOIN", channel);
211 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
215 protected void startUp() throws IllegalStateException {
216 checkState(username.isPresent(), "username must be set");
217 checkState(realName.isPresent(), "realName must be set");
221 protected void run() {
223 /* connect to remote socket. */
225 Socket socket = socketFactory.createSocket(hostname, port);
226 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
228 /* register connection. */
229 if (password.isPresent()) {
230 connectionHandler.sendCommand("PASSWORD", password.get());
232 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
233 nickname = nicknameChooser.getNickname();
234 connectionHandler.sendCommand("NICK", nickname);
236 } catch (IOException ioe1) {
237 eventBus.post(new ConnectionFailed(this, ioe1));
241 /* now read replies and react. */
243 /* some status variables. */
244 int oldConnectionStatus = 0;
245 int connectionStatus = 0;
246 boolean connected = true;
247 StringBuilder motd = new StringBuilder();
248 Set<Nickname> nicks = Sets.newHashSet();
251 Map<String, String> nickPrefixes = Maps.newHashMap();
252 Set<Character> channelTypes = Sets.newHashSet();
255 Reply reply = connectionHandler.readReply();
256 logger.finest(String.format("<< %s", reply));
257 String command = reply.command();
258 List<String> parameters = reply.parameters();
260 /* most common events. */
261 if (command.equalsIgnoreCase("PRIVMSG")) {
262 String recipient = parameters.get(0);
263 String message = parameters.get(1);
264 if (!channelTypes.contains(recipient.charAt(0))) {
265 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
267 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
270 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
271 } else if (command.equals("001")) {
272 connectionStatus |= 0x01;
273 } else if (command.equals("002")) {
274 connectionStatus |= 0x02;
275 } else if (command.equals("003")) {
276 connectionStatus |= 0x04;
277 } else if (command.equals("004")) {
278 connectionStatus |= 0x08;
280 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
281 } else if (command.equals("005")) {
282 for (String parameter : parameters) {
283 if (parameter.startsWith("PREFIX=")) {
284 int openParen = parameter.indexOf('(');
285 int closeParen = parameter.indexOf(')');
286 if ((openParen != -1) && (closeParen != -1)) {
287 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
288 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
289 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
290 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
292 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
294 } else if (parameter.startsWith("CHANTYPES=")) {
295 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
296 channelTypes.add(parameter.charAt(typeIndex));
298 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
302 /* 375, 372, and 376 handle the server’s MOTD. */
303 } else if (command.equals("375")) {
305 motd.append(parameters.get(1)).append('\n');
306 } else if (command.equals("372")) {
307 motd.append(parameters.get(1)).append('\n');
308 } else if (command.equals("376")) {
309 motd.append(parameters.get(1)).append('\n');
310 eventBus.post(new MotdReceived(this, motd.toString()));
313 /* 43x replies are for nick change errors. */
314 } else if (command.equals("431")) {
315 eventBus.post(new NoNicknameGivenReceived(this, reply));
316 } else if (command.equals("433")) {
317 if (connectionStatus == 0) {
318 nickname = nicknameChooser.getNickname();
319 connectionHandler.sendCommand("NICK", nickname);
321 eventBus.post(new NicknameInUseReceived(this, reply));
325 } else if (command.equalsIgnoreCase("JOIN")) {
326 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
327 } else if (command.equals("331")) {
328 /* no topic is set. */
329 } else if (command.equals("332")) {
330 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
331 } else if (command.equals("353")) {
332 for (String nickname : parameters.get(3).split(" ")) {
333 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
334 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
336 nicks.add(new Nickname(nickname, ""));
339 } else if (command.equals("366")) {
340 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
343 /* common channel join errors. */
344 } else if (command.equals("474")) {
345 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
346 } else if (command.equals("473")) {
347 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
348 } else if (command.equals("475")) {
349 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
351 /* basic connection housekeeping. */
352 } else if (command.equalsIgnoreCase("PING")) {
353 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
355 /* okay, everything else. */
357 eventBus.post(new UnknownReplyReceived(this, reply));
360 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
361 /* connection succeeded! */
362 eventBus.post(new ConnectionEstablished(this));
364 oldConnectionStatus = connectionStatus;
366 } catch (IOException ioe1) {
367 logger.log(Level.WARNING, "I/O error", ioe1);
369 logger.info("Closing Connection.");
371 Closeables.close(connectionHandler, true);
372 } catch (IOException ioe1) {
373 /* will not be thrown. */
384 * Returns an item from the list, or {@link Optional#absent()} if the list is
385 * shorter than required for the given index.
388 * The list to get an item from
390 * The index of the item
392 * The type of the list items
393 * @return This list item wrapped in an {@link Optional}, or {@link
394 * Optional#absent()} if the list is not long enough
396 private static <T> Optional<T> getOptional(List<T> list, int index) {
397 if (index < list.size()) {
398 return Optional.fromNullable(list.get(index));
400 return Optional.absent();
403 /** Handles input and output for the connection. */
404 private class ConnectionHandler implements Closeable {
406 /** The output stream of the connection. */
407 private final OutputStream outputStream;
409 /** The input stream of the connection. */
410 private final BufferedReader inputStreamReader;
413 * Creates a new connection handler for the given input stream and output
417 * The input stream of the connection
418 * @param outputStream
419 * The output stream of the connection
420 * @throws UnsupportedEncodingException
421 * if the encoding (currently “UTF-8”) is not valid
423 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
424 this.outputStream = outputStream;
425 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
433 * Sends a command with the given parameters, skipping all {@link
434 * Optional#absent()} optionals.
437 * The command to send
440 * @throws IOException
441 * if an I/O error occurs
443 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
444 List<String> setParameters = new ArrayList<String>();
445 for (Optional<String> maybeSetParameter : parameters) {
446 if (maybeSetParameter.isPresent()) {
447 setParameters.add(maybeSetParameter.get());
450 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
454 * Sends a command with the given parameters.
457 * The command to send
459 * The parameters of the command
460 * @throws IOException
461 * if an I/O error occurs
462 * @throws IllegalArgumentException
463 * if any parameter but that last contains a space character
465 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
466 StringBuilder commandBuilder = new StringBuilder();
468 commandBuilder.append(command);
469 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
470 String parameter = parameters[parameterIndex];
471 /* space is only allowed in the last parameter. */
472 commandBuilder.append(' ');
473 if (parameter.contains(" ")) {
474 if (parameterIndex == (parameters.length - 1)) {
475 commandBuilder.append(':');
477 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
480 commandBuilder.append(parameter);
483 logger.finest(String.format(">> %s", commandBuilder));
484 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
485 outputStream.flush();
489 * Reads a line of reply from the connection.
492 * @throws IOException
493 * if an I/O error occurs
494 * @throws EOFException
497 public Reply readReply() throws IOException, EOFException {
498 String line = inputStreamReader.readLine();
500 throw new EOFException();
503 return Reply.parseLine(line);
511 public void close() throws IOException {
512 Closeables.close(outputStream, true);
513 Closeables.close(inputStreamReader, true);