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