Finally here: the long awaited auto reconnect! Your auto reconnect settings
[quassel.git] / src / core / coresession.cpp
index 112f60c..23456ab 100644 (file)
  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
  ***************************************************************************/
 
+#include <QtScript>
+
 #include "core.h"
 #include "coresession.h"
 #include "networkconnection.h"
 
 #include "signalproxy.h"
+#include "buffersyncer.h"
 #include "storage.h"
 
 #include "network.h"
 #include "util.h"
 #include "coreusersettings.h"
 
-#include <QtScript>
-
 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent) : QObject(parent),
     _user(uid),
     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
+    _bufferSyncer(new BufferSyncer(this)),
     scriptEngine(new QScriptEngine(this))
 {
 
   SignalProxy *p = signalProxy();
 
-  CoreUserSettings s(user());
-  sessionData = s.sessionData();
-
   p->attachSlot(SIGNAL(requestConnect(QString)), this, SLOT(connectToNetwork(QString)));
   p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
@@ -55,9 +54,6 @@ CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent) : QObje
   p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
   p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
 
-  p->attachSignal(this, SIGNAL(sessionDataChanged(const QString &, const QVariant &)), SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)));
-  p->attachSlot(SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)), this, SLOT(storeSessionData(const QString &, const QVariant &)));
-
   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
   p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
@@ -73,6 +69,12 @@ CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent) : QObje
   loadSettings();
   initScriptEngine();
 
+  // init BufferSyncer
+  //QHash<BufferId, QDateTime> lastSeenHash = Core::bufferLastSeenDates(user());
+  //foreach(BufferId id, lastSeenHash.keys()) _bufferSyncer->requestSetLastSeen(id, lastSeenHash[id]);
+  // FIXME connect(_bufferSyncer, SIGNAL(lastSeenSet(BufferId, const QDateTime &)), this, SLOT(storeBufferLastSeen(BufferId, const QDateTime &)));
+  p->synchronize(_bufferSyncer);
+
   // Restore session state
   if(restoreState) restoreSessionState();
 
@@ -82,10 +84,10 @@ CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent) : QObje
 CoreSession::~CoreSession() {
   saveSessionState();
   foreach(NetworkConnection *conn, _connections.values()) {
-    conn->deleteLater();
+    delete conn;
   }
   foreach(Network *net, _networks.values()) {
-    net->deleteLater();
+    delete net;
   }
 }
 
@@ -134,37 +136,32 @@ void CoreSession::loadSettings() {
     createIdentity(i);
   }
 
-  foreach(NetworkId id, s.networkIds()) {
-    NetworkInfo info = s.networkInfo(id);
-    createNetwork(info, true);
-  }
 
-  // FIXME Migrate old settings if available...
-  if(!_networks.count()) {
-    QVariantMap networks = retrieveSessionData("Networks").toMap();
-    if(networks.keys().count()) {
-      qWarning() << "Migrating your old network settings to the new format!";
-      foreach(QString netname, networks.keys()) {
-        QVariantMap network = networks[netname].toMap();
-        NetworkId netid = Core::networkId(user(), netname);
-        NetworkInfo info;
-        info.networkId = netid;
-        info.networkName = netname;
-        info.identity = 1;
-        info.codecForEncoding = "ISO-8859-15";
-        info.codecForDecoding = "ISO-8859-15";
-        QVariantList slist;
-        foreach(QVariant v, network["Servers"].toList()) {
-          QVariantMap server;
-          server["Host"] = v.toMap()["Address"];
-          server["Port"] = v.toMap()["Port"];
-          slist << server;
-        }
-        info.serverList = slist;
-        createNetwork(info, true);
-      }
+  // migration to pure DB storage
+  QList<NetworkId> netIds = s.networkIds();
+  if(!netIds.isEmpty()) {
+    qDebug() << "Migrating Networksettings to DB Storage for User:" << user();
+    foreach(NetworkId id, netIds) {
+      NetworkInfo info = s.networkInfo(id);
+
+      // default new options
+      info.useRandomServer = false;
+      info.useAutoReconnect = true;
+      info.autoReconnectInterval = 60;
+      info.autoReconnectRetries = 20;
+      info.unlimitedReconnectRetries = false;
+      info.useAutoIdentify = false;
+      info.autoIdentifyService = "NickServ";
+      info.rejoinChannels = true;
+
+      Core::updateNetwork(user(), info);
+      s.removeNetworkInfo(id);
     }
   }
+
+  foreach(NetworkInfo info, Core::networks(user())) {
+    createNetwork(info);
+  }
 }
 
 void CoreSession::saveSessionState() const {
@@ -196,22 +193,6 @@ void CoreSession::restoreSessionState() {
   }
 }
 
-
-void CoreSession::storeSessionData(const QString &key, const QVariant &data) {
-  CoreUserSettings s(user());
-  s.setSessionValue(key, data);
-  sessionData[key] = data;
-  emit sessionDataChanged(key, data);
-  emit sessionDataChanged(key);
-}
-
-QVariant CoreSession::retrieveSessionData(const QString &key, const QVariant &def) {
-  QVariant data;
-  if(!sessionData.contains(key)) data = def;
-  else data = sessionData[key];
-  return data;
-}
-
 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
   if(uid == user()) emit bufferInfoUpdated(bufinfo);
 }
@@ -249,13 +230,14 @@ void CoreSession::connectToNetwork(NetworkId id, const QVariant &previousState)
 
 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
   connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
-  connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
+  connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
 
   // I guess we don't need these anymore, client-side can just connect the network's signals directly
   //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
   //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
 
-  connect(conn, SIGNAL(displayMsg(Message::Type, QString, QString, QString, quint8)), this, SLOT(recvMessageFromServer(Message::Type, QString, QString, QString, quint8)));
+  connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)),
+         this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)));
   connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
 
 }
@@ -287,22 +269,19 @@ SignalProxy *CoreSession::signalProxy() const {
 
 // FIXME we need a sane way for creating buffers!
 void CoreSession::networkConnected(NetworkId networkid) {
-  Core::bufferInfo(user(), networkConnection(networkid)->networkName()); // create status buffer
+  Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
 }
 
+// called now only on /quit and requested disconnects, not on normal disconnects!
 void CoreSession::networkDisconnected(NetworkId networkid) {
-  // FIXME
-  // connection should only go away on explicit /part, and handle reconnections etcpp internally otherwise
-
-  Q_ASSERT(_connections.contains(networkid));
-  _connections.take(networkid)->deleteLater();
+  if(_connections.contains(networkid)) _connections.take(networkid)->deleteLater();
 }
 
 // FIXME switch to BufferId
 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
   NetworkConnection *conn = networkConnection(bufinfo.networkId());
   if(conn) {
-    conn->userInput(bufinfo.buffer(), msg);
+    conn->userInput(bufinfo, msg);
   } else {
     qWarning() << "Trying to send to unconnected network!";
   }
@@ -310,16 +289,12 @@ void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
 
 // ALL messages coming pass through these functions before going to the GUI.
 // So this is the perfect place for storing the backlog and log stuff.
-void CoreSession::recvMessageFromServer(Message::Type type, QString target, QString text, QString sender, quint8 flags) {
-  NetworkConnection *s = qobject_cast<NetworkConnection*>(this->sender());
-  Q_ASSERT(s);
-  BufferInfo buf;
-  if((flags & Message::PrivMsg) && !(flags & Message::Self)) {
-    buf = Core::bufferInfo(user(), s->networkName(), nickFromMask(sender));
-  } else {
-    buf = Core::bufferInfo(user(), s->networkName(), target);
-  }
-  Message msg(buf, type, text, sender, flags);
+void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, quint8 flags) {
+  NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
+  Q_ASSERT(netCon);
+  
+  BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
+  Message msg(bufferInfo, type, text, sender, flags);
   msg.setMsgId(Core::storeMessage(msg));
   Q_ASSERT(msg.msgId() != 0);
   emit displayMsg(msg);
@@ -359,12 +334,14 @@ QVariant CoreSession::sessionState() {
   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
   v["Identities"] = idlist;
 
-  v["SessionData"] = sessionData;
-
-    //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
+  //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
   return v;
 }
 
+void CoreSession::storeBufferLastSeen(BufferId buffer, const QDateTime &lastSeen) {
+  Core::setBufferLastSeen(user(), buffer, lastSeen);
+}
+
 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
   QList<QVariant> log;
   QList<Message> msglist;
@@ -441,17 +418,18 @@ void CoreSession::removeIdentity(IdentityId id) {
 
 /*** Network Handling ***/
 
-void CoreSession::createNetwork(const NetworkInfo &_info, bool useId) {
-  NetworkInfo info = _info;
+void CoreSession::createNetwork(const NetworkInfo &info_) {
+  NetworkInfo info = info_;
   int id;
-  if(useId && info.networkId > 0) id = info.networkId.toInt();
-  else {
-    for(id = 1; id <= _networks.count(); id++) {
-      if(!_networks.keys().contains(id)) break;
-    }
-    //qDebug() << "found free id" << i;
-    info.networkId = id;
-  }
+
+  if(!info.networkId.isValid())
+    Core::createNetwork(user(), info);
+
+  Q_ASSERT(info.networkId.isValid());
+
+  id = info.networkId.toInt();
+  Q_ASSERT(!_networks.contains(id));
+  
   Network *net = new Network(id, this);
   connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
   connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
@@ -459,8 +437,6 @@ void CoreSession::createNetwork(const NetworkInfo &_info, bool useId) {
   net->setProxy(signalProxy());
   _networks[id] = net;
   signalProxy()->synchronize(net);
-  CoreUserSettings s(user());
-  s.storeNetworkInfo(info);
   emit networkCreated(id);
 }
 
@@ -470,16 +446,30 @@ void CoreSession::updateNetwork(const NetworkInfo &info) {
     return;
   }
   _networks[info.networkId]->setNetworkInfo(info);
-  CoreUserSettings s(user());
-  s.storeNetworkInfo(info);
+  Core::updateNetwork(user(), info);
 }
 
 void CoreSession::removeNetwork(NetworkId id) {
+  // Make sure the network is disconnected!
+  NetworkConnection *conn = _connections.value(id, 0);
+  if(conn) {
+    if(conn->connectionState() != Network::Disconnected) {
+      connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
+      conn->disconnectFromIrc();
+    } else {
+      _connections.take(id)->deleteLater();  // TODO make this saner
+      destroyNetwork(id);
+    }
+  } else {
+    destroyNetwork(id);
+  }
+}
+
+void CoreSession::destroyNetwork(NetworkId id) {
+  Q_ASSERT(!_connections.contains(id));
   Network *net = _networks.take(id);
-  if(net) {
+  if(net && Core::removeNetwork(user(), id)) {
     emit networkRemoved(id);
-    CoreUserSettings s(user());
-    s.removeNetworkInfo(id);
     net->deleteLater();
   }
 }