use std::{
collections::HashMap,
fmt::{self, Debug},
ops::Deref,
};
use serde::{
Deserialize, Deserializer, Serialize,
de::{MapAccess, Visitor},
};
use serde_repr::{Deserialize_repr, Serialize_repr};
#[cfg(not(feature = "qBittorrent-5_1"))]
use crate::models::ShareLimitAction;
#[cfg(feature = "qBittorrent-5_3")]
use crate::models::ShareLimitMode;
use crate::utilities::deserializers;
use crate::utilities::serializers;
#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq)]
pub struct Torrent {
pub hash: String,
pub infohash_v1: String,
pub infohash_v2: String,
pub name: String,
pub has_metadata: bool,
#[cfg(not(feature = "qBittorrent-5_1"))]
pub created_by: String,
#[cfg(not(feature = "qBittorrent-5_1"))]
pub creation_date: i64,
pub private: Option<bool>,
pub total_size: i64,
#[cfg(not(feature = "qBittorrent-5_1"))]
#[serde(rename = "pieces_num")]
pub pieces_count: i32,
#[cfg(not(feature = "qBittorrent-5_1"))]
pub piece_size: i64,
pub magnet_uri: String,
pub size: i64,
pub progress: f64,
#[cfg(not(feature = "qBittorrent-5_1"))]
pub total_wasted: i64,
#[cfg(not(feature = "qBittorrent-5_1"))]
pub pieces_have: i32,
#[serde(rename = "dlspeed")]
pub download_speed: i32,
#[serde(rename = "upspeed")]
pub upload_speed: i32,
#[serde(rename = "priority")]
pub queue_position: i32,
pub num_seeds: i32,
pub num_complete: i32,
pub num_leechs: i32,
pub num_incomplete: i32,
pub state: TorrentState,
pub eta: i64,
#[serde(rename = "seq_dl")]
pub sequential_download: bool,
#[serde(rename = "f_l_piece_prio")]
pub first_last_piece_prio: bool,
pub category: String,
#[serde(deserialize_with = "deserializers::string_to_vec_comma_separated")]
#[serde(serialize_with = "serializers::vec_to_string_comma_separated")]
pub tags: Vec<String>, pub super_seeding: bool,
pub force_start: bool,
pub save_path: String,
pub download_path: String,
pub content_path: String,
pub root_path: String,
pub added_on: i64,
pub completion_on: i64,
pub tracker: String,
pub trackers_count: i32,
#[serde(rename = "dl_limit")]
pub download_limit: i32,
#[serde(rename = "up_limit")]
pub upload_limit: i32,
pub downloaded: i64,
pub uploaded: i64,
pub downloaded_session: i64,
pub uploaded_session: i64,
#[serde(deserialize_with = "deserializers::from_null_to_default")]
pub amount_left: i64,
pub completed: i64,
#[cfg(not(feature = "qBittorrent-5_1"))]
pub connections_count: i32,
#[cfg(not(feature = "qBittorrent-5_1"))]
pub connections_limit: i32,
pub max_ratio: f64,
pub max_seeding_time: i32,
pub max_inactive_seeding_time: i32,
pub ratio: f64,
pub ratio_limit: f64,
pub popularity: f64,
pub seeding_time_limit: i32,
pub inactive_seeding_time_limit: i32,
#[cfg(feature = "qBittorrent-5_3")]
pub share_limits_mode: ShareLimitMode,
#[cfg(not(feature = "qBittorrent-5_1"))]
pub share_limit_action: ShareLimitAction,
pub seen_complete: i64,
pub auto_tmm: bool,
pub time_active: i64,
pub seeding_time: i64,
pub last_activity: i64,
pub availability: f64,
pub reannounce: i64,
pub comment: String,
#[cfg(not(feature = "qBittorrent-5_1"))]
pub files: Option<Vec<TorrentContent>>,
pub trackers: Option<Vec<TrackerInfo>>,
}
#[derive(Debug, Serialize, Clone, Default, PartialEq)]
pub struct TorrentsMap(pub HashMap<String, Torrent>);
impl Deref for TorrentsMap {
type Target = HashMap<String, Torrent>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'de> Deserialize<'de> for TorrentsMap {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_map(TorrentMapVisitor)
}
}
#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq)]
struct TorrentMapVisitor;
impl<'de> Visitor<'de> for TorrentMapVisitor {
type Value = TorrentsMap;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a map of torrent infohashes to torrent objects")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut map = HashMap::with_capacity(access.size_hint().unwrap_or(0));
#[derive(Deserialize)]
struct TmpTorrent {
infohash_v1: String,
infohash_v2: String,
name: String,
has_metadata: bool,
#[cfg(not(feature = "qBittorrent-5_1"))]
created_by: String,
#[cfg(not(feature = "qBittorrent-5_1"))]
creation_date: i64,
private: Option<bool>,
total_size: i64,
#[cfg(not(feature = "qBittorrent-5_1"))]
#[serde(rename = "pieces_num")]
pieces_count: i32,
#[cfg(not(feature = "qBittorrent-5_1"))]
piece_size: i64,
magnet_uri: String,
size: i64,
progress: f64,
#[cfg(not(feature = "qBittorrent-5_1"))]
total_wasted: i64,
#[cfg(not(feature = "qBittorrent-5_1"))]
pieces_have: i32,
#[serde(rename = "dlspeed")]
download_speed: i32,
#[serde(rename = "upspeed")]
upload_speed: i32,
#[serde(rename = "priority")]
queue_position: i32,
num_seeds: i32,
num_complete: i32,
num_leechs: i32,
num_incomplete: i32,
state: TorrentState,
eta: i64,
#[serde(rename = "seq_dl")]
sequential_download: bool,
#[serde(rename = "f_l_piece_prio")]
first_last_piece_prio: bool,
category: String,
#[serde(deserialize_with = "deserializers::string_to_vec_comma_separated")]
#[serde(serialize_with = "serializers::vec_to_string_comma_separated")]
tags: Vec<String>,
super_seeding: bool,
force_start: bool,
save_path: String,
download_path: String,
content_path: String,
root_path: String,
added_on: i64,
completion_on: i64,
tracker: String,
trackers_count: i32,
#[serde(rename = "dl_limit")]
download_limit: i32,
#[serde(rename = "up_limit")]
upload_limit: i32,
downloaded: i64,
uploaded: i64,
downloaded_session: i64,
uploaded_session: i64,
#[serde(deserialize_with = "deserializers::from_null_to_default")]
amount_left: i64,
completed: i64,
#[cfg(not(feature = "qBittorrent-5_1"))]
connections_count: i32,
#[cfg(not(feature = "qBittorrent-5_1"))]
connections_limit: i32,
max_ratio: f64,
max_seeding_time: i32,
max_inactive_seeding_time: i32,
ratio: f64,
ratio_limit: f64,
popularity: f64,
seeding_time_limit: i32,
inactive_seeding_time_limit: i32,
#[cfg(feature = "qBittorrent-5_3")]
share_limits_mode: ShareLimitMode,
#[cfg(not(feature = "qBittorrent-5_1"))]
share_limit_action: ShareLimitAction,
seen_complete: i64,
auto_tmm: bool,
time_active: i64,
seeding_time: i64,
last_activity: i64,
availability: f64,
reannounce: i64,
comment: String,
#[cfg(not(feature = "qBittorrent-5_1"))]
files: Option<Vec<TorrentContent>>,
trackers: Option<Vec<TrackerInfo>>,
}
while let Some(key) = access.next_key::<String>()? {
let temp_torrent: TmpTorrent = access.next_value()?;
let torrent = Torrent {
hash: key.clone(),
infohash_v1: temp_torrent.infohash_v1,
infohash_v2: temp_torrent.infohash_v2,
name: temp_torrent.name,
has_metadata: temp_torrent.has_metadata,
#[cfg(not(feature = "qBittorrent-5_1"))]
created_by: temp_torrent.created_by,
#[cfg(not(feature = "qBittorrent-5_1"))]
creation_date: temp_torrent.creation_date,
private: temp_torrent.private,
total_size: temp_torrent.total_size,
#[cfg(not(feature = "qBittorrent-5_1"))]
pieces_count: temp_torrent.pieces_count,
#[cfg(not(feature = "qBittorrent-5_1"))]
piece_size: temp_torrent.piece_size,
magnet_uri: temp_torrent.magnet_uri,
size: temp_torrent.size,
progress: temp_torrent.progress,
#[cfg(not(feature = "qBittorrent-5_1"))]
total_wasted: temp_torrent.total_wasted,
#[cfg(not(feature = "qBittorrent-5_1"))]
pieces_have: temp_torrent.pieces_have,
download_speed: temp_torrent.download_speed,
upload_speed: temp_torrent.upload_speed,
queue_position: temp_torrent.queue_position,
num_seeds: temp_torrent.num_seeds,
num_complete: temp_torrent.num_complete,
num_leechs: temp_torrent.num_leechs,
num_incomplete: temp_torrent.num_incomplete,
state: temp_torrent.state,
eta: temp_torrent.eta,
sequential_download: temp_torrent.sequential_download,
first_last_piece_prio: temp_torrent.first_last_piece_prio,
category: temp_torrent.category,
tags: temp_torrent.tags,
super_seeding: temp_torrent.super_seeding,
force_start: temp_torrent.force_start,
save_path: temp_torrent.save_path,
download_path: temp_torrent.download_path,
content_path: temp_torrent.content_path,
root_path: temp_torrent.root_path,
added_on: temp_torrent.added_on,
completion_on: temp_torrent.completion_on,
tracker: temp_torrent.tracker,
trackers_count: temp_torrent.trackers_count,
download_limit: temp_torrent.download_limit,
upload_limit: temp_torrent.upload_limit,
downloaded: temp_torrent.downloaded,
uploaded: temp_torrent.uploaded,
downloaded_session: temp_torrent.downloaded_session,
uploaded_session: temp_torrent.uploaded_session,
amount_left: temp_torrent.amount_left,
completed: temp_torrent.completed,
#[cfg(not(feature = "qBittorrent-5_1"))]
connections_count: temp_torrent.connections_count,
#[cfg(not(feature = "qBittorrent-5_1"))]
connections_limit: temp_torrent.connections_limit,
max_ratio: temp_torrent.max_ratio,
max_seeding_time: temp_torrent.max_seeding_time,
max_inactive_seeding_time: temp_torrent.max_inactive_seeding_time,
ratio: temp_torrent.ratio,
ratio_limit: temp_torrent.ratio_limit,
popularity: temp_torrent.popularity,
seeding_time_limit: temp_torrent.seeding_time_limit,
inactive_seeding_time_limit: temp_torrent.inactive_seeding_time_limit,
#[cfg(feature = "qBittorrent-5_3")]
share_limits_mode: temp_torrent.share_limits_mode,
#[cfg(not(feature = "qBittorrent-5_1"))]
share_limit_action: temp_torrent.share_limit_action,
seen_complete: temp_torrent.seen_complete,
auto_tmm: temp_torrent.auto_tmm,
time_active: temp_torrent.time_active,
seeding_time: temp_torrent.seeding_time,
last_activity: temp_torrent.last_activity,
availability: temp_torrent.availability,
reannounce: temp_torrent.reannounce,
comment: temp_torrent.comment,
#[cfg(not(feature = "qBittorrent-5_1"))]
files: temp_torrent.files,
trackers: temp_torrent.trackers,
};
map.insert(key, torrent);
}
Ok(TorrentsMap(map))
}
}
#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq)]
pub struct TorrentProperties {
pub infohash_v1: String,
pub infohash_v2: String,
pub name: String,
pub hash: String,
pub time_elapsed: i64,
pub seeding_time: i64,
pub eta: i64,
#[serde(rename = "nb_connections")]
pub connections_count: i32,
#[serde(rename = "nb_connections_limit")]
pub connections_limit: i32,
pub total_downloaded: i64,
pub total_downloaded_session: i64,
pub total_uploaded: i64,
pub total_uploaded_session: i64,
#[serde(rename = "dl_speed")]
pub download_speed: i32,
#[serde(rename = "dl_speed_avg")]
pub download_speed_avg: i32,
#[serde(rename = "up_speed")]
pub upload_speed: i32,
#[serde(rename = "up_speed_avg")]
pub upload_speed_avg: i32,
#[serde(rename = "dl_limit")]
pub download_limit: i32,
#[serde(rename = "up_limit")]
pub upload_limit: i32,
pub total_wasted: i64,
pub seeds: i32,
pub seeds_total: i32,
pub peers: i32,
pub peers_total: i32,
pub share_ratio: f64,
pub popularity: f64,
#[cfg(feature = "qBittorrent-5_3")]
pub availability: f64,
pub reannounce: i64,
pub total_size: i64,
#[serde(rename = "pieces_num")]
pub pieces_count: i32,
pub piece_size: i64,
pub pieces_have: i32,
pub created_by: String,
pub is_private: bool,
pub private: Option<bool>,
pub addition_date: i64,
pub last_seen: i64,
pub completion_date: i64,
pub creation_date: i64,
pub save_path: String,
pub download_path: String,
pub comment: String,
pub has_metadata: bool,
pub progress: f64,
}
#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq)]
pub struct Tracker {
pub url: String,
pub tier: i32,
#[cfg(not(feature = "qBittorrent-5_1"))]
#[serde(default = "default_false")]
pub updating: bool,
pub msg: String,
pub status: TrackerStatus,
#[serde(rename = "num_peers")]
pub peers_count: i32,
#[serde(rename = "num_seeds")]
pub seeds_count: i32,
#[serde(rename = "num_leeches")]
pub leeches_count: i32,
#[serde(rename = "num_downloaded")]
pub downloaded_count: i32,
#[cfg(not(feature = "qBittorrent-5_1"))]
#[serde(default = "default_zero")]
pub next_announce: i64,
#[cfg(not(feature = "qBittorrent-5_1"))]
#[serde(default = "default_zero")]
#[serde(rename = "min_announce")]
pub minimum_announce_interval: i64,
#[cfg(not(feature = "qBittorrent-5_1"))]
#[serde(default = "default_empty_vec")]
pub endpoints: Vec<TrackerEndpoint>,
}
#[cfg(not(feature = "qBittorrent-5_1"))]
fn default_false() -> bool {
false
}
#[cfg(not(feature = "qBittorrent-5_1"))]
fn default_zero() -> i64 {
0
}
#[cfg(not(feature = "qBittorrent-5_1"))]
fn default_empty_vec() -> Vec<TrackerEndpoint> {
Vec::new()
}
#[cfg(not(feature = "qBittorrent-5_1"))]
#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq)]
pub struct TrackerEndpoint {
pub name: String,
pub updating: bool,
pub status: TrackerStatus,
pub msg: String,
#[serde(rename = "bt_version")]
pub bittorrent_version: i32,
#[serde(rename = "num_peers")]
pub peers_count: i32,
#[serde(rename = "num_seeds")]
pub seeds_count: i32,
#[serde(rename = "num_leeches")]
pub leeches_count: i32,
#[serde(rename = "num_downloaded")]
pub downloaded_count: i32,
pub next_announce: i64,
#[serde(rename = "min_announce")]
pub minimum_announce_interval: i64,
}
#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
#[repr(u8)]
pub enum TrackerStatus {
#[default]
NotContacted = 1,
Working = 2,
#[cfg(feature = "qBittorrent-5_1")]
Updating = 3,
NotWorking = 4,
TrackerErr = 5,
Unreachable = 6,
}
#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq)]
pub struct WebSeed {
pub url: String,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct TrackerInfo {
pub url: String,
pub tier: i32,
pub status: TrackerStatus,
#[serde(rename = "msg")]
pub message: String,
#[serde(rename = "num_peers")]
pub peers_count: i32,
#[serde(rename = "num_seeds")]
pub seeds_count: i32,
#[serde(rename = "num_leeches")]
pub leeches_count: i32,
#[serde(rename = "num_downloaded")]
pub downloaded_count: i32,
}
#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq)]
pub struct TorrentContent {
pub index: i32,
pub progress: f64,
pub priority: FilePriority,
pub size: i64,
pub availability: f64,
pub name: String,
pub piece_range: Vec<i32>,
pub is_seed: Option<bool>,
}
#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
#[repr(u8)]
pub enum FilePriority {
DoNotDownload = 0,
#[default]
Normal = 1,
High = 6,
Maximal = 7,
}
#[derive(Debug, Deserialize_repr, Serialize_repr, Clone, Default, PartialEq)]
#[repr(u8)]
pub enum PiecesState {
#[default]
NotDownloaded = 0,
Downloading = 1,
Downloaded = 2,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum TorrentState {
#[serde(rename = "error")]
Error,
#[serde(rename = "missingFiles")]
MissingFiles,
#[serde(rename = "moving")]
Moving,
#[serde(rename = "unknown")]
Unknown,
#[serde(rename = "allocating")]
Allocating,
#[serde(rename = "checkingResumeData")]
CheckingResumeData,
#[serde(rename = "uploading")]
Uploading,
#[serde(rename = "stoppedUP")]
StoppedUploading,
#[serde(rename = "queuedUP")]
QueuedUploading,
#[serde(rename = "stalledUP")]
StalledUploading,
#[serde(rename = "checkingUP")]
CheckingUploading,
#[serde(rename = "forcedUP")]
ForcedUploading,
#[serde(rename = "downloading")]
Downloading,
#[serde(rename = "metaDL")]
MetadataDownloading,
#[serde(rename = "forcedMetaDL")]
ForcedMetadataDownloading,
#[serde(rename = "stoppedDL")]
StoppedDownloading,
#[serde(rename = "queuedDL")]
QueuedDownloading,
#[serde(rename = "stalledDL")]
StalledDownloading,
#[serde(rename = "checkingDL")]
CheckingDownloading,
#[serde(rename = "forcedDL")]
ForcedDownloading,
}
impl Default for TorrentState {
fn default() -> Self {
Self::Unknown
}
}
impl From<&str> for TorrentState {
fn from(value: &str) -> Self {
match value {
"error" => Self::Error,
"missingFiles" => Self::MissingFiles,
"uploading" => Self::Uploading,
"stoppedUP" => Self::StoppedUploading,
"queuedUP" => Self::QueuedUploading,
"stalledUP" => Self::StalledUploading,
"checkingUP" => Self::CheckingUploading,
"forcedUP" => Self::ForcedUploading,
"allocating" => Self::Allocating,
"downloading" => Self::Downloading,
"stoppedDL" => Self::StoppedDownloading,
"metaDL" => Self::MetadataDownloading,
"queuedDL" => Self::QueuedDownloading,
"stalledDL" => Self::StalledDownloading,
"checkingDL" => Self::CheckingDownloading,
"forcedDL" => Self::ForcedDownloading,
"forcedMetaDL" => Self::ForcedMetadataDownloading,
"checkingResumeData" => Self::CheckingResumeData,
"moving" => Self::Moving,
"unknown" => Self::Unknown,
_ => Self::Unknown,
}
}
}
impl From<String> for TorrentState {
fn from(value: String) -> Self {
Self::from(value.as_str())
}
}
impl Debug for TorrentState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
if f.alternate() {
match self {
TorrentState::Error => "Error",
TorrentState::MissingFiles => "Missing Files",
TorrentState::Moving => "Moving",
TorrentState::Unknown => "Unknown",
TorrentState::Allocating => "Allocating",
TorrentState::CheckingResumeData => "Checking Resume Data",
TorrentState::Uploading => "Uploading",
TorrentState::StoppedUploading => "Stopped Uploading",
TorrentState::QueuedUploading => "Queued Uploading",
TorrentState::StalledUploading => "Stalled Uploading",
TorrentState::CheckingUploading => "Checking Uploading",
TorrentState::ForcedUploading => "Forced Uploading",
TorrentState::Downloading => "Downloading",
TorrentState::MetadataDownloading => "Metadata Downloading",
TorrentState::ForcedMetadataDownloading => "Forced Metadata Downloading",
TorrentState::StoppedDownloading => "Stopped Downloading",
TorrentState::QueuedDownloading => "Queued Downloading",
TorrentState::StalledDownloading => "Stalled Downloading",
TorrentState::CheckingDownloading => "Checking Downloading",
TorrentState::ForcedDownloading => "Forced Downloading",
}
} else {
match self {
TorrentState::Error => "error",
TorrentState::MissingFiles => "missingFiles",
TorrentState::Moving => "moving",
TorrentState::Unknown => "unknown",
TorrentState::Uploading => "uploading",
TorrentState::StoppedUploading => "stoppedUP",
TorrentState::QueuedUploading => "queuedUP",
TorrentState::StalledUploading => "stalledUP",
TorrentState::CheckingUploading => "checkingUP",
TorrentState::ForcedUploading => "forcedUP",
TorrentState::Allocating => "allocating",
TorrentState::Downloading => "downloading",
TorrentState::StoppedDownloading => "stoppedDL",
TorrentState::MetadataDownloading => "metaDL",
TorrentState::QueuedDownloading => "queuedDL",
TorrentState::StalledDownloading => "stalledDL",
TorrentState::CheckingDownloading => "checkingDL",
TorrentState::ForcedDownloading => "forcedDL",
TorrentState::ForcedMetadataDownloading => "forcedMetaDL",
TorrentState::CheckingResumeData => "checkingResumeData",
}
}
)
}
}
impl TorrentState {
pub fn is_stopped(&self) -> bool {
*self == Self::StoppedUploading || *self == Self::StoppedDownloading
}
pub fn is_stalled(&self) -> bool {
*self == Self::StalledUploading || *self == Self::StalledDownloading
}
pub fn is_queued(&self) -> bool {
*self == Self::QueuedUploading || *self == Self::QueuedDownloading
}
pub fn is_checking(&self) -> bool {
*self == Self::CheckingUploading
|| *self == Self::CheckingDownloading
|| *self == Self::CheckingResumeData
}
pub fn is_forced(&self) -> bool {
*self == Self::ForcedUploading
|| *self == Self::ForcedDownloading
|| *self == Self::ForcedMetadataDownloading
}
pub fn is_uploading(&self) -> bool {
*self == Self::Uploading
|| *self == Self::ForcedUploading
|| *self == Self::QueuedUploading
|| *self == Self::StalledUploading
|| *self == Self::StoppedUploading
|| *self == Self::CheckingUploading
}
pub fn is_downloading(&self) -> bool {
*self == Self::Downloading
|| *self == Self::ForcedDownloading
|| *self == Self::ForcedMetadataDownloading
|| *self == Self::QueuedDownloading
|| *self == Self::StalledDownloading
|| *self == Self::StoppedDownloading
|| *self == Self::CheckingDownloading
|| *self == Self::MetadataDownloading
}
pub fn is_errored(&self) -> bool {
*self == Self::Error || *self == Self::MissingFiles
}
}
#[cfg(test)]
mod tests {
use super::*;
#[allow(unused_imports)]
use serde_json::{Number, Value, json};
mod serialization {
use super::*;
#[test]
fn torrent() {
let mut torrent = Torrent::default();
torrent.added_on = 6969;
torrent.name = "serialization.txt".to_string();
torrent.hash = "aaaaaaaaaaaaaaaaaaaa".to_string();
let res = serde_json::to_string(&torrent);
assert!(res.is_ok());
let data = res.unwrap();
assert!(data.contains("\"name\":\"serialization.txt\""));
assert!(data.contains("\"added_on\":6969"));
assert!(data.contains("\"hash\":\"aaaaaaaaaaaaaaaaaaaa\""));
}
#[test]
fn torrent_properties() {
let mut torrent = TorrentProperties::default();
torrent.addition_date = 6969;
torrent.name = "serialization.txt".to_string();
torrent.hash = "aaaaaaaaaaaaaaaaaaaa".to_string();
let res = serde_json::to_string(&torrent);
assert!(res.is_ok());
let data = res.unwrap();
assert!(data.contains("\"addition_date\":6969"));
assert!(data.contains("\"name\":\"serialization.txt\""));
assert!(data.contains("\"hash\":\"aaaaaaaaaaaaaaaaaaaa\""));
}
#[test]
fn tracker_basic() {
let mut tracker = Tracker::default();
tracker.url = "http://example.com".to_string();
tracker.msg = "example".to_string();
tracker.status = TrackerStatus::NotContacted;
let res = serde_json::to_string(&tracker);
assert!(res.is_ok());
let data = res.unwrap();
assert!(data.contains("\"url\":\"http://example.com\""));
assert!(data.contains("\"msg\":\"example\""));
assert!(data.contains("\"status\":1"));
}
#[cfg(not(feature = "qBittorrent-5_1"))]
#[test]
fn tracker_extended_with_endpoints() {
let mut tracker = Tracker::default();
tracker.url = "http://example.com".to_string();
tracker.msg = "example".to_string();
tracker.status = TrackerStatus::NotContacted;
tracker.tier = 0;
tracker.updating = false;
tracker.endpoints = vec![TrackerEndpoint::default()];
let res = serde_json::to_string(&tracker);
assert!(res.is_ok());
let data = res.unwrap();
assert!(data.contains("\"url\":\"http://example.com\""));
assert!(data.contains("\"msg\":\"example\""));
assert!(data.contains("\"status\":1"));
assert!(data.contains("\"tier\":0"));
assert!(data.contains("\"updating\":false"));
assert!(data.contains("\"endpoints\":[{\""));
}
}
mod deserialization {
use super::*;
#[test]
fn torrent() {
#[allow(unused_mut)]
let mut json = json!({
"hash": "ffffffffffffffffffffffffffffffffffffffff",
"infohash_v1": "ffffffffffffffffffffffffffffffffffffffff",
"infohash_v2": "",
"name": "file.pdf",
"has_metadata": true,
"private": false,
"total_size": 702545920,
"magnet_uri": "magnet:?xt=urn:btih:ffffffffffffffffffffffffffffffffffffffff",
"size": 702545920,
"progress": 0.4545,
"dlspeed": 0,
"upspeed": 0,
"priority": 13,
"num_seeds": 5,
"num_complete": 3,
"num_leechs": 4,
"num_incomplete": 56,
"state": "stoppedDL",
"eta": 6000,
"seq_dl": false,
"f_l_piece_prio": false,
"category": "cat1",
"tags": "tag1,tag2",
"super_seeding": false,
"force_start": false,
"save_path": "/downloads",
"download_path": "/path/to/downloads/",
"content_path": "/path/to/downloads/file.pdf",
"root_path": "/root",
"added_on": 1000,
"completion_on": -1,
"tracker": "http://file:6969/announce",
"trackers_count": 1,
"dl_limit": 0,
"up_limit": 0,
"downloaded": 198550558,
"uploaded": 0,
"downloaded_session": 0,
"uploaded_session": 0,
"amount_left": 2000,
"completed": 3000,
"max_ratio": 0.25,
"max_seeding_time": -1,
"max_inactive_seeding_time": -1,
"ratio": 0.1,
"ratio_limit": 0.25,
"popularity": 0.7,
"seeding_time_limit": -1,
"inactive_seeding_time_limit": -1,
"seen_complete": 7000,
"auto_tmm": false,
"time_active": 150,
"seeding_time": 5000,
"last_activity": 1781720956,
"availability": 0.3,
"reannounce": 67,
"comment": "This is a comment",
});
#[cfg(not(feature = "qBittorrent-5_1"))]
{
json["created_by"] = Value::String("Billy".to_string());
json["creation_date"] = Value::Number(Number::from(-1));
json["pieces_num"] = Value::Number(Number::from(2680));
json["piece_size"] = Value::Number(Number::from(262144));
json["total_wasted"] = Value::Number(Number::from(0));
json["pieces_have"] = Value::Number(Number::from(738));
json["connections_count"] = Value::Number(Number::from(2));
json["connections_limit"] = Value::Number(Number::from(100));
json["share_limit_action"] = Value::String("EnableSuperSeeding".to_string());
}
#[cfg(feature = "qBittorrent-5_3")]
{
json["share_limits_mode"] = Value::String("MatchAny".to_string());
}
let res: Result<Torrent, serde_json::Error> = serde_json::from_value(json);
assert!(res.is_ok());
let torrent = res.unwrap();
assert_eq!(
torrent.hash,
"ffffffffffffffffffffffffffffffffffffffff".to_string()
);
assert_eq!(
torrent.infohash_v1,
"ffffffffffffffffffffffffffffffffffffffff".to_string()
);
assert_eq!(torrent.infohash_v2, "".to_string());
assert_eq!(torrent.name, "file.pdf".to_string());
}
#[test]
fn torrent_properties() {
#[allow(unused_mut)]
let mut json = json!({
"infohash_v1": "ffffffffffffffffffffffffffffffffffffffff",
"infohash_v2": "",
"name": "test.torrent",
"hash": "ffffffffffffffffffffffffffffffffffffffff",
"time_elapsed": 1337,
"seeding_time": 6243,
"eta": 69,
"nb_connections": 234,
"nb_connections_limit": 780,
"total_downloaded": 750,
"total_downloaded_session": 770,
"total_uploaded": 760,
"total_uploaded_session": 790,
"dl_speed":23,
"dl_speed_avg": 24,
"up_speed": 25,
"up_speed_avg": 26,
"dl_limit": 556,
"up_limit": 555,
"total_wasted": 650,
"seeds": 651,
"seeds_total": 652,
"peers": 1,
"peers_total": 23,
"share_ratio": 1.55,
"popularity": 2.2,
"reannounce": 116,
"total_size": 117,
"pieces_num": 118,
"piece_size": 1024,
"pieces_have": 782,
"created_by": "bob",
"is_private": false,
"private": Value::Null,
"addition_date": 324,
"last_seen": 777,
"completion_date": 100,
"creation_date": 200,
"save_path": "/downloads",
"download_path": "/path/to/downloads/",
"comment": "this is a test comment",
"has_metadata": false,
"progress": 30.1,
});
#[cfg(feature = "qBittorrent-5_3")]
{
json["availability"] = Value::Number(Number::from(0.0));
}
let res: Result<TorrentProperties, serde_json::Error> =
serde_json::from_value(json.clone());
assert!(res.is_ok());
let torrent = res.unwrap();
assert_eq!(torrent.hash, "ffffffffffffffffffffffffffffffffffffffff");
assert_eq!(torrent.name, "test.torrent");
assert_eq!(torrent.private, None);
json["private"] = Value::Bool(true);
let res: Result<TorrentProperties, serde_json::Error> = serde_json::from_value(json);
assert!(res.is_ok());
let torrent = res.unwrap();
assert_eq!(torrent.private, Some(true));
}
#[test]
fn tracker_basic() {
let json = json!({
"url": "http://tracker.example.com",
"tier": 0,
"msg": "test",
"status": 2,
"num_peers": 10,
"num_seeds": 5,
"num_leeches": 5,
"num_downloaded": 5,
});
let res: Result<Tracker, serde_json::Error> = serde_json::from_value(json);
let tracker = res.unwrap();
assert_eq!(tracker.url, "http://tracker.example.com");
assert_eq!(tracker.tier, 0);
assert_eq!(tracker.msg, "test");
assert_eq!(tracker.status, TrackerStatus::Working);
}
#[cfg(not(feature = "qBittorrent-5_1"))]
#[test]
fn tracker_extended() {
let json = json!({
"url": "http://tracker.example.com",
"tier": 0,
"updating": false,
"msg": "test",
"status": 2,
"num_peers": 10,
"num_seeds": 5,
"num_leeches": 5,
"num_downloaded": 5,
"next_announce": 0,
"min_announce": 0,
"endpoints": [],
});
let res: Result<Tracker, serde_json::Error> = serde_json::from_value(json);
let tracker = res.unwrap();
assert_eq!(tracker.url, "http://tracker.example.com");
assert_eq!(tracker.tier, 0);
assert_eq!(tracker.msg, "test");
assert_eq!(tracker.status, TrackerStatus::Working);
}
#[cfg(not(feature = "qBittorrent-5_1"))]
#[test]
fn tracker_extended_with_endpoints() {
let json = json!({
"url": "http://tracker.example.com",
"tier": 0,
"msg": "test",
"status": 2,
"num_peers": 10,
"num_seeds": 5,
"num_leeches": 5,
"num_downloaded": 5,
"next_announce": 0,
"min_announce": 0,
"endpoints": [
{
"name": "endpoint.example.com",
"updating": false,
"status": 2,
"msg": "test",
"bt_version": 69,
"num_peers": 10,
"num_seeds": 5,
"num_leeches": 5,
"num_downloaded": 5,
"next_announce": 0,
"min_announce": 0,
},
],
});
let res: Result<Tracker, serde_json::Error> = serde_json::from_value(json);
assert!(res.is_ok());
let tracker = res.unwrap();
assert_eq!(tracker.url, "http://tracker.example.com");
assert_eq!(tracker.tier, 0);
assert_eq!(tracker.msg, "test");
assert_eq!(tracker.status, TrackerStatus::Working);
}
#[cfg(not(feature = "qBittorrent-5_1"))]
#[test]
fn tracker_endpoints() {
let json = json!({
"name": "endpoint.example.com",
"updating": false,
"status": 2,
"msg": "test",
"bt_version": 69,
"num_peers": 10,
"num_seeds": 5,
"num_leeches": 5,
"num_downloaded": 5,
"next_announce": 0,
"min_announce": 0,
});
let res: Result<TrackerEndpoint, serde_json::Error> = serde_json::from_value(json);
assert!(res.is_ok());
let endpoint = res.unwrap();
assert_eq!(endpoint.name, "endpoint.example.com");
assert!(!endpoint.updating);
assert_eq!(endpoint.status, TrackerStatus::Working);
assert_eq!(endpoint.msg, "test");
assert_eq!(endpoint.bittorrent_version, 69);
}
}
}