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