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