migration no longer eats memory
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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 "userinputhandler.h"
26 #include "signalproxy.h"
27 #include "corebuffersyncer.h"
28 #include "corebacklogmanager.h"
29 #include "corebufferviewmanager.h"
30 #include "coreirclisthelper.h"
31 #include "storage.h"
32
33 #include "coreidentity.h"
34 #include "corenetwork.h"
35 #include "ircuser.h"
36 #include "ircchannel.h"
37
38 #include "util.h"
39 #include "coreusersettings.h"
40 #include "logger.h"
41
42 class ProcessMessagesEvent : public QEvent {
43 public:
44   ProcessMessagesEvent() : QEvent(QEvent::User) {}
45 };
46
47 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
48   : QObject(parent),
49     _user(uid),
50     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
51     _aliasManager(this),
52     _bufferSyncer(new CoreBufferSyncer(this)),
53     _backlogManager(new CoreBacklogManager(this)),
54     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
55     _ircListHelper(new CoreIrcListHelper(this)),
56     _coreInfo(this),
57     scriptEngine(new QScriptEngine(this)),
58     _processMessages(false)
59 {
60   SignalProxy *p = signalProxy();
61   connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
62
63   connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
64   connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
65
66   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
67   p->attachSignal(this, SIGNAL(displayMsg(Message)));
68   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
69
70   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
71   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
72   p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
73   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
74
75   p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
76   p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
77   p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
78   p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
79
80   loadSettings();
81   initScriptEngine();
82
83   connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferSyncer, SLOT(storeDirtyIds()));
84   connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferViewManager, SLOT(saveBufferViews()));
85
86   p->synchronize(_bufferSyncer);
87   p->synchronize(&aliasManager());
88   p->synchronize(_backlogManager);
89   p->synchronize(ircListHelper());
90   p->synchronize(&_coreInfo);
91
92   // Restore session state
93   if(restoreState)
94     restoreSessionState();
95
96   emit initialized();
97 }
98
99 CoreSession::~CoreSession() {
100   saveSessionState();
101   foreach(CoreNetwork *net, _networks.values()) {
102     delete net;
103   }
104 }
105
106 CoreNetwork *CoreSession::network(NetworkId id) const {
107   if(_networks.contains(id)) return _networks[id];
108   return 0;
109 }
110
111 CoreIdentity *CoreSession::identity(IdentityId id) const {
112   if(_identities.contains(id)) return _identities[id];
113   return 0;
114 }
115
116 void CoreSession::loadSettings() {
117   CoreUserSettings s(user());
118
119   // migrate to db
120   QList<IdentityId> ids = s.identityIds();
121   QList<NetworkInfo> networkInfos = Core::networks(user());
122   foreach(IdentityId id, ids) {
123     CoreIdentity identity(s.identity(id));
124     IdentityId newId = Core::createIdentity(user(), identity);
125     QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
126     while(networkIter != networkInfos.end()) {
127       if(networkIter->identity == id) {
128         networkIter->identity = newId;
129         Core::updateNetwork(user(), *networkIter);
130         networkIter = networkInfos.erase(networkIter);
131       } else {
132         networkIter++;
133       }
134     }
135     s.removeIdentity(id);
136   }
137   // end of migration
138
139   foreach(CoreIdentity identity, Core::identities(user())) {
140     createIdentity(identity);
141   }
142
143   foreach(NetworkInfo info, Core::networks(user())) {
144     createNetwork(info);
145   }
146 }
147
148 void CoreSession::saveSessionState() const {
149   _bufferSyncer->storeDirtyIds();
150   _bufferViewManager->saveBufferViews();
151 }
152
153 void CoreSession::restoreSessionState() {
154   QList<NetworkId> nets = Core::connectedNetworks(user());
155   CoreNetwork *net = 0;
156   foreach(NetworkId id, nets) {
157     net = network(id);
158     Q_ASSERT(net);
159     net->connectToIrc();
160   }
161 }
162
163 void CoreSession::addClient(QIODevice *device) {
164   if(!device) {
165     qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
166   } else {
167     // if the socket is an orphan, the signalProxy adopts it.
168     // -> we don't need to care about it anymore
169     device->setParent(0);
170     signalProxy()->addPeer(device);
171     QVariantMap reply;
172     reply["MsgType"] = "SessionInit";
173     reply["SessionState"] = sessionState();
174     SignalProxy::writeDataToDevice(device, reply);
175   }
176 }
177
178 void CoreSession::addClient(SignalProxy *proxy) {
179   signalProxy()->addPeer(proxy);
180   emit sessionState(sessionState());
181 }
182
183 void CoreSession::removeClient(QIODevice *iodev) {
184   QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
185   if(socket)
186     quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
187 }
188
189 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
190   return Core::persistentChannels(user(), id);
191 }
192
193 // FIXME switch to BufferId
194 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
195   CoreNetwork *net = network(bufinfo.networkId());
196   if(net) {
197     net->userInput(bufinfo, msg);
198   } else {
199     qWarning() << "Trying to send to unconnected network:" << msg;
200   }
201 }
202
203 // ALL messages coming pass through these functions before going to the GUI.
204 // So this is the perfect place for storing the backlog and log stuff.
205 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
206                                         const QString &target, const QString &text, const QString &sender, Message::Flags flags) {
207   _messageQueue << RawMessage(networkId, type, bufferType, target, text, sender, flags);
208   if(!_processMessages) {
209     _processMessages = true;
210     QCoreApplication::postEvent(this, new ProcessMessagesEvent());
211   }
212 }
213
214 void CoreSession::recvStatusMsgFromServer(QString msg) {
215   CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
216   Q_ASSERT(net);
217   emit displayStatusMsg(net->networkName(), msg);
218 }
219
220 QList<BufferInfo> CoreSession::buffers() const {
221   return Core::requestBuffers(user());
222 }
223
224 void CoreSession::customEvent(QEvent *event) {
225   if(event->type() != QEvent::User)
226     return;
227
228   processMessages();
229   event->accept();
230 }
231
232 void CoreSession::processMessages() {
233   if(_messageQueue.count() == 1) {
234     const RawMessage &rawMsg = _messageQueue.first();
235     BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
236     Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
237     Core::storeMessage(msg);
238     emit displayMsg(msg);
239   } else {
240     QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
241     MessageList messages;
242     BufferInfo bufferInfo;
243     for(int i = 0; i < _messageQueue.count(); i++) {
244       const RawMessage &rawMsg = _messageQueue.at(i);
245       if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
246         bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
247       } else {
248         bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
249         bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
250       }
251       messages << Message(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
252     }
253     Core::storeMessages(messages);
254     // FIXME: extend protocol to a displayMessages(MessageList)
255     for(int i = 0; i < messages.count(); i++) {
256       emit displayMsg(messages[i]);
257     }
258   }
259   _processMessages = false;
260   _messageQueue.clear();
261 }
262
263 QVariant CoreSession::sessionState() {
264   QVariantMap v;
265
266   QVariantList bufs;
267   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
268   v["BufferInfos"] = bufs;
269   QVariantList networkids;
270   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
271   v["NetworkIds"] = networkids;
272
273   quint32 ircusercount = 0;
274   quint32 ircchannelcount = 0;
275   foreach(Network *net, _networks.values()) {
276     ircusercount += net->ircUserCount();
277     ircchannelcount += net->ircChannelCount();
278   }
279   v["IrcUserCount"] = ircusercount;
280   v["IrcChannelCount"] = ircchannelcount;
281
282   QList<QVariant> idlist;
283   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
284   v["Identities"] = idlist;
285
286   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
287   return v;
288 }
289
290 void CoreSession::initScriptEngine() {
291   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
292   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
293
294   // FIXME
295   //QScriptValue storage_ = scriptEngine->newQObject(storage);
296   //scriptEngine->globalObject().setProperty("storage", storage_);
297 }
298
299 void CoreSession::scriptRequest(QString script) {
300   emit scriptResult(scriptEngine->evaluate(script).toString());
301 }
302
303 /*** Identity Handling ***/
304 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
305 #ifndef HAVE_SSL
306   Q_UNUSED(additional)
307 #endif
308
309   CoreIdentity coreIdentity(identity);
310 #ifdef HAVE_SSL
311   if(additional.contains("KeyPem"))
312     coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
313   if(additional.contains("CertPem"))
314     coreIdentity.setSslCert(additional["CertPem"].toByteArray());
315 #endif
316   qDebug() << Q_FUNC_INFO;
317   IdentityId id = Core::createIdentity(user(), coreIdentity);
318   if(!id.isValid())
319     return;
320   else
321     createIdentity(coreIdentity);
322 }
323
324 void CoreSession::createIdentity(const CoreIdentity &identity) {
325   CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
326   _identities[identity.id()] = coreIdentity;
327   // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
328   coreIdentity->synchronize(signalProxy());
329   connect(coreIdentity, SIGNAL(updated(const QVariantMap &)), this, SLOT(updateIdentityBySender()));
330   emit identityCreated(*coreIdentity);
331 }
332
333 void CoreSession::updateIdentityBySender() {
334   CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
335   if(!identity)
336     return;
337   Core::updateIdentity(user(), *identity);
338 }
339
340 void CoreSession::removeIdentity(IdentityId id) {
341   CoreIdentity *identity = _identities.take(id);
342   if(identity) {
343     emit identityRemoved(id);
344     Core::removeIdentity(user(), id);
345     identity->deleteLater();
346   }
347 }
348
349 /*** Network Handling ***/
350
351 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
352   NetworkInfo info = info_;
353   int id;
354
355   if(!info.networkId.isValid())
356     Core::createNetwork(user(), info);
357
358   if(!info.networkId.isValid()) {
359     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
360     return;
361   }
362
363   id = info.networkId.toInt();
364   if(!_networks.contains(id)) {
365     CoreNetwork *net = new CoreNetwork(id, this);
366     connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
367             this, SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
368     connect(net, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
369
370     net->setNetworkInfo(info);
371     net->setProxy(signalProxy());
372     _networks[id] = net;
373     signalProxy()->synchronize(net);
374     emit networkCreated(id);
375     // create persistent chans
376     foreach(QString channel, persistentChans) {
377       Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, channel, true);
378       Core::setChannelPersistent(user(), info.networkId, channel, true);
379     }
380   } else {
381     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
382     _networks[info.networkId]->requestSetNetworkInfo(info);
383   }
384 }
385
386 void CoreSession::removeNetwork(NetworkId id) {
387   // Make sure the network is disconnected!
388   CoreNetwork *net = network(id);
389   if(!net)
390     return;
391
392   if(net->connectionState() != Network::Disconnected) {
393     connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
394     net->disconnectFromIrc();
395   } else {
396     destroyNetwork(id);
397   }
398 }
399
400 void CoreSession::destroyNetwork(NetworkId id) {
401   QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
402   Network *net = _networks.take(id);
403   if(net && Core::removeNetwork(user(), id)) {
404     foreach(BufferId bufferId, removedBuffers) {
405       _bufferSyncer->removeBuffer(bufferId);
406     }
407     emit networkRemoved(id);
408     net->deleteLater();
409   }
410 }
411
412 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
413   BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
414   if(bufferInfo.isValid()) {
415     _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
416   }
417 }
418
419 void CoreSession::clientsConnected() {
420   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
421   Identity *identity = 0;
422   CoreNetwork *net = 0;
423   IrcUser *me = 0;
424   while(netIter != _networks.end()) {
425     net = *netIter;
426     netIter++;
427
428     if(!net->isConnected())
429       continue;
430     identity = net->identityPtr();
431     if(!identity)
432       continue;
433     me = net->me();
434     if(!me)
435       continue;
436
437     if(identity->detachAwayEnabled() && me->isAway()) {
438       net->userInputHandler()->handleAway(BufferInfo(), QString());
439     }
440   }
441 }
442
443 void CoreSession::clientsDisconnected() {
444   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
445   Identity *identity = 0;
446   CoreNetwork *net = 0;
447   IrcUser *me = 0;
448   QString awayReason;
449   while(netIter != _networks.end()) {
450     net = *netIter;
451     netIter++;
452
453     if(!net->isConnected())
454       continue;
455     identity = net->identityPtr();
456     if(!identity)
457       continue;
458     me = net->me();
459     if(!me)
460       continue;
461
462     if(identity->detachAwayEnabled() && !me->isAway()) {
463       if(!identity->detachAwayReason().isEmpty())
464         awayReason = identity->detachAwayReason();
465       net->setAutoAwayActive(true);
466       net->userInputHandler()->handleAway(BufferInfo(), awayReason);
467     }
468   }
469 }