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(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
74 p->attachSlot(SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)), this, SLOT(sendBacklog(BufferInfo, QVariant, QVariant)));
75 p->attachSignal(this, SIGNAL(displayMsg(Message)));
76 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
77 p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
78 p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
80 p->attachSignal(this, SIGNAL(sessionDataChanged(const QString &, const QVariant &)), SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)));
81 p->attachSlot(SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)), this, SLOT(storeSessionData(const QString &, const QVariant &)));
83 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
84 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
85 p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
86 p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
87 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
91 foreach(Identity *id, _identities.values()) {
95 // Load and init networks.
96 // FIXME For now we use the old info from sessionData...
98 QVariantMap networks = retrieveSessionData("Networks").toMap();
99 foreach(QString netname, networks.keys()) {
100 QVariantMap network = networks[netname].toMap();
101 NetworkId netid = Core::networkId(user(), netname);
102 Network *net = new Network(netid, this);
103 connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
104 net->setNetworkName(netname);
105 net->setIdentity(1); // FIXME default identity for now
106 net->setCodecForEncoding("ISO-8859-15"); // FIXME
107 net->setCodecForDecoding("ISO-8859-15"); // FIXME
108 QList<QVariantMap> slist;
109 foreach(QVariant v, network["Servers"].toList()) slist << v.toMap();
110 net->setServerList(slist);
112 _networks[netid] = net;
116 // Restore session state
117 if(restoreState) restoreSessionState();
122 CoreSession::~CoreSession() {
126 UserId CoreSession::user() const {
130 Network *CoreSession::network(NetworkId id) const {
131 if(_networks.contains(id)) return _networks[id];
135 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
136 if(_connections.contains(id)) return _connections[id];
140 Identity *CoreSession::identity(IdentityId id) const {
141 if(_identities.contains(id)) return _identities[id];
145 void CoreSession::saveSessionState() const {
148 foreach(NetworkConnection *net, _connections.values()) {
150 m["NetworkId"] = QVariant::fromValue<NetworkId>(net->networkId());
151 m["State"] = net->state();
154 res["CoreBuild"] = Global::quasselBuild;
155 res["ConnectedNetworks"] = conn;
156 CoreUserSettings s(user());
157 s.setSessionState(res);
160 void CoreSession::restoreSessionState() {
161 CoreUserSettings s(user());
162 uint build = s.sessionState().toMap()["CoreBuild"].toUInt();
164 qWarning() << qPrintable(tr("Session state does not exist or is too old!"));
167 QVariantList conn = s.sessionState().toMap()["ConnectedNetworks"].toList();
168 foreach(QVariant v, conn) {
169 NetworkId id = v.toMap()["NetworkId"].value<NetworkId>();
170 if(_networks.keys().contains(id)) connectToNetwork(id, v.toMap()["State"]);
175 void CoreSession::storeSessionData(const QString &key, const QVariant &data) {
176 CoreUserSettings s(user());
177 s.setSessionValue(key, data);
178 sessionData[key] = data;
179 emit sessionDataChanged(key, data);
180 emit sessionDataChanged(key);
183 QVariant CoreSession::retrieveSessionData(const QString &key, const QVariant &def) {
185 if(!sessionData.contains(key)) data = def;
186 else data = sessionData[key];
190 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
191 if(uid == user()) emit bufferInfoUpdated(bufinfo);
195 void CoreSession::connectToNetwork(QString netname, const QVariant &previousState) {
197 foreach(Network *n, _networks.values()) {
198 if(n->networkName() == netname) {
203 qWarning() << "Connect to unknown network requested, ignoring!";
206 connectToNetwork(net->networkId(), previousState);
209 void CoreSession::connectToNetwork(NetworkId id, const QVariant &previousState) {
210 Network *net = network(id);
212 qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
216 NetworkConnection *conn = networkConnection(id);
218 conn = new NetworkConnection(net, this, previousState);
219 _connections[id] = conn;
220 attachNetworkConnection(conn);
221 conn->connectToIrc();
225 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
226 //connect(this, SIGNAL(connectToIrc(QString)), network, SLOT(connectToIrc(QString)));
227 //connect(this, SIGNAL(disconnectFromIrc(QString)), network, SLOT(disconnectFromIrc(QString)));
228 //connect(this, SIGNAL(msgFromGui(uint, QString, QString)), network, SLOT(userInput(uint, QString, QString)));
230 connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
231 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
232 signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
233 signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
235 connect(conn, SIGNAL(displayMsg(Message::Type, QString, QString, QString, quint8)), this, SLOT(recvMessageFromServer(Message::Type, QString, QString, QString, quint8)));
236 connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
238 // TODO add error handling
241 void CoreSession::networkStateRequested() {
244 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
245 QIODevice *device = qobject_cast<QIODevice *>(dev);
247 qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
249 signalProxy()->addPeer(device);
251 reply["MsgType"] = "SessionInit";
252 reply["SessionState"] = sessionState();
253 SignalProxy::writeDataToDevice(device, reply);
257 SignalProxy *CoreSession::signalProxy() const {
261 void CoreSession::networkConnected(NetworkId networkid) {
262 network(networkid)->setConnected(true);
263 Core::bufferInfo(user(), networkConnection(networkid)->networkName()); // create status buffer
266 void CoreSession::networkDisconnected(NetworkId networkid) {
268 // connection should only go away on explicit /part, and handle reconnections etcpp internally otherwise
269 network(networkid)->setConnected(false);
271 Q_ASSERT(_connections.contains(networkid));
272 _connections.take(networkid)->deleteLater();
273 Q_ASSERT(!_connections.contains(networkid));
276 // FIXME switch to BufferId
277 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
278 NetworkConnection *conn = networkConnection(bufinfo.networkId());
280 conn->userInput(bufinfo.buffer(), msg);
282 qWarning() << "Trying to send to unconnected network!";
286 // ALL messages coming pass through these functions before going to the GUI.
287 // So this is the perfect place for storing the backlog and log stuff.
288 void CoreSession::recvMessageFromServer(Message::Type type, QString target, QString text, QString sender, quint8 flags) {
289 NetworkConnection *s = qobject_cast<NetworkConnection*>(this->sender());
292 if((flags & Message::PrivMsg) && !(flags & Message::Self)) {
293 buf = Core::bufferInfo(user(), s->networkName(), nickFromMask(sender));
295 buf = Core::bufferInfo(user(), s->networkName(), target);
297 Message msg(buf, type, text, sender, flags);
298 msg.setMsgId(Core::storeMessage(msg));
299 Q_ASSERT(msg.msgId() != 0);
300 emit displayMsg(msg);
303 void CoreSession::recvStatusMsgFromServer(QString msg) {
304 NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
306 emit displayStatusMsg(s->networkName(), msg);
309 QList<BufferInfo> CoreSession::buffers() const {
310 return Core::requestBuffers(user());
314 QVariant CoreSession::sessionState() {
318 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
319 v["BufferInfos"] = bufs;
320 QVariantList networkids;
321 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
322 v["NetworkIds"] = networkids;
324 quint32 ircusercount = 0;
325 quint32 ircchannelcount = 0;
326 foreach(Network *net, _networks.values()) {
327 ircusercount += net->ircUserCount();
328 ircchannelcount += net->ircChannelCount();
330 v["IrcUserCount"] = ircusercount;
331 v["IrcChannelCount"] = ircchannelcount;
333 QList<QVariant> idlist;
334 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
335 v["Identities"] = idlist;
337 v["SessionData"] = sessionData;
339 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
343 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
345 QList<Message> msglist;
346 if(v1.type() == QVariant::DateTime) {
350 msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
353 // Send messages out in smaller packages - we don't want to make the signal data too large!
354 for(int i = 0; i < msglist.count(); i++) {
355 log.append(qVariantFromValue(msglist[i]));
356 if(log.count() >= 5) {
357 emit backlogData(id, log, i >= msglist.count() - 1);
361 if(log.count() > 0) emit backlogData(id, log, true);
365 void CoreSession::initScriptEngine() {
366 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
367 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
370 //QScriptValue storage_ = scriptEngine->newQObject(storage);
371 //scriptEngine->globalObject().setProperty("storage", storage_);
374 void CoreSession::scriptRequest(QString script) {
375 emit scriptResult(scriptEngine->evaluate(script).toString());
378 void CoreSession::createIdentity(const Identity &id) {
381 for(i = 1; i <= _identities.count(); i++) {
382 if(!_identities.keys().contains(i)) break;
384 //qDebug() << "found free id" << i;
385 Identity *newId = new Identity(id, this);
387 _identities[i] = newId;
388 signalProxy()->synchronize(newId);
389 CoreUserSettings s(user());
390 s.storeIdentity(*newId);
391 emit identityCreated(*newId);
394 void CoreSession::updateIdentity(const Identity &id) {
395 if(!_identities.contains(id.id())) {
396 qWarning() << "Update request for unknown identity received!";
399 _identities[id.id()]->update(id);
401 CoreUserSettings s(user());
405 void CoreSession::removeIdentity(IdentityId id) {
406 Identity *i = _identities.take(id);
408 emit identityRemoved(id);
409 CoreUserSettings s(user());
410 s.removeIdentity(id);