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