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 "signalproxy.h"
46 class ProcessMessagesEvent : public QEvent {
48 ProcessMessagesEvent() : QEvent(QEvent::User) {}
51 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
54 _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
56 _bufferSyncer(new CoreBufferSyncer(this)),
57 _backlogManager(new CoreBacklogManager(this)),
58 _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
59 _ircListHelper(new CoreIrcListHelper(this)),
60 _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
62 _eventManager(new EventManager(this)),
63 _eventProcessor(new CoreSessionEventProcessor(this)),
64 _ircParser(new IrcParser(this)),
65 scriptEngine(new QScriptEngine(this)),
66 _processMessages(false),
67 _ignoreListManager(this)
69 SignalProxy *p = signalProxy();
70 p->setHeartBeatInterval(30);
71 p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
73 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
75 connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
76 connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
78 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
79 p->attachSignal(this, SIGNAL(displayMsg(Message)));
80 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
82 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
83 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
84 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
85 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
87 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
88 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
89 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
90 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
95 eventManager()->registerObject(ircParser(), EventManager::NormalPriority, "process");
96 eventManager()->registerObject(eventProcessor(), EventManager::HighPriority, "process");
98 // periodically save our session state
99 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
101 p->synchronize(_bufferSyncer);
102 p->synchronize(&aliasManager());
103 p->synchronize(_backlogManager);
104 p->synchronize(ircListHelper());
105 p->synchronize(networkConfig());
106 p->synchronize(&_coreInfo);
107 p->synchronize(&_ignoreListManager);
108 // Restore session state
110 restoreSessionState();
115 CoreSession::~CoreSession() {
117 foreach(CoreNetwork *net, _networks.values()) {
122 CoreNetwork *CoreSession::network(NetworkId id) const {
123 if(_networks.contains(id)) return _networks[id];
127 CoreIdentity *CoreSession::identity(IdentityId id) const {
128 if(_identities.contains(id)) return _identities[id];
132 void CoreSession::loadSettings() {
133 CoreUserSettings s(user());
136 QList<IdentityId> ids = s.identityIds();
137 QList<NetworkInfo> networkInfos = Core::networks(user());
138 foreach(IdentityId id, ids) {
139 CoreIdentity identity(s.identity(id));
140 IdentityId newId = Core::createIdentity(user(), identity);
141 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
142 while(networkIter != networkInfos.end()) {
143 if(networkIter->identity == id) {
144 networkIter->identity = newId;
145 Core::updateNetwork(user(), *networkIter);
146 networkIter = networkInfos.erase(networkIter);
151 s.removeIdentity(id);
155 foreach(CoreIdentity identity, Core::identities(user())) {
156 createIdentity(identity);
159 foreach(NetworkInfo info, Core::networks(user())) {
164 void CoreSession::saveSessionState() const {
165 _bufferSyncer->storeDirtyIds();
166 _bufferViewManager->saveBufferViews();
167 _networkConfig->save();
170 void CoreSession::restoreSessionState() {
171 QList<NetworkId> nets = Core::connectedNetworks(user());
172 CoreNetwork *net = 0;
173 foreach(NetworkId id, nets) {
180 void CoreSession::addClient(QIODevice *device) {
182 qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
184 // if the socket is an orphan, the signalProxy adopts it.
185 // -> we don't need to care about it anymore
186 device->setParent(0);
187 signalProxy()->addPeer(device);
189 reply["MsgType"] = "SessionInit";
190 reply["SessionState"] = sessionState();
191 SignalProxy::writeDataToDevice(device, reply);
195 void CoreSession::addClient(SignalProxy *proxy) {
196 signalProxy()->addPeer(proxy);
197 emit sessionState(sessionState());
200 void CoreSession::removeClient(QIODevice *iodev) {
201 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
203 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
206 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
207 return Core::persistentChannels(user(), id);
210 // FIXME switch to BufferId
211 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
212 CoreNetwork *net = network(bufinfo.networkId());
214 net->userInput(bufinfo, msg);
216 qWarning() << "Trying to send to unconnected network:" << msg;
220 // ALL messages coming pass through these functions before going to the GUI.
221 // So this is the perfect place for storing the backlog and log stuff.
222 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
223 const QString &target, const QString &text_, const QString &sender, Message::Flags flags) {
225 // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
226 // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
227 // KDE's notifications), hence we remove those just to be safe.
228 QString text = text_;
229 text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
230 RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
232 // check for HardStrictness ignore
233 CoreNetwork *currentNetwork = network(networkId);
234 QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
235 if(_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
238 _messageQueue << rawMsg;
239 if(!_processMessages) {
240 _processMessages = true;
241 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
245 void CoreSession::recvStatusMsgFromServer(QString msg) {
246 CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
248 emit displayStatusMsg(net->networkName(), msg);
251 QList<BufferInfo> CoreSession::buffers() const {
252 return Core::requestBuffers(user());
255 void CoreSession::customEvent(QEvent *event) {
256 if(event->type() != QEvent::User)
263 void CoreSession::processMessages() {
264 if(_messageQueue.count() == 1) {
265 const RawMessage &rawMsg = _messageQueue.first();
266 bool createBuffer = !(rawMsg.flags & Message::Redirected);
267 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
268 if(!bufferInfo.isValid()) {
269 Q_ASSERT(!createBuffer);
270 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
272 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
273 Core::storeMessage(msg);
274 emit displayMsg(msg);
276 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
277 MessageList messages;
278 QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
279 BufferInfo bufferInfo;
280 for(int i = 0; i < _messageQueue.count(); i++) {
281 const RawMessage &rawMsg = _messageQueue.at(i);
282 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
283 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
285 bool createBuffer = !(rawMsg.flags & Message::Redirected);
286 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
287 if(!bufferInfo.isValid()) {
288 Q_ASSERT(!createBuffer);
289 redirectedMessages << rawMsg;
292 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
294 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
298 // recheck if there exists a buffer to store a redirected message in
299 for(int i = 0; i < redirectedMessages.count(); i++) {
300 const RawMessage &rawMsg = _messageQueue.at(i);
301 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
302 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
304 // no luck -> we store them in the StatusBuffer
305 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
306 // add the StatusBuffer to the Cache in case there are more Messages for the original target
307 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
309 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
313 Core::storeMessages(messages);
314 // FIXME: extend protocol to a displayMessages(MessageList)
315 for(int i = 0; i < messages.count(); i++) {
316 emit displayMsg(messages[i]);
319 _processMessages = false;
320 _messageQueue.clear();
323 QVariant CoreSession::sessionState() {
326 v["CoreFeatures"] = (int)Quassel::features();
329 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
330 v["BufferInfos"] = bufs;
331 QVariantList networkids;
332 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
333 v["NetworkIds"] = networkids;
335 quint32 ircusercount = 0;
336 quint32 ircchannelcount = 0;
337 foreach(Network *net, _networks.values()) {
338 ircusercount += net->ircUserCount();
339 ircchannelcount += net->ircChannelCount();
341 v["IrcUserCount"] = ircusercount;
342 v["IrcChannelCount"] = ircchannelcount;
344 QList<QVariant> idlist;
345 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
346 v["Identities"] = idlist;
348 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
352 void CoreSession::initScriptEngine() {
353 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
354 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
357 //QScriptValue storage_ = scriptEngine->newQObject(storage);
358 //scriptEngine->globalObject().setProperty("storage", storage_);
361 void CoreSession::scriptRequest(QString script) {
362 emit scriptResult(scriptEngine->evaluate(script).toString());
365 /*** Identity Handling ***/
366 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
371 CoreIdentity coreIdentity(identity);
373 if(additional.contains("KeyPem"))
374 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
375 if(additional.contains("CertPem"))
376 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
378 qDebug() << Q_FUNC_INFO;
379 IdentityId id = Core::createIdentity(user(), coreIdentity);
383 createIdentity(coreIdentity);
386 void CoreSession::createIdentity(const CoreIdentity &identity) {
387 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
388 _identities[identity.id()] = coreIdentity;
389 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
390 coreIdentity->synchronize(signalProxy());
391 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
392 emit identityCreated(*coreIdentity);
395 void CoreSession::updateIdentityBySender() {
396 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
399 Core::updateIdentity(user(), *identity);
402 void CoreSession::removeIdentity(IdentityId id) {
403 CoreIdentity *identity = _identities.take(id);
405 emit identityRemoved(id);
406 Core::removeIdentity(user(), id);
407 identity->deleteLater();
411 /*** Network Handling ***/
413 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
414 NetworkInfo info = info_;
417 if(!info.networkId.isValid())
418 Core::createNetwork(user(), info);
420 if(!info.networkId.isValid()) {
421 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
425 id = info.networkId.toInt();
426 if(!_networks.contains(id)) {
428 // create persistent chans
429 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
430 foreach(QString channel, persistentChans) {
431 if(!rx.exactMatch(channel)) {
432 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
435 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
436 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
437 if(!rx.cap(2).isEmpty())
438 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
441 CoreNetwork *net = new CoreNetwork(id, this);
442 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
443 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
444 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
446 net->setNetworkInfo(info);
447 net->setProxy(signalProxy());
449 signalProxy()->synchronize(net);
450 emit networkCreated(id);
452 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
453 _networks[info.networkId]->requestSetNetworkInfo(info);
457 void CoreSession::removeNetwork(NetworkId id) {
458 // Make sure the network is disconnected!
459 CoreNetwork *net = network(id);
463 if(net->connectionState() != Network::Disconnected) {
464 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
465 net->disconnectFromIrc();
471 void CoreSession::destroyNetwork(NetworkId id) {
472 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
473 Network *net = _networks.take(id);
474 if(net && Core::removeNetwork(user(), id)) {
475 foreach(BufferId bufferId, removedBuffers) {
476 _bufferSyncer->removeBuffer(bufferId);
478 emit networkRemoved(id);
483 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
484 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
485 if(bufferInfo.isValid()) {
486 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
490 void CoreSession::clientsConnected() {
491 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
492 Identity *identity = 0;
493 CoreNetwork *net = 0;
495 while(netIter != _networks.end()) {
499 if(!net->isConnected())
501 identity = net->identityPtr();
508 if(identity->detachAwayEnabled() && me->isAway()) {
509 net->userInputHandler()->handleAway(BufferInfo(), QString());
514 void CoreSession::clientsDisconnected() {
515 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
516 Identity *identity = 0;
517 CoreNetwork *net = 0;
520 while(netIter != _networks.end()) {
524 if(!net->isConnected())
527 identity = net->identityPtr();
534 if(identity->detachAwayEnabled() && !me->isAway()) {
535 if(!identity->detachAwayReason().isEmpty())
536 awayReason = identity->detachAwayReason();
537 net->setAutoAwayActive(true);
538 net->userInputHandler()->handleAway(BufferInfo(), awayReason);
544 void CoreSession::globalAway(const QString &msg) {
545 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
546 CoreNetwork *net = 0;
547 while(netIter != _networks.end()) {
551 if(!net->isConnected())
554 net->userInputHandler()->issueAway(msg, false /* no force away */);