Skip to main content

qbit/models/
application.rs

1use derive_builder::Builder;
2use serde::{Deserialize, Deserializer, Serialize, Serializer};
3use serde_json::Value as JsonValue;
4use serde_repr::{Deserialize_repr, Serialize_repr};
5use std::{collections::HashMap, fmt::Display};
6
7use crate::utilities::{deserializers, serializers};
8
9/// Build info response data object.
10///
11/// Contains version information of software used to run qbittorrent.
12#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq)]
13pub struct BuildInfo {
14    /// QT version
15    pub qt: String,
16    /// libtorrent version
17    pub libtorrent: String,
18    /// Boost version
19    pub boost: String,
20    /// OpenSSL version
21    pub openssl: String,
22    /// Application bitness (e.g. 64-bit)
23    pub bitness: u8,
24}
25
26/// Struct containing information about an individual cookie.
27#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq)]
28pub struct Cookie {
29    /// The name of the cookie.
30    pub name: String,
31    /// The domain associated with the cookie.
32    pub domain: String,
33    /// The path associated with the cookie.
34    pub path: String,
35    /// The value stored in the cookie.
36    pub value: String,
37    /// The expiration date of the cookie, represented as seconds since the Unix epoch.
38    #[serde(rename = "expirationDate")]
39    pub expiration: i64,
40}
41
42/// Preferences response data object.
43// https://github.com/qbittorrent/qBittorrent/blob/master/src/webui/api/appcontroller.cpp
44#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq, Builder)]
45pub struct Preferences {
46    // ======================================
47    // ============== Behavior ==============
48    // ======================================
49    /// Currently selected language (e.g. en_GB for English)
50    pub locale: String,
51
52    /// Log performance warnings as well as everything else.
53    pub performance_warning: bool,
54    /// Should the client external IP be shown in the status bar?
55    pub status_bar_external_ip: bool,
56    /// Show a confirmation message before deleting a torrent. Does not apply to the API
57    pub confirm_torrent_deletion: bool,
58    /// Allow using of sub-categories. Sub-categories are made by adding `/` between the parent and child.
59    // [qBittorrent #23585](https://github.com/qbittorrent/qBittorrent/pull/23585)
60    #[cfg(feature = "qBittorrent-5_1")]
61    pub use_subcategories: bool,
62
63    // ========== File Log Settings ==========
64    /// Enable storing logs to disk
65    pub file_log_enabled: bool,
66    /// The folder to store logs to
67    pub file_log_path: String,
68    /// Enable backing up log files when the file gets too big.
69    pub file_log_backup_enabled: bool,
70    /// How big should the log file be before being backed up (in KiB)
71    pub file_log_max_size: i32,
72    /// Should old logs be deleted?
73    pub file_log_delete_old: bool,
74    /// How old does the log need to be before being auto deleted?
75    /// See `file_log_age_type`
76    pub file_log_age: i32,
77    /// The type of age the log needs to be before being deleted.
78    pub file_log_age_type: FileAge,
79
80    /// To delete content files alongside the torrent. A "cache" setting
81    ///
82    /// NOTE: In the webui, this setting is only visible by checking the icon next to the `Also remove content files`
83    /// checkbox upon deleting a file.
84    pub delete_torrent_content_files: bool,
85
86    // ======================================
87    // ============= Downloads ==============
88    // ======================================
89
90    // ======== When adding a torrent =======
91    /// The default layout of the torrent content.
92    #[serde(
93        deserialize_with = "string_to_content_layout",
94        serialize_with = "content_layout_to_string"
95    )]
96    pub torrent_content_layout: ContentLayout,
97    /// To add new torrents to the top of the queue by default or not?
98    pub add_to_top_of_queue: bool,
99    /// Default setting for allowing new torrents to start automatically.
100    ///
101    /// - True = don't start downloading automatically.
102    /// - False = Start downloading automatically.
103    pub add_stopped_enabled: bool,
104    /// When does the torrent stop
105    #[serde(deserialize_with = "string_to_stop_condition")]
106    #[serde(serialize_with = "stop_condition_to_string")]
107    pub torrent_stop_condition: StopCondition,
108    /// If the torrent exists, do we merge trackers with it or fail to add the torrent altogether?
109    pub merge_trackers: bool,
110    /// When (and should) the `.torrent` file be deleted after added.
111    pub auto_delete_mode: AutoDeleteMode,
112    /// Should disk space be pre-allocated for all files?
113    pub preallocate_all: bool,
114    /// Should `.!qb` be added to incomplete files?
115    pub incomplete_files_ext: bool,
116    /// Should unchecked files be added to the `.unwanted` folder?
117    ///
118    /// See https://github.com/qbittorrent/qBittorrent/issues/13531 for an argument on the subject.
119    pub use_unwanted_folder: bool,
120
121    // ========= Saving Management ==========
122    /// Should `Automatic Torrent Mangament` be enabled for new torrents by default?
123    pub auto_tmm_enabled: bool,
124    /// Should the torrent be relocated or switched to manual mode when category is changed?
125    ///
126    /// True = Relocated, False = Manual Mode
127    pub torrent_changed_tmm_enabled: bool,
128    /// Should the affected torrents be relocated or switched to manual mode when the default save/incomplete path is changed?
129    ///
130    /// True = Relocated, False = Manual Mode
131    pub save_path_changed_tmm_enabled: bool,
132    /// Should the affected torrents be relocated or switched to manual mode when it's category save path has changed?
133    ///
134    /// True = Relocated, False = Manual Mode
135    pub category_changed_tmm_enabled: bool,
136    /// Default save path for torrents
137    pub save_path: String,
138    /// Should another path be used for incomplete torrents?
139    pub temp_path_enabled: bool,
140    /// The path to use for incomplete torrents.
141    pub temp_path: String,
142    /// Use the path specified by the category even if the torrent is in manual mode.
143    pub use_category_paths_in_manual_mode: bool,
144
145    // ========== .torrent files backup management ==========
146    /// Path to copy `.torrent` files to.
147    // [pr 24641](https://github.com/qbittorrent/qBittorrent/pull/24641)
148    #[cfg(not(feature = "qBittorrent-5_3"))]
149    pub export_dir: String,
150    /// Path to copy `.torrent` files of completed downloads to.
151    // [pr 24641](https://github.com/qbittorrent/qBittorrent/pull/24641)
152    #[cfg(not(feature = "qBittorrent-5_3"))]
153    #[serde(rename = "export_dir_fin")]
154    pub export_dir_finished: String,
155    /// Enable backup of `.torrent` files.
156    // [pr 24641](https://github.com/qbittorrent/qBittorrent/pull/24641)
157    #[cfg(feature = "qBittorrent-5_3")]
158    pub torrent_files_backup_enabled: bool,
159    /// Path to backup `.torrent` files to.
160    // [pr 24641](https://github.com/qbittorrent/qBittorrent/pull/24641)
161    #[cfg(feature = "qBittorrent-5_3")]
162    pub torrent_files_backup_dir: String,
163    /// Enable backup of `.torrent` files of completed downloads.
164    // [pr 24641](https://github.com/qbittorrent/qBittorrent/pull/24641)
165    #[cfg(feature = "qBittorrent-5_3")]
166    pub torrent_files_finished_backup_dir_enabled: bool,
167    /// Path to backup `.torrent` files of completed downloads to.
168    // [pr 24641](https://github.com/qbittorrent/qBittorrent/pull/24641)
169    #[cfg(feature = "qBittorrent-5_3")]
170    pub torrent_files_finished_backup_dir: String,
171    /// Remove backup when removing the torrent.
172    // [pr 24641](https://github.com/qbittorrent/qBittorrent/pull/24641)
173    #[cfg(feature = "qBittorrent-5_3")]
174    pub remove_torrent_file_backup: bool,
175
176    /// Directories to scan for `.torrent` files. `ScanDir` enum is used to
177    /// overwrite the default save path of adding torrents.
178    ///
179    /// NOTE: This is marked as deprecated in the qBittorrent source code. It
180    /// might be removed or replaced in future versions.
181    pub scan_dirs: HashMap<String, ScanDir>,
182
183    // ========== Excluded file names ==========
184    /// Is the filename blacklist enabled?
185    pub excluded_file_names_enabled: bool,
186    /// Blacklist filter file names from being downloaded from the torrent.
187    ///
188    /// Files matching any of this list will have the priority set to `Do Not Download` by default. (newline separator)
189    ///
190    /// The follow wildcards can be used:
191    /// - *: Any character
192    /// - ?: Any Single character
193    /// - [...]: Sets of characters
194    #[serde(deserialize_with = "deserializers::string_to_vec_newline_separated")]
195    #[serde(serialize_with = "serializers::vec_to_string_newline_separated")]
196    pub excluded_file_names: Vec<String>,
197
198    // ========== Email Notifications ==========
199    /// Should email notifications be sent after a download is finished?
200    pub mail_notification_enabled: bool,
201    /// e-mail where notifications should originate from
202    ///
203    /// Client default: qBittorrent_notification@example.com
204    pub mail_notification_sender: String,
205    /// e-mail to send notifications to
206    pub mail_notification_email: String,
207    /// smtp server for e-mail notifications
208    pub mail_notification_smtp: String,
209    /// Encryption type to use for SMTP notification emails.
210    // [qBittorrent #23838](https://github.com/qbittorrent/qBittorrent/pull/23838)
211    #[cfg(feature = "qBittorrent-5_3")]
212    pub mail_notification_encryption_type: SMTPEncryptionType,
213    /// Does the smtp server require a secure connection (SSL)?
214    // [qBittorrent #23838](https://github.com/qbittorrent/qBittorrent/pull/23838)
215    #[cfg(not(feature = "qBittorrent-5_3"))]
216    pub mail_notification_ssl_enabled: bool,
217    /// Does the smtp server require authentication?
218    pub mail_notification_auth_enabled: bool,
219    /// Username for smtp authentication
220    pub mail_notification_username: String,
221    /// Password for smtp authentication
222    pub mail_notification_password: String,
223
224    // ========== External Programs ==========
225    /// Should an external program be run after a torrent has been added?
226    pub autorun_on_torrent_added_enabled: bool,
227    /// Program path/name/argumets to run if `autorun_on_torrent_added_enabled` is enabled.
228    ///
229    /// See `autorun_program` for the supported parameters, tips and examples.
230    pub autorun_on_torrent_added_program: String,
231    /// Enables Mark-of-the-web. Tells external programs that this file is potentiall unsafe.
232    /// Should an external program be run after a torrent has completed?
233    pub autorun_enabled: bool,
234    /// Program path/name/arguments to run if `autorun_enabled` is enabled
235    ///
236    /// Supported parameters (case sensitive)
237    /// - %N: Torrent Name
238    /// - %L: Torrent Category
239    /// - %G: Torrent Tags (CSV)
240    /// - %F: Torrent Content Path (same as root path for multi-file torrents)
241    /// - %R: Torrent Root Path (first torrent subdirectory path)
242    /// - %D: Torrent Save Path
243    /// - %C: Number of files in torrent
244    /// - %Z: Torrent Size (bytes)
245    /// - %T: Current Tracker of Torrent
246    /// - %I: Torrent Hash v1
247    /// - %J: Torrent Hash v2
248    /// - %K: Torrent ID
249    ///
250    /// Tip: Encapsulate parameter with quotation marks to avoid text being cut off at whitespace (e.g., "%N")
251    ///
252    /// # Example
253    /// ```sh
254    /// ./path/to/some/program.sh "%N" "%C"
255    /// ```
256    pub autorun_program: String,
257
258    // =====================================
259    // ============ Connection =============
260    // =====================================
261    /// Port for incoming connections
262    pub listen_port: u16,
263    /// Should torrents use SSL connections
264    pub ssl_enabled: bool,
265    /// The port for SSL Torrents to connect to.
266    pub ssl_listen_port: u16,
267    /// True if the port is randomly selected
268    ///
269    /// NOTE: This is marked as deprecated in the src file
270    /// [Github referanse](https://github.com/qbittorrent/qBittorrent/blob/4f94eac235cefa8b83489cb3135dad87fcbed1e3/src/webui/api/appcontroller.cpp#L228)
271    #[deprecated(note = "This field is deprecated upstream; retained here for compatibility.")]
272    pub random_port: bool,
273    /// Is UPnP/NAT-PMP enabled?
274    pub upnp: bool,
275    /// Maximum global number of simultaneous connections
276    ///
277    /// `-1` means disabled
278    #[serde(rename = "max_connec")]
279    pub max_connections: i32,
280    /// Maximum number of simultaneous connections per torrent
281    ///
282    /// `-1` means disabled
283    #[serde(rename = "max_connec_per_torrent")]
284    pub max_connections_per_torrent: i32,
285    /// Maximum number of upload slots
286    ///
287    /// `-1` means disabled
288    pub max_uploads: i32,
289    /// Maximum number of upload slots per torrent
290    ///
291    /// `-1` means disabled
292    pub max_uploads_per_torrent: i32,
293
294    // ============ I2P Settings =============
295    /// Is I2P (Invisible Internet Project) networking enabled?
296    ///
297    /// NOTE: This is experimental!
298    pub i2p_enabled: bool,
299    /// I2P SAM bridge address
300    pub i2p_address: String,
301    /// I2P SAM bridge port
302    pub i2p_port: u16,
303    /// Should I2P mixed mode be enabled? (allows both I2P and regular connections)
304    pub i2p_mixed_mode: bool,
305    /// Number of inbound I2P tunnels to create
306    pub i2p_inbound_quantity: i32,
307    /// Number of outbound I2P tunnels to create
308    pub i2p_outbound_quantity: i32,
309    /// Length of inbound I2P tunnels (number of hops)
310    pub i2p_inbound_length: i32,
311    /// Length of outbound I2P tunnels (number of hops)
312    pub i2p_outbound_length: i32,
313
314    // ========== Proxy Settings ==========
315    /// The protocol to use for the proxy server
316    #[serde(deserialize_with = "string_to_proxy_type")]
317    #[serde(serialize_with = "proxy_type_to_string")]
318    pub proxy_type: ProxyType,
319    /// Proxy IP address or domain name
320    pub proxy_ip: String,
321    /// Proxy port
322    pub proxy_port: u16,
323    /// Does the proxy require authentication?
324    ///
325    /// Note: This does not apply when ProxyType is SOCKS4
326    pub proxy_auth_enabled: bool,
327    /// Username for proxy authentication
328    pub proxy_username: String,
329    /// Password for proxy authentication
330    pub proxy_password: String,
331    /// Should the proxyy be used for Hostname lookup?
332    pub proxy_hostname_lookup: bool,
333    /// Should the proxyy be used for bittorrent purposes?
334    pub proxy_bittorrent: bool,
335    /// Should the proxyy be used for peer and web seed connections?
336    ///
337    /// Note: requires `proxy_bittorrent`
338    pub proxy_peer_connections: bool,
339    /// Should the proxyy be used for RSS purposes?
340    pub proxy_rss: bool,
341    /// Should the proxyy be used for General purposes?
342    pub proxy_misc: bool,
343
344    // ========== IP Filtering ==========
345    /// Should external IPs be filtered?
346    pub ip_filter_enabled: bool,
347    /// Path to IP filter file (.dat, .p2p, .p2b files are supported); path is separated by slashes
348    pub ip_filter_path: String,
349    /// Is the IP filter also applied to trackers?
350    pub ip_filter_trackers: bool,
351    /// List of banned IPs. Separated by new lines (`\n`)
352    #[serde(rename = "banned_IPs")]
353    #[serde(deserialize_with = "deserializers::string_to_vec_newline_separated")]
354    #[serde(serialize_with = "serializers::vec_to_string_newline_separated")]
355    pub banned_ips: Vec<String>,
356
357    // ===================================
358    // ========= Speed Settings ==========
359    // ===================================
360    //
361    // ====== Global Rate Limits =========
362    /// Global download speed limit in KiB/s; 0 means unlimited
363    ///
364    /// Note: Value is in Bytes.
365    pub dl_limit: i32,
366    /// Global upload speed limit in KiB/s; 0 means unlimited
367    ///
368    /// Note: Value is in Bytes.
369    pub up_limit: i32,
370    /// Alternative global download speed limit in KiB/s. 0 means unlimited
371    ///
372    /// Note: Value is in Bytes.
373    pub alt_dl_limit: i32,
374    /// Alternative global upload speed limit in KiB/s. 0 means unlimited
375    ///
376    /// Note: Value is in Bytes.
377    pub alt_up_limit: i32,
378    /// Bittorrent Protocol to use (see list of possible values below)
379    pub bittorrent_protocol: BittorrentProtocol,
380    /// Should `dl_limit` be applied to uTP connections?
381    pub limit_utp_rate: bool,
382    /// Should `dl_limit` be applied to estimated TCP overhead? (e.g. service
383    /// data such as packet headers)
384    pub limit_tcp_overhead: bool,
385    /// Should `dl_limit` be applied to peers on the LAN?
386    pub limit_lan_peers: bool,
387
388    // ========== Scheduling ==========
389    /// Should alternative limits be applied according to the schedule
390    pub scheduler_enabled: bool,
391    /// Scheduler starting hour
392    pub schedule_from_hour: i8,
393    /// Scheduler starting minute
394    pub schedule_from_min: i8,
395    /// Scheduler ending hour
396    pub schedule_to_hour: i8,
397    /// Scheduler ending minute
398    pub schedule_to_min: i8,
399    /// Days on which the schedule is applied.
400    pub scheduler_days: SchedulerTime,
401
402    // ======================================
403    // ======== BitTorrent Settings =========
404    // ======================================
405    //
406    // ========== Privacy Settings ==========
407    // More info (can't work out where to place this): https://www.reddit.com/r/torrents/comments/jmcmx1/comment/gauf8kn/
408    /// Is DHT (Decentrialized Network) enabled?
409    ///
410    /// See https://superuser.com/a/592244 for more info.
411    pub dht: bool,
412    /// Is PeX (Peer Exchange) enabled?
413    pub pex: bool,
414    /// Is LSD (Local Peer Discovery) enabled?
415    pub lsd: bool,
416    /// State of encryption for file transfer.
417    pub encryption: Encryption,
418    /// Is the user anonymous?
419    ///
420    /// WARNING: This doesn't grant enough protection on its own.
421    /// See https://github.com/qbittorrent/qBittorrent/wiki/Anonymous-Mode for more information.
422    pub anonymous_mode: bool,
423
424    // ========== Queue Management ==========
425    /// How many torrents can be actively checking at one time.
426    pub max_active_checking_torrents: i32,
427    /// Is torrent queuing enabled?
428    pub queueing_enabled: bool,
429    /// Maximum number of active simultaneous downloads
430    pub max_active_downloads: i32,
431    /// Maximum number of active simultaneous downloads and uploads
432    pub max_active_torrents: i32,
433    /// Maximum number of active simultaneous uploads
434    pub max_active_uploads: i32,
435    /// If true torrents w/o any activity (stalled ones) will not be counted towards `max_active_*` limits
436    pub dont_count_slow_torrents: bool,
437    /// Download rate in KiB/s for a torrent to be considered "slow"
438    pub slow_torrent_dl_rate_threshold: i32,
439    /// Upload rate in KiB/s for a torrent to be considered "slow"
440    pub slow_torrent_ul_rate_threshold: i32,
441    /// Seconds a torrent should be inactive before considered "slow"
442    pub slow_torrent_inactive_timer: i32,
443
444    // ========== Seed Limits ==========
445    /// Show an action be taken once the torrent ratio is achieved?
446    pub max_ratio_enabled: bool,
447    /// THe ratio to achieve to take an action.
448    pub max_ratio: f64,
449    /// Should an action be taken once the torrent has been seeding for a certain amount of time?
450    pub max_seeding_time_enabled: bool,
451    /// Number of minutes to seed a torrent before an action is taken
452    ///
453    /// -1 = disabled (will also set `max_seeding_time_enabled` to false)
454    pub max_seeding_time: i32,
455    /// Should an action be taken once the torrent has been inactive (during
456    /// seeding) for a certain amount of time?
457    pub max_inactive_seeding_time_enabled: bool,
458    /// Number of minutes for the torrent to be inactive (during seeding) before an action is taken.
459    ///
460    /// -1 = disabled (will also set `max_inactive_seeding_time_enabled` to false)
461    pub max_inactive_seeding_time: i32,
462    /// The mode for share limits.
463    // [qBittorrent #24043](https://github.com/qbittorrent/qBittorrent/pull/24043)
464    #[cfg(feature = "qBittorrent-5_3")]
465    pub share_limits_mode: SeedLimitMode,
466    /// Action performed when a torrent reaches a ratio / seed limit.
467    ///
468    /// See: `max_ratio`, `max_seeding_time` and `max_inactive_seeding_time`
469    ///
470    /// The selected action in `max_ratio_act` is executed when either condition is met:
471    /// - If `max_ratio_enabled` is true and the torrent's ratio reaches or exceeds `max_ratio`.
472    /// - If `max_seeding_time_enabled` is true and the torrent has been seeding for at least `max_seeding_time` minutes.
473    /// - If `max_inactive_seeding_time_enabled` is true and the torrent has been inactive (during seeding) for at least `max_inactive_seeding_time` minutes.
474    ///
475    /// If any are enabled, the action occurs when either condition is satisfied.
476    pub max_ratio_act: SeedLimitActions,
477
478    // ============ Add Tracker  ============
479    /// Enable automatic adding of trackers to new torrents
480    pub add_trackers_enabled: bool,
481    /// List of trackers to add to new torrent. Separated by a new line (`\n`)
482    #[serde(deserialize_with = "deserializers::string_to_vec_newline_separated")]
483    #[serde(serialize_with = "serializers::vec_to_string_newline_separated")]
484    pub add_trackers: Vec<String>,
485    /// Enables automatic adding of trackers (from URL) to a new torrent
486    pub add_trackers_from_url_enabled: bool,
487    /// The URL to get the trackers from
488    pub add_trackers_url: String,
489    /// Read-only list of trackers automatiaclly updated from provided url in `add_trackers_url`.
490    #[serde(deserialize_with = "deserializers::string_to_vec_newline_separated")]
491    #[serde(serialize_with = "serializers::vec_to_string_newline_separated")]
492    pub add_trackers_url_list: Vec<String>,
493
494    // ==================================
495    // ============= Web UI =============
496    // ==================================
497    //
498    // =========== HTTP Server ==========
499    /// Semicolon-separated list of domains to accept when performing Host header validation. Accepts: '*'
500    ///
501    /// Requires: `web_ui_host_header_validation_enabled` to be true.
502    pub web_ui_domain_list: String,
503    /// IP address to use for the WebUI. Accepts: '*'
504    pub web_ui_address: String,
505    /// WebUI port
506    pub web_ui_port: u16,
507    /// Use UPnP for port forwarding from the router
508    pub web_ui_upnp: bool,
509    /// Does the server use HTTPS?
510    pub use_https: bool,
511    /// For API ≥ v2.0.1: Path to SSL certificate
512    ///
513    /// See https://httpd.apache.org/docs/current/ssl/ssl_faq.html#aboutcerts for information on certificates.
514    pub web_ui_https_cert_path: String,
515    /// For API ≥ v2.0.1: Path to SSL keyfile
516    pub web_ui_https_key_path: String,
517
518    // ========== WebUI Authentication ==========
519    /// WebUI username
520    pub web_ui_username: String,
521    /// For API ≥ v2.3.0: Plaintext WebUI password. This field is write-only and cannot be read back.
522    ///
523    /// The password is used exclusively for setting or updating the WebUI password.
524    #[serde(skip_serializing_if = "Option::is_none")] // Needed to acoid overwriting password
525    pub web_ui_password: Option<String>,
526    /// True if authentication challenge for loopback address (127.0.0.1) should be disabled
527    pub bypass_local_auth: bool,
528    /// True if webui authentication should be bypassed for clients whose ip resides within (at least) one of the subnets on the whitelist
529    pub bypass_auth_subnet_whitelist_enabled: bool,
530    /// (White)list of ipv4/ipv6 subnets for which webui authentication should be bypassed;
531    #[serde(deserialize_with = "deserializers::string_to_vec_newline_separated")]
532    #[serde(serialize_with = "serializers::vec_to_string_newline_separated")]
533    pub bypass_auth_subnet_whitelist: Vec<String>,
534    /// Maximum number of authentication failures before WebUI access ban
535    pub web_ui_max_auth_fail_count: i32,
536    /// WebUI access ban duration in seconds
537    pub web_ui_ban_duration: i32,
538    /// Seconds until WebUI is automatically signed off
539    pub web_ui_session_timeout: i32,
540    // TODO: verison, text, feature flag, etc...
541    #[cfg(feature = "qBittorrent-5_3")]
542    // https://github.com/qbittorrent/qBittorrent/pull/24720
543    pub web_ui_sessions_count_limit: i32,
544
545    // ========== API Key ==========
546    /// API key for WebUI authentication
547    // [qBittorrent #23212](https://github.com/qbittorrent/qBittorrent/pull/23212)
548    #[cfg(not(feature = "qBittorrent-5_1"))]
549    pub web_ui_api_key: String,
550
551    // ========== Alternative WebUI ==========
552    /// Should an alternative web ui be used?
553    ///
554    /// NOTE: This is not the same as a theme (`.qbttheme`)
555    pub alternative_webui_enabled: bool,
556    /// File path to the alternative WebUI
557    pub alternative_webui_path: String,
558
559    // ============== Security =============
560    /// True if WebUI clickjacking protection is enabled
561    pub web_ui_clickjacking_protection_enabled: bool,
562    /// True if WebUI CSRF protection is enabled
563    pub web_ui_csrf_protection_enabled: bool,
564    /// True if WebUI cookie Secure flag is enabled (requires `use_https`)
565    pub web_ui_secure_cookie_enabled: bool,
566    /// Is WebUI Host header validated?
567    pub web_ui_host_header_validation_enabled: bool,
568
569    // ========== Custom HTTP Headers ==========
570    /// For API ≥ v2.5.1: Enable custom http headers
571    pub web_ui_use_custom_http_headers_enabled: bool,
572    /// For API ≥ v2.5.1: List of custom http headers.
573    ///
574    /// Format: `Key: Value`.
575    #[serde(deserialize_with = "deserializers::string_to_vec_newline_separated")]
576    #[serde(serialize_with = "serializers::vec_to_string_newline_separated")]
577    pub web_ui_custom_http_headers: Vec<String>, //
578
579    // ========== Reverse Proxy ==========
580    /// Are using reverse proxies allowed?
581    pub web_ui_reverse_proxy_enabled: bool,
582    /// List of trusted proxies to access the webui. Separated by `;`
583    #[serde(deserialize_with = "deserializers::string_to_vec_semicolon_separated")]
584    #[serde(serialize_with = "serializers::vec_to_string_semicolon_separated")]
585    pub web_ui_reverse_proxies_list: Vec<String>,
586
587    // =========== Dynamic DNS ==========
588    /// Should the server DNS be updated dynamically?
589    pub dyndns_enabled: bool,
590    /// The DNS service that is in use.
591    pub dyndns_service: DyndnsService,
592    /// Username for DDNS service
593    pub dyndns_username: String,
594    /// Password for DDNS service
595    pub dyndns_password: String,
596    /// Your DDNS domain name
597    pub dyndns_domain: String,
598
599    // =================================
600    // ========= RSS Settings ==========
601    // =================================
602    /// How long (in minutes) before the feeds are refreshed?
603    pub rss_refresh_interval: i32,
604    /// How long (in seconds) should be waited before a fetch request from the same host?
605    pub rss_fetch_delay: i64,
606    /// Maximum number of articles stored per feed.
607    pub rss_max_articles_per_feed: i32,
608    /// Enable processing of RSS feeds (Also enables fetching them, etc)
609    pub rss_processing_enabled: bool,
610    /// Enable auto-downloading of torrents from the RSS feeds
611    pub rss_auto_downloading_enabled: bool,
612    /// Enable downloading of repack/proper Episodes
613    pub rss_download_repack_proper_episodes: bool,
614    /// List of RSS Smart Episode Filters.
615    #[serde(deserialize_with = "deserializers::string_to_vec_newline_separated")]
616    #[serde(serialize_with = "serializers::vec_to_string_newline_separated")]
617    pub rss_smart_episode_filters: Vec<String>,
618
619    // =================================
620    // ======= Advanced Settings =======
621    // =================================
622    //
623    // ===== Preferences Settings ======
624    /// What type of storage should be used to save the Fastresume files.
625    #[serde(
626        deserialize_with = "string_to_fast_resume_type",
627        serialize_with = "fast_resume_type_to_string"
628    )]
629    pub resume_data_storage_type: FastResumeType,
630    /// What to do with removing torrents.
631    #[serde(
632        deserialize_with = "string_to_torrent_deletion",
633        serialize_with = "torrent_deletion_to_string"
634    )]
635    pub torrent_content_remove_option: TorrentDeletion,
636    /// Memory usage limit of Physical RAM in MiB
637    pub memory_working_set_limit: i32,
638    /// Network Interface used
639    pub current_network_interface: String,
640    /// The name of the network interface used.
641    pub current_interface_name: String,
642    /// IP Address to bind to. Empty String means All addresses
643    pub current_interface_address: String,
644    /// How often the `fastresume` file is saved (in minutes). 0 = disabled
645    pub save_resume_data_interval: i32,
646    /// How often the `statistics` file is saved (in minutes). 0 = disabled
647    pub save_statistics_interval: i32,
648    /// The size limit of `.torrent` files
649    pub torrent_file_size_limit: i64,
650    /// Show a confirmation message before rechecking a torrent. Does not apply to the API
651    pub confirm_torrent_recheck: bool,
652    /// Recheck the torrent upon the torrent being completed.
653    pub recheck_completed_torrents: bool,
654    /// Customise the name of the app instance
655    pub app_instance_name: String,
656    /// How often should the UI refresh to get new updates? (in ms)
657    pub refresh_interval: i32,
658    /// Resolve peer host names
659    // [qBittorrent #23708](https://github.com/qbittorrent/qBittorrent/pull/23708)
660    #[cfg(not(feature = "qBittorrent-5_1"))]
661    pub resolve_peer_host_names: bool,
662    /// True resolves peer countries
663    pub resolve_peer_countries: bool,
664    /// Tells all trackers when either the IP or Port of our client changes.
665    pub reannounce_when_address_changed: bool,
666    /// Enable qbittorrent to become a tracker.
667    ///
668    /// See https://github.com/qbittorrent/qBittorrent/wiki/How-to-use-qBittorrent-as-a-tracker for more information.
669    pub enable_embedded_tracker: bool,
670    /// The port used for the embedded tracker.
671    pub embedded_tracker_port: u16,
672    /// Enables the embedded tracker to use port forwarding.
673    pub embedded_tracker_port_forwarding: bool,
674    ///
675    /// Windows (MOTW) and Mac (quarantine) only
676    pub mark_of_the_web: bool,
677    /// Affects certification validation and non-torrent activities.
678    pub ignore_ssl_errors: bool,
679    /// Python executable path. For use in stuff like search engine plugins which require python.
680    ///
681    /// Will attempt to find and use a system wide one if nothing is specified.
682    pub python_executable_path: String,
683
684    // ===================================
685    // ======= Libtorrent Settings =======
686    // ===================================
687    /// Specify the max number of nested lists/dictionaries in the data structure
688    ///
689    /// See https://www.libtorrent.org/reference-Bdecoding.html#bdecode() for more information
690    pub bdecode_depth_limit: i32,
691    /// The maximum number of tokens to be parsed from the buffer.
692    ///
693    /// See https://www.libtorrent.org/reference-Bdecoding.html#bdecode() for more information
694    pub bdecode_token_limit: i32,
695    /// Number of asynchronous I/O threads
696    pub async_io_threads: i32,
697    /// Number of threads to use for piece hash verification
698    ///
699    /// See https://www.libtorrent.org/reference-Settings.html#hashing_threads for more information.
700    pub hashing_threads: i32,
701    /// The maximum number of files this session will keep open.
702    ///
703    /// See https://www.libtorrent.org/reference-Settings.html#file_pool_size for more information.
704    pub file_pool_size: i32,
705    /// Keep x number of blocks outstanding to allow for faster re-checks at cost of memory.
706    /// Value in MiB.
707    ///
708    /// See https://www.libtorrent.org/reference-Settings.html#checking_mem_usage for more information.
709    pub checking_memory_use: i32,
710    /// Disk cache used in MiB
711    ///
712    /// Only supported in LibTorrent < 2.0
713    pub disk_cache: i32,
714    /// Disk cache expiry interval in seconds
715    ///
716    /// Only supported in LibTorrent < 2.0
717    pub disk_cache_ttl: i32,
718    /// Maximum number of bytes that can wait in the I/O thread queue.
719    ///
720    /// See https://www.libtorrent.org/reference-Settings.html#max_queued_disk_bytes for more information.
721    pub disk_queue_size: i64,
722    /// Configure how libtorrent should perform disk I/O for reading and writing
723    /// torrent data.
724    ///
725    /// See: https://www.libtorrent.org/single-page-ref.html#default-disk-io-constructor
726    pub disk_io_type: DiskIOType,
727    /// Is the OS allowed to cache read data from files?
728    pub disk_io_read_mode: DiskRead,
729    /// Is the OS allowed to cache write data to files?
730    pub disk_io_write_mode: DiskWrite,
731    /// Enable coalesce read/writes
732    ///
733    /// Requires LibTorrent < 2.0.0
734    pub enable_coalesce_read_write: bool,
735    /// Enables LibTorrent `piece_extent_affinity` setting.
736    ///
737    /// See https://libtorrent.org/single-page-ref.html#piece_extent_affinity for more information.
738    pub enable_piece_extent_affinity: bool,
739    /// Enable sending out a message with recent read pieces of a torrent in order to create a bias.
740    ///
741    /// See https://www.libtorrent.org/reference-Settings.html#suggest_mode for more information.
742    pub enable_upload_suggestions: bool,
743    /// Send buffer watermark in KiB. If the send buffer has fewer bytes than this value, another block will be read onto it; setting it too small hurts upload capacity, too large wastes memory.
744    ///
745    /// See https://www.libtorrent.org/reference-Settings.html#send_buffer_watermark for more information
746    pub send_buffer_watermark: i32,
747    /// Send buffer low watermark in KiB. The minimum send buffer target size (includes bytes pending read from disk); for snappy seeding set this high enough to fit a few blocks.
748    ///
749    /// See https://www.libtorrent.org/reference-Settings.html#send_buffer_low_watermark for more information
750    pub send_buffer_low_watermark: i32,
751    /// Send buffer watermark factor in percent. The current upload rate to a peer is multiplied by this percentage to derive the watermark (clamped to send_buffer_watermark); higher values can improve throughput but may waste RAM.
752    ///
753    /// See https://www.libtorrent.org/reference-Settings.html#send_buffer_watermark_factor for more information
754    pub send_buffer_watermark_factor: i64,
755    /// Number of connection attempts made per second.
756    ///
757    /// If number < 0, a default of 200 will be made.
758    pub connection_speed: i32,
759    /// Allow outgoing connections when seeding
760    // [qBittorrent #24158](https://github.com/qbittorrent/qBittorrent/pull/24158)
761    #[cfg(feature = "qBittorrent-5_3")]
762    pub seeding_outgoing_connections: bool,
763    /// Specify the buffer size on receiving peer sockets. 0 = system default.
764    ///
765    /// See https://www.libtorrent.org/reference-Settings.html#send_socket_buffer_size for more information
766    pub socket_send_buffer_size: i32,
767    /// Specify the buffer size on sending peer sockets. 0 = system default.
768    ///
769    /// See https://www.libtorrent.org/reference-Settings.html#send_socket_buffer_size for more information
770    pub socket_receive_buffer_size: i32,
771    /// Number of outstanding incoming connections to queue whilst not actively waiting for one to be accepted
772    ///
773    /// See https://www.libtorrent.org/reference-Settings.html#listen_queue_size for more information
774    pub socket_backlog_size: i32,
775    /// Minimal outgoing port (0: Disabled)
776    ///
777    /// See https://www.libtorrent.org/reference-Settings.html#outgoing_port for more information
778    pub outgoing_ports_min: i32,
779    /// Maximal outgoing port (0: Disabled)
780    ///
781    /// See https://www.libtorrent.org/reference-Settings.html#outgoing_port for more information
782    pub outgoing_ports_max: i32,
783    /// upnp lease duration specified in seconds (0: Permanent lease)
784    ///
785    /// See https://www.libtorrent.org/reference-Settings.html#upnp_lease_duration for more information
786    pub upnp_lease_duration: i32,
787    /// Determinds the DSCP field in the IP header
788    ///
789    /// See https://www.libtorrent.org/reference-Settings.html#peer_dscp for more information
790    #[serde(rename = "peer_tos")]
791    pub peer_dscp: i32,
792    /// μTP-TCP mixed mode algorithm (see list of possible values below)
793    pub utp_tcp_mixed_mode: UtpTcpMixedMode,
794    /// Hostname resolver cache TTL
795    // [qBittorrent #24158](https://github.com/qbittorrent/qBittorrent/pull/24158)
796    #[cfg(not(feature = "qBittorrent-5_1"))]
797    pub hostname_cache_ttl: i32,
798    /// Allows trackers/web seeds with an internationalised domain name.
799    ///
800    /// See https://www.libtorrent.org/reference-Settings.html#allow_idna for more information.
801    pub idn_support_enabled: bool,
802    /// Allows multiple connections from the same IP address.
803    ///
804    /// See https://www.libtorrent.org/reference-Settings.html#allow_multiple_connections_per_ip for more information.
805    pub enable_multi_connections_from_same_ip: bool,
806    // TODO: verison, text, feature flag, etc...
807    #[cfg(feature = "qBittorrent-5_3")]
808    // https://github.com/qbittorrent/qBittorrent/pull/24684
809    pub enable_multi_connections_from_same_peer_id: bool,
810    /// Makes the certificate of trackers and web seeds validated against the system certificate.
811    ///
812    /// See https://www.libtorrent.org/reference-Settings.html#validate_https_trackers for more information.
813    pub validate_https_tracker_certificate: bool,
814    /// Should Server-side request forgery (SSRF) be mitigated?
815    pub ssrf_mitigation: bool,
816    /// Don't make network requests to peers who ports are < 1024
817    ///
818    /// See https://libtorrent.org/single-page-ref.html#no_connect_privileged_ports for more information
819    pub block_peers_on_privileged_ports: bool,
820    /// Specify which algorithm to use to determine how many peers to unchoke.
821    ///
822    /// See https://www.libtorrent.org/reference-Settings.html#choking_algorithm for more information
823    pub upload_slots_behavior: UploadSlotsBehavior,
824    /// Controls the bahviour of unchocking. How peers are selected
825    ///
826    /// Read more: https://transfercloud.io/blog/2024/02/26/what-is-torrent-chokin/
827    pub upload_choking_algorithm: UploadChokingAlgorithm,
828    /// Always announce to all trackers in a tier.
829    ///
830    /// See https://www.libtorrent.org/reference-Settings.html#announce_to_all_trackers for more information
831    pub announce_to_all_trackers: bool,
832    /// Always announce to all tiers.
833    ///
834    /// See https://www.libtorrent.org/reference-Settings.html#announce_to_all_tiers for more information
835    pub announce_to_all_tiers: bool,
836    /// The IP address passed along to trackers. Requires qbittorrent restart
837    ///
838    /// More information: https://www.libtorrent.org/reference-Settings.html#announce_ip
839    pub announce_ip: String,
840    /// The port reported to trackers. 0 uses `listening_port`.
841    pub announce_port: u16,
842    /// Limits the number of concurrent HTTP tracker announces.
843    ///
844    /// See https://www.libtorrent.org/reference-Settings.html#max_concurrent_http_announces for more information.
845    pub max_concurrent_http_announces: i32,
846    /// Timeout in seconds for a stopped announce request to trackers
847    ///
848    /// If the value is set to 0, the connections to trackers with the stopped event are suppressed.
849    pub stop_tracker_timeout: i32,
850    /// Percentage of peers to disconnect every turnover.
851    ///
852    /// See https://www.libtorrent.org/reference-Settings.html#peer_turnover for more information.
853    pub peer_turnover: i32,
854    /// The limit of the maximum limit before turnover starts
855    ///
856    /// See https://www.libtorrent.org/reference-Settings.html#peer_turnover for more information.
857    pub peer_turnover_cutoff: i32,
858    /// How often the turnover occurs
859    ///
860    /// See https://www.libtorrent.org/reference-Settings.html#peer_turnover for more information.
861    pub peer_turnover_interval: i32,
862    /// Maximum number of outstanding requests to send to a peer.
863    ///
864    /// See ttps://www.libtorrent.org/reference-Settings.html#max_out_request_queue for more information.
865    pub request_queue_size: i32,
866    /// CSV of IP port-pairs added to the DHT Node if enabled
867    ///
868    /// See https://www.libtorrent.org/reference-Settings.html#dht_bootstrap_nodes for more information
869    pub dht_bootstrap_nodes: String,
870}
871
872/// Whether the `.torrent` file should be deleted after the torrent is added.
873#[repr(u8)]
874#[derive(Debug, Serialize_repr, Deserialize_repr, Clone, Default, PartialEq)]
875pub enum AutoDeleteMode {
876    /// Never delete the `.torrent` file.
877    #[default]
878    Never = 0,
879    /// Only delete the `.torrent` file if the torrent is added.
880    IfAdded = 1,
881    /// Always delete the `.torrent` file.
882    Always = 2,
883}
884
885/// The encryption type to use for SMTP notifications.
886// [qBittorrent #23838](https://github.com/qbittorrent/qBittorrent/pull/23838)
887#[cfg(feature = "qBittorrent-5_3")]
888#[repr(u8)]
889#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
890pub enum SMTPEncryptionType {
891    None = 0,
892    STARTTLS = 1,
893    #[default]
894    SMTPS = 2,
895}
896
897/// The mode for share limits.
898// [qBittorrent #24043](https://github.com/qbittorrent/qBittorrent/pull/24043)
899#[cfg(feature = "qBittorrent-5_3")]
900#[repr(i8)]
901#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
902pub enum SeedLimitMode {
903    /// Use the default mode
904    #[default]
905    Default = -1, // special value
906
907    /// Match any of the share limits
908    MatchAny = 0,
909    /// Match all of the share limits
910    MatchAll = 1,
911}
912
913/// What action should be taken when the seeding limit is reached?
914#[repr(i8)]
915#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
916pub enum SeedLimitActions {
917    /// Use the default action
918    #[default]
919    Default = -1, // special value
920    /// Stop the torrent upon the limit being reached
921    StopTorrent = 0,
922    /// Remove the torrent upon the limit being reached
923    RemoveTorrent = 1,
924    /// Remove the torrent and files upon the limit being reached
925    RemoveTorrentFiles = 2,
926    /// Make the torrent use the super seeding algorithm upon the limit being reached.
927    TorrentSuperSeeding = 3,
928}
929
930/// Bittorrent protocols
931#[repr(u8)]
932#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
933pub enum BittorrentProtocol {
934    /// To use both TCP and UTP
935    TcpUtp = 0,
936    #[default]
937    /// To just use TCP
938    Tcp = 1,
939    /// To just use UTP
940    Utp = 2,
941}
942
943/// Days on which the alternative speed limit schedule is applied.
944#[repr(u8)]
945#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
946pub enum SchedulerTime {
947    /// Every day
948    #[default]
949    Day = 0,
950    /// Every Weekday
951    Weekday = 1,
952    /// Every Weekend
953    Weekend = 2,
954    /// Every Monday
955    Monday = 3,
956    /// Every Tuesday
957    Tuesday = 4,
958    /// Every Wednesday
959    Wednesday = 5,
960    /// Every Thursday
961    Thursday = 6,
962    /// Every Friday
963    Friday = 7,
964    /// Every Saturday
965    Saturday = 8,
966    /// Every Sunday
967    Sunday = 9,
968}
969
970/// Encryption states
971#[repr(u8)]
972#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
973pub enum Encryption {
974    #[default]
975    /// Allows encryption for file transfer.
976    Allow = 0,
977    /// Requires encryption for file transfer.
978    Require = 1,
979    /// Disables encryption for file transfer.
980    Disable = 2,
981}
982
983/// Dyndns servcice types
984#[repr(i8)]
985#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
986pub enum DyndnsService {
987    /// No dynamic DNS service is selected.
988    None = -1,
989    #[default]
990    /// Uses DYN: https://account.dyn.com/
991    Dydns = 0,
992    /// Uses NO-IP: https://www.noip.com/
993    Noip = 1,
994}
995
996/// Upload choking algorithm
997#[repr(u8)]
998#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
999pub enum UploadChokingAlgorithm {
1000    #[default]
1001    /// Rotate unchoked peers in a round-robin fashion, giving each peer a fair chance to upload.
1002    RoundRobin = 0,
1003    /// Prefer peers that currently offer the fastest upload throughput to maximise overall upload performance.
1004    FastestUpload = 1,
1005    /// Use anti-leech heuristics to deprioritize peers that do not contribute, favouring peers that upload data back.
1006    AntiLeech = 2,
1007}
1008
1009/// Algorithm to use for unchoking peers.
1010#[repr(u8)]
1011#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
1012pub enum UploadSlotsBehavior {
1013    #[default]
1014    /// Unchokes a fixed amount of seeders
1015    Fixed = 0,
1016    /// Opens up slots based on the upload rate achieved to peers.
1017    UploadRate = 1,
1018}
1019
1020/// μTP / TCP mixed-mode algorithm selection.
1021///
1022/// This setting controls how the client mixes uTP and TCP connections when both
1023/// protocols are available. It determines the preference or distribution of
1024/// connection attempts between the two transport protocols.
1025#[repr(u8)]
1026#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
1027pub enum UtpTcpMixedMode {
1028    /// Prefer TCP connections when both TCP and uTP are available.
1029    ///
1030    /// When this mode is selected, the client will favour establishing TCP
1031    /// connections over uTP ones whenever possible.
1032    #[default]
1033    PreferTcp = 0,
1034    /// Distribute connections proportionally based on peer capabilities.
1035    ///
1036    /// In this mode the client attempts to balance or proportion connections
1037    /// between TCP and uTP according to peer availability and characteristics,
1038    /// rather than strictly preferring one protocol.
1039    PeerProportional = 1,
1040}
1041
1042/// Is the OS allowed to cache read data from files?
1043///
1044/// See https://www.libtorrent.org/reference-Settings.html#disk_io_read_mode for more information.
1045#[repr(u8)]
1046#[derive(
1047    Debug, Default, Serialize_repr, Deserialize_repr, PartialEq, Eq, PartialOrd, Ord, Clone,
1048)]
1049pub enum DiskRead {
1050    /// Don't Allow the OS to cache read data.
1051    Disable = 0,
1052    /// Allow the OS to cache read data.
1053    #[default]
1054    Enable = 1,
1055}
1056
1057/// Is the OS allowed to cache write data to files?
1058///
1059/// See https://www.libtorrent.org/reference-Settings.html#disk_io_write_mode for more information.
1060#[repr(u8)]
1061#[derive(
1062    Debug, Default, Serialize_repr, Deserialize_repr, PartialEq, Eq, PartialOrd, Ord, Clone,
1063)]
1064pub enum DiskWrite {
1065    /// Don't Allow the OS to cache write data.
1066    Disable = 0,
1067    /// Allow the OS to cache write data.
1068    #[default]
1069    Enable = 1,
1070    /// FLushes pieces to disk as they complete validation.
1071    WriteThrough = 2,
1072}
1073
1074/// Disk I/O constructor selection.
1075///
1076/// See: https://www.libtorrent.org/single-page-ref.html#default-disk-io-constructor
1077///
1078/// Enum values sourced from VueTorrent. Choose how libtorrent should perform
1079/// disk I/O for reading and writing torrent data.
1080#[repr(u8)]
1081#[derive(
1082    Debug, Default, Serialize_repr, Deserialize_repr, PartialEq, Eq, PartialOrd, Ord, Clone,
1083)]
1084pub enum DiskIOType {
1085    /// Use the library's default behaviour: memory-mapped I/O when available,
1086    /// otherwise fall back to POSIX-based I/O.
1087    #[default]
1088    Default = 0,
1089    /// Use memory-mapped files (mmap) for disk I/O. This can improve performance
1090    /// by mapping file contents directly into memory.
1091    MemoryMappedFiles = 1,
1092    /// Use POSIX-compliant file I/O methods. This variant selects a POSIX-style
1093    /// approach (e.g., pread/pwrite semantics) for compatibility on POSIX systems.
1094    PosixComplaint = 2,
1095    /// Use single pread/pwrite operations for reads and writes.
1096    /// This is a more basic I/O method that performs single-shot read/write calls.
1097    SinglePReadWrite = 3,
1098    /// Use pread/pwrite operations for reads and writes.
1099    PreadPwrite = 4,
1100}
1101
1102/// The type of age
1103#[repr(i8)]
1104#[derive(
1105    Debug, Default, Serialize_repr, Deserialize_repr, PartialEq, Eq, PartialOrd, Ord, Clone,
1106)]
1107pub enum FileAge {
1108    /// After X days
1109    Day = 0,
1110    /// After X months
1111    #[default]
1112    Month = 1,
1113    /// After X years
1114    Year = 2,
1115}
1116
1117/// How the torrent content is laied out.
1118#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq)]
1119pub enum ContentLayout {
1120    /// Does whatever the client says to do, which by default is Subfolder
1121    #[default]
1122    Original,
1123    /// In cases of batches, will create a separate subfolder automatically of the batch name.
1124    /// Example: `Save_path/Torrent_name/Torrent_files`
1125    Subfolder,
1126    /// In cases of batches, will just place them all in the save_path.
1127    /// Example: `Save_path/Torrent_files`
1128    NoSubfolder,
1129}
1130
1131impl std::fmt::Display for ContentLayout {
1132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1133        match self {
1134            ContentLayout::Original => write!(f, "Original"),
1135            ContentLayout::Subfolder => write!(f, "Subfolder"),
1136            ContentLayout::NoSubfolder => write!(f, "NoSubfolder"),
1137        }
1138    }
1139}
1140
1141pub fn string_to_content_layout<'de, D>(deserializer: D) -> Result<ContentLayout, D::Error>
1142where
1143    D: serde::Deserializer<'de>,
1144{
1145    let v = JsonValue::deserialize(deserializer)?;
1146
1147    match v {
1148        JsonValue::String(s) => match s.as_str() {
1149            "Original" => Ok(ContentLayout::Original),
1150            "Subfolder" => Ok(ContentLayout::Subfolder),
1151            "NoSubfolder" => Ok(ContentLayout::NoSubfolder),
1152            _ => Err(serde::de::Error::custom(format!(
1153                "invalid content layout: {}",
1154                s
1155            ))),
1156        },
1157        _ => Err(serde::de::Error::custom(format!(
1158            "unexpected type for content layout: {:?}",
1159            v
1160        ))),
1161    }
1162}
1163
1164pub fn option_string_to_content_layout<'de, D>(
1165    deserializer: D,
1166) -> Result<Option<ContentLayout>, D::Error>
1167where
1168    D: serde::Deserializer<'de>,
1169{
1170    let v = JsonValue::deserialize(deserializer)?;
1171
1172    match v {
1173        JsonValue::Null => Ok(None),
1174        JsonValue::String(s) => match s.as_str() {
1175            "" => Ok(None),
1176            "Original" => Ok(Some(ContentLayout::Original)),
1177            "Subfolder" => Ok(Some(ContentLayout::Subfolder)),
1178            "NoSubfolder" => Ok(Some(ContentLayout::NoSubfolder)),
1179            _ => Err(serde::de::Error::custom(format!(
1180                "invalid content layout: {}",
1181                s
1182            ))),
1183        },
1184        _ => Err(serde::de::Error::custom(format!(
1185            "unexpected type for content layout: {:?}",
1186            v
1187        ))),
1188    }
1189}
1190
1191pub fn content_layout_to_string<S>(value: &ContentLayout, serializer: S) -> Result<S::Ok, S::Error>
1192where
1193    S: serde::Serializer,
1194{
1195    serializer.serialize_str(&value.to_string())
1196}
1197
1198pub fn option_content_layout_to_string<S>(
1199    value: &Option<ContentLayout>,
1200    serializer: S,
1201) -> Result<S::Ok, S::Error>
1202where
1203    S: serde::Serializer,
1204{
1205    match value {
1206        Some(layout) => serializer.serialize_str(&layout.to_string()),
1207        None => serializer.serialize_str(""),
1208    }
1209}
1210
1211/// When does the torrent stop
1212#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
1213pub enum StopCondition {
1214    /// Don't stop and go straight to downloading
1215    #[default]
1216    None,
1217    /// Stop after receiving the metadata
1218    MetadataReceived,
1219    /// Stop after checking the files.
1220    FilesChecked,
1221}
1222
1223impl std::fmt::Display for StopCondition {
1224    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1225        match self {
1226            StopCondition::None => write!(f, "None"),
1227            StopCondition::MetadataReceived => write!(f, "MetadataReceived"),
1228            StopCondition::FilesChecked => write!(f, "FilesChecked"),
1229        }
1230    }
1231}
1232
1233pub fn string_to_stop_condition<'de, D>(deserializer: D) -> Result<StopCondition, D::Error>
1234where
1235    D: serde::Deserializer<'de>,
1236{
1237    let v = JsonValue::deserialize(deserializer)?;
1238
1239    match v {
1240        JsonValue::String(s) => match s.as_str() {
1241            "None" => Ok(StopCondition::None),
1242            "MetadataReceived" => Ok(StopCondition::MetadataReceived),
1243            "FilesChecked" => Ok(StopCondition::FilesChecked),
1244            _ => Err(serde::de::Error::custom(format!(
1245                "invalid stop condition: {}",
1246                s
1247            ))),
1248        },
1249        _ => Err(serde::de::Error::custom(format!(
1250            "unexpected type for stop condition: {:?}",
1251            v
1252        ))),
1253    }
1254}
1255
1256pub fn option_string_to_stop_condition<'de, D>(
1257    deserializer: D,
1258) -> Result<Option<StopCondition>, D::Error>
1259where
1260    D: serde::Deserializer<'de>,
1261{
1262    let v = JsonValue::deserialize(deserializer)?;
1263
1264    match v {
1265        JsonValue::Null => Ok(None),
1266        JsonValue::String(s) => match s.as_str() {
1267            "None" => Ok(Some(StopCondition::None)),
1268            "MetadataReceived" => Ok(Some(StopCondition::MetadataReceived)),
1269            "FilesChecked" => Ok(Some(StopCondition::FilesChecked)),
1270            _ => Err(serde::de::Error::custom(format!(
1271                "invalid stop condition: {}",
1272                s
1273            ))),
1274        },
1275        _ => Err(serde::de::Error::custom(format!(
1276            "unexpected type for stop condition: {:?}",
1277            v
1278        ))),
1279    }
1280}
1281
1282pub fn stop_condition_to_string<S>(value: &StopCondition, serializer: S) -> Result<S::Ok, S::Error>
1283where
1284    S: serde::Serializer,
1285{
1286    serializer.serialize_str(&value.to_string())
1287}
1288
1289pub fn option_stop_condition_to_string<S>(
1290    value: &Option<StopCondition>,
1291    serializer: S,
1292) -> Result<S::Ok, S::Error>
1293where
1294    S: serde::Serializer,
1295{
1296    match value {
1297        Some(condition) => stop_condition_to_string(condition, serializer),
1298        None => serializer.serialize_none(),
1299    }
1300}
1301
1302/// What to do when removing content files upon removing a torrent.
1303#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
1304pub enum TorrentDeletion {
1305    /// Erase from disk permanatly
1306    #[default]
1307    Delete,
1308    /// Attempts to move to Trash/Wastebin if possible.
1309    MoveToTrash,
1310}
1311
1312impl std::fmt::Display for TorrentDeletion {
1313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1314        match self {
1315            Self::Delete => write!(f, "Delete"),
1316            Self::MoveToTrash => write!(f, "MoveToTrash"),
1317        }
1318    }
1319}
1320
1321pub fn string_to_torrent_deletion<'de, D>(deserializer: D) -> Result<TorrentDeletion, D::Error>
1322where
1323    D: serde::Deserializer<'de>,
1324{
1325    let v = JsonValue::deserialize(deserializer)?;
1326
1327    match v {
1328        JsonValue::String(s) => match s.as_str() {
1329            "Delete" => Ok(TorrentDeletion::Delete),
1330            "MoveToTrash" => Ok(TorrentDeletion::MoveToTrash),
1331            _ => Err(serde::de::Error::custom(format!(
1332                "invalid torrent deletion: {}",
1333                s
1334            ))),
1335        },
1336        _ => Err(serde::de::Error::custom(format!(
1337            "unexpected type for torrent deletion: {:?}",
1338            v
1339        ))),
1340    }
1341}
1342
1343pub fn string_to_option_torrent_deletion<'de, D>(
1344    deserializer: D,
1345) -> Result<Option<TorrentDeletion>, D::Error>
1346where
1347    D: serde::Deserializer<'de>,
1348{
1349    let v = JsonValue::deserialize(deserializer)?;
1350
1351    match v {
1352        JsonValue::String(s) => match s.as_str() {
1353            "Delete" => Ok(Some(TorrentDeletion::Delete)),
1354            "MoveToTrash" => Ok(Some(TorrentDeletion::MoveToTrash)),
1355            _ => Err(serde::de::Error::custom(format!(
1356                "invalid torrent deletion: {}",
1357                s
1358            ))),
1359        },
1360        JsonValue::Null => Ok(None),
1361        _ => Err(serde::de::Error::custom(format!(
1362            "unexpected type for torrent deletion: {:?}",
1363            v
1364        ))),
1365    }
1366}
1367
1368pub fn torrent_deletion_to_string<S>(
1369    value: &TorrentDeletion,
1370    serializer: S,
1371) -> Result<S::Ok, S::Error>
1372where
1373    S: serde::Serializer,
1374{
1375    serializer.serialize_str(&value.to_string())
1376}
1377
1378pub fn option_torrent_deletion_to_string<S>(
1379    value: &Option<TorrentDeletion>,
1380    serializer: S,
1381) -> Result<S::Ok, S::Error>
1382where
1383    S: serde::Serializer,
1384{
1385    match value {
1386        Some(v) => torrent_deletion_to_string(v, serializer),
1387        None => serializer.serialize_none(),
1388    }
1389}
1390
1391/// Where to save the torrent if it's appears in the specified folder.
1392#[derive(Debug, Clone, Default, PartialEq)]
1393pub enum ScanDir {
1394    /// The folder that is monitored.
1395    MonitoredFolder,
1396    /// The default save path according to client settings.
1397    #[default]
1398    DefaultSavePath,
1399    /// A user-specified path.
1400    OtherPath(String),
1401}
1402
1403impl<'de> Deserialize<'de> for ScanDir {
1404    fn deserialize<D>(deserializer: D) -> Result<ScanDir, D::Error>
1405    where
1406        D: Deserializer<'de>,
1407    {
1408        #[derive(Deserialize)]
1409        #[serde(untagged)]
1410        enum Helper {
1411            Int(u8),
1412            Str(String),
1413        }
1414
1415        match Helper::deserialize(deserializer)? {
1416            Helper::Int(0) => Ok(ScanDir::MonitoredFolder),
1417            Helper::Int(1) => Ok(ScanDir::DefaultSavePath),
1418            Helper::Str(s) => Ok(ScanDir::OtherPath(s)),
1419            Helper::Int(x) => Err(serde::de::Error::custom(format!(
1420                "unexpected value, expected 0, 1, or a string (path): {}",
1421                x
1422            ))),
1423        }
1424    }
1425}
1426
1427impl Serialize for ScanDir {
1428    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1429    where
1430        S: Serializer,
1431    {
1432        match self {
1433            ScanDir::MonitoredFolder => serializer.serialize_i8(0),
1434            ScanDir::DefaultSavePath => serializer.serialize_i8(1),
1435            ScanDir::OtherPath(s) => serializer.serialize_str(s),
1436        }
1437    }
1438}
1439
1440/// The proxy protocol to use.
1441#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1442pub enum ProxyType {
1443    /// Use no proxy at all
1444    #[default]
1445    None,
1446    /// Use HTTP Protocol
1447    Http,
1448    /// Use SOCKS5 protocol
1449    Socks5,
1450    /// Use SOCKS4 protocol
1451    Socks4,
1452}
1453
1454impl std::fmt::Display for ProxyType {
1455    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1456        write!(
1457            f,
1458            "{}",
1459            match self {
1460                ProxyType::None => "None",
1461                ProxyType::Http => "HTTP",
1462                ProxyType::Socks5 => "SOCKS5",
1463                ProxyType::Socks4 => "SOCKS4",
1464            }
1465        )
1466    }
1467}
1468
1469pub fn string_to_proxy_type<'de, D>(deserializer: D) -> Result<ProxyType, D::Error>
1470where
1471    D: serde::Deserializer<'de>,
1472{
1473    let v = JsonValue::deserialize(deserializer)?;
1474
1475    match v {
1476        JsonValue::String(s) => match s.as_str() {
1477            "None" => Ok(ProxyType::None),
1478            "HTTP" => Ok(ProxyType::Http),
1479            "SOCKS5" => Ok(ProxyType::Socks5),
1480            "SOCKS4" => Ok(ProxyType::Socks4),
1481            _ => Err(serde::de::Error::custom(format!(
1482                "invalid proxy type: {}",
1483                s
1484            ))),
1485        },
1486        _ => Err(serde::de::Error::custom(format!(
1487            "unexpected type for proxy type: {:?}",
1488            v
1489        ))),
1490    }
1491}
1492
1493pub fn string_to_option_proxy_type<'de, D>(deserializer: D) -> Result<Option<ProxyType>, D::Error>
1494where
1495    D: serde::Deserializer<'de>,
1496{
1497    let v = JsonValue::deserialize(deserializer)?;
1498
1499    match v {
1500        JsonValue::Null => Ok(None),
1501        JsonValue::String(s) => match s.as_str() {
1502            "None" => Ok(Some(ProxyType::None)),
1503            "HTTP" => Ok(Some(ProxyType::Http)),
1504            "SOCKS5" => Ok(Some(ProxyType::Socks5)),
1505            "SOCKS4" => Ok(Some(ProxyType::Socks4)),
1506            _ => Err(serde::de::Error::custom(format!(
1507                "invalid proxy type: {}",
1508                s
1509            ))),
1510        },
1511        _ => Err(serde::de::Error::custom(format!(
1512            "unexpected type for proxy type: {:?}",
1513            v
1514        ))),
1515    }
1516}
1517
1518pub fn proxy_type_to_string<S>(value: &ProxyType, serializer: S) -> Result<S::Ok, S::Error>
1519where
1520    S: serde::Serializer,
1521{
1522    serializer.serialize_str(&value.to_string())
1523}
1524
1525pub fn option_proxy_type_to_string<S>(
1526    value: &Option<ProxyType>,
1527    serializer: S,
1528) -> Result<S::Ok, S::Error>
1529where
1530    S: serde::Serializer,
1531{
1532    match value {
1533        Some(v) => proxy_type_to_string(v, serializer),
1534        None => serializer.serialize_none(),
1535    }
1536}
1537
1538/// The type of results to get back whilst doing `get_directory_contents`
1539///
1540/// Hidden files are not included.
1541#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
1542pub enum DirMode {
1543    /// Only return directories
1544    Dirs,
1545    /// Only return files
1546    Files,
1547    /// Returns everything
1548    #[default]
1549    All,
1550}
1551
1552impl Display for DirMode {
1553    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1554        write!(
1555            f,
1556            "{}",
1557            match self {
1558                DirMode::Dirs => "dirs",
1559                DirMode::Files => "files",
1560                DirMode::All => "all",
1561            }
1562        )
1563    }
1564}
1565
1566pub fn deserialize_dir_mode<'de, D>(deserializer: D) -> Result<DirMode, D::Error>
1567where
1568    D: serde::Deserializer<'de>,
1569{
1570    let v = JsonValue::deserialize(deserializer)?;
1571
1572    match v {
1573        JsonValue::Number(n) => {
1574            let n = n.as_i64().unwrap_or(2);
1575            match n {
1576                0 => Ok(DirMode::Dirs),
1577                1 => Ok(DirMode::Files),
1578                2 => Ok(DirMode::All),
1579                _ => Err(serde::de::Error::custom(format!(
1580                    "invalid dir mode number: {}",
1581                    n
1582                ))),
1583            }
1584        }
1585        _ => Err(serde::de::Error::custom(format!(
1586            "unexpected type for dir mode: {:?}",
1587            v
1588        ))),
1589    }
1590}
1591
1592/// The file structure to use for the fastresume file.
1593#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone)]
1594pub enum FastResumeType {
1595    /// Use the "legacy" file format
1596    #[default]
1597    Files,
1598    /// Use the experimental SQLite Database format.
1599    SQLite,
1600}
1601
1602impl std::fmt::Display for FastResumeType {
1603    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1604        write!(
1605            f,
1606            "{}",
1607            match self {
1608                Self::Files => "Legacy",
1609                Self::SQLite => "SQLite",
1610            }
1611        )
1612    }
1613}
1614
1615pub fn string_to_fast_resume_type<'de, D>(deserializer: D) -> Result<FastResumeType, D::Error>
1616where
1617    D: serde::Deserializer<'de>,
1618{
1619    let v = JsonValue::deserialize(deserializer)?;
1620
1621    match v {
1622        JsonValue::String(s) => match s.as_str() {
1623            "Legacy" => Ok(FastResumeType::Files),
1624            "SQLite" => Ok(FastResumeType::SQLite),
1625            _ => Err(serde::de::Error::custom(format!(
1626                "invalid fast resume type: {}",
1627                s
1628            ))),
1629        },
1630        _ => Err(serde::de::Error::custom(format!(
1631            "unexpected type for fast resume type: {:?}",
1632            v
1633        ))),
1634    }
1635}
1636pub fn string_to_option_fast_resume_type<'de, D>(
1637    deserializer: D,
1638) -> Result<Option<FastResumeType>, D::Error>
1639where
1640    D: serde::Deserializer<'de>,
1641{
1642    let v = JsonValue::deserialize(deserializer)?;
1643
1644    match v {
1645        JsonValue::Null => Ok(None),
1646        JsonValue::String(s) => match s.as_str() {
1647            "" => Ok(None),
1648            "Legacy" => Ok(Some(FastResumeType::Files)),
1649            "SQLite" => Ok(Some(FastResumeType::SQLite)),
1650            _ => Err(serde::de::Error::custom(format!(
1651                "invalid fast resume type: {}",
1652                s
1653            ))),
1654        },
1655        _ => Err(serde::de::Error::custom(format!(
1656            "unexpected type for fast resume type: {:?}",
1657            v
1658        ))),
1659    }
1660}
1661
1662pub fn fast_resume_type_to_string<S>(
1663    value: &FastResumeType,
1664    serializer: S,
1665) -> Result<S::Ok, S::Error>
1666where
1667    S: serde::Serializer,
1668{
1669    serializer.serialize_str(&value.to_string())
1670}
1671
1672pub fn option_fast_resume_type_to_string<S>(
1673    value: &Option<FastResumeType>,
1674    serializer: S,
1675) -> Result<S::Ok, S::Error>
1676where
1677    S: serde::Serializer,
1678{
1679    match value {
1680        Some(v) => fast_resume_type_to_string(v, serializer),
1681        None => serializer.serialize_none(),
1682    }
1683}