Fixing BR #374 (hide marked as away messages when using away on detach)
[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 "networkconnection.h"
26 #include "userinputhandler.h"
27
28 #include "signalproxy.h"
29 #include "buffersyncer.h"
30 #include "corebacklogmanager.h"
31 #include "corebufferviewmanager.h"
32 #include "coreirclisthelper.h"
33 #include "storage.h"
34
35 #include "corenetwork.h"
36 #include "ircuser.h"
37 #include "ircchannel.h"
38 #include "identity.h"
39
40 #include "util.h"
41 #include "coreusersettings.h"
42 #include "logger.h"
43
44 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
45   : QObject(parent),
46     _user(uid),
47     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
48     _aliasManager(this),
49     _bufferSyncer(new BufferSyncer(this)),
50     _backlogManager(new CoreBacklogManager(this)),
51     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
52     _ircListHelper(new CoreIrcListHelper(this)),
53     _coreInfo(this),
54     scriptEngine(new QScriptEngine(this))
55 {
56
57   SignalProxy *p = signalProxy();
58   connect(p, SIGNAL(peerRemoved(QIODevice *)), this, SLOT(removeClient(QIODevice *)));
59
60   connect(p, SIGNAL(connected()), this, SLOT(clientsConnected()));
61   connect(p, SIGNAL(disconnected()), this, SLOT(clientsDisconnected()));
62
63   //p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
64   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
65   p->attachSignal(this, SIGNAL(displayMsg(Message)));
66   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
67   p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
68
69   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
70   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
71   p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
72   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
73
74   p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
75   p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
76   p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
77   p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
78
79   loadSettings();
80   initScriptEngine();
81
82   // init BufferSyncer
83   QHash<BufferId, MsgId> lastSeenHash = Core::bufferLastSeenMsgIds(user());
84   foreach(BufferId id, lastSeenHash.keys())
85     _bufferSyncer->requestSetLastSeenMsg(id, lastSeenHash[id]);
86
87   connect(_bufferSyncer, SIGNAL(lastSeenMsgSet(BufferId, MsgId)), this, SLOT(storeBufferLastSeenMsg(BufferId, MsgId)));
88   connect(_bufferSyncer, SIGNAL(removeBufferRequested(BufferId)), this, SLOT(removeBufferRequested(BufferId)));
89   connect(this, SIGNAL(bufferRemoved(BufferId)), _bufferSyncer, SLOT(removeBuffer(BufferId)));
90   connect(this, SIGNAL(bufferRenamed(BufferId, QString)), _bufferSyncer, SLOT(renameBuffer(BufferId, QString)));
91   p->synchronize(_bufferSyncer);
92
93
94   // init alias manager
95   p->synchronize(&aliasManager());
96
97   // init BacklogManager
98   p->synchronize(_backlogManager);
99
100   // init IrcListHelper
101   p->synchronize(ircListHelper());
102
103   // init CoreInfo
104   p->synchronize(&_coreInfo);
105
106   // Restore session state
107   if(restoreState) restoreSessionState();
108
109   emit initialized();
110 }
111
112 CoreSession::~CoreSession() {
113   saveSessionState();
114   foreach(NetworkConnection *conn, _connections.values()) {
115     delete conn;
116   }
117   foreach(CoreNetwork *net, _networks.values()) {
118     delete net;
119   }
120 }
121
122 CoreNetwork *CoreSession::network(NetworkId id) const {
123   if(_networks.contains(id)) return _networks[id];
124   return 0;
125 }
126
127 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
128   if(_connections.contains(id)) return _connections[id];
129   return 0;
130 }
131
132 Identity *CoreSession::identity(IdentityId id) const {
133   if(_identities.contains(id)) return _identities[id];
134   return 0;
135 }
136
137 void CoreSession::loadSettings() {
138   CoreUserSettings s(user());
139
140   foreach(IdentityId id, s.identityIds()) {
141     Identity *i = new Identity(s.identity(id), this);
142     if(!i->isValid()) {
143       qWarning() << "Invalid identity! Removing...";
144       s.removeIdentity(id);
145       delete i;
146       continue;
147     }
148     if(_identities.contains(i->id())) {
149       qWarning() << "Duplicate identity, ignoring!";
150       delete i;
151       continue;
152     }
153     connect(i, SIGNAL(updated(const QVariantMap &)), this, SLOT(identityUpdated(const QVariantMap &)));
154     _identities[i->id()] = i;
155     signalProxy()->synchronize(i);
156   }
157   if(!_identities.count()) {
158     Identity i(1);
159     i.setToDefaults();
160     i.setIdentityName(tr("Default Identity"));
161     createIdentity(i);
162   }
163
164   foreach(NetworkInfo info, Core::networks(user())) {
165     createNetwork(info);
166   }
167 }
168
169 void CoreSession::saveSessionState() const {
170
171 }
172
173 void CoreSession::restoreSessionState() {
174   QList<NetworkId> nets = Core::connectedNetworks(user());
175   foreach(NetworkId id, nets) {
176     connectToNetwork(id);
177   }
178 }
179
180 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
181   if(uid == user()) emit bufferInfoUpdated(bufinfo);
182 }
183
184 void CoreSession::connectToNetwork(NetworkId id) {
185   CoreNetwork *net = network(id);
186   if(!net) {
187     qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
188     return;
189   }
190
191   NetworkConnection *conn = networkConnection(id);
192   if(!conn) {
193     conn = new NetworkConnection(net, this);
194     _connections[id] = conn;
195     attachNetworkConnection(conn);
196   }
197   conn->connectToIrc();
198 }
199
200 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
201   connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
202   connect(conn, SIGNAL(quitRequested(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
203
204   // I guess we don't need these anymore, client-side can just connect the network's signals directly
205   //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
206   //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
207
208   connect(conn, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)),
209           this, SLOT(recvMessageFromServer(Message::Type, BufferInfo::Type, QString, QString, QString, Message::Flags)));
210   connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
211
212   connect(conn, SIGNAL(nickChanged(const NetworkId &, const QString &, const QString &)),
213           this, SLOT(renameBuffer(const NetworkId &, const QString &, const QString &)));
214   connect(conn, SIGNAL(channelJoined(NetworkId, const QString &, const QString &)),
215           this, SLOT(channelJoined(NetworkId, const QString &, const QString &)));
216   connect(conn, SIGNAL(channelParted(NetworkId, const QString &)),
217           this, SLOT(channelParted(NetworkId, const QString &)));
218 }
219
220 void CoreSession::disconnectFromNetwork(NetworkId id) {
221   if(!_connections.contains(id))
222     return;
223
224   //_connections[id]->disconnectFromIrc();
225   _connections[id]->userInputHandler()->handleQuit(BufferInfo(), QString());
226 }
227
228 void CoreSession::networkStateRequested() {
229 }
230
231 void CoreSession::addClient(QIODevice *device) {
232   if(!device) {
233     qCritical() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
234   } else {
235     // if the socket is an orphan, the signalProxy adopts it.
236     // -> we don't need to care about it anymore
237     device->setParent(0);
238     signalProxy()->addPeer(device);
239     QVariantMap reply;
240     reply["MsgType"] = "SessionInit";
241     reply["SessionState"] = sessionState();
242     SignalProxy::writeDataToDevice(device, reply);
243   }
244 }
245
246 void CoreSession::addClient(SignalProxy *proxy) {
247   signalProxy()->addPeer(proxy);
248   emit sessionState(sessionState());
249 }
250
251 void CoreSession::removeClient(QIODevice *iodev) {
252   QTcpSocket *socket = qobject_cast<QTcpSocket *>(iodev);
253   if(socket)
254     quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
255 }
256
257 SignalProxy *CoreSession::signalProxy() const {
258   return _signalProxy;
259 }
260
261 // FIXME we need a sane way for creating buffers!
262 void CoreSession::networkConnected(NetworkId networkid) {
263   Core::bufferInfo(user(), networkid, BufferInfo::StatusBuffer); // create status buffer
264   Core::setNetworkConnected(user(), networkid, true);
265 }
266
267 // called now only on /quit and requested disconnects, not on normal disconnects!
268 void CoreSession::networkDisconnected(NetworkId networkid) {
269   // if the network has already been removed, we don't have a networkconnection left either, so we don't do anything
270   // make sure to not depend on the network still existing when calling this function!
271   if(_connections.contains(networkid)) {
272     Core::setNetworkConnected(user(), networkid, false);
273     _connections.take(networkid)->deleteLater();
274   }
275 }
276
277 void CoreSession::channelJoined(NetworkId id, const QString &channel, const QString &key) {
278   Core::setChannelPersistent(user(), id, channel, true);
279   Core::setPersistentChannelKey(user(), id, channel, key);
280 }
281
282 void CoreSession::channelParted(NetworkId id, const QString &channel) {
283   Core::setChannelPersistent(user(), id, channel, false);
284 }
285
286 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const {
287   return Core::persistentChannels(user(), id);
288   return QHash<QString, QString>();
289 }
290
291 // FIXME switch to BufferId
292 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
293   NetworkConnection *conn = networkConnection(bufinfo.networkId());
294   if(conn) {
295     conn->userInput(bufinfo, msg);
296   } else {
297     qWarning() << "Trying to send to unconnected network:" << msg;
298   }
299 }
300
301 // ALL messages coming pass through these functions before going to the GUI.
302 // So this is the perfect place for storing the backlog and log stuff.
303 void CoreSession::recvMessageFromServer(Message::Type type, BufferInfo::Type bufferType,
304                                         QString target, QString text, QString sender, Message::Flags flags) {
305   NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
306   Q_ASSERT(netCon);
307
308   BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), bufferType, target);
309   Message msg(bufferInfo, type, text, sender, flags);
310   msg.setMsgId(Core::storeMessage(msg));
311   Q_ASSERT(msg.msgId() != 0);
312   emit displayMsg(msg);
313 }
314
315 void CoreSession::recvStatusMsgFromServer(QString msg) {
316   NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
317   Q_ASSERT(s);
318   emit displayStatusMsg(s->networkName(), msg);
319 }
320
321 QList<BufferInfo> CoreSession::buffers() const {
322   return Core::requestBuffers(user());
323 }
324
325
326 QVariant CoreSession::sessionState() {
327   QVariantMap v;
328
329   QVariantList bufs;
330   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
331   v["BufferInfos"] = bufs;
332   QVariantList networkids;
333   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
334   v["NetworkIds"] = networkids;
335
336   quint32 ircusercount = 0;
337   quint32 ircchannelcount = 0;
338   foreach(Network *net, _networks.values()) {
339     ircusercount += net->ircUserCount();
340     ircchannelcount += net->ircChannelCount();
341   }
342   v["IrcUserCount"] = ircusercount;
343   v["IrcChannelCount"] = ircchannelcount;
344
345   QList<QVariant> idlist;
346   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
347   v["Identities"] = idlist;
348
349   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
350   return v;
351 }
352
353 void CoreSession::storeBufferLastSeenMsg(BufferId buffer, const MsgId &msgId) {
354   Core::setBufferLastSeenMsg(user(), buffer, msgId);
355 }
356
357 void CoreSession::initScriptEngine() {
358   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
359   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
360
361   // FIXME
362   //QScriptValue storage_ = scriptEngine->newQObject(storage);
363   //scriptEngine->globalObject().setProperty("storage", storage_);
364 }
365
366 void CoreSession::scriptRequest(QString script) {
367   emit scriptResult(scriptEngine->evaluate(script).toString());
368 }
369
370 /*** Identity Handling ***/
371
372 void CoreSession::createIdentity(const Identity &id) {
373   // find free ID
374   int i;
375   for(i = 1; i <= _identities.count(); i++) {
376     if(!_identities.keys().contains(i)) break;
377   }
378   //qDebug() << "found free id" << i;
379   Identity *newId = new Identity(id, this);
380   newId->setId(i);
381   _identities[i] = newId;
382   signalProxy()->synchronize(newId);
383   CoreUserSettings s(user());
384   s.storeIdentity(*newId);
385   connect(newId, SIGNAL(updated(const QVariantMap &)), this, SLOT(identityUpdated(const QVariantMap &)));
386   emit identityCreated(*newId);
387 }
388
389 void CoreSession::removeIdentity(IdentityId id) {
390   Identity *i = _identities.take(id);
391   if(i) {
392     emit identityRemoved(id);
393     CoreUserSettings s(user());
394     s.removeIdentity(id);
395     i->deleteLater();
396   }
397 }
398
399 void CoreSession::identityUpdated(const QVariantMap &data) {
400   IdentityId id = data.value("identityId", 0).value<IdentityId>();
401   if(!id.isValid() || !_identities.contains(id)) {
402     qWarning() << "Update request for unknown identity received!";
403     return;
404   }
405   CoreUserSettings s(user());
406   s.storeIdentity(*_identities.value(id));
407 }
408
409 /*** Network Handling ***/
410
411 void CoreSession::createNetwork(const NetworkInfo &info_) {
412   NetworkInfo info = info_;
413   int id;
414
415   if(!info.networkId.isValid())
416     Core::createNetwork(user(), info);
417
418   if(!info.networkId.isValid()) {
419     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
420     return;
421   }
422
423   id = info.networkId.toInt();
424   if(!_networks.contains(id)) {
425     CoreNetwork *net = new CoreNetwork(id, this);
426     connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
427     connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
428     net->setNetworkInfo(info);
429     net->setProxy(signalProxy());
430     _networks[id] = net;
431     signalProxy()->synchronize(net);
432     emit networkCreated(id);
433   } else {
434     qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
435     _networks[info.networkId]->requestSetNetworkInfo(info);
436   }
437 }
438
439 void CoreSession::removeNetwork(NetworkId id) {
440   // Make sure the network is disconnected!
441   NetworkConnection *conn = _connections.value(id, 0);
442   if(conn) {
443     if(conn->connectionState() != Network::Disconnected) {
444       connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
445       conn->disconnectFromIrc();
446     } else {
447       _connections.take(id)->deleteLater();  // TODO make this saner
448       destroyNetwork(id);
449     }
450   } else {
451     destroyNetwork(id);
452   }
453 }
454
455 void CoreSession::destroyNetwork(NetworkId id) {
456   if(_connections.contains(id)) {
457     // this can happen if the network was reconnecting while being removed
458     _connections.take(id)->deleteLater();
459   }
460   QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
461   Network *net = _networks.take(id);
462   if(net && Core::removeNetwork(user(), id)) {
463     foreach(BufferId bufferId, removedBuffers) {
464       _bufferSyncer->removeBuffer(bufferId);
465     }
466     emit networkRemoved(id);
467     net->deleteLater();
468   }
469 }
470
471 void CoreSession::removeBufferRequested(BufferId bufferId) {
472   BufferInfo bufferInfo = Core::getBufferInfo(user(), bufferId);
473   if(!bufferInfo.isValid()) {
474     qWarning() << "CoreSession::removeBufferRequested(): invalid BufferId:" << bufferId << "for User:" << user();
475     return;
476   }
477
478   if(bufferInfo.type() == BufferInfo::StatusBuffer) {
479     qWarning() << "CoreSession::removeBufferRequested(): Status Buffers cannot be removed!";
480     return;
481   }
482
483   if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
484     CoreNetwork *net = network(bufferInfo.networkId());
485     if(!net) {
486       qWarning() << "CoreSession::removeBufferRequested(): Received BufferInfo with unknown networkId!";
487       return;
488     }
489     IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
490     if(chan) {
491       qWarning() << "CoreSession::removeBufferRequested(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
492       return;
493     }
494   }
495   if(Core::removeBuffer(user(), bufferId))
496     emit bufferRemoved(bufferId);
497 }
498
499 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) {
500   BufferId bufferId = Core::renameBuffer(user(), networkId, newName, oldName);
501   if(bufferId.isValid()) {
502     emit bufferRenamed(bufferId, newName);
503   }
504 }
505
506 void CoreSession::clientsConnected() {
507   QHash<NetworkId, NetworkConnection *>::iterator conIter = _connections.begin();
508   Identity *identity = 0;
509   NetworkConnection *con = 0;
510   Network *network = 0;
511   IrcUser *me = 0;
512   QString awayReason;
513   while(conIter != _connections.end()) {
514     con = *conIter;
515     conIter++;
516
517     if(!con->isConnected())
518       continue;
519     identity = con->identity();
520     if(!identity)
521       continue;
522     network = con->network();
523     if(!network)
524       continue;
525     me = network->me();
526     if(!me)
527       continue;
528
529     if(identity->detachAwayEnabled() && me->isAway()) {
530       con->userInputHandler()->handleAway(BufferInfo(), QString());
531     }
532   }
533 }
534
535 void CoreSession::clientsDisconnected() {
536   QHash<NetworkId, NetworkConnection *>::iterator conIter = _connections.begin();
537   Identity *identity = 0;
538   NetworkConnection *con = 0;
539   Network *network = 0;
540   IrcUser *me = 0;
541   QString awayReason;
542   while(conIter != _connections.end()) {
543     con = *conIter;
544     conIter++;
545
546     if(!con->isConnected())
547       continue;
548     identity = con->identity();
549     if(!identity)
550       continue;
551     network = con->network();
552     if(!network)
553       continue;
554     me = network->me();
555     if(!me)
556       continue;
557
558     if(identity->detachAwayEnabled() && !me->isAway()) {
559       if(identity->detachAwayReasonEnabled())
560         awayReason = identity->detachAwayReason();
561       else
562         awayReason = identity->awayReason();
563       network->setAutoAwayActive(true);
564       con->userInputHandler()->handleAway(BufferInfo(), awayReason);
565     }
566   }
567 }