Skip to main content

twapi_v2/api/
get_2_tweets_sample_stream.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, tweets::Tweets};
6use crate::{
7    api::{Authentication, TwapiOptions, apply_options, execute_twitter, make_url},
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, 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#[derive(Debug, Clone, Default)]
91pub struct Api {
92    backfill_minutes: Option<usize>,
93    end_time: Option<DateTime<Utc>>,
94    expansions: Option<HashSet<Expansions>>,
95    media_fields: Option<HashSet<MediaFields>>,
96    place_fields: Option<HashSet<PlaceFields>>,
97    poll_fields: Option<HashSet<PollFields>>,
98    start_time: Option<DateTime<Utc>>,
99    tweet_fields: Option<HashSet<TweetFields>>,
100    user_fields: Option<HashSet<UserFields>>,
101    twapi_options: Option<TwapiOptions>,
102}
103
104impl Api {
105    pub fn new() -> Self {
106        Self {
107            ..Default::default()
108        }
109    }
110
111    pub fn all() -> Self {
112        Self {
113            expansions: Some(Expansions::all()),
114            media_fields: Some(MediaFields::all()),
115            place_fields: Some(PlaceFields::all()),
116            poll_fields: Some(PollFields::all()),
117            tweet_fields: Some(TweetFields::organic()),
118            user_fields: Some(UserFields::all()),
119            ..Default::default()
120        }
121    }
122
123    pub fn open() -> Self {
124        Self {
125            expansions: Some(Expansions::all()),
126            media_fields: Some(MediaFields::open()),
127            place_fields: Some(PlaceFields::all()),
128            poll_fields: Some(PollFields::all()),
129            tweet_fields: Some(TweetFields::open()),
130            user_fields: Some(UserFields::all()),
131            ..Default::default()
132        }
133    }
134
135    pub fn backfill_minutes(mut self, value: usize) -> Self {
136        self.backfill_minutes = Some(value);
137        self
138    }
139
140    pub fn end_time(mut self, value: DateTime<Utc>) -> Self {
141        self.end_time = Some(value);
142        self
143    }
144
145    pub fn expansions(mut self, value: HashSet<Expansions>) -> Self {
146        self.expansions = Some(value);
147        self
148    }
149
150    pub fn media_fields(mut self, value: HashSet<MediaFields>) -> Self {
151        self.media_fields = Some(value);
152        self
153    }
154
155    pub fn place_fields(mut self, value: HashSet<PlaceFields>) -> Self {
156        self.place_fields = Some(value);
157        self
158    }
159
160    pub fn poll_fields(mut self, value: HashSet<PollFields>) -> Self {
161        self.poll_fields = Some(value);
162        self
163    }
164
165    pub fn start_time(mut self, value: DateTime<Utc>) -> Self {
166        self.start_time = Some(value);
167        self
168    }
169
170    pub fn tweet_fields(mut self, value: HashSet<TweetFields>) -> Self {
171        self.tweet_fields = Some(value);
172        self
173    }
174
175    pub fn user_fields(mut self, value: HashSet<UserFields>) -> Self {
176        self.user_fields = Some(value);
177        self
178    }
179
180    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
181        self.twapi_options = Some(value);
182        self
183    }
184
185    pub fn build(self, authentication: &impl Authentication) -> RequestBuilder {
186        let mut query_parameters = vec![];
187        if let Some(backfill_minutes) = self.backfill_minutes {
188            query_parameters.push(("backfill_minutes", backfill_minutes.to_string()));
189        }
190        if let Some(end_time) = self.end_time {
191            query_parameters.push((
192                "end_time",
193                end_time.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
194            ));
195        }
196        if let Some(expansions) = self.expansions {
197            query_parameters.push(("expansions", expansions.iter().join(",")));
198        }
199        if let Some(media_fields) = self.media_fields {
200            query_parameters.push(("media.fields", media_fields.iter().join(",")));
201        }
202        if let Some(place_fields) = self.place_fields {
203            query_parameters.push(("place.fields", place_fields.iter().join(",")));
204        }
205        if let Some(poll_fields) = self.poll_fields {
206            query_parameters.push(("poll.fields", poll_fields.iter().join(",")));
207        }
208        if let Some(start_time) = self.start_time {
209            query_parameters.push((
210                "start_time",
211                start_time.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
212            ));
213        }
214        if let Some(tweet_fields) = self.tweet_fields {
215            query_parameters.push(("tweet.fields", tweet_fields.iter().join(",")));
216        }
217        if let Some(user_fields) = self.user_fields {
218            query_parameters.push(("user.fields", user_fields.iter().join(",")));
219        }
220        let client = reqwest::Client::new();
221        let url = make_url(&self.twapi_options, URL);
222        let builder = client.get(&url).query(&query_parameters);
223        authentication.execute(
224            apply_options(builder, &self.twapi_options),
225            "GET",
226            &url,
227            &query_parameters
228                .iter()
229                .map(|it| (it.0, it.1.as_str()))
230                .collect::<Vec<_>>(),
231        )
232    }
233
234    pub async fn execute(
235        self,
236        authentication: &impl Authentication,
237    ) -> Result<(Response, Headers), Error> {
238        execute_twitter(self.build(authentication)).await
239    }
240}
241
242#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
243pub struct Response {
244    #[serde(skip_serializing_if = "Option::is_none")]
245    pub data: Option<Tweets>,
246    #[serde(skip_serializing_if = "Option::is_none")]
247    pub errors: Option<Vec<Errors>>,
248    #[serde(skip_serializing_if = "Option::is_none")]
249    pub includes: Option<Includes>,
250    #[serde(flatten)]
251    pub extra: std::collections::HashMap<String, serde_json::Value>,
252}
253
254impl Response {
255    pub fn is_empty_extra(&self) -> bool {
256        let res = self.extra.is_empty()
257            && self
258                .data
259                .as_ref()
260                .map(|it| it.is_empty_extra())
261                .unwrap_or(true)
262            && self
263                .errors
264                .as_ref()
265                .map(|it| it.iter().all(|item| item.is_empty_extra()))
266                .unwrap_or(true)
267            && self
268                .includes
269                .as_ref()
270                .map(|it| it.is_empty_extra())
271                .unwrap_or(true);
272        if !res {
273            println!("Response {:?}", self.extra);
274        }
275        res
276    }
277}