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