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 "eventstringifier.h"
39 #include "ircchannel.h"
40 #include "ircparser.h"
43 #include "messageevent.h"
44 #include "signalproxy.h"
48 class ProcessMessagesEvent : public QEvent {
50 ProcessMessagesEvent() : QEvent(QEvent::User) {}
53 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
56 _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
58 _bufferSyncer(new CoreBufferSyncer(this)),
59 _backlogManager(new CoreBacklogManager(this)),
60 _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
61 _ircListHelper(new CoreIrcListHelper(this)),
62 _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
64 _eventManager(new EventManager(this)),
65 _eventStringifier(new EventStringifier(this)),
66 _eventProcessor(new CoreSessionEventProcessor(this)),
67 _ircParser(new IrcParser(this)),
68 scriptEngine(new QScriptEngine(this)),
69 _processMessages(false),
70 _ignoreListManager(this)
72 SignalProxy *p = signalProxy();
73 p->setHeartBeatInterval(30);
74 p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
76 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
78 connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
79 connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
81 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
82 p->attachSignal(this, SIGNAL(displayMsg(Message)));
83 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
85 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
86 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
87 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
88 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
90 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
91 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
92 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
93 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
98 eventManager()->registerObject(ircParser(), EventManager::NormalPriority);
99 eventManager()->registerObject(eventProcessor(), EventManager::HighPriority);
100 eventManager()->registerObject(eventStringifier(), EventManager::NormalPriority);
101 eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client
103 // periodically save our session state
104 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
106 p->synchronize(_bufferSyncer);
107 p->synchronize(&aliasManager());
108 p->synchronize(_backlogManager);
109 p->synchronize(ircListHelper());
110 p->synchronize(networkConfig());
111 p->synchronize(&_coreInfo);
112 p->synchronize(&_ignoreListManager);
113 // Restore session state
115 restoreSessionState();
120 CoreSession::~CoreSession() {
122 foreach(CoreNetwork *net, _networks.values()) {
127 CoreNetwork *CoreSession::network(NetworkId id) const {
128 if(_networks.contains(id)) return _networks[id];
132 CoreIdentity *CoreSession::identity(IdentityId id) const {
133 if(_identities.contains(id)) return _identities[id];
137 void CoreSession::loadSettings() {
138 CoreUserSettings s(user());
141 QList<IdentityId> ids = s.identityIds();
142 QList<NetworkInfo> networkInfos = Core::networks(user());
143 foreach(IdentityId id, ids) {
144 CoreIdentity identity(s.identity(id));
145 IdentityId newId = Core::createIdentity(user(), identity);
146 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
147 while(networkIter != networkInfos.end()) {
148 if(networkIter->identity == id) {
149 networkIter->identity = newId;
150 Core::updateNetwork(user(), *networkIter);
151 networkIter = networkInfos.erase(networkIter);
156 s.removeIdentity(id);
160 foreach(CoreIdentity identity, Core::identities(user())) {
161 createIdentity(identity);
164 foreach(NetworkInfo info, Core::networks(user())) {
169 void CoreSession::saveSessionState() const {
170 _bufferSyncer->storeDirtyIds();
171 _bufferViewManager->saveBufferViews();
172 _networkConfig->save();
175 void CoreSession::restoreSessionState() {
176 QList<NetworkId> nets = Core::connectedNetworks(user());
177 CoreNetwork *net = 0;
178 foreach(NetworkId id, nets) {
185 void CoreSession::addClient(QIODevice *device) {
187 qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
189 // if the socket is an orphan, the signalProxy adopts it.
190 // -> we don't need to care about it anymore
191 device->setParent(0);
192 signalProxy()->addPeer(device);
194 reply["MsgType"] = "SessionInit";
195 reply["SessionState"] = sessionState();
196 SignalProxy::writeDataToDevice(device, reply);
200 void CoreSession::addClient(SignalProxy *proxy) {
201 signalProxy()->addPeer(proxy);
202 emit sessionState(sessionState());
205 void CoreSession::removeClient(QIODevice *iodev) {
206 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
208 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
211 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
212 return Core::persistentChannels(user(), id);
215 // FIXME switch to BufferId
216 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
217 CoreNetwork *net = network(bufinfo.networkId());
219 net->userInput(bufinfo, msg);
221 qWarning() << "Trying to send to unconnected network:" << msg;
225 // ALL messages coming pass through these functions before going to the GUI.
226 // So this is the perfect place for storing the backlog and log stuff.
227 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
228 const QString &target, const QString &text_, const QString &sender, Message::Flags flags) {
230 // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
231 // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
232 // KDE's notifications), hence we remove those just to be safe.
233 QString text = text_;
234 text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
235 RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
237 // check for HardStrictness ignore
238 CoreNetwork *currentNetwork = network(networkId);
239 QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
240 if(_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
243 _messageQueue << rawMsg;
244 if(!_processMessages) {
245 _processMessages = true;
246 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
250 void CoreSession::recvStatusMsgFromServer(QString msg) {
251 CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
253 emit displayStatusMsg(net->networkName(), msg);
256 void CoreSession::processMessageEvent(MessageEvent *event) {
257 recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(), event->target(),
258 event->text(), event->sender(), event->msgFlags());
261 QList<BufferInfo> CoreSession::buffers() const {
262 return Core::requestBuffers(user());
265 void CoreSession::customEvent(QEvent *event) {
266 if(event->type() != QEvent::User)
273 void CoreSession::processMessages() {
274 if(_messageQueue.count() == 1) {
275 const RawMessage &rawMsg = _messageQueue.first();
276 bool createBuffer = !(rawMsg.flags & Message::Redirected);
277 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
278 if(!bufferInfo.isValid()) {
279 Q_ASSERT(!createBuffer);
280 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
282 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
283 Core::storeMessage(msg);
284 emit displayMsg(msg);
286 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
287 MessageList messages;
288 QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
289 BufferInfo bufferInfo;
290 for(int i = 0; i < _messageQueue.count(); i++) {
291 const RawMessage &rawMsg = _messageQueue.at(i);
292 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
293 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
295 bool createBuffer = !(rawMsg.flags & Message::Redirected);
296 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
297 if(!bufferInfo.isValid()) {
298 Q_ASSERT(!createBuffer);
299 redirectedMessages << rawMsg;
302 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
304 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
308 // recheck if there exists a buffer to store a redirected message in
309 for(int i = 0; i < redirectedMessages.count(); i++) {
310 const RawMessage &rawMsg = _messageQueue.at(i);
311 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
312 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
314 // no luck -> we store them in the StatusBuffer
315 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
316 // add the StatusBuffer to the Cache in case there are more Messages for the original target
317 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
319 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
323 Core::storeMessages(messages);
324 // FIXME: extend protocol to a displayMessages(MessageList)
325 for(int i = 0; i < messages.count(); i++) {
326 emit displayMsg(messages[i]);
329 _processMessages = false;
330 _messageQueue.clear();
333 QVariant CoreSession::sessionState() {
336 v["CoreFeatures"] = (int)Quassel::features();
339 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
340 v["BufferInfos"] = bufs;
341 QVariantList networkids;
342 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
343 v["NetworkIds"] = networkids;
345 quint32 ircusercount = 0;
346 quint32 ircchannelcount = 0;
347 foreach(Network *net, _networks.values()) {
348 ircusercount += net->ircUserCount();
349 ircchannelcount += net->ircChannelCount();
351 v["IrcUserCount"] = ircusercount;
352 v["IrcChannelCount"] = ircchannelcount;
354 QList<QVariant> idlist;
355 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
356 v["Identities"] = idlist;
358 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
362 void CoreSession::initScriptEngine() {
363 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
364 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
367 //QScriptValue storage_ = scriptEngine->newQObject(storage);
368 //scriptEngine->globalObject().setProperty("storage", storage_);
371 void CoreSession::scriptRequest(QString script) {
372 emit scriptResult(scriptEngine->evaluate(script).toString());
375 /*** Identity Handling ***/
376 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
381 CoreIdentity coreIdentity(identity);
383 if(additional.contains("KeyPem"))
384 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
385 if(additional.contains("CertPem"))
386 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
388 qDebug() << Q_FUNC_INFO;
389 IdentityId id = Core::createIdentity(user(), coreIdentity);
393 createIdentity(coreIdentity);
396 void CoreSession::createIdentity(const CoreIdentity &identity) {
397 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
398 _identities[identity.id()] = coreIdentity;
399 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
400 coreIdentity->synchronize(signalProxy());
401 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
402 emit identityCreated(*coreIdentity);
405 void CoreSession::updateIdentityBySender() {
406 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
409 Core::updateIdentity(user(), *identity);
412 void CoreSession::removeIdentity(IdentityId id) {
413 CoreIdentity *identity = _identities.take(id);
415 emit identityRemoved(id);
416 Core::removeIdentity(user(), id);
417 identity->deleteLater();
421 /*** Network Handling ***/
423 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
424 NetworkInfo info = info_;
427 if(!info.networkId.isValid())
428 Core::createNetwork(user(), info);
430 if(!info.networkId.isValid()) {
431 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
435 id = info.networkId.toInt();
436 if(!_networks.contains(id)) {
438 // create persistent chans
439 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
440 foreach(QString channel, persistentChans) {
441 if(!rx.exactMatch(channel)) {
442 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
445 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
446 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
447 if(!rx.cap(2).isEmpty())
448 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
451 CoreNetwork *net = new CoreNetwork(id, this);
452 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
453 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
454 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
456 net->setNetworkInfo(info);
457 net->setProxy(signalProxy());
459 signalProxy()->synchronize(net);
460 emit networkCreated(id);
462 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
463 _networks[info.networkId]->requestSetNetworkInfo(info);
467 void CoreSession::removeNetwork(NetworkId id) {
468 // Make sure the network is disconnected!
469 CoreNetwork *net = network(id);
473 if(net->connectionState() != Network::Disconnected) {
474 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
475 net->disconnectFromIrc();
481 void CoreSession::destroyNetwork(NetworkId id) {
482 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
483 Network *net = _networks.take(id);
484 if(net && Core::removeNetwork(user(), id)) {
485 foreach(BufferId bufferId, removedBuffers) {
486 _bufferSyncer->removeBuffer(bufferId);
488 emit networkRemoved(id);
493 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
494 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
495 if(bufferInfo.isValid()) {
496 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
500 void CoreSession::clientsConnected() {
501 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
502 Identity *identity = 0;
503 CoreNetwork *net = 0;
505 while(netIter != _networks.end()) {
509 if(!net->isConnected())
511 identity = net->identityPtr();
518 if(identity->detachAwayEnabled() && me->isAway()) {
519 net->userInputHandler()->handleAway(BufferInfo(), QString());
524 void CoreSession::clientsDisconnected() {
525 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
526 Identity *identity = 0;
527 CoreNetwork *net = 0;
530 while(netIter != _networks.end()) {
534 if(!net->isConnected())
537 identity = net->identityPtr();
544 if(identity->detachAwayEnabled() && !me->isAway()) {
545 if(!identity->detachAwayReason().isEmpty())
546 awayReason = identity->detachAwayReason();
547 net->setAutoAwayActive(true);
548 net->userInputHandler()->handleAway(BufferInfo(), awayReason);
554 void CoreSession::globalAway(const QString &msg) {
555 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
556 CoreNetwork *net = 0;
557 while(netIter != _networks.end()) {
561 if(!net->isConnected())
564 net->userInputHandler()->issueAway(msg, false /* no force away */);