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 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
67 connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
68 connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
70 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
71 p->attachSignal(this, SIGNAL(displayMsg(Message)));
72 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
74 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
75 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
76 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
77 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
79 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
80 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
81 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
82 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
87 // periodically save our session state
88 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
90 p->synchronize(_bufferSyncer);
91 p->synchronize(&aliasManager());
92 p->synchronize(_backlogManager);
93 p->synchronize(ircListHelper());
94 p->synchronize(networkConfig());
95 p->synchronize(&_coreInfo);
96 p->synchronize(&_ignoreListManager);
97 // Restore session state
99 restoreSessionState();
104 CoreSession::~CoreSession() {
106 foreach(CoreNetwork *net, _networks.values()) {
111 CoreNetwork *CoreSession::network(NetworkId id) const {
112 if(_networks.contains(id)) return _networks[id];
116 CoreIdentity *CoreSession::identity(IdentityId id) const {
117 if(_identities.contains(id)) return _identities[id];
121 void CoreSession::loadSettings() {
122 CoreUserSettings s(user());
125 QList<IdentityId> ids = s.identityIds();
126 QList<NetworkInfo> networkInfos = Core::networks(user());
127 foreach(IdentityId id, ids) {
128 CoreIdentity identity(s.identity(id));
129 IdentityId newId = Core::createIdentity(user(), identity);
130 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
131 while(networkIter != networkInfos.end()) {
132 if(networkIter->identity == id) {
133 networkIter->identity = newId;
134 Core::updateNetwork(user(), *networkIter);
135 networkIter = networkInfos.erase(networkIter);
140 s.removeIdentity(id);
144 foreach(CoreIdentity identity, Core::identities(user())) {
145 createIdentity(identity);
148 foreach(NetworkInfo info, Core::networks(user())) {
153 void CoreSession::saveSessionState() const {
154 _bufferSyncer->storeDirtyIds();
155 _bufferViewManager->saveBufferViews();
156 _networkConfig->save();
159 void CoreSession::restoreSessionState() {
160 QList<NetworkId> nets = Core::connectedNetworks(user());
161 CoreNetwork *net = 0;
162 foreach(NetworkId id, nets) {
169 void CoreSession::addClient(QIODevice *device) {
171 qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
173 // if the socket is an orphan, the signalProxy adopts it.
174 // -> we don't need to care about it anymore
175 device->setParent(0);
176 signalProxy()->addPeer(device);
178 reply["MsgType"] = "SessionInit";
179 reply["SessionState"] = sessionState();
180 SignalProxy::writeDataToDevice(device, reply);
184 void CoreSession::addClient(SignalProxy *proxy) {
185 signalProxy()->addPeer(proxy);
186 emit sessionState(sessionState());
189 void CoreSession::removeClient(QIODevice *iodev) {
190 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
192 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
195 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
196 return Core::persistentChannels(user(), id);
199 // FIXME switch to BufferId
200 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
201 CoreNetwork *net = network(bufinfo.networkId());
203 net->userInput(bufinfo, msg);
205 qWarning() << "Trying to send to unconnected network:" << msg;
209 // ALL messages coming pass through these functions before going to the GUI.
210 // So this is the perfect place for storing the backlog and log stuff.
211 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
212 const QString &target, const QString &text_, const QString &sender, Message::Flags flags) {
214 // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
215 // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
216 // KDE's notifications), hence we remove those just to be safe.
217 QString text = text_;
218 text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
220 _messageQueue << RawMessage(networkId, type, bufferType, target, text, sender, flags);
221 if(!_processMessages) {
222 _processMessages = true;
223 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
227 void CoreSession::recvStatusMsgFromServer(QString msg) {
228 CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
230 emit displayStatusMsg(net->networkName(), msg);
233 QList<BufferInfo> CoreSession::buffers() const {
234 return Core::requestBuffers(user());
237 void CoreSession::customEvent(QEvent *event) {
238 if(event->type() != QEvent::User)
245 void CoreSession::processMessages() {
247 if(_messageQueue.count() == 1) {
248 const RawMessage &rawMsg = _messageQueue.first();
249 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
250 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
252 CoreNetwork *currentNetwork = network(bufferInfo.networkId());
253 networkName = currentNetwork ? currentNetwork->networkName() : QString("");
254 // if message is ignored with "HardStrictness" we discard it here
255 if(_ignoreListManager.match(msg, networkName) != IgnoreListManager::HardStrictness) {
256 Core::storeMessage(msg);
257 emit displayMsg(msg);
260 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
261 MessageList messages;
262 BufferInfo bufferInfo;
263 for(int i = 0; i < _messageQueue.count(); i++) {
264 const RawMessage &rawMsg = _messageQueue.at(i);
265 if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
266 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
268 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
269 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
272 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
273 CoreNetwork *currentNetwork = network(bufferInfo.networkId());
274 networkName = currentNetwork ? currentNetwork->networkName() : QString("");
275 // if message is ignored with "HardStrictness" we discard it here
276 if(_ignoreListManager.match(msg, networkName) == IgnoreListManager::HardStrictness)
280 Core::storeMessages(messages);
281 // FIXME: extend protocol to a displayMessages(MessageList)
282 for(int i = 0; i < messages.count(); i++) {
283 emit displayMsg(messages[i]);
286 _processMessages = false;
287 _messageQueue.clear();
290 QVariant CoreSession::sessionState() {
294 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
295 v["BufferInfos"] = bufs;
296 QVariantList networkids;
297 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
298 v["NetworkIds"] = networkids;
300 quint32 ircusercount = 0;
301 quint32 ircchannelcount = 0;
302 foreach(Network *net, _networks.values()) {
303 ircusercount += net->ircUserCount();
304 ircchannelcount += net->ircChannelCount();
306 v["IrcUserCount"] = ircusercount;
307 v["IrcChannelCount"] = ircchannelcount;
309 QList<QVariant> idlist;
310 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
311 v["Identities"] = idlist;
313 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
317 void CoreSession::initScriptEngine() {
318 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
319 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
322 //QScriptValue storage_ = scriptEngine->newQObject(storage);
323 //scriptEngine->globalObject().setProperty("storage", storage_);
326 void CoreSession::scriptRequest(QString script) {
327 emit scriptResult(scriptEngine->evaluate(script).toString());
330 /*** Identity Handling ***/
331 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
336 CoreIdentity coreIdentity(identity);
338 if(additional.contains("KeyPem"))
339 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
340 if(additional.contains("CertPem"))
341 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
343 qDebug() << Q_FUNC_INFO;
344 IdentityId id = Core::createIdentity(user(), coreIdentity);
348 createIdentity(coreIdentity);
351 void CoreSession::createIdentity(const CoreIdentity &identity) {
352 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
353 _identities[identity.id()] = coreIdentity;
354 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
355 coreIdentity->synchronize(signalProxy());
356 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
357 emit identityCreated(*coreIdentity);
360 void CoreSession::updateIdentityBySender() {
361 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
364 Core::updateIdentity(user(), *identity);
367 void CoreSession::removeIdentity(IdentityId id) {
368 CoreIdentity *identity = _identities.take(id);
370 emit identityRemoved(id);
371 Core::removeIdentity(user(), id);
372 identity->deleteLater();
376 /*** Network Handling ***/
378 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
379 NetworkInfo info = info_;
382 if(!info.networkId.isValid())
383 Core::createNetwork(user(), info);
385 if(!info.networkId.isValid()) {
386 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
390 id = info.networkId.toInt();
391 if(!_networks.contains(id)) {
393 // create persistent chans
394 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
395 foreach(QString channel, persistentChans) {
396 if(!rx.exactMatch(channel)) {
397 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
400 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
401 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
402 if(!rx.cap(2).isEmpty())
403 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
406 CoreNetwork *net = new CoreNetwork(id, this);
407 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
408 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
409 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
411 net->setNetworkInfo(info);
412 net->setProxy(signalProxy());
414 signalProxy()->synchronize(net);
415 emit networkCreated(id);
417 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
418 _networks[info.networkId]->requestSetNetworkInfo(info);
422 void CoreSession::removeNetwork(NetworkId id) {
423 // Make sure the network is disconnected!
424 CoreNetwork *net = network(id);
428 if(net->connectionState() != Network::Disconnected) {
429 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
430 net->disconnectFromIrc();
436 void CoreSession::destroyNetwork(NetworkId id) {
437 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
438 Network *net = _networks.take(id);
439 if(net && Core::removeNetwork(user(), id)) {
440 foreach(BufferId bufferId, removedBuffers) {
441 _bufferSyncer->removeBuffer(bufferId);
443 emit networkRemoved(id);
448 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
449 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
450 if(bufferInfo.isValid()) {
451 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
455 void CoreSession::clientsConnected() {
456 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
457 Identity *identity = 0;
458 CoreNetwork *net = 0;
460 while(netIter != _networks.end()) {
464 if(!net->isConnected())
466 identity = net->identityPtr();
473 if(identity->detachAwayEnabled() && me->isAway()) {
474 net->userInputHandler()->handleAway(BufferInfo(), QString());
479 void CoreSession::clientsDisconnected() {
480 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
481 Identity *identity = 0;
482 CoreNetwork *net = 0;
485 while(netIter != _networks.end()) {
489 if(!net->isConnected())
491 identity = net->identityPtr();
498 if(identity->detachAwayEnabled() && !me->isAway()) {
499 if(!identity->detachAwayReason().isEmpty())
500 awayReason = identity->detachAwayReason();
501 net->setAutoAwayActive(true);
502 net->userInputHandler()->handleAway(BufferInfo(), awayReason);