Browse Source

Merge pull request #10346 from glassez/download-manager

Improve "Download manager"
adaptive-webui-19844
Vladimir Golovnev 6 years ago committed by GitHub
parent
commit
928ce940c9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      src/base/CMakeLists.txt
  2. 2
      src/base/base.pri
  3. 36
      src/base/bittorrent/session.cpp
  4. 9
      src/base/bittorrent/session.h
  5. 43
      src/base/net/dnsupdater.cpp
  6. 8
      src/base/net/dnsupdater.h
  7. 255
      src/base/net/downloadhandler.cpp
  8. 81
      src/base/net/downloadhandler.h
  9. 257
      src/base/net/downloadmanager.cpp
  10. 58
      src/base/net/downloadmanager.h
  11. 38
      src/base/net/geoipmanager.cpp
  12. 8
      src/base/net/geoipmanager.h
  13. 37
      src/base/rss/rss_feed.cpp
  14. 10
      src/base/rss/rss_feed.h
  15. 45
      src/base/search/searchpluginmanager.cpp
  16. 11
      src/base/search/searchpluginmanager.h
  17. 47
      src/gui/addnewtorrentdialog.cpp
  18. 12
      src/gui/addnewtorrentdialog.h
  19. 42
      src/gui/mainwindow.cpp
  20. 8
      src/gui/mainwindow.h
  21. 27
      src/gui/programupdater.cpp
  22. 9
      src/gui/programupdater.h
  23. 30
      src/gui/properties/trackersadditiondialog.cpp
  24. 8
      src/gui/properties/trackersadditiondialog.h
  25. 27
      src/gui/search/pluginselectdialog.cpp
  26. 11
      src/gui/search/pluginselectdialog.h
  27. 42
      src/gui/transferlistfilterswidget.cpp
  28. 11
      src/gui/transferlistfilterswidget.h

2
src/base/CMakeLists.txt

@ -29,7 +29,6 @@ http/responsegenerator.h
http/server.h http/server.h
http/types.h http/types.h
net/dnsupdater.h net/dnsupdater.h
net/downloadhandler.h
net/downloadmanager.h net/downloadmanager.h
net/geoipmanager.h net/geoipmanager.h
net/portforwarder.h net/portforwarder.h
@ -100,7 +99,6 @@ http/responsebuilder.cpp
http/responsegenerator.cpp http/responsegenerator.cpp
http/server.cpp http/server.cpp
net/dnsupdater.cpp net/dnsupdater.cpp
net/downloadhandler.cpp
net/downloadmanager.cpp net/downloadmanager.cpp
net/geoipmanager.cpp net/geoipmanager.cpp
net/portforwarder.cpp net/portforwarder.cpp

2
src/base/base.pri

@ -34,7 +34,6 @@ HEADERS += \
$$PWD/indexrange.h \ $$PWD/indexrange.h \
$$PWD/logger.h \ $$PWD/logger.h \
$$PWD/net/dnsupdater.h \ $$PWD/net/dnsupdater.h \
$$PWD/net/downloadhandler.h \
$$PWD/net/downloadmanager.h \ $$PWD/net/downloadmanager.h \
$$PWD/net/geoipmanager.h \ $$PWD/net/geoipmanager.h \
$$PWD/net/portforwarder.h \ $$PWD/net/portforwarder.h \
@ -103,7 +102,6 @@ SOURCES += \
$$PWD/iconprovider.cpp \ $$PWD/iconprovider.cpp \
$$PWD/logger.cpp \ $$PWD/logger.cpp \
$$PWD/net/dnsupdater.cpp \ $$PWD/net/dnsupdater.cpp \
$$PWD/net/downloadhandler.cpp \
$$PWD/net/downloadmanager.cpp \ $$PWD/net/downloadmanager.cpp \
$$PWD/net/geoipmanager.cpp \ $$PWD/net/geoipmanager.cpp \
$$PWD/net/portforwarder.cpp \ $$PWD/net/portforwarder.cpp \

36
src/base/bittorrent/session.cpp

@ -67,7 +67,6 @@
#include "base/exceptions.h" #include "base/exceptions.h"
#include "base/global.h" #include "base/global.h"
#include "base/logger.h" #include "base/logger.h"
#include "base/net/downloadhandler.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
#include "base/net/portforwarder.h" #include "base/net/portforwarder.h"
#include "base/net/proxyconfigurationmanager.h" #include "base/net/proxyconfigurationmanager.h"
@ -1542,22 +1541,21 @@ void Session::processShareLimits()
} }
} }
void Session::handleDownloadFailed(const QString &url, const QString &reason)
{
emit downloadFromUrlFailed(url, reason);
}
void Session::handleRedirectedToMagnet(const QString &url, const QString &magnetUri)
{
addTorrent_impl(CreateTorrentParams(m_downloadedTorrents.take(url)), MagnetUri(magnetUri));
}
// Add to BitTorrent session the downloaded torrent file // Add to BitTorrent session the downloaded torrent file
void Session::handleDownloadFinished(const QString &url, const QByteArray &data) void Session::handleDownloadFinished(const Net::DownloadResult &result)
{ {
emit downloadFromUrlFinished(url); switch (result.status) {
addTorrent_impl(CreateTorrentParams(m_downloadedTorrents.take(url)) case Net::DownloadStatus::Success:
, MagnetUri(), TorrentInfo::load(data)); emit downloadFromUrlFinished(result.url);
addTorrent_impl(CreateTorrentParams(m_downloadedTorrents.take(result.url))
, MagnetUri(), TorrentInfo::load(result.data));
break;
case Net::DownloadStatus::RedirectedToMagnet:
addTorrent_impl(CreateTorrentParams(m_downloadedTorrents.take(result.url)), MagnetUri(result.magnet));
break;
default:
emit downloadFromUrlFailed(result.url, result.errorString);
}
} }
// Return the torrent handle, given its hash // Return the torrent handle, given its hash
@ -1795,13 +1793,9 @@ bool Session::addTorrent(const QString &source, const AddTorrentParams &params)
if (Net::DownloadManager::hasSupportedScheme(source)) { if (Net::DownloadManager::hasSupportedScheme(source)) {
LogMsg(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(source)); LogMsg(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(source));
// Launch downloader // Launch downloader
const Net::DownloadHandler *handler = Net::DownloadManager::instance()->download(Net::DownloadRequest(source).limit(10485760 /* 10MB */)
Net::DownloadManager::instance()->download(Net::DownloadRequest(source).limit(10485760 /* 10MB */).handleRedirectToMagnet(true));
connect(handler, static_cast<void (Net::DownloadHandler::*)(const QString &, const QByteArray &)>(&Net::DownloadHandler::downloadFinished)
, this, &Session::handleDownloadFinished); , this, &Session::handleDownloadFinished);
connect(handler, &Net::DownloadHandler::downloadFailed, this, &Session::handleDownloadFailed); m_downloadedTorrents[source] = params;
connect(handler, &Net::DownloadHandler::redirectedToMagnet, this, &Session::handleRedirectedToMagnet);
m_downloadedTorrents[handler->url()] = params;
return true; return true;
} }

9
src/base/bittorrent/session.h

@ -118,6 +118,11 @@ enum TorrentExportFolder
Finished Finished
}; };
namespace Net
{
struct DownloadResult;
}
namespace BitTorrent namespace BitTorrent
{ {
class InfoHash; class InfoHash;
@ -537,9 +542,7 @@ namespace BitTorrent
void generateResumeData(bool final = false); void generateResumeData(bool final = false);
void handleIPFilterParsed(int ruleCount); void handleIPFilterParsed(int ruleCount);
void handleIPFilterError(); void handleIPFilterError();
void handleDownloadFinished(const QString &url, const QByteArray &data); void handleDownloadFinished(const Net::DownloadResult &result);
void handleDownloadFailed(const QString &url, const QString &reason);
void handleRedirectedToMagnet(const QString &url, const QString &magnetUri);
// Session reconfiguration triggers // Session reconfiguration triggers
void networkOnlineStateChanged(bool online); void networkOnlineStateChanged(bool online);

43
src/base/net/dnsupdater.cpp

@ -33,7 +33,6 @@
#include <QUrlQuery> #include <QUrlQuery>
#include "base/logger.h" #include "base/logger.h"
#include "base/net/downloadhandler.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
using namespace Net; using namespace Net;
@ -74,21 +73,22 @@ void DNSUpdater::checkPublicIP()
{ {
Q_ASSERT(m_state == OK); Q_ASSERT(m_state == OK);
DownloadHandler *handler = DownloadManager::instance()->download( DownloadManager::instance()->download(
DownloadRequest("http://checkip.dyndns.org").userAgent("qBittorrent/" QBT_VERSION_2)); DownloadRequest("http://checkip.dyndns.org").userAgent("qBittorrent/" QBT_VERSION_2)
connect(handler, static_cast<void (Net::DownloadHandler::*)(const QString &, const QByteArray &)>(&Net::DownloadHandler::downloadFinished)
, this, &DNSUpdater::ipRequestFinished); , this, &DNSUpdater::ipRequestFinished);
connect(handler, &Net::DownloadHandler::downloadFailed, this, &DNSUpdater::ipRequestFailed);
m_lastIPCheckTime = QDateTime::currentDateTime(); m_lastIPCheckTime = QDateTime::currentDateTime();
} }
void DNSUpdater::ipRequestFinished(const QString &url, const QByteArray &data) void DNSUpdater::ipRequestFinished(const DownloadResult &result)
{ {
Q_UNUSED(url); if (result.status != DownloadStatus::Success) {
qWarning() << "IP request failed:" << result.errorString;
return;
}
// Parse response // Parse response
const QRegularExpressionMatch ipRegexMatch = QRegularExpression("Current IP Address:\\s+([^<]+)</body>").match(data); const QRegularExpressionMatch ipRegexMatch = QRegularExpression("Current IP Address:\\s+([^<]+)</body>").match(result.data);
if (ipRegexMatch.hasMatch()) { if (ipRegexMatch.hasMatch()) {
QString ipStr = ipRegexMatch.captured(1); QString ipStr = ipRegexMatch.captured(1);
qDebug() << Q_FUNC_INFO << "Regular expression captured the following IP:" << ipStr; qDebug() << Q_FUNC_INFO << "Regular expression captured the following IP:" << ipStr;
@ -110,22 +110,14 @@ void DNSUpdater::ipRequestFinished(const QString &url, const QByteArray &data)
} }
} }
void DNSUpdater::ipRequestFailed(const QString &url, const QString &error)
{
Q_UNUSED(url);
qWarning() << "IP request failed:" << error;
}
void DNSUpdater::updateDNSService() void DNSUpdater::updateDNSService()
{ {
qDebug() << Q_FUNC_INFO; qDebug() << Q_FUNC_INFO;
m_lastIPCheckTime = QDateTime::currentDateTime(); m_lastIPCheckTime = QDateTime::currentDateTime();
DownloadHandler *handler = DownloadManager::instance()->download( DownloadManager::instance()->download(
DownloadRequest(getUpdateUrl()).userAgent("qBittorrent/" QBT_VERSION_2)); DownloadRequest(getUpdateUrl()).userAgent("qBittorrent/" QBT_VERSION_2)
connect(handler, static_cast<void (Net::DownloadHandler::*)(const QString &, const QByteArray &)>(&Net::DownloadHandler::downloadFinished)
, this, &DNSUpdater::ipUpdateFinished); , this, &DNSUpdater::ipUpdateFinished);
connect(handler, &Net::DownloadHandler::downloadFailed, this, &DNSUpdater::ipUpdateFailed);
} }
QString DNSUpdater::getUpdateUrl() const QString DNSUpdater::getUpdateUrl() const
@ -164,17 +156,12 @@ QString DNSUpdater::getUpdateUrl() const
return url.toString(); return url.toString();
} }
void DNSUpdater::ipUpdateFinished(const QString &url, const QByteArray &data) void DNSUpdater::ipUpdateFinished(const DownloadResult &result)
{
Q_UNUSED(url);
// Parse reply
processIPUpdateReply(data);
}
void DNSUpdater::ipUpdateFailed(const QString &url, const QString &error)
{ {
Q_UNUSED(url); if (result.status == DownloadStatus::Success)
qWarning() << "IP update failed:" << error; processIPUpdateReply(result.data);
else
qWarning() << "IP update failed:" << result.errorString;
} }
void DNSUpdater::processIPUpdateReply(const QString &reply) void DNSUpdater::processIPUpdateReply(const QString &reply)

8
src/base/net/dnsupdater.h

@ -38,6 +38,8 @@
namespace Net namespace Net
{ {
struct DownloadResult;
// Based on http://www.dyndns.com/developers/specs/ // Based on http://www.dyndns.com/developers/specs/
class DNSUpdater : public QObject class DNSUpdater : public QObject
{ {
@ -54,11 +56,9 @@ namespace Net
private slots: private slots:
void checkPublicIP(); void checkPublicIP();
void ipRequestFinished(const QString &url, const QByteArray &data); void ipRequestFinished(const DownloadResult &result);
void ipRequestFailed(const QString &url, const QString &error);
void updateDNSService(); void updateDNSService();
void ipUpdateFinished(const QString &url, const QByteArray &data); void ipUpdateFinished(const DownloadResult &result);
void ipUpdateFailed(const QString &url, const QString &error);
private: private:
enum State enum State

255
src/base/net/downloadhandler.cpp

@ -1,255 +0,0 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015, 2018 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#include "downloadhandler.h"
#include <QCoreApplication>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkCookie>
#include <QNetworkProxy>
#include <QNetworkRequest>
#include <QTemporaryFile>
#include <QUrl>
#include "base/utils/fs.h"
#include "base/utils/gzip.h"
#include "base/utils/misc.h"
namespace
{
const int MAX_REDIRECTIONS = 20; // the common value for web browsers
bool saveToFile(const QByteArray &replyData, QString &filePath)
{
QTemporaryFile tmpfile {Utils::Fs::tempPath() + "XXXXXX"};
tmpfile.setAutoRemove(false);
if (!tmpfile.open())
return false;
filePath = tmpfile.fileName();
tmpfile.write(replyData);
return true;
}
}
Net::DownloadHandler::DownloadHandler(QNetworkReply *reply, DownloadManager *manager, const DownloadRequest &downloadRequest)
: QObject(manager)
, m_reply(reply)
, m_manager(manager)
, m_downloadRequest(downloadRequest)
{
if (reply)
assignNetworkReply(reply);
}
Net::DownloadHandler::~DownloadHandler()
{
if (m_reply)
delete m_reply;
}
void Net::DownloadHandler::assignNetworkReply(QNetworkReply *reply)
{
Q_ASSERT(reply);
m_reply = reply;
m_reply->setParent(this);
if (m_downloadRequest.limit() > 0)
connect(m_reply, &QNetworkReply::downloadProgress, this, &Net::DownloadHandler::checkDownloadSize);
connect(m_reply, &QNetworkReply::finished, this, &Net::DownloadHandler::processFinishedDownload);
}
// Returns original url
QString Net::DownloadHandler::url() const
{
return m_downloadRequest.url();
}
void Net::DownloadHandler::processFinishedDownload()
{
const QString url = m_reply->url().toString();
qDebug("Download finished: %s", qUtf8Printable(url));
// Check if the request was successful
if (m_reply->error() != QNetworkReply::NoError) {
// Failure
qDebug("Download failure (%s), reason: %s", qUtf8Printable(url), qUtf8Printable(errorCodeToString(m_reply->error())));
emit downloadFailed(m_downloadRequest.url(), errorCodeToString(m_reply->error()));
this->deleteLater();
return;
}
// Check if the server ask us to redirect somewhere else
const QVariant redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (redirection.isValid()) {
// We should redirect
handleRedirection(redirection.toUrl());
return;
}
// Success
const QByteArray replyData = (m_reply->rawHeader("Content-Encoding") == "gzip")
? Utils::Gzip::decompress(m_reply->readAll())
: m_reply->readAll();
if (m_downloadRequest.saveToFile()) {
QString filePath;
if (saveToFile(replyData, filePath))
emit downloadFinished(m_downloadRequest.url(), filePath);
else
emit downloadFailed(m_downloadRequest.url(), tr("I/O Error"));
}
else {
emit downloadFinished(m_downloadRequest.url(), replyData);
}
this->deleteLater();
}
void Net::DownloadHandler::checkDownloadSize(const qint64 bytesReceived, const qint64 bytesTotal)
{
QString msg = tr("The file size is %1. It exceeds the download limit of %2.");
if (bytesTotal > 0) {
// Total number of bytes is available
if (bytesTotal > m_downloadRequest.limit()) {
m_reply->abort();
emit downloadFailed(m_downloadRequest.url(), msg.arg(Utils::Misc::friendlyUnit(bytesTotal), Utils::Misc::friendlyUnit(m_downloadRequest.limit())));
}
else {
disconnect(m_reply, &QNetworkReply::downloadProgress, this, &Net::DownloadHandler::checkDownloadSize);
}
}
else if (bytesReceived > m_downloadRequest.limit()) {
m_reply->abort();
emit downloadFailed(m_downloadRequest.url(), msg.arg(Utils::Misc::friendlyUnit(bytesReceived), Utils::Misc::friendlyUnit(m_downloadRequest.limit())));
}
}
void Net::DownloadHandler::handleRedirection(const QUrl &newUrl)
{
if (m_redirectionCounter >= MAX_REDIRECTIONS) {
emit downloadFailed(url(), tr("Exceeded max redirections (%1)").arg(MAX_REDIRECTIONS));
this->deleteLater();
return;
}
// Resolve relative urls
const QUrl resolvedUrl = (newUrl.isRelative()) ? m_reply->url().resolved(newUrl) : newUrl;
const QString newUrlString = resolvedUrl.toString();
qDebug("Redirecting from %s to %s...", qUtf8Printable(m_reply->url().toString()), qUtf8Printable(newUrlString));
// Redirect to magnet workaround
if (newUrlString.startsWith("magnet:", Qt::CaseInsensitive)) {
qDebug("Magnet redirect detected.");
m_reply->abort();
if (m_downloadRequest.handleRedirectToMagnet())
emit redirectedToMagnet(m_downloadRequest.url(), newUrlString);
else
emit downloadFailed(m_downloadRequest.url(), tr("Unexpected redirect to magnet URI."));
this->deleteLater();
return;
}
DownloadHandler *redirected = m_manager->download(DownloadRequest(m_downloadRequest).url(newUrlString));
redirected->m_redirectionCounter = (m_redirectionCounter + 1);
connect(redirected, &DownloadHandler::destroyed, this, &DownloadHandler::deleteLater);
connect(redirected, &DownloadHandler::downloadFailed, this, [this](const QString &, const QString &reason)
{
emit downloadFailed(url(), reason);
});
connect(redirected, &DownloadHandler::redirectedToMagnet, this, [this](const QString &, const QString &magnetUri)
{
emit redirectedToMagnet(url(), magnetUri);
});
connect(redirected, static_cast<void (DownloadHandler::*)(const QString &, const QString &)>(&DownloadHandler::downloadFinished)
, this, [this](const QString &, const QString &fileName)
{
emit downloadFinished(url(), fileName);
});
connect(redirected, static_cast<void (DownloadHandler::*)(const QString &, const QByteArray &)>(&DownloadHandler::downloadFinished)
, this, [this](const QString &, const QByteArray &data)
{
emit downloadFinished(url(), data);
});
}
QString Net::DownloadHandler::errorCodeToString(const QNetworkReply::NetworkError status)
{
switch (status) {
case QNetworkReply::HostNotFoundError:
return tr("The remote host name was not found (invalid hostname)");
case QNetworkReply::OperationCanceledError:
return tr("The operation was canceled");
case QNetworkReply::RemoteHostClosedError:
return tr("The remote server closed the connection prematurely, before the entire reply was received and processed");
case QNetworkReply::TimeoutError:
return tr("The connection to the remote server timed out");
case QNetworkReply::SslHandshakeFailedError:
return tr("SSL/TLS handshake failed");
case QNetworkReply::ConnectionRefusedError:
return tr("The remote server refused the connection");
case QNetworkReply::ProxyConnectionRefusedError:
return tr("The connection to the proxy server was refused");
case QNetworkReply::ProxyConnectionClosedError:
return tr("The proxy server closed the connection prematurely");
case QNetworkReply::ProxyNotFoundError:
return tr("The proxy host name was not found");
case QNetworkReply::ProxyTimeoutError:
return tr("The connection to the proxy timed out or the proxy did not reply in time to the request sent");
case QNetworkReply::ProxyAuthenticationRequiredError:
return tr("The proxy requires authentication in order to honor the request but did not accept any credentials offered");
case QNetworkReply::ContentAccessDenied:
return tr("The access to the remote content was denied (401)");
case QNetworkReply::ContentOperationNotPermittedError:
return tr("The operation requested on the remote content is not permitted");
case QNetworkReply::ContentNotFoundError:
return tr("The remote content was not found at the server (404)");
case QNetworkReply::AuthenticationRequiredError:
return tr("The remote server requires authentication to serve the content but the credentials provided were not accepted");
case QNetworkReply::ProtocolUnknownError:
return tr("The Network Access API cannot honor the request because the protocol is not known");
case QNetworkReply::ProtocolInvalidOperationError:
return tr("The requested operation is invalid for this protocol");
case QNetworkReply::UnknownNetworkError:
return tr("An unknown network-related error was detected");
case QNetworkReply::UnknownProxyError:
return tr("An unknown proxy-related error was detected");
case QNetworkReply::UnknownContentError:
return tr("An unknown error related to the remote content was detected");
case QNetworkReply::ProtocolFailure:
return tr("A breakdown in protocol was detected");
default:
return tr("Unknown error");
}
}

81
src/base/net/downloadhandler.h

@ -1,81 +0,0 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015, 2018 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#ifndef NET_DOWNLOADHANDLER_H
#define NET_DOWNLOADHANDLER_H
#include <QNetworkReply>
#include <QObject>
#include "downloadmanager.h"
class QUrl;
namespace Net
{
class DownloadManager;
class DownloadHandler : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(DownloadHandler)
friend class DownloadManager;
DownloadHandler(QNetworkReply *reply, DownloadManager *manager, const DownloadRequest &downloadRequest);
public:
~DownloadHandler() override;
QString url() const;
signals:
void downloadFinished(const QString &url, const QByteArray &data);
void downloadFinished(const QString &url, const QString &filePath);
void downloadFailed(const QString &url, const QString &reason);
void redirectedToMagnet(const QString &url, const QString &magnetUri);
private slots:
void processFinishedDownload();
void checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal);
private:
void assignNetworkReply(QNetworkReply *reply);
void handleRedirection(const QUrl &newUrl);
static QString errorCodeToString(QNetworkReply::NetworkError status);
QNetworkReply *m_reply;
DownloadManager *m_manager;
const DownloadRequest m_downloadRequest;
short m_redirectionCounter = 0;
};
}
#endif // NET_DOWNLOADHANDLER_H

257
src/base/net/downloadmanager.cpp

@ -39,12 +39,15 @@
#include <QNetworkReply> #include <QNetworkReply>
#include <QNetworkRequest> #include <QNetworkRequest>
#include <QSslError> #include <QSslError>
#include <QTemporaryFile>
#include <QUrl> #include <QUrl>
#include "base/global.h" #include "base/global.h"
#include "base/logger.h" #include "base/logger.h"
#include "base/preferences.h" #include "base/preferences.h"
#include "downloadhandler.h" #include "base/utils/fs.h"
#include "base/utils/gzip.h"
#include "base/utils/misc.h"
#include "proxyconfigurationmanager.h" #include "proxyconfigurationmanager.h"
// Spoof Firefox 38 user agent to avoid web server banning // Spoof Firefox 38 user agent to avoid web server banning
@ -52,6 +55,8 @@ const char DEFAULT_USER_AGENT[] = "Mozilla/5.0 (X11; Linux i686; rv:38.0) Gecko/
namespace namespace
{ {
const int MAX_REDIRECTIONS = 20; // the common value for web browsers
class NetworkCookieJar : public QNetworkCookieJar class NetworkCookieJar : public QNetworkCookieJar
{ {
public: public:
@ -108,6 +113,33 @@ namespace
} }
}; };
class DownloadHandlerImpl : public Net::DownloadHandler
{
Q_DISABLE_COPY(DownloadHandlerImpl)
public:
explicit DownloadHandlerImpl(const Net::DownloadRequest &downloadRequest, QObject *parent);
~DownloadHandlerImpl() override;
QString url() const;
const Net::DownloadRequest downloadRequest() const;
void assignNetworkReply(QNetworkReply *reply);
private:
void processFinishedDownload();
void checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal);
void handleRedirection(const QUrl &newUrl);
void setError(const QString &error);
void finish();
static QString errorCodeToString(QNetworkReply::NetworkError status);
QNetworkReply *m_reply = nullptr;
const Net::DownloadRequest m_downloadRequest;
Net::DownloadResult m_result;
};
QNetworkRequest createNetworkRequest(const Net::DownloadRequest &downloadRequest) QNetworkRequest createNetworkRequest(const Net::DownloadRequest &downloadRequest)
{ {
QNetworkRequest request {downloadRequest.url()}; QNetworkRequest request {downloadRequest.url()};
@ -122,8 +154,25 @@ namespace
// Accept gzip // Accept gzip
request.setRawHeader("Accept-Encoding", "gzip"); request.setRawHeader("Accept-Encoding", "gzip");
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::UserVerifiedRedirectPolicy);
request.setMaximumRedirectsAllowed(MAX_REDIRECTIONS);
return request; return request;
} }
bool saveToFile(const QByteArray &replyData, QString &filePath)
{
QTemporaryFile tmpfile {Utils::Fs::tempPath() + "XXXXXX"};
tmpfile.setAutoRemove(false);
if (!tmpfile.open())
return false;
filePath = tmpfile.fileName();
tmpfile.write(replyData);
return true;
}
} }
Net::DownloadManager *Net::DownloadManager::m_instance = nullptr; Net::DownloadManager *Net::DownloadManager::m_instance = nullptr;
@ -164,20 +213,24 @@ Net::DownloadHandler *Net::DownloadManager::download(const DownloadRequest &down
const QNetworkRequest request = createNetworkRequest(downloadRequest); const QNetworkRequest request = createNetworkRequest(downloadRequest);
const ServiceID id = ServiceID::fromURL(request.url()); const ServiceID id = ServiceID::fromURL(request.url());
const bool isSequentialService = m_sequentialServices.contains(id); const bool isSequentialService = m_sequentialServices.contains(id);
auto downloadHandler = new DownloadHandlerImpl {downloadRequest, this};
connect(downloadHandler, &DownloadHandler::finished, downloadHandler, &QObject::deleteLater);
connect(downloadHandler, &QObject::destroyed, this, [this, id, downloadHandler]()
{
m_waitingJobs[id].removeOne(downloadHandler);
});
if (!isSequentialService || !m_busyServices.contains(id)) { if (!isSequentialService || !m_busyServices.contains(id)) {
qDebug("Downloading %s...", qUtf8Printable(downloadRequest.url())); qDebug("Downloading %s...", qUtf8Printable(downloadRequest.url()));
if (isSequentialService) if (isSequentialService)
m_busyServices.insert(id); m_busyServices.insert(id);
return new DownloadHandler { downloadHandler->assignNetworkReply(m_networkManager.get(request));
m_networkManager.get(request), this, downloadRequest};
} }
else {
auto *downloadHandler = new DownloadHandler {nullptr, this, downloadRequest};
connect(downloadHandler, &DownloadHandler::destroyed, this, [this, id, downloadHandler]()
{
m_waitingJobs[id].removeOne(downloadHandler);
});
m_waitingJobs[id].enqueue(downloadHandler); m_waitingJobs[id].enqueue(downloadHandler);
}
return downloadHandler; return downloadHandler;
} }
@ -262,9 +315,9 @@ void Net::DownloadManager::handleReplyFinished(const QNetworkReply *reply)
return; return;
} }
DownloadHandler *handler = waitingJobsIter.value().dequeue(); auto handler = static_cast<DownloadHandlerImpl *>(waitingJobsIter.value().dequeue());
qDebug("Downloading %s...", qUtf8Printable(handler->m_downloadRequest.url())); qDebug("Downloading %s...", qUtf8Printable(handler->url()));
handler->assignNetworkReply(m_networkManager.get(createNetworkRequest(handler->m_downloadRequest))); handler->assignNetworkReply(m_networkManager.get(createNetworkRequest(handler->downloadRequest())));
handler->disconnect(this); handler->disconnect(this);
} }
@ -328,17 +381,6 @@ Net::DownloadRequest &Net::DownloadRequest::saveToFile(const bool value)
return *this; return *this;
} }
bool Net::DownloadRequest::handleRedirectToMagnet() const
{
return m_handleRedirectToMagnet;
}
Net::DownloadRequest &Net::DownloadRequest::handleRedirectToMagnet(const bool value)
{
m_handleRedirectToMagnet = value;
return *this;
}
Net::ServiceID Net::ServiceID::fromURL(const QUrl &url) Net::ServiceID Net::ServiceID::fromURL(const QUrl &url)
{ {
return {url.host(), url.port(80)}; return {url.host(), url.port(80)};
@ -353,3 +395,172 @@ bool Net::operator==(const ServiceID &lhs, const ServiceID &rhs)
{ {
return ((lhs.hostName == rhs.hostName) && (lhs.port == rhs.port)); return ((lhs.hostName == rhs.hostName) && (lhs.port == rhs.port));
} }
namespace
{
DownloadHandlerImpl::DownloadHandlerImpl(const Net::DownloadRequest &downloadRequest, QObject *parent)
: DownloadHandler {parent}
, m_downloadRequest {downloadRequest}
{
m_result.url = url();
m_result.status = Net::DownloadStatus::Success;
}
DownloadHandlerImpl::~DownloadHandlerImpl()
{
if (m_reply)
delete m_reply;
}
void DownloadHandlerImpl::assignNetworkReply(QNetworkReply *reply)
{
Q_ASSERT(reply);
m_reply = reply;
m_reply->setParent(this);
if (m_downloadRequest.limit() > 0)
connect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadHandlerImpl::checkDownloadSize);
connect(m_reply, &QNetworkReply::finished, this, &DownloadHandlerImpl::processFinishedDownload);
connect(m_reply, &QNetworkReply::redirected, this, &DownloadHandlerImpl::handleRedirection);
}
// Returns original url
QString DownloadHandlerImpl::url() const
{
return m_downloadRequest.url();
}
const Net::DownloadRequest DownloadHandlerImpl::downloadRequest() const
{
return m_downloadRequest;
}
void DownloadHandlerImpl::processFinishedDownload()
{
const QString url = m_reply->url().toString();
qDebug("Download finished: %s", qUtf8Printable(url));
// Check if the request was successful
if (m_reply->error() != QNetworkReply::NoError) {
// Failure
qDebug("Download failure (%s), reason: %s", qUtf8Printable(url), qUtf8Printable(errorCodeToString(m_reply->error())));
setError(errorCodeToString(m_reply->error()));
finish();
return;
}
// Success
m_result.data = (m_reply->rawHeader("Content-Encoding") == "gzip")
? Utils::Gzip::decompress(m_reply->readAll())
: m_reply->readAll();
if (m_downloadRequest.saveToFile()) {
QString filePath;
if (saveToFile(m_result.data, filePath))
m_result.filePath = filePath;
else
setError(tr("I/O Error"));
}
finish();
}
void DownloadHandlerImpl::checkDownloadSize(const qint64 bytesReceived, const qint64 bytesTotal)
{
if ((bytesTotal > 0) && (bytesTotal <= m_downloadRequest.limit())) {
// Total number of bytes is available
disconnect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadHandlerImpl::checkDownloadSize);
return;
}
if ((bytesTotal > m_downloadRequest.limit()) || (bytesReceived > m_downloadRequest.limit())) {
m_reply->abort();
setError(tr("The file size is %1. It exceeds the download limit of %2.")
.arg(Utils::Misc::friendlyUnit(bytesTotal)
, Utils::Misc::friendlyUnit(m_downloadRequest.limit())));
finish();
}
}
void DownloadHandlerImpl::handleRedirection(const QUrl &newUrl)
{
// Resolve relative urls
const QUrl resolvedUrl = newUrl.isRelative() ? m_reply->url().resolved(newUrl) : newUrl;
const QString newUrlString = resolvedUrl.toString();
qDebug("Redirecting from %s to %s...", qUtf8Printable(m_reply->url().toString()), qUtf8Printable(newUrlString));
// Redirect to magnet workaround
if (newUrlString.startsWith("magnet:", Qt::CaseInsensitive)) {
qDebug("Magnet redirect detected.");
m_result.status = Net::DownloadStatus::RedirectedToMagnet;
m_result.magnet = newUrlString;
m_result.errorString = tr("Redirected to magnet URI.");
finish();
return;
}
emit m_reply->redirectAllowed();
}
void DownloadHandlerImpl::setError(const QString &error)
{
m_result.errorString = error;
m_result.status = Net::DownloadStatus::Failed;
}
void DownloadHandlerImpl::finish()
{
emit finished(m_result);
}
QString DownloadHandlerImpl::errorCodeToString(const QNetworkReply::NetworkError status)
{
switch (status) {
case QNetworkReply::HostNotFoundError:
return tr("The remote host name was not found (invalid hostname)");
case QNetworkReply::OperationCanceledError:
return tr("The operation was canceled");
case QNetworkReply::RemoteHostClosedError:
return tr("The remote server closed the connection prematurely, before the entire reply was received and processed");
case QNetworkReply::TimeoutError:
return tr("The connection to the remote server timed out");
case QNetworkReply::SslHandshakeFailedError:
return tr("SSL/TLS handshake failed");
case QNetworkReply::ConnectionRefusedError:
return tr("The remote server refused the connection");
case QNetworkReply::ProxyConnectionRefusedError:
return tr("The connection to the proxy server was refused");
case QNetworkReply::ProxyConnectionClosedError:
return tr("The proxy server closed the connection prematurely");
case QNetworkReply::ProxyNotFoundError:
return tr("The proxy host name was not found");
case QNetworkReply::ProxyTimeoutError:
return tr("The connection to the proxy timed out or the proxy did not reply in time to the request sent");
case QNetworkReply::ProxyAuthenticationRequiredError:
return tr("The proxy requires authentication in order to honor the request but did not accept any credentials offered");
case QNetworkReply::ContentAccessDenied:
return tr("The access to the remote content was denied (401)");
case QNetworkReply::ContentOperationNotPermittedError:
return tr("The operation requested on the remote content is not permitted");
case QNetworkReply::ContentNotFoundError:
return tr("The remote content was not found at the server (404)");
case QNetworkReply::AuthenticationRequiredError:
return tr("The remote server requires authentication to serve the content but the credentials provided were not accepted");
case QNetworkReply::ProtocolUnknownError:
return tr("The Network Access API cannot honor the request because the protocol is not known");
case QNetworkReply::ProtocolInvalidOperationError:
return tr("The requested operation is invalid for this protocol");
case QNetworkReply::UnknownNetworkError:
return tr("An unknown network-related error was detected");
case QNetworkReply::UnknownProxyError:
return tr("An unknown proxy-related error was detected");
case QNetworkReply::UnknownContentError:
return tr("An unknown error related to the remote content was detected");
case QNetworkReply::ProtocolFailure:
return tr("A breakdown in protocol was detected");
default:
return tr("Unknown error");
}
}
}

58
src/base/net/downloadmanager.h

@ -44,7 +44,23 @@ class QUrl;
namespace Net namespace Net
{ {
class DownloadHandler; struct ServiceID
{
QString hostName;
int port;
static ServiceID fromURL(const QUrl &url);
};
uint qHash(const ServiceID &serviceID, uint seed);
bool operator==(const ServiceID &lhs, const ServiceID &rhs);
enum class DownloadStatus
{
Success,
RedirectedToMagnet,
Failed
};
class DownloadRequest class DownloadRequest
{ {
@ -64,27 +80,34 @@ namespace Net
bool saveToFile() const; bool saveToFile() const;
DownloadRequest &saveToFile(bool value); DownloadRequest &saveToFile(bool value);
bool handleRedirectToMagnet() const;
DownloadRequest &handleRedirectToMagnet(bool value);
private: private:
QString m_url; QString m_url;
QString m_userAgent; QString m_userAgent;
qint64 m_limit = 0; qint64 m_limit = 0;
bool m_saveToFile = false; bool m_saveToFile = false;
bool m_handleRedirectToMagnet = false;
}; };
struct ServiceID struct DownloadResult
{ {
QString hostName; QString url;
int port; DownloadStatus status;
QString errorString;
static ServiceID fromURL(const QUrl &url); QByteArray data;
QString filePath;
QString magnet;
}; };
uint qHash(const ServiceID &serviceID, uint seed); class DownloadHandler : public QObject
bool operator==(const ServiceID &lhs, const ServiceID &rhs); {
Q_OBJECT
Q_DISABLE_COPY(DownloadHandler)
public:
using QObject::QObject;
signals:
void finished(const DownloadResult &result);
};
class DownloadManager : public QObject class DownloadManager : public QObject
{ {
@ -96,7 +119,8 @@ namespace Net
static void freeInstance(); static void freeInstance();
static DownloadManager *instance(); static DownloadManager *instance();
DownloadHandler *download(const DownloadRequest &downloadRequest); template <typename Context, typename Func>
void download(const DownloadRequest &downloadRequest, Context context, Func slot);
void registerSequentialService(const ServiceID &serviceID); void registerSequentialService(const ServiceID &serviceID);
@ -114,6 +138,7 @@ namespace Net
private: private:
explicit DownloadManager(QObject *parent = nullptr); explicit DownloadManager(QObject *parent = nullptr);
DownloadHandler *download(const DownloadRequest &downloadRequest);
void applyProxySettings(); void applyProxySettings();
void handleReplyFinished(const QNetworkReply *reply); void handleReplyFinished(const QNetworkReply *reply);
@ -124,6 +149,13 @@ namespace Net
QSet<ServiceID> m_busyServices; QSet<ServiceID> m_busyServices;
QHash<ServiceID, QQueue<DownloadHandler *>> m_waitingJobs; QHash<ServiceID, QQueue<DownloadHandler *>> m_waitingJobs;
}; };
template <typename Context, typename Func>
void DownloadManager::download(const DownloadRequest &downloadRequest, Context context, Func slot)
{
const DownloadHandler *handler = download(downloadRequest);
connect(handler, &DownloadHandler::finished, context, slot);
}
} }
#endif // NET_DOWNLOADMANAGER_H #endif // NET_DOWNLOADMANAGER_H

38
src/base/net/geoipmanager.cpp

@ -40,7 +40,6 @@
#include "base/profile.h" #include "base/profile.h"
#include "base/utils/fs.h" #include "base/utils/fs.h"
#include "base/utils/gzip.h" #include "base/utils/gzip.h"
#include "downloadhandler.h"
#include "downloadmanager.h" #include "downloadmanager.h"
#include "private/geoipdatabase.h" #include "private/geoipdatabase.h"
@ -118,10 +117,7 @@ void GeoIPManager::manageDatabaseUpdate()
void GeoIPManager::downloadDatabaseFile() void GeoIPManager::downloadDatabaseFile()
{ {
const DownloadHandler *handler = DownloadManager::instance()->download({DATABASE_URL}); DownloadManager::instance()->download({DATABASE_URL}, this, &GeoIPManager::downloadFinished);
connect(handler, static_cast<void (Net::DownloadHandler::*)(const QString &, const QByteArray &)>(&Net::DownloadHandler::downloadFinished)
, this, &GeoIPManager::downloadFinished);
connect(handler, &Net::DownloadHandler::downloadFailed, this, &GeoIPManager::downloadFailed);
} }
QString GeoIPManager::lookup(const QHostAddress &hostAddr) const QString GeoIPManager::lookup(const QHostAddress &hostAddr) const
@ -413,14 +409,17 @@ void GeoIPManager::configure()
} }
} }
void GeoIPManager::downloadFinished(const QString &url, QByteArray data) void GeoIPManager::downloadFinished(const DownloadResult &result)
{ {
Q_UNUSED(url); if (result.status != DownloadStatus::Success) {
LogMsg(tr("Couldn't download GeoIP database file. Reason: %1").arg(result.errorString), Log::WARNING);
return;
}
bool ok = false; bool ok = false;
data = Utils::Gzip::decompress(data, &ok); const QByteArray data = Utils::Gzip::decompress(result.data, &ok);
if (!ok) { if (!ok) {
Logger::instance()->addMessage(tr("Could not decompress GeoIP database file."), Log::WARNING); LogMsg(tr("Could not decompress GeoIP database file."), Log::WARNING);
return; return;
} }
@ -431,7 +430,7 @@ void GeoIPManager::downloadFinished(const QString &url, QByteArray data)
if (m_geoIPDatabase) if (m_geoIPDatabase)
delete m_geoIPDatabase; delete m_geoIPDatabase;
m_geoIPDatabase = geoIPDatabase; m_geoIPDatabase = geoIPDatabase;
Logger::instance()->addMessage(tr("GeoIP database loaded. Type: %1. Build time: %2.") LogMsg(tr("GeoIP database loaded. Type: %1. Build time: %2.")
.arg(m_geoIPDatabase->type(), m_geoIPDatabase->buildEpoch().toString()), .arg(m_geoIPDatabase->type(), m_geoIPDatabase->buildEpoch().toString()),
Log::INFO); Log::INFO);
const QString targetPath = Utils::Fs::expandPathAbs( const QString targetPath = Utils::Fs::expandPathAbs(
@ -439,25 +438,16 @@ void GeoIPManager::downloadFinished(const QString &url, QByteArray data)
if (!QDir(targetPath).exists()) if (!QDir(targetPath).exists())
QDir().mkpath(targetPath); QDir().mkpath(targetPath);
QFile targetFile(QString("%1/%2").arg(targetPath, GEOIP_FILENAME)); QFile targetFile(QString("%1/%2").arg(targetPath, GEOIP_FILENAME));
if (!targetFile.open(QFile::WriteOnly) || (targetFile.write(data) == -1)) { if (!targetFile.open(QFile::WriteOnly) || (targetFile.write(data) == -1))
Logger::instance()->addMessage( LogMsg(tr("Couldn't save downloaded GeoIP database file."), Log::WARNING);
tr("Couldn't save downloaded GeoIP database file."), Log::WARNING); else
} LogMsg(tr("Successfully updated GeoIP database."), Log::INFO);
else {
Logger::instance()->addMessage(tr("Successfully updated GeoIP database."), Log::INFO);
}
} }
else { else {
delete geoIPDatabase; delete geoIPDatabase;
} }
} }
else { else {
Logger::instance()->addMessage(tr("Couldn't load GeoIP database. Reason: %1").arg(error), Log::WARNING); LogMsg(tr("Couldn't load GeoIP database. Reason: %1").arg(error), Log::WARNING);
}
} }
void GeoIPManager::downloadFailed(const QString &url, const QString &reason)
{
Q_UNUSED(url);
Logger::instance()->addMessage(tr("Couldn't download GeoIP database file. Reason: %1").arg(reason), Log::WARNING);
} }

8
src/base/net/geoipmanager.h

@ -40,9 +40,12 @@ class GeoIPDatabase;
namespace Net namespace Net
{ {
struct DownloadResult;
class GeoIPManager : public QObject class GeoIPManager : public QObject
{ {
Q_OBJECT Q_OBJECT
Q_DISABLE_COPY(GeoIPManager)
public: public:
static void initInstance(); static void initInstance();
@ -55,12 +58,11 @@ namespace Net
private slots: private slots:
void configure(); void configure();
void downloadFinished(const QString &url, QByteArray data); void downloadFinished(const DownloadResult &result);
void downloadFailed(const QString &url, const QString &reason);
private: private:
GeoIPManager(); GeoIPManager();
~GeoIPManager(); ~GeoIPManager() override;
void loadDatabase(); void loadDatabase();
void manageDatabaseUpdate(); void manageDatabaseUpdate();

37
src/base/rss/rss_feed.cpp

@ -44,7 +44,6 @@
#include "../asyncfilestorage.h" #include "../asyncfilestorage.h"
#include "../global.h" #include "../global.h"
#include "../logger.h" #include "../logger.h"
#include "../net/downloadhandler.h"
#include "../net/downloadmanager.h" #include "../net/downloadmanager.h"
#include "../profile.h" #include "../profile.h"
#include "../utils/fs.h" #include "../utils/fs.h"
@ -130,11 +129,7 @@ void Feed::refresh()
// NOTE: Should we allow manually refreshing for disabled session? // NOTE: Should we allow manually refreshing for disabled session?
Net::DownloadHandler *handler = Net::DownloadManager::instance()->download(m_url); Net::DownloadManager::instance()->download(m_url, this, &Feed::handleDownloadFinished);
connect(handler
, static_cast<void (Net::DownloadHandler::*)(const QString &, const QByteArray &)>(&Net::DownloadHandler::downloadFinished)
, this, &Feed::handleDownloadFinished);
connect(handler, &Net::DownloadHandler::downloadFailed, this, &Feed::handleDownloadFailed);
m_isLoading = true; m_isLoading = true;
emit stateChanged(this); emit stateChanged(this);
@ -182,36 +177,36 @@ void Feed::handleMaxArticlesPerFeedChanged(const int n)
// We don't need store articles here // We don't need store articles here
} }
void Feed::handleIconDownloadFinished(const QString &url, const QString &filePath) void Feed::handleIconDownloadFinished(const Net::DownloadResult &result)
{ {
Q_UNUSED(url); if (result.status == Net::DownloadStatus::Success) {
m_iconPath = Utils::Fs::fromNativePath(result.filePath);
m_iconPath = Utils::Fs::fromNativePath(filePath);
emit iconLoaded(this); emit iconLoaded(this);
} }
}
bool Feed::hasError() const bool Feed::hasError() const
{ {
return m_hasError; return m_hasError;
} }
void Feed::handleDownloadFinished(const QString &url, const QByteArray &data) void Feed::handleDownloadFinished(const Net::DownloadResult &result)
{ {
qDebug() << "Successfully downloaded RSS feed at" << url; if (result.status == Net::DownloadStatus::Success) {
qDebug() << "Successfully downloaded RSS feed at" << result.url;
// Parse the download RSS // Parse the download RSS
m_parser->parse(data); m_parser->parse(result.data);
} }
else {
void Feed::handleDownloadFailed(const QString &url, const QString &error)
{
m_isLoading = false; m_isLoading = false;
m_hasError = true; m_hasError = true;
LogMsg(tr("Failed to download RSS feed at '%1'. Reason: %2").arg(url, error) LogMsg(tr("Failed to download RSS feed at '%1'. Reason: %2")
, Log::WARNING); .arg(result.url, result.errorString), Log::WARNING);
emit stateChanged(this); emit stateChanged(this);
} }
}
void Feed::handleParsingFinished(const RSS::Private::ParsingResult &result) void Feed::handleParsingFinished(const RSS::Private::ParsingResult &result)
{ {
@ -402,10 +397,8 @@ void Feed::downloadIcon()
// XXX: This works for most sites but it is not perfect // XXX: This works for most sites but it is not perfect
const QUrl url(m_url); const QUrl url(m_url);
const auto iconUrl = QString("%1://%2/favicon.ico").arg(url.scheme(), url.host()); const auto iconUrl = QString("%1://%2/favicon.ico").arg(url.scheme(), url.host());
const Net::DownloadHandler *handler = Net::DownloadManager::instance()->download( Net::DownloadManager::instance()->download(
Net::DownloadRequest(iconUrl).saveToFile(true)); Net::DownloadRequest(iconUrl).saveToFile(true)
connect(handler
, static_cast<void (Net::DownloadHandler::*)(const QString &, const QString &)>(&Net::DownloadHandler::downloadFinished)
, this, &Feed::handleIconDownloadFinished); , this, &Feed::handleIconDownloadFinished);
} }

10
src/base/rss/rss_feed.h

@ -39,6 +39,11 @@
class AsyncFileStorage; class AsyncFileStorage;
namespace Net
{
struct DownloadResult;
}
namespace RSS namespace RSS
{ {
class Article; class Article;
@ -85,9 +90,8 @@ namespace RSS
private slots: private slots:
void handleSessionProcessingEnabledChanged(bool enabled); void handleSessionProcessingEnabledChanged(bool enabled);
void handleMaxArticlesPerFeedChanged(int n); void handleMaxArticlesPerFeedChanged(int n);
void handleIconDownloadFinished(const QString &url, const QString &filePath); void handleIconDownloadFinished(const Net::DownloadResult &result);
void handleDownloadFinished(const QString &url, const QByteArray &data); void handleDownloadFinished(const Net::DownloadResult &result);
void handleDownloadFailed(const QString &url, const QString &error);
void handleParsingFinished(const Private::ParsingResult &result); void handleParsingFinished(const Private::ParsingResult &result);
void handleArticleRead(Article *article); void handleArticleRead(Article *article);

45
src/base/search/searchpluginmanager.cpp

@ -43,7 +43,6 @@
#include "base/global.h" #include "base/global.h"
#include "base/logger.h" #include "base/logger.h"
#include "base/net/downloadhandler.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
#include "base/preferences.h" #include "base/preferences.h"
#include "base/profile.h" #include "base/profile.h"
@ -199,10 +198,8 @@ void SearchPluginManager::installPlugin(const QString &source)
if (Net::DownloadManager::hasSupportedScheme(source)) { if (Net::DownloadManager::hasSupportedScheme(source)) {
using namespace Net; using namespace Net;
DownloadHandler *handler = DownloadManager::instance()->download(DownloadRequest(source).saveToFile(true)); DownloadManager::instance()->download(DownloadRequest(source).saveToFile(true)
connect(handler, static_cast<void (DownloadHandler::*)(const QString &, const QString &)>(&DownloadHandler::downloadFinished) , this, &SearchPluginManager::pluginDownloadFinished);
, this, &SearchPluginManager::pluginDownloaded);
connect(handler, &DownloadHandler::downloadFailed, this, &SearchPluginManager::pluginDownloadFailed);
} }
else { else {
QString path = source; QString path = source;
@ -304,10 +301,8 @@ void SearchPluginManager::checkForUpdates()
{ {
// Download version file from update server // Download version file from update server
using namespace Net; using namespace Net;
DownloadHandler *handler = DownloadManager::instance()->download({m_updateUrl + "versions.txt"}); DownloadManager::instance()->download({m_updateUrl + "versions.txt"}
connect(handler, static_cast<void (DownloadHandler::*)(const QString &, const QByteArray &)>(&DownloadHandler::downloadFinished) , this, &SearchPluginManager::versionInfoDownloadFinished);
, this, &SearchPluginManager::versionInfoDownloaded);
connect(handler, &DownloadHandler::downloadFailed, this, &SearchPluginManager::versionInfoDownloadFailed);
} }
SearchDownloadHandler *SearchPluginManager::downloadTorrent(const QString &siteUrl, const QString &url) SearchDownloadHandler *SearchPluginManager::downloadTorrent(const QString &siteUrl, const QString &url)
@ -364,36 +359,32 @@ QString SearchPluginManager::engineLocation()
return location; return location;
} }
void SearchPluginManager::versionInfoDownloaded(const QString &url, const QByteArray &data) void SearchPluginManager::versionInfoDownloadFinished(const Net::DownloadResult &result)
{ {
Q_UNUSED(url) if (result.status == Net::DownloadStatus::Success)
parseVersionInfo(data); parseVersionInfo(result.data);
} else
emit checkForUpdatesFailed(tr("Update server is temporarily unavailable. %1").arg(result.errorString));
void SearchPluginManager::versionInfoDownloadFailed(const QString &url, const QString &reason)
{
Q_UNUSED(url)
emit checkForUpdatesFailed(tr("Update server is temporarily unavailable. %1").arg(reason));
} }
void SearchPluginManager::pluginDownloaded(const QString &url, QString filePath) void SearchPluginManager::pluginDownloadFinished(const Net::DownloadResult &result)
{ {
filePath = Utils::Fs::fromNativePath(filePath); if (result.status == Net::DownloadStatus::Success) {
const QString filePath = Utils::Fs::fromNativePath(result.filePath);
QString pluginName = Utils::Fs::fileName(url); QString pluginName = Utils::Fs::fileName(result.url);
pluginName.chop(pluginName.size() - pluginName.lastIndexOf('.')); // Remove extension pluginName.chop(pluginName.size() - pluginName.lastIndexOf('.')); // Remove extension
installPlugin_impl(pluginName, filePath); installPlugin_impl(pluginName, filePath);
Utils::Fs::forceRemove(filePath); Utils::Fs::forceRemove(filePath);
} }
else {
void SearchPluginManager::pluginDownloadFailed(const QString &url, const QString &reason) QString pluginName = result.url.split('/').last();
{
QString pluginName = url.split('/').last();
pluginName.replace(".py", "", Qt::CaseInsensitive); pluginName.replace(".py", "", Qt::CaseInsensitive);
if (pluginInfo(pluginName)) if (pluginInfo(pluginName))
emit pluginUpdateFailed(pluginName, tr("Failed to download the plugin file. %1").arg(reason)); emit pluginUpdateFailed(pluginName, tr("Failed to download the plugin file. %1").arg(result.errorString));
else else
emit pluginInstallationFailed(pluginName, tr("Failed to download the plugin file. %1").arg(reason)); emit pluginInstallationFailed(pluginName, tr("Failed to download the plugin file. %1").arg(result.errorString));
}
} }
// Update nova.py search plugin if necessary // Update nova.py search plugin if necessary

11
src/base/search/searchpluginmanager.h

@ -38,6 +38,11 @@
using PluginVersion = Utils::Version<unsigned short, 2>; using PluginVersion = Utils::Version<unsigned short, 2>;
Q_DECLARE_METATYPE(PluginVersion) Q_DECLARE_METATYPE(PluginVersion)
namespace Net
{
struct DownloadResult;
}
struct PluginInfo struct PluginInfo
{ {
QString name; QString name;
@ -104,10 +109,8 @@ private:
void installPlugin_impl(const QString &name, const QString &path); void installPlugin_impl(const QString &name, const QString &path);
bool isUpdateNeeded(const QString &pluginName, PluginVersion newVersion) const; bool isUpdateNeeded(const QString &pluginName, PluginVersion newVersion) const;
void versionInfoDownloaded(const QString &url, const QByteArray &data); void versionInfoDownloadFinished(const Net::DownloadResult &result);
void versionInfoDownloadFailed(const QString &url, const QString &reason); void pluginDownloadFinished(const Net::DownloadResult &result);
void pluginDownloaded(const QString &url, QString filePath);
void pluginDownloadFailed(const QString &url, const QString &reason);
static QString pluginPath(const QString &name); static QString pluginPath(const QString &name);

47
src/gui/addnewtorrentdialog.cpp

@ -43,7 +43,6 @@
#include "base/bittorrent/torrenthandle.h" #include "base/bittorrent/torrenthandle.h"
#include "base/bittorrent/torrentinfo.h" #include "base/bittorrent/torrentinfo.h"
#include "base/global.h" #include "base/global.h"
#include "base/net/downloadhandler.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
#include "base/preferences.h" #include "base/preferences.h"
#include "base/settingsstorage.h" #include "base/settingsstorage.h"
@ -238,12 +237,9 @@ void AddNewTorrentDialog::show(const QString &source, const BitTorrent::AddTorre
if (Net::DownloadManager::hasSupportedScheme(source)) { if (Net::DownloadManager::hasSupportedScheme(source)) {
// Launch downloader // Launch downloader
Net::DownloadHandler *handler = Net::DownloadManager::instance()->download( Net::DownloadManager::instance()->download(
Net::DownloadRequest(source).limit(10485760 /* 10MB */).handleRedirectToMagnet(true)); Net::DownloadRequest(source).limit(10485760 /* 10MB */)
connect(handler, static_cast<void (Net::DownloadHandler::*)(const QString &, const QByteArray &)>(&Net::DownloadHandler::downloadFinished)
, dlg, &AddNewTorrentDialog::handleDownloadFinished); , dlg, &AddNewTorrentDialog::handleDownloadFinished);
connect(handler, &Net::DownloadHandler::downloadFailed, dlg, &AddNewTorrentDialog::handleDownloadFailed);
connect(handler, &Net::DownloadHandler::redirectedToMagnet, dlg, &AddNewTorrentDialog::handleRedirectedToMagnet);
return; return;
} }
@ -762,30 +758,15 @@ void AddNewTorrentDialog::setupTreeview()
showAdvancedSettings(settings()->loadValue(KEY_EXPANDED, false).toBool()); showAdvancedSettings(settings()->loadValue(KEY_EXPANDED, false).toBool());
} }
void AddNewTorrentDialog::handleDownloadFailed(const QString &url, const QString &reason) void AddNewTorrentDialog::handleDownloadFinished(const Net::DownloadResult &result)
{
RaisedMessageBox::critical(this, tr("Download Error"),
QString("Cannot download '%1': %2").arg(url, reason));
this->deleteLater();
}
void AddNewTorrentDialog::handleRedirectedToMagnet(const QString &url, const QString &magnetUri)
{
Q_UNUSED(url)
if (loadMagnet(BitTorrent::MagnetUri(magnetUri)))
open();
else
this->deleteLater();
}
void AddNewTorrentDialog::handleDownloadFinished(const QString &url, const QByteArray &data)
{ {
QString error; QString error;
m_torrentInfo = BitTorrent::TorrentInfo::load(data, &error); switch (result.status) {
case Net::DownloadStatus::Success:
m_torrentInfo = BitTorrent::TorrentInfo::load(result.data, &error);
if (!m_torrentInfo.isValid()) { if (!m_torrentInfo.isValid()) {
RaisedMessageBox::critical(this, tr("Invalid torrent"), tr("Failed to load from URL: %1.\nError: %2") RaisedMessageBox::critical(this, tr("Invalid torrent"), tr("Failed to load from URL: %1.\nError: %2")
.arg(url, error)); .arg(result.url, error));
return; return;
} }
@ -794,7 +775,19 @@ void AddNewTorrentDialog::handleDownloadFinished(const QString &url, const QByte
if (loadTorrentImpl()) if (loadTorrentImpl())
open(); open();
else else
this->deleteLater(); deleteLater();
break;
case Net::DownloadStatus::RedirectedToMagnet:
if (loadMagnet(BitTorrent::MagnetUri(result.magnet)))
open();
else
deleteLater();
break;
default:
RaisedMessageBox::critical(this, tr("Download Error"),
tr("Cannot download '%1': %2").arg(result.url, result.errorString));
deleteLater();
}
} }
void AddNewTorrentDialog::TMMChanged(int index) void AddNewTorrentDialog::TMMChanged(int index)

12
src/gui/addnewtorrentdialog.h

@ -43,6 +43,11 @@ namespace BitTorrent
class MagnetUri; class MagnetUri;
} }
namespace Net
{
struct DownloadResult;
}
namespace Ui namespace Ui
{ {
class AddNewTorrentDialog; class AddNewTorrentDialog;
@ -55,12 +60,13 @@ class TorrentFileGuard;
class AddNewTorrentDialog : public QDialog class AddNewTorrentDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
Q_DISABLE_COPY(AddNewTorrentDialog)
public: public:
static const int minPathHistoryLength = 0; static const int minPathHistoryLength = 0;
static const int maxPathHistoryLength = 99; static const int maxPathHistoryLength = 99;
~AddNewTorrentDialog(); ~AddNewTorrentDialog() override;
static bool isEnabled(); static bool isEnabled();
static void setEnabled(bool value); static void setEnabled(bool value);
@ -79,9 +85,7 @@ private slots:
void onSavePathChanged(const QString &newPath); void onSavePathChanged(const QString &newPath);
void renameSelectedFile(); void renameSelectedFile();
void updateMetadata(const BitTorrent::TorrentInfo &info); void updateMetadata(const BitTorrent::TorrentInfo &info);
void handleDownloadFailed(const QString &url, const QString &reason); void handleDownloadFinished(const Net::DownloadResult &result);
void handleRedirectedToMagnet(const QString &url, const QString &magnetUri);
void handleDownloadFinished(const QString &url, const QByteArray &data);
void TMMChanged(int index); void TMMChanged(int index);
void categoryChanged(int index); void categoryChanged(int index);
void doNotDeleteTorrentClicked(bool checked); void doNotDeleteTorrentClicked(bool checked);

42
src/gui/mainwindow.cpp

@ -97,7 +97,6 @@
#include "utils.h" #include "utils.h"
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
#include "base/net/downloadhandler.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
#endif #endif
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
@ -2013,28 +2012,33 @@ void MainWindow::installPython()
const QString installerURL = ((QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) const QString installerURL = ((QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA)
? "https://www.python.org/ftp/python/3.6.6/python-3.6.6.exe" ? "https://www.python.org/ftp/python/3.6.6/python-3.6.6.exe"
: "https://www.python.org/ftp/python/3.4.4/python-3.4.4.msi"); : "https://www.python.org/ftp/python/3.4.4/python-3.4.4.msi");
Net::DownloadHandler *handler = Net::DownloadManager::instance()->download( Net::DownloadManager::instance()->download(
Net::DownloadRequest(installerURL).saveToFile(true)); Net::DownloadRequest(installerURL).saveToFile(true)
, this, &MainWindow::pythonDownloadFinished);
using Func = void (Net::DownloadHandler::*)(const QString &, const QString &);
connect(handler, static_cast<Func>(&Net::DownloadHandler::downloadFinished), this, &MainWindow::pythonDownloadSuccess);
connect(handler, static_cast<Func>(&Net::DownloadHandler::downloadFailed), this, &MainWindow::pythonDownloadFailure);
} }
void MainWindow::pythonDownloadSuccess(const QString &url, const QString &filePath) void MainWindow::pythonDownloadFinished(const Net::DownloadResult &result)
{ {
Q_UNUSED(url) if (result.status != Net::DownloadStatus::Success) {
setCursor(QCursor(Qt::ArrowCursor));
QMessageBox::warning(
this, tr("Download error")
, tr("Python setup could not be downloaded, reason: %1.\nPlease install it manually.")
.arg(result.errorString));
return;
}
setCursor(QCursor(Qt::ArrowCursor)); setCursor(QCursor(Qt::ArrowCursor));
QProcess installer; QProcess installer;
qDebug("Launching Python installer in passive mode..."); qDebug("Launching Python installer in passive mode...");
if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) { if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) {
QFile::rename(filePath, filePath + ".exe"); QFile::rename(result.filePath, result.filePath + ".exe");
installer.start('"' + Utils::Fs::toNativePath(filePath) + ".exe\" /passive"); installer.start('"' + Utils::Fs::toNativePath(result.filePath) + ".exe\" /passive");
} }
else { else {
QFile::rename(filePath, filePath + ".msi"); QFile::rename(result.filePath, result.filePath + ".msi");
installer.start(Utils::Misc::windowsSystemPath() + "\\msiexec.exe /passive /i \"" + Utils::Fs::toNativePath(filePath) + ".msi\""); installer.start(Utils::Misc::windowsSystemPath() + "\\msiexec.exe /passive /i \"" + Utils::Fs::toNativePath(result.filePath) + ".msi\"");
} }
// Wait for setup to complete // Wait for setup to complete
@ -2045,21 +2049,13 @@ void MainWindow::pythonDownloadSuccess(const QString &url, const QString &filePa
qDebug("Setup should be complete!"); qDebug("Setup should be complete!");
// Delete temp file // Delete temp file
if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA)
Utils::Fs::forceRemove(filePath + ".exe"); Utils::Fs::forceRemove(result.filePath + ".exe");
else else
Utils::Fs::forceRemove(filePath + ".msi"); Utils::Fs::forceRemove(result.filePath + ".msi");
// Reload search engine // Reload search engine
if (Utils::ForeignApps::pythonInfo().isSupportedVersion()) { if (Utils::ForeignApps::pythonInfo().isSupportedVersion()) {
m_ui->actionSearchWidget->setChecked(true); m_ui->actionSearchWidget->setChecked(true);
displaySearchTab(true); displaySearchTab(true);
} }
} }
void MainWindow::pythonDownloadFailure(const QString &url, const QString &error)
{
Q_UNUSED(url)
setCursor(QCursor(Qt::ArrowCursor));
QMessageBox::warning(this, tr("Download error"), tr("Python setup could not be downloaded, reason: %1.\nPlease install it manually.").arg(error));
}
#endif // Q_OS_WIN #endif // Q_OS_WIN

8
src/gui/mainwindow.h

@ -62,6 +62,11 @@ namespace BitTorrent
class TorrentHandle; class TorrentHandle;
} }
namespace Net
{
struct DownloadResult;
}
namespace Ui namespace Ui
{ {
class MainWindow; class MainWindow;
@ -135,8 +140,7 @@ private slots:
void toggleAlternativeSpeeds(); void toggleAlternativeSpeeds();
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
void pythonDownloadSuccess(const QString &url, const QString &filePath); void pythonDownloadFinished(const Net::DownloadResult &result);
void pythonDownloadFailure(const QString &url, const QString &error);
#endif #endif
void addToolbarContextMenu(); void addToolbarContextMenu();
void manageCookies(); void manageCookies();

27
src/gui/programupdater.cpp

@ -35,7 +35,6 @@
#include <QSysInfo> #include <QSysInfo>
#include <QXmlStreamReader> #include <QXmlStreamReader>
#include "base/net/downloadhandler.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
#include "base/utils/fs.h" #include "base/utils/fs.h"
@ -56,16 +55,20 @@ void ProgramUpdater::checkForUpdates()
{ {
// Don't change this User-Agent. In case our updater goes haywire, // Don't change this User-Agent. In case our updater goes haywire,
// the filehost can identify it and contact us. // the filehost can identify it and contact us.
Net::DownloadHandler *handler = Net::DownloadManager::instance()->download( Net::DownloadManager::instance()->download(
Net::DownloadRequest(RSS_URL).userAgent("qBittorrent/" QBT_VERSION_2 " ProgramUpdater (www.qbittorrent.org)")); Net::DownloadRequest(RSS_URL).userAgent("qBittorrent/" QBT_VERSION_2 " ProgramUpdater (www.qbittorrent.org)")
connect(handler, static_cast<void (Net::DownloadHandler::*)(const QString &, const QByteArray &)>(&Net::DownloadHandler::downloadFinished)
, this, &ProgramUpdater::rssDownloadFinished); , this, &ProgramUpdater::rssDownloadFinished);
connect(handler, &Net::DownloadHandler::downloadFailed, this, &ProgramUpdater::rssDownloadFailed);
} }
void ProgramUpdater::rssDownloadFinished(const QString &url, const QByteArray &data) void ProgramUpdater::rssDownloadFinished(const Net::DownloadResult &result)
{ {
Q_UNUSED(url);
if (result.status != Net::DownloadStatus::Success) {
qDebug() << "Downloading the new qBittorrent updates RSS failed:" << result.errorString;
emit updateCheckFinished(false, QString(), m_invokedByUser);
return;
}
qDebug("Finished downloading the new qBittorrent updates RSS"); qDebug("Finished downloading the new qBittorrent updates RSS");
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
@ -77,7 +80,7 @@ void ProgramUpdater::rssDownloadFinished(const QString &url, const QByteArray &d
#endif #endif
QString version; QString version;
QXmlStreamReader xml(data); QXmlStreamReader xml(result.data);
bool inItem = false; bool inItem = false;
QString updateLink; QString updateLink;
QString type; QString type;
@ -118,14 +121,6 @@ void ProgramUpdater::rssDownloadFinished(const QString &url, const QByteArray &d
emit updateCheckFinished(!m_updateUrl.isEmpty(), version, m_invokedByUser); emit updateCheckFinished(!m_updateUrl.isEmpty(), version, m_invokedByUser);
} }
void ProgramUpdater::rssDownloadFailed(const QString &url, const QString &error)
{
Q_UNUSED(url);
qDebug() << "Downloading the new qBittorrent updates RSS failed:" << error;
emit updateCheckFinished(false, QString(), m_invokedByUser);
}
void ProgramUpdater::updateProgram() void ProgramUpdater::updateProgram()
{ {
Q_ASSERT(!m_updateUrl.isEmpty()); Q_ASSERT(!m_updateUrl.isEmpty());

9
src/gui/programupdater.h

@ -32,9 +32,15 @@
#include <QObject> #include <QObject>
#include <QUrl> #include <QUrl>
namespace Net
{
struct DownloadResult;
}
class ProgramUpdater : public QObject class ProgramUpdater : public QObject
{ {
Q_OBJECT Q_OBJECT
Q_DISABLE_COPY(ProgramUpdater)
public: public:
explicit ProgramUpdater(QObject *parent = nullptr, bool invokedByUser = false); explicit ProgramUpdater(QObject *parent = nullptr, bool invokedByUser = false);
@ -46,8 +52,7 @@ signals:
void updateCheckFinished(bool updateAvailable, QString version, bool invokedByUser); void updateCheckFinished(bool updateAvailable, QString version, bool invokedByUser);
private slots: private slots:
void rssDownloadFinished(const QString &url, const QByteArray &data); void rssDownloadFinished(const Net::DownloadResult &result);
void rssDownloadFailed(const QString &url, const QString &error);
private: private:
bool isVersionMoreRecent(const QString &remoteVersion) const; bool isVersionMoreRecent(const QString &remoteVersion) const;

30
src/gui/properties/trackersadditiondialog.cpp

@ -35,7 +35,6 @@
#include "base/bittorrent/torrenthandle.h" #include "base/bittorrent/torrenthandle.h"
#include "base/bittorrent/trackerentry.h" #include "base/bittorrent/trackerentry.h"
#include "base/global.h" #include "base/global.h"
#include "base/net/downloadhandler.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
#include "base/utils/fs.h" #include "base/utils/fs.h"
#include "base/utils/misc.h" #include "base/utils/misc.h"
@ -71,16 +70,25 @@ QStringList TrackersAdditionDialog::newTrackers() const
void TrackersAdditionDialog::on_uTorrentListButton_clicked() void TrackersAdditionDialog::on_uTorrentListButton_clicked()
{ {
m_ui->uTorrentListButton->setEnabled(false); m_ui->uTorrentListButton->setEnabled(false);
Net::DownloadHandler *handler = Net::DownloadManager::instance()->download(m_ui->lineEditListURL->text()); Net::DownloadManager::instance()->download(m_ui->lineEditListURL->text()
connect(handler, static_cast<void (Net::DownloadHandler::*)(const QString &, const QByteArray &)>(&Net::DownloadHandler::downloadFinished) , this, &TrackersAdditionDialog::torrentListDownloadFinished);
, this, &TrackersAdditionDialog::parseUTorrentList);
connect(handler, &Net::DownloadHandler::downloadFailed, this, &TrackersAdditionDialog::getTrackerError);
// Just to show that it takes times // Just to show that it takes times
setCursor(Qt::WaitCursor); setCursor(Qt::WaitCursor);
} }
void TrackersAdditionDialog::parseUTorrentList(const QString &, const QByteArray &data) void TrackersAdditionDialog::torrentListDownloadFinished(const Net::DownloadResult &result)
{ {
if (result.status != Net::DownloadStatus::Success) {
// To restore the cursor ...
setCursor(Qt::ArrowCursor);
m_ui->uTorrentListButton->setEnabled(true);
QMessageBox::warning(
this, tr("Download error")
, tr("The trackers list could not be downloaded, reason: %1")
.arg(result.errorString), QMessageBox::Ok);
return;
}
// Load from torrent handle // Load from torrent handle
QList<BitTorrent::TrackerEntry> existingTrackers = m_torrent->trackers(); QList<BitTorrent::TrackerEntry> existingTrackers = m_torrent->trackers();
// Load from current user list // Load from current user list
@ -96,7 +104,7 @@ void TrackersAdditionDialog::parseUTorrentList(const QString &, const QByteArray
m_ui->textEditTrackersList->insertPlainText("\n"); m_ui->textEditTrackersList->insertPlainText("\n");
int nb = 0; int nb = 0;
QBuffer buffer; QBuffer buffer;
buffer.setData(data); buffer.setData(result.data);
buffer.open(QBuffer::ReadOnly); buffer.open(QBuffer::ReadOnly);
while (!buffer.atEnd()) { while (!buffer.atEnd()) {
const QString line = buffer.readLine().trimmed(); const QString line = buffer.readLine().trimmed();
@ -117,14 +125,6 @@ void TrackersAdditionDialog::parseUTorrentList(const QString &, const QByteArray
QMessageBox::information(this, tr("No change"), tr("No additional trackers were found."), QMessageBox::Ok); QMessageBox::information(this, tr("No change"), tr("No additional trackers were found."), QMessageBox::Ok);
} }
void TrackersAdditionDialog::getTrackerError(const QString &, const QString &error)
{
// To restore the cursor ...
setCursor(Qt::ArrowCursor);
m_ui->uTorrentListButton->setEnabled(true);
QMessageBox::warning(this, tr("Download error"), tr("The trackers list could not be downloaded, reason: %1").arg(error), QMessageBox::Ok);
}
QStringList TrackersAdditionDialog::askForTrackers(QWidget *parent, BitTorrent::TorrentHandle *const torrent) QStringList TrackersAdditionDialog::askForTrackers(QWidget *parent, BitTorrent::TorrentHandle *const torrent)
{ {
QStringList trackers; QStringList trackers;

8
src/gui/properties/trackersadditiondialog.h

@ -39,6 +39,11 @@ namespace BitTorrent
class TorrentHandle; class TorrentHandle;
} }
namespace Net
{
struct DownloadResult;
}
namespace Ui namespace Ui
{ {
class TrackersAdditionDialog; class TrackersAdditionDialog;
@ -57,8 +62,7 @@ public:
public slots: public slots:
void on_uTorrentListButton_clicked(); void on_uTorrentListButton_clicked();
void parseUTorrentList(const QString &, const QByteArray &data); void torrentListDownloadFinished(const Net::DownloadResult &result);
void getTrackerError(const QString &, const QString &error);
private: private:
Ui::TrackersAdditionDialog *m_ui; Ui::TrackersAdditionDialog *m_ui;

27
src/gui/search/pluginselectdialog.cpp

@ -40,7 +40,6 @@
#include <QTableView> #include <QTableView>
#include "base/global.h" #include "base/global.h"
#include "base/net/downloadhandler.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
#include "base/utils/fs.h" #include "base/utils/fs.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
@ -291,11 +290,9 @@ void PluginSelectDialog::addNewPlugin(const QString &pluginName)
else { else {
// Icon is missing, we must download it // Icon is missing, we must download it
using namespace Net; using namespace Net;
DownloadHandler *handler = DownloadManager::instance()->download( DownloadManager::instance()->download(
DownloadRequest(plugin->url + "/favicon.ico").saveToFile(true)); DownloadRequest(plugin->url + "/favicon.ico").saveToFile(true)
connect(handler, static_cast<void (DownloadHandler::*)(const QString &, const QString &)>(&DownloadHandler::downloadFinished) , this, &PluginSelectDialog::iconDownloadFinished);
, this, &PluginSelectDialog::iconDownloaded);
connect(handler, &DownloadHandler::downloadFailed, this, &PluginSelectDialog::iconDownloadFailed);
} }
item->setText(PLUGIN_VERSION, plugin->version); item->setText(PLUGIN_VERSION, plugin->version);
} }
@ -369,9 +366,14 @@ void PluginSelectDialog::askForLocalPlugin()
} }
} }
void PluginSelectDialog::iconDownloaded(const QString &url, QString filePath) void PluginSelectDialog::iconDownloadFinished(const Net::DownloadResult &result)
{ {
filePath = Utils::Fs::fromNativePath(filePath); if (result.status != Net::DownloadStatus::Success) {
qDebug("Could not download favicon: %s, reason: %s", qUtf8Printable(result.url), qUtf8Printable(result.errorString));
return;
}
const QString filePath = Utils::Fs::fromNativePath(result.filePath);
// Icon downloaded // Icon downloaded
QIcon icon(filePath); QIcon icon(filePath);
@ -379,7 +381,7 @@ void PluginSelectDialog::iconDownloaded(const QString &url, QString filePath)
QList<QSize> sizes = icon.availableSizes(); QList<QSize> sizes = icon.availableSizes();
bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull()); bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull());
if (!invalid) { if (!invalid) {
for (QTreeWidgetItem *item : asConst(findItemsWithUrl(url))) { for (QTreeWidgetItem *item : asConst(findItemsWithUrl(result.url))) {
QString id = item->text(PLUGIN_ID); QString id = item->text(PLUGIN_ID);
PluginInfo *plugin = m_pluginManager->pluginInfo(id); PluginInfo *plugin = m_pluginManager->pluginInfo(id);
if (!plugin) continue; if (!plugin) continue;
@ -387,7 +389,7 @@ void PluginSelectDialog::iconDownloaded(const QString &url, QString filePath)
QString iconPath = QString("%1/%2.%3") QString iconPath = QString("%1/%2.%3")
.arg(SearchPluginManager::pluginsLocation() .arg(SearchPluginManager::pluginsLocation()
, id , id
, url.endsWith(".ico", Qt::CaseInsensitive) ? "ico" : "png"); , result.url.endsWith(".ico", Qt::CaseInsensitive) ? "ico" : "png");
if (QFile::copy(filePath, iconPath)) { if (QFile::copy(filePath, iconPath)) {
// This 2nd check is necessary. Some favicons (eg from piratebay) // This 2nd check is necessary. Some favicons (eg from piratebay)
// decode fine without an ext, but fail to do so when appending the ext // decode fine without an ext, but fail to do so when appending the ext
@ -409,11 +411,6 @@ void PluginSelectDialog::iconDownloaded(const QString &url, QString filePath)
Utils::Fs::forceRemove(filePath); Utils::Fs::forceRemove(filePath);
} }
void PluginSelectDialog::iconDownloadFailed(const QString &url, const QString &reason)
{
qDebug("Could not download favicon: %s, reason: %s", qUtf8Printable(url), qUtf8Printable(reason));
}
void PluginSelectDialog::checkForUpdatesFinished(const QHash<QString, PluginVersion> &updateInfo) void PluginSelectDialog::checkForUpdatesFinished(const QHash<QString, PluginVersion> &updateInfo)
{ {
finishAsyncOp(); finishAsyncOp();

11
src/gui/search/pluginselectdialog.h

@ -38,6 +38,11 @@ class QDropEvent;
class QStringList; class QStringList;
class QTreeWidgetItem; class QTreeWidgetItem;
namespace Net
{
struct DownloadResult;
}
namespace Ui namespace Ui
{ {
class PluginSelectDialog; class PluginSelectDialog;
@ -46,10 +51,11 @@ namespace Ui
class PluginSelectDialog : public QDialog class PluginSelectDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
Q_DISABLE_COPY(PluginSelectDialog)
public: public:
explicit PluginSelectDialog(SearchPluginManager *pluginManager, QWidget *parent = nullptr); explicit PluginSelectDialog(SearchPluginManager *pluginManager, QWidget *parent = nullptr);
~PluginSelectDialog(); ~PluginSelectDialog() override;
QList<QTreeWidgetItem*> findItemsWithUrl(const QString &url); QList<QTreeWidgetItem*> findItemsWithUrl(const QString &url);
QTreeWidgetItem *findItemWithID(const QString &id); QTreeWidgetItem *findItemWithID(const QString &id);
@ -69,8 +75,7 @@ private slots:
void enableSelection(bool enable); void enableSelection(bool enable);
void askForLocalPlugin(); void askForLocalPlugin();
void askForPluginUrl(); void askForPluginUrl();
void iconDownloaded(const QString &url, QString filePath); void iconDownloadFinished(const Net::DownloadResult &result);
void iconDownloadFailed(const QString &url, const QString &reason);
void checkForUpdatesFinished(const QHash<QString, PluginVersion> &updateInfo); void checkForUpdatesFinished(const QHash<QString, PluginVersion> &updateInfo);
void checkForUpdatesFailed(const QString &reason); void checkForUpdatesFailed(const QString &reason);

42
src/gui/transferlistfilterswidget.cpp

@ -42,7 +42,6 @@
#include "base/bittorrent/trackerentry.h" #include "base/bittorrent/trackerentry.h"
#include "base/global.h" #include "base/global.h"
#include "base/logger.h" #include "base/logger.h"
#include "base/net/downloadhandler.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
#include "base/preferences.h" #include "base/preferences.h"
#include "base/torrentfilter.h" #include "base/torrentfilter.h"
@ -406,49 +405,44 @@ void TrackerFiltersList::trackerWarning(const QString &hash, const QString &trac
void TrackerFiltersList::downloadFavicon(const QString &url) void TrackerFiltersList::downloadFavicon(const QString &url)
{ {
if (!m_downloadTrackerFavicon) return; if (!m_downloadTrackerFavicon) return;
Net::DownloadHandler *h = Net::DownloadManager::instance()->download( Net::DownloadManager::instance()->download(
Net::DownloadRequest(url).saveToFile(true)); Net::DownloadRequest(url).saveToFile(true)
using Func = void (Net::DownloadHandler::*)(const QString &, const QString &); , this, &TrackerFiltersList::handleFavicoDownloadFinished);
connect(h, static_cast<Func>(&Net::DownloadHandler::downloadFinished), this
, &TrackerFiltersList::handleFavicoDownload);
connect(h, static_cast<Func>(&Net::DownloadHandler::downloadFailed), this
, &TrackerFiltersList::handleFavicoFailure);
} }
void TrackerFiltersList::handleFavicoDownload(const QString &url, const QString &filePath) void TrackerFiltersList::handleFavicoDownloadFinished(const Net::DownloadResult &result)
{ {
const QString host = getHost(url); if (result.status != Net::DownloadStatus::Success) {
if (result.url.endsWith(".ico", Qt::CaseInsensitive))
downloadFavicon(result.url.left(result.url.size() - 4) + ".png");
return;
}
const QString host = getHost(result.url);
if (!m_trackers.contains(host)) { if (!m_trackers.contains(host)) {
Utils::Fs::forceRemove(filePath); Utils::Fs::forceRemove(result.filePath);
return; return;
} }
QListWidgetItem *trackerItem = item(rowFromTracker(host)); QListWidgetItem *trackerItem = item(rowFromTracker(host));
if (!trackerItem) return; if (!trackerItem) return;
QIcon icon(filePath); QIcon icon(result.filePath);
//Detect a non-decodable icon //Detect a non-decodable icon
QList<QSize> sizes = icon.availableSizes(); QList<QSize> sizes = icon.availableSizes();
bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull()); bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull());
if (invalid) { if (invalid) {
if (url.endsWith(".ico", Qt::CaseInsensitive)) if (result.url.endsWith(".ico", Qt::CaseInsensitive))
downloadFavicon(url.left(url.size() - 4) + ".png"); downloadFavicon(result.url.left(result.url.size() - 4) + ".png");
Utils::Fs::forceRemove(filePath); Utils::Fs::forceRemove(result.filePath);
} }
else { else {
trackerItem->setData(Qt::DecorationRole, QVariant(QIcon(filePath))); trackerItem->setData(Qt::DecorationRole, QVariant(QIcon(result.filePath)));
m_iconPaths.append(filePath); m_iconPaths.append(result.filePath);
} }
} }
void TrackerFiltersList::handleFavicoFailure(const QString &url, const QString &error)
{
Q_UNUSED(error)
if (url.endsWith(".ico", Qt::CaseInsensitive))
downloadFavicon(url.left(url.size() - 4) + ".png");
}
void TrackerFiltersList::showMenu(QPoint) void TrackerFiltersList::showMenu(QPoint)
{ {
QMenu menu(this); QMenu menu(this);

11
src/gui/transferlistfilterswidget.h

@ -42,9 +42,15 @@ namespace BitTorrent
class TrackerEntry; class TrackerEntry;
} }
namespace Net
{
struct DownloadResult;
}
class BaseFilterWidget : public QListWidget class BaseFilterWidget : public QListWidget
{ {
Q_OBJECT Q_OBJECT
Q_DISABLE_COPY(BaseFilterWidget)
public: public:
BaseFilterWidget(QWidget *parent, TransferListWidget *transferList); BaseFilterWidget(QWidget *parent, TransferListWidget *transferList);
@ -68,6 +74,7 @@ private slots:
class StatusFilterWidget : public BaseFilterWidget class StatusFilterWidget : public BaseFilterWidget
{ {
Q_OBJECT Q_OBJECT
Q_DISABLE_COPY(StatusFilterWidget)
public: public:
StatusFilterWidget(QWidget *parent, TransferListWidget *transferList); StatusFilterWidget(QWidget *parent, TransferListWidget *transferList);
@ -88,6 +95,7 @@ private:
class TrackerFiltersList : public BaseFilterWidget class TrackerFiltersList : public BaseFilterWidget
{ {
Q_OBJECT Q_OBJECT
Q_DISABLE_COPY(TrackerFiltersList)
public: public:
TrackerFiltersList(QWidget *parent, TransferListWidget *transferList); TrackerFiltersList(QWidget *parent, TransferListWidget *transferList);
@ -105,8 +113,7 @@ public slots:
void trackerWarning(const QString &hash, const QString &tracker); void trackerWarning(const QString &hash, const QString &tracker);
private slots: private slots:
void handleFavicoDownload(const QString &url, const QString &filePath); void handleFavicoDownloadFinished(const Net::DownloadResult &result);
void handleFavicoFailure(const QString &url, const QString &error);
private: private:
// These 4 methods are virtual slots in the base class. // These 4 methods are virtual slots in the base class.

Loading…
Cancel
Save