mirror of
https://github.com/kristoferssolo/transmission-rpc.git
synced 2025-10-21 20:10:37 +00:00
Format the code with rustfmt
This commit is contained in:
parent
510b79e57e
commit
2ca1444f18
@ -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<RpcResponse<SessionGet>> = 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(())
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<Nothing> = client.torrent_action(TorrentAction::Start, vec![Id::Id(1)]).await?;
|
||||
println!("Start result: {:?}", &res1.is_ok());
|
||||
let res2: RpcResponse<Nothing> = client.torrent_action(TorrentAction::Stop, vec![Id::Id(1)]).await?;
|
||||
println!("Stop result: {:?}", &res2.is_ok());
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<TorrentAdded> = client.torrent_add(add).await?;
|
||||
println!("Add result: {:?}", &res.is_ok());
|
||||
println!("response: {:?}", &res);
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<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);
|
||||
|
||||
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 first_three: Vec<String> = res1.arguments.torrents.iter().map(|it|
|
||||
format!("{}. {}",&it.id.as_ref().unwrap(), &it.name.as_ref().unwrap())
|
||||
).collect();
|
||||
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 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);
|
||||
|
||||
|
||||
let res2: RpcResponse<Torrents<Torrent>> = client.torrent_get(Some(vec![TorrentGetField::Id, TorrentGetField::HashString, TorrentGetField::Name]), 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();
|
||||
let res2: RpcResponse<Torrents<Torrent>> = client
|
||||
.torrent_get(
|
||||
Some(vec![
|
||||
TorrentGetField::Id,
|
||||
TorrentGetField::HashString,
|
||||
TorrentGetField::Name,
|
||||
]),
|
||||
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);
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<Nothing> = client.torrent_remove(vec![Id::Id(1)], false).await?;
|
||||
println!("Remove result: {:?}", &res.is_ok());
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<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());
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
194
src/lib.rs
194
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<BasicAuth>
|
||||
auth: Option<BasicAuth>,
|
||||
}
|
||||
|
||||
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<reqwest::Response> = self.rpc_request()
|
||||
.json(&RpcRequest::session_get())
|
||||
.send()
|
||||
.await;
|
||||
let response: reqwest::Result<reqwest::Response> = 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<Torrents<Torrent>> = 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<Torrents<Torrent>> = 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<String> = res1.arguments.torrents.iter().map(|it|
|
||||
/// 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);
|
||||
///
|
||||
///
|
||||
///
|
||||
///
|
||||
/// let res2: RpcResponse<Torrents<Torrent>> = client.torrent_get(Some(vec![TorrentGetField::Id, TorrentGetField::HashString, TorrentGetField::Name]), Some(vec![Id::Hash(String::from("64b0d9a53ac9cd1002dad1e15522feddb00152fe"))])).await?;
|
||||
/// let info: Vec<String> = res2.arguments.torrents.iter().map(|it|
|
||||
/// format!("{:5}. {:^45} {}",
|
||||
/// 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())
|
||||
/// &it.hash_string.as_ref().unwrap(),
|
||||
/// &it.name.as_ref().unwrap())
|
||||
/// ).collect();
|
||||
/// println!("{:#?}", info);
|
||||
///
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// 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<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
|
||||
}
|
||||
|
||||
/// 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<Id>, delete_local_data: bool) -> Result<RpcResponse<Nothing>> {
|
||||
self.call( RpcRequest::torrent_remove(ids, delete_local_data)).await
|
||||
pub async fn torrent_remove(
|
||||
&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
|
||||
@ -265,27 +280,33 @@ impl TransClient {
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
pub async fn torrent_set_location(&self, ids: Vec<Id>, location: String, move_from: Option<bool>) -> Result<RpcResponse<Nothing>> {
|
||||
self.call(RpcRequest::torrent_set_location(ids, location, move_from)).await
|
||||
pub async fn torrent_set_location(
|
||||
&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
|
||||
///
|
||||
///
|
||||
/// # 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<RS> (&self, request: RpcRequest) -> Result<RpcResponse<RS>>
|
||||
where RS : RpcResponseArgument + DeserializeOwned + std::fmt::Debug
|
||||
async fn call<RS>(&self, request: RpcRequest) -> Result<RpcResponse<RS>>
|
||||
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<RS> = 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(())
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
pub use self::response::Torrents;
|
||||
|
||||
@ -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<Args>,
|
||||
}
|
||||
|
||||
impl RpcRequest {
|
||||
pub fn session_get() -> RpcRequest {
|
||||
RpcRequest {
|
||||
RpcRequest {
|
||||
method: String::from("session-get"),
|
||||
arguments: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
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<Id>, delete_local_data: bool) -> RpcRequest {
|
||||
pub fn torrent_remove(ids: Vec<Id>, 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<Id>) -> RpcRequest {
|
||||
RpcRequest {
|
||||
method: action.to_str(),
|
||||
arguments: Some ( Args::TorrentActionArgs(TorrentActionArgs { ids })),
|
||||
}
|
||||
}
|
||||
pub fn torrent_action(action: TorrentAction, ids: Vec<Id>) -> RpcRequest {
|
||||
RpcRequest {
|
||||
method: action.to_str(),
|
||||
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 {
|
||||
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<Vec<String>>,
|
||||
#[serde(skip_serializing_if="Option::is_none")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
ids: Option<Vec<Id>>,
|
||||
}
|
||||
|
||||
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<Id>,
|
||||
#[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<Id>,
|
||||
location: String,
|
||||
#[serde(skip_serializing_if="Option::is_none", rename="move")]
|
||||
move_from: Option<bool>
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename = "move")]
|
||||
move_from: Option<bool>,
|
||||
}
|
||||
|
||||
#[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<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>,
|
||||
/// 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<String>,
|
||||
/// semi-optional
|
||||
/// base64-encoded .torrent content
|
||||
#[serde(skip_serializing_if="Option::is_none")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub metainfo: Option<String>,
|
||||
#[serde(skip_serializing_if="Option::is_none")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
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>,
|
||||
#[serde(skip_serializing_if="Option::is_none", rename="bandwidthPriority")]
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename = "bandwidthPriority")]
|
||||
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>>,
|
||||
#[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>>,
|
||||
#[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>>,
|
||||
#[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>>,
|
||||
#[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>>,
|
||||
}
|
||||
|
||||
@ -156,7 +172,7 @@ impl Default for TorrentAddArgs {
|
||||
files_unwanted: None,
|
||||
priority_high: None,
|
||||
priority_low: None,
|
||||
priority_normal: None
|
||||
priority_normal: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,7 +2,7 @@ use serde::Deserialize;
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct RpcResponse<T: RpcResponseArgument> {
|
||||
pub arguments: T,
|
||||
pub result: String
|
||||
pub result: String,
|
||||
}
|
||||
|
||||
impl<T: RpcResponseArgument> RpcResponse<T> {
|
||||
@ -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<i64>,
|
||||
#[serde(rename="downloadDir")]
|
||||
#[serde(rename = "downloadDir")]
|
||||
pub download_dir: Option<String>,
|
||||
pub error: Option<i64>,
|
||||
#[serde(rename="errorString")]
|
||||
#[serde(rename = "errorString")]
|
||||
pub error_string: Option<String>,
|
||||
pub eta: Option<i64>,
|
||||
pub id: Option<i64>,
|
||||
#[serde(rename="isFinished")]
|
||||
#[serde(rename = "isFinished")]
|
||||
pub is_finished: Option<bool>,
|
||||
#[serde(rename="isStalled")]
|
||||
#[serde(rename = "isStalled")]
|
||||
pub is_stalled: Option<bool>,
|
||||
#[serde(rename="leftUntilDone")]
|
||||
#[serde(rename = "leftUntilDone")]
|
||||
pub left_until_done: Option<i64>,
|
||||
#[serde(rename="metadataPercentComplete")]
|
||||
#[serde(rename = "metadataPercentComplete")]
|
||||
pub metadata_percent_complete: Option<f32>,
|
||||
pub name: Option<String>,
|
||||
#[serde(rename="hashString")]
|
||||
#[serde(rename = "hashString")]
|
||||
pub hash_string: Option<String>,
|
||||
#[serde(rename="peersConnected")]
|
||||
#[serde(rename = "peersConnected")]
|
||||
pub peers_connected: Option<i64>,
|
||||
#[serde(rename="peersGettingFromUs")]
|
||||
#[serde(rename = "peersGettingFromUs")]
|
||||
pub peers_getting_from_us: Option<i64>,
|
||||
#[serde(rename="peersSendingToUs")]
|
||||
#[serde(rename = "peersSendingToUs")]
|
||||
pub peers_sending_to_us: Option<i64>,
|
||||
#[serde(rename="percentDone")]
|
||||
#[serde(rename = "percentDone")]
|
||||
pub percent_done: Option<f32>,
|
||||
#[serde(rename="rateDownload")]
|
||||
#[serde(rename = "rateDownload")]
|
||||
pub rate_download: Option<i64>,
|
||||
#[serde(rename="rateUpload")]
|
||||
#[serde(rename = "rateUpload")]
|
||||
pub rate_upload: Option<i64>,
|
||||
#[serde(rename="recheckProgress")]
|
||||
#[serde(rename = "recheckProgress")]
|
||||
pub recheck_progress: Option<f32>,
|
||||
#[serde(rename="seedRatioLimit")]
|
||||
#[serde(rename = "seedRatioLimit")]
|
||||
pub seed_ratio_limit: Option<f32>,
|
||||
#[serde(rename="sizeWhenDone")]
|
||||
#[serde(rename = "sizeWhenDone")]
|
||||
pub size_when_done: Option<i64>,
|
||||
pub status: Option<i64>,
|
||||
#[serde(rename="totalSize")]
|
||||
#[serde(rename = "totalSize")]
|
||||
pub total_size: Option<i64>,
|
||||
pub trackers: Option<Vec<Trackers>>,
|
||||
#[serde(rename="uploadRatio")]
|
||||
#[serde(rename = "uploadRatio")]
|
||||
pub upload_ratio: Option<f32>,
|
||||
#[serde(rename="uploadedEver")]
|
||||
pub uploaded_ever: Option<i64>,
|
||||
#[serde(rename = "uploadedEver")]
|
||||
pub uploaded_ever: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, RustcEncodable)]
|
||||
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)]
|
||||
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<Torrent>
|
||||
#[serde(rename = "torrent-added")]
|
||||
pub torrent_added: Option<Torrent>,
|
||||
}
|
||||
impl RpcResponseArgument for TorrentAdded{}
|
||||
impl RpcResponseArgument for TorrentAdded {}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user