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