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