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