Fitting the SyncableObjects to the new Style
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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 "corenetworkconfig.h"
32 #include "storage.h"
33
34 #include "coreidentity.h"
35 #include "corenetwork.h"
36 #include "ircuser.h"
37 #include "ircchannel.h"
38
39 #include "util.h"
40 #include "coreusersettings.h"
41 #include "logger.h"
42
43 class ProcessMessagesEvent : public QEvent {
44 public:
45   ProcessMessagesEvent() : QEvent(QEvent::User) {}
46 };
47
48 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
49   : QObject(parent),
50     _user(uid),
51     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
52     _aliasManager(this),
53     _bufferSyncer(new CoreBufferSyncer(this)),
54     _backlogManager(new CoreBacklogManager(this)),
55     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
56     _ircListHelper(new CoreIrcListHelper(this)),
57     _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
58     _coreInfo(this),
59     scriptEngine(new QScriptEngine(this)),
60     _processMessages(false)
61 {
62   SignalProxy *p = signalProxy();
63   connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
64
65   connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
66   connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
67
68   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
69   p->attachSignal(this, SIGNAL(displayMsg(Message)));
70   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
71
72   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
73   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
74   p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
75   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
76
77   p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
78   p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
79   p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
80   p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
81
82   loadSettings();
83   initScriptEngine();
84
85   connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferSyncer, SLOT(storeDirtyIds()));
86   connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), _bufferViewManager, SLOT(saveBufferViews()));
87
88   p->synchronize(_bufferSyncer);
89   p->synchronize(&aliasManager());
90   p->synchronize(_backlogManager);
91   p->synchronize(ircListHelper());
92   p->synchronize(networkConfig());
93   p->synchronize(&_coreInfo);
94
95   // Restore session state
96   if(restoreState)
97     restoreSessionState();
98
99   emit initialized();
100 }
101
102 CoreSession::~CoreSession() {
103   saveSessionState();
104   foreach(CoreNetwork *net, _networks.values()) {
105     delete net;
106   }
107 }
108
109 CoreNetwork *CoreSession::network(NetworkId id) const {
110   if(_networks.contains(id)) return _networks[id];
111   return 0;
112 }
113
114 CoreIdentity *CoreSession::identity(IdentityId id) const {
115   if(_identities.contains(id)) return _identities[id];
116   return 0;
117 }
118
119 void CoreSession::loadSettings() {
120   CoreUserSettings s(user());
121
122   // migrate to db
123   QList<IdentityId> ids = s.identityIds();
124   QList<NetworkInfo> networkInfos = Core::networks(user());
125   foreach(IdentityId id, ids) {
126     CoreIdentity identity(s.identity(id));
127     IdentityId newId = Core::createIdentity(user(), identity);
128     QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
129     while(networkIter != networkInfos.end()) {
130       if(networkIter->identity == id) {
131         networkIter->identity = newId;
132         Core::updateNetwork(user(), *networkIter);
133         networkIter = networkInfos.erase(networkIter);
134       } else {
135         networkIter++;
136       }
137     }
138     s.removeIdentity(id);
139   }
140   // end of migration
141
142   foreach(CoreIdentity identity, Core::identities(user())) {
143     createIdentity(identity);
144   }
145
146   foreach(NetworkInfo info, Core::networks(user())) {
147     createNetwork(info);
148   }
149 }
150
151 void CoreSession::saveSessionState() const {
152   _bufferSyncer->storeDirtyIds();
153   _bufferViewManager->saveBufferViews();
154   _networkConfig->save();
155 }
156
157 void CoreSession::restoreSessionState() {
158   QList<NetworkId> nets = Core::connectedNetworks(user());
159   CoreNetwork *net = 0;
160   foreach(NetworkId id, nets) {
161     net = network(id);
162     Q_ASSERT(net);
163     net->connectToIrc();
164   }
165 }
166
167 void CoreSession::addClient(QIODevice *device) {
168   if(!device) {
169     qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
170   } else {
171     // if the socket is an orphan, the signalProxy adopts it.
172     // -> we don't need to care about it anymore
173     device->setParent(0);
174     signalProxy()->addPeer(device);
175     QVariantMap reply;
176     reply["MsgType"] = "SessionInit";
177     reply["SessionState"] = sessionState();
178     SignalProxy::writeDataToDevice(device, reply);
179   }
180 }
181
182 void CoreSession::addClient(SignalProxy *proxy) {
183   signalProxy()->addPeer(proxy);
184   emit sessionState(sessionState());
185 }
186
187 void CoreSession::removeClient(QIODevice *iodev) {
188   QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
189   if(socket)
190     quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
191 }
192
193 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
194   return Core::persistentChannels(user(), id);
195 }
196
197 // FIXME switch to BufferId
198 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
199   CoreNetwork *net = network(bufinfo.networkId());
200   if(net) {
201     net->userInput(bufinfo, msg);
202   } else {
203     qWarning() << "Trying to send to unconnected network:" << msg;
204   }
205 }
206
207 // ALL messages coming pass through these functions before going to the GUI.
208 // So this is the perfect place for storing the backlog and log stuff.
209 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
210                                         const QString &target, const QString &text_, const QString &sender, Message::Flags flags) {
211
212   // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
213   // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
214   // KDE's notifications), hence we remove those just to be safe.
215   QString text = text_;
216   text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
217
218   _messageQueue << RawMessage(networkId, type, bufferType, target, text, sender, flags);
219   if(!_processMessages) {
220     _processMessages = true;
221     QCoreApplication::postEvent(this, new ProcessMessagesEvent());
222   }
223 }
224
225 void CoreSession::recvStatusMsgFromServer(QString msg) {
226   CoreNetwork *net = qobject_cast<CoreNetwork*>(sender());
227   Q_ASSERT(net);
228   emit displayStatusMsg(net->networkName(), msg);
229 }
230
231 QList<BufferInfo> CoreSession::buffers() const {
232   return Core::requestBuffers(user());
233 }
234
235 void CoreSession::customEvent(QEvent *event) {
236   if(event->type() != QEvent::User)
237     return;
238
239   processMessages();
240   event->accept();
241 }
242
243 void CoreSession::processMessages() {
244   if(_messageQueue.count() == 1) {
245     const RawMessage &rawMsg = _messageQueue.first();
246     BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
247     Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
248     Core::storeMessage(msg);
249     emit displayMsg(msg);
250   } else {
251     QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
252     MessageList messages;
253     BufferInfo bufferInfo;
254     for(int i = 0; i < _messageQueue.count(); i++) {
255       const RawMessage &rawMsg = _messageQueue.at(i);
256       if(bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
257         bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
258       } else {
259         bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target);
260         bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
261       }
262       messages << Message(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
263     }
264     Core::storeMessages(messages);
265     // FIXME: extend protocol to a displayMessages(MessageList)
266     for(int i = 0; i < messages.count(); i++) {
267       emit displayMsg(messages[i]);
268     }
269   }
270   _processMessages = false;
271   _messageQueue.clear();
272 }
273
274 QVariant CoreSession::sessionState() {
275   QVariantMap v;
276
277   QVariantList bufs;
278   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
279   v["BufferInfos"] = bufs;
280   QVariantList networkids;
281   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
282   v["NetworkIds"] = networkids;
283
284   quint32 ircusercount = 0;
285   quint32 ircchannelcount = 0;
286   foreach(Network *net, _networks.values()) {
287     ircusercount += net->ircUserCount();
288     ircchannelcount += net->ircChannelCount();
289   }
290   v["IrcUserCount"] = ircusercount;
291   v["IrcChannelCount"] = ircchannelcount;
292
293   QList<QVariant> idlist;
294   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
295   v["Identities"] = idlist;
296
297   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
298   return v;
299 }
300
301 void CoreSession::initScriptEngine() {
302   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
303   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
304
305   // FIXME
306   //QScriptValue storage_ = scriptEngine->newQObject(storage);
307   //scriptEngine->globalObject().setProperty("storage", storage_);
308 }
309
310 void CoreSession::scriptRequest(QString script) {
311   emit scriptResult(scriptEngine->evaluate(script).toString());
312 }
313
314 /*** Identity Handling ***/
315 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) {
316 #ifndef HAVE_SSL
317   Q_UNUSED(additional)
318 #endif
319
320   CoreIdentity coreIdentity(identity);
321 #ifdef HAVE_SSL
322   if(additional.contains("KeyPem"))
323     coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
324   if(additional.contains("CertPem"))
325     coreIdentity.setSslCert(additional["CertPem"].toByteArray());
326 #endif
327   qDebug() << Q_FUNC_INFO;
328   IdentityId id = Core::createIdentity(user(), coreIdentity);
329   if(!id.isValid())
330     return;
331   else
332     createIdentity(coreIdentity);
333 }
334
335 void CoreSession::createIdentity(const CoreIdentity &identity) {
336   CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
337   _identities[identity.id()] = coreIdentity;
338   // CoreIdentity has it's own synchronize method since it's "private" sslManager needs to be synced aswell
339   coreIdentity->synchronize(signalProxy());
340   connect(coreIdentity, SIGNAL(updated(const QVariantMap &)), this, SLOT(updateIdentityBySender()));
341   emit identityCreated(*coreIdentity);
342 }
343
344 void CoreSession::updateIdentityBySender() {
345   CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
346   if(!identity)
347     return;
348   Core::updateIdentity(user(), *identity);
349 }
350
351 void CoreSession::removeIdentity(IdentityId id) {
352   CoreIdentity *identity = _identities.take(id);
353   if(identity) {
354     emit identityRemoved(id);
355     Core::removeIdentity(user(), id);
356     identity->deleteLater();
357   }
358 }
359
360 /*** Network Handling ***/
361
362 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) {
363   NetworkInfo info = info_;
364   int id;
365
366   if(!info.networkId.isValid())
367     Core::createNetwork(user(), info);
368
369   if(!info.networkId.isValid()) {
370     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
371     return;
372   }
373
374   id = info.networkId.toInt();
375   if(!_networks.contains(id)) {
376
377     // create persistent chans
378     QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
379     foreach(QString channel, persistentChans) {
380       if(!rx.exactMatch(channel)) {
381         qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
382         continue;
383       }
384       Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
385       Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
386       if(!rx.cap(2).isEmpty())
387         Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
388     }
389
390     CoreNetwork *net = new CoreNetwork(id, this);
391     connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
392                  SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
393     connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
394
395     net->setNetworkInfo(info);
396     net->setProxy(signalProxy());
397     _networks[id] = net;
398     signalProxy()->synchronize(net);
399     emit networkCreated(id);
400   } else {
401     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
402     _networks[info.networkId]->requestSetNetworkInfo(info);
403   }
404 }
405
406 void CoreSession::removeNetwork(NetworkId id) {
407   // Make sure the network is disconnected!
408   CoreNetwork *net = network(id);
409   if(!net)
410     return;
411
412   if(net->connectionState() != Network::Disconnected) {
413     connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
414     net->disconnectFromIrc();
415   } else {
416     destroyNetwork(id);
417   }
418 }
419
420 void CoreSession::destroyNetwork(NetworkId id) {
421   QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
422   Network *net = _networks.take(id);
423   if(net && Core::removeNetwork(user(), id)) {
424     foreach(BufferId bufferId, removedBuffers) {
425       _bufferSyncer->removeBuffer(bufferId);
426     }
427     emit networkRemoved(id);
428     net->deleteLater();
429   }
430 }
431
432 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
433   BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
434   if(bufferInfo.isValid()) {
435     _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
436   }
437 }
438
439 void CoreSession::clientsConnected() {
440   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
441   Identity *identity = 0;
442   CoreNetwork *net = 0;
443   IrcUser *me = 0;
444   while(netIter != _networks.end()) {
445     net = *netIter;
446     netIter++;
447
448     if(!net->isConnected())
449       continue;
450     identity = net->identityPtr();
451     if(!identity)
452       continue;
453     me = net->me();
454     if(!me)
455       continue;
456
457     if(identity->detachAwayEnabled() && me->isAway()) {
458       net->userInputHandler()->handleAway(BufferInfo(), QString());
459     }
460   }
461 }
462
463 void CoreSession::clientsDisconnected() {
464   QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
465   Identity *identity = 0;
466   CoreNetwork *net = 0;
467   IrcUser *me = 0;
468   QString awayReason;
469   while(netIter != _networks.end()) {
470     net = *netIter;
471     netIter++;
472
473     if(!net->isConnected())
474       continue;
475     identity = net->identityPtr();
476     if(!identity)
477       continue;
478     me = net->me();
479     if(!me)
480       continue;
481
482     if(identity->detachAwayEnabled() && !me->isAway()) {
483       if(!identity->detachAwayReason().isEmpty())
484         awayReason = identity->detachAwayReason();
485       net->setAutoAwayActive(true);
486       net->userInputHandler()->handleAway(BufferInfo(), awayReason);
487     }
488   }
489 }