Format the code with rustfmt

This commit is contained in:
Christiaan Biesterbosch 2020-12-27 17:51:17 +01:00
parent 510b79e57e
commit 2ca1444f18
No known key found for this signature in database
GPG Key ID: B29731CEDFC77003
10 changed files with 316 additions and 229 deletions

View File

@ -1,22 +1,25 @@
extern crate transmission_rpc; extern crate transmission_rpc;
use std::env;
use dotenv::dotenv; use dotenv::dotenv;
use std::env;
use transmission_rpc::types::{BasicAuth, Result, RpcResponse, SessionGet};
use transmission_rpc::TransClient; use transmission_rpc::TransClient;
use transmission_rpc::types::{Result, RpcResponse, SessionGet, BasicAuth};
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
dotenv().ok(); dotenv().ok();
env_logger::init(); env_logger::init();
let url= env::var("TURL")?; let url = env::var("TURL")?;
let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; let basic_auth = BasicAuth {
user: env::var("TUSER")?,
password: env::var("TPWD")?,
};
let client = TransClient::with_auth(&url, basic_auth); let client = TransClient::with_auth(&url, basic_auth);
let response: Result<RpcResponse<SessionGet>> = client.session_get().await; let response: Result<RpcResponse<SessionGet>> = client.session_get().await;
match response { match response {
Ok(_) => println!("Yay!"), Ok(_) => println!("Yay!"),
Err(_) => panic!("Oh no!") Err(_) => panic!("Oh no!")
} }
println!("Rpc reqsponse is ok: {}", response?.is_ok()); println!("Rpc response is ok: {}", response?.is_ok());
Ok(()) Ok(())
} }

View File

@ -1,17 +1,20 @@
extern crate transmission_rpc; extern crate transmission_rpc;
use std::env;
use dotenv::dotenv; 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::TransClient;
use transmission_rpc::types::{Result, RpcResponse, BasicAuth};
use transmission_rpc::types::{TorrentAction, Nothing, Id};
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
dotenv().ok(); dotenv().ok();
env_logger::init(); env_logger::init();
let url= env::var("TURL")?; let url = env::var("TURL")?;
let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; let basic_auth = BasicAuth {
user: env::var("TUSER")?,
password: env::var("TPWD")?,
};
let client = TransClient::with_auth(&url, basic_auth); let client = TransClient::with_auth(&url, basic_auth);
let res1: RpcResponse<Nothing> = client.torrent_action(TorrentAction::Start, vec![Id::Id(1)]).await?; let res1: RpcResponse<Nothing> = client.torrent_action(TorrentAction::Start, vec![Id::Id(1)]).await?;
println!("Start result: {:?}", &res1.is_ok()); println!("Start result: {:?}", &res1.is_ok());

View File

@ -1,17 +1,20 @@
extern crate transmission_rpc; extern crate transmission_rpc;
use std::env;
use dotenv::dotenv; use dotenv::dotenv;
use transmission_rpc::TransClient; use std::env;
use transmission_rpc::types::{Result, RpcResponse, BasicAuth}; use transmission_rpc::types::{BasicAuth, Result, RpcResponse};
use transmission_rpc::types::{TorrentAddArgs, TorrentAdded}; use transmission_rpc::types::{TorrentAddArgs, TorrentAdded};
use transmission_rpc::TransClient;
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
dotenv().ok(); dotenv().ok();
env_logger::init(); env_logger::init();
let url= env::var("TURL")?; let url = env::var("TURL")?;
let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; let basic_auth = BasicAuth {
user: env::var("TUSER")?,
password: env::var("TPWD")?,
};
let client = TransClient::with_auth(&url, basic_auth); let client = TransClient::with_auth(&url, basic_auth);
let add: TorrentAddArgs = TorrentAddArgs { let add: TorrentAddArgs = TorrentAddArgs {
filename: Some("https://releases.ubuntu.com/20.04/ubuntu-20.04-desktop-amd64.iso.torrent".to_string()), filename: Some("https://releases.ubuntu.com/20.04/ubuntu-20.04-desktop-amd64.iso.torrent".to_string()),

View File

@ -1,37 +1,58 @@
extern crate transmission_rpc; extern crate transmission_rpc;
use std::env;
use dotenv::dotenv; 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::TransClient;
use transmission_rpc::types::{Result, RpcResponse, BasicAuth};
use transmission_rpc::types::{Torrents, Torrent, TorrentGetField, Id};
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
dotenv().ok(); dotenv().ok();
env_logger::init(); env_logger::init();
let url= env::var("TURL")?; let url = env::var("TURL")?;
let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; let basic_auth = BasicAuth {
user: env::var("TUSER")?,
password: env::var("TPWD")?,
};
let client = TransClient::with_auth(&url, basic_auth); let client = TransClient::with_auth(&url, basic_auth);
let res: RpcResponse<Torrents<Torrent>> = client.torrent_get(None, None).await?; let res: RpcResponse<Torrents<Torrent>> = 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); println!("{:#?}", names);
let res1: RpcResponse<Torrents<Torrent>> = client.torrent_get(Some(vec![TorrentGetField::Id, TorrentGetField::Name]), Some(vec![Id::Id(1), Id::Id(2), Id::Id(3)])).await?; let res1: RpcResponse<Torrents<Torrent>> = client.torrent_get(
let first_three: Vec<String> = res1.arguments.torrents.iter().map(|it| Some(vec![TorrentGetField::Id, TorrentGetField::Name]),
format!("{}. {}",&it.id.as_ref().unwrap(), &it.name.as_ref().unwrap()) Some(vec![Id::Id(1), Id::Id(2), Id::Id(3)]),
).collect(); ).await?;
let first_three: Vec<String> = res1
.arguments
.torrents
.iter()
.map(|it| {format!("{}. {}", &it.id.as_ref().unwrap(), &it.name.as_ref().unwrap())})
.collect();
println!("{:#?}", first_three); println!("{:#?}", first_three);
let res2: RpcResponse<Torrents<Torrent>> = client
let res2: RpcResponse<Torrents<Torrent>> = client.torrent_get(Some(vec![TorrentGetField::Id, TorrentGetField::HashString, TorrentGetField::Name]), Some(vec![Id::Hash(String::from("64b0d9a53ac9cd1002dad1e15522feddb00152fe"))])).await?; .torrent_get(
let info: Vec<String> = res2.arguments.torrents.iter().map(|it| Some(vec![
format!("{:5}. {:^45} {}", TorrentGetField::Id,
&it.id.as_ref().unwrap(), TorrentGetField::HashString,
&it.hash_string.as_ref().unwrap(), TorrentGetField::Name,
&it.name.as_ref().unwrap()) ]),
).collect(); Some(vec![Id::Hash(String::from("64b0d9a53ac9cd1002dad1e15522feddb00152fe",))]),
).await?;
let info: Vec<String> = 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); println!("{:#?}", info);
Ok(()) Ok(())

View File

@ -1,17 +1,20 @@
extern crate transmission_rpc; extern crate transmission_rpc;
use std::env;
use dotenv::dotenv; 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::TransClient;
use transmission_rpc::types::{Result, RpcResponse, BasicAuth};
use transmission_rpc::types::{Nothing, Id};
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
dotenv().ok(); dotenv().ok();
env_logger::init(); env_logger::init();
let url= env::var("TURL")?; let url = env::var("TURL")?;
let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; let basic_auth = BasicAuth {
user: env::var("TUSER")?,
password: env::var("TPWD")?,
};
let client = TransClient::with_auth(&url, basic_auth); let client = TransClient::with_auth(&url, basic_auth);
let res: RpcResponse<Nothing> = client.torrent_remove(vec![Id::Id(1)], false).await?; let res: RpcResponse<Nothing> = client.torrent_remove(vec![Id::Id(1)], false).await?;
println!("Remove result: {:?}", &res.is_ok()); println!("Remove result: {:?}", &res.is_ok());

View File

@ -1,19 +1,26 @@
extern crate transmission_rpc; extern crate transmission_rpc;
use std::env;
use dotenv::dotenv; 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::TransClient;
use transmission_rpc::types::{Result, RpcResponse, BasicAuth};
use transmission_rpc::types::{Nothing, Id};
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
dotenv().ok(); dotenv().ok();
env_logger::init(); env_logger::init();
let url= env::var("TURL")?; let url = env::var("TURL")?;
let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; let basic_auth = BasicAuth {
user: env::var("TUSER")?,
password: env::var("TPWD")?,
};
let client = TransClient::with_auth(&url, basic_auth); let client = TransClient::with_auth(&url, basic_auth);
let res: RpcResponse<Nothing> = client.torrent_set_location(vec![Id::Id(1)], String::from("/new/location"), Option::from(false)).await?; let res: RpcResponse<Nothing> = client.torrent_set_location(
vec![Id::Id(1)],
String::from("/new/location"),
Option::from(false),
).await?;
println!("Set-location result: {:?}", &res.is_ok()); println!("Set-location result: {:?}", &res.is_ok());
Ok(()) Ok(())

View File

@ -6,20 +6,20 @@ extern crate env_logger;
extern crate log; extern crate log;
extern crate reqwest; extern crate reqwest;
use serde::de::DeserializeOwned;
use reqwest::header::CONTENT_TYPE; use reqwest::header::CONTENT_TYPE;
use serde::de::DeserializeOwned;
pub mod types; pub mod types;
use types::BasicAuth; use types::BasicAuth;
use types::{Result, RpcResponse, RpcResponseArgument, RpcRequest, Nothing};
use types::SessionGet; use types::SessionGet;
use types::{TorrentGetField, Torrents, Torrent, Id};
use types::TorrentAction; use types::TorrentAction;
use types::{Id, Torrent, TorrentGetField, Torrents};
use types::{Nothing, Result, RpcRequest, RpcResponse, RpcResponseArgument};
use types::{TorrentAddArgs, TorrentAdded}; use types::{TorrentAddArgs, TorrentAdded};
pub struct TransClient { pub struct TransClient {
url: String, url: String,
auth: Option<BasicAuth> auth: Option<BasicAuth>,
} }
impl TransClient { impl TransClient {
@ -27,7 +27,7 @@ impl TransClient {
pub fn with_auth(url: &str, basic_auth: BasicAuth) -> TransClient { pub fn with_auth(url: &str, basic_auth: BasicAuth) -> TransClient {
TransClient { TransClient {
url: url.to_string(), url: url.to_string(),
auth: Some(basic_auth) auth: Some(basic_auth),
} }
} }
@ -35,7 +35,7 @@ impl TransClient {
pub fn new(url: &str) -> TransClient { pub fn new(url: &str) -> TransClient {
TransClient { TransClient {
url: url.to_string(), url: url.to_string(),
auth: None auth: None,
} }
} }
@ -43,7 +43,8 @@ impl TransClient {
fn rpc_request(&self) -> reqwest::RequestBuilder { fn rpc_request(&self) -> reqwest::RequestBuilder {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
if let Some(auth) = &self.auth { if let Some(auth) = &self.auth {
client.post(&self.url) client
.post(&self.url)
.basic_auth(&auth.user, Some(&auth.password)) .basic_auth(&auth.user, Some(&auth.password))
} else { } else {
client.post(&self.url) client.post(&self.url)
@ -59,18 +60,19 @@ impl TransClient {
/// If response is impossible to unwrap then it will return an empty session_id /// If response is impossible to unwrap then it will return an empty session_id
async fn get_session_id(&self) -> String { async fn get_session_id(&self) -> String {
info!("Requesting session id info"); info!("Requesting session id info");
let response: reqwest::Result<reqwest::Response> = self.rpc_request() let response: reqwest::Result<reqwest::Response> = self
.rpc_request()
.json(&RpcRequest::session_get()) .json(&RpcRequest::session_get())
.send() .send()
.await; .await;
let session_id = match response { let session_id = match response {
Ok(ref resp) => Ok(ref resp) => match resp.headers().get("x-transmission-session-id") {
match resp.headers().get("x-transmission-session-id") {
Some(res) => res.to_str().expect("header value should be a string"), Some(res) => res.to_str().expect("header value should be a string"),
_ => "" _ => "",
},
_ => "",
} }
_ => "" .to_owned();
}.to_owned();
info!("Received session id: {}", session_id); info!("Received session id: {}", session_id);
session_id session_id
} }
@ -161,7 +163,11 @@ impl TransClient {
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
pub async fn torrent_get(&self, fields: Option<Vec<TorrentGetField>>, ids: Option<Vec<Id>>) -> Result<RpcResponse<Torrents<Torrent>>> { pub async fn torrent_get(
&self,
fields: Option<Vec<TorrentGetField>>,
ids: Option<Vec<Id>>,
) -> Result<RpcResponse<Torrents<Torrent>>> {
self.call(RpcRequest::torrent_get(fields, ids)).await self.call(RpcRequest::torrent_get(fields, ids)).await
} }
@ -197,7 +203,11 @@ impl TransClient {
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
pub async fn torrent_action(&self, action: TorrentAction, ids: Vec<Id>) -> Result<RpcResponse<Nothing>> { pub async fn torrent_action(
&self,
action: TorrentAction,
ids: Vec<Id>,
) -> Result<RpcResponse<Nothing>> {
self.call(RpcRequest::torrent_action(action, ids)).await self.call(RpcRequest::torrent_action(action, ids)).await
} }
@ -231,8 +241,13 @@ impl TransClient {
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
pub async fn torrent_remove(&self, ids: Vec<Id>, delete_local_data: bool) -> Result<RpcResponse<Nothing>> { pub async fn torrent_remove(
self.call( RpcRequest::torrent_remove(ids, delete_local_data)).await &self,
ids: Vec<Id>,
delete_local_data: bool,
) -> Result<RpcResponse<Nothing>> {
self.call(RpcRequest::torrent_remove(ids, delete_local_data))
.await
} }
/// Performs a torrent set location call /// Performs a torrent set location call
@ -265,8 +280,14 @@ impl TransClient {
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
pub async fn torrent_set_location(&self, ids: Vec<Id>, location: String, move_from: Option<bool>) -> Result<RpcResponse<Nothing>> { pub async fn torrent_set_location(
self.call(RpcRequest::torrent_set_location(ids, location, move_from)).await &self,
ids: Vec<Id>,
location: String,
move_from: Option<bool>,
) -> Result<RpcResponse<Nothing>> {
self.call(RpcRequest::torrent_set_location(ids, location, move_from))
.await
} }
/// Performs a torrent add call /// Performs a torrent add call
@ -308,7 +329,7 @@ impl TransClient {
if add.metainfo == None && add.filename == None { if add.metainfo == None && add.filename == None {
panic!("Metainfo or Filename should be provided") 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 /// Performs a JRPC call to the server
@ -316,16 +337,21 @@ impl TransClient {
/// # Errors /// # Errors
/// ///
/// Any IO Error or Deserialization error /// Any IO Error or Deserialization error
async fn call<RS> (&self, request: RpcRequest) -> Result<RpcResponse<RS>> async fn call<RS>(&self, request: RpcRequest) -> Result<RpcResponse<RS>>
where RS : RpcResponseArgument + DeserializeOwned + std::fmt::Debug where
RS: RpcResponseArgument + DeserializeOwned + std::fmt::Debug,
{ {
info!("Loaded auth: {:?}", &self.auth); 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) .header("X-Transmission-Session-Id", self.get_session_id().await)
.json(&request); .json(&request);
info!("Request body: {:?}", rq.try_clone() info!(
"Request body: {:?}",
rq.try_clone()
.expect("Unable to get the request body") .expect("Unable to get the request body")
.body_string()?); .body_string()?
);
let resp: reqwest::Response = rq.send().await?; let resp: reqwest::Response = rq.send().await?;
let rpc_response: RpcResponse<RS> = resp.json().await?; let rpc_response: RpcResponse<RS> = resp.json().await?;
info!("Response body: {:#?}", rpc_response); info!("Response body: {:#?}", rpc_response);
@ -349,19 +375,25 @@ impl BodyString for reqwest::RequestBuilder {
mod tests { mod tests {
use super::*; use super::*;
use std::env;
use dotenv::dotenv; use dotenv::dotenv;
use std::env;
#[tokio::test] #[tokio::test]
pub async fn test_malformed_url() -> Result<()> { pub async fn test_malformed_url() -> Result<()> {
dotenv().ok(); dotenv().ok();
env_logger::init(); env_logger::init();
let url= env::var("TURL")?; let url = env::var("TURL")?;
let basic_auth = BasicAuth{user: env::var("TUSER")?, password: env::var("TPWD")?}; let basic_auth = BasicAuth {
user: env::var("TUSER")?,
password: env::var("TPWD")?,
};
let client = TransClient::with_auth(&url, basic_auth); let client = TransClient::with_auth(&url, basic_auth);
info!("Client is ready!"); info!("Client is ready!");
let add: TorrentAddArgs = TorrentAddArgs { 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() ..TorrentAddArgs::default()
}; };
match client.torrent_add(add).await { match client.torrent_add(add).await {

View File

@ -1,4 +1,3 @@
mod request; mod request;
mod response; mod response;
@ -10,18 +9,18 @@ pub struct BasicAuth {
pub password: String, pub password: String,
} }
pub(crate) use self::request::RpcRequest;
pub use self::request::ArgumentFields; 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::File;
pub use self::request::Id; 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 use self::response::RpcResponse;
pub(crate) use self::response::RpcResponseArgument; pub(crate) use self::response::RpcResponseArgument;
pub use self::response::SessionGet; pub use self::response::SessionGet;
pub use self::response::Torrents;
pub use self::response::Torrent; pub use self::response::Torrent;
pub use self::response::TorrentAdded; pub use self::response::TorrentAdded;
pub use self::response::Nothing; pub use self::response::Torrents;

View File

@ -1,10 +1,10 @@
use serde::Serialize;
use enum_iterator::IntoEnumIterator; use enum_iterator::IntoEnumIterator;
use serde::Serialize;
#[derive(Serialize, Debug, RustcEncodable)] #[derive(Serialize, Debug, RustcEncodable)]
pub struct RpcRequest { pub struct RpcRequest {
method: String, method: String,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
arguments: Option<Args>, arguments: Option<Args>,
} }
@ -17,47 +17,61 @@ impl RpcRequest {
} }
pub fn torrent_get(fields: Option<Vec<TorrentGetField>>, ids: Option<Vec<Id>>) -> RpcRequest { pub fn torrent_get(fields: Option<Vec<TorrentGetField>>, ids: Option<Vec<Id>>) -> RpcRequest {
let string_fields = fields.unwrap_or(TorrentGetField::all()).iter().map(|f| f.to_str()).collect(); let string_fields = fields
.unwrap_or(TorrentGetField::all())
.iter()
.map(|f| f.to_str())
.collect();
RpcRequest { RpcRequest {
method: String::from("torrent-get"), method: String::from("torrent-get"),
arguments: Some ( Args::TorrentGetArgs(TorrentGetArgs { fields: Some(string_fields), ids } )), arguments: Some(Args::TorrentGetArgs(TorrentGetArgs {
fields: Some(string_fields),
ids,
})),
} }
} }
pub fn torrent_remove(ids: Vec<Id>, delete_local_data: bool) -> RpcRequest { pub fn torrent_remove(ids: Vec<Id>, delete_local_data: bool) -> RpcRequest {
RpcRequest { RpcRequest {
method: String::from("torrent-remove"), 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 { pub fn torrent_add(add: TorrentAddArgs) -> RpcRequest {
RpcRequest { RpcRequest {
method: String::from("torrent-add"), method: String::from("torrent-add"),
arguments: Some ( Args::TorrentAddArgs(add) ) arguments: Some(Args::TorrentAddArgs(add)),
} }
} }
pub fn torrent_action(action: TorrentAction, ids: Vec<Id>) -> RpcRequest { pub fn torrent_action(action: TorrentAction, ids: Vec<Id>) -> RpcRequest {
RpcRequest { RpcRequest {
method: action.to_str(), method: action.to_str(),
arguments: Some ( Args::TorrentActionArgs(TorrentActionArgs { ids })), arguments: Some(Args::TorrentActionArgs(TorrentActionArgs { ids })),
} }
} }
pub fn torrent_set_location(ids: Vec<Id>, location: String, move_from: Option<bool>) -> RpcRequest { pub fn torrent_set_location(ids: Vec<Id>, location: String, move_from: Option<bool>, ) -> RpcRequest {
RpcRequest { RpcRequest {
method: String::from("torrent-set-location"), 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 {} pub trait ArgumentFields {}
impl ArgumentFields for TorrentGetField{} impl ArgumentFields for TorrentGetField {}
#[derive(Serialize, Debug, RustcEncodable, Clone)] #[derive(Serialize, Debug, RustcEncodable, Clone)]
#[serde(untagged)] #[serde(untagged)]
pub enum Args{ pub enum Args {
TorrentGetArgs(TorrentGetArgs), TorrentGetArgs(TorrentGetArgs),
TorrentActionArgs(TorrentActionArgs), TorrentActionArgs(TorrentActionArgs),
TorrentRemoveArgs(TorrentRemoveArgs), TorrentRemoveArgs(TorrentRemoveArgs),
@ -67,18 +81,20 @@ pub enum Args{
#[derive(Serialize, Debug, RustcEncodable, Clone)] #[derive(Serialize, Debug, RustcEncodable, Clone)]
pub struct TorrentGetArgs { pub struct TorrentGetArgs {
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
fields: Option<Vec<String>>, fields: Option<Vec<String>>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
ids: Option<Vec<Id>>, ids: Option<Vec<Id>>,
} }
impl Default for TorrentGetArgs { impl Default for TorrentGetArgs {
fn default() -> Self { 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 { TorrentGetArgs {
fields: Some(all_fields), fields: Some(all_fields),
ids: None ids: None,
} }
} }
} }
@ -90,55 +106,55 @@ pub struct TorrentActionArgs {
#[derive(Serialize, Debug, RustcEncodable, Clone)] #[derive(Serialize, Debug, RustcEncodable, Clone)]
pub struct TorrentRemoveArgs { pub struct TorrentRemoveArgs {
ids: Vec<Id>, ids: Vec<Id>,
#[serde(rename="delete-local-data")] #[serde(rename = "delete-local-data")]
delete_local_data: bool delete_local_data: bool,
} }
#[derive(Serialize, Debug, RustcEncodable, Clone)] #[derive(Serialize, Debug, RustcEncodable, Clone)]
pub struct TorrentSetLocationArgs { pub struct TorrentSetLocationArgs {
ids: Vec<Id>, ids: Vec<Id>,
location: String, location: String,
#[serde(skip_serializing_if="Option::is_none", rename="move")] #[serde(skip_serializing_if = "Option::is_none", rename = "move")]
move_from: Option<bool> move_from: Option<bool>,
} }
#[derive(Serialize, Debug, RustcEncodable, Clone)] #[derive(Serialize, Debug, RustcEncodable, Clone)]
#[serde(untagged)] #[serde(untagged)]
pub enum Id { pub enum Id {
Id(i64), Id(i64),
Hash(String) Hash(String),
} }
#[derive(Serialize, Debug, RustcEncodable, Clone)] #[derive(Serialize, Debug, RustcEncodable, Clone)]
pub struct TorrentAddArgs { pub struct TorrentAddArgs {
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub cookies: Option<String>, pub cookies: Option<String>,
#[serde(skip_serializing_if="Option::is_none", rename="download-dir")] #[serde(skip_serializing_if = "Option::is_none", rename = "download-dir")]
pub download_dir: Option<String>, pub download_dir: Option<String>,
/// Either "filename" OR "metainfo" MUST be included /// Either "filename" OR "metainfo" MUST be included
/// semi-optional /// semi-optional
/// filename or URL of the .torrent file /// filename or URL of the .torrent file
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub filename: Option<String>, pub filename: Option<String>,
/// semi-optional /// semi-optional
/// base64-encoded .torrent content /// base64-encoded .torrent content
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub metainfo: Option<String>, pub metainfo: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub paused: Option<bool>, pub paused: Option<bool>,
#[serde(skip_serializing_if="Option::is_none", rename="peer-limit")] #[serde(skip_serializing_if = "Option::is_none", rename = "peer-limit")]
pub peer_limit: Option<i64>, pub peer_limit: Option<i64>,
#[serde(skip_serializing_if="Option::is_none", rename="bandwidthPriority")] #[serde(skip_serializing_if = "Option::is_none", rename = "bandwidthPriority")]
pub bandwidth_priority: Option<i64>, pub bandwidth_priority: Option<i64>,
#[serde(skip_serializing_if="Option::is_none", rename="files-wanted")] #[serde(skip_serializing_if = "Option::is_none", rename = "files-wanted")]
pub files_wanted: Option<Vec<File>>, pub files_wanted: Option<Vec<File>>,
#[serde(skip_serializing_if="Option::is_none", rename="files-unwanted")] #[serde(skip_serializing_if = "Option::is_none", rename = "files-unwanted")]
pub files_unwanted: Option<Vec<File>>, pub files_unwanted: Option<Vec<File>>,
#[serde(skip_serializing_if="Option::is_none", rename="priority-high")] #[serde(skip_serializing_if = "Option::is_none", rename = "priority-high")]
pub priority_high: Option<Vec<File>>, pub priority_high: Option<Vec<File>>,
#[serde(skip_serializing_if="Option::is_none", rename="priority-low")] #[serde(skip_serializing_if = "Option::is_none", rename = "priority-low")]
pub priority_low: Option<Vec<File>>, pub priority_low: Option<Vec<File>>,
#[serde(skip_serializing_if="Option::is_none", rename="priority-normal")] #[serde(skip_serializing_if = "Option::is_none", rename = "priority-normal")]
pub priority_normal: Option<Vec<File>>, pub priority_normal: Option<Vec<File>>,
} }
@ -156,7 +172,7 @@ impl Default for TorrentAddArgs {
files_unwanted: None, files_unwanted: None,
priority_high: None, priority_high: None,
priority_low: None, priority_low: None,
priority_normal: None priority_normal: None,
} }
} }
} }

View File

@ -2,7 +2,7 @@ use serde::Deserialize;
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
pub struct RpcResponse<T: RpcResponseArgument> { pub struct RpcResponse<T: RpcResponseArgument> {
pub arguments: T, pub arguments: T,
pub result: String pub result: String,
} }
impl<T: RpcResponseArgument> RpcResponse<T> { impl<T: RpcResponseArgument> RpcResponse<T> {
@ -14,74 +14,74 @@ pub trait RpcResponseArgument {}
#[derive(Deserialize, Debug, Clone)] #[derive(Deserialize, Debug, Clone)]
pub struct SessionGet { pub struct SessionGet {
#[serde(rename="blocklist-enabled")] #[serde(rename = "blocklist-enabled")]
pub blocklist_enabled: bool, pub blocklist_enabled: bool,
#[serde(rename="download-dir")] #[serde(rename = "download-dir")]
pub download_dir: String, pub download_dir: String,
pub encryption: String, pub encryption: String,
#[serde(rename="rpc-version")] #[serde(rename = "rpc-version")]
pub rpc_version: i32, pub rpc_version: i32,
#[serde(rename="rpc-version-minimum")] #[serde(rename = "rpc-version-minimum")]
pub rpc_version_minimum: i32, pub rpc_version_minimum: i32,
pub version: String, pub version: String,
} }
impl RpcResponseArgument for SessionGet{} impl RpcResponseArgument for SessionGet {}
#[derive(Deserialize, Debug, RustcEncodable, Clone)] #[derive(Deserialize, Debug, RustcEncodable, Clone)]
pub struct Torrent { pub struct Torrent {
#[serde(rename="addedDate")] #[serde(rename = "addedDate")]
pub added_date: Option<i64>, pub added_date: Option<i64>,
#[serde(rename="downloadDir")] #[serde(rename = "downloadDir")]
pub download_dir: Option<String>, pub download_dir: Option<String>,
pub error: Option<i64>, pub error: Option<i64>,
#[serde(rename="errorString")] #[serde(rename = "errorString")]
pub error_string: Option<String>, pub error_string: Option<String>,
pub eta: Option<i64>, pub eta: Option<i64>,
pub id: Option<i64>, pub id: Option<i64>,
#[serde(rename="isFinished")] #[serde(rename = "isFinished")]
pub is_finished: Option<bool>, pub is_finished: Option<bool>,
#[serde(rename="isStalled")] #[serde(rename = "isStalled")]
pub is_stalled: Option<bool>, pub is_stalled: Option<bool>,
#[serde(rename="leftUntilDone")] #[serde(rename = "leftUntilDone")]
pub left_until_done: Option<i64>, pub left_until_done: Option<i64>,
#[serde(rename="metadataPercentComplete")] #[serde(rename = "metadataPercentComplete")]
pub metadata_percent_complete: Option<f32>, pub metadata_percent_complete: Option<f32>,
pub name: Option<String>, pub name: Option<String>,
#[serde(rename="hashString")] #[serde(rename = "hashString")]
pub hash_string: Option<String>, pub hash_string: Option<String>,
#[serde(rename="peersConnected")] #[serde(rename = "peersConnected")]
pub peers_connected: Option<i64>, pub peers_connected: Option<i64>,
#[serde(rename="peersGettingFromUs")] #[serde(rename = "peersGettingFromUs")]
pub peers_getting_from_us: Option<i64>, pub peers_getting_from_us: Option<i64>,
#[serde(rename="peersSendingToUs")] #[serde(rename = "peersSendingToUs")]
pub peers_sending_to_us: Option<i64>, pub peers_sending_to_us: Option<i64>,
#[serde(rename="percentDone")] #[serde(rename = "percentDone")]
pub percent_done: Option<f32>, pub percent_done: Option<f32>,
#[serde(rename="rateDownload")] #[serde(rename = "rateDownload")]
pub rate_download: Option<i64>, pub rate_download: Option<i64>,
#[serde(rename="rateUpload")] #[serde(rename = "rateUpload")]
pub rate_upload: Option<i64>, pub rate_upload: Option<i64>,
#[serde(rename="recheckProgress")] #[serde(rename = "recheckProgress")]
pub recheck_progress: Option<f32>, pub recheck_progress: Option<f32>,
#[serde(rename="seedRatioLimit")] #[serde(rename = "seedRatioLimit")]
pub seed_ratio_limit: Option<f32>, pub seed_ratio_limit: Option<f32>,
#[serde(rename="sizeWhenDone")] #[serde(rename = "sizeWhenDone")]
pub size_when_done: Option<i64>, pub size_when_done: Option<i64>,
pub status: Option<i64>, pub status: Option<i64>,
#[serde(rename="totalSize")] #[serde(rename = "totalSize")]
pub total_size: Option<i64>, pub total_size: Option<i64>,
pub trackers: Option<Vec<Trackers>>, pub trackers: Option<Vec<Trackers>>,
#[serde(rename="uploadRatio")] #[serde(rename = "uploadRatio")]
pub upload_ratio: Option<f32>, pub upload_ratio: Option<f32>,
#[serde(rename="uploadedEver")] #[serde(rename = "uploadedEver")]
pub uploaded_ever: Option<i64>, pub uploaded_ever: Option<i64>,
} }
#[derive(Deserialize, Debug, RustcEncodable)] #[derive(Deserialize, Debug, RustcEncodable)]
pub struct Torrents<T> { pub struct Torrents<T> {
pub torrents: Vec<T> pub torrents: Vec<T>,
} }
impl RpcResponseArgument for Torrents<Torrent>{} impl RpcResponseArgument for Torrents<Torrent> {}
#[derive(Deserialize, Debug, RustcEncodable, Clone)] #[derive(Deserialize, Debug, RustcEncodable, Clone)]
pub struct Trackers { pub struct Trackers {
@ -90,12 +90,12 @@ pub struct Trackers {
} }
#[derive(Deserialize, Debug, RustcEncodable)] #[derive(Deserialize, Debug, RustcEncodable)]
pub struct Nothing{} pub struct Nothing {}
impl RpcResponseArgument for Nothing {} impl RpcResponseArgument for Nothing {}
#[derive(Deserialize, Debug, RustcEncodable)] #[derive(Deserialize, Debug, RustcEncodable)]
pub struct TorrentAdded { pub struct TorrentAdded {
#[serde(rename="torrent-added")] #[serde(rename = "torrent-added")]
pub torrent_added: Option<Torrent> pub torrent_added: Option<Torrent>,
} }
impl RpcResponseArgument for TorrentAdded{} impl RpcResponseArgument for TorrentAdded {}