Allow to save downloaded metadata as torrent file

This commit is contained in:
Vladimir Golovnev (Glassez)
2020-02-19 13:19:51 +03:00
parent 06ceac4cda
commit dd0cee44c1
8 changed files with 110 additions and 63 deletions

View File

@@ -32,6 +32,8 @@
#include <boost/optional.hpp>
#endif
#include <libtorrent/bencode.hpp>
#include <libtorrent/create_torrent.hpp>
#include <libtorrent/error_code.hpp>
#include <QByteArray>
@@ -42,6 +44,7 @@
#include <QStringList>
#include <QUrl>
#include "base/exceptions.h"
#include "base/global.h"
#include "base/utils/fs.h"
#include "base/utils/misc.h"
@@ -151,6 +154,27 @@ TorrentInfo TorrentInfo::loadFromFile(const QString &path, QString *error) noexc
return load(data, error);
}
void TorrentInfo::saveToFile(const QString &path) const
{
if (!isValid())
throw RuntimeError {tr("Invalid metadata.")};
#if (LIBTORRENT_VERSION_NUM < 10200)
const lt::create_torrent torrentCreator = lt::create_torrent(*(nativeInfo()), true);
#else
const lt::create_torrent torrentCreator = lt::create_torrent(*(nativeInfo()));
#endif
const lt::entry torrentEntry = torrentCreator.generate();
QByteArray out;
out.reserve(1024 * 1024); // most torrent file sizes are under 1 MB
lt::bencode(std::back_inserter(out), torrentEntry);
QFile torrentFile{path};
if (!torrentFile.open(QIODevice::WriteOnly) || (torrentFile.write(out) != out.size()))
throw RuntimeError {torrentFile.errorString()};
}
bool TorrentInfo::isValid() const
{
return (m_nativeInfo && m_nativeInfo->is_valid() && (m_nativeInfo->num_files() > 0));