1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
23 #include "abstractmessageprocessor.h"
24 #include "abstractui.h"
25 #include "bufferinfo.h"
26 #include "buffermodel.h"
27 #include "buffersettings.h"
28 #include "buffersyncer.h"
29 #include "bufferviewconfig.h"
30 #include "bufferviewoverlay.h"
31 #include "clientaliasmanager.h"
32 #include "clientbacklogmanager.h"
33 #include "clientbufferviewmanager.h"
34 #include "clientirclisthelper.h"
35 #include "clientidentity.h"
36 #include "clientignorelistmanager.h"
37 #include "clienttransfermanager.h"
38 #include "clientuserinputhandler.h"
39 #include "coreaccountmodel.h"
40 #include "coreconnection.h"
41 #include "dccconfig.h"
42 #include "ircchannel.h"
45 #include "messagemodel.h"
47 #include "networkconfig.h"
48 #include "networkmodel.h"
50 #include "signalproxy.h"
51 #include "transfermodel.h"
53 #include "clientauthhandler.h"
58 Client::Client(std::unique_ptr<AbstractUi> ui, QObject *parent)
59 : QObject(parent), Singleton<Client>(this),
60 _signalProxy(new SignalProxy(SignalProxy::Client, this)),
61 _mainUi(std::move(ui)),
62 _networkModel(new NetworkModel(this)),
63 _bufferModel(new BufferModel(_networkModel)),
64 _backlogManager(new ClientBacklogManager(this)),
65 _bufferViewOverlay(new BufferViewOverlay(this)),
66 _coreInfo(new CoreInfo(this)),
67 _ircListHelper(new ClientIrcListHelper(this)),
68 _inputHandler(new ClientUserInputHandler(this)),
69 _transferModel(new TransferModel(this)),
70 _messageModel(_mainUi->createMessageModel(this)),
71 _messageProcessor(_mainUi->createMessageProcessor(this)),
72 _coreAccountModel(new CoreAccountModel(this)),
73 _coreConnection(new CoreConnection(this))
76 Q_INIT_RESOURCE(data);
79 //connect(mainUi(), SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
80 connect(mainUi(), SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
81 connect(this, SIGNAL(connected()), mainUi(), SLOT(connectedToCore()));
82 connect(this, SIGNAL(disconnected()), mainUi(), SLOT(disconnectedFromCore()));
84 connect(this, SIGNAL(networkRemoved(NetworkId)), _networkModel, SLOT(networkRemoved(NetworkId)));
85 connect(this, SIGNAL(networkRemoved(NetworkId)), _messageProcessor, SLOT(networkRemoved(NetworkId)));
87 connect(backlogManager(), SIGNAL(messagesReceived(BufferId, int)), _messageModel, SLOT(messagesReceived(BufferId, int)));
88 connect(coreConnection(), SIGNAL(stateChanged(CoreConnection::ConnectionState)), SLOT(connectionStateChanged(CoreConnection::ConnectionState)));
90 SignalProxy *p = signalProxy();
92 p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &)));
93 p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
95 p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), _networkModel, SLOT(bufferUpdated(BufferInfo)));
96 p->attachSignal(inputHandler(), SIGNAL(sendInput(BufferInfo, QString)));
97 p->attachSignal(this, SIGNAL(requestNetworkStates()));
99 p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &, const QVariantMap &)), SIGNAL(createIdentity(const Identity &, const QVariantMap &)));
100 p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
101 p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
102 p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
104 p->attachSignal(this, SIGNAL(requestCreateNetwork(const NetworkInfo &, const QStringList &)), SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)));
105 p->attachSignal(this, SIGNAL(requestRemoveNetwork(NetworkId)), SIGNAL(removeNetwork(NetworkId)));
106 p->attachSlot(SIGNAL(networkCreated(NetworkId)), this, SLOT(coreNetworkCreated(NetworkId)));
107 p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, SLOT(coreNetworkRemoved(NetworkId)));
109 p->attachSignal(this, SIGNAL(requestPasswordChange(PeerPtr,QString,QString,QString)), SIGNAL(changePassword(PeerPtr,QString,QString,QString)));
110 p->attachSlot(SIGNAL(passwordChanged(PeerPtr,bool)), this, SLOT(corePasswordChanged(PeerPtr,bool)));
112 p->attachSignal(this, SIGNAL(requestKickClient(int)), SIGNAL(kickClient(int)));
113 p->attachSlot(SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
115 p->synchronize(backlogManager());
116 p->synchronize(coreInfo());
117 p->synchronize(_ircListHelper);
119 coreAccountModel()->load();
120 coreConnection()->init();
126 disconnectFromCore();
130 AbstractUi *Client::mainUi()
132 return instance()->_mainUi.get();
136 bool Client::isCoreFeatureEnabled(Quassel::Feature feature)
138 return coreConnection()->peer() ? coreConnection()->peer()->hasFeature(feature) : false;
142 bool Client::isConnected()
144 return instance()->_connected;
148 bool Client::internalCore()
150 return currentCoreAccount().isInternal();
154 void Client::onDbUpgradeInProgress(bool inProgress)
156 emit dbUpgradeInProgress(inProgress);
160 void Client::onExitRequested(int exitCode, const QString &reason)
162 if (!reason.isEmpty()) {
163 qCritical() << reason;
164 emit exitRequested(reason);
166 QCoreApplication::exit(exitCode);
170 /*** Network handling ***/
172 QList<NetworkId> Client::networkIds()
174 return instance()->_networks.keys();
178 const Network *Client::network(NetworkId networkid)
180 if (instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
185 void Client::createNetwork(const NetworkInfo &info, const QStringList &persistentChannels)
187 emit instance()->requestCreateNetwork(info, persistentChannels);
191 void Client::removeNetwork(NetworkId id)
193 emit instance()->requestRemoveNetwork(id);
197 void Client::updateNetwork(const NetworkInfo &info)
199 Network *netptr = instance()->_networks.value(info.networkId, 0);
201 qWarning() << "Update for unknown network requested:" << info;
204 netptr->requestSetNetworkInfo(info);
208 void Client::addNetwork(Network *net)
210 net->setProxy(signalProxy());
211 signalProxy()->synchronize(net);
212 networkModel()->attachNetwork(net);
213 connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
214 instance()->_networks[net->networkId()] = net;
215 emit instance()->networkCreated(net->networkId());
219 void Client::coreNetworkCreated(NetworkId id)
221 if (_networks.contains(id)) {
222 qWarning() << "Creation of already existing network requested!";
225 Network *net = new Network(id, this);
230 void Client::coreNetworkRemoved(NetworkId id)
232 if (!_networks.contains(id))
234 Network *net = _networks.take(id);
235 emit networkRemoved(net->networkId());
240 /*** Identity handling ***/
242 QList<IdentityId> Client::identityIds()
244 return instance()->_identities.keys();
248 const Identity *Client::identity(IdentityId id)
250 if (instance()->_identities.contains(id)) return instance()->_identities[id];
255 void Client::createIdentity(const CertIdentity &id)
257 QVariantMap additional;
259 additional["KeyPem"] = id.sslKey().toPem();
260 additional["CertPem"] = id.sslCert().toPem();
262 emit instance()->requestCreateIdentity(id, additional);
266 void Client::updateIdentity(IdentityId id, const QVariantMap &ser)
268 Identity *idptr = instance()->_identities.value(id, 0);
270 qWarning() << "Update for unknown identity requested:" << id;
273 idptr->requestUpdate(ser);
277 void Client::removeIdentity(IdentityId id)
279 emit instance()->requestRemoveIdentity(id);
283 void Client::coreIdentityCreated(const Identity &other)
285 if (!_identities.contains(other.id())) {
286 Identity *identity = new Identity(other, this);
287 _identities[other.id()] = identity;
288 identity->setInitialized();
289 signalProxy()->synchronize(identity);
290 emit identityCreated(other.id());
293 qWarning() << tr("Identity already exists in client!");
298 void Client::coreIdentityRemoved(IdentityId id)
300 if (_identities.contains(id)) {
301 emit identityRemoved(id);
302 Identity *i = _identities.take(id);
308 /*** User input handling ***/
310 void Client::userInput(const BufferInfo &bufferInfo, const QString &message)
312 // we need to make sure that AliasManager is ready before processing input
313 if (aliasManager() && aliasManager()->isInitialized())
314 inputHandler()->handleUserInput(bufferInfo, message);
316 instance()->_userInputBuffer.append(qMakePair(bufferInfo, message));
320 void Client::sendBufferedUserInput()
322 for (int i = 0; i < _userInputBuffer.count(); i++)
323 userInput(_userInputBuffer.at(i).first, _userInputBuffer.at(i).second);
325 _userInputBuffer.clear();
329 /*** core connection stuff ***/
331 void Client::connectionStateChanged(CoreConnection::ConnectionState state)
334 case CoreConnection::Disconnected:
335 setDisconnectedFromCore();
337 case CoreConnection::Synchronized:
346 void Client::setSyncedToCore()
348 // create buffersyncer
349 Q_ASSERT(!_bufferSyncer);
350 _bufferSyncer = new BufferSyncer(this);
351 connect(bufferSyncer(), SIGNAL(lastSeenMsgSet(BufferId, MsgId)), _networkModel, SLOT(setLastSeenMsgId(BufferId, MsgId)));
352 connect(bufferSyncer(), SIGNAL(markerLineSet(BufferId, MsgId)), _networkModel, SLOT(setMarkerLineMsgId(BufferId, MsgId)));
353 connect(bufferSyncer(), SIGNAL(bufferRemoved(BufferId)), this, SLOT(bufferRemoved(BufferId)));
354 connect(bufferSyncer(), SIGNAL(bufferRenamed(BufferId, QString)), this, SLOT(bufferRenamed(BufferId, QString)));
355 connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), this, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
356 connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), _messageModel, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
357 connect(bufferSyncer(), SIGNAL(bufferMarkedAsRead(BufferId)), SIGNAL(bufferMarkedAsRead(BufferId)));
358 connect(bufferSyncer(), SIGNAL(bufferActivityChanged(BufferId, const Message::Types)), _networkModel, SLOT(bufferActivityChanged(BufferId, const Message::Types)));
359 connect(bufferSyncer(), SIGNAL(highlightCountChanged(BufferId, int)), _networkModel, SLOT(highlightCountChanged(BufferId, int)));
360 connect(networkModel(), SIGNAL(requestSetLastSeenMsg(BufferId, MsgId)), bufferSyncer(), SLOT(requestSetLastSeenMsg(BufferId, const MsgId &)));
362 SignalProxy *p = signalProxy();
363 p->synchronize(bufferSyncer());
365 // create a new BufferViewManager
366 Q_ASSERT(!_bufferViewManager);
367 _bufferViewManager = new ClientBufferViewManager(p, this);
368 connect(_bufferViewManager, SIGNAL(initDone()), _bufferViewOverlay, SLOT(restore()));
370 // create AliasManager
371 Q_ASSERT(!_aliasManager);
372 _aliasManager = new ClientAliasManager(this);
373 connect(aliasManager(), SIGNAL(initDone()), SLOT(sendBufferedUserInput()));
374 p->synchronize(aliasManager());
376 // create NetworkConfig
377 Q_ASSERT(!_networkConfig);
378 _networkConfig = new NetworkConfig("GlobalNetworkConfig", this);
379 p->synchronize(networkConfig());
381 // create IgnoreListManager
382 Q_ASSERT(!_ignoreListManager);
383 _ignoreListManager = new ClientIgnoreListManager(this);
384 p->synchronize(ignoreListManager());
386 // create Core-Side HighlightRuleManager
387 Q_ASSERT(!_highlightRuleManager);
388 _highlightRuleManager = new HighlightRuleManager(this);
389 p->synchronize(highlightRuleManager());
390 // Listen to network removed events
391 connect(this, SIGNAL(networkRemoved(NetworkId)),
392 _highlightRuleManager, SLOT(networkRemoved(NetworkId)));
395 // create TransferManager and DccConfig if core supports them
396 Q_ASSERT(!_dccConfig);
397 Q_ASSERT(!_transferManager);
398 if (isCoreFeatureEnabled(Quassel::Feature::DccFileTransfer)) {
399 _dccConfig = new DccConfig(this);
400 p->synchronize(dccConfig());
401 _transferManager = new ClientTransferManager(this);
402 _transferModel->setManager(_transferManager);
403 p->synchronize(transferManager());
407 // trigger backlog request once all active bufferviews are initialized
408 connect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(finishConnectionInitialization()));
412 emit coreConnectionStateChanged(true);
415 void Client::finishConnectionInitialization()
417 // usually it _should_ take longer until the bufferViews are initialized, so that's what
418 // triggers this slot. But we have to make sure that we know all buffers yet.
419 // so we check the BufferSyncer and in case it wasn't initialized we wait for that instead
420 if (!bufferSyncer()->isInitialized()) {
421 disconnect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(finishConnectionInitialization()));
422 connect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(finishConnectionInitialization()));
425 disconnect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(finishConnectionInitialization()));
426 disconnect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(finishConnectionInitialization()));
428 requestInitialBacklog();
429 if (isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync)) {
430 bufferSyncer()->markActivitiesChanged();
431 bufferSyncer()->markHighlightCountsChanged();
436 void Client::requestInitialBacklog()
438 _backlogManager->requestInitialBacklog();
442 void Client::requestLegacyCoreInfo()
444 // On older cores, the CoreInfo object was only synchronized on demand. Synchronize now if
446 if (isConnected() && !isCoreFeatureEnabled(Quassel::Feature::SyncedCoreInfo)) {
447 // Delete the existing core info object (it will always exist as client is single-threaded)
448 _coreInfo->deleteLater();
449 // No need to set to null when creating new one immediately after
451 // Create a fresh, unsynchronized CoreInfo object, emulating legacy behavior of CoreInfo not
453 _coreInfo = new CoreInfo(this);
454 // Synchronize the new object
455 signalProxy()->synchronize(_coreInfo);
457 // Let others know signal handlers have been reset
458 emit coreInfoResynchronized();
463 void Client::disconnectFromCore()
465 if (!coreConnection()->isConnected())
468 coreConnection()->disconnectFromCore();
472 void Client::setDisconnectedFromCore()
477 emit coreConnectionStateChanged(false);
479 backlogManager()->reset();
480 messageProcessor()->reset();
482 // Clear internal data. Hopefully nothing relies on it at this point.
485 _bufferSyncer->deleteLater();
486 _bufferSyncer = nullptr;
491 if (_bufferViewManager) {
492 _bufferViewManager->deleteLater();
493 _bufferViewManager = nullptr;
496 _bufferViewOverlay->reset();
499 _aliasManager->deleteLater();
500 _aliasManager = nullptr;
503 if (_ignoreListManager) {
504 _ignoreListManager->deleteLater();
505 _ignoreListManager = nullptr;
508 if (_highlightRuleManager) {
509 _highlightRuleManager->deleteLater();
510 _highlightRuleManager = nullptr;
513 if (_transferManager) {
514 _transferModel->setManager(nullptr);
515 _transferManager->deleteLater();
516 _transferManager = nullptr;
520 _dccConfig->deleteLater();
521 _dccConfig = nullptr;
524 // we probably don't want to save pending input for reconnect
525 _userInputBuffer.clear();
527 _messageModel->clear();
528 _networkModel->clear();
530 QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
531 while (netIter != _networks.end()) {
532 Network *net = netIter.value();
533 emit networkRemoved(net->networkId());
534 disconnect(net, SIGNAL(destroyed()), this, nullptr);
535 netIter = _networks.erase(netIter);
538 Q_ASSERT(_networks.isEmpty());
540 QHash<IdentityId, Identity *>::iterator idIter = _identities.begin();
541 while (idIter != _identities.end()) {
542 emit identityRemoved(idIter.key());
543 Identity *id = idIter.value();
544 idIter = _identities.erase(idIter);
547 Q_ASSERT(_identities.isEmpty());
549 if (_networkConfig) {
550 _networkConfig->deleteLater();
551 _networkConfig = nullptr;
558 void Client::networkDestroyed()
560 Network *net = static_cast<Network *>(sender());
561 QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
562 while (netIter != _networks.end()) {
563 if (*netIter == net) {
564 netIter = _networks.erase(netIter);
574 // Hmm... we never used this...
575 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/)
577 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
581 void Client::recvMessage(const Message &msg)
584 messageProcessor()->process(msg_);
588 void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId)
591 bufferSyncer()->requestSetLastSeenMsg(id, msgId);
595 void Client::setMarkerLine(BufferId id, const MsgId &msgId)
598 bufferSyncer()->requestSetMarkerLine(id, msgId);
602 MsgId Client::markerLine(BufferId id)
604 if (id.isValid() && networkModel())
605 return networkModel()->markerLineMsgId(id);
610 void Client::removeBuffer(BufferId id)
612 if (!bufferSyncer()) return;
613 bufferSyncer()->requestRemoveBuffer(id);
617 void Client::renameBuffer(BufferId bufferId, const QString &newName)
621 bufferSyncer()->requestRenameBuffer(bufferId, newName);
625 void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2)
629 bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2);
633 void Client::purgeKnownBufferIds()
637 bufferSyncer()->requestPurgeBufferIds();
641 void Client::bufferRemoved(BufferId bufferId)
643 // select a sane buffer (status buffer)
644 /* we have to manually select a buffer because otherwise inconsitent changes
645 * to the model might occur:
646 * the result of a buffer removal triggers a change in the selection model.
647 * the newly selected buffer might be a channel that hasn't been selected yet
648 * and a new nickview would be created (which never heard of the "rowsAboutToBeRemoved").
649 * this new view (and/or) its sort filter will then only receive a "rowsRemoved" signal.
651 QModelIndex current = bufferModel()->currentIndex();
652 if (current.data(NetworkModel::BufferIdRole).value<BufferId>() == bufferId) {
653 bufferModel()->setCurrentIndex(current.sibling(0, 0));
656 // and remove it from the model
657 networkModel()->removeBuffer(bufferId);
661 void Client::bufferRenamed(BufferId bufferId, const QString &newName)
663 QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
664 if (bufferIndex.isValid()) {
665 networkModel()->setData(bufferIndex, newName, Qt::DisplayRole);
670 void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2)
672 QModelIndex idx = networkModel()->bufferIndex(bufferId1);
673 bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(idx));
674 networkModel()->removeBuffer(bufferId2);
678 void Client::markBufferAsRead(BufferId id)
680 if (bufferSyncer() && id.isValid())
681 bufferSyncer()->requestMarkBufferAsRead(id);
685 void Client::refreshLegacyCoreInfo()
687 instance()->requestLegacyCoreInfo();
691 void Client::changePassword(const QString &oldPassword, const QString &newPassword) {
692 CoreAccount account = currentCoreAccount();
693 account.setPassword(newPassword);
694 coreAccountModel()->createOrUpdateAccount(account);
695 emit instance()->requestPasswordChange(nullptr, account.user(), oldPassword, newPassword);
699 void Client::kickClient(int peerId)
701 emit instance()->requestKickClient(peerId);
705 void Client::corePasswordChanged(PeerPtr, bool success)
708 coreAccountModel()->save();
709 emit passwordChanged(success);