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