Changed the new layout of the settings files around a bit. SessionData is now
[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 "coresession.h"
22 #include "server.h"
23
24 #include "signalproxy.h"
25 #include "storage.h"
26
27 #include "networkinfo.h"
28 #include "ircuser.h"
29 #include "ircchannel.h"
30 #include "identity.h"
31
32 #include "util.h"
33 #include "coreusersettings.h"
34
35 #include <QtScript>
36
37 CoreSession::CoreSession(UserId uid, Storage *_storage, QObject *parent)
38   : QObject(parent),
39     user(uid),
40     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
41     storage(_storage),
42     scriptEngine(new QScriptEngine(this))
43 {
44
45   SignalProxy *p = signalProxy();
46
47   CoreUserSettings s(user);
48   sessionData = s.sessionData();
49 /*
50   CoreSettings cs;
51   foreach(QString id, cs.localChildKeys(QString("Identities/%1").arg(user))) {
52     Identity *i = new Identity(cs.localValue(QString("Identities/%1/%2").arg(user).arg(id)).value<Identity>(), this);
53     if(i->id() < 1) {
54       qDebug() << QString("Invalid identity!");
55       continue;
56     }
57     if(_identities.contains(i->id())) {
58       qDebug() << "Duplicate identity, ignoring!";
59       continue;
60     }
61     qDebug() << "loaded identity" << id;
62     _identities[i->id()] = i;
63   }
64   s.endGroup();
65   mutex.unlock();
66   if(!_identities.count()) {
67     Identity i(1);
68     i.setToDefaults();
69     //_identities[i->id()] = i;
70     createOrUpdateIdentity(i);
71   }
72   */
73
74   p->attachSlot(SIGNAL(requestNetworkStates()), this, SLOT(serverStateRequested()));
75   p->attachSlot(SIGNAL(requestConnect(QString)), this, SLOT(connectToNetwork(QString)));
76   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromGui(BufferInfo, QString)));
77   p->attachSlot(SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)), this, SLOT(sendBacklog(BufferInfo, QVariant, QVariant)));
78   p->attachSignal(this, SIGNAL(displayMsg(Message)));
79   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
80   p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
81   p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
82   p->attachSignal(storage, SIGNAL(bufferInfoUpdated(BufferInfo)));
83   p->attachSignal(this, SIGNAL(sessionDataChanged(const QString &, const QVariant &)), SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)));
84   p->attachSlot(SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)), this, SLOT(storeSessionData(const QString &, const QVariant &)));
85
86   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
87   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
88   p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createOrUpdateIdentity(const Identity &)));
89   p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(createOrUpdateIdentity(const Identity &)));
90   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
91
92   initScriptEngine();
93
94   foreach(Identity *id, _identities.values()) {
95     p->synchronize(id);
96   }
97 }
98
99 CoreSession::~CoreSession() {
100 }
101
102 UserId CoreSession::userId() const {
103   return user;
104 }
105
106 QVariant CoreSession::state() const {
107   QVariantMap res;
108   QList<QVariant> conn;
109   foreach(Server *server, servers.values()) {
110     if(server->isConnected()) {
111       QVariantMap m;
112       m["Network"] = server->networkName();
113       m["State"] = server->state();
114       conn << m;
115     }
116   }
117   res["ConnectedServers"] = conn;
118   return res;
119 }
120
121 void CoreSession::restoreState(const QVariant &previousState) {
122   // Session restore
123   QVariantMap state = previousState.toMap();
124   if(state.contains("ConnectedServers")) {
125     foreach(QVariant v, state["ConnectedServers"].toList()) {
126       QVariantMap m = v.toMap();
127       QString net = m["Network"].toString();
128       if(!net.isEmpty()) connectToNetwork(net, m["State"]);
129     }
130   }
131 }
132
133
134 void CoreSession::storeSessionData(const QString &key, const QVariant &data) {
135   CoreUserSettings s(user);
136   mutex.lock();
137   s.setSessionValue(key, data);
138   sessionData[key] = data;
139   mutex.unlock();
140   emit sessionDataChanged(key, data);
141   emit sessionDataChanged(key);
142 }
143
144 QVariant CoreSession::retrieveSessionData(const QString &key, const QVariant &def) {
145   QVariant data;
146   mutex.lock();
147   if(!sessionData.contains(key)) data = def;
148   else data = sessionData[key];
149   mutex.unlock();
150   return data;
151 }
152
153 // FIXME switch to NetworkIDs
154 void CoreSession::connectToNetwork(QString network, const QVariant &previousState) {
155   uint networkid = getNetworkId(network);
156   if(networkid == 0) {
157     qWarning() << "unable to connect to Network" << network << "(User:" << userId() << "): unable to determine NetworkId";
158     return;
159   }
160   if(!servers.contains(networkid)) {
161     Server *server = new Server(userId(), networkid, network, previousState);
162     servers[networkid] = server;
163     attachServer(server);
164     server->start();
165   }
166   emit connectToIrc(network);
167 }
168
169 void CoreSession::attachServer(Server *server) {
170   connect(this, SIGNAL(connectToIrc(QString)), server, SLOT(connectToIrc(QString)));
171   connect(this, SIGNAL(disconnectFromIrc(QString)), server, SLOT(disconnectFromIrc(QString)));
172   connect(this, SIGNAL(msgFromGui(uint, QString, QString)), server, SLOT(userInput(uint, QString, QString)));
173   
174   connect(server, SIGNAL(connected(uint)), this, SLOT(serverConnected(uint)));
175   connect(server, SIGNAL(disconnected(uint)), this, SLOT(serverDisconnected(uint)));
176   connect(server, SIGNAL(displayMsg(Message::Type, QString, QString, QString, quint8)), this, SLOT(recvMessageFromServer(Message::Type, QString, QString, QString, quint8)));
177   connect(server, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
178
179   // connect serversignals to proxy
180   signalProxy()->attachSignal(server, SIGNAL(serverState(QString, QVariantMap)), SIGNAL(networkState(QString, QVariantMap)));
181   signalProxy()->attachSignal(server, SIGNAL(connected(uint)), SIGNAL(networkConnected(uint)));
182   signalProxy()->attachSignal(server, SIGNAL(disconnected(uint)), SIGNAL(networkDisconnected(uint)));
183   // TODO add error handling
184 }
185
186 void CoreSession::serverStateRequested() {
187 }
188
189 void CoreSession::addClient(QIODevice *device) {
190   signalProxy()->addPeer(device);
191 }
192
193 SignalProxy *CoreSession::signalProxy() const {
194   return _signalProxy;
195 }
196
197 void CoreSession::serverConnected(uint networkid) {
198   storage->getBufferInfo(userId(), servers[networkid]->networkName()); // create status buffer
199 }
200
201 void CoreSession::serverDisconnected(uint networkid) {
202   Q_ASSERT(servers.contains(networkid));
203   servers.take(networkid)->deleteLater();
204   Q_ASSERT(!servers.contains(networkid));
205 }
206
207 void CoreSession::msgFromGui(BufferInfo bufid, QString msg) {
208   emit msgFromGui(bufid.networkId(), bufid.buffer(), msg);
209 }
210
211 // ALL messages coming pass through these functions before going to the GUI.
212 // So this is the perfect place for storing the backlog and log stuff.
213 void CoreSession::recvMessageFromServer(Message::Type type, QString target, QString text, QString sender, quint8 flags) {
214   Server *s = qobject_cast<Server*>(this->sender());
215   Q_ASSERT(s);
216   BufferInfo buf;
217   if((flags & Message::PrivMsg) && !(flags & Message::Self)) {
218     buf = storage->getBufferInfo(user, s->networkName(), nickFromMask(sender));
219   } else {
220     buf = storage->getBufferInfo(user, s->networkName(), target);
221   }
222   Message msg(buf, type, text, sender, flags);
223   msg.setMsgId(storage->logMessage(msg));
224   Q_ASSERT(msg.msgId());
225   emit displayMsg(msg);
226 }
227
228 void CoreSession::recvStatusMsgFromServer(QString msg) {
229   Server *s = qobject_cast<Server*>(sender());
230   Q_ASSERT(s);
231   emit displayStatusMsg(s->networkName(), msg);
232 }
233
234
235 uint CoreSession::getNetworkId(const QString &net) const {
236   return storage->getNetworkId(user, net);
237 }
238
239 QList<BufferInfo> CoreSession::buffers() const {
240   return storage->requestBuffers(user);
241 }
242
243
244 QVariant CoreSession::sessionState() {
245   QVariantMap v;
246
247   QVariantList bufs;
248   foreach(BufferInfo id, storage->requestBuffers(user))
249     bufs.append(QVariant::fromValue(id));
250   v["Buffers"] = bufs;
251
252   mutex.lock();
253   v["SessionData"] = sessionData;
254   mutex.unlock();
255
256   QVariantList networks;
257   foreach(NetworkId networkid, servers.keys())
258     networks.append(QVariant(networkid));
259   v["Networks"] = QVariant(networks);
260
261   QList<QVariant> idlist;
262   foreach(Identity *i, _identities.values()) idlist << QVariant::fromValue<Identity>(*i);
263   v["Identities"] = idlist;
264
265   // v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
266   return v;
267 }
268
269 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
270   QList<QVariant> log;
271   QList<Message> msglist;
272   if(v1.type() == QVariant::DateTime) {
273
274
275   } else {
276     msglist = storage->requestMsgs(id, v1.toInt(), v2.toInt());
277   }
278
279   // Send messages out in smaller packages - we don't want to make the signal data too large!
280   for(int i = 0; i < msglist.count(); i++) {
281     log.append(QVariant::fromValue(msglist[i]));
282     if(log.count() >= 5) {
283       emit backlogData(id, log, i >= msglist.count() - 1);
284       log.clear();
285     }
286   }
287   if(log.count() > 0) emit backlogData(id, log, true);
288 }
289
290
291 void CoreSession::initScriptEngine() {
292   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
293   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
294   
295   QScriptValue storage_ = scriptEngine->newQObject(storage);
296   scriptEngine->globalObject().setProperty("storage", storage_);
297 }
298
299 void CoreSession::scriptRequest(QString script) {
300   emit scriptResult(scriptEngine->evaluate(script).toString());
301 }
302
303 void CoreSession::createOrUpdateIdentity(const Identity &id) {
304   if(!_identities.contains(id.id())) {
305     // create new
306     _identities[id.id()] = new Identity(id, this);
307     signalProxy()->synchronize(_identities[id.id()]);
308     emit identityCreated(id.id());
309   } else {
310     // update
311     _identities[id.id()]->update(id);
312   }
313 /*
314   CoreSettings s;
315   s.beginGroup(QString("Identities/%1").arg(user));
316   s.setValue(QString::number(id.id()), QVariant::fromValue<Identity>(*_identities[id.id()]));
317   s.endGroup();*/
318 }
319
320 void CoreSession::removeIdentity(IdentityId id) {
321   Identity *i = _identities.take(id);
322   if(i) {
323     emit identityRemoved(id);
324     i->deleteLater();
325   }
326 }
327