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 "buffersyncer.h"
28 #include "corebacklogmanager.h"
29 #include "corebufferviewmanager.h"
30 #include "coreirclisthelper.h"
33 #include "corenetwork.h"
35 #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 BufferSyncer(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 &)), this, SLOT(createIdentity(const Identity &)));
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(_bufferSyncer, SIGNAL(lastSeenMsgSet(BufferId, MsgId)), this, SLOT(storeBufferLastSeenMsg(BufferId, MsgId)));
84 connect(_bufferSyncer, SIGNAL(removeBufferRequested(BufferId)), this, SLOT(removeBufferRequested(BufferId)));
85 connect(this, SIGNAL(bufferRemoved(BufferId)), _bufferSyncer, SLOT(removeBuffer(BufferId)));
86 connect(this, SIGNAL(bufferRenamed(BufferId, QString)), _bufferSyncer, SLOT(renameBuffer(BufferId, QString)));
87 p->synchronize(_bufferSyncer);
91 p->synchronize(&aliasManager());
93 // init BacklogManager
94 p->synchronize(_backlogManager);
97 p->synchronize(ircListHelper());
100 p->synchronize(&_coreInfo);
102 // Restore session state
103 if(restoreState) restoreSessionState();
108 CoreSession::~CoreSession() {
110 foreach(CoreNetwork *net, _networks.values()) {
115 CoreNetwork *CoreSession::network(NetworkId id) const {
116 if(_networks.contains(id)) return _networks[id];
120 Identity *CoreSession::identity(IdentityId id) const {
121 if(_identities.contains(id)) return _identities[id];
125 void CoreSession::loadSettings() {
126 CoreUserSettings s(user());
128 foreach(IdentityId id, s.identityIds()) {
129 Identity *i = new Identity(s.identity(id), this);
131 qWarning() << "Invalid identity! Removing...";
132 s.removeIdentity(id);
136 if(_identities.contains(i->id())) {
137 qWarning() << "Duplicate identity, ignoring!";
141 connect(i, SIGNAL(updated(const QVariantMap &)), this, SLOT(identityUpdated(const QVariantMap &)));
142 _identities[i->id()] = i;
143 signalProxy()->synchronize(i);
145 if(!_identities.count()) {
148 i.setIdentityName(tr("Default Identity"));
152 foreach(NetworkInfo info, Core::networks(user())) {
157 void CoreSession::saveSessionState() const {
160 void CoreSession::restoreSessionState() {
161 QList<NetworkId> nets = Core::connectedNetworks(user());
162 CoreNetwork *net = 0;
163 foreach(NetworkId id, nets) {
170 void CoreSession::addClient(QIODevice *device) {
172 qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
174 // if the socket is an orphan, the signalProxy adopts it.
175 // -> we don't need to care about it anymore
176 device->setParent(0);
177 signalProxy()->addPeer(device);
179 reply["MsgType"] = "SessionInit";
180 reply["SessionState"] = sessionState();
181 SignalProxy::writeDataToDevice(device, reply);
185 void CoreSession::addClient(SignalProxy *proxy) {
186 signalProxy()->addPeer(proxy);
187 emit sessionState(sessionState());
190 void CoreSession::removeClient(QIODevice *iodev) {
191 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
193 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
196 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
197 return Core::persistentChannels(user(), id);
198 return QHash<QString, QString>();
201 // FIXME switch to BufferId
202 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
203 CoreNetwork *net = network(bufinfo.networkId());
205 net->userInput(bufinfo, msg);
207 qWarning() << "Trying to send to unconnected network:" << msg;
211 // ALL messages coming pass through these functions before going to the GUI.
212 // So this is the perfect place for storing the backlog and log stuff.
213 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType,
214 QString target, QString text, QString sender, Message::Flags flags) {
215 CoreNetwork *net = qobject_cast<CoreNetwork*>(this->sender());
218 BufferInfo bufferInfo = Core::bufferInfo(user(), net->networkId(), bufferType, target);
219 Message msg(bufferInfo, type, text, sender, flags);
220 msg.setMsgId(Core::storeMessage(msg));
221 Q_ASSERT(msg.msgId() != 0);
222 emit displayMsg(msg);
225 void CoreSession::recvStatusMsgFromServer(QString msg) {
226 CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
228 emit displayStatusMsg(net->networkName(), msg);
231 QList<BufferInfo> CoreSession::buffers() const {
232 return Core::requestBuffers(user());
236 QVariant CoreSession::sessionState() {
240 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
241 v["BufferInfos"] = bufs;
242 QVariantList networkids;
243 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
244 v["NetworkIds"] = networkids;
246 quint32 ircusercount = 0;
247 quint32 ircchannelcount = 0;
248 foreach(Network *net, _networks.values()) {
249 ircusercount += net->ircUserCount();
250 ircchannelcount += net->ircChannelCount();
252 v["IrcUserCount"] = ircusercount;
253 v["IrcChannelCount"] = ircchannelcount;
255 QList<QVariant> idlist;
256 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
257 v["Identities"] = idlist;
259 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
263 void CoreSession::storeBufferLastSeenMsg(BufferId buffer, const MsgId &msgId) {
264 Core::setBufferLastSeenMsg(user(), buffer, msgId);
267 void CoreSession::initScriptEngine() {
268 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
269 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
272 //QScriptValue storage_ = scriptEngine->newQObject(storage);
273 //scriptEngine->globalObject().setProperty("storage", storage_);
276 void CoreSession::scriptRequest(QString script) {
277 emit scriptResult(scriptEngine->evaluate(script).toString());
280 /*** Identity Handling ***/
282 void CoreSession::createIdentity(const Identity &id) {
285 for(i = 1; i <= _identities.count(); i++) {
286 if(!_identities.keys().contains(i)) break;
288 //qDebug() << "found free id" << i;
289 Identity *newId = new Identity(id, this);
291 _identities[i] = newId;
292 signalProxy()->synchronize(newId);
293 CoreUserSettings s(user());
294 s.storeIdentity(*newId);
295 connect(newId, SIGNAL(updated(const QVariantMap &)), this, SLOT(identityUpdated(const QVariantMap &)));
296 emit identityCreated(*newId);
299 void CoreSession::removeIdentity(IdentityId id) {
300 Identity *i = _identities.take(id);
302 emit identityRemoved(id);
303 CoreUserSettings s(user());
304 s.removeIdentity(id);
309 void CoreSession::identityUpdated(const QVariantMap &data) {
310 IdentityId id = data.value("identityId", 0).value<IdentityId>();
311 if(!id.isValid() || !_identities.contains(id)) {
312 qWarning() << "Update request for unknown identity received!";
315 CoreUserSettings s(user());
316 s.storeIdentity(*_identities.value(id));
319 /*** Network Handling ***/
321 void CoreSession::createNetwork(const NetworkInfo &info_) {
322 NetworkInfo info = info_;
325 if(!info.networkId.isValid())
326 Core::createNetwork(user(), info);
328 if(!info.networkId.isValid()) {
329 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
333 id = info.networkId.toInt();
334 if(!_networks.contains(id)) {
335 CoreNetwork *net = new CoreNetwork(id, this);
336 connect(net, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)),
337 this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)));
338 connect(net, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
340 net->setNetworkInfo(info);
341 net->setProxy(signalProxy());
343 signalProxy()->synchronize(net);
344 emit networkCreated(id);
346 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
347 _networks[info.networkId]->requestSetNetworkInfo(info);
351 void CoreSession::removeNetwork(NetworkId id) {
352 // Make sure the network is disconnected!
353 CoreNetwork *net = network(id);
357 if(net->connectionState() != Network::Disconnected) {
358 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
359 net->disconnectFromIrc();
365 void CoreSession::destroyNetwork(NetworkId id) {
366 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
367 Network *net = _networks.take(id);
368 if(net && Core::removeNetwork(user(), id)) {
369 foreach(BufferId bufferId, removedBuffers) {
370 _bufferSyncer->removeBuffer(bufferId);
372 emit networkRemoved(id);
377 void CoreSession::removeBufferRequested(BufferId bufferId) {
378 BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
379 if(!bufferInfo.isValid()) {
380 qWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
384 if(bufferInfo.type() == BufferInfo::StatusBuffer) {
385 qWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
389 if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
390 CoreNetwork *net = network(bufferInfo.networkId());
392 qWarning() << "CoreSession::removeBufferRequested(): Received BufferInfo with unknown networkId!";
395 IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
397 qWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
401 if(Core::removeBuffer(user(), bufferId))
402 emit bufferRemoved(bufferId);
405 // FIXME: use a coreBufferSyncer for this
406 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
407 BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
408 if(bufferId.isValid()) {
409 emit bufferRenamed(bufferId, newName);
413 void CoreSession::clientsConnected() {
414 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
415 Identity *identity = 0;
416 CoreNetwork *net = 0;
419 while(netIter != _networks.end()) {
423 if(!net->isConnected())
425 identity = net->identityPtr();
432 if(identity->detachAwayEnabled() && me->isAway()) {
433 net->userInputHandler()->handleAway(BufferInfo(), QString());
438 void CoreSession::clientsDisconnected() {
439 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
440 Identity *identity = 0;
441 CoreNetwork *net = 0;
444 while(netIter != _networks.end()) {
448 if(!net->isConnected())
450 identity = net->identityPtr();
457 if(identity->detachAwayEnabled() && !me->isAway()) {
458 if(identity->detachAwayReasonEnabled())
459 awayReason = identity->detachAwayReason();
461 awayReason = identity->awayReason();
462 net->setAutoAwayActive(true);
463 net->userInputHandler()->handleAway(BufferInfo(), awayReason);