Browse Source

Merge pull request #10591 from Chocobo1/ngen2

Migrate to update-to-date libtorrent functions (part2)
adaptive-webui-19844
Mike Tzou 6 years ago committed by GitHub
parent
commit
4ed8b31641
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      src/base/CMakeLists.txt
  2. 1
      src/base/base.pri
  3. 8
      src/base/bittorrent/infohash.cpp
  4. 10
      src/base/bittorrent/infohash.h
  5. 9
      src/base/bittorrent/magneturi.cpp
  6. 4
      src/base/bittorrent/magneturi.h
  7. 55
      src/base/bittorrent/peerinfo.cpp
  8. 4
      src/base/bittorrent/peerinfo.h
  9. 40
      src/base/bittorrent/private/filterparserthread.cpp
  10. 4
      src/base/bittorrent/private/filterparserthread.h
  11. 81
      src/base/bittorrent/private/libtorrentfwd.h
  12. 2
      src/base/bittorrent/private/portforwarderimpl.cpp
  13. 7
      src/base/bittorrent/private/portforwarderimpl.h
  14. 906
      src/base/bittorrent/session.cpp
  15. 57
      src/base/bittorrent/session.h
  16. 23
      src/base/bittorrent/torrentcreatorthread.cpp
  17. 44
      src/base/bittorrent/torrenthandle.cpp
  18. 50
      src/base/bittorrent/torrenthandle.h
  19. 25
      src/base/bittorrent/torrentinfo.cpp
  20. 10
      src/base/bittorrent/torrentinfo.h
  21. 24
      src/base/bittorrent/tracker.cpp
  22. 9
      src/base/bittorrent/tracker.h
  23. 6
      src/base/bittorrent/trackerentry.cpp
  24. 6
      src/base/bittorrent/trackerentry.h

1
src/base/CMakeLists.txt

@ -9,7 +9,6 @@ bittorrent/infohash.h
bittorrent/magneturi.h bittorrent/magneturi.h
bittorrent/peerinfo.h bittorrent/peerinfo.h
bittorrent/private/bandwidthscheduler.h bittorrent/private/bandwidthscheduler.h
bittorrent/private/libtorrentfwd.h
bittorrent/private/filterparserthread.h bittorrent/private/filterparserthread.h
bittorrent/private/portforwarderimpl.h bittorrent/private/portforwarderimpl.h
bittorrent/private/resumedatasavingmanager.h bittorrent/private/resumedatasavingmanager.h

1
src/base/base.pri

@ -9,7 +9,6 @@ HEADERS += \
$$PWD/bittorrent/peerinfo.h \ $$PWD/bittorrent/peerinfo.h \
$$PWD/bittorrent/private/bandwidthscheduler.h \ $$PWD/bittorrent/private/bandwidthscheduler.h \
$$PWD/bittorrent/private/filterparserthread.h \ $$PWD/bittorrent/private/filterparserthread.h \
$$PWD/bittorrent/private/libtorrentfwd.h \
$$PWD/bittorrent/private/portforwarderimpl.h \ $$PWD/bittorrent/private/portforwarderimpl.h \
$$PWD/bittorrent/private/resumedatasavingmanager.h \ $$PWD/bittorrent/private/resumedatasavingmanager.h \
$$PWD/bittorrent/private/speedmonitor.h \ $$PWD/bittorrent/private/speedmonitor.h \

8
src/base/bittorrent/infohash.cpp

@ -38,7 +38,7 @@ InfoHash::InfoHash()
{ {
} }
InfoHash::InfoHash(const libtorrent::sha1_hash &nativeHash) InfoHash::InfoHash(const lt::sha1_hash &nativeHash)
: m_valid(true) : m_valid(true)
, m_nativeHash(nativeHash) , m_nativeHash(nativeHash)
{ {
@ -66,7 +66,7 @@ bool InfoHash::isValid() const
return m_valid; return m_valid;
} }
InfoHash::operator libtorrent::sha1_hash() const InfoHash::operator lt::sha1_hash() const
{ {
return m_nativeHash; return m_nativeHash;
} }
@ -78,8 +78,8 @@ InfoHash::operator QString() const
bool BitTorrent::operator==(const InfoHash &left, const InfoHash &right) bool BitTorrent::operator==(const InfoHash &left, const InfoHash &right)
{ {
return (static_cast<libtorrent::sha1_hash>(left) return (static_cast<lt::sha1_hash>(left)
== static_cast<libtorrent::sha1_hash>(right)); == static_cast<lt::sha1_hash>(right));
} }
bool BitTorrent::operator!=(const InfoHash &left, const InfoHash &right) bool BitTorrent::operator!=(const InfoHash &left, const InfoHash &right)

10
src/base/bittorrent/infohash.h

@ -40,27 +40,27 @@ namespace BitTorrent
{ {
public: public:
InfoHash(); InfoHash();
InfoHash(const libtorrent::sha1_hash &nativeHash); InfoHash(const lt::sha1_hash &nativeHash);
InfoHash(const QString &hashString); InfoHash(const QString &hashString);
InfoHash(const InfoHash &other) = default; InfoHash(const InfoHash &other) = default;
static constexpr int length() static constexpr int length()
{ {
#if (LIBTORRENT_VERSION_NUM < 10200) #if (LIBTORRENT_VERSION_NUM < 10200)
return libtorrent::sha1_hash::size; return lt::sha1_hash::size;
#else #else
return libtorrent::sha1_hash::size(); return lt::sha1_hash::size();
#endif #endif
} }
bool isValid() const; bool isValid() const;
operator libtorrent::sha1_hash() const; operator lt::sha1_hash() const;
operator QString() const; operator QString() const;
private: private:
bool m_valid; bool m_valid;
libtorrent::sha1_hash m_nativeHash; lt::sha1_hash m_nativeHash;
QString m_hashString; QString m_hashString;
}; };

9
src/base/bittorrent/magneturi.cpp

@ -56,7 +56,6 @@ namespace
} }
} }
namespace libt = libtorrent;
using namespace BitTorrent; using namespace BitTorrent;
MagnetUri::MagnetUri(const QString &source) MagnetUri::MagnetUri(const QString &source)
@ -68,8 +67,8 @@ MagnetUri::MagnetUri(const QString &source)
if (isBitTorrentInfoHash(source)) if (isBitTorrentInfoHash(source))
m_url = QLatin1String("magnet:?xt=urn:btih:") + source; m_url = QLatin1String("magnet:?xt=urn:btih:") + source;
libt::error_code ec; lt::error_code ec;
libt::parse_magnet_uri(m_url.toStdString(), m_addTorrentParams, ec); lt::parse_magnet_uri(m_url.toStdString(), m_addTorrentParams, ec);
if (ec) return; if (ec) return;
m_valid = true; m_valid = true;
@ -77,7 +76,7 @@ MagnetUri::MagnetUri(const QString &source)
m_name = QString::fromStdString(m_addTorrentParams.name); m_name = QString::fromStdString(m_addTorrentParams.name);
for (const std::string &tracker : m_addTorrentParams.trackers) for (const std::string &tracker : m_addTorrentParams.trackers)
m_trackers.append(libtorrent::announce_entry {tracker}); m_trackers.append(lt::announce_entry {tracker});
for (const std::string &urlSeed : m_addTorrentParams.url_seeds) for (const std::string &urlSeed : m_addTorrentParams.url_seeds)
m_urlSeeds.append(QUrl(QString::fromStdString(urlSeed))); m_urlSeeds.append(QUrl(QString::fromStdString(urlSeed)));
@ -113,7 +112,7 @@ QString MagnetUri::url() const
return m_url; return m_url;
} }
libtorrent::add_torrent_params MagnetUri::addTorrentParams() const lt::add_torrent_params MagnetUri::addTorrentParams() const
{ {
return m_addTorrentParams; return m_addTorrentParams;
} }

4
src/base/bittorrent/magneturi.h

@ -52,7 +52,7 @@ namespace BitTorrent
QList<QUrl> urlSeeds() const; QList<QUrl> urlSeeds() const;
QString url() const; QString url() const;
libtorrent::add_torrent_params addTorrentParams() const; lt::add_torrent_params addTorrentParams() const;
private: private:
bool m_valid; bool m_valid;
@ -61,7 +61,7 @@ namespace BitTorrent
QString m_name; QString m_name;
QList<TrackerEntry> m_trackers; QList<TrackerEntry> m_trackers;
QList<QUrl> m_urlSeeds; QList<QUrl> m_urlSeeds;
libtorrent::add_torrent_params m_addTorrentParams; lt::add_torrent_params m_addTorrentParams;
}; };
} }

55
src/base/bittorrent/peerinfo.cpp

@ -33,7 +33,6 @@
#include "base/unicodestrings.h" #include "base/unicodestrings.h"
#include "base/utils/string.h" #include "base/utils/string.h"
namespace libt = libtorrent;
using namespace BitTorrent; using namespace BitTorrent;
// PeerAddress // PeerAddress
@ -51,7 +50,7 @@ PeerAddress::PeerAddress(const QHostAddress &ip, ushort port)
// PeerInfo // PeerInfo
PeerInfo::PeerInfo(const TorrentHandle *torrent, const libt::peer_info &nativeInfo) PeerInfo::PeerInfo(const TorrentHandle *torrent, const lt::peer_info &nativeInfo)
: m_nativeInfo(nativeInfo) : m_nativeInfo(nativeInfo)
{ {
calcRelevance(torrent); calcRelevance(torrent);
@ -60,17 +59,17 @@ PeerInfo::PeerInfo(const TorrentHandle *torrent, const libt::peer_info &nativeIn
bool PeerInfo::fromDHT() const bool PeerInfo::fromDHT() const
{ {
return static_cast<bool>(m_nativeInfo.source & libt::peer_info::dht); return static_cast<bool>(m_nativeInfo.source & lt::peer_info::dht);
} }
bool PeerInfo::fromPeX() const bool PeerInfo::fromPeX() const
{ {
return static_cast<bool>(m_nativeInfo.source & libt::peer_info::pex); return static_cast<bool>(m_nativeInfo.source & lt::peer_info::pex);
} }
bool PeerInfo::fromLSD() const bool PeerInfo::fromLSD() const
{ {
return static_cast<bool>(m_nativeInfo.source & libt::peer_info::lsd); return static_cast<bool>(m_nativeInfo.source & lt::peer_info::lsd);
} }
#ifndef DISABLE_COUNTRIES_RESOLUTION #ifndef DISABLE_COUNTRIES_RESOLUTION
@ -82,102 +81,102 @@ QString PeerInfo::country() const
bool PeerInfo::isInteresting() const bool PeerInfo::isInteresting() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::interesting); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::interesting);
} }
bool PeerInfo::isChocked() const bool PeerInfo::isChocked() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::choked); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::choked);
} }
bool PeerInfo::isRemoteInterested() const bool PeerInfo::isRemoteInterested() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::remote_interested); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::remote_interested);
} }
bool PeerInfo::isRemoteChocked() const bool PeerInfo::isRemoteChocked() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::remote_choked); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::remote_choked);
} }
bool PeerInfo::isSupportsExtensions() const bool PeerInfo::isSupportsExtensions() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::supports_extensions); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::supports_extensions);
} }
bool PeerInfo::isLocalConnection() const bool PeerInfo::isLocalConnection() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::local_connection); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::local_connection);
} }
bool PeerInfo::isHandshake() const bool PeerInfo::isHandshake() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::handshake); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::handshake);
} }
bool PeerInfo::isConnecting() const bool PeerInfo::isConnecting() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::connecting); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::connecting);
} }
bool PeerInfo::isOnParole() const bool PeerInfo::isOnParole() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::on_parole); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::on_parole);
} }
bool PeerInfo::isSeed() const bool PeerInfo::isSeed() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::seed); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::seed);
} }
bool PeerInfo::optimisticUnchoke() const bool PeerInfo::optimisticUnchoke() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::optimistic_unchoke); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::optimistic_unchoke);
} }
bool PeerInfo::isSnubbed() const bool PeerInfo::isSnubbed() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::snubbed); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::snubbed);
} }
bool PeerInfo::isUploadOnly() const bool PeerInfo::isUploadOnly() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::upload_only); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::upload_only);
} }
bool PeerInfo::isEndgameMode() const bool PeerInfo::isEndgameMode() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::endgame_mode); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::endgame_mode);
} }
bool PeerInfo::isHolepunched() const bool PeerInfo::isHolepunched() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::holepunched); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::holepunched);
} }
bool PeerInfo::useI2PSocket() const bool PeerInfo::useI2PSocket() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::i2p_socket); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::i2p_socket);
} }
bool PeerInfo::useUTPSocket() const bool PeerInfo::useUTPSocket() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::utp_socket); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::utp_socket);
} }
bool PeerInfo::useSSLSocket() const bool PeerInfo::useSSLSocket() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::ssl_socket); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::ssl_socket);
} }
bool PeerInfo::isRC4Encrypted() const bool PeerInfo::isRC4Encrypted() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::rc4_encrypted); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::rc4_encrypted);
} }
bool PeerInfo::isPlaintextEncrypted() const bool PeerInfo::isPlaintextEncrypted() const
{ {
return static_cast<bool>(m_nativeInfo.flags & libt::peer_info::plaintext_encrypted); return static_cast<bool>(m_nativeInfo.flags & lt::peer_info::plaintext_encrypted);
} }
PeerAddress PeerInfo::address() const PeerAddress PeerInfo::address() const
@ -229,13 +228,13 @@ QBitArray PeerInfo::pieces() const
QString PeerInfo::connectionType() const QString PeerInfo::connectionType() const
{ {
if (m_nativeInfo.flags & libt::peer_info::utp_socket) if (m_nativeInfo.flags & lt::peer_info::utp_socket)
return QString::fromUtf8(C_UTP); return QString::fromUtf8(C_UTP);
QString connection; QString connection;
switch (m_nativeInfo.connection_type) { switch (m_nativeInfo.connection_type) {
case libt::peer_info::http_seed: case lt::peer_info::http_seed:
case libt::peer_info::web_seed: case lt::peer_info::web_seed:
connection = "Web"; connection = "Web";
break; break;
default: default:

4
src/base/bittorrent/peerinfo.h

@ -53,7 +53,7 @@ namespace BitTorrent
Q_DECLARE_TR_FUNCTIONS(PeerInfo) Q_DECLARE_TR_FUNCTIONS(PeerInfo)
public: public:
PeerInfo(const TorrentHandle *torrent, const libtorrent::peer_info &nativeInfo); PeerInfo(const TorrentHandle *torrent, const lt::peer_info &nativeInfo);
bool fromDHT() const; bool fromDHT() const;
bool fromPeX() const; bool fromPeX() const;
@ -105,7 +105,7 @@ namespace BitTorrent
void calcRelevance(const TorrentHandle *torrent); void calcRelevance(const TorrentHandle *torrent);
void determineFlags(); void determineFlags();
libtorrent::peer_info m_nativeInfo; lt::peer_info m_nativeInfo;
qreal m_relevance; qreal m_relevance;
QString m_flags; QString m_flags;
QString m_flagsDescription; QString m_flagsDescription;

40
src/base/bittorrent/private/filterparserthread.cpp

@ -35,8 +35,6 @@
#include "base/logger.h" #include "base/logger.h"
namespace libt = libtorrent;
namespace namespace
{ {
class IPv4Parser class IPv4Parser
@ -79,24 +77,24 @@ namespace
return false; return false;
} }
libt::address_v4::bytes_type parsed() const lt::address_v4::bytes_type parsed() const
{ {
return m_buf; return m_buf;
} }
private: private:
libt::address_v4::bytes_type m_buf; lt::address_v4::bytes_type m_buf;
}; };
bool parseIPAddress(const char *data, libt::address &address) bool parseIPAddress(const char *data, lt::address &address)
{ {
IPv4Parser parser; IPv4Parser parser;
boost::system::error_code ec; boost::system::error_code ec;
if (parser.tryParse(data)) if (parser.tryParse(data))
address = libt::address_v4(parser.parsed()); address = lt::address_v4(parser.parsed());
else else
address = libt::address_v6::from_string(data, ec); address = lt::address_v6::from_string(data, ec);
return !ec; return !ec;
} }
@ -214,7 +212,7 @@ int FilterParserThread::parseDATFilterFile()
continue; continue;
} }
libt::address startAddr; lt::address startAddr;
int newStart = trim(buffer.data(), start, delimIP - 1); int newStart = trim(buffer.data(), start, delimIP - 1);
if (!parseIPAddress(buffer.data() + newStart, startAddr)) { if (!parseIPAddress(buffer.data() + newStart, startAddr)) {
++parseErrorCount; ++parseErrorCount;
@ -223,7 +221,7 @@ int FilterParserThread::parseDATFilterFile()
continue; continue;
} }
libt::address endAddr; lt::address endAddr;
newStart = trim(buffer.data(), delimIP + 1, endOfIPRange); newStart = trim(buffer.data(), delimIP + 1, endOfIPRange);
if (!parseIPAddress(buffer.data() + newStart, endAddr)) { if (!parseIPAddress(buffer.data() + newStart, endAddr)) {
++parseErrorCount; ++parseErrorCount;
@ -244,7 +242,7 @@ int FilterParserThread::parseDATFilterFile()
// Now Add to the filter // Now Add to the filter
try { try {
m_filter.add_rule(startAddr, endAddr, libt::ip_filter::blocked); m_filter.add_rule(startAddr, endAddr, lt::ip_filter::blocked);
++ruleCount; ++ruleCount;
} }
catch (std::exception &e) { catch (std::exception &e) {
@ -353,7 +351,7 @@ int FilterParserThread::parseP2PFilterFile()
continue; continue;
} }
libt::address startAddr; lt::address startAddr;
int newStart = trim(buffer.data(), partsDelimiter + 1, delimIP - 1); int newStart = trim(buffer.data(), partsDelimiter + 1, delimIP - 1);
if (!parseIPAddress(buffer.data() + newStart, startAddr)) { if (!parseIPAddress(buffer.data() + newStart, startAddr)) {
++parseErrorCount; ++parseErrorCount;
@ -362,7 +360,7 @@ int FilterParserThread::parseP2PFilterFile()
continue; continue;
} }
libt::address endAddr; lt::address endAddr;
newStart = trim(buffer.data(), delimIP + 1, endOfLine); newStart = trim(buffer.data(), delimIP + 1, endOfLine);
if (!parseIPAddress(buffer.data() + newStart, endAddr)) { if (!parseIPAddress(buffer.data() + newStart, endAddr)) {
++parseErrorCount; ++parseErrorCount;
@ -382,7 +380,7 @@ int FilterParserThread::parseP2PFilterFile()
start = endOfLine; start = endOfLine;
try { try {
m_filter.add_rule(startAddr, endAddr, libt::ip_filter::blocked); m_filter.add_rule(startAddr, endAddr, lt::ip_filter::blocked);
++ruleCount; ++ruleCount;
} }
catch (std::exception &e) { catch (std::exception &e) {
@ -463,11 +461,11 @@ int FilterParserThread::parseP2BFilterFile()
// Network byte order to Host byte order // Network byte order to Host byte order
// asio address_v4 constructor expects it // asio address_v4 constructor expects it
// that way // that way
const libt::address_v4 first(ntohl(start)); const lt::address_v4 first(ntohl(start));
const libt::address_v4 last(ntohl(end)); const lt::address_v4 last(ntohl(end));
// Apply to bittorrent session // Apply to bittorrent session
try { try {
m_filter.add_rule(first, last, libt::ip_filter::blocked); m_filter.add_rule(first, last, lt::ip_filter::blocked);
++ruleCount; ++ruleCount;
} }
catch (std::exception &) {} catch (std::exception &) {}
@ -513,11 +511,11 @@ int FilterParserThread::parseP2BFilterFile()
// Network byte order to Host byte order // Network byte order to Host byte order
// asio address_v4 constructor expects it // asio address_v4 constructor expects it
// that way // that way
const libt::address_v4 first(ntohl(start)); const lt::address_v4 first(ntohl(start));
const libt::address_v4 last(ntohl(end)); const lt::address_v4 last(ntohl(end));
// Apply to bittorrent session // Apply to bittorrent session
try { try {
m_filter.add_rule(first, last, libt::ip_filter::blocked); m_filter.add_rule(first, last, lt::ip_filter::blocked);
++ruleCount; ++ruleCount;
} }
catch (std::exception &) {} catch (std::exception &) {}
@ -547,12 +545,12 @@ void FilterParserThread::processFilterFile(const QString &filePath)
m_abort = false; m_abort = false;
m_filePath = filePath; m_filePath = filePath;
m_filter = libt::ip_filter(); m_filter = lt::ip_filter();
// Run it // Run it
start(); start();
} }
libt::ip_filter FilterParserThread::IPfilter() lt::ip_filter FilterParserThread::IPfilter()
{ {
return m_filter; return m_filter;
} }

4
src/base/bittorrent/private/filterparserthread.h

@ -43,7 +43,7 @@ public:
FilterParserThread(QObject *parent = nullptr); FilterParserThread(QObject *parent = nullptr);
~FilterParserThread(); ~FilterParserThread();
void processFilterFile(const QString &filePath); void processFilterFile(const QString &filePath);
libtorrent::ip_filter IPfilter(); lt::ip_filter IPfilter();
signals: signals:
void IPFilterParsed(int ruleCount); void IPFilterParsed(int ruleCount);
@ -62,7 +62,7 @@ private:
bool m_abort; bool m_abort;
QString m_filePath; QString m_filePath;
libtorrent::ip_filter m_filter; lt::ip_filter m_filter;
}; };
#endif // BITTORRENT_FILTERPARSERTHREAD_H #endif // BITTORRENT_FILTERPARSERTHREAD_H

81
src/base/bittorrent/private/libtorrentfwd.h

@ -1,81 +0,0 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2019 Vladimir Golovnev <glassez@yandex.ru>
*
* 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.
*/
#pragma once
#include <libtorrent/version.hpp>
#if (LIBTORRENT_VERSION_NUM < 10200)
namespace libtorrent
{
class entry;
class session;
struct ip_filter;
struct settings_pack;
struct torrent_handle;
class alert;
struct add_torrent_alert;
struct external_ip_alert;
struct fastresume_rejected_alert;
struct file_completed_alert;
struct file_error_alert;
struct file_rename_failed_alert;
struct file_renamed_alert;
struct listen_failed_alert;
struct listen_succeeded_alert;
struct metadata_received_alert;
struct peer_ban_alert;
struct peer_blocked_alert;
struct portmap_alert;
struct portmap_error_alert;
struct save_resume_data_alert;
struct save_resume_data_failed_alert;
struct session_stats_alert;
struct state_update_alert;
struct stats_alert;
struct storage_moved_alert;
struct storage_moved_failed_alert;
struct torrent_alert;
struct torrent_checked_alert;
struct torrent_delete_failed_alert;
struct torrent_deleted_alert;
struct torrent_finished_alert;
struct torrent_paused_alert;
struct torrent_removed_alert;
struct torrent_resumed_alert;
struct tracker_error_alert;
struct tracker_reply_alert;
struct tracker_warning_alert;
struct url_seed_alert;
}
namespace lt = libtorrent;
#else
#include <libtorrent/fwd.hpp>
#endif

2
src/base/bittorrent/private/portforwarderimpl.cpp

@ -37,7 +37,7 @@
const QString KEY_ENABLED = QStringLiteral("Network/PortForwardingEnabled"); const QString KEY_ENABLED = QStringLiteral("Network/PortForwardingEnabled");
PortForwarderImpl::PortForwarderImpl(libtorrent::session *provider, QObject *parent) PortForwarderImpl::PortForwarderImpl(lt::session *provider, QObject *parent)
: Net::PortForwarder {parent} : Net::PortForwarder {parent}
, m_active {SettingsStorage::instance()->loadValue(KEY_ENABLED, true).toBool()} , m_active {SettingsStorage::instance()->loadValue(KEY_ENABLED, true).toBool()}
, m_provider {provider} , m_provider {provider}

7
src/base/bittorrent/private/portforwarderimpl.h

@ -29,10 +29,13 @@
#pragma once #pragma once
#include <vector> #include <vector>
#include <libtorrent/fwd.hpp>
#include <libtorrent/version.hpp>
#include <QHash> #include <QHash>
#include "base/net/portforwarder.h" #include "base/net/portforwarder.h"
#include "libtorrentfwd.h"
#if (LIBTORRENT_VERSION_NUM < 10200) #if (LIBTORRENT_VERSION_NUM < 10200)
using LTPortMapping = int; using LTPortMapping = int;
@ -60,6 +63,6 @@ private:
void stop(); void stop();
bool m_active; bool m_active;
libtorrent::session *m_provider; lt::session *m_provider;
QHash<quint16, std::vector<LTPortMapping>> m_mappedPorts; QHash<quint16, std::vector<LTPortMapping>> m_mappedPorts;
}; };

906
src/base/bittorrent/session.cpp

File diff suppressed because it is too large Load Diff

57
src/base/bittorrent/session.h

@ -32,6 +32,8 @@
#include <vector> #include <vector>
#include <libtorrent/fwd.hpp>
#include <QElapsedTimer> #include <QElapsedTimer>
#include <QFile> #include <QFile>
#include <QHash> #include <QHash>
@ -43,7 +45,6 @@
#include "base/settingvalue.h" #include "base/settingvalue.h"
#include "base/tristatebool.h" #include "base/tristatebool.h"
#include "base/types.h" #include "base/types.h"
#include "private/libtorrentfwd.h"
#include "addtorrentparams.h" #include "addtorrentparams.h"
#include "cachestatus.h" #include "cachestatus.h"
#include "sessionstatus.h" #include "sessionstatus.h"
@ -441,7 +442,7 @@ namespace BitTorrent
void handleTorrentTrackersChanged(TorrentHandle *const torrent); void handleTorrentTrackersChanged(TorrentHandle *const torrent);
void handleTorrentUrlSeedsAdded(TorrentHandle *const torrent, const QList<QUrl> &newUrlSeeds); void handleTorrentUrlSeedsAdded(TorrentHandle *const torrent, const QList<QUrl> &newUrlSeeds);
void handleTorrentUrlSeedsRemoved(TorrentHandle *const torrent, const QList<QUrl> &urlSeeds); void handleTorrentUrlSeedsRemoved(TorrentHandle *const torrent, const QList<QUrl> &urlSeeds);
void handleTorrentResumeDataReady(TorrentHandle *const torrent, const libtorrent::entry &data); void handleTorrentResumeDataReady(TorrentHandle *const torrent, const lt::entry &data);
void handleTorrentResumeDataFailed(TorrentHandle *const torrent); void handleTorrentResumeDataFailed(TorrentHandle *const torrent);
void handleTorrentTrackerReply(TorrentHandle *const torrent, const QString &trackerUrl); void handleTorrentTrackerReply(TorrentHandle *const torrent, const QString &trackerUrl);
void handleTorrentTrackerWarning(TorrentHandle *const torrent, const QString &trackerUrl); void handleTorrentTrackerWarning(TorrentHandle *const torrent, const QString &trackerUrl);
@ -518,14 +519,14 @@ namespace BitTorrent
// Session configuration // Session configuration
Q_INVOKABLE void configure(); Q_INVOKABLE void configure();
void configure(libtorrent::settings_pack &settingsPack); void configure(lt::settings_pack &settingsPack);
void configurePeerClasses(); void configurePeerClasses();
void adjustLimits(libtorrent::settings_pack &settingsPack); void adjustLimits(lt::settings_pack &settingsPack);
void applyBandwidthLimits(libtorrent::settings_pack &settingsPack); void applyBandwidthLimits(lt::settings_pack &settingsPack);
void initMetrics(); void initMetrics();
void adjustLimits(); void adjustLimits();
void applyBandwidthLimits(); void applyBandwidthLimits();
void processBannedIPs(libtorrent::ip_filter &filter); void processBannedIPs(lt::ip_filter &filter);
const QStringList getListeningIPs(); const QStringList getListeningIPs();
void configureListeningInterface(); void configureListeningInterface();
void enableTracker(bool enable); void enableTracker(bool enable);
@ -543,35 +544,35 @@ namespace BitTorrent
void exportTorrentFile(TorrentHandle *const torrent, TorrentExportFolder folder = TorrentExportFolder::Regular); void exportTorrentFile(TorrentHandle *const torrent, TorrentExportFolder folder = TorrentExportFolder::Regular);
void saveTorrentResumeData(TorrentHandle *const torrent); void saveTorrentResumeData(TorrentHandle *const torrent);
void handleAlert(const libtorrent::alert *a); void handleAlert(const lt::alert *a);
void dispatchTorrentAlert(const libtorrent::alert *a); void dispatchTorrentAlert(const lt::alert *a);
void handleAddTorrentAlert(const libtorrent::add_torrent_alert *p); void handleAddTorrentAlert(const lt::add_torrent_alert *p);
void handleStateUpdateAlert(const libtorrent::state_update_alert *p); void handleStateUpdateAlert(const lt::state_update_alert *p);
void handleMetadataReceivedAlert(const libtorrent::metadata_received_alert *p); void handleMetadataReceivedAlert(const lt::metadata_received_alert *p);
void handleFileErrorAlert(const libtorrent::file_error_alert *p); void handleFileErrorAlert(const lt::file_error_alert *p);
void handleTorrentRemovedAlert(const libtorrent::torrent_removed_alert *p); void handleTorrentRemovedAlert(const lt::torrent_removed_alert *p);
void handleTorrentDeletedAlert(const libtorrent::torrent_deleted_alert *p); void handleTorrentDeletedAlert(const lt::torrent_deleted_alert *p);
void handleTorrentDeleteFailedAlert(const libtorrent::torrent_delete_failed_alert *p); void handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_alert *p);
void handlePortmapWarningAlert(const libtorrent::portmap_error_alert *p); void handlePortmapWarningAlert(const lt::portmap_error_alert *p);
void handlePortmapAlert(const libtorrent::portmap_alert *p); void handlePortmapAlert(const lt::portmap_alert *p);
void handlePeerBlockedAlert(const libtorrent::peer_blocked_alert *p); void handlePeerBlockedAlert(const lt::peer_blocked_alert *p);
void handlePeerBanAlert(const libtorrent::peer_ban_alert *p); void handlePeerBanAlert(const lt::peer_ban_alert *p);
void handleUrlSeedAlert(const libtorrent::url_seed_alert *p); void handleUrlSeedAlert(const lt::url_seed_alert *p);
void handleListenSucceededAlert(const libtorrent::listen_succeeded_alert *p); void handleListenSucceededAlert(const lt::listen_succeeded_alert *p);
void handleListenFailedAlert(const libtorrent::listen_failed_alert *p); void handleListenFailedAlert(const lt::listen_failed_alert *p);
void handleExternalIPAlert(const libtorrent::external_ip_alert *p); void handleExternalIPAlert(const lt::external_ip_alert *p);
void handleSessionStatsAlert(const libtorrent::session_stats_alert *p); void handleSessionStatsAlert(const lt::session_stats_alert *p);
void createTorrentHandle(const libtorrent::torrent_handle &nativeHandle); void createTorrentHandle(const lt::torrent_handle &nativeHandle);
void saveResumeData(); void saveResumeData();
void saveTorrentsQueue(); void saveTorrentsQueue();
void removeTorrentsQueue(); void removeTorrentsQueue();
void getPendingAlerts(std::vector<libtorrent::alert *> &out, ulong time = 0); void getPendingAlerts(std::vector<lt::alert *> &out, ulong time = 0);
// BitTorrent // BitTorrent
libtorrent::session *m_nativeSession; lt::session *m_nativeSession;
bool m_deferredConfigureScheduled; bool m_deferredConfigureScheduled;
bool m_IPFilteringChanged; bool m_IPFilteringChanged;

23
src/base/bittorrent/torrentcreatorthread.cpp

@ -62,7 +62,6 @@ namespace
} }
} }
namespace libt = libtorrent;
using namespace BitTorrent; using namespace BitTorrent;
TorrentCreatorThread::TorrentCreatorThread(QObject *parent) TorrentCreatorThread::TorrentCreatorThread(QObject *parent)
@ -97,9 +96,9 @@ void TorrentCreatorThread::run()
const QString parentPath = Utils::Fs::branchPath(m_params.inputPath) + '/'; const QString parentPath = Utils::Fs::branchPath(m_params.inputPath) + '/';
// Adding files to the torrent // Adding files to the torrent
libt::file_storage fs; lt::file_storage fs;
if (QFileInfo(m_params.inputPath).isFile()) { if (QFileInfo(m_params.inputPath).isFile()) {
libt::add_files(fs, Utils::Fs::toNativePath(m_params.inputPath).toStdString(), fileFilter); lt::add_files(fs, Utils::Fs::toNativePath(m_params.inputPath).toStdString(), fileFilter);
} }
else { else {
// need to sort the file names by natural sort order // need to sort the file names by natural sort order
@ -137,8 +136,8 @@ void TorrentCreatorThread::run()
if (isInterruptionRequested()) return; if (isInterruptionRequested()) return;
libt::create_torrent newTorrent(fs, m_params.pieceSize, -1 lt::create_torrent newTorrent(fs, m_params.pieceSize, -1
, (m_params.isAlignmentOptimized ? libt::create_torrent::optimize_alignment : CreateFlags {})); , (m_params.isAlignmentOptimized ? lt::create_torrent::optimize_alignment : CreateFlags {}));
// Add url seeds // Add url seeds
for (QString seed : asConst(m_params.urlSeeds)) { for (QString seed : asConst(m_params.urlSeeds)) {
@ -158,7 +157,7 @@ void TorrentCreatorThread::run()
if (isInterruptionRequested()) return; if (isInterruptionRequested()) return;
// calculate the hash for all pieces // calculate the hash for all pieces
libt::set_piece_hashes(newTorrent, Utils::Fs::toNativePath(parentPath).toStdString() lt::set_piece_hashes(newTorrent, Utils::Fs::toNativePath(parentPath).toStdString()
, [this, &newTorrent](const int n) { sendProgressSignal(n, newTorrent.num_pieces()); }); , [this, &newTorrent](const int n) { sendProgressSignal(n, newTorrent.num_pieces()); });
// Set qBittorrent as creator and add user comment to // Set qBittorrent as creator and add user comment to
// torrent_info structure // torrent_info structure
@ -169,7 +168,7 @@ void TorrentCreatorThread::run()
if (isInterruptionRequested()) return; if (isInterruptionRequested()) return;
libt::entry entry = newTorrent.generate(); lt::entry entry = newTorrent.generate();
// add source field // add source field
if (!m_params.source.isEmpty()) if (!m_params.source.isEmpty())
@ -190,7 +189,7 @@ void TorrentCreatorThread::run()
if (isInterruptionRequested()) return; if (isInterruptionRequested()) return;
libt::bencode(std::ostream_iterator<char>(outfile), entry); lt::bencode(std::ostream_iterator<char>(outfile), entry);
outfile.close(); outfile.close();
emit updateProgress(100); emit updateProgress(100);
@ -206,9 +205,9 @@ int TorrentCreatorThread::calculateTotalPieces(const QString &inputPath, const i
if (inputPath.isEmpty()) if (inputPath.isEmpty())
return 0; return 0;
libt::file_storage fs; lt::file_storage fs;
libt::add_files(fs, Utils::Fs::toNativePath(inputPath).toStdString(), fileFilter); lt::add_files(fs, Utils::Fs::toNativePath(inputPath).toStdString(), fileFilter);
return libt::create_torrent(fs, pieceSize, -1 return lt::create_torrent(fs, pieceSize, -1
, (isAlignmentOptimized ? libt::create_torrent::optimize_alignment : CreateFlags {})).num_pieces(); , (isAlignmentOptimized ? lt::create_torrent::optimize_alignment : CreateFlags {})).num_pieces();
} }

44
src/base/bittorrent/torrenthandle.cpp

@ -165,7 +165,7 @@ const int TorrentHandle::NO_SEEDING_TIME_LIMIT = -1;
const qreal TorrentHandle::MAX_RATIO = 9999.; const qreal TorrentHandle::MAX_RATIO = 9999.;
const int TorrentHandle::MAX_SEEDING_TIME = 525600; const int TorrentHandle::MAX_SEEDING_TIME = 525600;
TorrentHandle::TorrentHandle(Session *session, const libtorrent::torrent_handle &nativeHandle, TorrentHandle::TorrentHandle(Session *session, const lt::torrent_handle &nativeHandle,
const CreateTorrentParams &params) const CreateTorrentParams &params)
: QObject(session) : QObject(session)
, m_session(session) , m_session(session)
@ -1509,7 +1509,7 @@ void TorrentHandle::handleStateUpdate(const lt::torrent_status &nativeStatus)
updateStatus(nativeStatus); updateStatus(nativeStatus);
} }
void TorrentHandle::handleStorageMovedAlert(const libtorrent::storage_moved_alert *p) void TorrentHandle::handleStorageMovedAlert(const lt::storage_moved_alert *p)
{ {
if (!isMoveInProgress()) { if (!isMoveInProgress()) {
qWarning() << "Unexpected " << Q_FUNC_INFO << " call."; qWarning() << "Unexpected " << Q_FUNC_INFO << " call.";
@ -1550,7 +1550,7 @@ void TorrentHandle::handleStorageMovedAlert(const libtorrent::storage_moved_aler
m_moveFinishedTriggers.takeFirst()(); m_moveFinishedTriggers.takeFirst()();
} }
void TorrentHandle::handleStorageMovedFailedAlert(const libtorrent::storage_moved_failed_alert *p) void TorrentHandle::handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert *p)
{ {
if (!isMoveInProgress()) { if (!isMoveInProgress()) {
qWarning() << "Unexpected " << Q_FUNC_INFO << " call."; qWarning() << "Unexpected " << Q_FUNC_INFO << " call.";
@ -1572,7 +1572,7 @@ void TorrentHandle::handleStorageMovedFailedAlert(const libtorrent::storage_move
m_moveFinishedTriggers.takeFirst()(); m_moveFinishedTriggers.takeFirst()();
} }
void TorrentHandle::handleTrackerReplyAlert(const libtorrent::tracker_reply_alert *p) void TorrentHandle::handleTrackerReplyAlert(const lt::tracker_reply_alert *p)
{ {
const QString trackerUrl(p->tracker_url()); const QString trackerUrl(p->tracker_url());
qDebug("Received a tracker reply from %s (Num_peers = %d)", qUtf8Printable(trackerUrl), p->num_peers); qDebug("Received a tracker reply from %s (Num_peers = %d)", qUtf8Printable(trackerUrl), p->num_peers);
@ -1583,7 +1583,7 @@ void TorrentHandle::handleTrackerReplyAlert(const libtorrent::tracker_reply_aler
m_session->handleTorrentTrackerReply(this, trackerUrl); m_session->handleTorrentTrackerReply(this, trackerUrl);
} }
void TorrentHandle::handleTrackerWarningAlert(const libtorrent::tracker_warning_alert *p) void TorrentHandle::handleTrackerWarningAlert(const lt::tracker_warning_alert *p)
{ {
const QString trackerUrl = p->tracker_url(); const QString trackerUrl = p->tracker_url();
const QString message = p->warning_message(); const QString message = p->warning_message();
@ -1594,7 +1594,7 @@ void TorrentHandle::handleTrackerWarningAlert(const libtorrent::tracker_warning_
m_session->handleTorrentTrackerWarning(this, trackerUrl); m_session->handleTorrentTrackerWarning(this, trackerUrl);
} }
void TorrentHandle::handleTrackerErrorAlert(const libtorrent::tracker_error_alert *p) void TorrentHandle::handleTrackerErrorAlert(const lt::tracker_error_alert *p)
{ {
const QString trackerUrl = p->tracker_url(); const QString trackerUrl = p->tracker_url();
const QString message = p->error_message(); const QString message = p->error_message();
@ -1604,7 +1604,7 @@ void TorrentHandle::handleTrackerErrorAlert(const libtorrent::tracker_error_aler
m_session->handleTorrentTrackerError(this, trackerUrl); m_session->handleTorrentTrackerError(this, trackerUrl);
} }
void TorrentHandle::handleTorrentCheckedAlert(const libtorrent::torrent_checked_alert *p) void TorrentHandle::handleTorrentCheckedAlert(const lt::torrent_checked_alert *p)
{ {
Q_UNUSED(p); Q_UNUSED(p);
qDebug("\"%s\" have just finished checking", qUtf8Printable(name())); qDebug("\"%s\" have just finished checking", qUtf8Printable(name()));
@ -1638,7 +1638,7 @@ void TorrentHandle::handleTorrentCheckedAlert(const libtorrent::torrent_checked_
m_session->handleTorrentChecked(this); m_session->handleTorrentChecked(this);
} }
void TorrentHandle::handleTorrentFinishedAlert(const libtorrent::torrent_finished_alert *p) void TorrentHandle::handleTorrentFinishedAlert(const lt::torrent_finished_alert *p)
{ {
Q_UNUSED(p); Q_UNUSED(p);
qDebug("Got a torrent finished alert for \"%s\"", qUtf8Printable(name())); qDebug("Got a torrent finished alert for \"%s\"", qUtf8Printable(name()));
@ -1665,7 +1665,7 @@ void TorrentHandle::handleTorrentFinishedAlert(const libtorrent::torrent_finishe
} }
} }
void TorrentHandle::handleTorrentPausedAlert(const libtorrent::torrent_paused_alert *p) void TorrentHandle::handleTorrentPausedAlert(const lt::torrent_paused_alert *p)
{ {
Q_UNUSED(p); Q_UNUSED(p);
@ -1676,7 +1676,7 @@ void TorrentHandle::handleTorrentPausedAlert(const libtorrent::torrent_paused_al
} }
} }
void TorrentHandle::handleTorrentResumedAlert(const libtorrent::torrent_resumed_alert *p) void TorrentHandle::handleTorrentResumedAlert(const lt::torrent_resumed_alert *p)
{ {
Q_UNUSED(p); Q_UNUSED(p);
@ -1686,12 +1686,12 @@ void TorrentHandle::handleTorrentResumedAlert(const libtorrent::torrent_resumed_
m_startupState = Started; m_startupState = Started;
} }
void TorrentHandle::handleSaveResumeDataAlert(const libtorrent::save_resume_data_alert *p) void TorrentHandle::handleSaveResumeDataAlert(const lt::save_resume_data_alert *p)
{ {
const bool useDummyResumeData = !(p && p->resume_data); const bool useDummyResumeData = !(p && p->resume_data);
libtorrent::entry dummyEntry; lt::entry dummyEntry;
libtorrent::entry &resumeData = useDummyResumeData ? dummyEntry : *(p->resume_data); lt::entry &resumeData = useDummyResumeData ? dummyEntry : *(p->resume_data);
if (useDummyResumeData) { if (useDummyResumeData) {
resumeData["qBt-magnetUri"] = toMagnetUri().toStdString(); resumeData["qBt-magnetUri"] = toMagnetUri().toStdString();
resumeData["qBt-paused"] = isPaused(); resumeData["qBt-paused"] = isPaused();
@ -1720,7 +1720,7 @@ void TorrentHandle::handleSaveResumeDataAlert(const libtorrent::save_resume_data
m_session->handleTorrentResumeDataReady(this, resumeData); m_session->handleTorrentResumeDataReady(this, resumeData);
} }
void TorrentHandle::handleSaveResumeDataFailedAlert(const libtorrent::save_resume_data_failed_alert *p) void TorrentHandle::handleSaveResumeDataFailedAlert(const lt::save_resume_data_failed_alert *p)
{ {
// if torrent has no metadata we should save dummy fastresume data // if torrent has no metadata we should save dummy fastresume data
// containing Magnet URI and qBittorrent own resume data only // containing Magnet URI and qBittorrent own resume data only
@ -1730,7 +1730,7 @@ void TorrentHandle::handleSaveResumeDataFailedAlert(const libtorrent::save_resum
m_session->handleTorrentResumeDataFailed(this); m_session->handleTorrentResumeDataFailed(this);
} }
void TorrentHandle::handleFastResumeRejectedAlert(const libtorrent::fastresume_rejected_alert *p) void TorrentHandle::handleFastResumeRejectedAlert(const lt::fastresume_rejected_alert *p)
{ {
if (p->error.value() == lt::errors::mismatching_file_size) { if (p->error.value() == lt::errors::mismatching_file_size) {
// Mismatching file size (files were probably moved) // Mismatching file size (files were probably moved)
@ -1743,7 +1743,7 @@ void TorrentHandle::handleFastResumeRejectedAlert(const libtorrent::fastresume_r
} }
} }
void TorrentHandle::handleFileRenamedAlert(const libtorrent::file_renamed_alert *p) void TorrentHandle::handleFileRenamedAlert(const lt::file_renamed_alert *p)
{ {
const QString newName = Utils::Fs::fromNativePath(p->new_name()); const QString newName = Utils::Fs::fromNativePath(p->new_name());
@ -1773,7 +1773,7 @@ void TorrentHandle::handleFileRenamedAlert(const libtorrent::file_renamed_alert
m_moveFinishedTriggers.takeFirst()(); m_moveFinishedTriggers.takeFirst()();
} }
void TorrentHandle::handleFileRenameFailedAlert(const libtorrent::file_rename_failed_alert *p) void TorrentHandle::handleFileRenameFailedAlert(const lt::file_rename_failed_alert *p)
{ {
Q_UNUSED(p); Q_UNUSED(p);
@ -1782,7 +1782,7 @@ void TorrentHandle::handleFileRenameFailedAlert(const libtorrent::file_rename_fa
m_moveFinishedTriggers.takeFirst()(); m_moveFinishedTriggers.takeFirst()();
} }
void TorrentHandle::handleFileCompletedAlert(const libtorrent::file_completed_alert *p) void TorrentHandle::handleFileCompletedAlert(const lt::file_completed_alert *p)
{ {
// We don't really need to call updateStatus() in this place. // We don't really need to call updateStatus() in this place.
// All we need to do is make sure we have a valid instance of the TorrentInfo object. // All we need to do is make sure we have a valid instance of the TorrentInfo object.
@ -1800,7 +1800,7 @@ void TorrentHandle::handleFileCompletedAlert(const libtorrent::file_completed_al
} }
} }
void TorrentHandle::handleStatsAlert(const libtorrent::stats_alert *p) void TorrentHandle::handleStatsAlert(const lt::stats_alert *p)
{ {
Q_ASSERT(p->interval >= 1000); Q_ASSERT(p->interval >= 1000);
const SpeedSample transferred(p->transferred[lt::stats_alert::download_payload] * 1000LL / p->interval, const SpeedSample transferred(p->transferred[lt::stats_alert::download_payload] * 1000LL / p->interval,
@ -1854,7 +1854,7 @@ void TorrentHandle::handleAppendExtensionToggled()
manageIncompleteFiles(); manageIncompleteFiles();
} }
void TorrentHandle::handleAlert(const libtorrent::alert *a) void TorrentHandle::handleAlert(const lt::alert *a)
{ {
switch (a->type()) { switch (a->type()) {
case lt::stats_alert::alert_type: case lt::stats_alert::alert_type:
@ -1965,7 +1965,7 @@ void TorrentHandle::adjustActualSavePath_impl()
moveStorage(Utils::Fs::toNativePath(path), true); moveStorage(Utils::Fs::toNativePath(path), true);
} }
libtorrent::torrent_handle TorrentHandle::nativeHandle() const lt::torrent_handle TorrentHandle::nativeHandle() const
{ {
return m_nativeHandle; return m_nativeHandle;
} }
@ -1992,7 +1992,7 @@ void TorrentHandle::updateStatus()
updateStatus(m_nativeHandle.status()); updateStatus(m_nativeHandle.status());
} }
void TorrentHandle::updateStatus(const libtorrent::torrent_status &nativeStatus) void TorrentHandle::updateStatus(const lt::torrent_status &nativeStatus)
{ {
m_nativeStatus = nativeStatus; m_nativeStatus = nativeStatus;

50
src/base/bittorrent/torrenthandle.h

@ -32,6 +32,7 @@
#include <functional> #include <functional>
#include <libtorrent/fwd.hpp>
#include <libtorrent/torrent_handle.hpp> #include <libtorrent/torrent_handle.hpp>
#include <libtorrent/torrent_status.hpp> #include <libtorrent/torrent_status.hpp>
@ -42,7 +43,6 @@
#include <QString> #include <QString>
#include <QVector> #include <QVector>
#include "private/libtorrentfwd.h"
#include "private/speedmonitor.h" #include "private/speedmonitor.h"
#include "downloadpriority.h" #include "downloadpriority.h"
#include "infohash.h" #include "infohash.h"
@ -142,7 +142,7 @@ namespace BitTorrent
static const qreal MAX_RATIO; static const qreal MAX_RATIO;
static const int MAX_SEEDING_TIME; static const int MAX_SEEDING_TIME;
TorrentHandle(Session *session, const libtorrent::torrent_handle &nativeHandle, TorrentHandle(Session *session, const lt::torrent_handle &nativeHandle,
const CreateTorrentParams &params); const CreateTorrentParams &params);
~TorrentHandle(); ~TorrentHandle();
@ -334,10 +334,10 @@ namespace BitTorrent
bool needSaveResumeData() const; bool needSaveResumeData() const;
// Session interface // Session interface
libtorrent::torrent_handle nativeHandle() const; lt::torrent_handle nativeHandle() const;
void handleAlert(const libtorrent::alert *a); void handleAlert(const lt::alert *a);
void handleStateUpdate(const libtorrent::torrent_status &nativeStatus); void handleStateUpdate(const lt::torrent_status &nativeStatus);
void handleTempPathChanged(); void handleTempPathChanged();
void handleCategorySavePathChanged(); void handleCategorySavePathChanged();
void handleAppendExtensionToggled(); void handleAppendExtensionToggled();
@ -355,27 +355,27 @@ namespace BitTorrent
typedef std::function<void ()> EventTrigger; typedef std::function<void ()> EventTrigger;
void updateStatus(); void updateStatus();
void updateStatus(const libtorrent::torrent_status &nativeStatus); void updateStatus(const lt::torrent_status &nativeStatus);
void updateState(); void updateState();
void updateTorrentInfo(); void updateTorrentInfo();
void handleStorageMovedAlert(const libtorrent::storage_moved_alert *p); void handleStorageMovedAlert(const lt::storage_moved_alert *p);
void handleStorageMovedFailedAlert(const libtorrent::storage_moved_failed_alert *p); void handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert *p);
void handleTrackerReplyAlert(const libtorrent::tracker_reply_alert *p); void handleTrackerReplyAlert(const lt::tracker_reply_alert *p);
void handleTrackerWarningAlert(const libtorrent::tracker_warning_alert *p); void handleTrackerWarningAlert(const lt::tracker_warning_alert *p);
void handleTrackerErrorAlert(const libtorrent::tracker_error_alert *p); void handleTrackerErrorAlert(const lt::tracker_error_alert *p);
void handleTorrentCheckedAlert(const libtorrent::torrent_checked_alert *p); void handleTorrentCheckedAlert(const lt::torrent_checked_alert *p);
void handleTorrentFinishedAlert(const libtorrent::torrent_finished_alert *p); void handleTorrentFinishedAlert(const lt::torrent_finished_alert *p);
void handleTorrentPausedAlert(const libtorrent::torrent_paused_alert *p); void handleTorrentPausedAlert(const lt::torrent_paused_alert *p);
void handleTorrentResumedAlert(const libtorrent::torrent_resumed_alert *p); void handleTorrentResumedAlert(const lt::torrent_resumed_alert *p);
void handleSaveResumeDataAlert(const libtorrent::save_resume_data_alert *p); void handleSaveResumeDataAlert(const lt::save_resume_data_alert *p);
void handleSaveResumeDataFailedAlert(const libtorrent::save_resume_data_failed_alert *p); void handleSaveResumeDataFailedAlert(const lt::save_resume_data_failed_alert *p);
void handleFastResumeRejectedAlert(const libtorrent::fastresume_rejected_alert *p); void handleFastResumeRejectedAlert(const lt::fastresume_rejected_alert *p);
void handleFileRenamedAlert(const libtorrent::file_renamed_alert *p); void handleFileRenamedAlert(const lt::file_renamed_alert *p);
void handleFileRenameFailedAlert(const libtorrent::file_rename_failed_alert *p); void handleFileRenameFailedAlert(const lt::file_rename_failed_alert *p);
void handleFileCompletedAlert(const libtorrent::file_completed_alert *p); void handleFileCompletedAlert(const lt::file_completed_alert *p);
void handleMetadataReceivedAlert(const libtorrent::metadata_received_alert *p); void handleMetadataReceivedAlert(const lt::metadata_received_alert *p);
void handleStatsAlert(const libtorrent::stats_alert *p); void handleStatsAlert(const lt::stats_alert *p);
void resume_impl(bool forced); void resume_impl(bool forced);
bool isMoveInProgress() const; bool isMoveInProgress() const;
@ -394,8 +394,8 @@ namespace BitTorrent
void setFirstLastPiecePriorityImpl(bool enabled, const QVector<DownloadPriority> &updatedFilePrio = {}); void setFirstLastPiecePriorityImpl(bool enabled, const QVector<DownloadPriority> &updatedFilePrio = {});
Session *const m_session; Session *const m_session;
libtorrent::torrent_handle m_nativeHandle; lt::torrent_handle m_nativeHandle;
libtorrent::torrent_status m_nativeStatus; lt::torrent_status m_nativeStatus;
TorrentState m_state; TorrentState m_state;
TorrentInfo m_torrentInfo; TorrentInfo m_torrentInfo;
SpeedMonitor m_speedMonitor; SpeedMonitor m_speedMonitor;

25
src/base/bittorrent/torrentinfo.cpp

@ -59,15 +59,14 @@ namespace
#endif #endif
} }
namespace libt = libtorrent;
using namespace BitTorrent; using namespace BitTorrent;
TorrentInfo::TorrentInfo(NativeConstPtr nativeInfo) TorrentInfo::TorrentInfo(NativeConstPtr nativeInfo)
{ {
#if (LIBTORRENT_VERSION_NUM < 10200) #if (LIBTORRENT_VERSION_NUM < 10200)
m_nativeInfo = boost::const_pointer_cast<libt::torrent_info>(nativeInfo); m_nativeInfo = boost::const_pointer_cast<lt::torrent_info>(nativeInfo);
#else #else
m_nativeInfo = std::const_pointer_cast<libt::torrent_info>(nativeInfo); m_nativeInfo = std::const_pointer_cast<lt::torrent_info>(nativeInfo);
#endif #endif
} }
@ -88,9 +87,9 @@ TorrentInfo TorrentInfo::load(const QByteArray &data, QString *error) noexcept
// used in `torrent_info()` constructor // used in `torrent_info()` constructor
const int depthLimit = 100; const int depthLimit = 100;
const int tokenLimit = 10000000; const int tokenLimit = 10000000;
libt::error_code ec; lt::error_code ec;
libt::bdecode_node node; lt::bdecode_node node;
bdecode(data.constData(), (data.constData() + data.size()), node, ec bdecode(data.constData(), (data.constData() + data.size()), node, ec
, nullptr, depthLimit, tokenLimit); , nullptr, depthLimit, tokenLimit);
if (ec) { if (ec) {
@ -99,7 +98,7 @@ TorrentInfo TorrentInfo::load(const QByteArray &data, QString *error) noexcept
return TorrentInfo(); return TorrentInfo();
} }
TorrentInfo info {NativePtr(new libt::torrent_info(node, ec))}; TorrentInfo info {NativePtr(new lt::torrent_info(node, ec))};
if (ec) { if (ec) {
if (error) if (error)
*error = QString::fromStdString(ec.message()); *error = QString::fromStdString(ec.message());
@ -270,7 +269,7 @@ QList<TrackerEntry> TorrentInfo::trackers() const
if (!isValid()) return {}; if (!isValid()) return {};
QList<TrackerEntry> trackers; QList<TrackerEntry> trackers;
for (const libt::announce_entry &tracker : m_nativeInfo->trackers()) for (const lt::announce_entry &tracker : m_nativeInfo->trackers())
trackers.append(tracker); trackers.append(tracker);
return trackers; return trackers;
@ -281,8 +280,8 @@ QList<QUrl> TorrentInfo::urlSeeds() const
if (!isValid()) return {}; if (!isValid()) return {};
QList<QUrl> urlSeeds; QList<QUrl> urlSeeds;
for (const libt::web_seed_entry &webSeed : m_nativeInfo->web_seeds()) for (const lt::web_seed_entry &webSeed : m_nativeInfo->web_seeds())
if (webSeed.type == libt::web_seed_entry::url_seed) if (webSeed.type == lt::web_seed_entry::url_seed)
urlSeeds.append(QUrl(webSeed.url.c_str())); urlSeeds.append(QUrl(webSeed.url.c_str()));
return urlSeeds; return urlSeeds;
@ -312,13 +311,13 @@ QVector<int> TorrentInfo::fileIndicesForPiece(const int pieceIndex) const
if (!isValid() || (pieceIndex < 0) || (pieceIndex >= piecesCount())) if (!isValid() || (pieceIndex < 0) || (pieceIndex >= piecesCount()))
return {}; return {};
const std::vector<libt::file_slice> files( const std::vector<lt::file_slice> files(
nativeInfo()->map_block(LTPieceIndex {pieceIndex}, 0 nativeInfo()->map_block(LTPieceIndex {pieceIndex}, 0
, nativeInfo()->piece_size(LTPieceIndex {pieceIndex}))); , nativeInfo()->piece_size(LTPieceIndex {pieceIndex})));
QVector<int> res; QVector<int> res;
res.reserve(int(files.size())); res.reserve(int(files.size()));
std::transform(files.begin(), files.end(), std::back_inserter(res), std::transform(files.begin(), files.end(), std::back_inserter(res),
[](const libt::file_slice &s) { return static_cast<int>(s.file_index); }); [](const lt::file_slice &s) { return static_cast<int>(s.file_index); });
return res; return res;
} }
@ -361,7 +360,7 @@ TorrentInfo::PieceRange TorrentInfo::filePieces(const int fileIndex) const
return {}; return {};
} }
const libt::file_storage &files = nativeInfo()->files(); const lt::file_storage &files = nativeInfo()->files();
const auto fileSize = files.file_size(LTFileIndex {fileIndex}); const auto fileSize = files.file_size(LTFileIndex {fileIndex});
const auto fileOffset = files.file_offset(LTFileIndex {fileIndex}); const auto fileOffset = files.file_offset(LTFileIndex {fileIndex});
return makeInterval(static_cast<int>(fileOffset / pieceLength()), return makeInterval(static_cast<int>(fileOffset / pieceLength()),
@ -414,7 +413,7 @@ void TorrentInfo::stripRootFolder()
{ {
if (!hasRootFolder()) return; if (!hasRootFolder()) return;
libtorrent::file_storage files = m_nativeInfo->files(); lt::file_storage files = m_nativeInfo->files();
// Solution for case of renamed root folder // Solution for case of renamed root folder
const std::string testName = filePath(0).split('/').value(0).toStdString(); const std::string testName = filePath(0).split('/').value(0).toStdString();

10
src/base/bittorrent/torrentinfo.h

@ -29,6 +29,7 @@
#ifndef BITTORRENT_TORRENTINFO_H #ifndef BITTORRENT_TORRENTINFO_H
#define BITTORRENT_TORRENTINFO_H #define BITTORRENT_TORRENTINFO_H
#include <libtorrent/fwd.hpp>
#include <libtorrent/torrent_info.hpp> #include <libtorrent/torrent_info.hpp>
#include <libtorrent/version.hpp> #include <libtorrent/version.hpp>
@ -37,7 +38,6 @@
#include <QVector> #include <QVector>
#include "base/indexrange.h" #include "base/indexrange.h"
#include "private/libtorrentfwd.h"
class QByteArray; class QByteArray;
class QDateTime; class QDateTime;
@ -56,11 +56,11 @@ namespace BitTorrent
public: public:
#if (LIBTORRENT_VERSION_NUM < 10200) #if (LIBTORRENT_VERSION_NUM < 10200)
using NativeConstPtr = boost::shared_ptr<const libtorrent::torrent_info>; using NativeConstPtr = boost::shared_ptr<const lt::torrent_info>;
using NativePtr = boost::shared_ptr<libtorrent::torrent_info>; using NativePtr = boost::shared_ptr<lt::torrent_info>;
#else #else
using NativeConstPtr = std::shared_ptr<const libtorrent::torrent_info>; using NativeConstPtr = std::shared_ptr<const lt::torrent_info>;
using NativePtr = std::shared_ptr<libtorrent::torrent_info>; using NativePtr = std::shared_ptr<lt::torrent_info>;
#endif #endif
explicit TorrentInfo(NativeConstPtr nativeInfo = {}); explicit TorrentInfo(NativeConstPtr nativeInfo = {});

24
src/base/bittorrent/tracker.cpp

@ -58,15 +58,15 @@ QString Peer::uid() const
return ip.toString() + ':' + QString::number(port); return ip.toString() + ':' + QString::number(port);
} }
libtorrent::entry Peer::toEntry(const bool noPeerId) const lt::entry Peer::toEntry(const bool noPeerId) const
{ {
libtorrent::entry::dictionary_type peerMap; lt::entry::dictionary_type peerMap;
if (!noPeerId) if (!noPeerId)
peerMap["id"] = libtorrent::entry(peerId.toStdString()); peerMap["id"] = lt::entry(peerId.toStdString());
peerMap["ip"] = libtorrent::entry(ip.toString().toStdString()); peerMap["ip"] = lt::entry(ip.toString().toStdString());
peerMap["port"] = libtorrent::entry(port); peerMap["port"] = lt::entry(port);
return libtorrent::entry(peerMap); return lt::entry(peerMap);
} }
// Tracker // Tracker
@ -247,18 +247,18 @@ void Tracker::unregisterPeer(const TrackerAnnounceRequest &announceReq)
void Tracker::replyWithPeerList(const TrackerAnnounceRequest &announceReq) void Tracker::replyWithPeerList(const TrackerAnnounceRequest &announceReq)
{ {
// Prepare the entry for bencoding // Prepare the entry for bencoding
libtorrent::entry::dictionary_type replyDict; lt::entry::dictionary_type replyDict;
replyDict["interval"] = libtorrent::entry(ANNOUNCE_INTERVAL); replyDict["interval"] = lt::entry(ANNOUNCE_INTERVAL);
libtorrent::entry::list_type peerList; lt::entry::list_type peerList;
for (const Peer &p : m_torrents.value(announceReq.infoHash)) for (const Peer &p : m_torrents.value(announceReq.infoHash))
peerList.push_back(p.toEntry(announceReq.noPeerId)); peerList.push_back(p.toEntry(announceReq.noPeerId));
replyDict["peers"] = libtorrent::entry(peerList); replyDict["peers"] = lt::entry(peerList);
const libtorrent::entry replyEntry(replyDict); const lt::entry replyEntry(replyDict);
// bencode // bencode
QByteArray reply; QByteArray reply;
libtorrent::bencode(std::back_inserter(reply), replyEntry); lt::bencode(std::back_inserter(reply), replyEntry);
qDebug("Tracker: reply with the following bencoded data:\n %s", reply.constData()); qDebug("Tracker: reply with the following bencoded data:\n %s", reply.constData());
// HTTP reply // HTTP reply

9
src/base/bittorrent/tracker.h

@ -30,6 +30,8 @@
#ifndef BITTORRENT_TRACKER_H #ifndef BITTORRENT_TRACKER_H
#define BITTORRENT_TRACKER_H #define BITTORRENT_TRACKER_H
#include <libtorrent/fwd.hpp>
#include <QHash> #include <QHash>
#include <QObject> #include <QObject>
#include <QHostAddress> #include <QHostAddress>
@ -37,11 +39,6 @@
#include "base/http/irequesthandler.h" #include "base/http/irequesthandler.h"
#include "base/http/responsebuilder.h" #include "base/http/responsebuilder.h"
namespace libtorrent
{
class entry;
}
namespace Http namespace Http
{ {
class Server; class Server;
@ -58,7 +55,7 @@ namespace BitTorrent
bool operator!=(const Peer &other) const; bool operator!=(const Peer &other) const;
bool operator==(const Peer &other) const; bool operator==(const Peer &other) const;
QString uid() const; QString uid() const;
libtorrent::entry toEntry(bool noPeerId) const; lt::entry toEntry(bool noPeerId) const;
}; };
struct TrackerAnnounceRequest struct TrackerAnnounceRequest

6
src/base/bittorrent/trackerentry.cpp

@ -42,7 +42,7 @@ TrackerEntry::TrackerEntry(const QString &url)
{ {
} }
TrackerEntry::TrackerEntry(const libtorrent::announce_entry &nativeEntry) TrackerEntry::TrackerEntry(const lt::announce_entry &nativeEntry)
: m_nativeEntry(nativeEntry) : m_nativeEntry(nativeEntry)
{ {
} }
@ -72,7 +72,7 @@ int TrackerEntry::tier() const
TrackerEntry::Status TrackerEntry::status() const TrackerEntry::Status TrackerEntry::status() const
{ {
// libtorrent::announce_entry::is_working() returns // lt::announce_entry::is_working() returns
// true when the tracker hasn't been tried yet. // true when the tracker hasn't been tried yet.
if (m_nativeEntry.verified && isWorking()) if (m_nativeEntry.verified && isWorking())
return Working; return Working;
@ -119,7 +119,7 @@ int TrackerEntry::numDownloaded() const
#endif #endif
} }
libtorrent::announce_entry TrackerEntry::nativeEntry() const lt::announce_entry TrackerEntry::nativeEntry() const
{ {
return m_nativeEntry; return m_nativeEntry;
} }

6
src/base/bittorrent/trackerentry.h

@ -48,7 +48,7 @@ namespace BitTorrent
}; };
TrackerEntry(const QString &url); TrackerEntry(const QString &url);
TrackerEntry(const libtorrent::announce_entry &nativeEntry); TrackerEntry(const lt::announce_entry &nativeEntry);
TrackerEntry(const TrackerEntry &other) = default; TrackerEntry(const TrackerEntry &other) = default;
TrackerEntry &operator=(const TrackerEntry &other) = default; TrackerEntry &operator=(const TrackerEntry &other) = default;
@ -63,10 +63,10 @@ namespace BitTorrent
int numLeeches() const; int numLeeches() const;
int numDownloaded() const; int numDownloaded() const;
libtorrent::announce_entry nativeEntry() const; lt::announce_entry nativeEntry() const;
private: private:
libtorrent::announce_entry m_nativeEntry; lt::announce_entry m_nativeEntry;
}; };
bool operator==(const TrackerEntry &left, const TrackerEntry &right); bool operator==(const TrackerEntry &left, const TrackerEntry &right);

Loading…
Cancel
Save