Skip to main content

twapi_v2/api/
get_2_users.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, 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";
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    ids: 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(ids: &str) -> Self {
57        Self {
58            ids: ids.to_owned(),
59            ..Default::default()
60        }
61    }
62
63    pub fn all(ids: &str) -> Self {
64        Self {
65            ids: ids.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(ids: &str) -> Self {
74        Self {
75            ids: ids.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        query_parameters.push(("ids", self.ids.to_string()));
106        if let Some(expansions) = self.expansions.as_ref() {
107            query_parameters.push(("expansions", expansions.iter().join(",")));
108        }
109        if let Some(tweet_fields) = self.tweet_fields.as_ref() {
110            query_parameters.push(("tweet.fields", tweet_fields.iter().join(",")));
111        }
112        if let Some(user_fields) = self.user_fields.as_ref() {
113            query_parameters.push(("user.fields", user_fields.iter().join(",")));
114        }
115        let client = reqwest::Client::new();
116        let url = make_url(&self.twapi_options, URL);
117        let builder = client.get(&url).query(&query_parameters);
118        authentication.execute(
119            builder,
120            "GET",
121            &url,
122            &query_parameters
123                .iter()
124                .map(|it| (it.0, it.1.as_str()))
125                .collect::<Vec<_>>(),
126        )
127    }
128
129    pub async fn execute(
130        &self,
131        authentication: &impl Authentication,
132    ) -> Result<(Response, Headers), Error> {
133        execute_twitter(|| self.build(authentication), &self.twapi_options).await
134    }
135}
136
137#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
138pub struct Response {
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub data: Option<Vec<Users>>,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub errors: Option<Vec<Errors>>,
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub includes: Option<Includes>,
145    #[serde(flatten)]
146    pub extra: std::collections::HashMap<String, serde_json::Value>,
147}
148
149impl Response {
150    pub fn is_empty_extra(&self) -> bool {
151        let res = self.extra.is_empty()
152            && self
153                .data
154                .as_ref()
155                .map(|it| it.iter().all(|item| item.is_empty_extra()))
156                .unwrap_or(true)
157            && self
158                .errors
159                .as_ref()
160                .map(|it| it.iter().all(|item| item.is_empty_extra()))
161                .unwrap_or(true)
162            && self
163                .includes
164                .as_ref()
165                .map(|it| it.is_empty_extra())
166                .unwrap_or(true);
167        if !res {
168            println!("Response {:?}", self.extra);
169        }
170        res
171    }
172}