Skip to main content

twapi_v2/api/
get_2_users_id.rs

1use crate::fields::{tweet_fields::TweetFields, user_fields::UserFields};
2use crate::responses::{errors::Errors, includes::Includes, users::Users};
3use crate::{
4    api::{Authentication, TwapiOptions, apply_options, execute_twitter, make_url},
5    error::Error,
6    headers::Headers,
7};
8use itertools::Itertools;
9use reqwest::RequestBuilder;
10use serde::{Deserialize, Serialize};
11use std::collections::HashSet;
12
13const URL: &str = "/2/users/:id";
14
15#[derive(Serialize, Deserialize, Debug, Eq, Hash, PartialEq, Clone, Default)]
16pub enum Expansions {
17    #[serde(rename = "affiliation.user_id")]
18    #[default]
19    AffiliationUserId,
20    #[serde(rename = "most_recent_tweet_id")]
21    MostRecentTweetId,
22    #[serde(rename = "pinned_tweet_id")]
23    PinnedTweetId,
24}
25
26impl Expansions {
27    pub fn all() -> HashSet<Self> {
28        let mut result = HashSet::new();
29        result.insert(Self::AffiliationUserId);
30        result.insert(Self::MostRecentTweetId);
31        result.insert(Self::PinnedTweetId);
32        result
33    }
34}
35
36impl std::fmt::Display for Expansions {
37    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
38        match self {
39            Self::AffiliationUserId => write!(f, "affiliation.user_id"),
40            Self::MostRecentTweetId => write!(f, "most_recent_tweet_id"),
41            Self::PinnedTweetId => write!(f, "pinned_tweet_id"),
42        }
43    }
44}
45
46#[derive(Debug, Clone, Default)]
47pub struct Api {
48    id: String,
49    expansions: Option<HashSet<Expansions>>,
50    tweet_fields: Option<HashSet<TweetFields>>,
51    user_fields: Option<HashSet<UserFields>>,
52    twapi_options: Option<TwapiOptions>,
53}
54
55impl Api {
56    pub fn new(id: &str) -> Self {
57        Self {
58            id: id.to_owned(),
59            ..Default::default()
60        }
61    }
62
63    pub fn all(id: &str) -> Self {
64        Self {
65            id: id.to_owned(),
66            expansions: Some(Expansions::all()),
67            tweet_fields: Some(TweetFields::organic()),
68            user_fields: Some(UserFields::all()),
69            ..Default::default()
70        }
71    }
72
73    pub fn open(id: &str) -> Self {
74        Self {
75            id: id.to_owned(),
76            expansions: Some(Expansions::all()),
77            tweet_fields: Some(TweetFields::open()),
78            user_fields: Some(UserFields::all()),
79            ..Default::default()
80        }
81    }
82
83    pub fn expansions(mut self, value: HashSet<Expansions>) -> Self {
84        self.expansions = Some(value);
85        self
86    }
87
88    pub fn tweet_fields(mut self, value: HashSet<TweetFields>) -> Self {
89        self.tweet_fields = Some(value);
90        self
91    }
92
93    pub fn user_fields(mut self, value: HashSet<UserFields>) -> Self {
94        self.user_fields = Some(value);
95        self
96    }
97
98    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
99        self.twapi_options = Some(value);
100        self
101    }
102
103    pub fn build(self, authentication: &impl Authentication) -> RequestBuilder {
104        let mut query_parameters = vec![];
105        if let Some(expansions) = self.expansions {
106            query_parameters.push(("expansions", expansions.iter().join(",")));
107        }
108        if let Some(tweet_fields) = self.tweet_fields {
109            query_parameters.push(("tweet.fields", tweet_fields.iter().join(",")));
110        }
111        if let Some(user_fields) = self.user_fields {
112            query_parameters.push(("user.fields", user_fields.iter().join(",")));
113        }
114        let client = reqwest::Client::new();
115        let url = make_url(&self.twapi_options, &URL.replace(":id", &self.id));
116        let builder = client.get(&url).query(&query_parameters);
117        authentication.execute(
118            apply_options(builder, &self.twapi_options),
119            "GET",
120            &url,
121            &query_parameters
122                .iter()
123                .map(|it| (it.0, it.1.as_str()))
124                .collect::<Vec<_>>(),
125        )
126    }
127
128    pub async fn execute(
129        self,
130        authentication: &impl Authentication,
131    ) -> Result<(Response, Headers), Error> {
132        execute_twitter(self.build(authentication)).await
133    }
134}
135
136#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
137pub struct Response {
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub data: Option<Users>,
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub errors: Option<Vec<Errors>>,
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub includes: Option<Includes>,
144    #[serde(flatten)]
145    pub extra: std::collections::HashMap<String, serde_json::Value>,
146}
147
148impl Response {
149    pub fn is_empty_extra(&self) -> bool {
150        let res = self.extra.is_empty()
151            && self
152                .data
153                .as_ref()
154                .map(|it| it.is_empty_extra())
155                .unwrap_or(true)
156            && self
157                .errors
158                .as_ref()
159                .map(|it| it.iter().all(|item| item.is_empty_extra()))
160                .unwrap_or(true)
161            && self
162                .includes
163                .as_ref()
164                .map(|it| it.is_empty_extra())
165                .unwrap_or(true);
166        if !res {
167            println!("Response {:?}", self.extra);
168        }
169        res
170    }
171}