fd9a872e60c4adf03d2caab2862d1157f5375d15
[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   connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferSyncer, SLOT(storeDirtyIds()));
85   p->synchronize(_bufferSyncer);
86
87
88   // init alias manager
89   p->synchronize(&aliasManager());
90
91   // init BacklogManager
92   p->synchronize(_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::storeBufferLastSeenMsg(BufferId buffer, const MsgId &msgId) {
269   Core::setBufferLastSeenMsg(user(), buffer, msgId);
270 }
271
272 void CoreSession::initScriptEngine() {
273   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
274   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
275
276   // FIXME
277   //QScriptValue storage_ = scriptEngine->newQObject(storage);
278   //scriptEngine->globalObject().setProperty("storage", storage_);
279 }
280
281 void CoreSession::scriptRequest(QString script) {
282   emit scriptResult(scriptEngine->evaluate(script).toString());
283 }
284
285 /*** Identity Handling ***/
286 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
287 #ifndef HAVE_SSL
288   Q_UNUSED(additional)
289 #endif
290
291   CoreIdentity coreIdentity(identity);
292 #ifdef HAVE_SSL
293   if(additional.contains("KeyPem"))
294     coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
295   if(additional.contains("CertPem"))
296     coreIdentity.setSslCert(additional["CertPem"].toByteArray());
297 #endif
298   IdentityId id = Core::createIdentity(user(), coreIdentity);
299   if(!id.isValid())
300     return;
301   else
302     createIdentity(coreIdentity);
303 }
304
305 void CoreSession::createIdentity(const CoreIdentity &identity) {
306   CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
307   _identities[identity.id()] = coreIdentity;
308   // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
309   coreIdentity->synchronize(signalProxy());
310   connect(coreIdentity, SIGNAL(updated(const QVariantMap &)), this, SLOT(updateIdentityBySender()));
311   emit identityCreated(*coreIdentity);
312 }
313
314 void CoreSession::updateIdentityBySender() {
315   CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
316   if(!identity)
317     return;
318   Core::updateIdentity(user(), *identity);
319 }
320
321 void CoreSession::removeIdentity(IdentityId id) {
322   CoreIdentity *identity = _identities.take(id);
323   if(identity) {
324     emit identityRemoved(id);
325     Core::removeIdentity(user(), id);
326     identity->deleteLater();
327   }
328 }
329
330 /*** Network Handling ***/
331
332 void CoreSession::createNetwork(const NetworkInfo &info_) {
333   NetworkInfo info = info_;
334   int id;
335
336   if(!info.networkId.isValid())
337     Core::createNetwork(user(), info);
338
339   if(!info.networkId.isValid()) {
340     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
341     return;
342   }
343
344   id = info.networkId.toInt();
345   if(!_networks.contains(id)) {
346     CoreNetwork *net = new CoreNetwork(id, this);
347     connect(net, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)),
348             this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)));
349     connect(net, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
350
351     net->setNetworkInfo(info);
352     net->setProxy(signalProxy());
353     _networks[id] = net;
354     signalProxy()->synchronize(net);
355     emit networkCreated(id);
356   } else {
357     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
358     _networks[info.networkId]->requestSetNetworkInfo(info);
359   }
360 }
361
362 void CoreSession::removeNetwork(NetworkId id) {
363   // Make sure the network is disconnected!
364   CoreNetwork *net = network(id);
365   if(!net)
366     return;
367
368   if(net->connectionState() != Network::Disconnected) {
369     connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
370     net->disconnectFromIrc();
371   } else {
372     destroyNetwork(id);
373   }
374 }
375
376 void CoreSession::destroyNetwork(NetworkId id) {
377   QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
378   Network *net = _networks.take(id);
379   if(net && Core::removeNetwork(user(), id)) {
380     foreach(BufferId bufferId, removedBuffers) {
381       _bufferSyncer->removeBuffer(bufferId);
382     }
383     emit networkRemoved(id);
384     net->deleteLater();
385   }
386 }
387
388 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
389   BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName);
390   _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
391 }
392
393 void CoreSession::clientsConnected() {
394   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
395   Identity *identity = 0;
396   CoreNetwork *net = 0;
397   IrcUser *me = 0;
398   QString awayReason;
399   while(netIter != _networks.end()) {
400     net = *netIter;
401     netIter++;
402
403     if(!net->isConnected())
404       continue;
405     identity = net->identityPtr();
406     if(!identity)
407       continue;
408     me = net->me();
409     if(!me)
410       continue;
411
412     if(identity->detachAwayEnabled() && me->isAway()) {
413       net->userInputHandler()->handleAway(BufferInfo(), QString());
414     }
415   }
416 }
417
418 void CoreSession::clientsDisconnected() {
419   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
420   Identity *identity = 0;
421   CoreNetwork *net = 0;
422   IrcUser *me = 0;
423   QString awayReason;
424   while(netIter != _networks.end()) {
425     net = *netIter;
426     netIter++;
427
428     if(!net->isConnected())
429       continue;
430     identity = net->identityPtr();
431     if(!identity)
432       continue;
433     me = net->me();
434     if(!me)
435       continue;
436
437     if(identity->detachAwayEnabled() && !me->isAway()) {
438       if(identity->detachAwayReasonEnabled())
439         awayReason = identity->detachAwayReason();
440       else
441         awayReason = identity->awayReason();
442       net->setAutoAwayActive(true);
443       net->userInputHandler()->handleAway(BufferInfo(), awayReason);
444     }
445   }
446 }