1 /***************************************************************************
2 * Copyright (C) 2005-09 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include "coresession.h"
26 #include "coreuserinputhandler.h"
27 #include "corebuffersyncer.h"
28 #include "corebacklogmanager.h"
29 #include "corebufferviewmanager.h"
30 #include "coreidentity.h"
31 #include "coreignorelistmanager.h"
32 #include "coreirclisthelper.h"
33 #include "corenetwork.h"
34 #include "corenetworkconfig.h"
35 #include "coresessioneventprocessor.h"
36 #include "coreusersettings.h"
37 #include "eventmanager.h"
38 #include "ircchannel.h"
39 #include "ircparser.h"
42 #include "messageevent.h"
43 #include "signalproxy.h"
47 class ProcessMessagesEvent : public QEvent {
49 ProcessMessagesEvent() : QEvent(QEvent::User) {}
52 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
55 _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
57 _bufferSyncer(new CoreBufferSyncer(this)),
58 _backlogManager(new CoreBacklogManager(this)),
59 _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
60 _ircListHelper(new CoreIrcListHelper(this)),
61 _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
63 _eventManager(new EventManager(this)),
64 _eventProcessor(new CoreSessionEventProcessor(this)),
65 _ircParser(new IrcParser(this)),
66 scriptEngine(new QScriptEngine(this)),
67 _processMessages(false),
68 _ignoreListManager(this)
70 SignalProxy *p = signalProxy();
71 p->setHeartBeatInterval(30);
72 p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
74 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
76 connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
77 connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
79 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
80 p->attachSignal(this, SIGNAL(displayMsg(Message)));
81 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
83 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
84 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
85 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
86 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
88 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
89 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
90 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
91 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
96 eventManager()->registerObject(ircParser(), EventManager::NormalPriority, "process");
97 eventManager()->registerObject(eventProcessor(), EventManager::HighPriority, "process");
98 eventManager()->registerObject(this, EventManager::LowPriority, "process"); // for sending MessageEvents to the client
100 // periodically save our session state
101 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
103 p->synchronize(_bufferSyncer);
104 p->synchronize(&aliasManager());
105 p->synchronize(_backlogManager);
106 p->synchronize(ircListHelper());
107 p->synchronize(networkConfig());
108 p->synchronize(&_coreInfo);
109 p->synchronize(&_ignoreListManager);
110 // Restore session state
112 restoreSessionState();
117 CoreSession::~CoreSession() {
119 foreach(CoreNetwork *net, _networks.values()) {
124 CoreNetwork *CoreSession::network(NetworkId id) const {
125 if(_networks.contains(id)) return _networks[id];
129 CoreIdentity *CoreSession::identity(IdentityId id) const {
130 if(_identities.contains(id)) return _identities[id];
134 void CoreSession::loadSettings() {
135 CoreUserSettings s(user());
138 QList<IdentityId> ids = s.identityIds();
139 QList<NetworkInfo> networkInfos = Core::networks(user());
140 foreach(IdentityId id, ids) {
141 CoreIdentity identity(s.identity(id));
142 IdentityId newId = Core::createIdentity(user(), identity);
143 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
144 while(networkIter != networkInfos.end()) {
145 if(networkIter->identity == id) {
146 networkIter->identity = newId;
147 Core::updateNetwork(user(), *networkIter);
148 networkIter = networkInfos.erase(networkIter);
153 s.removeIdentity(id);
157 foreach(CoreIdentity identity, Core::identities(user())) {
158 createIdentity(identity);
161 foreach(NetworkInfo info, Core::networks(user())) {
166 void CoreSession::saveSessionState() const {
167 _bufferSyncer->storeDirtyIds();
168 _bufferViewManager->saveBufferViews();
169 _networkConfig->save();
172 void CoreSession::restoreSessionState() {
173 QList<NetworkId> nets = Core::connectedNetworks(user());
174 CoreNetwork *net = 0;
175 foreach(NetworkId id, nets) {
182 void CoreSession::addClient(QIODevice *device) {
184 qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
186 // if the socket is an orphan, the signalProxy adopts it.
187 // -> we don't need to care about it anymore
188 device->setParent(0);
189 signalProxy()->addPeer(device);
191 reply["MsgType"] = "SessionInit";
192 reply["SessionState"] = sessionState();
193 SignalProxy::writeDataToDevice(device, reply);
197 void CoreSession::addClient(SignalProxy *proxy) {
198 signalProxy()->addPeer(proxy);
199 emit sessionState(sessionState());
202 void CoreSession::removeClient(QIODevice *iodev) {
203 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
205 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
208 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
209 return Core::persistentChannels(user(), id);
212 // FIXME switch to BufferId
213 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
214 CoreNetwork *net = network(bufinfo.networkId());
216 net->userInput(bufinfo, msg);
218 qWarning() << "Trying to send to unconnected network:" << msg;
222 // ALL messages coming pass through these functions before going to the GUI.
223 // So this is the perfect place for storing the backlog and log stuff.
224 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
225 const QString &target, const QString &text_, const QString &sender, Message::Flags flags) {
227 // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
228 // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
229 // KDE's notifications), hence we remove those just to be safe.
230 QString text = text_;
231 text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
232 RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
234 // check for HardStrictness ignore
235 CoreNetwork *currentNetwork = network(networkId);
236 QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
237 if(_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
240 _messageQueue << rawMsg;
241 if(!_processMessages) {
242 _processMessages = true;
243 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
247 void CoreSession::recvStatusMsgFromServer(QString msg) {
248 CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
250 emit displayStatusMsg(net->networkName(), msg);
253 void CoreSession::processMessageEvent(MessageEvent *event) {
254 recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(), event->target(),
255 event->text(), event->sender(), event->msgFlags());
258 QList<BufferInfo> CoreSession::buffers() const {
259 return Core::requestBuffers(user());
262 void CoreSession::customEvent(QEvent *event) {
263 if(event->type() != QEvent::User)
270 void CoreSession::processMessages() {
271 if(_messageQueue.count() == 1) {
272 const RawMessage &rawMsg = _messageQueue.first();
273 bool createBuffer = !(rawMsg.flags & Message::Redirected);
274 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
275 if(!bufferInfo.isValid()) {
276 Q_ASSERT(!createBuffer);
277 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
279 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
280 Core::storeMessage(msg);
281 emit displayMsg(msg);
283 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
284 MessageList messages;
285 QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
286 BufferInfo bufferInfo;
287 for(int i = 0; i < _messageQueue.count(); i++) {
288 const RawMessage &rawMsg = _messageQueue.at(i);
289 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
290 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
292 bool createBuffer = !(rawMsg.flags & Message::Redirected);
293 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
294 if(!bufferInfo.isValid()) {
295 Q_ASSERT(!createBuffer);
296 redirectedMessages << rawMsg;
299 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
301 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
305 // recheck if there exists a buffer to store a redirected message in
306 for(int i = 0; i < redirectedMessages.count(); i++) {
307 const RawMessage &rawMsg = _messageQueue.at(i);
308 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
309 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
311 // no luck -> we store them in the StatusBuffer
312 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
313 // add the StatusBuffer to the Cache in case there are more Messages for the original target
314 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
316 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
320 Core::storeMessages(messages);
321 // FIXME: extend protocol to a displayMessages(MessageList)
322 for(int i = 0; i < messages.count(); i++) {
323 emit displayMsg(messages[i]);
326 _processMessages = false;
327 _messageQueue.clear();
330 QVariant CoreSession::sessionState() {
333 v["CoreFeatures"] = (int)Quassel::features();
336 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
337 v["BufferInfos"] = bufs;
338 QVariantList networkids;
339 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
340 v["NetworkIds"] = networkids;
342 quint32 ircusercount = 0;
343 quint32 ircchannelcount = 0;
344 foreach(Network *net, _networks.values()) {
345 ircusercount += net->ircUserCount();
346 ircchannelcount += net->ircChannelCount();
348 v["IrcUserCount"] = ircusercount;
349 v["IrcChannelCount"] = ircchannelcount;
351 QList<QVariant> idlist;
352 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
353 v["Identities"] = idlist;
355 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
359 void CoreSession::initScriptEngine() {
360 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
361 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
364 //QScriptValue storage_ = scriptEngine->newQObject(storage);
365 //scriptEngine->globalObject().setProperty("storage", storage_);
368 void CoreSession::scriptRequest(QString script) {
369 emit scriptResult(scriptEngine->evaluate(script).toString());
372 /*** Identity Handling ***/
373 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
378 CoreIdentity coreIdentity(identity);
380 if(additional.contains("KeyPem"))
381 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
382 if(additional.contains("CertPem"))
383 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
385 qDebug() << Q_FUNC_INFO;
386 IdentityId id = Core::createIdentity(user(), coreIdentity);
390 createIdentity(coreIdentity);
393 void CoreSession::createIdentity(const CoreIdentity &identity) {
394 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
395 _identities[identity.id()] = coreIdentity;
396 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
397 coreIdentity->synchronize(signalProxy());
398 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
399 emit identityCreated(*coreIdentity);
402 void CoreSession::updateIdentityBySender() {
403 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
406 Core::updateIdentity(user(), *identity);
409 void CoreSession::removeIdentity(IdentityId id) {
410 CoreIdentity *identity = _identities.take(id);
412 emit identityRemoved(id);
413 Core::removeIdentity(user(), id);
414 identity->deleteLater();
418 /*** Network Handling ***/
420 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
421 NetworkInfo info = info_;
424 if(!info.networkId.isValid())
425 Core::createNetwork(user(), info);
427 if(!info.networkId.isValid()) {
428 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
432 id = info.networkId.toInt();
433 if(!_networks.contains(id)) {
435 // create persistent chans
436 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
437 foreach(QString channel, persistentChans) {
438 if(!rx.exactMatch(channel)) {
439 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
442 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
443 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
444 if(!rx.cap(2).isEmpty())
445 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
448 CoreNetwork *net = new CoreNetwork(id, this);
449 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
450 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
451 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
453 net->setNetworkInfo(info);
454 net->setProxy(signalProxy());
456 signalProxy()->synchronize(net);
457 emit networkCreated(id);
459 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
460 _networks[info.networkId]->requestSetNetworkInfo(info);
464 void CoreSession::removeNetwork(NetworkId id) {
465 // Make sure the network is disconnected!
466 CoreNetwork *net = network(id);
470 if(net->connectionState() != Network::Disconnected) {
471 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
472 net->disconnectFromIrc();
478 void CoreSession::destroyNetwork(NetworkId id) {
479 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
480 Network *net = _networks.take(id);
481 if(net && Core::removeNetwork(user(), id)) {
482 foreach(BufferId bufferId, removedBuffers) {
483 _bufferSyncer->removeBuffer(bufferId);
485 emit networkRemoved(id);
490 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
491 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
492 if(bufferInfo.isValid()) {
493 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
497 void CoreSession::clientsConnected() {
498 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
499 Identity *identity = 0;
500 CoreNetwork *net = 0;
502 while(netIter != _networks.end()) {
506 if(!net->isConnected())
508 identity = net->identityPtr();
515 if(identity->detachAwayEnabled() && me->isAway()) {
516 net->userInputHandler()->handleAway(BufferInfo(), QString());
521 void CoreSession::clientsDisconnected() {
522 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
523 Identity *identity = 0;
524 CoreNetwork *net = 0;
527 while(netIter != _networks.end()) {
531 if(!net->isConnected())
534 identity = net->identityPtr();
541 if(identity->detachAwayEnabled() && !me->isAway()) {
542 if(!identity->detachAwayReason().isEmpty())
543 awayReason = identity->detachAwayReason();
544 net->setAutoAwayActive(true);
545 net->userInputHandler()->handleAway(BufferInfo(), awayReason);
551 void CoreSession::globalAway(const QString &msg) {
552 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
553 CoreNetwork *net = 0;
554 while(netIter != _networks.end()) {
558 if(!net->isConnected())
561 net->userInputHandler()->issueAway(msg, false /* no force away */);