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 "userinputhandler.h"
26 #include "signalproxy.h"
27 #include "corebuffersyncer.h"
28 #include "corebacklogmanager.h"
29 #include "corebufferviewmanager.h"
30 #include "coreirclisthelper.h"
33 #include "coreidentity.h"
34 #include "corenetwork.h"
36 #include "ircchannel.h"
39 #include "coreusersettings.h"
42 class ProcessMessagesEvent : public QEvent {
44 ProcessMessagesEvent() : QEvent(QEvent::User) {}
47 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
50 _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
52 _bufferSyncer(new CoreBufferSyncer(this)),
53 _backlogManager(new CoreBacklogManager(this)),
54 _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
55 _ircListHelper(new CoreIrcListHelper(this)),
57 scriptEngine(new QScriptEngine(this)),
58 _processMessages(false)
60 SignalProxy *p = signalProxy();
61 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
63 connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
64 connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
66 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
67 p->attachSignal(this, SIGNAL(displayMsg(Message)));
68 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
70 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
71 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
72 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
73 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
75 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
76 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
77 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
78 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
83 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferSyncer, SLOT(storeDirtyIds()));
84 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferViewManager, SLOT(saveBufferViews()));
86 p->synchronize(_bufferSyncer);
87 p->synchronize(&aliasManager());
88 p->synchronize(_backlogManager);
89 p->synchronize(ircListHelper());
90 p->synchronize(&_coreInfo);
92 // Restore session state
94 restoreSessionState();
99 CoreSession::~CoreSession() {
101 foreach(CoreNetwork *net, _networks.values()) {
106 CoreNetwork *CoreSession::network(NetworkId id) const {
107 if(_networks.contains(id)) return _networks[id];
111 CoreIdentity *CoreSession::identity(IdentityId id) const {
112 if(_identities.contains(id)) return _identities[id];
116 void CoreSession::loadSettings() {
117 CoreUserSettings s(user());
120 QList<IdentityId> ids = s.identityIds();
121 QList<NetworkInfo> networkInfos = Core::networks(user());
122 foreach(IdentityId id, ids) {
123 CoreIdentity identity(s.identity(id));
124 IdentityId newId = Core::createIdentity(user(), identity);
125 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
126 while(networkIter != networkInfos.end()) {
127 if(networkIter->identity == id) {
128 networkIter->identity = newId;
129 Core::updateNetwork(user(), *networkIter);
130 networkIter = networkInfos.erase(networkIter);
135 s.removeIdentity(id);
139 foreach(CoreIdentity identity, Core::identities(user())) {
140 createIdentity(identity);
143 foreach(NetworkInfo info, Core::networks(user())) {
148 void CoreSession::saveSessionState() const {
149 _bufferSyncer->storeDirtyIds();
150 _bufferViewManager->saveBufferViews();
153 void CoreSession::restoreSessionState() {
154 QList<NetworkId> nets = Core::connectedNetworks(user());
155 CoreNetwork *net = 0;
156 foreach(NetworkId id, nets) {
163 void CoreSession::addClient(QIODevice *device) {
165 qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
167 // if the socket is an orphan, the signalProxy adopts it.
168 // -> we don't need to care about it anymore
169 device->setParent(0);
170 signalProxy()->addPeer(device);
172 reply["MsgType"] = "SessionInit";
173 reply["SessionState"] = sessionState();
174 SignalProxy::writeDataToDevice(device, reply);
178 void CoreSession::addClient(SignalProxy *proxy) {
179 signalProxy()->addPeer(proxy);
180 emit sessionState(sessionState());
183 void CoreSession::removeClient(QIODevice *iodev) {
184 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
186 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
189 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
190 return Core::persistentChannels(user(), id);
193 // FIXME switch to BufferId
194 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
195 CoreNetwork *net = network(bufinfo.networkId());
197 net->userInput(bufinfo, msg);
199 qWarning() << "Trying to send to unconnected network:" << msg;
203 // ALL messages coming pass through these functions before going to the GUI.
204 // So this is the perfect place for storing the backlog and log stuff.
205 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
206 const QString &target, const QString &text_, const QString &sender, Message::Flags flags) {
208 // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
209 // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
210 // KDE's notifications), hence we remove those just to be safe.
211 QString text = text_;
212 text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
214 _messageQueue << RawMessage(networkId, type, bufferType, target, text, sender, flags);
215 if(!_processMessages) {
216 _processMessages = true;
217 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
221 void CoreSession::recvStatusMsgFromServer(QString msg) {
222 CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
224 emit displayStatusMsg(net->networkName(), msg);
227 QList<BufferInfo> CoreSession::buffers() const {
228 return Core::requestBuffers(user());
231 void CoreSession::customEvent(QEvent *event) {
232 if(event->type() != QEvent::User)
239 void CoreSession::processMessages() {
240 if(_messageQueue.count() == 1) {
241 const RawMessage &rawMsg = _messageQueue.first();
242 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
243 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
244 Core::storeMessage(msg);
245 emit displayMsg(msg);
247 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
248 MessageList messages;
249 BufferInfo bufferInfo;
250 for(int i = 0; i < _messageQueue.count(); i++) {
251 const RawMessage &rawMsg = _messageQueue.at(i);
252 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
253 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
255 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
256 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
258 messages << Message(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
260 Core::storeMessages(messages);
261 // FIXME: extend protocol to a displayMessages(MessageList)
262 for(int i = 0; i < messages.count(); i++) {
263 emit displayMsg(messages[i]);
266 _processMessages = false;
267 _messageQueue.clear();
270 QVariant CoreSession::sessionState() {
274 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
275 v["BufferInfos"] = bufs;
276 QVariantList networkids;
277 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
278 v["NetworkIds"] = networkids;
280 quint32 ircusercount = 0;
281 quint32 ircchannelcount = 0;
282 foreach(Network *net, _networks.values()) {
283 ircusercount += net->ircUserCount();
284 ircchannelcount += net->ircChannelCount();
286 v["IrcUserCount"] = ircusercount;
287 v["IrcChannelCount"] = ircchannelcount;
289 QList<QVariant> idlist;
290 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
291 v["Identities"] = idlist;
293 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
297 void CoreSession::initScriptEngine() {
298 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
299 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
302 //QScriptValue storage_ = scriptEngine->newQObject(storage);
303 //scriptEngine->globalObject().setProperty("storage", storage_);
306 void CoreSession::scriptRequest(QString script) {
307 emit scriptResult(scriptEngine->evaluate(script).toString());
310 /*** Identity Handling ***/
311 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
316 CoreIdentity coreIdentity(identity);
318 if(additional.contains("KeyPem"))
319 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
320 if(additional.contains("CertPem"))
321 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
323 qDebug() << Q_FUNC_INFO;
324 IdentityId id = Core::createIdentity(user(), coreIdentity);
328 createIdentity(coreIdentity);
331 void CoreSession::createIdentity(const CoreIdentity &identity) {
332 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
333 _identities[identity.id()] = coreIdentity;
334 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
335 coreIdentity->synchronize(signalProxy());
336 connect(coreIdentity, SIGNAL(updated(const QVariantMap &)), this, SLOT(updateIdentityBySender()));
337 emit identityCreated(*coreIdentity);
340 void CoreSession::updateIdentityBySender() {
341 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
344 Core::updateIdentity(user(), *identity);
347 void CoreSession::removeIdentity(IdentityId id) {
348 CoreIdentity *identity = _identities.take(id);
350 emit identityRemoved(id);
351 Core::removeIdentity(user(), id);
352 identity->deleteLater();
356 /*** Network Handling ***/
358 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
359 NetworkInfo info = info_;
362 if(!info.networkId.isValid())
363 Core::createNetwork(user(), info);
365 if(!info.networkId.isValid()) {
366 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
370 id = info.networkId.toInt();
371 if(!_networks.contains(id)) {
373 // create persistent chans
374 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
375 foreach(QString channel, persistentChans) {
376 if(!rx.exactMatch(channel)) {
377 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
380 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
381 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
382 if(!rx.cap(2).isEmpty())
383 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
386 CoreNetwork *net = new CoreNetwork(id, this);
387 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
388 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
389 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
391 net->setNetworkInfo(info);
392 net->setProxy(signalProxy());
394 signalProxy()->synchronize(net);
395 emit networkCreated(id);
397 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
398 _networks[info.networkId]->requestSetNetworkInfo(info);
402 void CoreSession::removeNetwork(NetworkId id) {
403 // Make sure the network is disconnected!
404 CoreNetwork *net = network(id);
408 if(net->connectionState() != Network::Disconnected) {
409 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
410 net->disconnectFromIrc();
416 void CoreSession::destroyNetwork(NetworkId id) {
417 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
418 Network *net = _networks.take(id);
419 if(net && Core::removeNetwork(user(), id)) {
420 foreach(BufferId bufferId, removedBuffers) {
421 _bufferSyncer->removeBuffer(bufferId);
423 emit networkRemoved(id);
428 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
429 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
430 if(bufferInfo.isValid()) {
431 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
435 void CoreSession::clientsConnected() {
436 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
437 Identity *identity = 0;
438 CoreNetwork *net = 0;
440 while(netIter != _networks.end()) {
444 if(!net->isConnected())
446 identity = net->identityPtr();
453 if(identity->detachAwayEnabled() && me->isAway()) {
454 net->userInputHandler()->handleAway(BufferInfo(), QString());
459 void CoreSession::clientsDisconnected() {
460 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
461 Identity *identity = 0;
462 CoreNetwork *net = 0;
465 while(netIter != _networks.end()) {
469 if(!net->isConnected())
471 identity = net->identityPtr();
478 if(identity->detachAwayEnabled() && !me->isAway()) {
479 if(!identity->detachAwayReason().isEmpty())
480 awayReason = identity->detachAwayReason();
481 net->setAutoAwayActive(true);
482 net->userInputHandler()->handleAway(BufferInfo(), awayReason);