This hopefully fixes the occasional segfault when exiting the core.
[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   foreach(NetworkId id, s.networkIds()) {
132     NetworkInfo info = s.networkInfo(id);
133     createNetwork(info, true);
134   }
135
136   // FIXME Migrate old settings if available...
137   if(!_networks.count()) {
138     QVariantMap networks = s.sessionValue("Networks").toMap();
139     if(networks.keys().count()) {
140       qWarning() << "Migrating your old network settings to the new format!";
141       foreach(QString netname, networks.keys()) {
142         QVariantMap network = networks[netname].toMap();
143         NetworkId netid = Core::networkId(user(), netname);
144         NetworkInfo info;
145         info.networkId = netid;
146         info.networkName = netname;
147         info.identity = 1;
148         info.codecForEncoding = "ISO-8859-15";
149         info.codecForDecoding = "ISO-8859-15";
150         QVariantList slist;
151         foreach(QVariant v, network["Servers"].toList()) {
152           QVariantMap server;
153           server["Host"] = v.toMap()["Address"];
154           server["Port"] = v.toMap()["Port"];
155           slist << server;
156         }
157         info.serverList = slist;
158         createNetwork(info, true);
159       }
160     }
161   }
162 }
163
164 void CoreSession::saveSessionState() const {
165   QVariantMap res;
166   QVariantList conn;
167   foreach(NetworkConnection *net, _connections.values()) {
168     QVariantMap m;
169     m["NetworkId"] = QVariant::fromValue<NetworkId>(net->networkId());
170     m["State"] = net->state();
171     conn << m;
172   }
173   res["CoreBuild"] = Global::quasselBuild;
174   res["ConnectedNetworks"] = conn;
175   CoreUserSettings s(user());
176   s.setSessionState(res);
177 }
178
179 void CoreSession::restoreSessionState() {
180   CoreUserSettings s(user());
181   uint build = s.sessionState().toMap()["CoreBuild"].toUInt();
182   if(build < 362) {
183     qWarning() << qPrintable(tr("Session state does not exist or is too old!"));
184     return;
185   }
186   QVariantList conn = s.sessionState().toMap()["ConnectedNetworks"].toList();
187   foreach(QVariant v, conn) {
188     NetworkId id = v.toMap()["NetworkId"].value<NetworkId>();
189     if(_networks.keys().contains(id)) connectToNetwork(id, v.toMap()["State"]);
190   }
191 }
192
193 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
194   if(uid == user()) emit bufferInfoUpdated(bufinfo);
195 }
196
197 // FIXME remove
198 void CoreSession::connectToNetwork(QString netname, const QVariant &previousState) {
199   Network *net = 0;
200   foreach(Network *n, _networks.values()) {
201     if(n->networkName() == netname) {
202       net = n; break;
203     }
204   }
205   if(!net) {
206     qWarning() << "Connect to unknown network requested, ignoring!";
207     return;
208   }
209   connectToNetwork(net->networkId(), previousState);
210 }
211
212 void CoreSession::connectToNetwork(NetworkId id, const QVariant &previousState) {
213   Network *net = network(id);
214   if(!net) {
215     qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
216     return;
217   }
218
219   NetworkConnection *conn = networkConnection(id);
220   if(!conn) {
221     conn = new NetworkConnection(net, this, previousState);
222     _connections[id] = conn;
223     attachNetworkConnection(conn);
224   }
225   conn->connectToIrc();
226 }
227
228 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
229   connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
230   connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
231
232   // I guess we don't need these anymore, client-side can just connect the network's signals directly
233   //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
234   //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
235
236   connect(conn, SIGNAL(displayMsg(Message::Type, QString, QString, QString, quint8)), this, SLOT(recvMessageFromServer(Message::Type, QString, QString, QString, quint8)));
237   connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
238
239 }
240
241 void CoreSession::disconnectFromNetwork(NetworkId id) {
242   if(!_connections.contains(id)) return;
243   _connections[id]->disconnectFromIrc();
244 }
245
246 void CoreSession::networkStateRequested() {
247 }
248
249 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
250   QIODevice *device = qobject_cast<QIODevice *>(dev);
251   if(!device) {
252     qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
253   } else {
254     signalProxy()->addPeer(device);
255     QVariantMap reply;
256     reply["MsgType"] = "SessionInit";
257     reply["SessionState"] = sessionState();
258     SignalProxy::writeDataToDevice(device, reply);
259   }
260 }
261
262 SignalProxy *CoreSession::signalProxy() const {
263   return _signalProxy;
264 }
265
266 // FIXME we need a sane way for creating buffers!
267 void CoreSession::networkConnected(NetworkId networkid) {
268   Core::bufferInfo(user(), networkConnection(networkid)->networkName()); // create status buffer
269 }
270
271 void CoreSession::networkDisconnected(NetworkId networkid) {
272   // FIXME
273   // connection should only go away on explicit /part, and handle reconnections etcpp internally otherwise
274
275   Q_ASSERT(_connections.contains(networkid));
276   _connections.take(networkid)->deleteLater();
277 }
278
279 // FIXME switch to BufferId
280 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
281   NetworkConnection *conn = networkConnection(bufinfo.networkId());
282   if(conn) {
283     conn->userInput(bufinfo.buffer(), msg);
284   } else {
285     qWarning() << "Trying to send to unconnected network!";
286   }
287 }
288
289 // ALL messages coming pass through these functions before going to the GUI.
290 // So this is the perfect place for storing the backlog and log stuff.
291 void CoreSession::recvMessageFromServer(Message::Type type, QString target, QString text, QString sender, quint8 flags) {
292   NetworkConnection *s = qobject_cast<NetworkConnection*>(this->sender());
293   Q_ASSERT(s);
294   BufferInfo buf;
295   if((flags & Message::PrivMsg) && !(flags & Message::Self)) {
296     buf = Core::bufferInfo(user(), s->networkName(), nickFromMask(sender));
297   } else {
298     buf = Core::bufferInfo(user(), s->networkName(), target);
299   }
300   Message msg(buf, type, text, sender, flags);
301   msg.setMsgId(Core::storeMessage(msg));
302   Q_ASSERT(msg.msgId() != 0);
303   emit displayMsg(msg);
304 }
305
306 void CoreSession::recvStatusMsgFromServer(QString msg) {
307   NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
308   Q_ASSERT(s);
309   emit displayStatusMsg(s->networkName(), msg);
310 }
311
312 QList<BufferInfo> CoreSession::buffers() const {
313   return Core::requestBuffers(user());
314 }
315
316
317 QVariant CoreSession::sessionState() {
318   QVariantMap v;
319
320   QVariantList bufs;
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;
326
327   quint32 ircusercount = 0;
328   quint32 ircchannelcount = 0;
329   foreach(Network *net, _networks.values()) {
330     ircusercount += net->ircUserCount();
331     ircchannelcount += net->ircChannelCount();
332   }
333   v["IrcUserCount"] = ircusercount;
334   v["IrcChannelCount"] = ircchannelcount;
335
336   QList<QVariant> idlist;
337   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
338   v["Identities"] = idlist;
339
340   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
341   return v;
342 }
343
344 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
345   QList<QVariant> log;
346   QList<Message> msglist;
347   if(v1.type() == QVariant::DateTime) {
348
349
350   } else {
351     msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
352   }
353
354   // Send messages out in smaller packages - we don't want to make the signal data too large!
355   for(int i = 0; i < msglist.count(); i++) {
356     log.append(qVariantFromValue(msglist[i]));
357     if(log.count() >= 5) {
358       emit backlogData(id, log, i >= msglist.count() - 1);
359       log.clear();
360     }
361   }
362   if(log.count() > 0) emit backlogData(id, log, true);
363 }
364
365
366 void CoreSession::initScriptEngine() {
367   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
368   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
369
370   // FIXME
371   //QScriptValue storage_ = scriptEngine->newQObject(storage);
372   //scriptEngine->globalObject().setProperty("storage", storage_);
373 }
374
375 void CoreSession::scriptRequest(QString script) {
376   emit scriptResult(scriptEngine->evaluate(script).toString());
377 }
378
379 /*** Identity Handling ***/
380
381 void CoreSession::createIdentity(const Identity &id) {
382   // find free ID
383   int i;
384   for(i = 1; i <= _identities.count(); i++) {
385     if(!_identities.keys().contains(i)) break;
386   }
387   //qDebug() << "found free id" << i;
388   Identity *newId = new Identity(id, this);
389   newId->setId(i);
390   _identities[i] = newId;
391   signalProxy()->synchronize(newId);
392   CoreUserSettings s(user());
393   s.storeIdentity(*newId);
394   emit identityCreated(*newId);
395 }
396
397 void CoreSession::updateIdentity(const Identity &id) {
398   if(!_identities.contains(id.id())) {
399     qWarning() << "Update request for unknown identity received!";
400     return;
401   }
402   _identities[id.id()]->update(id);
403
404   CoreUserSettings s(user());
405   s.storeIdentity(id);
406 }
407
408 void CoreSession::removeIdentity(IdentityId id) {
409   Identity *i = _identities.take(id);
410   if(i) {
411     emit identityRemoved(id);
412     CoreUserSettings s(user());
413     s.removeIdentity(id);
414     i->deleteLater();
415   }
416 }
417
418 /*** Network Handling ***/
419
420 void CoreSession::createNetwork(const NetworkInfo &_info, bool useId) {
421   NetworkInfo info = _info;
422   int id;
423   if(useId && info.networkId > 0) id = info.networkId.toInt();
424   else {
425     for(id = 1; id <= _networks.count(); id++) {
426       if(!_networks.keys().contains(id)) break;
427     }
428     //qDebug() << "found free id" << i;
429     info.networkId = id;
430   }
431   Network *net = new Network(id, this);
432   connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
433   connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
434   net->setNetworkInfo(info);
435   net->setProxy(signalProxy());
436   _networks[id] = net;
437   signalProxy()->synchronize(net);
438   CoreUserSettings s(user());
439   s.storeNetworkInfo(info);
440   emit networkCreated(id);
441 }
442
443 void CoreSession::updateNetwork(const NetworkInfo &info) {
444   if(!_networks.contains(info.networkId)) {
445     qWarning() << "Update request for unknown network received!";
446     return;
447   }
448   _networks[info.networkId]->setNetworkInfo(info);
449   CoreUserSettings s(user());
450   s.storeNetworkInfo(info);
451 }
452
453 void CoreSession::removeNetwork(NetworkId id) {
454   Network *net = _networks.take(id);
455   if(net) {
456     emit networkRemoved(id);
457     CoreUserSettings s(user());
458     s.removeNetworkInfo(id);
459     net->deleteLater();
460   }
461 }