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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//! Foursquare provides a api bindings to the
//! [foursquare.com API](https://developer.foursquare.com/)
//!
//! # Examples
//!
//! Typical use will require instantiation of a `foursquare::Client`.
//! This requires a version string, set of `foursquare::Credentials`
//! and a tokio_core `Handle` reference.
//!
//! ```no_run
//! extern crate foursquare;
//! extern crate hyper;
//! extern crate tokio_core;
//!
//! use tokio_core::reactor::Core;
//! use foursquare::{Credentials, Client};
//!
//! fn main() {
//!   let mut core = Core::new().expect("reactor fail");
//!   let fs = Client::new(
//!     "YYYYMMDD",
//!     Credentials::client(
//!       "client_id", "client_secret"
//!     ),
//!     &core.handle()
//!   );
//! }
//! ```
//!
//! Access to various services are provided via methods on instances of
//! the `Client` type.
//!
//! The convention for executing operations typically looks like
//! `client.venues().operation(&OperationOptions)` where operation is the name
//! of the operation to perform
//!
//! # Errors
//!
//! Operations typically result in a `foursquare::Future` Type which is an alias
//! for the the [futures](https://docs.rs/futures/futures) crates Future trait
//! with the Error type fixed to the
//! [foursquare::Error](error/struct.Error.html) type.
//!
#![allow(missing_docs)] // todo: make this a deny eventually

#[macro_use]
extern crate derive_builder;
extern crate futures;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
extern crate hyper;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate serde_urlencoded;
extern crate url;
extern crate tokio_core;
#[cfg(feature = "tls")]
extern crate hyper_tls;

#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;

use futures::{Future as StdFuture, IntoFuture, Stream as StdStream};
use hyper::{Client as HyperClient, Method};
use hyper::client::{Connect, HttpConnector, Request};
#[cfg(feature = "tls")]
use hyper_tls::HttpsConnector;
use serde::de::DeserializeOwned;
use tokio_core::reactor::Handle;
use url::Url;

pub mod venue;
pub use venue::Venues;
pub mod error;
pub use error::{Error, ErrorKind, Result};

const DEFAULT_HOST: &str = "https://api.foursquare.com";

/// A type alias for `Futures` that may return `foursquare::Errors`
pub type Future<T> = Box<StdFuture<Item = T, Error = Error>>;

/// types of credentials used to authenticate requests
///
/// see [this doc](https://developer.foursquare.com/docs/api/configuration/authentication)
/// for more information
#[derive(Debug, PartialEq, Clone)]
pub enum Credentials {
    /// Userless authentication
    Client {
        client_id: String,
        client_secret: String,
    },
    /// User authentication, specific to a foursquare member
    User { oauth_token: String },
}

impl Credentials {
    /// Return a new set of Client credentials
    pub fn client<I, S>(id: I, secret: S) -> Self
    where
        I: Into<String>,
        S: Into<String>,
    {
        Credentials::Client {
            client_id: id.into(),
            client_secret: secret.into(),
        }
    }

    /// Return a new User credential
    pub fn user<T>(token: T) -> Self
    where
        T: Into<String>,
    {
        Credentials::User { oauth_token: token.into() }
    }
}

/// Entry point interface for interacting with Foursquare API
#[derive(Clone, Debug)]
pub struct Client<C>
where
    C: Clone + Connect,
{
    host: String,
    version: String,
    http: HyperClient<C>,
    credentials: Credentials,
}

#[cfg(feature = "tls")]
impl Client<HttpsConnector<HttpConnector>> {
    /// returns a new client
    ///
    /// version should be in `YYYYMMDD` format
    pub fn new<V>(version: V, credentials: Credentials, handle: &Handle) -> Self
    where
        V: Into<String>,
    {
        let connector = HttpsConnector::new(4, handle).unwrap();
        let http = HyperClient::configure()
            .connector(connector)
            .keep_alive(true)
            .build(handle);
        Self::custom(version, credentials, http)
    }
}

impl<C> Client<C>
where
    C: Clone + Connect,
{
    /// Return a new Client with a custom `hyper::Client`
    pub fn custom<V>(
        version: V,
        credentials: Credentials,
        http: HyperClient<C>,
    ) -> Self
    where
        V: Into<String>,
    {
        Self {
            host: DEFAULT_HOST.to_owned(),
            version: version.into(),
            http: http,
            credentials: credentials,
        }
    }

    /// Return an interface to venue operations
    pub fn venues(&self) -> Venues<C> {
        Venues::new(self.clone())
    }

    fn get<Out>(&self, uri: String) -> Future<Out>
    where
        Out: DeserializeOwned + 'static,
    {
        self.request(Method::Get, uri, None)
    }

    fn request<Out>(
        &self,
        method: Method,
        uri: String,
        body: Option<Vec<u8>>,
    ) -> Future<Out>
    where
        Out: DeserializeOwned + 'static,
    {
        let url = {
            let mut parsed = Url::parse(&uri).unwrap();
            parsed.query_pairs_mut().append_pair(
                "v",
                self.version.as_ref(),
            );
            if let Credentials::User { ref oauth_token } = self.credentials {
                parsed.query_pairs_mut().append_pair(
                    "oauth_token",
                    oauth_token.as_str(),
                );
            }
            if let Credentials::Client {
                ref client_id,
                ref client_secret,
            } = self.credentials
            {
                parsed
                    .query_pairs_mut()
                    .append_pair("client_id", client_id.as_str())
                    .append_pair("client_secret", client_secret.as_str());
            }
            parsed.to_string().parse().into_future()
        };
        let instance = self.clone();
        let body2 = body.clone();
        let method2 = method.clone();
        let response = url.map_err(Error::from).and_then(move |url| {
            let mut req = Request::new(method2, url);

            if let Some(body) = body2 {
                req.set_body(body)
            }
            instance.http.request(req).map_err(Error::from)
        });
        Box::new(response.and_then(move |response| {
            debug!("response headers {:?}", response.headers());
            let status = response.status();
            Box::new(response.body().concat2().map_err(Error::from).and_then(
                move |response_body| if status.is_success() {
                    debug!(
                        "response payload {}",
                        String::from_utf8_lossy(&response_body)
                    );
                    serde_json::from_slice::<Out>(&response_body).map_err(
                        |error| {
                            ErrorKind::Codec(error).into()
                        },
                    )
                } else {
                    debug!(
                        "response error {}",
                        String::from_utf8_lossy(&response_body)
                    );
                    Err(
                        ErrorKind::Fault {
                            code: status,
                            error: serde_json::from_slice(&response_body)?,
                        }.into(),
                    )
                },
            ))
        }))
    }
}

// representations

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Meta {
    pub code: u16,
    #[serde(rename = "requestId")]
    pub request_id: String,
    #[serde(rename = "errorType")]
    pub error_type: Option<String>,
    #[serde(rename = "errorDetail")]
    pub error_detail: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Response<T> {
    pub meta: Meta,
    pub response: T,
}