hightorrent_api 0.3.0

Highlevel torrent API client, supporting Bittorrent v1, v2 and hybrid torrents
Documentation
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use hightorrent::{
    InfoHash, MultiTarget, SingleTarget, ToTorrent, ToTorrentContent, Torrent, TorrentContent,
    TorrentID, TorrentList, Tracker, TryIntoTracker,
};
use reqwest::multipart::Form;
use reqwest::multipart::Part;
use reqwest::{Client, ClientBuilder, Response, StatusCode, Url};
use serde::de::DeserializeOwned;
use snafu::ResultExt;

use std::borrow::Borrow;

use crate::{
    api::*,
    api_error::{ApiError as Error, *},
    qbittorrent::{QBittorrentTorrent, QBittorrentTorrentContent, QBittorrentTracker},
};

#[derive(Clone, Debug)]
pub struct QBittorrentClient {
    host: String,
    user: String,
    password: String,
    client: Client,
}

impl QBittorrentClient {
    /// Create a new client that's not logged in yet.
    ///
    /// Then perform `QBittorrentClient::do_login` to actually login.
    pub fn new_not_logged_in(host: &str, user: &str, password: &str) -> Result<Self, Error> {
        let client = ClientBuilder::new()
            .cookie_store(true)
            .build()
            .boxed()
            .context(ClientInitError)?;

        Ok(Self {
            host: host.to_string(),
            user: user.to_string(),
            password: password.to_string(),
            client,
        })
    }

    pub async fn do_login(&self) -> Result<(), Error> {
        let form = Form::new()
            .text("username", self.user.to_string())
            .text("password", self.password.to_string());

        let res = self
            .client
            .post(format!("{}/api/v2/auth/login", self.host))
            .multipart(form)
            .send()
            .await
            .boxed()
            .context(HttpError)?;

        if res.headers().get("set-cookie").is_some() {
            Ok(())
        } else {
            Err(Error::InvalidLogin {
                host: self.host.to_string(),
                user: self.user.to_string(),
            })
        }
    }

    /// Returns the qBittorrent version, in a `vX.Y.Z` format.
    pub async fn qbittorrent_version(&self) -> Result<String, Error> {
        let res = self._get(self._endpoint("app/version")).await?;
        let bytes = res.bytes().await.boxed().context(HttpError)?;
        Ok(String::from_utf8_lossy(&bytes).to_string())
    }

    /// Returns the URL to an endpoint without params
    pub fn _endpoint(&self, path: &str) -> Url {
        Url::parse(&format!("{}/api/v2/{}", self.host, path))
            .expect("PROGRAMMING ERROR: invalid api URL")
    }

    /// Returns the URL to an endpoint with custom query params
    pub fn _endpoint_params<I, K, V>(&self, endpoint: &str, args: I) -> Url
    where
        I: IntoIterator,
        K: AsRef<str>,
        V: AsRef<str>,
        <I as IntoIterator>::Item: Borrow<(K, V)>,
    {
        Url::parse_with_params(&format!("{}/api/v2/{}", self.host, endpoint), args)
            .expect("PROGRAMMING ERROR: invalid api URL")
    }

    pub async fn _post_multipart(&self, endpoint: Url, form: Form) -> Result<Response, Error> {
        self.keepalive().await?;
        self.client
            .post(endpoint)
            .multipart(form)
            .send()
            .await
            .boxed()
            .context(HttpError)
    }

    pub async fn _post(&self, endpoint: Url) -> Result<Response, Error> {
        self.keepalive().await?;
        self.client
            .post(endpoint)
            .send()
            .await
            .boxed()
            .context(HttpError)
    }

    pub async fn _get(&self, endpoint: Url) -> Result<Response, Error> {
        self.keepalive().await?;
        self.client
            .get(endpoint)
            .send()
            .await
            .boxed()
            .context(HttpError)
    }

    /// Keeps the current session alive even if QBittorrent restarted
    ///
    /// Called before making a "real" API call in other methods. Not ideal because it now takes
    /// two round-trips (3 when reconnecting), but better than failing because cookie expired.
    pub async fn keepalive(&self) -> Result<(), Error> {
        let res = self
            .client
            .get(self._endpoint("app/version"))
            .send()
            .await
            .boxed()
            .context(HttpError)?;
        if res.status() == StatusCode::FORBIDDEN {
            // We have been disconnected. Reconnect now!
            // TODO: check if reconnect was successful?
            self.reconnect().await?;
        }

        Ok(())
    }

    /// Triggers a reconnection to the QBittorrent API.
    ///
    // TODO: check if reconnect was successful?
    pub async fn reconnect(&self) -> Result<(), Error> {
        let form = Form::new()
            .text("username", self.user.to_string())
            .text("password", self.password.to_string());

        let _ = self
            .client
            .post(self._endpoint("auth/login"))
            .multipart(form)
            .send()
            .await
            .boxed()
            .context(HttpError)?;

        Ok(())
    }

    pub async fn _json<U: DeserializeOwned>(&self, res: Response) -> Result<U, Error> {
        let full = res.bytes().await.boxed().context(HttpError)?;
        serde_json::from_slice(&full).context(DeserializationError)
    }

    pub async fn list_target(&self, target: &MultiTarget) -> Result<TorrentList, Error> {
        match target {
            MultiTarget::All => Ok(self.list().await?),
            MultiTarget::Hash(single_target) => {
                if let Some(t) = self.get(single_target).await? {
                    Ok(TorrentList::from_vec(vec![t]))
                } else {
                    Err(Error::MissingTorrent {
                        hash: single_target.to_string(),
                    })
                }
            }
        }
    }

    /// Returns a TorrentID for the requested SingleTarget
    ///
    /// TODO: This is a workaround until QBittorrent finally supports v1 hybrid hashes and full v2
    /// hashes in its API... This has HUGE performance implications.
    /// See [this issue ](https://github.com/qbittorrent/qBittorrent/issues/18185) for more info.
    pub async fn id(&self, target: &SingleTarget) -> Result<Option<TorrentID>, Error> {
        Ok(self.get(target).await?.map(|torrent| torrent.id.clone()))
    }

    /// Returns a list of torrents as a vector of a custom type
    pub async fn list_as<T: DeserializeOwned + AsRef<InfoHash>>(&self) -> Result<Vec<T>, Error> {
        let res = self._get(self._endpoint("torrents/info")).await?;
        self._json(res).await
    }

    /// Returns a single torrent as a custom type
    pub async fn get_as<T: DeserializeOwned + AsRef<InfoHash>>(
        &self,
        target: &SingleTarget,
    ) -> Result<Option<T>, Error> {
        self.list_as::<T>().await.map(|list| {
            list.into_iter()
                .find(|torrent| target.matches_hash(torrent.as_ref()))
        })
    }

    pub async fn set_location(&self, target: &SingleTarget, location: &str) -> Result<(), Error> {
        if let Some(id) = self.id(target).await? {
            let form = Form::new()
                .text("hashes", id.to_string())
                .text("location", location.to_string());
            self._post_multipart(self._endpoint("torrents/setLocation"), form)
                .await?;

            Ok(())
        } else {
            Err(Error::MissingTorrent {
                hash: target.to_string(),
            })
        }
    }
}

#[async_trait]
impl Api for QBittorrentClient {
    fn host(&self) -> String {
        self.host.to_string()
    }

    fn user(&self) -> String {
        self.user.to_string()
    }

    fn password(&self) -> String {
        self.user.to_string()
    }

    async fn login(host: &str, user: &str, password: &str) -> Result<Self, Error> {
        let api_client = Self::new_not_logged_in(host, user, password)?;
        api_client.do_login().await?;
        Ok(api_client)
    }

    async fn list(&self) -> Result<TorrentList, Error> {
        let res = self._get(self._endpoint("torrents/info")).await?;
        let concrete: Vec<QBittorrentTorrent> = self._json(res).await?;
        Ok(concrete.iter().map(|t| t.to_torrent()).collect())
    }

    async fn get(&self, target: &SingleTarget) -> Result<Option<Torrent>, Error> {
        Ok(self.list().await?.get(target))
    }

    async fn remove(&self, target: &SingleTarget, delete_files: bool) -> Result<(), Error> {
        if let Some(id) = self.id(target).await? {
            let mut form = Form::new();
            form = form.text("hashes", id.as_str().to_string());
            form = form.text("deleteFiles", delete_files.to_string());

            self._post_multipart(self._endpoint("torrents/delete"), form)
                .await?;
        }

        Ok(())
    }

    async fn get_trackers(&self, target: &SingleTarget) -> Result<Vec<Tracker>, Error> {
        let truncated = target.truncated();
        let res = self
            ._post(self._endpoint_params("torrents/trackers", vec![("hash", truncated)]))
            .await?;

        let trackers = self
            ._json::<Vec<QBittorrentTracker>>(res)
            .await?
            .into_iter()
            .filter_map(|tracker| {
                // Dismiss non-tracker types (DHT/PEX/LSD)
                tracker.try_into_tracker().ok()
            })
            .collect();

        Ok(trackers)
    }

    async fn remove_tracker(&self, target: &SingleTarget, tracker: &str) -> Result<(), Error> {
        //.context(InfoHashError as <ToSingleTarget::Error>)?;
        let truncated = target.truncated();
        let res = self
            ._post(self._endpoint_params(
                "torrent/removeTrackers",
                vec![("hash", truncated), ("urls", tracker)],
            ))
            .await?;

        match res.status() {
            StatusCode::NOT_FOUND => Err(Error::MissingTorrent {
                hash: target.to_string(),
            }),
            StatusCode::CONFLICT => {
                // Tracker URL was not found
                Ok(())
            }
            _ => Ok(()),
        }
    }

    async fn add_tracker(&self, target: &SingleTarget, tracker: &str) -> Result<(), Error> {
        let truncated = target.truncated();
        let res = self
            ._post(self._endpoint_params(
                "torrent/addTrackers",
                vec![("hash", truncated), ("urls", tracker)],
            ))
            .await?;

        if res.status().is_success() {
            Ok(())
        } else {
            Err(Error::MissingTorrent {
                hash: target.as_str().to_string(),
            })
        }
    }

    async fn get_files(&self, target: &SingleTarget) -> Result<Vec<TorrentContent>, Error> {
        let Some(id) = self.id(target).await? else {
            return Err(Error::MissingTorrent {
                hash: target.as_str().to_string(),
            });
        };

        let mut form = Form::new();
        form = form.text("hash", id.as_str().to_string());
        let res = self
            ._post_multipart(self._endpoint("torrents/files"), form)
            .await?;

        if res.status().is_success() {
            let concrete: Vec<QBittorrentTorrentContent> = self._json(res).await?;
            Ok(concrete.iter().map(|t| t.to_torrent_content()).collect())
        } else {
            Err(Error::MissingTorrent {
                hash: target.as_str().to_string(),
            })
        }
    }
}

#[async_trait]
impl<'a> ApiAdd<'a> for QBittorrentClient {
    async fn api_add_send(&self, add: AddBuilder<'a, AddSource>) -> Result<(), ApiError> {
        let mut form = Form::new();

        if let Some(save_path) = add.save_path {
            form = form.text("savepath", save_path);
        }

        if let Some(paused) = add.paused {
            form = form.text("stopped", paused.to_string());
        }

        if let Some(tags) = add.tags {
            form = form.text("tags", tags.join(","));
        }

        form = match add.source {
            AddSource::Magnet(magnet) => form.text("urls", magnet.to_string()),
            AddSource::Torrent(torrent) => form.part(
                "torrents",
                Part::bytes(torrent.to_vec()).file_name(format!("{}.torrent", torrent.id())),
            ),
        };

        let res = self
            ._post_multipart(self._endpoint("torrents/add"), form)
            .await?;
        add_success(res).await
    }
}

async fn add_success(res: reqwest::Response) -> Result<(), Error> {
    if res.status().is_success() {
        if res
            .text()
            .await
            .boxed()
            .context(HttpError)?
            .starts_with("Fail")
        {
            Err(Error::RejectedTorrent)
        } else {
            Ok(())
        }
    } else {
        Err(Error::RejectedTorrent)
    }
}