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