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