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 ***************************************************************************/
24 #include "coresession.h"
25 #include "coreuserinputhandler.h"
26 #include "signalproxy.h"
27 #include "corebuffersyncer.h"
28 #include "corebacklogmanager.h"
29 #include "corebufferviewmanager.h"
30 #include "coreirclisthelper.h"
31 #include "corenetworkconfig.h"
34 #include "coreidentity.h"
35 #include "corenetwork.h"
37 #include "ircchannel.h"
40 #include "coreusersettings.h"
42 #include "coreignorelistmanager.h"
44 class ProcessMessagesEvent : public QEvent {
46 ProcessMessagesEvent() : QEvent(QEvent::User) {}
49 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
52 _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
54 _bufferSyncer(new CoreBufferSyncer(this)),
55 _backlogManager(new CoreBacklogManager(this)),
56 _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
57 _ircListHelper(new CoreIrcListHelper(this)),
58 _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
60 scriptEngine(new QScriptEngine(this)),
61 _processMessages(false),
62 _ignoreListManager(this)
64 SignalProxy *p = signalProxy();
65 p->setHeartBeatInterval(30);
66 p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
68 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
70 connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
71 connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
73 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
74 p->attachSignal(this, SIGNAL(displayMsg(Message)));
75 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
77 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
78 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
79 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
80 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
82 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
83 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
84 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
85 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
90 // periodically save our session state
91 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
93 p->synchronize(_bufferSyncer);
94 p->synchronize(&aliasManager());
95 p->synchronize(_backlogManager);
96 p->synchronize(ircListHelper());
97 p->synchronize(networkConfig());
98 p->synchronize(&_coreInfo);
99 p->synchronize(&_ignoreListManager);
100 // Restore session state
102 restoreSessionState();
107 CoreSession::~CoreSession() {
109 foreach(CoreNetwork *net, _networks.values()) {
114 CoreNetwork *CoreSession::network(NetworkId id) const {
115 if(_networks.contains(id)) return _networks[id];
119 CoreIdentity *CoreSession::identity(IdentityId id) const {
120 if(_identities.contains(id)) return _identities[id];
124 void CoreSession::loadSettings() {
125 CoreUserSettings s(user());
128 QList<IdentityId> ids = s.identityIds();
129 QList<NetworkInfo> networkInfos = Core::networks(user());
130 foreach(IdentityId id, ids) {
131 CoreIdentity identity(s.identity(id));
132 IdentityId newId = Core::createIdentity(user(), identity);
133 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
134 while(networkIter != networkInfos.end()) {
135 if(networkIter->identity == id) {
136 networkIter->identity = newId;
137 Core::updateNetwork(user(), *networkIter);
138 networkIter = networkInfos.erase(networkIter);
143 s.removeIdentity(id);
147 foreach(CoreIdentity identity, Core::identities(user())) {
148 createIdentity(identity);
151 foreach(NetworkInfo info, Core::networks(user())) {
156 void CoreSession::saveSessionState() const {
157 _bufferSyncer->storeDirtyIds();
158 _bufferViewManager->saveBufferViews();
159 _networkConfig->save();
162 void CoreSession::restoreSessionState() {
163 QList<NetworkId> nets = Core::connectedNetworks(user());
164 CoreNetwork *net = 0;
165 foreach(NetworkId id, nets) {
172 void CoreSession::addClient(QIODevice *device) {
174 qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
176 // if the socket is an orphan, the signalProxy adopts it.
177 // -> we don't need to care about it anymore
178 device->setParent(0);
179 signalProxy()->addPeer(device);
181 reply["MsgType"] = "SessionInit";
182 reply["SessionState"] = sessionState();
183 SignalProxy::writeDataToDevice(device, reply);
187 void CoreSession::addClient(SignalProxy *proxy) {
188 signalProxy()->addPeer(proxy);
189 emit sessionState(sessionState());
192 void CoreSession::removeClient(QIODevice *iodev) {
193 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
195 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
198 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
199 return Core::persistentChannels(user(), id);
202 // FIXME switch to BufferId
203 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
204 CoreNetwork *net = network(bufinfo.networkId());
206 net->userInput(bufinfo, msg);
208 qWarning() << "Trying to send to unconnected network:" << msg;
212 // ALL messages coming pass through these functions before going to the GUI.
213 // So this is the perfect place for storing the backlog and log stuff.
214 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
215 const QString &target, const QString &text_, const QString &sender, Message::Flags flags) {
217 // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
218 // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
219 // KDE's notifications), hence we remove those just to be safe.
220 QString text = text_;
221 text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
222 RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
224 // check for HardStrictness ignore
225 CoreNetwork *currentNetwork = network(networkId);
226 QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
227 if(_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
230 _messageQueue << rawMsg;
231 if(!_processMessages) {
232 _processMessages = true;
233 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
237 void CoreSession::recvStatusMsgFromServer(QString msg) {
238 CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
240 emit displayStatusMsg(net->networkName(), msg);
243 QList<BufferInfo> CoreSession::buffers() const {
244 return Core::requestBuffers(user());
247 void CoreSession::customEvent(QEvent *event) {
248 if(event->type() != QEvent::User)
255 void CoreSession::processMessages() {
256 if(_messageQueue.count() == 1) {
257 const RawMessage &rawMsg = _messageQueue.first();
258 bool createBuffer = !(rawMsg.flags & Message::Redirected);
259 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
260 if(!bufferInfo.isValid()) {
261 Q_ASSERT(!createBuffer);
262 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
264 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
265 Core::storeMessage(msg);
266 emit displayMsg(msg);
268 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
269 MessageList messages;
270 QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
271 BufferInfo bufferInfo;
272 for(int i = 0; i < _messageQueue.count(); i++) {
273 const RawMessage &rawMsg = _messageQueue.at(i);
274 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
275 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
277 bool createBuffer = !(rawMsg.flags & Message::Redirected);
278 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
279 if(!bufferInfo.isValid()) {
280 Q_ASSERT(!createBuffer);
281 redirectedMessages << rawMsg;
284 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
286 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
290 // recheck if there exists a buffer to store a redirected message in
291 for(int i = 0; i < redirectedMessages.count(); i++) {
292 const RawMessage &rawMsg = _messageQueue.at(i);
293 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
294 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
296 // no luck -> we store them in the StatusBuffer
297 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
298 // add the StatusBuffer to the Cache in case there are more Messages for the original target
299 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
301 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
305 Core::storeMessages(messages);
306 // FIXME: extend protocol to a displayMessages(MessageList)
307 for(int i = 0; i < messages.count(); i++) {
308 emit displayMsg(messages[i]);
311 _processMessages = false;
312 _messageQueue.clear();
315 QVariant CoreSession::sessionState() {
318 v["CoreFeatures"] = (int)Quassel::features();
321 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
322 v["BufferInfos"] = bufs;
323 QVariantList networkids;
324 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
325 v["NetworkIds"] = networkids;
327 quint32 ircusercount = 0;
328 quint32 ircchannelcount = 0;
329 foreach(Network *net, _networks.values()) {
330 ircusercount += net->ircUserCount();
331 ircchannelcount += net->ircChannelCount();
333 v["IrcUserCount"] = ircusercount;
334 v["IrcChannelCount"] = ircchannelcount;
336 QList<QVariant> idlist;
337 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
338 v["Identities"] = idlist;
340 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
344 void CoreSession::initScriptEngine() {
345 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
346 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
349 //QScriptValue storage_ = scriptEngine->newQObject(storage);
350 //scriptEngine->globalObject().setProperty("storage", storage_);
353 void CoreSession::scriptRequest(QString script) {
354 emit scriptResult(scriptEngine->evaluate(script).toString());
357 /*** Identity Handling ***/
358 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
363 CoreIdentity coreIdentity(identity);
365 if(additional.contains("KeyPem"))
366 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
367 if(additional.contains("CertPem"))
368 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
370 qDebug() << Q_FUNC_INFO;
371 IdentityId id = Core::createIdentity(user(), coreIdentity);
375 createIdentity(coreIdentity);
378 void CoreSession::createIdentity(const CoreIdentity &identity) {
379 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
380 _identities[identity.id()] = coreIdentity;
381 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
382 coreIdentity->synchronize(signalProxy());
383 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
384 emit identityCreated(*coreIdentity);
387 void CoreSession::updateIdentityBySender() {
388 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
391 Core::updateIdentity(user(), *identity);
394 void CoreSession::removeIdentity(IdentityId id) {
395 CoreIdentity *identity = _identities.take(id);
397 emit identityRemoved(id);
398 Core::removeIdentity(user(), id);
399 identity->deleteLater();
403 /*** Network Handling ***/
405 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
406 NetworkInfo info = info_;
409 if(!info.networkId.isValid())
410 Core::createNetwork(user(), info);
412 if(!info.networkId.isValid()) {
413 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
417 id = info.networkId.toInt();
418 if(!_networks.contains(id)) {
420 // create persistent chans
421 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
422 foreach(QString channel, persistentChans) {
423 if(!rx.exactMatch(channel)) {
424 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
427 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
428 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
429 if(!rx.cap(2).isEmpty())
430 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
433 CoreNetwork *net = new CoreNetwork(id, this);
434 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
435 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
436 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
438 net->setNetworkInfo(info);
439 net->setProxy(signalProxy());
441 signalProxy()->synchronize(net);
442 emit networkCreated(id);
444 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
445 _networks[info.networkId]->requestSetNetworkInfo(info);
449 void CoreSession::removeNetwork(NetworkId id) {
450 // Make sure the network is disconnected!
451 CoreNetwork *net = network(id);
455 if(net->connectionState() != Network::Disconnected) {
456 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
457 net->disconnectFromIrc();
463 void CoreSession::destroyNetwork(NetworkId id) {
464 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
465 Network *net = _networks.take(id);
466 if(net && Core::removeNetwork(user(), id)) {
467 foreach(BufferId bufferId, removedBuffers) {
468 _bufferSyncer->removeBuffer(bufferId);
470 emit networkRemoved(id);
475 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
476 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
477 if(bufferInfo.isValid()) {
478 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
482 void CoreSession::clientsConnected() {
483 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
484 Identity *identity = 0;
485 CoreNetwork *net = 0;
487 while(netIter != _networks.end()) {
491 if(!net->isConnected())
493 identity = net->identityPtr();
500 if(identity->detachAwayEnabled() && me->isAway()) {
501 net->userInputHandler()->handleAway(BufferInfo(), QString());
506 void CoreSession::clientsDisconnected() {
507 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
508 Identity *identity = 0;
509 CoreNetwork *net = 0;
512 while(netIter != _networks.end()) {
516 if(!net->isConnected())
519 identity = net->identityPtr();
526 if(identity->detachAwayEnabled() && !me->isAway()) {
527 if(!identity->detachAwayReason().isEmpty())
528 awayReason = identity->detachAwayReason();
529 net->setAutoAwayActive(true);
530 net->userInputHandler()->handleAway(BufferInfo(), awayReason);
536 void CoreSession::globalAway(const QString &msg) {
537 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
538 CoreNetwork *net = 0;
539 while(netIter != _networks.end()) {
543 if(!net->isConnected())
546 net->userInputHandler()->issueAway(msg, false /* no force away */);