Started code clean up and optimization

This commit is contained in:
Christophe Dumez 2010-03-03 17:27:25 +00:00
parent 4efeb66b73
commit 7d0581a7a5
8 changed files with 182 additions and 199 deletions

View file

@ -62,10 +62,9 @@
#include <libtorrent/torrent_info.hpp> #include <libtorrent/torrent_info.hpp>
#include <boost/filesystem/exception.hpp> #include <boost/filesystem/exception.hpp>
#define MAX_TRACKER_ERRORS 2 const int MAX_TRACKER_ERRORS = 2;
#define MAX_RATIO 100. const float MAX_RATIO = 100.;
enum ProxyType {HTTP=1, SOCKS5=2, HTTP_PW=3, SOCKS5_PW=4, SOCKS4=5}; enum ProxyType {HTTP=1, SOCKS5=2, HTTP_PW=3, SOCKS5_PW=4, SOCKS4=5};
enum VersionType { NORMAL,ALPHA,BETA,RELEASE_CANDIDATE,DEVEL }; enum VersionType { NORMAL,ALPHA,BETA,RELEASE_CANDIDATE,DEVEL };
// Main constructor // Main constructor
@ -75,11 +74,10 @@ Bittorrent::Bittorrent()
UPnPEnabled(false), NATPMPEnabled(false), LSDEnabled(false), UPnPEnabled(false), NATPMPEnabled(false), LSDEnabled(false),
DHTEnabled(false), current_dht_port(0), queueingEnabled(false), DHTEnabled(false), current_dht_port(0), queueingEnabled(false),
torrentExport(false), exiting(false) torrentExport(false), exiting(false)
{
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
geoipDBLoaded = false; , geoipDBLoaded(false), resolve_countries(false)
resolve_countries = false;
#endif #endif
{
// To avoid some exceptions // To avoid some exceptions
fs::path::default_name_check(fs::no_check); fs::path::default_name_check(fs::no_check);
// For backward compatibility // For backward compatibility
@ -191,7 +189,7 @@ Bittorrent::~Bittorrent() {
} }
void Bittorrent::preAllocateAllFiles(bool b) { void Bittorrent::preAllocateAllFiles(bool b) {
bool change = (preAllocateAll != b); const bool change = (preAllocateAll != b);
if(change) { if(change) {
qDebug("PreAllocateAll changed, reloading all torrents!"); qDebug("PreAllocateAll changed, reloading all torrents!");
preAllocateAll = b; preAllocateAll = b;
@ -203,14 +201,13 @@ void Bittorrent::deleteBigRatios() {
std::vector<torrent_handle> torrents = getTorrents(); std::vector<torrent_handle> torrents = getTorrents();
std::vector<torrent_handle>::iterator torrentIT; std::vector<torrent_handle>::iterator torrentIT;
for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) {
QTorrentHandle h = QTorrentHandle(*torrentIT); const QTorrentHandle &h(*torrentIT);
if(!h.is_valid()) continue; if(!h.is_valid()) continue;
if(h.is_seed()) { if(h.is_seed()) {
QString hash = h.hash(); const QString hash = h.hash();
float ratio = getRealRatio(hash); const float ratio = getRealRatio(hash);
if(ratio <= MAX_RATIO && ratio > ratio_limit) { if(ratio <= MAX_RATIO && ratio > ratio_limit) {
QString fileName = h.name(); addConsoleMessage(tr("%1 reached the maximum ratio you set.").arg(h.name()));
addConsoleMessage(tr("%1 reached the maximum ratio you set.").arg(fileName));
deleteTorrent(hash); deleteTorrent(hash);
//emit torrent_ratio_deleted(fileName); //emit torrent_ratio_deleted(fileName);
} }
@ -240,8 +237,8 @@ void Bittorrent::setUploadLimit(QString hash, long val) {
void Bittorrent::handleDownloadFailure(QString url, QString reason) { void Bittorrent::handleDownloadFailure(QString url, QString reason) {
emit downloadFromUrlFailure(url, reason); emit downloadFromUrlFailure(url, reason);
// Clean up // Clean up
QUrl qurl = QUrl::fromEncoded(url.toLocal8Bit()); const QUrl &qurl = QUrl::fromEncoded(url.toLocal8Bit());
int index = url_skippingDlg.indexOf(qurl); const int index = url_skippingDlg.indexOf(qurl);
if(index >= 0) if(index >= 0)
url_skippingDlg.removeAt(index); url_skippingDlg.removeAt(index);
if(savepath_fromurl.contains(qurl)) if(savepath_fromurl.contains(qurl))
@ -286,7 +283,7 @@ void Bittorrent::configureSession() {
m_scanFolders->setDownloadAtPath(i, downloadInDirList.at(i).toBool()); m_scanFolders->setDownloadAtPath(i, downloadInDirList.at(i).toBool());
} }
// * Export Dir // * Export Dir
bool newTorrentExport = Preferences::isTorrentExportEnabled(); const bool newTorrentExport = Preferences::isTorrentExportEnabled();
if(torrentExport != newTorrentExport) { if(torrentExport != newTorrentExport) {
torrentExport = newTorrentExport; torrentExport = newTorrentExport;
if(torrentExport) { if(torrentExport) {
@ -296,14 +293,14 @@ void Bittorrent::configureSession() {
} }
// Connection // Connection
// * Ports binding // * Ports binding
unsigned short old_listenPort = getListenPort(); const unsigned short old_listenPort = getListenPort();
unsigned short new_listenPort = Preferences::getSessionPort(); const unsigned short new_listenPort = Preferences::getSessionPort();
if(old_listenPort != new_listenPort) { if(old_listenPort != new_listenPort) {
setListeningPort(new_listenPort); setListeningPort(new_listenPort);
addConsoleMessage(tr("qBittorrent is bound to port: TCP/%1", "e.g: qBittorrent is bound to port: 6881").arg( misc::toQString(new_listenPort))); addConsoleMessage(tr("qBittorrent is bound to port: TCP/%1", "e.g: qBittorrent is bound to port: 6881").arg(QString::number(new_listenPort)));
} }
// * Global download limit // * Global download limit
bool alternative_speeds = Preferences::isAltBandwidthEnabled(); const bool alternative_speeds = Preferences::isAltBandwidthEnabled();
int down_limit; int down_limit;
if(alternative_speeds) if(alternative_speeds)
down_limit = Preferences::getAltGlobalDownloadLimit(); down_limit = Preferences::getAltGlobalDownloadLimit();
@ -341,7 +338,7 @@ void Bittorrent::configureSession() {
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
// Resolve countries // Resolve countries
qDebug("Loading country resolution settings"); qDebug("Loading country resolution settings");
bool new_resolv_countries = Preferences::resolvePeerCountries(); const bool new_resolv_countries = Preferences::resolvePeerCountries();
if(resolve_countries != new_resolv_countries) { if(resolve_countries != new_resolv_countries) {
qDebug("in country reoslution settings"); qDebug("in country reoslution settings");
resolve_countries = new_resolv_countries; resolve_countries = new_resolv_countries;
@ -384,7 +381,7 @@ void Bittorrent::configureSession() {
QString version = Preferences::getClientVersion().replace(".", ""); QString version = Preferences::getClientVersion().replace(".", "");
while(version.size() < 4) while(version.size() < 4)
version.append("0"); version.append("0");
QString build = Preferences::getClientBuild(); const QString build = Preferences::getClientBuild();
sessionSettings.user_agent = QString("uTorrent/"+version+"("+build+")").toStdString(); sessionSettings.user_agent = QString("uTorrent/"+version+"("+build+")").toStdString();
} else { } else {
if(peer_id == "AZ") { if(peer_id == "AZ") {
@ -483,7 +480,7 @@ void Bittorrent::configureSession() {
addConsoleMessage(tr("Local Peer Discovery support [OFF]"), QString::fromUtf8("blue")); addConsoleMessage(tr("Local Peer Discovery support [OFF]"), QString::fromUtf8("blue"));
} }
// * Encryption // * Encryption
int encryptionState = Preferences::getEncryptionSetting(); const int encryptionState = Preferences::getEncryptionSetting();
// The most secure, rc4 only so that all streams and encrypted // The most secure, rc4 only so that all streams and encrypted
pe_settings encryptionSettings; pe_settings encryptionSettings;
encryptionSettings.allowed_enc_level = pe_settings::rc4; encryptionSettings.allowed_enc_level = pe_settings::rc4;
@ -518,9 +515,9 @@ void Bittorrent::configureSession() {
} }
// Update Web UI // Update Web UI
if (Preferences::isWebUiEnabled()) { if (Preferences::isWebUiEnabled()) {
quint16 port = Preferences::getWebUiPort(); const quint16 port = Preferences::getWebUiPort();
QString username = Preferences::getWebUiUsername(); const QString username = Preferences::getWebUiUsername();
QString password = Preferences::getWebUiPassword(); const QString password = Preferences::getWebUiPassword();
initWebUi(username, password, port); initWebUi(username, password, port);
} else if(httpServer) { } else if(httpServer) {
delete httpServer; delete httpServer;
@ -635,7 +632,7 @@ void Bittorrent::useAlternativeSpeedsLimit(bool alternative) {
void Bittorrent::takeETASamples() { void Bittorrent::takeETASamples() {
bool change = false;; bool change = false;;
foreach(const QString &hash, ETA_samples.keys()) { foreach(const QString &hash, ETA_samples.keys()) {
QTorrentHandle h = getTorrentHandle(hash); const QTorrentHandle &h = getTorrentHandle(hash);
if(h.is_valid() && !h.is_paused() && !h.is_seed()) { if(h.is_valid() && !h.is_paused() && !h.is_seed()) {
QList<int> samples = ETA_samples.value(h.hash(), QList<int>()); QList<int> samples = ETA_samples.value(h.hash(), QList<int>());
if(samples.size() >= MAX_SAMPLES) if(samples.size() >= MAX_SAMPLES)
@ -658,11 +655,11 @@ void Bittorrent::takeETASamples() {
// CSA: Current Speed Algorithm // CSA: Current Speed Algorithm
// WINX: Window of X Algorithm // WINX: Window of X Algorithm
qlonglong Bittorrent::getETA(QString hash) { qlonglong Bittorrent::getETA(QString hash) {
QTorrentHandle h = getTorrentHandle(hash); const QTorrentHandle &h = getTorrentHandle(hash);
if(!h.is_valid() || h.state() != torrent_status::downloading || !h.active_time()) if(!h.is_valid() || h.state() != torrent_status::downloading || !h.active_time())
return -1; return -1;
// See if the torrent is going to be completed soon // See if the torrent is going to be completed soon
qulonglong bytes_left = h.actual_size() - h.total_wanted_done(); const qulonglong bytes_left = h.actual_size() - h.total_wanted_done();
if(h.actual_size() > 10485760L) { // Size > 10MiB if(h.actual_size() > 10485760L) { // Size > 10MiB
if(h.progress() >= (float)0.99 && bytes_left < 10485760L) { // Progress>99% but less than 10MB left. if(h.progress() >= (float)0.99 && bytes_left < 10485760L) { // Progress>99% but less than 10MB left.
// Compute by taking samples // Compute by taking samples
@ -674,11 +671,11 @@ qlonglong Bittorrent::getETA(QString hash) {
connect(timerETA, SIGNAL(timeout()), this, SLOT(takeETASamples())); connect(timerETA, SIGNAL(timeout()), this, SLOT(takeETASamples()));
timerETA->start(); timerETA->start();
} else { } else {
QList<int> samples = ETA_samples.value(h.hash(), QList<int>()); const QList<int> &samples = ETA_samples.value(h.hash(), QList<int>());
int nb_samples = samples.size(); const int nb_samples = samples.size();
if(nb_samples > 3) { if(nb_samples > 3) {
long sum_samples = 0; long sum_samples = 0;
foreach(int val, samples) { foreach(const int val, samples) {
sum_samples += val; sum_samples += val;
} }
// Use WINX // Use WINX
@ -698,14 +695,14 @@ std::vector<torrent_handle> Bittorrent::getTorrents() const {
// Return the torrent handle, given its hash // Return the torrent handle, given its hash
QTorrentHandle Bittorrent::getTorrentHandle(QString hash) const{ QTorrentHandle Bittorrent::getTorrentHandle(QString hash) const{
return QTorrentHandle(s->find_torrent(misc::fromString<sha1_hash>((hash.toStdString())))); return QTorrentHandle(s->find_torrent(misc::QStringToSha1(hash)));
} }
bool Bittorrent::hasActiveTorrents() const { bool Bittorrent::hasActiveTorrents() const {
std::vector<torrent_handle> torrents = getTorrents(); std::vector<torrent_handle> torrents = getTorrents();
std::vector<torrent_handle>::iterator torrentIT; std::vector<torrent_handle>::iterator torrentIT;
for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) {
QTorrentHandle h = QTorrentHandle(*torrentIT); const QTorrentHandle &h = QTorrentHandle(*torrentIT);
if(h.is_valid() && !h.is_paused() && !h.is_queued()) if(h.is_valid() && !h.is_paused() && !h.is_queued())
return true; return true;
} }
@ -721,13 +718,12 @@ void Bittorrent::banIP(QString ip) {
// permanent = true means that the torrent will be removed from the hard-drive too // permanent = true means that the torrent will be removed from the hard-drive too
void Bittorrent::deleteTorrent(QString hash, bool delete_local_files) { void Bittorrent::deleteTorrent(QString hash, bool delete_local_files) {
qDebug("Deleting torrent with hash: %s", hash.toLocal8Bit().data()); qDebug("Deleting torrent with hash: %s", hash.toLocal8Bit().data());
QTorrentHandle h = getTorrentHandle(hash); const QTorrentHandle &h = getTorrentHandle(hash);
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
return; return;
} }
QString savePath = h.save_path(); const QString &fileName = h.name();
QString fileName = h.name();
// Remove it from session // Remove it from session
if(delete_local_files) if(delete_local_files)
s->remove_torrent(h.get_torrent_handle(), session::delete_files); s->remove_torrent(h.get_torrent_handle(), session::delete_files);
@ -737,7 +733,7 @@ void Bittorrent::deleteTorrent(QString hash, bool delete_local_files) {
QDir torrentBackup(misc::BTBackupLocation()); QDir torrentBackup(misc::BTBackupLocation());
QStringList filters; QStringList filters;
filters << hash+".*"; filters << hash+".*";
QStringList files = torrentBackup.entryList(filters, QDir::Files, QDir::Unsorted); const QStringList &files = torrentBackup.entryList(filters, QDir::Files, QDir::Unsorted);
foreach(const QString &file, files) { foreach(const QString &file, files) {
torrentBackup.remove(file); torrentBackup.remove(file);
} }
@ -795,12 +791,12 @@ void Bittorrent::resumeTorrent(QString hash) {
QTorrentHandle Bittorrent::addMagnetUri(QString magnet_uri, bool resumed) { QTorrentHandle Bittorrent::addMagnetUri(QString magnet_uri, bool resumed) {
QTorrentHandle h; QTorrentHandle h;
QString hash = misc::magnetUriToHash(magnet_uri); const QString &hash = misc::magnetUriToHash(magnet_uri);
if(hash.isEmpty()) { if(hash.isEmpty()) {
addConsoleMessage(tr("'%1' is not a valid magnet URI.").arg(magnet_uri)); addConsoleMessage(tr("'%1' is not a valid magnet URI.").arg(magnet_uri));
return h; return h;
} }
QDir torrentBackup(misc::BTBackupLocation()); const QDir &torrentBackup(misc::BTBackupLocation());
if(resumed) { if(resumed) {
qDebug("Resuming magnet URI: %s", hash.toLocal8Bit().data()); qDebug("Resuming magnet URI: %s", hash.toLocal8Bit().data());
// Load metadata // Load metadata
@ -832,14 +828,14 @@ QTorrentHandle Bittorrent::addMagnetUri(QString magnet_uri, bool resumed) {
qDebug("Successfuly loaded"); qDebug("Successfuly loaded");
} }
} }
QString savePath = getSavePath(hash); const QString &savePath = getSavePath(hash);
if(!defaultTempPath.isEmpty() && resumed && !TorrentPersistentData::isSeed(hash)) { if(!defaultTempPath.isEmpty() && resumed && !TorrentPersistentData::isSeed(hash)) {
qDebug("addMagnetURI: Temp folder is enabled."); qDebug("addMagnetURI: Temp folder is enabled.");
p.save_path = defaultTempPath.toLocal8Bit().data(); p.save_path = defaultTempPath.toLocal8Bit().constData();
qDebug("addMagnetURI: using save_path: %s", defaultTempPath.toLocal8Bit().data()); qDebug("addMagnetURI: using save_path: %s", qPrintable(defaultTempPath));
} else { } else {
p.save_path = savePath.toLocal8Bit().data(); p.save_path = savePath.toLocal8Bit().constData();
qDebug("addMagnetURI: using save_path: %s", savePath.toLocal8Bit().data()); qDebug("addMagnetURI: using save_path: %s", qPrintable(savePath));
} }
#ifdef LIBTORRENT_0_15 #ifdef LIBTORRENT_0_15
@ -894,7 +890,7 @@ QTorrentHandle Bittorrent::addMagnetUri(QString magnet_uri, bool resumed) {
qDebug("addMagnetURI Setting download as sequential (from tmp data)"); qDebug("addMagnetURI Setting download as sequential (from tmp data)");
h.set_sequential_download(TorrentTempData::isSequential(hash)); h.set_sequential_download(TorrentTempData::isSequential(hash));
} }
QString label = TorrentTempData::getLabel(hash); const QString &label = TorrentTempData::getLabel(hash);
// Save persistent data for new torrent // Save persistent data for new torrent
TorrentPersistentData::saveTorrentPersistentData(h, true); TorrentPersistentData::saveTorrentPersistentData(h, true);
// Save Label // Save Label
@ -903,7 +899,7 @@ QTorrentHandle Bittorrent::addMagnetUri(QString magnet_uri, bool resumed) {
} }
// Save save_path // Save save_path
if(!defaultTempPath.isEmpty()) { if(!defaultTempPath.isEmpty()) {
qDebug("addTorrent: Saving save_path in persistent data: %s", savePath.toLocal8Bit().data()); qDebug("addTorrent: Saving save_path in persistent data: %s", qPrintable(savePath));
TorrentPersistentData::saveSavePath(hash, savePath); TorrentPersistentData::saveSavePath(hash, savePath);
} }
} }
@ -924,8 +920,8 @@ QTorrentHandle Bittorrent::addMagnetUri(QString magnet_uri, bool resumed) {
QTorrentHandle Bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url, bool resumed) { QTorrentHandle Bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url, bool resumed) {
QTorrentHandle h; QTorrentHandle h;
bool fastResume=false; bool fastResume=false;
QDir torrentBackup(misc::BTBackupLocation()); const QDir &torrentBackup(misc::BTBackupLocation());
QString file, hash; QString hash;
boost::intrusive_ptr<torrent_info> t; boost::intrusive_ptr<torrent_info> t;
// Checking if BT_backup Dir exists // Checking if BT_backup Dir exists
@ -937,16 +933,16 @@ QTorrentHandle Bittorrent::addTorrent(QString path, bool fromScanDir, QString fr
} }
} }
// Processing torrents // Processing torrents
file = path.trimmed().replace("file://", "", Qt::CaseInsensitive); const QString &file = path.trimmed().replace("file://", "", Qt::CaseInsensitive);
if(file.isEmpty()) { if(file.isEmpty()) {
return h; return h;
} }
Q_ASSERT(!file.startsWith("http://", Qt::CaseInsensitive) && !file.startsWith("https://", Qt::CaseInsensitive) && !file.startsWith("ftp://", Qt::CaseInsensitive)); Q_ASSERT(!file.startsWith("http://", Qt::CaseInsensitive) && !file.startsWith("https://", Qt::CaseInsensitive) && !file.startsWith("ftp://", Qt::CaseInsensitive));
qDebug("Adding %s to download list", file.toLocal8Bit().data()); qDebug("Adding %s to download list", qPrintable(file));
try { try {
// Getting torrent file informations // Getting torrent file informations
t = new torrent_info(file.toLocal8Bit().data()); t = new torrent_info(file.toLocal8Bit().constData());
if(!t->is_valid()) if(!t->is_valid())
throw std::exception(); throw std::exception();
} catch(std::exception&) { } catch(std::exception&) {
@ -965,10 +961,11 @@ QTorrentHandle Bittorrent::addTorrent(QString path, bool fromScanDir, QString fr
} }
return h; return h;
} }
qDebug(" -> Hash: %s", misc::toString(t->info_hash()).c_str());
qDebug(" -> Name: %s", t->name().c_str());
hash = misc::toQString(t->info_hash()); hash = misc::toQString(t->info_hash());
qDebug(" -> Hash: %s", qPrintable(hash));
qDebug(" -> Name: %s", t->name().c_str());
// Check if torrent is already in download list // Check if torrent is already in download list
if(s->find_torrent(t->info_hash()).is_valid()) { if(s->find_torrent(t->info_hash()).is_valid()) {
qDebug("/!\\ Torrent is already in download list"); qDebug("/!\\ Torrent is already in download list");
@ -1009,10 +1006,10 @@ QTorrentHandle Bittorrent::addTorrent(QString path, bool fromScanDir, QString fr
addConsoleMessage(tr("Note: new trackers were added to the existing torrent.")); addConsoleMessage(tr("Note: new trackers were added to the existing torrent."));
} }
bool urlseeds_added = false; bool urlseeds_added = false;
QStringList old_urlseeds = h_ex.url_seeds(); const QStringList &old_urlseeds = h_ex.url_seeds();
std::vector<std::string> new_urlseeds = t->url_seeds(); std::vector<std::string> new_urlseeds = t->url_seeds();
for(std::vector<std::string>::iterator it = new_urlseeds.begin(); it != new_urlseeds.end(); it++) { for(std::vector<std::string>::iterator it = new_urlseeds.begin(); it != new_urlseeds.end(); it++) {
QString new_url = misc::toQString(it->c_str()); const QString &new_url = misc::toQString(it->c_str());
if(!old_urlseeds.contains(new_url)) { if(!old_urlseeds.contains(new_url)) {
urlseeds_added = true; urlseeds_added = true;
h_ex.add_url_seed(new_url); h_ex.add_url_seed(new_url);
@ -1048,11 +1045,11 @@ QTorrentHandle Bittorrent::addTorrent(QString path, bool fromScanDir, QString fr
} }
if(!defaultTempPath.isEmpty() && resumed && !TorrentPersistentData::isSeed(hash)) { if(!defaultTempPath.isEmpty() && resumed && !TorrentPersistentData::isSeed(hash)) {
qDebug("addTorrent::Temp folder is enabled."); qDebug("addTorrent::Temp folder is enabled.");
p.save_path = defaultTempPath.toLocal8Bit().data(); p.save_path = defaultTempPath.toLocal8Bit().constData();
qDebug("addTorrent: using save_path: %s", defaultTempPath.toLocal8Bit().data()); qDebug("addTorrent: using save_path: %s", qPrintable(defaultTempPath));
} else { } else {
p.save_path = savePath.toLocal8Bit().data(); p.save_path = savePath.toLocal8Bit().constData();
qDebug("addTorrent: using save_path: %s", savePath.toLocal8Bit().data()); qDebug("addTorrent: using save_path: %s", qPrintable(savePath));
} }
#ifdef LIBTORRENT_0_15 #ifdef LIBTORRENT_0_15
@ -1065,7 +1062,7 @@ QTorrentHandle Bittorrent::addTorrent(QString path, bool fromScanDir, QString fr
#endif #endif
// TODO: Remove in v1.6.0: For backward compatibility only // TODO: Remove in v1.6.0: For backward compatibility only
if(QFile::exists(misc::BTBackupLocation()+QDir::separator()+hash+".finished")) { if(QFile::exists(misc::BTBackupLocation()+QDir::separator()+hash+".finished")) {
p.save_path = savePath.toLocal8Bit().data(); p.save_path = savePath.toLocal8Bit().constData();
QFile::remove(misc::BTBackupLocation()+QDir::separator()+hash+".finished"); QFile::remove(misc::BTBackupLocation()+QDir::separator()+hash+".finished");
} }
p.ti = t; p.ti = t;
@ -1115,11 +1112,11 @@ QTorrentHandle Bittorrent::addTorrent(QString path, bool fromScanDir, QString fr
h.prioritize_files(TorrentTempData::getFilesPriority(hash)); h.prioritize_files(TorrentTempData::getFilesPriority(hash));
h.set_sequential_download(TorrentTempData::isSequential(hash)); h.set_sequential_download(TorrentTempData::isSequential(hash));
// Import Files names from torrent addition dialog // Import Files names from torrent addition dialog
QStringList files_path = TorrentTempData::getFilesPath(hash); const QStringList &files_path = TorrentTempData::getFilesPath(hash);
bool force_recheck = false; bool force_recheck = false;
if(files_path.size() == h.num_files()) { if(files_path.size() == h.num_files()) {
for(int i=0; i<h.num_files(); ++i) { for(int i=0; i<h.num_files(); ++i) {
QString path = files_path.at(i); const QString &path = files_path.at(i);
if(!force_recheck && QFile::exists(h.save_path()+QDir::separator()+path)) if(!force_recheck && QFile::exists(h.save_path()+QDir::separator()+path))
force_recheck = true; force_recheck = true;
h.rename_file(i, path); h.rename_file(i, path);
@ -1128,7 +1125,7 @@ QTorrentHandle Bittorrent::addTorrent(QString path, bool fromScanDir, QString fr
if(force_recheck) h.force_recheck(); if(force_recheck) h.force_recheck();
} }
} }
QString label = TorrentTempData::getLabel(hash); const QString &label = TorrentTempData::getLabel(hash);
// Save persistent data for new torrent // Save persistent data for new torrent
TorrentPersistentData::saveTorrentPersistentData(h); TorrentPersistentData::saveTorrentPersistentData(h);
// Save Label // Save Label
@ -1146,7 +1143,7 @@ QTorrentHandle Bittorrent::addTorrent(QString path, bool fromScanDir, QString fr
appendqBextensionToTorrent(h, true); appendqBextensionToTorrent(h, true);
#endif #endif
// Backup torrent file // Backup torrent file
QString newFile = torrentBackup.absoluteFilePath(hash + ".torrent"); const QString &newFile = torrentBackup.absoluteFilePath(hash + ".torrent");
if(file != newFile) { if(file != newFile) {
// Delete file from torrentBackup directory in case it exists because // Delete file from torrentBackup directory in case it exists because
// QFile::copy() do not overwrite // QFile::copy() do not overwrite
@ -1199,7 +1196,7 @@ void Bittorrent::exportTorrentFiles(QString path) {
QDir exportDir(path); QDir exportDir(path);
if(!exportDir.exists()) { if(!exportDir.exists()) {
if(!exportDir.mkpath(exportDir.absolutePath())) { if(!exportDir.mkpath(exportDir.absolutePath())) {
std::cerr << "Error: Could not create torrent export directory: " << exportDir.absolutePath().toLocal8Bit().data() << std::endl; std::cerr << "Error: Could not create torrent export directory: " << qPrintable(exportDir.absolutePath()) << std::endl;
return; return;
} }
} }
@ -1207,12 +1204,12 @@ void Bittorrent::exportTorrentFiles(QString path) {
std::vector<torrent_handle> handles = s->get_torrents(); std::vector<torrent_handle> handles = s->get_torrents();
std::vector<torrent_handle>::iterator itr; std::vector<torrent_handle>::iterator itr;
for(itr=handles.begin(); itr != handles.end(); itr++) { for(itr=handles.begin(); itr != handles.end(); itr++) {
QTorrentHandle h(*itr); const QTorrentHandle &h(*itr);
if(!h.is_valid()) { if(!h.is_valid()) {
std::cerr << "Torrent Export: torrent is invalid, skipping..." << std::endl; std::cerr << "Torrent Export: torrent is invalid, skipping..." << std::endl;
continue; continue;
} }
QString src_path = torrentBackup.absoluteFilePath(h.hash()+".torrent"); const QString &src_path = torrentBackup.absoluteFilePath(h.hash()+".torrent");
if(QFile::exists(src_path)) { if(QFile::exists(src_path)) {
QString dst_path = exportDir.absoluteFilePath(h.name()+".torrent"); QString dst_path = exportDir.absoluteFilePath(h.name()+".torrent");
if(QFile::exists(dst_path)) { if(QFile::exists(dst_path)) {
@ -1223,10 +1220,10 @@ void Bittorrent::exportTorrentFiles(QString path) {
continue; continue;
} }
} }
qDebug("Export Torrent: %s -> %s", src_path.toLocal8Bit().data(), dst_path.toLocal8Bit().data()); qDebug("Export Torrent: %s -> %s", qPrintable(src_path), qPrintable(dst_path));
QFile::copy(src_path, dst_path); QFile::copy(src_path, dst_path);
} else { } else {
std::cerr << "Error: could not export torrent "<< h.hash().toLocal8Bit().data() << ", maybe it has not metadata yet." <<std::endl; std::cerr << "Error: could not export torrent "<< qPrintable(h.hash()) << ", maybe it has not metadata yet." <<std::endl;
} }
} }
} }
@ -1344,7 +1341,7 @@ bool Bittorrent::enableDHT(bool b) {
if(b) { if(b) {
if(!DHTEnabled) { if(!DHTEnabled) {
entry dht_state; entry dht_state;
QString dht_state_path = misc::cacheLocation()+QDir::separator()+QString::fromUtf8("dht_state"); const QString &dht_state_path = misc::cacheLocation()+QDir::separator()+QString::fromUtf8("dht_state");
if(QFile::exists(dht_state_path)) { if(QFile::exists(dht_state_path)) {
boost::filesystem::ifstream dht_state_file(dht_state_path.toLocal8Bit().data(), std::ios_base::binary); boost::filesystem::ifstream dht_state_file(dht_state_path.toLocal8Bit().data(), std::ios_base::binary);
dht_state_file.unsetf(std::ios_base::skipws); dht_state_file.unsetf(std::ios_base::skipws);
@ -1376,6 +1373,9 @@ bool Bittorrent::enableDHT(bool b) {
float Bittorrent::getRealRatio(QString hash) const{ float Bittorrent::getRealRatio(QString hash) const{
QTorrentHandle h = getTorrentHandle(hash); QTorrentHandle h = getTorrentHandle(hash);
if(!h.is_valid()) {
return 0.;
}
Q_ASSERT(h.total_done() >= 0); Q_ASSERT(h.total_done() >= 0);
Q_ASSERT(h.all_time_upload() >= 0); Q_ASSERT(h.all_time_upload() >= 0);
if(h.total_done() == 0) { if(h.total_done() == 0) {
@ -1438,12 +1438,12 @@ void Bittorrent::saveFastResumeData() {
--num_resume_data; --num_resume_data;
if (!rd->resume_data) continue; if (!rd->resume_data) continue;
QDir torrentBackup(misc::BTBackupLocation()); QDir torrentBackup(misc::BTBackupLocation());
QTorrentHandle h(rd->handle); const QTorrentHandle &h(rd->handle);
if(!h.is_valid()) continue; if(!h.is_valid()) continue;
// Remove old fastresume file if it exists // Remove old fastresume file if it exists
QFile::remove(torrentBackup.path()+QDir::separator()+ h.hash() + ".fastresume"); QFile::remove(torrentBackup.path()+QDir::separator()+ h.hash() + ".fastresume");
QString file = h.hash()+".fastresume"; const QString &file = h.hash()+".fastresume";
boost::filesystem::ofstream out(fs::path(torrentBackup.path().toLocal8Bit().data()) / file.toLocal8Bit().data(), std::ios_base::binary); boost::filesystem::ofstream out(fs::path(torrentBackup.path().toLocal8Bit().constData()) / file.toLocal8Bit().constData(), std::ios_base::binary);
out.unsetf(std::ios_base::skipws); out.unsetf(std::ios_base::skipws);
bencode(std::ostream_iterator<char>(out), *rd->resume_data); bencode(std::ostream_iterator<char>(out), *rd->resume_data);
// Remove torrent from session // Remove torrent from session
@ -1484,15 +1484,14 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
bool Bittorrent::isFilePreviewPossible(QString hash) const{ bool Bittorrent::isFilePreviewPossible(QString hash) const{
// See if there are supported files in the torrent // See if there are supported files in the torrent
QTorrentHandle h = getTorrentHandle(hash); const QTorrentHandle &h = getTorrentHandle(hash);
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
return false; return false;
} }
unsigned int nbFiles = h.num_files(); const unsigned int nbFiles = h.num_files();
for(unsigned int i=0; i<nbFiles; ++i) { for(unsigned int i=0; i<nbFiles; ++i) {
QString fileName = h.file_at(i); const QString &extension = h.file_at(i).split('.').last();
QString extension = fileName.split('.').last();
if(misc::isPreviewable(extension)) if(misc::isPreviewable(extension))
return true; return true;
} }
@ -1504,9 +1503,10 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
qDebug("File %s added", qPrintable(file)); qDebug("File %s added", qPrintable(file));
try { try {
torrent_info t(file.toLocal8Bit().data()); torrent_info t(file.toLocal8Bit().data());
addTorrent(file, true); if(t.is_valid())
addTorrent(file, true);
} catch(std::exception&) { } catch(std::exception&) {
qDebug("Ignoring incomplete torrent file: %s", file.toLocal8Bit().data()); qDebug("Ignoring incomplete torrent file: %s", qPrintable(file));
} }
} }
} }
@ -1553,11 +1553,11 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
h.file_progress(fp); h.file_progress(fp);
for(int i=0; i<h.num_files(); ++i) { for(int i=0; i<h.num_files(); ++i) {
if(append) { if(append) {
qulonglong file_size = h.filesize_at(i); const qulonglong file_size = h.filesize_at(i);
if(file_size > 0 && (fp[i]/(double)file_size) < 1.) { if(file_size > 0 && (fp[i]/(double)file_size) < 1.) {
QString name = misc::toQString(h.get_torrent_info().file_at(i).path.string()); const QString &name = misc::toQString(h.get_torrent_info().file_at(i).path.string());
if(!name.endsWith(".!qB")) { if(!name.endsWith(".!qB")) {
qDebug("Renaming %s to %s", name.toLocal8Bit().data(), (name+".!qB").toLocal8Bit().data()); qDebug("Renaming %s to %s", qPrintable(name), qPrintable(name+".!qB"));
h.rename_file(i, name + ".!qB"); h.rename_file(i, name + ".!qB");
} }
} }
@ -1565,7 +1565,7 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
QString name = misc::toQString(h.get_torrent_info().file_at(i).path.string()); QString name = misc::toQString(h.get_torrent_info().file_at(i).path.string());
if(name.endsWith(".!qB")) { if(name.endsWith(".!qB")) {
name.chop(4); name.chop(4);
qDebug("Renaming %s to %s", (name+".!qB").toLocal8Bit().data(), name.toLocal8Bit().data()); qDebug("Renaming %s to %s", qPrintable(name+".!qB"), qPrintable(name));
h.rename_file(i, name); h.rename_file(i, name);
} }
} }
@ -1576,9 +1576,9 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
void Bittorrent::changeLabelInTorrentSavePath(QTorrentHandle h, QString old_label, QString new_label) { void Bittorrent::changeLabelInTorrentSavePath(QTorrentHandle h, QString old_label, QString new_label) {
if(!h.is_valid()) return; if(!h.is_valid()) return;
if(!appendLabelToSavePath) return; if(!appendLabelToSavePath) return;
QString old_save_path = TorrentPersistentData::getSavePath(h.hash()); const QString &old_save_path = TorrentPersistentData::getSavePath(h.hash());
QDir old_dir(old_save_path); QDir old_dir(old_save_path);
bool move_storage = (old_dir == QDir(h.save_path())); const bool move_storage = (old_dir == QDir(h.save_path()));
if(!old_label.isEmpty()) { if(!old_label.isEmpty()) {
Q_ASSERT(old_dir.dirName() == old_label); Q_ASSERT(old_dir.dirName() == old_label);
QString path = old_save_path; QString path = old_save_path;
@ -1605,13 +1605,13 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
void Bittorrent::appendLabelToTorrentSavePath(QTorrentHandle h) { void Bittorrent::appendLabelToTorrentSavePath(QTorrentHandle h) {
if(!h.is_valid()) return; if(!h.is_valid()) return;
QString label = TorrentPersistentData::getLabel(h.hash()); const QString &label = TorrentPersistentData::getLabel(h.hash());
if(label.isEmpty()) return; if(label.isEmpty()) return;
// Current save path // Current save path
QString old_save_path = TorrentPersistentData::getSavePath(h.hash()); const QString &old_save_path = TorrentPersistentData::getSavePath(h.hash());
QDir old_dir(old_save_path); const QDir &old_dir(old_save_path);
if(old_dir.dirName() != label) { if(old_dir.dirName() != label) {
QString new_save_path = old_dir.absoluteFilePath(label); const QString &new_save_path = old_dir.absoluteFilePath(label);
TorrentPersistentData::saveSavePath(h.hash(), new_save_path); TorrentPersistentData::saveSavePath(h.hash(), new_save_path);
if(old_dir == QDir(h.save_path())) { if(old_dir == QDir(h.save_path())) {
// Move storage // Move storage
@ -1685,9 +1685,9 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
ratio = 0; ratio = 0;
} }
std::vector<torrent_handle> handles = s->get_torrents(); std::vector<torrent_handle> handles = s->get_torrents();
unsigned int nbHandles = handles.size(); std::vector<torrent_handle>::iterator it;
for(unsigned int i=0; i<nbHandles; ++i) { for(it = handles.begin(); it != handles.end(); it++) {
QTorrentHandle h = handles[i]; QTorrentHandle h(*it);
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
continue; continue;
@ -1752,19 +1752,19 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
} }
// Set BT session settings (user_agent) // Set BT session settings (user_agent)
void Bittorrent::setSessionSettings(session_settings sessionSettings) { void Bittorrent::setSessionSettings(const session_settings &sessionSettings) {
qDebug("Set session settings"); qDebug("Set session settings");
s->set_settings(sessionSettings); s->set_settings(sessionSettings);
} }
// Set Proxy // Set Proxy
void Bittorrent::setPeerProxySettings(proxy_settings proxySettings) { void Bittorrent::setPeerProxySettings(const proxy_settings &proxySettings) {
qDebug("Set Peer Proxy settings"); qDebug("Set Peer Proxy settings");
s->set_peer_proxy(proxySettings); s->set_peer_proxy(proxySettings);
s->set_dht_proxy(proxySettings); s->set_dht_proxy(proxySettings);
} }
void Bittorrent::setHTTPProxySettings(proxy_settings proxySettings) { void Bittorrent::setHTTPProxySettings(const proxy_settings &proxySettings) {
s->set_tracker_proxy(proxySettings); s->set_tracker_proxy(proxySettings);
s->set_web_seed_proxy(proxySettings); s->set_web_seed_proxy(proxySettings);
QString proxy_str; QString proxy_str;
@ -1796,16 +1796,16 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
char proxystr[512]; char proxystr[512];
if(proxySettings.type == proxy_settings::socks5 || proxySettings.type == proxy_settings::socks5_pw) if(proxySettings.type == proxy_settings::socks5 || proxySettings.type == proxy_settings::socks5_pw)
snprintf(proxystr, 512, "sock_proxy=%s", proxy_str.toLocal8Bit().data()); snprintf(proxystr, 512, "sock_proxy=%s", proxy_str.toLocal8Bit().constData());
else else
snprintf(proxystr, 512, "http_proxy=%s", proxy_str.toLocal8Bit().data()); snprintf(proxystr, 512, "http_proxy=%s", proxy_str.toLocal8Bit().constData());
putenv(proxystr); putenv(proxystr);
#else #else
qDebug("HTTP communications proxy string: %s", proxy_str.toLocal8Bit().data()); qDebug("HTTP communications proxy string: %s", qPrintable(proxy_str));
if(proxySettings.type == proxy_settings::socks5 || proxySettings.type == proxy_settings::socks5_pw) if(proxySettings.type == proxy_settings::socks5 || proxySettings.type == proxy_settings::socks5_pw)
setenv("sock_proxy", proxy_str.toLocal8Bit().data(), 1); setenv("sock_proxy", proxy_str.toLocal8Bit().constData(), 1);
else else
setenv("http_proxy", proxy_str.toLocal8Bit().data(), 1); setenv("http_proxy", proxy_str.toLocal8Bit().constData(), 1);
#endif #endif
} }
@ -1818,7 +1818,7 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
QTorrentHandle h(p->handle); QTorrentHandle h(p->handle);
if(h.is_valid()) { if(h.is_valid()) {
emit finishedTorrent(h); emit finishedTorrent(h);
QString hash = h.hash(); const QString &hash = h.hash();
#ifdef LIBTORRENT_0_15 #ifdef LIBTORRENT_0_15
// Remove .!qB extension if necessary // Remove .!qB extension if necessary
if(appendqBExtension) if(appendqBExtension)
@ -1827,25 +1827,24 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
// Move to download directory if necessary // Move to download directory if necessary
if(!defaultTempPath.isEmpty()) { if(!defaultTempPath.isEmpty()) {
// Check if directory is different // Check if directory is different
QDir current_dir(h.save_path()); const QDir &current_dir(h.save_path());
QDir save_dir(getSavePath(hash)); const QDir &save_dir(getSavePath(hash));
if(current_dir != save_dir) { if(current_dir != save_dir) {
h.move_storage(save_dir.path()); h.move_storage(save_dir.path());
} }
} }
bool was_already_seeded = TorrentPersistentData::isSeed(hash); const bool was_already_seeded = TorrentPersistentData::isSeed(hash);
if(!was_already_seeded) { if(!was_already_seeded) {
h.save_resume_data(); h.save_resume_data();
// Check if there are torrent files inside // Check if there are torrent files inside
for(int i=0; i<h.get_torrent_info().num_files(); ++i) { for(int i=0; i<h.get_torrent_info().num_files(); ++i) {
QString torrent_relpath = misc::toQString(h.get_torrent_info().file_at(i).path); const QString &torrent_relpath = misc::toQString(h.get_torrent_info().file_at(i).path.string());
if(torrent_relpath.endsWith(".torrent")) { if(torrent_relpath.endsWith(".torrent")) {
addConsoleMessage(tr("Recursive download of file %1 embedded in torrent %2", "Recursive download of test.torrent embedded in torrent test2").arg(torrent_relpath).arg(h.name())); addConsoleMessage(tr("Recursive download of file %1 embedded in torrent %2", "Recursive download of test.torrent embedded in torrent test2").arg(torrent_relpath).arg(h.name()));
QString torrent_fullpath = h.save_path()+QDir::separator()+torrent_relpath; const QString &torrent_fullpath = h.save_path()+QDir::separator()+torrent_relpath;
boost::intrusive_ptr<torrent_info> t;
try { try {
t = new torrent_info(torrent_fullpath.toLocal8Bit().data()); boost::intrusive_ptr<torrent_info> t = new torrent_info(torrent_fullpath.toLocal8Bit().constData());
QString sub_hash = misc::toQString(t->info_hash()); const QString &sub_hash = misc::toQString(t->info_hash());
// Passing the save path along to the sub torrent file // Passing the save path along to the sub torrent file
TorrentTempData::setSavePath(sub_hash, h.save_path()); TorrentTempData::setSavePath(sub_hash, h.save_path());
addTorrent(torrent_fullpath); addTorrent(torrent_fullpath);
@ -1865,20 +1864,20 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
// Remember finished state // Remember finished state
TorrentPersistentData::saveSeedStatus(h); TorrentPersistentData::saveSeedStatus(h);
} }
qDebug("Received finished alert for %s", h.name().toLocal8Bit().data()); qDebug("Received finished alert for %s", qPrintable(h.name()));
} }
} }
else if (save_resume_data_alert* p = dynamic_cast<save_resume_data_alert*>(a.get())) { else if (save_resume_data_alert* p = dynamic_cast<save_resume_data_alert*>(a.get())) {
QDir torrentBackup(misc::BTBackupLocation()); const QDir &torrentBackup(misc::BTBackupLocation());
QTorrentHandle h(p->handle); const QTorrentHandle &h(p->handle);
if(h.is_valid()) { if(h.is_valid()) {
QString file = h.hash()+".fastresume"; const QString &file = h.hash()+".fastresume";
// Delete old fastresume file if necessary // Delete old fastresume file if necessary
if(QFile::exists(file)) if(QFile::exists(file))
QFile::remove(file); QFile::remove(file);
qDebug("Saving fastresume data in %s", file.toLocal8Bit().data()); qDebug("Saving fastresume data in %s", qPrintable(file));
if (p->resume_data) { if (p->resume_data) {
boost::filesystem::ofstream out(fs::path(torrentBackup.path().toLocal8Bit().data()) / file.toLocal8Bit().data(), std::ios_base::binary); boost::filesystem::ofstream out(fs::path(torrentBackup.path().toLocal8Bit().constData()) / file.toLocal8Bit().constData(), std::ios_base::binary);
out.unsetf(std::ios_base::skipws); out.unsetf(std::ios_base::skipws);
bencode(std::ostream_iterator<char>(out), *p->resume_data); bencode(std::ostream_iterator<char>(out), *p->resume_data);
} }
@ -1892,7 +1891,7 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
else if (metadata_received_alert* p = dynamic_cast<metadata_received_alert*>(a.get())) { else if (metadata_received_alert* p = dynamic_cast<metadata_received_alert*>(a.get())) {
QTorrentHandle h(p->handle); QTorrentHandle h(p->handle);
if(h.is_valid()) { if(h.is_valid()) {
qDebug("Received metadata for %s", h.hash().toLocal8Bit().data()); qDebug("Received metadata for %s", qPrintable(h.hash()));
#ifdef LIBTORRENT_0_15 #ifdef LIBTORRENT_0_15
// Append .!qB to incomplete files // Append .!qB to incomplete files
if(appendqBExtension) if(appendqBExtension)
@ -1900,7 +1899,7 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
#endif #endif
emit metadataReceived(h); emit metadataReceived(h);
// Save metadata // Save metadata
QDir torrentBackup(misc::BTBackupLocation()); const QDir &torrentBackup(misc::BTBackupLocation());
if(!QFile::exists(torrentBackup.path()+QDir::separator()+h.hash()+QString(".torrent"))) if(!QFile::exists(torrentBackup.path()+QDir::separator()+h.hash()+QString(".torrent")))
h.save_torrent_file(torrentBackup.path()+QDir::separator()+h.hash()+QString(".torrent")); h.save_torrent_file(torrentBackup.path()+QDir::separator()+h.hash()+QString(".torrent"));
// Copy the torrent file to the export folder // Copy the torrent file to the export folder
@ -1951,7 +1950,7 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
QString name = misc::toQString(h.get_torrent_info().file_at(p->index).path.string()); QString name = misc::toQString(h.get_torrent_info().file_at(p->index).path.string());
if(name.endsWith(".!qB")) { if(name.endsWith(".!qB")) {
name.chop(4); name.chop(4);
qDebug("Renaming %s to %s", (name+".!qB").toLocal8Bit().data(), name.toLocal8Bit().data()); qDebug("Renaming %s to %s", qPrintable(name+".!qB"), qPrintable(name));
h.rename_file(p->index, name); h.rename_file(p->index, name);
} }
} }
@ -1966,12 +1965,12 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
}*/ }*/
else if (tracker_error_alert* p = dynamic_cast<tracker_error_alert*>(a.get())) { else if (tracker_error_alert* p = dynamic_cast<tracker_error_alert*>(a.get())) {
// Level: fatal // Level: fatal
QTorrentHandle h(p->handle); const QTorrentHandle &h(p->handle);
if(h.is_valid()){ if(h.is_valid()){
// Authentication // Authentication
if(p->status_code != 401) { if(p->status_code != 401) {
qDebug("Received a tracker error for %s: %s", p->url.c_str(), p->msg.c_str()); qDebug("Received a tracker error for %s: %s", p->url.c_str(), p->msg.c_str());
QString tracker_url = misc::toQString(p->url); const QString &tracker_url = misc::toQString(p->url);
QHash<QString, TrackerInfos> trackers_data = trackersInfos.value(h.hash(), QHash<QString, TrackerInfos>()); QHash<QString, TrackerInfos> trackers_data = trackersInfos.value(h.hash(), QHash<QString, TrackerInfos>());
TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url)); TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url));
data.last_message = misc::toQString(p->msg); data.last_message = misc::toQString(p->msg);
@ -1987,12 +1986,12 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
} }
} }
else if (tracker_reply_alert* p = dynamic_cast<tracker_reply_alert*>(a.get())) { else if (tracker_reply_alert* p = dynamic_cast<tracker_reply_alert*>(a.get())) {
QTorrentHandle h(p->handle); const QTorrentHandle &h(p->handle);
if(h.is_valid()){ if(h.is_valid()){
qDebug("Received a tracker reply from %s (Num_peers=%d)", p->url.c_str(), p->num_peers); qDebug("Received a tracker reply from %s (Num_peers=%d)", p->url.c_str(), p->num_peers);
// Connection was successful now. Remove possible old errors // Connection was successful now. Remove possible old errors
QHash<QString, TrackerInfos> trackers_data = trackersInfos.value(h.hash(), QHash<QString, TrackerInfos>()); QHash<QString, TrackerInfos> trackers_data = trackersInfos.value(h.hash(), QHash<QString, TrackerInfos>());
QString tracker_url = misc::toQString(p->url); const QString &tracker_url = misc::toQString(p->url);
TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url)); TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url));
data.last_message = ""; // Reset error/warning message data.last_message = ""; // Reset error/warning message
data.num_peers = p->num_peers; data.num_peers = p->num_peers;
@ -2004,11 +2003,11 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
trackersInfos[h.hash()] = trackers_data; trackersInfos[h.hash()] = trackers_data;
} }
} else if (tracker_warning_alert* p = dynamic_cast<tracker_warning_alert*>(a.get())) { } else if (tracker_warning_alert* p = dynamic_cast<tracker_warning_alert*>(a.get())) {
QTorrentHandle h(p->handle); const QTorrentHandle &h(p->handle);
if(h.is_valid()){ if(h.is_valid()){
// Connection was successful now but there is a warning message // Connection was successful now but there is a warning message
QHash<QString, TrackerInfos> trackers_data = trackersInfos.value(h.hash(), QHash<QString, TrackerInfos>()); QHash<QString, TrackerInfos> trackers_data = trackersInfos.value(h.hash(), QHash<QString, TrackerInfos>());
QString tracker_url = misc::toQString(p->url); const QString &tracker_url = misc::toQString(p->url);
TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url)); TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url));
data.last_message = misc::toQString(p->msg); // Store warning message data.last_message = misc::toQString(p->msg); // Store warning message
#ifndef LIBTORRENT_0_15 #ifndef LIBTORRENT_0_15
@ -2026,7 +2025,7 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
} }
else if (portmap_alert* p = dynamic_cast<portmap_alert*>(a.get())) { else if (portmap_alert* p = dynamic_cast<portmap_alert*>(a.get())) {
qDebug("UPnP Success, msg: %s", p->message().c_str()); qDebug("UPnP Success, msg: %s", p->message().c_str());
addConsoleMessage(tr("UPnP/NAT-PMP: Port mapping successful, message: %1").arg(QString(p->message().c_str())), "blue"); addConsoleMessage(tr("UPnP/NAT-PMP: Port mapping successful, message: %1").arg(misc::toQString(p->message())), "blue");
//emit UPnPSuccess(QString(p->msg().c_str())); //emit UPnPSuccess(QString(p->msg().c_str()));
} }
else if (peer_blocked_alert* p = dynamic_cast<peer_blocked_alert*>(a.get())) { else if (peer_blocked_alert* p = dynamic_cast<peer_blocked_alert*>(a.get())) {
@ -2038,30 +2037,30 @@ void Bittorrent::addConsoleMessage(QString msg, QString) {
//emit peerBlocked(QString::fromUtf8(p->ip.to_string().c_str())); //emit peerBlocked(QString::fromUtf8(p->ip.to_string().c_str()));
} }
else if (fastresume_rejected_alert* p = dynamic_cast<fastresume_rejected_alert*>(a.get())) { else if (fastresume_rejected_alert* p = dynamic_cast<fastresume_rejected_alert*>(a.get())) {
QTorrentHandle h(p->handle); const QTorrentHandle &h(p->handle);
if(h.is_valid()){ if(h.is_valid()){
qDebug("/!\\ Fast resume failed for %s, reason: %s", h.name().toLocal8Bit().data(), p->message().c_str()); qDebug("/!\\ Fast resume failed for %s, reason: %s", qPrintable(h.name()), p->message().c_str());
addConsoleMessage(tr("Fast resume data was rejected for torrent %1, checking again...").arg(h.name()), QString::fromUtf8("red")); addConsoleMessage(tr("Fast resume data was rejected for torrent %1, checking again...").arg(h.name()), QString::fromUtf8("red"));
addConsoleMessage(tr("Reason: %1").arg(QString::fromUtf8(p->message().c_str()))); addConsoleMessage(tr("Reason: %1").arg(misc::toQString(p->message())));
//emit fastResumeDataRejected(h.name()); //emit fastResumeDataRejected(h.name());
} }
} }
else if (url_seed_alert* p = dynamic_cast<url_seed_alert*>(a.get())) { else if (url_seed_alert* p = dynamic_cast<url_seed_alert*>(a.get())) {
addConsoleMessage(tr("Url seed lookup failed for url: %1, message: %2").arg(QString::fromUtf8(p->url.c_str())).arg(QString::fromUtf8(p->message().c_str())), QString::fromUtf8("red")); addConsoleMessage(tr("Url seed lookup failed for url: %1, message: %2").arg(misc::toQString(p->url)).arg(misc::toQString(p->message())), QString::fromUtf8("red"));
//emit urlSeedProblem(QString::fromUtf8(p->url.c_str()), QString::fromUtf8(p->msg().c_str())); //emit urlSeedProblem(QString::fromUtf8(p->url.c_str()), QString::fromUtf8(p->msg().c_str()));
} }
else if (torrent_checked_alert* p = dynamic_cast<torrent_checked_alert*>(a.get())) { else if (torrent_checked_alert* p = dynamic_cast<torrent_checked_alert*>(a.get())) {
QTorrentHandle h(p->handle); QTorrentHandle h(p->handle);
if(h.is_valid()){ if(h.is_valid()){
QString hash = h.hash(); const QString &hash = h.hash();
qDebug("%s have just finished checking", hash.toLocal8Bit().data()); qDebug("%s have just finished checking", qPrintable(hash));
// Save seed status // Save seed status
TorrentPersistentData::saveSeedStatus(h); TorrentPersistentData::saveSeedStatus(h);
// Move to temp directory if necessary // Move to temp directory if necessary
if(!h.is_seed() && !defaultTempPath.isEmpty()) { if(!h.is_seed() && !defaultTempPath.isEmpty()) {
// Check if directory is different // Check if directory is different
QDir current_dir(h.save_path()); const QDir &current_dir(h.save_path());
QDir save_dir(getSavePath(h.hash())); const QDir &save_dir(getSavePath(h.hash()));
if(current_dir == save_dir) { if(current_dir == save_dir) {
h.move_storage(defaultTempPath); h.move_storage(defaultTempPath);
} }

View file

@ -124,11 +124,6 @@ private:
#endif #endif
QString defaultSavePath; QString defaultSavePath;
QString defaultTempPath; QString defaultTempPath;
// GeoIP
#ifndef DISABLE_GUI
bool resolve_countries;
bool geoipDBLoaded;
#endif
// ETA Computation // ETA Computation
QPointer<QTimer> timerETA; QPointer<QTimer> timerETA;
QHash<QString, QList<int> > ETA_samples; QHash<QString, QList<int> > ETA_samples;
@ -140,6 +135,11 @@ private:
QList<QUrl> url_skippingDlg; QList<QUrl> url_skippingDlg;
// Fast exit (async) // Fast exit (async)
bool exiting; bool exiting;
// GeoIP
#ifndef DISABLE_GUI
bool geoipDBLoaded;
bool resolve_countries;
#endif
protected: protected:
QString getSavePath(QString hash, bool fromScanDir = false, QString filePath = QString()); QString getSavePath(QString hash, bool fromScanDir = false, QString filePath = QString());
@ -210,9 +210,9 @@ public slots:
void setGlobalRatio(float ratio); void setGlobalRatio(float ratio);
void setDeleteRatio(float ratio); void setDeleteRatio(float ratio);
void setDHTPort(int dht_port); void setDHTPort(int dht_port);
void setPeerProxySettings(proxy_settings proxySettings); void setPeerProxySettings(const proxy_settings &proxySettings);
void setHTTPProxySettings(proxy_settings proxySettings); void setHTTPProxySettings(const proxy_settings &proxySettings);
void setSessionSettings(session_settings sessionSettings); void setSessionSettings(const session_settings &sessionSettings);
void startTorrentsInPause(bool b); void startTorrentsInPause(bool b);
void setDefaultTempPath(QString temppath); void setDefaultTempPath(QString temppath);
void setAppendLabelToSavePath(bool append); void setAppendLabelToSavePath(bool append);
@ -256,7 +256,7 @@ signals:
void finishedTorrent(QTorrentHandle& h); void finishedTorrent(QTorrentHandle& h);
void fullDiskError(QTorrentHandle& h, QString msg); void fullDiskError(QTorrentHandle& h, QString msg);
void trackerError(QString hash, QString time, QString msg); void trackerError(QString hash, QString time, QString msg);
void trackerAuthenticationRequired(QTorrentHandle& h); void trackerAuthenticationRequired(const QTorrentHandle& h);
void newDownloadedTorrent(QString path, QString url); void newDownloadedTorrent(QString path, QString url);
void updateFileSize(QString hash); void updateFileSize(QString hash);
void downloadFromUrlFailure(QString url, QString reason); void downloadFromUrlFailure(QString url, QString reason);

View file

@ -82,47 +82,31 @@ class misc : public QObject{
Q_OBJECT Q_OBJECT
public: public:
// Convert any type of variable to C++ String static inline QString toQString(std::string str) {
// convert=true will convert -1 to 0 return QString::fromLocal8Bit(str.c_str());
template <class T> static std::string toString(const T& x, bool convert=false) {
std::ostringstream o;
if(!(o<<x)) {
throw std::runtime_error("::toString()");
}
if(o.str() == "-1" && convert)
return "0";
return o.str();
} }
template <class T> static QString toQString(const T& x, bool convert=false) { static inline QString toQString(char* str) {
std::ostringstream o; return QString::fromLocal8Bit(str);
if(!(o<<x)) {
throw std::runtime_error("::toString()");
}
if(o.str() == "-1" && convert)
return QString::fromUtf8("0");
return QString::fromUtf8(o.str().c_str());
} }
template <class T> static QByteArray toQByteArray(const T& x, bool convert=false) { static inline QString toQString(sha1_hash hash) {
std::ostringstream o; std::ostringstream o;
if(!(o<<x)) { if(!(o<<hash)) {
throw std::runtime_error("::toString()"); throw std::runtime_error("::toString()");
} }
if(o.str() == "-1" && convert) return QString::fromLocal8Bit(o.str().c_str());
return "0"; //return QString::fromLocal8Bit(hash.to_string().c_str());
return QByteArray(o.str().c_str());
} }
// Convert C++ string to any type of variable static inline sha1_hash QStringToSha1(const QString& s) {
template <class T> static T fromString(const std::string& s) { sha1_hash x;
T x; std::istringstream i(s.toStdString());
std::istringstream i(s); if(!(i>>x)) {
if(!(i>>x)) { throw std::runtime_error("::fromString()");
throw std::runtime_error("::fromString()"); }
return x;
} }
return x;
}
static bool sameFiles(QString path1, QString path2) { static bool sameFiles(QString path1, QString path2) {
QFile f1(path1); QFile f1(path1);
@ -515,7 +499,7 @@ public:
QString found = regHex.cap(1); QString found = regHex.cap(1);
if(found.length() == 40) { if(found.length() == 40) {
sha1_hash sha1(QString(QByteArray::fromHex(regHex.cap(1).toLocal8Bit())).toStdString()); sha1_hash sha1(QString(QByteArray::fromHex(regHex.cap(1).toLocal8Bit())).toStdString());
qDebug("magnetUriToHash (Hex): hash: %s", misc::toString(sha1).c_str()); qDebug("magnetUriToHash (Hex): hash: %s", sha1.to_string().c_str());
return misc::toQString(sha1); return misc::toQString(sha1);
} }
} }
@ -567,17 +551,17 @@ public:
} }
int minutes = seconds / 60; int minutes = seconds / 60;
if(minutes < 60) { if(minutes < 60) {
return tr("%1m","e.g: 10minutes").arg(QString::QString::fromUtf8(misc::toString(minutes).c_str())); return tr("%1m","e.g: 10minutes").arg(QString::number(minutes));
} }
int hours = minutes / 60; int hours = minutes / 60;
minutes = minutes - hours*60; minutes = minutes - hours*60;
if(hours < 24) { if(hours < 24) {
return tr("%1h%2m", "e.g: 3hours 5minutes").arg(QString::fromUtf8(misc::toString(hours).c_str())).arg(QString::fromUtf8(misc::toString(minutes).c_str())); return tr("%1h%2m", "e.g: 3hours 5minutes").arg(QString::number(hours)).arg(QString::number(minutes));
} }
int days = hours / 24; int days = hours / 24;
hours = hours - days * 24; hours = hours - days * 24;
if(days < 100) { if(days < 100) {
return tr("%1d%2h%3m", "e.g: 2days 10hours 2minutes").arg(QString::fromUtf8(misc::toString(days).c_str())).arg(QString::fromUtf8(misc::toString(hours).c_str())).arg(QString::fromUtf8(misc::toString(minutes).c_str())); return tr("%1d%2h%3m", "e.g: 2days 10hours 2minutes").arg(QString::number(days)).arg(QString::number(hours)).arg(QString::number(minutes));
} }
return QString::fromUtf8(""); return QString::fromUtf8("");
} }

View file

@ -279,7 +279,7 @@ void PeerListWidget::saveSettings() const {
else else
sortOrderLetter = QString::fromUtf8("d"); sortOrderLetter = QString::fromUtf8("d");
int index = header()->sortIndicatorSection(); int index = header()->sortIndicatorSection();
settings.setValue(QString::fromUtf8("TorrentProperties/Peers/PeerListSortedCol"), misc::toQString(index)+sortOrderLetter); settings.setValue(QString::fromUtf8("TorrentProperties/Peers/PeerListSortedCol"), QString::number(index)+sortOrderLetter);
} }
void PeerListWidget::loadPeers(const QTorrentHandle &h, bool force_hostname_resolution) { void PeerListWidget::loadPeers(const QTorrentHandle &h, bool force_hostname_resolution) {

View file

@ -326,7 +326,7 @@ size_type QTorrentHandle::total_redundant_bytes() const {
return h.status().total_redundant_bytes; return h.status().total_redundant_bytes;
} }
void QTorrentHandle::file_progress(std::vector<size_type>& fp) { void QTorrentHandle::file_progress(std::vector<size_type>& fp) const {
Q_ASSERT(h.is_valid()); Q_ASSERT(h.is_valid());
return h.file_progress(fp); return h.file_progress(fp);
} }
@ -336,27 +336,27 @@ bool QTorrentHandle::is_checking() const {
return h.status().state == torrent_status::checking_files || h.status().state == torrent_status::checking_resume_data; return h.status().state == torrent_status::checking_files || h.status().state == torrent_status::checking_resume_data;
} }
size_type QTorrentHandle::total_done() { size_type QTorrentHandle::total_done() const {
Q_ASSERT(h.is_valid()); Q_ASSERT(h.is_valid());
return h.status().total_done; return h.status().total_done;
} }
size_type QTorrentHandle::all_time_download() { size_type QTorrentHandle::all_time_download() const {
Q_ASSERT(h.is_valid()); Q_ASSERT(h.is_valid());
return h.status().all_time_download; return h.status().all_time_download;
} }
size_type QTorrentHandle::all_time_upload() { size_type QTorrentHandle::all_time_upload() const {
Q_ASSERT(h.is_valid()); Q_ASSERT(h.is_valid());
return h.status().all_time_upload; return h.status().all_time_upload;
} }
size_type QTorrentHandle::total_payload_download() { size_type QTorrentHandle::total_payload_download() const {
Q_ASSERT(h.is_valid()); Q_ASSERT(h.is_valid());
return h.status().total_payload_download; return h.status().total_payload_download;
} }
size_type QTorrentHandle::total_payload_upload() { size_type QTorrentHandle::total_payload_upload() const {
Q_ASSERT(h.is_valid()); Q_ASSERT(h.is_valid());
return h.status().total_payload_upload; return h.status().total_payload_upload;
} }
@ -481,12 +481,12 @@ void QTorrentHandle::resume() {
void QTorrentHandle::remove_url_seed(QString seed) { void QTorrentHandle::remove_url_seed(QString seed) {
Q_ASSERT(h.is_valid()); Q_ASSERT(h.is_valid());
h.remove_url_seed(misc::toString((const char*)seed.toLocal8Bit())); h.remove_url_seed(seed.toStdString());
} }
void QTorrentHandle::add_url_seed(QString seed) { void QTorrentHandle::add_url_seed(QString seed) {
Q_ASSERT(h.is_valid()); Q_ASSERT(h.is_valid());
h.add_url_seed(misc::toString((const char*)seed.toLocal8Bit())); h.add_url_seed(seed.toStdString());
} }
void QTorrentHandle::set_max_uploads(int val) { void QTorrentHandle::set_max_uploads(int val) {

View file

@ -102,12 +102,12 @@ class QTorrentHandle {
QString comment() const; QString comment() const;
size_type total_failed_bytes() const; size_type total_failed_bytes() const;
size_type total_redundant_bytes() const; size_type total_redundant_bytes() const;
void file_progress(std::vector<size_type>& fp); void file_progress(std::vector<size_type>& fp) const;
size_type total_payload_download(); size_type total_payload_download() const;
size_type total_payload_upload(); size_type total_payload_upload() const;
size_type all_time_upload(); size_type all_time_upload() const;
size_type all_time_download(); size_type all_time_download() const;
size_type total_done(); size_type total_done() const;
QStringList files_path() const; QStringList files_path() const;
int num_uploads() const; int num_uploads() const;
bool is_seed() const; bool is_seed() const;

View file

@ -301,11 +301,11 @@ void SearchEngine::saveResultsColumnsWidth() {
new_width_list << width_list.at(i); new_width_list << width_list.at(i);
} else if(treeview->columnWidth(i)>=1) { } else if(treeview->columnWidth(i)>=1) {
// usual case, save the current width // usual case, save the current width
new_width_list << QString::fromUtf8(misc::toString(treeview->columnWidth(i)).c_str()); new_width_list << QString::number(treeview->columnWidth(i));
} else { } else {
// default width // default width
treeview->resizeColumnToContents(i); treeview->resizeColumnToContents(i);
new_width_list << QString::fromUtf8(misc::toString(treeview->columnWidth(i)).c_str()); new_width_list << QString::number(treeview->columnWidth(i));
} }
} }
settings.setValue("SearchResultsColsWidth", new_width_list.join(" ")); settings.setValue("SearchResultsColsWidth", new_width_list.join(" "));
@ -353,7 +353,7 @@ void SearchEngine::readSearchOutput(){
appendSearchResult(QString::fromUtf8(line)); appendSearchResult(QString::fromUtf8(line));
} }
if(currentSearchTab) if(currentSearchTab)
currentSearchTab->getCurrentLabel()->setText(tr("Results")+QString::fromUtf8(" <i>(")+misc::toQString(nb_search_results)+QString::fromUtf8(")</i>:")); currentSearchTab->getCurrentLabel()->setText(tr("Results")+QString::fromUtf8(" <i>(")+QString::number(nb_search_results)+QString::fromUtf8(")</i>:"));
} }
void SearchEngine::downloadFinished(int exitcode, QProcess::ExitStatus) { void SearchEngine::downloadFinished(int exitcode, QProcess::ExitStatus) {
@ -478,7 +478,7 @@ void SearchEngine::searchFinished(int exitcode,QProcess::ExitStatus){
} }
} }
if(currentSearchTab) if(currentSearchTab)
currentSearchTab->getCurrentLabel()->setText(tr("Results", "i.e: Search results")+QString::fromUtf8(" <i>(")+misc::toQString(nb_search_results)+QString::fromUtf8(")</i>:")); currentSearchTab->getCurrentLabel()->setText(tr("Results", "i.e: Search results")+QString::fromUtf8(" <i>(")+QString::number(nb_search_results)+QString::fromUtf8(")</i>:"));
search_button->setText("Search"); search_button->setText("Search");
} }

View file

@ -1200,11 +1200,11 @@ void TransferListWidget::saveColWidthList() {
new_width_list << width_list.at(i); new_width_list << width_list.at(i);
} else if(columnWidth(i)>=1) { } else if(columnWidth(i)>=1) {
// usual case, save the current width // usual case, save the current width
new_width_list << misc::toQString(columnWidth(i)); new_width_list << QString::number(columnWidth(i));
} else { } else {
// default width // default width
resizeColumnToContents(i); resizeColumnToContents(i);
new_width_list << misc::toQString(columnWidth(i)); new_width_list << QString::number(columnWidth(i));
} }
} }
settings.setValue(QString::fromUtf8("TransferListColsWidth"), new_width_list.join(QString::fromUtf8(" "))); settings.setValue(QString::fromUtf8("TransferListColsWidth"), new_width_list.join(QString::fromUtf8(" ")));
@ -1262,7 +1262,7 @@ void TransferListWidget::saveLastSortedColumn() {
else else
sortOrderLetter = QString::fromUtf8("d"); sortOrderLetter = QString::fromUtf8("d");
int index = header()->sortIndicatorSection(); int index = header()->sortIndicatorSection();
settings.setValue(QString::fromUtf8("TransferListSortedCol"), misc::toQString(index)+sortOrderLetter); settings.setValue(QString::fromUtf8("TransferListSortedCol"), QString::number(index)+sortOrderLetter);
} }
void TransferListWidget::loadLastSortedColumn() { void TransferListWidget::loadLastSortedColumn() {