Skip to main content

twapi_v2/api/
post_2_oauth2_token_refresh_token.rs

1use crate::{
2    api::{TwapiOptions, execute_twitter, make_url},
3    error::Error,
4    headers::Headers,
5};
6use reqwest::RequestBuilder;
7use serde::{Deserialize, Serialize};
8
9use super::apply_options;
10
11const URL: &str = "/2/oauth2/token";
12
13#[derive(Debug, Clone, Default)]
14pub struct Api {
15    api_key_code: String,
16    api_secret_code: String,
17    refresh_token: String,
18    twapi_options: Option<TwapiOptions>,
19}
20
21impl Api {
22    pub fn new(api_key_code: &str, api_secret_code: &str, refresh_token: &str) -> Self {
23        Self {
24            api_key_code: api_key_code.to_owned(),
25            api_secret_code: api_secret_code.to_owned(),
26            refresh_token: refresh_token.to_owned(),
27            ..Default::default()
28        }
29    }
30
31    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
32        self.twapi_options = Some(value);
33        self
34    }
35
36    pub fn build(self) -> RequestBuilder {
37        let form_parameters = vec![
38            ("client_id", self.api_key_code.clone()),
39            ("grant_type", "refresh_token".to_owned()),
40            ("refresh_token", self.refresh_token),
41        ];
42
43        let client = reqwest::Client::new();
44        let url = make_url(&self.twapi_options, URL);
45        apply_options(client.post(url), &self.twapi_options)
46            .form(&form_parameters)
47            .basic_auth(&self.api_key_code, Some(&self.api_secret_code))
48    }
49
50    pub async fn execute(self) -> Result<(Response, Headers), Error> {
51        execute_twitter(self.build()).await
52    }
53}
54
55#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
56pub struct Response {
57    pub access_token: Option<String>,
58    pub refresh_token: Option<String>,
59    pub expires_in: Option<i64>,
60    pub token_type: Option<String>,
61    pub scope: Option<String>,
62    #[serde(flatten)]
63    pub extra: std::collections::HashMap<String, serde_json::Value>,
64}
65
66impl Response {
67    pub fn is_empty_extra(&self) -> bool {
68        let res = self.extra.is_empty();
69        if !res {
70            println!("Response {:?}", self.extra);
71        }
72        res
73    }
74}