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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Modio provides a set of building blocks for interacting with the [mod.io](https://mod.io) API.
//!
//! The client uses asynchronous I/O, backed by the `futures` and `tokio` crates, and requires both
//! to be used alongside.
//!
//! # Authentication
//!
//! To access the API authentication is required and can be done via 3 ways:
//!
//! - Request an [API key (Read-only)](https://mod.io/apikey)
//! - Manually create an [OAuth 2 Access Token (Read + Write)](https://mod.io/oauth)
//! - [Email Authentication Flow](auth/struct.Auth.html#example) to create an OAuth 2 Access Token
//! (Read + Write)
//!
//! # Rate Limiting
//!
//! For API requests using API key authentication are **unlimited** and for OAuth 2 authentication
//! requests are limited to **120 requests per hour**.
//!
//! A special error [Error::RateLimit](error/enum.Error.html#variant.RateLimit) will
//! be return from api operations when the rate limit associated with credentials has been
//! exhausted.
//!
//! # Examples
//!
//! ```no_run
//! extern crate modio;
//! extern crate tokio;
//!
//! use modio::{Credentials, Error, Modio};
//! use tokio::runtime::Runtime;
//!
//! fn main() -> Result<(), Error> {
//!     let mut rt = Runtime::new()?;
//!     let modio = Modio::new(
//!         "user-agent-name/1.0",
//!         Credentials::ApiKey(String::from("user-or-game-api-key")),
//!     );
//!
//!     // create some tasks and execute them
//!     // let result = rt.block_on(task)?;
//!     Ok(())
//! }
//! ```
//!
//! For testing purposes use [`Modio::host`](struct.Modio.html#method.host) to create a client for the
//! mod.io [test environment](https://docs.mod.io/#testing).
//!

#![doc(html_root_url = "https://docs.rs/modio/0.2.0")]

extern crate futures;
extern crate http;
extern crate hyper;
extern crate hyper_multipart_rfc7578 as hyper_multipart;
extern crate hyper_tls;
extern crate mime;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate url;
extern crate url_serde;

use std::marker::PhantomData;
use std::time::Duration;

use futures::{Future as StdFuture, IntoFuture, Stream as StdStream};
use hyper::client::connect::Connect;
use hyper::client::HttpConnector;
use hyper::header::{AUTHORIZATION, CONTENT_TYPE, LOCATION, USER_AGENT};
use hyper::{Body, Client, Method, Request, StatusCode, Uri};
use hyper_multipart::client::multipart;
use hyper_tls::HttpsConnector;
use mime::Mime;
use serde::de::DeserializeOwned;
use url::Url;

pub mod auth;
#[macro_use]
pub mod filter;
pub mod comments;
pub mod error;
pub mod files;
pub mod games;
pub mod me;
pub mod metadata;
pub mod mods;
pub mod reports;
pub mod teams;
mod types;
pub mod users;

use auth::Auth;
use comments::Comments;
use games::{GameRef, Games};
use me::Me;
use mods::{ModRef, Mods};
use reports::Reports;
use users::Users;

pub use auth::Credentials;
pub use error::Error;
pub use types::{Event, EventType, ModioErrorResponse, ModioListResponse, ModioMessage};

const DEFAULT_HOST: &str = "https://api.mod.io/v1";

pub type Future<T> = Box<StdFuture<Item = T, Error = Error> + Send>;
pub type Stream<T> = Box<StdStream<Item = T, Error = Error> + Send>;

#[allow(dead_code)]
const X_RATELIMIT_LIMIT: &str = "x-ratelimit-limit";
const X_RATELIMIT_REMAINING: &str = "x-ratelimit-remaining";
const X_RATELIMIT_RETRY_AFTER: &str = "x-ratelimit-retryafter";

/// Endpoint interface to interacting with the [mod.io](https://mod.io) API.
#[derive(Clone, Debug)]
pub struct Modio<C>
where
    C: Clone + Connect + 'static,
{
    host: String,
    agent: String,
    client: Client<C>,
    credentials: Credentials,
}

impl Modio<HttpsConnector<HttpConnector>> {
    /// Create an endpoint to [https://api.mod.io/v1](https://docs.mod.io/#mod-io-api-v1).
    pub fn new<A, C>(agent: A, credentials: C) -> Self
    where
        A: Into<String>,
        C: Into<Credentials>,
    {
        Self::host(DEFAULT_HOST, agent, credentials)
    }

    /// Create an endpoint to a different host.
    pub fn host<H, A, C>(host: H, agent: A, credentials: C) -> Self
    where
        H: Into<String>,
        A: Into<String>,
        C: Into<Credentials>,
    {
        let connector = HttpsConnector::new(4).unwrap();
        let client = Client::builder().keep_alive(true).build(connector);

        Self::custom(host, agent, credentials, client)
    }
}

impl<C> Modio<C>
where
    C: Clone + Connect + 'static,
{
    /// Create an endpoint with a custom hyper client.
    pub fn custom<H, A, CR>(host: H, agent: A, credentials: CR, client: Client<C>) -> Self
    where
        H: Into<String>,
        A: Into<String>,
        CR: Into<Credentials>,
    {
        Self {
            host: host.into(),
            agent: agent.into(),
            client,
            credentials: credentials.into(),
        }
    }

    /// Consume the endpoint and create an endpoint with new credentials.
    pub fn with_credentials<CR>(self, credentials: CR) -> Self
    where
        CR: Into<Credentials>,
    {
        Self {
            host: self.host,
            agent: self.agent,
            client: self.client,
            credentials: credentials.into(),
        }
    }

    /// Return a reference to an interface for requesting access tokens.
    pub fn auth(&self) -> Auth<C> {
        Auth::new(self.clone())
    }

    /// Return a reference to an interface that provides access to game informations.
    pub fn games(&self) -> Games<C> {
        Games::new(self.clone())
    }

    /// Return a reference to a game.
    pub fn game(&self, game_id: u32) -> GameRef<C> {
        GameRef::new(self.clone(), game_id)
    }

    /// Return a reference to a mod.
    pub fn mod_(&self, game_id: u32, mod_id: u32) -> ModRef<C> {
        ModRef::new(self.clone(), game_id, mod_id)
    }

    /// Return a reference to an interface that provides access to resources owned by the user
    /// associated with the current authentication credentials.
    pub fn me(&self) -> Me<C> {
        Me::new(self.clone())
    }

    /// Return a reference to an interface that provides access to user informations.
    pub fn users(&self) -> Users<C> {
        Users::new(self.clone())
    }

    /// Return a reference to an interface to report games, mods and users.
    pub fn reports(&self) -> Reports<C> {
        Reports::new(self.clone())
    }

    fn request<Out>(&self, method: Method, uri: &str, body: RequestBody) -> Future<Out>
    where
        Out: DeserializeOwned + 'static + Send,
    {
        let url = if let Credentials::ApiKey(ref api_key) = self.credentials {
            let mut parsed = Url::parse(&uri).unwrap();
            parsed.query_pairs_mut().append_pair("api_key", api_key);
            parsed.to_string().parse::<Uri>().into_future()
        } else {
            uri.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::builder();
            req.method(method2)
                .uri(url)
                .header(USER_AGENT, &*instance.agent);

            if let Credentials::Token(ref token) = instance.credentials {
                req.header(AUTHORIZATION, &*format!("Bearer {}", token));
            }

            let req = match body2 {
                RequestBody::Vec(body, mime) => {
                    req.header(CONTENT_TYPE, &*mime.to_string());
                    req.body(Body::from(body)).map_err(Error::from)
                }
                RequestBody::Form(data) => data
                    .to_form()
                    .and_then(move |form| form.set_body(&mut req).map_err(Error::from)),
                RequestBody::Empty => req.body(Body::empty()).map_err(Error::from),
            };

            req.into_future()
                .and_then(move |req| instance.client.request(req).map_err(Error::from))
        });

        let instance2 = self.clone();
        Box::new(response.and_then(move |response| {
            let remaining = response
                .headers()
                .get(X_RATELIMIT_REMAINING)
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.parse::<u64>().ok());
            let reset = response
                .headers()
                .get(X_RATELIMIT_RETRY_AFTER)
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.parse::<u64>().ok());

            let status = response.status();
            if StatusCode::MOVED_PERMANENTLY == status || StatusCode::TEMPORARY_REDIRECT == status {
                if let Some(location) = response.headers().get(LOCATION) {
                    let location = location.to_str().unwrap().to_owned();
                    return instance2.request(method, &location, body);
                }
            }
            Box::new(
                response
                    .into_body()
                    .concat2()
                    .map_err(Error::from)
                    .and_then(move |response_body| {
                        if status.is_success() {
                            serde_json::from_slice::<Out>(&response_body).map_err(Error::from)
                        } else {
                            let error = match (remaining, reset) {
                                (Some(remaining), Some(reset)) if remaining == 0 => {
                                    Error::RateLimit {
                                        reset: Duration::from_secs(reset as u64 * 60),
                                    }
                                }
                                _ => {
                                    let mer: ModioErrorResponse =
                                        serde_json::from_slice(&response_body)?;
                                    Error::Fault {
                                        code: status,
                                        error: mer.error,
                                    }
                                }
                            };
                            Err(error)
                        }
                    }),
            )
        }))
    }

    fn get<D>(&self, uri: &str) -> Future<D>
    where
        D: DeserializeOwned + 'static + Send,
    {
        self.request(Method::GET, &(self.host.clone() + uri), RequestBody::Empty)
    }

    fn post<D, M>(&self, uri: &str, message: M) -> Future<D>
    where
        D: DeserializeOwned + 'static + Send,
        M: Into<Vec<u8>>,
    {
        self.request(
            Method::POST,
            &(self.host.clone() + uri),
            RequestBody::Vec(message.into(), mime::APPLICATION_WWW_FORM_URLENCODED),
        )
    }

    fn post_form<F, D>(&self, uri: &str, data: F) -> Future<D>
    where
        D: DeserializeOwned + 'static + Send,
        F: MultipartForm + Clone + 'static,
    {
        self.request(
            Method::POST,
            &(self.host.clone() + uri),
            RequestBody::Form(Box::new(data)),
        )
    }

    fn put<D, M>(&self, uri: &str, message: M) -> Future<D>
    where
        D: DeserializeOwned + 'static + Send,
        M: Into<Vec<u8>>,
    {
        self.request(
            Method::PUT,
            &(self.host.clone() + uri),
            RequestBody::Vec(message.into(), mime::APPLICATION_WWW_FORM_URLENCODED),
        )
    }

    fn delete<M>(&self, uri: &str, message: M) -> Future<()>
    where
        M: Into<Vec<u8>>,
    {
        Box::new(
            self.request(
                Method::DELETE,
                &(self.host.clone() + uri),
                RequestBody::Vec(message.into(), mime::APPLICATION_WWW_FORM_URLENCODED),
            ).or_else(|err| match err {
                error::Error::Codec(_) => Ok(()),
                otherwise => Err(otherwise),
            }),
        )
    }
}

#[derive(Clone)]
enum RequestBody {
    Empty,
    Vec(Vec<u8>, Mime),
    Form(Box<MultipartForm>),
}

/// Generic endpoint for sub-resources
pub struct Endpoint<C, Out>
where
    C: Clone + Connect + 'static,
    Out: DeserializeOwned + 'static,
{
    modio: Modio<C>,
    path: String,
    phantom: PhantomData<Out>,
}

impl<C, Out> Endpoint<C, Out>
where
    C: Clone + Connect,
    Out: DeserializeOwned + 'static + Send,
{
    pub(crate) fn new(modio: Modio<C>, path: String) -> Endpoint<C, Out> {
        Self {
            modio,
            path,
            phantom: PhantomData,
        }
    }

    pub fn list(&self) -> Future<ModioListResponse<Out>> {
        self.modio.get(&self.path)
    }

    pub fn add<T: AddOptions + QueryParams>(&self, options: &T) -> Future<ModioMessage> {
        let params = options.to_query_params();
        self.modio.post(&self.path, params)
    }

    pub fn delete<T: DeleteOptions + QueryParams>(&self, options: &T) -> Future<()> {
        let params = options.to_query_params();
        self.modio.delete(&self.path, params)
    }
}

filter_options!{
    /// Options used to filter event listings.
    ///
    /// # Filter parameters
    /// - id
    /// - mod_id
    /// - user_id
    /// - date_added
    /// - event_type
    ///
    /// # Sorting
    /// - id
    ///
    /// See the [modio docs](https://docs.mod.io/#events) for more informations.
    ///
    /// By default this returns up to `100` items. You can limit the result using `limit` and
    /// `offset`.
    /// # Example
    /// ```
    /// use modio::filter::{Order, Operator};
    /// use modio::EventListOptions;
    /// use modio::EventType;
    ///
    /// let mut opts = EventListOptions::new();
    /// opts.id(Operator::GreaterThan, 1024);
    /// opts.event_type(Operator::Equals, EventType::ModfileChanged);
    /// ```
    #[derive(Debug)]
    pub struct EventListOptions {
        Filters
        - id = "id";
        - mod_id = "mod_id";
        - user_id = "user_id";
        - date_added = "date_added";
        - event_type = "event_type";

        Sort
        - ID = "id";
    }
}

trait MultipartForm: MultipartFormClone + Send {
    fn to_form(&self) -> Result<multipart::Form, error::Error>;
}

trait MultipartFormClone {
    fn clone_box(&self) -> Box<MultipartForm>;
}

impl<T> MultipartFormClone for T
where
    T: 'static + MultipartForm + Clone,
{
    fn clone_box(&self) -> Box<MultipartForm> {
        Box::new(self.clone())
    }
}

impl Clone for Box<MultipartForm> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

pub trait AddOptions {}
pub trait DeleteOptions {}

pub trait QueryParams {
    fn to_query_params(&self) -> String;
}