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