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