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