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)),
51 scriptEngine(new QScriptEngine(this))
54 SignalProxy *p = signalProxy();
55 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
57 //p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
58 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
59 p->attachSignal(this, SIGNAL(displayMsg(Message)));
60 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
61 p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
63 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
64 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
65 p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
66 p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
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 &)), this, SLOT(createNetwork(const NetworkInfo &)));
72 p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(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);
90 // init BacklogManager;
91 p->synchronize(_backlogManager);
93 // init IrcListHelper;
94 p->synchronize(ircListHelper());
96 // Restore session state
97 if(restoreState) restoreSessionState();
102 CoreSession::~CoreSession() {
104 foreach(NetworkConnection *conn, _connections.values()) {
107 foreach(CoreNetwork *net, _networks.values()) {
112 UserId CoreSession::user() const {
116 CoreNetwork *CoreSession::network(NetworkId id) const {
117 if(_networks.contains(id)) return _networks[id];
121 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
122 if(_connections.contains(id)) return _connections[id];
126 Identity *CoreSession::identity(IdentityId id) const {
127 if(_identities.contains(id)) return _identities[id];
131 void CoreSession::loadSettings() {
132 CoreUserSettings s(user());
134 foreach(IdentityId id, s.identityIds()) {
135 Identity *i = new Identity(s.identity(id), this);
137 qWarning() << QString("Invalid identity! Removing...");
138 s.removeIdentity(id);
142 if(_identities.contains(i->id())) {
143 qWarning() << "Duplicate identity, ignoring!";
147 _identities[i->id()] = i;
148 signalProxy()->synchronize(i);
150 if(!_identities.count()) {
153 i.setIdentityName(tr("Default Identity"));
157 foreach(NetworkInfo info, Core::networks(user())) {
162 void CoreSession::saveSessionState() const {
166 void CoreSession::restoreSessionState() {
167 QList<NetworkId> nets = Core::connectedNetworks(user());
168 foreach(NetworkId id, nets) {
169 connectToNetwork(id);
173 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
174 if(uid == user()) emit bufferInfoUpdated(bufinfo);
177 void CoreSession::connectToNetwork(NetworkId id) {
178 CoreNetwork *net = network(id);
180 qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
184 NetworkConnection *conn = networkConnection(id);
186 conn = new NetworkConnection(net, this);
187 _connections[id] = conn;
188 attachNetworkConnection(conn);
190 conn->connectToIrc();
193 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
194 connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
195 connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
197 // I guess we don't need these anymore, client-side can just connect the network's signals directly
198 //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
199 //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
201 connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)),
202 this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)));
203 connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
205 connect(conn, SIGNAL(nickChanged(const NetworkId &, const QString &, const QString &)),
206 this, SLOT(renameBuffer(const NetworkId &, const QString &, const QString &)));
207 connect(conn, SIGNAL(channelJoined(NetworkId, const QString &, const QString &)),
208 this, SLOT(channelJoined(NetworkId, const QString &, const QString &)));
209 connect(conn, SIGNAL(channelParted(NetworkId, const QString &)),
210 this, SLOT(channelParted(NetworkId, const QString &)));
213 void CoreSession::disconnectFromNetwork(NetworkId id) {
214 if(!_connections.contains(id))
217 //_connections[id]->disconnectFromIrc();
218 _connections[id]->userInputHandler()->handleQuit(BufferInfo(), QString());
221 void CoreSession::networkStateRequested() {
224 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
225 QIODevice *device = qobject_cast<QIODevice *>(dev);
227 qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
229 signalProxy()->addPeer(device);
231 reply["MsgType"] = "SessionInit";
232 reply["SessionState"] = sessionState();
233 SignalProxy::writeDataToDevice(device, reply);
237 void CoreSession::removeClient(QIODevice *iodev) {
238 // no checks for validity check - privateslot...
239 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
241 qDebug() << qPrintable(tr("Client %1 disconnected (UserId: %2).").arg(socket->peerAddress().toString()).arg(user().toInt()));
243 qDebug() << "Local client disconnedted.";
244 disconnect(socket, 0, this, 0);
245 socket->deleteLater();
248 SignalProxy *CoreSession::signalProxy() const {
252 // FIXME we need a sane way for creating buffers!
253 void CoreSession::networkConnected(NetworkId networkid) {
254 Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
255 Core::setNetworkConnected(user(), networkid, true);
258 // called now only on /quit and requested disconnects, not on normal disconnects!
259 void CoreSession::networkDisconnected(NetworkId networkid) {
260 // if the network has already been removed, we don't have a networkconnection left either, so we don't do anything
261 // make sure to not depend on the network still existing when calling this function!
262 if(_connections.contains(networkid)) {
263 Core::setNetworkConnected(user(), networkid, false);
264 _connections.take(networkid)->deleteLater();
268 void CoreSession::channelJoined(NetworkId id, const QString &channel, const QString &key) {
269 Core::setChannelPersistent(user(), id, channel, true);
270 Core::setPersistentChannelKey(user(), id, channel, key);
273 void CoreSession::channelParted(NetworkId id, const QString &channel) {
274 Core::setChannelPersistent(user(), id, channel, false);
277 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
278 return Core::persistentChannels(user(), id);
279 return QHash<QString, QString>();
282 // FIXME switch to BufferId
283 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
284 NetworkConnection *conn = networkConnection(bufinfo.networkId());
286 conn->userInput(bufinfo, msg);
288 qWarning() << "Trying to send to unconnected network:" << msg;
292 // ALL messages coming pass through these functions before going to the GUI.
293 // So this is the perfect place for storing the backlog and log stuff.
294 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType,
295 QString target, QString text, QString sender, Message::Flags flags) {
296 NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
299 BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
300 Message msg(bufferInfo, type, text, sender, flags);
301 msg.setMsgId(Core::storeMessage(msg));
302 Q_ASSERT(msg.msgId() != 0);
303 emit displayMsg(msg);
306 void CoreSession::recvStatusMsgFromServer(QString msg) {
307 NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
309 emit displayStatusMsg(s->networkName(), msg);
312 QList<BufferInfo> CoreSession::buffers() const {
313 return Core::requestBuffers(user());
317 QVariant CoreSession::sessionState() {
321 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
322 v["BufferInfos"] = bufs;
323 QVariantList networkids;
324 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
325 v["NetworkIds"] = networkids;
327 quint32 ircusercount = 0;
328 quint32 ircchannelcount = 0;
329 foreach(Network *net, _networks.values()) {
330 ircusercount += net->ircUserCount();
331 ircchannelcount += net->ircChannelCount();
333 v["IrcUserCount"] = ircusercount;
334 v["IrcChannelCount"] = ircchannelcount;
336 QList<QVariant> idlist;
337 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
338 v["Identities"] = idlist;
340 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
344 void CoreSession::storeBufferLastSeenMsg(BufferId buffer, const MsgId &msgId) {
345 Core::setBufferLastSeenMsg(user(), buffer, msgId);
348 void CoreSession::initScriptEngine() {
349 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
350 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
353 //QScriptValue storage_ = scriptEngine->newQObject(storage);
354 //scriptEngine->globalObject().setProperty("storage", storage_);
357 void CoreSession::scriptRequest(QString script) {
358 emit scriptResult(scriptEngine->evaluate(script).toString());
361 /*** Identity Handling ***/
363 void CoreSession::createIdentity(const Identity &id) {
366 for(i = 1; i <= _identities.count(); i++) {
367 if(!_identities.keys().contains(i)) break;
369 //qDebug() << "found free id" << i;
370 Identity *newId = new Identity(id, this);
372 _identities[i] = newId;
373 signalProxy()->synchronize(newId);
374 CoreUserSettings s(user());
375 s.storeIdentity(*newId);
376 emit identityCreated(*newId);
379 void CoreSession::updateIdentity(const Identity &id) {
380 if(!_identities.contains(id.id())) {
381 qWarning() << "Update request for unknown identity received!";
384 _identities[id.id()]->update(id);
386 CoreUserSettings s(user());
390 void CoreSession::removeIdentity(IdentityId id) {
391 Identity *i = _identities.take(id);
393 emit identityRemoved(id);
394 CoreUserSettings s(user());
395 s.removeIdentity(id);
400 /*** Network Handling ***/
402 void CoreSession::createNetwork(const NetworkInfo &info_) {
403 NetworkInfo info = info_;
406 if(!info.networkId.isValid())
407 Core::createNetwork(user(), info);
409 if(!info.networkId.isValid()) {
410 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
414 id = info.networkId.toInt();
415 if(!_networks.contains(id)) {
416 CoreNetwork *net = new CoreNetwork(id, this);
417 connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
418 connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
419 net->setNetworkInfo(info);
420 net->setProxy(signalProxy());
422 signalProxy()->synchronize(net);
423 emit networkCreated(id);
425 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
430 // FIXME: move to CoreNetwork
431 void CoreSession::updateNetwork(const NetworkInfo &info) {
432 if(!_networks.contains(info.networkId)) {
433 qWarning() << "Update request for unknown network received!";
436 _networks[info.networkId]->setNetworkInfo(info);
437 Core::updateNetwork(user(), info);
440 void CoreSession::removeNetwork(NetworkId id) {
441 // Make sure the network is disconnected!
442 NetworkConnection *conn = _connections.value(id, 0);
444 if(conn->connectionState() != Network::Disconnected) {
445 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
446 conn->disconnectFromIrc();
448 _connections.take(id)->deleteLater(); // TODO make this saner
456 void CoreSession::destroyNetwork(NetworkId id) {
457 if(_connections.contains(id)) {
458 // this can happen if the network was reconnecting while being removed
459 _connections.take(id)->deleteLater();
461 Network *net = _networks.take(id);
462 if(net && Core::removeNetwork(user(), id)) {
463 emit networkRemoved(id);
468 void CoreSession::removeBufferRequested(BufferId bufferId) {
469 BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
470 if(!bufferInfo.isValid()) {
471 qWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
475 if(bufferInfo.type() == BufferInfo::StatusBuffer) {
476 qWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
480 if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
481 CoreNetwork *net = network(bufferInfo.networkId());
483 qWarning() << "CoreSession::removeBufferRequested(): Received BufferInfo with unknown networkId!";
486 IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
488 qWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
492 if(Core::removeBuffer(user(), bufferId))
493 emit bufferRemoved(bufferId);
496 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
497 BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
498 if(bufferId.isValid()) {
499 emit bufferRenamed(bufferId, newName);