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