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