twapi_v2/api/
post_2_media_upload_append.rs

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