Boilerplate work for CoreSessionEventProcessor
[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 "coresession.h"
22
23 #include <QtScript>
24
25 #include "core.h"
26 #include "coreuserinputhandler.h"
27 #include "corebuffersyncer.h"
28 #include "corebacklogmanager.h"
29 #include "corebufferviewmanager.h"
30 #include "coreidentity.h"
31 #include "coreignorelistmanager.h"
32 #include "coreirclisthelper.h"
33 #include "corenetwork.h"
34 #include "corenetworkconfig.h"
35 #include "coresessioneventprocessor.h"
36 #include "coreusersettings.h"
37 #include "eventmanager.h"
38 #include "ircchannel.h"
39 #include "ircuser.h"
40 #include "logger.h"
41 #include "signalproxy.h"
42 #include "storage.h"
43 #include "util.h"
44
45 class ProcessMessagesEvent : public QEvent {
46 public:
47   ProcessMessagesEvent() : QEvent(QEvent::User) {}
48 };
49
50 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
51   : QObject(parent),
52     _user(uid),
53     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
54     _aliasManager(this),
55     _bufferSyncer(new CoreBufferSyncer(this)),
56     _backlogManager(new CoreBacklogManager(this)),
57     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
58     _ircListHelper(new CoreIrcListHelper(this)),
59     _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
60     _coreInfo(this),
61     _eventManager(new EventManager(this)),
62     _eventProcessor(new CoreSessionEventProcessor(this)),
63     scriptEngine(new QScriptEngine(this)),
64     _processMessages(false),
65     _ignoreListManager(this)
66 {
67   SignalProxy *p = signalProxy();
68   p->setHeartBeatInterval(30);
69   p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
70
71   connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
72
73   connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
74   connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
75
76   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
77   p->attachSignal(this, SIGNAL(displayMsg(Message)));
78   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
79
80   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
81   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
82   p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
83   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
84
85   p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
86   p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
87   p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
88   p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
89
90   loadSettings();
91   initScriptEngine();
92
93   eventManager()->registerObject(eventProcessor(), EventManager::Prepend, "process");
94
95   // periodically save our session state
96   connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
97
98   p->synchronize(_bufferSyncer);
99   p->synchronize(&aliasManager());
100   p->synchronize(_backlogManager);
101   p->synchronize(ircListHelper());
102   p->synchronize(networkConfig());
103   p->synchronize(&_coreInfo);
104   p->synchronize(&_ignoreListManager);
105   // Restore session state
106   if(restoreState)
107     restoreSessionState();
108
109   emit initialized();
110 }
111
112 CoreSession::~CoreSession() {
113   saveSessionState();
114   foreach(CoreNetwork *net, _networks.values()) {
115     delete net;
116   }
117 }
118
119 CoreNetwork *CoreSession::network(NetworkId id) const {
120   if(_networks.contains(id)) return _networks[id];
121   return 0;
122 }
123
124 CoreIdentity *CoreSession::identity(IdentityId id) const {
125   if(_identities.contains(id)) return _identities[id];
126   return 0;
127 }
128
129 void CoreSession::loadSettings() {
130   CoreUserSettings s(user());
131
132   // migrate to db
133   QList<IdentityId> ids = s.identityIds();
134   QList<NetworkInfo> networkInfos = Core::networks(user());
135   foreach(IdentityId id, ids) {
136     CoreIdentity identity(s.identity(id));
137     IdentityId newId = Core::createIdentity(user(), identity);
138     QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
139     while(networkIter != networkInfos.end()) {
140       if(networkIter->identity == id) {
141         networkIter->identity = newId;
142         Core::updateNetwork(user(), *networkIter);
143         networkIter = networkInfos.erase(networkIter);
144       } else {
145         networkIter++;
146       }
147     }
148     s.removeIdentity(id);
149   }
150   // end of migration
151
152   foreach(CoreIdentity identity, Core::identities(user())) {
153     createIdentity(identity);
154   }
155
156   foreach(NetworkInfo info, Core::networks(user())) {
157     createNetwork(info);
158   }
159 }
160
161 void CoreSession::saveSessionState() const {
162   _bufferSyncer->storeDirtyIds();
163   _bufferViewManager->saveBufferViews();
164   _networkConfig->save();
165 }
166
167 void CoreSession::restoreSessionState() {
168   QList<NetworkId> nets = Core::connectedNetworks(user());
169   CoreNetwork *net = 0;
170   foreach(NetworkId id, nets) {
171     net = network(id);
172     Q_ASSERT(net);
173     net->connectToIrc();
174   }
175 }
176
177 void CoreSession::addClient(QIODevice *device) {
178   if(!device) {
179     qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
180   } else {
181     // if the socket is an orphan, the signalProxy adopts it.
182     // -> we don't need to care about it anymore
183     device->setParent(0);
184     signalProxy()->addPeer(device);
185     QVariantMap reply;
186     reply["MsgType"] = "SessionInit";
187     reply["SessionState"] = sessionState();
188     SignalProxy::writeDataToDevice(device, reply);
189   }
190 }
191
192 void CoreSession::addClient(SignalProxy *proxy) {
193   signalProxy()->addPeer(proxy);
194   emit sessionState(sessionState());
195 }
196
197 void CoreSession::removeClient(QIODevice *iodev) {
198   QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
199   if(socket)
200     quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
201 }
202
203 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
204   return Core::persistentChannels(user(), id);
205 }
206
207 // FIXME switch to BufferId
208 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
209   CoreNetwork *net = network(bufinfo.networkId());
210   if(net) {
211     net->userInput(bufinfo, msg);
212   } else {
213     qWarning() << "Trying to send to unconnected network:" << msg;
214   }
215 }
216
217 // ALL messages coming pass through these functions before going to the GUI.
218 // So this is the perfect place for storing the backlog and log stuff.
219 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
220                                         const QString &target, const QString &text_, const QString &sender, Message::Flags flags) {
221
222   // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
223   // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
224   // KDE's notifications), hence we remove those just to be safe.
225   QString text = text_;
226   text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
227   RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
228
229   // check for HardStrictness ignore
230   CoreNetwork *currentNetwork = network(networkId);
231   QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
232   if(_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
233     return;
234
235   _messageQueue << rawMsg;
236   if(!_processMessages) {
237     _processMessages = true;
238     QCoreApplication::postEvent(this, new ProcessMessagesEvent());
239   }
240 }
241
242 void CoreSession::recvStatusMsgFromServer(QString msg) {
243   CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
244   Q_ASSERT(net);
245   emit displayStatusMsg(net->networkName(), msg);
246 }
247
248 QList<BufferInfo> CoreSession::buffers() const {
249   return Core::requestBuffers(user());
250 }
251
252 void CoreSession::customEvent(QEvent *event) {
253   if(event->type() != QEvent::User)
254     return;
255
256   processMessages();
257   event->accept();
258 }
259
260 void CoreSession::processMessages() {
261   if(_messageQueue.count() == 1) {
262     const RawMessage &rawMsg = _messageQueue.first();
263     bool createBuffer = !(rawMsg.flags & Message::Redirected);
264     BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
265     if(!bufferInfo.isValid()) {
266       Q_ASSERT(!createBuffer);
267       bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
268     }
269     Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
270     Core::storeMessage(msg);
271     emit displayMsg(msg);
272   } else {
273     QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
274     MessageList messages;
275     QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
276     BufferInfo bufferInfo;
277     for(int i = 0; i < _messageQueue.count(); i++) {
278       const RawMessage &rawMsg = _messageQueue.at(i);
279       if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
280         bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
281       } else {
282         bool createBuffer = !(rawMsg.flags & Message::Redirected);
283         bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
284         if(!bufferInfo.isValid()) {
285           Q_ASSERT(!createBuffer);
286           redirectedMessages << rawMsg;
287           continue;
288         }
289         bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
290       }
291       Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
292       messages << msg;
293     }
294
295     // recheck if there exists a buffer to store a redirected message in
296     for(int i = 0; i < redirectedMessages.count(); i++) {
297       const RawMessage &rawMsg = _messageQueue.at(i);
298       if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
299         bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
300       } else {
301         // no luck -> we store them in the StatusBuffer
302         bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
303         // add the StatusBuffer to the Cache in case there are more Messages for the original target
304         bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
305       }
306       Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
307       messages << msg;
308     }
309
310     Core::storeMessages(messages);
311     // FIXME: extend protocol to a displayMessages(MessageList)
312     for(int i = 0; i < messages.count(); i++) {
313       emit displayMsg(messages[i]);
314     }
315   }
316   _processMessages = false;
317   _messageQueue.clear();
318 }
319
320 QVariant CoreSession::sessionState() {
321   QVariantMap v;
322
323   v["CoreFeatures"] = (int)Quassel::features();
324
325   QVariantList bufs;
326   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
327   v["BufferInfos"] = bufs;
328   QVariantList networkids;
329   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
330   v["NetworkIds"] = networkids;
331
332   quint32 ircusercount = 0;
333   quint32 ircchannelcount = 0;
334   foreach(Network *net, _networks.values()) {
335     ircusercount += net->ircUserCount();
336     ircchannelcount += net->ircChannelCount();
337   }
338   v["IrcUserCount"] = ircusercount;
339   v["IrcChannelCount"] = ircchannelcount;
340
341   QList<QVariant> idlist;
342   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
343   v["Identities"] = idlist;
344
345   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
346   return v;
347 }
348
349 void CoreSession::initScriptEngine() {
350   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
351   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
352
353   // FIXME
354   //QScriptValue storage_ = scriptEngine->newQObject(storage);
355   //scriptEngine->globalObject().setProperty("storage", storage_);
356 }
357
358 void CoreSession::scriptRequest(QString script) {
359   emit scriptResult(scriptEngine->evaluate(script).toString());
360 }
361
362 /*** Identity Handling ***/
363 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
364 #ifndef HAVE_SSL
365   Q_UNUSED(additional)
366 #endif
367
368   CoreIdentity coreIdentity(identity);
369 #ifdef HAVE_SSL
370   if(additional.contains("KeyPem"))
371     coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
372   if(additional.contains("CertPem"))
373     coreIdentity.setSslCert(additional["CertPem"].toByteArray());
374 #endif
375   qDebug() << Q_FUNC_INFO;
376   IdentityId id = Core::createIdentity(user(), coreIdentity);
377   if(!id.isValid())
378     return;
379   else
380     createIdentity(coreIdentity);
381 }
382
383 void CoreSession::createIdentity(const CoreIdentity &identity) {
384   CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
385   _identities[identity.id()] = coreIdentity;
386   // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
387   coreIdentity->synchronize(signalProxy());
388   connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
389   emit identityCreated(*coreIdentity);
390 }
391
392 void CoreSession::updateIdentityBySender() {
393   CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
394   if(!identity)
395     return;
396   Core::updateIdentity(user(), *identity);
397 }
398
399 void CoreSession::removeIdentity(IdentityId id) {
400   CoreIdentity *identity = _identities.take(id);
401   if(identity) {
402     emit identityRemoved(id);
403     Core::removeIdentity(user(), id);
404     identity->deleteLater();
405   }
406 }
407
408 /*** Network Handling ***/
409
410 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
411   NetworkInfo info = info_;
412   int id;
413
414   if(!info.networkId.isValid())
415     Core::createNetwork(user(), info);
416
417   if(!info.networkId.isValid()) {
418     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
419     return;
420   }
421
422   id = info.networkId.toInt();
423   if(!_networks.contains(id)) {
424
425     // create persistent chans
426     QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
427     foreach(QString channel, persistentChans) {
428       if(!rx.exactMatch(channel)) {
429         qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
430         continue;
431       }
432       Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
433       Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
434       if(!rx.cap(2).isEmpty())
435         Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
436     }
437
438     CoreNetwork *net = new CoreNetwork(id, this);
439     connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
440                  SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
441     connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
442
443     net->setNetworkInfo(info);
444     net->setProxy(signalProxy());
445     _networks[id] = net;
446     signalProxy()->synchronize(net);
447     emit networkCreated(id);
448   } else {
449     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
450     _networks[info.networkId]->requestSetNetworkInfo(info);
451   }
452 }
453
454 void CoreSession::removeNetwork(NetworkId id) {
455   // Make sure the network is disconnected!
456   CoreNetwork *net = network(id);
457   if(!net)
458     return;
459
460   if(net->connectionState() != Network::Disconnected) {
461     connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
462     net->disconnectFromIrc();
463   } else {
464     destroyNetwork(id);
465   }
466 }
467
468 void CoreSession::destroyNetwork(NetworkId id) {
469   QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
470   Network *net = _networks.take(id);
471   if(net && Core::removeNetwork(user(), id)) {
472     foreach(BufferId bufferId, removedBuffers) {
473       _bufferSyncer->removeBuffer(bufferId);
474     }
475     emit networkRemoved(id);
476     net->deleteLater();
477   }
478 }
479
480 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
481   BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
482   if(bufferInfo.isValid()) {
483     _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
484   }
485 }
486
487 void CoreSession::clientsConnected() {
488   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
489   Identity *identity = 0;
490   CoreNetwork *net = 0;
491   IrcUser *me = 0;
492   while(netIter != _networks.end()) {
493     net = *netIter;
494     netIter++;
495
496     if(!net->isConnected())
497       continue;
498     identity = net->identityPtr();
499     if(!identity)
500       continue;
501     me = net->me();
502     if(!me)
503       continue;
504
505     if(identity->detachAwayEnabled() && me->isAway()) {
506       net->userInputHandler()->handleAway(BufferInfo(), QString());
507     }
508   }
509 }
510
511 void CoreSession::clientsDisconnected() {
512   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
513   Identity *identity = 0;
514   CoreNetwork *net = 0;
515   IrcUser *me = 0;
516   QString awayReason;
517   while(netIter != _networks.end()) {
518     net = *netIter;
519     netIter++;
520
521     if(!net->isConnected())
522       continue;
523
524     identity = net->identityPtr();
525     if(!identity)
526       continue;
527     me = net->me();
528     if(!me)
529       continue;
530
531     if(identity->detachAwayEnabled() && !me->isAway()) {
532       if(!identity->detachAwayReason().isEmpty())
533         awayReason = identity->detachAwayReason();
534       net->setAutoAwayActive(true);
535       net->userInputHandler()->handleAway(BufferInfo(), awayReason);
536     }
537   }
538 }
539
540
541 void CoreSession::globalAway(const QString &msg) {
542   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
543   CoreNetwork *net = 0;
544   while(netIter != _networks.end()) {
545     net = *netIter;
546     netIter++;
547
548     if(!net->isConnected())
549       continue;
550
551     net->userInputHandler()->issueAway(msg, false /* no force away */);
552   }
553 }