Further improvements to the postgres backend:
[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   qDebug() << "processing" << _messageQueue.count() << "messages..";
234   if(_messageQueue.count() == 1) {
235     const RawMessage &rawMsg = _messageQueue.first();
236     BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
237     Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
238     Core::storeMessage(msg);
239     emit displayMsg(msg);
240   } else {
241     QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
242     MessageList messages;
243     BufferInfo bufferInfo;
244     for(int i = 0; i < _messageQueue.count(); i++) {
245       const RawMessage &rawMsg = _messageQueue.at(i);
246       if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
247         bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
248       } else {
249         bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
250         bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
251       }
252       messages << Message(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
253     }
254
255     Core::storeMessages(messages);
256     // FIXME: extend protocol to a displayMessages(MessageList)
257     for(int i = 0; i < messages.count(); i++) {
258       emit displayMsg(messages[i]);
259     }
260   }
261   _processMessages = false;
262   _messageQueue.clear();
263 }
264
265 QVariant CoreSession::sessionState() {
266   QVariantMap v;
267
268   QVariantList bufs;
269   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
270   v["BufferInfos"] = bufs;
271   QVariantList networkids;
272   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
273   v["NetworkIds"] = networkids;
274
275   quint32 ircusercount = 0;
276   quint32 ircchannelcount = 0;
277   foreach(Network *net, _networks.values()) {
278     ircusercount += net->ircUserCount();
279     ircchannelcount += net->ircChannelCount();
280   }
281   v["IrcUserCount"] = ircusercount;
282   v["IrcChannelCount"] = ircchannelcount;
283
284   QList<QVariant> idlist;
285   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
286   v["Identities"] = idlist;
287
288   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
289   return v;
290 }
291
292 void CoreSession::initScriptEngine() {
293   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
294   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
295
296   // FIXME
297   //QScriptValue storage_ = scriptEngine->newQObject(storage);
298   //scriptEngine->globalObject().setProperty("storage", storage_);
299 }
300
301 void CoreSession::scriptRequest(QString script) {
302   emit scriptResult(scriptEngine->evaluate(script).toString());
303 }
304
305 /*** Identity Handling ***/
306 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
307 #ifndef HAVE_SSL
308   Q_UNUSED(additional)
309 #endif
310
311   CoreIdentity coreIdentity(identity);
312 #ifdef HAVE_SSL
313   if(additional.contains("KeyPem"))
314     coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
315   if(additional.contains("CertPem"))
316     coreIdentity.setSslCert(additional["CertPem"].toByteArray());
317 #endif
318   qDebug() << Q_FUNC_INFO;
319   IdentityId id = Core::createIdentity(user(), coreIdentity);
320   if(!id.isValid())
321     return;
322   else
323     createIdentity(coreIdentity);
324 }
325
326 void CoreSession::createIdentity(const CoreIdentity &identity) {
327   CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
328   _identities[identity.id()] = coreIdentity;
329   // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
330   coreIdentity->synchronize(signalProxy());
331   connect(coreIdentity, SIGNAL(updated(const QVariantMap &)), this, SLOT(updateIdentityBySender()));
332   emit identityCreated(*coreIdentity);
333 }
334
335 void CoreSession::updateIdentityBySender() {
336   CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
337   if(!identity)
338     return;
339   Core::updateIdentity(user(), *identity);
340 }
341
342 void CoreSession::removeIdentity(IdentityId id) {
343   CoreIdentity *identity = _identities.take(id);
344   if(identity) {
345     emit identityRemoved(id);
346     Core::removeIdentity(user(), id);
347     identity->deleteLater();
348   }
349 }
350
351 /*** Network Handling ***/
352
353 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
354   NetworkInfo info = info_;
355   int id;
356
357   if(!info.networkId.isValid())
358     Core::createNetwork(user(), info);
359
360   if(!info.networkId.isValid()) {
361     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
362     return;
363   }
364
365   id = info.networkId.toInt();
366   if(!_networks.contains(id)) {
367     CoreNetwork *net = new CoreNetwork(id, this);
368     connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
369             this, SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
370     connect(net, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
371
372     net->setNetworkInfo(info);
373     net->setProxy(signalProxy());
374     _networks[id] = net;
375     signalProxy()->synchronize(net);
376     emit networkCreated(id);
377     // create persistent chans
378     foreach(QString channel, persistentChans) {
379       Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, channel, true);
380       Core::setChannelPersistent(user(), info.networkId, channel, true);
381     }
382   } else {
383     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
384     _networks[info.networkId]->requestSetNetworkInfo(info);
385   }
386 }
387
388 void CoreSession::removeNetwork(NetworkId id) {
389   // Make sure the network is disconnected!
390   CoreNetwork *net = network(id);
391   if(!net)
392     return;
393
394   if(net->connectionState() != Network::Disconnected) {
395     connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
396     net->disconnectFromIrc();
397   } else {
398     destroyNetwork(id);
399   }
400 }
401
402 void CoreSession::destroyNetwork(NetworkId id) {
403   QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
404   Network *net = _networks.take(id);
405   if(net && Core::removeNetwork(user(), id)) {
406     foreach(BufferId bufferId, removedBuffers) {
407       _bufferSyncer->removeBuffer(bufferId);
408     }
409     emit networkRemoved(id);
410     net->deleteLater();
411   }
412 }
413
414 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
415   BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
416   if(bufferInfo.isValid()) {
417     _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
418   }
419 }
420
421 void CoreSession::clientsConnected() {
422   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
423   Identity *identity = 0;
424   CoreNetwork *net = 0;
425   IrcUser *me = 0;
426   while(netIter != _networks.end()) {
427     net = *netIter;
428     netIter++;
429
430     if(!net->isConnected())
431       continue;
432     identity = net->identityPtr();
433     if(!identity)
434       continue;
435     me = net->me();
436     if(!me)
437       continue;
438
439     if(identity->detachAwayEnabled() && me->isAway()) {
440       net->userInputHandler()->handleAway(BufferInfo(), QString());
441     }
442   }
443 }
444
445 void CoreSession::clientsDisconnected() {
446   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
447   Identity *identity = 0;
448   CoreNetwork *net = 0;
449   IrcUser *me = 0;
450   QString awayReason;
451   while(netIter != _networks.end()) {
452     net = *netIter;
453     netIter++;
454
455     if(!net->isConnected())
456       continue;
457     identity = net->identityPtr();
458     if(!identity)
459       continue;
460     me = net->me();
461     if(!me)
462       continue;
463
464     if(identity->detachAwayEnabled() && !me->isAway()) {
465       if(!identity->detachAwayReason().isEmpty())
466         awayReason = identity->detachAwayReason();
467       net->setAutoAwayActive(true);
468       net->userInputHandler()->handleAway(BufferInfo(), awayReason);
469     }
470   }
471 }