355d867f8b665aca521e66fec098e8de126caf83
[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   QVariantList bufs;
297   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
298   v["BufferInfos"] = bufs;
299   QVariantList networkids;
300   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
301   v["NetworkIds"] = networkids;
302
303   quint32 ircusercount = 0;
304   quint32 ircchannelcount = 0;
305   foreach(Network *net, _networks.values()) {
306     ircusercount += net->ircUserCount();
307     ircchannelcount += net->ircChannelCount();
308   }
309   v["IrcUserCount"] = ircusercount;
310   v["IrcChannelCount"] = ircchannelcount;
311
312   QList<QVariant> idlist;
313   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
314   v["Identities"] = idlist;
315
316   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
317   return v;
318 }
319
320 void CoreSession::initScriptEngine() {
321   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
322   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
323
324   // FIXME
325   //QScriptValue storage_ = scriptEngine->newQObject(storage);
326   //scriptEngine->globalObject().setProperty("storage", storage_);
327 }
328
329 void CoreSession::scriptRequest(QString script) {
330   emit scriptResult(scriptEngine->evaluate(script).toString());
331 }
332
333 /*** Identity Handling ***/
334 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
335 #ifndef HAVE_SSL
336   Q_UNUSED(additional)
337 #endif
338
339   CoreIdentity coreIdentity(identity);
340 #ifdef HAVE_SSL
341   if(additional.contains("KeyPem"))
342     coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
343   if(additional.contains("CertPem"))
344     coreIdentity.setSslCert(additional["CertPem"].toByteArray());
345 #endif
346   qDebug() << Q_FUNC_INFO;
347   IdentityId id = Core::createIdentity(user(), coreIdentity);
348   if(!id.isValid())
349     return;
350   else
351     createIdentity(coreIdentity);
352 }
353
354 void CoreSession::createIdentity(const CoreIdentity &identity) {
355   CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
356   _identities[identity.id()] = coreIdentity;
357   // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
358   coreIdentity->synchronize(signalProxy());
359   connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
360   emit identityCreated(*coreIdentity);
361 }
362
363 void CoreSession::updateIdentityBySender() {
364   CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
365   if(!identity)
366     return;
367   Core::updateIdentity(user(), *identity);
368 }
369
370 void CoreSession::removeIdentity(IdentityId id) {
371   CoreIdentity *identity = _identities.take(id);
372   if(identity) {
373     emit identityRemoved(id);
374     Core::removeIdentity(user(), id);
375     identity->deleteLater();
376   }
377 }
378
379 /*** Network Handling ***/
380
381 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
382   NetworkInfo info = info_;
383   int id;
384
385   if(!info.networkId.isValid())
386     Core::createNetwork(user(), info);
387
388   if(!info.networkId.isValid()) {
389     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
390     return;
391   }
392
393   id = info.networkId.toInt();
394   if(!_networks.contains(id)) {
395
396     // create persistent chans
397     QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
398     foreach(QString channel, persistentChans) {
399       if(!rx.exactMatch(channel)) {
400         qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
401         continue;
402       }
403       Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
404       Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
405       if(!rx.cap(2).isEmpty())
406         Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
407     }
408
409     CoreNetwork *net = new CoreNetwork(id, this);
410     connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
411                  SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
412     connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
413
414     net->setNetworkInfo(info);
415     net->setProxy(signalProxy());
416     _networks[id] = net;
417     signalProxy()->synchronize(net);
418     emit networkCreated(id);
419   } else {
420     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
421     _networks[info.networkId]->requestSetNetworkInfo(info);
422   }
423 }
424
425 void CoreSession::removeNetwork(NetworkId id) {
426   // Make sure the network is disconnected!
427   CoreNetwork *net = network(id);
428   if(!net)
429     return;
430
431   if(net->connectionState() != Network::Disconnected) {
432     connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
433     net->disconnectFromIrc();
434   } else {
435     destroyNetwork(id);
436   }
437 }
438
439 void CoreSession::destroyNetwork(NetworkId id) {
440   QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
441   Network *net = _networks.take(id);
442   if(net && Core::removeNetwork(user(), id)) {
443     foreach(BufferId bufferId, removedBuffers) {
444       _bufferSyncer->removeBuffer(bufferId);
445     }
446     emit networkRemoved(id);
447     net->deleteLater();
448   }
449 }
450
451 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
452   BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
453   if(bufferInfo.isValid()) {
454     _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
455   }
456 }
457
458 void CoreSession::clientsConnected() {
459   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
460   Identity *identity = 0;
461   CoreNetwork *net = 0;
462   IrcUser *me = 0;
463   while(netIter != _networks.end()) {
464     net = *netIter;
465     netIter++;
466
467     if(!net->isConnected())
468       continue;
469     identity = net->identityPtr();
470     if(!identity)
471       continue;
472     me = net->me();
473     if(!me)
474       continue;
475
476     if(identity->detachAwayEnabled() && me->isAway()) {
477       net->userInputHandler()->handleAway(BufferInfo(), QString());
478     }
479   }
480 }
481
482 void CoreSession::clientsDisconnected() {
483   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
484   Identity *identity = 0;
485   CoreNetwork *net = 0;
486   IrcUser *me = 0;
487   QString awayReason;
488   while(netIter != _networks.end()) {
489     net = *netIter;
490     netIter++;
491
492     if(!net->isConnected())
493       continue;
494     identity = net->identityPtr();
495     if(!identity)
496       continue;
497     me = net->me();
498     if(!me)
499       continue;
500
501     if(identity->detachAwayEnabled() && !me->isAway()) {
502       if(!identity->detachAwayReason().isEmpty())
503         awayReason = identity->detachAwayReason();
504       net->setAutoAwayActive(true);
505       net->userInputHandler()->handleAway(BufferInfo(), awayReason);
506     }
507   }
508 }