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