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