Encodings are now honored for both sending and receiving. Cleaned up encode/decode
[quassel.git] / src / core / networkconnection.cpp
index 0369c21..ed1a72b 100644 (file)
@@ -36,6 +36,7 @@
 #include "ctcphandler.h"
 
 NetworkConnection::NetworkConnection(Network *network, CoreSession *session, const QVariant &state) : QObject(network),
+    _connectionState(Network::Disconnected),
     _network(network),
     _coreSession(session),
     _ircServerHandler(new IrcServerHandler(this)),
@@ -43,10 +44,10 @@ NetworkConnection::NetworkConnection(Network *network, CoreSession *session, con
     _ctcpHandler(new CtcpHandler(this)),
     _previousState(state)
 {
-  connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(sendPerform()));
+  connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
 
   connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
-  //connect(&socket, SIGNAL(disconnected()), this, SLOT(quit())); FIXME
+  connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
@@ -54,13 +55,25 @@ NetworkConnection::NetworkConnection(Network *network, CoreSession *session, con
 }
 
 NetworkConnection::~NetworkConnection() {
+  disconnectFromIrc();
   delete _ircServerHandler;
   delete _userInputHandler;
   delete _ctcpHandler;
 }
 
 bool NetworkConnection::isConnected() const {
-  return socket.state() == QAbstractSocket::ConnectedState;
+  // return socket.state() == QAbstractSocket::ConnectedState;
+  return connectionState() == Network::Initialized;
+}
+
+Network::ConnectionState NetworkConnection::connectionState() const {
+  return _connectionState;
+}
+
+void NetworkConnection::setConnectionState(Network::ConnectionState state) {
+  _connectionState = state;
+  network()->setConnectionState(state);
+  emit connectionStateChanged(state);
 }
 
 NetworkId NetworkConnection::networkId() const {
@@ -71,6 +84,10 @@ QString NetworkConnection::networkName() const {
   return network()->networkName();
 }
 
+Identity *NetworkConnection::identity() const {
+  return coreSession()->identity(network()->identity());
+}
+
 Network *NetworkConnection::network() const {
   return _network;
 }
@@ -125,7 +142,7 @@ QByteArray NetworkConnection::userEncode(const QString &userNick, const QString
 
 
 void NetworkConnection::connectToIrc() {
-  QList<QVariantMap> serverList = network()->serverList();
+  QVariantList serverList = network()->serverList();
   Identity *identity = coreSession()->identity(network()->identity());
   if(!serverList.count()) {
     qWarning() << "Server list empty, ignoring connect request!";
@@ -135,34 +152,44 @@ void NetworkConnection::connectToIrc() {
     qWarning() << "Invalid identity configures, ignoring connect request!";
     return;
   }
-
   // TODO implement cycling / random servers
-  QString host = serverList[0]["Address"].toString();
-  quint16 port = serverList[0]["Port"].toUInt();
+  QString host = serverList[0].toMap()["Host"].toString();
+  quint16 port = serverList[0].toMap()["Port"].toUInt();
   displayStatusMsg(QString("Connecting to %1:%2...").arg(host).arg(port));
   socket.connectToHost(host, port);
 }
 
-void NetworkConnection::sendPerform() {
-  // TODO: reimplement perform List!
-  //// send performlist
-  //QStringList performList = networkSettings["Perform"].toString().split( "\n" );
-  //int count = performList.count();
-  //for(int a = 0; a < count; a++) {
-  //  if(!performList[a].isEmpty() ) {
-  //    userInput(network, "", performList[a]);
-  //  }
-  //}
-
-  // rejoin channels we've been in
+void NetworkConnection::networkInitialized(const QString &currentServer) {
+  if(currentServer.isEmpty()) return;
+
+  sendPerform();
+
+    // rejoin channels we've been in
   QStringList chans = _previousState.toStringList();
   if(chans.count() > 0) {
     qDebug() << "autojoining" << chans;
-    QString list = chans.join(",");
-    putCmd("join", QStringList(list));
+    QVariantList list;
+    foreach(QString chan, chans) list << serverEncode(chan);
+    putCmd("JOIN", list);  // FIXME check for 512 byte limit!
   }
   // delete _previousState, we won't need it again
   _previousState = QVariant();
+  // now we are initialized
+  setConnectionState(Network::Initialized);
+  network()->setConnected(true);
+  emit connected(networkId());
+}
+
+void NetworkConnection::sendPerform() {
+  BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
+  // do auto identify
+  if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
+    userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
+  }
+  // send perform list
+  foreach(QString line, network()->perform()) {
+    if(!line.isEmpty()) userInput(statusBuf, line);
+  }
 }
 
 QVariant NetworkConnection::state() const {
@@ -182,49 +209,73 @@ void NetworkConnection::socketHasData() {
   }
 }
 
-void NetworkConnection::socketError( QAbstractSocket::SocketError err ) {
-  Q_UNUSED(err);
-  qDebug() << "Socket Error!";
+void NetworkConnection::socketError(QAbstractSocket::SocketError) {
+  qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
+  emit connectionError(socket.errorString());
+  emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
+  network()->emitConnectionError(socket.errorString());
 }
 
 void NetworkConnection::socketConnected() {
-  emit connected(networkId());
+  //emit connected(networkId());  initialize first!
   Identity *identity = coreSession()->identity(network()->identity());
   if(!identity) {
     qWarning() << "Identity invalid!";
     disconnectFromIrc();
     return;
   }
-  putRawLine(QString("NICK :%1").arg(identity->nicks()[0]));  // FIXME: try more nicks if error occurs
-  putRawLine(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName()));
+  putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));  // FIXME: try more nicks if error occurs
+  putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
 }
 
-void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState state) {
-  Q_UNUSED(state);
-  //qDebug() << "Socket state changed: " << state;
+void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
+  Network::ConnectionState state;
+  switch(socketState) {
+    case QAbstractSocket::UnconnectedState:
+      state = Network::Disconnected;
+      break;
+    case QAbstractSocket::HostLookupState:
+    case QAbstractSocket::ConnectingState:
+      state = Network::Connecting;
+      break;
+    case QAbstractSocket::ConnectedState:
+      state = Network::Initializing;
+      break;
+    case QAbstractSocket::ClosingState:
+      state = Network::Disconnecting;
+      break;
+    default:
+      state = Network::Disconnected;
+  }
+  setConnectionState(state);
+}
+
+void NetworkConnection::socketDisconnected() {
+  network()->setConnected(false);
+  emit disconnected(networkId());
 }
 
 // FIXME switch to BufferId
-void NetworkConnection::userInput(QString buf, QString msg) {
+void NetworkConnection::userInput(BufferInfo buf, QString msg) {
   userInputHandler()->handleUserInput(buf, msg);
 }
 
-void NetworkConnection::putRawLine(QString s) {
+void NetworkConnection::putRawLine(QByteArray s) {
   s += "\r\n";
-  socket.write(s.toAscii());
+  socket.write(s);
 }
 
-void NetworkConnection::putCmd(QString cmd, QStringList params, QString prefix) {
-  QString msg;
+void NetworkConnection::putCmd(const QString &cmd, const QVariantList &params, const QByteArray &prefix) {
+  QByteArray msg;
   if(!prefix.isEmpty())
     msg += ":" + prefix + " ";
-  msg += cmd.toUpper();
-  
+  msg += cmd.toUpper().toAscii();
+
   for(int i = 0; i < params.size() - 1; i++) {
-    msg += " " + params[i];
+    msg += " " + params[i].toByteArray();
   }
   if(!params.isEmpty())
-    msg += " :" + params.last();
+    msg += " :" + params.last().toByteArray();
 
   putRawLine(msg);
 }