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