diff --git a/examples/session-get.rs b/examples/session-get.rs index f396538..db180ce 100644 --- a/examples/session-get.rs +++ b/examples/session-get.rs @@ -1,22 +1,25 @@ extern crate transmission_rpc; -use std::env; use dotenv::dotenv; +use std::env; +use transmission_rpc::types::{BasicAuth, Result, RpcResponse, SessionGet}; use transmission_rpc::TransClient; -use transmission_rpc::types::{Result, RpcResponse, SessionGet, BasicAuth}; #[tokio::main] async fn main() -> Result<()> { dotenv().ok(); env_logger::init(); - let url= env::var("TURL")?; - let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; + let url = env::var("TURL")?; + let basic_auth = BasicAuth { + user: env::var("TUSER")?, + password: env::var("TPWD")?, + }; let client = TransClient::with_auth(&url, basic_auth); let response: Result> = client.session_get().await; match response { Ok(_) => println!("Yay!"), Err(_) => panic!("Oh no!") } - println!("Rpc reqsponse is ok: {}", response?.is_ok()); + println!("Rpc response is ok: {}", response?.is_ok()); Ok(()) -} \ No newline at end of file +} diff --git a/examples/torrent-action.rs b/examples/torrent-action.rs index 2a4dffb..e9aadc7 100644 --- a/examples/torrent-action.rs +++ b/examples/torrent-action.rs @@ -1,22 +1,25 @@ extern crate transmission_rpc; -use std::env; use dotenv::dotenv; +use std::env; +use transmission_rpc::types::{BasicAuth, Result, RpcResponse}; +use transmission_rpc::types::{Id, Nothing, TorrentAction}; use transmission_rpc::TransClient; -use transmission_rpc::types::{Result, RpcResponse, BasicAuth}; -use transmission_rpc::types::{TorrentAction, Nothing, Id}; #[tokio::main] async fn main() -> Result<()> { dotenv().ok(); env_logger::init(); - let url= env::var("TURL")?; - let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; + let url = env::var("TURL")?; + let basic_auth = BasicAuth { + user: env::var("TUSER")?, + password: env::var("TPWD")?, + }; let client = TransClient::with_auth(&url, basic_auth); let res1: RpcResponse = client.torrent_action(TorrentAction::Start, vec![Id::Id(1)]).await?; println!("Start result: {:?}", &res1.is_ok()); let res2: RpcResponse = client.torrent_action(TorrentAction::Stop, vec![Id::Id(1)]).await?; println!("Stop result: {:?}", &res2.is_ok()); - + Ok(()) -} \ No newline at end of file +} diff --git a/examples/torrent-add.rs b/examples/torrent-add.rs index 71501b6..e8f75ef 100644 --- a/examples/torrent-add.rs +++ b/examples/torrent-add.rs @@ -1,17 +1,20 @@ extern crate transmission_rpc; -use std::env; use dotenv::dotenv; -use transmission_rpc::TransClient; -use transmission_rpc::types::{Result, RpcResponse, BasicAuth}; +use std::env; +use transmission_rpc::types::{BasicAuth, Result, RpcResponse}; use transmission_rpc::types::{TorrentAddArgs, TorrentAdded}; +use transmission_rpc::TransClient; #[tokio::main] async fn main() -> Result<()> { dotenv().ok(); env_logger::init(); - let url= env::var("TURL")?; - let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; + let url = env::var("TURL")?; + let basic_auth = BasicAuth { + user: env::var("TUSER")?, + password: env::var("TPWD")?, + }; let client = TransClient::with_auth(&url, basic_auth); let add: TorrentAddArgs = TorrentAddArgs { filename: Some("https://releases.ubuntu.com/20.04/ubuntu-20.04-desktop-amd64.iso.torrent".to_string()), @@ -20,6 +23,6 @@ async fn main() -> Result<()> { let res: RpcResponse = client.torrent_add(add).await?; println!("Add result: {:?}", &res.is_ok()); println!("response: {:?}", &res); - + Ok(()) -} \ No newline at end of file +} diff --git a/examples/torrent-get.rs b/examples/torrent-get.rs index aab9ec7..41342ab 100644 --- a/examples/torrent-get.rs +++ b/examples/torrent-get.rs @@ -1,38 +1,59 @@ extern crate transmission_rpc; -use std::env; use dotenv::dotenv; +use std::env; +use transmission_rpc::types::{BasicAuth, Result, RpcResponse}; +use transmission_rpc::types::{Id, Torrent, TorrentGetField, Torrents}; use transmission_rpc::TransClient; -use transmission_rpc::types::{Result, RpcResponse, BasicAuth}; -use transmission_rpc::types::{Torrents, Torrent, TorrentGetField, Id}; #[tokio::main] async fn main() -> Result<()> { dotenv().ok(); env_logger::init(); - let url= env::var("TURL")?; - let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; + let url = env::var("TURL")?; + let basic_auth = BasicAuth { + user: env::var("TUSER")?, + password: env::var("TPWD")?, + }; let client = TransClient::with_auth(&url, basic_auth); let res: RpcResponse> = client.torrent_get(None, None).await?; - let names: Vec<&String> = res.arguments.torrents.iter().map(|it| it.name.as_ref().unwrap()).collect(); + let names: Vec<&String> = res + .arguments + .torrents + .iter() + .map(|it| it.name.as_ref().unwrap()) + .collect(); println!("{:#?}", names); - let res1: RpcResponse> = client.torrent_get(Some(vec![TorrentGetField::Id, TorrentGetField::Name]), Some(vec![Id::Id(1), Id::Id(2), Id::Id(3)])).await?; - let first_three: Vec = res1.arguments.torrents.iter().map(|it| - format!("{}. {}",&it.id.as_ref().unwrap(), &it.name.as_ref().unwrap()) - ).collect(); + let res1: RpcResponse> = client.torrent_get( + Some(vec![TorrentGetField::Id, TorrentGetField::Name]), + Some(vec![Id::Id(1), Id::Id(2), Id::Id(3)]), + ).await?; + let first_three: Vec = res1 + .arguments + .torrents + .iter() + .map(|it| {format!("{}. {}", &it.id.as_ref().unwrap(), &it.name.as_ref().unwrap())}) + .collect(); println!("{:#?}", first_three); - - let res2: RpcResponse> = client.torrent_get(Some(vec![TorrentGetField::Id, TorrentGetField::HashString, TorrentGetField::Name]), Some(vec![Id::Hash(String::from("64b0d9a53ac9cd1002dad1e15522feddb00152fe"))])).await?; - let info: Vec = res2.arguments.torrents.iter().map(|it| - format!("{:5}. {:^45} {}", - &it.id.as_ref().unwrap(), - &it.hash_string.as_ref().unwrap(), - &it.name.as_ref().unwrap()) - ).collect(); + let res2: RpcResponse> = client + .torrent_get( + Some(vec![ + TorrentGetField::Id, + TorrentGetField::HashString, + TorrentGetField::Name, + ]), + Some(vec![Id::Hash(String::from("64b0d9a53ac9cd1002dad1e15522feddb00152fe",))]), + ).await?; + let info: Vec = res2 + .arguments + .torrents + .iter() + .map(|it| {format!("{:5}. {:^45} {}", &it.id.as_ref().unwrap(), &it.hash_string.as_ref().unwrap(), &it.name.as_ref().unwrap())}) + .collect(); println!("{:#?}", info); - + Ok(()) -} \ No newline at end of file +} diff --git a/examples/torrent-remove.rs b/examples/torrent-remove.rs index 083042b..898e886 100644 --- a/examples/torrent-remove.rs +++ b/examples/torrent-remove.rs @@ -1,20 +1,23 @@ extern crate transmission_rpc; -use std::env; use dotenv::dotenv; +use std::env; +use transmission_rpc::types::{BasicAuth, Result, RpcResponse}; +use transmission_rpc::types::{Id, Nothing}; use transmission_rpc::TransClient; -use transmission_rpc::types::{Result, RpcResponse, BasicAuth}; -use transmission_rpc::types::{Nothing, Id}; #[tokio::main] async fn main() -> Result<()> { dotenv().ok(); env_logger::init(); - let url= env::var("TURL")?; - let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; + let url = env::var("TURL")?; + let basic_auth = BasicAuth { + user: env::var("TUSER")?, + password: env::var("TPWD")?, + }; let client = TransClient::with_auth(&url, basic_auth); let res: RpcResponse = client.torrent_remove(vec![Id::Id(1)], false).await?; println!("Remove result: {:?}", &res.is_ok()); - + Ok(()) -} \ No newline at end of file +} diff --git a/examples/torrent-set-location.rs b/examples/torrent-set-location.rs index 15f7542..61a204d 100644 --- a/examples/torrent-set-location.rs +++ b/examples/torrent-set-location.rs @@ -1,20 +1,27 @@ extern crate transmission_rpc; -use std::env; use dotenv::dotenv; +use std::env; +use transmission_rpc::types::{BasicAuth, Result, RpcResponse}; +use transmission_rpc::types::{Id, Nothing}; use transmission_rpc::TransClient; -use transmission_rpc::types::{Result, RpcResponse, BasicAuth}; -use transmission_rpc::types::{Nothing, Id}; #[tokio::main] async fn main() -> Result<()> { dotenv().ok(); env_logger::init(); - let url= env::var("TURL")?; - let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; + let url = env::var("TURL")?; + let basic_auth = BasicAuth { + user: env::var("TUSER")?, + password: env::var("TPWD")?, + }; let client = TransClient::with_auth(&url, basic_auth); - let res: RpcResponse = client.torrent_set_location(vec![Id::Id(1)], String::from("/new/location"), Option::from(false)).await?; + let res: RpcResponse = client.torrent_set_location( + vec![Id::Id(1)], + String::from("/new/location"), + Option::from(false), + ).await?; println!("Set-location result: {:?}", &res.is_ok()); - + Ok(()) -} \ No newline at end of file +} diff --git a/src/lib.rs b/src/lib.rs index 5fd6f5f..f9c5a0a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,20 +6,20 @@ extern crate env_logger; extern crate log; extern crate reqwest; -use serde::de::DeserializeOwned; use reqwest::header::CONTENT_TYPE; +use serde::de::DeserializeOwned; pub mod types; use types::BasicAuth; -use types::{Result, RpcResponse, RpcResponseArgument, RpcRequest, Nothing}; use types::SessionGet; -use types::{TorrentGetField, Torrents, Torrent, Id}; use types::TorrentAction; +use types::{Id, Torrent, TorrentGetField, Torrents}; +use types::{Nothing, Result, RpcRequest, RpcResponse, RpcResponseArgument}; use types::{TorrentAddArgs, TorrentAdded}; pub struct TransClient { url: String, - auth: Option + auth: Option, } impl TransClient { @@ -27,7 +27,7 @@ impl TransClient { pub fn with_auth(url: &str, basic_auth: BasicAuth) -> TransClient { TransClient { url: url.to_string(), - auth: Some(basic_auth) + auth: Some(basic_auth), } } @@ -35,7 +35,7 @@ impl TransClient { pub fn new(url: &str) -> TransClient { TransClient { url: url.to_string(), - auth: None + auth: None, } } @@ -43,54 +43,56 @@ impl TransClient { fn rpc_request(&self) -> reqwest::RequestBuilder { let client = reqwest::Client::new(); if let Some(auth) = &self.auth { - client.post(&self.url) - .basic_auth(&auth.user, Some(&auth.password)) + client + .post(&self.url) + .basic_auth(&auth.user, Some(&auth.password)) } else { client.post(&self.url) } .header(CONTENT_TYPE, "application/json") } - + /// Performs session-get call and takes the x-transmission-session-id /// header to perform calls, using it's value - /// + /// /// # Errors - /// + /// /// If response is impossible to unwrap then it will return an empty session_id async fn get_session_id(&self) -> String { info!("Requesting session id info"); - let response: reqwest::Result = self.rpc_request() - .json(&RpcRequest::session_get()) - .send() - .await; + let response: reqwest::Result = self + .rpc_request() + .json(&RpcRequest::session_get()) + .send() + .await; let session_id = match response { - Ok(ref resp) => - match resp.headers().get("x-transmission-session-id") { - Some(res) => res.to_str().expect("header value should be a string"), - _ => "" - } - _ => "" - }.to_owned(); + Ok(ref resp) => match resp.headers().get("x-transmission-session-id") { + Some(res) => res.to_str().expect("header value should be a string"), + _ => "", + }, + _ => "", + } + .to_owned(); info!("Received session id: {}", session_id); session_id } /// Performs a session get call - /// + /// /// # Errors - /// + /// /// Any IO Error or Deserialization error - /// + /// /// # Example - /// + /// /// ``` /// extern crate transmission_rpc; - /// + /// /// use std::env; /// use dotenv::dotenv; /// use transmission_rpc::TransClient; /// use transmission_rpc::types::{Result, RpcResponse, SessionGet, BasicAuth}; - /// + /// /// #[tokio::main] /// async fn main() -> Result<()> { /// dotenv().ok(); @@ -114,22 +116,22 @@ impl TransClient { /// Performs a torrent get call /// fileds - if None then ALL fields /// ids - if None then All items - /// + /// /// # Errors - /// + /// /// Any IO Error or Deserialization error - /// + /// /// # Example - /// + /// /// ``` /// extern crate transmission_rpc; - /// + /// /// use std::env; /// use dotenv::dotenv; /// use transmission_rpc::TransClient; /// use transmission_rpc::types::{Result, RpcResponse, BasicAuth}; /// use transmission_rpc::types::{Torrents, Torrent, TorrentGetField, Id}; - /// + /// /// #[tokio::main] /// async fn main() -> Result<()> { /// dotenv().ok(); @@ -137,51 +139,55 @@ impl TransClient { /// let url= env::var("TURL")?; /// let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; /// let client = TransClient::with_auth(&url, basic_auth); - /// + /// /// let res: RpcResponse> = client.torrent_get(None, None).await?; /// let names: Vec<&String> = res.arguments.torrents.iter().map(|it| it.name.as_ref().unwrap()).collect(); /// println!("{:#?}", names); - /// + /// /// let res1: RpcResponse> = client.torrent_get(Some(vec![TorrentGetField::Id, TorrentGetField::Name]), Some(vec![Id::Id(1), Id::Id(2), Id::Id(3)])).await?; - /// let first_three: Vec = res1.arguments.torrents.iter().map(|it| + /// let first_three: Vec = res1.arguments.torrents.iter().map(|it| /// format!("{}. {}",&it.id.as_ref().unwrap(), &it.name.as_ref().unwrap()) /// ).collect(); /// println!("{:#?}", first_three); - /// - /// + /// + /// /// let res2: RpcResponse> = client.torrent_get(Some(vec![TorrentGetField::Id, TorrentGetField::HashString, TorrentGetField::Name]), Some(vec![Id::Hash(String::from("64b0d9a53ac9cd1002dad1e15522feddb00152fe"))])).await?; - /// let info: Vec = res2.arguments.torrents.iter().map(|it| - /// format!("{:5}. {:^45} {}", + /// let info: Vec = res2.arguments.torrents.iter().map(|it| + /// format!("{:5}. {:^45} {}", /// &it.id.as_ref().unwrap(), - /// &it.hash_string.as_ref().unwrap(), - /// &it.name.as_ref().unwrap()) + /// &it.hash_string.as_ref().unwrap(), + /// &it.name.as_ref().unwrap()) /// ).collect(); /// println!("{:#?}", info); /// /// Ok(()) /// } /// ``` - pub async fn torrent_get(&self, fields: Option>, ids: Option>) -> Result>> { + pub async fn torrent_get( + &self, + fields: Option>, + ids: Option>, + ) -> Result>> { self.call(RpcRequest::torrent_get(fields, ids)).await } /// Performs a torrent action call - /// + /// /// # Errors - /// + /// /// Any IO Error or Deserialization error - /// + /// /// # Example - /// + /// /// ``` /// extern crate transmission_rpc; - /// + /// /// use std::env; /// use dotenv::dotenv; /// use transmission_rpc::TransClient; /// use transmission_rpc::types::{Result, RpcResponse, BasicAuth}; /// use transmission_rpc::types::{TorrentAction, Nothing, Id}; - /// + /// /// #[tokio::main] /// async fn main() -> Result<()> { /// dotenv().ok(); @@ -197,27 +203,31 @@ impl TransClient { /// Ok(()) /// } /// ``` - pub async fn torrent_action(&self, action: TorrentAction, ids: Vec) -> Result> { + pub async fn torrent_action( + &self, + action: TorrentAction, + ids: Vec, + ) -> Result> { self.call(RpcRequest::torrent_action(action, ids)).await } /// Performs a torrent remove call - /// + /// /// # Errors - /// + /// /// Any IO Error or Deserialization error - /// + /// /// # Example - /// + /// /// ``` /// extern crate transmission_rpc; - /// + /// /// use std::env; /// use dotenv::dotenv; /// use transmission_rpc::TransClient; /// use transmission_rpc::types::{Result, RpcResponse, BasicAuth}; /// use transmission_rpc::types::{Nothing, Id}; - /// + /// /// #[tokio::main] /// async fn main() -> Result<()> { /// dotenv().ok(); @@ -231,8 +241,13 @@ impl TransClient { /// Ok(()) /// } /// ``` - pub async fn torrent_remove(&self, ids: Vec, delete_local_data: bool) -> Result> { - self.call( RpcRequest::torrent_remove(ids, delete_local_data)).await + pub async fn torrent_remove( + &self, + ids: Vec, + delete_local_data: bool, + ) -> Result> { + self.call(RpcRequest::torrent_remove(ids, delete_local_data)) + .await } /// Performs a torrent set location call @@ -265,27 +280,33 @@ impl TransClient { /// Ok(()) /// } /// ``` - pub async fn torrent_set_location(&self, ids: Vec, location: String, move_from: Option) -> Result> { - self.call(RpcRequest::torrent_set_location(ids, location, move_from)).await + pub async fn torrent_set_location( + &self, + ids: Vec, + location: String, + move_from: Option, + ) -> Result> { + self.call(RpcRequest::torrent_set_location(ids, location, move_from)) + .await } /// Performs a torrent add call - /// + /// /// # Errors - /// + /// /// Any IO Error or Deserialization error - /// + /// /// # Example - /// + /// /// ``` /// extern crate transmission_rpc; - /// + /// /// use std::env; /// use dotenv::dotenv; /// use transmission_rpc::TransClient; /// use transmission_rpc::types::{Result, RpcResponse, BasicAuth}; /// use transmission_rpc::types::{TorrentAddArgs, TorrentAdded}; - /// + /// /// #[tokio::main] /// async fn main() -> Result<()> { /// dotenv().ok(); @@ -308,24 +329,29 @@ impl TransClient { if add.metainfo == None && add.filename == None { panic!("Metainfo or Filename should be provided") } - self.call( RpcRequest::torrent_add(add)).await + self.call(RpcRequest::torrent_add(add)).await } /// Performs a JRPC call to the server - /// + /// /// # Errors - /// + /// /// Any IO Error or Deserialization error - async fn call (&self, request: RpcRequest) -> Result> - where RS : RpcResponseArgument + DeserializeOwned + std::fmt::Debug + async fn call(&self, request: RpcRequest) -> Result> + where + RS: RpcResponseArgument + DeserializeOwned + std::fmt::Debug, { info!("Loaded auth: {:?}", &self.auth); - let rq: reqwest::RequestBuilder = self.rpc_request() + let rq: reqwest::RequestBuilder = self + .rpc_request() .header("X-Transmission-Session-Id", self.get_session_id().await) .json(&request); - info!("Request body: {:?}", rq.try_clone() - .expect("Unable to get the request body") - .body_string()?); + info!( + "Request body: {:?}", + rq.try_clone() + .expect("Unable to get the request body") + .body_string()? + ); let resp: reqwest::Response = rq.send().await?; let rpc_response: RpcResponse = resp.json().await?; info!("Response body: {:#?}", rpc_response); @@ -349,19 +375,25 @@ impl BodyString for reqwest::RequestBuilder { mod tests { use super::*; - use std::env; use dotenv::dotenv; + use std::env; #[tokio::test] pub async fn test_malformed_url() -> Result<()> { dotenv().ok(); env_logger::init(); - let url= env::var("TURL")?; - let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; + let url = env::var("TURL")?; + let basic_auth = BasicAuth { + user: env::var("TUSER")?, + password: env::var("TPWD")?, + }; let client = TransClient::with_auth(&url, basic_auth); info!("Client is ready!"); let add: TorrentAddArgs = TorrentAddArgs { - filename: Some("https://releases.ubuntu.com/20.04/ubuntu-20.04-desktop-amd64.iso.torrentt".to_string()), + filename: Some( + "https://releases.ubuntu.com/20.04/ubuntu-20.04-desktop-amd64.iso.torrentt" + .to_string(), + ), ..TorrentAddArgs::default() }; match client.torrent_add(add).await { @@ -374,7 +406,7 @@ mod tests { println!("Error: {:#?}", e); } } - + Ok(()) } } diff --git a/src/types/mod.rs b/src/types/mod.rs index 09d7a10..f601540 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -1,4 +1,3 @@ - mod request; mod response; @@ -10,18 +9,18 @@ pub struct BasicAuth { pub password: String, } -pub(crate) use self::request::RpcRequest; pub use self::request::ArgumentFields; -pub use self::request::TorrentGetField; -pub use self::request::TorrentAction; -pub use self::request::TorrentAddArgs; pub use self::request::File; pub use self::request::Id; +pub(crate) use self::request::RpcRequest; +pub use self::request::TorrentAction; +pub use self::request::TorrentAddArgs; +pub use self::request::TorrentGetField; +pub use self::response::Nothing; pub use self::response::RpcResponse; pub(crate) use self::response::RpcResponseArgument; pub use self::response::SessionGet; -pub use self::response::Torrents; pub use self::response::Torrent; pub use self::response::TorrentAdded; -pub use self::response::Nothing; \ No newline at end of file +pub use self::response::Torrents; diff --git a/src/types/request.rs b/src/types/request.rs index 3c0f71a..6210b6c 100644 --- a/src/types/request.rs +++ b/src/types/request.rs @@ -1,84 +1,100 @@ -use serde::Serialize; use enum_iterator::IntoEnumIterator; +use serde::Serialize; #[derive(Serialize, Debug, RustcEncodable)] pub struct RpcRequest { method: String, - #[serde(skip_serializing_if="Option::is_none")] + #[serde(skip_serializing_if = "Option::is_none")] arguments: Option, } impl RpcRequest { pub fn session_get() -> RpcRequest { - RpcRequest { + RpcRequest { method: String::from("session-get"), arguments: None, } - } + } pub fn torrent_get(fields: Option>, ids: Option>) -> RpcRequest { - let string_fields = fields.unwrap_or(TorrentGetField::all()).iter().map(|f| f.to_str()).collect(); - RpcRequest { - method: String::from("torrent-get"), - arguments: Some ( Args::TorrentGetArgs(TorrentGetArgs { fields: Some(string_fields), ids } )), - } - } + let string_fields = fields + .unwrap_or(TorrentGetField::all()) + .iter() + .map(|f| f.to_str()) + .collect(); + RpcRequest { + method: String::from("torrent-get"), + arguments: Some(Args::TorrentGetArgs(TorrentGetArgs { + fields: Some(string_fields), + ids, + })), + } + } - pub fn torrent_remove(ids: Vec, delete_local_data: bool) -> RpcRequest { + pub fn torrent_remove(ids: Vec, delete_local_data: bool) -> RpcRequest { RpcRequest { method: String::from("torrent-remove"), - arguments: Some ( Args::TorrentRemoveArgs(TorrentRemoveArgs {ids, delete_local_data} ) ) + arguments: Some(Args::TorrentRemoveArgs(TorrentRemoveArgs { + ids, + delete_local_data, + })), } - } + } - pub fn torrent_add(add: TorrentAddArgs) -> RpcRequest { - RpcRequest { - method: String::from("torrent-add"), - arguments: Some ( Args::TorrentAddArgs(add) ) - } - } + pub fn torrent_add(add: TorrentAddArgs) -> RpcRequest { + RpcRequest { + method: String::from("torrent-add"), + arguments: Some(Args::TorrentAddArgs(add)), + } + } - pub fn torrent_action(action: TorrentAction, ids: Vec) -> RpcRequest { - RpcRequest { - method: action.to_str(), - arguments: Some ( Args::TorrentActionArgs(TorrentActionArgs { ids })), - } - } + pub fn torrent_action(action: TorrentAction, ids: Vec) -> RpcRequest { + RpcRequest { + method: action.to_str(), + arguments: Some(Args::TorrentActionArgs(TorrentActionArgs { ids })), + } + } - pub fn torrent_set_location(ids: Vec, location: String, move_from: Option) -> RpcRequest { + pub fn torrent_set_location(ids: Vec, location: String, move_from: Option, ) -> RpcRequest { RpcRequest { method: String::from("torrent-set-location"), - arguments: Some( Args::TorrentSetLocationArgs(TorrentSetLocationArgs{ids, location, move_from})) + arguments: Some(Args::TorrentSetLocationArgs(TorrentSetLocationArgs { + ids, + location, + move_from, + })), } } } pub trait ArgumentFields {} -impl ArgumentFields for TorrentGetField{} +impl ArgumentFields for TorrentGetField {} #[derive(Serialize, Debug, RustcEncodable, Clone)] #[serde(untagged)] -pub enum Args{ +pub enum Args { TorrentGetArgs(TorrentGetArgs), - TorrentActionArgs(TorrentActionArgs), + TorrentActionArgs(TorrentActionArgs), TorrentRemoveArgs(TorrentRemoveArgs), TorrentAddArgs(TorrentAddArgs), TorrentSetLocationArgs(TorrentSetLocationArgs), } #[derive(Serialize, Debug, RustcEncodable, Clone)] -pub struct TorrentGetArgs { - #[serde(skip_serializing_if="Option::is_none")] +pub struct TorrentGetArgs { + #[serde(skip_serializing_if = "Option::is_none")] fields: Option>, - #[serde(skip_serializing_if="Option::is_none")] + #[serde(skip_serializing_if = "Option::is_none")] ids: Option>, } impl Default for TorrentGetArgs { fn default() -> Self { - let all_fields = TorrentGetField::into_enum_iter().map (|it| it.to_str()).collect(); + let all_fields = TorrentGetField::into_enum_iter() + .map(|it| it.to_str()) + .collect(); TorrentGetArgs { fields: Some(all_fields), - ids: None + ids: None, } } } @@ -90,55 +106,55 @@ pub struct TorrentActionArgs { #[derive(Serialize, Debug, RustcEncodable, Clone)] pub struct TorrentRemoveArgs { ids: Vec, - #[serde(rename="delete-local-data")] - delete_local_data: bool + #[serde(rename = "delete-local-data")] + delete_local_data: bool, } #[derive(Serialize, Debug, RustcEncodable, Clone)] pub struct TorrentSetLocationArgs { ids: Vec, location: String, - #[serde(skip_serializing_if="Option::is_none", rename="move")] - move_from: Option + #[serde(skip_serializing_if = "Option::is_none", rename = "move")] + move_from: Option, } #[derive(Serialize, Debug, RustcEncodable, Clone)] #[serde(untagged)] pub enum Id { Id(i64), - Hash(String) + Hash(String), } #[derive(Serialize, Debug, RustcEncodable, Clone)] pub struct TorrentAddArgs { - #[serde(skip_serializing_if="Option::is_none")] + #[serde(skip_serializing_if = "Option::is_none")] pub cookies: Option, - #[serde(skip_serializing_if="Option::is_none", rename="download-dir")] + #[serde(skip_serializing_if = "Option::is_none", rename = "download-dir")] pub download_dir: Option, /// Either "filename" OR "metainfo" MUST be included /// semi-optional /// filename or URL of the .torrent file - #[serde(skip_serializing_if="Option::is_none")] + #[serde(skip_serializing_if = "Option::is_none")] pub filename: Option, /// semi-optional /// base64-encoded .torrent content - #[serde(skip_serializing_if="Option::is_none")] + #[serde(skip_serializing_if = "Option::is_none")] pub metainfo: Option, - #[serde(skip_serializing_if="Option::is_none")] + #[serde(skip_serializing_if = "Option::is_none")] pub paused: Option, - #[serde(skip_serializing_if="Option::is_none", rename="peer-limit")] + #[serde(skip_serializing_if = "Option::is_none", rename = "peer-limit")] pub peer_limit: Option, - #[serde(skip_serializing_if="Option::is_none", rename="bandwidthPriority")] + #[serde(skip_serializing_if = "Option::is_none", rename = "bandwidthPriority")] pub bandwidth_priority: Option, - #[serde(skip_serializing_if="Option::is_none", rename="files-wanted")] + #[serde(skip_serializing_if = "Option::is_none", rename = "files-wanted")] pub files_wanted: Option>, - #[serde(skip_serializing_if="Option::is_none", rename="files-unwanted")] + #[serde(skip_serializing_if = "Option::is_none", rename = "files-unwanted")] pub files_unwanted: Option>, - #[serde(skip_serializing_if="Option::is_none", rename="priority-high")] + #[serde(skip_serializing_if = "Option::is_none", rename = "priority-high")] pub priority_high: Option>, - #[serde(skip_serializing_if="Option::is_none", rename="priority-low")] + #[serde(skip_serializing_if = "Option::is_none", rename = "priority-low")] pub priority_low: Option>, - #[serde(skip_serializing_if="Option::is_none", rename="priority-normal")] + #[serde(skip_serializing_if = "Option::is_none", rename = "priority-normal")] pub priority_normal: Option>, } @@ -156,7 +172,7 @@ impl Default for TorrentAddArgs { files_unwanted: None, priority_high: None, priority_low: None, - priority_normal: None + priority_normal: None, } } } diff --git a/src/types/response.rs b/src/types/response.rs index f39288a..e2fed1e 100644 --- a/src/types/response.rs +++ b/src/types/response.rs @@ -2,7 +2,7 @@ use serde::Deserialize; #[derive(Deserialize, Debug)] pub struct RpcResponse { pub arguments: T, - pub result: String + pub result: String, } impl RpcResponse { @@ -14,74 +14,74 @@ pub trait RpcResponseArgument {} #[derive(Deserialize, Debug, Clone)] pub struct SessionGet { - #[serde(rename="blocklist-enabled")] + #[serde(rename = "blocklist-enabled")] pub blocklist_enabled: bool, - #[serde(rename="download-dir")] + #[serde(rename = "download-dir")] pub download_dir: String, pub encryption: String, - #[serde(rename="rpc-version")] + #[serde(rename = "rpc-version")] pub rpc_version: i32, - #[serde(rename="rpc-version-minimum")] + #[serde(rename = "rpc-version-minimum")] pub rpc_version_minimum: i32, pub version: String, } -impl RpcResponseArgument for SessionGet{} +impl RpcResponseArgument for SessionGet {} #[derive(Deserialize, Debug, RustcEncodable, Clone)] pub struct Torrent { - #[serde(rename="addedDate")] + #[serde(rename = "addedDate")] pub added_date: Option, - #[serde(rename="downloadDir")] + #[serde(rename = "downloadDir")] pub download_dir: Option, pub error: Option, - #[serde(rename="errorString")] + #[serde(rename = "errorString")] pub error_string: Option, pub eta: Option, pub id: Option, - #[serde(rename="isFinished")] + #[serde(rename = "isFinished")] pub is_finished: Option, - #[serde(rename="isStalled")] + #[serde(rename = "isStalled")] pub is_stalled: Option, - #[serde(rename="leftUntilDone")] + #[serde(rename = "leftUntilDone")] pub left_until_done: Option, - #[serde(rename="metadataPercentComplete")] + #[serde(rename = "metadataPercentComplete")] pub metadata_percent_complete: Option, pub name: Option, - #[serde(rename="hashString")] + #[serde(rename = "hashString")] pub hash_string: Option, - #[serde(rename="peersConnected")] + #[serde(rename = "peersConnected")] pub peers_connected: Option, - #[serde(rename="peersGettingFromUs")] + #[serde(rename = "peersGettingFromUs")] pub peers_getting_from_us: Option, - #[serde(rename="peersSendingToUs")] + #[serde(rename = "peersSendingToUs")] pub peers_sending_to_us: Option, - #[serde(rename="percentDone")] + #[serde(rename = "percentDone")] pub percent_done: Option, - #[serde(rename="rateDownload")] + #[serde(rename = "rateDownload")] pub rate_download: Option, - #[serde(rename="rateUpload")] + #[serde(rename = "rateUpload")] pub rate_upload: Option, - #[serde(rename="recheckProgress")] + #[serde(rename = "recheckProgress")] pub recheck_progress: Option, - #[serde(rename="seedRatioLimit")] + #[serde(rename = "seedRatioLimit")] pub seed_ratio_limit: Option, - #[serde(rename="sizeWhenDone")] + #[serde(rename = "sizeWhenDone")] pub size_when_done: Option, pub status: Option, - #[serde(rename="totalSize")] + #[serde(rename = "totalSize")] pub total_size: Option, pub trackers: Option>, - #[serde(rename="uploadRatio")] + #[serde(rename = "uploadRatio")] pub upload_ratio: Option, - #[serde(rename="uploadedEver")] - pub uploaded_ever: Option, + #[serde(rename = "uploadedEver")] + pub uploaded_ever: Option, } #[derive(Deserialize, Debug, RustcEncodable)] pub struct Torrents { - pub torrents: Vec + pub torrents: Vec, } -impl RpcResponseArgument for Torrents{} +impl RpcResponseArgument for Torrents {} #[derive(Deserialize, Debug, RustcEncodable, Clone)] pub struct Trackers { @@ -90,12 +90,12 @@ pub struct Trackers { } #[derive(Deserialize, Debug, RustcEncodable)] -pub struct Nothing{} +pub struct Nothing {} impl RpcResponseArgument for Nothing {} #[derive(Deserialize, Debug, RustcEncodable)] pub struct TorrentAdded { - #[serde(rename="torrent-added")] - pub torrent_added: Option + #[serde(rename = "torrent-added")] + pub torrent_added: Option, } -impl RpcResponseArgument for TorrentAdded{} \ No newline at end of file +impl RpcResponseArgument for TorrentAdded {}