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