Move utilities to core/utils folder.

Also move the names to Utils namespace.
This commit is contained in:
Vladimir Golovnev (Glassez)
2015-05-06 14:53:27 +03:00
parent 427688cb34
commit 191cdc2849
67 changed files with 1172 additions and 1135 deletions

View File

@@ -48,10 +48,10 @@ MagnetUri::MagnetUri(const QString &url)
m_valid = true;
m_hash = m_addTorrentParams.info_hash;
m_name = String::fromStdString(m_addTorrentParams.name);
m_name = Utils::String::fromStdString(m_addTorrentParams.name);
foreach (const std::string &tracker, m_addTorrentParams.trackers)
m_trackers.append(String::fromStdString(tracker));
m_trackers.append(Utils::String::fromStdString(tracker));
#if LIBTORRENT_VERSION_NUM >= 10000
foreach (const std::string &urlSeed, m_addTorrentParams.url_seeds)

View File

@@ -202,7 +202,7 @@ PeerAddress PeerInfo::address() const
QString PeerInfo::client() const
{
return String::fromStdString(m_nativeInfo.client);
return Utils::String::fromStdString(m_nativeInfo.client);
}

View File

@@ -66,8 +66,8 @@ using namespace BitTorrent;
#include "geoipmanager.h"
#endif
#include "core/misc.h"
#include "core/fs_utils.h"
#include "core/utils/misc.h"
#include "core/utils/fs.h"
#include "core/utils/string.h"
#include "core/logger.h"
#include "core/preferences.h"
@@ -163,7 +163,7 @@ Session::Session(QObject *parent)
// Construct session
libt::fingerprint fingerprint(PEER_ID, VERSION_MAJOR, VERSION_MINOR, VERSION_BUGFIX, VERSION_BUILD);
m_nativeSession = new libt::session(fingerprint, 0);
Logger::instance()->addMessage("Peer ID: " + String::fromStdString(fingerprint.to_string()));
Logger::instance()->addMessage("Peer ID: " + Utils::String::fromStdString(fingerprint.to_string()));
m_nativeSession->set_alert_dispatch(boost::bind(&Session::dispatchAlerts, this, _1));
@@ -318,12 +318,12 @@ Session *Session::instance()
void Session::loadState()
{
const QString statePath = fsutils::cacheLocation() + QLatin1String("/ses_state");
const QString statePath = Utils::Fs::cacheLocation() + QLatin1String("/ses_state");
if (!QFile::exists(statePath)) return;
if (QFile(statePath).size() == 0) {
// Remove empty invalid state file
fsutils::forceRemove(statePath);
Utils::Fs::forceRemove(statePath);
return;
}
@@ -343,7 +343,7 @@ void Session::saveState()
{
qDebug("Saving session state to disk...");
const QString state_path = fsutils::cacheLocation() + QLatin1String("/ses_state");
const QString state_path = Utils::Fs::cacheLocation() + QLatin1String("/ses_state");
libt::entry session_state;
m_nativeSession->save_state(session_state);
std::vector<char> out;
@@ -364,7 +364,7 @@ void Session::setSessionSettings()
libt::session_settings sessionSettings = m_nativeSession->settings();
sessionSettings.user_agent = "qBittorrent " VERSION;
//std::cout << "HTTP user agent is " << sessionSettings.user_agent << std::endl;
logger->addMessage(tr("HTTP user agent is %1").arg(String::fromStdString(sessionSettings.user_agent)));
logger->addMessage(tr("HTTP user agent is %1").arg(Utils::String::fromStdString(sessionSettings.user_agent)));
sessionSettings.upnp_ignore_nonrouters = true;
sessionSettings.use_dht_as_fallback = false;
@@ -422,7 +422,7 @@ void Session::setSessionSettings()
// IP address to announce to trackers
QString announce_ip = pref->getNetworkAddress();
if (!announce_ip.isEmpty())
sessionSettings.announce_ip = String::toStdString(announce_ip);
sessionSettings.announce_ip = Utils::String::toStdString(announce_ip);
// Super seeding
sessionSettings.strict_super_seeding = pref->isSuperSeedingEnabled();
// * Max Half-open connections
@@ -668,13 +668,13 @@ void Session::configure()
libt::proxy_settings proxySettings;
if (pref->isProxyEnabled()) {
qDebug("Enabling P2P proxy");
proxySettings.hostname = String::toStdString(pref->getProxyIp());
proxySettings.hostname = Utils::String::toStdString(pref->getProxyIp());
qDebug("hostname is %s", proxySettings.hostname.c_str());
proxySettings.port = pref->getProxyPort();
qDebug("port is %d", proxySettings.port);
if (pref->isProxyAuthEnabled()) {
proxySettings.username = String::toStdString(pref->getProxyUsername());
proxySettings.password = String::toStdString(pref->getProxyPassword());
proxySettings.username = Utils::String::toStdString(pref->getProxyUsername());
proxySettings.password = Utils::String::toStdString(pref->getProxyPassword());
qDebug("username is %s", proxySettings.username.c_str());
qDebug("password is %s", proxySettings.password.c_str());
}
@@ -780,7 +780,7 @@ void Session::handleDownloadFinished(const QString &url, const QString &filePath
{
emit downloadFromUrlFinished(url);
addTorrent_impl(m_downloadedTorrents.take(url), MagnetUri(), TorrentInfo::loadFromFile(filePath));
fsutils::forceRemove(filePath); // remove temporary file
Utils::Fs::forceRemove(filePath); // remove temporary file
}
void Session::changeSpeedLimitMode(bool alternative)
@@ -870,8 +870,8 @@ bool Session::deleteTorrent(const QString &hash, bool deleteLocalFiles)
// Remove unwanted and incomplete files
foreach (const QString &unwantedFile, unwantedFiles) {
qDebug("Removing unwanted file: %s", qPrintable(unwantedFile));
fsutils::forceRemove(unwantedFile);
const QString parentFolder = fsutils::branchPath(unwantedFile);
Utils::Fs::forceRemove(unwantedFile);
const QString parentFolder = Utils::Fs::branchPath(unwantedFile);
qDebug("Attempt to remove parent folder (if empty): %s", qPrintable(parentFolder));
QDir().rmpath(parentFolder);
}
@@ -883,7 +883,7 @@ bool Session::deleteTorrent(const QString &hash, bool deleteLocalFiles)
filters << QString("%1.*").arg(torrent->hash());
const QStringList files = resumeDataDir.entryList(filters, QDir::Files, QDir::Unsorted);
foreach (const QString &file, files)
fsutils::forceRemove(resumeDataDir.absoluteFilePath(file));
Utils::Fs::forceRemove(resumeDataDir.absoluteFilePath(file));
if (deleteLocalFiles)
Logger::instance()->addMessage(tr("'%1' was removed from transfer list and hard disk.", "'xxx.avi' was removed...").arg(torrent->name()));
@@ -1038,10 +1038,10 @@ bool Session::addTorrent(QString source, const AddTorrentParams &params)
if (source.startsWith("bc://bt/", Qt::CaseInsensitive)) {
qDebug("Converting bc link to magnet link");
source = misc::bcLinkToMagnet(source);
source = Utils::Misc::bcLinkToMagnet(source);
}
if (misc::isUrl(source)) {
if (Utils::Misc::isUrl(source)) {
Logger::instance()->addMessage(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(source));
// Launch downloader
Net::DownloadHandler *handler = Net::DownloadManager::instance()->downloadUrl(source, 10485760 /* 10MB */);
@@ -1164,7 +1164,7 @@ bool Session::addTorrent_impl(const AddTorrentData &addData, const MagnetUri &ma
savePath += "/";
}
p.save_path = String::toStdString(fsutils::toNativePath(savePath));
p.save_path = Utils::String::toStdString(Utils::Fs::toNativePath(savePath));
// Check if save path exists, creating it otherwise
if (!QDir(savePath).exists())
QDir().mkpath(savePath);
@@ -1214,7 +1214,7 @@ bool Session::loadMetadata(const QString &magnetUri)
#endif
QString savePath = QString("%1/%2").arg(QDir::tempPath()).arg(hash);
p.save_path = String::toStdString(fsutils::toNativePath(savePath));
p.save_path = Utils::String::toStdString(Utils::Fs::toNativePath(savePath));
// Check if save path exists, creating it otherwise
if (!QDir(savePath).exists())
QDir().mkpath(savePath);
@@ -1253,7 +1253,7 @@ void Session::exportTorrentFile(TorrentHandle *const torrent, TorrentExportFolde
QDir exportPath(folder == TorrentExportFolder::Regular ? Preferences::instance()->getTorrentExportDir() : Preferences::instance()->getFinishedTorrentExportDir());
if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) {
QString newTorrentPath = exportPath.absoluteFilePath(torrentFilename);
if (QFile::exists(newTorrentPath) && fsutils::sameFiles(torrentPath, newTorrentPath)) {
if (QFile::exists(newTorrentPath) && Utils::Fs::sameFiles(torrentPath, newTorrentPath)) {
// Append hash to torrent name to make it unique
newTorrentPath = exportPath.absoluteFilePath(torrent->name() + "-" + torrentFilename);
}
@@ -1285,7 +1285,7 @@ void Session::exportTorrentFiles(QString path)
if (QFile::exists(srcPath)) {
QString dstPath = exportDir.absoluteFilePath(QString("%1.torrent").arg(torrent->name()));
if (QFile::exists(dstPath)) {
if (!fsutils::sameFiles(srcPath, dstPath)) {
if (!Utils::Fs::sameFiles(srcPath, dstPath)) {
dstPath = exportDir.absoluteFilePath(QString("%1-%2.torrent").arg(torrent->name()).arg(torrent->hash()));
}
else {
@@ -1375,7 +1375,7 @@ void Session::enableDHT(bool enable)
}
catch(std::exception &e) {
qDebug("Could not enable DHT, reason: %s", e.what());
logger->addMessage(tr("DHT support [OFF]. Reason: %1").arg(String::fromStdString(e.what())), Log::CRITICAL);
logger->addMessage(tr("DHT support [OFF]. Reason: %1").arg(Utils::String::fromStdString(e.what())), Log::CRITICAL);
}
}
}
@@ -1442,7 +1442,7 @@ void Session::setDefaultSavePath(const QString &path)
{
if (path.isEmpty()) return;
QString defaultSavePath = fsutils::fromNativePath(path);
QString defaultSavePath = Utils::Fs::fromNativePath(path);
if (!defaultSavePath.endsWith("/"))
defaultSavePath += "/";
if (m_defaultSavePath != defaultSavePath) {
@@ -1457,7 +1457,7 @@ void Session::setDefaultTempPath(const QString &path)
QString tempPath;
if (!path.isEmpty()) {
tempPath = fsutils::fromNativePath(path);
tempPath = Utils::Fs::fromNativePath(path);
if (!tempPath.endsWith("/"))
tempPath += "/";
}
@@ -1506,7 +1506,7 @@ void Session::setListeningPort(int port)
m_nativeSession->listen_on(ports, ec, 0, libt::session::listen_no_system_port);
if (ec)
logger->addMessage(tr("qBittorrent failed to listen on any interface port: %1. Reason: %2", "e.g: qBittorrent failed to listen on any interface port: TCP/6881. Reason: no such interface" ).arg(QString::number(port)).arg(String::fromStdString(ec.message())), Log::CRITICAL);
logger->addMessage(tr("qBittorrent failed to listen on any interface port: %1. Reason: %2", "e.g: qBittorrent failed to listen on any interface port: TCP/6881. Reason: no such interface" ).arg(QString::number(port)).arg(Utils::String::fromStdString(ec.message())), Log::CRITICAL);
return;
}
@@ -1716,7 +1716,7 @@ void Session::handleTorrentFinished(TorrentHandle *const torrent)
}
else {
qDebug("Caught error loading torrent");
Logger::instance()->addMessage(tr("Unable to decode %1 torrent file.").arg(fsutils::toNativePath(torrentFullpath)), Log::CRITICAL);
Logger::instance()->addMessage(tr("Unable to decode %1 torrent file.").arg(Utils::Fs::toNativePath(torrentFullpath)), Log::CRITICAL);
}
}
}
@@ -1773,7 +1773,7 @@ bool Session::hasPerTorrentRatioLimit() const
void Session::initResumeFolder()
{
m_resumeFolderPath = fsutils::expandPathAbs(fsutils::QDesktopServicesDataLocation() + RESUME_FOLDER);
m_resumeFolderPath = Utils::Fs::expandPathAbs(Utils::Fs::QDesktopServicesDataLocation() + RESUME_FOLDER);
QDir resumeFolderDir(m_resumeFolderPath);
if (resumeFolderDir.exists() || resumeFolderDir.mkpath(resumeFolderDir.absolutePath())) {
m_resumeFolderLock.setFileName(resumeFolderDir.absoluteFilePath("session.lock"));
@@ -1795,9 +1795,9 @@ void Session::enableIPFilter(const QString &filterPath, bool force)
connect(m_filterParser.data(), SIGNAL(IPFilterParsed(int)), SLOT(handleIPFilterParsed(int)));
connect(m_filterParser.data(), SIGNAL(IPFilterError()), SLOT(handleIPFilterError()));
}
if (m_filterPath.isEmpty() || m_filterPath != fsutils::fromNativePath(filterPath) || force) {
m_filterPath = fsutils::fromNativePath(filterPath);
m_filterParser->processFilterFile(fsutils::fromNativePath(filterPath));
if (m_filterPath.isEmpty() || m_filterPath != Utils::Fs::fromNativePath(filterPath) || force) {
m_filterPath = Utils::Fs::fromNativePath(filterPath);
m_filterParser->processFilterFile(Utils::Fs::fromNativePath(filterPath));
}
}
@@ -1824,7 +1824,7 @@ void Session::recursiveTorrentDownload(const InfoHash &hash)
Logger::instance()->addMessage(
tr("Recursive download of file %1 embedded in torrent %2"
, "Recursive download of test.torrent embedded in torrent test2")
.arg(fsutils::toNativePath(torrentRelpath)).arg(torrent->name()));
.arg(Utils::Fs::toNativePath(torrentRelpath)).arg(torrent->name()));
const QString torrentFullpath = torrent->savePath() + "/" + torrentRelpath;
AddTorrentParams params;
@@ -1857,18 +1857,18 @@ void Session::setProxySettings(libt::proxy_settings proxySettings)
QString proxy_str;
switch(proxySettings.type) {
case libt::proxy_settings::http_pw:
proxy_str = QString("http://%1:%2@%3:%4").arg(String::fromStdString(proxySettings.username)).arg(String::fromStdString(proxySettings.password))
.arg(String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
proxy_str = QString("http://%1:%2@%3:%4").arg(Utils::String::fromStdString(proxySettings.username)).arg(Utils::String::fromStdString(proxySettings.password))
.arg(Utils::String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
break;
case libt::proxy_settings::http:
proxy_str = QString("http://%1:%2").arg(String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
proxy_str = QString("http://%1:%2").arg(Utils::String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
break;
case libt::proxy_settings::socks5:
proxy_str = QString("%1:%2").arg(String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
proxy_str = QString("%1:%2").arg(Utils::String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
break;
case libt::proxy_settings::socks5_pw:
proxy_str = QString("%1:%2@%3:%4").arg(String::fromStdString(proxySettings.username)).arg(String::fromStdString(proxySettings.password))
.arg(String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
proxy_str = QString("%1:%2@%3:%4").arg(Utils::String::fromStdString(proxySettings.username)).arg(Utils::String::fromStdString(proxySettings.password))
.arg(Utils::String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
break;
default:
qDebug("Disabling HTTP communications proxy");
@@ -1930,11 +1930,11 @@ void Session::startUpTorrents()
qDebug("Starting up torrent %s ...", qPrintable(hash));
if (!addTorrent_impl(resumeData, MagnetUri(), TorrentInfo::loadFromFile(filePath), data))
logger->addMessage(tr("Unable to resume torrent '%1'.", "e.g: Unable to resume torrent 'hash'.")
.arg(fsutils::toNativePath(hash)), Log::CRITICAL);
.arg(Utils::Fs::toNativePath(hash)), Log::CRITICAL);
}
else {
logger->addMessage(tr("Unable to resume torrent '%1': torrent file not found.", "e.g: Unable to resume torrent 'hash': torrent file not found.")
.arg(fsutils::toNativePath(hash)), Log::CRITICAL);
.arg(Utils::Fs::toNativePath(hash)), Log::CRITICAL);
}
}
}
@@ -2074,7 +2074,7 @@ void Session::handleAlert(libt::alert *a)
}
}
catch (std::exception &exc) {
qWarning() << "Caught exception in readAlerts(): " << String::fromStdString(exc.what());
qWarning() << "Caught exception in readAlerts(): " << Utils::String::fromStdString(exc.what());
}
}
@@ -2090,7 +2090,7 @@ void Session::handleAddTorrentAlert(libtorrent::add_torrent_alert *p)
Logger *const logger = Logger::instance();
if (p->error) {
qDebug("/!\\ Error: Failed to add torrent!");
QString msg = String::fromStdString(p->message());
QString msg = Utils::String::fromStdString(p->message());
logger->addMessage(tr("Couldn't add torrent. Reason: %1").arg(msg), Log::WARNING);
emit addTorrentFailed(msg);
return;
@@ -2166,7 +2166,7 @@ void Session::handleTorrentDeletedAlert(libt::torrent_deleted_alert *p)
qDebug("A torrent was deleted from the hard disk, attempting to remove the root folder too...");
const QString dirpath = m_savePathsToRemove.take(p->info_hash);
qDebug() << "Removing save path: " << dirpath << "...";
bool ok = fsutils::smartRemoveEmptyFolderTree(dirpath);
bool ok = Utils::Fs::smartRemoveEmptyFolderTree(dirpath);
Q_UNUSED(ok);
qDebug() << "Folder was removed: " << ok;
}
@@ -2194,7 +2194,7 @@ void Session::handleFileErrorAlert(libt::file_error_alert *p)
// NOTE: Check this function!
TorrentHandle *const torrent = m_torrents.value(p->handle.info_hash());
if (torrent) {
QString msg = String::fromStdString(p->message());
QString msg = Utils::String::fromStdString(p->message());
Logger::instance()->addMessage(tr("An I/O error occurred, '%1' paused. %2")
.arg(torrent->name()).arg(msg));
emit fullDiskError(torrent, msg);
@@ -2203,13 +2203,13 @@ void Session::handleFileErrorAlert(libt::file_error_alert *p)
void Session::handlePortmapWarningAlert(libt::portmap_error_alert *p)
{
Logger::instance()->addMessage(tr("UPnP/NAT-PMP: Port mapping failure, message: %1").arg(String::fromStdString(p->message())), Log::CRITICAL);
Logger::instance()->addMessage(tr("UPnP/NAT-PMP: Port mapping failure, message: %1").arg(Utils::String::fromStdString(p->message())), Log::CRITICAL);
}
void Session::handlePortmapAlert(libt::portmap_alert *p)
{
qDebug("UPnP Success, msg: %s", p->message().c_str());
Logger::instance()->addMessage(tr("UPnP/NAT-PMP: Port mapping successful, message: %1").arg(String::fromStdString(p->message())), Log::INFO);
Logger::instance()->addMessage(tr("UPnP/NAT-PMP: Port mapping successful, message: %1").arg(Utils::String::fromStdString(p->message())), Log::INFO);
}
void Session::handlePeerBlockedAlert(libt::peer_blocked_alert *p)
@@ -2257,7 +2257,7 @@ void Session::handlePeerBanAlert(libt::peer_ban_alert *p)
void Session::handleUrlSeedAlert(libt::url_seed_alert *p)
{
Logger::instance()->addMessage(tr("Url seed lookup failed for url: %1, message: %2").arg(String::fromStdString(p->url)).arg(String::fromStdString(p->message())), Log::CRITICAL);
Logger::instance()->addMessage(tr("Url seed lookup failed for url: %1, message: %2").arg(Utils::String::fromStdString(p->url)).arg(Utils::String::fromStdString(p->message())), Log::CRITICAL);
}
void Session::handleListenSucceededAlert(libt::listen_succeeded_alert *p)
@@ -2304,7 +2304,7 @@ void Session::handleListenFailedAlert(libt::listen_failed_alert *p)
tr("qBittorrent failed listening on interface %1 port: %2/%3. Reason: %4",
"e.g: qBittorrent failed listening on interface 192.168.0.1 port: TCP/6881. Reason: already in use")
.arg(p->endpoint.address().to_string(ec).c_str()).arg(proto).arg(QString::number(p->endpoint.port()))
.arg(String::fromStdString(p->error.message())), Log::CRITICAL);
.arg(Utils::String::fromStdString(p->error.message())), Log::CRITICAL);
}
void Session::handleExternalIPAlert(libt::external_ip_alert *p)
@@ -2367,10 +2367,10 @@ bool loadTorrentResumeData(const QByteArray &data, AddTorrentData &out)
if ((fast.type() != libt::lazy_entry::dict_t) && !ec) return false;
out.addedTime = QDateTime::fromTime_t(fast.dict_find_int_value("qBt-addedTime"));
out.savePath = fsutils::fromNativePath(QString::fromUtf8(fast.dict_find_string_value("qBt-savePath").c_str()));
out.ratioLimit = QString::fromUtf8(fast.dict_find_string_value("qBt-ratioLimit").c_str()).toDouble();
out.label = QString::fromUtf8(fast.dict_find_string_value("qBt-label").c_str());
out.name = QString::fromUtf8(fast.dict_find_string_value("qBt-name").c_str());
out.savePath = Utils::Fs::fromNativePath(Utils::String::fromStdString(fast.dict_find_string_value("qBt-savePath")));
out.ratioLimit = Utils::String::fromStdString(fast.dict_find_string_value("qBt-ratioLimit")).toDouble();
out.label = Utils::String::fromStdString(fast.dict_find_string_value("qBt-label"));
out.name = Utils::String::fromStdString(fast.dict_find_string_value("qBt-name"));
out.hasSeedStatus = fast.dict_find_int_value("qBt-seedStatus");
out.disableTempPath = fast.dict_find_int_value("qBt-tempPathDisabled");
@@ -2384,7 +2384,7 @@ bool Session::writeResumeDataFile(TorrentHandle *const torrent, const libt::entr
QStringList filters(QString("%1.fastresume.*").arg(torrent->hash()));
const QStringList files = resumeDataDir.entryList(filters, QDir::Files, QDir::Unsorted);
foreach (const QString &file, files)
fsutils::forceRemove(resumeDataDir.absoluteFilePath(file));
Utils::Fs::forceRemove(resumeDataDir.absoluteFilePath(file));
QString filename = QString("%1.fastresume.%2").arg(torrent->hash()).arg(torrent->queuePosition());
QString filepath = resumeDataDir.absoluteFilePath(filename);

View File

@@ -44,8 +44,8 @@
#include <iostream>
#include <fstream>
#include "core/fs_utils.h"
#include "core/misc.h"
#include "core/utils/fs.h"
#include "core/utils/misc.h"
#include "core/utils/string.h"
#include "torrentcreatorthread.h"
@@ -73,10 +73,10 @@ TorrentCreatorThread::~TorrentCreatorThread()
void TorrentCreatorThread::create(const QString &inputPath, const QString &savePath, const QStringList &trackers,
const QStringList &urlSeeds, const QString &comment, bool isPrivate, int pieceSize)
{
m_inputPath = fsutils::fromNativePath(inputPath);
m_savePath = fsutils::fromNativePath(savePath);
m_inputPath = Utils::Fs::fromNativePath(inputPath);
m_savePath = Utils::Fs::fromNativePath(savePath);
if (QFile(m_savePath).exists())
fsutils::forceRemove(m_savePath);
Utils::Fs::forceRemove(m_savePath);
m_trackers = trackers;
m_urlSeeds = urlSeeds;
m_comment = comment;
@@ -105,14 +105,14 @@ void TorrentCreatorThread::run()
try {
libt::file_storage fs;
// Adding files to the torrent
libt::add_files(fs, String::toStdString(fsutils::toNativePath(m_inputPath)), fileFilter);
libt::add_files(fs, Utils::String::toStdString(Utils::Fs::toNativePath(m_inputPath)), fileFilter);
if (m_abort) return;
libt::create_torrent t(fs, m_pieceSize);
// Add url seeds
foreach (const QString &seed, m_urlSeeds)
t.add_url_seed(String::toStdString(seed.trimmed()));
t.add_url_seed(Utils::String::toStdString(seed.trimmed()));
int tier = 0;
bool newline = false;
@@ -124,14 +124,14 @@ void TorrentCreatorThread::run()
newline = true;
continue;
}
t.add_tracker(String::toStdString(tracker.trimmed()), tier);
t.add_tracker(Utils::String::toStdString(tracker.trimmed()), tier);
newline = false;
}
if (m_abort) return;
// calculate the hash for all pieces
const QString parentPath = fsutils::branchPath(m_inputPath) + "/";
libt::set_piece_hashes(t, String::toStdString(fsutils::toNativePath(parentPath)), boost::bind(&TorrentCreatorThread::sendProgressSignal, this, _1, t.num_pieces()));
const QString parentPath = Utils::Fs::branchPath(m_inputPath) + "/";
libt::set_piece_hashes(t, Utils::String::toStdString(Utils::Fs::toNativePath(parentPath)), boost::bind(&TorrentCreatorThread::sendProgressSignal, this, _1, t.num_pieces()));
// Set qBittorrent as creator and add user comment to
// torrent_info structure
t.set_creator(creator_str.toUtf8().constData());
@@ -144,12 +144,12 @@ void TorrentCreatorThread::run()
qDebug("Saving to %s", qPrintable(m_savePath));
#ifdef _MSC_VER
wchar_t *savePathW = new wchar_t[m_savePath.length() + 1];
int len = fsutils::toNativePath(m_savePath).toWCharArray(savePathW);
int len = Utils::Fs::toNativePath(m_savePath).toWCharArray(savePathW);
savePathW[len] = L'\0';
std::ofstream outfile(savePathW, std::ios_base::out | std::ios_base::binary);
delete[] savePathW;
#else
std::ofstream outfile(fsutils::toNativePath(m_savePath).toLocal8Bit().constData(), std::ios_base::out | std::ios_base::binary);
std::ofstream outfile(Utils::Fs::toNativePath(m_savePath).toLocal8Bit().constData(), std::ios_base::out | std::ios_base::binary);
#endif
if (outfile.fail())
throw std::exception();
@@ -161,6 +161,6 @@ void TorrentCreatorThread::run()
emit creationSuccess(m_savePath, parentPath);
}
catch (std::exception& e) {
emit creationFailure(String::fromStdString(e.what()));
emit creationFailure(Utils::String::fromStdString(e.what()));
}
}

View File

@@ -45,11 +45,11 @@
#include <Windows.h>
#endif
#include "core/fs_utils.h"
#include "core/misc.h"
#include "core/logger.h"
#include "core/preferences.h"
#include "core/utils/string.h"
#include "core/utils/fs.h"
#include "core/utils/misc.h"
#include "session.h"
#include "peerinfo.h"
#include "trackerentry.h"
@@ -186,7 +186,7 @@ TorrentHandle::TorrentHandle(Session *session, const libtorrent::torrent_handle
, m_state(TorrentState::Unknown)
, m_name(data.name)
, m_addedTime(data.resumed ? data.addedTime : QDateTime::currentDateTime())
, m_savePath(fsutils::toNativePath(data.savePath))
, m_savePath(Utils::Fs::toNativePath(data.savePath))
, m_label(data.label)
, m_hasSeedStatus(data.resumed ? data.hasSeedStatus : false)
, m_ratioLimit(data.resumed ? data.ratioLimit : (data.ignoreShareRatio ? NO_RATIO_LIMIT : USE_GLOBAL_RATIO))
@@ -230,7 +230,7 @@ QString TorrentHandle::name() const
#if LIBTORRENT_VERSION_NUM < 10000
name = m_nativeName;
#else
name = String::fromStdString(m_nativeStatus.name);
name = Utils::String::fromStdString(m_nativeStatus.name);
#endif
}
@@ -293,12 +293,12 @@ qlonglong TorrentHandle::wastedSize() const
QString TorrentHandle::currentTracker() const
{
return String::fromStdString(m_nativeStatus.current_tracker);
return Utils::String::fromStdString(m_nativeStatus.current_tracker);
}
QString TorrentHandle::savePath() const
{
return fsutils::fromNativePath(m_savePath);
return Utils::Fs::fromNativePath(m_savePath);
}
QString TorrentHandle::rootPath() const
@@ -318,13 +318,13 @@ QString TorrentHandle::nativeActualSavePath() const
#if LIBTORRENT_VERSION_NUM < 10000
return m_nativeSavePath;
#else
return String::fromStdString(m_nativeStatus.save_path);
return Utils::String::fromStdString(m_nativeStatus.save_path);
#endif
}
QString TorrentHandle::actualSavePath() const
{
return fsutils::fromNativePath(nativeActualSavePath());
return Utils::Fs::fromNativePath(nativeActualSavePath());
}
QList<TrackerEntry> TorrentHandle::trackers() const
@@ -437,7 +437,7 @@ bool TorrentHandle::addUrlSeed(const QUrl &urlSeed)
QList<QUrl> seeds = urlSeeds();
if (seeds.contains(urlSeed)) return false;
SAFE_CALL_BOOL(add_url_seed, String::toStdString(urlSeed.toString()));
SAFE_CALL_BOOL(add_url_seed, Utils::String::toStdString(urlSeed.toString()));
}
bool TorrentHandle::removeUrlSeed(const QUrl &urlSeed)
@@ -445,13 +445,13 @@ bool TorrentHandle::removeUrlSeed(const QUrl &urlSeed)
QList<QUrl> seeds = urlSeeds();
if (!seeds.contains(urlSeed)) return false;
SAFE_CALL_BOOL(remove_url_seed, String::toStdString(urlSeed.toString()));
SAFE_CALL_BOOL(remove_url_seed, Utils::String::toStdString(urlSeed.toString()));
}
bool TorrentHandle::connectPeer(const PeerAddress &peerAddress)
{
libt::error_code ec;
libt::address addr = libt::address::from_string(String::toStdString(peerAddress.ip.toString()), ec);
libt::address addr = libt::address::from_string(Utils::String::toStdString(peerAddress.ip.toString()), ec);
if (ec) return false;
libt::asio::ip::tcp::endpoint ep(addr, peerAddress.port);
@@ -479,7 +479,7 @@ QString TorrentHandle::savePathParsed() const
else
p = savePath();
return fsutils::toNativePath(p);
return Utils::Fs::toNativePath(p);
}
int TorrentHandle::filesCount() const
@@ -544,7 +544,7 @@ QString TorrentHandle::filePath(int index) const
QString TorrentHandle::fileName(int index) const
{
if (!hasMetadata()) return QString();
return fsutils::fileName(filePath(index));
return Utils::Fs::fileName(filePath(index));
}
qlonglong TorrentHandle::fileSize(int index) const
@@ -561,7 +561,7 @@ QStringList TorrentHandle::absoluteFilePaths() const
QDir saveDir(actualSavePath());
QStringList res;
for (int i = 0; i < filesCount(); ++i)
res << fsutils::expandPathAbs(saveDir.absoluteFilePath(filePath(i)));
res << Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(filePath(i)));
return res;
}
@@ -577,7 +577,7 @@ QStringList TorrentHandle::absoluteFilePathsUnwanted() const
int count = static_cast<int>(fp.size());
for (int i = 0; i < count; ++i) {
if (fp[i] == 0) {
const QString path = fsutils::expandPathAbs(saveDir.absoluteFilePath(filePath(i)));
const QString path = Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(filePath(i)));
if (path.contains(".unwanted"))
res << path;
}
@@ -720,8 +720,8 @@ bool TorrentHandle::hasFirstLastPiecePriority() const
bool found = false;
int count = static_cast<int>(fp.size());
for (int i = 0; i < count; ++i) {
const QString ext = fsutils::fileExtension(filePath(i));
if (misc::isPreviewable(ext) && (fp[i] > 0)) {
const QString ext = Utils::Fs::fileExtension(filePath(i));
if (Utils::Misc::isPreviewable(ext) && (fp[i] > 0)) {
extremities = fileExtremityPieces(i);
found = true;
break;
@@ -824,7 +824,7 @@ int TorrentHandle::queuePosition() const
QString TorrentHandle::error() const
{
return String::fromStdString(m_nativeStatus.error);
return Utils::String::fromStdString(m_nativeStatus.error);
}
qlonglong TorrentHandle::totalDownload() const
@@ -1114,7 +1114,7 @@ void TorrentHandle::move(QString path)
// even if new path same as default.
m_useDefaultSavePath = false;
path = fsutils::toNativePath(path);
path = Utils::Fs::toNativePath(path);
if (path == savePath()) return;
if (!useTempPath()) {
@@ -1183,8 +1183,8 @@ void TorrentHandle::setFirstLastPiecePriority(bool b)
int nbfiles = static_cast<int>(fp.size());
for (int index = 0; index < nbfiles; ++index) {
const QString path = filePath(index);
const QString ext = fsutils::fileExtension(path);
if (misc::isPreviewable(ext) && (fp[index] > 0)) {
const QString ext = Utils::Fs::fileExtension(path);
if (Utils::Misc::isPreviewable(ext) && (fp[index] > 0)) {
qDebug() << "File" << path << "is previewable, toggle downloading of first/last pieces first";
// Determine the priority to set
int prio = b ? 7 : fp[index];
@@ -1258,7 +1258,7 @@ void TorrentHandle::setTrackerLogin(const QString &username, const QString &pass
void TorrentHandle::renameFile(int index, const QString &name)
{
qDebug() << Q_FUNC_INFO << index << name;
SAFE_CALL(rename_file, index, String::toStdString(fsutils::toNativePath(name)));
SAFE_CALL(rename_file, index, Utils::String::toStdString(Utils::Fs::toNativePath(name)));
}
bool TorrentHandle::saveTorrentFile(const QString &path)
@@ -1307,7 +1307,7 @@ void TorrentHandle::handleStorageMovedAlert(libtorrent::storage_moved_alert *p)
return;
}
QString newPath = String::fromStdString(p->path);
QString newPath = Utils::String::fromStdString(p->path);
if (newPath != m_newPath) {
qWarning("TorrentHandleImpl::handleStorageMoved(): New path doesn't match a path in a queue.");
return;
@@ -1328,7 +1328,7 @@ void TorrentHandle::handleStorageMovedAlert(libtorrent::storage_moved_alert *p)
}
// Attempt to remove old folder if empty
QDir oldSaveDir(fsutils::fromNativePath(m_oldPath));
QDir oldSaveDir(Utils::Fs::fromNativePath(m_oldPath));
if ((oldSaveDir != QDir(m_session->defaultSavePath())) && (oldSaveDir != QDir(m_session->tempPath()))) {
qDebug("Attempting to remove %s", qPrintable(m_oldPath));
QDir().rmpath(m_oldPath);
@@ -1348,7 +1348,7 @@ void TorrentHandle::handleStorageMovedFailedAlert(libtorrent::storage_moved_fail
}
Logger::instance()->addMessage(tr("Could not move torrent: '%1'. Reason: %2")
.arg(name()).arg(String::fromStdString(p->message())), Log::CRITICAL);
.arg(name()).arg(Utils::String::fromStdString(p->message())), Log::CRITICAL);
m_newPath.clear();
if (!m_queuedPath.isEmpty()) {
@@ -1364,7 +1364,7 @@ void TorrentHandle::handleStorageMovedFailedAlert(libtorrent::storage_moved_fail
void TorrentHandle::handleTrackerReplyAlert(libtorrent::tracker_reply_alert *p)
{
QString trackerUrl = String::fromStdString(p->url);
QString trackerUrl = Utils::String::fromStdString(p->url);
qDebug("Received a tracker reply from %s (Num_peers = %d)", qPrintable(trackerUrl), p->num_peers);
// Connection was successful now. Remove possible old errors
m_trackerInfos[trackerUrl].lastMessage.clear(); // Reset error/warning message
@@ -1375,8 +1375,8 @@ void TorrentHandle::handleTrackerReplyAlert(libtorrent::tracker_reply_alert *p)
void TorrentHandle::handleTrackerWarningAlert(libtorrent::tracker_warning_alert *p)
{
QString trackerUrl = String::fromStdString(p->url);
QString message = String::fromStdString(p->msg);
QString trackerUrl = Utils::String::fromStdString(p->url);
QString message = Utils::String::fromStdString(p->msg);
qDebug("Received a tracker warning for %s: %s", qPrintable(trackerUrl), qPrintable(message));
// Connection was successful now but there is a warning message
m_trackerInfos[trackerUrl].lastMessage = message; // Store warning message
@@ -1386,8 +1386,8 @@ void TorrentHandle::handleTrackerWarningAlert(libtorrent::tracker_warning_alert
void TorrentHandle::handleTrackerErrorAlert(libtorrent::tracker_error_alert *p)
{
QString trackerUrl = String::fromStdString(p->url);
QString message = String::fromStdString(p->msg);
QString trackerUrl = Utils::String::fromStdString(p->url);
QString message = Utils::String::fromStdString(p->msg);
qDebug("Received a tracker error for %s: %s", qPrintable(trackerUrl), qPrintable(message));
m_trackerInfos[trackerUrl].lastMessage = message;
@@ -1487,13 +1487,13 @@ void TorrentHandle::handleFastResumeRejectedAlert(libtorrent::fastresume_rejecte
}
else {
logger->addMessage(tr("Fast resume data was rejected for torrent %1. Reason: %2. Checking again...")
.arg(name()).arg(String::fromStdString(p->message())), Log::CRITICAL);
.arg(name()).arg(Utils::String::fromStdString(p->message())), Log::CRITICAL);
}
}
void TorrentHandle::handleFileRenamedAlert(libtorrent::file_renamed_alert *p)
{
QString newName = fsutils::fromNativePath(String::fromStdString(p->name));
QString newName = Utils::Fs::fromNativePath(Utils::String::fromStdString(p->name));
// TODO: Check this!
if (filesCount() > 1) {
@@ -1573,7 +1573,7 @@ void TorrentHandle::adjustSavePath()
QString defaultSavePath = m_session->defaultSavePath();
if (m_session->useAppendLabelToSavePath() && !m_label.isEmpty())
defaultSavePath += QString("%1/").arg(m_label);
defaultSavePath = fsutils::toNativePath(defaultSavePath);
defaultSavePath = Utils::Fs::toNativePath(defaultSavePath);
if (m_savePath != defaultSavePath) {
if (!useTempPath()) {
moveStorage(defaultSavePath);
@@ -1702,7 +1702,7 @@ void TorrentHandle::adjustActualSavePath()
qDebug("Moving torrent to its temp save path: %s", qPrintable(path));
}
moveStorage(fsutils::toNativePath(path));
moveStorage(Utils::Fs::toNativePath(path));
}
libtorrent::torrent_handle TorrentHandle::nativeHandle() const
@@ -1764,8 +1764,8 @@ void TorrentHandle::updateStatus(const libtorrent::torrent_status &nativeStatus)
m_nativeStatus = nativeStatus;
#if LIBTORRENT_VERSION_NUM < 10000
try {
m_nativeName = String::fromStdString(m_nativeHandle.name());
m_nativeSavePath = fsutils::fromNativePath(String::fromStdString(m_nativeHandle.save_path()));
m_nativeName = Utils::String::fromStdString(m_nativeHandle.name());
m_nativeSavePath = Utils::Fs::fromNativePath(Utils::String::fromStdString(m_nativeHandle.save_path()));
}
catch (std::exception &exc) {
qDebug("torrent_handle method inside TorrentHandleImpl::updateStatus() throws exception: %s", exc.what());
@@ -1835,11 +1835,11 @@ void TorrentHandle::prioritizeFiles(const QVector<int> &priorities)
// Move unwanted files to a .unwanted subfolder
if (priorities[i] == 0) {
QString oldAbsPath = QDir(spath).absoluteFilePath(filepath);
QString parentAbsPath = fsutils::branchPath(oldAbsPath);
QString parentAbsPath = Utils::Fs::branchPath(oldAbsPath);
// Make sure the file does not already exists
if (QDir(parentAbsPath).dirName() != ".unwanted") {
QString unwantedAbsPath = parentAbsPath + "/.unwanted";
QString newAbsPath = unwantedAbsPath + "/" + fsutils::fileName(filepath);
QString newAbsPath = unwantedAbsPath + "/" + Utils::Fs::fileName(filepath);
qDebug() << "Unwanted path is" << unwantedAbsPath;
if (QFile::exists(newAbsPath)) {
qWarning() << "File" << newAbsPath << "already exists at destination.";
@@ -1852,25 +1852,25 @@ void TorrentHandle::prioritizeFiles(const QVector<int> &priorities)
if (created) {
// Hide the folder on Windows
qDebug() << "Hiding folder (Windows)";
std::wstring winPath = fsutils::toNativePath(unwantedAbsPath).toStdWString();
std::wstring winPath = Utils::Fs::toNativePath(unwantedAbsPath).toStdWString();
DWORD dwAttrs = ::GetFileAttributesW(winPath.c_str());
bool ret = ::SetFileAttributesW(winPath.c_str(), dwAttrs | FILE_ATTRIBUTE_HIDDEN);
Q_ASSERT(ret != 0); Q_UNUSED(ret);
}
#endif
QString parentPath = fsutils::branchPath(filepath);
QString parentPath = Utils::Fs::branchPath(filepath);
if (!parentPath.isEmpty() && !parentPath.endsWith("/"))
parentPath += "/";
renameFile(i, parentPath + ".unwanted/" + fsutils::fileName(filepath));
renameFile(i, parentPath + ".unwanted/" + Utils::Fs::fileName(filepath));
}
}
// Move wanted files back to their original folder
if (priorities[i] > 0) {
QString parentRelPath = fsutils::branchPath(filepath);
QString parentRelPath = Utils::Fs::branchPath(filepath);
if (QDir(parentRelPath).dirName() == ".unwanted") {
QString oldName = fsutils::fileName(filepath);
QString newRelPath = fsutils::branchPath(parentRelPath);
QString oldName = Utils::Fs::fileName(filepath);
QString newRelPath = Utils::Fs::branchPath(parentRelPath);
if (newRelPath.isEmpty())
renameFile(i, oldName);
else

View File

@@ -34,8 +34,8 @@
#include <libtorrent/error_code.hpp>
#include <libtorrent/magnet_uri.hpp>
#include "core/misc.h"
#include "core/fs_utils.h"
#include "core/utils/misc.h"
#include "core/utils/fs.h"
#include "core/utils/string.h"
#include "infohash.h"
#include "trackerentry.h"
@@ -64,7 +64,7 @@ TorrentInfo TorrentInfo::loadFromFile(const QString &path, QString &error)
{
error.clear();
libt::error_code ec;
TorrentInfo info(new libt::torrent_info(String::toStdString(fsutils::toNativePath(path)), ec));
TorrentInfo info(new libt::torrent_info(Utils::String::toStdString(Utils::Fs::toNativePath(path)), ec));
if (ec) {
error = QString::fromUtf8(ec.message().c_str());
qDebug("Cannot load .torrent file: %s", qPrintable(error));
@@ -93,7 +93,7 @@ InfoHash TorrentInfo::hash() const
QString TorrentInfo::name() const
{
if (!isValid()) return QString();
return String::fromStdString(m_nativeInfo->name());
return Utils::String::fromStdString(m_nativeInfo->name());
}
QDateTime TorrentInfo::creationDate() const
@@ -106,13 +106,13 @@ QDateTime TorrentInfo::creationDate() const
QString TorrentInfo::creator() const
{
if (!isValid()) return QString();
return String::fromStdString(m_nativeInfo->creator());
return Utils::String::fromStdString(m_nativeInfo->creator());
}
QString TorrentInfo::comment() const
{
if (!isValid()) return QString();
return String::fromStdString(m_nativeInfo->comment());
return Utils::String::fromStdString(m_nativeInfo->comment());
}
bool TorrentInfo::isPrivate() const
@@ -148,7 +148,7 @@ int TorrentInfo::piecesCount() const
QString TorrentInfo::filePath(int index) const
{
if (!isValid()) return QString();
return fsutils::fromNativePath(String::fromStdString(m_nativeInfo->files().file_path(index)));
return Utils::Fs::fromNativePath(Utils::String::fromStdString(m_nativeInfo->files().file_path(index)));
}
QStringList TorrentInfo::filePaths() const
@@ -162,13 +162,13 @@ QStringList TorrentInfo::filePaths() const
QString TorrentInfo::fileName(int index) const
{
return fsutils::fileName(filePath(index));
return Utils::Fs::fileName(filePath(index));
}
QString TorrentInfo::origFilePath(int index) const
{
if (!isValid()) return QString();
return fsutils::fromNativePath(String::fromStdString(m_nativeInfo->orig_files().file_path(index)));
return Utils::Fs::fromNativePath(Utils::String::fromStdString(m_nativeInfo->orig_files().file_path(index)));
}
qlonglong TorrentInfo::fileSize(int index) const
@@ -215,13 +215,13 @@ QByteArray TorrentInfo::metadata() const
QString TorrentInfo::toMagnetUri() const
{
if (!isValid()) return QString();
return String::fromStdString(libt::make_magnet_uri(*m_nativeInfo));
return Utils::String::fromStdString(libt::make_magnet_uri(*m_nativeInfo));
}
void TorrentInfo::renameFile(uint index, const QString &newPath)
{
if (!isValid()) return;
m_nativeInfo->rename_file(index, String::toStdString(newPath));
m_nativeInfo->rename_file(index, Utils::String::toStdString(newPath));
}
boost::intrusive_ptr<libtorrent::torrent_info> TorrentInfo::nativeInfo() const

View File

@@ -65,8 +65,8 @@ libtorrent::entry Peer::toEntry(bool noPeerId) const
{
libtorrent::entry::dictionary_type peerMap;
if (!noPeerId)
peerMap["id"] = libtorrent::entry(String::toStdString(peerId));
peerMap["ip"] = libtorrent::entry(String::toStdString(ip));
peerMap["id"] = libtorrent::entry(Utils::String::toStdString(peerId));
peerMap["ip"] = libtorrent::entry(Utils::String::toStdString(ip));
peerMap["port"] = libtorrent::entry(port);
return libtorrent::entry(peerMap);

View File

@@ -28,14 +28,14 @@
#include <QString>
#include "core/misc.h"
#include "core/utils/misc.h"
#include "core/utils/string.h"
#include "trackerentry.h"
using namespace BitTorrent;
TrackerEntry::TrackerEntry(const QString &url)
: m_nativeEntry(libtorrent::announce_entry(String::toStdString(url)))
: m_nativeEntry(libtorrent::announce_entry(Utils::String::toStdString(url)))
{
}
@@ -51,7 +51,7 @@ TrackerEntry::TrackerEntry(const TrackerEntry &other)
QString TrackerEntry::url() const
{
return String::fromStdString(m_nativeEntry.url);
return Utils::String::fromStdString(m_nativeEntry.url);
}
int TrackerEntry::tier() const