Send event when a client parts a channel.
[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.InetAddress;
31 import java.net.Socket;
32 import java.net.UnknownHostException;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Set;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
39 import javax.net.SocketFactory;
40
41 import net.pterodactylus.irc.event.ChannelJoined;
42 import net.pterodactylus.irc.event.ChannelLeft;
43 import net.pterodactylus.irc.event.ChannelMessageReceived;
44 import net.pterodactylus.irc.event.ChannelNicknames;
45 import net.pterodactylus.irc.event.ChannelNotJoined;
46 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
47 import net.pterodactylus.irc.event.ChannelTopic;
48 import net.pterodactylus.irc.event.ConnectionEstablished;
49 import net.pterodactylus.irc.event.ConnectionFailed;
50 import net.pterodactylus.irc.event.DccSendReceived;
51 import net.pterodactylus.irc.event.MotdReceived;
52 import net.pterodactylus.irc.event.NicknameInUseReceived;
53 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
54 import net.pterodactylus.irc.event.PrivateMessageReceived;
55 import net.pterodactylus.irc.event.UnknownReplyReceived;
56 import net.pterodactylus.irc.util.RandomNickname;
57
58 import com.google.common.base.Optional;
59 import com.google.common.collect.Maps;
60 import com.google.common.collect.Sets;
61 import com.google.common.eventbus.EventBus;
62 import com.google.common.io.Closeables;
63 import com.google.common.primitives.Ints;
64 import com.google.common.primitives.Longs;
65 import com.google.common.util.concurrent.AbstractExecutionThreadService;
66 import com.google.common.util.concurrent.Service;
67
68 /**
69  * A connection to an IRC server.
70  *
71  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
72  */
73 public class Connection extends AbstractExecutionThreadService implements Service {
74
75         /* The logger. */
76         private static final Logger logger = Logger.getLogger(Connection.class.getName());
77
78         /** The event bus. */
79         private final EventBus eventBus;
80
81         /** The socket factory. */
82         private final SocketFactory socketFactory;
83
84         /** The hostname to connect to. */
85         private final String hostname;
86
87         /** The port to connect to. */
88         private final int port;
89
90         /** The nickname chooser. */
91         private NicknameChooser nicknameChooser = new NicknameChooser() {
92
93                 @Override
94                 public String getNickname() {
95                         return RandomNickname.get();
96                 }
97         };
98
99         /** The nickname. */
100         private String nickname = null;
101
102         /** The username. */
103         private Optional<String> username = Optional.absent();
104
105         /** The real name. */
106         private Optional<String> realName = Optional.absent();
107
108         /** The optional password for the connection. */
109         private Optional<String> password = Optional.absent();
110
111         /** The connection handler. */
112         private ConnectionHandler connectionHandler;
113
114         /**
115          * Creates a new connection.
116          *
117          * @param eventBus
118          *              The event bus
119          * @param socketFactory
120          *              The socket factory
121          * @param hostname
122          *              The hostname of the IRC server
123          * @param port
124          *              The port number of the IRC server
125          */
126         public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
127                 this.eventBus = eventBus;
128                 this.socketFactory = socketFactory;
129                 this.hostname = hostname;
130                 this.port = port;
131         }
132
133         //
134         // ACCESSORS
135         //
136
137         /**
138          * Returns the nickname that is currently in use by this connection. The
139          * nickname is only available once the connection has been {@link #start()}ed.
140          *
141          * @return The current nickname
142          */
143         public String nickname() {
144                 return nickname;
145         }
146
147         //
148         // MUTATORS
149         //
150
151         /**
152          * Sets the nickname chooser. The nickname chooser is only used during the
153          * creation of the connection.
154          *
155          * @param nicknameChooser
156          *              The nickname chooser
157          * @return This connection
158          */
159         public Connection nicknameChooser(NicknameChooser nicknameChooser) {
160                 this.nicknameChooser = nicknameChooser;
161                 return this;
162         }
163
164         /**
165          * Sets the username to use.
166          *
167          * @param username
168          *              The username to use
169          * @return This connection
170          */
171         public Connection username(String username) {
172                 this.username = Optional.fromNullable(username);
173                 return this;
174         }
175
176         /**
177          * Sets the real name to use.
178          *
179          * @param realName
180          *              The real name to use
181          * @return This connection
182          */
183         public Connection realName(String realName) {
184                 this.realName = Optional.fromNullable(realName);
185                 return this;
186         }
187
188         /**
189          * Sets the optional password for the connection.
190          *
191          * @param password
192          *              The password for the connection
193          * @return This connection
194          */
195         public Connection password(String password) {
196                 this.password = Optional.fromNullable(password);
197                 return this;
198         }
199
200         //
201         // ACTIONS
202         //
203
204         /**
205          * Checks whether the given source is the client represented by this
206          * connection.
207          *
208          * @param source
209          *              The source to check
210          * @return {@code true} if this connection represents the given source, {@code
211          *         false} otherwise
212          */
213         public boolean isSource(Source source) {
214                 return source.nick().isPresent() && source.nick().get().equals(nickname);
215         }
216
217         /**
218          * Joins the given channel.
219          *
220          * @param channel
221          *              The channel to join
222          * @throws IOException
223          *              if an I/O error occurs
224          */
225         public void joinChannel(final String channel) throws IOException {
226                 connectionHandler.sendCommand("JOIN", channel);
227         }
228
229         /**
230          * Sends a message to the given recipient, which may be a channel or another
231          * nickname.
232          *
233          * @param recipient
234          *              The recipient of the message
235          * @param message
236          *              The message
237          * @throws IOException
238          *              if an I/O error occurs
239          */
240         public void sendMessage(String recipient, String message) throws IOException {
241                 connectionHandler.sendCommand("PRIVMSG", recipient, message);
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                                         String message = parameters.get(1);
298                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
299                                                 /* CTCP! */
300                                                 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
301                                                 String ctcpCommand = messageWords[0];
302                                                 if (ctcpCommand.equalsIgnoreCase("DCC")) {
303                                                         if (messageWords[1].equalsIgnoreCase("SEND")) {
304                                                                 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
305                                                                 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
306                                                                 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
307                                                                 if (inetAddress.isPresent() && port.isPresent()) {
308                                                                         eventBus.post(new DccSendReceived(this, reply.source().get(), messageWords[2], inetAddress.get(), port.get(), fileSize));
309                                                                 } else {
310                                                                         logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
311                                                                 }
312                                                         }
313                                                 }
314                                         } else if (!channelTypes.contains(recipient.charAt(0))) {
315                                                 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
316                                         } else {
317                                                 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
318                                         }
319
320                                 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
321                                 } else if (command.equals("001")) {
322                                         connectionStatus |= 0x01;
323                                 } else if (command.equals("002")) {
324                                         connectionStatus |= 0x02;
325                                 } else if (command.equals("003")) {
326                                         connectionStatus |= 0x04;
327                                 } else if (command.equals("004")) {
328                                         connectionStatus |= 0x08;
329
330                                 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
331                                 } else if (command.equals("005")) {
332                                         for (String parameter : parameters) {
333                                                 if (parameter.startsWith("PREFIX=")) {
334                                                         int openParen = parameter.indexOf('(');
335                                                         int closeParen = parameter.indexOf(')');
336                                                         if ((openParen != -1) && (closeParen != -1)) {
337                                                                 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
338                                                                         char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
339                                                                         char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
340                                                                         nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
341                                                                 }
342                                                                 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
343                                                         }
344                                                 } else if (parameter.startsWith("CHANTYPES=")) {
345                                                         for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
346                                                                 channelTypes.add(parameter.charAt(typeIndex));
347                                                         }
348                                                         logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
349                                                 }
350                                         }
351
352                                 /* 375, 372, and 376 handle the server’s MOTD. */
353                                 } else if (command.equals("375")) {
354                                         /* MOTD starts. */
355                                         motd.append(parameters.get(1)).append('\n');
356                                 } else if (command.equals("372")) {
357                                         motd.append(parameters.get(1)).append('\n');
358                                 } else if (command.equals("376")) {
359                                         motd.append(parameters.get(1)).append('\n');
360                                         eventBus.post(new MotdReceived(this, motd.toString()));
361                                         motd.setLength(0);
362
363                                 /* 43x replies are for nick change errors. */
364                                 } else if (command.equals("431")) {
365                                         eventBus.post(new NoNicknameGivenReceived(this, reply));
366                                 } else if (command.equals("433")) {
367                                         if (connectionStatus == 0) {
368                                                 nickname = nicknameChooser.getNickname();
369                                                 connectionHandler.sendCommand("NICK", nickname);
370                                         } else {
371                                                 eventBus.post(new NicknameInUseReceived(this, reply));
372                                         }
373
374                                 /* channel stuff. */
375                                 } else if (command.equalsIgnoreCase("JOIN")) {
376                                         eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
377                                 } else if (command.equals("331")) {
378                                         /* no topic is set. */
379                                 } else if (command.equals("332")) {
380                                         eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
381                                 } else if (command.equals("353")) {
382                                         for (String nickname : parameters.get(3).split(" ")) {
383                                                 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
384                                                         nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
385                                                 } else {
386                                                         nicks.add(new Nickname(nickname, ""));
387                                                 }
388                                         }
389                                 } else if (command.equals("366")) {
390                                         eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
391                                         nicks.clear();
392                                 } else if (command.equalsIgnoreCase("PART")) {
393                                         eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), parameters.get(1)));
394
395                                 /* common channel join errors. */
396                                 } else if (command.equals("474")) {
397                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
398                                 } else if (command.equals("473")) {
399                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
400                                 } else if (command.equals("475")) {
401                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
402
403                                 /* basic connection housekeeping. */
404                                 } else if (command.equalsIgnoreCase("PING")) {
405                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
406
407                                 /* okay, everything else. */
408                                 } else {
409                                         eventBus.post(new UnknownReplyReceived(this, reply));
410                                 }
411
412                                 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
413                                         /* connection succeeded! */
414                                         eventBus.post(new ConnectionEstablished(this));
415                                 }
416                                 oldConnectionStatus = connectionStatus;
417                         }
418                 } catch (IOException ioe1) {
419                         logger.log(Level.WARNING, "I/O error", ioe1);
420                 } finally {
421                         logger.info("Closing Connection.");
422                         try {
423                                 Closeables.close(connectionHandler, true);
424                         } catch (IOException ioe1) {
425                                 /* will not be thrown. */
426                         }
427                 }
428
429         }
430
431         //
432         // PRIVATE METHODS
433         //
434
435         /**
436          * Returns an item from the list, or {@link Optional#absent()} if the list is
437          * shorter than required for the given index.
438          *
439          * @param list
440          *              The list to get an item from
441          * @param index
442          *              The index of the item
443          * @param <T>
444          *              The type of the list items
445          * @return This list item wrapped in an {@link Optional}, or {@link
446          *         Optional#absent()} if the list is not long enough
447          */
448         private static <T> Optional<T> getOptional(List<T> list, int index) {
449                 if (index < list.size()) {
450                         return Optional.fromNullable(list.get(index));
451                 }
452                 return Optional.absent();
453         }
454
455         /**
456          * Parses the given {@code ip} and returns an {@link InetAddress} from it.
457          *
458          * @param ip
459          *              The IP to parse
460          * @return The parsed inet address, or {@link Optional#absent()} if no inet
461          *         address could be parsed
462          */
463         private Optional<InetAddress> parseInetAddress(String ip) {
464                 Long ipNumber = Longs.tryParse(ip);
465                 if (ipNumber == null) {
466                         return Optional.absent();
467                 }
468
469                 StringBuilder hostname = new StringBuilder(15);
470                 hostname.append((ipNumber >>> 24) & 0xff).append('.');
471                 hostname.append((ipNumber >>> 16) & 0xff).append('.');
472                 hostname.append((ipNumber >>> 8) & 0xff).append('.');
473                 hostname.append(ipNumber & 0xff);
474                 try {
475                         return Optional.of(InetAddress.getByName(hostname.toString()));
476                 } catch (UnknownHostException uhe1) {
477                         return Optional.absent();
478                 }
479         }
480
481         /** Handles input and output for the connection. */
482         private class ConnectionHandler implements Closeable {
483
484                 /** The output stream of the connection. */
485                 private final OutputStream outputStream;
486
487                 /** The input stream of the connection. */
488                 private final BufferedReader inputStreamReader;
489
490                 /**
491                  * Creates a new connection handler for the given input stream and output
492                  * stream.
493                  *
494                  * @param inputStream
495                  *              The input stream of the connection
496                  * @param outputStream
497                  *              The output stream of the connection
498                  * @throws UnsupportedEncodingException
499                  *              if the encoding (currently “UTF-8”) is not valid
500                  */
501                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
502                         this.outputStream = outputStream;
503                         inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
504                 }
505
506                 //
507                 // ACTIONS
508                 //
509
510                 /**
511                  * Sends a command with the given parameters, skipping all {@link
512                  * Optional#absent()} optionals.
513                  *
514                  * @param command
515                  *              The command to send
516                  * @param parameters
517                  *              The parameters
518                  * @throws IOException
519                  *              if an I/O error occurs
520                  */
521                 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
522                         List<String> setParameters = new ArrayList<String>();
523                         for (Optional<String> maybeSetParameter : parameters) {
524                                 if (maybeSetParameter.isPresent()) {
525                                         setParameters.add(maybeSetParameter.get());
526                                 }
527                         }
528                         sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
529                 }
530
531                 /**
532                  * Sends a command with the given parameters.
533                  *
534                  * @param command
535                  *              The command to send
536                  * @param parameters
537                  *              The parameters of the command
538                  * @throws IOException
539                  *              if an I/O error occurs
540                  * @throws IllegalArgumentException
541                  *              if any parameter but that last contains a space character
542                  */
543                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
544                         StringBuilder commandBuilder = new StringBuilder();
545
546                         commandBuilder.append(command);
547                         for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
548                                 String parameter = parameters[parameterIndex];
549                                 /* space is only allowed in the last parameter. */
550                                 commandBuilder.append(' ');
551                                 if (parameter.contains(" ")) {
552                                         if (parameterIndex == (parameters.length - 1)) {
553                                                 commandBuilder.append(':');
554                                         } else {
555                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
556                                         }
557                                 }
558                                 commandBuilder.append(parameter);
559                         }
560
561                         logger.finest(String.format(">> %s", commandBuilder));
562                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
563                         outputStream.flush();
564                 }
565
566                 /**
567                  * Reads a line of reply from the connection.
568                  *
569                  * @return The reply
570                  * @throws IOException
571                  *              if an I/O error occurs
572                  * @throws EOFException
573                  *              if EOF was reached
574                  */
575                 public Reply readReply() throws IOException, EOFException {
576                         String line = inputStreamReader.readLine();
577                         if (line == null) {
578                                 throw new EOFException();
579                         }
580
581                         return Reply.parseLine(line);
582                 }
583
584                 //
585                 // CLOSEABLE METHODS
586                 //
587
588                 @Override
589                 public void close() throws IOException {
590                         Closeables.close(outputStream, true);
591                         Closeables.close(inputStreamReader, true);
592                 }
593
594         }
595
596 }