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