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(requestConnect(QString)), this, SLOT(connectToNetwork(QString)));
49 p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
50 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
51 p->attachSlot(SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)), this, SLOT(sendBacklog(BufferInfo, QVariant, QVariant)));
52 p->attachSignal(this, SIGNAL(displayMsg(Message)));
53 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
54 p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
55 p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
57 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
58 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
59 p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
60 p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
61 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
63 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
64 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
65 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
66 p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
67 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
73 //QHash<BufferId, QDateTime> lastSeenHash = Core::bufferLastSeenDates(user());
74 //foreach(BufferId id, lastSeenHash.keys()) _bufferSyncer->requestSetLastSeen(id, lastSeenHash[id]);
75 // FIXME connect(_bufferSyncer, SIGNAL(lastSeenSet(BufferId, const QDateTime &)), this, SLOT(storeBufferLastSeen(BufferId, const QDateTime &)));
76 p->synchronize(_bufferSyncer);
78 // Restore session state
79 if(restoreState) restoreSessionState();
84 CoreSession::~CoreSession() {
86 foreach(NetworkConnection *conn, _connections.values()) {
89 foreach(Network *net, _networks.values()) {
94 UserId CoreSession::user() const {
98 Network *CoreSession::network(NetworkId id) const {
99 if(_networks.contains(id)) return _networks[id];
103 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
104 if(_connections.contains(id)) return _connections[id];
108 Identity *CoreSession::identity(IdentityId id) const {
109 if(_identities.contains(id)) return _identities[id];
113 void CoreSession::loadSettings() {
114 CoreUserSettings s(user());
116 foreach(IdentityId id, s.identityIds()) {
117 Identity *i = new Identity(s.identity(id), this);
119 qWarning() << QString("Invalid identity! Removing...");
120 s.removeIdentity(id);
124 if(_identities.contains(i->id())) {
125 qWarning() << "Duplicate identity, ignoring!";
129 _identities[i->id()] = i;
130 signalProxy()->synchronize(i);
132 if(!_identities.count()) {
135 i.setIdentityName(tr("Default Identity"));
140 // migration to pure DB storage
141 QList<NetworkId> netIds = s.networkIds();
142 if(!netIds.isEmpty()) {
143 qDebug() << "Migrating Networksettings to DB Storage for User:" << user();
144 foreach(NetworkId id, netIds) {
145 NetworkInfo info = s.networkInfo(id);
147 // default new options
148 info.useRandomServer = false;
149 info.useAutoReconnect = true;
150 info.autoReconnectInterval = 60;
151 info.autoReconnectRetries = 20;
152 info.unlimitedReconnectRetries = false;
153 info.useAutoIdentify = false;
154 info.autoIdentifyService = "NickServ";
155 info.rejoinChannels = true;
157 Core::updateNetwork(user(), info);
158 s.removeNetworkInfo(id);
162 foreach(NetworkInfo info, Core::networks(user())) {
167 void CoreSession::saveSessionState() const {
170 foreach(NetworkConnection *net, _connections.values()) {
172 m["NetworkId"] = QVariant::fromValue<NetworkId>(net->networkId());
173 m["State"] = net->state();
176 res["CoreBuild"] = Global::quasselBuild;
177 res["ConnectedNetworks"] = conn;
178 CoreUserSettings s(user());
179 s.setSessionState(res);
182 void CoreSession::restoreSessionState() {
183 CoreUserSettings s(user());
184 uint build = s.sessionState().toMap()["CoreBuild"].toUInt();
186 qWarning() << qPrintable(tr("Session state does not exist or is too old!"));
189 QVariantList conn = s.sessionState().toMap()["ConnectedNetworks"].toList();
190 foreach(QVariant v, conn) {
191 NetworkId id = v.toMap()["NetworkId"].value<NetworkId>();
192 if(_networks.keys().contains(id)) connectToNetwork(id, v.toMap()["State"]);
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);
228 conn->connectToIrc();
231 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
232 connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
233 connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
235 // I guess we don't need these anymore, client-side can just connect the network's signals directly
236 //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
237 //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
239 connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)),
240 this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)));
241 connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
245 void CoreSession::disconnectFromNetwork(NetworkId id) {
246 if(!_connections.contains(id)) return;
247 _connections[id]->disconnectFromIrc();
250 void CoreSession::networkStateRequested() {
253 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
254 QIODevice *device = qobject_cast<QIODevice *>(dev);
256 qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
258 signalProxy()->addPeer(device);
260 reply["MsgType"] = "SessionInit";
261 reply["SessionState"] = sessionState();
262 SignalProxy::writeDataToDevice(device, reply);
266 SignalProxy *CoreSession::signalProxy() const {
270 // FIXME we need a sane way for creating buffers!
271 void CoreSession::networkConnected(NetworkId networkid) {
272 Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
275 // called now only on /quit and requested disconnects, not on normal disconnects!
276 void CoreSession::networkDisconnected(NetworkId networkid) {
277 if(_connections.contains(networkid)) _connections.take(networkid)->deleteLater();
280 // FIXME switch to BufferId
281 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
282 NetworkConnection *conn = networkConnection(bufinfo.networkId());
284 conn->userInput(bufinfo, msg);
286 qWarning() << "Trying to send to unconnected network!";
290 // ALL messages coming pass through these functions before going to the GUI.
291 // So this is the perfect place for storing the backlog and log stuff.
292 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, quint8 flags) {
293 NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
296 BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
297 Message msg(bufferInfo, 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["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
341 void CoreSession::storeBufferLastSeen(BufferId buffer, const QDateTime &lastSeen) {
342 Core::setBufferLastSeen(user(), buffer, lastSeen);
345 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
347 QList<Message> msglist;
348 if(v1.type() == QVariant::DateTime) {
352 msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
355 // Send messages out in smaller packages - we don't want to make the signal data too large!
356 for(int i = 0; i < msglist.count(); i++) {
357 log.append(qVariantFromValue(msglist[i]));
358 if(log.count() >= 5) {
359 emit backlogData(id, log, i >= msglist.count() - 1);
363 if(log.count() > 0) emit backlogData(id, log, true);
367 void CoreSession::initScriptEngine() {
368 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
369 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
372 //QScriptValue storage_ = scriptEngine->newQObject(storage);
373 //scriptEngine->globalObject().setProperty("storage", storage_);
376 void CoreSession::scriptRequest(QString script) {
377 emit scriptResult(scriptEngine->evaluate(script).toString());
380 /*** Identity Handling ***/
382 void CoreSession::createIdentity(const Identity &id) {
385 for(i = 1; i <= _identities.count(); i++) {
386 if(!_identities.keys().contains(i)) break;
388 //qDebug() << "found free id" << i;
389 Identity *newId = new Identity(id, this);
391 _identities[i] = newId;
392 signalProxy()->synchronize(newId);
393 CoreUserSettings s(user());
394 s.storeIdentity(*newId);
395 emit identityCreated(*newId);
398 void CoreSession::updateIdentity(const Identity &id) {
399 if(!_identities.contains(id.id())) {
400 qWarning() << "Update request for unknown identity received!";
403 _identities[id.id()]->update(id);
405 CoreUserSettings s(user());
409 void CoreSession::removeIdentity(IdentityId id) {
410 Identity *i = _identities.take(id);
412 emit identityRemoved(id);
413 CoreUserSettings s(user());
414 s.removeIdentity(id);
419 /*** Network Handling ***/
421 void CoreSession::createNetwork(const NetworkInfo &info_) {
422 NetworkInfo info = info_;
425 if(!info.networkId.isValid())
426 Core::createNetwork(user(), info);
428 Q_ASSERT(info.networkId.isValid());
430 id = info.networkId.toInt();
431 Q_ASSERT(!_networks.contains(id));
433 Network *net = new Network(id, this);
434 connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
435 connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
436 net->setNetworkInfo(info);
437 net->setProxy(signalProxy());
439 signalProxy()->synchronize(net);
440 emit networkCreated(id);
443 void CoreSession::updateNetwork(const NetworkInfo &info) {
444 if(!_networks.contains(info.networkId)) {
445 qWarning() << "Update request for unknown network received!";
448 _networks[info.networkId]->setNetworkInfo(info);
449 Core::updateNetwork(user(), info);
452 void CoreSession::removeNetwork(NetworkId id) {
453 // Make sure the network is disconnected!
454 NetworkConnection *conn = _connections.value(id, 0);
456 if(conn->connectionState() != Network::Disconnected) {
457 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
458 conn->disconnectFromIrc();
460 _connections.take(id)->deleteLater(); // TODO make this saner
468 void CoreSession::destroyNetwork(NetworkId id) {
469 Q_ASSERT(!_connections.contains(id));
470 Network *net = _networks.take(id);
471 if(net && Core::removeNetwork(user(), id)) {
472 emit networkRemoved(id);