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"
44 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
47 _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
49 _bufferSyncer(new BufferSyncer(this)),
50 _backlogManager(new CoreBacklogManager(this)),
51 _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
52 _ircListHelper(new CoreIrcListHelper(this)),
54 scriptEngine(new QScriptEngine(this))
57 SignalProxy *p = signalProxy();
58 connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
60 //p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
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)));
64 p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
66 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
67 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
68 p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
69 p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
70 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
72 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
73 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
74 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
75 p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
76 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
82 QHash<BufferId, MsgId> lastSeenHash = Core::bufferLastSeenMsgIds(user());
83 foreach(BufferId id, lastSeenHash.keys())
84 _bufferSyncer->requestSetLastSeenMsg(id, lastSeenHash[id]);
86 connect(_bufferSyncer, SIGNAL(lastSeenMsgSet(BufferId, MsgId)), this, SLOT(storeBufferLastSeenMsg(BufferId, MsgId)));
87 connect(_bufferSyncer, SIGNAL(removeBufferRequested(BufferId)), this, SLOT(removeBufferRequested(BufferId)));
88 connect(this, SIGNAL(bufferRemoved(BufferId)), _bufferSyncer, SLOT(removeBuffer(BufferId)));
89 connect(this, SIGNAL(bufferRenamed(BufferId, QString)), _bufferSyncer, SLOT(renameBuffer(BufferId, QString)));
90 p->synchronize(_bufferSyncer);
94 p->synchronize(&aliasManager());
96 // init BacklogManager
97 p->synchronize(_backlogManager);
100 p->synchronize(ircListHelper());
103 p->synchronize(&_coreInfo);
105 // Restore session state
106 if(restoreState) restoreSessionState();
111 CoreSession::~CoreSession() {
113 foreach(NetworkConnection *conn, _connections.values()) {
116 foreach(CoreNetwork *net, _networks.values()) {
121 UserId CoreSession::user() const {
125 CoreNetwork *CoreSession::network(NetworkId id) const {
126 if(_networks.contains(id)) return _networks[id];
130 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
131 if(_connections.contains(id)) return _connections[id];
135 Identity *CoreSession::identity(IdentityId id) const {
136 if(_identities.contains(id)) return _identities[id];
140 void CoreSession::loadSettings() {
141 CoreUserSettings s(user());
143 foreach(IdentityId id, s.identityIds()) {
144 Identity *i = new Identity(s.identity(id), this);
146 quWarning() << "Invalid identity! Removing...";
147 s.removeIdentity(id);
151 if(_identities.contains(i->id())) {
152 quWarning() << "Duplicate identity, ignoring!";
156 _identities[i->id()] = i;
157 signalProxy()->synchronize(i);
159 if(!_identities.count()) {
162 i.setIdentityName(tr("Default Identity"));
166 foreach(NetworkInfo info, Core::networks(user())) {
171 void CoreSession::saveSessionState() const {
175 void CoreSession::restoreSessionState() {
176 QList<NetworkId> nets = Core::connectedNetworks(user());
177 foreach(NetworkId id, nets) {
178 connectToNetwork(id);
182 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
183 if(uid == user()) emit bufferInfoUpdated(bufinfo);
186 void CoreSession::connectToNetwork(NetworkId id) {
187 CoreNetwork *net = network(id);
189 quWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
193 NetworkConnection *conn = networkConnection(id);
195 conn = new NetworkConnection(net, this);
196 _connections[id] = conn;
197 attachNetworkConnection(conn);
199 conn->connectToIrc();
202 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
203 connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
204 connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
206 // I guess we don't need these anymore, client-side can just connect the network's signals directly
207 //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
208 //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
210 connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)),
211 this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)));
212 connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
214 connect(conn, SIGNAL(nickChanged(const NetworkId &, const QString &, const QString &)),
215 this, SLOT(renameBuffer(const NetworkId &, const QString &, const QString &)));
216 connect(conn, SIGNAL(channelJoined(NetworkId, const QString &, const QString &)),
217 this, SLOT(channelJoined(NetworkId, const QString &, const QString &)));
218 connect(conn, SIGNAL(channelParted(NetworkId, const QString &)),
219 this, SLOT(channelParted(NetworkId, const QString &)));
222 void CoreSession::disconnectFromNetwork(NetworkId id) {
223 if(!_connections.contains(id))
226 //_connections[id]->disconnectFromIrc();
227 _connections[id]->userInputHandler()->handleQuit(BufferInfo(), QString());
230 void CoreSession::networkStateRequested() {
233 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
234 QIODevice *device = qobject_cast<QIODevice *>(dev);
236 quError() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
238 signalProxy()->addPeer(device);
240 reply["MsgType"] = "SessionInit";
241 reply["SessionState"] = sessionState();
242 SignalProxy::writeDataToDevice(device, reply);
246 void CoreSession::removeClient(QIODevice *iodev) {
247 // no checks for validity check - privateslot...
248 QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
250 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
252 quInfo() << "Local client disconnedted.";
253 disconnect(socket, 0, this, 0);
254 socket->deleteLater();
257 SignalProxy *CoreSession::signalProxy() const {
261 // FIXME we need a sane way for creating buffers!
262 void CoreSession::networkConnected(NetworkId networkid) {
263 Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
264 Core::setNetworkConnected(user(), networkid, true);
267 // called now only on /quit and requested disconnects, not on normal disconnects!
268 void CoreSession::networkDisconnected(NetworkId networkid) {
269 // if the network has already been removed, we don't have a networkconnection left either, so we don't do anything
270 // make sure to not depend on the network still existing when calling this function!
271 if(_connections.contains(networkid)) {
272 Core::setNetworkConnected(user(), networkid, false);
273 _connections.take(networkid)->deleteLater();
277 void CoreSession::channelJoined(NetworkId id, const QString &channel, const QString &key) {
278 Core::setChannelPersistent(user(), id, channel, true);
279 Core::setPersistentChannelKey(user(), id, channel, key);
282 void CoreSession::channelParted(NetworkId id, const QString &channel) {
283 Core::setChannelPersistent(user(), id, channel, false);
286 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
287 return Core::persistentChannels(user(), id);
288 return QHash<QString, QString>();
291 // FIXME switch to BufferId
292 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
293 NetworkConnection *conn = networkConnection(bufinfo.networkId());
295 conn->userInput(bufinfo, msg);
297 quWarning() << "Trying to send to unconnected network:" << msg;
301 // ALL messages coming pass through these functions before going to the GUI.
302 // So this is the perfect place for storing the backlog and log stuff.
303 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType,
304 QString target, QString text, QString sender, Message::Flags flags) {
305 NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
308 BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
309 Message msg(bufferInfo, type, text, sender, flags);
310 msg.setMsgId(Core::storeMessage(msg));
311 Q_ASSERT(msg.msgId() != 0);
312 emit displayMsg(msg);
315 void CoreSession::recvStatusMsgFromServer(QString msg) {
316 NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
318 emit displayStatusMsg(s->networkName(), msg);
321 QList<BufferInfo> CoreSession::buffers() const {
322 return Core::requestBuffers(user());
326 QVariant CoreSession::sessionState() {
330 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
331 v["BufferInfos"] = bufs;
332 QVariantList networkids;
333 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
334 v["NetworkIds"] = networkids;
336 quint32 ircusercount = 0;
337 quint32 ircchannelcount = 0;
338 foreach(Network *net, _networks.values()) {
339 ircusercount += net->ircUserCount();
340 ircchannelcount += net->ircChannelCount();
342 v["IrcUserCount"] = ircusercount;
343 v["IrcChannelCount"] = ircchannelcount;
345 QList<QVariant> idlist;
346 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
347 v["Identities"] = idlist;
349 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
353 void CoreSession::storeBufferLastSeenMsg(BufferId buffer, const MsgId &msgId) {
354 Core::setBufferLastSeenMsg(user(), buffer, msgId);
357 void CoreSession::initScriptEngine() {
358 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
359 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
362 //QScriptValue storage_ = scriptEngine->newQObject(storage);
363 //scriptEngine->globalObject().setProperty("storage", storage_);
366 void CoreSession::scriptRequest(QString script) {
367 emit scriptResult(scriptEngine->evaluate(script).toString());
370 /*** Identity Handling ***/
372 void CoreSession::createIdentity(const Identity &id) {
375 for(i = 1; i <= _identities.count(); i++) {
376 if(!_identities.keys().contains(i)) break;
378 //qDebug() << "found free id" << i;
379 Identity *newId = new Identity(id, this);
381 _identities[i] = newId;
382 signalProxy()->synchronize(newId);
383 CoreUserSettings s(user());
384 s.storeIdentity(*newId);
385 emit identityCreated(*newId);
388 void CoreSession::updateIdentity(const Identity &id) {
389 if(!_identities.contains(id.id())) {
390 quWarning() << "Update request for unknown identity received!";
393 _identities[id.id()]->update(id);
395 CoreUserSettings s(user());
399 void CoreSession::removeIdentity(IdentityId id) {
400 Identity *i = _identities.take(id);
402 emit identityRemoved(id);
403 CoreUserSettings s(user());
404 s.removeIdentity(id);
409 /*** Network Handling ***/
411 void CoreSession::createNetwork(const NetworkInfo &info_) {
412 NetworkInfo info = info_;
415 if(!info.networkId.isValid())
416 Core::createNetwork(user(), info);
418 if(!info.networkId.isValid()) {
419 quWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
423 id = info.networkId.toInt();
424 if(!_networks.contains(id)) {
425 CoreNetwork *net = new CoreNetwork(id, this);
426 connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
427 connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
428 net->setNetworkInfo(info);
429 net->setProxy(signalProxy());
431 signalProxy()->synchronize(net);
432 emit networkCreated(id);
434 quWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
439 // FIXME: move to CoreNetwork
440 void CoreSession::updateNetwork(const NetworkInfo &info) {
441 if(!_networks.contains(info.networkId)) {
442 quWarning() << "Update request for unknown network received!";
445 _networks[info.networkId]->setNetworkInfo(info);
446 Core::updateNetwork(user(), info);
449 void CoreSession::removeNetwork(NetworkId id) {
450 // Make sure the network is disconnected!
451 NetworkConnection *conn = _connections.value(id, 0);
453 if(conn->connectionState() != Network::Disconnected) {
454 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
455 conn->disconnectFromIrc();
457 _connections.take(id)->deleteLater(); // TODO make this saner
465 void CoreSession::destroyNetwork(NetworkId id) {
466 if(_connections.contains(id)) {
467 // this can happen if the network was reconnecting while being removed
468 _connections.take(id)->deleteLater();
470 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
471 Network *net = _networks.take(id);
472 if(net && Core::removeNetwork(user(), id)) {
473 foreach(BufferId bufferId, removedBuffers) {
474 _bufferSyncer->removeBuffer(bufferId);
476 emit networkRemoved(id);
481 void CoreSession::removeBufferRequested(BufferId bufferId) {
482 BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
483 if(!bufferInfo.isValid()) {
484 quWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
488 if(bufferInfo.type() == BufferInfo::StatusBuffer) {
489 quWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
493 if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
494 CoreNetwork *net = network(bufferInfo.networkId());
496 quWarning() << "CoreSession::removeBufferRequested(): Received BufferInfo with unknown networkId!";
499 IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
501 quWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
505 if(Core::removeBuffer(user(), bufferId))
506 emit bufferRemoved(bufferId);
509 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
510 BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
511 if(bufferId.isValid()) {
512 emit bufferRenamed(bufferId, newName);