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 if (!channelTypes.contains(recipient.charAt(0))) {
264 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), parameters.get(1)));
266 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), parameters.get(1)));
269 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
270 } else if (command.equals("001")) {
271 connectionStatus |= 0x01;
272 } else if (command.equals("002")) {
273 connectionStatus |= 0x02;
274 } else if (command.equals("003")) {
275 connectionStatus |= 0x04;
276 } else if (command.equals("004")) {
277 connectionStatus |= 0x08;
279 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
280 } else if (command.equals("005")) {
281 for (String parameter : parameters) {
282 if (parameter.startsWith("PREFIX=")) {
283 int openParen = parameter.indexOf('(');
284 int closeParen = parameter.indexOf(')');
285 if ((openParen != -1) && (closeParen != -1)) {
286 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
287 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
288 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
289 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
291 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
293 } else if (parameter.startsWith("CHANTYPES=")) {
294 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
295 channelTypes.add(parameter.charAt(typeIndex));
297 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
301 /* 375, 372, and 376 handle the server’s MOTD. */
302 } else if (command.equals("375")) {
304 motd.append(parameters.get(1)).append('\n');
305 } else if (command.equals("372")) {
306 motd.append(parameters.get(1)).append('\n');
307 } else if (command.equals("376")) {
308 motd.append(parameters.get(1)).append('\n');
309 eventBus.post(new MotdReceived(this, motd.toString()));
312 /* 43x replies are for nick change errors. */
313 } else if (command.equals("431")) {
314 eventBus.post(new NoNicknameGivenReceived(this, reply));
315 } else if (command.equals("433")) {
316 if (connectionStatus == 0) {
317 nickname = nicknameChooser.getNickname();
318 connectionHandler.sendCommand("NICK", nickname);
320 eventBus.post(new NicknameInUseReceived(this, reply));
324 } else if (command.equalsIgnoreCase("JOIN")) {
325 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
326 } else if (command.equals("331")) {
327 /* no topic is set. */
328 } else if (command.equals("332")) {
329 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
330 } else if (command.equals("353")) {
331 for (String nickname : parameters.get(3).split(" ")) {
332 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
333 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
335 nicks.add(new Nickname(nickname, ""));
338 } else if (command.equals("366")) {
339 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
342 /* common channel join errors. */
343 } else if (command.equals("474")) {
344 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
345 } else if (command.equals("473")) {
346 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
347 } else if (command.equals("475")) {
348 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
350 /* basic connection housekeeping. */
351 } else if (command.equalsIgnoreCase("PING")) {
352 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
354 /* okay, everything else. */
356 eventBus.post(new UnknownReplyReceived(this, reply));
359 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
360 /* connection succeeded! */
361 eventBus.post(new ConnectionEstablished(this));
363 oldConnectionStatus = connectionStatus;
365 } catch (IOException ioe1) {
366 logger.log(Level.WARNING, "I/O error", ioe1);
368 logger.info("Closing Connection.");
370 Closeables.close(connectionHandler, true);
371 } catch (IOException ioe1) {
372 /* will not be thrown. */
383 * Returns an item from the list, or {@link Optional#absent()} if the list is
384 * shorter than required for the given index.
387 * The list to get an item from
389 * The index of the item
391 * The type of the list items
392 * @return This list item wrapped in an {@link Optional}, or {@link
393 * Optional#absent()} if the list is not long enough
395 private static <T> Optional<T> getOptional(List<T> list, int index) {
396 if (index < list.size()) {
397 return Optional.fromNullable(list.get(index));
399 return Optional.absent();
402 /** Handles input and output for the connection. */
403 private class ConnectionHandler implements Closeable {
405 /** The output stream of the connection. */
406 private final OutputStream outputStream;
408 /** The input stream of the connection. */
409 private final BufferedReader inputStreamReader;
412 * Creates a new connection handler for the given input stream and output
416 * The input stream of the connection
417 * @param outputStream
418 * The output stream of the connection
419 * @throws UnsupportedEncodingException
420 * if the encoding (currently “UTF-8”) is not valid
422 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
423 this.outputStream = outputStream;
424 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
432 * Sends a command with the given parameters, skipping all {@link
433 * Optional#absent()} optionals.
436 * The command to send
439 * @throws IOException
440 * if an I/O error occurs
442 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
443 List<String> setParameters = new ArrayList<String>();
444 for (Optional<String> maybeSetParameter : parameters) {
445 if (maybeSetParameter.isPresent()) {
446 setParameters.add(maybeSetParameter.get());
449 sendCommand(command, setParameters.toArray(new String[0]));
453 * Sends a command with the given parameters.
456 * The command to send
458 * The parameters of the command
459 * @throws IOException
460 * if an I/O error occurs
461 * @throws IllegalArgumentException
462 * if any parameter but that last contains a space character
464 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
465 StringBuilder commandBuilder = new StringBuilder();
467 commandBuilder.append(command);
468 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
469 String parameter = parameters[parameterIndex];
470 /* space is only allowed in the last parameter. */
471 commandBuilder.append(' ');
472 if (parameter.contains(" ")) {
473 if (parameterIndex == (parameters.length - 1)) {
474 commandBuilder.append(':');
476 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
479 commandBuilder.append(parameter);
482 logger.finest(String.format(">> %s", commandBuilder));
483 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
484 outputStream.flush();
488 * Reads a line of reply from the connection.
491 * @throws IOException
492 * if an I/O error occurs
493 * @throws EOFException
496 public Reply readReply() throws IOException, EOFException {
497 String line = inputStreamReader.readLine();
499 throw new EOFException();
502 return Reply.parseLine(line);
510 public void close() throws IOException {
511 Closeables.close(outputStream, true);
512 Closeables.close(inputStreamReader, true);