WebUI: Add 'Confirm torrent recheck' option
[qBittorrent.git] / src / webui / api / appcontroller.cpp
blobfd6cd442c712458e4eab1ef0fcbb8a04b953b61d
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 // Transfer List
131 data[u"confirm_torrent_deletion"_s] = pref->confirmTorrentDeletion();
132 // Log file
133 data[u"file_log_enabled"_s] = app()->isFileLoggerEnabled();
134 data[u"file_log_path"_s] = app()->fileLoggerPath().toString();
135 data[u"file_log_backup_enabled"_s] = app()->isFileLoggerBackup();
136 data[u"file_log_max_size"_s] = app()->fileLoggerMaxSize() / 1024;
137 data[u"file_log_delete_old"_s] = app()->isFileLoggerDeleteOld();
138 data[u"file_log_age"_s] = app()->fileLoggerAge();
139 data[u"file_log_age_type"_s] = app()->fileLoggerAgeType();
140 // Delete torrent contents files on torrent removal
141 data[u"delete_torrent_content_files"_s] = pref->removeTorrentContent();
143 // Downloads
144 // When adding a torrent
145 data[u"torrent_content_layout"_s] = Utils::String::fromEnum(session->torrentContentLayout());
146 data[u"add_to_top_of_queue"_s] = session->isAddTorrentToQueueTop();
147 data[u"add_stopped_enabled"_s] = session->isAddTorrentStopped();
148 data[u"torrent_stop_condition"_s] = Utils::String::fromEnum(session->torrentStopCondition());
149 data[u"merge_trackers"_s] = session->isMergeTrackersEnabled();
150 data[u"auto_delete_mode"_s] = static_cast<int>(TorrentFileGuard::autoDeleteMode());
151 data[u"preallocate_all"_s] = session->isPreallocationEnabled();
152 data[u"incomplete_files_ext"_s] = session->isAppendExtensionEnabled();
153 data[u"use_unwanted_folder"_s] = session->isUnwantedFolderEnabled();
154 // Saving Management
155 data[u"auto_tmm_enabled"_s] = !session->isAutoTMMDisabledByDefault();
156 data[u"torrent_changed_tmm_enabled"_s] = !session->isDisableAutoTMMWhenCategoryChanged();
157 data[u"save_path_changed_tmm_enabled"_s] = !session->isDisableAutoTMMWhenDefaultSavePathChanged();
158 data[u"category_changed_tmm_enabled"_s] = !session->isDisableAutoTMMWhenCategorySavePathChanged();
159 data[u"use_subcategories"] = session->isSubcategoriesEnabled();
160 data[u"save_path"_s] = session->savePath().toString();
161 data[u"temp_path_enabled"_s] = session->isDownloadPathEnabled();
162 data[u"temp_path"_s] = session->downloadPath().toString();
163 data[u"use_category_paths_in_manual_mode"_s] = session->useCategoryPathsInManualMode();
164 data[u"export_dir"_s] = session->torrentExportDirectory().toString();
165 data[u"export_dir_fin"_s] = session->finishedTorrentExportDirectory().toString();
167 // TODO: The following code is deprecated. Delete it once replaced by updated API method.
168 // === BEGIN DEPRECATED CODE === //
169 TorrentFilesWatcher *fsWatcher = TorrentFilesWatcher::instance();
170 const QHash<Path, TorrentFilesWatcher::WatchedFolderOptions> watchedFolders = fsWatcher->folders();
171 QJsonObject nativeDirs;
172 for (auto i = watchedFolders.cbegin(); i != watchedFolders.cend(); ++i)
174 const Path &watchedFolder = i.key();
175 const BitTorrent::AddTorrentParams params = i.value().addTorrentParams;
176 if (params.savePath.isEmpty())
177 nativeDirs.insert(watchedFolder.toString(), 1);
178 else if (params.savePath == watchedFolder)
179 nativeDirs.insert(watchedFolder.toString(), 0);
180 else
181 nativeDirs.insert(watchedFolder.toString(), params.savePath.toString());
183 data[u"scan_dirs"_s] = nativeDirs;
184 // === END DEPRECATED CODE === //
186 // Excluded file names
187 data[u"excluded_file_names_enabled"_s] = session->isExcludedFileNamesEnabled();
188 data[u"excluded_file_names"_s] = session->excludedFileNames().join(u'\n');
190 // Email notification upon download completion
191 data[u"mail_notification_enabled"_s] = pref->isMailNotificationEnabled();
192 data[u"mail_notification_sender"_s] = pref->getMailNotificationSender();
193 data[u"mail_notification_email"_s] = pref->getMailNotificationEmail();
194 data[u"mail_notification_smtp"_s] = pref->getMailNotificationSMTP();
195 data[u"mail_notification_ssl_enabled"_s] = pref->getMailNotificationSMTPSSL();
196 data[u"mail_notification_auth_enabled"_s] = pref->getMailNotificationSMTPAuth();
197 data[u"mail_notification_username"_s] = pref->getMailNotificationSMTPUsername();
198 data[u"mail_notification_password"_s] = pref->getMailNotificationSMTPPassword();
199 // Run an external program on torrent added
200 data[u"autorun_on_torrent_added_enabled"_s] = pref->isAutoRunOnTorrentAddedEnabled();
201 data[u"autorun_on_torrent_added_program"_s] = pref->getAutoRunOnTorrentAddedProgram();
202 // Run an external program on torrent finished
203 data[u"autorun_enabled"_s] = pref->isAutoRunOnTorrentFinishedEnabled();
204 data[u"autorun_program"_s] = pref->getAutoRunOnTorrentFinishedProgram();
206 // Connection
207 // Listening Port
208 data[u"listen_port"_s] = session->port();
209 data[u"ssl_enabled"_s] = session->isSSLEnabled();
210 data[u"ssl_listen_port"_s] = session->sslPort();
211 data[u"random_port"_s] = (session->port() == 0); // deprecated
212 data[u"upnp"_s] = Net::PortForwarder::instance()->isEnabled();
213 // Connections Limits
214 data[u"max_connec"_s] = session->maxConnections();
215 data[u"max_connec_per_torrent"_s] = session->maxConnectionsPerTorrent();
216 data[u"max_uploads"_s] = session->maxUploads();
217 data[u"max_uploads_per_torrent"_s] = session->maxUploadsPerTorrent();
219 // I2P
220 data[u"i2p_enabled"_s] = session->isI2PEnabled();
221 data[u"i2p_address"_s] = session->I2PAddress();
222 data[u"i2p_port"_s] = session->I2PPort();
223 data[u"i2p_mixed_mode"_s] = session->I2PMixedMode();
224 data[u"i2p_inbound_quantity"_s] = session->I2PInboundQuantity();
225 data[u"i2p_outbound_quantity"_s] = session->I2POutboundQuantity();
226 data[u"i2p_inbound_length"_s] = session->I2PInboundLength();
227 data[u"i2p_outbound_length"_s] = session->I2POutboundLength();
229 // Proxy Server
230 const auto *proxyManager = Net::ProxyConfigurationManager::instance();
231 Net::ProxyConfiguration proxyConf = proxyManager->proxyConfiguration();
232 data[u"proxy_type"_s] = Utils::String::fromEnum(proxyConf.type);
233 data[u"proxy_ip"_s] = proxyConf.ip;
234 data[u"proxy_port"_s] = proxyConf.port;
235 data[u"proxy_auth_enabled"_s] = proxyConf.authEnabled;
236 data[u"proxy_username"_s] = proxyConf.username;
237 data[u"proxy_password"_s] = proxyConf.password;
238 data[u"proxy_hostname_lookup"_s] = proxyConf.hostnameLookupEnabled;
240 data[u"proxy_bittorrent"_s] = pref->useProxyForBT();
241 data[u"proxy_peer_connections"_s] = session->isProxyPeerConnectionsEnabled();
242 data[u"proxy_rss"_s] = pref->useProxyForRSS();
243 data[u"proxy_misc"_s] = pref->useProxyForGeneralPurposes();
245 // IP Filtering
246 data[u"ip_filter_enabled"_s] = session->isIPFilteringEnabled();
247 data[u"ip_filter_path"_s] = session->IPFilterFile().toString();
248 data[u"ip_filter_trackers"_s] = session->isTrackerFilteringEnabled();
249 data[u"banned_IPs"_s] = session->bannedIPs().join(u'\n');
251 // Speed
252 // Global Rate Limits
253 data[u"dl_limit"_s] = session->globalDownloadSpeedLimit();
254 data[u"up_limit"_s] = session->globalUploadSpeedLimit();
255 data[u"alt_dl_limit"_s] = session->altGlobalDownloadSpeedLimit();
256 data[u"alt_up_limit"_s] = session->altGlobalUploadSpeedLimit();
257 data[u"bittorrent_protocol"_s] = static_cast<int>(session->btProtocol());
258 data[u"limit_utp_rate"_s] = session->isUTPRateLimited();
259 data[u"limit_tcp_overhead"_s] = session->includeOverheadInLimits();
260 data[u"limit_lan_peers"_s] = !session->ignoreLimitsOnLAN();
261 // Scheduling
262 data[u"scheduler_enabled"_s] = session->isBandwidthSchedulerEnabled();
263 const QTime start_time = pref->getSchedulerStartTime();
264 data[u"schedule_from_hour"_s] = start_time.hour();
265 data[u"schedule_from_min"_s] = start_time.minute();
266 const QTime end_time = pref->getSchedulerEndTime();
267 data[u"schedule_to_hour"_s] = end_time.hour();
268 data[u"schedule_to_min"_s] = end_time.minute();
269 data[u"scheduler_days"_s] = static_cast<int>(pref->getSchedulerDays());
271 // Bittorrent
272 // Privacy
273 data[u"dht"_s] = session->isDHTEnabled();
274 data[u"pex"_s] = session->isPeXEnabled();
275 data[u"lsd"_s] = session->isLSDEnabled();
276 data[u"encryption"_s] = session->encryption();
277 data[u"anonymous_mode"_s] = session->isAnonymousModeEnabled();
278 // Max active checking torrents
279 data[u"max_active_checking_torrents"_s] = session->maxActiveCheckingTorrents();
280 // Torrent Queueing
281 data[u"queueing_enabled"_s] = session->isQueueingSystemEnabled();
282 data[u"max_active_downloads"_s] = session->maxActiveDownloads();
283 data[u"max_active_torrents"_s] = session->maxActiveTorrents();
284 data[u"max_active_uploads"_s] = session->maxActiveUploads();
285 data[u"dont_count_slow_torrents"_s] = session->ignoreSlowTorrentsForQueueing();
286 data[u"slow_torrent_dl_rate_threshold"_s] = session->downloadRateForSlowTorrents();
287 data[u"slow_torrent_ul_rate_threshold"_s] = session->uploadRateForSlowTorrents();
288 data[u"slow_torrent_inactive_timer"_s] = session->slowTorrentsInactivityTimer();
289 // Share Ratio Limiting
290 data[u"max_ratio_enabled"_s] = (session->globalMaxRatio() >= 0.);
291 data[u"max_ratio"_s] = session->globalMaxRatio();
292 data[u"max_seeding_time_enabled"_s] = (session->globalMaxSeedingMinutes() >= 0.);
293 data[u"max_seeding_time"_s] = session->globalMaxSeedingMinutes();
294 data[u"max_inactive_seeding_time_enabled"_s] = (session->globalMaxInactiveSeedingMinutes() >= 0.);
295 data[u"max_inactive_seeding_time"_s] = session->globalMaxInactiveSeedingMinutes();
296 data[u"max_ratio_act"_s] = static_cast<int>(session->shareLimitAction());
297 // Add trackers
298 data[u"add_trackers_enabled"_s] = session->isAddTrackersEnabled();
299 data[u"add_trackers"_s] = session->additionalTrackers();
301 // WebUI
302 // HTTP Server
303 data[u"web_ui_domain_list"_s] = pref->getServerDomains();
304 data[u"web_ui_address"_s] = pref->getWebUIAddress();
305 data[u"web_ui_port"_s] = pref->getWebUIPort();
306 data[u"web_ui_upnp"_s] = pref->useUPnPForWebUIPort();
307 data[u"use_https"_s] = pref->isWebUIHttpsEnabled();
308 data[u"web_ui_https_cert_path"_s] = pref->getWebUIHttpsCertificatePath().toString();
309 data[u"web_ui_https_key_path"_s] = pref->getWebUIHttpsKeyPath().toString();
310 // Authentication
311 data[u"web_ui_username"_s] = pref->getWebUIUsername();
312 data[u"bypass_local_auth"_s] = !pref->isWebUILocalAuthEnabled();
313 data[u"bypass_auth_subnet_whitelist_enabled"_s] = pref->isWebUIAuthSubnetWhitelistEnabled();
314 QStringList authSubnetWhitelistStringList;
315 for (const Utils::Net::Subnet &subnet : asConst(pref->getWebUIAuthSubnetWhitelist()))
316 authSubnetWhitelistStringList << Utils::Net::subnetToString(subnet);
317 data[u"bypass_auth_subnet_whitelist"_s] = authSubnetWhitelistStringList.join(u'\n');
318 data[u"web_ui_max_auth_fail_count"_s] = pref->getWebUIMaxAuthFailCount();
319 data[u"web_ui_ban_duration"_s] = static_cast<int>(pref->getWebUIBanDuration().count());
320 data[u"web_ui_session_timeout"_s] = pref->getWebUISessionTimeout();
321 // Use alternative WebUI
322 data[u"alternative_webui_enabled"_s] = pref->isAltWebUIEnabled();
323 data[u"alternative_webui_path"_s] = pref->getWebUIRootFolder().toString();
324 // Security
325 data[u"web_ui_clickjacking_protection_enabled"_s] = pref->isWebUIClickjackingProtectionEnabled();
326 data[u"web_ui_csrf_protection_enabled"_s] = pref->isWebUICSRFProtectionEnabled();
327 data[u"web_ui_secure_cookie_enabled"_s] = pref->isWebUISecureCookieEnabled();
328 data[u"web_ui_host_header_validation_enabled"_s] = pref->isWebUIHostHeaderValidationEnabled();
329 // Custom HTTP headers
330 data[u"web_ui_use_custom_http_headers_enabled"_s] = pref->isWebUICustomHTTPHeadersEnabled();
331 data[u"web_ui_custom_http_headers"_s] = pref->getWebUICustomHTTPHeaders();
332 // Reverse proxy
333 data[u"web_ui_reverse_proxy_enabled"_s] = pref->isWebUIReverseProxySupportEnabled();
334 data[u"web_ui_reverse_proxies_list"_s] = pref->getWebUITrustedReverseProxiesList();
335 // Update my dynamic domain name
336 data[u"dyndns_enabled"_s] = pref->isDynDNSEnabled();
337 data[u"dyndns_service"_s] = static_cast<int>(pref->getDynDNSService());
338 data[u"dyndns_username"_s] = pref->getDynDNSUsername();
339 data[u"dyndns_password"_s] = pref->getDynDNSPassword();
340 data[u"dyndns_domain"_s] = pref->getDynDomainName();
342 // RSS settings
343 data[u"rss_refresh_interval"_s] = RSS::Session::instance()->refreshInterval();
344 data[u"rss_fetch_delay"_s] = static_cast<qlonglong>(RSS::Session::instance()->fetchDelay().count());
345 data[u"rss_max_articles_per_feed"_s] = RSS::Session::instance()->maxArticlesPerFeed();
346 data[u"rss_processing_enabled"_s] = RSS::Session::instance()->isProcessingEnabled();
347 data[u"rss_auto_downloading_enabled"_s] = RSS::AutoDownloader::instance()->isProcessingEnabled();
348 data[u"rss_download_repack_proper_episodes"_s] = RSS::AutoDownloader::instance()->downloadRepacks();
349 data[u"rss_smart_episode_filters"_s] = RSS::AutoDownloader::instance()->smartEpisodeFilters().join(u'\n');
351 // Advanced settings
352 // qBitorrent preferences
353 // Resume data storage type
354 data[u"resume_data_storage_type"_s] = Utils::String::fromEnum(session->resumeDataStorageType());
355 // Torrent content removing mode
356 data[u"torrent_content_remove_option"_s] = Utils::String::fromEnum(session->torrentContentRemoveOption());
357 // Physical memory (RAM) usage limit
358 data[u"memory_working_set_limit"_s] = app()->memoryWorkingSetLimit();
359 // Current network interface
360 data[u"current_network_interface"_s] = session->networkInterface();
361 // Current network interface name
362 data[u"current_interface_name"_s] = session->networkInterfaceName();
363 // Current network interface address
364 data[u"current_interface_address"_s] = session->networkInterfaceAddress();
365 // Save resume data interval
366 data[u"save_resume_data_interval"_s] = session->saveResumeDataInterval();
367 // Save statistics interval
368 data[u"save_statistics_interval"_s] = static_cast<int>(session->saveStatisticsInterval().count());
369 // .torrent file size limit
370 data[u"torrent_file_size_limit"_s] = pref->getTorrentFileSizeLimit();
371 // Confirm torrent recheck
372 data[u"confirm_torrent_recheck"_s] = pref->confirmTorrentRecheck();
373 // Recheck completed torrents
374 data[u"recheck_completed_torrents"_s] = pref->recheckTorrentsOnCompletion();
375 // Customize application instance name
376 data[u"app_instance_name"_s] = app()->instanceName();
377 // Refresh interval
378 data[u"refresh_interval"_s] = session->refreshInterval();
379 // Resolve peer countries
380 data[u"resolve_peer_countries"_s] = pref->resolvePeerCountries();
381 // Reannounce to all trackers when ip/port changed
382 data[u"reannounce_when_address_changed"_s] = session->isReannounceWhenAddressChangedEnabled();
384 // libtorrent preferences
385 // Bdecode depth limit
386 data[u"bdecode_depth_limit"_s] = pref->getBdecodeDepthLimit();
387 // Bdecode token limit
388 data[u"bdecode_token_limit"_s] = pref->getBdecodeTokenLimit();
389 // Async IO threads
390 data[u"async_io_threads"_s] = session->asyncIOThreads();
391 // Hashing threads
392 data[u"hashing_threads"_s] = session->hashingThreads();
393 // File pool size
394 data[u"file_pool_size"_s] = session->filePoolSize();
395 // Checking memory usage
396 data[u"checking_memory_use"_s] = session->checkingMemUsage();
397 // Disk write cache
398 data[u"disk_cache"_s] = session->diskCacheSize();
399 data[u"disk_cache_ttl"_s] = session->diskCacheTTL();
400 // Disk queue size
401 data[u"disk_queue_size"_s] = session->diskQueueSize();
402 // Disk IO Type
403 data[u"disk_io_type"_s] = static_cast<int>(session->diskIOType());
404 // Disk IO read mode
405 data[u"disk_io_read_mode"_s] = static_cast<int>(session->diskIOReadMode());
406 // Disk IO write mode
407 data[u"disk_io_write_mode"_s] = static_cast<int>(session->diskIOWriteMode());
408 // Coalesce reads & writes
409 data[u"enable_coalesce_read_write"_s] = session->isCoalesceReadWriteEnabled();
410 // Piece Extent Affinity
411 data[u"enable_piece_extent_affinity"_s] = session->usePieceExtentAffinity();
412 // Suggest mode
413 data[u"enable_upload_suggestions"_s] = session->isSuggestModeEnabled();
414 // Send buffer watermark
415 data[u"send_buffer_watermark"_s] = session->sendBufferWatermark();
416 data[u"send_buffer_low_watermark"_s] = session->sendBufferLowWatermark();
417 data[u"send_buffer_watermark_factor"_s] = session->sendBufferWatermarkFactor();
418 // Outgoing connections per second
419 data[u"connection_speed"_s] = session->connectionSpeed();
420 // Socket send buffer size
421 data[u"socket_send_buffer_size"_s] = session->socketSendBufferSize();
422 // Socket receive buffer size
423 data[u"socket_receive_buffer_size"_s] = session->socketReceiveBufferSize();
424 // Socket listen backlog size
425 data[u"socket_backlog_size"_s] = session->socketBacklogSize();
426 // Outgoing ports
427 data[u"outgoing_ports_min"_s] = session->outgoingPortsMin();
428 data[u"outgoing_ports_max"_s] = session->outgoingPortsMax();
429 // UPnP lease duration
430 data[u"upnp_lease_duration"_s] = session->UPnPLeaseDuration();
431 // Type of service
432 data[u"peer_tos"_s] = session->peerToS();
433 // uTP-TCP mixed mode
434 data[u"utp_tcp_mixed_mode"_s] = static_cast<int>(session->utpMixedMode());
435 // Support internationalized domain name (IDN)
436 data[u"idn_support_enabled"_s] = session->isIDNSupportEnabled();
437 // Multiple connections per IP
438 data[u"enable_multi_connections_from_same_ip"_s] = session->multiConnectionsPerIpEnabled();
439 // Validate HTTPS tracker certificate
440 data[u"validate_https_tracker_certificate"_s] = session->validateHTTPSTrackerCertificate();
441 // SSRF mitigation
442 data[u"ssrf_mitigation"_s] = session->isSSRFMitigationEnabled();
443 // Disallow connection to peers on privileged ports
444 data[u"block_peers_on_privileged_ports"_s] = session->blockPeersOnPrivilegedPorts();
445 // Embedded tracker
446 data[u"enable_embedded_tracker"_s] = session->isTrackerEnabled();
447 data[u"embedded_tracker_port"_s] = pref->getTrackerPort();
448 data[u"embedded_tracker_port_forwarding"_s] = pref->isTrackerPortForwardingEnabled();
449 // Mark-of-the-Web
450 data[u"mark_of_the_web"_s] = pref->isMarkOfTheWebEnabled();
451 // Python executable path
452 data[u"python_executable_path"_s] = pref->getPythonExecutablePath().toString();
453 // Choking algorithm
454 data[u"upload_slots_behavior"_s] = static_cast<int>(session->chokingAlgorithm());
455 // Seed choking algorithm
456 data[u"upload_choking_algorithm"_s] = static_cast<int>(session->seedChokingAlgorithm());
457 // Announce
458 data[u"announce_to_all_trackers"_s] = session->announceToAllTrackers();
459 data[u"announce_to_all_tiers"_s] = session->announceToAllTiers();
460 data[u"announce_ip"_s] = session->announceIP();
461 data[u"max_concurrent_http_announces"_s] = session->maxConcurrentHTTPAnnounces();
462 data[u"stop_tracker_timeout"_s] = session->stopTrackerTimeout();
463 // Peer Turnover
464 data[u"peer_turnover"_s] = session->peerTurnover();
465 data[u"peer_turnover_cutoff"_s] = session->peerTurnoverCutoff();
466 data[u"peer_turnover_interval"_s] = session->peerTurnoverInterval();
467 // Maximum outstanding requests to a single peer
468 data[u"request_queue_size"_s] = session->requestQueueSize();
469 // DHT bootstrap nodes
470 data[u"dht_bootstrap_nodes"_s] = session->getDHTBootstrapNodes();
472 setResult(data);
475 void AppController::setPreferencesAction()
477 requireParams({u"json"_s});
479 auto *pref = Preferences::instance();
480 auto *session = BitTorrent::Session::instance();
481 const QVariantHash m = QJsonDocument::fromJson(params()[u"json"_s].toUtf8()).toVariant().toHash();
483 QVariantHash::ConstIterator it;
484 const auto hasKey = [&it, &m](const QString &key) -> bool
486 it = m.find(key);
487 return (it != m.constEnd());
490 // Behavior
491 // Language
492 if (hasKey(u"locale"_s))
494 QString locale = it.value().toString();
495 if (pref->getLocale() != locale)
497 auto *translator = new QTranslator;
498 if (translator->load(u":/lang/qbittorrent_"_s + locale))
500 qDebug("%s locale recognized, using translation.", qUtf8Printable(locale));
502 else
504 qDebug("%s locale unrecognized, using default (en).", qUtf8Printable(locale));
506 qApp->installTranslator(translator);
508 pref->setLocale(locale);
511 if (hasKey(u"performance_warning"_s))
512 session->setPerformanceWarningEnabled(it.value().toBool());
513 // Transfer List
514 if (hasKey(u"confirm_torrent_deletion"_s))
515 pref->setConfirmTorrentDeletion(it.value().toBool());
516 // Log file
517 if (hasKey(u"file_log_enabled"_s))
518 app()->setFileLoggerEnabled(it.value().toBool());
519 if (hasKey(u"file_log_path"_s))
520 app()->setFileLoggerPath(Path(it.value().toString()));
521 if (hasKey(u"file_log_backup_enabled"_s))
522 app()->setFileLoggerBackup(it.value().toBool());
523 if (hasKey(u"file_log_max_size"_s))
524 app()->setFileLoggerMaxSize(it.value().toInt() * 1024);
525 if (hasKey(u"file_log_delete_old"_s))
526 app()->setFileLoggerDeleteOld(it.value().toBool());
527 if (hasKey(u"file_log_age"_s))
528 app()->setFileLoggerAge(it.value().toInt());
529 if (hasKey(u"file_log_age_type"_s))
530 app()->setFileLoggerAgeType(it.value().toInt());
531 // Delete torrent content files on torrent removal
532 if (hasKey(u"delete_torrent_content_files"_s))
533 pref->setRemoveTorrentContent(it.value().toBool());
535 // Downloads
536 // When adding a torrent
537 if (hasKey(u"torrent_content_layout"_s))
538 session->setTorrentContentLayout(Utils::String::toEnum(it.value().toString(), BitTorrent::TorrentContentLayout::Original));
539 if (hasKey(u"add_to_top_of_queue"_s))
540 session->setAddTorrentToQueueTop(it.value().toBool());
541 if (hasKey(u"add_stopped_enabled"_s))
542 session->setAddTorrentStopped(it.value().toBool());
543 if (hasKey(u"torrent_stop_condition"_s))
544 session->setTorrentStopCondition(Utils::String::toEnum(it.value().toString(), BitTorrent::Torrent::StopCondition::None));
545 if (hasKey(u"merge_trackers"_s))
546 session->setMergeTrackersEnabled(it.value().toBool());
547 if (hasKey(u"auto_delete_mode"_s))
548 TorrentFileGuard::setAutoDeleteMode(static_cast<TorrentFileGuard::AutoDeleteMode>(it.value().toInt()));
550 if (hasKey(u"preallocate_all"_s))
551 session->setPreallocationEnabled(it.value().toBool());
552 if (hasKey(u"incomplete_files_ext"_s))
553 session->setAppendExtensionEnabled(it.value().toBool());
554 if (hasKey(u"use_unwanted_folder"_s))
555 session->setUnwantedFolderEnabled(it.value().toBool());
557 // Saving Management
558 if (hasKey(u"auto_tmm_enabled"_s))
559 session->setAutoTMMDisabledByDefault(!it.value().toBool());
560 if (hasKey(u"torrent_changed_tmm_enabled"_s))
561 session->setDisableAutoTMMWhenCategoryChanged(!it.value().toBool());
562 if (hasKey(u"save_path_changed_tmm_enabled"_s))
563 session->setDisableAutoTMMWhenDefaultSavePathChanged(!it.value().toBool());
564 if (hasKey(u"category_changed_tmm_enabled"_s))
565 session->setDisableAutoTMMWhenCategorySavePathChanged(!it.value().toBool());
566 if (hasKey(u"use_subcategories"_s))
567 session->setSubcategoriesEnabled(it.value().toBool());
568 if (hasKey(u"save_path"_s))
569 session->setSavePath(Path(it.value().toString()));
570 if (hasKey(u"temp_path_enabled"_s))
571 session->setDownloadPathEnabled(it.value().toBool());
572 if (hasKey(u"temp_path"_s))
573 session->setDownloadPath(Path(it.value().toString()));
574 if (hasKey(u"use_category_paths_in_manual_mode"_s))
575 session->setUseCategoryPathsInManualMode(it.value().toBool());
576 if (hasKey(u"export_dir"_s))
577 session->setTorrentExportDirectory(Path(it.value().toString()));
578 if (hasKey(u"export_dir_fin"_s))
579 session->setFinishedTorrentExportDirectory(Path(it.value().toString()));
581 // TODO: The following code is deprecated. Delete it once replaced by updated API method.
582 // === BEGIN DEPRECATED CODE === //
583 if (hasKey(u"scan_dirs"_s))
585 PathList scanDirs;
586 TorrentFilesWatcher *fsWatcher = TorrentFilesWatcher::instance();
587 const PathList oldScanDirs = fsWatcher->folders().keys();
588 const QVariantHash nativeDirs = it.value().toHash();
589 for (auto i = nativeDirs.cbegin(); i != nativeDirs.cend(); ++i)
593 const Path watchedFolder {i.key()};
594 TorrentFilesWatcher::WatchedFolderOptions options = fsWatcher->folders().value(watchedFolder);
595 BitTorrent::AddTorrentParams &params = options.addTorrentParams;
597 bool isInt = false;
598 const int intVal = i.value().toInt(&isInt);
599 if (isInt)
601 if (intVal == 0)
603 params.savePath = watchedFolder;
604 params.useAutoTMM = false;
607 else
609 const Path customSavePath {i.value().toString()};
610 params.savePath = customSavePath;
611 params.useAutoTMM = false;
614 fsWatcher->setWatchedFolder(watchedFolder, options);
615 scanDirs.append(watchedFolder);
617 catch (...)
622 // Update deleted folders
623 for (const Path &path : oldScanDirs)
625 if (!scanDirs.contains(path))
626 fsWatcher->removeWatchedFolder(path);
629 // === END DEPRECATED CODE === //
631 // Excluded file names
632 if (hasKey(u"excluded_file_names_enabled"_s))
633 session->setExcludedFileNamesEnabled(it.value().toBool());
634 if (hasKey(u"excluded_file_names"_s))
635 session->setExcludedFileNames(it.value().toString().split(u'\n'));
637 // Email notification upon download completion
638 if (hasKey(u"mail_notification_enabled"_s))
639 pref->setMailNotificationEnabled(it.value().toBool());
640 if (hasKey(u"mail_notification_sender"_s))
641 pref->setMailNotificationSender(it.value().toString());
642 if (hasKey(u"mail_notification_email"_s))
643 pref->setMailNotificationEmail(it.value().toString());
644 if (hasKey(u"mail_notification_smtp"_s))
645 pref->setMailNotificationSMTP(it.value().toString());
646 if (hasKey(u"mail_notification_ssl_enabled"_s))
647 pref->setMailNotificationSMTPSSL(it.value().toBool());
648 if (hasKey(u"mail_notification_auth_enabled"_s))
649 pref->setMailNotificationSMTPAuth(it.value().toBool());
650 if (hasKey(u"mail_notification_username"_s))
651 pref->setMailNotificationSMTPUsername(it.value().toString());
652 if (hasKey(u"mail_notification_password"_s))
653 pref->setMailNotificationSMTPPassword(it.value().toString());
654 // Run an external program on torrent added
655 if (hasKey(u"autorun_on_torrent_added_enabled"_s))
656 pref->setAutoRunOnTorrentAddedEnabled(it.value().toBool());
657 if (hasKey(u"autorun_on_torrent_added_program"_s))
658 pref->setAutoRunOnTorrentAddedProgram(it.value().toString());
659 // Run an external program on torrent finished
660 if (hasKey(u"autorun_enabled"_s))
661 pref->setAutoRunOnTorrentFinishedEnabled(it.value().toBool());
662 if (hasKey(u"autorun_program"_s))
663 pref->setAutoRunOnTorrentFinishedProgram(it.value().toString());
665 // Connection
666 // Listening Port
667 if (hasKey(u"random_port"_s) && it.value().toBool()) // deprecated
669 session->setPort(0);
671 else if (hasKey(u"listen_port"_s))
673 session->setPort(it.value().toInt());
675 // SSL Torrents
676 if (hasKey(u"ssl_enabled"_s))
677 session->setSSLEnabled(it.value().toBool());
678 if (hasKey(u"ssl_listen_port"_s))
679 session->setSSLPort(it.value().toInt());
680 if (hasKey(u"upnp"_s))
681 Net::PortForwarder::instance()->setEnabled(it.value().toBool());
682 // Connections Limits
683 if (hasKey(u"max_connec"_s))
684 session->setMaxConnections(it.value().toInt());
685 if (hasKey(u"max_connec_per_torrent"_s))
686 session->setMaxConnectionsPerTorrent(it.value().toInt());
687 if (hasKey(u"max_uploads"_s))
688 session->setMaxUploads(it.value().toInt());
689 if (hasKey(u"max_uploads_per_torrent"_s))
690 session->setMaxUploadsPerTorrent(it.value().toInt());
692 // I2P
693 if (hasKey(u"i2p_enabled"_s))
694 session->setI2PEnabled(it.value().toBool());
695 if (hasKey(u"i2p_address"_s))
696 session->setI2PAddress(it.value().toString());
697 if (hasKey(u"i2p_port"_s))
698 session->setI2PPort(it.value().toInt());
699 if (hasKey(u"i2p_mixed_mode"_s))
700 session->setI2PMixedMode(it.value().toBool());
701 if (hasKey(u"i2p_inbound_quantity"_s))
702 session->setI2PInboundQuantity(it.value().toInt());
703 if (hasKey(u"i2p_outbound_quantity"_s))
704 session->setI2POutboundQuantity(it.value().toInt());
705 if (hasKey(u"i2p_inbound_length"_s))
706 session->setI2PInboundLength(it.value().toInt());
707 if (hasKey(u"i2p_outbound_length"_s))
708 session->setI2POutboundLength(it.value().toInt());
710 // Proxy Server
711 auto *proxyManager = Net::ProxyConfigurationManager::instance();
712 Net::ProxyConfiguration proxyConf = proxyManager->proxyConfiguration();
713 if (hasKey(u"proxy_type"_s))
714 proxyConf.type = Utils::String::toEnum(it.value().toString(), Net::ProxyType::None);
715 if (hasKey(u"proxy_ip"_s))
716 proxyConf.ip = it.value().toString();
717 if (hasKey(u"proxy_port"_s))
718 proxyConf.port = it.value().toUInt();
719 if (hasKey(u"proxy_auth_enabled"_s))
720 proxyConf.authEnabled = it.value().toBool();
721 if (hasKey(u"proxy_username"_s))
722 proxyConf.username = it.value().toString();
723 if (hasKey(u"proxy_password"_s))
724 proxyConf.password = it.value().toString();
725 if (hasKey(u"proxy_hostname_lookup"_s))
726 proxyConf.hostnameLookupEnabled = it.value().toBool();
727 proxyManager->setProxyConfiguration(proxyConf);
729 if (hasKey(u"proxy_bittorrent"_s))
730 pref->setUseProxyForBT(it.value().toBool());
731 if (hasKey(u"proxy_peer_connections"_s))
732 session->setProxyPeerConnectionsEnabled(it.value().toBool());
733 if (hasKey(u"proxy_rss"_s))
734 pref->setUseProxyForRSS(it.value().toBool());
735 if (hasKey(u"proxy_misc"_s))
736 pref->setUseProxyForGeneralPurposes(it.value().toBool());
738 // IP Filtering
739 if (hasKey(u"ip_filter_enabled"_s))
740 session->setIPFilteringEnabled(it.value().toBool());
741 if (hasKey(u"ip_filter_path"_s))
742 session->setIPFilterFile(Path(it.value().toString()));
743 if (hasKey(u"ip_filter_trackers"_s))
744 session->setTrackerFilteringEnabled(it.value().toBool());
745 if (hasKey(u"banned_IPs"_s))
746 session->setBannedIPs(it.value().toString().split(u'\n', Qt::SkipEmptyParts));
748 // Speed
749 // Global Rate Limits
750 if (hasKey(u"dl_limit"_s))
751 session->setGlobalDownloadSpeedLimit(it.value().toInt());
752 if (hasKey(u"up_limit"_s))
753 session->setGlobalUploadSpeedLimit(it.value().toInt());
754 if (hasKey(u"alt_dl_limit"_s))
755 session->setAltGlobalDownloadSpeedLimit(it.value().toInt());
756 if (hasKey(u"alt_up_limit"_s))
757 session->setAltGlobalUploadSpeedLimit(it.value().toInt());
758 if (hasKey(u"bittorrent_protocol"_s))
759 session->setBTProtocol(static_cast<BitTorrent::BTProtocol>(it.value().toInt()));
760 if (hasKey(u"limit_utp_rate"_s))
761 session->setUTPRateLimited(it.value().toBool());
762 if (hasKey(u"limit_tcp_overhead"_s))
763 session->setIncludeOverheadInLimits(it.value().toBool());
764 if (hasKey(u"limit_lan_peers"_s))
765 session->setIgnoreLimitsOnLAN(!it.value().toBool());
766 // Scheduling
767 if (hasKey(u"scheduler_enabled"_s))
768 session->setBandwidthSchedulerEnabled(it.value().toBool());
769 if (m.contains(u"schedule_from_hour"_s) && m.contains(u"schedule_from_min"_s))
770 pref->setSchedulerStartTime(QTime(m[u"schedule_from_hour"_s].toInt(), m[u"schedule_from_min"_s].toInt()));
771 if (m.contains(u"schedule_to_hour"_s) && m.contains(u"schedule_to_min"_s))
772 pref->setSchedulerEndTime(QTime(m[u"schedule_to_hour"_s].toInt(), m[u"schedule_to_min"_s].toInt()));
773 if (hasKey(u"scheduler_days"_s))
774 pref->setSchedulerDays(static_cast<Scheduler::Days>(it.value().toInt()));
776 // Bittorrent
777 // Privacy
778 if (hasKey(u"dht"_s))
779 session->setDHTEnabled(it.value().toBool());
780 if (hasKey(u"pex"_s))
781 session->setPeXEnabled(it.value().toBool());
782 if (hasKey(u"lsd"_s))
783 session->setLSDEnabled(it.value().toBool());
784 if (hasKey(u"encryption"_s))
785 session->setEncryption(it.value().toInt());
786 if (hasKey(u"anonymous_mode"_s))
787 session->setAnonymousModeEnabled(it.value().toBool());
788 // Max active checking torrents
789 if (hasKey(u"max_active_checking_torrents"_s))
790 session->setMaxActiveCheckingTorrents(it.value().toInt());
791 // Torrent Queueing
792 if (hasKey(u"queueing_enabled"_s))
793 session->setQueueingSystemEnabled(it.value().toBool());
794 if (hasKey(u"max_active_downloads"_s))
795 session->setMaxActiveDownloads(it.value().toInt());
796 if (hasKey(u"max_active_torrents"_s))
797 session->setMaxActiveTorrents(it.value().toInt());
798 if (hasKey(u"max_active_uploads"_s))
799 session->setMaxActiveUploads(it.value().toInt());
800 if (hasKey(u"dont_count_slow_torrents"_s))
801 session->setIgnoreSlowTorrentsForQueueing(it.value().toBool());
802 if (hasKey(u"slow_torrent_dl_rate_threshold"_s))
803 session->setDownloadRateForSlowTorrents(it.value().toInt());
804 if (hasKey(u"slow_torrent_ul_rate_threshold"_s))
805 session->setUploadRateForSlowTorrents(it.value().toInt());
806 if (hasKey(u"slow_torrent_inactive_timer"_s))
807 session->setSlowTorrentsInactivityTimer(it.value().toInt());
808 // Share Ratio Limiting
809 if (hasKey(u"max_ratio_enabled"_s))
811 if (it.value().toBool())
812 session->setGlobalMaxRatio(m[u"max_ratio"_s].toReal());
813 else
814 session->setGlobalMaxRatio(-1);
816 if (hasKey(u"max_seeding_time_enabled"_s))
818 if (it.value().toBool())
819 session->setGlobalMaxSeedingMinutes(m[u"max_seeding_time"_s].toInt());
820 else
821 session->setGlobalMaxSeedingMinutes(-1);
823 if (hasKey(u"max_inactive_seeding_time_enabled"_s))
825 session->setGlobalMaxInactiveSeedingMinutes(it.value().toBool()
826 ? m[u"max_inactive_seeding_time"_s].toInt() : -1);
828 if (hasKey(u"max_ratio_act"_s))
830 switch (it.value().toInt())
832 default:
833 case 0:
834 session->setShareLimitAction(BitTorrent::ShareLimitAction::Stop);
835 break;
836 case 1:
837 session->setShareLimitAction(BitTorrent::ShareLimitAction::Remove);
838 break;
839 case 2:
840 session->setShareLimitAction(BitTorrent::ShareLimitAction::EnableSuperSeeding);
841 break;
842 case 3:
843 session->setShareLimitAction(BitTorrent::ShareLimitAction::RemoveWithContent);
844 break;
847 // Add trackers
848 if (hasKey(u"add_trackers_enabled"_s))
849 session->setAddTrackersEnabled(it.value().toBool());
850 if (hasKey(u"add_trackers"_s))
851 session->setAdditionalTrackers(it.value().toString());
853 // WebUI
854 // HTTP Server
855 if (hasKey(u"web_ui_domain_list"_s))
856 pref->setServerDomains(it.value().toString());
857 if (hasKey(u"web_ui_address"_s))
858 pref->setWebUIAddress(it.value().toString());
859 if (hasKey(u"web_ui_port"_s))
860 pref->setWebUIPort(it.value().value<quint16>());
861 if (hasKey(u"web_ui_upnp"_s))
862 pref->setUPnPForWebUIPort(it.value().toBool());
863 if (hasKey(u"use_https"_s))
864 pref->setWebUIHttpsEnabled(it.value().toBool());
865 if (hasKey(u"web_ui_https_cert_path"_s))
866 pref->setWebUIHttpsCertificatePath(Path(it.value().toString()));
867 if (hasKey(u"web_ui_https_key_path"_s))
868 pref->setWebUIHttpsKeyPath(Path(it.value().toString()));
869 // Authentication
870 if (hasKey(u"web_ui_username"_s))
871 pref->setWebUIUsername(it.value().toString());
872 if (hasKey(u"web_ui_password"_s))
873 pref->setWebUIPassword(Utils::Password::PBKDF2::generate(it.value().toByteArray()));
874 if (hasKey(u"bypass_local_auth"_s))
875 pref->setWebUILocalAuthEnabled(!it.value().toBool());
876 if (hasKey(u"bypass_auth_subnet_whitelist_enabled"_s))
877 pref->setWebUIAuthSubnetWhitelistEnabled(it.value().toBool());
878 if (hasKey(u"bypass_auth_subnet_whitelist"_s))
880 // recognize new lines and commas as delimiters
881 pref->setWebUIAuthSubnetWhitelist(it.value().toString().split(QRegularExpression(u"\n|,"_s), Qt::SkipEmptyParts));
883 if (hasKey(u"web_ui_max_auth_fail_count"_s))
884 pref->setWebUIMaxAuthFailCount(it.value().toInt());
885 if (hasKey(u"web_ui_ban_duration"_s))
886 pref->setWebUIBanDuration(std::chrono::seconds {it.value().toInt()});
887 if (hasKey(u"web_ui_session_timeout"_s))
888 pref->setWebUISessionTimeout(it.value().toInt());
889 // Use alternative WebUI
890 if (hasKey(u"alternative_webui_enabled"_s))
891 pref->setAltWebUIEnabled(it.value().toBool());
892 if (hasKey(u"alternative_webui_path"_s))
893 pref->setWebUIRootFolder(Path(it.value().toString()));
894 // Security
895 if (hasKey(u"web_ui_clickjacking_protection_enabled"_s))
896 pref->setWebUIClickjackingProtectionEnabled(it.value().toBool());
897 if (hasKey(u"web_ui_csrf_protection_enabled"_s))
898 pref->setWebUICSRFProtectionEnabled(it.value().toBool());
899 if (hasKey(u"web_ui_secure_cookie_enabled"_s))
900 pref->setWebUISecureCookieEnabled(it.value().toBool());
901 if (hasKey(u"web_ui_host_header_validation_enabled"_s))
902 pref->setWebUIHostHeaderValidationEnabled(it.value().toBool());
903 // Custom HTTP headers
904 if (hasKey(u"web_ui_use_custom_http_headers_enabled"_s))
905 pref->setWebUICustomHTTPHeadersEnabled(it.value().toBool());
906 if (hasKey(u"web_ui_custom_http_headers"_s))
907 pref->setWebUICustomHTTPHeaders(it.value().toString());
908 // Reverse proxy
909 if (hasKey(u"web_ui_reverse_proxy_enabled"_s))
910 pref->setWebUIReverseProxySupportEnabled(it.value().toBool());
911 if (hasKey(u"web_ui_reverse_proxies_list"_s))
912 pref->setWebUITrustedReverseProxiesList(it.value().toString());
913 // Update my dynamic domain name
914 if (hasKey(u"dyndns_enabled"_s))
915 pref->setDynDNSEnabled(it.value().toBool());
916 if (hasKey(u"dyndns_service"_s))
917 pref->setDynDNSService(static_cast<DNS::Service>(it.value().toInt()));
918 if (hasKey(u"dyndns_username"_s))
919 pref->setDynDNSUsername(it.value().toString());
920 if (hasKey(u"dyndns_password"_s))
921 pref->setDynDNSPassword(it.value().toString());
922 if (hasKey(u"dyndns_domain"_s))
923 pref->setDynDomainName(it.value().toString());
925 if (hasKey(u"rss_refresh_interval"_s))
926 RSS::Session::instance()->setRefreshInterval(it.value().toInt());
927 if (hasKey(u"rss_fetch_delay"_s))
928 RSS::Session::instance()->setFetchDelay(std::chrono::seconds(it.value().toLongLong()));
929 if (hasKey(u"rss_max_articles_per_feed"_s))
930 RSS::Session::instance()->setMaxArticlesPerFeed(it.value().toInt());
931 if (hasKey(u"rss_processing_enabled"_s))
932 RSS::Session::instance()->setProcessingEnabled(it.value().toBool());
933 if (hasKey(u"rss_auto_downloading_enabled"_s))
934 RSS::AutoDownloader::instance()->setProcessingEnabled(it.value().toBool());
935 if (hasKey(u"rss_download_repack_proper_episodes"_s))
936 RSS::AutoDownloader::instance()->setDownloadRepacks(it.value().toBool());
937 if (hasKey(u"rss_smart_episode_filters"_s))
938 RSS::AutoDownloader::instance()->setSmartEpisodeFilters(it.value().toString().split(u'\n'));
940 // Advanced settings
941 // qBittorrent preferences
942 // Resume data storage type
943 if (hasKey(u"resume_data_storage_type"_s))
944 session->setResumeDataStorageType(Utils::String::toEnum(it.value().toString(), BitTorrent::ResumeDataStorageType::Legacy));
945 // Torrent content removing mode
946 if (hasKey(u"torrent_content_remove_option"_s))
947 session->setTorrentContentRemoveOption(Utils::String::toEnum(it.value().toString(), BitTorrent::TorrentContentRemoveOption::MoveToTrash));
948 // Physical memory (RAM) usage limit
949 if (hasKey(u"memory_working_set_limit"_s))
950 app()->setMemoryWorkingSetLimit(it.value().toInt());
951 // Current network interface
952 if (hasKey(u"current_network_interface"_s))
954 const QString ifaceValue {it.value().toString()};
956 const QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
957 const auto ifacesIter = std::find_if(ifaces.cbegin(), ifaces.cend(), [&ifaceValue](const QNetworkInterface &iface)
959 return (!iface.addressEntries().isEmpty()) && (iface.name() == ifaceValue);
961 const QString ifaceName = (ifacesIter != ifaces.cend()) ? ifacesIter->humanReadableName() : QString {};
963 session->setNetworkInterface(ifaceValue);
964 if (!ifaceName.isEmpty() || ifaceValue.isEmpty())
965 session->setNetworkInterfaceName(ifaceName);
967 // Current network interface address
968 if (hasKey(u"current_interface_address"_s))
970 const QHostAddress ifaceAddress {it.value().toString().trimmed()};
971 session->setNetworkInterfaceAddress(ifaceAddress.isNull() ? QString {} : ifaceAddress.toString());
973 // Save resume data interval
974 if (hasKey(u"save_resume_data_interval"_s))
975 session->setSaveResumeDataInterval(it.value().toInt());
976 // Save statistics interval
977 if (hasKey(u"save_statistics_interval"_s))
978 session->setSaveStatisticsInterval(std::chrono::minutes(it.value().toInt()));
979 // .torrent file size limit
980 if (hasKey(u"torrent_file_size_limit"_s))
981 pref->setTorrentFileSizeLimit(it.value().toLongLong());
982 // Confirm torrent recheck
983 if (hasKey(u"confirm_torrent_recheck"_s))
984 pref->setConfirmTorrentRecheck(it.value().toBool());
985 // Recheck completed torrents
986 if (hasKey(u"recheck_completed_torrents"_s))
987 pref->recheckTorrentsOnCompletion(it.value().toBool());
988 // Customize application instance name
989 if (hasKey(u"app_instance_name"_s))
990 app()->setInstanceName(it.value().toString());
991 // Refresh interval
992 if (hasKey(u"refresh_interval"_s))
993 session->setRefreshInterval(it.value().toInt());
994 // Resolve peer countries
995 if (hasKey(u"resolve_peer_countries"_s))
996 pref->resolvePeerCountries(it.value().toBool());
997 // Reannounce to all trackers when ip/port changed
998 if (hasKey(u"reannounce_when_address_changed"_s))
999 session->setReannounceWhenAddressChangedEnabled(it.value().toBool());
1001 // libtorrent preferences
1002 // Bdecode depth limit
1003 if (hasKey(u"bdecode_depth_limit"_s))
1004 pref->setBdecodeDepthLimit(it.value().toInt());
1005 // Bdecode token limit
1006 if (hasKey(u"bdecode_token_limit"_s))
1007 pref->setBdecodeTokenLimit(it.value().toInt());
1008 // Async IO threads
1009 if (hasKey(u"async_io_threads"_s))
1010 session->setAsyncIOThreads(it.value().toInt());
1011 // Hashing threads
1012 if (hasKey(u"hashing_threads"_s))
1013 session->setHashingThreads(it.value().toInt());
1014 // File pool size
1015 if (hasKey(u"file_pool_size"_s))
1016 session->setFilePoolSize(it.value().toInt());
1017 // Checking Memory Usage
1018 if (hasKey(u"checking_memory_use"_s))
1019 session->setCheckingMemUsage(it.value().toInt());
1020 // Disk write cache
1021 if (hasKey(u"disk_cache"_s))
1022 session->setDiskCacheSize(it.value().toInt());
1023 if (hasKey(u"disk_cache_ttl"_s))
1024 session->setDiskCacheTTL(it.value().toInt());
1025 // Disk queue size
1026 if (hasKey(u"disk_queue_size"_s))
1027 session->setDiskQueueSize(it.value().toLongLong());
1028 // Disk IO Type
1029 if (hasKey(u"disk_io_type"_s))
1030 session->setDiskIOType(static_cast<BitTorrent::DiskIOType>(it.value().toInt()));
1031 // Disk IO read mode
1032 if (hasKey(u"disk_io_read_mode"_s))
1033 session->setDiskIOReadMode(static_cast<BitTorrent::DiskIOReadMode>(it.value().toInt()));
1034 // Disk IO write mode
1035 if (hasKey(u"disk_io_write_mode"_s))
1036 session->setDiskIOWriteMode(static_cast<BitTorrent::DiskIOWriteMode>(it.value().toInt()));
1037 // Coalesce reads & writes
1038 if (hasKey(u"enable_coalesce_read_write"_s))
1039 session->setCoalesceReadWriteEnabled(it.value().toBool());
1040 // Piece extent affinity
1041 if (hasKey(u"enable_piece_extent_affinity"_s))
1042 session->setPieceExtentAffinity(it.value().toBool());
1043 // Suggest mode
1044 if (hasKey(u"enable_upload_suggestions"_s))
1045 session->setSuggestMode(it.value().toBool());
1046 // Send buffer watermark
1047 if (hasKey(u"send_buffer_watermark"_s))
1048 session->setSendBufferWatermark(it.value().toInt());
1049 if (hasKey(u"send_buffer_low_watermark"_s))
1050 session->setSendBufferLowWatermark(it.value().toInt());
1051 if (hasKey(u"send_buffer_watermark_factor"_s))
1052 session->setSendBufferWatermarkFactor(it.value().toInt());
1053 // Outgoing connections per second
1054 if (hasKey(u"connection_speed"_s))
1055 session->setConnectionSpeed(it.value().toInt());
1056 // Socket send buffer size
1057 if (hasKey(u"socket_send_buffer_size"_s))
1058 session->setSocketSendBufferSize(it.value().toInt());
1059 // Socket receive buffer size
1060 if (hasKey(u"socket_receive_buffer_size"_s))
1061 session->setSocketReceiveBufferSize(it.value().toInt());
1062 // Socket listen backlog size
1063 if (hasKey(u"socket_backlog_size"_s))
1064 session->setSocketBacklogSize(it.value().toInt());
1065 // Outgoing ports
1066 if (hasKey(u"outgoing_ports_min"_s))
1067 session->setOutgoingPortsMin(it.value().toInt());
1068 if (hasKey(u"outgoing_ports_max"_s))
1069 session->setOutgoingPortsMax(it.value().toInt());
1070 // UPnP lease duration
1071 if (hasKey(u"upnp_lease_duration"_s))
1072 session->setUPnPLeaseDuration(it.value().toInt());
1073 // Type of service
1074 if (hasKey(u"peer_tos"_s))
1075 session->setPeerToS(it.value().toInt());
1076 // uTP-TCP mixed mode
1077 if (hasKey(u"utp_tcp_mixed_mode"_s))
1078 session->setUtpMixedMode(static_cast<BitTorrent::MixedModeAlgorithm>(it.value().toInt()));
1079 // Support internationalized domain name (IDN)
1080 if (hasKey(u"idn_support_enabled"_s))
1081 session->setIDNSupportEnabled(it.value().toBool());
1082 // Multiple connections per IP
1083 if (hasKey(u"enable_multi_connections_from_same_ip"_s))
1084 session->setMultiConnectionsPerIpEnabled(it.value().toBool());
1085 // Validate HTTPS tracker certificate
1086 if (hasKey(u"validate_https_tracker_certificate"_s))
1087 session->setValidateHTTPSTrackerCertificate(it.value().toBool());
1088 // SSRF mitigation
1089 if (hasKey(u"ssrf_mitigation"_s))
1090 session->setSSRFMitigationEnabled(it.value().toBool());
1091 // Disallow connection to peers on privileged ports
1092 if (hasKey(u"block_peers_on_privileged_ports"_s))
1093 session->setBlockPeersOnPrivilegedPorts(it.value().toBool());
1094 // Embedded tracker
1095 if (hasKey(u"embedded_tracker_port"_s))
1096 pref->setTrackerPort(it.value().toInt());
1097 if (hasKey(u"embedded_tracker_port_forwarding"_s))
1098 pref->setTrackerPortForwardingEnabled(it.value().toBool());
1099 if (hasKey(u"enable_embedded_tracker"_s))
1100 session->setTrackerEnabled(it.value().toBool());
1101 // Mark-of-the-Web
1102 if (hasKey(u"mark_of_the_web"_s))
1103 pref->setMarkOfTheWebEnabled(it.value().toBool());
1104 // Python executable path
1105 if (hasKey(u"python_executable_path"_s))
1106 pref->setPythonExecutablePath(Path(it.value().toString()));
1107 // Choking algorithm
1108 if (hasKey(u"upload_slots_behavior"_s))
1109 session->setChokingAlgorithm(static_cast<BitTorrent::ChokingAlgorithm>(it.value().toInt()));
1110 // Seed choking algorithm
1111 if (hasKey(u"upload_choking_algorithm"_s))
1112 session->setSeedChokingAlgorithm(static_cast<BitTorrent::SeedChokingAlgorithm>(it.value().toInt()));
1113 // Announce
1114 if (hasKey(u"announce_to_all_trackers"_s))
1115 session->setAnnounceToAllTrackers(it.value().toBool());
1116 if (hasKey(u"announce_to_all_tiers"_s))
1117 session->setAnnounceToAllTiers(it.value().toBool());
1118 if (hasKey(u"announce_ip"_s))
1120 const QHostAddress announceAddr {it.value().toString().trimmed()};
1121 session->setAnnounceIP(announceAddr.isNull() ? QString {} : announceAddr.toString());
1123 if (hasKey(u"max_concurrent_http_announces"_s))
1124 session->setMaxConcurrentHTTPAnnounces(it.value().toInt());
1125 if (hasKey(u"stop_tracker_timeout"_s))
1126 session->setStopTrackerTimeout(it.value().toInt());
1127 // Peer Turnover
1128 if (hasKey(u"peer_turnover"_s))
1129 session->setPeerTurnover(it.value().toInt());
1130 if (hasKey(u"peer_turnover_cutoff"_s))
1131 session->setPeerTurnoverCutoff(it.value().toInt());
1132 if (hasKey(u"peer_turnover_interval"_s))
1133 session->setPeerTurnoverInterval(it.value().toInt());
1134 // Maximum outstanding requests to a single peer
1135 if (hasKey(u"request_queue_size"_s))
1136 session->setRequestQueueSize(it.value().toInt());
1137 // DHT bootstrap nodes
1138 if (hasKey(u"dht_bootstrap_nodes"_s))
1139 session->setDHTBootstrapNodes(it.value().toString());
1141 // Save preferences
1142 pref->apply();
1145 void AppController::defaultSavePathAction()
1147 setResult(BitTorrent::Session::instance()->savePath().toString());
1150 void AppController::sendTestEmailAction()
1152 app()->sendTestEmail();
1156 void AppController::getDirectoryContentAction()
1158 requireParams({u"dirPath"_s});
1160 const QString dirPath = params().value(u"dirPath"_s);
1161 if (dirPath.isEmpty() || dirPath.startsWith(u':'))
1162 throw APIError(APIErrorType::BadParams, tr("Invalid directory path"));
1164 const QDir dir {dirPath};
1165 if (!dir.isAbsolute())
1166 throw APIError(APIErrorType::BadParams, tr("Invalid directory path"));
1167 if (!dir.exists())
1168 throw APIError(APIErrorType::NotFound, tr("Directory does not exist"));
1170 const QString visibility = params().value(u"mode"_s, u"all"_s);
1172 const auto parseDirectoryContentMode = [](const QString &visibility) -> QDir::Filters
1174 if (visibility == u"dirs")
1175 return QDir::Dirs;
1176 if (visibility == u"files")
1177 return QDir::Files;
1178 if (visibility == u"all")
1179 return (QDir::Dirs | QDir::Files);
1180 throw APIError(APIErrorType::BadParams, tr("Invalid mode, allowed values: %1").arg(u"all, dirs, files"_s));
1183 QJsonArray ret;
1184 QDirIterator it {dirPath, (QDir::NoDotAndDotDot | parseDirectoryContentMode(visibility))};
1185 while (it.hasNext())
1186 ret.append(it.next());
1187 setResult(ret);
1190 void AppController::networkInterfaceListAction()
1192 QJsonArray ifaceList;
1193 for (const QNetworkInterface &iface : asConst(QNetworkInterface::allInterfaces()))
1195 if (!iface.addressEntries().isEmpty())
1197 ifaceList.append(QJsonObject
1199 {u"name"_s, iface.humanReadableName()},
1200 {u"value"_s, iface.name()}
1205 setResult(ifaceList);
1208 void AppController::networkInterfaceAddressListAction()
1210 requireParams({u"iface"_s});
1212 const QString ifaceName = params().value(u"iface"_s);
1213 QJsonArray addressList;
1215 const auto appendAddress = [&addressList](const QHostAddress &addr)
1217 if (addr.protocol() == QAbstractSocket::IPv6Protocol)
1218 addressList.append(Utils::Net::canonicalIPv6Addr(addr).toString());
1219 else
1220 addressList.append(addr.toString());
1223 if (ifaceName.isEmpty())
1225 for (const QHostAddress &addr : asConst(QNetworkInterface::allAddresses()))
1226 appendAddress(addr);
1228 else
1230 const QNetworkInterface iface = QNetworkInterface::interfaceFromName(ifaceName);
1231 for (const QNetworkAddressEntry &entry : asConst(iface.addressEntries()))
1232 appendAddress(entry.ip());
1235 setResult(addressList);