forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.rs
More file actions
380 lines (315 loc) · 12.6 KB
/
api.rs
File metadata and controls
380 lines (315 loc) · 12.6 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/// Integration tests for the tracker API
///
/// cargo test `tracker_api` -- --nocapture
extern crate rand;
mod common;
mod tracker_api {
use core::panic;
use std::env;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes};
use reqwest::Response;
use tokio::task::JoinHandle;
use torrust_tracker::api::resource;
use torrust_tracker::api::resource::auth_key::AuthKey;
use torrust_tracker::api::resource::stats::Stats;
use torrust_tracker::api::resource::torrent::{self, Torrent};
use torrust_tracker::config::Configuration;
use torrust_tracker::jobs::tracker_api;
use torrust_tracker::protocol::clock::DurationSinceUnixEpoch;
use torrust_tracker::protocol::info_hash::InfoHash;
use torrust_tracker::tracker::statistics::Keeper;
use torrust_tracker::tracker::{auth, peer};
use torrust_tracker::{ephemeral_instance_keys, logging, static_time, tracker};
use crate::common::ephemeral_random_port;
#[tokio::test]
async fn should_allow_generating_a_new_auth_key() {
let api_server = ApiServer::new_running_instance().await;
let seconds_valid = 60;
let auth_key = ApiClient::new(api_server.get_connection_info().unwrap())
.generate_auth_key(seconds_valid)
.await;
// Verify the key with the tracker
assert!(api_server
.tracker
.unwrap()
.verify_auth_key(&auth::Key::from(auth_key))
.await
.is_ok());
}
#[tokio::test]
async fn should_allow_whitelisting_a_torrent() {
let api_server = ApiServer::new_running_instance().await;
let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned();
let res = ApiClient::new(api_server.get_connection_info().unwrap())
.whitelist_a_torrent(&info_hash)
.await;
assert_eq!(res.status(), 200);
assert!(
api_server
.tracker
.unwrap()
.is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap())
.await
);
}
#[tokio::test]
async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() {
let api_server = ApiServer::new_running_instance().await;
let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned();
let api_client = ApiClient::new(api_server.get_connection_info().unwrap());
let res = api_client.whitelist_a_torrent(&info_hash).await;
assert_eq!(res.status(), 200);
let res = api_client.whitelist_a_torrent(&info_hash).await;
assert_eq!(res.status(), 200);
}
#[tokio::test]
async fn should_allow_getting_a_torrent_info() {
let api_server = ApiServer::new_running_instance().await;
let api_connection_info = api_server.get_connection_info().unwrap();
let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap();
let (peer, peer_resource) = sample_torrent_peer();
// Add a torrent to the tracker
api_server
.tracker
.unwrap()
.update_torrent_with_peer_and_get_stats(&info_hash, &peer)
.await;
let torrent_resource = ApiClient::new(api_connection_info).get_torrent(&info_hash.to_string()).await;
assert_eq!(
torrent_resource,
Torrent {
info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(),
seeders: 1,
completed: 0,
leechers: 0,
peers: Some(vec![peer_resource])
}
);
}
#[tokio::test]
async fn should_allow_getting_torrents() {
let api_server = ApiServer::new_running_instance().await;
let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap();
let (peer, _peer_resource) = sample_torrent_peer();
let api_connection_info = api_server.get_connection_info().unwrap();
// Add a torrent to the tracker
api_server
.tracker
.unwrap()
.update_torrent_with_peer_and_get_stats(&info_hash, &peer)
.await;
let torrent_resources = ApiClient::new(api_connection_info).get_torrents().await;
assert_eq!(
torrent_resources,
vec![torrent::ListItem {
info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(),
seeders: 1,
completed: 0,
leechers: 0,
peers: None // Torrent list does not include peer list
}]
);
}
#[tokio::test]
async fn should_allow_getting_tracker_statistics() {
let api_server = ApiServer::new_running_instance().await;
let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap();
let (peer, _peer_resource) = sample_torrent_peer();
let api_connection_info = api_server.get_connection_info().unwrap();
// Add a torrent to the tracker
api_server
.tracker
.unwrap()
.update_torrent_with_peer_and_get_stats(&info_hash, &peer)
.await;
let stats_resource = ApiClient::new(api_connection_info).get_tracker_statistics().await;
assert_eq!(
stats_resource,
Stats {
torrents: 1,
seeders: 1,
completed: 0,
leechers: 0,
tcp4_connections_handled: 0,
tcp4_announces_handled: 0,
tcp4_scrapes_handled: 0,
tcp6_connections_handled: 0,
tcp6_announces_handled: 0,
tcp6_scrapes_handled: 0,
udp4_connections_handled: 0,
udp4_announces_handled: 0,
udp4_scrapes_handled: 0,
udp6_connections_handled: 0,
udp6_announces_handled: 0,
udp6_scrapes_handled: 0,
}
);
}
fn sample_torrent_peer() -> (peer::Peer, resource::peer::Peer) {
let torrent_peer = peer::Peer {
peer_id: peer::Id(*b"-qB00000000000000000"),
peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080),
updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0),
uploaded: NumberOfBytes(0),
downloaded: NumberOfBytes(0),
left: NumberOfBytes(0),
event: AnnounceEvent::Started,
};
let torrent_peer_resource = resource::peer::Peer::from(torrent_peer);
(torrent_peer, torrent_peer_resource)
}
fn tracker_configuration() -> Arc<Configuration> {
let mut config = Configuration::default();
config.log_level = Some("off".to_owned());
// Ephemeral socket address
let port = ephemeral_random_port();
config.http_api.bind_address = format!("127.0.0.1:{}", &port);
// Ephemeral database
let temp_directory = env::temp_dir();
let temp_file = temp_directory.join(format!("data_{}.db", &port));
config.db_path = temp_file.to_str().unwrap().to_owned();
Arc::new(config)
}
#[derive(Clone)]
struct ApiConnectionInfo {
pub bind_address: String,
pub api_token: String,
}
impl ApiConnectionInfo {
pub fn new(bind_address: &str, api_token: &str) -> Self {
Self {
bind_address: bind_address.to_string(),
api_token: api_token.to_string(),
}
}
}
struct ApiServer {
pub started: AtomicBool,
pub job: Option<JoinHandle<()>>,
pub tracker: Option<Arc<tracker::Tracker>>,
pub connection_info: Option<ApiConnectionInfo>,
}
impl ApiServer {
pub fn new() -> Self {
Self {
started: AtomicBool::new(false),
job: None,
tracker: None,
connection_info: None,
}
}
pub async fn new_running_instance() -> ApiServer {
let configuration = tracker_configuration();
ApiServer::new_running_custom_instance(configuration.clone()).await
}
async fn new_running_custom_instance(configuration: Arc<Configuration>) -> ApiServer {
let mut api_server = ApiServer::new();
api_server.start(configuration).await;
api_server
}
pub async fn start(&mut self, configuration: Arc<Configuration>) {
if !self.started.load(Ordering::Relaxed) {
self.connection_info = Some(ApiConnectionInfo::new(
&configuration.http_api.bind_address.clone(),
&configuration.http_api.access_tokens.get_key_value("admin").unwrap().1.clone(),
));
// Set the time of Torrust app starting
lazy_static::initialize(&static_time::TIME_AT_APP_START);
// Initialize the Ephemeral Instance Random Seed
lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED);
// Initialize stats tracker
let (stats_event_sender, stats_repository) = Keeper::new_active_instance();
// Initialize Torrust tracker
let tracker = match tracker::Tracker::new(&configuration.clone(), Some(stats_event_sender), stats_repository) {
Ok(tracker) => Arc::new(tracker),
Err(error) => {
panic!("{}", error)
}
};
self.tracker = Some(tracker.clone());
// Initialize logging
logging::setup(&configuration);
// Start the HTTP API job
self.job = Some(tracker_api::start_job(&configuration, tracker).await);
self.started.store(true, Ordering::Relaxed);
}
}
pub fn get_connection_info(&self) -> Option<ApiConnectionInfo> {
self.connection_info.clone()
}
}
struct ApiClient {
connection_info: ApiConnectionInfo,
}
impl ApiClient {
pub fn new(connection_info: ApiConnectionInfo) -> Self {
Self { connection_info }
}
pub async fn generate_auth_key(&self, seconds_valid: i32) -> AuthKey {
let url = format!(
"http://{}/api/key/{}?token={}",
&self.connection_info.bind_address, &seconds_valid, &self.connection_info.api_token
);
reqwest::Client::new().post(url).send().await.unwrap().json().await.unwrap()
}
pub async fn whitelist_a_torrent(&self, info_hash: &str) -> Response {
let url = format!(
"http://{}/api/whitelist/{}?token={}",
&self.connection_info.bind_address, &info_hash, &self.connection_info.api_token
);
reqwest::Client::new().post(url.clone()).send().await.unwrap()
}
pub async fn get_torrent(&self, info_hash: &str) -> Torrent {
let url = format!(
"http://{}/api/torrent/{}?token={}",
&self.connection_info.bind_address, &info_hash, &self.connection_info.api_token
);
reqwest::Client::builder()
.build()
.unwrap()
.get(url)
.send()
.await
.unwrap()
.json::<Torrent>()
.await
.unwrap()
}
pub async fn get_torrents(&self) -> Vec<torrent::ListItem> {
let url = format!(
"http://{}/api/torrents?token={}",
&self.connection_info.bind_address, &self.connection_info.api_token
);
reqwest::Client::builder()
.build()
.unwrap()
.get(url)
.send()
.await
.unwrap()
.json::<Vec<torrent::ListItem>>()
.await
.unwrap()
}
pub async fn get_tracker_statistics(&self) -> Stats {
let url = format!(
"http://{}/api/stats?token={}",
&self.connection_info.bind_address, &self.connection_info.api_token
);
reqwest::Client::builder()
.build()
.unwrap()
.get(url)
.send()
.await
.unwrap()
.json::<Stats>()
.await
.unwrap()
}
}
}