Add basic IRC framework.
[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
280                         while (connected) {
281                                 Reply reply = connectionHandler.readReply();
282                                 System.err.println("<< " + reply);
283                                 String command = reply.command();
284                                 List<String> parameters = reply.parameters();
285
286                                 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
287                                 if (command.equals("001")) {
288                                         connectionStatus |= 0x01;
289                                 } else if (command.equals("002")) {
290                                         connectionStatus |= 0x02;
291                                 } else if (command.equals("003")) {
292                                         connectionStatus |= 0x04;
293                                 } else if (command.equals("004")) {
294                                         connectionStatus |= 0x08;
295
296                                 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
297                                 } else if (command.equals("005")) {
298                                         for (String parameter : parameters) {
299                                                 if (parameter.startsWith("PREFIX=")) {
300                                                         int openParen = parameter.indexOf('(');
301                                                         int closeParen = parameter.indexOf(')');
302                                                         if ((openParen != -1) && (closeParen != -1)) {
303                                                                 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
304                                                                         char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
305                                                                         char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
306                                                                         nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
307                                                                 }
308                                                         }
309                                                 }
310                                         }
311
312                                 /* 375, 372, and 376 handle the server’s MOTD. */
313                                 } else if (command.equals("375")) {
314                                         /* MOTD starts. */
315                                         motd.append(parameters.get(1)).append('\n');
316                                 } else if (command.equals("372")) {
317                                         motd.append(parameters.get(1)).append('\n');
318                                 } else if (command.equals("376")) {
319                                         motd.append(parameters.get(1)).append('\n');
320                                         eventBus.post(new MotdReceived(this, motd.toString()));
321                                         motd.setLength(0);
322
323                                 /* 43x replies are for nick change errors. */
324                                 } else if (command.equals("431")) {
325                                         eventBus.post(new NoNicknameGivenReceived(this, reply));
326                                 } else if (command.equals("433")) {
327                                         if (connectionStatus == 0) {
328                                                 nickname = nicknameChooser.getNickname();
329                                                 connectionHandler.sendCommand("NICK", nickname);
330                                         } else {
331                                                 eventBus.post(new NicknameInUseReceived(this, reply));
332                                         }
333
334                                 /* channel stuff. */
335                                 } else if (command.equalsIgnoreCase("JOIN")) {
336                                         eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
337                                 } else if (command.equals("331")) {
338                                         /* no topic is set. */
339                                 } else if (command.equals("332")) {
340                                         eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
341                                 } else if (command.equals("353")) {
342                                         String channel = parameters.get(2);
343                                         for (String nickname : parameters.get(3).split(" ")) {
344                                                 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
345                                                         nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
346                                                 } else {
347                                                         nicks.add(new Nickname(nickname, ""));
348                                                 }
349                                         }
350                                 } else if (command.equals("366")) {
351                                         eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
352                                         System.out.println("Found Nicknames: " + nicks);
353                                         nicks.clear();
354
355                                 /* common channel join errors. */
356                                 } else if (command.equals("474")) {
357                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
358                                 } else if (command.equals("473")) {
359                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
360                                 } else if (command.equals("475")) {
361                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
362
363                                 /* basic connection housekeeping. */
364                                 } else if (command.equalsIgnoreCase("PING")) {
365                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
366
367                                 /* okay, everything else. */
368                                 } else {
369                                         eventBus.post(new UnknownReplyReceived(this, reply));
370                                 }
371
372                                 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
373                                         /* connection succeeded! */
374                                         eventBus.post(new ConnectionEstablished(this));
375                                 }
376                                 oldConnectionStatus = connectionStatus;
377                         }
378                 } catch (IOException ioe1) {
379                         ioe1.printStackTrace();
380                 } finally {
381                         System.out.println("Closing Connection.");
382                         try {
383                                 Closeables.close(connectionHandler, true);
384                         } catch (IOException ioe1) {
385                                 /* will not be thrown. */
386                         }
387                 }
388
389         }
390
391         //
392         // PRIVATE METHODS
393         //
394
395         /**
396          * Returns an item from the list, or {@link Optional#absent()} if the list is
397          * shorter than required for the given index.
398          *
399          * @param list
400          *              The list to get an item from
401          * @param index
402          *              The index of the item
403          * @param <T>
404          *              The type of the list items
405          * @return This list item wrapped in an {@link Optional}, or {@link
406          *         Optional#absent()} if the list is not long enough
407          */
408         private static <T> Optional<T> getOptional(List<T> list, int index) {
409                 if (index < list.size()) {
410                         return Optional.fromNullable(list.get(index));
411                 }
412                 return Optional.absent();
413         }
414
415         /** Handles input and output for the connection. */
416         private class ConnectionHandler implements Closeable {
417
418                 /** The output stream of the connection. */
419                 private final OutputStream outputStream;
420
421                 /** The input stream of the connection. */
422                 private final BufferedReader inputStreamReader;
423
424                 /**
425                  * Creates a new connection handler for the given input stream and output
426                  * stream.
427                  *
428                  * @param inputStream
429                  *              The input stream of the connection
430                  * @param outputStream
431                  *              The output stream of the connection
432                  * @throws UnsupportedEncodingException
433                  *              if the encoding (currently “UTF-8”) is not valid
434                  */
435                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
436                         this.outputStream = outputStream;
437                         inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
438                 }
439
440                 //
441                 // ACTIONS
442                 //
443
444                 /**
445                  * Sends a command with the given parameters, skipping all {@link
446                  * Optional#absent()} optionals.
447                  *
448                  * @param command
449                  *              The command to send
450                  * @param parameters
451                  *              The parameters
452                  * @throws IOException
453                  *              if an I/O error occurs
454                  */
455                 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
456                         List<String> setParameters = new ArrayList<String>();
457                         for (Optional<String> maybeSetParameter : parameters) {
458                                 if (maybeSetParameter.isPresent()) {
459                                         setParameters.add(maybeSetParameter.get());
460                                 }
461                         }
462                         sendCommand(command, setParameters.toArray(new String[0]));
463                 }
464
465                 /**
466                  * Sends a command with the given parameters.
467                  *
468                  * @param command
469                  *              The command to send
470                  * @param parameters
471                  *              The parameters of the command
472                  * @throws IOException
473                  *              if an I/O error occurs
474                  * @throws IllegalArgumentException
475                  *              if any parameter but that last contains a space character
476                  */
477                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
478                         StringBuilder commandBuilder = new StringBuilder();
479
480                         commandBuilder.append(command);
481                         for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
482                                 String parameter = parameters[parameterIndex];
483                                 /* space is only allowed in the last parameter. */
484                                 commandBuilder.append(' ');
485                                 if (parameter.contains(" ")) {
486                                         if (parameterIndex == (parameters.length - 1)) {
487                                                 commandBuilder.append(':');
488                                         } else {
489                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
490                                         }
491                                 }
492                                 commandBuilder.append(parameter);
493                         }
494
495                         System.out.println(">> " + commandBuilder.toString());
496                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
497                         outputStream.flush();
498                 }
499
500                 /**
501                  * Reads a line of reply from the connection.
502                  *
503                  * @return The reply
504                  * @throws IOException
505                  *              if an I/O error occurs
506                  * @throws EOFException
507                  *              if EOF was reached
508                  */
509                 public Reply readReply() throws IOException, EOFException {
510                         String line = inputStreamReader.readLine();
511                         if (line == null) {
512                                 throw new EOFException();
513                         }
514
515                         return Reply.parseLine(line);
516                 }
517
518                 //
519                 // CLOSEABLE METHODS
520                 //
521
522                 @Override
523                 public void close() throws IOException {
524                         Closeables.close(outputStream, true);
525                         Closeables.close(inputStreamReader, true);
526                 }
527
528         }
529
530 }