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