Fix nasty bug that made the client sometimes crash at sync.
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20
21 #include <QtScript>
22
23 #include "core.h"
24 #include "coresession.h"
25 #include "networkconnection.h"
26
27 #include "signalproxy.h"
28 #include "buffersyncer.h"
29 #include "storage.h"
30
31 #include "network.h"
32 #include "ircuser.h"
33 #include "ircchannel.h"
34 #include "identity.h"
35
36 #include "util.h"
37 #include "coreusersettings.h"
38
39 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent) : QObject(parent),
40     _user(uid),
41     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
42     _bufferSyncer(new BufferSyncer(this)),
43     scriptEngine(new QScriptEngine(this))
44 {
45
46   SignalProxy *p = signalProxy();
47
48   //p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
49   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
50   p->attachSlot(SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)), this, SLOT(sendBacklog(BufferInfo, QVariant, QVariant)));
51   p->attachSignal(this, SIGNAL(displayMsg(Message)));
52   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
53   p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
54   p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
55
56   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
57   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
58   p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
59   p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
60   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
61
62   p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
63   p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
64   p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
65   p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
66   p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
67
68   loadSettings();
69   initScriptEngine();
70
71   // init BufferSyncer
72   QHash<BufferId, QDateTime> lastSeenHash = Core::bufferLastSeenDates(user());
73   foreach(BufferId id, lastSeenHash.keys()) _bufferSyncer->requestSetLastSeen(id, lastSeenHash[id]);
74   connect(_bufferSyncer, SIGNAL(lastSeenSet(BufferId, const QDateTime &)), this, SLOT(storeBufferLastSeen(BufferId, const QDateTime &)));
75   connect(_bufferSyncer, SIGNAL(removeBufferRequested(BufferId)), this, SLOT(removeBufferRequested(BufferId)));
76   connect(this, SIGNAL(bufferRemoved(BufferId)), _bufferSyncer, SLOT(removeBuffer(BufferId)));
77   connect(this, SIGNAL(bufferRenamed(BufferId, QString)), _bufferSyncer, SLOT(renameBuffer(BufferId, QString)));
78   p->synchronize(_bufferSyncer);
79
80   // Restore session state
81   if(restoreState) restoreSessionState();
82
83   emit initialized();
84 }
85
86 CoreSession::~CoreSession() {
87   saveSessionState();
88   foreach(NetworkConnection *conn, _connections.values()) {
89     delete conn;
90   }
91   foreach(Network *net, _networks.values()) {
92     delete net;
93   }
94 }
95
96 UserId CoreSession::user() const {
97   return _user;
98 }
99
100 Network *CoreSession::network(NetworkId id) const {
101   if(_networks.contains(id)) return _networks[id];
102   return 0;
103 }
104
105 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
106   if(_connections.contains(id)) return _connections[id];
107   return 0;
108 }
109
110 Identity *CoreSession::identity(IdentityId id) const {
111   if(_identities.contains(id)) return _identities[id];
112   return 0;
113 }
114
115 void CoreSession::loadSettings() {
116   CoreUserSettings s(user());
117
118   foreach(IdentityId id, s.identityIds()) {
119     Identity *i = new Identity(s.identity(id), this);
120     if(!i->isValid()) {
121       qWarning() << QString("Invalid identity! Removing...");
122       s.removeIdentity(id);
123       delete i;
124       continue;
125     }
126     if(_identities.contains(i->id())) {
127       qWarning() << "Duplicate identity, ignoring!";
128       delete i;
129       continue;
130     }
131     _identities[i->id()] = i;
132     signalProxy()->synchronize(i);
133   }
134   if(!_identities.count()) {
135     Identity i(1);
136     i.setToDefaults();
137     i.setIdentityName(tr("Default Identity"));
138     createIdentity(i);
139   }
140
141
142   // migration to pure DB storage
143   QList<NetworkId> netIds = s.networkIds();
144   if(!netIds.isEmpty()) {
145     qDebug() << "Migrating Networksettings to DB Storage for User:" << user();
146     foreach(NetworkId id, netIds) {
147       NetworkInfo info = s.networkInfo(id);
148
149       // default new options
150       info.useRandomServer = false;
151       info.useAutoReconnect = true;
152       info.autoReconnectInterval = 60;
153       info.autoReconnectRetries = 20;
154       info.unlimitedReconnectRetries = false;
155       info.useAutoIdentify = false;
156       info.autoIdentifyService = "NickServ";
157       info.rejoinChannels = true;
158
159       Core::updateNetwork(user(), info);
160       s.removeNetworkInfo(id);
161     }
162   }
163
164   foreach(NetworkInfo info, Core::networks(user())) {
165     createNetwork(info);
166   }
167 }
168
169 void CoreSession::saveSessionState() const {
170   QVariantMap res;
171   QVariantList conn;
172   foreach(NetworkConnection *nc, _connections.values()) {
173     QHash<QString, QString> persistentChans = nc->network()->persistentChannels();
174     QStringList list;
175     foreach(QString chan, persistentChans.keys()) list << QString("%1/%2").arg(chan).arg(persistentChans.value(chan));
176     QVariantMap m;
177     m["NetworkId"] = QVariant::fromValue<NetworkId>(nc->networkId());
178     m["PersistentChannels"] = list;
179     conn << m;
180   }
181   res["CoreBuild"] = Global::quasselBuild;
182   res["ConnectedNetworks"] = conn;
183   CoreUserSettings s(user());
184   s.setSessionState(res);
185 }
186
187 void CoreSession::restoreSessionState() {
188   CoreUserSettings s(user());
189   uint build = s.sessionState().toMap()["CoreBuild"].toUInt();
190   if(build < 362) {
191     qWarning() << qPrintable(tr("Session state does not exist or is too old!"));
192     return;
193   }
194   QVariantList conn = s.sessionState().toMap()["ConnectedNetworks"].toList();
195   foreach(QVariant v, conn) {
196     NetworkId id = v.toMap()["NetworkId"].value<NetworkId>();
197     // TODO remove migration code some time
198     QStringList list = v.toMap()["PersistentChannels"].toStringList();
199     if(!list.count()) {
200       // migrate older state
201       QStringList old = v.toMap()["State"].toStringList();
202       foreach(QString chan, old) list << QString("%1/").arg(chan);
203     }
204     foreach(QString chan, list) {
205       QStringList l = chan.split("/");
206       network(id)->addPersistentChannel(l[0], l[1]);
207     }
208     //qDebug() << "User" << user() << "connecting to" << network(id)->networkName();
209     connectToNetwork(id);
210   }
211 }
212
213 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
214   if(uid == user()) emit bufferInfoUpdated(bufinfo);
215 }
216
217 // FIXME remove
218 /*
219 void CoreSession::connectToNetwork(QString netname, const QVariant &previousState) {
220   Network *net = 0;
221   foreach(Network *n, _networks.values()) {
222     if(n->networkName() == netname) {
223       net = n; break;
224     }
225   }
226   if(!net) {
227     qWarning() << "Connect to unknown network requested, ignoring!";
228     return;
229   }
230   connectToNetwork(net->networkId(), previousState);
231 }
232 */
233
234 void CoreSession::connectToNetwork(NetworkId id) {
235   Network *net = network(id);
236   if(!net) {
237     qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
238     return;
239   }
240
241   NetworkConnection *conn = networkConnection(id);
242   if(!conn) {
243     conn = new NetworkConnection(net, this);
244     _connections[id] = conn;
245     attachNetworkConnection(conn);
246   }
247   conn->connectToIrc();
248 }
249
250 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
251   connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
252   connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
253
254   // I guess we don't need these anymore, client-side can just connect the network's signals directly
255   //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
256   //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
257
258   connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)),
259           this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)));
260   connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
261
262   connect(conn, SIGNAL(nickChanged(const NetworkId &, const QString &, const QString &)),
263           this, SLOT(renameBuffer(const NetworkId &, const QString &, const QString &)));
264 }
265
266 void CoreSession::disconnectFromNetwork(NetworkId id) {
267   if(!_connections.contains(id)) return;
268   _connections[id]->disconnectFromIrc();
269 }
270
271 void CoreSession::networkStateRequested() {
272 }
273
274 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
275   QIODevice *device = qobject_cast<QIODevice *>(dev);
276   if(!device) {
277     qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
278   } else {
279     signalProxy()->addPeer(device);
280     QVariantMap reply;
281     reply["MsgType"] = "SessionInit";
282     reply["SessionState"] = sessionState();
283     SignalProxy::writeDataToDevice(device, reply);
284   }
285 }
286
287 SignalProxy *CoreSession::signalProxy() const {
288   return _signalProxy;
289 }
290
291 // FIXME we need a sane way for creating buffers!
292 void CoreSession::networkConnected(NetworkId networkid) {
293   Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
294 }
295
296 // called now only on /quit and requested disconnects, not on normal disconnects!
297 void CoreSession::networkDisconnected(NetworkId networkid) {
298   if(_connections.contains(networkid)) _connections.take(networkid)->deleteLater();
299 }
300
301 // FIXME switch to BufferId
302 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
303   NetworkConnection *conn = networkConnection(bufinfo.networkId());
304   if(conn) {
305     conn->userInput(bufinfo, msg);
306   } else {
307     qWarning() << "Trying to send to unconnected network!";
308   }
309 }
310
311 // ALL messages coming pass through these functions before going to the GUI.
312 // So this is the perfect place for storing the backlog and log stuff.
313 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, quint8 flags) {
314   NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
315   Q_ASSERT(netCon);
316   
317   BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
318   Message msg(bufferInfo, type, text, sender, flags);
319   msg.setMsgId(Core::storeMessage(msg));
320   Q_ASSERT(msg.msgId() != 0);
321   emit displayMsg(msg);
322 }
323
324 void CoreSession::recvStatusMsgFromServer(QString msg) {
325   NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
326   Q_ASSERT(s);
327   emit displayStatusMsg(s->networkName(), msg);
328 }
329
330 QList<BufferInfo> CoreSession::buffers() const {
331   return Core::requestBuffers(user());
332 }
333
334
335 QVariant CoreSession::sessionState() {
336   QVariantMap v;
337
338   QVariantList bufs;
339   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
340   v["BufferInfos"] = bufs;
341   QVariantList networkids;
342   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
343   v["NetworkIds"] = networkids;
344
345   quint32 ircusercount = 0;
346   quint32 ircchannelcount = 0;
347   foreach(Network *net, _networks.values()) {
348     ircusercount += net->ircUserCount();
349     ircchannelcount += net->ircChannelCount();
350   }
351   v["IrcUserCount"] = ircusercount;
352   v["IrcChannelCount"] = ircchannelcount;
353
354   QList<QVariant> idlist;
355   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
356   v["Identities"] = idlist;
357
358   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
359   return v;
360 }
361
362 void CoreSession::storeBufferLastSeen(BufferId buffer, const QDateTime &lastSeen) {
363   Core::setBufferLastSeen(user(), buffer, lastSeen);
364 }
365
366 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
367   QList<QVariant> log;
368   QList<Message> msglist;
369   if(v1.type() == QVariant::DateTime) {
370
371
372   } else {
373     msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
374   }
375
376   // Send messages out in smaller packages - we don't want to make the signal data too large!
377   for(int i = 0; i < msglist.count(); i++) {
378     log.append(qVariantFromValue(msglist[i]));
379     if(log.count() >= 5) {
380       emit backlogData(id, log, i >= msglist.count() - 1);
381       log.clear();
382     }
383   }
384   if(log.count() > 0) emit backlogData(id, log, true);
385 }
386
387
388 void CoreSession::initScriptEngine() {
389   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
390   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
391
392   // FIXME
393   //QScriptValue storage_ = scriptEngine->newQObject(storage);
394   //scriptEngine->globalObject().setProperty("storage", storage_);
395 }
396
397 void CoreSession::scriptRequest(QString script) {
398   emit scriptResult(scriptEngine->evaluate(script).toString());
399 }
400
401 /*** Identity Handling ***/
402
403 void CoreSession::createIdentity(const Identity &id) {
404   // find free ID
405   int i;
406   for(i = 1; i <= _identities.count(); i++) {
407     if(!_identities.keys().contains(i)) break;
408   }
409   //qDebug() << "found free id" << i;
410   Identity *newId = new Identity(id, this);
411   newId->setId(i);
412   _identities[i] = newId;
413   signalProxy()->synchronize(newId);
414   CoreUserSettings s(user());
415   s.storeIdentity(*newId);
416   emit identityCreated(*newId);
417 }
418
419 void CoreSession::updateIdentity(const Identity &id) {
420   if(!_identities.contains(id.id())) {
421     qWarning() << "Update request for unknown identity received!";
422     return;
423   }
424   _identities[id.id()]->update(id);
425
426   CoreUserSettings s(user());
427   s.storeIdentity(id);
428 }
429
430 void CoreSession::removeIdentity(IdentityId id) {
431   Identity *i = _identities.take(id);
432   if(i) {
433     emit identityRemoved(id);
434     CoreUserSettings s(user());
435     s.removeIdentity(id);
436     i->deleteLater();
437   }
438 }
439
440 /*** Network Handling ***/
441
442 void CoreSession::createNetwork(const NetworkInfo &info_) {
443   NetworkInfo info = info_;
444   int id;
445
446   if(!info.networkId.isValid())
447     Core::createNetwork(user(), info);
448
449   Q_ASSERT(info.networkId.isValid());
450
451   id = info.networkId.toInt();
452   Q_ASSERT(!_networks.contains(id));
453   
454   Network *net = new Network(id, this);
455   connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
456   connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
457   net->setNetworkInfo(info);
458   net->setProxy(signalProxy());
459   _networks[id] = net;
460   signalProxy()->synchronize(net);
461   emit networkCreated(id);
462 }
463
464 void CoreSession::updateNetwork(const NetworkInfo &info) {
465   if(!_networks.contains(info.networkId)) {
466     qWarning() << "Update request for unknown network received!";
467     return;
468   }
469   _networks[info.networkId]->setNetworkInfo(info);
470   Core::updateNetwork(user(), info);
471 }
472
473 void CoreSession::removeNetwork(NetworkId id) {
474   // Make sure the network is disconnected!
475   NetworkConnection *conn = _connections.value(id, 0);
476   if(conn) {
477     if(conn->connectionState() != Network::Disconnected) {
478       connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
479       conn->disconnectFromIrc();
480     } else {
481       _connections.take(id)->deleteLater();  // TODO make this saner
482       destroyNetwork(id);
483     }
484   } else {
485     destroyNetwork(id);
486   }
487 }
488
489 void CoreSession::destroyNetwork(NetworkId id) {
490   Q_ASSERT(!_connections.contains(id));
491   Network *net = _networks.take(id);
492   if(net && Core::removeNetwork(user(), id)) {
493     emit networkRemoved(id);
494     net->deleteLater();
495   }
496 }
497
498 void CoreSession::removeBufferRequested(BufferId bufferId) {
499   BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
500   if(!bufferInfo.isValid()) {
501     qWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
502     return;
503   }
504   
505   if(bufferInfo.type() == BufferInfo::StatusBuffer) {
506     qWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
507     return;
508   }
509   
510   if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
511     Network *net = network(bufferInfo.networkId());
512     Q_ASSERT(net);
513     IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
514     if(chan) {
515       qWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
516       return;
517     }
518   }
519   if(Core::removeBuffer(user(), bufferId))
520     emit bufferRemoved(bufferId);
521 }
522
523 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
524   BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
525   if(bufferId.isValid()) {
526     emit bufferRenamed(bufferId, newName);
527   }
528 }