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(disconnected(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 void CoreSession::networkDisconnected(NetworkId networkid) {
277 // connection should only go away on explicit /part, and handle reconnections etcpp internally otherwise
279 //Q_ASSERT(_connections.contains(networkid));
280 if(_connections.contains(networkid)) _connections.take(networkid)->deleteLater();
283 // FIXME switch to BufferId
284 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
285 NetworkConnection *conn = networkConnection(bufinfo.networkId());
287 conn->userInput(bufinfo, msg);
289 qWarning() << "Trying to send to unconnected network!";
293 // ALL messages coming pass through these functions before going to the GUI.
294 // So this is the perfect place for storing the backlog and log stuff.
295 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, quint8 flags) {
296 NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
299 BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
300 Message msg(bufferInfo, type, text, sender, flags);
301 msg.setMsgId(Core::storeMessage(msg));
302 Q_ASSERT(msg.msgId() != 0);
303 emit displayMsg(msg);
306 void CoreSession::recvStatusMsgFromServer(QString msg) {
307 NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
309 emit displayStatusMsg(s->networkName(), msg);
312 QList<BufferInfo> CoreSession::buffers() const {
313 return Core::requestBuffers(user());
317 QVariant CoreSession::sessionState() {
321 foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
322 v["BufferInfos"] = bufs;
323 QVariantList networkids;
324 foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
325 v["NetworkIds"] = networkids;
327 quint32 ircusercount = 0;
328 quint32 ircchannelcount = 0;
329 foreach(Network *net, _networks.values()) {
330 ircusercount += net->ircUserCount();
331 ircchannelcount += net->ircChannelCount();
333 v["IrcUserCount"] = ircusercount;
334 v["IrcChannelCount"] = ircchannelcount;
336 QList<QVariant> idlist;
337 foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
338 v["Identities"] = idlist;
340 //v["Payload"] = QByteArray(100000000, 'a'); // for testing purposes
344 void CoreSession::storeBufferLastSeen(BufferId buffer, const QDateTime &lastSeen) {
345 Core::setBufferLastSeen(user(), buffer, lastSeen);
348 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
350 QList<Message> msglist;
351 if(v1.type() == QVariant::DateTime) {
355 msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
358 // Send messages out in smaller packages - we don't want to make the signal data too large!
359 for(int i = 0; i < msglist.count(); i++) {
360 log.append(qVariantFromValue(msglist[i]));
361 if(log.count() >= 5) {
362 emit backlogData(id, log, i >= msglist.count() - 1);
366 if(log.count() > 0) emit backlogData(id, log, true);
370 void CoreSession::initScriptEngine() {
371 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
372 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
375 //QScriptValue storage_ = scriptEngine->newQObject(storage);
376 //scriptEngine->globalObject().setProperty("storage", storage_);
379 void CoreSession::scriptRequest(QString script) {
380 emit scriptResult(scriptEngine->evaluate(script).toString());
383 /*** Identity Handling ***/
385 void CoreSession::createIdentity(const Identity &id) {
388 for(i = 1; i <= _identities.count(); i++) {
389 if(!_identities.keys().contains(i)) break;
391 //qDebug() << "found free id" << i;
392 Identity *newId = new Identity(id, this);
394 _identities[i] = newId;
395 signalProxy()->synchronize(newId);
396 CoreUserSettings s(user());
397 s.storeIdentity(*newId);
398 emit identityCreated(*newId);
401 void CoreSession::updateIdentity(const Identity &id) {
402 if(!_identities.contains(id.id())) {
403 qWarning() << "Update request for unknown identity received!";
406 _identities[id.id()]->update(id);
408 CoreUserSettings s(user());
412 void CoreSession::removeIdentity(IdentityId id) {
413 Identity *i = _identities.take(id);
415 emit identityRemoved(id);
416 CoreUserSettings s(user());
417 s.removeIdentity(id);
422 /*** Network Handling ***/
424 void CoreSession::createNetwork(const NetworkInfo &info_) {
425 NetworkInfo info = info_;
428 if(!info.networkId.isValid())
429 Core::createNetwork(user(), info);
431 Q_ASSERT(info.networkId.isValid());
433 id = info.networkId.toInt();
434 Q_ASSERT(!_networks.contains(id));
436 Network *net = new Network(id, this);
437 connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
438 connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
439 net->setNetworkInfo(info);
440 net->setProxy(signalProxy());
442 signalProxy()->synchronize(net);
443 emit networkCreated(id);
446 void CoreSession::updateNetwork(const NetworkInfo &info) {
447 if(!_networks.contains(info.networkId)) {
448 qWarning() << "Update request for unknown network received!";
451 _networks[info.networkId]->setNetworkInfo(info); qDebug() << "unlim" << info.unlimitedReconnectRetries << _networks[info.networkId]->unlimitedReconnectRetries();
452 Core::updateNetwork(user(), info);
455 void CoreSession::removeNetwork(NetworkId id) {
456 // Make sure the network is disconnected!
457 NetworkConnection *conn = _connections.value(id, 0);
459 if(conn->connectionState() != Network::Disconnected) {
460 connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
461 conn->disconnectFromIrc();
463 _connections.take(id)->deleteLater(); // TODO make this saner
471 void CoreSession::destroyNetwork(NetworkId id) {
472 Q_ASSERT(!_connections.contains(id));
473 Network *net = _networks.take(id);
474 if(net && Core::removeNetwork(user(), id)) {
475 emit networkRemoved(id);