improved backlog replay performance
[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   QList<NetworkId> nets = Core::connectedNetworks(user());
152   foreach(NetworkId id, nets) {
153     connectToNetwork(id);
154   }
155 }
156
157 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
158   if(uid == user()) emit bufferInfoUpdated(bufinfo);
159 }
160
161 void CoreSession::connectToNetwork(NetworkId id) {
162   Network *net = network(id);
163   if(!net) {
164     qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
165     return;
166   }
167
168   NetworkConnection *conn = networkConnection(id);
169   if(!conn) {
170     conn = new NetworkConnection(net, this);
171     _connections[id] = conn;
172     attachNetworkConnection(conn);
173   }
174   conn->connectToIrc();
175 }
176
177 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
178   connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
179   connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
180
181   // I guess we don't need these anymore, client-side can just connect the network's signals directly
182   //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
183   //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
184
185   connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)),
186           this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, quint8)));
187   connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
188
189   connect(conn, SIGNAL(nickChanged(const NetworkId &, const QString &, const QString &)),
190           this, SLOT(renameBuffer(const NetworkId &, const QString &, const QString &)));
191   connect(conn, SIGNAL(channelJoined(NetworkId, const QString &, const QString &)),
192           this, SLOT(channelJoined(NetworkId, const QString &, const QString &)));
193   connect(conn, SIGNAL(channelParted(NetworkId, const QString &)),
194           this, SLOT(channelParted(NetworkId, const QString &)));
195 }
196
197 void CoreSession::disconnectFromNetwork(NetworkId id) {
198   if(!_connections.contains(id)) return;
199   _connections[id]->disconnectFromIrc();
200 }
201
202 void CoreSession::networkStateRequested() {
203 }
204
205 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
206   QIODevice *device = qobject_cast<QIODevice *>(dev);
207   if(!device) {
208     qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
209   } else {
210     signalProxy()->addPeer(device);
211     QVariantMap reply;
212     reply["MsgType"] = "SessionInit";
213     reply["SessionState"] = sessionState();
214     SignalProxy::writeDataToDevice(device, reply);
215   }
216 }
217
218 SignalProxy *CoreSession::signalProxy() const {
219   return _signalProxy;
220 }
221
222 // FIXME we need a sane way for creating buffers!
223 void CoreSession::networkConnected(NetworkId networkid) {
224   Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
225   Core::setNetworkConnected(user(), networkid, true);
226 }
227
228 // called now only on /quit and requested disconnects, not on normal disconnects!
229 void CoreSession::networkDisconnected(NetworkId networkid) {
230   Core::setNetworkConnected(user(), networkid, false);
231   if(_connections.contains(networkid)) _connections.take(networkid)->deleteLater();
232 }
233
234 void CoreSession::channelJoined(NetworkId id, const QString &channel, const QString &key) {
235   Core::setChannelPersistent(user(), id, channel, true);
236   Core::setPersistentChannelKey(user(), id, channel, key);
237 }
238
239 void CoreSession::channelParted(NetworkId id, const QString &channel) {
240   Core::setChannelPersistent(user(), id, channel, false);
241 }
242
243 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
244   return Core::persistentChannels(user(), id);
245   return QHash<QString, QString>();
246 }
247
248 // FIXME switch to BufferId
249 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
250   NetworkConnection *conn = networkConnection(bufinfo.networkId());
251   if(conn) {
252     conn->userInput(bufinfo, msg);
253   } else {
254     qWarning() << "Trying to send to unconnected network!";
255   }
256 }
257
258 // ALL messages coming pass through these functions before going to the GUI.
259 // So this is the perfect place for storing the backlog and log stuff.
260 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, quint8 flags) {
261   NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
262   Q_ASSERT(netCon);
263   
264   BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
265   Message msg(bufferInfo, type, text, sender, flags);
266   msg.setMsgId(Core::storeMessage(msg));
267   Q_ASSERT(msg.msgId() != 0);
268   emit displayMsg(msg);
269 }
270
271 void CoreSession::recvStatusMsgFromServer(QString msg) {
272   NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
273   Q_ASSERT(s);
274   emit displayStatusMsg(s->networkName(), msg);
275 }
276
277 QList<BufferInfo> CoreSession::buffers() const {
278   return Core::requestBuffers(user());
279 }
280
281
282 QVariant CoreSession::sessionState() {
283   QVariantMap v;
284
285   QVariantList bufs;
286   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
287   v["BufferInfos"] = bufs;
288   QVariantList networkids;
289   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
290   v["NetworkIds"] = networkids;
291
292   quint32 ircusercount = 0;
293   quint32 ircchannelcount = 0;
294   foreach(Network *net, _networks.values()) {
295     ircusercount += net->ircUserCount();
296     ircchannelcount += net->ircChannelCount();
297   }
298   v["IrcUserCount"] = ircusercount;
299   v["IrcChannelCount"] = ircchannelcount;
300
301   QList<QVariant> idlist;
302   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
303   v["Identities"] = idlist;
304
305   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
306   return v;
307 }
308
309 void CoreSession::storeBufferLastSeen(BufferId buffer, const QDateTime &lastSeen) {
310   Core::setBufferLastSeen(user(), buffer, lastSeen);
311 }
312
313 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
314   QList<QVariant> log;
315   QList<Message> msglist;
316   if(v1.type() == QVariant::DateTime) {
317
318
319   } else {
320     msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
321   }
322
323   // Send messages out in smaller packages - we don't want to make the signal data too large!
324   for(int i = 0; i < msglist.count(); i++) {
325     log.append(qVariantFromValue(msglist[i]));
326     if(log.count() >= 5) {
327       emit backlogData(id, log, i >= msglist.count() - 1);
328       log.clear();
329     }
330   }
331   if(log.count() > 0) emit backlogData(id, log, true);
332 }
333
334
335 void CoreSession::initScriptEngine() {
336   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
337   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
338
339   // FIXME
340   //QScriptValue storage_ = scriptEngine->newQObject(storage);
341   //scriptEngine->globalObject().setProperty("storage", storage_);
342 }
343
344 void CoreSession::scriptRequest(QString script) {
345   emit scriptResult(scriptEngine->evaluate(script).toString());
346 }
347
348 /*** Identity Handling ***/
349
350 void CoreSession::createIdentity(const Identity &id) {
351   // find free ID
352   int i;
353   for(i = 1; i <= _identities.count(); i++) {
354     if(!_identities.keys().contains(i)) break;
355   }
356   //qDebug() << "found free id" << i;
357   Identity *newId = new Identity(id, this);
358   newId->setId(i);
359   _identities[i] = newId;
360   signalProxy()->synchronize(newId);
361   CoreUserSettings s(user());
362   s.storeIdentity(*newId);
363   emit identityCreated(*newId);
364 }
365
366 void CoreSession::updateIdentity(const Identity &id) {
367   if(!_identities.contains(id.id())) {
368     qWarning() << "Update request for unknown identity received!";
369     return;
370   }
371   _identities[id.id()]->update(id);
372
373   CoreUserSettings s(user());
374   s.storeIdentity(id);
375 }
376
377 void CoreSession::removeIdentity(IdentityId id) {
378   Identity *i = _identities.take(id);
379   if(i) {
380     emit identityRemoved(id);
381     CoreUserSettings s(user());
382     s.removeIdentity(id);
383     i->deleteLater();
384   }
385 }
386
387 /*** Network Handling ***/
388
389 void CoreSession::createNetwork(const NetworkInfo &info_) {
390   NetworkInfo info = info_;
391   int id;
392
393   if(!info.networkId.isValid())
394     Core::createNetwork(user(), info);
395
396   Q_ASSERT(info.networkId.isValid());
397
398   id = info.networkId.toInt();
399   Q_ASSERT(!_networks.contains(id));
400   
401   Network *net = new Network(id, this);
402   connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
403   connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
404   net->setNetworkInfo(info);
405   net->setProxy(signalProxy());
406   _networks[id] = net;
407   signalProxy()->synchronize(net);
408   emit networkCreated(id);
409 }
410
411 void CoreSession::updateNetwork(const NetworkInfo &info) {
412   if(!_networks.contains(info.networkId)) {
413     qWarning() << "Update request for unknown network received!";
414     return;
415   }
416   _networks[info.networkId]->setNetworkInfo(info);
417   Core::updateNetwork(user(), info);
418 }
419
420 void CoreSession::removeNetwork(NetworkId id) {
421   // Make sure the network is disconnected!
422   NetworkConnection *conn = _connections.value(id, 0);
423   if(conn) {
424     if(conn->connectionState() != Network::Disconnected) {
425       connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
426       conn->disconnectFromIrc();
427     } else {
428       _connections.take(id)->deleteLater();  // TODO make this saner
429       destroyNetwork(id);
430     }
431   } else {
432     destroyNetwork(id);
433   }
434 }
435
436 void CoreSession::destroyNetwork(NetworkId id) {
437   Q_ASSERT(!_connections.contains(id));
438   Network *net = _networks.take(id);
439   if(net && Core::removeNetwork(user(), id)) {
440     emit networkRemoved(id);
441     net->deleteLater();
442   }
443 }
444
445 void CoreSession::removeBufferRequested(BufferId bufferId) {
446   BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
447   if(!bufferInfo.isValid()) {
448     qWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
449     return;
450   }
451   
452   if(bufferInfo.type() == BufferInfo::StatusBuffer) {
453     qWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
454     return;
455   }
456   
457   if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
458     Network *net = network(bufferInfo.networkId());
459     Q_ASSERT(net);
460     IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
461     if(chan) {
462       qWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
463       return;
464     }
465   }
466   if(Core::removeBuffer(user(), bufferId))
467     emit bufferRemoved(bufferId);
468 }
469
470 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
471   BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
472   if(bufferId.isValid()) {
473     emit bufferRenamed(bufferId, newName);
474   }
475 }