Skip to main content

twapi_v2/api/
post_2_media_upload_id_append.rs

1use std::io::Cursor;
2
3use crate::{
4    api::{Authentication, TwapiOptions, make_url},
5    error::Error,
6    headers::Headers,
7};
8use reqwest::RequestBuilder;
9use reqwest::multipart::{Form, Part};
10
11const URL: &str = "/2/media/upload/:id/append";
12
13#[derive(Debug, Clone, Default)]
14pub struct FormData {
15    pub segment_index: u64,
16    pub cursor: Cursor<Vec<u8>>,
17}
18
19impl FormData {
20    fn make_form(&self) -> Form {
21        Form::new()
22            .text("segment_index", self.segment_index.to_string())
23            .part("media", Part::bytes(self.cursor.clone().into_inner()))
24    }
25}
26
27#[derive(Debug, Clone, Default)]
28pub struct Api {
29    id: String,
30    form: FormData,
31    twapi_options: Option<TwapiOptions>,
32}
33
34impl Api {
35    pub fn new(id: &str, form: FormData) -> Self {
36        Self {
37            id: id.to_string(),
38            form,
39            ..Default::default()
40        }
41    }
42
43    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
44        self.twapi_options = Some(value);
45        self
46    }
47
48    pub fn build(&self, authentication: &impl Authentication) -> RequestBuilder {
49        let client = reqwest::Client::new();
50        let url = make_url(&self.twapi_options, &URL.replace(":id", &self.id));
51        let builder = client.post(&url).multipart(self.form.make_form());
52        authentication.execute(builder, "POST", &url, &[])
53    }
54
55    pub async fn execute(&self, authentication: &impl Authentication) -> Result<Headers, Error> {
56        let response = self.build(authentication).send().await?;
57        let status_code = response.status();
58        let header = response.headers();
59        let headers = Headers::new(header);
60        if status_code.is_success() {
61            Ok(headers)
62        } else {
63            let body = response.text().await?;
64            Err(Error::Other(body, Some(status_code)))
65        }
66    }
67}