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, 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)]
20#[derive(Default)]
21pub enum Expansions {
22    #[serde(rename = "article.cover_media")]
23    #[default]
24    ArticleCoverMedia,
25    #[serde(rename = "article.media_entities")]
26    ArticleMediaEntities,
27    #[serde(rename = "attachments.media_keys")]
28    AttachmentsMediaKeys,
29    #[serde(rename = "attachments.media_source_tweet")]
30    AttachmentsMediaSourceTweet,
31    #[serde(rename = "attachments.poll_ids")]
32    AttachmentsPollIds,
33    #[serde(rename = "author_id")]
34    AuthorId,
35    #[serde(rename = "edit_history_tweet_ids")]
36    EditHistoryTweetIds,
37    #[serde(rename = "entities.mentions.username")]
38    EntitiesMentionsUsername,
39    #[serde(rename = "geo.place_id")]
40    GeoPlaceId,
41    #[serde(rename = "in_reply_to_user_id")]
42    InReplyToUserId,
43    #[serde(rename = "entities.note.mentions.username")]
44    EntitiesNoteMentionsUsername,
45    #[serde(rename = "referenced_tweets.id")]
46    ReferencedTweetsId,
47    #[serde(rename = "referenced_tweets.id.author_id")]
48    ReferencedTweetsIdAuthorId,
49}
50
51impl Expansions {
52    pub fn all() -> HashSet<Self> {
53        let mut result = HashSet::new();
54        result.insert(Self::ArticleCoverMedia);
55        result.insert(Self::ArticleMediaEntities);
56        result.insert(Self::AttachmentsMediaKeys);
57        result.insert(Self::AttachmentsMediaSourceTweet);
58        result.insert(Self::AttachmentsPollIds);
59        result.insert(Self::AuthorId);
60        result.insert(Self::EditHistoryTweetIds);
61        result.insert(Self::EntitiesMentionsUsername);
62        result.insert(Self::GeoPlaceId);
63        result.insert(Self::InReplyToUserId);
64        result.insert(Self::EntitiesNoteMentionsUsername);
65        result.insert(Self::ReferencedTweetsId);
66        result.insert(Self::ReferencedTweetsIdAuthorId);
67        result
68    }
69}
70
71impl std::fmt::Display for Expansions {
72    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
73        match self {
74            Self::ArticleCoverMedia => write!(f, "article.cover_media"),
75            Self::ArticleMediaEntities => write!(f, "article.media_entities"),
76            Self::AttachmentsMediaKeys => write!(f, "attachments.media_keys"),
77            Self::AttachmentsMediaSourceTweet => write!(f, "attachments.media_source_tweet"),
78            Self::AttachmentsPollIds => write!(f, "attachments.poll_ids"),
79            Self::AuthorId => write!(f, "author_id"),
80            Self::EditHistoryTweetIds => write!(f, "edit_history_tweet_ids"),
81            Self::EntitiesMentionsUsername => write!(f, "entities.mentions.username"),
82            Self::GeoPlaceId => write!(f, "geo.place_id"),
83            Self::InReplyToUserId => write!(f, "in_reply_to_user_id"),
84            Self::EntitiesNoteMentionsUsername => write!(f, "entities.note.mentions.username"),
85            Self::ReferencedTweetsId => write!(f, "referenced_tweets.id"),
86            Self::ReferencedTweetsIdAuthorId => write!(f, "referenced_tweets.id.author_id"),
87        }
88    }
89}
90
91
92#[derive(Debug, Clone, Default)]
93pub struct Api {
94    backfill_minutes: Option<usize>,
95    end_time: Option<DateTime<Utc>>,
96    expansions: Option<HashSet<Expansions>>,
97    media_fields: Option<HashSet<MediaFields>>,
98    place_fields: Option<HashSet<PlaceFields>>,
99    poll_fields: Option<HashSet<PollFields>>,
100    start_time: Option<DateTime<Utc>>,
101    tweet_fields: Option<HashSet<TweetFields>>,
102    user_fields: Option<HashSet<UserFields>>,
103    twapi_options: Option<TwapiOptions>,
104}
105
106impl Api {
107    pub fn new() -> Self {
108        Self {
109            ..Default::default()
110        }
111    }
112
113    pub fn all() -> Self {
114        Self {
115            expansions: Some(Expansions::all()),
116            media_fields: Some(MediaFields::all()),
117            place_fields: Some(PlaceFields::all()),
118            poll_fields: Some(PollFields::all()),
119            tweet_fields: Some(TweetFields::organic()),
120            user_fields: Some(UserFields::all()),
121            ..Default::default()
122        }
123    }
124
125    pub fn open() -> Self {
126        Self {
127            expansions: Some(Expansions::all()),
128            media_fields: Some(MediaFields::open()),
129            place_fields: Some(PlaceFields::all()),
130            poll_fields: Some(PollFields::all()),
131            tweet_fields: Some(TweetFields::open()),
132            user_fields: Some(UserFields::all()),
133            ..Default::default()
134        }
135    }
136
137    pub fn backfill_minutes(mut self, value: usize) -> Self {
138        self.backfill_minutes = Some(value);
139        self
140    }
141
142    pub fn end_time(mut self, value: DateTime<Utc>) -> Self {
143        self.end_time = Some(value);
144        self
145    }
146
147    pub fn expansions(mut self, value: HashSet<Expansions>) -> Self {
148        self.expansions = Some(value);
149        self
150    }
151
152    pub fn media_fields(mut self, value: HashSet<MediaFields>) -> Self {
153        self.media_fields = Some(value);
154        self
155    }
156
157    pub fn place_fields(mut self, value: HashSet<PlaceFields>) -> Self {
158        self.place_fields = Some(value);
159        self
160    }
161
162    pub fn poll_fields(mut self, value: HashSet<PollFields>) -> Self {
163        self.poll_fields = Some(value);
164        self
165    }
166
167    pub fn start_time(mut self, value: DateTime<Utc>) -> Self {
168        self.start_time = Some(value);
169        self
170    }
171
172    pub fn tweet_fields(mut self, value: HashSet<TweetFields>) -> Self {
173        self.tweet_fields = Some(value);
174        self
175    }
176
177    pub fn user_fields(mut self, value: HashSet<UserFields>) -> Self {
178        self.user_fields = Some(value);
179        self
180    }
181
182    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
183        self.twapi_options = Some(value);
184        self
185    }
186
187    pub fn build(&self, authentication: &impl Authentication) -> RequestBuilder {
188        let mut query_parameters = vec![];
189        if let Some(backfill_minutes) = self.backfill_minutes.as_ref() {
190            query_parameters.push(("backfill_minutes", backfill_minutes.to_string()));
191        }
192        if let Some(end_time) = self.end_time.as_ref() {
193            query_parameters.push((
194                "end_time",
195                end_time.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
196            ));
197        }
198        if let Some(expansions) = self.expansions.as_ref() {
199            query_parameters.push(("expansions", expansions.iter().join(",")));
200        }
201        if let Some(media_fields) = self.media_fields.as_ref() {
202            query_parameters.push(("media.fields", media_fields.iter().join(",")));
203        }
204        if let Some(place_fields) = self.place_fields.as_ref() {
205            query_parameters.push(("place.fields", place_fields.iter().join(",")));
206        }
207        if let Some(poll_fields) = self.poll_fields.as_ref() {
208            query_parameters.push(("poll.fields", poll_fields.iter().join(",")));
209        }
210        if let Some(start_time) = self.start_time.as_ref() {
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.as_ref() {
217            query_parameters.push(("tweet.fields", tweet_fields.iter().join(",")));
218        }
219        if let Some(user_fields) = self.user_fields.as_ref() {
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            builder,
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), &self.twapi_options).await
241    }
242}
243
244#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
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}