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); // needs to process events *before* the stringifier!
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(),
258 event->target().isNull()? "" : event->target(),
259 event->text().isNull()? "" : event->text(),
260 event->sender().isNull()? "" : event->sender(),
264 QList<BufferInfo> CoreSession::buffers() const {
265 return Core::requestBuffers(user());
268 void CoreSession::customEvent(QEvent *event) {
269 if(event->type() != QEvent::User)
276 void CoreSession::processMessages() {
277 if(_messageQueue.count() == 1) {
278 const RawMessage &rawMsg = _messageQueue.first();
279 bool createBuffer = !(rawMsg.flags & Message::Redirected);
280 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
281 if(!bufferInfo.isValid()) {
282 Q_ASSERT(!createBuffer);
283 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
285 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
286 Core::storeMessage(msg);
287 emit displayMsg(msg);
289 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
290 MessageList messages;
291 QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
292 BufferInfo bufferInfo;
293 for(int i = 0; i < _messageQueue.count(); i++) {
294 const RawMessage &rawMsg = _messageQueue.at(i);
295 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
296 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
298 bool createBuffer = !(rawMsg.flags & Message::Redirected);
299 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
300 if(!bufferInfo.isValid()) {
301 Q_ASSERT(!createBuffer);
302 redirectedMessages << rawMsg;
305 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
307 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
311 // recheck if there exists a buffer to store a redirected message in
312 for(int i = 0; i < redirectedMessages.count(); i++) {
313 const RawMessage &rawMsg = _messageQueue.at(i);
314 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
315 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
317 // no luck -> we store them in the StatusBuffer
318 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
319 // add the StatusBuffer to the Cache in case there are more Messages for the original target
320 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
322 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
326 Core::storeMessages(messages);
327 // FIXME: extend protocol to a displayMessages(MessageList)
328 for(int i = 0; i < messages.count(); i++) {
329 emit displayMsg(messages[i]);
332 _processMessages = false;
333 _messageQueue.clear();
336 QVariant CoreSession::sessionState() {
339 v["CoreFeatures"] = (int)Quassel::features();
342 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
343 v["BufferInfos"] = bufs;
344 QVariantList networkids;
345 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
346 v["NetworkIds"] = networkids;
348 quint32 ircusercount = 0;
349 quint32 ircchannelcount = 0;
350 foreach(Network *net, _networks.values()) {
351 ircusercount += net->ircUserCount();
352 ircchannelcount += net->ircChannelCount();
354 v["IrcUserCount"] = ircusercount;
355 v["IrcChannelCount"] = ircchannelcount;
357 QList<QVariant> idlist;
358 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
359 v["Identities"] = idlist;
361 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
365 void CoreSession::initScriptEngine() {
366 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
367 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
370 //QScriptValue storage_ = scriptEngine->newQObject(storage);
371 //scriptEngine->globalObject().setProperty("storage", storage_);
374 void CoreSession::scriptRequest(QString script) {
375 emit scriptResult(scriptEngine->evaluate(script).toString());
378 /*** Identity Handling ***/
379 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
384 CoreIdentity coreIdentity(identity);
386 if(additional.contains("KeyPem"))
387 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
388 if(additional.contains("CertPem"))
389 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
391 qDebug() << Q_FUNC_INFO;
392 IdentityId id = Core::createIdentity(user(), coreIdentity);
396 createIdentity(coreIdentity);
399 void CoreSession::createIdentity(const CoreIdentity &identity) {
400 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
401 _identities[identity.id()] = coreIdentity;
402 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
403 coreIdentity->synchronize(signalProxy());
404 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
405 emit identityCreated(*coreIdentity);
408 void CoreSession::updateIdentityBySender() {
409 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
412 Core::updateIdentity(user(), *identity);
415 void CoreSession::removeIdentity(IdentityId id) {
416 CoreIdentity *identity = _identities.take(id);
418 emit identityRemoved(id);
419 Core::removeIdentity(user(), id);
420 identity->deleteLater();
424 /*** Network Handling ***/
426 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
427 NetworkInfo info = info_;
430 if(!info.networkId.isValid())
431 Core::createNetwork(user(), info);
433 if(!info.networkId.isValid()) {
434 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
438 id = info.networkId.toInt();
439 if(!_networks.contains(id)) {
441 // create persistent chans
442 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
443 foreach(QString channel, persistentChans) {
444 if(!rx.exactMatch(channel)) {
445 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
448 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
449 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
450 if(!rx.cap(2).isEmpty())
451 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
454 CoreNetwork *net = new CoreNetwork(id, this);
455 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
456 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
457 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
459 net->setNetworkInfo(info);
460 net->setProxy(signalProxy());
462 signalProxy()->synchronize(net);
463 emit networkCreated(id);
465 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
466 _networks[info.networkId]->requestSetNetworkInfo(info);
470 void CoreSession::removeNetwork(NetworkId id) {
471 // Make sure the network is disconnected!
472 CoreNetwork *net = network(id);
476 if(net->connectionState() != Network::Disconnected) {
477 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
478 net->disconnectFromIrc();
484 void CoreSession::destroyNetwork(NetworkId id) {
485 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
486 Network *net = _networks.take(id);
487 if(net && Core::removeNetwork(user(), id)) {
488 foreach(BufferId bufferId, removedBuffers) {
489 _bufferSyncer->removeBuffer(bufferId);
491 emit networkRemoved(id);
496 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
497 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
498 if(bufferInfo.isValid()) {
499 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
503 void CoreSession::clientsConnected() {
504 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
505 Identity *identity = 0;
506 CoreNetwork *net = 0;
508 while(netIter != _networks.end()) {
512 if(!net->isConnected())
514 identity = net->identityPtr();
521 if(identity->detachAwayEnabled() && me->isAway()) {
522 net->userInputHandler()->handleAway(BufferInfo(), QString());
527 void CoreSession::clientsDisconnected() {
528 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
529 Identity *identity = 0;
530 CoreNetwork *net = 0;
533 while(netIter != _networks.end()) {
537 if(!net->isConnected())
540 identity = net->identityPtr();
547 if(identity->detachAwayEnabled() && !me->isAway()) {
548 if(!identity->detachAwayReason().isEmpty())
549 awayReason = identity->detachAwayReason();
550 net->setAutoAwayActive(true);
551 net->userInputHandler()->handleAway(BufferInfo(), awayReason);
557 void CoreSession::globalAway(const QString &msg) {
558 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
559 CoreNetwork *net = 0;
560 while(netIter != _networks.end()) {
564 if(!net->isConnected())
567 net->userInputHandler()->issueAway(msg, false /* no force away */);