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 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))
54 SignalProxy *p = signalProxy();
55 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
57 connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
58 connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
60 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
61 p->attachSignal(this, SIGNAL(displayMsg(Message)));
62 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
64 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
65 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
66 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
67 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
69 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
70 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
71 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
72 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
77 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferSyncer, SLOT(storeDirtyIds()));
78 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferViewManager, SLOT(saveBufferViews()));
80 p->synchronize(_bufferSyncer);
81 p->synchronize(&aliasManager());
82 p->synchronize(_backlogManager);
83 p->synchronize(ircListHelper());
84 p->synchronize(&_coreInfo);
86 // Restore session state
88 restoreSessionState();
93 CoreSession::~CoreSession() {
95 foreach(CoreNetwork *net, _networks.values()) {
100 CoreNetwork *CoreSession::network(NetworkId id) const {
101 if(_networks.contains(id)) return _networks[id];
105 CoreIdentity *CoreSession::identity(IdentityId id) const {
106 if(_identities.contains(id)) return _identities[id];
110 void CoreSession::loadSettings() {
111 CoreUserSettings s(user());
114 QList<IdentityId> ids = s.identityIds();
115 QList<NetworkInfo> networkInfos = Core::networks(user());
116 foreach(IdentityId id, ids) {
117 CoreIdentity identity(s.identity(id));
118 IdentityId newId = Core::createIdentity(user(), identity);
119 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
120 while(networkIter != networkInfos.end()) {
121 if(networkIter->identity == id) {
122 networkIter->identity = newId;
123 Core::updateNetwork(user(), *networkIter);
124 networkIter = networkInfos.erase(networkIter);
129 s.removeIdentity(id);
133 foreach(CoreIdentity identity, Core::identities(user())) {
134 createIdentity(identity);
137 foreach(NetworkInfo info, Core::networks(user())) {
142 void CoreSession::saveSessionState() const {
143 _bufferSyncer->storeDirtyIds();
144 _bufferViewManager->saveBufferViews();
147 void CoreSession::restoreSessionState() {
148 QList<NetworkId> nets = Core::connectedNetworks(user());
149 CoreNetwork *net = 0;
150 foreach(NetworkId id, nets) {
157 void CoreSession::addClient(QIODevice *device) {
159 qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
161 // if the socket is an orphan, the signalProxy adopts it.
162 // -> we don't need to care about it anymore
163 device->setParent(0);
164 signalProxy()->addPeer(device);
166 reply["MsgType"] = "SessionInit";
167 reply["SessionState"] = sessionState();
168 SignalProxy::writeDataToDevice(device, reply);
172 void CoreSession::addClient(SignalProxy *proxy) {
173 signalProxy()->addPeer(proxy);
174 emit sessionState(sessionState());
177 void CoreSession::removeClient(QIODevice *iodev) {
178 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
180 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
183 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
184 return Core::persistentChannels(user(), id);
187 // FIXME switch to BufferId
188 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
189 CoreNetwork *net = network(bufinfo.networkId());
191 net->userInput(bufinfo, msg);
193 qWarning() << "Trying to send to unconnected network:" << msg;
197 // ALL messages coming pass through these functions before going to the GUI.
198 // So this is the perfect place for storing the backlog and log stuff.
199 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType,
200 QString target, QString text, QString sender, Message::Flags flags) {
201 CoreNetwork *net = qobject_cast<CoreNetwork*>(this->sender());
204 BufferInfo bufferInfo = Core::bufferInfo(user(), net->networkId(), bufferType, target);
205 Message msg(bufferInfo, type, text, sender, flags);
206 msg.setMsgId(Core::storeMessage(msg));
207 Q_ASSERT(msg.msgId() != 0);
208 emit displayMsg(msg);
211 void CoreSession::recvStatusMsgFromServer(QString msg) {
212 CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
214 emit displayStatusMsg(net->networkName(), msg);
217 QList<BufferInfo> CoreSession::buffers() const {
218 return Core::requestBuffers(user());
222 QVariant CoreSession::sessionState() {
226 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
227 v["BufferInfos"] = bufs;
228 QVariantList networkids;
229 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
230 v["NetworkIds"] = networkids;
232 quint32 ircusercount = 0;
233 quint32 ircchannelcount = 0;
234 foreach(Network *net, _networks.values()) {
235 ircusercount += net->ircUserCount();
236 ircchannelcount += net->ircChannelCount();
238 v["IrcUserCount"] = ircusercount;
239 v["IrcChannelCount"] = ircchannelcount;
241 QList<QVariant> idlist;
242 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
243 v["Identities"] = idlist;
245 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
249 void CoreSession::initScriptEngine() {
250 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
251 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
254 //QScriptValue storage_ = scriptEngine->newQObject(storage);
255 //scriptEngine->globalObject().setProperty("storage", storage_);
258 void CoreSession::scriptRequest(QString script) {
259 emit scriptResult(scriptEngine->evaluate(script).toString());
262 /*** Identity Handling ***/
263 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
268 CoreIdentity coreIdentity(identity);
270 if(additional.contains("KeyPem"))
271 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
272 if(additional.contains("CertPem"))
273 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
275 IdentityId id = Core::createIdentity(user(), coreIdentity);
279 createIdentity(coreIdentity);
282 void CoreSession::createIdentity(const CoreIdentity &identity) {
283 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
284 _identities[identity.id()] = coreIdentity;
285 // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
286 coreIdentity->synchronize(signalProxy());
287 connect(coreIdentity, SIGNAL(updated(const QVariantMap &)), this, SLOT(updateIdentityBySender()));
288 emit identityCreated(*coreIdentity);
291 void CoreSession::updateIdentityBySender() {
292 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
295 Core::updateIdentity(user(), *identity);
298 void CoreSession::removeIdentity(IdentityId id) {
299 CoreIdentity *identity = _identities.take(id);
301 emit identityRemoved(id);
302 Core::removeIdentity(user(), id);
303 identity->deleteLater();
307 /*** Network Handling ***/
309 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
310 NetworkInfo info = info_;
313 if(!info.networkId.isValid())
314 Core::createNetwork(user(), info);
316 if(!info.networkId.isValid()) {
317 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
321 id = info.networkId.toInt();
322 if(!_networks.contains(id)) {
323 CoreNetwork *net = new CoreNetwork(id, this);
324 connect(net, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)),
325 this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)));
326 connect(net, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
328 net->setNetworkInfo(info);
329 net->setProxy(signalProxy());
331 signalProxy()->synchronize(net);
332 emit networkCreated(id);
333 // create persistent chans
334 foreach(QString channel, persistentChans) {
335 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, channel, true);
336 Core::setChannelPersistent(user(), info.networkId, channel, true);
339 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
340 _networks[info.networkId]->requestSetNetworkInfo(info);
344 void CoreSession::removeNetwork(NetworkId id) {
345 // Make sure the network is disconnected!
346 CoreNetwork *net = network(id);
350 if(net->connectionState() != Network::Disconnected) {
351 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
352 net->disconnectFromIrc();
358 void CoreSession::destroyNetwork(NetworkId id) {
359 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
360 Network *net = _networks.take(id);
361 if(net && Core::removeNetwork(user(), id)) {
362 foreach(BufferId bufferId, removedBuffers) {
363 _bufferSyncer->removeBuffer(bufferId);
365 emit networkRemoved(id);
370 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
371 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
372 if(bufferInfo.isValid()) {
373 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
377 void CoreSession::clientsConnected() {
378 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
379 Identity *identity = 0;
380 CoreNetwork *net = 0;
383 while(netIter != _networks.end()) {
387 if(!net->isConnected())
389 identity = net->identityPtr();
396 if(identity->detachAwayEnabled() && me->isAway()) {
397 net->userInputHandler()->handleAway(BufferInfo(), QString());
402 void CoreSession::clientsDisconnected() {
403 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
404 Identity *identity = 0;
405 CoreNetwork *net = 0;
408 while(netIter != _networks.end()) {
412 if(!net->isConnected())
414 identity = net->identityPtr();
421 if(identity->detachAwayEnabled() && !me->isAway()) {
422 if(identity->detachAwayReasonEnabled())
423 awayReason = identity->detachAwayReason();
425 awayReason = identity->awayReason();
426 net->setAutoAwayActive(true);
427 net->userInputHandler()->handleAway(BufferInfo(), awayReason);