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 p->attachSlot(SIGNAL(requestConnect(QString)), this, SLOT(connectToNetwork(QString)));
47 p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
48 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
49 p->attachSlot(SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)), this, SLOT(sendBacklog(BufferInfo, QVariant, QVariant)));
50 p->attachSignal(this, SIGNAL(displayMsg(Message)));
51 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
52 p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
53 p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
55 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
56 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
57 p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
58 p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
59 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
61 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
62 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
63 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
64 p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
65 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
70 // Restore session state
71 if(restoreState) restoreSessionState();
76 CoreSession::~CoreSession() {
78 foreach(NetworkConnection *conn, _connections.values()) {
81 foreach(Network *net, _networks.values()) {
86 UserId CoreSession::user() const {
90 Network *CoreSession::network(NetworkId id) const {
91 if(_networks.contains(id)) return _networks[id];
95 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
96 if(_connections.contains(id)) return _connections[id];
100 Identity *CoreSession::identity(IdentityId id) const {
101 if(_identities.contains(id)) return _identities[id];
105 void CoreSession::loadSettings() {
106 CoreUserSettings s(user());
108 foreach(IdentityId id, s.identityIds()) {
109 Identity *i = new Identity(s.identity(id), this);
111 qWarning() << QString("Invalid identity! Removing...");
112 s.removeIdentity(id);
116 if(_identities.contains(i->id())) {
117 qWarning() << "Duplicate identity, ignoring!";
121 _identities[i->id()] = i;
122 signalProxy()->synchronize(i);
124 if(!_identities.count()) {
127 i.setIdentityName(tr("Default Identity"));
132 // migration to pure DB storage
133 QList<NetworkId> netIds = s.networkIds();
134 if(!netIds.isEmpty()) {
135 qDebug() << "Migrating Networksettings to DB Storage for User:" << user();
136 foreach(NetworkId id, netIds) {
137 NetworkInfo info = s.networkInfo(id);
139 // default new options
140 info.useRandomServer = false;
141 info.useAutoReconnect = true;
142 info.autoReconnectInterval = 60;
143 info.autoReconnectRetries = 20;
144 info.useAutoIdentify = false;
145 info.rejoinChannels = true;
147 Core::updateNetwork(user(), info);
148 s.removeNetworkInfo(id);
152 foreach(NetworkInfo info, Core::networks(user())) {
157 void CoreSession::saveSessionState() const {
160 foreach(NetworkConnection *net, _connections.values()) {
162 m["NetworkId"] = QVariant::fromValue<NetworkId>(net->networkId());
163 m["State"] = net->state();
166 res["CoreBuild"] = Global::quasselBuild;
167 res["ConnectedNetworks"] = conn;
168 CoreUserSettings s(user());
169 s.setSessionState(res);
172 void CoreSession::restoreSessionState() {
173 CoreUserSettings s(user());
174 uint build = s.sessionState().toMap()["CoreBuild"].toUInt();
176 qWarning() << qPrintable(tr("Session state does not exist or is too old!"));
179 QVariantList conn = s.sessionState().toMap()["ConnectedNetworks"].toList();
180 foreach(QVariant v, conn) {
181 NetworkId id = v.toMap()["NetworkId"].value<NetworkId>();
182 if(_networks.keys().contains(id)) connectToNetwork(id, v.toMap()["State"]);
186 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
187 if(uid == user()) emit bufferInfoUpdated(bufinfo);
191 void CoreSession::connectToNetwork(QString netname, const QVariant &previousState) {
193 foreach(Network *n, _networks.values()) {
194 if(n->networkName() == netname) {
199 qWarning() << "Connect to unknown network requested, ignoring!";
202 connectToNetwork(net->networkId(), previousState);
205 void CoreSession::connectToNetwork(NetworkId id, const QVariant &previousState) {
206 Network *net = network(id);
208 qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
212 NetworkConnection *conn = networkConnection(id);
214 conn = new NetworkConnection(net, this, previousState);
215 _connections[id] = conn;
216 attachNetworkConnection(conn);
218 conn->connectToIrc();
221 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
222 connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
223 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
225 // I guess we don't need these anymore, client-side can just connect the network's signals directly
226 //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
227 //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
229 connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)),
230 this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)));
231 connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
235 void CoreSession::disconnectFromNetwork(NetworkId id) {
236 if(!_connections.contains(id)) return;
237 _connections[id]->disconnectFromIrc();
240 void CoreSession::networkStateRequested() {
243 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
244 QIODevice *device = qobject_cast<QIODevice *>(dev);
246 qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
248 signalProxy()->addPeer(device);
250 reply["MsgType"] = "SessionInit";
251 reply["SessionState"] = sessionState();
252 SignalProxy::writeDataToDevice(device, reply);
256 SignalProxy *CoreSession::signalProxy() const {
260 // FIXME we need a sane way for creating buffers!
261 void CoreSession::networkConnected(NetworkId networkid) {
262 Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
265 void CoreSession::networkDisconnected(NetworkId networkid) {
267 // connection should only go away on explicit /part, and handle reconnections etcpp internally otherwise
269 Q_ASSERT(_connections.contains(networkid));
270 _connections.take(networkid)->deleteLater();
273 // FIXME switch to BufferId
274 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
275 NetworkConnection *conn = networkConnection(bufinfo.networkId());
277 conn->userInput(bufinfo, msg);
279 qWarning() << "Trying to send to unconnected network!";
283 // ALL messages coming pass through these functions before going to the GUI.
284 // So this is the perfect place for storing the backlog and log stuff.
285 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, quint8 flags) {
286 NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
289 BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
290 Message msg(bufferInfo, type, text, sender, flags);
291 msg.setMsgId(Core::storeMessage(msg));
292 Q_ASSERT(msg.msgId() != 0);
293 emit displayMsg(msg);
296 void CoreSession::recvStatusMsgFromServer(QString msg) {
297 NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
299 emit displayStatusMsg(s->networkName(), msg);
302 QList<BufferInfo> CoreSession::buffers() const {
303 return Core::requestBuffers(user());
307 QVariant CoreSession::sessionState() {
311 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
312 v["BufferInfos"] = bufs;
313 QVariantList networkids;
314 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
315 v["NetworkIds"] = networkids;
317 quint32 ircusercount = 0;
318 quint32 ircchannelcount = 0;
319 foreach(Network *net, _networks.values()) {
320 ircusercount += net->ircUserCount();
321 ircchannelcount += net->ircChannelCount();
323 v["IrcUserCount"] = ircusercount;
324 v["IrcChannelCount"] = ircchannelcount;
326 QList<QVariant> idlist;
327 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
328 v["Identities"] = idlist;
330 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
334 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
336 QList<Message> msglist;
337 if(v1.type() == QVariant::DateTime) {
341 msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
344 // Send messages out in smaller packages - we don't want to make the signal data too large!
345 for(int i = 0; i < msglist.count(); i++) {
346 log.append(qVariantFromValue(msglist[i]));
347 if(log.count() >= 5) {
348 emit backlogData(id, log, i >= msglist.count() - 1);
352 if(log.count() > 0) emit backlogData(id, log, true);
356 void CoreSession::initScriptEngine() {
357 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
358 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
361 //QScriptValue storage_ = scriptEngine->newQObject(storage);
362 //scriptEngine->globalObject().setProperty("storage", storage_);
365 void CoreSession::scriptRequest(QString script) {
366 emit scriptResult(scriptEngine->evaluate(script).toString());
369 /*** Identity Handling ***/
371 void CoreSession::createIdentity(const Identity &id) {
374 for(i = 1; i <= _identities.count(); i++) {
375 if(!_identities.keys().contains(i)) break;
377 //qDebug() << "found free id" << i;
378 Identity *newId = new Identity(id, this);
380 _identities[i] = newId;
381 signalProxy()->synchronize(newId);
382 CoreUserSettings s(user());
383 s.storeIdentity(*newId);
384 emit identityCreated(*newId);
387 void CoreSession::updateIdentity(const Identity &id) {
388 if(!_identities.contains(id.id())) {
389 qWarning() << "Update request for unknown identity received!";
392 _identities[id.id()]->update(id);
394 CoreUserSettings s(user());
398 void CoreSession::removeIdentity(IdentityId id) {
399 Identity *i = _identities.take(id);
401 emit identityRemoved(id);
402 CoreUserSettings s(user());
403 s.removeIdentity(id);
408 /*** Network Handling ***/
410 void CoreSession::createNetwork(const NetworkInfo &info_) {
411 NetworkInfo info = info_;
414 if(!info.networkId.isValid())
415 Core::createNetwork(user(), info);
417 Q_ASSERT(info.networkId.isValid());
419 id = info.networkId.toInt();
420 Q_ASSERT(!_networks.contains(id));
422 Network *net = new Network(id, this);
423 connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
424 connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
425 net->setNetworkInfo(info);
426 net->setProxy(signalProxy());
428 signalProxy()->synchronize(net);
429 emit networkCreated(id);
432 void CoreSession::updateNetwork(const NetworkInfo &info) {
433 if(!_networks.contains(info.networkId)) {
434 qWarning() << "Update request for unknown network received!";
437 _networks[info.networkId]->setNetworkInfo(info);
438 Core::updateNetwork(user(), info);
441 void CoreSession::removeNetwork(NetworkId id) {
442 // Make sure the network is disconnected!
443 NetworkConnection *conn = _connections.value(id, 0);
445 if(conn->connectionState() != Network::Disconnected) {
446 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
447 conn->disconnectFromIrc();
449 _connections.take(id)->deleteLater(); // TODO make this saner
457 void CoreSession::destroyNetwork(NetworkId id) {
458 Q_ASSERT(!_connections.contains(id));
459 Network *net = _networks.take(id);
460 if(net && Core::removeNetwork(user(), id)) {
461 emit networkRemoved(id);