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"
41 #include "signalproxy.h"
45 class ProcessMessagesEvent : public QEvent {
47 ProcessMessagesEvent() : QEvent(QEvent::User) {}
50 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
53 _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
55 _bufferSyncer(new CoreBufferSyncer(this)),
56 _backlogManager(new CoreBacklogManager(this)),
57 _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
58 _ircListHelper(new CoreIrcListHelper(this)),
59 _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
61 _eventManager(new EventManager(this)),
62 _eventProcessor(new CoreSessionEventProcessor(this)),
63 scriptEngine(new QScriptEngine(this)),
64 _processMessages(false),
65 _ignoreListManager(this)
67 SignalProxy *p = signalProxy();
68 p->setHeartBeatInterval(30);
69 p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
71 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
73 connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
74 connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
76 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
77 p->attachSignal(this, SIGNAL(displayMsg(Message)));
78 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
80 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
81 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
82 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
83 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
85 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
86 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
87 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
88 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
93 eventManager()->registerObject(eventProcessor(), EventManager::Prepend, "process");
95 // periodically save our session state
96 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
98 p->synchronize(_bufferSyncer);
99 p->synchronize(&aliasManager());
100 p->synchronize(_backlogManager);
101 p->synchronize(ircListHelper());
102 p->synchronize(networkConfig());
103 p->synchronize(&_coreInfo);
104 p->synchronize(&_ignoreListManager);
105 // Restore session state
107 restoreSessionState();
112 CoreSession::~CoreSession() {
114 foreach(CoreNetwork *net, _networks.values()) {
119 CoreNetwork *CoreSession::network(NetworkId id) const {
120 if(_networks.contains(id)) return _networks[id];
124 CoreIdentity *CoreSession::identity(IdentityId id) const {
125 if(_identities.contains(id)) return _identities[id];
129 void CoreSession::loadSettings() {
130 CoreUserSettings s(user());
133 QList<IdentityId> ids = s.identityIds();
134 QList<NetworkInfo> networkInfos = Core::networks(user());
135 foreach(IdentityId id, ids) {
136 CoreIdentity identity(s.identity(id));
137 IdentityId newId = Core::createIdentity(user(), identity);
138 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
139 while(networkIter != networkInfos.end()) {
140 if(networkIter->identity == id) {
141 networkIter->identity = newId;
142 Core::updateNetwork(user(), *networkIter);
143 networkIter = networkInfos.erase(networkIter);
148 s.removeIdentity(id);
152 foreach(CoreIdentity identity, Core::identities(user())) {
153 createIdentity(identity);
156 foreach(NetworkInfo info, Core::networks(user())) {
161 void CoreSession::saveSessionState() const {
162 _bufferSyncer->storeDirtyIds();
163 _bufferViewManager->saveBufferViews();
164 _networkConfig->save();
167 void CoreSession::restoreSessionState() {
168 QList<NetworkId> nets = Core::connectedNetworks(user());
169 CoreNetwork *net = 0;
170 foreach(NetworkId id, nets) {
177 void CoreSession::addClient(QIODevice *device) {
179 qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
181 // if the socket is an orphan, the signalProxy adopts it.
182 // -> we don't need to care about it anymore
183 device->setParent(0);
184 signalProxy()->addPeer(device);
186 reply["MsgType"] = "SessionInit";
187 reply["SessionState"] = sessionState();
188 SignalProxy::writeDataToDevice(device, reply);
192 void CoreSession::addClient(SignalProxy *proxy) {
193 signalProxy()->addPeer(proxy);
194 emit sessionState(sessionState());
197 void CoreSession::removeClient(QIODevice *iodev) {
198 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
200 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
203 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
204 return Core::persistentChannels(user(), id);
207 // FIXME switch to BufferId
208 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
209 CoreNetwork *net = network(bufinfo.networkId());
211 net->userInput(bufinfo, msg);
213 qWarning() << "Trying to send to unconnected network:" << msg;
217 // ALL messages coming pass through these functions before going to the GUI.
218 // So this is the perfect place for storing the backlog and log stuff.
219 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
220 const QString &target, const QString &text_, const QString &sender, Message::Flags flags) {
222 // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
223 // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
224 // KDE's notifications), hence we remove those just to be safe.
225 QString text = text_;
226 text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
227 RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
229 // check for HardStrictness ignore
230 CoreNetwork *currentNetwork = network(networkId);
231 QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
232 if(_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
235 _messageQueue << rawMsg;
236 if(!_processMessages) {
237 _processMessages = true;
238 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
242 void CoreSession::recvStatusMsgFromServer(QString msg) {
243 CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
245 emit displayStatusMsg(net->networkName(), msg);
248 QList<BufferInfo> CoreSession::buffers() const {
249 return Core::requestBuffers(user());
252 void CoreSession::customEvent(QEvent *event) {
253 if(event->type() != QEvent::User)
260 void CoreSession::processMessages() {
261 if(_messageQueue.count() == 1) {
262 const RawMessage &rawMsg = _messageQueue.first();
263 bool createBuffer = !(rawMsg.flags & Message::Redirected);
264 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
265 if(!bufferInfo.isValid()) {
266 Q_ASSERT(!createBuffer);
267 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
269 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
270 Core::storeMessage(msg);
271 emit displayMsg(msg);
273 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
274 MessageList messages;
275 QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
276 BufferInfo bufferInfo;
277 for(int i = 0; i < _messageQueue.count(); i++) {
278 const RawMessage &rawMsg = _messageQueue.at(i);
279 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
280 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
282 bool createBuffer = !(rawMsg.flags & Message::Redirected);
283 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
284 if(!bufferInfo.isValid()) {
285 Q_ASSERT(!createBuffer);
286 redirectedMessages << rawMsg;
289 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
291 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
295 // recheck if there exists a buffer to store a redirected message in
296 for(int i = 0; i < redirectedMessages.count(); i++) {
297 const RawMessage &rawMsg = _messageQueue.at(i);
298 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
299 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
301 // no luck -> we store them in the StatusBuffer
302 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
303 // add the StatusBuffer to the Cache in case there are more Messages for the original target
304 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
306 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
310 Core::storeMessages(messages);
311 // FIXME: extend protocol to a displayMessages(MessageList)
312 for(int i = 0; i < messages.count(); i++) {
313 emit displayMsg(messages[i]);
316 _processMessages = false;
317 _messageQueue.clear();
320 QVariant CoreSession::sessionState() {
323 v["CoreFeatures"] = (int)Quassel::features();
326 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
327 v["BufferInfos"] = bufs;
328 QVariantList networkids;
329 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
330 v["NetworkIds"] = networkids;
332 quint32 ircusercount = 0;
333 quint32 ircchannelcount = 0;
334 foreach(Network *net, _networks.values()) {
335 ircusercount += net->ircUserCount();
336 ircchannelcount += net->ircChannelCount();
338 v["IrcUserCount"] = ircusercount;
339 v["IrcChannelCount"] = ircchannelcount;
341 QList<QVariant> idlist;
342 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
343 v["Identities"] = idlist;
345 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
349 void CoreSession::initScriptEngine() {
350 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
351 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
354 //QScriptValue storage_ = scriptEngine->newQObject(storage);
355 //scriptEngine->globalObject().setProperty("storage", storage_);
358 void CoreSession::scriptRequest(QString script) {
359 emit scriptResult(scriptEngine->evaluate(script).toString());
362 /*** Identity Handling ***/
363 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
368 CoreIdentity coreIdentity(identity);
370 if(additional.contains("KeyPem"))
371 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
372 if(additional.contains("CertPem"))
373 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
375 qDebug() << Q_FUNC_INFO;
376 IdentityId id = Core::createIdentity(user(), coreIdentity);
380 createIdentity(coreIdentity);
383 void CoreSession::createIdentity(const CoreIdentity &identity) {
384 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
385 _identities[identity.id()] = coreIdentity;
386 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
387 coreIdentity->synchronize(signalProxy());
388 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
389 emit identityCreated(*coreIdentity);
392 void CoreSession::updateIdentityBySender() {
393 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
396 Core::updateIdentity(user(), *identity);
399 void CoreSession::removeIdentity(IdentityId id) {
400 CoreIdentity *identity = _identities.take(id);
402 emit identityRemoved(id);
403 Core::removeIdentity(user(), id);
404 identity->deleteLater();
408 /*** Network Handling ***/
410 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
411 NetworkInfo info = info_;
414 if(!info.networkId.isValid())
415 Core::createNetwork(user(), info);
417 if(!info.networkId.isValid()) {
418 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
422 id = info.networkId.toInt();
423 if(!_networks.contains(id)) {
425 // create persistent chans
426 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
427 foreach(QString channel, persistentChans) {
428 if(!rx.exactMatch(channel)) {
429 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
432 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
433 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
434 if(!rx.cap(2).isEmpty())
435 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
438 CoreNetwork *net = new CoreNetwork(id, this);
439 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
440 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
441 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
443 net->setNetworkInfo(info);
444 net->setProxy(signalProxy());
446 signalProxy()->synchronize(net);
447 emit networkCreated(id);
449 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
450 _networks[info.networkId]->requestSetNetworkInfo(info);
454 void CoreSession::removeNetwork(NetworkId id) {
455 // Make sure the network is disconnected!
456 CoreNetwork *net = network(id);
460 if(net->connectionState() != Network::Disconnected) {
461 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
462 net->disconnectFromIrc();
468 void CoreSession::destroyNetwork(NetworkId id) {
469 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
470 Network *net = _networks.take(id);
471 if(net && Core::removeNetwork(user(), id)) {
472 foreach(BufferId bufferId, removedBuffers) {
473 _bufferSyncer->removeBuffer(bufferId);
475 emit networkRemoved(id);
480 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
481 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
482 if(bufferInfo.isValid()) {
483 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
487 void CoreSession::clientsConnected() {
488 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
489 Identity *identity = 0;
490 CoreNetwork *net = 0;
492 while(netIter != _networks.end()) {
496 if(!net->isConnected())
498 identity = net->identityPtr();
505 if(identity->detachAwayEnabled() && me->isAway()) {
506 net->userInputHandler()->handleAway(BufferInfo(), QString());
511 void CoreSession::clientsDisconnected() {
512 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
513 Identity *identity = 0;
514 CoreNetwork *net = 0;
517 while(netIter != _networks.end()) {
521 if(!net->isConnected())
524 identity = net->identityPtr();
531 if(identity->detachAwayEnabled() && !me->isAway()) {
532 if(!identity->detachAwayReason().isEmpty())
533 awayReason = identity->detachAwayReason();
534 net->setAutoAwayActive(true);
535 net->userInputHandler()->handleAway(BufferInfo(), awayReason);
541 void CoreSession::globalAway(const QString &msg) {
542 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
543 CoreNetwork *net = 0;
544 while(netIter != _networks.end()) {
548 if(!net->isConnected())
551 net->userInputHandler()->issueAway(msg, false /* no force away */);