Use logger instead of System.out.
[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.concurrent.SynchronousQueue;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38 import javax.net.SocketFactory;
39
40 import net.pterodactylus.irc.event.ChannelJoined;
41 import net.pterodactylus.irc.event.ChannelMessageReceived;
42 import net.pterodactylus.irc.event.ChannelNicknames;
43 import net.pterodactylus.irc.event.ChannelNotJoined;
44 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
45 import net.pterodactylus.irc.event.ChannelTopic;
46 import net.pterodactylus.irc.event.ConnectionEstablished;
47 import net.pterodactylus.irc.event.ConnectionFailed;
48 import net.pterodactylus.irc.event.MotdReceived;
49 import net.pterodactylus.irc.event.NicknameInUseReceived;
50 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
51 import net.pterodactylus.irc.event.PrivateMessageReceived;
52 import net.pterodactylus.irc.event.UnknownReplyReceived;
53 import net.pterodactylus.irc.util.RandomNickname;
54
55 import com.beust.jcommander.internal.Maps;
56 import com.beust.jcommander.internal.Sets;
57 import com.google.common.base.Optional;
58 import com.google.common.eventbus.EventBus;
59 import com.google.common.eventbus.Subscribe;
60 import com.google.common.io.Closeables;
61 import com.google.common.util.concurrent.AbstractExecutionThreadService;
62 import com.google.common.util.concurrent.Service;
63
64 /**
65  * A connection to an IRC server.
66  *
67  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
68  */
69 public class Connection extends AbstractExecutionThreadService implements Service {
70
71         /* The logger. */
72         private static final Logger logger = Logger.getLogger(Connection.class.getName());
73
74         /** The event bus. */
75         private final EventBus eventBus;
76
77         /** The socket factory. */
78         private final SocketFactory socketFactory;
79
80         /** The hostname to connect to. */
81         private final String hostname;
82
83         /** The port to connect to. */
84         private final int port;
85
86         /** The nickname chooser. */
87         private NicknameChooser nicknameChooser = new NicknameChooser() {
88
89                 @Override
90                 public String getNickname() {
91                         return RandomNickname.get();
92                 }
93         };
94
95         /** The nickname. */
96         private String nickname = null;
97
98         /** The username. */
99         private Optional<String> username = Optional.absent();
100
101         /** The real name. */
102         private Optional<String> realName = Optional.absent();
103
104         /** The optional password for the connection. */
105         private Optional<String> password = Optional.absent();
106
107         /** The connection handler. */
108         private ConnectionHandler connectionHandler;
109
110         /**
111          * Creates a new connection.
112          *
113          * @param eventBus
114          *              The event bus
115          * @param socketFactory
116          *              The socket factory
117          * @param hostname
118          *              The hostname of the IRC server
119          * @param port
120          *              The port number of the IRC server
121          */
122         public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
123                 this.eventBus = eventBus;
124                 this.socketFactory = socketFactory;
125                 this.hostname = hostname;
126                 this.port = port;
127         }
128
129         //
130         // ACCESSORS
131         //
132
133         /**
134          * Returns the nickname that is currently in use by this connection. The
135          * nickname is only available once the connection has been {@link #start()}ed.
136          *
137          * @return The current nickname
138          */
139         public String nickname() {
140                 return nickname;
141         }
142
143         //
144         // MUTATORS
145         //
146
147         /**
148          * Sets the nickname chooser. The nickname chooser is only used during the
149          * creation of the connection.
150          *
151          * @param nicknameChooser
152          *              The nickname chooser
153          * @return This connection
154          */
155         public Connection nicknameChooser(NicknameChooser nicknameChooser) {
156                 this.nicknameChooser = nicknameChooser;
157                 return this;
158         }
159
160         /**
161          * Sets the username to use.
162          *
163          * @param username
164          *              The username to use
165          * @return
166          */
167         public Connection username(String username) {
168                 this.username = Optional.fromNullable(username);
169                 return this;
170         }
171
172         /**
173          * Sets the real name to use.
174          *
175          * @param realName
176          *              The real name to use
177          * @return This connection
178          */
179         public Connection realName(String realName) {
180                 this.realName = Optional.fromNullable(realName);
181                 return this;
182         }
183
184         /**
185          * Sets the optional password for the connection.
186          *
187          * @param password
188          *              The password for the connection
189          * @return This connection
190          */
191         public Connection password(String password) {
192                 this.password = Optional.fromNullable(password);
193                 return this;
194         }
195
196         //
197         // ACTIONS
198         //
199
200         /**
201          * Joins the given channel.
202          *
203          * @param channel
204          *              The channel to join
205          * @return {@code true} if the channel was joined, {@code false} otherwise
206          */
207         public boolean joinChannel(final String channel) {
208                 final SynchronousQueue<Boolean> result = new SynchronousQueue<Boolean>();
209                 Object eventHandler = new Object() {
210
211                         @Subscribe
212                         public void channelJoined(ChannelJoined channelJoined) throws InterruptedException {
213                                 if (!channelJoined.channel().equalsIgnoreCase(channel)) {
214                                         return;
215                                 }
216                                 Optional<String> nickname = channelJoined.client().nick();
217                                 if (!nickname.isPresent() || (nickname.isPresent() && nickname().equalsIgnoreCase(nickname.get()))) {
218                                         eventBus.unregister(this);
219                                         result.put(true);
220                                 }
221                         }
222
223                         @Subscribe
224                         public void channelNotJoined(ChannelNotJoined channelNotJoined) throws InterruptedException {
225                                 if (!channelNotJoined.channel().equalsIgnoreCase(channel)) {
226                                         return;
227                                 }
228                                 eventBus.unregister(this);
229                                 result.put(false);
230                         }
231                 };
232                 eventBus.register(eventHandler);
233                 try {
234                         connectionHandler.sendCommand("JOIN", channel);
235                         return result.take();
236                 } catch (IOException ioe1) {
237                         eventBus.unregister(eventHandler);
238                 } catch (InterruptedException ie1) {
239                         /* TODO - how to handle? */
240                 }
241                 return false;
242         }
243
244         //
245         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
246         //
247
248         @Override
249         protected void startUp() throws IllegalStateException {
250                 checkState(username.isPresent(), "username must be set");
251                 checkState(realName.isPresent(), "realName must be set");
252         }
253
254         @Override
255         protected void run() {
256
257                 /* connect to remote socket. */
258                 try {
259                         Socket socket = socketFactory.createSocket(hostname, port);
260                         connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
261
262                         /* register connection. */
263                         if (password.isPresent()) {
264                                 connectionHandler.sendCommand("PASSWORD", password.get());
265                         }
266                         connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
267                         nickname = nicknameChooser.getNickname();
268                         connectionHandler.sendCommand("NICK", nickname);
269
270                 } catch (IOException ioe1) {
271                         eventBus.post(new ConnectionFailed(this, ioe1));
272                         return;
273                 }
274
275                 /* now read replies and react. */
276                 try {
277                         /* some status variables. */
278                         int oldConnectionStatus = 0;
279                         int connectionStatus = 0;
280                         boolean connected = true;
281                         StringBuilder motd = new StringBuilder();
282                         Set<Nickname> nicks = Sets.newHashSet();
283
284                         /* server modes. */
285                         Map<String, String> nickPrefixes = Maps.newHashMap();
286                         Set<Character> channelTypes = Sets.newHashSet();
287
288                         while (connected) {
289                                 Reply reply = connectionHandler.readReply();
290                                 logger.finest(String.format("<< %s", reply));
291                                 String command = reply.command();
292                                 List<String> parameters = reply.parameters();
293
294                                 /* most common events. */
295                                 if (command.equalsIgnoreCase("PRIVMSG")) {
296                                         String recipient = parameters.get(0);
297                                         if (!channelTypes.contains(recipient.charAt(0))) {
298                                                 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), parameters.get(1)));
299                                         } else {
300                                                 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), parameters.get(1)));
301                                         }
302
303                                 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
304                                 } else if (command.equals("001")) {
305                                         connectionStatus |= 0x01;
306                                 } else if (command.equals("002")) {
307                                         connectionStatus |= 0x02;
308                                 } else if (command.equals("003")) {
309                                         connectionStatus |= 0x04;
310                                 } else if (command.equals("004")) {
311                                         connectionStatus |= 0x08;
312
313                                 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
314                                 } else if (command.equals("005")) {
315                                         for (String parameter : parameters) {
316                                                 if (parameter.startsWith("PREFIX=")) {
317                                                         int openParen = parameter.indexOf('(');
318                                                         int closeParen = parameter.indexOf(')');
319                                                         if ((openParen != -1) && (closeParen != -1)) {
320                                                                 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
321                                                                         char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
322                                                                         char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
323                                                                         nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
324                                                                 }
325                                                                 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
326                                                         }
327                                                 } else if (parameter.startsWith("CHANTYPES=")) {
328                                                         for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
329                                                                 channelTypes.add(parameter.charAt(typeIndex));
330                                                         }
331                                                         logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
332                                                 }
333                                         }
334
335                                 /* 375, 372, and 376 handle the server’s MOTD. */
336                                 } else if (command.equals("375")) {
337                                         /* MOTD starts. */
338                                         motd.append(parameters.get(1)).append('\n');
339                                 } else if (command.equals("372")) {
340                                         motd.append(parameters.get(1)).append('\n');
341                                 } else if (command.equals("376")) {
342                                         motd.append(parameters.get(1)).append('\n');
343                                         eventBus.post(new MotdReceived(this, motd.toString()));
344                                         motd.setLength(0);
345
346                                 /* 43x replies are for nick change errors. */
347                                 } else if (command.equals("431")) {
348                                         eventBus.post(new NoNicknameGivenReceived(this, reply));
349                                 } else if (command.equals("433")) {
350                                         if (connectionStatus == 0) {
351                                                 nickname = nicknameChooser.getNickname();
352                                                 connectionHandler.sendCommand("NICK", nickname);
353                                         } else {
354                                                 eventBus.post(new NicknameInUseReceived(this, reply));
355                                         }
356
357                                 /* channel stuff. */
358                                 } else if (command.equalsIgnoreCase("JOIN")) {
359                                         eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
360                                 } else if (command.equals("331")) {
361                                         /* no topic is set. */
362                                 } else if (command.equals("332")) {
363                                         eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
364                                 } else if (command.equals("353")) {
365                                         String channel = parameters.get(2);
366                                         for (String nickname : parameters.get(3).split(" ")) {
367                                                 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
368                                                         nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
369                                                 } else {
370                                                         nicks.add(new Nickname(nickname, ""));
371                                                 }
372                                         }
373                                 } else if (command.equals("366")) {
374                                         eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
375                                         nicks.clear();
376
377                                 /* common channel join errors. */
378                                 } else if (command.equals("474")) {
379                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
380                                 } else if (command.equals("473")) {
381                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
382                                 } else if (command.equals("475")) {
383                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
384
385                                 /* basic connection housekeeping. */
386                                 } else if (command.equalsIgnoreCase("PING")) {
387                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
388
389                                 /* okay, everything else. */
390                                 } else {
391                                         eventBus.post(new UnknownReplyReceived(this, reply));
392                                 }
393
394                                 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
395                                         /* connection succeeded! */
396                                         eventBus.post(new ConnectionEstablished(this));
397                                 }
398                                 oldConnectionStatus = connectionStatus;
399                         }
400                 } catch (IOException ioe1) {
401                         logger.log(Level.WARNING, "I/O error", ioe1);
402                 } finally {
403                         logger.info("Closing Connection.");
404                         try {
405                                 Closeables.close(connectionHandler, true);
406                         } catch (IOException ioe1) {
407                                 /* will not be thrown. */
408                         }
409                 }
410
411         }
412
413         //
414         // PRIVATE METHODS
415         //
416
417         /**
418          * Returns an item from the list, or {@link Optional#absent()} if the list is
419          * shorter than required for the given index.
420          *
421          * @param list
422          *              The list to get an item from
423          * @param index
424          *              The index of the item
425          * @param <T>
426          *              The type of the list items
427          * @return This list item wrapped in an {@link Optional}, or {@link
428          *         Optional#absent()} if the list is not long enough
429          */
430         private static <T> Optional<T> getOptional(List<T> list, int index) {
431                 if (index < list.size()) {
432                         return Optional.fromNullable(list.get(index));
433                 }
434                 return Optional.absent();
435         }
436
437         /** Handles input and output for the connection. */
438         private class ConnectionHandler implements Closeable {
439
440                 /** The output stream of the connection. */
441                 private final OutputStream outputStream;
442
443                 /** The input stream of the connection. */
444                 private final BufferedReader inputStreamReader;
445
446                 /**
447                  * Creates a new connection handler for the given input stream and output
448                  * stream.
449                  *
450                  * @param inputStream
451                  *              The input stream of the connection
452                  * @param outputStream
453                  *              The output stream of the connection
454                  * @throws UnsupportedEncodingException
455                  *              if the encoding (currently “UTF-8”) is not valid
456                  */
457                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
458                         this.outputStream = outputStream;
459                         inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
460                 }
461
462                 //
463                 // ACTIONS
464                 //
465
466                 /**
467                  * Sends a command with the given parameters, skipping all {@link
468                  * Optional#absent()} optionals.
469                  *
470                  * @param command
471                  *              The command to send
472                  * @param parameters
473                  *              The parameters
474                  * @throws IOException
475                  *              if an I/O error occurs
476                  */
477                 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
478                         List<String> setParameters = new ArrayList<String>();
479                         for (Optional<String> maybeSetParameter : parameters) {
480                                 if (maybeSetParameter.isPresent()) {
481                                         setParameters.add(maybeSetParameter.get());
482                                 }
483                         }
484                         sendCommand(command, setParameters.toArray(new String[0]));
485                 }
486
487                 /**
488                  * Sends a command with the given parameters.
489                  *
490                  * @param command
491                  *              The command to send
492                  * @param parameters
493                  *              The parameters of the command
494                  * @throws IOException
495                  *              if an I/O error occurs
496                  * @throws IllegalArgumentException
497                  *              if any parameter but that last contains a space character
498                  */
499                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
500                         StringBuilder commandBuilder = new StringBuilder();
501
502                         commandBuilder.append(command);
503                         for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
504                                 String parameter = parameters[parameterIndex];
505                                 /* space is only allowed in the last parameter. */
506                                 commandBuilder.append(' ');
507                                 if (parameter.contains(" ")) {
508                                         if (parameterIndex == (parameters.length - 1)) {
509                                                 commandBuilder.append(':');
510                                         } else {
511                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
512                                         }
513                                 }
514                                 commandBuilder.append(parameter);
515                         }
516
517                         logger.finest(String.format(">> %s", commandBuilder));
518                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
519                         outputStream.flush();
520                 }
521
522                 /**
523                  * Reads a line of reply from the connection.
524                  *
525                  * @return The reply
526                  * @throws IOException
527                  *              if an I/O error occurs
528                  * @throws EOFException
529                  *              if EOF was reached
530                  */
531                 public Reply readReply() throws IOException, EOFException {
532                         String line = inputStreamReader.readLine();
533                         if (line == null) {
534                                 throw new EOFException();
535                         }
536
537                         return Reply.parseLine(line);
538                 }
539
540                 //
541                 // CLOSEABLE METHODS
542                 //
543
544                 @Override
545                 public void close() throws IOException {
546                         Closeables.close(outputStream, true);
547                         Closeables.close(inputStreamReader, true);
548                 }
549
550         }
551
552 }