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 "networkconnection.h"
26 #include "userinputhandler.h"
28 #include "signalproxy.h"
29 #include "buffersyncer.h"
30 #include "corebacklogmanager.h"
31 #include "corebufferviewmanager.h"
32 #include "coreirclisthelper.h"
35 #include "corenetwork.h"
37 #include "ircchannel.h"
41 #include "coreusersettings.h"
43 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
46 _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 //p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
59 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
60 p->attachSignal(this, SIGNAL(displayMsg(Message)));
61 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
62 p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
64 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
65 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
66 p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
67 p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(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(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
74 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
80 QHash<BufferId, MsgId> lastSeenHash = Core::bufferLastSeenMsgIds(user());
81 foreach(BufferId id, lastSeenHash.keys())
82 _bufferSyncer->requestSetLastSeenMsg(id, lastSeenHash[id]);
84 connect(_bufferSyncer, SIGNAL(lastSeenMsgSet(BufferId, MsgId)), this, SLOT(storeBufferLastSeenMsg(BufferId, MsgId)));
85 connect(_bufferSyncer, SIGNAL(removeBufferRequested(BufferId)), this, SLOT(removeBufferRequested(BufferId)));
86 connect(this, SIGNAL(bufferRemoved(BufferId)), _bufferSyncer, SLOT(removeBuffer(BufferId)));
87 connect(this, SIGNAL(bufferRenamed(BufferId, QString)), _bufferSyncer, SLOT(renameBuffer(BufferId, QString)));
88 p->synchronize(_bufferSyncer);
91 // init BacklogManager;
92 p->synchronize(_backlogManager);
94 // init IrcListHelper;
95 p->synchronize(ircListHelper());
98 p->synchronize(&_coreInfo);
100 // Restore session state
101 if(restoreState) restoreSessionState();
106 CoreSession::~CoreSession() {
108 foreach(NetworkConnection *conn, _connections.values()) {
111 foreach(CoreNetwork *net, _networks.values()) {
116 UserId CoreSession::user() const {
120 CoreNetwork *CoreSession::network(NetworkId id) const {
121 if(_networks.contains(id)) return _networks[id];
125 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
126 if(_connections.contains(id)) return _connections[id];
130 Identity *CoreSession::identity(IdentityId id) const {
131 if(_identities.contains(id)) return _identities[id];
135 void CoreSession::loadSettings() {
136 CoreUserSettings s(user());
138 foreach(IdentityId id, s.identityIds()) {
139 Identity *i = new Identity(s.identity(id), this);
141 qWarning() << QString("Invalid identity! Removing...");
142 s.removeIdentity(id);
146 if(_identities.contains(i->id())) {
147 qWarning() << "Duplicate identity, ignoring!";
151 _identities[i->id()] = i;
152 signalProxy()->synchronize(i);
154 if(!_identities.count()) {
157 i.setIdentityName(tr("Default Identity"));
161 foreach(NetworkInfo info, Core::networks(user())) {
166 void CoreSession::saveSessionState() const {
170 void CoreSession::restoreSessionState() {
171 QList<NetworkId> nets = Core::connectedNetworks(user());
172 foreach(NetworkId id, nets) {
173 connectToNetwork(id);
177 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
178 if(uid == user()) emit bufferInfoUpdated(bufinfo);
181 void CoreSession::connectToNetwork(NetworkId id) {
182 CoreNetwork *net = network(id);
184 qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
188 NetworkConnection *conn = networkConnection(id);
190 conn = new NetworkConnection(net, this);
191 _connections[id] = conn;
192 attachNetworkConnection(conn);
194 conn->connectToIrc();
197 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
198 connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
199 connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
201 // I guess we don't need these anymore, client-side can just connect the network's signals directly
202 //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
203 //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
205 connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)),
206 this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)));
207 connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
209 connect(conn, SIGNAL(nickChanged(const NetworkId &, const QString &, const QString &)),
210 this, SLOT(renameBuffer(const NetworkId &, const QString &, const QString &)));
211 connect(conn, SIGNAL(channelJoined(NetworkId, const QString &, const QString &)),
212 this, SLOT(channelJoined(NetworkId, const QString &, const QString &)));
213 connect(conn, SIGNAL(channelParted(NetworkId, const QString &)),
214 this, SLOT(channelParted(NetworkId, const QString &)));
217 void CoreSession::disconnectFromNetwork(NetworkId id) {
218 if(!_connections.contains(id))
221 //_connections[id]->disconnectFromIrc();
222 _connections[id]->userInputHandler()->handleQuit(BufferInfo(), QString());
225 void CoreSession::networkStateRequested() {
228 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
229 QIODevice *device = qobject_cast<QIODevice *>(dev);
231 qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
233 signalProxy()->addPeer(device);
235 reply["MsgType"] = "SessionInit";
236 reply["SessionState"] = sessionState();
237 SignalProxy::writeDataToDevice(device, reply);
241 void CoreSession::removeClient(QIODevice *iodev) {
242 // no checks for validity check - privateslot...
243 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
245 qDebug() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
247 qDebug() << "Local client disconnedted.";
248 disconnect(socket, 0, this, 0);
249 socket->deleteLater();
252 SignalProxy *CoreSession::signalProxy() const {
256 // FIXME we need a sane way for creating buffers!
257 void CoreSession::networkConnected(NetworkId networkid) {
258 Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
259 Core::setNetworkConnected(user(), networkid, true);
262 // called now only on /quit and requested disconnects, not on normal disconnects!
263 void CoreSession::networkDisconnected(NetworkId networkid) {
264 // if the network has already been removed, we don't have a networkconnection left either, so we don't do anything
265 // make sure to not depend on the network still existing when calling this function!
266 if(_connections.contains(networkid)) {
267 Core::setNetworkConnected(user(), networkid, false);
268 _connections.take(networkid)->deleteLater();
272 void CoreSession::channelJoined(NetworkId id, const QString &channel, const QString &key) {
273 Core::setChannelPersistent(user(), id, channel, true);
274 Core::setPersistentChannelKey(user(), id, channel, key);
277 void CoreSession::channelParted(NetworkId id, const QString &channel) {
278 Core::setChannelPersistent(user(), id, channel, false);
281 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
282 return Core::persistentChannels(user(), id);
283 return QHash<QString, QString>();
286 // FIXME switch to BufferId
287 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
288 NetworkConnection *conn = networkConnection(bufinfo.networkId());
290 conn->userInput(bufinfo, msg);
292 qWarning() << "Trying to send to unconnected network:" << msg;
296 // ALL messages coming pass through these functions before going to the GUI.
297 // So this is the perfect place for storing the backlog and log stuff.
298 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType,
299 QString target, QString text, QString sender, Message::Flags flags) {
300 NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
303 BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
304 Message msg(bufferInfo, type, text, sender, flags);
305 msg.setMsgId(Core::storeMessage(msg));
306 Q_ASSERT(msg.msgId() != 0);
307 emit displayMsg(msg);
310 void CoreSession::recvStatusMsgFromServer(QString msg) {
311 NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
313 emit displayStatusMsg(s->networkName(), msg);
316 QList<BufferInfo> CoreSession::buffers() const {
317 return Core::requestBuffers(user());
321 QVariant CoreSession::sessionState() {
325 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
326 v["BufferInfos"] = bufs;
327 QVariantList networkids;
328 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
329 v["NetworkIds"] = networkids;
331 quint32 ircusercount = 0;
332 quint32 ircchannelcount = 0;
333 foreach(Network *net, _networks.values()) {
334 ircusercount += net->ircUserCount();
335 ircchannelcount += net->ircChannelCount();
337 v["IrcUserCount"] = ircusercount;
338 v["IrcChannelCount"] = ircchannelcount;
340 QList<QVariant> idlist;
341 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
342 v["Identities"] = idlist;
344 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
348 void CoreSession::storeBufferLastSeenMsg(BufferId buffer, const MsgId &msgId) {
349 Core::setBufferLastSeenMsg(user(), buffer, msgId);
352 void CoreSession::initScriptEngine() {
353 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
354 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
357 //QScriptValue storage_ = scriptEngine->newQObject(storage);
358 //scriptEngine->globalObject().setProperty("storage", storage_);
361 void CoreSession::scriptRequest(QString script) {
362 emit scriptResult(scriptEngine->evaluate(script).toString());
365 /*** Identity Handling ***/
367 void CoreSession::createIdentity(const Identity &id) {
370 for(i = 1; i <= _identities.count(); i++) {
371 if(!_identities.keys().contains(i)) break;
373 //qDebug() << "found free id" << i;
374 Identity *newId = new Identity(id, this);
376 _identities[i] = newId;
377 signalProxy()->synchronize(newId);
378 CoreUserSettings s(user());
379 s.storeIdentity(*newId);
380 emit identityCreated(*newId);
383 void CoreSession::updateIdentity(const Identity &id) {
384 if(!_identities.contains(id.id())) {
385 qWarning() << "Update request for unknown identity received!";
388 _identities[id.id()]->update(id);
390 CoreUserSettings s(user());
394 void CoreSession::removeIdentity(IdentityId id) {
395 Identity *i = _identities.take(id);
397 emit identityRemoved(id);
398 CoreUserSettings s(user());
399 s.removeIdentity(id);
404 /*** Network Handling ***/
406 void CoreSession::createNetwork(const NetworkInfo &info_) {
407 NetworkInfo info = info_;
410 if(!info.networkId.isValid())
411 Core::createNetwork(user(), info);
413 if(!info.networkId.isValid()) {
414 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
418 id = info.networkId.toInt();
419 if(!_networks.contains(id)) {
420 CoreNetwork *net = new CoreNetwork(id, this);
421 connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
422 connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
423 net->setNetworkInfo(info);
424 net->setProxy(signalProxy());
426 signalProxy()->synchronize(net);
427 emit networkCreated(id);
429 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
434 // FIXME: move to CoreNetwork
435 void CoreSession::updateNetwork(const NetworkInfo &info) {
436 if(!_networks.contains(info.networkId)) {
437 qWarning() << "Update request for unknown network received!";
440 _networks[info.networkId]->setNetworkInfo(info);
441 Core::updateNetwork(user(), info);
444 void CoreSession::removeNetwork(NetworkId id) {
445 // Make sure the network is disconnected!
446 NetworkConnection *conn = _connections.value(id, 0);
448 if(conn->connectionState() != Network::Disconnected) {
449 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
450 conn->disconnectFromIrc();
452 _connections.take(id)->deleteLater(); // TODO make this saner
460 void CoreSession::destroyNetwork(NetworkId id) {
461 if(_connections.contains(id)) {
462 // this can happen if the network was reconnecting while being removed
463 _connections.take(id)->deleteLater();
465 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
466 Network *net = _networks.take(id);
467 if(net && Core::removeNetwork(user(), id)) {
468 foreach(BufferId bufferId, removedBuffers) {
469 _bufferSyncer->removeBuffer(bufferId);
471 emit networkRemoved(id);
476 void CoreSession::removeBufferRequested(BufferId bufferId) {
477 BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
478 if(!bufferInfo.isValid()) {
479 qWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
483 if(bufferInfo.type() == BufferInfo::StatusBuffer) {
484 qWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
488 if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
489 CoreNetwork *net = network(bufferInfo.networkId());
491 qWarning() << "CoreSession::removeBufferRequested(): Received BufferInfo with unknown networkId!";
494 IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
496 qWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
500 if(Core::removeBuffer(user(), bufferId))
501 emit bufferRemoved(bufferId);
504 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
505 BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
506 if(bufferId.isValid()) {
507 emit bufferRenamed(bufferId, newName);