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