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