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));
223 _messageQueue << RawMessage(networkId, type, bufferType, target, text, sender, flags);
224 if(!_processMessages) {
225 _processMessages = true;
226 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
230 void CoreSession::recvStatusMsgFromServer(QString msg) {
231 CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
233 emit displayStatusMsg(net->networkName(), msg);
236 QList<BufferInfo> CoreSession::buffers() const {
237 return Core::requestBuffers(user());
240 void CoreSession::customEvent(QEvent *event) {
241 if(event->type() != QEvent::User)
248 void CoreSession::processMessages() {
250 if(_messageQueue.count() == 1) {
251 const RawMessage &rawMsg = _messageQueue.first();
252 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
253 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
255 CoreNetwork *currentNetwork = network(bufferInfo.networkId());
256 networkName = currentNetwork ? currentNetwork->networkName() : QString("");
257 // if message is ignored with "HardStrictness" we discard it here
258 if(_ignoreListManager.match(msg, networkName) != IgnoreListManager::HardStrictness) {
259 Core::storeMessage(msg);
260 emit displayMsg(msg);
263 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
264 MessageList messages;
265 BufferInfo bufferInfo;
266 for(int i = 0; i < _messageQueue.count(); i++) {
267 const RawMessage &rawMsg = _messageQueue.at(i);
268 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
269 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
271 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
272 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
275 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
276 CoreNetwork *currentNetwork = network(bufferInfo.networkId());
277 networkName = currentNetwork ? currentNetwork->networkName() : QString("");
278 // if message is ignored with "HardStrictness" we discard it here
279 if(_ignoreListManager.match(msg, networkName) == IgnoreListManager::HardStrictness)
283 Core::storeMessages(messages);
284 // FIXME: extend protocol to a displayMessages(MessageList)
285 for(int i = 0; i < messages.count(); i++) {
286 emit displayMsg(messages[i]);
289 _processMessages = false;
290 _messageQueue.clear();
293 QVariant CoreSession::sessionState() {
296 v["CoreFeatures"] = (int)Quassel::features();
299 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
300 v["BufferInfos"] = bufs;
301 QVariantList networkids;
302 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
303 v["NetworkIds"] = networkids;
305 quint32 ircusercount = 0;
306 quint32 ircchannelcount = 0;
307 foreach(Network *net, _networks.values()) {
308 ircusercount += net->ircUserCount();
309 ircchannelcount += net->ircChannelCount();
311 v["IrcUserCount"] = ircusercount;
312 v["IrcChannelCount"] = ircchannelcount;
314 QList<QVariant> idlist;
315 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
316 v["Identities"] = idlist;
318 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
322 void CoreSession::initScriptEngine() {
323 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
324 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
327 //QScriptValue storage_ = scriptEngine->newQObject(storage);
328 //scriptEngine->globalObject().setProperty("storage", storage_);
331 void CoreSession::scriptRequest(QString script) {
332 emit scriptResult(scriptEngine->evaluate(script).toString());
335 /*** Identity Handling ***/
336 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
341 CoreIdentity coreIdentity(identity);
343 if(additional.contains("KeyPem"))
344 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
345 if(additional.contains("CertPem"))
346 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
348 qDebug() << Q_FUNC_INFO;
349 IdentityId id = Core::createIdentity(user(), coreIdentity);
353 createIdentity(coreIdentity);
356 void CoreSession::createIdentity(const CoreIdentity &identity) {
357 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
358 _identities[identity.id()] = coreIdentity;
359 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
360 coreIdentity->synchronize(signalProxy());
361 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
362 emit identityCreated(*coreIdentity);
365 void CoreSession::updateIdentityBySender() {
366 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
369 Core::updateIdentity(user(), *identity);
372 void CoreSession::removeIdentity(IdentityId id) {
373 CoreIdentity *identity = _identities.take(id);
375 emit identityRemoved(id);
376 Core::removeIdentity(user(), id);
377 identity->deleteLater();
381 /*** Network Handling ***/
383 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
384 NetworkInfo info = info_;
387 if(!info.networkId.isValid())
388 Core::createNetwork(user(), info);
390 if(!info.networkId.isValid()) {
391 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
395 id = info.networkId.toInt();
396 if(!_networks.contains(id)) {
398 // create persistent chans
399 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
400 foreach(QString channel, persistentChans) {
401 if(!rx.exactMatch(channel)) {
402 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
405 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
406 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
407 if(!rx.cap(2).isEmpty())
408 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
411 CoreNetwork *net = new CoreNetwork(id, this);
412 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
413 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
414 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
416 net->setNetworkInfo(info);
417 net->setProxy(signalProxy());
419 signalProxy()->synchronize(net);
420 emit networkCreated(id);
422 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
423 _networks[info.networkId]->requestSetNetworkInfo(info);
427 void CoreSession::removeNetwork(NetworkId id) {
428 // Make sure the network is disconnected!
429 CoreNetwork *net = network(id);
433 if(net->connectionState() != Network::Disconnected) {
434 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
435 net->disconnectFromIrc();
441 void CoreSession::destroyNetwork(NetworkId id) {
442 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
443 Network *net = _networks.take(id);
444 if(net && Core::removeNetwork(user(), id)) {
445 foreach(BufferId bufferId, removedBuffers) {
446 _bufferSyncer->removeBuffer(bufferId);
448 emit networkRemoved(id);
453 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
454 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
455 if(bufferInfo.isValid()) {
456 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
460 void CoreSession::clientsConnected() {
461 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
462 Identity *identity = 0;
463 CoreNetwork *net = 0;
465 while(netIter != _networks.end()) {
469 if(!net->isConnected())
471 identity = net->identityPtr();
478 if(identity->detachAwayEnabled() && me->isAway()) {
479 net->userInputHandler()->handleAway(BufferInfo(), QString());
484 void CoreSession::clientsDisconnected() {
485 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
486 Identity *identity = 0;
487 CoreNetwork *net = 0;
490 while(netIter != _networks.end()) {
494 if(!net->isConnected())
496 identity = net->identityPtr();
503 if(identity->detachAwayEnabled() && !me->isAway()) {
504 if(!identity->detachAwayReason().isEmpty())
505 awayReason = identity->detachAwayReason();
506 net->setAutoAwayActive(true);
507 net->userInputHandler()->handleAway(BufferInfo(), awayReason);