WebUI: Improve torrent deletion
[qBittorrent.git] / src / webui / api / appcontroller.cpp
blob2b3fc7e2d278b4de5a61b6dfbc09977a43f5e1ce
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 // .torrent file size limit
368 data[u"torrent_file_size_limit"_s] = pref->getTorrentFileSizeLimit();
369 // Recheck completed torrents
370 data[u"recheck_completed_torrents"_s] = pref->recheckTorrentsOnCompletion();
371 // Customize application instance name
372 data[u"app_instance_name"_s] = app()->instanceName();
373 // Refresh interval
374 data[u"refresh_interval"_s] = session->refreshInterval();
375 // Resolve peer countries
376 data[u"resolve_peer_countries"_s] = pref->resolvePeerCountries();
377 // Reannounce to all trackers when ip/port changed
378 data[u"reannounce_when_address_changed"_s] = session->isReannounceWhenAddressChangedEnabled();
380 // libtorrent preferences
381 // Bdecode depth limit
382 data[u"bdecode_depth_limit"_s] = pref->getBdecodeDepthLimit();
383 // Bdecode token limit
384 data[u"bdecode_token_limit"_s] = pref->getBdecodeTokenLimit();
385 // Async IO threads
386 data[u"async_io_threads"_s] = session->asyncIOThreads();
387 // Hashing threads
388 data[u"hashing_threads"_s] = session->hashingThreads();
389 // File pool size
390 data[u"file_pool_size"_s] = session->filePoolSize();
391 // Checking memory usage
392 data[u"checking_memory_use"_s] = session->checkingMemUsage();
393 // Disk write cache
394 data[u"disk_cache"_s] = session->diskCacheSize();
395 data[u"disk_cache_ttl"_s] = session->diskCacheTTL();
396 // Disk queue size
397 data[u"disk_queue_size"_s] = session->diskQueueSize();
398 // Disk IO Type
399 data[u"disk_io_type"_s] = static_cast<int>(session->diskIOType());
400 // Disk IO read mode
401 data[u"disk_io_read_mode"_s] = static_cast<int>(session->diskIOReadMode());
402 // Disk IO write mode
403 data[u"disk_io_write_mode"_s] = static_cast<int>(session->diskIOWriteMode());
404 // Coalesce reads & writes
405 data[u"enable_coalesce_read_write"_s] = session->isCoalesceReadWriteEnabled();
406 // Piece Extent Affinity
407 data[u"enable_piece_extent_affinity"_s] = session->usePieceExtentAffinity();
408 // Suggest mode
409 data[u"enable_upload_suggestions"_s] = session->isSuggestModeEnabled();
410 // Send buffer watermark
411 data[u"send_buffer_watermark"_s] = session->sendBufferWatermark();
412 data[u"send_buffer_low_watermark"_s] = session->sendBufferLowWatermark();
413 data[u"send_buffer_watermark_factor"_s] = session->sendBufferWatermarkFactor();
414 // Outgoing connections per second
415 data[u"connection_speed"_s] = session->connectionSpeed();
416 // Socket send buffer size
417 data[u"socket_send_buffer_size"_s] = session->socketSendBufferSize();
418 // Socket receive buffer size
419 data[u"socket_receive_buffer_size"_s] = session->socketReceiveBufferSize();
420 // Socket listen backlog size
421 data[u"socket_backlog_size"_s] = session->socketBacklogSize();
422 // Outgoing ports
423 data[u"outgoing_ports_min"_s] = session->outgoingPortsMin();
424 data[u"outgoing_ports_max"_s] = session->outgoingPortsMax();
425 // UPnP lease duration
426 data[u"upnp_lease_duration"_s] = session->UPnPLeaseDuration();
427 // Type of service
428 data[u"peer_tos"_s] = session->peerToS();
429 // uTP-TCP mixed mode
430 data[u"utp_tcp_mixed_mode"_s] = static_cast<int>(session->utpMixedMode());
431 // Support internationalized domain name (IDN)
432 data[u"idn_support_enabled"_s] = session->isIDNSupportEnabled();
433 // Multiple connections per IP
434 data[u"enable_multi_connections_from_same_ip"_s] = session->multiConnectionsPerIpEnabled();
435 // Validate HTTPS tracker certificate
436 data[u"validate_https_tracker_certificate"_s] = session->validateHTTPSTrackerCertificate();
437 // SSRF mitigation
438 data[u"ssrf_mitigation"_s] = session->isSSRFMitigationEnabled();
439 // Disallow connection to peers on privileged ports
440 data[u"block_peers_on_privileged_ports"_s] = session->blockPeersOnPrivilegedPorts();
441 // Embedded tracker
442 data[u"enable_embedded_tracker"_s] = session->isTrackerEnabled();
443 data[u"embedded_tracker_port"_s] = pref->getTrackerPort();
444 data[u"embedded_tracker_port_forwarding"_s] = pref->isTrackerPortForwardingEnabled();
445 // Mark-of-the-Web
446 data[u"mark_of_the_web"_s] = pref->isMarkOfTheWebEnabled();
447 // Python executable path
448 data[u"python_executable_path"_s] = pref->getPythonExecutablePath().toString();
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 // Transfer List
510 if (hasKey(u"confirm_torrent_deletion"_s))
511 pref->setConfirmTorrentDeletion(it.value().toBool());
512 // Log file
513 if (hasKey(u"file_log_enabled"_s))
514 app()->setFileLoggerEnabled(it.value().toBool());
515 if (hasKey(u"file_log_path"_s))
516 app()->setFileLoggerPath(Path(it.value().toString()));
517 if (hasKey(u"file_log_backup_enabled"_s))
518 app()->setFileLoggerBackup(it.value().toBool());
519 if (hasKey(u"file_log_max_size"_s))
520 app()->setFileLoggerMaxSize(it.value().toInt() * 1024);
521 if (hasKey(u"file_log_delete_old"_s))
522 app()->setFileLoggerDeleteOld(it.value().toBool());
523 if (hasKey(u"file_log_age"_s))
524 app()->setFileLoggerAge(it.value().toInt());
525 if (hasKey(u"file_log_age_type"_s))
526 app()->setFileLoggerAgeType(it.value().toInt());
527 // Delete torrent content files on torrent removal
528 if (hasKey(u"delete_torrent_content_files"_s))
529 pref->setRemoveTorrentContent(it.value().toBool());
531 // Downloads
532 // When adding a torrent
533 if (hasKey(u"torrent_content_layout"_s))
534 session->setTorrentContentLayout(Utils::String::toEnum(it.value().toString(), BitTorrent::TorrentContentLayout::Original));
535 if (hasKey(u"add_to_top_of_queue"_s))
536 session->setAddTorrentToQueueTop(it.value().toBool());
537 if (hasKey(u"add_stopped_enabled"_s))
538 session->setAddTorrentStopped(it.value().toBool());
539 if (hasKey(u"torrent_stop_condition"_s))
540 session->setTorrentStopCondition(Utils::String::toEnum(it.value().toString(), BitTorrent::Torrent::StopCondition::None));
541 if (hasKey(u"merge_trackers"_s))
542 session->setMergeTrackersEnabled(it.value().toBool());
543 if (hasKey(u"auto_delete_mode"_s))
544 TorrentFileGuard::setAutoDeleteMode(static_cast<TorrentFileGuard::AutoDeleteMode>(it.value().toInt()));
546 if (hasKey(u"preallocate_all"_s))
547 session->setPreallocationEnabled(it.value().toBool());
548 if (hasKey(u"incomplete_files_ext"_s))
549 session->setAppendExtensionEnabled(it.value().toBool());
550 if (hasKey(u"use_unwanted_folder"_s))
551 session->setUnwantedFolderEnabled(it.value().toBool());
553 // Saving Management
554 if (hasKey(u"auto_tmm_enabled"_s))
555 session->setAutoTMMDisabledByDefault(!it.value().toBool());
556 if (hasKey(u"torrent_changed_tmm_enabled"_s))
557 session->setDisableAutoTMMWhenCategoryChanged(!it.value().toBool());
558 if (hasKey(u"save_path_changed_tmm_enabled"_s))
559 session->setDisableAutoTMMWhenDefaultSavePathChanged(!it.value().toBool());
560 if (hasKey(u"category_changed_tmm_enabled"_s))
561 session->setDisableAutoTMMWhenCategorySavePathChanged(!it.value().toBool());
562 if (hasKey(u"use_subcategories"_s))
563 session->setSubcategoriesEnabled(it.value().toBool());
564 if (hasKey(u"save_path"_s))
565 session->setSavePath(Path(it.value().toString()));
566 if (hasKey(u"temp_path_enabled"_s))
567 session->setDownloadPathEnabled(it.value().toBool());
568 if (hasKey(u"temp_path"_s))
569 session->setDownloadPath(Path(it.value().toString()));
570 if (hasKey(u"use_category_paths_in_manual_mode"_s))
571 session->setUseCategoryPathsInManualMode(it.value().toBool());
572 if (hasKey(u"export_dir"_s))
573 session->setTorrentExportDirectory(Path(it.value().toString()));
574 if (hasKey(u"export_dir_fin"_s))
575 session->setFinishedTorrentExportDirectory(Path(it.value().toString()));
577 // TODO: The following code is deprecated. Delete it once replaced by updated API method.
578 // === BEGIN DEPRECATED CODE === //
579 if (hasKey(u"scan_dirs"_s))
581 PathList scanDirs;
582 TorrentFilesWatcher *fsWatcher = TorrentFilesWatcher::instance();
583 const PathList oldScanDirs = fsWatcher->folders().keys();
584 const QVariantHash nativeDirs = it.value().toHash();
585 for (auto i = nativeDirs.cbegin(); i != nativeDirs.cend(); ++i)
589 const Path watchedFolder {i.key()};
590 TorrentFilesWatcher::WatchedFolderOptions options = fsWatcher->folders().value(watchedFolder);
591 BitTorrent::AddTorrentParams &params = options.addTorrentParams;
593 bool isInt = false;
594 const int intVal = i.value().toInt(&isInt);
595 if (isInt)
597 if (intVal == 0)
599 params.savePath = watchedFolder;
600 params.useAutoTMM = false;
603 else
605 const Path customSavePath {i.value().toString()};
606 params.savePath = customSavePath;
607 params.useAutoTMM = false;
610 fsWatcher->setWatchedFolder(watchedFolder, options);
611 scanDirs.append(watchedFolder);
613 catch (...)
618 // Update deleted folders
619 for (const Path &path : oldScanDirs)
621 if (!scanDirs.contains(path))
622 fsWatcher->removeWatchedFolder(path);
625 // === END DEPRECATED CODE === //
627 // Excluded file names
628 if (hasKey(u"excluded_file_names_enabled"_s))
629 session->setExcludedFileNamesEnabled(it.value().toBool());
630 if (hasKey(u"excluded_file_names"_s))
631 session->setExcludedFileNames(it.value().toString().split(u'\n'));
633 // Email notification upon download completion
634 if (hasKey(u"mail_notification_enabled"_s))
635 pref->setMailNotificationEnabled(it.value().toBool());
636 if (hasKey(u"mail_notification_sender"_s))
637 pref->setMailNotificationSender(it.value().toString());
638 if (hasKey(u"mail_notification_email"_s))
639 pref->setMailNotificationEmail(it.value().toString());
640 if (hasKey(u"mail_notification_smtp"_s))
641 pref->setMailNotificationSMTP(it.value().toString());
642 if (hasKey(u"mail_notification_ssl_enabled"_s))
643 pref->setMailNotificationSMTPSSL(it.value().toBool());
644 if (hasKey(u"mail_notification_auth_enabled"_s))
645 pref->setMailNotificationSMTPAuth(it.value().toBool());
646 if (hasKey(u"mail_notification_username"_s))
647 pref->setMailNotificationSMTPUsername(it.value().toString());
648 if (hasKey(u"mail_notification_password"_s))
649 pref->setMailNotificationSMTPPassword(it.value().toString());
650 // Run an external program on torrent added
651 if (hasKey(u"autorun_on_torrent_added_enabled"_s))
652 pref->setAutoRunOnTorrentAddedEnabled(it.value().toBool());
653 if (hasKey(u"autorun_on_torrent_added_program"_s))
654 pref->setAutoRunOnTorrentAddedProgram(it.value().toString());
655 // Run an external program on torrent finished
656 if (hasKey(u"autorun_enabled"_s))
657 pref->setAutoRunOnTorrentFinishedEnabled(it.value().toBool());
658 if (hasKey(u"autorun_program"_s))
659 pref->setAutoRunOnTorrentFinishedProgram(it.value().toString());
661 // Connection
662 // Listening Port
663 if (hasKey(u"random_port"_s) && it.value().toBool()) // deprecated
665 session->setPort(0);
667 else if (hasKey(u"listen_port"_s))
669 session->setPort(it.value().toInt());
671 // SSL Torrents
672 if (hasKey(u"ssl_enabled"_s))
673 session->setSSLEnabled(it.value().toBool());
674 if (hasKey(u"ssl_listen_port"_s))
675 session->setSSLPort(it.value().toInt());
676 if (hasKey(u"upnp"_s))
677 Net::PortForwarder::instance()->setEnabled(it.value().toBool());
678 // Connections Limits
679 if (hasKey(u"max_connec"_s))
680 session->setMaxConnections(it.value().toInt());
681 if (hasKey(u"max_connec_per_torrent"_s))
682 session->setMaxConnectionsPerTorrent(it.value().toInt());
683 if (hasKey(u"max_uploads"_s))
684 session->setMaxUploads(it.value().toInt());
685 if (hasKey(u"max_uploads_per_torrent"_s))
686 session->setMaxUploadsPerTorrent(it.value().toInt());
688 // I2P
689 if (hasKey(u"i2p_enabled"_s))
690 session->setI2PEnabled(it.value().toBool());
691 if (hasKey(u"i2p_address"_s))
692 session->setI2PAddress(it.value().toString());
693 if (hasKey(u"i2p_port"_s))
694 session->setI2PPort(it.value().toInt());
695 if (hasKey(u"i2p_mixed_mode"_s))
696 session->setI2PMixedMode(it.value().toBool());
697 if (hasKey(u"i2p_inbound_quantity"_s))
698 session->setI2PInboundQuantity(it.value().toInt());
699 if (hasKey(u"i2p_outbound_quantity"_s))
700 session->setI2POutboundQuantity(it.value().toInt());
701 if (hasKey(u"i2p_inbound_length"_s))
702 session->setI2PInboundLength(it.value().toInt());
703 if (hasKey(u"i2p_outbound_length"_s))
704 session->setI2POutboundLength(it.value().toInt());
706 // Proxy Server
707 auto *proxyManager = Net::ProxyConfigurationManager::instance();
708 Net::ProxyConfiguration proxyConf = proxyManager->proxyConfiguration();
709 if (hasKey(u"proxy_type"_s))
710 proxyConf.type = Utils::String::toEnum(it.value().toString(), Net::ProxyType::None);
711 if (hasKey(u"proxy_ip"_s))
712 proxyConf.ip = it.value().toString();
713 if (hasKey(u"proxy_port"_s))
714 proxyConf.port = it.value().toUInt();
715 if (hasKey(u"proxy_auth_enabled"_s))
716 proxyConf.authEnabled = it.value().toBool();
717 if (hasKey(u"proxy_username"_s))
718 proxyConf.username = it.value().toString();
719 if (hasKey(u"proxy_password"_s))
720 proxyConf.password = it.value().toString();
721 if (hasKey(u"proxy_hostname_lookup"_s))
722 proxyConf.hostnameLookupEnabled = it.value().toBool();
723 proxyManager->setProxyConfiguration(proxyConf);
725 if (hasKey(u"proxy_bittorrent"_s))
726 pref->setUseProxyForBT(it.value().toBool());
727 if (hasKey(u"proxy_peer_connections"_s))
728 session->setProxyPeerConnectionsEnabled(it.value().toBool());
729 if (hasKey(u"proxy_rss"_s))
730 pref->setUseProxyForRSS(it.value().toBool());
731 if (hasKey(u"proxy_misc"_s))
732 pref->setUseProxyForGeneralPurposes(it.value().toBool());
734 // IP Filtering
735 if (hasKey(u"ip_filter_enabled"_s))
736 session->setIPFilteringEnabled(it.value().toBool());
737 if (hasKey(u"ip_filter_path"_s))
738 session->setIPFilterFile(Path(it.value().toString()));
739 if (hasKey(u"ip_filter_trackers"_s))
740 session->setTrackerFilteringEnabled(it.value().toBool());
741 if (hasKey(u"banned_IPs"_s))
742 session->setBannedIPs(it.value().toString().split(u'\n', Qt::SkipEmptyParts));
744 // Speed
745 // Global Rate Limits
746 if (hasKey(u"dl_limit"_s))
747 session->setGlobalDownloadSpeedLimit(it.value().toInt());
748 if (hasKey(u"up_limit"_s))
749 session->setGlobalUploadSpeedLimit(it.value().toInt());
750 if (hasKey(u"alt_dl_limit"_s))
751 session->setAltGlobalDownloadSpeedLimit(it.value().toInt());
752 if (hasKey(u"alt_up_limit"_s))
753 session->setAltGlobalUploadSpeedLimit(it.value().toInt());
754 if (hasKey(u"bittorrent_protocol"_s))
755 session->setBTProtocol(static_cast<BitTorrent::BTProtocol>(it.value().toInt()));
756 if (hasKey(u"limit_utp_rate"_s))
757 session->setUTPRateLimited(it.value().toBool());
758 if (hasKey(u"limit_tcp_overhead"_s))
759 session->setIncludeOverheadInLimits(it.value().toBool());
760 if (hasKey(u"limit_lan_peers"_s))
761 session->setIgnoreLimitsOnLAN(!it.value().toBool());
762 // Scheduling
763 if (hasKey(u"scheduler_enabled"_s))
764 session->setBandwidthSchedulerEnabled(it.value().toBool());
765 if (m.contains(u"schedule_from_hour"_s) && m.contains(u"schedule_from_min"_s))
766 pref->setSchedulerStartTime(QTime(m[u"schedule_from_hour"_s].toInt(), m[u"schedule_from_min"_s].toInt()));
767 if (m.contains(u"schedule_to_hour"_s) && m.contains(u"schedule_to_min"_s))
768 pref->setSchedulerEndTime(QTime(m[u"schedule_to_hour"_s].toInt(), m[u"schedule_to_min"_s].toInt()));
769 if (hasKey(u"scheduler_days"_s))
770 pref->setSchedulerDays(static_cast<Scheduler::Days>(it.value().toInt()));
772 // Bittorrent
773 // Privacy
774 if (hasKey(u"dht"_s))
775 session->setDHTEnabled(it.value().toBool());
776 if (hasKey(u"pex"_s))
777 session->setPeXEnabled(it.value().toBool());
778 if (hasKey(u"lsd"_s))
779 session->setLSDEnabled(it.value().toBool());
780 if (hasKey(u"encryption"_s))
781 session->setEncryption(it.value().toInt());
782 if (hasKey(u"anonymous_mode"_s))
783 session->setAnonymousModeEnabled(it.value().toBool());
784 // Max active checking torrents
785 if (hasKey(u"max_active_checking_torrents"_s))
786 session->setMaxActiveCheckingTorrents(it.value().toInt());
787 // Torrent Queueing
788 if (hasKey(u"queueing_enabled"_s))
789 session->setQueueingSystemEnabled(it.value().toBool());
790 if (hasKey(u"max_active_downloads"_s))
791 session->setMaxActiveDownloads(it.value().toInt());
792 if (hasKey(u"max_active_torrents"_s))
793 session->setMaxActiveTorrents(it.value().toInt());
794 if (hasKey(u"max_active_uploads"_s))
795 session->setMaxActiveUploads(it.value().toInt());
796 if (hasKey(u"dont_count_slow_torrents"_s))
797 session->setIgnoreSlowTorrentsForQueueing(it.value().toBool());
798 if (hasKey(u"slow_torrent_dl_rate_threshold"_s))
799 session->setDownloadRateForSlowTorrents(it.value().toInt());
800 if (hasKey(u"slow_torrent_ul_rate_threshold"_s))
801 session->setUploadRateForSlowTorrents(it.value().toInt());
802 if (hasKey(u"slow_torrent_inactive_timer"_s))
803 session->setSlowTorrentsInactivityTimer(it.value().toInt());
804 // Share Ratio Limiting
805 if (hasKey(u"max_ratio_enabled"_s))
807 if (it.value().toBool())
808 session->setGlobalMaxRatio(m[u"max_ratio"_s].toReal());
809 else
810 session->setGlobalMaxRatio(-1);
812 if (hasKey(u"max_seeding_time_enabled"_s))
814 if (it.value().toBool())
815 session->setGlobalMaxSeedingMinutes(m[u"max_seeding_time"_s].toInt());
816 else
817 session->setGlobalMaxSeedingMinutes(-1);
819 if (hasKey(u"max_inactive_seeding_time_enabled"_s))
821 session->setGlobalMaxInactiveSeedingMinutes(it.value().toBool()
822 ? m[u"max_inactive_seeding_time"_s].toInt() : -1);
824 if (hasKey(u"max_ratio_act"_s))
826 switch (it.value().toInt())
828 default:
829 case 0:
830 session->setShareLimitAction(BitTorrent::ShareLimitAction::Stop);
831 break;
832 case 1:
833 session->setShareLimitAction(BitTorrent::ShareLimitAction::Remove);
834 break;
835 case 2:
836 session->setShareLimitAction(BitTorrent::ShareLimitAction::EnableSuperSeeding);
837 break;
838 case 3:
839 session->setShareLimitAction(BitTorrent::ShareLimitAction::RemoveWithContent);
840 break;
843 // Add trackers
844 if (hasKey(u"add_trackers_enabled"_s))
845 session->setAddTrackersEnabled(it.value().toBool());
846 if (hasKey(u"add_trackers"_s))
847 session->setAdditionalTrackers(it.value().toString());
849 // WebUI
850 // HTTP Server
851 if (hasKey(u"web_ui_domain_list"_s))
852 pref->setServerDomains(it.value().toString());
853 if (hasKey(u"web_ui_address"_s))
854 pref->setWebUIAddress(it.value().toString());
855 if (hasKey(u"web_ui_port"_s))
856 pref->setWebUIPort(it.value().value<quint16>());
857 if (hasKey(u"web_ui_upnp"_s))
858 pref->setUPnPForWebUIPort(it.value().toBool());
859 if (hasKey(u"use_https"_s))
860 pref->setWebUIHttpsEnabled(it.value().toBool());
861 if (hasKey(u"web_ui_https_cert_path"_s))
862 pref->setWebUIHttpsCertificatePath(Path(it.value().toString()));
863 if (hasKey(u"web_ui_https_key_path"_s))
864 pref->setWebUIHttpsKeyPath(Path(it.value().toString()));
865 // Authentication
866 if (hasKey(u"web_ui_username"_s))
867 pref->setWebUIUsername(it.value().toString());
868 if (hasKey(u"web_ui_password"_s))
869 pref->setWebUIPassword(Utils::Password::PBKDF2::generate(it.value().toByteArray()));
870 if (hasKey(u"bypass_local_auth"_s))
871 pref->setWebUILocalAuthEnabled(!it.value().toBool());
872 if (hasKey(u"bypass_auth_subnet_whitelist_enabled"_s))
873 pref->setWebUIAuthSubnetWhitelistEnabled(it.value().toBool());
874 if (hasKey(u"bypass_auth_subnet_whitelist"_s))
876 // recognize new lines and commas as delimiters
877 pref->setWebUIAuthSubnetWhitelist(it.value().toString().split(QRegularExpression(u"\n|,"_s), Qt::SkipEmptyParts));
879 if (hasKey(u"web_ui_max_auth_fail_count"_s))
880 pref->setWebUIMaxAuthFailCount(it.value().toInt());
881 if (hasKey(u"web_ui_ban_duration"_s))
882 pref->setWebUIBanDuration(std::chrono::seconds {it.value().toInt()});
883 if (hasKey(u"web_ui_session_timeout"_s))
884 pref->setWebUISessionTimeout(it.value().toInt());
885 // Use alternative WebUI
886 if (hasKey(u"alternative_webui_enabled"_s))
887 pref->setAltWebUIEnabled(it.value().toBool());
888 if (hasKey(u"alternative_webui_path"_s))
889 pref->setWebUIRootFolder(Path(it.value().toString()));
890 // Security
891 if (hasKey(u"web_ui_clickjacking_protection_enabled"_s))
892 pref->setWebUIClickjackingProtectionEnabled(it.value().toBool());
893 if (hasKey(u"web_ui_csrf_protection_enabled"_s))
894 pref->setWebUICSRFProtectionEnabled(it.value().toBool());
895 if (hasKey(u"web_ui_secure_cookie_enabled"_s))
896 pref->setWebUISecureCookieEnabled(it.value().toBool());
897 if (hasKey(u"web_ui_host_header_validation_enabled"_s))
898 pref->setWebUIHostHeaderValidationEnabled(it.value().toBool());
899 // Custom HTTP headers
900 if (hasKey(u"web_ui_use_custom_http_headers_enabled"_s))
901 pref->setWebUICustomHTTPHeadersEnabled(it.value().toBool());
902 if (hasKey(u"web_ui_custom_http_headers"_s))
903 pref->setWebUICustomHTTPHeaders(it.value().toString());
904 // Reverse proxy
905 if (hasKey(u"web_ui_reverse_proxy_enabled"_s))
906 pref->setWebUIReverseProxySupportEnabled(it.value().toBool());
907 if (hasKey(u"web_ui_reverse_proxies_list"_s))
908 pref->setWebUITrustedReverseProxiesList(it.value().toString());
909 // Update my dynamic domain name
910 if (hasKey(u"dyndns_enabled"_s))
911 pref->setDynDNSEnabled(it.value().toBool());
912 if (hasKey(u"dyndns_service"_s))
913 pref->setDynDNSService(static_cast<DNS::Service>(it.value().toInt()));
914 if (hasKey(u"dyndns_username"_s))
915 pref->setDynDNSUsername(it.value().toString());
916 if (hasKey(u"dyndns_password"_s))
917 pref->setDynDNSPassword(it.value().toString());
918 if (hasKey(u"dyndns_domain"_s))
919 pref->setDynDomainName(it.value().toString());
921 if (hasKey(u"rss_refresh_interval"_s))
922 RSS::Session::instance()->setRefreshInterval(it.value().toInt());
923 if (hasKey(u"rss_fetch_delay"_s))
924 RSS::Session::instance()->setFetchDelay(std::chrono::seconds(it.value().toLongLong()));
925 if (hasKey(u"rss_max_articles_per_feed"_s))
926 RSS::Session::instance()->setMaxArticlesPerFeed(it.value().toInt());
927 if (hasKey(u"rss_processing_enabled"_s))
928 RSS::Session::instance()->setProcessingEnabled(it.value().toBool());
929 if (hasKey(u"rss_auto_downloading_enabled"_s))
930 RSS::AutoDownloader::instance()->setProcessingEnabled(it.value().toBool());
931 if (hasKey(u"rss_download_repack_proper_episodes"_s))
932 RSS::AutoDownloader::instance()->setDownloadRepacks(it.value().toBool());
933 if (hasKey(u"rss_smart_episode_filters"_s))
934 RSS::AutoDownloader::instance()->setSmartEpisodeFilters(it.value().toString().split(u'\n'));
936 // Advanced settings
937 // qBittorrent preferences
938 // Resume data storage type
939 if (hasKey(u"resume_data_storage_type"_s))
940 session->setResumeDataStorageType(Utils::String::toEnum(it.value().toString(), BitTorrent::ResumeDataStorageType::Legacy));
941 // Torrent content removing mode
942 if (hasKey(u"torrent_content_remove_option"_s))
943 session->setTorrentContentRemoveOption(Utils::String::toEnum(it.value().toString(), BitTorrent::TorrentContentRemoveOption::MoveToTrash));
944 // Physical memory (RAM) usage limit
945 if (hasKey(u"memory_working_set_limit"_s))
946 app()->setMemoryWorkingSetLimit(it.value().toInt());
947 // Current network interface
948 if (hasKey(u"current_network_interface"_s))
950 const QString ifaceValue {it.value().toString()};
952 const QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
953 const auto ifacesIter = std::find_if(ifaces.cbegin(), ifaces.cend(), [&ifaceValue](const QNetworkInterface &iface)
955 return (!iface.addressEntries().isEmpty()) && (iface.name() == ifaceValue);
957 const QString ifaceName = (ifacesIter != ifaces.cend()) ? ifacesIter->humanReadableName() : QString {};
959 session->setNetworkInterface(ifaceValue);
960 if (!ifaceName.isEmpty() || ifaceValue.isEmpty())
961 session->setNetworkInterfaceName(ifaceName);
963 // Current network interface address
964 if (hasKey(u"current_interface_address"_s))
966 const QHostAddress ifaceAddress {it.value().toString().trimmed()};
967 session->setNetworkInterfaceAddress(ifaceAddress.isNull() ? QString {} : ifaceAddress.toString());
969 // Save resume data interval
970 if (hasKey(u"save_resume_data_interval"_s))
971 session->setSaveResumeDataInterval(it.value().toInt());
972 // .torrent file size limit
973 if (hasKey(u"torrent_file_size_limit"_s))
974 pref->setTorrentFileSizeLimit(it.value().toLongLong());
975 // Recheck completed torrents
976 if (hasKey(u"recheck_completed_torrents"_s))
977 pref->recheckTorrentsOnCompletion(it.value().toBool());
978 // Customize application instance name
979 if (hasKey(u"app_instance_name"_s))
980 app()->setInstanceName(it.value().toString());
981 // Refresh interval
982 if (hasKey(u"refresh_interval"_s))
983 session->setRefreshInterval(it.value().toInt());
984 // Resolve peer countries
985 if (hasKey(u"resolve_peer_countries"_s))
986 pref->resolvePeerCountries(it.value().toBool());
987 // Reannounce to all trackers when ip/port changed
988 if (hasKey(u"reannounce_when_address_changed"_s))
989 session->setReannounceWhenAddressChangedEnabled(it.value().toBool());
991 // libtorrent preferences
992 // Bdecode depth limit
993 if (hasKey(u"bdecode_depth_limit"_s))
994 pref->setBdecodeDepthLimit(it.value().toInt());
995 // Bdecode token limit
996 if (hasKey(u"bdecode_token_limit"_s))
997 pref->setBdecodeTokenLimit(it.value().toInt());
998 // Async IO threads
999 if (hasKey(u"async_io_threads"_s))
1000 session->setAsyncIOThreads(it.value().toInt());
1001 // Hashing threads
1002 if (hasKey(u"hashing_threads"_s))
1003 session->setHashingThreads(it.value().toInt());
1004 // File pool size
1005 if (hasKey(u"file_pool_size"_s))
1006 session->setFilePoolSize(it.value().toInt());
1007 // Checking Memory Usage
1008 if (hasKey(u"checking_memory_use"_s))
1009 session->setCheckingMemUsage(it.value().toInt());
1010 // Disk write cache
1011 if (hasKey(u"disk_cache"_s))
1012 session->setDiskCacheSize(it.value().toInt());
1013 if (hasKey(u"disk_cache_ttl"_s))
1014 session->setDiskCacheTTL(it.value().toInt());
1015 // Disk queue size
1016 if (hasKey(u"disk_queue_size"_s))
1017 session->setDiskQueueSize(it.value().toLongLong());
1018 // Disk IO Type
1019 if (hasKey(u"disk_io_type"_s))
1020 session->setDiskIOType(static_cast<BitTorrent::DiskIOType>(it.value().toInt()));
1021 // Disk IO read mode
1022 if (hasKey(u"disk_io_read_mode"_s))
1023 session->setDiskIOReadMode(static_cast<BitTorrent::DiskIOReadMode>(it.value().toInt()));
1024 // Disk IO write mode
1025 if (hasKey(u"disk_io_write_mode"_s))
1026 session->setDiskIOWriteMode(static_cast<BitTorrent::DiskIOWriteMode>(it.value().toInt()));
1027 // Coalesce reads & writes
1028 if (hasKey(u"enable_coalesce_read_write"_s))
1029 session->setCoalesceReadWriteEnabled(it.value().toBool());
1030 // Piece extent affinity
1031 if (hasKey(u"enable_piece_extent_affinity"_s))
1032 session->setPieceExtentAffinity(it.value().toBool());
1033 // Suggest mode
1034 if (hasKey(u"enable_upload_suggestions"_s))
1035 session->setSuggestMode(it.value().toBool());
1036 // Send buffer watermark
1037 if (hasKey(u"send_buffer_watermark"_s))
1038 session->setSendBufferWatermark(it.value().toInt());
1039 if (hasKey(u"send_buffer_low_watermark"_s))
1040 session->setSendBufferLowWatermark(it.value().toInt());
1041 if (hasKey(u"send_buffer_watermark_factor"_s))
1042 session->setSendBufferWatermarkFactor(it.value().toInt());
1043 // Outgoing connections per second
1044 if (hasKey(u"connection_speed"_s))
1045 session->setConnectionSpeed(it.value().toInt());
1046 // Socket send buffer size
1047 if (hasKey(u"socket_send_buffer_size"_s))
1048 session->setSocketSendBufferSize(it.value().toInt());
1049 // Socket receive buffer size
1050 if (hasKey(u"socket_receive_buffer_size"_s))
1051 session->setSocketReceiveBufferSize(it.value().toInt());
1052 // Socket listen backlog size
1053 if (hasKey(u"socket_backlog_size"_s))
1054 session->setSocketBacklogSize(it.value().toInt());
1055 // Outgoing ports
1056 if (hasKey(u"outgoing_ports_min"_s))
1057 session->setOutgoingPortsMin(it.value().toInt());
1058 if (hasKey(u"outgoing_ports_max"_s))
1059 session->setOutgoingPortsMax(it.value().toInt());
1060 // UPnP lease duration
1061 if (hasKey(u"upnp_lease_duration"_s))
1062 session->setUPnPLeaseDuration(it.value().toInt());
1063 // Type of service
1064 if (hasKey(u"peer_tos"_s))
1065 session->setPeerToS(it.value().toInt());
1066 // uTP-TCP mixed mode
1067 if (hasKey(u"utp_tcp_mixed_mode"_s))
1068 session->setUtpMixedMode(static_cast<BitTorrent::MixedModeAlgorithm>(it.value().toInt()));
1069 // Support internationalized domain name (IDN)
1070 if (hasKey(u"idn_support_enabled"_s))
1071 session->setIDNSupportEnabled(it.value().toBool());
1072 // Multiple connections per IP
1073 if (hasKey(u"enable_multi_connections_from_same_ip"_s))
1074 session->setMultiConnectionsPerIpEnabled(it.value().toBool());
1075 // Validate HTTPS tracker certificate
1076 if (hasKey(u"validate_https_tracker_certificate"_s))
1077 session->setValidateHTTPSTrackerCertificate(it.value().toBool());
1078 // SSRF mitigation
1079 if (hasKey(u"ssrf_mitigation"_s))
1080 session->setSSRFMitigationEnabled(it.value().toBool());
1081 // Disallow connection to peers on privileged ports
1082 if (hasKey(u"block_peers_on_privileged_ports"_s))
1083 session->setBlockPeersOnPrivilegedPorts(it.value().toBool());
1084 // Embedded tracker
1085 if (hasKey(u"embedded_tracker_port"_s))
1086 pref->setTrackerPort(it.value().toInt());
1087 if (hasKey(u"embedded_tracker_port_forwarding"_s))
1088 pref->setTrackerPortForwardingEnabled(it.value().toBool());
1089 if (hasKey(u"enable_embedded_tracker"_s))
1090 session->setTrackerEnabled(it.value().toBool());
1091 // Mark-of-the-Web
1092 if (hasKey(u"mark_of_the_web"_s))
1093 pref->setMarkOfTheWebEnabled(it.value().toBool());
1094 // Python executable path
1095 if (hasKey(u"python_executable_path"_s))
1096 pref->setPythonExecutablePath(Path(it.value().toString()));
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);