Skip to main content

twapi_v2/api/
get_2_spaces_by_creator_ids.rs

1use crate::fields::{
2    space_fields::SpaceFields, topic_fields::TopicFields, user_fields::UserFields,
3};
4use crate::responses::{errors::Errors, includes::Includes, meta::Meta, spaces::Spaces};
5use crate::{
6    api::{Authentication, TwapiOptions, execute_twitter, make_url},
7    error::Error,
8    headers::Headers,
9};
10use itertools::Itertools;
11use reqwest::RequestBuilder;
12use serde::{Deserialize, Serialize};
13use std::collections::HashSet;
14
15const URL: &str = "/2/spaces/by/creator_ids";
16
17#[derive(Serialize, Deserialize, Debug, Eq, Hash, PartialEq, Clone, Default)]
18pub enum Expansions {
19    #[serde(rename = "invited_user_ids")]
20    #[default]
21    InvitedUserIds,
22    #[serde(rename = "speaker_ids")]
23    SpeakerIds,
24    #[serde(rename = "creator_id")]
25    CreatorId,
26    #[serde(rename = "host_ids")]
27    HostIds,
28    #[serde(rename = "topics_ids")]
29    TopicsIds,
30}
31
32impl Expansions {
33    pub fn all() -> HashSet<Self> {
34        let mut result = HashSet::new();
35        result.insert(Self::InvitedUserIds);
36        result.insert(Self::SpeakerIds);
37        result.insert(Self::CreatorId);
38        result.insert(Self::HostIds);
39        result.insert(Self::TopicsIds);
40        result
41    }
42}
43
44impl std::fmt::Display for Expansions {
45    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
46        match self {
47            Self::InvitedUserIds => write!(f, "invited_user_ids"),
48            Self::SpeakerIds => write!(f, "speaker_ids"),
49            Self::CreatorId => write!(f, "creator_id"),
50            Self::HostIds => write!(f, "host_ids"),
51            Self::TopicsIds => write!(f, "topics_ids"),
52        }
53    }
54}
55
56#[derive(Debug, Clone, Default)]
57pub struct Api {
58    user_ids: String,
59    expansions: Option<HashSet<Expansions>>,
60    space_fields: Option<HashSet<SpaceFields>>,
61    topic_fields: Option<HashSet<TopicFields>>,
62    user_fields: Option<HashSet<UserFields>>,
63    twapi_options: Option<TwapiOptions>,
64}
65
66impl Api {
67    pub fn new(user_ids: &str) -> Self {
68        Self {
69            user_ids: user_ids.to_owned(),
70            ..Default::default()
71        }
72    }
73
74    pub fn all(user_ids: &str) -> Self {
75        Self {
76            user_ids: user_ids.to_owned(),
77            expansions: Some(Expansions::all()),
78            space_fields: Some(SpaceFields::all()),
79            topic_fields: Some(TopicFields::all()),
80            user_fields: Some(UserFields::all()),
81            ..Default::default()
82        }
83    }
84
85    pub fn expansions(mut self, value: HashSet<Expansions>) -> Self {
86        self.expansions = Some(value);
87        self
88    }
89
90    pub fn space_fields(mut self, value: HashSet<SpaceFields>) -> Self {
91        self.space_fields = Some(value);
92        self
93    }
94
95    pub fn topic_fields(mut self, value: HashSet<TopicFields>) -> Self {
96        self.topic_fields = Some(value);
97        self
98    }
99
100    pub fn user_fields(mut self, value: HashSet<UserFields>) -> Self {
101        self.user_fields = Some(value);
102        self
103    }
104
105    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
106        self.twapi_options = Some(value);
107        self
108    }
109
110    pub fn build(&self, authentication: &impl Authentication) -> RequestBuilder {
111        let mut query_parameters = vec![];
112        query_parameters.push(("user_ids", self.user_ids.to_string()));
113        if let Some(expansions) = self.expansions.as_ref() {
114            query_parameters.push(("expansions", expansions.iter().join(",")));
115        }
116        if let Some(space_fields) = self.space_fields.as_ref() {
117            query_parameters.push(("space.fields", space_fields.iter().join(",")));
118        }
119        if let Some(topic_fields) = self.topic_fields.as_ref() {
120            query_parameters.push(("topic.fields", topic_fields.iter().join(",")));
121        }
122        if let Some(user_fields) = self.user_fields.as_ref() {
123            query_parameters.push(("user.fields", user_fields.iter().join(",")));
124        }
125        let client = reqwest::Client::new();
126        let url = make_url(&self.twapi_options, URL);
127        let builder = client.get(&url).query(&query_parameters);
128        authentication.execute(
129            builder,
130            "GET",
131            &url,
132            &query_parameters
133                .iter()
134                .map(|it| (it.0, it.1.as_str()))
135                .collect::<Vec<_>>(),
136        )
137    }
138
139    pub async fn execute(
140        &self,
141        authentication: &impl Authentication,
142    ) -> Result<(Response, Headers), Error> {
143        execute_twitter(|| self.build(authentication), &self.twapi_options).await
144    }
145}
146
147#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
148pub struct Response {
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub data: Option<Vec<Spaces>>,
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub errors: Option<Vec<Errors>>,
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub includes: Option<Includes>,
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub meta: Option<Meta>,
157    #[serde(flatten)]
158    pub extra: std::collections::HashMap<String, serde_json::Value>,
159}
160
161impl Response {
162    pub fn is_empty_extra(&self) -> bool {
163        let res = self.extra.is_empty()
164            && self
165                .data
166                .as_ref()
167                .map(|it| it.iter().all(|item| item.is_empty_extra()))
168                .unwrap_or(true)
169            && self
170                .errors
171                .as_ref()
172                .map(|it| it.iter().all(|item| item.is_empty_extra()))
173                .unwrap_or(true)
174            && self
175                .includes
176                .as_ref()
177                .map(|it| it.is_empty_extra())
178                .unwrap_or(true)
179            && self
180                .meta
181                .as_ref()
182                .map(|it| it.is_empty_extra())
183                .unwrap_or(true);
184        if !res {
185            println!("Response {:?}", self.extra);
186        }
187        res
188    }
189}