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