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 foreach(IdentityId id, s.identityIds()) {
50 Identity *i = new Identity(s.identity(id), this);
52 qWarning() << QString("Invalid identity! Removing...");
57 if(_identities.contains(i->id())) {
58 qWarning() << "Duplicate identity, ignoring!";
62 _identities[i->id()] = i;
64 if(!_identities.count()) {
67 i.setIdentityName(tr("Default Identity"));
71 //p->attachSlot(SIGNAL(requestNetworkStates()), this, SLOT(networkStateRequested()));
72 p->attachSlot(SIGNAL(requestConnect(QString)), this, SLOT(connectToNetwork(QString)));
73 p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
74 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
75 p->attachSlot(SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)), this, SLOT(sendBacklog(BufferInfo, QVariant, QVariant)));
76 p->attachSignal(this, SIGNAL(displayMsg(Message)));
77 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
78 p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
79 p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
81 p->attachSignal(this, SIGNAL(sessionDataChanged(const QString &, const QVariant &)), SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)));
82 p->attachSlot(SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)), this, SLOT(storeSessionData(const QString &, const QVariant &)));
84 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
85 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
86 p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
87 p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
88 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
92 foreach(Identity *id, _identities.values()) {
96 // Load and init networks.
97 // FIXME For now we use the old info from sessionData...
99 QVariantMap networks = retrieveSessionData("Networks").toMap();
100 foreach(QString netname, networks.keys()) {
101 QVariantMap network = networks[netname].toMap();
102 NetworkId netid = Core::networkId(user(), netname);
103 Network *net = new Network(netid, this);
104 connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
105 net->setNetworkName(netname);
106 net->setIdentity(1); // FIXME default identity for now
107 net->setCodecForEncoding("ISO-8859-15"); // FIXME
108 net->setCodecForDecoding("ISO-8859-15"); // FIXME
109 QList<QVariantMap> slist;
110 foreach(QVariant v, network["Servers"].toList()) {
112 server["Host"] = v.toMap()["Address"];
113 server["Port"] = v.toMap()["Port"];
116 net->setServerList(slist);
118 _networks[netid] = net;
122 // Restore session state
123 if(restoreState) restoreSessionState();
128 CoreSession::~CoreSession() {
132 UserId CoreSession::user() const {
136 Network *CoreSession::network(NetworkId id) const {
137 if(_networks.contains(id)) return _networks[id];
141 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
142 if(_connections.contains(id)) return _connections[id];
146 Identity *CoreSession::identity(IdentityId id) const {
147 if(_identities.contains(id)) return _identities[id];
151 void CoreSession::saveSessionState() const {
154 foreach(NetworkConnection *net, _connections.values()) {
156 m["NetworkId"] = QVariant::fromValue<NetworkId>(net->networkId());
157 m["State"] = net->state();
160 res["CoreBuild"] = Global::quasselBuild;
161 res["ConnectedNetworks"] = conn;
162 CoreUserSettings s(user());
163 s.setSessionState(res);
166 void CoreSession::restoreSessionState() {
167 CoreUserSettings s(user());
168 uint build = s.sessionState().toMap()["CoreBuild"].toUInt();
170 qWarning() << qPrintable(tr("Session state does not exist or is too old!"));
173 QVariantList conn = s.sessionState().toMap()["ConnectedNetworks"].toList();
174 foreach(QVariant v, conn) {
175 NetworkId id = v.toMap()["NetworkId"].value<NetworkId>();
176 if(_networks.keys().contains(id)) connectToNetwork(id, v.toMap()["State"]);
181 void CoreSession::storeSessionData(const QString &key, const QVariant &data) {
182 CoreUserSettings s(user());
183 s.setSessionValue(key, data);
184 sessionData[key] = data;
185 emit sessionDataChanged(key, data);
186 emit sessionDataChanged(key);
189 QVariant CoreSession::retrieveSessionData(const QString &key, const QVariant &def) {
191 if(!sessionData.contains(key)) data = def;
192 else data = sessionData[key];
196 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
197 if(uid == user()) emit bufferInfoUpdated(bufinfo);
201 void CoreSession::connectToNetwork(QString netname, const QVariant &previousState) {
203 foreach(Network *n, _networks.values()) {
204 if(n->networkName() == netname) {
209 qWarning() << "Connect to unknown network requested, ignoring!";
212 connectToNetwork(net->networkId(), previousState);
215 void CoreSession::connectToNetwork(NetworkId id, const QVariant &previousState) {
216 Network *net = network(id);
218 qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
222 NetworkConnection *conn = networkConnection(id);
224 conn = new NetworkConnection(net, this, previousState);
225 _connections[id] = conn;
226 attachNetworkConnection(conn);
227 conn->connectToIrc();
231 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
232 //connect(this, SIGNAL(connectToIrc(QString)), network, SLOT(connectToIrc(QString)));
233 //connect(this, SIGNAL(disconnectFromIrc(QString)), network, SLOT(disconnectFromIrc(QString)));
234 //connect(this, SIGNAL(msgFromGui(uint, QString, QString)), network, SLOT(userInput(uint, QString, QString)));
236 connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
237 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
238 signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
239 signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
241 connect(conn, SIGNAL(displayMsg(Message::Type, QString, QString, QString, quint8)), this, SLOT(recvMessageFromServer(Message::Type, QString, QString, QString, quint8)));
242 connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
244 // TODO add error handling
247 void CoreSession::disconnectFromNetwork(NetworkId id) {
248 _connections[id]->disconnectFromIrc();
251 void CoreSession::networkStateRequested() {
254 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
255 QIODevice *device = qobject_cast<QIODevice *>(dev);
257 qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
259 signalProxy()->addPeer(device);
261 reply["MsgType"] = "SessionInit";
262 reply["SessionState"] = sessionState();
263 SignalProxy::writeDataToDevice(device, reply);
267 SignalProxy *CoreSession::signalProxy() const {
271 void CoreSession::networkConnected(NetworkId networkid) {
272 network(networkid)->setConnected(true);
273 Core::bufferInfo(user(), networkConnection(networkid)->networkName()); // create status buffer
276 void CoreSession::networkDisconnected(NetworkId networkid) {
278 // connection should only go away on explicit /part, and handle reconnections etcpp internally otherwise
279 network(networkid)->setConnected(false);
281 Q_ASSERT(_connections.contains(networkid));
282 _connections.take(networkid)->deleteLater();
283 Q_ASSERT(!_connections.contains(networkid));
286 // FIXME switch to BufferId
287 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
288 NetworkConnection *conn = networkConnection(bufinfo.networkId());
290 conn->userInput(bufinfo.buffer(), msg);
292 qWarning() << "Trying to send to unconnected network!";
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, QString target, QString text, QString sender, quint8 flags) {
299 NetworkConnection *s = qobject_cast<NetworkConnection*>(this->sender());
302 if((flags & Message::PrivMsg) && !(flags & Message::Self)) {
303 buf = Core::bufferInfo(user(), s->networkName(), nickFromMask(sender));
305 buf = Core::bufferInfo(user(), s->networkName(), target);
307 Message msg(buf, type, text, sender, flags);
308 msg.setMsgId(Core::storeMessage(msg));
309 Q_ASSERT(msg.msgId() != 0);
310 emit displayMsg(msg);
313 void CoreSession::recvStatusMsgFromServer(QString msg) {
314 NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
316 emit displayStatusMsg(s->networkName(), msg);
319 QList<BufferInfo> CoreSession::buffers() const {
320 return Core::requestBuffers(user());
324 QVariant CoreSession::sessionState() {
328 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
329 v["BufferInfos"] = bufs;
330 QVariantList networkids;
331 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
332 v["NetworkIds"] = networkids;
334 quint32 ircusercount = 0;
335 quint32 ircchannelcount = 0;
336 foreach(Network *net, _networks.values()) {
337 ircusercount += net->ircUserCount();
338 ircchannelcount += net->ircChannelCount();
340 v["IrcUserCount"] = ircusercount;
341 v["IrcChannelCount"] = ircchannelcount;
343 QList<QVariant> idlist;
344 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
345 v["Identities"] = idlist;
347 v["SessionData"] = sessionData;
349 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
353 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
355 QList<Message> msglist;
356 if(v1.type() == QVariant::DateTime) {
360 msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
363 // Send messages out in smaller packages - we don't want to make the signal data too large!
364 for(int i = 0; i < msglist.count(); i++) {
365 log.append(qVariantFromValue(msglist[i]));
366 if(log.count() >= 5) {
367 emit backlogData(id, log, i >= msglist.count() - 1);
371 if(log.count() > 0) emit backlogData(id, log, true);
375 void CoreSession::initScriptEngine() {
376 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
377 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
380 //QScriptValue storage_ = scriptEngine->newQObject(storage);
381 //scriptEngine->globalObject().setProperty("storage", storage_);
384 void CoreSession::scriptRequest(QString script) {
385 emit scriptResult(scriptEngine->evaluate(script).toString());
388 void CoreSession::createIdentity(const Identity &id) {
391 for(i = 1; i <= _identities.count(); i++) {
392 if(!_identities.keys().contains(i)) break;
394 //qDebug() << "found free id" << i;
395 Identity *newId = new Identity(id, this);
397 _identities[i] = newId;
398 signalProxy()->synchronize(newId);
399 CoreUserSettings s(user());
400 s.storeIdentity(*newId);
401 emit identityCreated(*newId);
404 void CoreSession::updateIdentity(const Identity &id) {
405 if(!_identities.contains(id.id())) {
406 qWarning() << "Update request for unknown identity received!";
409 _identities[id.id()]->update(id);
411 CoreUserSettings s(user());
415 void CoreSession::removeIdentity(IdentityId id) {
416 Identity *i = _identities.take(id);
418 emit identityRemoved(id);
419 CoreUserSettings s(user());
420 s.removeIdentity(id);