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