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
//! # Spectacles REST
//! Spectacles REST offers a simple, easy-to-use client for making HTTP requests to the Discord API.
//! All HTTP requests are made asynchronously and never block the thread, with the help of the Tokio runtime.
//!
//! ## Creating a Client
//! A [`RestClient`], resoponsible for performing all requests, can be easily constructed with the `new` function.
//! ```rust
//! use spectacles_rest::RestClient;
//! let token = std::env::var("DISCORD_TOKEN").expect("Failed to parse token");
//! let rest = RestClient::new(token, true);
//! ```
//! The client accepts a boolean as a second parameter, which determines whether or not the internal rate limiter will be used on each request.
//!
//! ## Views
//! The Client ships with three views for specific endpoints of the Discord API.
//!
//! The [`ChannelView`] provides a set of methods for interacting with a Discord channel.
//!
//! The [`GuildView`] provides a set of methods for interacting with a Discord guild, or "server".
//!
//! The [`WebhookView`] provides a set of methods for interacting with Discord webhooks.
//!
//! [`ChannelView`]: struct.ChannelView.html
//! [`GuildView`]: struct.GuildView.html
//! [`WebhookView`]: struct.WebhookView.html
//! [`RestClient`]: struct.RestClient.html
//!
//! Here is a brief example of sending a message to a Discord channel using the ChannelView.
//! ```rust, norun
//! use tokio::prelude::*;
//! use spectacles_rest::RestClient;
//! use spectacles_model::Snowflake;
//!
//! fn main() {
//!     // Initialize the Rest Client, with a token.
//!     let rest = RestClient::new(token, true);
//!     tokio::run(rest.channel(&Snowflake(CHANNEL_ID_HERE)).create_message("Hello World")
//!         .map(|message| println!("Message Sent: {:?}", message))
//!         .map_err(|err| {
//!             eprintln!("Error whilst attempting to send message. {:?}", err);
//!         })
//!     );
//! }
//! ```
//! ## Rate Limiting
//! As mentioned earlier, the library includes an in-memory rate limiter bucket system for preemptively managing Discord Ratelimits.
//! This is sufficient if you do not plan on accessing the Discord API from a single server.
//! If you plan to make requests in a distributed fashion, you will need to make use of an external state for keeping track of rate limits.
//!
//! The library currently supports using a custom Discord proxy, featured in the Spectacles client, to be used as a central hub for handling requests.
//! ```rust
//! use spectacles_rest::RestClient;
//! let proxy = std::env::var("PROXY").expect("Failed to parse proxy URL.");
//! let rest = RestClient::new(token, false) // false tells the client to skip the default in memory rate limiter.
//!     .set_proxy(proxy);
//!
//! ```
//! More rate limiting strategies will be considered in future.
//!
//!
//! ## Installation
//! Simply add the package to your Cargo.toml file.
//! ```toml
//! [dependencies]
//! spectacles-rest = "0.1.0"
//!

#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
#[warn(rust_2018_idioms)]
#[macro_use]
extern crate serde_json;

use std::sync::Arc;

use futures::future::{Future, Loop};
use http::header::HeaderValue;
use parking_lot::Mutex;
use reqwest::header::HeaderMap;
use reqwest::Method;
use reqwest::r#async::{
    Client as ReqwestClient,
    ClientBuilder,
    multipart::Form,
};
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use serde_json::Value;

pub(crate) use ratelimit::*;
use spectacles_model::channel::Channel;
use spectacles_model::guild::{CreateGuildOptions, Guild};
use spectacles_model::invite::Invite;
use spectacles_model::snowflake::Snowflake;
use spectacles_model::User;
use spectacles_model::voice::VoiceRegion;
/// A collection of interfaces for endpoint-specific Discord objects.
pub use views::*;

pub use crate::errors::{Error, Result};

mod errors;
mod ratelimit;
mod views;
mod constants;

/// The Main client which is used to interface with the various components of the Discord API.
#[derive(Clone, Debug)]
pub struct RestClient {
    /// The bot token for this user.
    pub token: String,
    /// The base URL of the client. This may be changed to accomodate an external proxy system.
    pub base_url: String,
    pub http: ReqwestClient,
    ratelimiter: Option<Arc<Mutex<Ratelimter>>>,
}

impl RestClient {
    /// Creates a new REST client with the provided configuration.
    /// The second argument denotes whether or not to use the built-in rate limiter to rate limit requests to the Discord API.
    /// If you plan to use a distributed architecture, you will need an external ratelimiter to ensure ratelimis are kept across servers.
    pub fn new(token: String, using_ratelimiter: bool) -> Self {
        let token = if token.starts_with("Bot ") {
            token
        } else {
            format!("Bot {}", token)
        };
        let mut headers = HeaderMap::new();
        let value = HeaderValue::from_str(&token).unwrap();
        let agent = HeaderValue::from_str(
            "DiscordBot (https://github.com/spec-tacles/spectacles-rs, v1.0.0)"
        ).unwrap();
        headers.insert("Authorization", value);
        headers.insert("User-Agent", agent);

        let client = ClientBuilder::new().default_headers(headers).build()
            .expect("Failed to build HTTP client");

        let mut rest = RestClient {
            token,
            http: client.clone(),
            base_url: constants::BASE_URL.to_string(),
            ratelimiter: None,
        };

        if using_ratelimiter {
            rest.ratelimiter = Some(Arc::new(Mutex::new(Ratelimter::new(client))));
        };

        rest
    }

    /// Enables support for routing all requests though an HTTP rate limiting proxy.
    /// If you plan on making distributed REST requests, an HTTP proxy is recommended for handling rate limits in a distributed manner.
    pub fn set_proxy(mut self, url: String) -> Self {
        self.base_url = url;
        self
    }

    /// Opens a ChannelView for the provided Channel snowflake.
    pub fn channel(&self, id: &Snowflake) -> ChannelView {
        ChannelView::new(id.0, self.clone())
    }

    /// Opens a GuildView for the provided Guild snowflake.
    pub fn guild(&self, id: &Snowflake) -> GuildView {
        GuildView::new(id.0, self.clone())
    }

    /// Opens a WebhookView for the provided Webhook snowflake.
    pub fn webhook(&self, id: &Snowflake) -> WebhookView {
        WebhookView::new(id.0, self.clone())
    }

    /// Gets a User object for the provided snowflake.
    pub fn get_user(&self, id: &Snowflake) -> impl Future<Item=User, Error=Error> {
        self.request(Endpoint::new(
            Method::GET,
            format!("/users/{}", id.0),
        ))
    }

    /// Opens a new DM channel with the user at the provided user ID.
    pub fn create_dm(&self, user: &Snowflake) -> impl Future<Item=Channel, Error=Error> {
        let json = json!({
            "recipient_id": user.0
        });

        self.request(Endpoint::new(
            Method::POST,
            String::from("/users/@me/channels"),
        ).json(json))
    }

    /// Creates a new guild, setting the current client user as owner.
    /// This endpoint may only be used for bots who are in less than 10 guilds.
    pub fn create_guild(&self, opts: CreateGuildOptions) -> impl Future<Item=Guild, Error=Error> {
        self.request(Endpoint::new(
            Method::POST,
            String::from("/guilds"),
        ).json(opts))
    }

    /// Leaves the guild using the provided guild ID.
    pub fn leave_guild(&self, id: &Snowflake) -> impl Future<Item=(), Error=Error> {
        self.request_empty(Endpoint::new(
            Method::DELETE,
            format!("/users/@me/guilds/{}", id.0),
        ))
    }


    /// Modifies properties for the current user.
    /*pub fn modify_current_user(&self) -> impl Future<Item = User, Error = Error> {
        self.client.request(Endpoint::new(
            Method::PATCH,
            String::from("/users/@me)",
        ))
    }*/

    /// Obtains a list of Discord voice regions.
    pub fn get_voice_regions(&self) -> impl Future<Item=Vec<VoiceRegion>, Error=Error> {
        self.request(Endpoint::new(
            Method::GET,
            String::from("/voice/regions"),
        ))
    }

    /// Obtains an invite object from Discord using the given code.
    /// The second argument denotes whether the invite should contain approximate member counts
    pub fn get_invite(&self, code: &str, member_counts: bool) -> impl Future<Item=Invite, Error=Error> {
        self.request(Endpoint::new(
            Method::GET,
            format!("/invites/{}?with_counts={}", code, member_counts),
        ))
    }

    /// Deletes this invite from the its parent channel.
    /// This requires that the client have the `MANAGE_CHANNELS` permission.
    pub fn delete_invite(&self, code: &str) -> impl Future<Item=Invite, Error=Error> {
        self.request(Endpoint::new(
            Method::GET,
            format!("/invites/{}", code),
        ))
    }

    /// Makes an HTTP request to the provided Discord API endpoint.
    /// Depending on the ratelimiter status, the request may or may not be rate limited.
    pub fn request<T>(&self, mut endpt: Endpoint) -> Box<Future<Item=T, Error=Error> + Send>
        where T: DeserializeOwned + Send + 'static
    {
        if let Some(ref rl) = self.ratelimiter {
            let http = self.http.clone();
            let base = self.base_url.clone();
            Box::new(futures::future::loop_fn(Arc::clone(rl), move |ratelimit| {
                let req_url = format!("{}{}", base, &endpt.url);
                let route = Bucket::make_route(endpt.method.clone(), req_url.clone());
                let mut req = http.request(endpt.method.clone(), &req_url)
                    .query(&endpt.query)
                    .json(&endpt.json);
                if endpt.multipart.is_some() {
                    let form = endpt.multipart.take().unwrap();
                    req = req.multipart(form);
                };
                let limiter = Arc::clone(&ratelimit);
                let limiter_2 = Arc::clone(&limiter);
                ratelimit.lock().enqueue(route.clone())
                    .and_then(|_| req.send().from_err())
                    .and_then(move |resp| limiter.lock().handle_resp(route, resp))
                    .map(move |status| match status {
                        ResponseStatus::Success(resp) => Loop::Break(resp),
                        ResponseStatus::Ratelimited | ResponseStatus::ServerError => Loop::Continue(limiter_2)
                    })
            }).and_then(|mut resp| resp.json().from_err()))
        } else {
            let req_url = format!("{}{}", self.base_url, &endpt.url);
            let req = self.http.request(endpt.method.clone(), &req_url)
                .query(&endpt.query)
                .json(&endpt.json);
            Box::new(req.send().map_err(Error::from)
                .and_then(|mut resp| resp.json().from_err())
            )
        }
    }

    /// Similar to the above method, but does not attempt to deserialize a JSON payload from the request.
    /// Use this method if you are dealing with routes that return 204 (No content).
    pub fn request_empty(&self, mut endpt: Endpoint) -> Box<Future<Item=(), Error=Error> + Send> {
        if let Some(ref rl) = self.ratelimiter {
            let http = self.http.clone();
            let base = self.base_url.clone();
            Box::new(futures::future::loop_fn(Arc::clone(rl), move |ratelimit| {
                let req_url = format!("{}{}", base, &endpt.url);
                let route = Bucket::make_route(endpt.method.clone(), req_url.clone());
                let mut req = http.request(endpt.method.clone(), &req_url)
                    .query(&endpt.query)
                    .json(&endpt.json);
                if endpt.multipart.is_some() {
                    let form = endpt.multipart.take().unwrap();
                    req = req.multipart(form);
                };
                let limiter = Arc::clone(&ratelimit);
                let limiter_2 = Arc::clone(&limiter);
                ratelimit.lock().enqueue(route.clone())
                    .and_then(|_| req.send().from_err())
                    .and_then(move |resp| limiter.lock().handle_resp(route, resp))
                    .map(move |status| match status {
                        ResponseStatus::Success(resp) => Loop::Break(resp),
                        ResponseStatus::Ratelimited | ResponseStatus::ServerError => Loop::Continue(limiter_2)
                    })
            }).map(|_| ()))
        } else {
            let req_url = format!("{}{}", self.base_url, &endpt.url);
            let req = self.http.request(endpt.method.clone(), &req_url)
                .query(&endpt.query)
                .json(&endpt.json);
            Box::new(req.send().map_err(Error::from)
                .map(|_| ())
            )
        }
    }
}

/// A structure representing a Discord API endpoint, in the context of an HTTP request.
#[derive(Debug)]
pub struct Endpoint {
    url: String,
    method: Method,
    json: Option<Value>,
    query: Option<Value>,
    multipart: Option<Form>,
}

impl Endpoint {
    /// Creates a new endpoint from the following HTTP method and URL string.
    pub fn new(method: Method, url: String) -> Self {
        Self {
            method,
            url,
            json: None,
            query: None,
            multipart: None,
        }
    }

    /// Adds a json body to the request.
    pub fn json<T: Serialize>(mut self, payload: T) -> Endpoint {
        match serde_json::to_value(payload) {
            Ok(val) => self.json = Some(val),
            Err(_) => self.json = None
        };

        self
    }

    /// Adds a query parameter to the endpoint.
    pub fn query<T: Serialize>(mut self, payload: T) -> Endpoint {
        match serde_json::to_value(payload) {
            Ok(val) => self.query = Some(val),
            Err(_) => self.query = None
        };

        self
    }

    /// Adds a multipart form to the endpoint, which is useful for sending files to the Discord API.
    pub fn multipart(mut self, payload: Form) -> Endpoint {
        self.multipart = Some(payload);
        self
    }
}