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"
27 #include "signalproxy.h"
28 #include "buffersyncer.h"
33 #include "ircchannel.h"
37 #include "coreusersettings.h"
39 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent) : QObject(parent),
41 _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
42 _bufferSyncer(new BufferSyncer(this)),
43 scriptEngine(new QScriptEngine(this))
46 SignalProxy *p = signalProxy();
48 //p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
49 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
50 p->attachSlot(SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)), this, SLOT(sendBacklog(BufferInfo, QVariant, QVariant)));
51 p->attachSignal(this, SIGNAL(displayMsg(Message)));
52 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
53 p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
54 p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
56 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
57 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
58 p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
59 p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
60 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
62 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
63 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
64 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
65 p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
66 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
72 QHash<BufferId, QDateTime> lastSeenHash = Core::bufferLastSeenDates(user());
73 foreach(BufferId id, lastSeenHash.keys()) _bufferSyncer->requestSetLastSeen(id, lastSeenHash[id]);
74 connect(_bufferSyncer, SIGNAL(lastSeenSet(BufferId, const QDateTime &)), this, SLOT(storeBufferLastSeen(BufferId, const QDateTime &)));
75 connect(_bufferSyncer, SIGNAL(removeBufferRequested(BufferId)), this, SLOT(removeBufferRequested(BufferId)));
76 connect(this, SIGNAL(bufferRemoved(BufferId)), _bufferSyncer, SLOT(removeBuffer(BufferId)));
77 connect(this, SIGNAL(bufferRenamed(BufferId, QString)), _bufferSyncer, SLOT(renameBuffer(BufferId, QString)));
78 p->synchronize(_bufferSyncer);
80 // Restore session state
81 if(restoreState) restoreSessionState();
86 CoreSession::~CoreSession() {
88 foreach(NetworkConnection *conn, _connections.values()) {
91 foreach(Network *net, _networks.values()) {
96 UserId CoreSession::user() const {
100 Network *CoreSession::network(NetworkId id) const {
101 if(_networks.contains(id)) return _networks[id];
105 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
106 if(_connections.contains(id)) return _connections[id];
110 Identity *CoreSession::identity(IdentityId id) const {
111 if(_identities.contains(id)) return _identities[id];
115 void CoreSession::loadSettings() {
116 CoreUserSettings s(user());
118 foreach(IdentityId id, s.identityIds()) {
119 Identity *i = new Identity(s.identity(id), this);
121 qWarning() << QString("Invalid identity! Removing...");
122 s.removeIdentity(id);
126 if(_identities.contains(i->id())) {
127 qWarning() << "Duplicate identity, ignoring!";
131 _identities[i->id()] = i;
132 signalProxy()->synchronize(i);
134 if(!_identities.count()) {
137 i.setIdentityName(tr("Default Identity"));
141 foreach(NetworkInfo info, Core::networks(user())) {
146 void CoreSession::saveSessionState() const {
150 void CoreSession::restoreSessionState() {
152 //QList<NetworkId> nets = Core::connectedNetworks(user());
153 QList<NetworkId> nets;
154 foreach(NetworkId id, nets) {
155 connectToNetwork(id);
159 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
160 if(uid == user()) emit bufferInfoUpdated(bufinfo);
163 void CoreSession::connectToNetwork(NetworkId id) {
164 Network *net = network(id);
166 qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
170 NetworkConnection *conn = networkConnection(id);
172 conn = new NetworkConnection(net, this);
173 _connections[id] = conn;
174 attachNetworkConnection(conn);
176 conn->connectToIrc();
179 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
180 connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
181 connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
183 // I guess we don't need these anymore, client-side can just connect the network's signals directly
184 //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
185 //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
187 connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)),
188 this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)));
189 connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
191 connect(conn, SIGNAL(nickChanged(const NetworkId &, const QString &, const QString &)),
192 this, SLOT(renameBuffer(const NetworkId &, const QString &, const QString &)));
193 connect(conn, SIGNAL(channelJoined(NetworkId, const QString &, const QString &)),
194 this, SLOT(channelJoined(NetworkId, const QString &, const QString &)));
195 connect(conn, SIGNAL(channelParted(NetworkId, const QString &)),
196 this, SLOT(channelParted(NetworkId, const QString &)));
199 void CoreSession::disconnectFromNetwork(NetworkId id) {
200 if(!_connections.contains(id)) return;
201 _connections[id]->disconnectFromIrc();
204 void CoreSession::networkStateRequested() {
207 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
208 QIODevice *device = qobject_cast<QIODevice *>(dev);
210 qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
212 signalProxy()->addPeer(device);
214 reply["MsgType"] = "SessionInit";
215 reply["SessionState"] = sessionState();
216 SignalProxy::writeDataToDevice(device, reply);
220 SignalProxy *CoreSession::signalProxy() const {
224 // FIXME we need a sane way for creating buffers!
225 void CoreSession::networkConnected(NetworkId networkid) {
226 Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
227 //Core::setNetworkConnected(user(), networkid, true);
230 // called now only on /quit and requested disconnects, not on normal disconnects!
231 void CoreSession::networkDisconnected(NetworkId networkid) {
232 //Core::setNetworkConnected(user(), networkid, false);
233 if(_connections.contains(networkid)) _connections.take(networkid)->deleteLater();
236 void CoreSession::channelJoined(NetworkId id, const QString &channel, const QString &key) {
237 //Core::setChannelPersistent(user(), id, channel, true);
238 //Core::setPersistentChannelKey(user(), id, channel, key);
241 void CoreSession::channelParted(NetworkId id, const QString &channel) {
242 //Core::setChannelPersistent(user(), id, channel, false);
245 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
246 //return Core::persistentChannels(user(), id);
247 return QHash<QString, QString>();
250 // FIXME switch to BufferId
251 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
252 NetworkConnection *conn = networkConnection(bufinfo.networkId());
254 conn->userInput(bufinfo, msg);
256 qWarning() << "Trying to send to unconnected network!";
260 // ALL messages coming pass through these functions before going to the GUI.
261 // So this is the perfect place for storing the backlog and log stuff.
262 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, quint8 flags) {
263 NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
266 BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
267 Message msg(bufferInfo, type, text, sender, flags);
268 msg.setMsgId(Core::storeMessage(msg));
269 Q_ASSERT(msg.msgId() != 0);
270 emit displayMsg(msg);
273 void CoreSession::recvStatusMsgFromServer(QString msg) {
274 NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
276 emit displayStatusMsg(s->networkName(), msg);
279 QList<BufferInfo> CoreSession::buffers() const {
280 return Core::requestBuffers(user());
284 QVariant CoreSession::sessionState() {
288 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
289 v["BufferInfos"] = bufs;
290 QVariantList networkids;
291 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
292 v["NetworkIds"] = networkids;
294 quint32 ircusercount = 0;
295 quint32 ircchannelcount = 0;
296 foreach(Network *net, _networks.values()) {
297 ircusercount += net->ircUserCount();
298 ircchannelcount += net->ircChannelCount();
300 v["IrcUserCount"] = ircusercount;
301 v["IrcChannelCount"] = ircchannelcount;
303 QList<QVariant> idlist;
304 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
305 v["Identities"] = idlist;
307 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
311 void CoreSession::storeBufferLastSeen(BufferId buffer, const QDateTime &lastSeen) {
312 Core::setBufferLastSeen(user(), buffer, lastSeen);
315 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
317 QList<Message> msglist;
318 if(v1.type() == QVariant::DateTime) {
322 msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
325 // Send messages out in smaller packages - we don't want to make the signal data too large!
326 for(int i = 0; i < msglist.count(); i++) {
327 log.append(qVariantFromValue(msglist[i]));
328 if(log.count() >= 5) {
329 emit backlogData(id, log, i >= msglist.count() - 1);
333 if(log.count() > 0) emit backlogData(id, log, true);
337 void CoreSession::initScriptEngine() {
338 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
339 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
342 //QScriptValue storage_ = scriptEngine->newQObject(storage);
343 //scriptEngine->globalObject().setProperty("storage", storage_);
346 void CoreSession::scriptRequest(QString script) {
347 emit scriptResult(scriptEngine->evaluate(script).toString());
350 /*** Identity Handling ***/
352 void CoreSession::createIdentity(const Identity &id) {
355 for(i = 1; i <= _identities.count(); i++) {
356 if(!_identities.keys().contains(i)) break;
358 //qDebug() << "found free id" << i;
359 Identity *newId = new Identity(id, this);
361 _identities[i] = newId;
362 signalProxy()->synchronize(newId);
363 CoreUserSettings s(user());
364 s.storeIdentity(*newId);
365 emit identityCreated(*newId);
368 void CoreSession::updateIdentity(const Identity &id) {
369 if(!_identities.contains(id.id())) {
370 qWarning() << "Update request for unknown identity received!";
373 _identities[id.id()]->update(id);
375 CoreUserSettings s(user());
379 void CoreSession::removeIdentity(IdentityId id) {
380 Identity *i = _identities.take(id);
382 emit identityRemoved(id);
383 CoreUserSettings s(user());
384 s.removeIdentity(id);
389 /*** Network Handling ***/
391 void CoreSession::createNetwork(const NetworkInfo &info_) {
392 NetworkInfo info = info_;
395 if(!info.networkId.isValid())
396 Core::createNetwork(user(), info);
398 Q_ASSERT(info.networkId.isValid());
400 id = info.networkId.toInt();
401 Q_ASSERT(!_networks.contains(id));
403 Network *net = new Network(id, this);
404 connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
405 connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
406 net->setNetworkInfo(info);
407 net->setProxy(signalProxy());
409 signalProxy()->synchronize(net);
410 emit networkCreated(id);
413 void CoreSession::updateNetwork(const NetworkInfo &info) {
414 if(!_networks.contains(info.networkId)) {
415 qWarning() << "Update request for unknown network received!";
418 _networks[info.networkId]->setNetworkInfo(info);
419 Core::updateNetwork(user(), info);
422 void CoreSession::removeNetwork(NetworkId id) {
423 // Make sure the network is disconnected!
424 NetworkConnection *conn = _connections.value(id, 0);
426 if(conn->connectionState() != Network::Disconnected) {
427 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
428 conn->disconnectFromIrc();
430 _connections.take(id)->deleteLater(); // TODO make this saner
438 void CoreSession::destroyNetwork(NetworkId id) {
439 Q_ASSERT(!_connections.contains(id));
440 Network *net = _networks.take(id);
441 if(net && Core::removeNetwork(user(), id)) {
442 emit networkRemoved(id);
447 void CoreSession::removeBufferRequested(BufferId bufferId) {
448 BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
449 if(!bufferInfo.isValid()) {
450 qWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
454 if(bufferInfo.type() == BufferInfo::StatusBuffer) {
455 qWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
459 if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
460 Network *net = network(bufferInfo.networkId());
462 IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
464 qWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
468 if(Core::removeBuffer(user(), bufferId))
469 emit bufferRemoved(bufferId);
472 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
473 BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
474 if(bufferId.isValid()) {
475 emit bufferRenamed(bufferId, newName);