migrated passwords from blob to strings (still hashed), for easier migration between...
[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 <QtScript>
22
23 #include "core.h"
24 #include "coresession.h"
25 #include "networkconnection.h"
26
27 #include "signalproxy.h"
28 #include "buffersyncer.h"
29 #include "storage.h"
30
31 #include "network.h"
32 #include "ircuser.h"
33 #include "ircchannel.h"
34 #include "identity.h"
35
36 #include "util.h"
37 #include "coreusersettings.h"
38
39 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent) : QObject(parent),
40     _user(uid),
41     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
42     _bufferSyncer(new BufferSyncer(this)),
43     scriptEngine(new QScriptEngine(this))
44 {
45
46   SignalProxy *p = signalProxy();
47
48   //p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
49   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
50   p->attachSlot(SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)), this, SLOT(sendBacklog(BufferInfo, QVariant, QVariant)));
51   p->attachSignal(this, SIGNAL(displayMsg(Message)));
52   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
53   p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
54   p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
55
56   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
57   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
58   p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
59   p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
60   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
61
62   p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
63   p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
64   p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
65   p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
66   p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
67
68   loadSettings();
69   initScriptEngine();
70
71   // init BufferSyncer
72   QHash<BufferId, QDateTime> lastSeenHash = Core::bufferLastSeenDates(user());
73   foreach(BufferId id, lastSeenHash.keys()) _bufferSyncer->requestSetLastSeen(id, lastSeenHash[id]);
74   connect(_bufferSyncer, SIGNAL(lastSeenSet(BufferId, const QDateTime &)), this, SLOT(storeBufferLastSeen(BufferId, const QDateTime &)));
75   connect(_bufferSyncer, SIGNAL(removeBufferRequested(BufferId)), this, SLOT(removeBufferRequested(BufferId)));
76   connect(this, SIGNAL(bufferRemoved(BufferId)), _bufferSyncer, SLOT(removeBuffer(BufferId)));
77   connect(this, SIGNAL(bufferRenamed(BufferId, QString)), _bufferSyncer, SLOT(renameBuffer(BufferId, QString)));
78   p->synchronize(_bufferSyncer);
79
80   // Restore session state
81   if(restoreState) restoreSessionState();
82
83   emit initialized();
84 }
85
86 CoreSession::~CoreSession() {
87   saveSessionState();
88   foreach(NetworkConnection *conn, _connections.values()) {
89     delete conn;
90   }
91   foreach(Network *net, _networks.values()) {
92     delete net;
93   }
94 }
95
96 UserId CoreSession::user() const {
97   return _user;
98 }
99
100 Network *CoreSession::network(NetworkId id) const {
101   if(_networks.contains(id)) return _networks[id];
102   return 0;
103 }
104
105 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
106   if(_connections.contains(id)) return _connections[id];
107   return 0;
108 }
109
110 Identity *CoreSession::identity(IdentityId id) const {
111   if(_identities.contains(id)) return _identities[id];
112   return 0;
113 }
114
115 void CoreSession::loadSettings() {
116   CoreUserSettings s(user());
117
118   foreach(IdentityId id, s.identityIds()) {
119     Identity *i = new Identity(s.identity(id), this);
120     if(!i->isValid()) {
121       qWarning() << QString("Invalid identity! Removing...");
122       s.removeIdentity(id);
123       delete i;
124       continue;
125     }
126     if(_identities.contains(i->id())) {
127       qWarning() << "Duplicate identity, ignoring!";
128       delete i;
129       continue;
130     }
131     _identities[i->id()] = i;
132     signalProxy()->synchronize(i);
133   }
134   if(!_identities.count()) {
135     Identity i(1);
136     i.setToDefaults();
137     i.setIdentityName(tr("Default Identity"));
138     createIdentity(i);
139   }
140
141   foreach(NetworkInfo info, Core::networks(user())) {
142     createNetwork(info);
143   }
144 }
145
146 void CoreSession::saveSessionState() const {
147
148 }
149
150 void CoreSession::restoreSessionState() {
151   // FIXME db support
152   //QList<NetworkId> nets = Core::connectedNetworks(user());
153   QList<NetworkId> nets;
154   foreach(NetworkId id, nets) {
155     connectToNetwork(id);
156   }
157 }
158
159 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
160   if(uid == user()) emit bufferInfoUpdated(bufinfo);
161 }
162
163 void CoreSession::connectToNetwork(NetworkId id) {
164   Network *net = network(id);
165   if(!net) {
166     qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
167     return;
168   }
169
170   NetworkConnection *conn = networkConnection(id);
171   if(!conn) {
172     conn = new NetworkConnection(net, this);
173     _connections[id] = conn;
174     attachNetworkConnection(conn);
175   }
176   conn->connectToIrc();
177 }
178
179 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
180   connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
181   connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
182
183   // I guess we don't need these anymore, client-side can just connect the network's signals directly
184   //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
185   //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
186
187   connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)),
188           this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)));
189   connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
190
191   connect(conn, SIGNAL(nickChanged(const NetworkId &, const QString &, const QString &)),
192           this, SLOT(renameBuffer(const NetworkId &, const QString &, const QString &)));
193   connect(conn, SIGNAL(channelJoined(NetworkId, const QString &, const QString &)),
194           this, SLOT(channelJoined(NetworkId, const QString &, const QString &)));
195   connect(conn, SIGNAL(channelParted(NetworkId, const QString &)),
196           this, SLOT(channelParted(NetworkId, const QString &)));
197 }
198
199 void CoreSession::disconnectFromNetwork(NetworkId id) {
200   if(!_connections.contains(id)) return;
201   _connections[id]->disconnectFromIrc();
202 }
203
204 void CoreSession::networkStateRequested() {
205 }
206
207 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
208   QIODevice *device = qobject_cast<QIODevice *>(dev);
209   if(!device) {
210     qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
211   } else {
212     signalProxy()->addPeer(device);
213     QVariantMap reply;
214     reply["MsgType"] = "SessionInit";
215     reply["SessionState"] = sessionState();
216     SignalProxy::writeDataToDevice(device, reply);
217   }
218 }
219
220 SignalProxy *CoreSession::signalProxy() const {
221   return _signalProxy;
222 }
223
224 // FIXME we need a sane way for creating buffers!
225 void CoreSession::networkConnected(NetworkId networkid) {
226   Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
227   //Core::setNetworkConnected(user(), networkid, true);
228 }
229
230 // called now only on /quit and requested disconnects, not on normal disconnects!
231 void CoreSession::networkDisconnected(NetworkId networkid) {
232   //Core::setNetworkConnected(user(), networkid, false);
233   if(_connections.contains(networkid)) _connections.take(networkid)->deleteLater();
234 }
235
236 void CoreSession::channelJoined(NetworkId id, const QString &channel, const QString &key) {
237   //Core::setChannelPersistent(user(), id, channel, true);
238   //Core::setPersistentChannelKey(user(), id, channel, key);
239 }
240
241 void CoreSession::channelParted(NetworkId id, const QString &channel) {
242   //Core::setChannelPersistent(user(), id, channel, false);
243 }
244
245 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
246   //return Core::persistentChannels(user(), id);
247   return QHash<QString, QString>();
248 }
249
250 // FIXME switch to BufferId
251 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
252   NetworkConnection *conn = networkConnection(bufinfo.networkId());
253   if(conn) {
254     conn->userInput(bufinfo, msg);
255   } else {
256     qWarning() << "Trying to send to unconnected network!";
257   }
258 }
259
260 // ALL messages coming pass through these functions before going to the GUI.
261 // So this is the perfect place for storing the backlog and log stuff.
262 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, quint8 flags) {
263   NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
264   Q_ASSERT(netCon);
265   
266   BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
267   Message msg(bufferInfo, type, text, sender, flags);
268   msg.setMsgId(Core::storeMessage(msg));
269   Q_ASSERT(msg.msgId() != 0);
270   emit displayMsg(msg);
271 }
272
273 void CoreSession::recvStatusMsgFromServer(QString msg) {
274   NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
275   Q_ASSERT(s);
276   emit displayStatusMsg(s->networkName(), msg);
277 }
278
279 QList<BufferInfo> CoreSession::buffers() const {
280   return Core::requestBuffers(user());
281 }
282
283
284 QVariant CoreSession::sessionState() {
285   QVariantMap v;
286
287   QVariantList bufs;
288   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
289   v["BufferInfos"] = bufs;
290   QVariantList networkids;
291   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
292   v["NetworkIds"] = networkids;
293
294   quint32 ircusercount = 0;
295   quint32 ircchannelcount = 0;
296   foreach(Network *net, _networks.values()) {
297     ircusercount += net->ircUserCount();
298     ircchannelcount += net->ircChannelCount();
299   }
300   v["IrcUserCount"] = ircusercount;
301   v["IrcChannelCount"] = ircchannelcount;
302
303   QList<QVariant> idlist;
304   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
305   v["Identities"] = idlist;
306
307   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
308   return v;
309 }
310
311 void CoreSession::storeBufferLastSeen(BufferId buffer, const QDateTime &lastSeen) {
312   Core::setBufferLastSeen(user(), buffer, lastSeen);
313 }
314
315 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
316   QList<QVariant> log;
317   QList<Message> msglist;
318   if(v1.type() == QVariant::DateTime) {
319
320
321   } else {
322     msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
323   }
324
325   // Send messages out in smaller packages - we don't want to make the signal data too large!
326   for(int i = 0; i < msglist.count(); i++) {
327     log.append(qVariantFromValue(msglist[i]));
328     if(log.count() >= 5) {
329       emit backlogData(id, log, i >= msglist.count() - 1);
330       log.clear();
331     }
332   }
333   if(log.count() > 0) emit backlogData(id, log, true);
334 }
335
336
337 void CoreSession::initScriptEngine() {
338   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
339   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
340
341   // FIXME
342   //QScriptValue storage_ = scriptEngine->newQObject(storage);
343   //scriptEngine->globalObject().setProperty("storage", storage_);
344 }
345
346 void CoreSession::scriptRequest(QString script) {
347   emit scriptResult(scriptEngine->evaluate(script).toString());
348 }
349
350 /*** Identity Handling ***/
351
352 void CoreSession::createIdentity(const Identity &id) {
353   // find free ID
354   int i;
355   for(i = 1; i <= _identities.count(); i++) {
356     if(!_identities.keys().contains(i)) break;
357   }
358   //qDebug() << "found free id" << i;
359   Identity *newId = new Identity(id, this);
360   newId->setId(i);
361   _identities[i] = newId;
362   signalProxy()->synchronize(newId);
363   CoreUserSettings s(user());
364   s.storeIdentity(*newId);
365   emit identityCreated(*newId);
366 }
367
368 void CoreSession::updateIdentity(const Identity &id) {
369   if(!_identities.contains(id.id())) {
370     qWarning() << "Update request for unknown identity received!";
371     return;
372   }
373   _identities[id.id()]->update(id);
374
375   CoreUserSettings s(user());
376   s.storeIdentity(id);
377 }
378
379 void CoreSession::removeIdentity(IdentityId id) {
380   Identity *i = _identities.take(id);
381   if(i) {
382     emit identityRemoved(id);
383     CoreUserSettings s(user());
384     s.removeIdentity(id);
385     i->deleteLater();
386   }
387 }
388
389 /*** Network Handling ***/
390
391 void CoreSession::createNetwork(const NetworkInfo &info_) {
392   NetworkInfo info = info_;
393   int id;
394
395   if(!info.networkId.isValid())
396     Core::createNetwork(user(), info);
397
398   Q_ASSERT(info.networkId.isValid());
399
400   id = info.networkId.toInt();
401   Q_ASSERT(!_networks.contains(id));
402   
403   Network *net = new Network(id, this);
404   connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
405   connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
406   net->setNetworkInfo(info);
407   net->setProxy(signalProxy());
408   _networks[id] = net;
409   signalProxy()->synchronize(net);
410   emit networkCreated(id);
411 }
412
413 void CoreSession::updateNetwork(const NetworkInfo &info) {
414   if(!_networks.contains(info.networkId)) {
415     qWarning() << "Update request for unknown network received!";
416     return;
417   }
418   _networks[info.networkId]->setNetworkInfo(info);
419   Core::updateNetwork(user(), info);
420 }
421
422 void CoreSession::removeNetwork(NetworkId id) {
423   // Make sure the network is disconnected!
424   NetworkConnection *conn = _connections.value(id, 0);
425   if(conn) {
426     if(conn->connectionState() != Network::Disconnected) {
427       connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
428       conn->disconnectFromIrc();
429     } else {
430       _connections.take(id)->deleteLater();  // TODO make this saner
431       destroyNetwork(id);
432     }
433   } else {
434     destroyNetwork(id);
435   }
436 }
437
438 void CoreSession::destroyNetwork(NetworkId id) {
439   Q_ASSERT(!_connections.contains(id));
440   Network *net = _networks.take(id);
441   if(net && Core::removeNetwork(user(), id)) {
442     emit networkRemoved(id);
443     net->deleteLater();
444   }
445 }
446
447 void CoreSession::removeBufferRequested(BufferId bufferId) {
448   BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
449   if(!bufferInfo.isValid()) {
450     qWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
451     return;
452   }
453   
454   if(bufferInfo.type() == BufferInfo::StatusBuffer) {
455     qWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
456     return;
457   }
458   
459   if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
460     Network *net = network(bufferInfo.networkId());
461     Q_ASSERT(net);
462     IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
463     if(chan) {
464       qWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
465       return;
466     }
467   }
468   if(Core::removeBuffer(user(), bufferId))
469     emit bufferRemoved(bufferId);
470 }
471
472 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
473   BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
474   if(bufferId.isValid()) {
475     emit bufferRenamed(bufferId, newName);
476   }
477 }