twapi_v2/api/
get_2_users_me.rs

1use crate::fields::{tweet_fields::TweetFields, user_fields::UserFields};
2use crate::responses::{errors::Errors, includes::Includes, users::Users};
3use crate::{
4    api::{apply_options, execute_twitter, make_url, Authentication, TwapiOptions},
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/me";
14
15#[derive(Serialize, Deserialize, Debug, Eq, Hash, PartialEq, Clone)]
16pub enum Expansions {
17    #[serde(rename = "affiliation.user_id")]
18    AffiliationUserId,
19    #[serde(rename = "most_recent_tweet_id")]
20    MostRecentTweetId,
21    #[serde(rename = "pinned_tweet_id")]
22    PinnedTweetId,
23}
24
25impl Expansions {
26    pub fn all() -> HashSet<Self> {
27        let mut result = HashSet::new();
28        result.insert(Self::AffiliationUserId);
29        result.insert(Self::MostRecentTweetId);
30        result.insert(Self::PinnedTweetId);
31        result
32    }
33}
34
35impl std::fmt::Display for Expansions {
36    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
37        match self {
38            Self::AffiliationUserId => write!(f, "affiliation.user_id"),
39            Self::MostRecentTweetId => write!(f, "most_recent_tweet_id"),
40            Self::PinnedTweetId => write!(f, "pinned_tweet_id"),
41        }
42    }
43}
44
45impl Default for Expansions {
46    fn default() -> Self {
47        Self::AffiliationUserId
48    }
49}
50
51#[derive(Debug, Clone, Default)]
52pub struct Api {
53    expansions: Option<HashSet<Expansions>>,
54    tweet_fields: Option<HashSet<TweetFields>>,
55    user_fields: Option<HashSet<UserFields>>,
56    twapi_options: Option<TwapiOptions>,
57}
58
59impl Api {
60    pub fn new() -> Self {
61        Self {
62            ..Default::default()
63        }
64    }
65
66    pub fn all() -> Self {
67        Self {
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() -> Self {
76        Self {
77            expansions: Some(Expansions::all()),
78            tweet_fields: Some(TweetFields::open()),
79            user_fields: Some(UserFields::all()),
80            ..Default::default()
81        }
82    }
83
84    pub fn expansions(mut self, value: HashSet<Expansions>) -> Self {
85        self.expansions = Some(value);
86        self
87    }
88
89    pub fn tweet_fields(mut self, value: HashSet<TweetFields>) -> Self {
90        self.tweet_fields = Some(value);
91        self
92    }
93
94    pub fn user_fields(mut self, value: HashSet<UserFields>) -> Self {
95        self.user_fields = Some(value);
96        self
97    }
98
99    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
100        self.twapi_options = Some(value);
101        self
102    }
103
104    pub fn build(self, authentication: &impl Authentication) -> RequestBuilder {
105        let mut query_parameters = vec![];
106        if let Some(expansions) = self.expansions {
107            query_parameters.push(("expansions", expansions.iter().join(",")));
108        }
109        if let Some(tweet_fields) = self.tweet_fields {
110            query_parameters.push(("tweet.fields", tweet_fields.iter().join(",")));
111        }
112        if let Some(user_fields) = self.user_fields {
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            apply_options(builder, &self.twapi_options),
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)).await
134    }
135}
136
137#[derive(Serialize, Deserialize, Debug, Clone, Default)]
138pub struct Response {
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub data: Option<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.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}