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