Reorder code to match UI
[qBittorrent.git] / src / webui / api / appcontroller.cpp
blob922754ee1f5ff8166ca6713c13dea091085a847a
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2024 Jonathan Ketchker
4 * Copyright (C) 2018 Vladimir Golovnev <glassez@yandex.ru>
5 * Copyright (C) 2006-2012 Christophe Dumez <chris@qbittorrent.org>
6 * Copyright (C) 2006-2012 Ishan Arora <ishan@qbittorrent.org>
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * In addition, as a special exception, the copyright holders give permission to
23 * link this program with the OpenSSL project's "OpenSSL" library (or with
24 * modified versions of it that use the same license as the "OpenSSL" library),
25 * and distribute the linked executables. You must obey the GNU General Public
26 * License in all respects for all of the code used other than "OpenSSL". If you
27 * modify file(s), you may extend this exception to your version of the file(s),
28 * but you are not obligated to do so. If you do not wish to do so, delete this
29 * exception statement from your version.
32 #include "appcontroller.h"
34 #include <algorithm>
35 #include <chrono>
37 #include <QCoreApplication>
38 #include <QDebug>
39 #include <QDir>
40 #include <QDirIterator>
41 #include <QJsonArray>
42 #include <QJsonDocument>
43 #include <QJsonObject>
44 #include <QNetworkInterface>
45 #include <QRegularExpression>
46 #include <QStringList>
47 #include <QTimer>
48 #include <QTranslator>
50 #include "base/bittorrent/session.h"
51 #include "base/global.h"
52 #include "base/interfaces/iapplication.h"
53 #include "base/net/portforwarder.h"
54 #include "base/net/proxyconfigurationmanager.h"
55 #include "base/path.h"
56 #include "base/preferences.h"
57 #include "base/rss/rss_autodownloader.h"
58 #include "base/rss/rss_session.h"
59 #include "base/torrentfileguard.h"
60 #include "base/torrentfileswatcher.h"
61 #include "base/utils/fs.h"
62 #include "base/utils/misc.h"
63 #include "base/utils/net.h"
64 #include "base/utils/password.h"
65 #include "base/utils/string.h"
66 #include "base/version.h"
67 #include "apierror.h"
68 #include "../webapplication.h"
70 using namespace std::chrono_literals;
72 void AppController::webapiVersionAction()
74 setResult(API_VERSION.toString());
77 void AppController::versionAction()
79 setResult(QStringLiteral(QBT_VERSION));
82 void AppController::buildInfoAction()
84 const QString platformName =
85 #ifdef Q_OS_LINUX
86 u"linux"_s;
87 #elif defined(Q_OS_MACOS)
88 u"macos"_s;
89 #elif defined(Q_OS_WIN)
90 u"windows"_s;
91 #else
92 u"unknown"_s;
93 #endif
95 const QJsonObject versions =
97 {u"qt"_s, QStringLiteral(QT_VERSION_STR)},
98 {u"libtorrent"_s, Utils::Misc::libtorrentVersionString()},
99 {u"boost"_s, Utils::Misc::boostVersionString()},
100 {u"openssl"_s, Utils::Misc::opensslVersionString()},
101 {u"zlib"_s, Utils::Misc::zlibVersionString()},
102 {u"bitness"_s, (QT_POINTER_SIZE * 8)},
103 {u"platform"_s, platformName}
105 setResult(versions);
108 void AppController::shutdownAction()
110 // Special handling for shutdown, we
111 // need to reply to the WebUI before
112 // actually shutting down.
113 QTimer::singleShot(100ms, Qt::CoarseTimer, qApp, []
115 QCoreApplication::exit();
119 void AppController::preferencesAction()
121 const auto *pref = Preferences::instance();
122 const auto *session = BitTorrent::Session::instance();
124 QJsonObject data;
126 // Behavior
127 // Language
128 data[u"locale"_s] = pref->getLocale();
129 data[u"performance_warning"_s] = session->isPerformanceWarningEnabled();
130 // Log file
131 data[u"file_log_enabled"_s] = app()->isFileLoggerEnabled();
132 data[u"file_log_path"_s] = app()->fileLoggerPath().toString();
133 data[u"file_log_backup_enabled"_s] = app()->isFileLoggerBackup();
134 data[u"file_log_max_size"_s] = app()->fileLoggerMaxSize() / 1024;
135 data[u"file_log_delete_old"_s] = app()->isFileLoggerDeleteOld();
136 data[u"file_log_age"_s] = app()->fileLoggerAge();
137 data[u"file_log_age_type"_s] = app()->fileLoggerAgeType();
138 // Delete torrent contents files on torrent removal
139 data[u"delete_torrent_content_files"_s] = pref->removeTorrentContent();
141 // Downloads
142 // When adding a torrent
143 data[u"torrent_content_layout"_s] = Utils::String::fromEnum(session->torrentContentLayout());
144 data[u"add_to_top_of_queue"_s] = session->isAddTorrentToQueueTop();
145 data[u"add_stopped_enabled"_s] = session->isAddTorrentStopped();
146 data[u"torrent_stop_condition"_s] = Utils::String::fromEnum(session->torrentStopCondition());
147 data[u"merge_trackers"_s] = session->isMergeTrackersEnabled();
148 data[u"auto_delete_mode"_s] = static_cast<int>(TorrentFileGuard::autoDeleteMode());
149 data[u"preallocate_all"_s] = session->isPreallocationEnabled();
150 data[u"incomplete_files_ext"_s] = session->isAppendExtensionEnabled();
151 data[u"use_unwanted_folder"_s] = session->isUnwantedFolderEnabled();
152 // Saving Management
153 data[u"auto_tmm_enabled"_s] = !session->isAutoTMMDisabledByDefault();
154 data[u"torrent_changed_tmm_enabled"_s] = !session->isDisableAutoTMMWhenCategoryChanged();
155 data[u"save_path_changed_tmm_enabled"_s] = !session->isDisableAutoTMMWhenDefaultSavePathChanged();
156 data[u"category_changed_tmm_enabled"_s] = !session->isDisableAutoTMMWhenCategorySavePathChanged();
157 data[u"use_subcategories"] = session->isSubcategoriesEnabled();
158 data[u"save_path"_s] = session->savePath().toString();
159 data[u"temp_path_enabled"_s] = session->isDownloadPathEnabled();
160 data[u"temp_path"_s] = session->downloadPath().toString();
161 data[u"use_category_paths_in_manual_mode"_s] = session->useCategoryPathsInManualMode();
162 data[u"export_dir"_s] = session->torrentExportDirectory().toString();
163 data[u"export_dir_fin"_s] = session->finishedTorrentExportDirectory().toString();
165 // TODO: The following code is deprecated. Delete it once replaced by updated API method.
166 // === BEGIN DEPRECATED CODE === //
167 TorrentFilesWatcher *fsWatcher = TorrentFilesWatcher::instance();
168 const QHash<Path, TorrentFilesWatcher::WatchedFolderOptions> watchedFolders = fsWatcher->folders();
169 QJsonObject nativeDirs;
170 for (auto i = watchedFolders.cbegin(); i != watchedFolders.cend(); ++i)
172 const Path &watchedFolder = i.key();
173 const BitTorrent::AddTorrentParams params = i.value().addTorrentParams;
174 if (params.savePath.isEmpty())
175 nativeDirs.insert(watchedFolder.toString(), 1);
176 else if (params.savePath == watchedFolder)
177 nativeDirs.insert(watchedFolder.toString(), 0);
178 else
179 nativeDirs.insert(watchedFolder.toString(), params.savePath.toString());
181 data[u"scan_dirs"_s] = nativeDirs;
182 // === END DEPRECATED CODE === //
184 // Excluded file names
185 data[u"excluded_file_names_enabled"_s] = session->isExcludedFileNamesEnabled();
186 data[u"excluded_file_names"_s] = session->excludedFileNames().join(u'\n');
188 // Email notification upon download completion
189 data[u"mail_notification_enabled"_s] = pref->isMailNotificationEnabled();
190 data[u"mail_notification_sender"_s] = pref->getMailNotificationSender();
191 data[u"mail_notification_email"_s] = pref->getMailNotificationEmail();
192 data[u"mail_notification_smtp"_s] = pref->getMailNotificationSMTP();
193 data[u"mail_notification_ssl_enabled"_s] = pref->getMailNotificationSMTPSSL();
194 data[u"mail_notification_auth_enabled"_s] = pref->getMailNotificationSMTPAuth();
195 data[u"mail_notification_username"_s] = pref->getMailNotificationSMTPUsername();
196 data[u"mail_notification_password"_s] = pref->getMailNotificationSMTPPassword();
197 // Run an external program on torrent added
198 data[u"autorun_on_torrent_added_enabled"_s] = pref->isAutoRunOnTorrentAddedEnabled();
199 data[u"autorun_on_torrent_added_program"_s] = pref->getAutoRunOnTorrentAddedProgram();
200 // Run an external program on torrent finished
201 data[u"autorun_enabled"_s] = pref->isAutoRunOnTorrentFinishedEnabled();
202 data[u"autorun_program"_s] = pref->getAutoRunOnTorrentFinishedProgram();
204 // Connection
205 // Listening Port
206 data[u"listen_port"_s] = session->port();
207 data[u"ssl_enabled"_s] = session->isSSLEnabled();
208 data[u"ssl_listen_port"_s] = session->sslPort();
209 data[u"random_port"_s] = (session->port() == 0); // deprecated
210 data[u"upnp"_s] = Net::PortForwarder::instance()->isEnabled();
211 // Connections Limits
212 data[u"max_connec"_s] = session->maxConnections();
213 data[u"max_connec_per_torrent"_s] = session->maxConnectionsPerTorrent();
214 data[u"max_uploads"_s] = session->maxUploads();
215 data[u"max_uploads_per_torrent"_s] = session->maxUploadsPerTorrent();
217 // I2P
218 data[u"i2p_enabled"_s] = session->isI2PEnabled();
219 data[u"i2p_address"_s] = session->I2PAddress();
220 data[u"i2p_port"_s] = session->I2PPort();
221 data[u"i2p_mixed_mode"_s] = session->I2PMixedMode();
222 data[u"i2p_inbound_quantity"_s] = session->I2PInboundQuantity();
223 data[u"i2p_outbound_quantity"_s] = session->I2POutboundQuantity();
224 data[u"i2p_inbound_length"_s] = session->I2PInboundLength();
225 data[u"i2p_outbound_length"_s] = session->I2POutboundLength();
227 // Proxy Server
228 const auto *proxyManager = Net::ProxyConfigurationManager::instance();
229 Net::ProxyConfiguration proxyConf = proxyManager->proxyConfiguration();
230 data[u"proxy_type"_s] = Utils::String::fromEnum(proxyConf.type);
231 data[u"proxy_ip"_s] = proxyConf.ip;
232 data[u"proxy_port"_s] = proxyConf.port;
233 data[u"proxy_auth_enabled"_s] = proxyConf.authEnabled;
234 data[u"proxy_username"_s] = proxyConf.username;
235 data[u"proxy_password"_s] = proxyConf.password;
236 data[u"proxy_hostname_lookup"_s] = proxyConf.hostnameLookupEnabled;
238 data[u"proxy_bittorrent"_s] = pref->useProxyForBT();
239 data[u"proxy_peer_connections"_s] = session->isProxyPeerConnectionsEnabled();
240 data[u"proxy_rss"_s] = pref->useProxyForRSS();
241 data[u"proxy_misc"_s] = pref->useProxyForGeneralPurposes();
243 // IP Filtering
244 data[u"ip_filter_enabled"_s] = session->isIPFilteringEnabled();
245 data[u"ip_filter_path"_s] = session->IPFilterFile().toString();
246 data[u"ip_filter_trackers"_s] = session->isTrackerFilteringEnabled();
247 data[u"banned_IPs"_s] = session->bannedIPs().join(u'\n');
249 // Speed
250 // Global Rate Limits
251 data[u"dl_limit"_s] = session->globalDownloadSpeedLimit();
252 data[u"up_limit"_s] = session->globalUploadSpeedLimit();
253 data[u"alt_dl_limit"_s] = session->altGlobalDownloadSpeedLimit();
254 data[u"alt_up_limit"_s] = session->altGlobalUploadSpeedLimit();
255 data[u"bittorrent_protocol"_s] = static_cast<int>(session->btProtocol());
256 data[u"limit_utp_rate"_s] = session->isUTPRateLimited();
257 data[u"limit_tcp_overhead"_s] = session->includeOverheadInLimits();
258 data[u"limit_lan_peers"_s] = !session->ignoreLimitsOnLAN();
259 // Scheduling
260 data[u"scheduler_enabled"_s] = session->isBandwidthSchedulerEnabled();
261 const QTime start_time = pref->getSchedulerStartTime();
262 data[u"schedule_from_hour"_s] = start_time.hour();
263 data[u"schedule_from_min"_s] = start_time.minute();
264 const QTime end_time = pref->getSchedulerEndTime();
265 data[u"schedule_to_hour"_s] = end_time.hour();
266 data[u"schedule_to_min"_s] = end_time.minute();
267 data[u"scheduler_days"_s] = static_cast<int>(pref->getSchedulerDays());
269 // Bittorrent
270 // Privacy
271 data[u"dht"_s] = session->isDHTEnabled();
272 data[u"pex"_s] = session->isPeXEnabled();
273 data[u"lsd"_s] = session->isLSDEnabled();
274 data[u"encryption"_s] = session->encryption();
275 data[u"anonymous_mode"_s] = session->isAnonymousModeEnabled();
276 // Max active checking torrents
277 data[u"max_active_checking_torrents"_s] = session->maxActiveCheckingTorrents();
278 // Torrent Queueing
279 data[u"queueing_enabled"_s] = session->isQueueingSystemEnabled();
280 data[u"max_active_downloads"_s] = session->maxActiveDownloads();
281 data[u"max_active_torrents"_s] = session->maxActiveTorrents();
282 data[u"max_active_uploads"_s] = session->maxActiveUploads();
283 data[u"dont_count_slow_torrents"_s] = session->ignoreSlowTorrentsForQueueing();
284 data[u"slow_torrent_dl_rate_threshold"_s] = session->downloadRateForSlowTorrents();
285 data[u"slow_torrent_ul_rate_threshold"_s] = session->uploadRateForSlowTorrents();
286 data[u"slow_torrent_inactive_timer"_s] = session->slowTorrentsInactivityTimer();
287 // Share Ratio Limiting
288 data[u"max_ratio_enabled"_s] = (session->globalMaxRatio() >= 0.);
289 data[u"max_ratio"_s] = session->globalMaxRatio();
290 data[u"max_seeding_time_enabled"_s] = (session->globalMaxSeedingMinutes() >= 0.);
291 data[u"max_seeding_time"_s] = session->globalMaxSeedingMinutes();
292 data[u"max_inactive_seeding_time_enabled"_s] = (session->globalMaxInactiveSeedingMinutes() >= 0.);
293 data[u"max_inactive_seeding_time"_s] = session->globalMaxInactiveSeedingMinutes();
294 data[u"max_ratio_act"_s] = static_cast<int>(session->shareLimitAction());
295 // Add trackers
296 data[u"add_trackers_enabled"_s] = session->isAddTrackersEnabled();
297 data[u"add_trackers"_s] = session->additionalTrackers();
299 // WebUI
300 // HTTP Server
301 data[u"web_ui_domain_list"_s] = pref->getServerDomains();
302 data[u"web_ui_address"_s] = pref->getWebUIAddress();
303 data[u"web_ui_port"_s] = pref->getWebUIPort();
304 data[u"web_ui_upnp"_s] = pref->useUPnPForWebUIPort();
305 data[u"use_https"_s] = pref->isWebUIHttpsEnabled();
306 data[u"web_ui_https_cert_path"_s] = pref->getWebUIHttpsCertificatePath().toString();
307 data[u"web_ui_https_key_path"_s] = pref->getWebUIHttpsKeyPath().toString();
308 // Authentication
309 data[u"web_ui_username"_s] = pref->getWebUIUsername();
310 data[u"bypass_local_auth"_s] = !pref->isWebUILocalAuthEnabled();
311 data[u"bypass_auth_subnet_whitelist_enabled"_s] = pref->isWebUIAuthSubnetWhitelistEnabled();
312 QStringList authSubnetWhitelistStringList;
313 for (const Utils::Net::Subnet &subnet : asConst(pref->getWebUIAuthSubnetWhitelist()))
314 authSubnetWhitelistStringList << Utils::Net::subnetToString(subnet);
315 data[u"bypass_auth_subnet_whitelist"_s] = authSubnetWhitelistStringList.join(u'\n');
316 data[u"web_ui_max_auth_fail_count"_s] = pref->getWebUIMaxAuthFailCount();
317 data[u"web_ui_ban_duration"_s] = static_cast<int>(pref->getWebUIBanDuration().count());
318 data[u"web_ui_session_timeout"_s] = pref->getWebUISessionTimeout();
319 // Use alternative WebUI
320 data[u"alternative_webui_enabled"_s] = pref->isAltWebUIEnabled();
321 data[u"alternative_webui_path"_s] = pref->getWebUIRootFolder().toString();
322 // Security
323 data[u"web_ui_clickjacking_protection_enabled"_s] = pref->isWebUIClickjackingProtectionEnabled();
324 data[u"web_ui_csrf_protection_enabled"_s] = pref->isWebUICSRFProtectionEnabled();
325 data[u"web_ui_secure_cookie_enabled"_s] = pref->isWebUISecureCookieEnabled();
326 data[u"web_ui_host_header_validation_enabled"_s] = pref->isWebUIHostHeaderValidationEnabled();
327 // Custom HTTP headers
328 data[u"web_ui_use_custom_http_headers_enabled"_s] = pref->isWebUICustomHTTPHeadersEnabled();
329 data[u"web_ui_custom_http_headers"_s] = pref->getWebUICustomHTTPHeaders();
330 // Reverse proxy
331 data[u"web_ui_reverse_proxy_enabled"_s] = pref->isWebUIReverseProxySupportEnabled();
332 data[u"web_ui_reverse_proxies_list"_s] = pref->getWebUITrustedReverseProxiesList();
333 // Update my dynamic domain name
334 data[u"dyndns_enabled"_s] = pref->isDynDNSEnabled();
335 data[u"dyndns_service"_s] = static_cast<int>(pref->getDynDNSService());
336 data[u"dyndns_username"_s] = pref->getDynDNSUsername();
337 data[u"dyndns_password"_s] = pref->getDynDNSPassword();
338 data[u"dyndns_domain"_s] = pref->getDynDomainName();
340 // RSS settings
341 data[u"rss_refresh_interval"_s] = RSS::Session::instance()->refreshInterval();
342 data[u"rss_fetch_delay"_s] = static_cast<qlonglong>(RSS::Session::instance()->fetchDelay().count());
343 data[u"rss_max_articles_per_feed"_s] = RSS::Session::instance()->maxArticlesPerFeed();
344 data[u"rss_processing_enabled"_s] = RSS::Session::instance()->isProcessingEnabled();
345 data[u"rss_auto_downloading_enabled"_s] = RSS::AutoDownloader::instance()->isProcessingEnabled();
346 data[u"rss_download_repack_proper_episodes"_s] = RSS::AutoDownloader::instance()->downloadRepacks();
347 data[u"rss_smart_episode_filters"_s] = RSS::AutoDownloader::instance()->smartEpisodeFilters().join(u'\n');
349 // Advanced settings
350 // qBitorrent preferences
351 // Resume data storage type
352 data[u"resume_data_storage_type"_s] = Utils::String::fromEnum(session->resumeDataStorageType());
353 // Torrent content removing mode
354 data[u"torrent_content_remove_option"_s] = Utils::String::fromEnum(session->torrentContentRemoveOption());
355 // Physical memory (RAM) usage limit
356 data[u"memory_working_set_limit"_s] = app()->memoryWorkingSetLimit();
357 // Current network interface
358 data[u"current_network_interface"_s] = session->networkInterface();
359 // Current network interface name
360 data[u"current_interface_name"_s] = session->networkInterfaceName();
361 // Current network interface address
362 data[u"current_interface_address"_s] = session->networkInterfaceAddress();
363 // Save resume data interval
364 data[u"save_resume_data_interval"_s] = session->saveResumeDataInterval();
365 // .torrent file size limit
366 data[u"torrent_file_size_limit"_s] = pref->getTorrentFileSizeLimit();
367 // Recheck completed torrents
368 data[u"recheck_completed_torrents"_s] = pref->recheckTorrentsOnCompletion();
369 // Customize application instance name
370 data[u"app_instance_name"_s] = app()->instanceName();
371 // Refresh interval
372 data[u"refresh_interval"_s] = session->refreshInterval();
373 // Resolve peer countries
374 data[u"resolve_peer_countries"_s] = pref->resolvePeerCountries();
375 // Reannounce to all trackers when ip/port changed
376 data[u"reannounce_when_address_changed"_s] = session->isReannounceWhenAddressChangedEnabled();
377 // Embedded tracker
378 data[u"enable_embedded_tracker"_s] = session->isTrackerEnabled();
379 data[u"embedded_tracker_port"_s] = pref->getTrackerPort();
380 data[u"embedded_tracker_port_forwarding"_s] = pref->isTrackerPortForwardingEnabled();
381 // Mark-of-the-Web
382 data[u"mark_of_the_web"_s] = pref->isMarkOfTheWebEnabled();
383 // Ignore SSL errors
384 data[u"ignore_ssl_errors"_s] = pref->isIgnoreSSLErrors();
385 // Python executable path
386 data[u"python_executable_path"_s] = pref->getPythonExecutablePath().toString();
388 // libtorrent preferences
389 // Bdecode depth limit
390 data[u"bdecode_depth_limit"_s] = pref->getBdecodeDepthLimit();
391 // Bdecode token limit
392 data[u"bdecode_token_limit"_s] = pref->getBdecodeTokenLimit();
393 // Async IO threads
394 data[u"async_io_threads"_s] = session->asyncIOThreads();
395 // Hashing threads
396 data[u"hashing_threads"_s] = session->hashingThreads();
397 // File pool size
398 data[u"file_pool_size"_s] = session->filePoolSize();
399 // Checking memory usage
400 data[u"checking_memory_use"_s] = session->checkingMemUsage();
401 // Disk write cache
402 data[u"disk_cache"_s] = session->diskCacheSize();
403 data[u"disk_cache_ttl"_s] = session->diskCacheTTL();
404 // Disk queue size
405 data[u"disk_queue_size"_s] = session->diskQueueSize();
406 // Disk IO Type
407 data[u"disk_io_type"_s] = static_cast<int>(session->diskIOType());
408 // Disk IO read mode
409 data[u"disk_io_read_mode"_s] = static_cast<int>(session->diskIOReadMode());
410 // Disk IO write mode
411 data[u"disk_io_write_mode"_s] = static_cast<int>(session->diskIOWriteMode());
412 // Coalesce reads & writes
413 data[u"enable_coalesce_read_write"_s] = session->isCoalesceReadWriteEnabled();
414 // Piece Extent Affinity
415 data[u"enable_piece_extent_affinity"_s] = session->usePieceExtentAffinity();
416 // Suggest mode
417 data[u"enable_upload_suggestions"_s] = session->isSuggestModeEnabled();
418 // Send buffer watermark
419 data[u"send_buffer_watermark"_s] = session->sendBufferWatermark();
420 data[u"send_buffer_low_watermark"_s] = session->sendBufferLowWatermark();
421 data[u"send_buffer_watermark_factor"_s] = session->sendBufferWatermarkFactor();
422 // Outgoing connections per second
423 data[u"connection_speed"_s] = session->connectionSpeed();
424 // Socket send buffer size
425 data[u"socket_send_buffer_size"_s] = session->socketSendBufferSize();
426 // Socket receive buffer size
427 data[u"socket_receive_buffer_size"_s] = session->socketReceiveBufferSize();
428 // Socket listen backlog size
429 data[u"socket_backlog_size"_s] = session->socketBacklogSize();
430 // Outgoing ports
431 data[u"outgoing_ports_min"_s] = session->outgoingPortsMin();
432 data[u"outgoing_ports_max"_s] = session->outgoingPortsMax();
433 // UPnP lease duration
434 data[u"upnp_lease_duration"_s] = session->UPnPLeaseDuration();
435 // Type of service
436 data[u"peer_tos"_s] = session->peerToS();
437 // uTP-TCP mixed mode
438 data[u"utp_tcp_mixed_mode"_s] = static_cast<int>(session->utpMixedMode());
439 // Support internationalized domain name (IDN)
440 data[u"idn_support_enabled"_s] = session->isIDNSupportEnabled();
441 // Multiple connections per IP
442 data[u"enable_multi_connections_from_same_ip"_s] = session->multiConnectionsPerIpEnabled();
443 // Validate HTTPS tracker certificate
444 data[u"validate_https_tracker_certificate"_s] = session->validateHTTPSTrackerCertificate();
445 // SSRF mitigation
446 data[u"ssrf_mitigation"_s] = session->isSSRFMitigationEnabled();
447 // Disallow connection to peers on privileged ports
448 data[u"block_peers_on_privileged_ports"_s] = session->blockPeersOnPrivilegedPorts();
449 // Choking algorithm
450 data[u"upload_slots_behavior"_s] = static_cast<int>(session->chokingAlgorithm());
451 // Seed choking algorithm
452 data[u"upload_choking_algorithm"_s] = static_cast<int>(session->seedChokingAlgorithm());
453 // Announce
454 data[u"announce_to_all_trackers"_s] = session->announceToAllTrackers();
455 data[u"announce_to_all_tiers"_s] = session->announceToAllTiers();
456 data[u"announce_ip"_s] = session->announceIP();
457 data[u"max_concurrent_http_announces"_s] = session->maxConcurrentHTTPAnnounces();
458 data[u"stop_tracker_timeout"_s] = session->stopTrackerTimeout();
459 // Peer Turnover
460 data[u"peer_turnover"_s] = session->peerTurnover();
461 data[u"peer_turnover_cutoff"_s] = session->peerTurnoverCutoff();
462 data[u"peer_turnover_interval"_s] = session->peerTurnoverInterval();
463 // Maximum outstanding requests to a single peer
464 data[u"request_queue_size"_s] = session->requestQueueSize();
465 // DHT bootstrap nodes
466 data[u"dht_bootstrap_nodes"_s] = session->getDHTBootstrapNodes();
468 setResult(data);
471 void AppController::setPreferencesAction()
473 requireParams({u"json"_s});
475 auto *pref = Preferences::instance();
476 auto *session = BitTorrent::Session::instance();
477 const QVariantHash m = QJsonDocument::fromJson(params()[u"json"_s].toUtf8()).toVariant().toHash();
479 QVariantHash::ConstIterator it;
480 const auto hasKey = [&it, &m](const QString &key) -> bool
482 it = m.find(key);
483 return (it != m.constEnd());
486 // Behavior
487 // Language
488 if (hasKey(u"locale"_s))
490 QString locale = it.value().toString();
491 if (pref->getLocale() != locale)
493 auto *translator = new QTranslator;
494 if (translator->load(u":/lang/qbittorrent_"_s + locale))
496 qDebug("%s locale recognized, using translation.", qUtf8Printable(locale));
498 else
500 qDebug("%s locale unrecognized, using default (en).", qUtf8Printable(locale));
502 qApp->installTranslator(translator);
504 pref->setLocale(locale);
507 if (hasKey(u"performance_warning"_s))
508 session->setPerformanceWarningEnabled(it.value().toBool());
509 // Log file
510 if (hasKey(u"file_log_enabled"_s))
511 app()->setFileLoggerEnabled(it.value().toBool());
512 if (hasKey(u"file_log_path"_s))
513 app()->setFileLoggerPath(Path(it.value().toString()));
514 if (hasKey(u"file_log_backup_enabled"_s))
515 app()->setFileLoggerBackup(it.value().toBool());
516 if (hasKey(u"file_log_max_size"_s))
517 app()->setFileLoggerMaxSize(it.value().toInt() * 1024);
518 if (hasKey(u"file_log_delete_old"_s))
519 app()->setFileLoggerDeleteOld(it.value().toBool());
520 if (hasKey(u"file_log_age"_s))
521 app()->setFileLoggerAge(it.value().toInt());
522 if (hasKey(u"file_log_age_type"_s))
523 app()->setFileLoggerAgeType(it.value().toInt());
524 // Delete torrent content files on torrent removal
525 if (hasKey(u"delete_torrent_content_files"_s))
526 pref->setRemoveTorrentContent(it.value().toBool());
528 // Downloads
529 // When adding a torrent
530 if (hasKey(u"torrent_content_layout"_s))
531 session->setTorrentContentLayout(Utils::String::toEnum(it.value().toString(), BitTorrent::TorrentContentLayout::Original));
532 if (hasKey(u"add_to_top_of_queue"_s))
533 session->setAddTorrentToQueueTop(it.value().toBool());
534 if (hasKey(u"add_stopped_enabled"_s))
535 session->setAddTorrentStopped(it.value().toBool());
536 if (hasKey(u"torrent_stop_condition"_s))
537 session->setTorrentStopCondition(Utils::String::toEnum(it.value().toString(), BitTorrent::Torrent::StopCondition::None));
538 if (hasKey(u"merge_trackers"_s))
539 session->setMergeTrackersEnabled(it.value().toBool());
540 if (hasKey(u"auto_delete_mode"_s))
541 TorrentFileGuard::setAutoDeleteMode(static_cast<TorrentFileGuard::AutoDeleteMode>(it.value().toInt()));
543 if (hasKey(u"preallocate_all"_s))
544 session->setPreallocationEnabled(it.value().toBool());
545 if (hasKey(u"incomplete_files_ext"_s))
546 session->setAppendExtensionEnabled(it.value().toBool());
547 if (hasKey(u"use_unwanted_folder"_s))
548 session->setUnwantedFolderEnabled(it.value().toBool());
550 // Saving Management
551 if (hasKey(u"auto_tmm_enabled"_s))
552 session->setAutoTMMDisabledByDefault(!it.value().toBool());
553 if (hasKey(u"torrent_changed_tmm_enabled"_s))
554 session->setDisableAutoTMMWhenCategoryChanged(!it.value().toBool());
555 if (hasKey(u"save_path_changed_tmm_enabled"_s))
556 session->setDisableAutoTMMWhenDefaultSavePathChanged(!it.value().toBool());
557 if (hasKey(u"category_changed_tmm_enabled"_s))
558 session->setDisableAutoTMMWhenCategorySavePathChanged(!it.value().toBool());
559 if (hasKey(u"use_subcategories"_s))
560 session->setSubcategoriesEnabled(it.value().toBool());
561 if (hasKey(u"save_path"_s))
562 session->setSavePath(Path(it.value().toString()));
563 if (hasKey(u"temp_path_enabled"_s))
564 session->setDownloadPathEnabled(it.value().toBool());
565 if (hasKey(u"temp_path"_s))
566 session->setDownloadPath(Path(it.value().toString()));
567 if (hasKey(u"use_category_paths_in_manual_mode"_s))
568 session->setUseCategoryPathsInManualMode(it.value().toBool());
569 if (hasKey(u"export_dir"_s))
570 session->setTorrentExportDirectory(Path(it.value().toString()));
571 if (hasKey(u"export_dir_fin"_s))
572 session->setFinishedTorrentExportDirectory(Path(it.value().toString()));
574 // TODO: The following code is deprecated. Delete it once replaced by updated API method.
575 // === BEGIN DEPRECATED CODE === //
576 if (hasKey(u"scan_dirs"_s))
578 PathList scanDirs;
579 TorrentFilesWatcher *fsWatcher = TorrentFilesWatcher::instance();
580 const PathList oldScanDirs = fsWatcher->folders().keys();
581 const QVariantHash nativeDirs = it.value().toHash();
582 for (auto i = nativeDirs.cbegin(); i != nativeDirs.cend(); ++i)
586 const Path watchedFolder {i.key()};
587 TorrentFilesWatcher::WatchedFolderOptions options = fsWatcher->folders().value(watchedFolder);
588 BitTorrent::AddTorrentParams &params = options.addTorrentParams;
590 bool isInt = false;
591 const int intVal = i.value().toInt(&isInt);
592 if (isInt)
594 if (intVal == 0)
596 params.savePath = watchedFolder;
597 params.useAutoTMM = false;
600 else
602 const Path customSavePath {i.value().toString()};
603 params.savePath = customSavePath;
604 params.useAutoTMM = false;
607 fsWatcher->setWatchedFolder(watchedFolder, options);
608 scanDirs.append(watchedFolder);
610 catch (...)
615 // Update deleted folders
616 for (const Path &path : oldScanDirs)
618 if (!scanDirs.contains(path))
619 fsWatcher->removeWatchedFolder(path);
622 // === END DEPRECATED CODE === //
624 // Excluded file names
625 if (hasKey(u"excluded_file_names_enabled"_s))
626 session->setExcludedFileNamesEnabled(it.value().toBool());
627 if (hasKey(u"excluded_file_names"_s))
628 session->setExcludedFileNames(it.value().toString().split(u'\n'));
630 // Email notification upon download completion
631 if (hasKey(u"mail_notification_enabled"_s))
632 pref->setMailNotificationEnabled(it.value().toBool());
633 if (hasKey(u"mail_notification_sender"_s))
634 pref->setMailNotificationSender(it.value().toString());
635 if (hasKey(u"mail_notification_email"_s))
636 pref->setMailNotificationEmail(it.value().toString());
637 if (hasKey(u"mail_notification_smtp"_s))
638 pref->setMailNotificationSMTP(it.value().toString());
639 if (hasKey(u"mail_notification_ssl_enabled"_s))
640 pref->setMailNotificationSMTPSSL(it.value().toBool());
641 if (hasKey(u"mail_notification_auth_enabled"_s))
642 pref->setMailNotificationSMTPAuth(it.value().toBool());
643 if (hasKey(u"mail_notification_username"_s))
644 pref->setMailNotificationSMTPUsername(it.value().toString());
645 if (hasKey(u"mail_notification_password"_s))
646 pref->setMailNotificationSMTPPassword(it.value().toString());
647 // Run an external program on torrent added
648 if (hasKey(u"autorun_on_torrent_added_enabled"_s))
649 pref->setAutoRunOnTorrentAddedEnabled(it.value().toBool());
650 if (hasKey(u"autorun_on_torrent_added_program"_s))
651 pref->setAutoRunOnTorrentAddedProgram(it.value().toString());
652 // Run an external program on torrent finished
653 if (hasKey(u"autorun_enabled"_s))
654 pref->setAutoRunOnTorrentFinishedEnabled(it.value().toBool());
655 if (hasKey(u"autorun_program"_s))
656 pref->setAutoRunOnTorrentFinishedProgram(it.value().toString());
658 // Connection
659 // Listening Port
660 if (hasKey(u"random_port"_s) && it.value().toBool()) // deprecated
662 session->setPort(0);
664 else if (hasKey(u"listen_port"_s))
666 session->setPort(it.value().toInt());
668 // SSL Torrents
669 if (hasKey(u"ssl_enabled"_s))
670 session->setSSLEnabled(it.value().toBool());
671 if (hasKey(u"ssl_listen_port"_s))
672 session->setSSLPort(it.value().toInt());
673 if (hasKey(u"upnp"_s))
674 Net::PortForwarder::instance()->setEnabled(it.value().toBool());
675 // Connections Limits
676 if (hasKey(u"max_connec"_s))
677 session->setMaxConnections(it.value().toInt());
678 if (hasKey(u"max_connec_per_torrent"_s))
679 session->setMaxConnectionsPerTorrent(it.value().toInt());
680 if (hasKey(u"max_uploads"_s))
681 session->setMaxUploads(it.value().toInt());
682 if (hasKey(u"max_uploads_per_torrent"_s))
683 session->setMaxUploadsPerTorrent(it.value().toInt());
685 // I2P
686 if (hasKey(u"i2p_enabled"_s))
687 session->setI2PEnabled(it.value().toBool());
688 if (hasKey(u"i2p_address"_s))
689 session->setI2PAddress(it.value().toString());
690 if (hasKey(u"i2p_port"_s))
691 session->setI2PPort(it.value().toInt());
692 if (hasKey(u"i2p_mixed_mode"_s))
693 session->setI2PMixedMode(it.value().toBool());
694 if (hasKey(u"i2p_inbound_quantity"_s))
695 session->setI2PInboundQuantity(it.value().toInt());
696 if (hasKey(u"i2p_outbound_quantity"_s))
697 session->setI2POutboundQuantity(it.value().toInt());
698 if (hasKey(u"i2p_inbound_length"_s))
699 session->setI2PInboundLength(it.value().toInt());
700 if (hasKey(u"i2p_outbound_length"_s))
701 session->setI2POutboundLength(it.value().toInt());
703 // Proxy Server
704 auto *proxyManager = Net::ProxyConfigurationManager::instance();
705 Net::ProxyConfiguration proxyConf = proxyManager->proxyConfiguration();
706 if (hasKey(u"proxy_type"_s))
707 proxyConf.type = Utils::String::toEnum(it.value().toString(), Net::ProxyType::None);
708 if (hasKey(u"proxy_ip"_s))
709 proxyConf.ip = it.value().toString();
710 if (hasKey(u"proxy_port"_s))
711 proxyConf.port = it.value().toUInt();
712 if (hasKey(u"proxy_auth_enabled"_s))
713 proxyConf.authEnabled = it.value().toBool();
714 if (hasKey(u"proxy_username"_s))
715 proxyConf.username = it.value().toString();
716 if (hasKey(u"proxy_password"_s))
717 proxyConf.password = it.value().toString();
718 if (hasKey(u"proxy_hostname_lookup"_s))
719 proxyConf.hostnameLookupEnabled = it.value().toBool();
720 proxyManager->setProxyConfiguration(proxyConf);
722 if (hasKey(u"proxy_bittorrent"_s))
723 pref->setUseProxyForBT(it.value().toBool());
724 if (hasKey(u"proxy_peer_connections"_s))
725 session->setProxyPeerConnectionsEnabled(it.value().toBool());
726 if (hasKey(u"proxy_rss"_s))
727 pref->setUseProxyForRSS(it.value().toBool());
728 if (hasKey(u"proxy_misc"_s))
729 pref->setUseProxyForGeneralPurposes(it.value().toBool());
731 // IP Filtering
732 if (hasKey(u"ip_filter_enabled"_s))
733 session->setIPFilteringEnabled(it.value().toBool());
734 if (hasKey(u"ip_filter_path"_s))
735 session->setIPFilterFile(Path(it.value().toString()));
736 if (hasKey(u"ip_filter_trackers"_s))
737 session->setTrackerFilteringEnabled(it.value().toBool());
738 if (hasKey(u"banned_IPs"_s))
739 session->setBannedIPs(it.value().toString().split(u'\n', Qt::SkipEmptyParts));
741 // Speed
742 // Global Rate Limits
743 if (hasKey(u"dl_limit"_s))
744 session->setGlobalDownloadSpeedLimit(it.value().toInt());
745 if (hasKey(u"up_limit"_s))
746 session->setGlobalUploadSpeedLimit(it.value().toInt());
747 if (hasKey(u"alt_dl_limit"_s))
748 session->setAltGlobalDownloadSpeedLimit(it.value().toInt());
749 if (hasKey(u"alt_up_limit"_s))
750 session->setAltGlobalUploadSpeedLimit(it.value().toInt());
751 if (hasKey(u"bittorrent_protocol"_s))
752 session->setBTProtocol(static_cast<BitTorrent::BTProtocol>(it.value().toInt()));
753 if (hasKey(u"limit_utp_rate"_s))
754 session->setUTPRateLimited(it.value().toBool());
755 if (hasKey(u"limit_tcp_overhead"_s))
756 session->setIncludeOverheadInLimits(it.value().toBool());
757 if (hasKey(u"limit_lan_peers"_s))
758 session->setIgnoreLimitsOnLAN(!it.value().toBool());
759 // Scheduling
760 if (hasKey(u"scheduler_enabled"_s))
761 session->setBandwidthSchedulerEnabled(it.value().toBool());
762 if (m.contains(u"schedule_from_hour"_s) && m.contains(u"schedule_from_min"_s))
763 pref->setSchedulerStartTime(QTime(m[u"schedule_from_hour"_s].toInt(), m[u"schedule_from_min"_s].toInt()));
764 if (m.contains(u"schedule_to_hour"_s) && m.contains(u"schedule_to_min"_s))
765 pref->setSchedulerEndTime(QTime(m[u"schedule_to_hour"_s].toInt(), m[u"schedule_to_min"_s].toInt()));
766 if (hasKey(u"scheduler_days"_s))
767 pref->setSchedulerDays(static_cast<Scheduler::Days>(it.value().toInt()));
769 // Bittorrent
770 // Privacy
771 if (hasKey(u"dht"_s))
772 session->setDHTEnabled(it.value().toBool());
773 if (hasKey(u"pex"_s))
774 session->setPeXEnabled(it.value().toBool());
775 if (hasKey(u"lsd"_s))
776 session->setLSDEnabled(it.value().toBool());
777 if (hasKey(u"encryption"_s))
778 session->setEncryption(it.value().toInt());
779 if (hasKey(u"anonymous_mode"_s))
780 session->setAnonymousModeEnabled(it.value().toBool());
781 // Max active checking torrents
782 if (hasKey(u"max_active_checking_torrents"_s))
783 session->setMaxActiveCheckingTorrents(it.value().toInt());
784 // Torrent Queueing
785 if (hasKey(u"queueing_enabled"_s))
786 session->setQueueingSystemEnabled(it.value().toBool());
787 if (hasKey(u"max_active_downloads"_s))
788 session->setMaxActiveDownloads(it.value().toInt());
789 if (hasKey(u"max_active_torrents"_s))
790 session->setMaxActiveTorrents(it.value().toInt());
791 if (hasKey(u"max_active_uploads"_s))
792 session->setMaxActiveUploads(it.value().toInt());
793 if (hasKey(u"dont_count_slow_torrents"_s))
794 session->setIgnoreSlowTorrentsForQueueing(it.value().toBool());
795 if (hasKey(u"slow_torrent_dl_rate_threshold"_s))
796 session->setDownloadRateForSlowTorrents(it.value().toInt());
797 if (hasKey(u"slow_torrent_ul_rate_threshold"_s))
798 session->setUploadRateForSlowTorrents(it.value().toInt());
799 if (hasKey(u"slow_torrent_inactive_timer"_s))
800 session->setSlowTorrentsInactivityTimer(it.value().toInt());
801 // Share Ratio Limiting
802 if (hasKey(u"max_ratio_enabled"_s))
804 if (it.value().toBool())
805 session->setGlobalMaxRatio(m[u"max_ratio"_s].toReal());
806 else
807 session->setGlobalMaxRatio(-1);
809 if (hasKey(u"max_seeding_time_enabled"_s))
811 if (it.value().toBool())
812 session->setGlobalMaxSeedingMinutes(m[u"max_seeding_time"_s].toInt());
813 else
814 session->setGlobalMaxSeedingMinutes(-1);
816 if (hasKey(u"max_inactive_seeding_time_enabled"_s))
818 session->setGlobalMaxInactiveSeedingMinutes(it.value().toBool()
819 ? m[u"max_inactive_seeding_time"_s].toInt() : -1);
821 if (hasKey(u"max_ratio_act"_s))
823 switch (it.value().toInt())
825 default:
826 case 0:
827 session->setShareLimitAction(BitTorrent::ShareLimitAction::Stop);
828 break;
829 case 1:
830 session->setShareLimitAction(BitTorrent::ShareLimitAction::Remove);
831 break;
832 case 2:
833 session->setShareLimitAction(BitTorrent::ShareLimitAction::EnableSuperSeeding);
834 break;
835 case 3:
836 session->setShareLimitAction(BitTorrent::ShareLimitAction::RemoveWithContent);
837 break;
840 // Add trackers
841 if (hasKey(u"add_trackers_enabled"_s))
842 session->setAddTrackersEnabled(it.value().toBool());
843 if (hasKey(u"add_trackers"_s))
844 session->setAdditionalTrackers(it.value().toString());
846 // WebUI
847 // HTTP Server
848 if (hasKey(u"web_ui_domain_list"_s))
849 pref->setServerDomains(it.value().toString());
850 if (hasKey(u"web_ui_address"_s))
851 pref->setWebUIAddress(it.value().toString());
852 if (hasKey(u"web_ui_port"_s))
853 pref->setWebUIPort(it.value().value<quint16>());
854 if (hasKey(u"web_ui_upnp"_s))
855 pref->setUPnPForWebUIPort(it.value().toBool());
856 if (hasKey(u"use_https"_s))
857 pref->setWebUIHttpsEnabled(it.value().toBool());
858 if (hasKey(u"web_ui_https_cert_path"_s))
859 pref->setWebUIHttpsCertificatePath(Path(it.value().toString()));
860 if (hasKey(u"web_ui_https_key_path"_s))
861 pref->setWebUIHttpsKeyPath(Path(it.value().toString()));
862 // Authentication
863 if (hasKey(u"web_ui_username"_s))
864 pref->setWebUIUsername(it.value().toString());
865 if (hasKey(u"web_ui_password"_s))
866 pref->setWebUIPassword(Utils::Password::PBKDF2::generate(it.value().toByteArray()));
867 if (hasKey(u"bypass_local_auth"_s))
868 pref->setWebUILocalAuthEnabled(!it.value().toBool());
869 if (hasKey(u"bypass_auth_subnet_whitelist_enabled"_s))
870 pref->setWebUIAuthSubnetWhitelistEnabled(it.value().toBool());
871 if (hasKey(u"bypass_auth_subnet_whitelist"_s))
873 // recognize new lines and commas as delimiters
874 pref->setWebUIAuthSubnetWhitelist(it.value().toString().split(QRegularExpression(u"\n|,"_s), Qt::SkipEmptyParts));
876 if (hasKey(u"web_ui_max_auth_fail_count"_s))
877 pref->setWebUIMaxAuthFailCount(it.value().toInt());
878 if (hasKey(u"web_ui_ban_duration"_s))
879 pref->setWebUIBanDuration(std::chrono::seconds {it.value().toInt()});
880 if (hasKey(u"web_ui_session_timeout"_s))
881 pref->setWebUISessionTimeout(it.value().toInt());
882 // Use alternative WebUI
883 if (hasKey(u"alternative_webui_enabled"_s))
884 pref->setAltWebUIEnabled(it.value().toBool());
885 if (hasKey(u"alternative_webui_path"_s))
886 pref->setWebUIRootFolder(Path(it.value().toString()));
887 // Security
888 if (hasKey(u"web_ui_clickjacking_protection_enabled"_s))
889 pref->setWebUIClickjackingProtectionEnabled(it.value().toBool());
890 if (hasKey(u"web_ui_csrf_protection_enabled"_s))
891 pref->setWebUICSRFProtectionEnabled(it.value().toBool());
892 if (hasKey(u"web_ui_secure_cookie_enabled"_s))
893 pref->setWebUISecureCookieEnabled(it.value().toBool());
894 if (hasKey(u"web_ui_host_header_validation_enabled"_s))
895 pref->setWebUIHostHeaderValidationEnabled(it.value().toBool());
896 // Custom HTTP headers
897 if (hasKey(u"web_ui_use_custom_http_headers_enabled"_s))
898 pref->setWebUICustomHTTPHeadersEnabled(it.value().toBool());
899 if (hasKey(u"web_ui_custom_http_headers"_s))
900 pref->setWebUICustomHTTPHeaders(it.value().toString());
901 // Reverse proxy
902 if (hasKey(u"web_ui_reverse_proxy_enabled"_s))
903 pref->setWebUIReverseProxySupportEnabled(it.value().toBool());
904 if (hasKey(u"web_ui_reverse_proxies_list"_s))
905 pref->setWebUITrustedReverseProxiesList(it.value().toString());
906 // Update my dynamic domain name
907 if (hasKey(u"dyndns_enabled"_s))
908 pref->setDynDNSEnabled(it.value().toBool());
909 if (hasKey(u"dyndns_service"_s))
910 pref->setDynDNSService(static_cast<DNS::Service>(it.value().toInt()));
911 if (hasKey(u"dyndns_username"_s))
912 pref->setDynDNSUsername(it.value().toString());
913 if (hasKey(u"dyndns_password"_s))
914 pref->setDynDNSPassword(it.value().toString());
915 if (hasKey(u"dyndns_domain"_s))
916 pref->setDynDomainName(it.value().toString());
918 if (hasKey(u"rss_refresh_interval"_s))
919 RSS::Session::instance()->setRefreshInterval(it.value().toInt());
920 if (hasKey(u"rss_fetch_delay"_s))
921 RSS::Session::instance()->setFetchDelay(std::chrono::seconds(it.value().toLongLong()));
922 if (hasKey(u"rss_max_articles_per_feed"_s))
923 RSS::Session::instance()->setMaxArticlesPerFeed(it.value().toInt());
924 if (hasKey(u"rss_processing_enabled"_s))
925 RSS::Session::instance()->setProcessingEnabled(it.value().toBool());
926 if (hasKey(u"rss_auto_downloading_enabled"_s))
927 RSS::AutoDownloader::instance()->setProcessingEnabled(it.value().toBool());
928 if (hasKey(u"rss_download_repack_proper_episodes"_s))
929 RSS::AutoDownloader::instance()->setDownloadRepacks(it.value().toBool());
930 if (hasKey(u"rss_smart_episode_filters"_s))
931 RSS::AutoDownloader::instance()->setSmartEpisodeFilters(it.value().toString().split(u'\n'));
933 // Advanced settings
934 // qBittorrent preferences
935 // Resume data storage type
936 if (hasKey(u"resume_data_storage_type"_s))
937 session->setResumeDataStorageType(Utils::String::toEnum(it.value().toString(), BitTorrent::ResumeDataStorageType::Legacy));
938 // Torrent content removing mode
939 if (hasKey(u"torrent_content_remove_option"_s))
940 session->setTorrentContentRemoveOption(Utils::String::toEnum(it.value().toString(), BitTorrent::TorrentContentRemoveOption::MoveToTrash));
941 // Physical memory (RAM) usage limit
942 if (hasKey(u"memory_working_set_limit"_s))
943 app()->setMemoryWorkingSetLimit(it.value().toInt());
944 // Current network interface
945 if (hasKey(u"current_network_interface"_s))
947 const QString ifaceValue {it.value().toString()};
949 const QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
950 const auto ifacesIter = std::find_if(ifaces.cbegin(), ifaces.cend(), [&ifaceValue](const QNetworkInterface &iface)
952 return (!iface.addressEntries().isEmpty()) && (iface.name() == ifaceValue);
954 const QString ifaceName = (ifacesIter != ifaces.cend()) ? ifacesIter->humanReadableName() : QString {};
956 session->setNetworkInterface(ifaceValue);
957 if (!ifaceName.isEmpty() || ifaceValue.isEmpty())
958 session->setNetworkInterfaceName(ifaceName);
960 // Current network interface address
961 if (hasKey(u"current_interface_address"_s))
963 const QHostAddress ifaceAddress {it.value().toString().trimmed()};
964 session->setNetworkInterfaceAddress(ifaceAddress.isNull() ? QString {} : ifaceAddress.toString());
966 // Save resume data interval
967 if (hasKey(u"save_resume_data_interval"_s))
968 session->setSaveResumeDataInterval(it.value().toInt());
969 // .torrent file size limit
970 if (hasKey(u"torrent_file_size_limit"_s))
971 pref->setTorrentFileSizeLimit(it.value().toLongLong());
972 // Recheck completed torrents
973 if (hasKey(u"recheck_completed_torrents"_s))
974 pref->recheckTorrentsOnCompletion(it.value().toBool());
975 // Customize application instance name
976 if (hasKey(u"app_instance_name"_s))
977 app()->setInstanceName(it.value().toString());
978 // Refresh interval
979 if (hasKey(u"refresh_interval"_s))
980 session->setRefreshInterval(it.value().toInt());
981 // Resolve peer countries
982 if (hasKey(u"resolve_peer_countries"_s))
983 pref->resolvePeerCountries(it.value().toBool());
984 // Reannounce to all trackers when ip/port changed
985 if (hasKey(u"reannounce_when_address_changed"_s))
986 session->setReannounceWhenAddressChangedEnabled(it.value().toBool());
987 // Embedded tracker
988 if (hasKey(u"embedded_tracker_port"_s))
989 pref->setTrackerPort(it.value().toInt());
990 if (hasKey(u"embedded_tracker_port_forwarding"_s))
991 pref->setTrackerPortForwardingEnabled(it.value().toBool());
992 if (hasKey(u"enable_embedded_tracker"_s))
993 session->setTrackerEnabled(it.value().toBool());
994 // Mark-of-the-Web
995 if (hasKey(u"mark_of_the_web"_s))
996 pref->setMarkOfTheWebEnabled(it.value().toBool());
997 // Ignore SLL errors
998 if (hasKey(u"ignore_ssl_errors"_s))
999 pref->setIgnoreSSLErrors(it.value().toBool());
1000 // Python executable path
1001 if (hasKey(u"python_executable_path"_s))
1002 pref->setPythonExecutablePath(Path(it.value().toString()));
1004 // libtorrent preferences
1005 // Bdecode depth limit
1006 if (hasKey(u"bdecode_depth_limit"_s))
1007 pref->setBdecodeDepthLimit(it.value().toInt());
1008 // Bdecode token limit
1009 if (hasKey(u"bdecode_token_limit"_s))
1010 pref->setBdecodeTokenLimit(it.value().toInt());
1011 // Async IO threads
1012 if (hasKey(u"async_io_threads"_s))
1013 session->setAsyncIOThreads(it.value().toInt());
1014 // Hashing threads
1015 if (hasKey(u"hashing_threads"_s))
1016 session->setHashingThreads(it.value().toInt());
1017 // File pool size
1018 if (hasKey(u"file_pool_size"_s))
1019 session->setFilePoolSize(it.value().toInt());
1020 // Checking Memory Usage
1021 if (hasKey(u"checking_memory_use"_s))
1022 session->setCheckingMemUsage(it.value().toInt());
1023 // Disk write cache
1024 if (hasKey(u"disk_cache"_s))
1025 session->setDiskCacheSize(it.value().toInt());
1026 if (hasKey(u"disk_cache_ttl"_s))
1027 session->setDiskCacheTTL(it.value().toInt());
1028 // Disk queue size
1029 if (hasKey(u"disk_queue_size"_s))
1030 session->setDiskQueueSize(it.value().toLongLong());
1031 // Disk IO Type
1032 if (hasKey(u"disk_io_type"_s))
1033 session->setDiskIOType(static_cast<BitTorrent::DiskIOType>(it.value().toInt()));
1034 // Disk IO read mode
1035 if (hasKey(u"disk_io_read_mode"_s))
1036 session->setDiskIOReadMode(static_cast<BitTorrent::DiskIOReadMode>(it.value().toInt()));
1037 // Disk IO write mode
1038 if (hasKey(u"disk_io_write_mode"_s))
1039 session->setDiskIOWriteMode(static_cast<BitTorrent::DiskIOWriteMode>(it.value().toInt()));
1040 // Coalesce reads & writes
1041 if (hasKey(u"enable_coalesce_read_write"_s))
1042 session->setCoalesceReadWriteEnabled(it.value().toBool());
1043 // Piece extent affinity
1044 if (hasKey(u"enable_piece_extent_affinity"_s))
1045 session->setPieceExtentAffinity(it.value().toBool());
1046 // Suggest mode
1047 if (hasKey(u"enable_upload_suggestions"_s))
1048 session->setSuggestMode(it.value().toBool());
1049 // Send buffer watermark
1050 if (hasKey(u"send_buffer_watermark"_s))
1051 session->setSendBufferWatermark(it.value().toInt());
1052 if (hasKey(u"send_buffer_low_watermark"_s))
1053 session->setSendBufferLowWatermark(it.value().toInt());
1054 if (hasKey(u"send_buffer_watermark_factor"_s))
1055 session->setSendBufferWatermarkFactor(it.value().toInt());
1056 // Outgoing connections per second
1057 if (hasKey(u"connection_speed"_s))
1058 session->setConnectionSpeed(it.value().toInt());
1059 // Socket send buffer size
1060 if (hasKey(u"socket_send_buffer_size"_s))
1061 session->setSocketSendBufferSize(it.value().toInt());
1062 // Socket receive buffer size
1063 if (hasKey(u"socket_receive_buffer_size"_s))
1064 session->setSocketReceiveBufferSize(it.value().toInt());
1065 // Socket listen backlog size
1066 if (hasKey(u"socket_backlog_size"_s))
1067 session->setSocketBacklogSize(it.value().toInt());
1068 // Outgoing ports
1069 if (hasKey(u"outgoing_ports_min"_s))
1070 session->setOutgoingPortsMin(it.value().toInt());
1071 if (hasKey(u"outgoing_ports_max"_s))
1072 session->setOutgoingPortsMax(it.value().toInt());
1073 // UPnP lease duration
1074 if (hasKey(u"upnp_lease_duration"_s))
1075 session->setUPnPLeaseDuration(it.value().toInt());
1076 // Type of service
1077 if (hasKey(u"peer_tos"_s))
1078 session->setPeerToS(it.value().toInt());
1079 // uTP-TCP mixed mode
1080 if (hasKey(u"utp_tcp_mixed_mode"_s))
1081 session->setUtpMixedMode(static_cast<BitTorrent::MixedModeAlgorithm>(it.value().toInt()));
1082 // Support internationalized domain name (IDN)
1083 if (hasKey(u"idn_support_enabled"_s))
1084 session->setIDNSupportEnabled(it.value().toBool());
1085 // Multiple connections per IP
1086 if (hasKey(u"enable_multi_connections_from_same_ip"_s))
1087 session->setMultiConnectionsPerIpEnabled(it.value().toBool());
1088 // Validate HTTPS tracker certificate
1089 if (hasKey(u"validate_https_tracker_certificate"_s))
1090 session->setValidateHTTPSTrackerCertificate(it.value().toBool());
1091 // SSRF mitigation
1092 if (hasKey(u"ssrf_mitigation"_s))
1093 session->setSSRFMitigationEnabled(it.value().toBool());
1094 // Disallow connection to peers on privileged ports
1095 if (hasKey(u"block_peers_on_privileged_ports"_s))
1096 session->setBlockPeersOnPrivilegedPorts(it.value().toBool());
1097 // Choking algorithm
1098 if (hasKey(u"upload_slots_behavior"_s))
1099 session->setChokingAlgorithm(static_cast<BitTorrent::ChokingAlgorithm>(it.value().toInt()));
1100 // Seed choking algorithm
1101 if (hasKey(u"upload_choking_algorithm"_s))
1102 session->setSeedChokingAlgorithm(static_cast<BitTorrent::SeedChokingAlgorithm>(it.value().toInt()));
1103 // Announce
1104 if (hasKey(u"announce_to_all_trackers"_s))
1105 session->setAnnounceToAllTrackers(it.value().toBool());
1106 if (hasKey(u"announce_to_all_tiers"_s))
1107 session->setAnnounceToAllTiers(it.value().toBool());
1108 if (hasKey(u"announce_ip"_s))
1110 const QHostAddress announceAddr {it.value().toString().trimmed()};
1111 session->setAnnounceIP(announceAddr.isNull() ? QString {} : announceAddr.toString());
1113 if (hasKey(u"max_concurrent_http_announces"_s))
1114 session->setMaxConcurrentHTTPAnnounces(it.value().toInt());
1115 if (hasKey(u"stop_tracker_timeout"_s))
1116 session->setStopTrackerTimeout(it.value().toInt());
1117 // Peer Turnover
1118 if (hasKey(u"peer_turnover"_s))
1119 session->setPeerTurnover(it.value().toInt());
1120 if (hasKey(u"peer_turnover_cutoff"_s))
1121 session->setPeerTurnoverCutoff(it.value().toInt());
1122 if (hasKey(u"peer_turnover_interval"_s))
1123 session->setPeerTurnoverInterval(it.value().toInt());
1124 // Maximum outstanding requests to a single peer
1125 if (hasKey(u"request_queue_size"_s))
1126 session->setRequestQueueSize(it.value().toInt());
1127 // DHT bootstrap nodes
1128 if (hasKey(u"dht_bootstrap_nodes"_s))
1129 session->setDHTBootstrapNodes(it.value().toString());
1131 // Save preferences
1132 pref->apply();
1135 void AppController::defaultSavePathAction()
1137 setResult(BitTorrent::Session::instance()->savePath().toString());
1140 void AppController::sendTestEmailAction()
1142 app()->sendTestEmail();
1146 void AppController::getDirectoryContentAction()
1148 requireParams({u"dirPath"_s});
1150 const QString dirPath = params().value(u"dirPath"_s);
1151 if (dirPath.isEmpty() || dirPath.startsWith(u':'))
1152 throw APIError(APIErrorType::BadParams, tr("Invalid directory path"));
1154 const QDir dir {dirPath};
1155 if (!dir.isAbsolute())
1156 throw APIError(APIErrorType::BadParams, tr("Invalid directory path"));
1157 if (!dir.exists())
1158 throw APIError(APIErrorType::NotFound, tr("Directory does not exist"));
1160 const QString visibility = params().value(u"mode"_s, u"all"_s);
1162 const auto parseDirectoryContentMode = [](const QString &visibility) -> QDir::Filters
1164 if (visibility == u"dirs")
1165 return QDir::Dirs;
1166 if (visibility == u"files")
1167 return QDir::Files;
1168 if (visibility == u"all")
1169 return (QDir::Dirs | QDir::Files);
1170 throw APIError(APIErrorType::BadParams, tr("Invalid mode, allowed values: %1").arg(u"all, dirs, files"_s));
1173 QJsonArray ret;
1174 QDirIterator it {dirPath, (QDir::NoDotAndDotDot | parseDirectoryContentMode(visibility))};
1175 while (it.hasNext())
1176 ret.append(it.next());
1177 setResult(ret);
1180 void AppController::networkInterfaceListAction()
1182 QJsonArray ifaceList;
1183 for (const QNetworkInterface &iface : asConst(QNetworkInterface::allInterfaces()))
1185 if (!iface.addressEntries().isEmpty())
1187 ifaceList.append(QJsonObject
1189 {u"name"_s, iface.humanReadableName()},
1190 {u"value"_s, iface.name()}
1195 setResult(ifaceList);
1198 void AppController::networkInterfaceAddressListAction()
1200 requireParams({u"iface"_s});
1202 const QString ifaceName = params().value(u"iface"_s);
1203 QJsonArray addressList;
1205 const auto appendAddress = [&addressList](const QHostAddress &addr)
1207 if (addr.protocol() == QAbstractSocket::IPv6Protocol)
1208 addressList.append(Utils::Net::canonicalIPv6Addr(addr).toString());
1209 else
1210 addressList.append(addr.toString());
1213 if (ifaceName.isEmpty())
1215 for (const QHostAddress &addr : asConst(QNetworkInterface::allAddresses()))
1216 appendAddress(addr);
1218 else
1220 const QNetworkInterface iface = QNetworkInterface::interfaceFromName(ifaceName);
1221 for (const QNetworkAddressEntry &entry : asConst(iface.addressEntries()))
1222 appendAddress(entry.ip());
1225 setResult(addressList);