Browse Source

Add unified class to represent parsed torrent metadata

* Add unified class to represent parsed torrent metadata
* Unify startup logic of "Add new torrent dialog"

PR #19301.
adaptive-webui-19844
Vladimir Golovnev 1 year ago committed by GitHub
parent
commit
f27f2c20e0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      src/base/CMakeLists.txt
  2. 150
      src/base/bittorrent/magneturi.cpp
  3. 7
      src/base/bittorrent/session.h
  4. 86
      src/base/bittorrent/sessionimpl.cpp
  5. 10
      src/base/bittorrent/sessionimpl.h
  6. 232
      src/base/bittorrent/torrentdescriptor.cpp
  7. 55
      src/base/bittorrent/torrentdescriptor.h
  8. 30
      src/base/bittorrent/torrentinfo.cpp
  9. 2
      src/base/bittorrent/torrentinfo.h
  10. 4
      src/base/net/downloadhandlerimpl.cpp
  11. 4
      src/base/net/downloadmanager.h
  12. 4
      src/base/rss/rss_autodownloader.cpp
  13. 35
      src/base/torrentfileswatcher.cpp
  14. 11
      src/base/torrentfileswatcher.h
  15. 224
      src/gui/addnewtorrentdialog.cpp
  16. 11
      src/gui/addnewtorrentdialog.h
  17. 8
      src/gui/torrentcreatordialog.cpp
  18. 16
      src/webui/api/torrentscontroller.cpp

4
src/base/CMakeLists.txt

@ -21,7 +21,6 @@ add_library(qbt_base STATIC
bittorrent/loadtorrentparams.h bittorrent/loadtorrentparams.h
bittorrent/ltqbitarray.h bittorrent/ltqbitarray.h
bittorrent/lttypecast.h bittorrent/lttypecast.h
bittorrent/magneturi.h
bittorrent/nativesessionextension.h bittorrent/nativesessionextension.h
bittorrent/nativetorrentextension.h bittorrent/nativetorrentextension.h
bittorrent/peeraddress.h bittorrent/peeraddress.h
@ -36,6 +35,7 @@ add_library(qbt_base STATIC
bittorrent/torrentcontenthandler.h bittorrent/torrentcontenthandler.h
bittorrent/torrentcontentlayout.h bittorrent/torrentcontentlayout.h
bittorrent/torrentcreatorthread.h bittorrent/torrentcreatorthread.h
bittorrent/torrentdescriptor.h
bittorrent/torrentimpl.h bittorrent/torrentimpl.h
bittorrent/torrentinfo.h bittorrent/torrentinfo.h
bittorrent/tracker.h bittorrent/tracker.h
@ -120,7 +120,6 @@ add_library(qbt_base STATIC
bittorrent/filterparserthread.cpp bittorrent/filterparserthread.cpp
bittorrent/infohash.cpp bittorrent/infohash.cpp
bittorrent/ltqbitarray.cpp bittorrent/ltqbitarray.cpp
bittorrent/magneturi.cpp
bittorrent/nativesessionextension.cpp bittorrent/nativesessionextension.cpp
bittorrent/nativetorrentextension.cpp bittorrent/nativetorrentextension.cpp
bittorrent/peeraddress.cpp bittorrent/peeraddress.cpp
@ -132,6 +131,7 @@ add_library(qbt_base STATIC
bittorrent/torrent.cpp bittorrent/torrent.cpp
bittorrent/torrentcontenthandler.cpp bittorrent/torrentcontenthandler.cpp
bittorrent/torrentcreatorthread.cpp bittorrent/torrentcreatorthread.cpp
bittorrent/torrentdescriptor.cpp
bittorrent/torrentimpl.cpp bittorrent/torrentimpl.cpp
bittorrent/torrentinfo.cpp bittorrent/torrentinfo.cpp
bittorrent/tracker.cpp bittorrent/tracker.cpp

150
src/base/bittorrent/magneturi.cpp

@ -1,150 +0,0 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015 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.
*/
#include "magneturi.h"
#include <libtorrent/bencode.hpp>
#include <libtorrent/error_code.hpp>
#include <libtorrent/magnet_uri.hpp>
#include <libtorrent/sha1_hash.hpp>
#include <QRegularExpression>
#include "base/global.h"
#include "infohash.h"
namespace
{
// BEP9 Extension for Peers to Send Metadata Files
bool isV1Hash(const QString &string)
{
// There are 2 representations for BitTorrent v1 info hash:
// 1. 40 chars hex-encoded string
// == 20 (SHA-1 length in bytes) * 2 (each byte maps to 2 hex characters)
// 2. 32 chars Base32 encoded string
// == 20 (SHA-1 length in bytes) * 1.6 (the efficiency of Base32 encoding)
const int V1_HEX_SIZE = SHA1Hash::length() * 2;
const int V1_BASE32_SIZE = SHA1Hash::length() * 1.6;
return ((((string.size() == V1_HEX_SIZE))
&& !string.contains(QRegularExpression(u"[^0-9A-Fa-f]"_s)))
|| ((string.size() == V1_BASE32_SIZE)
&& !string.contains(QRegularExpression(u"[^2-7A-Za-z]"_s))));
}
bool isV2Hash(const QString &string)
{
// There are 1 representation for BitTorrent v2 info hash:
// 1. 64 chars hex-encoded string
// == 32 (SHA-2 256 length in bytes) * 2 (each byte maps to 2 hex characters)
const int V2_HEX_SIZE = SHA256Hash::length() * 2;
return (string.size() == V2_HEX_SIZE)
&& !string.contains(QRegularExpression(u"[^0-9A-Fa-f]"_s));
}
}
using namespace BitTorrent;
const int magnetUriId = qRegisterMetaType<MagnetUri>();
MagnetUri::MagnetUri(const QString &source)
: m_url(source)
{
if (source.isEmpty()) return;
if (isV2Hash(source))
m_url = u"magnet:?xt=urn:btmh:1220" + source; // 0x12 0x20 is the "multihash format" tag for the SHA-256 hashing scheme.
else if (isV1Hash(source))
m_url = u"magnet:?xt=urn:btih:" + source;
lt::error_code ec;
lt::parse_magnet_uri(m_url.toStdString(), m_addTorrentParams, ec);
if (ec) return;
m_valid = true;
#ifdef QBT_USES_LIBTORRENT2
m_infoHash = m_addTorrentParams.info_hashes;
#else
m_infoHash = m_addTorrentParams.info_hash;
#endif
m_name = QString::fromStdString(m_addTorrentParams.name);
m_trackers.reserve(static_cast<decltype(m_trackers)::size_type>(m_addTorrentParams.trackers.size()));
int tier = 0;
auto tierIter = m_addTorrentParams.tracker_tiers.cbegin();
for (const std::string &url : m_addTorrentParams.trackers)
{
if (tierIter != m_addTorrentParams.tracker_tiers.cend())
tier = *tierIter++;
m_trackers.append({QString::fromStdString(url), tier});
}
m_urlSeeds.reserve(static_cast<decltype(m_urlSeeds)::size_type>(m_addTorrentParams.url_seeds.size()));
for (const std::string &urlSeed : m_addTorrentParams.url_seeds)
m_urlSeeds.append(QString::fromStdString(urlSeed));
}
bool MagnetUri::isValid() const
{
return m_valid;
}
InfoHash MagnetUri::infoHash() const
{
return m_infoHash;
}
QString MagnetUri::name() const
{
return m_name;
}
QVector<TrackerEntry> MagnetUri::trackers() const
{
return m_trackers;
}
QVector<QUrl> MagnetUri::urlSeeds() const
{
return m_urlSeeds;
}
QString MagnetUri::url() const
{
return m_url;
}
lt::add_torrent_params MagnetUri::addTorrentParams() const
{
return m_addTorrentParams;
}

7
src/base/bittorrent/session.h

@ -58,8 +58,8 @@ enum DeleteOption
namespace BitTorrent namespace BitTorrent
{ {
class InfoHash; class InfoHash;
class MagnetUri;
class Torrent; class Torrent;
class TorrentDescriptor;
class TorrentID; class TorrentID;
class TorrentInfo; class TorrentInfo;
struct CacheStatus; struct CacheStatus;
@ -441,10 +441,9 @@ namespace BitTorrent
virtual bool isKnownTorrent(const InfoHash &infoHash) const = 0; virtual bool isKnownTorrent(const InfoHash &infoHash) const = 0;
virtual bool addTorrent(const QString &source, const AddTorrentParams &params = {}) = 0; virtual bool addTorrent(const QString &source, const AddTorrentParams &params = {}) = 0;
virtual bool addTorrent(const MagnetUri &magnetUri, const AddTorrentParams &params = {}) = 0; virtual bool addTorrent(const TorrentDescriptor &torrentDescr, const AddTorrentParams &params = {}) = 0;
virtual bool addTorrent(const TorrentInfo &torrentInfo, const AddTorrentParams &params = {}) = 0;
virtual bool deleteTorrent(const TorrentID &id, DeleteOption deleteOption = DeleteOption::DeleteTorrent) = 0; virtual bool deleteTorrent(const TorrentID &id, DeleteOption deleteOption = DeleteOption::DeleteTorrent) = 0;
virtual bool downloadMetadata(const MagnetUri &magnetUri) = 0; virtual bool downloadMetadata(const TorrentDescriptor &torrentDescr) = 0;
virtual bool cancelDownloadMetadata(const TorrentID &id) = 0; virtual bool cancelDownloadMetadata(const TorrentID &id) = 0;
virtual void recursiveTorrentDownload(const TorrentID &id) = 0; virtual void recursiveTorrentDownload(const TorrentID &id) = 0;

86
src/base/bittorrent/sessionimpl.cpp

@ -101,10 +101,10 @@
#include "filterparserthread.h" #include "filterparserthread.h"
#include "loadtorrentparams.h" #include "loadtorrentparams.h"
#include "lttypecast.h" #include "lttypecast.h"
#include "magneturi.h"
#include "nativesessionextension.h" #include "nativesessionextension.h"
#include "portforwarderimpl.h" #include "portforwarderimpl.h"
#include "resumedatastorage.h" #include "resumedatastorage.h"
#include "torrentdescriptor.h"
#include "torrentimpl.h" #include "torrentimpl.h"
#include "tracker.h" #include "tracker.h"
@ -2250,14 +2250,22 @@ void SessionImpl::handleDownloadFinished(const Net::DownloadResult &result)
{ {
case Net::DownloadStatus::Success: case Net::DownloadStatus::Success:
emit downloadFromUrlFinished(result.url); emit downloadFromUrlFinished(result.url);
if (const nonstd::expected<TorrentInfo, QString> loadResult = TorrentInfo::load(result.data); loadResult) if (const auto loadResult = TorrentDescriptor::load(result.data))
addTorrent(loadResult.value(), m_downloadedTorrents.take(result.url)); addTorrent(loadResult.value(), m_downloadedTorrents.take(result.url));
else else
LogMsg(tr("Failed to load torrent. Reason: \"%1\"").arg(loadResult.error()), Log::WARNING); LogMsg(tr("Failed to load torrent. Reason: \"%1\"").arg(loadResult.error()), Log::WARNING);
break; break;
case Net::DownloadStatus::RedirectedToMagnet: case Net::DownloadStatus::RedirectedToMagnet:
emit downloadFromUrlFinished(result.url); emit downloadFromUrlFinished(result.url);
addTorrent(MagnetUri(result.magnet), m_downloadedTorrents.take(result.url)); if (const auto parseResult = TorrentDescriptor::parse(result.magnetURI))
{
addTorrent(parseResult.value(), m_downloadedTorrents.take(result.url));
}
else
{
LogMsg(tr("Failed to load torrent. The request was redirected to invalid Magnet URI. Reason: \"%1\"")
.arg(parseResult.error()), Log::WARNING);
}
break; break;
default: default:
emit downloadFromUrlFailed(result.url, result.errorString); emit downloadFromUrlFailed(result.url, result.errorString);
@ -2592,13 +2600,12 @@ bool SessionImpl::addTorrent(const QString &source, const AddTorrentParams &para
return true; return true;
} }
const MagnetUri magnetUri {source}; if (const auto parseResult = TorrentDescriptor::parse(source))
if (magnetUri.isValid()) return addTorrent(parseResult.value(), params);
return addTorrent(magnetUri, params);
const Path path {source}; const Path path {source};
TorrentFileGuard guard {path}; TorrentFileGuard guard {path};
const nonstd::expected<TorrentInfo, QString> loadResult = TorrentInfo::loadFromFile(path); const auto loadResult = TorrentDescriptor::loadFromFile(path);
if (!loadResult) if (!loadResult)
{ {
LogMsg(tr("Failed to load torrent. Source: \"%1\". Reason: \"%2\"").arg(source, loadResult.error()), Log::WARNING); LogMsg(tr("Failed to load torrent. Source: \"%1\". Reason: \"%2\"").arg(source, loadResult.error()), Log::WARNING);
@ -2609,23 +2616,12 @@ bool SessionImpl::addTorrent(const QString &source, const AddTorrentParams &para
return addTorrent(loadResult.value(), params); return addTorrent(loadResult.value(), params);
} }
bool SessionImpl::addTorrent(const MagnetUri &magnetUri, const AddTorrentParams &params) bool SessionImpl::addTorrent(const TorrentDescriptor &torrentDescr, const AddTorrentParams &params)
{ {
if (!isRestored()) if (!isRestored())
return false; return false;
if (!magnetUri.isValid()) return addTorrent_impl(torrentDescr, params);
return false;
return addTorrent_impl(magnetUri, params);
}
bool SessionImpl::addTorrent(const TorrentInfo &torrentInfo, const AddTorrentParams &params)
{
if (!isRestored())
return false;
return addTorrent_impl(torrentInfo, params);
} }
LoadTorrentParams SessionImpl::initLoadTorrentParams(const AddTorrentParams &addTorrentParams) LoadTorrentParams SessionImpl::initLoadTorrentParams(const AddTorrentParams &addTorrentParams)
@ -2690,12 +2686,12 @@ LoadTorrentParams SessionImpl::initLoadTorrentParams(const AddTorrentParams &add
} }
// Add a torrent to the BitTorrent session // Add a torrent to the BitTorrent session
bool SessionImpl::addTorrent_impl(const std::variant<MagnetUri, TorrentInfo> &source, const AddTorrentParams &addTorrentParams) bool SessionImpl::addTorrent_impl(const TorrentDescriptor &source, const AddTorrentParams &addTorrentParams)
{ {
Q_ASSERT(isRestored()); Q_ASSERT(isRestored());
const bool hasMetadata = std::holds_alternative<TorrentInfo>(source); const bool hasMetadata = (source.info().has_value());
const auto infoHash = (hasMetadata ? std::get<TorrentInfo>(source).infoHash() : std::get<MagnetUri>(source).infoHash()); const auto infoHash = source.infoHash();
const auto id = TorrentID::fromInfoHash(infoHash); const auto id = TorrentID::fromInfoHash(infoHash);
// alternative ID can be useful to find existing torrent in case if hybrid torrent was added by v1 info hash // alternative ID can be useful to find existing torrent in case if hybrid torrent was added by v1 info hash
@ -2712,7 +2708,7 @@ bool SessionImpl::addTorrent_impl(const std::variant<MagnetUri, TorrentInfo> &so
if (hasMetadata) if (hasMetadata)
{ {
// Trying to set metadata to existing torrent in case if it has none // Trying to set metadata to existing torrent in case if it has none
torrent->setMetadata(std::get<TorrentInfo>(source)); torrent->setMetadata(*source.info());
} }
if (!isMergeTrackersEnabled()) if (!isMergeTrackersEnabled())
@ -2721,29 +2717,16 @@ bool SessionImpl::addTorrent_impl(const std::variant<MagnetUri, TorrentInfo> &so
return false; return false;
} }
const bool isPrivate = torrent->isPrivate() || (hasMetadata && std::get<TorrentInfo>(source).isPrivate()); const bool isPrivate = torrent->isPrivate() || (hasMetadata && source.info()->isPrivate());
if (isPrivate) if (isPrivate)
{ {
LogMsg(tr("Detected an attempt to add a duplicate torrent. Trackers cannot be merged because it is a private torrent. Torrent: %1").arg(torrent->name())); LogMsg(tr("Detected an attempt to add a duplicate torrent. Trackers cannot be merged because it is a private torrent. Torrent: %1").arg(torrent->name()));
return false; return false;
} }
if (hasMetadata)
{
const TorrentInfo &torrentInfo = std::get<TorrentInfo>(source);
// merge trackers and web seeds // merge trackers and web seeds
torrent->addTrackers(torrentInfo.trackers()); torrent->addTrackers(source.trackers());
torrent->addUrlSeeds(torrentInfo.urlSeeds()); torrent->addUrlSeeds(source.urlSeeds());
}
else
{
const MagnetUri &magnetUri = std::get<MagnetUri>(source);
// merge trackers and web seeds
torrent->addTrackers(magnetUri.trackers());
torrent->addUrlSeeds(magnetUri.urlSeeds());
}
LogMsg(tr("Detected an attempt to add a duplicate torrent. Trackers are merged from new source. Torrent: %1").arg(torrent->name())); LogMsg(tr("Detected an attempt to add a duplicate torrent. Trackers are merged from new source. Torrent: %1").arg(torrent->name()));
return false; return false;
@ -2759,6 +2742,7 @@ bool SessionImpl::addTorrent_impl(const std::variant<MagnetUri, TorrentInfo> &so
LoadTorrentParams loadTorrentParams = initLoadTorrentParams(addTorrentParams); LoadTorrentParams loadTorrentParams = initLoadTorrentParams(addTorrentParams);
lt::add_torrent_params &p = loadTorrentParams.ltAddTorrentParams; lt::add_torrent_params &p = loadTorrentParams.ltAddTorrentParams;
p = source.ltAddTorrentParams();
bool isFindingIncompleteFiles = false; bool isFindingIncompleteFiles = false;
@ -2767,7 +2751,7 @@ bool SessionImpl::addTorrent_impl(const std::variant<MagnetUri, TorrentInfo> &so
if (hasMetadata) if (hasMetadata)
{ {
const TorrentInfo &torrentInfo = std::get<TorrentInfo>(source); const TorrentInfo &torrentInfo = *source.info();
Q_ASSERT(addTorrentParams.filePaths.isEmpty() || (addTorrentParams.filePaths.size() == torrentInfo.filesCount())); Q_ASSERT(addTorrentParams.filePaths.isEmpty() || (addTorrentParams.filePaths.size() == torrentInfo.filesCount()));
@ -2779,8 +2763,7 @@ bool SessionImpl::addTorrent_impl(const std::variant<MagnetUri, TorrentInfo> &so
{ {
const Path originalRootFolder = Path::findRootFolder(filePaths); const Path originalRootFolder = Path::findRootFolder(filePaths);
const auto originalContentLayout = (originalRootFolder.isEmpty() const auto originalContentLayout = (originalRootFolder.isEmpty()
? TorrentContentLayout::NoSubfolder ? TorrentContentLayout::NoSubfolder : TorrentContentLayout::Subfolder);
: TorrentContentLayout::Subfolder);
if (loadTorrentParams.contentLayout != originalContentLayout) if (loadTorrentParams.contentLayout != originalContentLayout)
{ {
if (loadTorrentParams.contentLayout == TorrentContentLayout::NoSubfolder) if (loadTorrentParams.contentLayout == TorrentContentLayout::NoSubfolder)
@ -2843,13 +2826,10 @@ bool SessionImpl::addTorrent_impl(const std::variant<MagnetUri, TorrentInfo> &so
p.file_priorities[LT::toUnderlyingType(nativeIndexes[i])] = LT::toNative(addTorrentParams.filePriorities[i]); p.file_priorities[LT::toUnderlyingType(nativeIndexes[i])] = LT::toNative(addTorrentParams.filePriorities[i]);
} }
p.ti = torrentInfo.nativeInfo(); Q_ASSERT(p.ti);
} }
else else
{ {
const MagnetUri &magnetUri = std::get<MagnetUri>(source);
p = magnetUri.addTorrentParams();
if (loadTorrentParams.name.isEmpty() && !p.name.empty()) if (loadTorrentParams.name.isEmpty() && !p.name.empty())
loadTorrentParams.name = QString::fromStdString(p.name); loadTorrentParams.name = QString::fromStdString(p.name);
} }
@ -3009,19 +2989,20 @@ void SessionImpl::invokeAsync(std::function<void ()> func)
// Add a torrent to libtorrent session in hidden mode // Add a torrent to libtorrent session in hidden mode
// and force it to download its metadata // and force it to download its metadata
bool SessionImpl::downloadMetadata(const MagnetUri &magnetUri) bool SessionImpl::downloadMetadata(const TorrentDescriptor &torrentDescr)
{ {
if (!magnetUri.isValid()) Q_ASSERT(!torrentDescr.info().has_value());
if (Q_UNLIKELY(torrentDescr.info().has_value()))
return false; return false;
const InfoHash infoHash = magnetUri.infoHash(); const InfoHash infoHash = torrentDescr.infoHash();
// We should not add torrent if it's already // We should not add torrent if it's already
// processed or adding to session // processed or adding to session
if (isKnownTorrent(infoHash)) if (isKnownTorrent(infoHash))
return false; return false;
lt::add_torrent_params p = magnetUri.addTorrentParams(); lt::add_torrent_params p = torrentDescr.ltAddTorrentParams();
if (isAddTrackersEnabled()) if (isAddTrackersEnabled())
{ {
@ -5281,8 +5262,7 @@ void SessionImpl::recursiveTorrentDownload(const TorrentID &id)
AddTorrentParams params; AddTorrentParams params;
// Passing the save path along to the sub torrent file // Passing the save path along to the sub torrent file
params.savePath = torrent->savePath(); params.savePath = torrent->savePath();
const nonstd::expected<TorrentInfo, QString> loadResult = TorrentInfo::loadFromFile(torrentFullpath); if (const auto loadResult = TorrentDescriptor::loadFromFile(torrentFullpath))
if (loadResult)
{ {
addTorrent(loadResult.value(), params); addTorrent(loadResult.value(), params);
} }

10
src/base/bittorrent/sessionimpl.h

@ -30,7 +30,6 @@
#pragma once #pragma once
#include <utility> #include <utility>
#include <variant>
#include <vector> #include <vector>
#include <libtorrent/fwd.hpp> #include <libtorrent/fwd.hpp>
@ -76,9 +75,9 @@ namespace Net
namespace BitTorrent namespace BitTorrent
{ {
class InfoHash; class InfoHash;
class MagnetUri;
class ResumeDataStorage; class ResumeDataStorage;
class Torrent; class Torrent;
class TorrentDescriptor;
class TorrentImpl; class TorrentImpl;
class Tracker; class Tracker;
struct LoadTorrentParams; struct LoadTorrentParams;
@ -416,10 +415,9 @@ namespace BitTorrent
bool isKnownTorrent(const InfoHash &infoHash) const override; bool isKnownTorrent(const InfoHash &infoHash) const override;
bool addTorrent(const QString &source, const AddTorrentParams &params = {}) override; bool addTorrent(const QString &source, const AddTorrentParams &params = {}) override;
bool addTorrent(const MagnetUri &magnetUri, const AddTorrentParams &params = {}) override; bool addTorrent(const TorrentDescriptor &torrentDescr, const AddTorrentParams &params = {}) override;
bool addTorrent(const TorrentInfo &torrentInfo, const AddTorrentParams &params = {}) override;
bool deleteTorrent(const TorrentID &id, DeleteOption deleteOption = DeleteTorrent) override; bool deleteTorrent(const TorrentID &id, DeleteOption deleteOption = DeleteTorrent) override;
bool downloadMetadata(const MagnetUri &magnetUri) override; bool downloadMetadata(const TorrentDescriptor &torrentDescr) override;
bool cancelDownloadMetadata(const TorrentID &id) override; bool cancelDownloadMetadata(const TorrentID &id) override;
void recursiveTorrentDownload(const TorrentID &id) override; void recursiveTorrentDownload(const TorrentID &id) override;
@ -532,7 +530,7 @@ namespace BitTorrent
void endStartup(ResumeSessionContext *context); void endStartup(ResumeSessionContext *context);
LoadTorrentParams initLoadTorrentParams(const AddTorrentParams &addTorrentParams); LoadTorrentParams initLoadTorrentParams(const AddTorrentParams &addTorrentParams);
bool addTorrent_impl(const std::variant<MagnetUri, TorrentInfo> &source, const AddTorrentParams &addTorrentParams); bool addTorrent_impl(const TorrentDescriptor &source, const AddTorrentParams &addTorrentParams);
void updateSeedingLimitTimer(); void updateSeedingLimitTimer();
void exportTorrentFile(const Torrent *torrent, const Path &folderPath); void exportTorrentFile(const Torrent *torrent, const Path &folderPath);

232
src/base/bittorrent/torrentdescriptor.cpp

@ -0,0 +1,232 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015-2023 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.
*/
#include "torrentdescriptor.h"
#include <libtorrent/load_torrent.hpp>
#include <libtorrent/magnet_uri.hpp>
#include <libtorrent/torrent_info.hpp>
#include <libtorrent/version.hpp>
#include <libtorrent/write_resume_data.hpp>
#include <QByteArray>
#include <QDateTime>
#include <QRegularExpression>
#include <QString>
#include <QUrl>
#include "base/global.h"
#include "base/preferences.h"
#include "base/utils/io.h"
#include "infohash.h"
#include "trackerentry.h"
namespace
{
// BEP9 Extension for Peers to Send Metadata Files
bool isV1Hash(const QString &string)
{
// There are 2 representations for BitTorrent v1 info hash:
// 1. 40 chars hex-encoded string
// == 20 (SHA-1 length in bytes) * 2 (each byte maps to 2 hex characters)
// 2. 32 chars Base32 encoded string
// == 20 (SHA-1 length in bytes) * 1.6 (the efficiency of Base32 encoding)
const int V1_HEX_SIZE = SHA1Hash::length() * 2;
const int V1_BASE32_SIZE = SHA1Hash::length() * 1.6;
return ((((string.size() == V1_HEX_SIZE)) && !string.contains(QRegularExpression(u"[^0-9A-Fa-f]"_s)))
|| ((string.size() == V1_BASE32_SIZE) && !string.contains(QRegularExpression(u"[^2-7A-Za-z]"_s))));
}
bool isV2Hash(const QString &string)
{
// There are 1 representation for BitTorrent v2 info hash:
// 1. 64 chars hex-encoded string
// == 32 (SHA-2 256 length in bytes) * 2 (each byte maps to 2 hex characters)
const int V2_HEX_SIZE = SHA256Hash::length() * 2;
return (string.size() == V2_HEX_SIZE) && !string.contains(QRegularExpression(u"[^0-9A-Fa-f]"_s));
}
lt::load_torrent_limits loadTorrentLimits()
{
const auto *pref = Preferences::instance();
lt::load_torrent_limits limits;
limits.max_buffer_size = static_cast<int>(pref->getTorrentFileSizeLimit());
limits.max_decode_depth = pref->getBdecodeDepthLimit();
limits.max_decode_tokens = pref->getBdecodeTokenLimit();
return limits;
}
}
const int TORRENTDESCRIPTOR_TYPEID = qRegisterMetaType<BitTorrent::TorrentDescriptor>();
nonstd::expected<BitTorrent::TorrentDescriptor, QString>
BitTorrent::TorrentDescriptor::load(const QByteArray &data) noexcept
try
{
return TorrentDescriptor(lt::load_torrent_buffer(lt::span<const char>(data.data(), data.size()), loadTorrentLimits()));
}
catch (const lt::system_error &err)
{
return nonstd::make_unexpected(QString::fromLocal8Bit(err.what()));
}
nonstd::expected<BitTorrent::TorrentDescriptor, QString>
BitTorrent::TorrentDescriptor::loadFromFile(const Path &path) noexcept
try
{
return TorrentDescriptor(lt::load_torrent_file(path.toString().toStdString(), loadTorrentLimits()));
}
catch (const lt::system_error &err)
{
return nonstd::make_unexpected(QString::fromLocal8Bit(err.what()));
}
nonstd::expected<BitTorrent::TorrentDescriptor, QString>
BitTorrent::TorrentDescriptor::parse(const QString &str) noexcept
try
{
QString magnetURI = str;
if (isV2Hash(str))
magnetURI = u"magnet:?xt=urn:btmh:1220" + str; // 0x12 0x20 is the "multihash format" tag for the SHA-256 hashing scheme.
else if (isV1Hash(str))
magnetURI = u"magnet:?xt=urn:btih:" + str;
return TorrentDescriptor(lt::parse_magnet_uri(magnetURI.toStdString()));
}
catch (const lt::system_error &err)
{
return nonstd::make_unexpected(QString::fromLocal8Bit(err.what()));
}
nonstd::expected<void, QString> BitTorrent::TorrentDescriptor::saveToFile(const Path &path) const
try
{
const lt::entry torrentEntry = lt::write_torrent_file(m_ltAddTorrentParams);
const nonstd::expected<void, QString> result = Utils::IO::saveToFile(path, torrentEntry);
if (!result)
return result.get_unexpected();
return {};
}
catch (const lt::system_error &err)
{
return nonstd::make_unexpected(QString::fromLocal8Bit(err.what()));
}
BitTorrent::TorrentDescriptor::TorrentDescriptor(lt::add_torrent_params ltAddTorrentParams)
: m_ltAddTorrentParams {std::move(ltAddTorrentParams)}
{
if (m_ltAddTorrentParams.ti && m_ltAddTorrentParams.ti->is_valid())
m_info.emplace(*m_ltAddTorrentParams.ti);
}
BitTorrent::InfoHash BitTorrent::TorrentDescriptor::infoHash() const
{
#ifdef QBT_USES_LIBTORRENT2
return m_ltAddTorrentParams.info_hashes;
#else
return m_ltAddTorrentParams.info_hash;
#endif
}
QString BitTorrent::TorrentDescriptor::name() const
{
return m_info ? m_info->name() : QString::fromStdString(m_ltAddTorrentParams.name);
}
QDateTime BitTorrent::TorrentDescriptor::creationDate() const
{
return ((m_ltAddTorrentParams.ti->creation_date() != 0)
? QDateTime::fromSecsSinceEpoch(m_ltAddTorrentParams.ti->creation_date()) : QDateTime());
}
QString BitTorrent::TorrentDescriptor::creator() const
{
return QString::fromStdString(m_ltAddTorrentParams.ti->creator());
}
QString BitTorrent::TorrentDescriptor::comment() const
{
return QString::fromStdString(m_ltAddTorrentParams.ti->comment());
}
const std::optional<BitTorrent::TorrentInfo> &BitTorrent::TorrentDescriptor::info() const
{
return m_info;
}
void BitTorrent::TorrentDescriptor::setTorrentInfo(TorrentInfo torrentInfo)
{
if (!torrentInfo.isValid())
{
m_info.reset();
m_ltAddTorrentParams.ti.reset();
}
else
{
m_info = std::move(torrentInfo);
m_ltAddTorrentParams.ti = torrentInfo.nativeInfo();
#ifdef QBT_USES_LIBTORRENT2
m_ltAddTorrentParams.info_hashes = m_ltAddTorrentParams.ti->info_hashes();
#else
m_ltAddTorrentParams.info_hash = m_ltAddTorrentParams.ti->info_hash();
#endif
}
}
QVector<BitTorrent::TrackerEntry> BitTorrent::TorrentDescriptor::trackers() const
{
QVector<TrackerEntry> ret;
ret.reserve(static_cast<decltype(ret)::size_type>(m_ltAddTorrentParams.trackers.size()));
std::size_t i = 0;
for (const std::string &tracker : m_ltAddTorrentParams.trackers)
ret.append({QString::fromStdString(tracker), m_ltAddTorrentParams.tracker_tiers[i++]});
return ret;
}
QVector<QUrl> BitTorrent::TorrentDescriptor::urlSeeds() const
{
QVector<QUrl> urlSeeds;
urlSeeds.reserve(static_cast<decltype(urlSeeds)::size_type>(m_ltAddTorrentParams.url_seeds.size()));
for (const std::string &nativeURLSeed : m_ltAddTorrentParams.url_seeds)
urlSeeds.append(QUrl(QString::fromStdString(nativeURLSeed)));
return urlSeeds;
}
const libtorrent::add_torrent_params &BitTorrent::TorrentDescriptor::ltAddTorrentParams() const
{
return m_ltAddTorrentParams;
}

55
src/base/bittorrent/magneturi.h → src/base/bittorrent/torrentdescriptor.h

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2015-2023 Vladimir Golovnev <glassez@yandex.ru>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
@ -28,40 +28,57 @@
#pragma once #pragma once
#include <optional>
#include <libtorrent/add_torrent_params.hpp> #include <libtorrent/add_torrent_params.hpp>
#include <QString> #include <QtContainerFwd>
#include <QUrl> #include <QMetaType>
#include <QVector>
#include "base/3rdparty/expected.hpp"
#include "base/path.h"
#include "torrentdescriptor.h"
#include "torrentinfo.h"
#include "infohash.h" class QByteArray;
#include "trackerentry.h" class QDateTime;
class QString;
class QUrl;
namespace BitTorrent namespace BitTorrent
{ {
class MagnetUri class InfoHash;
struct TrackerEntry;
class TorrentDescriptor
{ {
public: public:
explicit MagnetUri(const QString &source = {}); TorrentDescriptor() = default;
bool isValid() const;
InfoHash infoHash() const; InfoHash infoHash() const;
QString name() const; QString name() const;
QDateTime creationDate() const;
QString creator() const;
QString comment() const;
QVector<TrackerEntry> trackers() const; QVector<TrackerEntry> trackers() const;
QVector<QUrl> urlSeeds() const; QVector<QUrl> urlSeeds() const;
QString url() const; const std::optional<TorrentInfo> &info() const;
lt::add_torrent_params addTorrentParams() const; void setTorrentInfo(TorrentInfo torrentInfo);
static nonstd::expected<TorrentDescriptor, QString> load(const QByteArray &data) noexcept;
static nonstd::expected<TorrentDescriptor, QString> loadFromFile(const Path &path) noexcept;
static nonstd::expected<TorrentDescriptor, QString> parse(const QString &str) noexcept;
nonstd::expected<void, QString> saveToFile(const Path &path) const;
const lt::add_torrent_params &ltAddTorrentParams() const;
private: private:
bool m_valid = false; explicit TorrentDescriptor(lt::add_torrent_params ltAddTorrentParams);
QString m_url;
InfoHash m_infoHash; lt::add_torrent_params m_ltAddTorrentParams;
QString m_name; std::optional<TorrentInfo> m_info;
QVector<TrackerEntry> m_trackers;
QVector<QUrl> m_urlSeeds;
lt::add_torrent_params m_addTorrentParams;
}; };
} }
Q_DECLARE_METATYPE(BitTorrent::MagnetUri) Q_DECLARE_METATYPE(BitTorrent::TorrentDescriptor)

30
src/base/bittorrent/torrentinfo.cpp

@ -51,7 +51,7 @@
using namespace BitTorrent; using namespace BitTorrent;
const int torrentInfoId = qRegisterMetaType<TorrentInfo>(); const int TORRENTINFO_TYPEID = qRegisterMetaType<TorrentInfo>();
TorrentInfo::TorrentInfo(const lt::torrent_info &nativeInfo) TorrentInfo::TorrentInfo(const lt::torrent_info &nativeInfo)
: m_nativeInfo {std::make_shared<const lt::torrent_info>(nativeInfo)} : m_nativeInfo {std::make_shared<const lt::torrent_info>(nativeInfo)}
@ -401,6 +401,34 @@ TorrentInfo::PieceRange TorrentInfo::filePieces(const int fileIndex) const
return makeInterval(beginIdx, endIdx); return makeInterval(beginIdx, endIdx);
} }
bool TorrentInfo::matchesInfoHash(const InfoHash &otherInfoHash) const
{
if (!isValid())
return false;
const InfoHash thisInfoHash = infoHash();
if (thisInfoHash.v1().isValid() && otherInfoHash.v1().isValid()
&& (thisInfoHash.v1() != otherInfoHash.v1()))
{
return false;
}
if (thisInfoHash.v2().isValid() && otherInfoHash.v2().isValid()
&& (thisInfoHash.v2() != otherInfoHash.v2()))
{
return false;
}
if (!thisInfoHash.v1().isValid() && otherInfoHash.v1().isValid())
return false;
if (!thisInfoHash.v2().isValid() && otherInfoHash.v2().isValid())
return false;
return true;
}
int TorrentInfo::fileIndex(const Path &filePath) const int TorrentInfo::fileIndex(const Path &filePath) const
{ {
// the check whether the object is valid is not needed here // the check whether the object is valid is not needed here

2
src/base/bittorrent/torrentinfo.h

@ -93,6 +93,8 @@ namespace BitTorrent
PieceRange filePieces(const Path &filePath) const; PieceRange filePieces(const Path &filePath) const;
PieceRange filePieces(int fileIndex) const; PieceRange filePieces(int fileIndex) const;
bool matchesInfoHash(const InfoHash &otherInfoHash) const;
std::shared_ptr<lt::torrent_info> nativeInfo() const; std::shared_ptr<lt::torrent_info> nativeInfo() const;
QVector<lt::file_index_t> nativeIndexes() const; QVector<lt::file_index_t> nativeIndexes() const;

4
src/base/net/downloadhandlerimpl.cpp

@ -199,11 +199,9 @@ void Net::DownloadHandlerImpl::handleRedirection(const QUrl &newUrl)
// Redirect to magnet workaround // Redirect to magnet workaround
if (newUrlString.startsWith(u"magnet:", Qt::CaseInsensitive)) if (newUrlString.startsWith(u"magnet:", Qt::CaseInsensitive))
{ {
qDebug("Magnet redirect detected.");
m_result.status = Net::DownloadStatus::RedirectedToMagnet; m_result.status = Net::DownloadStatus::RedirectedToMagnet;
m_result.magnet = newUrlString; m_result.magnetURI = newUrlString;
m_result.errorString = tr("Redirected to magnet URI"); m_result.errorString = tr("Redirected to magnet URI");
finish(); finish();
return; return;
} }

4
src/base/net/downloadmanager.h

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015, 2018 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2015-2023 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org> * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
@ -103,7 +103,7 @@ namespace Net
QString errorString; QString errorString;
QByteArray data; QByteArray data;
Path filePath; Path filePath;
QString magnet; QString magnetURI;
}; };
class DownloadHandler : public QObject class DownloadHandler : public QObject

4
src/base/rss/rss_autodownloader.cpp

@ -41,8 +41,8 @@
#include <QVariant> #include <QVariant>
#include <QVector> #include <QVector>
#include "../bittorrent/magneturi.h"
#include "../bittorrent/session.h" #include "../bittorrent/session.h"
#include "../bittorrent/torrentdescriptor.h"
#include "../asyncfilestorage.h" #include "../asyncfilestorage.h"
#include "../global.h" #include "../global.h"
#include "../logger.h" #include "../logger.h"
@ -474,7 +474,7 @@ void AutoDownloader::processJob(const QSharedPointer<ProcessingJob> &job)
const auto torrentURL = job->articleData.value(Article::KeyTorrentURL).toString(); const auto torrentURL = job->articleData.value(Article::KeyTorrentURL).toString();
BitTorrent::Session::instance()->addTorrent(torrentURL, rule.addTorrentParams()); BitTorrent::Session::instance()->addTorrent(torrentURL, rule.addTorrentParams());
if (BitTorrent::MagnetUri(torrentURL).isValid()) if (BitTorrent::TorrentDescriptor::parse(torrentURL))
{ {
if (Feed *feed = Session::instance()->feedByURL(job->feedURL)) if (Feed *feed = Session::instance()->feedByURL(job->feedURL))
{ {

35
src/base/torrentfileswatcher.cpp

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2021 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2021-2023 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2010 Christian Kandeler, Christophe Dumez <chris@qbittorrent.org> * Copyright (C) 2010 Christian Kandeler, Christophe Dumez <chris@qbittorrent.org>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
@ -44,11 +44,9 @@
#include <QVariant> #include <QVariant>
#include "base/algorithm.h" #include "base/algorithm.h"
#include "base/bittorrent/magneturi.h"
#include "base/bittorrent/torrentcontentlayout.h" #include "base/bittorrent/torrentcontentlayout.h"
#include "base/bittorrent/session.h" #include "base/bittorrent/session.h"
#include "base/bittorrent/torrent.h" #include "base/bittorrent/torrent.h"
#include "base/bittorrent/torrentinfo.h"
#include "base/exceptions.h" #include "base/exceptions.h"
#include "base/global.h" #include "base/global.h"
#include "base/logger.h" #include "base/logger.h"
@ -99,8 +97,7 @@ public slots:
void removeWatchedFolder(const Path &path); void removeWatchedFolder(const Path &path);
signals: signals:
void magnetFound(const BitTorrent::MagnetUri &magnetURI, const BitTorrent::AddTorrentParams &addTorrentParams); void torrentFound(const BitTorrent::TorrentDescriptor &torrentDescr, const BitTorrent::AddTorrentParams &addTorrentParams);
void torrentFound(const BitTorrent::TorrentInfo &torrentInfo, const BitTorrent::AddTorrentParams &addTorrentParams);
private: private:
void onTimeout(); void onTimeout();
@ -159,7 +156,6 @@ void TorrentFilesWatcher::initWorker()
m_asyncWorker = new TorrentFilesWatcher::Worker; m_asyncWorker = new TorrentFilesWatcher::Worker;
connect(m_asyncWorker, &TorrentFilesWatcher::Worker::magnetFound, this, &TorrentFilesWatcher::onMagnetFound);
connect(m_asyncWorker, &TorrentFilesWatcher::Worker::torrentFound, this, &TorrentFilesWatcher::onTorrentFound); connect(m_asyncWorker, &TorrentFilesWatcher::Worker::torrentFound, this, &TorrentFilesWatcher::onTorrentFound);
m_asyncWorker->moveToThread(m_ioThread.get()); m_asyncWorker->moveToThread(m_ioThread.get());
@ -332,16 +328,10 @@ void TorrentFilesWatcher::removeWatchedFolder(const Path &path)
} }
} }
void TorrentFilesWatcher::onMagnetFound(const BitTorrent::MagnetUri &magnetURI void TorrentFilesWatcher::onTorrentFound(const BitTorrent::TorrentDescriptor &torrentDescr
, const BitTorrent::AddTorrentParams &addTorrentParams) , const BitTorrent::AddTorrentParams &addTorrentParams)
{ {
BitTorrent::Session::instance()->addTorrent(magnetURI, addTorrentParams); BitTorrent::Session::instance()->addTorrent(torrentDescr, addTorrentParams);
}
void TorrentFilesWatcher::onTorrentFound(const BitTorrent::TorrentInfo &torrentInfo
, const BitTorrent::AddTorrentParams &addTorrentParams)
{
BitTorrent::Session::instance()->addTorrent(torrentInfo, addTorrentParams);
} }
TorrentFilesWatcher::Worker::Worker() TorrentFilesWatcher::Worker::Worker()
@ -438,7 +428,10 @@ void TorrentFilesWatcher::Worker::processFolder(const Path &path, const Path &wa
while (!file.atEnd()) while (!file.atEnd())
{ {
const auto line = QString::fromLatin1(file.readLine()).trimmed(); const auto line = QString::fromLatin1(file.readLine()).trimmed();
emit magnetFound(BitTorrent::MagnetUri(line), addTorrentParams); if (const auto parseResult = BitTorrent::TorrentDescriptor::parse(line))
emit torrentFound(parseResult.value(), addTorrentParams);
else
LogMsg(tr("Invalid Magnet URI. URI: %1. Reason: %2").arg(line, parseResult.error()), Log::WARNING);
} }
file.close(); file.close();
@ -446,7 +439,7 @@ void TorrentFilesWatcher::Worker::processFolder(const Path &path, const Path &wa
} }
else else
{ {
LogMsg(tr("Magnet file too big. File: %1").arg(file.errorString())); LogMsg(tr("Magnet file too big. File: %1").arg(file.errorString()), Log::WARNING);
} }
} }
else else
@ -456,10 +449,9 @@ void TorrentFilesWatcher::Worker::processFolder(const Path &path, const Path &wa
} }
else else
{ {
const nonstd::expected<BitTorrent::TorrentInfo, QString> result = BitTorrent::TorrentInfo::loadFromFile(filePath); if (const auto loadResult = BitTorrent::TorrentDescriptor::loadFromFile(filePath))
if (result)
{ {
emit torrentFound(result.value(), addTorrentParams); emit torrentFound(loadResult.value(), addTorrentParams);
Utils::Fs::removeFile(filePath); Utils::Fs::removeFile(filePath);
} }
else else
@ -496,8 +488,7 @@ void TorrentFilesWatcher::Worker::processFailedTorrents()
if (!torrentPath.exists()) if (!torrentPath.exists())
return true; return true;
const nonstd::expected<BitTorrent::TorrentInfo, QString> result = BitTorrent::TorrentInfo::loadFromFile(torrentPath); if (const auto loadResult = BitTorrent::TorrentDescriptor::loadFromFile(torrentPath))
if (result)
{ {
BitTorrent::AddTorrentParams addTorrentParams = options.addTorrentParams; BitTorrent::AddTorrentParams addTorrentParams = options.addTorrentParams;
if (torrentPath != watchedFolderPath) if (torrentPath != watchedFolderPath)
@ -515,7 +506,7 @@ void TorrentFilesWatcher::Worker::processFailedTorrents()
} }
} }
emit torrentFound(result.value(), addTorrentParams); emit torrentFound(loadResult.value(), addTorrentParams);
Utils::Fs::removeFile(torrentPath); Utils::Fs::removeFile(torrentPath);
return true; return true;

11
src/base/torrentfileswatcher.h

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2021 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2021-2023 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2010 Christian Kandeler, Christophe Dumez <chris@qbittorrent.org> * Copyright (C) 2010 Christian Kandeler, Christophe Dumez <chris@qbittorrent.org>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
@ -32,16 +32,12 @@
#include <QHash> #include <QHash>
#include "base/bittorrent/addtorrentparams.h" #include "base/bittorrent/addtorrentparams.h"
#include "base/bittorrent/torrentdescriptor.h"
#include "base/path.h" #include "base/path.h"
#include "base/utils/thread.h" #include "base/utils/thread.h"
class QThread; class QThread;
namespace BitTorrent
{
class MagnetUri;
}
/* /*
* Watches the configured directories for new .torrent files in order * Watches the configured directories for new .torrent files in order
* to add torrents to BitTorrent session. Supports Network File System * to add torrents to BitTorrent session. Supports Network File System
@ -72,8 +68,7 @@ signals:
void watchedFolderRemoved(const Path &path); void watchedFolderRemoved(const Path &path);
private slots: private slots:
void onMagnetFound(const BitTorrent::MagnetUri &magnetURI, const BitTorrent::AddTorrentParams &addTorrentParams); void onTorrentFound(const BitTorrent::TorrentDescriptor &torrentDescr, const BitTorrent::AddTorrentParams &addTorrentParams);
void onTorrentFound(const BitTorrent::TorrentInfo &torrentInfo, const BitTorrent::AddTorrentParams &addTorrentParams);
private: private:
explicit TorrentFilesWatcher(QObject *parent = nullptr); explicit TorrentFilesWatcher(QObject *parent = nullptr);

224
src/gui/addnewtorrentdialog.cpp

@ -45,7 +45,6 @@
#include "base/bittorrent/downloadpriority.h" #include "base/bittorrent/downloadpriority.h"
#include "base/bittorrent/infohash.h" #include "base/bittorrent/infohash.h"
#include "base/bittorrent/magneturi.h"
#include "base/bittorrent/session.h" #include "base/bittorrent/session.h"
#include "base/bittorrent/torrent.h" #include "base/bittorrent/torrent.h"
#include "base/bittorrent/torrentcontenthandler.h" #include "base/bittorrent/torrentcontenthandler.h"
@ -139,13 +138,13 @@ class AddNewTorrentDialog::TorrentContentAdaptor final
: public BitTorrent::TorrentContentHandler : public BitTorrent::TorrentContentHandler
{ {
public: public:
TorrentContentAdaptor(BitTorrent::TorrentInfo &torrentInfo, PathList &filePaths TorrentContentAdaptor(const BitTorrent::TorrentInfo &torrentInfo, PathList &filePaths
, QVector<BitTorrent::DownloadPriority> &filePriorities) , QVector<BitTorrent::DownloadPriority> &filePriorities)
: m_torrentInfo {torrentInfo} : m_torrentInfo {torrentInfo}
, m_filePaths {filePaths} , m_filePaths {filePaths}
, m_filePriorities {filePriorities} , m_filePriorities {filePriorities}
{ {
Q_ASSERT(filePaths.isEmpty() || (filePaths.size() == torrentInfo.filesCount())); Q_ASSERT(filePaths.isEmpty() || (filePaths.size() == m_torrentInfo.filesCount()));
m_originalRootFolder = Path::findRootFolder(m_torrentInfo.filePaths()); m_originalRootFolder = Path::findRootFolder(m_torrentInfo.filePaths());
m_currentContentLayout = (m_originalRootFolder.isEmpty() m_currentContentLayout = (m_originalRootFolder.isEmpty()
@ -210,8 +209,7 @@ public:
else else
{ {
const auto rootFolder = ((originalContentLayout == BitTorrent::TorrentContentLayout::Subfolder) const auto rootFolder = ((originalContentLayout == BitTorrent::TorrentContentLayout::Subfolder)
? m_originalRootFolder ? m_originalRootFolder : m_filePaths.at(0).removedExtension());
: m_filePaths.at(0).removedExtension());
Path::addRootFolder(m_filePaths, rootFolder); Path::addRootFolder(m_filePaths, rootFolder);
} }
@ -262,7 +260,7 @@ public:
} }
private: private:
BitTorrent::TorrentInfo &m_torrentInfo; const BitTorrent::TorrentInfo &m_torrentInfo;
PathList &m_filePaths; PathList &m_filePaths;
QVector<BitTorrent::DownloadPriority> &m_filePriorities; QVector<BitTorrent::DownloadPriority> &m_filePriorities;
Path m_originalRootFolder; Path m_originalRootFolder;
@ -489,12 +487,7 @@ void AddNewTorrentDialog::show(const QString &source, const BitTorrent::AddTorre
return; return;
} }
const BitTorrent::MagnetUri magnetUri {source}; if (dlg->loadTorrent(source))
const bool isLoaded = magnetUri.isValid()
? dlg->loadMagnet(magnetUri)
: dlg->loadTorrentFile(source);
if (isLoaded)
dlg->QDialog::show(); dlg->QDialog::show();
else else
delete dlg; delete dlg;
@ -505,42 +498,56 @@ void AddNewTorrentDialog::show(const QString &source, QWidget *parent)
show(source, BitTorrent::AddTorrentParams(), parent); show(source, BitTorrent::AddTorrentParams(), parent);
} }
bool AddNewTorrentDialog::loadTorrentFile(const QString &source) bool AddNewTorrentDialog::loadTorrent(const QString &source)
{ {
const Path decodedPath {source.startsWith(u"file://", Qt::CaseInsensitive) if (const auto parseResult = BitTorrent::TorrentDescriptor::parse(source))
? QUrl::fromEncoded(source.toLocal8Bit()).toLocalFile() {
: source}; m_torrentDescr = parseResult.value();
return loadTorrentImpl();
const nonstd::expected<BitTorrent::TorrentInfo, QString> result = BitTorrent::TorrentInfo::loadFromFile(decodedPath); }
if (!result) else if (source.startsWith(u"magnet:", Qt::CaseInsensitive))
{ {
RaisedMessageBox::critical(this, tr("Invalid torrent") RaisedMessageBox::critical(this, tr("Invalid torrent")
, tr("Failed to load the torrent: %1.\nError: %2", "Don't remove the '\n' characters. They insert a newline.") , tr("Failed to load the torrent: %1.\nError: %2").arg(source, parseResult.error()));
.arg(decodedPath.toString(), result.error()));
return false; return false;
} }
m_torrentInfo = result.value(); const Path decodedPath {source.startsWith(u"file://", Qt::CaseInsensitive)
? QUrl::fromEncoded(source.toLocal8Bit()).toLocalFile() : source};
if (const auto loadResult = BitTorrent::TorrentDescriptor::loadFromFile(decodedPath))
{
m_torrentDescr = loadResult.value();
m_torrentGuard = std::make_unique<TorrentFileGuard>(decodedPath); m_torrentGuard = std::make_unique<TorrentFileGuard>(decodedPath);
return loadTorrentImpl(); return loadTorrentImpl();
} }
else
{
RaisedMessageBox::critical(this, tr("Invalid torrent")
, tr("Failed to load the torrent: %1.\nError: %2", "Don't remove the '\n' characters. They insert a newline.")
.arg(decodedPath.toString(), loadResult.error()));
return false;
}
}
bool AddNewTorrentDialog::loadTorrentImpl() bool AddNewTorrentDialog::loadTorrentImpl()
{ {
const BitTorrent::InfoHash infoHash = m_torrentInfo.infoHash(); const BitTorrent::InfoHash infoHash = m_torrentDescr.infoHash();
// Prevent showing the dialog if download is already present // Prevent showing the dialog if download is already present
const auto *btSession = BitTorrent::Session::instance(); const auto *btSession = BitTorrent::Session::instance();
if (btSession->isKnownTorrent(infoHash)) if (btSession->isKnownTorrent(infoHash))
{ {
BitTorrent::Torrent *const torrent = btSession->findTorrent(infoHash); if (BitTorrent::Torrent *torrent = btSession->findTorrent(infoHash))
if (torrent) {
if (hasMetadata())
{ {
// Trying to set metadata to existing torrent in case if it has none // Trying to set metadata to existing torrent in case if it has none
torrent->setMetadata(m_torrentInfo); torrent->setMetadata(*m_torrentDescr.info());
}
if (torrent->isPrivate() || m_torrentInfo.isPrivate()) if (torrent->isPrivate() || (hasMetadata() && m_torrentDescr.info()->isPrivate()))
{ {
RaisedMessageBox::warning(this, tr("Torrent is already present"), tr("Torrent '%1' is already in the transfer list. Trackers cannot be merged because it is a private torrent.").arg(torrent->name()), QMessageBox::Ok); RaisedMessageBox::warning(this, tr("Torrent is already present"), tr("Torrent '%1' is already in the transfer list. Trackers cannot be merged because it is a private torrent.").arg(torrent->name()), QMessageBox::Ok);
} }
@ -557,8 +564,8 @@ bool AddNewTorrentDialog::loadTorrentImpl()
if (mergeTrackers) if (mergeTrackers)
{ {
torrent->addTrackers(m_torrentInfo.trackers()); torrent->addTrackers(m_torrentDescr.trackers());
torrent->addUrlSeeds(m_torrentInfo.urlSeeds()); torrent->addUrlSeeds(m_torrentDescr.urlSeeds());
} }
} }
} }
@ -570,85 +577,35 @@ bool AddNewTorrentDialog::loadTorrentImpl()
return false; return false;
} }
m_ui->labelInfohash1Data->setText(m_torrentInfo.infoHash().v1().isValid() ? m_torrentInfo.infoHash().v1().toString() : tr("N/A")); m_ui->labelInfohash1Data->setText(infoHash.v1().isValid() ? infoHash.v1().toString() : tr("N/A"));
m_ui->labelInfohash2Data->setText(m_torrentInfo.infoHash().v2().isValid() ? m_torrentInfo.infoHash().v2().toString() : tr("N/A")); m_ui->labelInfohash2Data->setText(infoHash.v2().isValid() ? infoHash.v2().toString() : tr("N/A"));
setupTreeview();
TMMChanged(m_ui->comboTTM->currentIndex());
return true;
}
bool AddNewTorrentDialog::loadMagnet(const BitTorrent::MagnetUri &magnetUri)
{
if (!magnetUri.isValid())
{
RaisedMessageBox::critical(this, tr("Invalid magnet link"), tr("This magnet link was not recognized"));
return false;
}
m_torrentGuard = std::make_unique<TorrentFileGuard>();
const BitTorrent::InfoHash infoHash = magnetUri.infoHash();
// Prevent showing the dialog if download is already present
auto *btSession = BitTorrent::Session::instance();
if (btSession->isKnownTorrent(infoHash))
{
BitTorrent::Torrent *const torrent = btSession->findTorrent(infoHash);
if (torrent)
{
if (torrent->isPrivate())
{
RaisedMessageBox::warning(this, tr("Torrent is already present"), tr("Torrent '%1' is already in the transfer list. Trackers haven't been merged because it is a private torrent.").arg(torrent->name()), QMessageBox::Ok);
}
else
{
bool mergeTrackers = btSession->isMergeTrackersEnabled();
if (Preferences::instance()->confirmMergeTrackers())
{
const QMessageBox::StandardButton btn = RaisedMessageBox::question(this, tr("Torrent is already present")
, tr("Torrent '%1' is already in the transfer list. Do you want to merge trackers from new source?").arg(torrent->name())
, (QMessageBox::Yes | QMessageBox::No), QMessageBox::Yes);
mergeTrackers = (btn == QMessageBox::Yes);
}
if (mergeTrackers) if (hasMetadata())
{ {
torrent->addTrackers(magnetUri.trackers()); setupTreeview();
torrent->addUrlSeeds(magnetUri.urlSeeds());
}
}
} }
else else
{ {
RaisedMessageBox::information(this, tr("Torrent is already present"), tr("Magnet link is already queued for processing."), QMessageBox::Ok); connect(BitTorrent::Session::instance(), &BitTorrent::Session::metadataDownloaded, this, &AddNewTorrentDialog::updateMetadata);
}
return false;
}
connect(btSession, &BitTorrent::Session::metadataDownloaded, this, &AddNewTorrentDialog::updateMetadata);
// Set dialog title // Set dialog title
const QString torrentName = magnetUri.name(); const QString torrentName = m_torrentDescr.name();
setWindowTitle(torrentName.isEmpty() ? tr("Magnet link") : torrentName); setWindowTitle(torrentName.isEmpty() ? tr("Magnet link") : torrentName);
updateDiskSpaceLabel(); updateDiskSpaceLabel();
TMMChanged(m_ui->comboTTM->currentIndex()); BitTorrent::Session::instance()->downloadMetadata(m_torrentDescr);
btSession->downloadMetadata(magnetUri);
setMetadataProgressIndicator(true, tr("Retrieving metadata...")); setMetadataProgressIndicator(true, tr("Retrieving metadata..."));
m_ui->labelInfohash1Data->setText(magnetUri.infoHash().v1().isValid() ? magnetUri.infoHash().v1().toString() : tr("N/A")); }
m_ui->labelInfohash2Data->setText(magnetUri.infoHash().v2().isValid() ? magnetUri.infoHash().v2().toString() : tr("N/A"));
TMMChanged(m_ui->comboTTM->currentIndex());
m_magnetURI = magnetUri;
return true; return true;
} }
void AddNewTorrentDialog::showEvent(QShowEvent *event) void AddNewTorrentDialog::showEvent(QShowEvent *event)
{ {
QDialog::showEvent(event); QDialog::showEvent(event);
if (!isTopLevel()) return; if (!isTopLevel())
return;
activateWindow(); activateWindow();
raise(); raise();
@ -661,12 +618,13 @@ void AddNewTorrentDialog::updateDiskSpaceLabel()
if (hasMetadata()) if (hasMetadata())
{ {
const auto torrentInfo = *m_torrentDescr.info();
const QVector<BitTorrent::DownloadPriority> &priorities = m_contentAdaptor->filePriorities(); const QVector<BitTorrent::DownloadPriority> &priorities = m_contentAdaptor->filePriorities();
Q_ASSERT(priorities.size() == m_torrentInfo.filesCount()); Q_ASSERT(priorities.size() == torrentInfo.filesCount());
for (int i = 0; i < priorities.size(); ++i) for (int i = 0; i < priorities.size(); ++i)
{ {
if (priorities[i] > BitTorrent::DownloadPriority::Ignored) if (priorities[i] > BitTorrent::DownloadPriority::Ignored)
torrentSize += m_torrentInfo.fileSize(i); torrentSize += torrentInfo.fileSize(i);
} }
} }
@ -734,18 +692,22 @@ void AddNewTorrentDialog::contentLayoutChanged()
void AddNewTorrentDialog::saveTorrentFile() void AddNewTorrentDialog::saveTorrentFile()
{ {
Q_ASSERT(hasMetadata()); Q_ASSERT(hasMetadata());
if (Q_UNLIKELY(!hasMetadata()))
return;
const auto torrentInfo = *m_torrentDescr.info();
const QString filter {tr("Torrent file (*%1)").arg(TORRENT_FILE_EXTENSION)}; const QString filter {tr("Torrent file (*%1)").arg(TORRENT_FILE_EXTENSION)};
Path path {QFileDialog::getSaveFileName(this, tr("Save as torrent file") Path path {QFileDialog::getSaveFileName(this, tr("Save as torrent file")
, QDir::home().absoluteFilePath(m_torrentInfo.name() + TORRENT_FILE_EXTENSION) , QDir::home().absoluteFilePath(torrentInfo.name() + TORRENT_FILE_EXTENSION)
, filter)}; , filter)};
if (path.isEmpty()) return; if (path.isEmpty()) return;
if (!path.hasExtension(TORRENT_FILE_EXTENSION)) if (!path.hasExtension(TORRENT_FILE_EXTENSION))
path += TORRENT_FILE_EXTENSION; path += TORRENT_FILE_EXTENSION;
const nonstd::expected<void, QString> result = m_torrentInfo.saveToFile(path); const auto result = m_torrentDescr.saveToFile(path);
if (!result) if (!result)
{ {
QMessageBox::critical(this, tr("I/O Error") QMessageBox::critical(this, tr("I/O Error")
@ -755,7 +717,7 @@ void AddNewTorrentDialog::saveTorrentFile()
bool AddNewTorrentDialog::hasMetadata() const bool AddNewTorrentDialog::hasMetadata() const
{ {
return m_torrentInfo.isValid(); return m_torrentDescr.info().has_value();
} }
void AddNewTorrentDialog::populateSavePaths() void AddNewTorrentDialog::populateSavePaths()
@ -882,11 +844,9 @@ void AddNewTorrentDialog::accept()
setEnabled(!m_ui->checkBoxNeverShow->isChecked()); setEnabled(!m_ui->checkBoxNeverShow->isChecked());
// Add torrent // Add torrent
if (!hasMetadata()) BitTorrent::Session::instance()->addTorrent(m_torrentDescr, m_torrentParams);
BitTorrent::Session::instance()->addTorrent(m_magnetURI, m_torrentParams);
else
BitTorrent::Session::instance()->addTorrent(m_torrentInfo, m_torrentParams);
if (m_torrentGuard)
m_torrentGuard->markAsAddedToSession(); m_torrentGuard->markAsAddedToSession();
QDialog::accept(); QDialog::accept();
} }
@ -896,7 +856,7 @@ void AddNewTorrentDialog::reject()
if (!hasMetadata()) if (!hasMetadata())
{ {
setMetadataProgressIndicator(false); setMetadataProgressIndicator(false);
BitTorrent::Session::instance()->cancelDownloadMetadata(m_magnetURI.infoHash().toTorrentID()); BitTorrent::Session::instance()->cancelDownloadMetadata(m_torrentDescr.infoHash().toTorrentID());
} }
QDialog::reject(); QDialog::reject();
@ -906,12 +866,13 @@ void AddNewTorrentDialog::updateMetadata(const BitTorrent::TorrentInfo &metadata
{ {
Q_ASSERT(metadata.isValid()); Q_ASSERT(metadata.isValid());
if (metadata.infoHash() != m_magnetURI.infoHash()) return; if (!metadata.matchesInfoHash(m_torrentDescr.infoHash()))
return;
disconnect(BitTorrent::Session::instance(), &BitTorrent::Session::metadataDownloaded, this, &AddNewTorrentDialog::updateMetadata); disconnect(BitTorrent::Session::instance(), &BitTorrent::Session::metadataDownloaded, this, &AddNewTorrentDialog::updateMetadata);
// Good to go // Good to go
m_torrentInfo = metadata; m_torrentDescr.setTorrentInfo(metadata);
setMetadataProgressIndicator(true, tr("Parsing metadata...")); setMetadataProgressIndicator(true, tr("Parsing metadata..."));
// Update UI // Update UI
@ -919,7 +880,7 @@ void AddNewTorrentDialog::updateMetadata(const BitTorrent::TorrentInfo &metadata
setMetadataProgressIndicator(false, tr("Metadata retrieval complete")); setMetadataProgressIndicator(false, tr("Metadata retrieval complete"));
m_ui->buttonSave->setVisible(true); m_ui->buttonSave->setVisible(true);
if (m_torrentInfo.infoHash().v2().isValid()) if (m_torrentDescr.infoHash().v2().isValid())
{ {
m_ui->buttonSave->setEnabled(false); m_ui->buttonSave->setEnabled(false);
m_ui->buttonSave->setToolTip(tr("Cannot create v2 torrent until its data is fully downloaded.")); m_ui->buttonSave->setToolTip(tr("Cannot create v2 torrent until its data is fully downloaded."));
@ -941,16 +902,18 @@ void AddNewTorrentDialog::setupTreeview()
return; return;
// Set dialog title // Set dialog title
setWindowTitle(m_torrentInfo.name()); setWindowTitle(m_torrentDescr.name());
const auto &torrentInfo = *m_torrentDescr.info();
// Set torrent information // Set torrent information
m_ui->labelCommentData->setText(Utils::Misc::parseHtmlLinks(m_torrentInfo.comment().toHtmlEscaped())); m_ui->labelCommentData->setText(Utils::Misc::parseHtmlLinks(torrentInfo.comment().toHtmlEscaped()));
m_ui->labelDateData->setText(!m_torrentInfo.creationDate().isNull() ? QLocale().toString(m_torrentInfo.creationDate(), QLocale::ShortFormat) : tr("Not available")); m_ui->labelDateData->setText(!torrentInfo.creationDate().isNull() ? QLocale().toString(torrentInfo.creationDate(), QLocale::ShortFormat) : tr("Not available"));
if (m_torrentParams.filePaths.isEmpty()) if (m_torrentParams.filePaths.isEmpty())
m_torrentParams.filePaths = m_torrentInfo.filePaths(); m_torrentParams.filePaths = torrentInfo.filePaths();
m_contentAdaptor = new TorrentContentAdaptor(m_torrentInfo, m_torrentParams.filePaths, m_torrentParams.filePriorities); m_contentAdaptor = new TorrentContentAdaptor(torrentInfo, m_torrentParams.filePaths, m_torrentParams.filePriorities);
const auto contentLayout = static_cast<BitTorrent::TorrentContentLayout>(m_ui->contentLayoutComboBox->currentIndex()); const auto contentLayout = static_cast<BitTorrent::TorrentContentLayout>(m_ui->contentLayoutComboBox->currentIndex());
m_contentAdaptor->applyContentLayout(contentLayout); m_contentAdaptor->applyContentLayout(contentLayout);
@ -964,7 +927,7 @@ void AddNewTorrentDialog::setupTreeview()
if (priorities[i] == BitTorrent::DownloadPriority::Ignored) if (priorities[i] == BitTorrent::DownloadPriority::Ignored)
continue; continue;
if (BitTorrent::Session::instance()->isFilenameExcluded(m_torrentInfo.filePath(i).filename())) if (BitTorrent::Session::instance()->isFilenameExcluded(torrentInfo.filePath(i).filename()))
priorities[i] = BitTorrent::DownloadPriority::Ignored; priorities[i] = BitTorrent::DownloadPriority::Ignored;
} }
@ -983,35 +946,43 @@ void AddNewTorrentDialog::handleDownloadFinished(const Net::DownloadResult &down
switch (downloadResult.status) switch (downloadResult.status)
{ {
case Net::DownloadStatus::Success: case Net::DownloadStatus::Success:
if (const auto loadResult = BitTorrent::TorrentDescriptor::load(downloadResult.data))
{ {
const nonstd::expected<BitTorrent::TorrentInfo, QString> result = BitTorrent::TorrentInfo::load(downloadResult.data); m_torrentDescr = loadResult.value();
if (!result)
{
RaisedMessageBox::critical(this, tr("Invalid torrent"), tr("Failed to load from URL: %1.\nError: %2")
.arg(downloadResult.url, result.error()));
return;
} }
m_torrentInfo = result.value();
m_torrentGuard = std::make_unique<TorrentFileGuard>();
if (loadTorrentImpl())
open();
else else
{
RaisedMessageBox::critical(this, tr("Invalid torrent")
, tr("Failed to load from URL: %1.\nError: %2").arg(downloadResult.url, loadResult.error()));
deleteLater(); deleteLater();
return;
} }
break; break;
case Net::DownloadStatus::RedirectedToMagnet: case Net::DownloadStatus::RedirectedToMagnet:
if (loadMagnet(BitTorrent::MagnetUri(downloadResult.magnet))) if (const auto parseResult = BitTorrent::TorrentDescriptor::parse(downloadResult.magnetURI))
open(); {
m_torrentDescr = parseResult.value();
}
else else
{
RaisedMessageBox::critical(this, tr("Invalid torrent")
, tr("Failed to load torrent. The request was redirected to invalid Magnet URI.\nError: %1")
.arg(parseResult.error()));
deleteLater(); deleteLater();
return;
}
break; break;
default: default:
RaisedMessageBox::critical(this, tr("Download Error"), RaisedMessageBox::critical(this, tr("Download Error")
tr("Cannot download '%1': %2").arg(downloadResult.url, downloadResult.errorString)); , tr("Cannot download '%1': %2").arg(downloadResult.url, downloadResult.errorString));
deleteLater(); deleteLater();
return;
} }
if (loadTorrentImpl())
open();
else
deleteLater();
} }
void AddNewTorrentDialog::TMMChanged(int index) void AddNewTorrentDialog::TMMChanged(int index)
@ -1046,5 +1017,6 @@ void AddNewTorrentDialog::TMMChanged(int index)
void AddNewTorrentDialog::doNotDeleteTorrentClicked(bool checked) void AddNewTorrentDialog::doNotDeleteTorrentClicked(bool checked)
{ {
if (m_torrentGuard)
m_torrentGuard->setAutoRemove(!checked); m_torrentGuard->setAutoRemove(!checked);
} }

11
src/gui/addnewtorrentdialog.h

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2022 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2022-2023 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2012 Christophe Dumez <chris@qbittorrent.org> * Copyright (C) 2012 Christophe Dumez <chris@qbittorrent.org>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
@ -34,8 +34,7 @@
#include <QDialog> #include <QDialog>
#include "base/bittorrent/addtorrentparams.h" #include "base/bittorrent/addtorrentparams.h"
#include "base/bittorrent/magneturi.h" #include "base/bittorrent/torrentdescriptor.h"
#include "base/bittorrent/torrentinfo.h"
#include "base/path.h" #include "base/path.h"
#include "base/settingvalue.h" #include "base/settingvalue.h"
@ -98,9 +97,8 @@ private:
explicit AddNewTorrentDialog(const BitTorrent::AddTorrentParams &inParams, QWidget *parent); explicit AddNewTorrentDialog(const BitTorrent::AddTorrentParams &inParams, QWidget *parent);
bool loadTorrentFile(const QString &source); bool loadTorrent(const QString &source);
bool loadTorrentImpl(); bool loadTorrentImpl();
bool loadMagnet(const BitTorrent::MagnetUri &magnetUri);
void populateSavePaths(); void populateSavePaths();
void loadState(); void loadState();
void saveState(); void saveState();
@ -113,8 +111,7 @@ private:
Ui::AddNewTorrentDialog *m_ui = nullptr; Ui::AddNewTorrentDialog *m_ui = nullptr;
TorrentContentAdaptor *m_contentAdaptor = nullptr; TorrentContentAdaptor *m_contentAdaptor = nullptr;
BitTorrent::MagnetUri m_magnetURI; BitTorrent::TorrentDescriptor m_torrentDescr;
BitTorrent::TorrentInfo m_torrentInfo;
int m_savePathIndex = -1; int m_savePathIndex = -1;
int m_downloadPathIndex = -1; int m_downloadPathIndex = -1;
bool m_useDownloadPath = false; bool m_useDownloadPath = false;

8
src/gui/torrentcreatordialog.cpp

@ -36,7 +36,7 @@
#include <QUrl> #include <QUrl>
#include "base/bittorrent/session.h" #include "base/bittorrent/session.h"
#include "base/bittorrent/torrentinfo.h" #include "base/bittorrent/torrentdescriptor.h"
#include "base/global.h" #include "base/global.h"
#include "base/utils/fs.h" #include "base/utils/fs.h"
#include "ui_torrentcreatordialog.h" #include "ui_torrentcreatordialog.h"
@ -252,8 +252,8 @@ void TorrentCreatorDialog::handleCreationSuccess(const Path &path, const Path &b
if (m_ui->checkStartSeeding->isChecked()) if (m_ui->checkStartSeeding->isChecked())
{ {
// Create save path temp data // Create save path temp data
const nonstd::expected<BitTorrent::TorrentInfo, QString> result = BitTorrent::TorrentInfo::loadFromFile(path); const auto loadResult = BitTorrent::TorrentDescriptor::loadFromFile(path);
if (!result) if (!loadResult)
{ {
QMessageBox::critical(this, tr("Torrent creation failed"), tr("Reason: Created torrent is invalid. It won't be added to download list.")); QMessageBox::critical(this, tr("Torrent creation failed"), tr("Reason: Created torrent is invalid. It won't be added to download list."));
return; return;
@ -270,7 +270,7 @@ void TorrentCreatorDialog::handleCreationSuccess(const Path &path, const Path &b
} }
params.useAutoTMM = false; // otherwise if it is on by default, it will overwrite `savePath` to the default save path params.useAutoTMM = false; // otherwise if it is on by default, it will overwrite `savePath` to the default save path
BitTorrent::Session::instance()->addTorrent(result.value(), params); BitTorrent::Session::instance()->addTorrent(loadResult.value(), params);
} }
QMessageBox::information(this, tr("Torrent creator") QMessageBox::information(this, tr("Torrent creator")
, u"%1\n%2"_s.arg(tr("Torrent created:"), path.toString())); , u"%1\n%2"_s.arg(tr("Torrent created:"), path.toString()));

16
src/webui/api/torrentscontroller.cpp

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2018 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2018-2023 Vladimir Golovnev <glassez@yandex.ru>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
@ -45,7 +45,7 @@
#include "base/bittorrent/peerinfo.h" #include "base/bittorrent/peerinfo.h"
#include "base/bittorrent/session.h" #include "base/bittorrent/session.h"
#include "base/bittorrent/torrent.h" #include "base/bittorrent/torrent.h"
#include "base/bittorrent/torrentinfo.h" #include "base/bittorrent/torrentdescriptor.h"
#include "base/bittorrent/trackerentry.h" #include "base/bittorrent/trackerentry.h"
#include "base/global.h" #include "base/global.h"
#include "base/logger.h" #include "base/logger.h"
@ -739,14 +739,14 @@ void TorrentsController::addAction()
const DataMap torrents = data(); const DataMap torrents = data();
for (auto it = torrents.constBegin(); it != torrents.constEnd(); ++it) for (auto it = torrents.constBegin(); it != torrents.constEnd(); ++it)
{ {
const nonstd::expected<BitTorrent::TorrentInfo, QString> result = BitTorrent::TorrentInfo::load(it.value()); if (const auto loadResult = BitTorrent::TorrentDescriptor::load(it.value()))
if (!result)
{ {
throw APIError(APIErrorType::BadData partialSuccess |= BitTorrent::Session::instance()->addTorrent(loadResult.value(), addTorrentParams);
, tr("Error: '%1' is not a valid torrent file.").arg(it.key())); }
else
{
throw APIError(APIErrorType::BadData, tr("Error: '%1' is not a valid torrent file.").arg(it.key()));
} }
partialSuccess |= BitTorrent::Session::instance()->addTorrent(result.value(), addTorrentParams);
} }
if (partialSuccess) if (partialSuccess)

Loading…
Cancel
Save