1 /***************************************************************************
2 * Copyright (C) 2005-2014 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 ***************************************************************************/
21 #include "coreconnection.h"
24 #include "clientauthhandler.h"
25 #include "clientsettings.h"
26 #include "coreaccountmodel.h"
28 #include "internalpeer.h"
30 #include "networkmodel.h"
32 #include "signalproxy.h"
35 #include "protocols/legacy/legacypeer.h"
37 CoreConnection::CoreConnection(QObject *parent)
41 _wantReconnect(false),
48 qRegisterMetaType<ConnectionState>("CoreConnection::ConnectionState");
52 void CoreConnection::init()
54 Client::signalProxy()->setHeartBeatInterval(30);
55 connect(Client::signalProxy(), SIGNAL(lagUpdated(int)), SIGNAL(lagUpdated(int)));
57 _reconnectTimer.setSingleShot(true);
58 connect(&_reconnectTimer, SIGNAL(timeout()), SLOT(reconnectTimeout()));
61 connect(Solid::Networking::notifier(), SIGNAL(statusChanged(Solid::Networking::Status)),
62 SLOT(solidNetworkStatusChanged(Solid::Networking::Status)));
65 CoreConnectionSettings s;
66 s.initAndNotify("PingTimeoutInterval", this, SLOT(pingTimeoutIntervalChanged(QVariant)), 60);
67 s.initAndNotify("ReconnectInterval", this, SLOT(reconnectIntervalChanged(QVariant)), 60);
68 s.notify("NetworkDetectionMode", this, SLOT(networkDetectionModeChanged(QVariant)));
69 networkDetectionModeChanged(s.networkDetectionMode());
73 CoreAccountModel *CoreConnection::accountModel() const
75 return Client::coreAccountModel();
79 void CoreConnection::setProgressText(const QString &text)
81 if (_progressText != text) {
83 emit progressTextChanged(text);
88 void CoreConnection::setProgressValue(int value)
90 if (_progressValue != value) {
91 _progressValue = value;
92 emit progressValueChanged(value);
97 void CoreConnection::setProgressMinimum(int minimum)
99 if (_progressMinimum != minimum) {
100 _progressMinimum = minimum;
101 emit progressRangeChanged(minimum, _progressMaximum);
106 void CoreConnection::setProgressMaximum(int maximum)
108 if (_progressMaximum != maximum) {
109 _progressMaximum = maximum;
110 emit progressRangeChanged(_progressMinimum, maximum);
115 void CoreConnection::updateProgress(int value, int max)
117 if (max != _progressMaximum) {
118 _progressMaximum = max;
119 emit progressRangeChanged(_progressMinimum, _progressMaximum);
121 setProgressValue(value);
125 void CoreConnection::reconnectTimeout()
128 CoreConnectionSettings s;
129 if (_wantReconnect && s.autoReconnect()) {
131 // If using Solid, we don't want to reconnect if we're offline
132 if (s.networkDetectionMode() == CoreConnectionSettings::UseSolid) {
133 if (Solid::Networking::status() != Solid::Networking::Connected
134 && Solid::Networking::status() != Solid::Networking::Unknown) {
138 #endif /* HAVE_KDE */
146 void CoreConnection::networkDetectionModeChanged(const QVariant &vmode)
148 CoreConnectionSettings s;
149 CoreConnectionSettings::NetworkDetectionMode mode = (CoreConnectionSettings::NetworkDetectionMode)vmode.toInt();
150 if (mode == CoreConnectionSettings::UsePingTimeout)
151 Client::signalProxy()->setMaxHeartBeatCount(s.pingTimeoutInterval() / 30);
153 Client::signalProxy()->setMaxHeartBeatCount(-1);
158 void CoreConnection::pingTimeoutIntervalChanged(const QVariant &interval)
160 CoreConnectionSettings s;
161 if (s.networkDetectionMode() == CoreConnectionSettings::UsePingTimeout)
162 Client::signalProxy()->setMaxHeartBeatCount(interval.toInt() / 30); // interval is 30 seconds
166 void CoreConnection::reconnectIntervalChanged(const QVariant &interval)
168 _reconnectTimer.setInterval(interval.toInt() * 1000);
174 void CoreConnection::solidNetworkStatusChanged(Solid::Networking::Status status)
176 CoreConnectionSettings s;
177 if (s.networkDetectionMode() != CoreConnectionSettings::UseSolid)
181 case Solid::Networking::Unknown:
182 case Solid::Networking::Connected:
183 //qDebug() << "Solid: Network status changed to connected or unknown";
184 if (state() == Disconnected) {
185 if (_wantReconnect && s.autoReconnect()) {
190 case Solid::Networking::Disconnecting:
191 case Solid::Networking::Unconnected:
192 if (state() != Disconnected && !isLocalConnection())
193 disconnectFromCore(tr("Network is down"), true);
202 bool CoreConnection::isEncrypted() const
204 return _peer && _peer->isSecure();
208 bool CoreConnection::isLocalConnection() const
212 if (currentAccount().isInternal())
214 if (_peer->isLocal())
221 void CoreConnection::onConnectionReady()
227 void CoreConnection::setState(ConnectionState state)
229 if (state != _state) {
231 emit stateChanged(state);
232 if (state == Disconnected)
238 void CoreConnection::coreSocketError(QAbstractSocket::SocketError error, const QString &errorString)
242 disconnectFromCore(errorString, true);
246 void CoreConnection::coreSocketDisconnected()
248 setState(Disconnected);
249 _wasReconnect = false;
250 resetConnection(_wantReconnect);
254 void CoreConnection::disconnectFromCore()
256 disconnectFromCore(QString(), false); // requested disconnect, so don't try to reconnect
260 void CoreConnection::disconnectFromCore(const QString &errorString, bool wantReconnect)
263 _reconnectTimer.start();
265 _reconnectTimer.stop();
267 _wantReconnect = wantReconnect; // store if disconnect was requested
268 _wasReconnect = false;
271 _authHandler->close();
275 if (errorString.isEmpty())
276 emit connectionError(tr("Disconnected"));
278 emit connectionError(errorString);
282 void CoreConnection::resetConnection(bool wantReconnect)
288 _wantReconnect = wantReconnect;
291 disconnect(_authHandler, 0, this, 0);
292 _authHandler->close();
293 _authHandler->deleteLater();
298 disconnect(_peer, 0, this, 0);
299 // peer belongs to the sigproxy and thus gets deleted by it
307 setProgressMaximum(-1); // disable
308 setState(Disconnected);
311 emit connectionMsg(tr("Disconnected from core."));
312 emit encrypted(false);
313 setState(Disconnected);
315 // initiate if a reconnect if appropriate
316 CoreConnectionSettings s;
317 if (wantReconnect && s.autoReconnect()) {
318 _reconnectTimer.start();
325 void CoreConnection::reconnectToCore()
327 if (currentAccount().isValid()) {
328 _wasReconnect = true;
329 connectToCore(currentAccount().accountId());
334 bool CoreConnection::connectToCore(AccountId accId)
339 CoreAccountSettings s;
341 // FIXME: Don't force connection to internal core in mono client
342 if (Quassel::runMode() == Quassel::Monolithic) {
343 _account = accountModel()->account(accountModel()->internalAccount());
344 Q_ASSERT(_account.isValid());
347 if (!accId.isValid()) {
348 // check our settings and figure out what to do
349 if (!s.autoConnectOnStartup())
351 if (s.autoConnectToFixedAccount())
352 accId = s.autoConnectAccount();
354 accId = s.lastAccount();
355 if (!accId.isValid())
358 _account = accountModel()->account(accId);
359 if (!_account.accountId().isValid()) {
362 if (Quassel::runMode() != Quassel::Monolithic) {
363 if (_account.isInternal())
368 s.setLastAccount(accId);
369 connectToCurrentAccount();
374 void CoreConnection::connectToCurrentAccount()
377 qWarning() << Q_FUNC_INFO << "Already connected!";
381 if (currentAccount().isInternal()) {
382 if (Quassel::runMode() != Quassel::Monolithic) {
383 qWarning() << "Cannot connect to internal core in client-only mode!";
386 emit startInternalCore();
388 InternalPeer *peer = new InternalPeer();
390 Client::instance()->signalProxy()->addPeer(peer); // sigproxy will take ownership
391 emit connectToInternalCore(peer);
397 _authHandler = new ClientAuthHandler(currentAccount(), this);
399 connect(_authHandler, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
400 connect(_authHandler, SIGNAL(connectionReady()), SLOT(onConnectionReady()));
401 connect(_authHandler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(coreSocketError(QAbstractSocket::SocketError,QString)));
402 connect(_authHandler, SIGNAL(transferProgress(int,int)), SLOT(updateProgress(int,int)));
403 connect(_authHandler, SIGNAL(requestDisconnect(QString,bool)), SLOT(disconnectFromCore(QString,bool)));
405 connect(_authHandler, SIGNAL(errorMessage(QString)), SIGNAL(connectionError(QString)));
406 connect(_authHandler, SIGNAL(errorPopup(QString)), SIGNAL(connectionErrorPopup(QString)), Qt::QueuedConnection);
407 connect(_authHandler, SIGNAL(statusMessage(QString)), SIGNAL(connectionMsg(QString)));
408 connect(_authHandler, SIGNAL(encrypted(bool)), SIGNAL(encrypted(bool)));
409 connect(_authHandler, SIGNAL(startCoreSetup(QVariantList)), SIGNAL(startCoreSetup(QVariantList)));
410 connect(_authHandler, SIGNAL(coreSetupFailed(QString)), SIGNAL(coreSetupFailed(QString)));
411 connect(_authHandler, SIGNAL(coreSetupSuccessful()), SIGNAL(coreSetupSuccess()));
412 connect(_authHandler, SIGNAL(userAuthenticationRequired(CoreAccount*,bool*,QString)), SIGNAL(userAuthenticationRequired(CoreAccount*,bool*,QString)));
413 connect(_authHandler, SIGNAL(handleNoSslInClient(bool*)), SIGNAL(handleNoSslInClient(bool*)));
414 connect(_authHandler, SIGNAL(handleNoSslInCore(bool*)), SIGNAL(handleNoSslInCore(bool*)));
416 connect(_authHandler, SIGNAL(handleSslErrors(const QSslSocket*,bool*,bool*)), SIGNAL(handleSslErrors(const QSslSocket*,bool*,bool*)));
419 connect(_authHandler, SIGNAL(loginSuccessful(CoreAccount)), SLOT(onLoginSuccessful(CoreAccount)));
420 connect(_authHandler, SIGNAL(handshakeComplete(RemotePeer*,Protocol::SessionState)), SLOT(onHandshakeComplete(RemotePeer*,Protocol::SessionState)));
422 setState(Connecting);
423 _authHandler->connectToCore();
427 void CoreConnection::setupCore(const Protocol::SetupData &setupData)
429 _authHandler->setupCore(setupData);
433 void CoreConnection::loginToCore(const QString &user, const QString &password, bool remember)
435 _authHandler->login(user, password, remember);
439 void CoreConnection::onLoginSuccessful(const CoreAccount &account)
441 updateProgress(0, 0);
443 // save current account data
444 accountModel()->createOrUpdateAccount(account);
445 accountModel()->save();
447 _reconnectTimer.stop();
449 setProgressText(tr("Receiving session state"));
450 setState(Synchronizing);
451 emit connectionMsg(tr("Synchronizing to %1...").arg(account.accountName()));
455 void CoreConnection::onHandshakeComplete(RemotePeer *peer, const Protocol::SessionState &sessionState)
457 updateProgress(100, 100);
459 disconnect(_authHandler, 0, this, 0);
460 _authHandler->deleteLater();
464 connect(peer, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
465 connect(peer, SIGNAL(statusMessage(QString)), SIGNAL(connectionMsg(QString)));
466 connect(peer, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(coreSocketError(QAbstractSocket::SocketError,QString)));
468 Client::signalProxy()->addPeer(_peer); // sigproxy takes ownership of the peer!
470 syncToCore(sessionState);
474 void CoreConnection::internalSessionStateReceived(const Protocol::SessionState &sessionState)
476 updateProgress(100, 100);
478 Client::setCoreFeatures(Quassel::features()); // mono connection...
480 setState(Synchronizing);
481 syncToCore(sessionState);
485 void CoreConnection::syncToCore(const Protocol::SessionState &sessionState)
487 setProgressText(tr("Receiving network states"));
488 updateProgress(0, 100);
491 foreach(const QVariant &vid, sessionState.identities) {
492 Client::instance()->coreIdentityCreated(vid.value<Identity>());
496 // FIXME: get rid of this crap -- why?
497 NetworkModel *networkModel = Client::networkModel();
498 Q_ASSERT(networkModel);
499 foreach(const QVariant &vinfo, sessionState.bufferInfos)
500 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
502 // prepare sync progress thingys...
503 // FIXME: Care about removal of networks
504 _numNetsToSync = sessionState.networkIds.count();
505 updateProgress(0, _numNetsToSync);
507 // create network objects
508 foreach(const QVariant &networkid, sessionState.networkIds) {
509 NetworkId netid = networkid.value<NetworkId>();
510 if (Client::network(netid))
512 Network *net = new Network(netid, Client::instance());
513 _netsToSync.insert(net);
514 connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
515 connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
516 Client::addNetwork(net);
522 // this is also called for destroyed networks!
523 void CoreConnection::networkInitDone()
525 QObject *net = sender();
527 disconnect(net, 0, this, 0);
528 _netsToSync.remove(net);
529 updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
534 void CoreConnection::checkSyncState()
536 if (_netsToSync.isEmpty() && state() >= Synchronizing) {
537 setState(Synchronized);
538 setProgressText(tr("Synchronized to %1").arg(currentAccount().accountName()));
539 setProgressMaximum(-1);