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