1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
use crate::models::bearer::BearerToken;
use crate::TwitterAPI;
use anyhow::Result;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};

/// A `ClientBuilder` can help construct a [`TwitterAPI`] instance with your configuration.
/// Before calling [`build`] method, you must set four values:
///
/// 1. `Access token`
/// 2. `Access token secret`
/// 3. `API key`
/// 4. `API secret key`
///
/// The four setter methods can be called with any order.
///
/// # Example
///
/// ```rust
/// # async fn doc() -> Result<(), anyhow::Error> {
/// use kuon::ClientBuilder;
/// let builder = ClientBuilder::new();
///
/// // The order of setter methods can be changed.
/// let api_client = builder
///     .access_token("YOUR_ACCESS_TOKEN")
///     .access_token_secret("YOUR_ACCESS_TOKEN_SECRET")
///     .api_key("YOUR_API_KEY")
///     .api_secret_key("YOUR_API_SECRET_KEY")
///     .build() // This can be called only after all values have been set.
///     .await?;
/// # Ok(())
/// # }
/// ```
///
/// [`TwitterAPI`]: struct.TwitterAPI.html
/// [`build`]: struct.ClientBuilder.html#method.build
#[derive(Debug, Default)]
pub struct ClientBuilder<AccessTokenType, AccessTokenSecretType, ApiKeyType, ApiKeySecretType> {
    access_token: AccessTokenType,
    access_token_secret: AccessTokenSecretType,
    api_key: ApiKeyType,
    api_secret_key: ApiKeySecretType,
}

impl ClientBuilder<(), (), (), ()> {
    /// Creates a builder instance.
    ///
    /// This is exactly equivalent to [`TwitterAPI::builder`].
    ///
    /// [`TwitterAPI::builder`]: struct.TwitterAPI.html#method.builder
    pub fn new() -> Self {
        ClientBuilder {
            access_token: (),
            access_token_secret: (),
            api_key: (),
            api_secret_key: (),
        }
    }
}

impl ClientBuilder<String, String, String, String> {
    /// Builds a [`TwitterAPI`] instance with the values you've set.
    ///
    /// You can call this method only after the four required values have been set.
    ///
    /// # Error
    ///
    /// This method fails if there is an error when obtaining a bearer token.
    ///
    /// [`TwitterAPI`]: struct.TwitterAPI.html
    pub async fn build(self) -> Result<TwitterAPI> {
        let client = reqwest::Client::new();
        let bearer = self.get_bearer(&client).await?;

        Ok(TwitterAPI {
            access_token: self.access_token,
            access_token_secret: self.access_token_secret,
            api_key: self.api_key,
            api_secret_key: self.api_secret_key,
            bearer,
            client,
        })
    }

    async fn get_bearer(&self, client: &reqwest::Client) -> Result<BearerToken> {
        let endpoint = "https://api.twitter.com/oauth2/token";
        let headers = self.setup_header()?;
        let bearer: BearerToken = Self::request_oauth(client, endpoint, headers).await?;
        Ok(bearer)
    }

    async fn request_oauth(
        client: &reqwest::Client,
        endpoint: impl reqwest::IntoUrl,
        header: HeaderMap<HeaderValue>,
    ) -> Result<BearerToken> {
        // TODO: #8 better error handling
        let res = client
            .post(endpoint)
            .body("grant_type=client_credentials")
            .headers(header)
            .send()
            .await?
            .text()
            .await?;
        let bearer: BearerToken = serde_json::from_str(&res)?;
        Ok(bearer)
    }

    fn setup_header(&self) -> Result<HeaderMap<HeaderValue>> {
        let encoded_keys = base64::encode(&format!("{}:{}", &self.api_key, &self.api_secret_key));
        let header_auth = format!("Basic {}", encoded_keys);

        let mut headers = HeaderMap::new();
        headers.insert(AUTHORIZATION, header_auth.parse()?);
        headers.insert(
            CONTENT_TYPE,
            HeaderValue::from_static("application/x-www-form-urlencoded"),
        );
        Ok(headers)
    }
}

impl<AccessTokenType, AccessTokenSecretType, ApiKeyType, ApiKeySecretType>
    ClientBuilder<AccessTokenType, AccessTokenSecretType, ApiKeyType, ApiKeySecretType>
{
    /// Sets the access token.
    pub fn access_token(
        self,
        access_token: impl Into<String>,
    ) -> ClientBuilder<String, AccessTokenSecretType, ApiKeyType, ApiKeySecretType> {
        ClientBuilder {
            access_token: access_token.into(),
            access_token_secret: self.access_token_secret,
            api_key: self.api_key,
            api_secret_key: self.api_secret_key,
        }
    }

    /// Sets the access token secret.
    pub fn access_token_secret(
        self,
        access_token_secret: impl Into<String>,
    ) -> ClientBuilder<AccessTokenType, String, ApiKeyType, ApiKeySecretType> {
        ClientBuilder {
            access_token: self.access_token,
            access_token_secret: access_token_secret.into(),
            api_key: self.api_key,
            api_secret_key: self.api_secret_key,
        }
    }

    /// Sets the api key.
    pub fn api_key(
        self,
        api_key: impl Into<String>,
    ) -> ClientBuilder<AccessTokenType, AccessTokenSecretType, String, ApiKeySecretType> {
        ClientBuilder {
            access_token: self.access_token,
            access_token_secret: self.access_token_secret,
            api_key: api_key.into(),
            api_secret_key: self.api_secret_key,
        }
    }

    /// Sets the api secret key.
    pub fn api_secret_key(
        self,
        api_secret_key: impl Into<String>,
    ) -> ClientBuilder<AccessTokenType, AccessTokenSecretType, ApiKeyType, String> {
        ClientBuilder {
            access_token: self.access_token,
            access_token_secret: self.access_token_secret,
            api_key: self.api_key,
            api_secret_key: api_secret_key.into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[test]
    fn builder_method_chain() {
        let builder = ClientBuilder::new()
            .api_key("foo")
            .access_token_secret("bar")
            .api_secret_key("baz")
            .access_token("qux");

        assert_eq!(builder.api_key, "foo");
        assert_eq!(builder.api_secret_key, "baz");
        assert_eq!(builder.access_token, "qux");
        assert_eq!(builder.access_token_secret, "bar");
    }

    #[test]
    fn setup_header() {
        let builder = ClientBuilder::new()
            .api_key("foo")
            .access_token_secret("bar")
            .api_secret_key("baz")
            .access_token("qux");

        let expected = {
            let mut h = HeaderMap::new();
            h.insert(
                AUTHORIZATION,
                HeaderValue::from_static("Basic Zm9vOmJheg=="),
            );
            h.insert(
                CONTENT_TYPE,
                HeaderValue::from_static("application/x-www-form-urlencoded"),
            );
            h
        };

        assert_eq!(builder.setup_header().unwrap(), expected);
    }

    #[tokio::test]
    async fn request_oauth() {
        // arrange the behavior of the mock server
        let mock_server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "foo",
                "token_type": "bar",
            })))
            .expect(1)
            .mount(&mock_server)
            .await;

        // prepare for calling `ClientBuilder::request_oauth`
        let client = reqwest::Client::new();
        let uri = mock_server.uri();

        let res = ClientBuilder::request_oauth(&client, &uri, HeaderMap::new())
            .await
            .unwrap();

        assert_eq!(
            res,
            BearerToken {
                access_token: "foo".to_string(),
                token_type: "bar".to_string(),
            }
        );
    }
}