+/*
+ * XdccDownloader - Connection.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.irc;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import java.io.BufferedReader;
+import java.io.Closeable;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.SynchronousQueue;
+import javax.net.SocketFactory;
+
+import net.pterodactylus.irc.event.ChannelJoined;
+import net.pterodactylus.irc.event.ChannelNicknames;
+import net.pterodactylus.irc.event.ChannelNotJoined;
+import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
+import net.pterodactylus.irc.event.ChannelTopic;
+import net.pterodactylus.irc.event.ConnectionEstablished;
+import net.pterodactylus.irc.event.ConnectionFailed;
+import net.pterodactylus.irc.event.MotdReceived;
+import net.pterodactylus.irc.event.NicknameInUseReceived;
+import net.pterodactylus.irc.event.NoNicknameGivenReceived;
+import net.pterodactylus.irc.event.UnknownReplyReceived;
+import net.pterodactylus.irc.util.RandomNickname;
+
+import com.beust.jcommander.internal.Maps;
+import com.beust.jcommander.internal.Sets;
+import com.google.common.base.Optional;
+import com.google.common.eventbus.EventBus;
+import com.google.common.eventbus.Subscribe;
+import com.google.common.io.Closeables;
+import com.google.common.util.concurrent.AbstractExecutionThreadService;
+import com.google.common.util.concurrent.Service;
+
+/**
+ * A connection to an IRC server.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public class Connection extends AbstractExecutionThreadService implements Service {
+
+ /** The event bus. */
+ private final EventBus eventBus;
+
+ /** The socket factory. */
+ private final SocketFactory socketFactory;
+
+ /** The hostname to connect to. */
+ private final String hostname;
+
+ /** The port to connect to. */
+ private final int port;
+
+ /** The nickname chooser. */
+ private NicknameChooser nicknameChooser = new NicknameChooser() {
+
+ @Override
+ public String getNickname() {
+ return RandomNickname.get();
+ }
+ };
+
+ /** The nickname. */
+ private String nickname = null;
+
+ /** The username. */
+ private Optional<String> username = Optional.absent();
+
+ /** The real name. */
+ private Optional<String> realName = Optional.absent();
+
+ /** The optional password for the connection. */
+ private Optional<String> password = Optional.absent();
+
+ /** The connection handler. */
+ private ConnectionHandler connectionHandler;
+
+ /**
+ * Creates a new connection.
+ *
+ * @param eventBus
+ * The event bus
+ * @param socketFactory
+ * The socket factory
+ * @param hostname
+ * The hostname of the IRC server
+ * @param port
+ * The port number of the IRC server
+ */
+ public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
+ this.eventBus = eventBus;
+ this.socketFactory = socketFactory;
+ this.hostname = hostname;
+ this.port = port;
+ }
+
+ //
+ // ACCESSORS
+ //
+
+ /**
+ * Returns the nickname that is currently in use by this connection. The
+ * nickname is only available once the connection has been {@link #start()}ed.
+ *
+ * @return The current nickname
+ */
+ public String nickname() {
+ return nickname;
+ }
+
+ //
+ // MUTATORS
+ //
+
+ /**
+ * Sets the nickname chooser. The nickname chooser is only used during the
+ * creation of the connection.
+ *
+ * @param nicknameChooser
+ * The nickname chooser
+ * @return This connection
+ */
+ public Connection nicknameChooser(NicknameChooser nicknameChooser) {
+ this.nicknameChooser = nicknameChooser;
+ return this;
+ }
+
+ /**
+ * Sets the username to use.
+ *
+ * @param username
+ * The username to use
+ * @return
+ */
+ public Connection username(String username) {
+ this.username = Optional.fromNullable(username);
+ return this;
+ }
+
+ /**
+ * Sets the real name to use.
+ *
+ * @param realName
+ * The real name to use
+ * @return This connection
+ */
+ public Connection realName(String realName) {
+ this.realName = Optional.fromNullable(realName);
+ return this;
+ }
+
+ /**
+ * Sets the optional password for the connection.
+ *
+ * @param password
+ * The password for the connection
+ * @return This connection
+ */
+ public Connection password(String password) {
+ this.password = Optional.fromNullable(password);
+ return this;
+ }
+
+ //
+ // ACTIONS
+ //
+
+ /**
+ * Joins the given channel.
+ *
+ * @param channel
+ * The channel to join
+ * @return {@code true} if the channel was joined, {@code false} otherwise
+ */
+ public boolean joinChannel(final String channel) {
+ final SynchronousQueue<Boolean> result = new SynchronousQueue<Boolean>();
+ Object eventHandler = new Object() {
+
+ @Subscribe
+ public void channelJoined(ChannelJoined channelJoined) throws InterruptedException {
+ if (!channelJoined.channel().equalsIgnoreCase(channel)) {
+ return;
+ }
+ Optional<String> nickname = channelJoined.client().nick();
+ if (!nickname.isPresent() || (nickname.isPresent() && nickname().equalsIgnoreCase(nickname.get()))) {
+ eventBus.unregister(this);
+ result.put(true);
+ }
+ }
+
+ @Subscribe
+ public void channelNotJoined(ChannelNotJoined channelNotJoined) throws InterruptedException {
+ if (!channelNotJoined.channel().equalsIgnoreCase(channel)) {
+ return;
+ }
+ eventBus.unregister(this);
+ result.put(false);
+ }
+ };
+ eventBus.register(eventHandler);
+ try {
+ connectionHandler.sendCommand("JOIN", channel);
+ return result.take();
+ } catch (IOException ioe1) {
+ eventBus.unregister(eventHandler);
+ } catch (InterruptedException ie1) {
+ /* TODO - how to handle? */
+ }
+ return false;
+ }
+
+ //
+ // ABSTRACTEXECUTIONTHREADSERVICE METHODS
+ //
+
+ @Override
+ protected void startUp() throws IllegalStateException {
+ checkState(username.isPresent(), "username must be set");
+ checkState(realName.isPresent(), "realName must be set");
+ }
+
+ @Override
+ protected void run() {
+
+ /* connect to remote socket. */
+ try {
+ Socket socket = socketFactory.createSocket(hostname, port);
+ connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
+
+ /* register connection. */
+ if (password.isPresent()) {
+ connectionHandler.sendCommand("PASSWORD", password.get());
+ }
+ connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
+ nickname = nicknameChooser.getNickname();
+ connectionHandler.sendCommand("NICK", nickname);
+
+ } catch (IOException ioe1) {
+ eventBus.post(new ConnectionFailed(this, ioe1));
+ return;
+ }
+
+ /* 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();
+
+ while (connected) {
+ Reply reply = connectionHandler.readReply();
+ System.err.println("<< " + reply);
+ String command = reply.command();
+ List<String> parameters = reply.parameters();
+
+ /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
+ 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));
+ }
+ }
+ }
+ }
+
+ /* 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);
+
+ /* 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) {
+ nickname = nicknameChooser.getNickname();
+ connectionHandler.sendCommand("NICK", nickname);
+ } else {
+ eventBus.post(new NicknameInUseReceived(this, reply));
+ }
+
+ /* channel stuff. */
+ } else if (command.equalsIgnoreCase("JOIN")) {
+ eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
+ } else if (command.equals("331")) {
+ /* 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")) {
+ String channel = parameters.get(2);
+ 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));
+ System.out.println("Found Nicknames: " + nicks);
+ nicks.clear();
+
+ /* 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));
+
+ /* okay, everything else. */
+ } else {
+ eventBus.post(new UnknownReplyReceived(this, reply));
+ }
+
+ if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
+ /* connection succeeded! */
+ eventBus.post(new ConnectionEstablished(this));
+ }
+ oldConnectionStatus = connectionStatus;
+ }
+ } catch (IOException ioe1) {
+ ioe1.printStackTrace();
+ } finally {
+ System.out.println("Closing Connection.");
+ try {
+ Closeables.close(connectionHandler, true);
+ } catch (IOException ioe1) {
+ /* will not be thrown. */
+ }
+ }
+
+ }
+
+ //
+ // PRIVATE METHODS
+ //
+
+ /**
+ * Returns an item from the list, or {@link Optional#absent()} if the list is
+ * shorter than required for the given index.
+ *
+ * @param list
+ * The list to get an item from
+ * @param index
+ * The index of the item
+ * @param <T>
+ * The type of the list items
+ * @return This list item wrapped in an {@link Optional}, or {@link
+ * Optional#absent()} if the list is not long enough
+ */
+ private static <T> Optional<T> getOptional(List<T> list, int index) {
+ if (index < list.size()) {
+ return Optional.fromNullable(list.get(index));
+ }
+ return Optional.absent();
+ }
+
+ /** Handles input and output for the connection. */
+ private class ConnectionHandler implements Closeable {
+
+ /** The output stream of the connection. */
+ private final OutputStream outputStream;
+
+ /** The input stream of the connection. */
+ private final BufferedReader inputStreamReader;
+
+ /**
+ * Creates a new connection handler for the given input stream and output
+ * stream.
+ *
+ * @param inputStream
+ * The input stream of the connection
+ * @param outputStream
+ * The output stream of the connection
+ * @throws UnsupportedEncodingException
+ * if the encoding (currently “UTF-8”) is not valid
+ */
+ private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
+ this.outputStream = outputStream;
+ inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
+ }
+
+ //
+ // ACTIONS
+ //
+
+ /**
+ * Sends a command with the given parameters, skipping all {@link
+ * Optional#absent()} optionals.
+ *
+ * @param command
+ * The command to send
+ * @param parameters
+ * The parameters
+ * @throws IOException
+ * if an I/O error occurs
+ */
+ public void sendCommand(String command, Optional<String>... parameters) throws IOException {
+ List<String> setParameters = new ArrayList<String>();
+ for (Optional<String> maybeSetParameter : parameters) {
+ if (maybeSetParameter.isPresent()) {
+ setParameters.add(maybeSetParameter.get());
+ }
+ }
+ sendCommand(command, setParameters.toArray(new String[0]));
+ }
+
+ /**
+ * Sends a command with the given parameters.
+ *
+ * @param command
+ * The command to send
+ * @param parameters
+ * The parameters of the command
+ * @throws IOException
+ * if an I/O error occurs
+ * @throws IllegalArgumentException
+ * if any parameter but that last contains a space character
+ */
+ public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
+ StringBuilder commandBuilder = new StringBuilder();
+
+ commandBuilder.append(command);
+ for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
+ String parameter = parameters[parameterIndex];
+ /* space is only allowed in the last parameter. */
+ commandBuilder.append(' ');
+ if (parameter.contains(" ")) {
+ if (parameterIndex == (parameters.length - 1)) {
+ commandBuilder.append(':');
+ } else {
+ throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
+ }
+ }
+ commandBuilder.append(parameter);
+ }
+
+ System.out.println(">> " + commandBuilder.toString());
+ outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
+ outputStream.flush();
+ }
+
+ /**
+ * Reads a line of reply from the connection.
+ *
+ * @return The reply
+ * @throws IOException
+ * if an I/O error occurs
+ * @throws EOFException
+ * if EOF was reached
+ */
+ public Reply readReply() throws IOException, EOFException {
+ String line = inputStreamReader.readLine();
+ if (line == null) {
+ throw new EOFException();
+ }
+
+ return Reply.parseLine(line);
+ }
+
+ //
+ // CLOSEABLE METHODS
+ //
+
+ @Override
+ public void close() throws IOException {
+ Closeables.close(outputStream, true);
+ Closeables.close(inputStreamReader, true);
+ }
+
+ }
+
+}