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