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