Move nick changes into simple command handler.
[xudocci.git] / src / main / java / net / pterodactylus / irc / Connection.java
index 15dde44..30344be 100644 (file)
@@ -18,6 +18,7 @@
 package net.pterodactylus.irc;
 
 import static com.google.common.base.Preconditions.checkState;
+import static java.util.Arrays.asList;
 import static java.util.concurrent.TimeUnit.SECONDS;
 
 import java.io.BufferedReader;
@@ -28,51 +29,47 @@ import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.io.UnsupportedEncodingException;
-import java.net.InetAddress;
 import java.net.Socket;
-import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
 import javax.net.SocketFactory;
 
+import net.pterodactylus.irc.connection.ChannelNickHandler;
+import net.pterodactylus.irc.connection.ChannelNotJoinedHandler;
+import net.pterodactylus.irc.connection.ConnectionEstablishHandler;
+import net.pterodactylus.irc.connection.CtcpHandler;
+import net.pterodactylus.irc.connection.Handler;
+import net.pterodactylus.irc.connection.MessageHandler;
+import net.pterodactylus.irc.connection.MotdHandler;
+import net.pterodactylus.irc.connection.PrefixHandler;
+import net.pterodactylus.irc.connection.SimpleCommandHandler;
 import net.pterodactylus.irc.event.ChannelJoined;
 import net.pterodactylus.irc.event.ChannelLeft;
-import net.pterodactylus.irc.event.ChannelMessageReceived;
-import net.pterodactylus.irc.event.ChannelNicknames;
-import net.pterodactylus.irc.event.ChannelNotJoined;
-import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
-import net.pterodactylus.irc.event.ChannelNoticeReceived;
 import net.pterodactylus.irc.event.ChannelTopic;
 import net.pterodactylus.irc.event.ClientQuit;
 import net.pterodactylus.irc.event.ConnectionClosed;
 import net.pterodactylus.irc.event.ConnectionEstablished;
 import net.pterodactylus.irc.event.ConnectionFailed;
-import net.pterodactylus.irc.event.DccAcceptReceived;
-import net.pterodactylus.irc.event.DccSendReceived;
-import net.pterodactylus.irc.event.MotdReceived;
+import net.pterodactylus.irc.event.KickedFromChannel;
 import net.pterodactylus.irc.event.NicknameChanged;
 import net.pterodactylus.irc.event.NicknameInUseReceived;
 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
-import net.pterodactylus.irc.event.PrivateMessageReceived;
-import net.pterodactylus.irc.event.PrivateNoticeReceived;
+import net.pterodactylus.irc.event.ReplyReceived;
 import net.pterodactylus.irc.event.UnknownReplyReceived;
 import net.pterodactylus.irc.util.RandomNickname;
 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
 
 import com.google.common.base.Optional;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
 import com.google.common.eventbus.EventBus;
+import com.google.common.eventbus.Subscribe;
 import com.google.common.io.Closeables;
-import com.google.common.primitives.Ints;
-import com.google.common.primitives.Longs;
 import com.google.common.util.concurrent.AbstractExecutionThreadService;
 import com.google.common.util.concurrent.Service;
+import org.apache.log4j.Logger;
 
 /**
  * A connection to an IRC server.
@@ -121,7 +118,7 @@ public class Connection extends AbstractExecutionThreadService implements Servic
        private ConnectionHandler connectionHandler;
 
        /** Whether the connection has already been established. */
-       private boolean established;
+       private final AtomicBoolean established = new AtomicBoolean();
 
        /**
         * Creates a new connection.
@@ -171,7 +168,7 @@ public class Connection extends AbstractExecutionThreadService implements Servic
         *         false} otherwise
         */
        public boolean established() {
-               return established;
+               return established.get();
        }
 
        /**
@@ -324,7 +321,9 @@ public class Connection extends AbstractExecutionThreadService implements Servic
         *              if an I/O error occurs
         */
        public void close() throws IOException {
-               connectionHandler.close();
+               if (connectionHandler != null) {
+                       connectionHandler.close();
+               }
        }
 
        //
@@ -343,6 +342,7 @@ public class Connection extends AbstractExecutionThreadService implements Servic
                /* connect to remote socket. */
                try {
                        Socket socket = socketFactory.createSocket(hostname, port);
+                       socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
                        connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
 
                        /* register connection. */
@@ -358,65 +358,52 @@ public class Connection extends AbstractExecutionThreadService implements Servic
                        return;
                }
 
+               eventBus.register(this);
                /* now read replies and react. */
                try {
                        /* some status variables. */
-                       int oldConnectionStatus = 0;
-                       int connectionStatus = 0;
                        boolean connected = true;
-                       StringBuilder motd = new StringBuilder();
-                       Set<Nickname> nicks = Sets.newHashSet();
 
-                       /* server modes. */
-                       Map<String, String> nickPrefixes = Maps.newHashMap();
-                       Set<Character> channelTypes = Sets.newHashSet();
+                       PrefixHandler prefixHandler = new PrefixHandler();
+                       List<Handler> handlers = asList(
+                                       new MessageHandler(eventBus, this, prefixHandler),
+                                       new CtcpHandler(eventBus, this),
+                                       new ChannelNickHandler(eventBus, this, prefixHandler),
+                                       new SimpleCommandHandler()
+                                                       .addCommand("431", (s, p) -> eventBus.post(
+                                                                       new NoNicknameGivenReceived(this)))
+                                                       .addCommand("NICK", (s, p) -> eventBus.post(
+                                                                       new NicknameChanged(this, s.get(),
+                                                                                       p.get(0)))),
+                                       new MotdHandler(eventBus, this),
+                                       new ChannelNotJoinedHandler(eventBus, this),
+                                       new ConnectionEstablishHandler(eventBus, this),
+                                       prefixHandler
+                       );
 
                        while (connected) {
                                Reply reply = connectionHandler.readReply();
-                               logger.finest(String.format("<< %s", reply));
+                               eventBus.post(new ReplyReceived(this, reply));
+                               logger.trace(String.format("<< %s", reply));
                                String command = reply.command();
                                List<String> parameters = reply.parameters();
 
-                               /* most common events. */
-                               if (command.equalsIgnoreCase("PRIVMSG")) {
-                                       String recipient = parameters.get(0);
-                                       String message = parameters.get(1);
-                                       if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
-                                               /* CTCP! */
-                                               handleCtcp(reply.source().get(), message);
-                                       } else if (!channelTypes.contains(recipient.charAt(0))) {
-                                               eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
-                                       } else {
-                                               eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
-                                       }
-
-                               } else if (command.equalsIgnoreCase("NOTICE")) {
-                                       String recipient = parameters.get(0);
-                                       String message = parameters.get(1);
-                                       if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
-                                               /* CTCP! */
-                                               handleCtcp(reply.source().get(), message);
-                                       } else if (!channelTypes.contains(recipient.charAt(0))) {
-                                               eventBus.post(new PrivateNoticeReceived(this, reply));
-                                       } else {
-                                               eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
+                               for (Handler handler : handlers) {
+                                       if (handler.willHandle(reply)) {
+                                               handler.handleReply(reply);
+                                               break;
                                        }
+                               }
 
                                /* 43x replies are for nick change errors. */
-                               } else if (command.equals("431")) {
-                                       eventBus.post(new NoNicknameGivenReceived(this, reply));
-                               } else if (command.equals("433")) {
-                                       if (connectionStatus == 0) {
+                               if (command.equals("433")) {
+                                       if (!established.get()) {
                                                nickname = nicknameChooser.getNickname();
                                                connectionHandler.sendCommand("NICK", nickname);
                                        } else {
                                                eventBus.post(new NicknameInUseReceived(this, reply));
                                        }
 
-                               /* client stuff. */
-                               } else if (command.equalsIgnoreCase("NICK")) {
-                                       eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
-
                                /* channel stuff. */
                                } else if (command.equalsIgnoreCase("JOIN")) {
                                        eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
@@ -424,95 +411,33 @@ public class Connection extends AbstractExecutionThreadService implements Servic
                                        /* no topic is set. */
                                } else if (command.equals("332")) {
                                        eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
-                               } else if (command.equals("353")) {
-                                       for (String nickname : parameters.get(3).split(" ")) {
-                                               if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
-                                                       nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
-                                               } else {
-                                                       nicks.add(new Nickname(nickname, ""));
-                                               }
-                                       }
-                               } else if (command.equals("366")) {
-                                       eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
-                                       nicks.clear();
                                } else if (command.equalsIgnoreCase("PART")) {
                                        eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
                                } else if (command.equalsIgnoreCase("QUIT")) {
                                        eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
 
-                               /* common channel join errors. */
-                               } else if (command.equals("474")) {
-                                       eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
-                               } else if (command.equals("473")) {
-                                       eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
-                               } else if (command.equals("475")) {
-                                       eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
-
                                /* basic connection housekeeping. */
                                } else if (command.equalsIgnoreCase("PING")) {
                                        connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
 
-                               /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
-                               } else if (command.equals("001")) {
-                                       connectionStatus |= 0x01;
-                               } else if (command.equals("002")) {
-                                       connectionStatus |= 0x02;
-                               } else if (command.equals("003")) {
-                                       connectionStatus |= 0x04;
-                               } else if (command.equals("004")) {
-                                       connectionStatus |= 0x08;
-
-                               /* 005 originally was a bounce message, now used to transmit useful information about the server. */
-                               } else if (command.equals("005")) {
-                                       for (String parameter : parameters) {
-                                               if (parameter.startsWith("PREFIX=")) {
-                                                       int openParen = parameter.indexOf('(');
-                                                       int closeParen = parameter.indexOf(')');
-                                                       if ((openParen != -1) && (closeParen != -1)) {
-                                                               for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
-                                                                       char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
-                                                                       char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
-                                                                       nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
-                                                               }
-                                                               logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
-                                                       }
-                                               } else if (parameter.startsWith("CHANTYPES=")) {
-                                                       for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
-                                                               channelTypes.add(parameter.charAt(typeIndex));
-                                                       }
-                                                       logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
-                                               }
-                                       }
-
-                               /* 375, 372, and 376 handle the server’s MOTD. */
-                               } else if (command.equals("375")) {
-                                       /* MOTD starts. */
-                                       motd.append(parameters.get(1)).append('\n');
-                               } else if (command.equals("372")) {
-                                       motd.append(parameters.get(1)).append('\n');
-                               } else if (command.equals("376")) {
-                                       motd.append(parameters.get(1)).append('\n');
-                                       eventBus.post(new MotdReceived(this, motd.toString()));
-                                       motd.setLength(0);
+                               } else if (command.equalsIgnoreCase("KICK")) {
+                                       eventBus.post(new KickedFromChannel(this, parameters.get(0), reply.source().get(), parameters.get(1), getOptional(parameters, 2)));
 
                                /* okay, everything else. */
                                } else {
                                        eventBus.post(new UnknownReplyReceived(this, reply));
                                }
-
-                               if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
-                                       /* connection succeeded! */
-                                       established = true;
-                                       eventBus.post(new ConnectionEstablished(this));
-                               }
-                               oldConnectionStatus = connectionStatus;
                        }
                        eventBus.post(new ConnectionClosed(this));
                } catch (IOException ioe1) {
-                       logger.log(Level.WARNING, "I/O error", ioe1);
+                       logger.warn("I/O error", ioe1);
                        eventBus.post(new ConnectionClosed(this, ioe1));
+               } catch (RuntimeException re1) {
+                       logger.error("Runtime error", re1);
+                       eventBus.post(new ConnectionClosed(this, re1));
                } finally {
-                       established = false;
+                       established.set(false);
+                       eventBus.unregister(this);
                        logger.info("Closing Connection.");
                        try {
                                Closeables.close(connectionHandler, true);
@@ -523,44 +448,18 @@ public class Connection extends AbstractExecutionThreadService implements Servic
 
        }
 
+       @Subscribe
+       public void connectionEstablished(ConnectionEstablished connectionEstablished) {
+               if (connectionEstablished.connection() == this) {
+                       established.set(true);
+               }
+       }
+
        //
        // PRIVATE METHODS
        //
 
        /**
-        * Handles a CTCP message.
-        *
-        * @param client
-        *              The client sending the message
-        * @param message
-        *              The message
-        */
-       private void handleCtcp(Source client, String message) {
-               String[] messageWords = message.substring(1, message.length() - 1).split(" +");
-               String ctcpCommand = messageWords[0];
-               if (ctcpCommand.equalsIgnoreCase("DCC")) {
-                       if (messageWords[1].equalsIgnoreCase("SEND")) {
-                               Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
-                               Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
-                               long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
-                               if (inetAddress.isPresent() && port.isPresent()) {
-                                       eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
-                               } else {
-                                       logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
-                               }
-                       } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
-                               Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
-                               long position = Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L);
-                               if (port.isPresent()) {
-                                       eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
-                               } else {
-                                       logger.warning(String.format("Received malformed DCC ACCEPT: “%s”", message));
-                               }
-                       }
-               }
-       }
-
-       /**
         * Returns an item from the list, or {@link Optional#absent()} if the list is
         * shorter than required for the given index.
         *
@@ -580,32 +479,6 @@ public class Connection extends AbstractExecutionThreadService implements Servic
                return Optional.absent();
        }
 
-       /**
-        * Parses the given {@code ip} and returns an {@link InetAddress} from it.
-        *
-        * @param ip
-        *              The IP to parse
-        * @return The parsed inet address, or {@link Optional#absent()} if no inet
-        *         address could be parsed
-        */
-       private Optional<InetAddress> parseInetAddress(String ip) {
-               Long ipNumber = Longs.tryParse(ip);
-               if (ipNumber == null) {
-                       return Optional.absent();
-               }
-
-               StringBuilder hostname = new StringBuilder(15);
-               hostname.append((ipNumber >>> 24) & 0xff).append('.');
-               hostname.append((ipNumber >>> 16) & 0xff).append('.');
-               hostname.append((ipNumber >>> 8) & 0xff).append('.');
-               hostname.append(ipNumber & 0xff);
-               try {
-                       return Optional.of(InetAddress.getByName(hostname.toString()));
-               } catch (UnknownHostException uhe1) {
-                       return Optional.absent();
-               }
-       }
-
        /** Handles input and output for the connection. */
        private class ConnectionHandler implements Closeable {
 
@@ -708,7 +581,7 @@ public class Connection extends AbstractExecutionThreadService implements Servic
                                commandBuilder.append(parameter);
                        }
 
-                       logger.finest(String.format(">> %s", commandBuilder));
+                       logger.trace(String.format(">> %s", commandBuilder));
                        outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
                        outputStream.flush();
                }
@@ -739,6 +612,7 @@ public class Connection extends AbstractExecutionThreadService implements Servic
                public void close() throws IOException {
                        Closeables.close(outputStream, true);
                        Closeables.close(inputStreamReader, true);
+                       Closeables.close(inputStream, true);
                }
 
        }