Networks can now be removed even when they're connected.
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "core.h"
22 #include "coresession.h"
23 #include "networkconnection.h"
24
25 #include "signalproxy.h"
26 #include "storage.h"
27
28 #include "network.h"
29 #include "ircuser.h"
30 #include "ircchannel.h"
31 #include "identity.h"
32
33 #include "util.h"
34 #include "coreusersettings.h"
35
36 #include <QtScript>
37
38 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent) : QObject(parent),
39     _user(uid),
40     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
41     scriptEngine(new QScriptEngine(this))
42 {
43
44   SignalProxy *p = signalProxy();
45
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)));
54
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)));
60
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)));
66
67   loadSettings();
68   initScriptEngine();
69
70   // Restore session state
71   if(restoreState) restoreSessionState();
72
73   emit initialized();
74 }
75
76 CoreSession::~CoreSession() {
77   saveSessionState();
78   foreach(NetworkConnection *conn, _connections.values()) {
79     delete conn;
80   }
81   foreach(Network *net, _networks.values()) {
82     delete net;
83   }
84 }
85
86 UserId CoreSession::user() const {
87   return _user;
88 }
89
90 Network *CoreSession::network(NetworkId id) const {
91   if(_networks.contains(id)) return _networks[id];
92   return 0;
93 }
94
95 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
96   if(_connections.contains(id)) return _connections[id];
97   return 0;
98 }
99
100 Identity *CoreSession::identity(IdentityId id) const {
101   if(_identities.contains(id)) return _identities[id];
102   return 0;
103 }
104
105 void CoreSession::loadSettings() {
106   CoreUserSettings s(user());
107
108   foreach(IdentityId id, s.identityIds()) {
109     Identity *i = new Identity(s.identity(id), this);
110     if(!i->isValid()) {
111       qWarning() << QString("Invalid identity! Removing...");
112       s.removeIdentity(id);
113       delete i;
114       continue;
115     }
116     if(_identities.contains(i->id())) {
117       qWarning() << "Duplicate identity, ignoring!";
118       delete i;
119       continue;
120     }
121     _identities[i->id()] = i;
122     signalProxy()->synchronize(i);
123   }
124   if(!_identities.count()) {
125     Identity i(1);
126     i.setToDefaults();
127     i.setIdentityName(tr("Default Identity"));
128     createIdentity(i);
129   }
130
131
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);
138       Core::updateNetwork(user(), info);
139       s.removeNetworkInfo(id);
140     }
141   }
142
143   foreach(NetworkInfo info, Core::networks(user())) {
144     createNetwork(info);
145   }
146 }
147
148 void CoreSession::saveSessionState() const {
149   QVariantMap res;
150   QVariantList conn;
151   foreach(NetworkConnection *net, _connections.values()) {
152     QVariantMap m;
153     m["NetworkId"] = QVariant::fromValue<NetworkId>(net->networkId());
154     m["State"] = net->state();
155     conn << m;
156   }
157   res["CoreBuild"] = Global::quasselBuild;
158   res["ConnectedNetworks"] = conn;
159   CoreUserSettings s(user());
160   s.setSessionState(res);
161 }
162
163 void CoreSession::restoreSessionState() {
164   CoreUserSettings s(user());
165   uint build = s.sessionState().toMap()["CoreBuild"].toUInt();
166   if(build < 362) {
167     qWarning() << qPrintable(tr("Session state does not exist or is too old!"));
168     return;
169   }
170   QVariantList conn = s.sessionState().toMap()["ConnectedNetworks"].toList();
171   foreach(QVariant v, conn) {
172     NetworkId id = v.toMap()["NetworkId"].value<NetworkId>();
173     if(_networks.keys().contains(id)) connectToNetwork(id, v.toMap()["State"]);
174   }
175 }
176
177 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
178   if(uid == user()) emit bufferInfoUpdated(bufinfo);
179 }
180
181 // FIXME remove
182 void CoreSession::connectToNetwork(QString netname, const QVariant &previousState) {
183   Network *net = 0;
184   foreach(Network *n, _networks.values()) {
185     if(n->networkName() == netname) {
186       net = n; break;
187     }
188   }
189   if(!net) {
190     qWarning() << "Connect to unknown network requested, ignoring!";
191     return;
192   }
193   connectToNetwork(net->networkId(), previousState);
194 }
195
196 void CoreSession::connectToNetwork(NetworkId id, const QVariant &previousState) {
197   Network *net = network(id);
198   if(!net) {
199     qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
200     return;
201   }
202
203   NetworkConnection *conn = networkConnection(id);
204   if(!conn) {
205     conn = new NetworkConnection(net, this, previousState);
206     _connections[id] = conn;
207     attachNetworkConnection(conn);
208   }
209   conn->connectToIrc();
210 }
211
212 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
213   connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
214   connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
215
216   // I guess we don't need these anymore, client-side can just connect the network's signals directly
217   //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
218   //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
219
220   connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)),
221           this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)));
222   connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
223
224 }
225
226 void CoreSession::disconnectFromNetwork(NetworkId id) {
227   if(!_connections.contains(id)) return;
228   _connections[id]->disconnectFromIrc();
229 }
230
231 void CoreSession::networkStateRequested() {
232 }
233
234 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
235   QIODevice *device = qobject_cast<QIODevice *>(dev);
236   if(!device) {
237     qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
238   } else {
239     signalProxy()->addPeer(device);
240     QVariantMap reply;
241     reply["MsgType"] = "SessionInit";
242     reply["SessionState"] = sessionState();
243     SignalProxy::writeDataToDevice(device, reply);
244   }
245 }
246
247 SignalProxy *CoreSession::signalProxy() const {
248   return _signalProxy;
249 }
250
251 // FIXME we need a sane way for creating buffers!
252 void CoreSession::networkConnected(NetworkId networkid) {
253   Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
254 }
255
256 void CoreSession::networkDisconnected(NetworkId networkid) {
257   // FIXME
258   // connection should only go away on explicit /part, and handle reconnections etcpp internally otherwise
259
260   Q_ASSERT(_connections.contains(networkid));
261   _connections.take(networkid)->deleteLater();
262 }
263
264 // FIXME switch to BufferId
265 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
266   NetworkConnection *conn = networkConnection(bufinfo.networkId());
267   if(conn) {
268     conn->userInput(bufinfo, msg);
269   } else {
270     qWarning() << "Trying to send to unconnected network!";
271   }
272 }
273
274 // ALL messages coming pass through these functions before going to the GUI.
275 // So this is the perfect place for storing the backlog and log stuff.
276 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, quint8 flags) {
277   NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
278   Q_ASSERT(netCon);
279   
280   BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
281   Message msg(bufferInfo, type, text, sender, flags);
282   msg.setMsgId(Core::storeMessage(msg));
283   Q_ASSERT(msg.msgId() != 0);
284   emit displayMsg(msg);
285 }
286
287 void CoreSession::recvStatusMsgFromServer(QString msg) {
288   NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
289   Q_ASSERT(s);
290   emit displayStatusMsg(s->networkName(), msg);
291 }
292
293 QList<BufferInfo> CoreSession::buffers() const {
294   return Core::requestBuffers(user());
295 }
296
297
298 QVariant CoreSession::sessionState() {
299   QVariantMap v;
300
301   QVariantList bufs;
302   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
303   v["BufferInfos"] = bufs;
304   QVariantList networkids;
305   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
306   v["NetworkIds"] = networkids;
307
308   quint32 ircusercount = 0;
309   quint32 ircchannelcount = 0;
310   foreach(Network *net, _networks.values()) {
311     ircusercount += net->ircUserCount();
312     ircchannelcount += net->ircChannelCount();
313   }
314   v["IrcUserCount"] = ircusercount;
315   v["IrcChannelCount"] = ircchannelcount;
316
317   QList<QVariant> idlist;
318   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
319   v["Identities"] = idlist;
320
321   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
322   return v;
323 }
324
325 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
326   QList<QVariant> log;
327   QList<Message> msglist;
328   if(v1.type() == QVariant::DateTime) {
329
330
331   } else {
332     msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
333   }
334
335   // Send messages out in smaller packages - we don't want to make the signal data too large!
336   for(int i = 0; i < msglist.count(); i++) {
337     log.append(qVariantFromValue(msglist[i]));
338     if(log.count() >= 5) {
339       emit backlogData(id, log, i >= msglist.count() - 1);
340       log.clear();
341     }
342   }
343   if(log.count() > 0) emit backlogData(id, log, true);
344 }
345
346
347 void CoreSession::initScriptEngine() {
348   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
349   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
350
351   // FIXME
352   //QScriptValue storage_ = scriptEngine->newQObject(storage);
353   //scriptEngine->globalObject().setProperty("storage", storage_);
354 }
355
356 void CoreSession::scriptRequest(QString script) {
357   emit scriptResult(scriptEngine->evaluate(script).toString());
358 }
359
360 /*** Identity Handling ***/
361
362 void CoreSession::createIdentity(const Identity &id) {
363   // find free ID
364   int i;
365   for(i = 1; i <= _identities.count(); i++) {
366     if(!_identities.keys().contains(i)) break;
367   }
368   //qDebug() << "found free id" << i;
369   Identity *newId = new Identity(id, this);
370   newId->setId(i);
371   _identities[i] = newId;
372   signalProxy()->synchronize(newId);
373   CoreUserSettings s(user());
374   s.storeIdentity(*newId);
375   emit identityCreated(*newId);
376 }
377
378 void CoreSession::updateIdentity(const Identity &id) {
379   if(!_identities.contains(id.id())) {
380     qWarning() << "Update request for unknown identity received!";
381     return;
382   }
383   _identities[id.id()]->update(id);
384
385   CoreUserSettings s(user());
386   s.storeIdentity(id);
387 }
388
389 void CoreSession::removeIdentity(IdentityId id) {
390   Identity *i = _identities.take(id);
391   if(i) {
392     emit identityRemoved(id);
393     CoreUserSettings s(user());
394     s.removeIdentity(id);
395     i->deleteLater();
396   }
397 }
398
399 /*** Network Handling ***/
400
401 void CoreSession::createNetwork(const NetworkInfo &info_) {
402   NetworkInfo info = info_;
403   int id;
404
405   if(!info.networkId.isValid())
406     Core::createNetwork(user(), info);
407
408   Q_ASSERT(info.networkId.isValid());
409
410   id = info.networkId.toInt();
411   Q_ASSERT(!_networks.contains(id));
412   
413   Network *net = new Network(id, this);
414   connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
415   connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
416   net->setNetworkInfo(info);
417   net->setProxy(signalProxy());
418   _networks[id] = net;
419   signalProxy()->synchronize(net);
420   emit networkCreated(id);
421 }
422
423 void CoreSession::updateNetwork(const NetworkInfo &info) {
424   if(!_networks.contains(info.networkId)) {
425     qWarning() << "Update request for unknown network received!";
426     return;
427   }
428   _networks[info.networkId]->setNetworkInfo(info);
429   Core::updateNetwork(user(), info);
430 }
431
432 void CoreSession::removeNetwork(NetworkId id) {
433   // Make sure the network is disconnected!
434   NetworkConnection *conn = _connections.value(id, 0);
435   if(conn) {
436     if(conn->connectionState() != Network::Disconnected) {
437       connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
438       conn->disconnectFromIrc();
439     } else {
440       _connections.take(id)->deleteLater();  // TODO make this saner
441       destroyNetwork(id);
442     }
443   } else {
444     destroyNetwork(id);
445   }
446 }
447
448 void CoreSession::destroyNetwork(NetworkId id) {
449   Q_ASSERT(!_connections.contains(id));
450   Network *net = _networks.take(id);
451   if(net && Core::removeNetwork(user(), id)) {
452     emit networkRemoved(id);
453     net->deleteLater();
454   }
455 }