making use of postgres timestamps
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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 "userinputhandler.h"
26 #include "signalproxy.h"
27 #include "corebuffersyncer.h"
28 #include "corebacklogmanager.h"
29 #include "corebufferviewmanager.h"
30 #include "coreirclisthelper.h"
31 #include "storage.h"
32
33 #include "coreidentity.h"
34 #include "corenetwork.h"
35 #include "ircuser.h"
36 #include "ircchannel.h"
37
38 #include "util.h"
39 #include "coreusersettings.h"
40 #include "logger.h"
41
42 class ProcessMessagesEvent : public QEvent {
43 public:
44   ProcessMessagesEvent() : QEvent(QEvent::User) {}
45 };
46
47 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
48   : QObject(parent),
49     _user(uid),
50     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
51     _aliasManager(this),
52     _bufferSyncer(new CoreBufferSyncer(this)),
53     _backlogManager(new CoreBacklogManager(this)),
54     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
55     _ircListHelper(new CoreIrcListHelper(this)),
56     _coreInfo(this),
57     scriptEngine(new QScriptEngine(this)),
58     _processMessages(false)
59 {
60   SignalProxy *p = signalProxy();
61   connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
62
63   connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
64   connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
65
66   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
67   p->attachSignal(this, SIGNAL(displayMsg(Message)));
68   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
69
70   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
71   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
72   p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
73   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
74
75   p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
76   p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
77   p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
78   p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
79
80   loadSettings();
81   initScriptEngine();
82
83   connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferSyncer, SLOT(storeDirtyIds()));
84   connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferViewManager, SLOT(saveBufferViews()));
85
86   p->synchronize(_bufferSyncer);
87   p->synchronize(&aliasManager());
88   p->synchronize(_backlogManager);
89   p->synchronize(ircListHelper());
90   p->synchronize(&_coreInfo);
91
92   // Restore session state
93   if(restoreState)
94     restoreSessionState();
95
96   emit initialized();
97 }
98
99 CoreSession::~CoreSession() {
100   saveSessionState();
101   foreach(CoreNetwork *net, _networks.values()) {
102     delete net;
103   }
104 }
105
106 CoreNetwork *CoreSession::network(NetworkId id) const {
107   if(_networks.contains(id)) return _networks[id];
108   return 0;
109 }
110
111 CoreIdentity *CoreSession::identity(IdentityId id) const {
112   if(_identities.contains(id)) return _identities[id];
113   return 0;
114 }
115
116 void CoreSession::loadSettings() {
117   CoreUserSettings s(user());
118
119   // migrate to db
120   QList<IdentityId> ids = s.identityIds();
121   QList<NetworkInfo> networkInfos = Core::networks(user());
122   foreach(IdentityId id, ids) {
123     CoreIdentity identity(s.identity(id));
124     IdentityId newId = Core::createIdentity(user(), identity);
125     QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
126     while(networkIter != networkInfos.end()) {
127       if(networkIter->identity == id) {
128         networkIter->identity = newId;
129         Core::updateNetwork(user(), *networkIter);
130         networkIter = networkInfos.erase(networkIter);
131       } else {
132         networkIter++;
133       }
134     }
135     s.removeIdentity(id);
136   }
137   // end of migration
138
139   foreach(CoreIdentity identity, Core::identities(user())) {
140     createIdentity(identity);
141   }
142
143   foreach(NetworkInfo info, Core::networks(user())) {
144     createNetwork(info);
145   }
146 }
147
148 void CoreSession::saveSessionState() const {
149   _bufferSyncer->storeDirtyIds();
150   _bufferViewManager->saveBufferViews();
151 }
152
153 void CoreSession::restoreSessionState() {
154   QList<NetworkId> nets = Core::connectedNetworks(user());
155   CoreNetwork *net = 0;
156   foreach(NetworkId id, nets) {
157     net = network(id);
158     Q_ASSERT(net);
159     net->connectToIrc();
160   }
161 }
162
163 void CoreSession::addClient(QIODevice *device) {
164   if(!device) {
165     qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
166   } else {
167     // if the socket is an orphan, the signalProxy adopts it.
168     // -> we don't need to care about it anymore
169     device->setParent(0);
170     signalProxy()->addPeer(device);
171     QVariantMap reply;
172     reply["MsgType"] = "SessionInit";
173     reply["SessionState"] = sessionState();
174     SignalProxy::writeDataToDevice(device, reply);
175   }
176 }
177
178 void CoreSession::addClient(SignalProxy *proxy) {
179   signalProxy()->addPeer(proxy);
180   emit sessionState(sessionState());
181 }
182
183 void CoreSession::removeClient(QIODevice *iodev) {
184   QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
185   if(socket)
186     quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
187 }
188
189 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
190   return Core::persistentChannels(user(), id);
191 }
192
193 // FIXME switch to BufferId
194 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
195   CoreNetwork *net = network(bufinfo.networkId());
196   if(net) {
197     net->userInput(bufinfo, msg);
198   } else {
199     qWarning() << "Trying to send to unconnected network:" << msg;
200   }
201 }
202
203 // ALL messages coming pass through these functions before going to the GUI.
204 // So this is the perfect place for storing the backlog and log stuff.
205 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
206                                         const QString &target, const QString &text, const QString &sender, Message::Flags flags) {
207   _messageQueue << RawMessage(networkId, type, bufferType, target, text, sender, flags);
208   if(!_processMessages) {
209     _processMessages = true;
210     QCoreApplication::postEvent(this, new ProcessMessagesEvent());
211   }
212 }
213
214 void CoreSession::recvStatusMsgFromServer(QString msg) {
215   CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
216   Q_ASSERT(net);
217   emit displayStatusMsg(net->networkName(), msg);
218 }
219
220 QList<BufferInfo> CoreSession::buffers() const {
221   return Core::requestBuffers(user());
222 }
223
224 void CoreSession::customEvent(QEvent *event) {
225   if(event->type() != QEvent::User)
226     return;
227
228   processMessages();
229   event->accept();
230 }
231
232 void CoreSession::processMessages() {
233   qDebug() << "processing" << _messageQueue.count() << "messages..";
234   if(_messageQueue.count() == 1) {
235     const RawMessage &rawMsg = _messageQueue.first();
236     BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
237     Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
238     Core::storeMessage(msg);
239     emit displayMsg(msg);
240   } else {
241     QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
242     MessageList messages;
243     BufferInfo bufferInfo;
244     for(int i = 0; i < _messageQueue.count(); i++) {
245       const RawMessage &rawMsg = _messageQueue.at(i);
246       if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
247         bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
248       } else {
249         bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
250         bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
251       }
252       messages << Message(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
253     }
254     Core::storeMessages(messages);
255     // FIXME: extend protocol to a displayMessages(MessageList)
256     for(int i = 0; i < messages.count(); i++) {
257       emit displayMsg(messages[i]);
258     }
259   }
260   _processMessages = false;
261   _messageQueue.clear();
262 }
263
264 QVariant CoreSession::sessionState() {
265   QVariantMap v;
266
267   QVariantList bufs;
268   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
269   v["BufferInfos"] = bufs;
270   QVariantList networkids;
271   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
272   v["NetworkIds"] = networkids;
273
274   quint32 ircusercount = 0;
275   quint32 ircchannelcount = 0;
276   foreach(Network *net, _networks.values()) {
277     ircusercount += net->ircUserCount();
278     ircchannelcount += net->ircChannelCount();
279   }
280   v["IrcUserCount"] = ircusercount;
281   v["IrcChannelCount"] = ircchannelcount;
282
283   QList<QVariant> idlist;
284   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
285   v["Identities"] = idlist;
286
287   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
288   return v;
289 }
290
291 void CoreSession::initScriptEngine() {
292   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
293   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
294
295   // FIXME
296   //QScriptValue storage_ = scriptEngine->newQObject(storage);
297   //scriptEngine->globalObject().setProperty("storage", storage_);
298 }
299
300 void CoreSession::scriptRequest(QString script) {
301   emit scriptResult(scriptEngine->evaluate(script).toString());
302 }
303
304 /*** Identity Handling ***/
305 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
306 #ifndef HAVE_SSL
307   Q_UNUSED(additional)
308 #endif
309
310   CoreIdentity coreIdentity(identity);
311 #ifdef HAVE_SSL
312   if(additional.contains("KeyPem"))
313     coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
314   if(additional.contains("CertPem"))
315     coreIdentity.setSslCert(additional["CertPem"].toByteArray());
316 #endif
317   qDebug() << Q_FUNC_INFO;
318   IdentityId id = Core::createIdentity(user(), coreIdentity);
319   if(!id.isValid())
320     return;
321   else
322     createIdentity(coreIdentity);
323 }
324
325 void CoreSession::createIdentity(const CoreIdentity &identity) {
326   CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
327   _identities[identity.id()] = coreIdentity;
328   // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
329   coreIdentity->synchronize(signalProxy());
330   connect(coreIdentity, SIGNAL(updated(const QVariantMap &)), this, SLOT(updateIdentityBySender()));
331   emit identityCreated(*coreIdentity);
332 }
333
334 void CoreSession::updateIdentityBySender() {
335   CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
336   if(!identity)
337     return;
338   Core::updateIdentity(user(), *identity);
339 }
340
341 void CoreSession::removeIdentity(IdentityId id) {
342   CoreIdentity *identity = _identities.take(id);
343   if(identity) {
344     emit identityRemoved(id);
345     Core::removeIdentity(user(), id);
346     identity->deleteLater();
347   }
348 }
349
350 /*** Network Handling ***/
351
352 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
353   NetworkInfo info = info_;
354   int id;
355
356   if(!info.networkId.isValid())
357     Core::createNetwork(user(), info);
358
359   if(!info.networkId.isValid()) {
360     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
361     return;
362   }
363
364   id = info.networkId.toInt();
365   if(!_networks.contains(id)) {
366     CoreNetwork *net = new CoreNetwork(id, this);
367     connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
368             this, SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
369     connect(net, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
370
371     net->setNetworkInfo(info);
372     net->setProxy(signalProxy());
373     _networks[id] = net;
374     signalProxy()->synchronize(net);
375     emit networkCreated(id);
376     // create persistent chans
377     foreach(QString channel, persistentChans) {
378       Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, channel, true);
379       Core::setChannelPersistent(user(), info.networkId, channel, true);
380     }
381   } else {
382     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
383     _networks[info.networkId]->requestSetNetworkInfo(info);
384   }
385 }
386
387 void CoreSession::removeNetwork(NetworkId id) {
388   // Make sure the network is disconnected!
389   CoreNetwork *net = network(id);
390   if(!net)
391     return;
392
393   if(net->connectionState() != Network::Disconnected) {
394     connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
395     net->disconnectFromIrc();
396   } else {
397     destroyNetwork(id);
398   }
399 }
400
401 void CoreSession::destroyNetwork(NetworkId id) {
402   QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
403   Network *net = _networks.take(id);
404   if(net && Core::removeNetwork(user(), id)) {
405     foreach(BufferId bufferId, removedBuffers) {
406       _bufferSyncer->removeBuffer(bufferId);
407     }
408     emit networkRemoved(id);
409     net->deleteLater();
410   }
411 }
412
413 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
414   BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
415   if(bufferInfo.isValid()) {
416     _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
417   }
418 }
419
420 void CoreSession::clientsConnected() {
421   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
422   Identity *identity = 0;
423   CoreNetwork *net = 0;
424   IrcUser *me = 0;
425   while(netIter != _networks.end()) {
426     net = *netIter;
427     netIter++;
428
429     if(!net->isConnected())
430       continue;
431     identity = net->identityPtr();
432     if(!identity)
433       continue;
434     me = net->me();
435     if(!me)
436       continue;
437
438     if(identity->detachAwayEnabled() && me->isAway()) {
439       net->userInputHandler()->handleAway(BufferInfo(), QString());
440     }
441   }
442 }
443
444 void CoreSession::clientsDisconnected() {
445   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
446   Identity *identity = 0;
447   CoreNetwork *net = 0;
448   IrcUser *me = 0;
449   QString awayReason;
450   while(netIter != _networks.end()) {
451     net = *netIter;
452     netIter++;
453
454     if(!net->isConnected())
455       continue;
456     identity = net->identityPtr();
457     if(!identity)
458       continue;
459     me = net->me();
460     if(!me)
461       continue;
462
463     if(identity->detachAwayEnabled() && !me->isAway()) {
464       if(!identity->detachAwayReason().isEmpty())
465         awayReason = identity->detachAwayReason();
466       net->setAutoAwayActive(true);
467       net->userInputHandler()->handleAway(BufferInfo(), awayReason);
468     }
469   }
470 }