twapi_v2/api/
get_2_users_id_blocking.rs

1use crate::fields::{tweet_fields::TweetFields, user_fields::UserFields};
2use crate::responses::{errors::Errors, includes::Includes, meta::Meta, 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/:id/blocking";
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    id: String,
54    expansions: Option<HashSet<Expansions>>,
55    max_results: Option<usize>,
56    pagination_token: Option<String>,
57    tweet_fields: Option<HashSet<TweetFields>>,
58    user_fields: Option<HashSet<UserFields>>,
59    twapi_options: Option<TwapiOptions>,
60}
61
62impl Api {
63    pub fn new(id: &str) -> Self {
64        Self {
65            id: id.to_owned(),
66            ..Default::default()
67        }
68    }
69
70    pub fn all(id: &str) -> Self {
71        Self {
72            id: id.to_owned(),
73            expansions: Some(Expansions::all()),
74            tweet_fields: Some(TweetFields::organic()),
75            user_fields: Some(UserFields::all()),
76            max_results: Some(1000),
77            ..Default::default()
78        }
79    }
80
81    pub fn open(id: &str) -> Self {
82        Self {
83            id: id.to_owned(),
84            expansions: Some(Expansions::all()),
85            tweet_fields: Some(TweetFields::open()),
86            user_fields: Some(UserFields::all()),
87            max_results: Some(1000),
88            ..Default::default()
89        }
90    }
91
92    pub fn expansions(mut self, value: HashSet<Expansions>) -> Self {
93        self.expansions = Some(value);
94        self
95    }
96
97    pub fn max_results(mut self, value: usize) -> Self {
98        self.max_results = Some(value);
99        self
100    }
101
102    pub fn pagination_token(mut self, value: &str) -> Self {
103        self.pagination_token = Some(value.to_owned());
104        self
105    }
106
107    pub fn tweet_fields(mut self, value: HashSet<TweetFields>) -> Self {
108        self.tweet_fields = Some(value);
109        self
110    }
111
112    pub fn user_fields(mut self, value: HashSet<UserFields>) -> Self {
113        self.user_fields = Some(value);
114        self
115    }
116
117    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
118        self.twapi_options = Some(value);
119        self
120    }
121
122    pub fn build(self, authentication: &impl Authentication) -> RequestBuilder {
123        let mut query_parameters = vec![];
124        if let Some(expansions) = self.expansions {
125            query_parameters.push(("expansions", expansions.iter().join(",")));
126        }
127        if let Some(max_results) = self.max_results {
128            query_parameters.push(("max_results", max_results.to_string()));
129        }
130        if let Some(pagination_token) = self.pagination_token {
131            query_parameters.push(("pagination_token", pagination_token));
132        }
133        if let Some(tweet_fields) = self.tweet_fields {
134            query_parameters.push(("tweet.fields", tweet_fields.iter().join(",")));
135        }
136        if let Some(user_fields) = self.user_fields {
137            query_parameters.push(("user.fields", user_fields.iter().join(",")));
138        }
139        let client = reqwest::Client::new();
140        let url = make_url(&self.twapi_options, &URL.replace(":id", &self.id));
141        let builder = client.get(&url).query(&query_parameters);
142        authentication.execute(
143            apply_options(builder, &self.twapi_options),
144            "GET",
145            &url,
146            &query_parameters
147                .iter()
148                .map(|it| (it.0, it.1.as_str()))
149                .collect::<Vec<_>>(),
150        )
151    }
152
153    pub async fn execute(
154        self,
155        authentication: &impl Authentication,
156    ) -> Result<(Response, Headers), Error> {
157        execute_twitter(self.build(authentication)).await
158    }
159}
160
161#[derive(Serialize, Deserialize, Debug, Clone, Default)]
162pub struct Response {
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub data: Option<Vec<Users>>,
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub errors: Option<Vec<Errors>>,
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub includes: Option<Includes>,
169    #[serde(skip_serializing_if = "Option::is_none")]
170    pub meta: Option<Meta>,
171    #[serde(flatten)]
172    pub extra: std::collections::HashMap<String, serde_json::Value>,
173}
174
175impl Response {
176    pub fn is_empty_extra(&self) -> bool {
177        let res = self.extra.is_empty()
178            && self
179                .data
180                .as_ref()
181                .map(|it| it.iter().all(|item| item.is_empty_extra()))
182                .unwrap_or(true)
183            && self
184                .errors
185                .as_ref()
186                .map(|it| it.iter().all(|item| item.is_empty_extra()))
187                .unwrap_or(true)
188            && self
189                .includes
190                .as_ref()
191                .map(|it| it.is_empty_extra())
192                .unwrap_or(true)
193            && self
194                .meta
195                .as_ref()
196                .map(|it| it.is_empty_extra())
197                .unwrap_or(true);
198        if !res {
199            println!("Response {:?}", self.extra);
200        }
201        res
202    }
203}