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