1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
//! Client for download management.

use std::collections::BTreeMap;
use std::convert::TryInto;

use serde::Serialize;

use crate::Error;
mod payload;
use payload::Request;
use payload::Response;
mod list;
use list::FieldList;
use list::TorrentList;
mod torrent;
use torrent::Torrent;
use torrent::AddTorrent;
use torrent::AddTorrentResponse;
//use torrent::AddedTorrent;

/// Interface into the major functions of Transmission
/// including adding, and removing torrents.
///
/// The `Client` does not keep track of the created torrents itself.
///
/// Example of creating a session and adding a torrent and waiting for it to complete.
/// ```no_run
/// use transmission::{ ClientConfig, Client};
///
/// # let test_dir = "/tmp/tr-test-long";
/// # let config_dir = test_dir;
/// # let download_dir = test_dir;
/// let file_path = "./alpine.torrent";
///
/// # std::fs::create_dir(test_dir).unwrap();
///
/// let c = ClientConfig::new()
///    .app_name("testing")
///    .config_dir(config_dir)
///    .download_dir(download_dir);
/// let mut c = Client::new(c);
///
/// let t = c.add_torrent_file(file_path).unwrap();
/// t.start();
///
/// // Run until done
/// while t.stats().percent_complete < 1.0 {
///     print!("{:#?}\r", t.stats().percent_complete);
/// }
/// c.close();
///
/// # std::fs::remove_dir_all(test_dir).unwrap();
/// ```
#[derive(Clone)]
pub struct Client {
	host: String,
	port: u16,
	tls: bool,
	auth: Option<(String, String)>,

	base_url: String,
	session_id: Option<String>,

	http: reqwest::Client,
}

impl Client {
	// TODO:  Take Option<(&str, &str)> for auth
	pub fn new(host: impl ToString, port: u16, tls: bool, auth: Option<(String, String)>) -> Result<Self, Error> {
		let mut headers = reqwest::header::HeaderMap::new();
		headers.insert(reqwest::header::USER_AGENT, "transmission-rs/0.1".try_into()?);
		let this = Self{
			host: host.to_string(),
			port: port,
			tls: tls,
			auth: auth,
			base_url: {
				let protocol = match tls {
					true => "https",
					false => "http"
				};
				format!("{}://{}:{}", protocol, host.to_string(), port)
			},
			session_id: None,
			http: reqwest::Client::builder()
				.gzip(true)
				.default_headers(headers)
				.build()?
		};
		Ok(this)
	}

	fn build_url(&self, path: impl AsRef<str>) -> String {
		format!("{}{}", self.base_url, path.as_ref()).to_string()
	}

	pub async fn authenticate(&mut self) -> Result<(), Error> {
		let response = self.post("/transmission/rpc/")
			.header("Content-Type", "application/x-www-form-urlencoded")
			.send()
			.await?;
		self.session_id = match response.headers().get("X-Transmission-Session-Id") {
			Some(v) => Some(v.to_str()?.to_string()),
			None => None // TODO:  Return an error
		};
		Ok(())
	}

	pub fn post(&self, path: impl AsRef<str>) -> reqwest::RequestBuilder {
		let url = self.build_url(path);
		//println!("{}", url);
		let mut request = self.http.post(&url);
		request = match &self.auth {
			Some(auth) => request.basic_auth(&auth.0, Some(&auth.1)),
			None => request
		};
		request = match &self.session_id {
			Some(token) => request.header("X-Transmission-Session-Id", token),
			None => request
		};
		request
	}

	pub async fn rpc(&self, method: impl ToString, tag: u8, body: impl Serialize) -> Result<reqwest::Response, Error> {
		let request = Request::new(method, tag, body);
		Ok(self.post("/transmission/rpc/")
			// Content-Type doesn't actually appear to be necessary, and is
			//    technically a lie, since there's no key/value being passed,
			//    just some JSON, but the official client sends this, so we
			//    will too.
			.header("Content-Type", "application/x-www-form-urlencoded")
			.body(serde_json::to_string(&request)?)
			.send().await?
			.error_for_status()?
		)
	}

	pub async fn list(&self) -> Result<Vec<Torrent>, Error> {
		let response: Response<TorrentList> = self.rpc("torrent-get", 4, FieldList::new()).await?.error_for_status()?.json().await?;
		Ok(response.arguments.torrents)
	}

	// TODO:  Borrow key from value
	pub async fn list_by_name(&self) -> Result<BTreeMap<String, Torrent>, Error> {
		Ok(self.list().await?.into_iter().map(|v| (v.name.clone(), v)).collect::<BTreeMap<_, _>>())
	}

	pub async fn add_torrent_from_link(&self, url: impl ToString) -> Result<AddTorrentResponse, Error> {
		let response: Response<AddTorrentResponse> = self.rpc("torrent-add", 8, AddTorrent{filename: url.to_string()}).await?.error_for_status()?.json().await?;
		Ok(response.arguments)
	}
}