Remove unnecessary variable.
[xudocci.git] / src / main / java / net / pterodactylus / irc / Connection.java
1 /*
2  * XdccDownloader - Connection.java - Copyright © 2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.irc;
19
20 import static com.google.common.base.Preconditions.checkState;
21
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;
33 import java.util.Map;
34 import java.util.Set;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
37 import javax.net.SocketFactory;
38
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;
53
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;
61
62 /**
63  * A connection to an IRC server.
64  *
65  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
66  */
67 public class Connection extends AbstractExecutionThreadService implements Service {
68
69         /* The logger. */
70         private static final Logger logger = Logger.getLogger(Connection.class.getName());
71
72         /** The event bus. */
73         private final EventBus eventBus;
74
75         /** The socket factory. */
76         private final SocketFactory socketFactory;
77
78         /** The hostname to connect to. */
79         private final String hostname;
80
81         /** The port to connect to. */
82         private final int port;
83
84         /** The nickname chooser. */
85         private NicknameChooser nicknameChooser = new NicknameChooser() {
86
87                 @Override
88                 public String getNickname() {
89                         return RandomNickname.get();
90                 }
91         };
92
93         /** The nickname. */
94         private String nickname = null;
95
96         /** The username. */
97         private Optional<String> username = Optional.absent();
98
99         /** The real name. */
100         private Optional<String> realName = Optional.absent();
101
102         /** The optional password for the connection. */
103         private Optional<String> password = Optional.absent();
104
105         /** The connection handler. */
106         private ConnectionHandler connectionHandler;
107
108         /**
109          * Creates a new connection.
110          *
111          * @param eventBus
112          *              The event bus
113          * @param socketFactory
114          *              The socket factory
115          * @param hostname
116          *              The hostname of the IRC server
117          * @param port
118          *              The port number of the IRC server
119          */
120         public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
121                 this.eventBus = eventBus;
122                 this.socketFactory = socketFactory;
123                 this.hostname = hostname;
124                 this.port = port;
125         }
126
127         //
128         // ACCESSORS
129         //
130
131         /**
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.
134          *
135          * @return The current nickname
136          */
137         public String nickname() {
138                 return nickname;
139         }
140
141         //
142         // MUTATORS
143         //
144
145         /**
146          * Sets the nickname chooser. The nickname chooser is only used during the
147          * creation of the connection.
148          *
149          * @param nicknameChooser
150          *              The nickname chooser
151          * @return This connection
152          */
153         public Connection nicknameChooser(NicknameChooser nicknameChooser) {
154                 this.nicknameChooser = nicknameChooser;
155                 return this;
156         }
157
158         /**
159          * Sets the username to use.
160          *
161          * @param username
162          *              The username to use
163          * @return
164          */
165         public Connection username(String username) {
166                 this.username = Optional.fromNullable(username);
167                 return this;
168         }
169
170         /**
171          * Sets the real name to use.
172          *
173          * @param realName
174          *              The real name to use
175          * @return This connection
176          */
177         public Connection realName(String realName) {
178                 this.realName = Optional.fromNullable(realName);
179                 return this;
180         }
181
182         /**
183          * Sets the optional password for the connection.
184          *
185          * @param password
186          *              The password for the connection
187          * @return This connection
188          */
189         public Connection password(String password) {
190                 this.password = Optional.fromNullable(password);
191                 return this;
192         }
193
194         //
195         // ACTIONS
196         //
197
198         /**
199          * Joins the given channel.
200          *
201          * @param channel
202          *              The channel to join
203          * @return {@code true} if the channel was joined, {@code false} otherwise
204          * @throws IOException
205          *              if an I/O error occurs
206          */
207         public void joinChannel(final String channel) throws IOException {
208                 connectionHandler.sendCommand("JOIN", channel);
209         }
210
211         //
212         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
213         //
214
215         @Override
216         protected void startUp() throws IllegalStateException {
217                 checkState(username.isPresent(), "username must be set");
218                 checkState(realName.isPresent(), "realName must be set");
219         }
220
221         @Override
222         protected void run() {
223
224                 /* connect to remote socket. */
225                 try {
226                         Socket socket = socketFactory.createSocket(hostname, port);
227                         connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
228
229                         /* register connection. */
230                         if (password.isPresent()) {
231                                 connectionHandler.sendCommand("PASSWORD", password.get());
232                         }
233                         connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
234                         nickname = nicknameChooser.getNickname();
235                         connectionHandler.sendCommand("NICK", nickname);
236
237                 } catch (IOException ioe1) {
238                         eventBus.post(new ConnectionFailed(this, ioe1));
239                         return;
240                 }
241
242                 /* now read replies and react. */
243                 try {
244                         /* some status variables. */
245                         int oldConnectionStatus = 0;
246                         int connectionStatus = 0;
247                         boolean connected = true;
248                         StringBuilder motd = new StringBuilder();
249                         Set<Nickname> nicks = Sets.newHashSet();
250
251                         /* server modes. */
252                         Map<String, String> nickPrefixes = Maps.newHashMap();
253                         Set<Character> channelTypes = Sets.newHashSet();
254
255                         while (connected) {
256                                 Reply reply = connectionHandler.readReply();
257                                 logger.finest(String.format("<< %s", reply));
258                                 String command = reply.command();
259                                 List<String> parameters = reply.parameters();
260
261                                 /* most common events. */
262                                 if (command.equalsIgnoreCase("PRIVMSG")) {
263                                         String recipient = parameters.get(0);
264                                         if (!channelTypes.contains(recipient.charAt(0))) {
265                                                 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), parameters.get(1)));
266                                         } else {
267                                                 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), parameters.get(1)));
268                                         }
269
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;
279
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));
291                                                                 }
292                                                                 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
293                                                         }
294                                                 } else if (parameter.startsWith("CHANTYPES=")) {
295                                                         for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
296                                                                 channelTypes.add(parameter.charAt(typeIndex));
297                                                         }
298                                                         logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
299                                                 }
300                                         }
301
302                                 /* 375, 372, and 376 handle the server’s MOTD. */
303                                 } else if (command.equals("375")) {
304                                         /* MOTD starts. */
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()));
311                                         motd.setLength(0);
312
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);
320                                         } else {
321                                                 eventBus.post(new NicknameInUseReceived(this, reply));
322                                         }
323
324                                 /* channel stuff. */
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)));
335                                                 } else {
336                                                         nicks.add(new Nickname(nickname, ""));
337                                                 }
338                                         }
339                                 } else if (command.equals("366")) {
340                                         eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
341                                         nicks.clear();
342
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));
350
351                                 /* basic connection housekeeping. */
352                                 } else if (command.equalsIgnoreCase("PING")) {
353                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
354
355                                 /* okay, everything else. */
356                                 } else {
357                                         eventBus.post(new UnknownReplyReceived(this, reply));
358                                 }
359
360                                 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
361                                         /* connection succeeded! */
362                                         eventBus.post(new ConnectionEstablished(this));
363                                 }
364                                 oldConnectionStatus = connectionStatus;
365                         }
366                 } catch (IOException ioe1) {
367                         logger.log(Level.WARNING, "I/O error", ioe1);
368                 } finally {
369                         logger.info("Closing Connection.");
370                         try {
371                                 Closeables.close(connectionHandler, true);
372                         } catch (IOException ioe1) {
373                                 /* will not be thrown. */
374                         }
375                 }
376
377         }
378
379         //
380         // PRIVATE METHODS
381         //
382
383         /**
384          * Returns an item from the list, or {@link Optional#absent()} if the list is
385          * shorter than required for the given index.
386          *
387          * @param list
388          *              The list to get an item from
389          * @param index
390          *              The index of the item
391          * @param <T>
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
395          */
396         private static <T> Optional<T> getOptional(List<T> list, int index) {
397                 if (index < list.size()) {
398                         return Optional.fromNullable(list.get(index));
399                 }
400                 return Optional.absent();
401         }
402
403         /** Handles input and output for the connection. */
404         private class ConnectionHandler implements Closeable {
405
406                 /** The output stream of the connection. */
407                 private final OutputStream outputStream;
408
409                 /** The input stream of the connection. */
410                 private final BufferedReader inputStreamReader;
411
412                 /**
413                  * Creates a new connection handler for the given input stream and output
414                  * stream.
415                  *
416                  * @param inputStream
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
422                  */
423                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
424                         this.outputStream = outputStream;
425                         inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
426                 }
427
428                 //
429                 // ACTIONS
430                 //
431
432                 /**
433                  * Sends a command with the given parameters, skipping all {@link
434                  * Optional#absent()} optionals.
435                  *
436                  * @param command
437                  *              The command to send
438                  * @param parameters
439                  *              The parameters
440                  * @throws IOException
441                  *              if an I/O error occurs
442                  */
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());
448                                 }
449                         }
450                         sendCommand(command, setParameters.toArray(new String[0]));
451                 }
452
453                 /**
454                  * Sends a command with the given parameters.
455                  *
456                  * @param command
457                  *              The command to send
458                  * @param parameters
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
464                  */
465                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
466                         StringBuilder commandBuilder = new StringBuilder();
467
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(':');
476                                         } else {
477                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
478                                         }
479                                 }
480                                 commandBuilder.append(parameter);
481                         }
482
483                         logger.finest(String.format(">> %s", commandBuilder));
484                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
485                         outputStream.flush();
486                 }
487
488                 /**
489                  * Reads a line of reply from the connection.
490                  *
491                  * @return The reply
492                  * @throws IOException
493                  *              if an I/O error occurs
494                  * @throws EOFException
495                  *              if EOF was reached
496                  */
497                 public Reply readReply() throws IOException, EOFException {
498                         String line = inputStreamReader.readLine();
499                         if (line == null) {
500                                 throw new EOFException();
501                         }
502
503                         return Reply.parseLine(line);
504                 }
505
506                 //
507                 // CLOSEABLE METHODS
508                 //
509
510                 @Override
511                 public void close() throws IOException {
512                         Closeables.close(outputStream, true);
513                         Closeables.close(inputStreamReader, true);
514                 }
515
516         }
517
518 }