forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.rs
More file actions
200 lines (162 loc) · 6.21 KB
/
client.rs
File metadata and controls
200 lines (162 loc) · 6.21 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use std::time::Duration;
use hyper::HeaderMap;
use reqwest::{Error, Response};
use serde::Serialize;
use url::Url;
use uuid::Uuid;
use crate::common::http::{Query, QueryParam, ReqwestQuery};
use crate::connection_info::ConnectionInfo;
const TOKEN_PARAM_NAME: &str = "token";
const API_PATH: &str = "api/v1/";
const DEFAULT_REQUEST_TIMEOUT_IN_SECS: u64 = 5;
/// API Client
pub struct Client {
connection_info: ConnectionInfo,
base_path: String,
client: reqwest::Client,
}
impl Client {
/// # Errors
///
/// Will return an error if the HTTP client can't be created.
pub fn new(connection_info: ConnectionInfo) -> Result<Self, Error> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(DEFAULT_REQUEST_TIMEOUT_IN_SECS))
.build()?;
Ok(Self {
connection_info,
base_path: API_PATH.to_string(),
client,
})
}
pub async fn generate_auth_key(&self, seconds_valid: i32, headers: Option<HeaderMap>) -> Response {
self.post_empty(&format!("key/{}", &seconds_valid), headers).await
}
pub async fn add_auth_key(&self, add_key_form: AddKeyForm, headers: Option<HeaderMap>) -> Response {
self.post_form("keys", &add_key_form, headers).await
}
pub async fn delete_auth_key(&self, key: &str, headers: Option<HeaderMap>) -> Response {
self.delete(&format!("key/{}", &key), headers).await
}
pub async fn reload_keys(&self, headers: Option<HeaderMap>) -> Response {
self.get("keys/reload", Query::default(), headers).await
}
pub async fn whitelist_a_torrent(&self, info_hash: &str, headers: Option<HeaderMap>) -> Response {
self.post_empty(&format!("whitelist/{}", &info_hash), headers).await
}
pub async fn remove_torrent_from_whitelist(&self, info_hash: &str, headers: Option<HeaderMap>) -> Response {
self.delete(&format!("whitelist/{}", &info_hash), headers).await
}
pub async fn reload_whitelist(&self, headers: Option<HeaderMap>) -> Response {
self.get("whitelist/reload", Query::default(), headers).await
}
pub async fn get_torrent(&self, info_hash: &str, headers: Option<HeaderMap>) -> Response {
self.get(&format!("torrent/{}", &info_hash), Query::default(), headers).await
}
pub async fn get_torrents(&self, params: Query, headers: Option<HeaderMap>) -> Response {
self.get("torrents", params, headers).await
}
pub async fn get_tracker_statistics(&self, headers: Option<HeaderMap>) -> Response {
self.get("stats", Query::default(), headers).await
}
pub async fn get(&self, path: &str, params: Query, headers: Option<HeaderMap>) -> Response {
let mut query: Query = params;
if let Some(token) = &self.connection_info.api_token {
query.add_param(QueryParam::new(TOKEN_PARAM_NAME, token));
}
self.get_request_with_query(path, query, headers).await
}
/// # Panics
///
/// Will panic if the request can't be sent
pub async fn post_empty(&self, path: &str, headers: Option<HeaderMap>) -> Response {
let builder = self
.client
.post(self.base_url(path).clone())
.query(&ReqwestQuery::from(self.query_with_token()));
let builder = match headers {
Some(headers) => builder.headers(headers),
None => builder,
};
builder.send().await.unwrap()
}
/// # Panics
///
/// Will panic if the request can't be sent
pub async fn post_form<T: Serialize + ?Sized>(&self, path: &str, form: &T, headers: Option<HeaderMap>) -> Response {
let builder = self
.client
.post(self.base_url(path).clone())
.query(&ReqwestQuery::from(self.query_with_token()))
.json(&form);
let builder = match headers {
Some(headers) => builder.headers(headers),
None => builder,
};
builder.send().await.unwrap()
}
/// # Panics
///
/// Will panic if the request can't be sent
async fn delete(&self, path: &str, headers: Option<HeaderMap>) -> Response {
let builder = self
.client
.delete(self.base_url(path).clone())
.query(&ReqwestQuery::from(self.query_with_token()));
let builder = match headers {
Some(headers) => builder.headers(headers),
None => builder,
};
builder.send().await.unwrap()
}
pub async fn get_request_with_query(&self, path: &str, params: Query, headers: Option<HeaderMap>) -> Response {
get(self.base_url(path), Some(params), headers).await
}
pub async fn get_request(&self, path: &str) -> Response {
get(self.base_url(path), None, None).await
}
fn query_with_token(&self) -> Query {
match &self.connection_info.api_token {
Some(token) => Query::params([QueryParam::new("token", token)].to_vec()),
None => Query::default(),
}
}
fn base_url(&self, path: &str) -> Url {
Url::parse(&format!("{}{}{path}", &self.connection_info.origin, &self.base_path)).unwrap()
}
}
/// # Panics
///
/// Will panic if the request can't be sent
pub async fn get(path: Url, query: Option<Query>, headers: Option<HeaderMap>) -> Response {
let builder = reqwest::Client::builder()
.timeout(Duration::from_secs(DEFAULT_REQUEST_TIMEOUT_IN_SECS))
.build()
.unwrap();
let builder = match query {
Some(params) => builder.get(path).query(&ReqwestQuery::from(params)),
None => builder.get(path),
};
let builder = match headers {
Some(headers) => builder.headers(headers),
None => builder,
};
builder.send().await.unwrap()
}
/// Returns a `HeaderMap` with a request id header
///
/// # Panics
///
/// Will panic if the request ID can't be parsed into a string.
#[must_use]
pub fn headers_with_request_id(request_id: Uuid) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert("x-request-id", request_id.to_string().parse().unwrap());
headers
}
#[derive(Serialize, Debug)]
pub struct AddKeyForm {
#[serde(rename = "key")]
pub opt_key: Option<String>,
pub seconds_valid: Option<u64>,
}