From 6cb15706f5eee546ef357a8cefd99be87168619a Mon Sep 17 00:00:00 2001 From: "Vladimir Golovnev (Glassez)" Date: Fri, 1 Mar 2019 10:38:16 +0300 Subject: [PATCH] Reduce number of DownloadManager signals --- src/base/bittorrent/session.cpp | 34 ++++---- src/base/bittorrent/session.h | 9 +- src/base/net/dnsupdater.cpp | 38 +++------ src/base/net/dnsupdater.h | 8 +- src/base/net/downloadhandler.cpp | 85 +++++++++---------- src/base/net/downloadhandler.h | 8 +- src/base/net/downloadmanager.cpp | 11 --- src/base/net/downloadmanager.h | 21 ++++- src/base/net/geoipmanager.cpp | 36 +++----- src/base/net/geoipmanager.h | 8 +- src/base/rss/rss_feed.cpp | 45 +++++----- src/base/rss/rss_feed.h | 10 ++- src/base/search/searchpluginmanager.cpp | 54 +++++------- src/base/search/searchpluginmanager.h | 11 ++- src/gui/addnewtorrentdialog.cpp | 64 +++++++------- src/gui/addnewtorrentdialog.h | 12 ++- src/gui/mainwindow.cpp | 37 ++++---- src/gui/mainwindow.h | 8 +- src/gui/programupdater.cpp | 24 +++--- src/gui/programupdater.h | 9 +- src/gui/properties/trackersadditiondialog.cpp | 27 +++--- src/gui/properties/trackersadditiondialog.h | 8 +- src/gui/search/pluginselectdialog.cpp | 22 +++-- src/gui/search/pluginselectdialog.h | 11 ++- src/gui/transferlistfilterswidget.cpp | 37 ++++---- src/gui/transferlistfilterswidget.h | 11 ++- 26 files changed, 314 insertions(+), 334 deletions(-) diff --git a/src/base/bittorrent/session.cpp b/src/base/bittorrent/session.cpp index 95d5d2708..0c1d7290a 100644 --- a/src/base/bittorrent/session.cpp +++ b/src/base/bittorrent/session.cpp @@ -1542,22 +1542,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 -void Session::handleDownloadFinished(const QString &url, const QByteArray &data) +void Session::handleDownloadFinished(const Net::DownloadResult &result) { - emit downloadFromUrlFinished(url); - addTorrent_impl(CreateTorrentParams(m_downloadedTorrents.take(url)) - , MagnetUri(), TorrentInfo::load(data)); + switch (result.status) { + case Net::DownloadStatus::Success: + 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 @@ -1796,11 +1795,8 @@ bool Session::addTorrent(const QString &source, const AddTorrentParams ¶ms) LogMsg(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(source)); // Launch downloader const Net::DownloadHandler *handler = - Net::DownloadManager::instance()->download(Net::DownloadRequest(source).limit(10485760 /* 10MB */).handleRedirectToMagnet(true)); - connect(handler, static_cast(&Net::DownloadHandler::downloadFinished) - , this, &Session::handleDownloadFinished); - connect(handler, &Net::DownloadHandler::downloadFailed, this, &Session::handleDownloadFailed); - connect(handler, &Net::DownloadHandler::redirectedToMagnet, this, &Session::handleRedirectedToMagnet); + Net::DownloadManager::instance()->download(Net::DownloadRequest(source).limit(10485760 /* 10MB */)); + connect(handler, &Net::DownloadHandler::finished, this, &Session::handleDownloadFinished); m_downloadedTorrents[handler->url()] = params; return true; } diff --git a/src/base/bittorrent/session.h b/src/base/bittorrent/session.h index 45629acd2..dc9103e7d 100644 --- a/src/base/bittorrent/session.h +++ b/src/base/bittorrent/session.h @@ -118,6 +118,11 @@ enum TorrentExportFolder Finished }; +namespace Net +{ + struct DownloadResult; +} + namespace BitTorrent { class InfoHash; @@ -537,9 +542,7 @@ namespace BitTorrent void generateResumeData(bool final = false); void handleIPFilterParsed(int ruleCount); void handleIPFilterError(); - void handleDownloadFinished(const QString &url, const QByteArray &data); - void handleDownloadFailed(const QString &url, const QString &reason); - void handleRedirectedToMagnet(const QString &url, const QString &magnetUri); + void handleDownloadFinished(const Net::DownloadResult &result); // Session reconfiguration triggers void networkOnlineStateChanged(bool online); diff --git a/src/base/net/dnsupdater.cpp b/src/base/net/dnsupdater.cpp index a262b5c65..6479c7d63 100644 --- a/src/base/net/dnsupdater.cpp +++ b/src/base/net/dnsupdater.cpp @@ -76,19 +76,20 @@ void DNSUpdater::checkPublicIP() DownloadHandler *handler = DownloadManager::instance()->download( DownloadRequest("http://checkip.dyndns.org").userAgent("qBittorrent/" QBT_VERSION_2)); - connect(handler, static_cast(&Net::DownloadHandler::downloadFinished) - , this, &DNSUpdater::ipRequestFinished); - connect(handler, &Net::DownloadHandler::downloadFailed, this, &DNSUpdater::ipRequestFailed); + connect(handler, &DownloadHandler::finished, this, &DNSUpdater::ipRequestFinished); 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 - const QRegularExpressionMatch ipRegexMatch = QRegularExpression("Current IP Address:\\s+([^<]+)").match(data); + const QRegularExpressionMatch ipRegexMatch = QRegularExpression("Current IP Address:\\s+([^<]+)").match(result.data); if (ipRegexMatch.hasMatch()) { QString ipStr = ipRegexMatch.captured(1); qDebug() << Q_FUNC_INFO << "Regular expression captured the following IP:" << ipStr; @@ -110,12 +111,6 @@ 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() { qDebug() << Q_FUNC_INFO; @@ -123,9 +118,7 @@ void DNSUpdater::updateDNSService() m_lastIPCheckTime = QDateTime::currentDateTime(); DownloadHandler *handler = DownloadManager::instance()->download( DownloadRequest(getUpdateUrl()).userAgent("qBittorrent/" QBT_VERSION_2)); - connect(handler, static_cast(&Net::DownloadHandler::downloadFinished) - , this, &DNSUpdater::ipUpdateFinished); - connect(handler, &Net::DownloadHandler::downloadFailed, this, &DNSUpdater::ipUpdateFailed); + connect(handler, &DownloadHandler::finished, this, &DNSUpdater::ipUpdateFinished); } QString DNSUpdater::getUpdateUrl() const @@ -164,17 +157,12 @@ QString DNSUpdater::getUpdateUrl() const return url.toString(); } -void DNSUpdater::ipUpdateFinished(const QString &url, const QByteArray &data) -{ - Q_UNUSED(url); - // Parse reply - processIPUpdateReply(data); -} - -void DNSUpdater::ipUpdateFailed(const QString &url, const QString &error) +void DNSUpdater::ipUpdateFinished(const DownloadResult &result) { - Q_UNUSED(url); - qWarning() << "IP update failed:" << error; + if (result.status == DownloadStatus::Success) + processIPUpdateReply(result.data); + else + qWarning() << "IP update failed:" << result.errorString; } void DNSUpdater::processIPUpdateReply(const QString &reply) diff --git a/src/base/net/dnsupdater.h b/src/base/net/dnsupdater.h index 99002fdc9..54459e4da 100644 --- a/src/base/net/dnsupdater.h +++ b/src/base/net/dnsupdater.h @@ -38,6 +38,8 @@ namespace Net { + struct DownloadResult; + // Based on http://www.dyndns.com/developers/specs/ class DNSUpdater : public QObject { @@ -54,11 +56,9 @@ namespace Net private slots: void checkPublicIP(); - void ipRequestFinished(const QString &url, const QByteArray &data); - void ipRequestFailed(const QString &url, const QString &error); + void ipRequestFinished(const DownloadResult &result); void updateDNSService(); - void ipUpdateFinished(const QString &url, const QByteArray &data); - void ipUpdateFailed(const QString &url, const QString &error); + void ipUpdateFinished(const DownloadResult &result); private: enum State diff --git a/src/base/net/downloadhandler.cpp b/src/base/net/downloadhandler.cpp index d94efe22c..78de6109d 100644 --- a/src/base/net/downloadhandler.cpp +++ b/src/base/net/downloadhandler.cpp @@ -69,6 +69,8 @@ Net::DownloadHandler::DownloadHandler(QNetworkReply *reply, DownloadManager *man { if (reply) assignNetworkReply(reply); + m_result.url = url(); + m_result.status = DownloadStatus::Success; } Net::DownloadHandler::~DownloadHandler() @@ -103,8 +105,8 @@ void Net::DownloadHandler::processFinishedDownload() 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(); + setError(errorCodeToString(m_reply->error())); + finish(); return; } @@ -117,49 +119,43 @@ void Net::DownloadHandler::processFinishedDownload() } // Success - const QByteArray replyData = (m_reply->rawHeader("Content-Encoding") == "gzip") + 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(replyData, filePath)) - emit downloadFinished(m_downloadRequest.url(), filePath); + if (saveToFile(m_result.data, filePath)) + m_result.filePath = filePath; else - emit downloadFailed(m_downloadRequest.url(), tr("I/O Error")); - } - else { - emit downloadFinished(m_downloadRequest.url(), replyData); + setError(tr("I/O Error")); } - this->deleteLater(); + finish(); } 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) { + if ((bytesTotal > 0) && (bytesTotal <= m_downloadRequest.limit())) { // 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); - } + disconnect(m_reply, &QNetworkReply::downloadProgress, this, &Net::DownloadHandler::checkDownloadSize); + return; } - else if (bytesReceived > m_downloadRequest.limit()) { + + if ((bytesTotal > m_downloadRequest.limit()) || (bytesReceived > m_downloadRequest.limit())) { m_reply->abort(); - emit downloadFailed(m_downloadRequest.url(), msg.arg(Utils::Misc::friendlyUnit(bytesReceived), Utils::Misc::friendlyUnit(m_downloadRequest.limit()))); + 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 Net::DownloadHandler::handleRedirection(const QUrl &newUrl) { if (m_redirectionCounter >= MAX_REDIRECTIONS) { - emit downloadFailed(url(), tr("Exceeded max redirections (%1)").arg(MAX_REDIRECTIONS)); - this->deleteLater(); + setError(tr("Exceeded max redirections (%1)").arg(MAX_REDIRECTIONS)); + finish(); return; } @@ -172,38 +168,35 @@ void Net::DownloadHandler::handleRedirection(const QUrl &newUrl) 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.")); + m_result.status = DownloadStatus::RedirectedToMagnet; + m_result.magnet = newUrlString; - this->deleteLater(); + finish(); 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(&DownloadHandler::downloadFinished) - , this, [this](const QString &, const QString &fileName) + connect(redirected, &DownloadHandler::finished, this, [this](const DownloadResult &result) { - emit downloadFinished(url(), fileName); - }); - connect(redirected, static_cast(&DownloadHandler::downloadFinished) - , this, [this](const QString &, const QByteArray &data) - { - emit downloadFinished(url(), data); + m_result = result; + m_result.url = url(); + finish(); }); } +void Net::DownloadHandler::setError(const QString &error) +{ + m_result.errorString = error; + m_result.status = DownloadStatus::Failed; +} + +void Net::DownloadHandler::finish() +{ + emit finished(m_result); + deleteLater(); +} + QString Net::DownloadHandler::errorCodeToString(const QNetworkReply::NetworkError status) { switch (status) { diff --git a/src/base/net/downloadhandler.h b/src/base/net/downloadhandler.h index cd13a8448..113920ad6 100644 --- a/src/base/net/downloadhandler.h +++ b/src/base/net/downloadhandler.h @@ -56,10 +56,7 @@ namespace Net 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); + void finished(const DownloadResult &result); private slots: void processFinishedDownload(); @@ -68,6 +65,8 @@ namespace Net private: void assignNetworkReply(QNetworkReply *reply); void handleRedirection(const QUrl &newUrl); + void setError(const QString &error); + void finish(); static QString errorCodeToString(QNetworkReply::NetworkError status); @@ -75,6 +74,7 @@ namespace Net DownloadManager *m_manager; const DownloadRequest m_downloadRequest; short m_redirectionCounter = 0; + DownloadResult m_result; }; } diff --git a/src/base/net/downloadmanager.cpp b/src/base/net/downloadmanager.cpp index 680d2e233..eb9eb924d 100644 --- a/src/base/net/downloadmanager.cpp +++ b/src/base/net/downloadmanager.cpp @@ -328,17 +328,6 @@ Net::DownloadRequest &Net::DownloadRequest::saveToFile(const bool value) 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) { return {url.host(), url.port(80)}; diff --git a/src/base/net/downloadmanager.h b/src/base/net/downloadmanager.h index 3e83dbc3f..1ff70dbde 100644 --- a/src/base/net/downloadmanager.h +++ b/src/base/net/downloadmanager.h @@ -64,15 +64,28 @@ namespace Net bool saveToFile() const; DownloadRequest &saveToFile(bool value); - bool handleRedirectToMagnet() const; - DownloadRequest &handleRedirectToMagnet(bool value); - private: QString m_url; QString m_userAgent; qint64 m_limit = 0; bool m_saveToFile = false; - bool m_handleRedirectToMagnet = false; + }; + + enum class DownloadStatus + { + Success, + RedirectedToMagnet, + Failed + }; + + struct DownloadResult + { + QString url; + DownloadStatus status; + QString errorString; + QByteArray data; + QString filePath; + QString magnet; }; struct ServiceID diff --git a/src/base/net/geoipmanager.cpp b/src/base/net/geoipmanager.cpp index 541ebad0d..23cc151f7 100644 --- a/src/base/net/geoipmanager.cpp +++ b/src/base/net/geoipmanager.cpp @@ -119,9 +119,7 @@ void GeoIPManager::manageDatabaseUpdate() void GeoIPManager::downloadDatabaseFile() { const DownloadHandler *handler = DownloadManager::instance()->download({DATABASE_URL}); - connect(handler, static_cast(&Net::DownloadHandler::downloadFinished) - , this, &GeoIPManager::downloadFinished); - connect(handler, &Net::DownloadHandler::downloadFailed, this, &GeoIPManager::downloadFailed); + connect(handler, &DownloadHandler::finished, this, &GeoIPManager::downloadFinished); } QString GeoIPManager::lookup(const QHostAddress &hostAddr) const @@ -413,14 +411,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; - data = Utils::Gzip::decompress(data, &ok); + const QByteArray data = Utils::Gzip::decompress(result.data, &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; } @@ -431,7 +432,7 @@ void GeoIPManager::downloadFinished(const QString &url, QByteArray data) if (m_geoIPDatabase) delete m_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()), Log::INFO); const QString targetPath = Utils::Fs::expandPathAbs( @@ -439,25 +440,16 @@ void GeoIPManager::downloadFinished(const QString &url, QByteArray data) if (!QDir(targetPath).exists()) QDir().mkpath(targetPath); QFile targetFile(QString("%1/%2").arg(targetPath, GEOIP_FILENAME)); - if (!targetFile.open(QFile::WriteOnly) || (targetFile.write(data) == -1)) { - Logger::instance()->addMessage( - tr("Couldn't save downloaded GeoIP database file."), Log::WARNING); - } - else { - Logger::instance()->addMessage(tr("Successfully updated GeoIP database."), Log::INFO); - } + if (!targetFile.open(QFile::WriteOnly) || (targetFile.write(data) == -1)) + LogMsg(tr("Couldn't save downloaded GeoIP database file."), Log::WARNING); + else + LogMsg(tr("Successfully updated GeoIP database."), Log::INFO); } else { delete geoIPDatabase; } } 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); -} diff --git a/src/base/net/geoipmanager.h b/src/base/net/geoipmanager.h index b185354e2..ef9ef5a4d 100644 --- a/src/base/net/geoipmanager.h +++ b/src/base/net/geoipmanager.h @@ -40,9 +40,12 @@ class GeoIPDatabase; namespace Net { + struct DownloadResult; + class GeoIPManager : public QObject { Q_OBJECT + Q_DISABLE_COPY(GeoIPManager) public: static void initInstance(); @@ -55,12 +58,11 @@ namespace Net private slots: void configure(); - void downloadFinished(const QString &url, QByteArray data); - void downloadFailed(const QString &url, const QString &reason); + void downloadFinished(const DownloadResult &result); private: GeoIPManager(); - ~GeoIPManager(); + ~GeoIPManager() override; void loadDatabase(); void manageDatabaseUpdate(); diff --git a/src/base/rss/rss_feed.cpp b/src/base/rss/rss_feed.cpp index d2c785522..4a2c6c298 100644 --- a/src/base/rss/rss_feed.cpp +++ b/src/base/rss/rss_feed.cpp @@ -131,10 +131,7 @@ void Feed::refresh() // NOTE: Should we allow manually refreshing for disabled session? Net::DownloadHandler *handler = Net::DownloadManager::instance()->download(m_url); - connect(handler - , static_cast(&Net::DownloadHandler::downloadFinished) - , this, &Feed::handleDownloadFinished); - connect(handler, &Net::DownloadHandler::downloadFailed, this, &Feed::handleDownloadFailed); + connect(handler, &Net::DownloadHandler::finished, this, &Feed::handleDownloadFinished); m_isLoading = true; emit stateChanged(this); @@ -182,12 +179,12 @@ void Feed::handleMaxArticlesPerFeedChanged(const int n) // 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); - - m_iconPath = Utils::Fs::fromNativePath(filePath); - emit iconLoaded(this); + if (result.status == Net::DownloadStatus::Success) { + m_iconPath = Utils::Fs::fromNativePath(result.filePath); + emit iconLoaded(this); + } } bool Feed::hasError() const @@ -195,22 +192,22 @@ bool Feed::hasError() const return m_hasError; } -void Feed::handleDownloadFinished(const QString &url, const QByteArray &data) -{ - qDebug() << "Successfully downloaded RSS feed at" << url; - // Parse the download RSS - m_parser->parse(data); -} - -void Feed::handleDownloadFailed(const QString &url, const QString &error) +void Feed::handleDownloadFinished(const Net::DownloadResult &result) { - m_isLoading = false; - m_hasError = true; + if (result.status == Net::DownloadStatus::Success) { + qDebug() << "Successfully downloaded RSS feed at" << result.url; + // Parse the download RSS + m_parser->parse(result.data); + } + else { + m_isLoading = false; + m_hasError = true; - LogMsg(tr("Failed to download RSS feed at '%1'. Reason: %2").arg(url, error) - , Log::WARNING); + LogMsg(tr("Failed to download RSS feed at '%1'. Reason: %2") + .arg(result.url, result.errorString), Log::WARNING); - emit stateChanged(this); + emit stateChanged(this); + } } void Feed::handleParsingFinished(const RSS::Private::ParsingResult &result) @@ -404,9 +401,7 @@ void Feed::downloadIcon() const auto iconUrl = QString("%1://%2/favicon.ico").arg(url.scheme(), url.host()); const Net::DownloadHandler *handler = Net::DownloadManager::instance()->download( Net::DownloadRequest(iconUrl).saveToFile(true)); - connect(handler - , static_cast(&Net::DownloadHandler::downloadFinished) - , this, &Feed::handleIconDownloadFinished); + connect(handler, &Net::DownloadHandler::finished, this, &Feed::handleIconDownloadFinished); } int Feed::updateArticles(const QList &loadedArticles) diff --git a/src/base/rss/rss_feed.h b/src/base/rss/rss_feed.h index 3e75ab3b9..140d3aa92 100644 --- a/src/base/rss/rss_feed.h +++ b/src/base/rss/rss_feed.h @@ -39,6 +39,11 @@ class AsyncFileStorage; +namespace Net +{ + struct DownloadResult; +} + namespace RSS { class Article; @@ -85,9 +90,8 @@ namespace RSS private slots: void handleSessionProcessingEnabledChanged(bool enabled); void handleMaxArticlesPerFeedChanged(int n); - void handleIconDownloadFinished(const QString &url, const QString &filePath); - void handleDownloadFinished(const QString &url, const QByteArray &data); - void handleDownloadFailed(const QString &url, const QString &error); + void handleIconDownloadFinished(const Net::DownloadResult &result); + void handleDownloadFinished(const Net::DownloadResult &result); void handleParsingFinished(const Private::ParsingResult &result); void handleArticleRead(Article *article); diff --git a/src/base/search/searchpluginmanager.cpp b/src/base/search/searchpluginmanager.cpp index 3bfd4d4de..7d3d3bd7a 100644 --- a/src/base/search/searchpluginmanager.cpp +++ b/src/base/search/searchpluginmanager.cpp @@ -200,9 +200,7 @@ void SearchPluginManager::installPlugin(const QString &source) if (Net::DownloadManager::hasSupportedScheme(source)) { using namespace Net; DownloadHandler *handler = DownloadManager::instance()->download(DownloadRequest(source).saveToFile(true)); - connect(handler, static_cast(&DownloadHandler::downloadFinished) - , this, &SearchPluginManager::pluginDownloaded); - connect(handler, &DownloadHandler::downloadFailed, this, &SearchPluginManager::pluginDownloadFailed); + connect(handler, &Net::DownloadHandler::finished, this, &SearchPluginManager::pluginDownloadFinished); } else { QString path = source; @@ -305,9 +303,7 @@ void SearchPluginManager::checkForUpdates() // Download version file from update server using namespace Net; DownloadHandler *handler = DownloadManager::instance()->download({m_updateUrl + "versions.txt"}); - connect(handler, static_cast(&DownloadHandler::downloadFinished) - , this, &SearchPluginManager::versionInfoDownloaded); - connect(handler, &DownloadHandler::downloadFailed, this, &SearchPluginManager::versionInfoDownloadFailed); + connect(handler, &Net::DownloadHandler::finished, this, &SearchPluginManager::versionInfoDownloadFinished); } SearchDownloadHandler *SearchPluginManager::downloadTorrent(const QString &siteUrl, const QString &url) @@ -364,36 +360,32 @@ QString SearchPluginManager::engineLocation() return location; } -void SearchPluginManager::versionInfoDownloaded(const QString &url, const QByteArray &data) +void SearchPluginManager::versionInfoDownloadFinished(const Net::DownloadResult &result) { - Q_UNUSED(url) - parseVersionInfo(data); -} - -void SearchPluginManager::versionInfoDownloadFailed(const QString &url, const QString &reason) -{ - Q_UNUSED(url) - emit checkForUpdatesFailed(tr("Update server is temporarily unavailable. %1").arg(reason)); + if (result.status == Net::DownloadStatus::Success) + parseVersionInfo(result.data); + else + emit checkForUpdatesFailed(tr("Update server is temporarily unavailable. %1").arg(result.errorString)); } -void SearchPluginManager::pluginDownloaded(const QString &url, QString filePath) +void SearchPluginManager::pluginDownloadFinished(const Net::DownloadResult &result) { - filePath = Utils::Fs::fromNativePath(filePath); - - QString pluginName = Utils::Fs::fileName(url); - pluginName.chop(pluginName.size() - pluginName.lastIndexOf('.')); // Remove extension - installPlugin_impl(pluginName, filePath); - Utils::Fs::forceRemove(filePath); -} + if (result.status == Net::DownloadStatus::Success) { + const QString filePath = Utils::Fs::fromNativePath(result.filePath); -void SearchPluginManager::pluginDownloadFailed(const QString &url, const QString &reason) -{ - QString pluginName = url.split('/').last(); - pluginName.replace(".py", "", Qt::CaseInsensitive); - if (pluginInfo(pluginName)) - emit pluginUpdateFailed(pluginName, tr("Failed to download the plugin file. %1").arg(reason)); - else - emit pluginInstallationFailed(pluginName, tr("Failed to download the plugin file. %1").arg(reason)); + QString pluginName = Utils::Fs::fileName(result.url); + pluginName.chop(pluginName.size() - pluginName.lastIndexOf('.')); // Remove extension + installPlugin_impl(pluginName, filePath); + Utils::Fs::forceRemove(filePath); + } + else { + QString pluginName = result.url.split('/').last(); + pluginName.replace(".py", "", Qt::CaseInsensitive); + if (pluginInfo(pluginName)) + emit pluginUpdateFailed(pluginName, tr("Failed to download the plugin file. %1").arg(result.errorString)); + else + emit pluginInstallationFailed(pluginName, tr("Failed to download the plugin file. %1").arg(result.errorString)); + } } // Update nova.py search plugin if necessary diff --git a/src/base/search/searchpluginmanager.h b/src/base/search/searchpluginmanager.h index ac485807d..60b32e8ff 100644 --- a/src/base/search/searchpluginmanager.h +++ b/src/base/search/searchpluginmanager.h @@ -38,6 +38,11 @@ using PluginVersion = Utils::Version; Q_DECLARE_METATYPE(PluginVersion) +namespace Net +{ + struct DownloadResult; +} + struct PluginInfo { QString name; @@ -104,10 +109,8 @@ private: void installPlugin_impl(const QString &name, const QString &path); bool isUpdateNeeded(const QString &pluginName, PluginVersion newVersion) const; - void versionInfoDownloaded(const QString &url, const QByteArray &data); - void versionInfoDownloadFailed(const QString &url, const QString &reason); - void pluginDownloaded(const QString &url, QString filePath); - void pluginDownloadFailed(const QString &url, const QString &reason); + void versionInfoDownloadFinished(const Net::DownloadResult &result); + void pluginDownloadFinished(const Net::DownloadResult &result); static QString pluginPath(const QString &name); diff --git a/src/gui/addnewtorrentdialog.cpp b/src/gui/addnewtorrentdialog.cpp index 0a6d15f8d..d40da8c01 100644 --- a/src/gui/addnewtorrentdialog.cpp +++ b/src/gui/addnewtorrentdialog.cpp @@ -238,11 +238,8 @@ void AddNewTorrentDialog::show(const QString &source, const BitTorrent::AddTorre if (Net::DownloadManager::hasSupportedScheme(source)) { // Launch downloader Net::DownloadHandler *handler = Net::DownloadManager::instance()->download( - Net::DownloadRequest(source).limit(10485760 /* 10MB */).handleRedirectToMagnet(true)); - connect(handler, static_cast(&Net::DownloadHandler::downloadFinished) - , dlg, &AddNewTorrentDialog::handleDownloadFinished); - connect(handler, &Net::DownloadHandler::downloadFailed, dlg, &AddNewTorrentDialog::handleDownloadFailed); - connect(handler, &Net::DownloadHandler::redirectedToMagnet, dlg, &AddNewTorrentDialog::handleRedirectedToMagnet); + Net::DownloadRequest(source).limit(10485760 /* 10MB */)); + connect(handler, &Net::DownloadHandler::finished, dlg, &AddNewTorrentDialog::handleDownloadFinished); return; } @@ -761,39 +758,36 @@ void AddNewTorrentDialog::setupTreeview() showAdvancedSettings(settings()->loadValue(KEY_EXPANDED, false).toBool()); } -void AddNewTorrentDialog::handleDownloadFailed(const QString &url, const QString &reason) -{ - 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) +void AddNewTorrentDialog::handleDownloadFinished(const Net::DownloadResult &result) { QString error; - m_torrentInfo = BitTorrent::TorrentInfo::load(data, &error); - if (!m_torrentInfo.isValid()) { - RaisedMessageBox::critical(this, tr("Invalid torrent"), tr("Failed to load from URL: %1.\nError: %2") - .arg(url, error)); - return; - } - - m_torrentGuard.reset(new TorrentFileGuard); + switch (result.status) { + case Net::DownloadStatus::Success: + m_torrentInfo = BitTorrent::TorrentInfo::load(result.data, &error); + if (!m_torrentInfo.isValid()) { + RaisedMessageBox::critical(this, tr("Invalid torrent"), tr("Failed to load from URL: %1.\nError: %2") + .arg(result.url, error)); + return; + } - if (loadTorrentImpl()) - open(); - else - this->deleteLater(); + m_torrentGuard.reset(new TorrentFileGuard); + + if (loadTorrentImpl()) + open(); + else + 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) diff --git a/src/gui/addnewtorrentdialog.h b/src/gui/addnewtorrentdialog.h index dd9268f0b..49fe4279b 100644 --- a/src/gui/addnewtorrentdialog.h +++ b/src/gui/addnewtorrentdialog.h @@ -43,6 +43,11 @@ namespace BitTorrent class MagnetUri; } +namespace Net +{ + struct DownloadResult; +} + namespace Ui { class AddNewTorrentDialog; @@ -55,12 +60,13 @@ class TorrentFileGuard; class AddNewTorrentDialog : public QDialog { Q_OBJECT + Q_DISABLE_COPY(AddNewTorrentDialog) public: static const int minPathHistoryLength = 0; static const int maxPathHistoryLength = 99; - ~AddNewTorrentDialog(); + ~AddNewTorrentDialog() override; static bool isEnabled(); static void setEnabled(bool value); @@ -79,9 +85,7 @@ private slots: void onSavePathChanged(const QString &newPath); void renameSelectedFile(); void updateMetadata(const BitTorrent::TorrentInfo &info); - void handleDownloadFailed(const QString &url, const QString &reason); - void handleRedirectedToMagnet(const QString &url, const QString &magnetUri); - void handleDownloadFinished(const QString &url, const QByteArray &data); + void handleDownloadFinished(const Net::DownloadResult &result); void TMMChanged(int index); void categoryChanged(int index); void doNotDeleteTorrentClicked(bool checked); diff --git a/src/gui/mainwindow.cpp b/src/gui/mainwindow.cpp index e8b50e035..ed3e917f3 100644 --- a/src/gui/mainwindow.cpp +++ b/src/gui/mainwindow.cpp @@ -2020,26 +2020,31 @@ void MainWindow::installPython() : "https://www.python.org/ftp/python/3.4.4/python-3.4.4.msi"); Net::DownloadHandler *handler = Net::DownloadManager::instance()->download( Net::DownloadRequest(installerURL).saveToFile(true)); - - using Func = void (Net::DownloadHandler::*)(const QString &, const QString &); - connect(handler, static_cast(&Net::DownloadHandler::downloadFinished), this, &MainWindow::pythonDownloadSuccess); - connect(handler, static_cast(&Net::DownloadHandler::downloadFailed), this, &MainWindow::pythonDownloadFailure); + connect(handler, &Net::DownloadHandler::finished, this, &MainWindow::pythonDownloadFinished); } -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)); QProcess installer; qDebug("Launching Python installer in passive mode..."); if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) { - QFile::rename(filePath, filePath + ".exe"); - installer.start('"' + Utils::Fs::toNativePath(filePath) + ".exe\" /passive"); + QFile::rename(result.filePath, result.filePath + ".exe"); + installer.start('"' + Utils::Fs::toNativePath(result.filePath) + ".exe\" /passive"); } else { - QFile::rename(filePath, filePath + ".msi"); - installer.start(Utils::Misc::windowsSystemPath() + "\\msiexec.exe /passive /i \"" + Utils::Fs::toNativePath(filePath) + ".msi\""); + QFile::rename(result.filePath, result.filePath + ".msi"); + installer.start(Utils::Misc::windowsSystemPath() + "\\msiexec.exe /passive /i \"" + Utils::Fs::toNativePath(result.filePath) + ".msi\""); } // Wait for setup to complete @@ -2050,21 +2055,13 @@ void MainWindow::pythonDownloadSuccess(const QString &url, const QString &filePa qDebug("Setup should be complete!"); // Delete temp file if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) - Utils::Fs::forceRemove(filePath + ".exe"); + Utils::Fs::forceRemove(result.filePath + ".exe"); else - Utils::Fs::forceRemove(filePath + ".msi"); + Utils::Fs::forceRemove(result.filePath + ".msi"); // Reload search engine if (Utils::ForeignApps::pythonInfo().isSupportedVersion()) { m_ui->actionSearchWidget->setChecked(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 diff --git a/src/gui/mainwindow.h b/src/gui/mainwindow.h index f02983921..b11f82482 100644 --- a/src/gui/mainwindow.h +++ b/src/gui/mainwindow.h @@ -62,6 +62,11 @@ namespace BitTorrent class TorrentHandle; } +namespace Net +{ + struct DownloadResult; +} + namespace Ui { class MainWindow; @@ -135,8 +140,7 @@ private slots: void toggleAlternativeSpeeds(); #ifdef Q_OS_WIN - void pythonDownloadSuccess(const QString &url, const QString &filePath); - void pythonDownloadFailure(const QString &url, const QString &error); + void pythonDownloadFinished(const Net::DownloadResult &result); #endif void addToolbarContextMenu(); void manageCookies(); diff --git a/src/gui/programupdater.cpp b/src/gui/programupdater.cpp index 4669c5ca6..46d84cd57 100644 --- a/src/gui/programupdater.cpp +++ b/src/gui/programupdater.cpp @@ -58,14 +58,18 @@ void ProgramUpdater::checkForUpdates() // the filehost can identify it and contact us. Net::DownloadHandler *handler = Net::DownloadManager::instance()->download( Net::DownloadRequest(RSS_URL).userAgent("qBittorrent/" QBT_VERSION_2 " ProgramUpdater (www.qbittorrent.org)")); - connect(handler, static_cast(&Net::DownloadHandler::downloadFinished) - , this, &ProgramUpdater::rssDownloadFinished); - connect(handler, &Net::DownloadHandler::downloadFailed, this, &ProgramUpdater::rssDownloadFailed); + connect(handler, &Net::DownloadHandler::finished, this, &ProgramUpdater::rssDownloadFinished); } -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"); #ifdef Q_OS_MAC @@ -77,7 +81,7 @@ void ProgramUpdater::rssDownloadFinished(const QString &url, const QByteArray &d #endif QString version; - QXmlStreamReader xml(data); + QXmlStreamReader xml(result.data); bool inItem = false; QString updateLink; QString type; @@ -118,14 +122,6 @@ void ProgramUpdater::rssDownloadFinished(const QString &url, const QByteArray &d 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() { Q_ASSERT(!m_updateUrl.isEmpty()); diff --git a/src/gui/programupdater.h b/src/gui/programupdater.h index 34b8e1762..f87836869 100644 --- a/src/gui/programupdater.h +++ b/src/gui/programupdater.h @@ -32,9 +32,15 @@ #include #include +namespace Net +{ + struct DownloadResult; +} + class ProgramUpdater : public QObject { Q_OBJECT + Q_DISABLE_COPY(ProgramUpdater) public: explicit ProgramUpdater(QObject *parent = nullptr, bool invokedByUser = false); @@ -46,8 +52,7 @@ signals: void updateCheckFinished(bool updateAvailable, QString version, bool invokedByUser); private slots: - void rssDownloadFinished(const QString &url, const QByteArray &data); - void rssDownloadFailed(const QString &url, const QString &error); + void rssDownloadFinished(const Net::DownloadResult &result); private: bool isVersionMoreRecent(const QString &remoteVersion) const; diff --git a/src/gui/properties/trackersadditiondialog.cpp b/src/gui/properties/trackersadditiondialog.cpp index c63628e86..bc1f23e79 100644 --- a/src/gui/properties/trackersadditiondialog.cpp +++ b/src/gui/properties/trackersadditiondialog.cpp @@ -72,15 +72,24 @@ void TrackersAdditionDialog::on_uTorrentListButton_clicked() { m_ui->uTorrentListButton->setEnabled(false); Net::DownloadHandler *handler = Net::DownloadManager::instance()->download(m_ui->lineEditListURL->text()); - connect(handler, static_cast(&Net::DownloadHandler::downloadFinished) - , this, &TrackersAdditionDialog::parseUTorrentList); - connect(handler, &Net::DownloadHandler::downloadFailed, this, &TrackersAdditionDialog::getTrackerError); + connect(handler, &Net::DownloadHandler::finished, this, &TrackersAdditionDialog::torrentListDownloadFinished); // Just to show that it takes times 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 QList existingTrackers = m_torrent->trackers(); // Load from current user list @@ -96,7 +105,7 @@ void TrackersAdditionDialog::parseUTorrentList(const QString &, const QByteArray m_ui->textEditTrackersList->insertPlainText("\n"); int nb = 0; QBuffer buffer; - buffer.setData(data); + buffer.setData(result.data); buffer.open(QBuffer::ReadOnly); while (!buffer.atEnd()) { const QString line = buffer.readLine().trimmed(); @@ -117,14 +126,6 @@ void TrackersAdditionDialog::parseUTorrentList(const QString &, const QByteArray 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 trackers; diff --git a/src/gui/properties/trackersadditiondialog.h b/src/gui/properties/trackersadditiondialog.h index c6843d340..29566079b 100644 --- a/src/gui/properties/trackersadditiondialog.h +++ b/src/gui/properties/trackersadditiondialog.h @@ -39,6 +39,11 @@ namespace BitTorrent class TorrentHandle; } +namespace Net +{ + struct DownloadResult; +} + namespace Ui { class TrackersAdditionDialog; @@ -57,8 +62,7 @@ public: public slots: void on_uTorrentListButton_clicked(); - void parseUTorrentList(const QString &, const QByteArray &data); - void getTrackerError(const QString &, const QString &error); + void torrentListDownloadFinished(const Net::DownloadResult &result); private: Ui::TrackersAdditionDialog *m_ui; diff --git a/src/gui/search/pluginselectdialog.cpp b/src/gui/search/pluginselectdialog.cpp index 17666bd91..e67e9c89f 100644 --- a/src/gui/search/pluginselectdialog.cpp +++ b/src/gui/search/pluginselectdialog.cpp @@ -293,9 +293,7 @@ void PluginSelectDialog::addNewPlugin(const QString &pluginName) using namespace Net; DownloadHandler *handler = DownloadManager::instance()->download( DownloadRequest(plugin->url + "/favicon.ico").saveToFile(true)); - connect(handler, static_cast(&DownloadHandler::downloadFinished) - , this, &PluginSelectDialog::iconDownloaded); - connect(handler, &DownloadHandler::downloadFailed, this, &PluginSelectDialog::iconDownloadFailed); + connect(handler, &DownloadHandler::finished, this, &PluginSelectDialog::iconDownloadFinished); } item->setText(PLUGIN_VERSION, plugin->version); } @@ -369,9 +367,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 QIcon icon(filePath); @@ -379,7 +382,7 @@ void PluginSelectDialog::iconDownloaded(const QString &url, QString filePath) QList sizes = icon.availableSizes(); bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull()); if (!invalid) { - for (QTreeWidgetItem *item : asConst(findItemsWithUrl(url))) { + for (QTreeWidgetItem *item : asConst(findItemsWithUrl(result.url))) { QString id = item->text(PLUGIN_ID); PluginInfo *plugin = m_pluginManager->pluginInfo(id); if (!plugin) continue; @@ -387,7 +390,7 @@ void PluginSelectDialog::iconDownloaded(const QString &url, QString filePath) QString iconPath = QString("%1/%2.%3") .arg(SearchPluginManager::pluginsLocation() , id - , url.endsWith(".ico", Qt::CaseInsensitive) ? "ico" : "png"); + , result.url.endsWith(".ico", Qt::CaseInsensitive) ? "ico" : "png"); if (QFile::copy(filePath, iconPath)) { // This 2nd check is necessary. Some favicons (eg from piratebay) // decode fine without an ext, but fail to do so when appending the ext @@ -409,11 +412,6 @@ void PluginSelectDialog::iconDownloaded(const QString &url, QString 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 &updateInfo) { finishAsyncOp(); diff --git a/src/gui/search/pluginselectdialog.h b/src/gui/search/pluginselectdialog.h index c2754f8bf..c8bf18c25 100644 --- a/src/gui/search/pluginselectdialog.h +++ b/src/gui/search/pluginselectdialog.h @@ -38,6 +38,11 @@ class QDropEvent; class QStringList; class QTreeWidgetItem; +namespace Net +{ + struct DownloadResult; +} + namespace Ui { class PluginSelectDialog; @@ -46,10 +51,11 @@ namespace Ui class PluginSelectDialog : public QDialog { Q_OBJECT + Q_DISABLE_COPY(PluginSelectDialog) public: explicit PluginSelectDialog(SearchPluginManager *pluginManager, QWidget *parent = nullptr); - ~PluginSelectDialog(); + ~PluginSelectDialog() override; QList findItemsWithUrl(const QString &url); QTreeWidgetItem *findItemWithID(const QString &id); @@ -69,8 +75,7 @@ private slots: void enableSelection(bool enable); void askForLocalPlugin(); void askForPluginUrl(); - void iconDownloaded(const QString &url, QString filePath); - void iconDownloadFailed(const QString &url, const QString &reason); + void iconDownloadFinished(const Net::DownloadResult &result); void checkForUpdatesFinished(const QHash &updateInfo); void checkForUpdatesFailed(const QString &reason); diff --git a/src/gui/transferlistfilterswidget.cpp b/src/gui/transferlistfilterswidget.cpp index 64f65d118..5e84f2568 100644 --- a/src/gui/transferlistfilterswidget.cpp +++ b/src/gui/transferlistfilterswidget.cpp @@ -408,47 +408,42 @@ void TrackerFiltersList::downloadFavicon(const QString &url) if (!m_downloadTrackerFavicon) return; Net::DownloadHandler *h = Net::DownloadManager::instance()->download( Net::DownloadRequest(url).saveToFile(true)); - using Func = void (Net::DownloadHandler::*)(const QString &, const QString &); - connect(h, static_cast(&Net::DownloadHandler::downloadFinished), this - , &TrackerFiltersList::handleFavicoDownload); - connect(h, static_cast(&Net::DownloadHandler::downloadFailed), this - , &TrackerFiltersList::handleFavicoFailure); + connect(h, &Net::DownloadHandler::finished, this, &TrackerFiltersList::handleFavicoDownloadFinished); } -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)) { - Utils::Fs::forceRemove(filePath); + Utils::Fs::forceRemove(result.filePath); return; } QListWidgetItem *trackerItem = item(rowFromTracker(host)); if (!trackerItem) return; - QIcon icon(filePath); + QIcon icon(result.filePath); //Detect a non-decodable icon QList sizes = icon.availableSizes(); bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull()); if (invalid) { - if (url.endsWith(".ico", Qt::CaseInsensitive)) - downloadFavicon(url.left(url.size() - 4) + ".png"); - Utils::Fs::forceRemove(filePath); + if (result.url.endsWith(".ico", Qt::CaseInsensitive)) + downloadFavicon(result.url.left(result.url.size() - 4) + ".png"); + Utils::Fs::forceRemove(result.filePath); } else { - trackerItem->setData(Qt::DecorationRole, QVariant(QIcon(filePath))); - m_iconPaths.append(filePath); + trackerItem->setData(Qt::DecorationRole, QVariant(QIcon(result.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) { QMenu menu(this); diff --git a/src/gui/transferlistfilterswidget.h b/src/gui/transferlistfilterswidget.h index bbea12e7f..da5422905 100644 --- a/src/gui/transferlistfilterswidget.h +++ b/src/gui/transferlistfilterswidget.h @@ -42,9 +42,15 @@ namespace BitTorrent class TrackerEntry; } +namespace Net +{ + struct DownloadResult; +} + class BaseFilterWidget : public QListWidget { Q_OBJECT + Q_DISABLE_COPY(BaseFilterWidget) public: BaseFilterWidget(QWidget *parent, TransferListWidget *transferList); @@ -68,6 +74,7 @@ private slots: class StatusFilterWidget : public BaseFilterWidget { Q_OBJECT + Q_DISABLE_COPY(StatusFilterWidget) public: StatusFilterWidget(QWidget *parent, TransferListWidget *transferList); @@ -88,6 +95,7 @@ private: class TrackerFiltersList : public BaseFilterWidget { Q_OBJECT + Q_DISABLE_COPY(TrackerFiltersList) public: TrackerFiltersList(QWidget *parent, TransferListWidget *transferList); @@ -105,8 +113,7 @@ public slots: void trackerWarning(const QString &hash, const QString &tracker); private slots: - void handleFavicoDownload(const QString &url, const QString &filePath); - void handleFavicoFailure(const QString &url, const QString &error); + void handleFavicoDownloadFinished(const Net::DownloadResult &result); private: // These 4 methods are virtual slots in the base class.