1 /***************************************************************************
2 * Copyright (C) 2005-08 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 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
45 _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
47 _bufferSyncer(new CoreBufferSyncer(this)),
48 _backlogManager(new CoreBacklogManager(this)),
49 _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
50 _ircListHelper(new CoreIrcListHelper(this)),
52 scriptEngine(new QScriptEngine(this))
55 SignalProxy *p = signalProxy();
56 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
58 connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
59 connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
61 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
62 p->attachSignal(this, SIGNAL(displayMsg(Message)));
63 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
65 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
66 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
67 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
68 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
70 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
71 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
72 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
73 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
79 QHash<BufferId, MsgId> lastSeenHash = Core::bufferLastSeenMsgIds(user());
80 foreach(BufferId id, lastSeenHash.keys())
81 _bufferSyncer->requestSetLastSeenMsg(id, lastSeenHash[id]);
83 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferSyncer, SLOT(storeDirtyIds()));
84 p->synchronize(_bufferSyncer);
88 p->synchronize(&aliasManager());
90 // init BacklogManager
91 p->synchronize(_backlogManager);
92 p->dumpSyncMap(_backlogManager);
95 p->synchronize(ircListHelper());
98 p->synchronize(&_coreInfo);
100 // Restore session state
101 if(restoreState) restoreSessionState();
106 CoreSession::~CoreSession() {
108 foreach(CoreNetwork *net, _networks.values()) {
113 CoreNetwork *CoreSession::network(NetworkId id) const {
114 if(_networks.contains(id)) return _networks[id];
118 CoreIdentity *CoreSession::identity(IdentityId id) const {
119 if(_identities.contains(id)) return _identities[id];
123 void CoreSession::loadSettings() {
124 CoreUserSettings s(user());
127 QList<IdentityId> ids = s.identityIds();
128 QList<NetworkInfo> networkInfos = Core::networks(user());
129 foreach(IdentityId id, ids) {
130 CoreIdentity identity(s.identity(id));
131 IdentityId newId = Core::createIdentity(user(), identity);
132 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
133 while(networkIter != networkInfos.end()) {
134 if(networkIter->identity == id) {
135 networkIter->identity = newId;
136 Core::updateNetwork(user(), *networkIter);
137 networkIter = networkInfos.erase(networkIter);
142 s.removeIdentity(id);
146 foreach(CoreIdentity identity, Core::identities(user())) {
147 createIdentity(identity);
149 if(!_identities.count()) {
151 identity.setToDefaults();
152 identity.setIdentityName(tr("Default Identity"));
153 createIdentity(identity, QVariantMap());
156 foreach(NetworkInfo info, Core::networks(user())) {
161 void CoreSession::saveSessionState() const {
162 _bufferSyncer->storeDirtyIds();
165 void CoreSession::restoreSessionState() {
166 QList<NetworkId> nets = Core::connectedNetworks(user());
167 CoreNetwork *net = 0;
168 foreach(NetworkId id, nets) {
175 void CoreSession::addClient(QIODevice *device) {
177 qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
179 // if the socket is an orphan, the signalProxy adopts it.
180 // -> we don't need to care about it anymore
181 device->setParent(0);
182 signalProxy()->addPeer(device);
184 reply["MsgType"] = "SessionInit";
185 reply["SessionState"] = sessionState();
186 SignalProxy::writeDataToDevice(device, reply);
190 void CoreSession::addClient(SignalProxy *proxy) {
191 signalProxy()->addPeer(proxy);
192 emit sessionState(sessionState());
195 void CoreSession::removeClient(QIODevice *iodev) {
196 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
198 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
201 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
202 return Core::persistentChannels(user(), id);
203 return QHash<QString, QString>();
206 // FIXME switch to BufferId
207 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
208 CoreNetwork *net = network(bufinfo.networkId());
210 net->userInput(bufinfo, msg);
212 qWarning() << "Trying to send to unconnected network:" << msg;
216 // ALL messages coming pass through these functions before going to the GUI.
217 // So this is the perfect place for storing the backlog and log stuff.
218 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType,
219 QString target, QString text, QString sender, Message::Flags flags) {
220 CoreNetwork *net = qobject_cast<CoreNetwork*>(this->sender());
223 BufferInfo bufferInfo = Core::bufferInfo(user(), net->networkId(), bufferType, target);
224 Message msg(bufferInfo, type, text, sender, flags);
225 msg.setMsgId(Core::storeMessage(msg));
226 Q_ASSERT(msg.msgId() != 0);
227 emit displayMsg(msg);
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());
241 QVariant CoreSession::sessionState() {
245 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
246 v["BufferInfos"] = bufs;
247 QVariantList networkids;
248 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
249 v["NetworkIds"] = networkids;
251 quint32 ircusercount = 0;
252 quint32 ircchannelcount = 0;
253 foreach(Network *net, _networks.values()) {
254 ircusercount += net->ircUserCount();
255 ircchannelcount += net->ircChannelCount();
257 v["IrcUserCount"] = ircusercount;
258 v["IrcChannelCount"] = ircchannelcount;
260 QList<QVariant> idlist;
261 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
262 v["Identities"] = idlist;
264 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
268 void CoreSession::initScriptEngine() {
269 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
270 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
273 //QScriptValue storage_ = scriptEngine->newQObject(storage);
274 //scriptEngine->globalObject().setProperty("storage", storage_);
277 void CoreSession::scriptRequest(QString script) {
278 emit scriptResult(scriptEngine->evaluate(script).toString());
281 /*** Identity Handling ***/
282 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
287 CoreIdentity coreIdentity(identity);
289 if(additional.contains("KeyPem"))
290 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
291 if(additional.contains("CertPem"))
292 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
294 IdentityId id = Core::createIdentity(user(), coreIdentity);
298 createIdentity(coreIdentity);
301 void CoreSession::createIdentity(const CoreIdentity &identity) {
302 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
303 _identities[identity.id()] = coreIdentity;
304 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
305 coreIdentity->synchronize(signalProxy());
306 connect(coreIdentity, SIGNAL(updated(const QVariantMap &)), this, SLOT(updateIdentityBySender()));
307 emit identityCreated(*coreIdentity);
310 void CoreSession::updateIdentityBySender() {
311 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
314 Core::updateIdentity(user(), *identity);
317 void CoreSession::removeIdentity(IdentityId id) {
318 CoreIdentity *identity = _identities.take(id);
320 emit identityRemoved(id);
321 Core::removeIdentity(user(), id);
322 identity->deleteLater();
326 /*** Network Handling ***/
328 void CoreSession::createNetwork(const NetworkInfo &info_) {
329 NetworkInfo info = info_;
332 if(!info.networkId.isValid())
333 Core::createNetwork(user(), info);
335 if(!info.networkId.isValid()) {
336 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
340 id = info.networkId.toInt();
341 if(!_networks.contains(id)) {
342 CoreNetwork *net = new CoreNetwork(id, this);
343 connect(net, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)),
344 this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)));
345 connect(net, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
347 net->setNetworkInfo(info);
348 net->setProxy(signalProxy());
350 signalProxy()->synchronize(net);
351 emit networkCreated(id);
353 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
354 _networks[info.networkId]->requestSetNetworkInfo(info);
358 void CoreSession::removeNetwork(NetworkId id) {
359 // Make sure the network is disconnected!
360 CoreNetwork *net = network(id);
364 if(net->connectionState() != Network::Disconnected) {
365 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
366 net->disconnectFromIrc();
372 void CoreSession::destroyNetwork(NetworkId id) {
373 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
374 Network *net = _networks.take(id);
375 if(net && Core::removeNetwork(user(), id)) {
376 foreach(BufferId bufferId, removedBuffers) {
377 _bufferSyncer->removeBuffer(bufferId);
379 emit networkRemoved(id);
384 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
385 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
386 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
389 void CoreSession::clientsConnected() {
390 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
391 Identity *identity = 0;
392 CoreNetwork *net = 0;
395 while(netIter != _networks.end()) {
399 if(!net->isConnected())
401 identity = net->identityPtr();
408 if(identity->detachAwayEnabled() && me->isAway()) {
409 net->userInputHandler()->handleAway(BufferInfo(), QString());
414 void CoreSession::clientsDisconnected() {
415 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
416 Identity *identity = 0;
417 CoreNetwork *net = 0;
420 while(netIter != _networks.end()) {
424 if(!net->isConnected())
426 identity = net->identityPtr();
433 if(identity->detachAwayEnabled() && !me->isAway()) {
434 if(identity->detachAwayReasonEnabled())
435 awayReason = identity->detachAwayReason();
437 awayReason = identity->awayReason();
438 net->setAutoAwayActive(true);
439 net->userInputHandler()->handleAway(BufferInfo(), awayReason);