twapi_v2/api/
get_2_users_id_bookmarks.rs

1use crate::fields::{
2    media_fields::MediaFields, place_fields::PlaceFields, poll_fields::PollFields,
3    tweet_fields::TweetFields, user_fields::UserFields,
4};
5use crate::responses::{errors::Errors, includes::Includes, meta::Meta, tweets::Tweets};
6use crate::{
7    api::{apply_options, execute_twitter, make_url, Authentication, TwapiOptions},
8    error::Error,
9    headers::Headers,
10};
11use itertools::Itertools;
12use reqwest::RequestBuilder;
13use serde::{Deserialize, Serialize};
14use std::collections::HashSet;
15
16const URL: &str = "/2/users/:id/bookmarks";
17
18#[derive(Serialize, Deserialize, Debug, Eq, Hash, PartialEq, Clone)]
19pub enum Expansions {
20    #[serde(rename = "article.cover_media")]
21    ArticleCoverMedia,
22    #[serde(rename = "article.media_entities")]
23    ArticleMediaEntities,
24    #[serde(rename = "attachments.media_keys")]
25    AttachmentsMediaKeys,
26    #[serde(rename = "attachments.media_source_tweet")]
27    AttachmentsMediaSourceTweet,
28    #[serde(rename = "attachments.poll_ids")]
29    AttachmentsPollIds,
30    #[serde(rename = "author_id")]
31    AuthorId,
32    #[serde(rename = "edit_history_tweet_ids")]
33    EditHistoryTweetIds,
34    #[serde(rename = "entities.mentions.username")]
35    EntitiesMentionsUsername,
36    #[serde(rename = "geo.place_id")]
37    GeoPlaceId,
38    #[serde(rename = "in_reply_to_user_id")]
39    InReplyToUserId,
40    #[serde(rename = "entities.note.mentions.username")]
41    EntitiesNoteMentionsUsername,
42    #[serde(rename = "referenced_tweets.id")]
43    ReferencedTweetsId,
44    #[serde(rename = "referenced_tweets.id.author_id")]
45    ReferencedTweetsIdAuthorId,
46}
47
48impl Expansions {
49    pub fn all() -> HashSet<Self> {
50        let mut result = HashSet::new();
51        result.insert(Self::ArticleCoverMedia);
52        result.insert(Self::ArticleMediaEntities);
53        result.insert(Self::AttachmentsMediaKeys);
54        result.insert(Self::AttachmentsMediaSourceTweet);
55        result.insert(Self::AttachmentsPollIds);
56        result.insert(Self::AuthorId);
57        result.insert(Self::EditHistoryTweetIds);
58        result.insert(Self::EntitiesMentionsUsername);
59        result.insert(Self::GeoPlaceId);
60        result.insert(Self::InReplyToUserId);
61        result.insert(Self::EntitiesNoteMentionsUsername);
62        result.insert(Self::ReferencedTweetsId);
63        result.insert(Self::ReferencedTweetsIdAuthorId);
64        result
65    }
66}
67
68impl std::fmt::Display for Expansions {
69    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
70        match self {
71            Self::ArticleCoverMedia => write!(f, "article.cover_media"),
72            Self::ArticleMediaEntities => write!(f, "article.media_entities"),
73            Self::AttachmentsMediaKeys => write!(f, "attachments.media_keys"),
74            Self::AttachmentsMediaSourceTweet => write!(f, "attachments.media_source_tweet"),
75            Self::AttachmentsPollIds => write!(f, "attachments.poll_ids"),
76            Self::AuthorId => write!(f, "author_id"),
77            Self::EditHistoryTweetIds => write!(f, "edit_history_tweet_ids"),
78            Self::EntitiesMentionsUsername => write!(f, "entities.mentions.username"),
79            Self::GeoPlaceId => write!(f, "geo.place_id"),
80            Self::InReplyToUserId => write!(f, "in_reply_to_user_id"),
81            Self::EntitiesNoteMentionsUsername => write!(f, "entities.note.mentions.username"),
82            Self::ReferencedTweetsId => write!(f, "referenced_tweets.id"),
83            Self::ReferencedTweetsIdAuthorId => write!(f, "referenced_tweets.id.author_id"),
84        }
85    }
86}
87
88impl Default for Expansions {
89    fn default() -> Self {
90        Self::ArticleCoverMedia
91    }
92}
93
94#[derive(Debug, Clone, Default)]
95pub struct Api {
96    id: String,
97    expansions: Option<HashSet<Expansions>>,
98    max_results: Option<usize>,
99    media_fields: Option<HashSet<MediaFields>>,
100    pagination_token: Option<String>,
101    place_fields: Option<HashSet<PlaceFields>>,
102    poll_fields: Option<HashSet<PollFields>>,
103    tweet_fields: Option<HashSet<TweetFields>>,
104    user_fields: Option<HashSet<UserFields>>,
105    twapi_options: Option<TwapiOptions>,
106}
107
108impl Api {
109    pub fn new(id: &str) -> Self {
110        Self {
111            id: id.to_owned(),
112            ..Default::default()
113        }
114    }
115
116    pub fn all(id: &str) -> Self {
117        Self {
118            id: id.to_owned(),
119            expansions: Some(Expansions::all()),
120            media_fields: Some(MediaFields::all()),
121            place_fields: Some(PlaceFields::all()),
122            poll_fields: Some(PollFields::all()),
123            tweet_fields: Some(TweetFields::organic()),
124            user_fields: Some(UserFields::all()),
125            max_results: Some(100),
126            ..Default::default()
127        }
128    }
129
130    pub fn open(id: &str) -> Self {
131        Self {
132            id: id.to_owned(),
133            expansions: Some(Expansions::all()),
134            media_fields: Some(MediaFields::open()),
135            place_fields: Some(PlaceFields::all()),
136            poll_fields: Some(PollFields::all()),
137            tweet_fields: Some(TweetFields::open()),
138            user_fields: Some(UserFields::all()),
139            max_results: Some(100),
140            ..Default::default()
141        }
142    }
143
144    pub fn expansions(mut self, value: HashSet<Expansions>) -> Self {
145        self.expansions = Some(value);
146        self
147    }
148
149    pub fn max_results(mut self, value: usize) -> Self {
150        self.max_results = Some(value);
151        self
152    }
153
154    pub fn media_fields(mut self, value: HashSet<MediaFields>) -> Self {
155        self.media_fields = Some(value);
156        self
157    }
158
159    pub fn pagination_token(mut self, value: &str) -> Self {
160        self.pagination_token = Some(value.to_owned());
161        self
162    }
163
164    pub fn place_fields(mut self, value: HashSet<PlaceFields>) -> Self {
165        self.place_fields = Some(value);
166        self
167    }
168
169    pub fn poll_fields(mut self, value: HashSet<PollFields>) -> Self {
170        self.poll_fields = Some(value);
171        self
172    }
173
174    pub fn tweet_fields(mut self, value: HashSet<TweetFields>) -> Self {
175        self.tweet_fields = Some(value);
176        self
177    }
178
179    pub fn user_fields(mut self, value: HashSet<UserFields>) -> Self {
180        self.user_fields = Some(value);
181        self
182    }
183
184    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
185        self.twapi_options = Some(value);
186        self
187    }
188
189    pub fn build(self, authentication: &impl Authentication) -> RequestBuilder {
190        let mut query_parameters = vec![];
191        if let Some(expansions) = self.expansions {
192            query_parameters.push(("expansions", expansions.iter().join(",")));
193        }
194        if let Some(max_results) = self.max_results {
195            query_parameters.push(("max_results", max_results.to_string()));
196        }
197        if let Some(media_fields) = self.media_fields {
198            query_parameters.push(("media.fields", media_fields.iter().join(",")));
199        }
200        if let Some(pagination_token) = self.pagination_token {
201            query_parameters.push(("pagination_token", pagination_token));
202        }
203        if let Some(place_fields) = self.place_fields {
204            query_parameters.push(("place.fields", place_fields.iter().join(",")));
205        }
206        if let Some(poll_fields) = self.poll_fields {
207            query_parameters.push(("poll.fields", poll_fields.iter().join(",")));
208        }
209        if let Some(tweet_fields) = self.tweet_fields {
210            query_parameters.push(("tweet.fields", tweet_fields.iter().join(",")));
211        }
212        if let Some(user_fields) = self.user_fields {
213            query_parameters.push(("user.fields", user_fields.iter().join(",")));
214        }
215        let client = reqwest::Client::new();
216        let url = make_url(&self.twapi_options, &URL.replace(":id", &self.id));
217        let builder = client.get(&url).query(&query_parameters);
218        authentication.execute(
219            apply_options(builder, &self.twapi_options),
220            "GET",
221            &url,
222            &query_parameters
223                .iter()
224                .map(|it| (it.0, it.1.as_str()))
225                .collect::<Vec<_>>(),
226        )
227    }
228
229    pub async fn execute(
230        self,
231        authentication: &impl Authentication,
232    ) -> Result<(Response, Headers), Error> {
233        execute_twitter(self.build(authentication)).await
234    }
235}
236
237#[derive(Serialize, Deserialize, Debug, Clone, Default)]
238pub struct Response {
239    #[serde(skip_serializing_if = "Option::is_none")]
240    pub data: Option<Vec<Tweets>>,
241    #[serde(skip_serializing_if = "Option::is_none")]
242    pub errors: Option<Vec<Errors>>,
243    #[serde(skip_serializing_if = "Option::is_none")]
244    pub includes: Option<Includes>,
245    #[serde(skip_serializing_if = "Option::is_none")]
246    pub meta: Option<Meta>,
247    #[serde(flatten)]
248    pub extra: std::collections::HashMap<String, serde_json::Value>,
249}
250
251impl Response {
252    pub fn is_empty_extra(&self) -> bool {
253        let res = self.extra.is_empty()
254            && self
255                .data
256                .as_ref()
257                .map(|it| it.iter().all(|item| item.is_empty_extra()))
258                .unwrap_or(true)
259            && self
260                .errors
261                .as_ref()
262                .map(|it| it.iter().all(|item| item.is_empty_extra()))
263                .unwrap_or(true)
264            && self
265                .includes
266                .as_ref()
267                .map(|it| it.is_empty_extra())
268                .unwrap_or(true)
269            && self
270                .meta
271                .as_ref()
272                .map(|it| it.is_empty_extra())
273                .unwrap_or(true);
274        if !res {
275            println!("Response {:?}", self.extra);
276        }
277        res
278    }
279}