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 ***************************************************************************/
22 #include "coresession.h"
23 #include "networkconnection.h"
25 #include "signalproxy.h"
30 #include "ircchannel.h"
34 #include "coreusersettings.h"
38 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent) : QObject(parent),
40 _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
41 scriptEngine(new QScriptEngine(this))
44 SignalProxy *p = signalProxy();
46 CoreUserSettings s(user());
47 sessionData = s.sessionData();
49 p->attachSlot(SIGNAL(requestConnect(QString)), this, SLOT(connectToNetwork(QString)));
50 p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
51 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
52 p->attachSlot(SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)), this, SLOT(sendBacklog(BufferInfo, QVariant, QVariant)));
53 p->attachSignal(this, SIGNAL(displayMsg(Message)));
54 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
55 p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
56 p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
58 p->attachSignal(this, SIGNAL(sessionDataChanged(const QString &, const QVariant &)), SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)));
59 p->attachSlot(SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)), this, SLOT(storeSessionData(const QString &, const QVariant &)));
61 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
62 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
63 p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
64 p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
65 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
67 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
68 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
69 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
70 p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
71 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
76 // Restore session state
77 if(restoreState) restoreSessionState();
82 CoreSession::~CoreSession() {
84 foreach(NetworkConnection *conn, _connections.values()) {
87 foreach(Network *net, _networks.values()) {
92 UserId CoreSession::user() const {
96 Network *CoreSession::network(NetworkId id) const {
97 if(_networks.contains(id)) return _networks[id];
101 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
102 if(_connections.contains(id)) return _connections[id];
106 Identity *CoreSession::identity(IdentityId id) const {
107 if(_identities.contains(id)) return _identities[id];
111 void CoreSession::loadSettings() {
112 CoreUserSettings s(user());
114 foreach(IdentityId id, s.identityIds()) {
115 Identity *i = new Identity(s.identity(id), this);
117 qWarning() << QString("Invalid identity! Removing...");
118 s.removeIdentity(id);
122 if(_identities.contains(i->id())) {
123 qWarning() << "Duplicate identity, ignoring!";
127 _identities[i->id()] = i;
128 signalProxy()->synchronize(i);
130 if(!_identities.count()) {
133 i.setIdentityName(tr("Default Identity"));
137 foreach(NetworkId id, s.networkIds()) {
138 NetworkInfo info = s.networkInfo(id);
139 createNetwork(info, true);
142 // FIXME Migrate old settings if available...
143 if(!_networks.count()) {
144 QVariantMap networks = retrieveSessionData("Networks").toMap();
145 if(networks.keys().count()) {
146 qWarning() << "Migrating your old network settings to the new format!";
147 foreach(QString netname, networks.keys()) {
148 QVariantMap network = networks[netname].toMap();
149 NetworkId netid = Core::networkId(user(), netname);
151 info.networkId = netid;
152 info.networkName = netname;
154 info.codecForEncoding = "ISO-8859-15";
155 info.codecForDecoding = "ISO-8859-15";
157 foreach(QVariant v, network["Servers"].toList()) {
159 server["Host"] = v.toMap()["Address"];
160 server["Port"] = v.toMap()["Port"];
163 info.serverList = slist;
164 createNetwork(info, true);
170 void CoreSession::saveSessionState() const {
173 foreach(NetworkConnection *net, _connections.values()) {
175 m["NetworkId"] = QVariant::fromValue<NetworkId>(net->networkId());
176 m["State"] = net->state();
179 res["CoreBuild"] = Global::quasselBuild;
180 res["ConnectedNetworks"] = conn;
181 CoreUserSettings s(user());
182 s.setSessionState(res);
185 void CoreSession::restoreSessionState() {
186 CoreUserSettings s(user());
187 uint build = s.sessionState().toMap()["CoreBuild"].toUInt();
189 qWarning() << qPrintable(tr("Session state does not exist or is too old!"));
192 QVariantList conn = s.sessionState().toMap()["ConnectedNetworks"].toList();
193 foreach(QVariant v, conn) {
194 NetworkId id = v.toMap()["NetworkId"].value<NetworkId>();
195 if(_networks.keys().contains(id)) connectToNetwork(id, v.toMap()["State"]);
200 void CoreSession::storeSessionData(const QString &key, const QVariant &data) {
201 CoreUserSettings s(user());
202 s.setSessionValue(key, data);
203 sessionData[key] = data;
204 emit sessionDataChanged(key, data);
205 emit sessionDataChanged(key);
208 QVariant CoreSession::retrieveSessionData(const QString &key, const QVariant &def) {
210 if(!sessionData.contains(key)) data = def;
211 else data = sessionData[key];
215 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
216 if(uid == user()) emit bufferInfoUpdated(bufinfo);
220 void CoreSession::connectToNetwork(QString netname, const QVariant &previousState) {
222 foreach(Network *n, _networks.values()) {
223 if(n->networkName() == netname) {
228 qWarning() << "Connect to unknown network requested, ignoring!";
231 connectToNetwork(net->networkId(), previousState);
234 void CoreSession::connectToNetwork(NetworkId id, const QVariant &previousState) {
235 Network *net = network(id);
237 qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
241 NetworkConnection *conn = networkConnection(id);
243 conn = new NetworkConnection(net, this, previousState);
244 _connections[id] = conn;
245 attachNetworkConnection(conn);
247 conn->connectToIrc();
250 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
251 connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
252 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
254 // I guess we don't need these anymore, client-side can just connect the network's signals directly
255 //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
256 //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
258 connect(conn, SIGNAL(displayMsg(Message::Type, QString, QString, QString, quint8)), this, SLOT(recvMessageFromServer(Message::Type, QString, QString, QString, quint8)));
259 connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
263 void CoreSession::disconnectFromNetwork(NetworkId id) {
264 if(!_connections.contains(id)) return;
265 _connections[id]->disconnectFromIrc();
268 void CoreSession::networkStateRequested() {
271 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
272 QIODevice *device = qobject_cast<QIODevice *>(dev);
274 qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
276 signalProxy()->addPeer(device);
278 reply["MsgType"] = "SessionInit";
279 reply["SessionState"] = sessionState();
280 SignalProxy::writeDataToDevice(device, reply);
284 SignalProxy *CoreSession::signalProxy() const {
288 // FIXME we need a sane way for creating buffers!
289 void CoreSession::networkConnected(NetworkId networkid) {
290 Core::bufferInfo(user(), networkConnection(networkid)->networkName()); // create status buffer
293 void CoreSession::networkDisconnected(NetworkId networkid) {
295 // connection should only go away on explicit /part, and handle reconnections etcpp internally otherwise
297 Q_ASSERT(_connections.contains(networkid));
298 _connections.take(networkid)->deleteLater();
301 // FIXME switch to BufferId
302 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
303 NetworkConnection *conn = networkConnection(bufinfo.networkId());
305 conn->userInput(bufinfo.buffer(), msg);
307 qWarning() << "Trying to send to unconnected network!";
311 // ALL messages coming pass through these functions before going to the GUI.
312 // So this is the perfect place for storing the backlog and log stuff.
313 void CoreSession::recvMessageFromServer(Message::Type type, QString target, QString text, QString sender, quint8 flags) {
314 NetworkConnection *s = qobject_cast<NetworkConnection*>(this->sender());
317 if((flags & Message::PrivMsg) && !(flags & Message::Self)) {
318 buf = Core::bufferInfo(user(), s->networkName(), nickFromMask(sender));
320 buf = Core::bufferInfo(user(), s->networkName(), target);
322 Message msg(buf, type, text, sender, flags);
323 msg.setMsgId(Core::storeMessage(msg));
324 Q_ASSERT(msg.msgId() != 0);
325 emit displayMsg(msg);
328 void CoreSession::recvStatusMsgFromServer(QString msg) {
329 NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
331 emit displayStatusMsg(s->networkName(), msg);
334 QList<BufferInfo> CoreSession::buffers() const {
335 return Core::requestBuffers(user());
339 QVariant CoreSession::sessionState() {
343 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
344 v["BufferInfos"] = bufs;
345 QVariantList networkids;
346 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
347 v["NetworkIds"] = networkids;
349 quint32 ircusercount = 0;
350 quint32 ircchannelcount = 0;
351 foreach(Network *net, _networks.values()) {
352 ircusercount += net->ircUserCount();
353 ircchannelcount += net->ircChannelCount();
355 v["IrcUserCount"] = ircusercount;
356 v["IrcChannelCount"] = ircchannelcount;
358 QList<QVariant> idlist;
359 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
360 v["Identities"] = idlist;
362 v["SessionData"] = sessionData;
364 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
368 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
370 QList<Message> msglist;
371 if(v1.type() == QVariant::DateTime) {
375 msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
378 // Send messages out in smaller packages - we don't want to make the signal data too large!
379 for(int i = 0; i < msglist.count(); i++) {
380 log.append(qVariantFromValue(msglist[i]));
381 if(log.count() >= 5) {
382 emit backlogData(id, log, i >= msglist.count() - 1);
386 if(log.count() > 0) emit backlogData(id, log, true);
390 void CoreSession::initScriptEngine() {
391 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
392 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
395 //QScriptValue storage_ = scriptEngine->newQObject(storage);
396 //scriptEngine->globalObject().setProperty("storage", storage_);
399 void CoreSession::scriptRequest(QString script) {
400 emit scriptResult(scriptEngine->evaluate(script).toString());
403 /*** Identity Handling ***/
405 void CoreSession::createIdentity(const Identity &id) {
408 for(i = 1; i <= _identities.count(); i++) {
409 if(!_identities.keys().contains(i)) break;
411 //qDebug() << "found free id" << i;
412 Identity *newId = new Identity(id, this);
414 _identities[i] = newId;
415 signalProxy()->synchronize(newId);
416 CoreUserSettings s(user());
417 s.storeIdentity(*newId);
418 emit identityCreated(*newId);
421 void CoreSession::updateIdentity(const Identity &id) {
422 if(!_identities.contains(id.id())) {
423 qWarning() << "Update request for unknown identity received!";
426 _identities[id.id()]->update(id);
428 CoreUserSettings s(user());
432 void CoreSession::removeIdentity(IdentityId id) {
433 Identity *i = _identities.take(id);
435 emit identityRemoved(id);
436 CoreUserSettings s(user());
437 s.removeIdentity(id);
442 /*** Network Handling ***/
444 void CoreSession::createNetwork(const NetworkInfo &_info, bool useId) {
445 NetworkInfo info = _info;
447 if(useId && info.networkId > 0) id = info.networkId.toInt();
449 for(id = 1; id <= _networks.count(); id++) {
450 if(!_networks.keys().contains(id)) break;
452 //qDebug() << "found free id" << i;
455 Network *net = new Network(id, this);
456 connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
457 connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
458 net->setNetworkInfo(info);
459 net->setProxy(signalProxy());
461 signalProxy()->synchronize(net);
462 CoreUserSettings s(user());
463 s.storeNetworkInfo(info);
464 emit networkCreated(id);
467 void CoreSession::updateNetwork(const NetworkInfo &info) {
468 if(!_networks.contains(info.networkId)) {
469 qWarning() << "Update request for unknown network received!";
472 _networks[info.networkId]->setNetworkInfo(info);
473 CoreUserSettings s(user());
474 s.storeNetworkInfo(info);
477 void CoreSession::removeNetwork(NetworkId id) {
478 Network *net = _networks.take(id);
480 emit networkRemoved(id);
481 CoreUserSettings s(user());
482 s.removeNetworkInfo(id);