Browse Source

Don't use Preferences in BitTorrent::Session

adaptive-webui-19844
Vladimir Golovnev (Glassez) 9 years ago
parent
commit
b2cb473b63
  1. 3
      src/app/application.cpp
  2. 3
      src/base/base.pri
  3. 5
      src/base/bittorrent/private/bandwidthscheduler.cpp
  4. 1994
      src/base/bittorrent/session.cpp
  5. 257
      src/base/bittorrent/session.h
  6. 2
      src/base/bittorrent/torrenthandle.cpp
  7. 31
      src/base/net/downloadmanager.cpp
  8. 160
      src/base/net/proxyconfigurationmanager.cpp
  9. 87
      src/base/net/proxyconfigurationmanager.h
  10. 684
      src/base/preferences.cpp
  11. 145
      src/base/preferences.h
  12. 88
      src/base/settingsstorage.cpp
  13. 73
      src/base/settingvalue.h
  14. 82
      src/gui/advancedsettings.cpp
  15. 26
      src/gui/mainwindow.cpp
  16. 243
      src/gui/optionsdlg.cpp
  17. 7
      src/gui/optionsdlg.h
  18. 2
      src/gui/properties/trackerlist.cpp
  19. 73
      src/gui/statusbar.cpp
  20. 12
      src/gui/transferlistwidget.cpp
  21. 24
      src/gui/updownratiodlg.cpp
  22. 16
      src/webui/btjson.cpp
  23. 212
      src/webui/prefjson.cpp
  24. 30
      src/webui/webapplication.cpp

3
src/app/application.cpp

@ -70,6 +70,7 @@
#include "base/net/smtp.h" #include "base/net/smtp.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
#include "base/net/geoipmanager.h" #include "base/net/geoipmanager.h"
#include "base/net/proxyconfigurationmanager.h"
#include "base/bittorrent/session.h" #include "base/bittorrent/session.h"
#include "base/bittorrent/torrenthandle.h" #include "base/bittorrent/torrenthandle.h"
@ -393,6 +394,7 @@ void Application::processParams(const QStringList &params)
int Application::exec(const QStringList &params) int Application::exec(const QStringList &params)
{ {
Net::ProxyConfigurationManager::initInstance();
Net::DownloadManager::initInstance(); Net::DownloadManager::initInstance();
#ifdef DISABLE_GUI #ifdef DISABLE_GUI
IconProvider::initInstance(); IconProvider::initInstance();
@ -619,6 +621,7 @@ void Application::cleanup()
Net::GeoIPManager::freeInstance(); Net::GeoIPManager::freeInstance();
#endif #endif
Net::DownloadManager::freeInstance(); Net::DownloadManager::freeInstance();
Net::ProxyConfigurationManager::freeInstance();
Preferences::freeInstance(); Preferences::freeInstance();
SettingsStorage::freeInstance(); SettingsStorage::freeInstance();
delete m_fileLogger; delete m_fileLogger;

3
src/base/base.pri

@ -5,6 +5,7 @@ HEADERS += \
$$PWD/qinisettings.h \ $$PWD/qinisettings.h \
$$PWD/logger.h \ $$PWD/logger.h \
$$PWD/settingsstorage.h \ $$PWD/settingsstorage.h \
$$PWD/settingvalue.h \
$$PWD/preferences.h \ $$PWD/preferences.h \
$$PWD/indexrange.h \ $$PWD/indexrange.h \
$$PWD/iconprovider.h \ $$PWD/iconprovider.h \
@ -20,6 +21,7 @@ HEADERS += \
$$PWD/net/downloadhandler.h \ $$PWD/net/downloadhandler.h \
$$PWD/net/geoipmanager.h \ $$PWD/net/geoipmanager.h \
$$PWD/net/portforwarder.h \ $$PWD/net/portforwarder.h \
$$PWD/net/proxyconfigurationmanager.h \
$$PWD/net/reverseresolution.h \ $$PWD/net/reverseresolution.h \
$$PWD/net/smtp.h \ $$PWD/net/smtp.h \
$$PWD/net/private/geoipdatabase.h \ $$PWD/net/private/geoipdatabase.h \
@ -74,6 +76,7 @@ SOURCES += \
$$PWD/net/downloadhandler.cpp \ $$PWD/net/downloadhandler.cpp \
$$PWD/net/geoipmanager.cpp \ $$PWD/net/geoipmanager.cpp \
$$PWD/net/portforwarder.cpp \ $$PWD/net/portforwarder.cpp \
$$PWD/net/proxyconfigurationmanager.cpp \
$$PWD/net/reverseresolution.cpp \ $$PWD/net/reverseresolution.cpp \
$$PWD/net/smtp.cpp \ $$PWD/net/smtp.cpp \
$$PWD/net/private/geoipdatabase.cpp \ $$PWD/net/private/geoipdatabase.cpp \

5
src/base/bittorrent/private/bandwidthscheduler.cpp

@ -31,13 +31,13 @@
#include <QTime> #include <QTime>
#include <QDateTime> #include <QDateTime>
#include "base/bittorrent/session.h"
#include "base/preferences.h" #include "base/preferences.h"
#include "bandwidthscheduler.h" #include "bandwidthscheduler.h"
BandwidthScheduler::BandwidthScheduler(QObject *parent) BandwidthScheduler::BandwidthScheduler(QObject *parent)
: QTimer(parent) : QTimer(parent)
{ {
Q_ASSERT(Preferences::instance()->isSchedulerEnabled());
// Single shot, we call start() again manually // Single shot, we call start() again manually
setSingleShot(true); setSingleShot(true);
// Connect Signals/Slots // Connect Signals/Slots
@ -47,8 +47,7 @@ BandwidthScheduler::BandwidthScheduler(QObject *parent)
void BandwidthScheduler::start() void BandwidthScheduler::start()
{ {
const Preferences* const pref = Preferences::instance(); const Preferences* const pref = Preferences::instance();
Q_ASSERT(pref->isSchedulerEnabled()); bool alt_bw_enabled = BitTorrent::Session::instance()->isAltGlobalSpeedLimitEnabled();
bool alt_bw_enabled = pref->isAltBandwidthEnabled();
QTime start = pref->getSchedulerStartTime(); QTime start = pref->getSchedulerStartTime();
QTime end = pref->getSchedulerEndTime(); QTime end = pref->getSchedulerEndTime();

1994
src/base/bittorrent/session.cpp

File diff suppressed because it is too large Load Diff

257
src/base/bittorrent/session.h

@ -30,17 +30,22 @@
#ifndef BITTORRENT_SESSION_H #ifndef BITTORRENT_SESSION_H
#define BITTORRENT_SESSION_H #define BITTORRENT_SESSION_H
#include <vector>
#include <libtorrent/version.hpp>
#include <QFile> #include <QFile>
#include <QHash> #include <QHash>
#include <QMap> #include <QMap>
#if LIBTORRENT_VERSION_NUM < 10100
#include <QMutex>
#endif
#include <QNetworkConfigurationManager>
#include <QPointer> #include <QPointer>
#include <QStringList>
#include <QVector> #include <QVector>
#include <QMutex>
#include <QWaitCondition> #include <QWaitCondition>
#include <QNetworkConfigurationManager>
#include <libtorrent/version.hpp>
#include "base/settingvalue.h"
#include "base/tristatebool.h" #include "base/tristatebool.h"
#include "base/types.h" #include "base/types.h"
#include "torrentinfo.h" #include "torrentinfo.h"
@ -55,17 +60,6 @@ namespace libtorrent
struct session_settings; struct session_settings;
struct session_status; struct session_status;
#if LIBTORRENT_VERSION_NUM < 10100
struct proxy_settings;
#else
namespace aux
{
struct proxy_settings;
}
typedef aux::proxy_settings proxy_settings;
#endif
class alert; class alert;
struct torrent_alert; struct torrent_alert;
struct state_update_alert; struct state_update_alert;
@ -111,7 +105,6 @@ class FilterParserThread;
class BandwidthScheduler; class BandwidthScheduler;
class Statistics; class Statistics;
class ResumeDataSavingManager; class ResumeDataSavingManager;
class SettingsStorage;
enum MaxRatioAction enum MaxRatioAction
{ {
@ -172,13 +165,6 @@ namespace BitTorrent
static void freeInstance(); static void freeInstance();
static Session *instance(); static Session *instance();
bool isDHTEnabled() const;
bool isLSDEnabled() const;
bool isPexEnabled() const;
bool isQueueingEnabled() const;
qreal globalMaxRatio() const;
bool isAppendExtensionEnabled() const;
QString defaultSavePath() const; QString defaultSavePath() const;
void setDefaultSavePath(QString path); void setDefaultSavePath(QString path);
QString tempPath() const; QString tempPath() const;
@ -219,8 +205,122 @@ namespace BitTorrent
bool isDisableAutoTMMWhenCategorySavePathChanged() const; bool isDisableAutoTMMWhenCategorySavePathChanged() const;
void setDisableAutoTMMWhenCategorySavePathChanged(bool value); void setDisableAutoTMMWhenCategorySavePathChanged(bool value);
qreal globalMaxRatio() const;
void setGlobalMaxRatio(qreal ratio);
bool isDHTEnabled() const;
void setDHTEnabled(bool enabled);
bool isLSDEnabled() const;
void setLSDEnabled(bool enabled);
bool isPeXEnabled() const;
void setPeXEnabled(bool enabled);
bool isTrackerExchangeEnabled() const;
void setTrackerExchangeEnabled(bool enabled);
bool isAddTorrentPaused() const; bool isAddTorrentPaused() const;
void setAddTorrentPaused(bool value); void setAddTorrentPaused(bool value);
bool isTrackerEnabled() const;
void setTrackerEnabled(bool enabled);
bool isAppendExtensionEnabled() const;
void setAppendExtensionEnabled(bool enabled);
uint refreshInterval() const;
void setRefreshInterval(uint value);
bool isPreallocationEnabled() const;
void setPreallocationEnabled(bool enabled);
QString torrentExportDirectory() const;
void setTorrentExportDirectory(const QString &path);
QString finishedTorrentExportDirectory() const;
void setFinishedTorrentExportDirectory(const QString &path);
int globalDownloadSpeedLimit() const;
void setGlobalDownloadSpeedLimit(int limit);
int globalUploadSpeedLimit() const;
void setGlobalUploadSpeedLimit(int limit);
int altGlobalDownloadSpeedLimit() const;
void setAltGlobalDownloadSpeedLimit(int limit);
int altGlobalUploadSpeedLimit() const;
void setAltGlobalUploadSpeedLimit(int limit);
int downloadSpeedLimit() const;
void setDownloadSpeedLimit(int limit);
int uploadSpeedLimit() const;
void setUploadSpeedLimit(int limit);
bool isAltGlobalSpeedLimitEnabled() const;
void setAltGlobalSpeedLimitEnabled(bool enabled);
bool isBandwidthSchedulerEnabled() const;
void setBandwidthSchedulerEnabled(bool enabled);
uint saveResumeDataInterval() const;
void setSaveResumeDataInterval(uint value);
int port() const;
void setPort(int port);
bool useRandomPort() const;
void setUseRandomPort(bool value);
QString networkInterface() const;
void setNetworkInterface(const QString &interface);
QString networkInterfaceAddress() const;
void setNetworkInterfaceAddress(const QString &address);
bool isIPv6Enabled() const;
void setIPv6Enabled(bool enabled);
int encryption() const;
void setEncryption(int state);
bool isForceProxyEnabled() const;
void setForceProxyEnabled(bool enabled);
bool isProxyPeerConnectionsEnabled() const;
void setProxyPeerConnectionsEnabled(bool enabled);
bool isAddTrackersEnabled() const;
void setAddTrackersEnabled(bool enabled);
QString additionalTrackers() const;
void setAdditionalTrackers(const QString &trackers);
bool isFilteringEnabled() const;
void setFilteringEnabled(bool enabled);
QString IPFilterFile() const;
void setIPFilterFile(QString path);
bool announceToAllTrackers() const;
void setAnnounceToAllTrackers(bool val);
uint diskCacheSize() const;
void setDiskCacheSize(uint size);
uint diskCacheTTL() const;
void setDiskCacheTTL(uint ttl);
bool useOSCache() const;
void setUseOSCache(bool use);
bool isAnonymousModeEnabled() const;
void setAnonymousModeEnabled(bool enabled);
bool isQueueingSystemEnabled() const;
void setQueueingSystemEnabled(bool enabled);
bool ignoreSlowTorrentsForQueueing() const;
void setIgnoreSlowTorrentsForQueueing(bool ignore);
uint outgoingPortsMin() const;
void setOutgoingPortsMin(uint min);
uint outgoingPortsMax() const;
void setOutgoingPortsMax(uint max);
bool ignoreLimitsOnLAN() const;
void setIgnoreLimitsOnLAN(bool ignore);
bool includeOverheadInLimits() const;
void setIncludeOverheadInLimits(bool include);
QString networkAddress() const;
void setNetworkAddress(const QString &addr);
bool isSuperSeedingEnabled() const;
void setSuperSeedingEnabled(bool enabled);
int maxConnections() const;
void setMaxConnections(int max);
int maxHalfOpenConnections() const;
void setMaxHalfOpenConnections(int max);
int maxConnectionsPerTorrent() const;
void setMaxConnectionsPerTorrent(int max);
int maxUploads() const;
void setMaxUploads(int max);
int maxUploadsPerTorrent() const;
void setMaxUploadsPerTorrent(int max);
int maxActiveDownloads() const;
void setMaxActiveDownloads(int max);
int maxActiveUploads() const;
void setMaxActiveUploads(int max);
int maxActiveTorrents() const;
void setMaxActiveTorrents(int max);
bool isUTPEnabled() const;
void setUTPEnabled(bool enabled);
bool isUTPRateLimited() const;
void setUTPRateLimited(bool limited);
bool isTrackerFilteringEnabled() const;
void setTrackerFilteringEnabled(bool enabled);
TorrentHandle *findTorrent(const InfoHash &hash) const; TorrentHandle *findTorrent(const InfoHash &hash) const;
QHash<InfoHash, TorrentHandle *> torrents() const; QHash<InfoHash, TorrentHandle *> torrents() const;
@ -231,17 +331,11 @@ namespace BitTorrent
CacheStatus cacheStatus() const; CacheStatus cacheStatus() const;
quint64 getAlltimeDL() const; quint64 getAlltimeDL() const;
quint64 getAlltimeUL() const; quint64 getAlltimeUL() const;
int downloadRateLimit() const;
int uploadRateLimit() const;
bool isListening() const; bool isListening() const;
MaxRatioAction maxRatioAction() const; MaxRatioAction maxRatioAction() const;
void setMaxRatioAction(MaxRatioAction act); void setMaxRatioAction(MaxRatioAction act);
void changeSpeedLimitMode(bool alternative);
void setDownloadRateLimit(int rate);
void setUploadRateLimit(int rate);
void setGlobalMaxRatio(qreal ratio);
void enableIPFilter(const QString &filterPath, bool force = false); void enableIPFilter(const QString &filterPath, bool force = false);
void disableIPFilter(); void disableIPFilter();
void banIP(const QString &ip); void banIP(const QString &ip);
@ -304,7 +398,7 @@ namespace BitTorrent
void trackerAuthenticationRequired(BitTorrent::TorrentHandle *const torrent); void trackerAuthenticationRequired(BitTorrent::TorrentHandle *const torrent);
void recursiveTorrentDownloadPossible(BitTorrent::TorrentHandle *const torrent); void recursiveTorrentDownloadPossible(BitTorrent::TorrentHandle *const torrent);
void speedLimitModeChanged(bool alternative); void speedLimitModeChanged(bool alternative);
void ipFilterParsed(bool error, int ruleCount); void IPFilterParsed(bool error, int ruleCount);
void trackersAdded(BitTorrent::TorrentHandle *const torrent, const QList<BitTorrent::TrackerEntry> &trackers); void trackersAdded(BitTorrent::TorrentHandle *const torrent, const QList<BitTorrent::TrackerEntry> &trackers);
void trackersRemoved(BitTorrent::TorrentHandle *const torrent, const QList<BitTorrent::TrackerEntry> &trackers); void trackersRemoved(BitTorrent::TorrentHandle *const torrent, const QList<BitTorrent::TrackerEntry> &trackers);
void trackersChanged(BitTorrent::TorrentHandle *const torrent); void trackersChanged(BitTorrent::TorrentHandle *const torrent);
@ -316,7 +410,7 @@ namespace BitTorrent
void subcategoriesSupportChanged(); void subcategoriesSupportChanged();
private slots: private slots:
void configure(); void configureDeferred();
void readAlerts(); void readAlerts();
void refresh(); void refresh();
void processBigRatios(); void processBigRatios();
@ -341,20 +435,19 @@ namespace BitTorrent
void initResumeFolder(); void initResumeFolder();
// Session configuration // Session configuration
void setSessionSettings(); Q_INVOKABLE void configure();
void setProxySettings(libtorrent::proxy_settings proxySettings);
void adjustLimits(); void adjustLimits();
void adjustLimits(libtorrent::session_settings &sessionSettings); void adjustLimits(libtorrent::session_settings &sessionSettings);
const QStringList getListeningIPs(); const QStringList getListeningIPs();
void setListeningPort(); void configureListeningInterface();
void preAllocateAllFiles(bool b);
void setMaxConnectionsPerTorrent(int max);
void setMaxUploadsPerTorrent(int max);
void enableLSD(bool enable); void enableLSD(bool enable);
void enableDHT(bool enable); void enableDHT(bool enable);
void changeSpeedLimitMode_impl(bool alternative); void changeSpeedLimitMode_impl(bool alternative);
void enableTracker(bool enable);
void setAppendExtension(bool append); void enableBandwidthScheduler();
void populateAdditionalTrackers();
void configureEncryption();
void configureProxy();
void startUpTorrents(); void startUpTorrents();
bool addTorrent_impl(AddTorrentData addData, const MagnetUri &magnetUri, bool addTorrent_impl(AddTorrentData addData, const MagnetUri &magnetUri,
@ -393,31 +486,85 @@ namespace BitTorrent
#endif #endif
void getPendingAlerts(std::vector<libtorrent::alert *> &out, ulong time = 0); void getPendingAlerts(std::vector<libtorrent::alert *> &out, ulong time = 0);
SettingsStorage *m_settings;
// BitTorrent // BitTorrent
libtorrent::session *m_nativeSession; libtorrent::session *m_nativeSession;
bool m_LSDEnabled; bool m_deferredConfigureScheduled;
bool m_DHTEnabled; CachedSettingValue<bool> m_isDHTEnabled;
bool m_PeXEnabled; CachedSettingValue<bool> m_isLSDEnabled;
bool m_queueingEnabled; CachedSettingValue<bool> m_isPeXEnabled;
bool m_torrentExportEnabled; CachedSettingValue<bool> m_isTrackerExchangeEnabled;
bool m_finishedTorrentExportEnabled; CachedSettingValue<bool> m_isFilteringEnabled;
bool m_preAllocateAll; CachedSettingValue<bool> m_isTrackerFilteringEnabled;
qreal m_globalMaxRatio; CachedSettingValue<QString> m_IPFilterFile;
CachedSettingValue<bool> m_announceToAllTrackers;
CachedSettingValue<uint> m_diskCacheSize;
CachedSettingValue<uint> m_diskCacheTTL;
CachedSettingValue<bool> m_useOSCache;
CachedSettingValue<bool> m_isAnonymousModeEnabled;
CachedSettingValue<bool> m_isQueueingEnabled;
CachedSettingValue<int> m_maxActiveDownloads;
CachedSettingValue<int> m_maxActiveUploads;
CachedSettingValue<int> m_maxActiveTorrents;
CachedSettingValue<bool> m_ignoreSlowTorrentsForQueueing;
CachedSettingValue<uint> m_outgoingPortsMin;
CachedSettingValue<uint> m_outgoingPortsMax;
CachedSettingValue<bool> m_ignoreLimitsOnLAN;
CachedSettingValue<bool> m_includeOverheadInLimits;
CachedSettingValue<QString> m_networkAddress;
CachedSettingValue<bool> m_isSuperSeedingEnabled;
CachedSettingValue<int> m_maxConnections;
CachedSettingValue<int> m_maxHalfOpenConnections;
CachedSettingValue<int> m_maxUploads;
CachedSettingValue<int> m_maxConnectionsPerTorrent;
CachedSettingValue<int> m_maxUploadsPerTorrent;
CachedSettingValue<bool> m_isUTPEnabled;
CachedSettingValue<bool> m_isUTPRateLimited;
CachedSettingValue<bool> m_isAddTrackersEnabled;
CachedSettingValue<QString> m_additionalTrackers;
CachedSettingValue<qreal> m_globalMaxRatio;
CachedSettingValue<bool> m_isAddTorrentPaused;
CachedSettingValue<bool> m_isAppendExtensionEnabled;
CachedSettingValue<uint> m_refreshInterval;
CachedSettingValue<bool> m_isPreallocationEnabled;
CachedSettingValue<QString> m_torrentExportDirectory;
CachedSettingValue<QString> m_finishedTorrentExportDirectory;
CachedSettingValue<int> m_globalDownloadSpeedLimit;
CachedSettingValue<int> m_globalUploadSpeedLimit;
CachedSettingValue<int> m_altGlobalDownloadSpeedLimit;
CachedSettingValue<int> m_altGlobalUploadSpeedLimit;
CachedSettingValue<bool> m_isAltGlobalSpeedLimitEnabled;
CachedSettingValue<bool> m_isBandwidthSchedulerEnabled;
CachedSettingValue<uint> m_saveResumeDataInterval;
CachedSettingValue<int> m_port;
CachedSettingValue<bool> m_useRandomPort;
CachedSettingValue<QString> m_networkInterface;
CachedSettingValue<QString> m_networkInterfaceAddress;
CachedSettingValue<bool> m_isIPv6Enabled;
CachedSettingValue<int> m_encryption;
CachedSettingValue<bool> m_isForceProxyEnabled;
CachedSettingValue<bool> m_isProxyPeerConnectionsEnabled;
CachedSettingValue<QVariantMap> m_storedCategories;
CachedSettingValue<int> m_maxRatioAction;
CachedSettingValue<QString> m_defaultSavePath;
CachedSettingValue<QString> m_tempPath;
CachedSettingValue<bool> m_isSubcategoriesEnabled;
CachedSettingValue<bool> m_isTempPathEnabled;
CachedSettingValue<bool> m_isAutoTMMDisabledByDefault;
CachedSettingValue<bool> m_isDisableAutoTMMWhenCategoryChanged;
CachedSettingValue<bool> m_isDisableAutoTMMWhenDefaultSavePathChanged;
CachedSettingValue<bool> m_isDisableAutoTMMWhenCategorySavePathChanged;
CachedSettingValue<bool> m_isTrackerEnabled;
CachedSettingValue<QStringList> m_bannedIPs;
int m_numResumeData; int m_numResumeData;
int m_extraLimit; int m_extraLimit;
bool m_appendExtension; QList<BitTorrent::TrackerEntry> m_additionalTrackerList;
uint m_refreshInterval;
MaxRatioAction m_maxRatioAction;
QList<BitTorrent::TrackerEntry> m_additionalTrackers;
QString m_defaultSavePath;
QString m_tempPath;
QString m_filterPath; QString m_filterPath;
QString m_resumeFolderPath; QString m_resumeFolderPath;
QFile m_resumeFolderLock; QFile m_resumeFolderLock;
QHash<InfoHash, QString> m_savePathsToRemove; QHash<InfoHash, QString> m_savePathsToRemove;
bool m_useProxy;
QTimer *m_refreshTimer; QTimer *m_refreshTimer;
QTimer *m_bigRatioTimer; QTimer *m_bigRatioTimer;

2
src/base/bittorrent/torrenthandle.cpp

@ -752,7 +752,7 @@ void TorrentHandle::updateState()
m_state = isSeed() ? TorrentState::PausedUploading : TorrentState::PausedDownloading; m_state = isSeed() ? TorrentState::PausedUploading : TorrentState::PausedDownloading;
} }
else { else {
if (m_session->isQueueingEnabled() && isQueued() && !isChecking()) { if (m_session->isQueueingSystemEnabled() && isQueued() && !isChecking()) {
m_state = isSeed() ? TorrentState::QueuedUploading : TorrentState::QueuedDownloading; m_state = isSeed() ? TorrentState::QueuedUploading : TorrentState::QueuedDownloading;
} }
else { else {

31
src/base/net/downloadmanager.cpp

@ -27,20 +27,21 @@
* exception statement from your version. * exception statement from your version.
*/ */
#include "downloadmanager.h"
#include <QDateTime> #include <QDateTime>
#include <QNetworkRequest> #include <QDebug>
#include <QNetworkProxy>
#include <QNetworkCookieJar>
#include <QNetworkReply>
#include <QNetworkCookie> #include <QNetworkCookie>
#include <QNetworkCookieJar> #include <QNetworkCookieJar>
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslError> #include <QSslError>
#include <QUrl> #include <QUrl>
#include <QDebug>
#include "base/preferences.h" #include "base/preferences.h"
#include "downloadhandler.h" #include "downloadhandler.h"
#include "downloadmanager.h" #include "proxyconfigurationmanager.h"
// Spoof Firefox 38 user agent to avoid web server banning // Spoof Firefox 38 user agent to avoid web server banning
const char DEFAULT_USER_AGENT[] = "Mozilla/5.0 (X11; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0"; const char DEFAULT_USER_AGENT[] = "Mozilla/5.0 (X11; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0";
@ -208,16 +209,16 @@ bool DownloadManager::deleteCookie(const QNetworkCookie &cookie)
void DownloadManager::applyProxySettings() void DownloadManager::applyProxySettings()
{ {
auto proxyManager = ProxyConfigurationManager::instance();
ProxyConfiguration proxyConfig = proxyManager->proxyConfiguration();
QNetworkProxy proxy; QNetworkProxy proxy;
const Preferences* const pref = Preferences::instance();
if (pref->isProxyEnabled() && !pref->isProxyOnlyForTorrents()) { if (!proxyManager->isProxyDisabled() && (proxyConfig.type != ProxyType::None)) {
// Proxy enabled // Proxy enabled
proxy.setHostName(pref->getProxyIp()); proxy.setHostName(proxyConfig.ip);
proxy.setPort(pref->getProxyPort()); proxy.setPort(proxyConfig.port);
// Default proxy type is HTTP, we must change if it is SOCKS5 // Default proxy type is HTTP, we must change if it is SOCKS5
const int proxyType = pref->getProxyType(); if ((proxyConfig.type == ProxyType::SOCKS5) || (proxyConfig.type == ProxyType::SOCKS5_PW)) {
if ((proxyType == Proxy::SOCKS5) || (proxyType == Proxy::SOCKS5_PW)) {
qDebug() << Q_FUNC_INFO << "using SOCKS proxy"; qDebug() << Q_FUNC_INFO << "using SOCKS proxy";
proxy.setType(QNetworkProxy::Socks5Proxy); proxy.setType(QNetworkProxy::Socks5Proxy);
} }
@ -226,10 +227,10 @@ void DownloadManager::applyProxySettings()
proxy.setType(QNetworkProxy::HttpProxy); proxy.setType(QNetworkProxy::HttpProxy);
} }
// Authentication? // Authentication?
if (pref->isProxyAuthEnabled()) { if (proxyManager->isAuthenticationRequired()) {
qDebug("Proxy requires authentication, authenticating"); qDebug("Proxy requires authentication, authenticating");
proxy.setUser(pref->getProxyUsername()); proxy.setUser(proxyConfig.username);
proxy.setPassword(pref->getProxyPassword()); proxy.setPassword(proxyConfig.password);
} }
} }
else { else {

160
src/base/net/proxyconfigurationmanager.cpp

@ -0,0 +1,160 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2016 Vladimir Golovnev <glassez@yandex.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#include "proxyconfigurationmanager.h"
#include "base/settingsstorage.h"
#define SETTINGS_KEY(name) "Network/Proxy/" name
const QString KEY_DISABLED = SETTINGS_KEY("Disabled");
const QString KEY_TYPE = SETTINGS_KEY("Type");
const QString KEY_IP = SETTINGS_KEY("IP");
const QString KEY_PORT = SETTINGS_KEY("Port");
const QString KEY_AUTHENTICATION = SETTINGS_KEY("Authentication");
const QString KEY_USERNAME = SETTINGS_KEY("Username");
const QString KEY_PASSWORD = SETTINGS_KEY("Password");
namespace
{
inline SettingsStorage *settings() { return SettingsStorage::instance(); }
inline bool isSameConfig(const Net::ProxyConfiguration &conf1, const Net::ProxyConfiguration &conf2)
{
return conf1.type == conf2.type
&& conf1.ip == conf2.ip
&& conf1.port == conf2.port
&& conf1.username == conf2.username
&& conf1.password == conf2.password;
}
}
using namespace Net;
ProxyConfigurationManager *ProxyConfigurationManager::m_instance = nullptr;
ProxyConfigurationManager::ProxyConfigurationManager(QObject *parent)
: QObject(parent)
{
m_proxyDisabled = settings()->loadValue(KEY_DISABLED, false).toBool();
m_config.type = static_cast<ProxyType>(
settings()->loadValue(KEY_TYPE, static_cast<int>(ProxyType::None)).toInt());
if ((m_config.type < ProxyType::None) || (m_config.type > ProxyType::SOCKS4))
m_config.type = ProxyType::None;
m_config.ip = settings()->loadValue(KEY_IP, "0.0.0.0").toString();
m_config.port = static_cast<ushort>(settings()->loadValue(KEY_PORT, 8080).toUInt());
m_config.username = settings()->loadValue(KEY_USERNAME).toString();
m_config.password = settings()->loadValue(KEY_PASSWORD).toString();
}
void ProxyConfigurationManager::initInstance()
{
if (!m_instance)
m_instance = new ProxyConfigurationManager;
}
void ProxyConfigurationManager::freeInstance()
{
delete m_instance;
}
ProxyConfigurationManager *ProxyConfigurationManager::instance()
{
return m_instance;
}
ProxyConfiguration ProxyConfigurationManager::proxyConfiguration() const
{
return m_config;
}
void ProxyConfigurationManager::setProxyConfiguration(const ProxyConfiguration &config)
{
if (!isSameConfig(config, m_config)) {
m_config = config;
settings()->storeValue(KEY_TYPE, static_cast<int>(config.type));
settings()->storeValue(KEY_IP, config.ip);
settings()->storeValue(KEY_PORT, config.port);
settings()->storeValue(KEY_USERNAME, config.username);
settings()->storeValue(KEY_PASSWORD, config.password);
configureProxy();
emit proxyConfigurationChanged();
}
}
bool ProxyConfigurationManager::isProxyDisabled() const
{
return m_proxyDisabled;
}
void ProxyConfigurationManager::setProxyDisabled(bool disabled)
{
if (m_proxyDisabled != disabled) {
settings()->storeValue(KEY_DISABLED, disabled);
m_proxyDisabled = disabled;
}
}
bool ProxyConfigurationManager::isAuthenticationRequired() const
{
return m_config.type == ProxyType::SOCKS5_PW
|| m_config.type == ProxyType::HTTP_PW;
}
void ProxyConfigurationManager::configureProxy()
{
// Define environment variables for urllib in search engine plugins
QString proxyStrHTTP, proxyStrSOCK;
if (!m_proxyDisabled) {
switch (m_config.type) {
case ProxyType::HTTP_PW:
proxyStrHTTP = QString("http://%1:%2@%3:%4").arg(m_config.username)
.arg(m_config.password).arg(m_config.ip).arg(m_config.port);
break;
case ProxyType::HTTP:
proxyStrHTTP = QString("http://%1:%2").arg(m_config.ip).arg(m_config.port);
break;
case ProxyType::SOCKS5:
proxyStrSOCK = QString("%1:%2").arg(m_config.ip).arg(m_config.port);
break;
case ProxyType::SOCKS5_PW:
proxyStrSOCK = QString("%1:%2@%3:%4").arg(m_config.username)
.arg(m_config.password).arg(m_config.ip).arg(m_config.port);
break;
default:
qDebug("Disabling HTTP communications proxy");
}
qDebug("HTTP communications proxy string: %s"
, qPrintable((m_config.type == ProxyType::SOCKS5) || (m_config.type == ProxyType::SOCKS5_PW)
? proxyStrSOCK : proxyStrHTTP));
}
qputenv("http_proxy", proxyStrHTTP.toLocal8Bit());
qputenv("https_proxy", proxyStrHTTP.toLocal8Bit());
qputenv("sock_proxy", proxyStrSOCK.toLocal8Bit());
}

87
src/base/net/proxyconfigurationmanager.h

@ -0,0 +1,87 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2016 Vladimir Golovnev <glassez@yandex.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#ifndef NET_PROXYCONFIGURATIONMANAGER_H
#define NET_PROXYCONFIGURATIONMANAGER_H
#include <QObject>
namespace Net
{
enum class ProxyType
{
None = 0,
HTTP = 1,
SOCKS5 = 2,
HTTP_PW = 3,
SOCKS5_PW = 4,
SOCKS4 = 5
};
struct ProxyConfiguration
{
ProxyType type = ProxyType::None;
QString ip = "0.0.0.0";
ushort port = 8080;
QString username;
QString password;
};
class ProxyConfigurationManager: public QObject
{
Q_OBJECT
Q_DISABLE_COPY(ProxyConfigurationManager)
explicit ProxyConfigurationManager(QObject *parent = nullptr);
~ProxyConfigurationManager() = default;
public:
static void initInstance();
static void freeInstance();
static ProxyConfigurationManager *instance();
ProxyConfiguration proxyConfiguration() const;
void setProxyConfiguration(const ProxyConfiguration &config);
bool isProxyDisabled() const;
void setProxyDisabled(bool disabled);
bool isAuthenticationRequired() const;
signals:
void proxyConfigurationChanged();
private:
void configureProxy();
static ProxyConfigurationManager *m_instance;
ProxyConfiguration m_config;
bool m_proxyDisabled;
};
}
#endif // NET_PROXYCONFIGURATIONMANAGER_H

684
src/base/preferences.cpp

@ -50,8 +50,6 @@
#include <CoreServices/CoreServices.h> #include <CoreServices/CoreServices.h>
#endif #endif
#include <cstdlib>
#include "utils/fs.h" #include "utils/fs.h"
#include "utils/misc.h" #include "utils/misc.h"
#include "settingsstorage.h" #include "settingsstorage.h"
@ -60,10 +58,7 @@
Preferences* Preferences::m_instance = 0; Preferences* Preferences::m_instance = 0;
Preferences::Preferences() Preferences::Preferences() {}
: m_randomPort(rand() % 64512 + 1024)
{
}
Preferences *Preferences::instance() Preferences *Preferences::instance()
{ {
@ -165,16 +160,6 @@ void Preferences::setHideZeroComboValues(int n)
setValue("Preferences/General/HideZeroComboValues", n); setValue("Preferences/General/HideZeroComboValues", n);
} }
bool Preferences::useRandomPort() const
{
return value("Preferences/General/UseRandomPort", false).toBool();
}
void Preferences::setRandomPort(bool b)
{
setValue("Preferences/General/UseRandomPort", b);
}
bool Preferences::systrayIntegration() const bool Preferences::systrayIntegration() const
{ {
return value("Preferences/General/SystrayEnabled", true).toBool(); return value("Preferences/General/SystrayEnabled", true).toBool();
@ -267,16 +252,6 @@ void Preferences::setWinStartup(bool b)
#endif #endif
// Downloads // Downloads
bool Preferences::useIncompleteFilesExtension() const
{
return value("Preferences/Downloads/UseIncompleteExtension", false).toBool();
}
void Preferences::useIncompleteFilesExtension(bool enabled)
{
setValue("Preferences/Downloads/UseIncompleteExtension", enabled);
}
QString Preferences::lastLocationPath() const QString Preferences::lastLocationPath() const
{ {
return Utils::Fs::fromNativePath(value("Preferences/Downloads/LastLocationPath").toString()); return Utils::Fs::fromNativePath(value("Preferences/Downloads/LastLocationPath").toString());
@ -287,16 +262,6 @@ void Preferences::setLastLocationPath(const QString &path)
setValue("Preferences/Downloads/LastLocationPath", Utils::Fs::fromNativePath(path)); setValue("Preferences/Downloads/LastLocationPath", Utils::Fs::fromNativePath(path));
} }
bool Preferences::preAllocateAllFiles() const
{
return value("Preferences/Downloads/PreAllocation", false).toBool();
}
void Preferences::preAllocateAllFiles(bool enabled)
{
return setValue("Preferences/Downloads/PreAllocation", enabled);
}
QVariantHash Preferences::getScanDirs() const QVariantHash Preferences::getScanDirs() const
{ {
return value("Preferences/Downloads/ScanDirsV2").toHash(); return value("Preferences/Downloads/ScanDirsV2").toHash();
@ -318,36 +283,6 @@ void Preferences::setScanDirsLastPath(const QString &path)
setValue("Preferences/Downloads/ScanDirsLastPath", Utils::Fs::fromNativePath(path)); setValue("Preferences/Downloads/ScanDirsLastPath", Utils::Fs::fromNativePath(path));
} }
bool Preferences::isTorrentExportEnabled() const
{
return !value("Preferences/Downloads/TorrentExportDir").toString().isEmpty();
}
QString Preferences::getTorrentExportDir() const
{
return Utils::Fs::fromNativePath(value("Preferences/Downloads/TorrentExportDir").toString());
}
void Preferences::setTorrentExportDir(QString path)
{
setValue("Preferences/Downloads/TorrentExportDir", Utils::Fs::fromNativePath(path.trimmed()));
}
bool Preferences::isFinishedTorrentExportEnabled() const
{
return !value("Preferences/Downloads/FinishedTorrentExportDir").toString().isEmpty();
}
QString Preferences::getFinishedTorrentExportDir() const
{
return Utils::Fs::fromNativePath(value("Preferences/Downloads/FinishedTorrentExportDir").toString());
}
void Preferences::setFinishedTorrentExportDir(QString path)
{
setValue("Preferences/Downloads/FinishedTorrentExportDir", Utils::Fs::fromNativePath(path.trimmed()));
}
bool Preferences::isMailNotificationEnabled() const bool Preferences::isMailNotificationEnabled() const
{ {
return value("Preferences/MailNotification/enabled", false).toBool(); return value("Preferences/MailNotification/enabled", false).toBool();
@ -439,18 +374,6 @@ void Preferences::setActionOnDblClOnTorrentFn(int act)
} }
// Connection options // Connection options
int Preferences::getSessionPort() const
{
if (useRandomPort())
return m_randomPort;
return value("Preferences/Connection/PortRangeMin", 8999).toInt();
}
void Preferences::setSessionPort(int port)
{
setValue("Preferences/Connection/PortRangeMin", port);
}
bool Preferences::isUPnPEnabled() const bool Preferences::isUPnPEnabled() const
{ {
return value("Preferences/Connection/UPnP", true).toBool(); return value("Preferences/Connection/UPnP", true).toBool();
@ -461,74 +384,6 @@ void Preferences::setUPnPEnabled(bool enabled)
setValue("Preferences/Connection/UPnP", enabled); setValue("Preferences/Connection/UPnP", enabled);
} }
int Preferences::getGlobalDownloadLimit() const
{
return value("Preferences/Connection/GlobalDLLimit", -1).toInt();
}
void Preferences::setGlobalDownloadLimit(int limit)
{
if (limit <= 0)
limit = -1;
setValue("Preferences/Connection/GlobalDLLimit", limit);
}
int Preferences::getGlobalUploadLimit() const
{
return value("Preferences/Connection/GlobalUPLimit", -1).toInt();
}
void Preferences::setGlobalUploadLimit(int limit)
{
if (limit <= 0)
limit = -1;
setValue("Preferences/Connection/GlobalUPLimit", limit);
}
int Preferences::getAltGlobalDownloadLimit() const
{
return value("Preferences/Connection/GlobalDLLimitAlt", 10).toInt();
}
void Preferences::setAltGlobalDownloadLimit(int limit)
{
if (limit <= 0)
limit = -1;
setValue("Preferences/Connection/GlobalDLLimitAlt", limit);
}
int Preferences::getAltGlobalUploadLimit() const
{
return value("Preferences/Connection/GlobalUPLimitAlt", 10).toInt();
}
void Preferences::setAltGlobalUploadLimit(int limit)
{
if (limit <= 0)
limit = -1;
setValue("Preferences/Connection/GlobalUPLimitAlt", limit);
}
bool Preferences::isAltBandwidthEnabled() const
{
return value("Preferences/Connection/alt_speeds_on", false).toBool();
}
void Preferences::setAltBandwidthEnabled(bool enabled)
{
setValue("Preferences/Connection/alt_speeds_on", enabled);
}
bool Preferences::isSchedulerEnabled() const
{
return value("Preferences/Scheduler/Enabled", false).toBool();
}
void Preferences::setSchedulerEnabled(bool enabled)
{
setValue("Preferences/Scheduler/Enabled", enabled);
}
QTime Preferences::getSchedulerStartTime() const QTime Preferences::getSchedulerStartTime() const
{ {
return value("Preferences/Scheduler/start_time", QTime(8,0)).toTime(); return value("Preferences/Scheduler/start_time", QTime(8,0)).toTime();
@ -559,286 +414,6 @@ void Preferences::setSchedulerDays(scheduler_days days)
setValue("Preferences/Scheduler/days", (int)days); setValue("Preferences/Scheduler/days", (int)days);
} }
// Proxy options
bool Preferences::isProxyEnabled() const
{
return getProxyType() > 0;
}
bool Preferences::isProxyAuthEnabled() const
{
return value("Preferences/Connection/Proxy/Authentication", false).toBool();
}
void Preferences::setProxyAuthEnabled(bool enabled)
{
setValue("Preferences/Connection/Proxy/Authentication", enabled);
}
QString Preferences::getProxyIp() const
{
return value("Preferences/Connection/Proxy/IP", "0.0.0.0").toString();
}
void Preferences::setProxyIp(const QString &ip)
{
setValue("Preferences/Connection/Proxy/IP", ip);
}
unsigned short Preferences::getProxyPort() const
{
return value("Preferences/Connection/Proxy/Port", 8080).toInt();
}
void Preferences::setProxyPort(unsigned short port)
{
setValue("Preferences/Connection/Proxy/Port", port);
}
QString Preferences::getProxyUsername() const
{
return value("Preferences/Connection/Proxy/Username").toString();
}
void Preferences::setProxyUsername(const QString &username)
{
setValue("Preferences/Connection/Proxy/Username", username);
}
QString Preferences::getProxyPassword() const
{
return value("Preferences/Connection/Proxy/Password").toString();
}
void Preferences::setProxyPassword(const QString &password)
{
setValue("Preferences/Connection/Proxy/Password", password);
}
int Preferences::getProxyType() const
{
return value("Preferences/Connection/ProxyType", 0).toInt();
}
void Preferences::setProxyType(int type)
{
setValue("Preferences/Connection/ProxyType", type);
}
bool Preferences::proxyPeerConnections() const
{
return value("Preferences/Connection/ProxyPeerConnections", false).toBool();
}
void Preferences::setProxyPeerConnections(bool enabled)
{
setValue("Preferences/Connection/ProxyPeerConnections", enabled);
}
bool Preferences::getForceProxy() const
{
return value("Preferences/Connection/ProxyForce", true).toBool();
}
void Preferences::setForceProxy(bool enabled)
{
setValue("Preferences/Connection/ProxyForce", enabled);
}
void Preferences::setProxyOnlyForTorrents(bool enabled)
{
setValue("Preferences/Connection/ProxyOnlyForTorrents", enabled);
}
bool Preferences::isProxyOnlyForTorrents() const
{
return value("Preferences/Connection/ProxyOnlyForTorrents", false).toBool();
}
// Bittorrent options
int Preferences::getMaxConnecs() const
{
return value("Preferences/Bittorrent/MaxConnecs", 500).toInt();
}
void Preferences::setMaxConnecs(int val)
{
if (val <= 0)
val = -1;
setValue("Preferences/Bittorrent/MaxConnecs", val);
}
int Preferences::getMaxConnecsPerTorrent() const
{
return value("Preferences/Bittorrent/MaxConnecsPerTorrent", 100).toInt();
}
void Preferences::setMaxConnecsPerTorrent(int val)
{
if (val <= 0)
val = -1;
setValue("Preferences/Bittorrent/MaxConnecsPerTorrent", val);
}
int Preferences::getMaxUploads() const
{
return value("Preferences/Bittorrent/MaxUploads", -1).toInt();
}
void Preferences::setMaxUploads(int val)
{
if (val <= 0)
val = -1;
setValue("Preferences/Bittorrent/MaxUploads", val);
}
int Preferences::getMaxUploadsPerTorrent() const
{
return value("Preferences/Bittorrent/MaxUploadsPerTorrent", -1).toInt();
}
void Preferences::setMaxUploadsPerTorrent(int val)
{
if (val <= 0)
val = -1;
setValue("Preferences/Bittorrent/MaxUploadsPerTorrent", val);
}
bool Preferences::isuTPEnabled() const
{
return value("Preferences/Bittorrent/uTP", true).toBool();
}
void Preferences::setuTPEnabled(bool enabled)
{
setValue("Preferences/Bittorrent/uTP", enabled);
}
bool Preferences::isuTPRateLimited() const
{
return value("Preferences/Bittorrent/uTP_rate_limited", true).toBool();
}
void Preferences::setuTPRateLimited(bool enabled)
{
setValue("Preferences/Bittorrent/uTP_rate_limited", enabled);
}
bool Preferences::isDHTEnabled() const
{
return value("Preferences/Bittorrent/DHT", true).toBool();
}
void Preferences::setDHTEnabled(bool enabled)
{
setValue("Preferences/Bittorrent/DHT", enabled);
}
bool Preferences::isPeXEnabled() const
{
return value("Preferences/Bittorrent/PeX", true).toBool();
}
void Preferences::setPeXEnabled(bool enabled)
{
setValue("Preferences/Bittorrent/PeX", enabled);
}
bool Preferences::isLSDEnabled() const
{
return value("Preferences/Bittorrent/LSD", true).toBool();
}
void Preferences::setLSDEnabled(bool enabled)
{
setValue("Preferences/Bittorrent/LSD", enabled);
}
int Preferences::getEncryptionSetting() const
{
return value("Preferences/Bittorrent/Encryption", 0).toInt();
}
void Preferences::setEncryptionSetting(int val)
{
setValue("Preferences/Bittorrent/Encryption", val);
}
bool Preferences::isAddTrackersEnabled() const
{
return value("Preferences/Bittorrent/AddTrackers", false).toBool();
}
void Preferences::setAddTrackersEnabled(bool enabled)
{
setValue("Preferences/Bittorrent/AddTrackers", enabled);
}
QString Preferences::getTrackersList() const
{
return value("Preferences/Bittorrent/TrackersList").toString();
}
void Preferences::setTrackersList(const QString &val)
{
setValue("Preferences/Bittorrent/TrackersList", val);
}
qreal Preferences::getGlobalMaxRatio() const
{
return value("Preferences/Bittorrent/MaxRatio", -1).toReal();
}
void Preferences::setGlobalMaxRatio(qreal ratio)
{
setValue("Preferences/Bittorrent/MaxRatio", ratio);
}
// IP Filter
bool Preferences::isFilteringEnabled() const
{
return value("Preferences/IPFilter/Enabled", false).toBool();
}
void Preferences::setFilteringEnabled(bool enabled)
{
setValue("Preferences/IPFilter/Enabled", enabled);
}
bool Preferences::isFilteringTrackerEnabled() const
{
return value("Preferences/IPFilter/FilterTracker", false).toBool();
}
void Preferences::setFilteringTrackerEnabled(bool enabled)
{
setValue("Preferences/IPFilter/FilterTracker", enabled);
}
QString Preferences::getFilter() const
{
return Utils::Fs::fromNativePath(value("Preferences/IPFilter/File").toString());
}
void Preferences::setFilter(const QString &path)
{
setValue("Preferences/IPFilter/File", Utils::Fs::fromNativePath(path));
}
QStringList Preferences::bannedIPs() const
{
return value("Preferences/IPFilter/BannedIPs").toStringList();
}
void Preferences::banIP(const QString &ip)
{
QStringList banned_ips = value("Preferences/IPFilter/BannedIPs").toStringList();
if (!banned_ips.contains(ip)) {
banned_ips << ip;
setValue("Preferences/IPFilter/BannedIPs", banned_ips);
}
}
// Search // Search
bool Preferences::isSearchEnabled() const bool Preferences::isSearchEnabled() const
{ {
@ -850,63 +425,6 @@ void Preferences::setSearchEnabled(bool enabled)
setValue("Preferences/Search/SearchEnabled", enabled); setValue("Preferences/Search/SearchEnabled", enabled);
} }
// Queueing system
bool Preferences::isQueueingSystemEnabled() const
{
return value("Preferences/Queueing/QueueingEnabled", true).toBool();
}
void Preferences::setQueueingSystemEnabled(bool enabled)
{
setValue("Preferences/Queueing/QueueingEnabled", enabled);
}
int Preferences::getMaxActiveDownloads() const
{
return value("Preferences/Queueing/MaxActiveDownloads", 3).toInt();
}
void Preferences::setMaxActiveDownloads(int val)
{
if (val < 0)
val = -1;
setValue("Preferences/Queueing/MaxActiveDownloads", val);
}
int Preferences::getMaxActiveUploads() const
{
return value("Preferences/Queueing/MaxActiveUploads", 3).toInt();
}
void Preferences::setMaxActiveUploads(int val)
{
if (val < 0)
val = -1;
setValue("Preferences/Queueing/MaxActiveUploads", val);
}
int Preferences::getMaxActiveTorrents() const
{
return value("Preferences/Queueing/MaxActiveTorrents", 5).toInt();
}
void Preferences::setMaxActiveTorrents(int val)
{
if (val < 0)
val = -1;
setValue("Preferences/Queueing/MaxActiveTorrents", val);
}
bool Preferences::ignoreSlowTorrentsForQueueing() const
{
return value("Preferences/Queueing/IgnoreSlowTorrents", false).toBool();
}
void Preferences::setIgnoreSlowTorrentsForQueueing(bool ignore)
{
setValue("Preferences/Queueing/IgnoreSlowTorrents", ignore);
}
bool Preferences::isWebUiEnabled() const bool Preferences::isWebUiEnabled() const
{ {
#ifdef DISABLE_GUI #ifdef DISABLE_GUI
@ -1164,111 +682,6 @@ void Preferences::setDontConfirmAutoExit(bool dontConfirmAutoExit)
setValue("ShutdownConfirmDlg/DontConfirmAutoExit", dontConfirmAutoExit); setValue("ShutdownConfirmDlg/DontConfirmAutoExit", dontConfirmAutoExit);
} }
uint Preferences::diskCacheSize() const
{
uint size = value("Preferences/Downloads/DiskWriteCacheSize", 0).toUInt();
// These macros may not be available on compilers other than MSVC and GCC
#if defined(__x86_64__) || defined(_M_X64)
size = qMin(size, (uint) 4096); // 4GiB
#else
// When build as 32bit binary, set the maximum at less than 2GB to prevent crashes
// allocate 1536MiB and leave 512MiB to the rest of program data in RAM
size = qMin(size, (uint) 1536);
#endif
return size;
}
void Preferences::setDiskCacheSize(uint size)
{
#if defined(__x86_64__) || defined(_M_X64)
size = qMin(size, (uint) 4096); // 4GiB
#else
// allocate 1536MiB and leave 512MiB to the rest of program data in RAM
size = qMin(size, (uint) 1536);
#endif
setValue("Preferences/Downloads/DiskWriteCacheSize", size);
}
uint Preferences::diskCacheTTL() const
{
return value("Preferences/Downloads/DiskWriteCacheTTL", 60).toUInt();
}
void Preferences::setDiskCacheTTL(uint ttl)
{
setValue("Preferences/Downloads/DiskWriteCacheTTL", ttl);
}
bool Preferences::osCache() const
{
return value("Preferences/Advanced/osCache", true).toBool();
}
void Preferences::setOsCache(bool enable)
{
setValue("Preferences/Advanced/osCache", enable);
}
uint Preferences::saveResumeDataInterval() const
{
return value("Preferences/Downloads/SaveResumeDataInterval", 3).toUInt();
}
void Preferences::setSaveResumeDataInterval(uint m)
{
setValue("Preferences/Downloads/SaveResumeDataInterval", m);
}
uint Preferences::outgoingPortsMin() const
{
return value("Preferences/Advanced/OutgoingPortsMin", 0).toUInt();
}
void Preferences::setOutgoingPortsMin(uint val)
{
setValue("Preferences/Advanced/OutgoingPortsMin", val);
}
uint Preferences::outgoingPortsMax() const
{
return value("Preferences/Advanced/OutgoingPortsMax", 0).toUInt();
}
void Preferences::setOutgoingPortsMax(uint val)
{
setValue("Preferences/Advanced/OutgoingPortsMax", val);
}
bool Preferences::getIgnoreLimitsOnLAN() const
{
return value("Preferences/Advanced/IgnoreLimitsLAN", true).toBool();
}
void Preferences::setIgnoreLimitsOnLAN(bool ignore)
{
setValue("Preferences/Advanced/IgnoreLimitsLAN", ignore);
}
bool Preferences::includeOverheadInLimits() const
{
return value("Preferences/Advanced/IncludeOverhead", false).toBool();
}
void Preferences::includeOverheadInLimits(bool include)
{
setValue("Preferences/Advanced/IncludeOverhead", include);
}
bool Preferences::trackerExchangeEnabled() const
{
return value("Preferences/Advanced/LtTrackerExchange", false).toBool();
}
void Preferences::setTrackerExchangeEnabled(bool enable)
{
setValue("Preferences/Advanced/LtTrackerExchange", enable);
}
bool Preferences::recheckTorrentsOnCompletion() const bool Preferences::recheckTorrentsOnCompletion() const
{ {
return value("Preferences/Advanced/RecheckOnCompletion", false).toBool(); return value("Preferences/Advanced/RecheckOnCompletion", false).toBool();
@ -1279,16 +692,6 @@ void Preferences::recheckTorrentsOnCompletion(bool recheck)
setValue("Preferences/Advanced/RecheckOnCompletion", recheck); setValue("Preferences/Advanced/RecheckOnCompletion", recheck);
} }
unsigned int Preferences::getRefreshInterval() const
{
return value("Preferences/General/RefreshInterval", 1500).toUInt();
}
void Preferences::setRefreshInterval(uint interval)
{
setValue("Preferences/General/RefreshInterval", interval);
}
bool Preferences::resolvePeerCountries() const bool Preferences::resolvePeerCountries() const
{ {
return value("Preferences/Connection/ResolvePeerCountries", true).toBool(); return value("Preferences/Connection/ResolvePeerCountries", true).toBool();
@ -1309,31 +712,6 @@ void Preferences::resolvePeerHostNames(bool resolve)
setValue("Preferences/Connection/ResolvePeerHostNames", resolve); setValue("Preferences/Connection/ResolvePeerHostNames", resolve);
} }
int Preferences::getMaxHalfOpenConnections() const
{
const int val = value("Preferences/Connection/MaxHalfOpenConnec", 20).toInt();
if (val <= 0)
return -1;
return val;
}
void Preferences::setMaxHalfOpenConnections(int value)
{
if (value <= 0)
value = -1;
setValue("Preferences/Connection/MaxHalfOpenConnec", value);
}
QString Preferences::getNetworkInterface() const
{
return value("Preferences/Connection/Interface").toString();
}
void Preferences::setNetworkInterface(const QString& iface)
{
setValue("Preferences/Connection/Interface", iface);
}
QString Preferences::getNetworkInterfaceName() const QString Preferences::getNetworkInterfaceName() const
{ {
return value("Preferences/Connection/InterfaceName").toString(); return value("Preferences/Connection/InterfaceName").toString();
@ -1354,56 +732,6 @@ QString Preferences::getNetworkInterfaceAddress() const
return value("Preferences/Connection/InterfaceAddress").toString(); return value("Preferences/Connection/InterfaceAddress").toString();
} }
bool Preferences::getListenIPv6() const
{
return value("Preferences/Connection/InterfaceListenIPv6", false).toBool();
}
void Preferences::setListenIPv6(bool enable)
{
setValue("Preferences/Connection/InterfaceListenIPv6", enable);
}
QString Preferences::getNetworkAddress() const
{
return value("Preferences/Connection/InetAddress").toString();
}
void Preferences::setNetworkAddress(const QString& addr)
{
setValue("Preferences/Connection/InetAddress", addr);
}
bool Preferences::isAnonymousModeEnabled() const
{
return value("Preferences/Advanced/AnonymousMode", false).toBool();
}
void Preferences::enableAnonymousMode(bool enabled)
{
setValue("Preferences/Advanced/AnonymousMode", enabled);
}
bool Preferences::isSuperSeedingEnabled() const
{
return value("Preferences/Advanced/SuperSeeding", false).toBool();
}
void Preferences::enableSuperSeeding(bool enabled)
{
setValue("Preferences/Advanced/SuperSeeding", enabled);
}
bool Preferences::announceToAllTrackers() const
{
return value("Preferences/Advanced/AnnounceToAllTrackers", true).toBool();
}
void Preferences::setAnnounceToAllTrackers(bool enabled)
{
setValue("Preferences/Advanced/AnnounceToAllTrackers", enabled);
}
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
bool Preferences::useSystemIconTheme() const bool Preferences::useSystemIconTheme() const
{ {
@ -1710,16 +1038,6 @@ void Preferences::setMagnetLinkAssoc()
} }
#endif #endif
bool Preferences::isTrackerEnabled() const
{
return value("Preferences/Advanced/trackerEnabled", false).toBool();
}
void Preferences::setTrackerEnabled(bool enabled)
{
setValue("Preferences/Advanced/trackerEnabled", enabled);
}
int Preferences::getTrackerPort() const int Preferences::getTrackerPort() const
{ {
return value("Preferences/Advanced/trackerPort", 9000).toInt(); return value("Preferences/Advanced/trackerPort", 9000).toInt();

145
src/base/preferences.h

@ -57,18 +57,6 @@ enum scheduler_days
SUN SUN
}; };
namespace Proxy
{
enum ProxyType
{
HTTP = 1,
SOCKS5 = 2,
HTTP_PW = 3,
SOCKS5_PW = 4,
SOCKS4 = 5
};
}
namespace TrayIcon namespace TrayIcon
{ {
enum Style enum Style
@ -102,7 +90,6 @@ class Preferences: public QObject
void setValue(const QString &key, const QVariant &value); void setValue(const QString &key, const QVariant &value);
static Preferences* m_instance; static Preferences* m_instance;
int m_randomPort;
signals: signals:
void changed(); void changed();
@ -127,8 +114,6 @@ public:
void setHideZeroValues(bool b); void setHideZeroValues(bool b);
int getHideZeroComboValues() const; int getHideZeroComboValues() const;
void setHideZeroComboValues(int n); void setHideZeroComboValues(int n);
bool useRandomPort() const;
void setRandomPort(bool b);
bool systrayIntegration() const; bool systrayIntegration() const;
void setSystrayIntegration(bool enabled); void setSystrayIntegration(bool enabled);
bool isToolbarDisplayed() const; bool isToolbarDisplayed() const;
@ -149,22 +134,12 @@ public:
#endif #endif
// Downloads // Downloads
bool useIncompleteFilesExtension() const;
void useIncompleteFilesExtension(bool enabled);
QString lastLocationPath() const; QString lastLocationPath() const;
void setLastLocationPath(const QString &path); void setLastLocationPath(const QString &path);
bool preAllocateAllFiles() const;
void preAllocateAllFiles(bool enabled);
QVariantHash getScanDirs() const; QVariantHash getScanDirs() const;
void setScanDirs(const QVariantHash &dirs); void setScanDirs(const QVariantHash &dirs);
QString getScanDirsLastPath() const; QString getScanDirsLastPath() const;
void setScanDirsLastPath(const QString &path); void setScanDirsLastPath(const QString &path);
bool isTorrentExportEnabled() const;
QString getTorrentExportDir() const;
void setTorrentExportDir(QString path);
bool isFinishedTorrentExportEnabled() const;
QString getFinishedTorrentExportDir() const;
void setFinishedTorrentExportDir(QString path);
bool isMailNotificationEnabled() const; bool isMailNotificationEnabled() const;
void setMailNotificationEnabled(bool enabled); void setMailNotificationEnabled(bool enabled);
QString getMailNotificationEmail() const; QString getMailNotificationEmail() const;
@ -185,22 +160,8 @@ public:
void setActionOnDblClOnTorrentFn(int act); void setActionOnDblClOnTorrentFn(int act);
// Connection options // Connection options
int getSessionPort() const;
void setSessionPort(int port);
bool isUPnPEnabled() const; bool isUPnPEnabled() const;
void setUPnPEnabled(bool enabled); void setUPnPEnabled(bool enabled);
int getGlobalDownloadLimit() const;
void setGlobalDownloadLimit(int limit);
int getGlobalUploadLimit() const;
void setGlobalUploadLimit(int limit);
int getAltGlobalDownloadLimit() const;
void setAltGlobalDownloadLimit(int limit);
int getAltGlobalUploadLimit() const;
void setAltGlobalUploadLimit(int limit);
bool isAltBandwidthEnabled() const;
void setAltBandwidthEnabled(bool enabled);
bool isSchedulerEnabled() const;
void setSchedulerEnabled(bool enabled);
QTime getSchedulerStartTime() const; QTime getSchedulerStartTime() const;
void setSchedulerStartTime(const QTime &time); void setSchedulerStartTime(const QTime &time);
QTime getSchedulerEndTime() const; QTime getSchedulerEndTime() const;
@ -208,80 +169,10 @@ public:
scheduler_days getSchedulerDays() const; scheduler_days getSchedulerDays() const;
void setSchedulerDays(scheduler_days days); void setSchedulerDays(scheduler_days days);
// Proxy options
bool isProxyEnabled() const;
bool isProxyAuthEnabled() const;
void setProxyAuthEnabled(bool enabled);
QString getProxyIp() const;
void setProxyIp(const QString &ip);
unsigned short getProxyPort() const;
void setProxyPort(unsigned short port);
QString getProxyUsername() const;
void setProxyUsername(const QString &username);
QString getProxyPassword() const;
void setProxyPassword(const QString &password);
int getProxyType() const;
void setProxyType(int type);
bool proxyPeerConnections() const;
void setProxyPeerConnections(bool enabled);
bool getForceProxy() const;
void setForceProxy(bool enabled);
void setProxyOnlyForTorrents(bool enabled);
bool isProxyOnlyForTorrents() const;
// Bittorrent options
int getMaxConnecs() const;
void setMaxConnecs(int val);
int getMaxConnecsPerTorrent() const;
void setMaxConnecsPerTorrent(int val);
int getMaxUploads() const;
void setMaxUploads(int val);
int getMaxUploadsPerTorrent() const;
void setMaxUploadsPerTorrent(int val);
bool isuTPEnabled() const;
void setuTPEnabled(bool enabled);
bool isuTPRateLimited() const;
void setuTPRateLimited(bool enabled);
bool isDHTEnabled() const;
void setDHTEnabled(bool enabled);
bool isPeXEnabled() const;
void setPeXEnabled(bool enabled);
bool isLSDEnabled() const;
void setLSDEnabled(bool enabled);
int getEncryptionSetting() const;
void setEncryptionSetting(int val);
bool isAddTrackersEnabled() const;
void setAddTrackersEnabled(bool enabled);
QString getTrackersList() const;
void setTrackersList(const QString &val);
qreal getGlobalMaxRatio() const;
void setGlobalMaxRatio(qreal ratio);
// IP Filter
bool isFilteringEnabled() const;
void setFilteringEnabled(bool enabled);
bool isFilteringTrackerEnabled() const;
void setFilteringTrackerEnabled(bool enabled);
QString getFilter() const;
void setFilter(const QString &path);
QStringList bannedIPs() const;
void banIP(const QString &ip);
// Search // Search
bool isSearchEnabled() const; bool isSearchEnabled() const;
void setSearchEnabled(bool enabled); void setSearchEnabled(bool enabled);
// Queueing system
bool isQueueingSystemEnabled() const;
void setQueueingSystemEnabled(bool enabled);
int getMaxActiveDownloads() const;
void setMaxActiveDownloads(int val);
int getMaxActiveUploads() const;
void setMaxActiveUploads(int val);
int getMaxActiveTorrents() const;
void setMaxActiveTorrents(int val);
bool ignoreSlowTorrentsForQueueing() const;
void setIgnoreSlowTorrentsForQueueing(bool ignore);
bool isWebUiEnabled() const; bool isWebUiEnabled() const;
void setWebUiEnabled(bool enabled); void setWebUiEnabled(bool enabled);
bool isWebUiLocalAuthEnabled() const; bool isWebUiLocalAuthEnabled() const;
@ -331,50 +222,16 @@ public:
void setShutdownqBTWhenDownloadsComplete(bool shutdown); void setShutdownqBTWhenDownloadsComplete(bool shutdown);
bool dontConfirmAutoExit() const; bool dontConfirmAutoExit() const;
void setDontConfirmAutoExit(bool dontConfirmAutoExit); void setDontConfirmAutoExit(bool dontConfirmAutoExit);
uint diskCacheSize() const;
void setDiskCacheSize(uint size);
uint diskCacheTTL() const;
void setDiskCacheTTL(uint ttl);
bool osCache() const;
void setOsCache(bool enable);
uint saveResumeDataInterval() const;
void setSaveResumeDataInterval(uint m);
uint outgoingPortsMin() const;
void setOutgoingPortsMin(uint val);
uint outgoingPortsMax() const;
void setOutgoingPortsMax(uint val);
bool getIgnoreLimitsOnLAN() const;
void setIgnoreLimitsOnLAN(bool ignore);
bool includeOverheadInLimits() const;
void includeOverheadInLimits(bool include);
bool trackerExchangeEnabled() const;
void setTrackerExchangeEnabled(bool enable);
bool recheckTorrentsOnCompletion() const; bool recheckTorrentsOnCompletion() const;
void recheckTorrentsOnCompletion(bool recheck); void recheckTorrentsOnCompletion(bool recheck);
unsigned int getRefreshInterval() const;
void setRefreshInterval(uint interval);
bool resolvePeerCountries() const; bool resolvePeerCountries() const;
void resolvePeerCountries(bool resolve); void resolvePeerCountries(bool resolve);
bool resolvePeerHostNames() const; bool resolvePeerHostNames() const;
void resolvePeerHostNames(bool resolve); void resolvePeerHostNames(bool resolve);
int getMaxHalfOpenConnections() const;
void setMaxHalfOpenConnections(int value);
QString getNetworkInterface() const;
void setNetworkInterface(const QString& iface);
QString getNetworkInterfaceName() const; QString getNetworkInterfaceName() const;
void setNetworkInterfaceName(const QString& iface); void setNetworkInterfaceName(const QString& iface);
QString getNetworkInterfaceAddress() const; QString getNetworkInterfaceAddress() const;
void setNetworkInterfaceAddress(const QString& addr); void setNetworkInterfaceAddress(const QString& addr);
bool getListenIPv6() const;
void setListenIPv6(bool enable);
QString getNetworkAddress() const;
void setNetworkAddress(const QString& addr);
bool isAnonymousModeEnabled() const;
void enableAnonymousMode(bool enabled);
bool isSuperSeedingEnabled() const;
void enableSuperSeeding(bool enabled);
bool announceToAllTrackers() const;
void setAnnounceToAllTrackers(bool enabled);
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
bool useSystemIconTheme() const; bool useSystemIconTheme() const;
void useSystemIconTheme(bool enabled); void useSystemIconTheme(bool enabled);
@ -396,8 +253,6 @@ public:
static void setTorrentFileAssoc(); static void setTorrentFileAssoc();
static void setMagnetLinkAssoc(); static void setMagnetLinkAssoc();
#endif #endif
bool isTrackerEnabled() const;
void setTrackerEnabled(bool enabled);
int getTrackerPort() const; int getTrackerPort() const;
void setTrackerPort(int port); void setTrackerPort(int port);
#if defined(Q_OS_WIN) || defined(Q_OS_MAC) #if defined(Q_OS_WIN) || defined(Q_OS_MAC)

88
src/base/settingsstorage.cpp

@ -98,22 +98,84 @@ namespace
{ {
static const MappingTable keyMapping = { static const MappingTable keyMapping = {
{ "BitTorrent/Session/MaxRatioAction", "Preferences/Bittorrent/MaxRatioAction" }, {"BitTorrent/Session/MaxRatioAction", "Preferences/Bittorrent/MaxRatioAction"},
{ "BitTorrent/Session/DefaultSavePath", "Preferences/Downloads/SavePath" }, {"BitTorrent/Session/DefaultSavePath", "Preferences/Downloads/SavePath"},
{ "BitTorrent/Session/TempPath", "Preferences/Downloads/TempPath" }, {"BitTorrent/Session/TempPath", "Preferences/Downloads/TempPath"},
{ "BitTorrent/Session/TempPathEnabled", "Preferences/Downloads/TempPathEnabled" }, {"BitTorrent/Session/TempPathEnabled", "Preferences/Downloads/TempPathEnabled"},
{ "BitTorrent/Session/AddTorrentPaused", "Preferences/Downloads/StartInPause" }, {"BitTorrent/Session/AddTorrentPaused", "Preferences/Downloads/StartInPause"},
{"BitTorrent/Session/RefreshInterval", "Preferences/General/RefreshInterval"},
{"BitTorrent/Session/Preallocation", "Preferences/Downloads/PreAllocation"},
{"BitTorrent/Session/AddExtensionToIncompleteFiles", "Preferences/Downloads/UseIncompleteExtension"},
{"BitTorrent/Session/TorrentExportDirectory", "Preferences/Downloads/TorrentExportDir"},
{"BitTorrent/Session/FinishedTorrentExportDirectory", "Preferences/Downloads/FinishedTorrentExportDir"},
{"BitTorrent/Session/GlobalUPSpeedLimit", "Preferences/Connection/GlobalUPLimit"},
{"BitTorrent/Session/GlobalDLSpeedLimit", "Preferences/Connection/GlobalDLLimit"},
{"BitTorrent/Session/AlternativeGlobalUPSpeedLimit", "Preferences/Connection/GlobalUPLimitAlt"},
{"BitTorrent/Session/AlternativeGlobalDLSpeedLimit", "Preferences/Connection/GlobalDLLimitAlt"},
{"BitTorrent/Session/UseAlternativeGlobalSpeedLimit", "Preferences/Connection/alt_speeds_on"},
{"BitTorrent/Session/BandwidthSchedulerEnabled", "Preferences/Scheduler/Enabled"},
{"BitTorrent/Session/Port", "Preferences/Connection/PortRangeMin"},
{"BitTorrent/Session/UseRandomPort", "Preferences/General/UseRandomPort"},
{"BitTorrent/Session/IPv6Enabled", "Preferences/Connection/InterfaceListenIPv6"},
{"BitTorrent/Session/Interface", "Preferences/Connection/Interface"},
{"BitTorrent/Session/SaveResumeDataInterval", "Preferences/Downloads/SaveResumeDataInterval"},
{"BitTorrent/Session/Encryption", "Preferences/Bittorrent/Encryption"},
{"BitTorrent/Session/ForceProxy", "Preferences/Connection/ProxyForce"},
{"BitTorrent/Session/ProxyPeerConnections", "Preferences/Connection/ProxyPeerConnections"},
{"BitTorrent/Session/MaxConnections", "Preferences/Bittorrent/MaxConnecs"},
{"BitTorrent/Session/MaxUploads", "Preferences/Bittorrent/MaxUploads"},
{"BitTorrent/Session/MaxConnectionsPerTorrent", "Preferences/Bittorrent/MaxConnecsPerTorrent"},
{"BitTorrent/Session/MaxUploadsPerTorrent", "Preferences/Bittorrent/MaxUploadsPerTorrent"},
{"BitTorrent/Session/DHTEnabled", "Preferences/Bittorrent/DHT"},
{"BitTorrent/Session/LSDEnabled", "Preferences/Bittorrent/LSD"},
{"BitTorrent/Session/PeXEnabled", "Preferences/Bittorrent/PeX"},
{"BitTorrent/Session/TrackerExchangeEnabled", "Preferences/Advanced/LtTrackerExchange"},
{"BitTorrent/Session/AddTrackersEnabled", "Preferences/Bittorrent/AddTrackers"},
{"BitTorrent/Session/AdditionalTrackers", "Preferences/Bittorrent/TrackersList"},
{"BitTorrent/Session/FilteringEnabled", "Preferences/IPFilter/Enabled"},
{"BitTorrent/Session/TrackerFilteringEnabled", "Preferences/IPFilter/FilterTracker"},
{"BitTorrent/Session/IPFilter", "Preferences/IPFilter/File"},
{"BitTorrent/Session/GlobalMaxRatio", "Preferences/Bittorrent/MaxRatio"},
{"BitTorrent/Session/AnnounceToAllTrackers", "Preferences/Advanced/AnnounceToAllTrackers"},
{"BitTorrent/Session/DiskCacheSize", "Preferences/Downloads/DiskWriteCacheSize"},
{"BitTorrent/Session/DiskCacheTTL", "Preferences/Downloads/DiskWriteCacheTTL"},
{"BitTorrent/Session/UseOSCache", "Preferences/Advanced/osCache"},
{"BitTorrent/Session/AnonymousModeEnabled", "Preferences/Advanced/AnonymousMode"},
{"BitTorrent/Session/QueueingSystemEnabled", "Preferences/Queueing/QueueingEnabled"},
{"BitTorrent/Session/MaxActiveDownloads", "Preferences/Queueing/MaxActiveDownloads"},
{"BitTorrent/Session/MaxActiveUploads", "Preferences/Queueing/MaxActiveUploads"},
{"BitTorrent/Session/MaxActiveTorrents", "Preferences/Queueing/MaxActiveTorrents"},
{"BitTorrent/Session/IgnoreSlowTorrentsForQueueing", "Preferences/Queueing/IgnoreSlowTorrents"},
{"BitTorrent/Session/OutgoingPortsMin", "Preferences/Advanced/OutgoingPortsMin"},
{"BitTorrent/Session/OutgoingPortsMax", "Preferences/Advanced/OutgoingPortsMax"},
{"BitTorrent/Session/IgnoreLimitsOnLAN", "Preferences/Advanced/IgnoreLimitsLAN"},
{"BitTorrent/Session/IncludeOverheadInLimits", "Preferences/Advanced/IncludeOverhead"},
{"BitTorrent/Session/NetworkAddress", "Preferences/Connection/InetAddress"},
{"BitTorrent/Session/SuperSeedingEnabled", "Preferences/Advanced/SuperSeeding"},
{"BitTorrent/Session/MaxHalfOpenConnections", "Preferences/Connection/MaxHalfOpenConnec"},
{"BitTorrent/Session/uTPEnabled", "Preferences/Bittorrent/uTP"},
{"BitTorrent/Session/uTPRateLimited", "Preferences/Bittorrent/uTP_rate_limited"},
{"BitTorrent/TrackerEnabled", "Preferences/TrackerEnabled"},
{"Network/Proxy/Disabled", "Preferences/Connection/ProxyOnlyForTorrents"},
{"Network/Proxy/Type", "Preferences/Connection/ProxyType"},
{"Network/Proxy/Authentication", "Preferences/Connection/Proxy/Authentication"},
{"Network/Proxy/Username", "Preferences/Connection/Proxy/Username"},
{"Network/Proxy/Password", "Preferences/Connection/Proxy/Password"},
{"Network/Proxy/IP", "Preferences/Connection/Proxy/IP"},
{"Network/Proxy/Port", "Preferences/Connection/Proxy/Port"},
#ifdef QBT_USES_QT5 #ifdef QBT_USES_QT5
{ "AddNewTorrentDialog/TreeHeaderState", "AddNewTorrentDialog/qt5/treeHeaderState" }, {"AddNewTorrentDialog/TreeHeaderState", "AddNewTorrentDialog/qt5/treeHeaderState"},
#else #else
{ "AddNewTorrentDialog/TreeHeaderState", "AddNewTorrentDialog/treeHeaderState" }, {"AddNewTorrentDialog/TreeHeaderState", "AddNewTorrentDialog/treeHeaderState"},
#endif #endif
{ "AddNewTorrentDialog/Width", "AddNewTorrentDialog/width" }, {"AddNewTorrentDialog/Width", "AddNewTorrentDialog/width"},
{ "AddNewTorrentDialog/Position", "AddNewTorrentDialog/y" }, {"AddNewTorrentDialog/Position", "AddNewTorrentDialog/y"},
{ "AddNewTorrentDialog/Expanded", "AddNewTorrentDialog/expanded" }, {"AddNewTorrentDialog/Expanded", "AddNewTorrentDialog/expanded"},
{ "AddNewTorrentDialog/SavePathHistory", "TorrentAdditionDlg/save_path_history" }, {"AddNewTorrentDialog/SavePathHistory", "TorrentAdditionDlg/save_path_history"},
{ "AddNewTorrentDialog/Enabled", "Preferences/Downloads/NewAdditionDialog" }, {"AddNewTorrentDialog/Enabled", "Preferences/Downloads/NewAdditionDialog"},
{ "AddNewTorrentDialog/TopLevel", "Preferences/Downloads/NewAdditionDialogFront" } {"AddNewTorrentDialog/TopLevel", "Preferences/Downloads/NewAdditionDialogFront"},
{"State/BannedIPs", "Preferences/IPFilter/BannedIPs"}
}; };

73
src/base/settingvalue.h

@ -0,0 +1,73 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2016 Vladimir Golovnev <glassez@yandex.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#ifndef SETTINGVALUE_H
#define SETTINGVALUE_H
#include <functional>
#include <QString>
#include "settingsstorage.h"
template <typename T>
class CachedSettingValue
{
using ProxyFunc = std::function<T (const T&)>;
public:
explicit CachedSettingValue(const char *keyName, const T &defaultValue = T()
, ProxyFunc proxyFunc = [](const T &value) { return value; })
: m_keyName(QLatin1String(keyName))
, m_value(proxyFunc(SettingsStorage::instance()->loadValue(
m_keyName, defaultValue).template value<T>()))
{
}
T value() const
{
return m_value;
}
CachedSettingValue<T> &operator=(const T &newValue)
{
m_value = newValue;
SettingsStorage::instance()->storeValue(m_keyName, m_value);
return *this;
}
operator T() const
{
return value();
}
private:
const QString m_keyName;
T m_value;
};
#endif // SETTINGVALUE_H

82
src/gui/advancedsettings.cpp

@ -27,11 +27,14 @@
*/ */
#include "advancedsettings.h" #include "advancedsettings.h"
#include <QFont> #include <QFont>
#include <QHeaderView> #include <QHeaderView>
#include <QHostAddress> #include <QHostAddress>
#include <QNetworkInterface> #include <QNetworkInterface>
#include "app/application.h" #include "app/application.h"
#include "base/bittorrent/session.h"
#include "base/preferences.h" #include "base/preferences.h"
#include "gui/mainwindow.h" #include "gui/mainwindow.h"
@ -116,39 +119,40 @@ AdvancedSettings::AdvancedSettings(QWidget *parent)
void AdvancedSettings::saveAdvancedSettings() void AdvancedSettings::saveAdvancedSettings()
{ {
Preferences* const pref = Preferences::instance(); Preferences* const pref = Preferences::instance();
BitTorrent::Session *const session = BitTorrent::Session::instance();
// Disk write cache // Disk write cache
pref->setDiskCacheSize(spin_cache.value()); session->setDiskCacheSize(spin_cache.value());
pref->setDiskCacheTTL(spin_cache_ttl.value()); session->setDiskCacheTTL(spin_cache_ttl.value());
// Enable OS cache // Enable OS cache
pref->setOsCache(cb_os_cache.isChecked()); session->setUseOSCache(cb_os_cache.isChecked());
// Save resume data interval // Save resume data interval
pref->setSaveResumeDataInterval(spin_save_resume_data_interval.value()); session->setSaveResumeDataInterval(spin_save_resume_data_interval.value());
// Outgoing ports // Outgoing ports
pref->setOutgoingPortsMin(outgoing_ports_min.value()); session->setOutgoingPortsMin(outgoing_ports_min.value());
pref->setOutgoingPortsMax(outgoing_ports_max.value()); session->setOutgoingPortsMax(outgoing_ports_max.value());
// Recheck torrents on completion // Recheck torrents on completion
pref->recheckTorrentsOnCompletion(cb_recheck_completed.isChecked()); pref->recheckTorrentsOnCompletion(cb_recheck_completed.isChecked());
// Transfer list refresh interval // Transfer list refresh interval
pref->setRefreshInterval(spin_list_refresh.value()); session->setRefreshInterval(spin_list_refresh.value());
// Peer resolution // Peer resolution
pref->resolvePeerCountries(cb_resolve_countries.isChecked()); pref->resolvePeerCountries(cb_resolve_countries.isChecked());
pref->resolvePeerHostNames(cb_resolve_hosts.isChecked()); pref->resolvePeerHostNames(cb_resolve_hosts.isChecked());
// Max Half-Open connections // Max Half-Open connections
pref->setMaxHalfOpenConnections(spin_maxhalfopen.value()); session->setMaxHalfOpenConnections(spin_maxhalfopen.value());
// Super seeding // Super seeding
pref->enableSuperSeeding(cb_super_seeding.isChecked()); session->setSuperSeedingEnabled(cb_super_seeding.isChecked());
// Network interface // Network interface
if (combo_iface.currentIndex() == 0) { if (combo_iface.currentIndex() == 0) {
// All interfaces (default) // All interfaces (default)
pref->setNetworkInterface(QString::null); session->setNetworkInterface(QString());
pref->setNetworkInterfaceName(QString::null); pref->setNetworkInterfaceName(QString());
} }
else { else {
pref->setNetworkInterface(combo_iface.itemData(combo_iface.currentIndex()).toString()); session->setNetworkInterface(combo_iface.itemData(combo_iface.currentIndex()).toString());
pref->setNetworkInterfaceName(combo_iface.currentText()); pref->setNetworkInterfaceName(combo_iface.currentText());
} }
// Listen on IPv6 address
pref->setListenIPv6(cb_listen_ipv6.isChecked());
// Interface address // Interface address
if (combo_iface_address.currentIndex() == 0) { if (combo_iface_address.currentIndex() == 0) {
// All addresses (default) // All addresses (default)
@ -158,19 +162,18 @@ void AdvancedSettings::saveAdvancedSettings()
QHostAddress ifaceAddr(combo_iface_address.currentText().trimmed()); QHostAddress ifaceAddr(combo_iface_address.currentText().trimmed());
ifaceAddr.isNull() ? pref->setNetworkInterfaceAddress(QString::null) : pref->setNetworkInterfaceAddress(ifaceAddr.toString()); ifaceAddr.isNull() ? pref->setNetworkInterfaceAddress(QString::null) : pref->setNetworkInterfaceAddress(ifaceAddr.toString());
} }
// Network Announce address session->setIPv6Enabled(cb_listen_ipv6.isChecked());
QHostAddress networkAddr(txt_network_address.text().trimmed()); // Network address
if (networkAddr.isNull()) QHostAddress addr(txt_network_address.text().trimmed());
pref->setNetworkAddress(""); session->setNetworkAddress(addr.isNull() ? "" : addr.toString());
else
pref->setNetworkAddress(networkAddr.toString());
// Program notification // Program notification
MainWindow * const mainWindow = static_cast<Application*>(QCoreApplication::instance())->mainWindow(); MainWindow * const mainWindow = static_cast<Application*>(QCoreApplication::instance())->mainWindow();
mainWindow->setNotificationsEnabled(cb_program_notifications.isChecked()); mainWindow->setNotificationsEnabled(cb_program_notifications.isChecked());
mainWindow->setTorrentAddedNotificationsEnabled(cb_torrent_added_notifications.isChecked()); mainWindow->setTorrentAddedNotificationsEnabled(cb_torrent_added_notifications.isChecked());
// Tracker // Tracker
pref->setTrackerEnabled(cb_tracker_status.isChecked()); session->setTrackerEnabled(cb_tracker_status.isChecked());
pref->setTrackerPort(spin_tracker_port.value()); pref->setTrackerPort(spin_tracker_port.value());
#if defined(Q_OS_WIN) || defined(Q_OS_MAC) #if defined(Q_OS_WIN) || defined(Q_OS_MAC)
pref->setUpdateCheckEnabled(cb_update_check.isChecked()); pref->setUpdateCheckEnabled(cb_update_check.isChecked());
@ -181,8 +184,8 @@ void AdvancedSettings::saveAdvancedSettings()
#endif #endif
pref->setConfirmTorrentRecheck(cb_confirm_torrent_recheck.isChecked()); pref->setConfirmTorrentRecheck(cb_confirm_torrent_recheck.isChecked());
// Tracker exchange // Tracker exchange
pref->setTrackerExchangeEnabled(cb_enable_tracker_ext.isChecked()); session->setTrackerExchangeEnabled(cb_enable_tracker_ext.isChecked());
pref->setAnnounceToAllTrackers(cb_announce_all_trackers.isChecked()); session->setAnnounceToAllTrackers(cb_announce_all_trackers.isChecked());
} }
void AdvancedSettings::updateCacheSpinSuffix(int value) void AdvancedSettings::updateCacheSpinSuffix(int value)
@ -233,6 +236,8 @@ void AdvancedSettings::updateInterfaceAddressCombo()
void AdvancedSettings::loadAdvancedSettings() void AdvancedSettings::loadAdvancedSettings()
{ {
const Preferences* const pref = Preferences::instance(); const Preferences* const pref = Preferences::instance();
BitTorrent::Session *const session = BitTorrent::Session::instance();
// add section headers // add section headers
QFont boldFont; QFont boldFont;
boldFont.setBold(true); boldFont.setBold(true);
@ -255,33 +260,33 @@ void AdvancedSettings::loadAdvancedSettings()
// allocate 1536MiB and leave 512MiB to the rest of program data in RAM // allocate 1536MiB and leave 512MiB to the rest of program data in RAM
spin_cache.setMaximum(1536); spin_cache.setMaximum(1536);
#endif #endif
spin_cache.setValue(pref->diskCacheSize()); spin_cache.setValue(session->diskCacheSize());
updateCacheSpinSuffix(spin_cache.value()); updateCacheSpinSuffix(spin_cache.value());
addRow(DISK_CACHE, tr("Disk write cache size"), &spin_cache); addRow(DISK_CACHE, tr("Disk write cache size"), &spin_cache);
// Disk cache expiry // Disk cache expiry
spin_cache_ttl.setMinimum(15); spin_cache_ttl.setMinimum(15);
spin_cache_ttl.setMaximum(600); spin_cache_ttl.setMaximum(600);
spin_cache_ttl.setValue(pref->diskCacheTTL()); spin_cache_ttl.setValue(session->diskCacheTTL());
spin_cache_ttl.setSuffix(tr(" s", " seconds")); spin_cache_ttl.setSuffix(tr(" s", " seconds"));
addRow(DISK_CACHE_TTL, tr("Disk cache expiry interval"), &spin_cache_ttl); addRow(DISK_CACHE_TTL, tr("Disk cache expiry interval"), &spin_cache_ttl);
// Enable OS cache // Enable OS cache
cb_os_cache.setChecked(pref->osCache()); cb_os_cache.setChecked(session->useOSCache());
addRow(OS_CACHE, tr("Enable OS cache"), &cb_os_cache); addRow(OS_CACHE, tr("Enable OS cache"), &cb_os_cache);
// Save resume data interval // Save resume data interval
spin_save_resume_data_interval.setMinimum(1); spin_save_resume_data_interval.setMinimum(1);
spin_save_resume_data_interval.setMaximum(1440); spin_save_resume_data_interval.setMaximum(1440);
spin_save_resume_data_interval.setValue(pref->saveResumeDataInterval()); spin_save_resume_data_interval.setValue(session->saveResumeDataInterval());
spin_save_resume_data_interval.setSuffix(tr(" m", " minutes")); spin_save_resume_data_interval.setSuffix(tr(" m", " minutes"));
addRow(SAVE_RESUME_DATA_INTERVAL, tr("Save resume data interval", "How often the fastresume file is saved."), &spin_save_resume_data_interval); addRow(SAVE_RESUME_DATA_INTERVAL, tr("Save resume data interval", "How often the fastresume file is saved."), &spin_save_resume_data_interval);
// Outgoing port Min // Outgoing port Min
outgoing_ports_min.setMinimum(0); outgoing_ports_min.setMinimum(0);
outgoing_ports_min.setMaximum(65535); outgoing_ports_min.setMaximum(65535);
outgoing_ports_min.setValue(pref->outgoingPortsMin()); outgoing_ports_min.setValue(session->outgoingPortsMin());
addRow(OUTGOING_PORT_MIN, tr("Outgoing ports (Min) [0: Disabled]"), &outgoing_ports_min); addRow(OUTGOING_PORT_MIN, tr("Outgoing ports (Min) [0: Disabled]"), &outgoing_ports_min);
// Outgoing port Min // Outgoing port Min
outgoing_ports_max.setMinimum(0); outgoing_ports_max.setMinimum(0);
outgoing_ports_max.setMaximum(65535); outgoing_ports_max.setMaximum(65535);
outgoing_ports_max.setValue(pref->outgoingPortsMax()); outgoing_ports_max.setValue(session->outgoingPortsMax());
addRow(OUTGOING_PORT_MAX, tr("Outgoing ports (Max) [0: Disabled]"), &outgoing_ports_max); addRow(OUTGOING_PORT_MAX, tr("Outgoing ports (Max) [0: Disabled]"), &outgoing_ports_max);
// Recheck completed torrents // Recheck completed torrents
cb_recheck_completed.setChecked(pref->recheckTorrentsOnCompletion()); cb_recheck_completed.setChecked(pref->recheckTorrentsOnCompletion());
@ -289,7 +294,7 @@ void AdvancedSettings::loadAdvancedSettings()
// Transfer list refresh interval // Transfer list refresh interval
spin_list_refresh.setMinimum(30); spin_list_refresh.setMinimum(30);
spin_list_refresh.setMaximum(99999); spin_list_refresh.setMaximum(99999);
spin_list_refresh.setValue(pref->getRefreshInterval()); spin_list_refresh.setValue(session->refreshInterval());
spin_list_refresh.setSuffix(tr(" ms", " milliseconds")); spin_list_refresh.setSuffix(tr(" ms", " milliseconds"));
addRow(LIST_REFRESH, tr("Transfer list refresh interval"), &spin_list_refresh); addRow(LIST_REFRESH, tr("Transfer list refresh interval"), &spin_list_refresh);
// Resolve Peer countries // Resolve Peer countries
@ -301,14 +306,14 @@ void AdvancedSettings::loadAdvancedSettings()
// Max Half Open connections // Max Half Open connections
spin_maxhalfopen.setMinimum(0); spin_maxhalfopen.setMinimum(0);
spin_maxhalfopen.setMaximum(99999); spin_maxhalfopen.setMaximum(99999);
spin_maxhalfopen.setValue(pref->getMaxHalfOpenConnections()); spin_maxhalfopen.setValue(session->maxHalfOpenConnections());
addRow(MAX_HALF_OPEN, tr("Maximum number of half-open connections [0: Unlimited]"), &spin_maxhalfopen); addRow(MAX_HALF_OPEN, tr("Maximum number of half-open connections [0: Unlimited]"), &spin_maxhalfopen);
// Super seeding // Super seeding
cb_super_seeding.setChecked(pref->isSuperSeedingEnabled()); cb_super_seeding.setChecked(session->isSuperSeedingEnabled());
addRow(SUPER_SEEDING, tr("Strict super seeding"), &cb_super_seeding); addRow(SUPER_SEEDING, tr("Strict super seeding"), &cb_super_seeding);
// Network interface // Network interface
combo_iface.addItem(tr("Any interface", "i.e. Any network interface")); combo_iface.addItem(tr("Any interface", "i.e. Any network interface"));
const QString current_iface = pref->getNetworkInterface(); const QString current_iface = session->networkInterface();
bool interface_exists = current_iface.isEmpty(); bool interface_exists = current_iface.isEmpty();
int i = 1; int i = 1;
foreach (const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) { foreach (const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) {
@ -336,10 +341,10 @@ void AdvancedSettings::loadAdvancedSettings()
updateInterfaceAddressCombo(); updateInterfaceAddressCombo();
addRow(NETWORK_IFACE_ADDRESS, tr("Optional IP Address to bind to (requires restart)"), &combo_iface_address); addRow(NETWORK_IFACE_ADDRESS, tr("Optional IP Address to bind to (requires restart)"), &combo_iface_address);
// Listen on IPv6 address // Listen on IPv6 address
cb_listen_ipv6.setChecked(pref->getListenIPv6()); cb_listen_ipv6.setChecked(session->isIPv6Enabled());
addRow(NETWORK_LISTEN_IPV6, tr("Listen on IPv6 address (requires restart)"), &cb_listen_ipv6); addRow(NETWORK_LISTEN_IPV6, tr("Listen on IPv6 address (requires restart)"), &cb_listen_ipv6);
// Announce address // Announce address
txt_network_address.setText(pref->getNetworkAddress()); txt_network_address.setText(session->networkAddress());
addRow(NETWORK_ADDRESS, tr("IP Address to report to trackers (requires restart)"), &txt_network_address); addRow(NETWORK_ADDRESS, tr("IP Address to report to trackers (requires restart)"), &txt_network_address);
// Program notifications // Program notifications
@ -349,8 +354,9 @@ void AdvancedSettings::loadAdvancedSettings()
// Torrent added notifications // Torrent added notifications
cb_torrent_added_notifications.setChecked(mainWindow->isTorrentAddedNotificationsEnabled()); cb_torrent_added_notifications.setChecked(mainWindow->isTorrentAddedNotificationsEnabled());
addRow(TORRENT_ADDED_NOTIFICATIONS, tr("Display notifications for added torrents"), &cb_torrent_added_notifications); addRow(TORRENT_ADDED_NOTIFICATIONS, tr("Display notifications for added torrents"), &cb_torrent_added_notifications);
// Tracker State // Tracker State
cb_tracker_status.setChecked(pref->isTrackerEnabled()); cb_tracker_status.setChecked(session->isTrackerEnabled());
addRow(TRACKER_STATUS, tr("Enable embedded tracker"), &cb_tracker_status); addRow(TRACKER_STATUS, tr("Enable embedded tracker"), &cb_tracker_status);
// Tracker port // Tracker port
spin_tracker_port.setMinimum(1); spin_tracker_port.setMinimum(1);
@ -369,10 +375,10 @@ void AdvancedSettings::loadAdvancedSettings()
cb_confirm_torrent_recheck.setChecked(pref->confirmTorrentRecheck()); cb_confirm_torrent_recheck.setChecked(pref->confirmTorrentRecheck());
addRow(CONFIRM_RECHECK_TORRENT, tr("Confirm torrent recheck"), &cb_confirm_torrent_recheck); addRow(CONFIRM_RECHECK_TORRENT, tr("Confirm torrent recheck"), &cb_confirm_torrent_recheck);
// Tracker exchange // Tracker exchange
cb_enable_tracker_ext.setChecked(pref->trackerExchangeEnabled()); cb_enable_tracker_ext.setChecked(session->isTrackerExchangeEnabled());
addRow(TRACKER_EXCHANGE, tr("Exchange trackers with other peers"), &cb_enable_tracker_ext); addRow(TRACKER_EXCHANGE, tr("Exchange trackers with other peers"), &cb_enable_tracker_ext);
// Announce to all trackers // Announce to all trackers
cb_announce_all_trackers.setChecked(pref->announceToAllTrackers()); cb_announce_all_trackers.setChecked(session->announceToAllTrackers());
addRow(ANNOUNCE_ALL_TRACKERS, tr("Always announce to all trackers"), &cb_announce_all_trackers); addRow(ANNOUNCE_ALL_TRACKERS, tr("Always announce to all trackers"), &cb_announce_all_trackers);
} }

26
src/gui/mainwindow.cpp

@ -820,32 +820,26 @@ void MainWindow::handleDownloadFromUrlFailure(QString url, QString reason) const
void MainWindow::on_actionSetGlobalUploadLimit_triggered() void MainWindow::on_actionSetGlobalUploadLimit_triggered()
{ {
qDebug() << Q_FUNC_INFO; qDebug() << Q_FUNC_INFO;
BitTorrent::Session *const session = BitTorrent::Session::instance();
bool ok; bool ok;
int curLimit = BitTorrent::Session::instance()->uploadRateLimit(); const long newLimit = SpeedLimitDialog::askSpeedLimit(
const long newLimit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), curLimit); &ok, tr("Global Upload Speed Limit"), session->uploadSpeedLimit());
if (ok) { if (ok) {
qDebug("Setting global upload rate limit to %.1fKb/s", newLimit / 1024.); qDebug("Setting global upload rate limit to %.1fKb/s", newLimit / 1024.);
BitTorrent::Session::instance()->setUploadRateLimit(newLimit); session->setUploadSpeedLimit(newLimit);
if (newLimit <= 0)
Preferences::instance()->setGlobalUploadLimit(-1);
else
Preferences::instance()->setGlobalUploadLimit(newLimit / 1024.);
} }
} }
void MainWindow::on_actionSetGlobalDownloadLimit_triggered() void MainWindow::on_actionSetGlobalDownloadLimit_triggered()
{ {
qDebug() << Q_FUNC_INFO; qDebug() << Q_FUNC_INFO;
BitTorrent::Session *const session = BitTorrent::Session::instance();
bool ok; bool ok;
int curLimit = BitTorrent::Session::instance()->downloadRateLimit(); const long newLimit = SpeedLimitDialog::askSpeedLimit(
const long newLimit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), curLimit); &ok, tr("Global Download Speed Limit"), session->downloadSpeedLimit());
if (ok) { if (ok) {
qDebug("Setting global download rate limit to %.1fKb/s", newLimit / 1024.); qDebug("Setting global download rate limit to %.1fKb/s", newLimit / 1024.);
BitTorrent::Session::instance()->setDownloadRateLimit(newLimit); session->setDownloadSpeedLimit(newLimit);
if (newLimit <= 0)
Preferences::instance()->setGlobalDownloadLimit(-1);
else
Preferences::instance()->setGlobalDownloadLimit(newLimit / 1024.);
} }
} }
@ -1221,7 +1215,7 @@ void MainWindow::loadPreferences(bool configureSession)
m_propertiesWidget->getPeerList()->setAlternatingRowColors(pref->useAlternatingRowColors()); m_propertiesWidget->getPeerList()->setAlternatingRowColors(pref->useAlternatingRowColors());
// Queueing System // Queueing System
if (pref->isQueueingSystemEnabled()) { if (BitTorrent::Session::instance()->isQueueingSystemEnabled()) {
if (!m_ui->actionDecreasePriority->isVisible()) { if (!m_ui->actionDecreasePriority->isVisible()) {
m_transferListWidget->hidePriorityColumn(false); m_transferListWidget->hidePriorityColumn(false);
m_ui->actionDecreasePriority->setVisible(true); m_ui->actionDecreasePriority->setVisible(true);
@ -1412,7 +1406,7 @@ QMenu* MainWindow::trayIconMenu()
m_trayIconMenu->addAction(m_ui->actionOpen); m_trayIconMenu->addAction(m_ui->actionOpen);
m_trayIconMenu->addAction(m_ui->actionDownloadFromURL); m_trayIconMenu->addAction(m_ui->actionDownloadFromURL);
m_trayIconMenu->addSeparator(); m_trayIconMenu->addSeparator();
const bool isAltBWEnabled = Preferences::instance()->isAltBandwidthEnabled(); const bool isAltBWEnabled = BitTorrent::Session::instance()->isAltGlobalSpeedLimitEnabled();
updateAltSpeedsBtn(isAltBWEnabled); updateAltSpeedsBtn(isAltBWEnabled);
m_ui->actionUseAlternativeSpeedLimits->setChecked(isAltBWEnabled); m_ui->actionUseAlternativeSpeedLimits->setChecked(isAltBWEnabled);
m_trayIconMenu->addAction(m_ui->actionUseAlternativeSpeedLimits); m_trayIconMenu->addAction(m_ui->actionUseAlternativeSpeedLimits);

243
src/gui/optionsdlg.cpp

@ -51,6 +51,7 @@
#include "app/application.h" #include "app/application.h"
#include "base/bittorrent/session.h" #include "base/bittorrent/session.h"
#include "base/net/dnsupdater.h" #include "base/net/dnsupdater.h"
#include "base/net/proxyconfigurationmanager.h"
#include "base/preferences.h" #include "base/preferences.h"
#include "base/scanfoldersmodel.h" #include "base/scanfoldersmodel.h"
#include "base/torrentfileguard.h" #include "base/torrentfileguard.h"
@ -506,8 +507,8 @@ void OptionsDialog::saveOptions()
session->setDisableAutoTMMWhenDefaultSavePathChanged(m_ui->comboCategoryDefaultPathChanged->currentIndex() == 1); session->setDisableAutoTMMWhenDefaultSavePathChanged(m_ui->comboCategoryDefaultPathChanged->currentIndex() == 1);
session->setTempPathEnabled(m_ui->checkTempFolder->isChecked()); session->setTempPathEnabled(m_ui->checkTempFolder->isChecked());
session->setTempPath(Utils::Fs::expandPathAbs(m_ui->textTempPath->text())); session->setTempPath(Utils::Fs::expandPathAbs(m_ui->textTempPath->text()));
pref->useIncompleteFilesExtension(m_ui->checkAppendqB->isChecked()); session->setAppendExtensionEnabled(m_ui->checkAppendqB->isChecked());
pref->preAllocateAllFiles(preAllocateAllFiles()); session->setPreallocationEnabled(preAllocateAllFiles());
AddNewTorrentDialog::setEnabled(useAdditionDialog()); AddNewTorrentDialog::setEnabled(useAdditionDialog());
AddNewTorrentDialog::setTopLevel(m_ui->checkAdditionDialogFront->isChecked()); AddNewTorrentDialog::setTopLevel(m_ui->checkAdditionDialogFront->isChecked());
session->setAddTorrentPaused(addTorrentsInPause()); session->setAddTorrentPaused(addTorrentsInPause());
@ -516,8 +517,8 @@ void OptionsDialog::saveOptions()
ScanFoldersModel::instance()->makePersistent(); ScanFoldersModel::instance()->makePersistent();
removedScanDirs.clear(); removedScanDirs.clear();
addedScanDirs.clear(); addedScanDirs.clear();
pref->setTorrentExportDir(getTorrentExportDir()); session->setTorrentExportDirectory(getTorrentExportDir());
pref->setFinishedTorrentExportDir(getFinishedTorrentExportDir()); session->setFinishedTorrentExportDirectory(getFinishedTorrentExportDir());
pref->setMailNotificationEnabled(m_ui->groupMailNotification->isChecked()); pref->setMailNotificationEnabled(m_ui->groupMailNotification->isChecked());
pref->setMailNotificationEmail(m_ui->dest_email_txt->text()); pref->setMailNotificationEmail(m_ui->dest_email_txt->text());
pref->setMailNotificationSMTP(m_ui->smtp_server_txt->text()); pref->setMailNotificationSMTP(m_ui->smtp_server_txt->text());
@ -535,61 +536,66 @@ void OptionsDialog::saveOptions()
// End Downloads preferences // End Downloads preferences
// Connection preferences // Connection preferences
pref->setSessionPort(getPort()); session->setPort(getPort());
pref->setRandomPort(m_ui->checkRandomPort->isChecked()); session->setUseRandomPort(m_ui->checkRandomPort->isChecked());
pref->setUPnPEnabled(isUPnPEnabled()); pref->setUPnPEnabled(isUPnPEnabled());
const QPair<int, int> down_up_limit = getGlobalBandwidthLimits(); const QPair<int, int> down_up_limit = getGlobalBandwidthLimits();
pref->setGlobalDownloadLimit(down_up_limit.first); session->setGlobalDownloadSpeedLimit(down_up_limit.first);
pref->setGlobalUploadLimit(down_up_limit.second); session->setGlobalUploadSpeedLimit(down_up_limit.second);
pref->setuTPEnabled(m_ui->checkuTP->isChecked()); session->setUTPEnabled(m_ui->checkuTP->isChecked());
pref->setuTPRateLimited(m_ui->checkLimituTPConnections->isChecked()); session->setUTPRateLimited(m_ui->checkLimituTPConnections->isChecked());
pref->includeOverheadInLimits(m_ui->checkLimitTransportOverhead->isChecked()); session->setIncludeOverheadInLimits(m_ui->checkLimitTransportOverhead->isChecked());
pref->setIgnoreLimitsOnLAN(!m_ui->checkLimitLocalPeerRate->isChecked()); session->setIgnoreLimitsOnLAN(!m_ui->checkLimitLocalPeerRate->isChecked());
const QPair<int, int> alt_down_up_limit = getAltGlobalBandwidthLimits(); const QPair<int, int> alt_down_up_limit = getAltGlobalBandwidthLimits();
pref->setAltGlobalDownloadLimit(alt_down_up_limit.first); session->setAltGlobalDownloadSpeedLimit(alt_down_up_limit.first);
pref->setAltGlobalUploadLimit(alt_down_up_limit.second); session->setAltGlobalUploadSpeedLimit(alt_down_up_limit.second);
pref->setSchedulerEnabled(m_ui->check_schedule->isChecked()); session->setBandwidthSchedulerEnabled(m_ui->check_schedule->isChecked());
pref->setSchedulerStartTime(m_ui->schedule_from->time()); pref->setSchedulerStartTime(m_ui->schedule_from->time());
pref->setSchedulerEndTime(m_ui->schedule_to->time()); pref->setSchedulerEndTime(m_ui->schedule_to->time());
pref->setSchedulerDays((scheduler_days)m_ui->schedule_days->currentIndex()); pref->setSchedulerDays((scheduler_days)m_ui->schedule_days->currentIndex());
pref->setProxyType(getProxyType());
pref->setProxyIp(getProxyIp()); auto proxyConfigManager = Net::ProxyConfigurationManager::instance();
pref->setProxyPort(getProxyPort()); Net::ProxyConfiguration proxyConf;
pref->setProxyPeerConnections(m_ui->checkProxyPeerConnecs->isChecked()); proxyConf.type = getProxyType();
pref->setForceProxy(m_ui->checkForceProxy->isChecked()); proxyConf.ip = getProxyIp();
pref->setProxyOnlyForTorrents(m_ui->isProxyOnlyForTorrents->isChecked()); proxyConf.port = getProxyPort();
pref->setProxyAuthEnabled(isProxyAuthEnabled()); proxyConf.username = getProxyUsername();
pref->setProxyUsername(getProxyUsername()); proxyConf.password = getProxyPassword();
pref->setProxyPassword(getProxyPassword()); proxyConfigManager->setProxyDisabled(m_ui->isProxyOnlyForTorrents->isChecked());
proxyConfigManager->setProxyConfiguration(proxyConf);
session->setProxyPeerConnectionsEnabled(m_ui->checkProxyPeerConnecs->isChecked());
session->setForceProxyEnabled(m_ui->checkForceProxy->isChecked());
// End Connection preferences // End Connection preferences
// Bittorrent preferences // Bittorrent preferences
pref->setMaxConnecs(getMaxConnecs()); session->setMaxConnections(getMaxConnecs());
pref->setMaxConnecsPerTorrent(getMaxConnecsPerTorrent()); session->setMaxConnectionsPerTorrent(getMaxConnecsPerTorrent());
pref->setMaxUploads(getMaxUploads()); session->setMaxUploads(getMaxUploads());
pref->setMaxUploadsPerTorrent(getMaxUploadsPerTorrent()); session->setMaxUploadsPerTorrent(getMaxUploadsPerTorrent());
pref->setDHTEnabled(isDHTEnabled()); session->setDHTEnabled(isDHTEnabled());
pref->setPeXEnabled(m_ui->checkPeX->isChecked()); session->setPeXEnabled(m_ui->checkPeX->isChecked());
pref->setLSDEnabled(isLSDEnabled()); session->setLSDEnabled(isLSDEnabled());
pref->setEncryptionSetting(getEncryptionSetting()); session->setEncryption(getEncryptionSetting());
pref->enableAnonymousMode(m_ui->checkAnonymousMode->isChecked()); session->setAnonymousModeEnabled(m_ui->checkAnonymousMode->isChecked());
pref->setAddTrackersEnabled(m_ui->checkEnableAddTrackers->isChecked()); session->setAddTrackersEnabled(m_ui->checkEnableAddTrackers->isChecked());
pref->setTrackersList(m_ui->textTrackers->toPlainText()); session->setAdditionalTrackers(m_ui->textTrackers->toPlainText());
pref->setGlobalMaxRatio(getMaxRatio()); session->setGlobalMaxRatio(getMaxRatio());
session->setMaxRatioAction(static_cast<MaxRatioAction>(m_ui->comboRatioLimitAct->currentIndex())); session->setMaxRatioAction(static_cast<MaxRatioAction>(m_ui->comboRatioLimitAct->currentIndex()));
// End Bittorrent preferences // End Bittorrent preferences
// Misc preferences // Misc preferences
// * IPFilter // * IPFilter
pref->setFilteringEnabled(isFilteringEnabled()); session->setFilteringEnabled(isFilteringEnabled());
pref->setFilteringTrackerEnabled(m_ui->checkIpFilterTrackers->isChecked()); session->setTrackerFilteringEnabled(m_ui->checkIpFilterTrackers->isChecked());
pref->setFilter(m_ui->textFilterPath->text()); session->setIPFilterFile(m_ui->textFilterPath->text());
// End IPFilter preferences // End IPFilter preferences
// Queueing system // Queueing system
pref->setQueueingSystemEnabled(isQueueingSystemEnabled()); session->setQueueingSystemEnabled(isQueueingSystemEnabled());
pref->setMaxActiveDownloads(m_ui->spinMaxActiveDownloads->value()); session->setMaxActiveDownloads(m_ui->spinMaxActiveDownloads->value());
pref->setMaxActiveUploads(m_ui->spinMaxActiveUploads->value()); session->setMaxActiveUploads(m_ui->spinMaxActiveUploads->value());
pref->setMaxActiveTorrents(m_ui->spinMaxActiveTorrents->value()); session->setMaxActiveTorrents(m_ui->spinMaxActiveTorrents->value());
pref->setIgnoreSlowTorrentsForQueueing(m_ui->checkIgnoreSlowTorrentsForQueueing->isChecked()); session->setIgnoreSlowTorrentsForQueueing(m_ui->checkIgnoreSlowTorrentsForQueueing->isChecked());
// End Queueing system preferences // End Queueing system preferences
// Web UI // Web UI
pref->setWebUiEnabled(isWebUiEnabled()); pref->setWebUiEnabled(isWebUiEnabled());
@ -625,29 +631,28 @@ bool OptionsDialog::isFilteringEnabled() const
return m_ui->checkIPFilter->isChecked(); return m_ui->checkIPFilter->isChecked();
} }
int OptionsDialog::getProxyType() const Net::ProxyType OptionsDialog::getProxyType() const
{ {
switch (m_ui->comboProxyType->currentIndex()) { switch (m_ui->comboProxyType->currentIndex()) {
case 1: case 1:
return Proxy::SOCKS4; return Net::ProxyType::SOCKS4;
break; break;
case 2: case 2:
if (isProxyAuthEnabled()) if (isProxyAuthEnabled())
return Proxy::SOCKS5_PW; return Net::ProxyType::SOCKS5_PW;
return Proxy::SOCKS5; return Net::ProxyType::SOCKS5;
case 3: case 3:
if (isProxyAuthEnabled()) if (isProxyAuthEnabled())
return Proxy::HTTP_PW; return Net::ProxyType::HTTP_PW;
return Proxy::HTTP; return Net::ProxyType::HTTP;
default: default:
return -1; return Net::ProxyType::None;
} }
} }
void OptionsDialog::loadOptions() void OptionsDialog::loadOptions()
{ {
int intValue; int intValue;
qreal floatValue;
QString strValue; QString strValue;
bool fileLogBackup = true; bool fileLogBackup = true;
bool fileLogDelete = true; bool fileLogDelete = true;
@ -722,10 +727,10 @@ void OptionsDialog::loadOptions()
m_ui->textTempPath->setEnabled(m_ui->checkTempFolder->isChecked()); m_ui->textTempPath->setEnabled(m_ui->checkTempFolder->isChecked());
m_ui->browseTempDirButton->setEnabled(m_ui->checkTempFolder->isChecked()); m_ui->browseTempDirButton->setEnabled(m_ui->checkTempFolder->isChecked());
m_ui->textTempPath->setText(Utils::Fs::toNativePath(session->tempPath())); m_ui->textTempPath->setText(Utils::Fs::toNativePath(session->tempPath()));
m_ui->checkAppendqB->setChecked(pref->useIncompleteFilesExtension()); m_ui->checkAppendqB->setChecked(session->isAppendExtensionEnabled());
m_ui->checkPreallocateAll->setChecked(pref->preAllocateAllFiles()); m_ui->checkPreallocateAll->setChecked(session->isPreallocationEnabled());
strValue = Utils::Fs::toNativePath(pref->getTorrentExportDir()); strValue = Utils::Fs::toNativePath(session->torrentExportDirectory());
if (strValue.isEmpty()) { if (strValue.isEmpty()) {
// Disable // Disable
m_ui->checkExportDir->setChecked(false); m_ui->checkExportDir->setChecked(false);
@ -740,7 +745,7 @@ void OptionsDialog::loadOptions()
m_ui->textExportDir->setText(strValue); m_ui->textExportDir->setText(strValue);
} }
strValue = Utils::Fs::toNativePath(pref->getFinishedTorrentExportDir()); strValue = Utils::Fs::toNativePath(session->finishedTorrentExportDirectory());
if (strValue.isEmpty()) { if (strValue.isEmpty()) {
// Disable // Disable
m_ui->checkExportDirFin->setChecked(false); m_ui->checkExportDirFin->setChecked(false);
@ -777,11 +782,11 @@ void OptionsDialog::loadOptions()
// Connection preferences // Connection preferences
m_ui->checkUPnP->setChecked(pref->isUPnPEnabled()); m_ui->checkUPnP->setChecked(pref->isUPnPEnabled());
m_ui->checkRandomPort->setChecked(pref->useRandomPort()); m_ui->checkRandomPort->setChecked(session->useRandomPort());
m_ui->spinPort->setValue(pref->getSessionPort()); m_ui->spinPort->setValue(session->port());
m_ui->spinPort->setDisabled(m_ui->checkRandomPort->isChecked()); m_ui->spinPort->setDisabled(m_ui->checkRandomPort->isChecked());
intValue = pref->getMaxConnecs(); intValue = session->maxConnections();
if (intValue > 0) { if (intValue > 0) {
// enable // enable
m_ui->checkMaxConnecs->setChecked(true); m_ui->checkMaxConnecs->setChecked(true);
@ -793,7 +798,7 @@ void OptionsDialog::loadOptions()
m_ui->checkMaxConnecs->setChecked(false); m_ui->checkMaxConnecs->setChecked(false);
m_ui->spinMaxConnec->setEnabled(false); m_ui->spinMaxConnec->setEnabled(false);
} }
intValue = pref->getMaxConnecsPerTorrent(); intValue = session->maxConnectionsPerTorrent();
if (intValue > 0) { if (intValue > 0) {
// enable // enable
m_ui->checkMaxConnecsPerTorrent->setChecked(true); m_ui->checkMaxConnecsPerTorrent->setChecked(true);
@ -805,7 +810,7 @@ void OptionsDialog::loadOptions()
m_ui->checkMaxConnecsPerTorrent->setChecked(false); m_ui->checkMaxConnecsPerTorrent->setChecked(false);
m_ui->spinMaxConnecPerTorrent->setEnabled(false); m_ui->spinMaxConnecPerTorrent->setEnabled(false);
} }
intValue = pref->getMaxUploads(); intValue = session->maxUploads();
if (intValue > 0) { if (intValue > 0) {
// enable // enable
m_ui->checkMaxUploads->setChecked(true); m_ui->checkMaxUploads->setChecked(true);
@ -817,7 +822,7 @@ void OptionsDialog::loadOptions()
m_ui->checkMaxUploads->setChecked(false); m_ui->checkMaxUploads->setChecked(false);
m_ui->spinMaxUploads->setEnabled(false); m_ui->spinMaxUploads->setEnabled(false);
} }
intValue = pref->getMaxUploadsPerTorrent(); intValue = session->maxUploadsPerTorrent();
if (intValue > 0) { if (intValue > 0) {
// enable // enable
m_ui->checkMaxUploadsPerTorrent->setChecked(true); m_ui->checkMaxUploadsPerTorrent->setChecked(true);
@ -830,39 +835,45 @@ void OptionsDialog::loadOptions()
m_ui->spinMaxUploadsPerTorrent->setEnabled(false); m_ui->spinMaxUploadsPerTorrent->setEnabled(false);
} }
intValue = pref->getProxyType(); auto proxyConfigManager = Net::ProxyConfigurationManager::instance();
switch (intValue) { Net::ProxyConfiguration proxyConf = proxyConfigManager->proxyConfiguration();
case Proxy::SOCKS4: using Net::ProxyType;
bool useProxyAuth = false;
switch (proxyConf.type) {
case ProxyType::SOCKS4:
m_ui->comboProxyType->setCurrentIndex(1); m_ui->comboProxyType->setCurrentIndex(1);
break; break;
case Proxy::SOCKS5: case ProxyType::SOCKS5_PW:
case Proxy::SOCKS5_PW: useProxyAuth = true;
case ProxyType::SOCKS5:
m_ui->comboProxyType->setCurrentIndex(2); m_ui->comboProxyType->setCurrentIndex(2);
break; break;
case Proxy::HTTP: case ProxyType::HTTP_PW:
case Proxy::HTTP_PW: useProxyAuth = true;
case ProxyType::HTTP:
m_ui->comboProxyType->setCurrentIndex(3); m_ui->comboProxyType->setCurrentIndex(3);
break; break;
default: default:
m_ui->comboProxyType->setCurrentIndex(0); m_ui->comboProxyType->setCurrentIndex(0);
} }
enableProxy(m_ui->comboProxyType->currentIndex()); enableProxy(m_ui->comboProxyType->currentIndex() > 0);
m_ui->textProxyIP->setText(pref->getProxyIp()); m_ui->textProxyIP->setText(proxyConf.ip);
m_ui->spinProxyPort->setValue(pref->getProxyPort()); m_ui->spinProxyPort->setValue(proxyConf.port);
m_ui->checkProxyPeerConnecs->setChecked(pref->proxyPeerConnections()); m_ui->checkProxyAuth->setChecked(useProxyAuth);
m_ui->checkForceProxy->setChecked(pref->getForceProxy()); m_ui->textProxyUsername->setText(proxyConf.username);
m_ui->isProxyOnlyForTorrents->setChecked(pref->isProxyOnlyForTorrents()); m_ui->textProxyPassword->setText(proxyConf.password);
m_ui->checkProxyAuth->setChecked(pref->isProxyAuthEnabled());
m_ui->textProxyUsername->setText(pref->getProxyUsername()); m_ui->checkProxyPeerConnecs->setChecked(session->isProxyPeerConnectionsEnabled());
m_ui->textProxyPassword->setText(pref->getProxyPassword()); m_ui->checkForceProxy->setChecked(session->isForceProxyEnabled());
m_ui->isProxyOnlyForTorrents->setChecked(proxyConfigManager->isProxyDisabled());
m_ui->checkIPFilter->setChecked(pref->isFilteringEnabled());
m_ui->checkIpFilterTrackers->setChecked(pref->isFilteringTrackerEnabled()); m_ui->checkIPFilter->setChecked(session->isFilteringEnabled());
m_ui->textFilterPath->setText(Utils::Fs::toNativePath(pref->getFilter())); m_ui->checkIpFilterTrackers->setChecked(session->isTrackerFilteringEnabled());
m_ui->textFilterPath->setText(Utils::Fs::toNativePath(session->IPFilterFile()));
// End Connection preferences // End Connection preferences
// Speed preferences // Speed preferences
intValue = pref->getGlobalDownloadLimit(); intValue = session->globalDownloadSpeedLimit();
if (intValue > 0) { if (intValue > 0) {
// Enabled // Enabled
m_ui->checkDownloadLimit->setChecked(true); m_ui->checkDownloadLimit->setChecked(true);
@ -874,8 +885,8 @@ void OptionsDialog::loadOptions()
m_ui->checkDownloadLimit->setChecked(false); m_ui->checkDownloadLimit->setChecked(false);
m_ui->spinDownloadLimit->setEnabled(false); m_ui->spinDownloadLimit->setEnabled(false);
} }
intValue = pref->getGlobalUploadLimit(); intValue = session->globalUploadSpeedLimit();
if (intValue != -1) { if (intValue > 0) {
// Enabled // Enabled
m_ui->checkUploadLimit->setChecked(true); m_ui->checkUploadLimit->setChecked(true);
m_ui->spinUploadLimit->setEnabled(true); m_ui->spinUploadLimit->setEnabled(true);
@ -887,7 +898,7 @@ void OptionsDialog::loadOptions()
m_ui->spinUploadLimit->setEnabled(false); m_ui->spinUploadLimit->setEnabled(false);
} }
intValue = pref->getAltGlobalDownloadLimit(); intValue = session->altGlobalDownloadSpeedLimit();
if (intValue > 0) { if (intValue > 0) {
// Enabled // Enabled
m_ui->checkDownloadLimitAlt->setChecked(true); m_ui->checkDownloadLimitAlt->setChecked(true);
@ -899,8 +910,8 @@ void OptionsDialog::loadOptions()
m_ui->checkDownloadLimitAlt->setChecked(false); m_ui->checkDownloadLimitAlt->setChecked(false);
m_ui->spinDownloadLimitAlt->setEnabled(false); m_ui->spinDownloadLimitAlt->setEnabled(false);
} }
intValue = pref->getAltGlobalUploadLimit(); intValue = session->altGlobalUploadSpeedLimit();
if (intValue != -1) { if (intValue > 0) {
// Enabled // Enabled
m_ui->checkUploadLimitAlt->setChecked(true); m_ui->checkUploadLimitAlt->setChecked(true);
m_ui->spinUploadLimitAlt->setEnabled(true); m_ui->spinUploadLimitAlt->setEnabled(true);
@ -912,40 +923,39 @@ void OptionsDialog::loadOptions()
m_ui->spinUploadLimitAlt->setEnabled(false); m_ui->spinUploadLimitAlt->setEnabled(false);
} }
m_ui->checkuTP->setChecked(pref->isuTPEnabled()); m_ui->checkuTP->setChecked(session->isUTPEnabled());
m_ui->checkLimituTPConnections->setEnabled(m_ui->checkuTP->isChecked()); m_ui->checkLimituTPConnections->setEnabled(m_ui->checkuTP->isChecked());
m_ui->checkLimituTPConnections->setChecked(pref->isuTPRateLimited()); m_ui->checkLimituTPConnections->setChecked(session->isUTPRateLimited());
m_ui->checkLimitTransportOverhead->setChecked(pref->includeOverheadInLimits()); m_ui->checkLimitTransportOverhead->setChecked(session->includeOverheadInLimits());
m_ui->checkLimitLocalPeerRate->setChecked(!pref->getIgnoreLimitsOnLAN()); m_ui->checkLimitLocalPeerRate->setChecked(!session->ignoreLimitsOnLAN());
m_ui->check_schedule->setChecked(pref->isSchedulerEnabled()); m_ui->check_schedule->setChecked(session->isBandwidthSchedulerEnabled());
m_ui->schedule_from->setTime(pref->getSchedulerStartTime()); m_ui->schedule_from->setTime(pref->getSchedulerStartTime());
m_ui->schedule_to->setTime(pref->getSchedulerEndTime()); m_ui->schedule_to->setTime(pref->getSchedulerEndTime());
m_ui->schedule_days->setCurrentIndex((int)pref->getSchedulerDays()); m_ui->schedule_days->setCurrentIndex((int)pref->getSchedulerDays());
// End Speed preferences // End Speed preferences
// Bittorrent preferences // Bittorrent preferences
m_ui->checkDHT->setChecked(pref->isDHTEnabled()); m_ui->checkDHT->setChecked(session->isDHTEnabled());
m_ui->checkPeX->setChecked(pref->isPeXEnabled()); m_ui->checkPeX->setChecked(session->isPeXEnabled());
m_ui->checkLSD->setChecked(pref->isLSDEnabled()); m_ui->checkLSD->setChecked(session->isLSDEnabled());
m_ui->comboEncryption->setCurrentIndex(pref->getEncryptionSetting()); m_ui->comboEncryption->setCurrentIndex(session->encryption());
m_ui->checkAnonymousMode->setChecked(pref->isAnonymousModeEnabled()); m_ui->checkAnonymousMode->setChecked(session->isAnonymousModeEnabled());
m_ui->checkEnableAddTrackers->setChecked(pref->isAddTrackersEnabled()); m_ui->checkEnableAddTrackers->setChecked(session->isAddTrackersEnabled());
m_ui->textTrackers->setPlainText(pref->getTrackersList()); m_ui->textTrackers->setPlainText(session->additionalTrackers());
m_ui->checkEnableQueueing->setChecked(pref->isQueueingSystemEnabled()); m_ui->checkEnableQueueing->setChecked(session->isQueueingSystemEnabled());
m_ui->spinMaxActiveDownloads->setValue(pref->getMaxActiveDownloads()); m_ui->spinMaxActiveDownloads->setValue(session->maxActiveDownloads());
m_ui->spinMaxActiveUploads->setValue(pref->getMaxActiveUploads()); m_ui->spinMaxActiveUploads->setValue(session->maxActiveUploads());
m_ui->spinMaxActiveTorrents->setValue(pref->getMaxActiveTorrents()); m_ui->spinMaxActiveTorrents->setValue(session->maxActiveTorrents());
m_ui->checkIgnoreSlowTorrentsForQueueing->setChecked(pref->ignoreSlowTorrentsForQueueing()); m_ui->checkIgnoreSlowTorrentsForQueueing->setChecked(session->ignoreSlowTorrentsForQueueing());
floatValue = pref->getGlobalMaxRatio(); if (session->globalMaxRatio() >= 0.) {
if (floatValue >= 0.) {
// Enable // Enable
m_ui->checkMaxRatio->setChecked(true); m_ui->checkMaxRatio->setChecked(true);
m_ui->spinMaxRatio->setEnabled(true); m_ui->spinMaxRatio->setEnabled(true);
m_ui->comboRatioLimitAct->setEnabled(true); m_ui->comboRatioLimitAct->setEnabled(true);
m_ui->spinMaxRatio->setValue(floatValue); m_ui->spinMaxRatio->setValue(session->globalMaxRatio());
} }
else { else {
// Disable // Disable
@ -1521,13 +1531,12 @@ void OptionsDialog::on_IpFilterRefreshBtn_clicked()
if (m_refreshingIpFilter) return; if (m_refreshingIpFilter) return;
m_refreshingIpFilter = true; m_refreshingIpFilter = true;
// Updating program preferences // Updating program preferences
Preferences* const pref = Preferences::instance(); BitTorrent::Session *const session = BitTorrent::Session::instance();
pref->setFilteringEnabled(true); session->setFilteringEnabled(true);
pref->setFilter(getFilter()); session->setIPFilterFile(""); // forcing Session reload filter file
// Force refresh session->setIPFilterFile(getFilter());
connect(BitTorrent::Session::instance(), SIGNAL(ipFilterParsed(bool, int)), SLOT(handleIPFilterParsed(bool, int))); connect(session, SIGNAL(IPFilterParsed(bool, int)), SLOT(handleIPFilterParsed(bool, int)));
setCursor(QCursor(Qt::WaitCursor)); setCursor(QCursor(Qt::WaitCursor));
BitTorrent::Session::instance()->enableIPFilter(getFilter(), true);
} }
void OptionsDialog::handleIPFilterParsed(bool error, int ruleCount) void OptionsDialog::handleIPFilterParsed(bool error, int ruleCount)
@ -1538,7 +1547,7 @@ void OptionsDialog::handleIPFilterParsed(bool error, int ruleCount)
else else
QMessageBox::information(this, tr("Successfully refreshed"), tr("Successfully parsed the provided IP filter: %1 rules were applied.", "%1 is a number").arg(ruleCount)); QMessageBox::information(this, tr("Successfully refreshed"), tr("Successfully parsed the provided IP filter: %1 rules were applied.", "%1 is a number").arg(ruleCount));
m_refreshingIpFilter = false; m_refreshingIpFilter = false;
disconnect(BitTorrent::Session::instance(), SIGNAL(ipFilterParsed(bool, int)), this, SLOT(handleIPFilterParsed(bool, int))); disconnect(BitTorrent::Session::instance(), SIGNAL(IPFilterParsed(bool, int)), this, SLOT(handleIPFilterParsed(bool, int)));
} }
QString OptionsDialog::languageToLocalizedString(const QLocale &locale) QString OptionsDialog::languageToLocalizedString(const QLocale &locale)

7
src/gui/optionsdlg.h

@ -47,6 +47,11 @@ enum DoubleClickAction
NO_ACTION NO_ACTION
}; };
namespace Net
{
enum class ProxyType;
}
namespace Ui namespace Ui
{ {
class OptionsDialog; class OptionsDialog;
@ -149,7 +154,7 @@ private:
unsigned short getProxyPort() const; unsigned short getProxyPort() const;
QString getProxyUsername() const; QString getProxyUsername() const;
QString getProxyPassword() const; QString getProxyPassword() const;
int getProxyType() const; Net::ProxyType getProxyType() const;
// IP Filter // IP Filter
bool isFilteringEnabled() const; bool isFilteringEnabled() const;
QString getFilter() const; QString getFilter() const;

2
src/gui/properties/trackerlist.cpp

@ -224,7 +224,7 @@ void TrackerList::loadStickyItems(BitTorrent::TorrentHandle *const torrent) {
dht_item->setText(COL_STATUS, disabled); dht_item->setText(COL_STATUS, disabled);
// Load PeX Information // Load PeX Information
if (BitTorrent::Session::instance()->isPexEnabled() && !torrent->isPrivate()) if (BitTorrent::Session::instance()->isPeXEnabled() && !torrent->isPrivate())
pex_item->setText(COL_STATUS, working); pex_item->setText(COL_STATUS, working);
else else
pex_item->setText(COL_STATUS, disabled); pex_item->setText(COL_STATUS, disabled);

73
src/gui/statusbar.cpp

@ -43,7 +43,6 @@
#include "base/bittorrent/sessionstatus.h" #include "base/bittorrent/sessionstatus.h"
#include "speedlimitdlg.h" #include "speedlimitdlg.h"
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "base/preferences.h"
#include "base/utils/misc.h" #include "base/utils/misc.h"
#include "base/logger.h" #include "base/logger.h"
@ -52,8 +51,8 @@ StatusBar::StatusBar(QStatusBar *bar)
{ {
qApp->setStyleSheet("QStatusBar::item { border-width: 0; }"); qApp->setStyleSheet("QStatusBar::item { border-width: 0; }");
Preferences* const pref = Preferences::instance(); BitTorrent::Session *const session = BitTorrent::Session::instance();
connect(BitTorrent::Session::instance(), SIGNAL(speedLimitModeChanged(bool)), this, SLOT(updateAltSpeedsBtn(bool))); connect(session, SIGNAL(speedLimitModeChanged(bool)), this, SLOT(updateAltSpeedsBtn(bool)));
m_container = new QWidget(bar); m_container = new QWidget(bar);
m_layout = new QHBoxLayout(m_container); m_layout = new QHBoxLayout(m_container);
m_layout->setContentsMargins(0,0,0,0); m_layout->setContentsMargins(0,0,0,0);
@ -91,7 +90,7 @@ StatusBar::StatusBar(QStatusBar *bar)
m_altSpeedsBtn->setFlat(true); m_altSpeedsBtn->setFlat(true);
m_altSpeedsBtn->setFocusPolicy(Qt::NoFocus); m_altSpeedsBtn->setFocusPolicy(Qt::NoFocus);
m_altSpeedsBtn->setCursor(Qt::PointingHandCursor); m_altSpeedsBtn->setCursor(Qt::PointingHandCursor);
updateAltSpeedsBtn(pref->isAltBandwidthEnabled()); updateAltSpeedsBtn(session->isAltGlobalSpeedLimitEnabled());
connect(m_altSpeedsBtn, SIGNAL(clicked()), this, SLOT(toggleAlternativeSpeeds())); connect(m_altSpeedsBtn, SIGNAL(clicked()), this, SLOT(toggleAlternativeSpeeds()));
// Because on some platforms the default icon size is bigger // Because on some platforms the default icon size is bigger
@ -134,7 +133,7 @@ StatusBar::StatusBar(QStatusBar *bar)
m_container->adjustSize(); m_container->adjustSize();
bar->adjustSize(); bar->adjustSize();
// Is DHT enabled // Is DHT enabled
m_DHTLbl->setVisible(pref->isDHTEnabled()); m_DHTLbl->setVisible(session->isDHTEnabled());
m_refreshTimer = new QTimer(bar); m_refreshTimer = new QTimer(bar);
refreshStatusBar(); refreshStatusBar();
connect(m_refreshTimer, SIGNAL(timeout()), this, SLOT(refreshStatusBar())); connect(m_refreshTimer, SIGNAL(timeout()), this, SLOT(refreshStatusBar()));
@ -175,18 +174,18 @@ void StatusBar::stopTimer()
void StatusBar::updateConnectionStatus(const BitTorrent::SessionStatus &sessionStatus) void StatusBar::updateConnectionStatus(const BitTorrent::SessionStatus &sessionStatus)
{ {
if (!BitTorrent::Session::instance()->isListening()) { if (!BitTorrent::Session::instance()->isListening()) {
m_connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/icons/skin/disconnected.png"))); m_connecStatusLblIcon->setIcon(QIcon(QLatin1String(":/icons/skin/disconnected.png")));
m_connecStatusLblIcon->setToolTip(QString::fromUtf8("<b>") + tr("Connection Status:") + QString::fromUtf8("</b><br>") + tr("Offline. This usually means that qBittorrent failed to listen on the selected port for incoming connections.")); m_connecStatusLblIcon->setToolTip(QLatin1String("<b>") + tr("Connection Status:") + QLatin1String("</b><br>") + tr("Offline. This usually means that qBittorrent failed to listen on the selected port for incoming connections."));
} }
else { else {
if (sessionStatus.hasIncomingConnections()) { if (sessionStatus.hasIncomingConnections()) {
// Connection OK // Connection OK
m_connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/icons/skin/connected.png"))); m_connecStatusLblIcon->setIcon(QIcon(QLatin1String(":/icons/skin/connected.png")));
m_connecStatusLblIcon->setToolTip(QString::fromUtf8("<b>") + tr("Connection Status:") + QString::fromUtf8("</b><br>") + tr("Online")); m_connecStatusLblIcon->setToolTip(QLatin1String("<b>") + tr("Connection Status:") + QLatin1String("</b><br>") + tr("Online"));
} }
else { else {
m_connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/icons/skin/firewalled.png"))); m_connecStatusLblIcon->setIcon(QIcon(QLatin1String(":/icons/skin/firewalled.png")));
m_connecStatusLblIcon->setToolTip(QString::fromUtf8("<b>") + tr("Connection status:") + QString::fromUtf8("</b><br>") + QString::fromUtf8("<i>") + tr("No direct connections. This may indicate network configuration problems.") + QString::fromUtf8("</i>")); m_connecStatusLblIcon->setToolTip(QLatin1String("<b>") + tr("Connection status:") + QLatin1String("</b><br>") + QLatin1String("<i>") + tr("No direct connections. This may indicate network configuration problems.") + QLatin1String("</i>"));
} }
} }
} }
@ -205,14 +204,14 @@ void StatusBar::updateDHTNodesNumber(const BitTorrent::SessionStatus &sessionSta
void StatusBar::updateSpeedLabels(const BitTorrent::SessionStatus &sessionStatus) void StatusBar::updateSpeedLabels(const BitTorrent::SessionStatus &sessionStatus)
{ {
QString speedLbl = Utils::Misc::friendlyUnit(sessionStatus.payloadDownloadRate(), true); QString speedLbl = Utils::Misc::friendlyUnit(sessionStatus.payloadDownloadRate(), true);
int speedLimit = BitTorrent::Session::instance()->downloadRateLimit(); int speedLimit = BitTorrent::Session::instance()->downloadSpeedLimit();
if (speedLimit) if (speedLimit >= 0)
speedLbl += " [" + Utils::Misc::friendlyUnit(speedLimit, true) + "]"; speedLbl += " [" + Utils::Misc::friendlyUnit(speedLimit, true) + "]";
speedLbl += " (" + Utils::Misc::friendlyUnit(sessionStatus.totalPayloadDownload()) + ")"; speedLbl += " (" + Utils::Misc::friendlyUnit(sessionStatus.totalPayloadDownload()) + ")";
m_dlSpeedLbl->setText(speedLbl); m_dlSpeedLbl->setText(speedLbl);
speedLimit = BitTorrent::Session::instance()->uploadRateLimit(); speedLimit = BitTorrent::Session::instance()->uploadSpeedLimit();
speedLbl = Utils::Misc::friendlyUnit(sessionStatus.payloadUploadRate(), true); speedLbl = Utils::Misc::friendlyUnit(sessionStatus.payloadUploadRate(), true);
if (speedLimit) if (speedLimit >= 0)
speedLbl += " [" + Utils::Misc::friendlyUnit(speedLimit, true) + "]"; speedLbl += " [" + Utils::Misc::friendlyUnit(speedLimit, true) + "]";
speedLbl += " (" + Utils::Misc::friendlyUnit(sessionStatus.totalPayloadUpload()) + ")"; speedLbl += " (" + Utils::Misc::friendlyUnit(sessionStatus.totalPayloadUpload()) + ")";
m_upSpeedLbl->setText(speedLbl); m_upSpeedLbl->setText(speedLbl);
@ -243,35 +242,26 @@ void StatusBar::updateAltSpeedsBtn(bool alternative)
void StatusBar::toggleAlternativeSpeeds() void StatusBar::toggleAlternativeSpeeds()
{ {
Preferences* const pref = Preferences::instance(); BitTorrent::Session *const session = BitTorrent::Session::instance();
if (pref->isSchedulerEnabled()) if (session->isBandwidthSchedulerEnabled())
m_bar->showMessage(tr("Manual change of rate limits mode. The scheduler is disabled."), 5000); m_bar->showMessage(tr("Manual change of rate limits mode. The scheduler is disabled."), 5000);
BitTorrent::Session::instance()->changeSpeedLimitMode(!pref->isAltBandwidthEnabled()); session->setAltGlobalSpeedLimitEnabled(!session->isAltGlobalSpeedLimitEnabled());
} }
void StatusBar::capDownloadSpeed() void StatusBar::capDownloadSpeed()
{ {
BitTorrent::Session *const session = BitTorrent::Session::instance();
bool ok = false; bool ok = false;
int curLimit = BitTorrent::Session::instance()->downloadRateLimit(); long newLimit = SpeedLimitDialog::askSpeedLimit(
long newLimit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), curLimit); &ok, tr("Global Download Speed Limit"), session->downloadSpeedLimit());
if (ok) { if (ok) {
Preferences* const pref = Preferences::instance();
bool alt = pref->isAltBandwidthEnabled();
if (newLimit <= 0) { if (newLimit <= 0) {
qDebug("Setting global download rate limit to Unlimited"); qDebug("Setting global download rate limit to Unlimited");
BitTorrent::Session::instance()->setDownloadRateLimit(-1); session->setDownloadSpeedLimit(-1);
if (!alt)
pref->setGlobalDownloadLimit(-1);
else
pref->setAltGlobalDownloadLimit(-1);
} }
else { else {
qDebug("Setting global download rate limit to %.1fKb/s", newLimit / 1024.); qDebug("Setting global download rate limit to %.1fKb/s", newLimit / 1024.);
BitTorrent::Session::instance()->setDownloadRateLimit(newLimit); session->setDownloadSpeedLimit(newLimit);
if (!alt)
pref->setGlobalDownloadLimit(newLimit / 1024.);
else
pref->setAltGlobalDownloadLimit(newLimit / 1024.);
} }
refreshStatusBar(); refreshStatusBar();
} }
@ -279,27 +269,18 @@ void StatusBar::capDownloadSpeed()
void StatusBar::capUploadSpeed() void StatusBar::capUploadSpeed()
{ {
BitTorrent::Session *const session = BitTorrent::Session::instance();
bool ok = false; bool ok = false;
int curLimit = BitTorrent::Session::instance()->uploadRateLimit(); long newLimit = SpeedLimitDialog::askSpeedLimit(
long newLimit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), curLimit); &ok, tr("Global Upload Speed Limit"), session->uploadSpeedLimit());
if (ok) { if (ok) {
Preferences* const pref = Preferences::instance();
bool alt = pref->isAltBandwidthEnabled();
if (newLimit <= 0) { if (newLimit <= 0) {
qDebug("Setting global upload rate limit to Unlimited"); qDebug("Setting global upload rate limit to Unlimited");
BitTorrent::Session::instance()->setUploadRateLimit(-1); session->setUploadSpeedLimit(-1);
if (!alt)
Preferences::instance()->setGlobalUploadLimit(-1);
else
Preferences::instance()->setAltGlobalUploadLimit(-1);
} }
else { else {
qDebug("Setting global upload rate limit to %.1fKb/s", newLimit / 1024.); qDebug("Setting global upload rate limit to %.1fKb/s", newLimit / 1024.);
BitTorrent::Session::instance()->setUploadRateLimit(newLimit); session->setUploadSpeedLimit(newLimit);
if (!alt)
Preferences::instance()->setGlobalUploadLimit(newLimit / 1024.);
else
Preferences::instance()->setAltGlobalUploadLimit(newLimit / 1024.);
} }
refreshStatusBar(); refreshStatusBar();
} }

12
src/gui/transferlistwidget.cpp

@ -437,7 +437,9 @@ void TransferListWidget::setDlLimitSelectedTorrents()
int default_limit = -1; int default_limit = -1;
if (all_same_limit) if (all_same_limit)
default_limit = selected_torrents.first()->downloadLimit(); default_limit = selected_torrents.first()->downloadLimit();
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Download Speed Limiting"), default_limit, Preferences::instance()->getGlobalDownloadLimit() * 1024.); const long new_limit = SpeedLimitDialog::askSpeedLimit(
&ok, tr("Torrent Download Speed Limiting"), default_limit
, BitTorrent::Session::instance()->globalDownloadSpeedLimit());
if (ok) { if (ok) {
foreach (BitTorrent::TorrentHandle *const torrent, selected_torrents) { foreach (BitTorrent::TorrentHandle *const torrent, selected_torrents) {
qDebug("Applying download speed limit of %ld Kb/s to torrent %s", (long)(new_limit / 1024.), qPrintable(torrent->hash())); qDebug("Applying download speed limit of %ld Kb/s to torrent %s", (long)(new_limit / 1024.), qPrintable(torrent->hash()));
@ -466,7 +468,9 @@ void TransferListWidget::setUpLimitSelectedTorrents()
int default_limit = -1; int default_limit = -1;
if (all_same_limit) if (all_same_limit)
default_limit = selected_torrents.first()->uploadLimit(); default_limit = selected_torrents.first()->uploadLimit();
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Upload Speed Limiting"), default_limit, Preferences::instance()->getGlobalUploadLimit() * 1024.); const long new_limit = SpeedLimitDialog::askSpeedLimit(
&ok, tr("Torrent Upload Speed Limiting"), default_limit
, BitTorrent::Session::instance()->globalUploadSpeedLimit());
if (ok) { if (ok) {
foreach (BitTorrent::TorrentHandle *const torrent, selected_torrents) { foreach (BitTorrent::TorrentHandle *const torrent, selected_torrents) {
qDebug("Applying upload speed limit of %ld Kb/s to torrent %s", (long)(new_limit / 1024.), qPrintable(torrent->hash())); qDebug("Applying upload speed limit of %ld Kb/s to torrent %s", (long)(new_limit / 1024.), qPrintable(torrent->hash()));
@ -512,7 +516,7 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&)
hideshowColumn.setTitle(tr("Column visibility")); hideshowColumn.setTitle(tr("Column visibility"));
QList<QAction*> actions; QList<QAction*> actions;
for (int i = 0; i < listModel->columnCount(); ++i) { for (int i = 0; i < listModel->columnCount(); ++i) {
if (!BitTorrent::Session::instance()->isQueueingEnabled() && i == TorrentModel::TR_PRIORITY) { if (!BitTorrent::Session::instance()->isQueueingSystemEnabled() && i == TorrentModel::TR_PRIORITY) {
actions.append(0); actions.append(0);
continue; continue;
} }
@ -827,7 +831,7 @@ void TransferListWidget::displayListMenu(const QPoint&)
listMenu.addSeparator(); listMenu.addSeparator();
} }
listMenu.addAction(&actionOpen_destination_folder); listMenu.addAction(&actionOpen_destination_folder);
if (BitTorrent::Session::instance()->isQueueingEnabled() && one_not_seed) { if (BitTorrent::Session::instance()->isQueueingSystemEnabled() && one_not_seed) {
listMenu.addSeparator(); listMenu.addSeparator();
QMenu *prioMenu = listMenu.addMenu(tr("Priority")); QMenu *prioMenu = listMenu.addMenu(tr("Priority"));
prioMenu->addAction(&actionTopPriority); prioMenu->addAction(&actionTopPriority);

24
src/gui/updownratiodlg.cpp

@ -1,5 +1,5 @@
/* /*
* Bittorrent Client using Qt4 and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2011 Christian Kandeler, Christophe Dumez * Copyright (C) 2011 Christian Kandeler, Christophe Dumez
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
@ -29,28 +29,32 @@
*/ */
#include "updownratiodlg.h" #include "updownratiodlg.h"
#include "ui_updownratiodlg.h"
#include "base/preferences.h" #include "base/bittorrent/session.h"
#include "ui_updownratiodlg.h"
UpDownRatioDlg::UpDownRatioDlg(bool useDefault, qreal initialValue, UpDownRatioDlg::UpDownRatioDlg(bool useDefault, qreal initialValue,
qreal maxValue, QWidget *parent) qreal maxValue, QWidget *parent)
: QDialog(parent), ui(new Ui::UpDownRatioDlg) : QDialog(parent)
, ui(new Ui::UpDownRatioDlg)
{ {
ui->setupUi(this); ui->setupUi(this);
if (useDefault) { if (useDefault) {
ui->useDefaultButton->setChecked(true); ui->useDefaultButton->setChecked(true);
} else if (initialValue == -1) { }
else if (initialValue == -1) {
ui->noLimitButton->setChecked(true); ui->noLimitButton->setChecked(true);
initialValue = Preferences::instance()->getGlobalMaxRatio(); initialValue = BitTorrent::Session::instance()->globalMaxRatio();
} else { }
else {
ui->torrentLimitButton->setChecked(true); ui->torrentLimitButton->setChecked(true);
} }
ui->ratioSpinBox->setMinimum(0); ui->ratioSpinBox->setMinimum(0);
ui->ratioSpinBox->setMaximum(maxValue); ui->ratioSpinBox->setMaximum(maxValue);
ui->ratioSpinBox->setValue(initialValue); ui->ratioSpinBox->setValue(initialValue);
connect(ui->buttonGroup, SIGNAL(buttonClicked(int)), connect(ui->buttonGroup, SIGNAL(buttonClicked(int)), SLOT(handleRatioTypeChanged()));
SLOT(handleRatioTypeChanged()));
handleRatioTypeChanged(); handleRatioTypeChanged();
} }

16
src/webui/btjson.cpp

@ -364,7 +364,9 @@ QByteArray btjson::getSyncMainData(int acceptedResponseId, QVariantMap &lastData
QVariantMap data; QVariantMap data;
QVariantHash torrents; QVariantHash torrents;
foreach (BitTorrent::TorrentHandle *const torrent, BitTorrent::Session::instance()->torrents()) { BitTorrent::Session *const session = BitTorrent::Session::instance();
foreach (BitTorrent::TorrentHandle *const torrent, session->torrents()) {
QVariantMap map = toMap(torrent); QVariantMap map = toMap(torrent);
map.remove(KEY_TORRENT_HASH); map.remove(KEY_TORRENT_HASH);
torrents[torrent->hash()] = map; torrents[torrent->hash()] = map;
@ -373,15 +375,15 @@ QByteArray btjson::getSyncMainData(int acceptedResponseId, QVariantMap &lastData
data["torrents"] = torrents; data["torrents"] = torrents;
QVariantList categories; QVariantList categories;
foreach (const QString &category, BitTorrent::Session::instance()->categories()) foreach (const QString &category, session->categories())
categories << category; categories << category;
data["categories"] = categories; data["categories"] = categories;
QVariantMap serverState = getTranserInfoMap(); QVariantMap serverState = getTranserInfoMap();
serverState[KEY_SYNC_MAINDATA_QUEUEING] = BitTorrent::Session::instance()->isQueueingEnabled(); serverState[KEY_SYNC_MAINDATA_QUEUEING] = session->isQueueingSystemEnabled();
serverState[KEY_SYNC_MAINDATA_USE_ALT_SPEED_LIMITS] = Preferences::instance()->isAltBandwidthEnabled(); serverState[KEY_SYNC_MAINDATA_USE_ALT_SPEED_LIMITS] = session->isAltGlobalSpeedLimitEnabled();
serverState[KEY_SYNC_MAINDATA_REFRESH_INTERVAL] = Preferences::instance()->getRefreshInterval(); serverState[KEY_SYNC_MAINDATA_REFRESH_INTERVAL] = session->refreshInterval();
data["server_state"] = serverState; data["server_state"] = serverState;
return json::toJson(generateSyncData(acceptedResponseId, data, lastAcceptedData, lastData)); return json::toJson(generateSyncData(acceptedResponseId, data, lastAcceptedData, lastData));
@ -669,8 +671,8 @@ QVariantMap getTranserInfoMap()
map[KEY_TRANSFER_DLDATA] = sessionStatus.totalPayloadDownload(); map[KEY_TRANSFER_DLDATA] = sessionStatus.totalPayloadDownload();
map[KEY_TRANSFER_UPSPEED] = sessionStatus.payloadUploadRate(); map[KEY_TRANSFER_UPSPEED] = sessionStatus.payloadUploadRate();
map[KEY_TRANSFER_UPDATA] = sessionStatus.totalPayloadUpload(); map[KEY_TRANSFER_UPDATA] = sessionStatus.totalPayloadUpload();
map[KEY_TRANSFER_DLRATELIMIT] = BitTorrent::Session::instance()->downloadRateLimit(); map[KEY_TRANSFER_DLRATELIMIT] = BitTorrent::Session::instance()->downloadSpeedLimit();
map[KEY_TRANSFER_UPRATELIMIT] = BitTorrent::Session::instance()->uploadRateLimit(); map[KEY_TRANSFER_UPRATELIMIT] = BitTorrent::Session::instance()->uploadSpeedLimit();
map[KEY_TRANSFER_DHT_NODES] = sessionStatus.dhtNodes(); map[KEY_TRANSFER_DHT_NODES] = sessionStatus.dhtNodes();
if (!BitTorrent::Session::instance()->isListening()) if (!BitTorrent::Session::instance()->isListening())
map[KEY_TRANSFER_CONNECTION_STATUS] = "disconnected"; map[KEY_TRANSFER_CONNECTION_STATUS] = "disconnected";

212
src/webui/prefjson.cpp

@ -28,20 +28,22 @@
* Contact : chris@qbittorrent.org * Contact : chris@qbittorrent.org
*/ */
#include "prefjson.h"
#include <QCoreApplication>
#ifndef QT_NO_OPENSSL #ifndef QT_NO_OPENSSL
#include <QSslCertificate> #include <QSslCertificate>
#include <QSslKey> #include <QSslKey>
#endif #endif
#include <QStringList> #include <QStringList>
#include <QTranslator> #include <QTranslator>
#include <QCoreApplication>
#include "base/bittorrent/session.h"
#include "base/net/proxyconfigurationmanager.h"
#include "base/preferences.h" #include "base/preferences.h"
#include "base/scanfoldersmodel.h" #include "base/scanfoldersmodel.h"
#include "base/utils/fs.h" #include "base/utils/fs.h"
#include "base/bittorrent/session.h"
#include "jsonutils.h" #include "jsonutils.h"
#include "prefjson.h"
prefjson::prefjson() prefjson::prefjson()
{ {
@ -58,8 +60,8 @@ QByteArray prefjson::getPreferences()
data["save_path"] = Utils::Fs::toNativePath(session->defaultSavePath()); data["save_path"] = Utils::Fs::toNativePath(session->defaultSavePath());
data["temp_path_enabled"] = session->isTempPathEnabled(); data["temp_path_enabled"] = session->isTempPathEnabled();
data["temp_path"] = Utils::Fs::toNativePath(session->tempPath()); data["temp_path"] = Utils::Fs::toNativePath(session->tempPath());
data["preallocate_all"] = pref->preAllocateAllFiles(); data["preallocate_all"] = session->isPreallocationEnabled();
data["incomplete_files_ext"] = pref->useIncompleteFilesExtension(); data["incomplete_files_ext"] = session->isAppendExtensionEnabled();
QVariantHash dirs = pref->getScanDirs(); QVariantHash dirs = pref->getScanDirs();
QVariantMap nativeDirs; QVariantMap nativeDirs;
for (QVariantHash::const_iterator i = dirs.begin(), e = dirs.end(); i != e; ++i) { for (QVariantHash::const_iterator i = dirs.begin(), e = dirs.end(); i != e; ++i) {
@ -69,8 +71,8 @@ QByteArray prefjson::getPreferences()
nativeDirs.insert(Utils::Fs::toNativePath(i.key()), Utils::Fs::toNativePath(i.value().toString())); nativeDirs.insert(Utils::Fs::toNativePath(i.key()), Utils::Fs::toNativePath(i.value().toString()));
} }
data["scan_dirs"] = nativeDirs; data["scan_dirs"] = nativeDirs;
data["export_dir"] = Utils::Fs::toNativePath(pref->getTorrentExportDir()); data["export_dir"] = Utils::Fs::toNativePath(session->torrentExportDirectory());
data["export_dir_fin"] = Utils::Fs::toNativePath(pref->getFinishedTorrentExportDir()); data["export_dir_fin"] = Utils::Fs::toNativePath(session->finishedTorrentExportDirectory());
// Email notification upon download completion // Email notification upon download completion
data["mail_notification_enabled"] = pref->isMailNotificationEnabled(); data["mail_notification_enabled"] = pref->isMailNotificationEnabled();
data["mail_notification_email"] = pref->getMailNotificationEmail(); data["mail_notification_email"] = pref->getMailNotificationEmail();
@ -85,39 +87,44 @@ QByteArray prefjson::getPreferences()
// Connection // Connection
// Listening Port // Listening Port
data["listen_port"] = pref->getSessionPort(); data["listen_port"] = session->port();
data["upnp"] = pref->isUPnPEnabled(); data["upnp"] = pref->isUPnPEnabled();
data["random_port"] = pref->useRandomPort(); data["random_port"] = session->useRandomPort();
// Connections Limits // Connections Limits
data["max_connec"] = pref->getMaxConnecs(); data["max_connec"] = session->maxConnections();
data["max_connec_per_torrent"] = pref->getMaxConnecsPerTorrent(); data["max_connec_per_torrent"] = session->maxConnectionsPerTorrent();
data["max_uploads"] = pref->getMaxUploads(); data["max_uploads"] = session->maxUploads();
data["max_uploads_per_torrent"] = pref->getMaxUploadsPerTorrent(); data["max_uploads_per_torrent"] = session->maxUploadsPerTorrent();
// Proxy Server // Proxy Server
data["proxy_type"] = pref->getProxyType(); auto proxyManager = Net::ProxyConfigurationManager::instance();
data["proxy_ip"] = pref->getProxyIp(); Net::ProxyConfiguration proxyConf = proxyManager->proxyConfiguration();
data["proxy_port"] = pref->getProxyPort(); data["proxy_type"] = static_cast<int>(proxyConf.type);
data["proxy_peer_connections"] = pref->proxyPeerConnections(); data["proxy_ip"] = proxyConf.ip;
data["force_proxy"] = pref->getForceProxy(); data["proxy_port"] = proxyConf.port;
data["proxy_auth_enabled"] = pref->isProxyAuthEnabled(); data["proxy_auth_enabled"] = proxyManager->isAuthenticationRequired(); // deprecated
data["proxy_username"] = pref->getProxyUsername(); data["proxy_username"] = proxyConf.username;
data["proxy_password"] = pref->getProxyPassword(); data["proxy_password"] = proxyConf.password;
data["proxy_peer_connections"] = session->isProxyPeerConnectionsEnabled();
data["force_proxy"] = session->isForceProxyEnabled();
// IP Filtering // IP Filtering
data["ip_filter_enabled"] = pref->isFilteringEnabled(); data["ip_filter_enabled"] = session->isFilteringEnabled();
data["ip_filter_path"] = Utils::Fs::toNativePath(pref->getFilter()); data["ip_filter_path"] = Utils::Fs::toNativePath(session->IPFilterFile());
data["ip_filter_trackers"] = pref->isFilteringTrackerEnabled(); data["ip_filter_trackers"] = session->isTrackerFilteringEnabled();
// Speed // Speed
// Global Rate Limits // Global Rate Limits
data["dl_limit"] = pref->getGlobalDownloadLimit(); data["dl_limit"] = session->globalDownloadSpeedLimit();
data["up_limit"] = pref->getGlobalUploadLimit(); data["up_limit"] = session->globalUploadSpeedLimit();
data["enable_utp"] = pref->isuTPEnabled(); data["enable_utp"] = session->isUTPEnabled();
data["limit_utp_rate"] = pref->isuTPRateLimited(); data["limit_utp_rate"] = session->isUTPRateLimited();
data["limit_tcp_overhead"] = pref->includeOverheadInLimits(); data["limit_tcp_overhead"] = session->includeOverheadInLimits();
data["alt_dl_limit"] = pref->getAltGlobalDownloadLimit(); data["alt_dl_limit"] = session->altGlobalDownloadSpeedLimit();
data["alt_up_limit"] = pref->getAltGlobalUploadLimit(); data["alt_up_limit"] = session->altGlobalUploadSpeedLimit();
// Scheduling // Scheduling
data["scheduler_enabled"] = pref->isSchedulerEnabled(); data["scheduler_enabled"] = session->isBandwidthSchedulerEnabled();
const QTime start_time = pref->getSchedulerStartTime(); const QTime start_time = pref->getSchedulerStartTime();
data["schedule_from_hour"] = start_time.hour(); data["schedule_from_hour"] = start_time.hour();
data["schedule_from_min"] = start_time.minute(); data["schedule_from_min"] = start_time.minute();
@ -128,24 +135,24 @@ QByteArray prefjson::getPreferences()
// Bittorrent // Bittorrent
// Privacy // Privacy
data["dht"] = pref->isDHTEnabled(); data["dht"] = session->isDHTEnabled();
data["pex"] = pref->isPeXEnabled(); data["pex"] = session->isPeXEnabled();
data["lsd"] = pref->isLSDEnabled(); data["lsd"] = session->isLSDEnabled();
data["encryption"] = pref->getEncryptionSetting(); data["encryption"] = session->encryption();
data["anonymous_mode"] = pref->isAnonymousModeEnabled(); data["anonymous_mode"] = session->isAnonymousModeEnabled();
// Torrent Queueing // Torrent Queueing
data["queueing_enabled"] = pref->isQueueingSystemEnabled(); data["queueing_enabled"] = session->isQueueingSystemEnabled();
data["max_active_downloads"] = pref->getMaxActiveDownloads(); data["max_active_downloads"] = session->maxActiveDownloads();
data["max_active_torrents"] = pref->getMaxActiveTorrents(); data["max_active_torrents"] = session->maxActiveTorrents();
data["max_active_uploads"] = pref->getMaxActiveUploads(); data["max_active_uploads"] = session->maxActiveUploads();
data["dont_count_slow_torrents"] = pref->ignoreSlowTorrentsForQueueing(); data["dont_count_slow_torrents"] = session->ignoreSlowTorrentsForQueueing();
// Share Ratio Limiting // Share Ratio Limiting
data["max_ratio_enabled"] = (pref->getGlobalMaxRatio() >= 0.); data["max_ratio_enabled"] = (session->globalMaxRatio() >= 0.);
data["max_ratio"] = pref->getGlobalMaxRatio(); data["max_ratio"] = session->globalMaxRatio();
data["max_ratio_act"] = BitTorrent::Session::instance()->maxRatioAction(); data["max_ratio_act"] = session->maxRatioAction();
// Add trackers // Add trackers
data["add_trackers_enabled"] = pref->isAddTrackersEnabled(); data["add_trackers_enabled"] = session->isAddTrackersEnabled();
data["add_trackers"] = pref->getTrackersList(); data["add_trackers"] = session->additionalTrackers();
// Web UI // Web UI
// Language // Language
@ -185,9 +192,9 @@ void prefjson::setPreferences(const QString& json)
if (m.contains("temp_path")) if (m.contains("temp_path"))
session->setTempPath(m["temp_path"].toString()); session->setTempPath(m["temp_path"].toString());
if (m.contains("preallocate_all")) if (m.contains("preallocate_all"))
pref->preAllocateAllFiles(m["preallocate_all"].toBool()); session->setPreallocationEnabled(m["preallocate_all"].toBool());
if (m.contains("incomplete_files_ext")) if (m.contains("incomplete_files_ext"))
pref->useIncompleteFilesExtension(m["incomplete_files_ext"].toBool()); session->setAppendExtensionEnabled(m["incomplete_files_ext"].toBool());
if (m.contains("scan_dirs")) { if (m.contains("scan_dirs")) {
QVariantMap nativeDirs = m["scan_dirs"].toMap(); QVariantMap nativeDirs = m["scan_dirs"].toMap();
QVariantHash oldScanDirs = pref->getScanDirs(); QVariantHash oldScanDirs = pref->getScanDirs();
@ -232,9 +239,9 @@ void prefjson::setPreferences(const QString& json)
pref->setScanDirs(scanDirs); pref->setScanDirs(scanDirs);
} }
if (m.contains("export_dir")) if (m.contains("export_dir"))
pref->setTorrentExportDir(m["export_dir"].toString()); session->setTorrentExportDirectory(m["export_dir"].toString());
if (m.contains("export_dir_fin")) if (m.contains("export_dir_fin"))
pref->setFinishedTorrentExportDir(m["export_dir_fin"].toString()); session->setFinishedTorrentExportDirectory(m["export_dir_fin"].toString());
// Email notification upon download completion // Email notification upon download completion
if (m.contains("mail_notification_enabled")) if (m.contains("mail_notification_enabled"))
pref->setMailNotificationEnabled(m["mail_notification_enabled"].toBool()); pref->setMailNotificationEnabled(m["mail_notification_enabled"].toBool());
@ -259,109 +266,108 @@ void prefjson::setPreferences(const QString& json)
// Connection // Connection
// Listening Port // Listening Port
if (m.contains("listen_port")) if (m.contains("listen_port"))
pref->setSessionPort(m["listen_port"].toInt()); session->setPort(m["listen_port"].toInt());
if (m.contains("upnp")) if (m.contains("upnp"))
pref->setUPnPEnabled(m["upnp"].toBool()); pref->setUPnPEnabled(m["upnp"].toBool());
if (m.contains("random_port")) if (m.contains("random_port"))
pref->setRandomPort(m["random_port"].toBool()); session->setUseRandomPort(m["random_port"].toBool());
// Connections Limits // Connections Limits
if (m.contains("max_connec")) if (m.contains("max_connec"))
pref->setMaxConnecs(m["max_connec"].toInt()); session->setMaxConnections(m["max_connec"].toInt());
if (m.contains("max_connec_per_torrent")) if (m.contains("max_connec_per_torrent"))
pref->setMaxConnecsPerTorrent(m["max_connec_per_torrent"].toInt()); session->setMaxConnectionsPerTorrent(m["max_connec_per_torrent"].toInt());
if (m.contains("max_uploads")) if (m.contains("max_uploads"))
pref->setMaxUploads(m["max_uploads"].toInt()); session->setMaxUploads(m["max_uploads"].toInt());
if (m.contains("max_uploads_per_torrent")) if (m.contains("max_uploads_per_torrent"))
pref->setMaxUploadsPerTorrent(m["max_uploads_per_torrent"].toInt()); session->setMaxUploadsPerTorrent(m["max_uploads_per_torrent"].toInt());
// Proxy Server // Proxy Server
auto proxyManager = Net::ProxyConfigurationManager::instance();
Net::ProxyConfiguration proxyConf = proxyManager->proxyConfiguration();
if (m.contains("proxy_type")) if (m.contains("proxy_type"))
pref->setProxyType(m["proxy_type"].toInt()); proxyConf.type = static_cast<Net::ProxyType>(m["proxy_type"].toInt());
if (m.contains("proxy_ip")) if (m.contains("proxy_ip"))
pref->setProxyIp(m["proxy_ip"].toString()); proxyConf.ip = m["proxy_ip"].toString();
if (m.contains("proxy_port")) if (m.contains("proxy_port"))
pref->setProxyPort(m["proxy_port"].toUInt()); proxyConf.port = m["proxy_port"].toUInt();
if (m.contains("proxy_peer_connections"))
pref->setProxyPeerConnections(m["proxy_peer_connections"].toBool());
if (m.contains("force_proxy"))
pref->setForceProxy(m["force_proxy"].toBool());
if (m.contains("proxy_auth_enabled"))
pref->setProxyAuthEnabled(m["proxy_auth_enabled"].toBool());
if (m.contains("proxy_username")) if (m.contains("proxy_username"))
pref->setProxyUsername(m["proxy_username"].toString()); proxyConf.username = m["proxy_username"].toString();
if (m.contains("proxy_password")) if (m.contains("proxy_password"))
pref->setProxyPassword(m["proxy_password"].toString()); proxyConf.password = m["proxy_password"].toString();
proxyManager->setProxyConfiguration(proxyConf);
if (m.contains("proxy_peer_connections"))
session->setProxyPeerConnectionsEnabled(m["proxy_peer_connections"].toBool());
if (m.contains("force_proxy"))
session->setForceProxyEnabled(m["force_proxy"].toBool());
// IP Filtering // IP Filtering
if (m.contains("ip_filter_enabled")) if (m.contains("ip_filter_enabled"))
pref->setFilteringEnabled(m["ip_filter_enabled"].toBool()); session->setFilteringEnabled(m["ip_filter_enabled"].toBool());
if (m.contains("ip_filter_path")) if (m.contains("ip_filter_path"))
pref->setFilter(m["ip_filter_path"].toString()); session->setIPFilterFile(m["ip_filter_path"].toString());
if (m.contains("ip_filter_trackers")) if (m.contains("ip_filter_trackers"))
pref->setFilteringTrackerEnabled(m["ip_filter_trackers"].toBool()); session->setTrackerFilteringEnabled(m["ip_filter_trackers"].toBool());
// Speed // Speed
// Global Rate Limits // Global Rate Limits
if (m.contains("dl_limit")) if (m.contains("dl_limit"))
pref->setGlobalDownloadLimit(m["dl_limit"].toInt()); session->setGlobalDownloadSpeedLimit(m["dl_limit"].toInt());
if (m.contains("up_limit")) if (m.contains("up_limit"))
pref->setGlobalUploadLimit(m["up_limit"].toInt()); session->setGlobalUploadSpeedLimit(m["up_limit"].toInt());
if (m.contains("enable_utp")) if (m.contains("enable_utp"))
pref->setuTPEnabled(m["enable_utp"].toBool()); session->setUTPEnabled(m["enable_utp"].toBool());
if (m.contains("limit_utp_rate")) if (m.contains("limit_utp_rate"))
pref->setuTPRateLimited(m["limit_utp_rate"].toBool()); session->setUTPRateLimited(m["limit_utp_rate"].toBool());
if (m.contains("limit_tcp_overhead")) if (m.contains("limit_tcp_overhead"))
pref->includeOverheadInLimits(m["limit_tcp_overhead"].toBool()); session->setIncludeOverheadInLimits(m["limit_tcp_overhead"].toBool());
if (m.contains("alt_dl_limit")) if (m.contains("alt_dl_limit"))
pref->setAltGlobalDownloadLimit(m["alt_dl_limit"].toInt()); session->setAltGlobalDownloadSpeedLimit(m["alt_dl_limit"].toInt());
if (m.contains("alt_up_limit")) if (m.contains("alt_up_limit"))
pref->setAltGlobalUploadLimit(m["alt_up_limit"].toInt()); session->setAltGlobalUploadSpeedLimit(m["alt_up_limit"].toInt());
// Scheduling // Scheduling
if (m.contains("scheduler_enabled")) if (m.contains("scheduler_enabled"))
pref->setSchedulerEnabled(m["scheduler_enabled"].toBool()); session->setBandwidthSchedulerEnabled(m["scheduler_enabled"].toBool());
if (m.contains("schedule_from_hour") && m.contains("schedule_from_min")) { if (m.contains("schedule_from_hour") && m.contains("schedule_from_min"))
pref->setSchedulerStartTime(QTime(m["schedule_from_hour"].toInt(), pref->setSchedulerStartTime(QTime(m["schedule_from_hour"].toInt(), m["schedule_from_min"].toInt()));
m["schedule_from_min"].toInt())); if (m.contains("schedule_to_hour") && m.contains("schedule_to_min"))
} pref->setSchedulerEndTime(QTime(m["schedule_to_hour"].toInt(), m["schedule_to_min"].toInt()));
if (m.contains("schedule_to_hour") && m.contains("schedule_to_min")) {
pref->setSchedulerEndTime(QTime(m["schedule_to_hour"].toInt(),
m["schedule_to_min"].toInt()));
}
if (m.contains("scheduler_days")) if (m.contains("scheduler_days"))
pref->setSchedulerDays(scheduler_days(m["scheduler_days"].toInt())); pref->setSchedulerDays(scheduler_days(m["scheduler_days"].toInt()));
// Bittorrent // Bittorrent
// Privacy // Privacy
if (m.contains("dht")) if (m.contains("dht"))
pref->setDHTEnabled(m["dht"].toBool()); session->setDHTEnabled(m["dht"].toBool());
if (m.contains("pex")) if (m.contains("pex"))
pref->setPeXEnabled(m["pex"].toBool()); session->setPeXEnabled(m["pex"].toBool());
if (m.contains("lsd")) if (m.contains("lsd"))
pref->setLSDEnabled(m["lsd"].toBool()); session->setLSDEnabled(m["lsd"].toBool());
if (m.contains("encryption")) if (m.contains("encryption"))
pref->setEncryptionSetting(m["encryption"].toInt()); session->setEncryption(m["encryption"].toInt());
if (m.contains("anonymous_mode")) if (m.contains("anonymous_mode"))
pref->enableAnonymousMode(m["anonymous_mode"].toBool()); session->setAnonymousModeEnabled(m["anonymous_mode"].toBool());
// Torrent Queueing // Torrent Queueing
if (m.contains("queueing_enabled")) if (m.contains("queueing_enabled"))
pref->setQueueingSystemEnabled(m["queueing_enabled"].toBool()); session->setQueueingSystemEnabled(m["queueing_enabled"].toBool());
if (m.contains("max_active_downloads")) if (m.contains("max_active_downloads"))
pref->setMaxActiveDownloads(m["max_active_downloads"].toInt()); session->setMaxActiveDownloads(m["max_active_downloads"].toInt());
if (m.contains("max_active_torrents")) if (m.contains("max_active_torrents"))
pref->setMaxActiveTorrents(m["max_active_torrents"].toInt()); session->setMaxActiveTorrents(m["max_active_torrents"].toInt());
if (m.contains("max_active_uploads")) if (m.contains("max_active_uploads"))
pref->setMaxActiveUploads(m["max_active_uploads"].toInt()); session->setMaxActiveUploads(m["max_active_uploads"].toInt());
if (m.contains("dont_count_slow_torrents")) if (m.contains("dont_count_slow_torrents"))
pref->setIgnoreSlowTorrentsForQueueing(m["dont_count_slow_torrents"].toBool()); session->setIgnoreSlowTorrentsForQueueing(m["dont_count_slow_torrents"].toBool());
// Share Ratio Limiting // Share Ratio Limiting
if (m.contains("max_ratio_enabled")) if (m.contains("max_ratio_enabled"))
pref->setGlobalMaxRatio(m["max_ratio"].toReal()); session->setGlobalMaxRatio(m["max_ratio"].toReal());
else else
pref->setGlobalMaxRatio(-1); session->setGlobalMaxRatio(-1);
if (m.contains("max_ratio_act")) if (m.contains("max_ratio_act"))
BitTorrent::Session::instance()->setMaxRatioAction( session->setMaxRatioAction(static_cast<MaxRatioAction>(m["max_ratio_act"].toInt()));
static_cast<MaxRatioAction>(m["max_ratio_act"].toInt()));
// Add trackers // Add trackers
pref->setAddTrackersEnabled(m["add_trackers_enabled"].toBool()); session->setAddTrackersEnabled(m["add_trackers_enabled"].toBool());
pref->setTrackersList(m["add_trackers"].toString()); session->setAdditionalTrackers(m["add_trackers"].toString());
// Web UI // Web UI
// Language // Language

30
src/webui/webapplication.cpp

@ -518,13 +518,13 @@ void WebApplication::action_command_setFilePrio()
void WebApplication::action_command_getGlobalUpLimit() void WebApplication::action_command_getGlobalUpLimit()
{ {
CHECK_URI(0); CHECK_URI(0);
print(QByteArray::number(BitTorrent::Session::instance()->uploadRateLimit()), Http::CONTENT_TYPE_TXT); print(QByteArray::number(BitTorrent::Session::instance()->uploadSpeedLimit()), Http::CONTENT_TYPE_TXT);
} }
void WebApplication::action_command_getGlobalDlLimit() void WebApplication::action_command_getGlobalDlLimit()
{ {
CHECK_URI(0); CHECK_URI(0);
print(QByteArray::number(BitTorrent::Session::instance()->downloadRateLimit()), Http::CONTENT_TYPE_TXT); print(QByteArray::number(BitTorrent::Session::instance()->downloadSpeedLimit()), Http::CONTENT_TYPE_TXT);
} }
void WebApplication::action_command_setGlobalUpLimit() void WebApplication::action_command_setGlobalUpLimit()
@ -534,11 +534,7 @@ void WebApplication::action_command_setGlobalUpLimit()
qlonglong limit = request().posts["limit"].toLongLong(); qlonglong limit = request().posts["limit"].toLongLong();
if (limit == 0) limit = -1; if (limit == 0) limit = -1;
BitTorrent::Session::instance()->setUploadRateLimit(limit); BitTorrent::Session::instance()->setUploadSpeedLimit(limit);
if (Preferences::instance()->isAltBandwidthEnabled())
Preferences::instance()->setAltGlobalUploadLimit(limit / 1024.);
else
Preferences::instance()->setGlobalUploadLimit(limit / 1024.);
} }
void WebApplication::action_command_setGlobalDlLimit() void WebApplication::action_command_setGlobalDlLimit()
@ -548,11 +544,7 @@ void WebApplication::action_command_setGlobalDlLimit()
qlonglong limit = request().posts["limit"].toLongLong(); qlonglong limit = request().posts["limit"].toLongLong();
if (limit == 0) limit = -1; if (limit == 0) limit = -1;
BitTorrent::Session::instance()->setDownloadRateLimit(limit); BitTorrent::Session::instance()->setDownloadSpeedLimit(limit);
if (Preferences::instance()->isAltBandwidthEnabled())
Preferences::instance()->setAltGlobalDownloadLimit(limit / 1024.);
else
Preferences::instance()->setGlobalDownloadLimit(limit / 1024.);
} }
void WebApplication::action_command_getTorrentsUpLimit() void WebApplication::action_command_getTorrentsUpLimit()
@ -608,13 +600,15 @@ void WebApplication::action_command_setTorrentsDlLimit()
void WebApplication::action_command_toggleAlternativeSpeedLimits() void WebApplication::action_command_toggleAlternativeSpeedLimits()
{ {
CHECK_URI(0); CHECK_URI(0);
BitTorrent::Session::instance()->changeSpeedLimitMode(!Preferences::instance()->isAltBandwidthEnabled()); BitTorrent::Session *const session = BitTorrent::Session::instance();
session->setAltGlobalSpeedLimitEnabled(!session->isAltGlobalSpeedLimitEnabled());
} }
void WebApplication::action_command_alternativeSpeedLimitsEnabled() void WebApplication::action_command_alternativeSpeedLimitsEnabled()
{ {
CHECK_URI(0); CHECK_URI(0);
print(QByteArray::number(Preferences::instance()->isAltBandwidthEnabled()), Http::CONTENT_TYPE_TXT); print(QByteArray::number(BitTorrent::Session::instance()->isAltGlobalSpeedLimitEnabled())
, Http::CONTENT_TYPE_TXT);
} }
void WebApplication::action_command_toggleSequentialDownload() void WebApplication::action_command_toggleSequentialDownload()
@ -690,7 +684,7 @@ void WebApplication::action_command_increasePrio()
CHECK_URI(0); CHECK_URI(0);
CHECK_PARAMETERS("hashes"); CHECK_PARAMETERS("hashes");
if (!Preferences::instance()->isQueueingSystemEnabled()) { if (!BitTorrent::Session::instance()->isQueueingSystemEnabled()) {
status(403, "Torrent queueing must be enabled"); status(403, "Torrent queueing must be enabled");
return; return;
} }
@ -704,7 +698,7 @@ void WebApplication::action_command_decreasePrio()
CHECK_URI(0); CHECK_URI(0);
CHECK_PARAMETERS("hashes"); CHECK_PARAMETERS("hashes");
if (!Preferences::instance()->isQueueingSystemEnabled()) { if (!BitTorrent::Session::instance()->isQueueingSystemEnabled()) {
status(403, "Torrent queueing must be enabled"); status(403, "Torrent queueing must be enabled");
return; return;
} }
@ -718,7 +712,7 @@ void WebApplication::action_command_topPrio()
CHECK_URI(0); CHECK_URI(0);
CHECK_PARAMETERS("hashes"); CHECK_PARAMETERS("hashes");
if (!Preferences::instance()->isQueueingSystemEnabled()) { if (!BitTorrent::Session::instance()->isQueueingSystemEnabled()) {
status(403, "Torrent queueing must be enabled"); status(403, "Torrent queueing must be enabled");
return; return;
} }
@ -732,7 +726,7 @@ void WebApplication::action_command_bottomPrio()
CHECK_URI(0); CHECK_URI(0);
CHECK_PARAMETERS("hashes"); CHECK_PARAMETERS("hashes");
if (!Preferences::instance()->isQueueingSystemEnabled()) { if (!BitTorrent::Session::instance()->isQueueingSystemEnabled()) {
status(403, "Torrent queueing must be enabled"); status(403, "Torrent queueing must be enabled");
return; return;
} }

Loading…
Cancel
Save