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