torrust_index_backend/tracker/
api.rs

1use reqwest::{Error, Response};
2pub struct ConnectionInfo {
3    /// The URL of the tracker. Eg: <https://tracker:7070> or <udp://tracker:6969>
4    pub url: String,
5    /// The token used to authenticate with the tracker API.
6    pub token: String,
7}
8
9impl ConnectionInfo {
10    #[must_use]
11    pub fn new(url: String, token: String) -> Self {
12        Self { url, token }
13    }
14}
15
16pub struct Client {
17    pub connection_info: ConnectionInfo,
18    base_url: String,
19}
20
21impl Client {
22    #[must_use]
23    pub fn new(connection_info: ConnectionInfo) -> Self {
24        let base_url = format!("{}/api/v1", connection_info.url);
25        Self {
26            connection_info,
27            base_url,
28        }
29    }
30
31    /// Add a torrent to the tracker whitelist.
32    ///
33    /// # Errors
34    ///
35    /// Will return an error if the HTTP request fails.
36    pub async fn whitelist_torrent(&self, info_hash: &str) -> Result<Response, Error> {
37        let request_url = format!(
38            "{}/whitelist/{}?token={}",
39            self.base_url, info_hash, self.connection_info.token
40        );
41
42        let client = reqwest::Client::new();
43
44        client.post(request_url).send().await
45    }
46
47    /// Remove a torrent from the tracker whitelist.
48    ///
49    /// # Errors
50    ///
51    /// Will return an error if the HTTP request fails.
52    pub async fn remove_torrent_from_whitelist(&self, info_hash: &str) -> Result<Response, Error> {
53        let request_url = format!(
54            "{}/whitelist/{}?token={}",
55            self.base_url, info_hash, self.connection_info.token
56        );
57
58        let client = reqwest::Client::new();
59
60        client.delete(request_url).send().await
61    }
62
63    /// Retrieve a new tracker key.
64    ///
65    /// # Errors
66    ///
67    /// Will return an error if the HTTP request fails.
68    pub async fn retrieve_new_tracker_key(&self, token_valid_seconds: u64) -> Result<Response, Error> {
69        let request_url = format!(
70            "{}/key/{}?token={}",
71            self.base_url, token_valid_seconds, self.connection_info.token
72        );
73
74        let client = reqwest::Client::new();
75
76        client.post(request_url).send().await
77    }
78
79    /// Retrieve the info for a torrent.
80    ///
81    /// # Errors
82    ///
83    /// Will return an error if the HTTP request fails.
84    pub async fn get_torrent_info(&self, info_hash: &str) -> Result<Response, Error> {
85        let request_url = format!("{}/torrent/{}?token={}", self.base_url, info_hash, self.connection_info.token);
86
87        let client = reqwest::Client::new();
88
89        client.get(request_url).send().await
90    }
91}