forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
220 lines (192 loc) · 6.4 KB
/
mod.rs
File metadata and controls
220 lines (192 loc) · 6.4 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
pub mod requests;
pub mod responses;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use derive_more::Display;
use hyper::StatusCode;
use requests::{announce, scrape};
use reqwest::{Response, Url};
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Debug, Clone, Error)]
pub enum Error {
#[error("Failed to Build a Http Client: {err:?}")]
ClientBuildingError { err: Arc<reqwest::Error> },
#[error("Failed to get a response: {err:?}")]
ResponseError { err: Arc<reqwest::Error> },
#[error("Returned a non-success code: \"{code}\" with the response: \"{response:?}\"")]
UnsuccessfulResponse { code: StatusCode, response: Arc<Response> },
}
/// HTTP Tracker Client
pub struct Client {
client: reqwest::Client,
base_url: Url,
key: Option<Key>,
}
/// URL components in this context:
///
/// ```text
/// http://127.0.0.1:62304/announce/YZ....rJ?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22
/// \_____________________/\_______________/ \__________________________________________________________/
/// | | |
/// base url path query
/// ```
impl Client {
/// # Errors
///
/// This method fails if the client builder fails.
pub fn new(base_url: Url, timeout: Duration) -> Result<Self, Error> {
let client = reqwest::Client::builder()
.timeout(timeout)
.build()
.map_err(|e| Error::ClientBuildingError { err: e.into() })?;
Ok(Self {
base_url,
client,
key: None,
})
}
/// Creates the new client binding it to an specific local address.
///
/// # Errors
///
/// This method fails if the client builder fails.
pub fn bind(base_url: Url, timeout: Duration, local_address: IpAddr) -> Result<Self, Error> {
let client = reqwest::Client::builder()
.timeout(timeout)
.local_address(local_address)
.build()
.map_err(|e| Error::ClientBuildingError { err: e.into() })?;
Ok(Self {
base_url,
client,
key: None,
})
}
/// # Errors
///
/// This method fails if the client builder fails.
pub fn authenticated(base_url: Url, timeout: Duration, key: Key) -> Result<Self, Error> {
let client = reqwest::Client::builder()
.timeout(timeout)
.build()
.map_err(|e| Error::ClientBuildingError { err: e.into() })?;
Ok(Self {
base_url,
client,
key: Some(key),
})
}
/// # Errors
///
/// This method fails if the returned response was not successful
pub async fn announce(&self, query: &announce::Query) -> Result<Response, Error> {
let response = self.get(&self.build_announce_path_and_query(query)).await?;
if response.status().is_success() {
Ok(response)
} else {
Err(Error::UnsuccessfulResponse {
code: response.status(),
response: response.into(),
})
}
}
/// # Errors
///
/// This method fails if the returned response was not successful
pub async fn scrape(&self, query: &scrape::Query) -> Result<Response, Error> {
let response = self.get(&self.build_scrape_path_and_query(query)).await?;
if response.status().is_success() {
Ok(response)
} else {
Err(Error::UnsuccessfulResponse {
code: response.status(),
response: response.into(),
})
}
}
/// # Errors
///
/// This method fails if the returned response was not successful
pub async fn announce_with_header(&self, query: &announce::Query, key: &str, value: &str) -> Result<Response, Error> {
let response = self
.get_with_header(&self.build_announce_path_and_query(query), key, value)
.await?;
if response.status().is_success() {
Ok(response)
} else {
Err(Error::UnsuccessfulResponse {
code: response.status(),
response: response.into(),
})
}
}
/// # Errors
///
/// This method fails if the returned response was not successful
pub async fn health_check(&self) -> Result<Response, Error> {
let response = self.get(&self.build_path("health_check")).await?;
if response.status().is_success() {
Ok(response)
} else {
Err(Error::UnsuccessfulResponse {
code: response.status(),
response: response.into(),
})
}
}
/// # Errors
///
/// This method fails if there was an error while sending request.
pub async fn get(&self, path: &str) -> Result<Response, Error> {
self.client
.get(self.build_url(path))
.send()
.await
.map_err(|e| Error::ResponseError { err: e.into() })
}
/// # Errors
///
/// This method fails if there was an error while sending request.
pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Result<Response, Error> {
self.client
.get(self.build_url(path))
.header(key, value)
.send()
.await
.map_err(|e| Error::ResponseError { err: e.into() })
}
fn build_announce_path_and_query(&self, query: &announce::Query) -> String {
format!("{}?{query}", self.build_path("announce"))
}
fn build_scrape_path_and_query(&self, query: &scrape::Query) -> String {
format!("{}?{query}", self.build_path("scrape"))
}
fn build_path(&self, path: &str) -> String {
match &self.key {
Some(key) => format!("{path}/{key}"),
None => path.to_string(),
}
}
fn build_url(&self, path: &str) -> String {
let base_url = self.base_url();
format!("{base_url}{path}")
}
fn base_url(&self) -> String {
self.base_url.to_string()
}
}
/// A token used for authentication.
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)]
pub struct Key(String);
impl Key {
#[must_use]
pub fn new(value: &str) -> Self {
Self(value.to_owned())
}
#[must_use]
pub fn value(&self) -> &str {
&self.0
}
}