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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
mod rate_limit;
mod routing;

use rate_limit::RateLimit;
use routing::Route;

use crate::{
    error::{PandaError, Result},
    models::{
        channel::{Channel, Embed, Message},
        user::User,
    },
};

use isahc::{
    http::{Method, StatusCode},
    prelude::*,
    HttpClient as IsachClient,
};
use serde::Serialize;

pub struct HttpClient {
    token: String,
    client: IsachClient,
    rate_limit: RateLimit,
}

impl HttpClient {
    /// Creates a new http client
    pub fn new(token: impl Into<String>) -> HttpClient {
        let client = IsachClient::new().expect("Can't create Http Client");
        HttpClient {
            token: token.into(),
            client,
            rate_limit: RateLimit::default(),
        }
    }

    async fn _make_request<B: Into<Body>>(&self, route: Route<B>) -> Result<Response<Body>> {
        // Check and wait if we reach the limit
        self.rate_limit.check_and_sleep(&route.bucket_key).await;

        let response = match route.method {
            Method::GET | Method::PUT | Method::DELETE => {
                let request = Request::builder()
                    .method(route.method)
                    .uri(&route.uri)
                    .header("Authorization", &self.token)
                    .body(())
                    .unwrap();

                // Get response
                // TODO: ERROR WRAPPER
                self.client
                    .send_async(request)
                    .await
                    .map_err(|_| PandaError::HttpNoResponse)?
            }
            Method::POST | Method::PATCH => {
                let request = Request::builder()
                    .method(route.method)
                    .uri(&route.uri)
                    .header("Authorization", &self.token)
                    .header("Content-Type", "application/json")
                    .body(route.body)
                    .unwrap();

                // Get response
                // TODO: ERROR WRAPPER
                self.client
                    .send_async(request)
                    .await
                    .map_err(|_| PandaError::HttpNoResponse)?
            }
            _ => unimplemented!(),
        };

        // Update the limit with the response headers
        self.rate_limit.update(route.bucket_key, &response).await;

        Ok(response)
    }

    // TODO: Rename this and improve
    fn _catch_http_errors(&self, res: &Response<Body>) -> Result<()> {
        let err = match res.status() {
            StatusCode::OK
            | StatusCode::CREATED
            | StatusCode::NO_CONTENT
            | StatusCode::NOT_MODIFIED
            | StatusCode::TOO_MANY_REQUESTS => return Ok(()),

            StatusCode::BAD_REQUEST => PandaError::HttpImproperlyFormatted,
            StatusCode::FORBIDDEN => PandaError::HttpForbidden, // no autorizado
            StatusCode::NOT_FOUND => PandaError::HttpInvalidParameters, // not found or bad format
            StatusCode::METHOD_NOT_ALLOWED => PandaError::HttpNoResponse, // method not allowed
            // HANDLED BY RATELIMIT StatusCode::TOO_MANY_REQUESTS => PandaError::HttpNoResponse,
            StatusCode::BAD_GATEWAY => PandaError::HttpNoResponse, // gateway unavailable
            _ => PandaError::HttpNoResponse,
        };

        Err(err)

        //TODO: Remove HttpNoResponse here
    }

    // *******************************************************************************
    // * HTTP METHODS
    // *******************************************************************************

    /// Get a channel by ID. Returns a [`Channel`] object, it will fail if the ID it's invalid
    ///
    /// [`Channel`]: ../../panda/models/channel/struct.Channel.html
    pub async fn get_channel(&self, channel_id: impl AsRef<str>) -> Result<Channel> {
        // Create Route
        let route = Route::<()>::get_channel(channel_id);
        let mut res = self._make_request(route).await?;

        Ok(res.json()?)
    }

    /// Update a channel's settings. Requires the **MANAGE_CHANNELS** permission for the guild.
    /// Returns a [`Channel`] on success. It's recommended to use [`MessageEdit`] builder.
    /// Fires a [`ChannelUpdate`] event.
    ///
    /// [`Channel`]: ../../panda/models/channel/struct.Channel.html
    /// [`MessageEdit`]: ../../panda/utils/builder/struct.MessageEdit.html
    /// [`ChannelUpdate`]: ../../panda/models/gateway/events/struct.ChannelUpdate.html
    pub async fn edit_channel(&self, channel_id: impl AsRef<str>, body: impl Serialize) -> Result<Channel> {
        // Create route
        let body = serde_json::to_string(&body)?;
        let route = Route::<String>::edit_channel(channel_id, body);

        let mut res = self._make_request(route).await?;

        // If an error wasn't returned, it's safe to unwrap
        Ok(res.json()?)
    }

    /// Delete a channel, or close a private message. Requires the **MANAGE_CHANNELS** permission
    /// for the guild. Returns a [`Channel`] on success.
    /// Fires a [`ChannelDelete`] event.
    ///
    /// [`Channel`]: ../../panda/models/channel/struct.Channel.html
    /// [`ChannelDelete`]: ../../panda/models/gateway/events/struct.ChannelDelete.html
    pub async fn delete_channel(&self, channel_id: impl AsRef<str>) -> Result<Channel> {
        // Parse URL
        let route = Route::<()>::delete_channel(channel_id);

        let mut res = self._make_request(route).await?;

        Ok(res.json()?)
    }

    /// Returns a Vec<[`Message`]> of a channel. If operating on a guild channel, this endpoint
    /// requires the **VIEW_CHANNEL** permission to be present on the current user.
    ///
    /// [`Channel`]: ../../panda/models/channel/struct.Channel.html
    pub async fn get_messages_around(
        &self,
        channel_id: impl AsRef<str>,
        message_id: impl AsRef<str>,
        limit: u8,
    ) -> Result<Vec<Message>> {
        // Create route
        let route = Route::<()>::get_channel_messages("around", channel_id, message_id, limit);

        let mut res = self._make_request(route).await?;

        Ok(res.json()?)
    }

    /// Returns a Vec<[`Message`]> of a channel. If operating on a guild channel, this endpoint
    /// requires the **VIEW_CHANNEL** permission to be present on the current user.
    ///
    /// [`Channel`]: ../../panda/models/channel/struct.Channel.html
    pub async fn get_messages_before(
        &self,
        channel_id: impl AsRef<str>,
        message_id: impl AsRef<str>,
        limit: u8,
    ) -> Result<Vec<Message>> {
        // Create route
        let route = Route::<()>::get_channel_messages("before", channel_id, message_id, limit);

        let mut res = self._make_request(route).await?;

        Ok(res.json()?)
    }

    /// Returns a Vec<[`Message`]> of a channel. If operating on a guild channel, this endpoint
    /// requires the **VIEW_CHANNEL** permission to be present on the current user.
    ///
    /// [`Channel`]: ../../panda/models/channel/struct.Channel.html
    pub async fn get_messages_after(
        &self,
        channel_id: impl AsRef<str>,
        message_id: impl AsRef<str>,
        limit: u8,
    ) -> Result<Vec<Message>> {
        // Create route
        let route = Route::<()>::get_channel_messages("after", channel_id, message_id, limit);

        let mut res = self._make_request(route).await?;

        Ok(res.json()?)
    }

    /// Returns a specific [`Message`] in the channel. If operating on a guild channel, this endpoint
    /// requires the **READ_MESSAGE_HISTORY** permission to be present on the current user.
    ///
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    pub async fn get_message(&self, channel_id: impl AsRef<str>, msg_id: impl AsRef<str>) -> Result<Message> {
        // Create route
        let route = Route::<()>::get_channel_message(channel_id, msg_id);

        let mut res = self._make_request(route).await?;

        Ok(res.json()?)
    }

    /// Creates a new message, and returns the [`Message`]. This will also trigger
    /// [`MessageCreate`] event
    ///
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    /// [`MessageCreate`]: ../../panda/models/gateway/events/struct.MessageCreate.html
    pub async fn send_message(&self, channel_id: impl AsRef<str>, content: impl AsRef<str>) -> Result<Message> {
        // Create message body
        let body = serde_json::json!({
            "content": content.as_ref(),
            "tts": false
        });
        // Parse to a valid Body, isahc::Body
        let body = serde_json::to_string(&body)?;

        // Create route
        let route = Route::<String>::create_message(channel_id, body);
        let mut res = self._make_request(route).await?;

        Ok(res.json()?)
    }

    /// Creates a new message, and returns the [`Message`]. This will also trigger
    /// [`MessageCreate`] event
    ///
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    /// [`MessageCreate`]: ../../panda/models/gateway/events/struct.MessageCreate.html
    pub async fn send_embed(&self, channel_id: impl AsRef<str>, embed: Embed) -> Result<Message> {
        let body = serde_json::json!({
            "embed": embed,
            "tts": false
        });

        let body = serde_json::to_string(&body)?;

        // Create route
        let route = Route::<String>::create_message(channel_id, body);

        let mut res = self._make_request(route).await?;

        Ok(res.json()?)
    }

    /// Add a reaction to a [`Message`], it needs the [`Channel`] ID, and [`Message`] ID
    ///
    /// [`Channel`]: ../../panda/models/channel/struct.channel.html
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    pub async fn add_reaction(
        &self,
        channel_id: impl AsRef<str>,
        message_id: impl AsRef<str>,
        emoji: impl AsRef<str>,
    ) -> Result<()> {
        // Create route
        let route = Route::<()>::create_reaction(channel_id, message_id, emoji);

        let _res = self._make_request(route).await?;

        Ok(())
    }

    /// Remove a own reaction to a [`Message`], it needs the [`Channel`] ID, and [`Message`] ID
    ///
    /// [`Channel`]: ../../panda/models/channel/struct.channel.html
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    pub async fn remove_own_reaction(
        &self,
        channel_id: impl AsRef<str>,
        message_id: impl AsRef<str>,
        emoji: impl AsRef<str>,
    ) -> Result<()> {
        // Create route
        let route = Route::<()>::delete_own_reaction(channel_id, message_id, emoji);

        let _res = self._make_request(route).await?;

        Ok(())
    }

    /// Remove an [`User`] reaction to a [`Message`], it needs the [`Channel`] ID, [`Message`] ID
    /// and [`User`] ID.
    ///
    /// [`Channel`]: ../../panda/models/channel/struct.channel.html
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    /// [`User`]: ../../panda/models/user/struct.User.html
    pub async fn remove_user_reaction(
        &self,
        channel_id: impl AsRef<str>,
        message_id: impl AsRef<str>,
        user_id: impl AsRef<str>,
        emoji: impl AsRef<str>,
    ) -> Result<()> {
        // Create route
        let route = Route::<()>::delete_user_reaction(channel_id, message_id, emoji, user_id);

        let _res = self._make_request(route).await?;

        Ok(())
    }

    /// Get all [`User`]s that reacted with given emoji to a [`Message`],
    /// it needs the [`Channel`] ID, [`Message`] ID
    ///
    /// [`Channel`]: ../../panda/models/channel/struct.channel.html
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    /// [`User`]: ../../panda/models/user/struct.User.html
    pub async fn get_reactions(
        &self,
        channel_id: impl AsRef<str>,
        message_id: impl AsRef<str>,
        emoji: impl AsRef<str>,
    ) -> Result<Vec<User>> {
        let route = Route::<()>::get_reactions(channel_id, message_id, emoji);

        let mut res = self._make_request(route).await?;

        Ok(res.json()?)
    }

    /// Deletes all reactions on a [`Message`]. This endpoint requires the **MANAGE_MESSAGES**
    /// permission to be present on the current user. Fires a [`MessageReactionRemoveAll`].
    ///
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    /// [`MessageReactionRemoveAll`]: ../../panda/models/gateway/events/struct.MessageReactionRemoveAll.html
    pub async fn remove_all_reactions(&self, channel_id: impl AsRef<str>, message_id: impl AsRef<str>) -> Result<()> {
        let route = Route::<()>::delete_all_reactions(channel_id, message_id);

        let _res = self._make_request(route).await?;

        Ok(())
    }

    /// Deletes all reactions on a [`Message`]. This endpoint requires the **MANAGE_MESSAGES**
    /// permission to be present on the current user. Fires a [`MessageReactionRemoveEmoji`].
    ///
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    /// [`MessageReactionRemoveEmoji`]: ../../panda/models/gateway/events/struct.MessageReactionRemoveEmoji.html
    pub async fn remove_all_emoji_reactions(
        &self,
        channel_id: impl AsRef<str>,
        message_id: impl AsRef<str>,
        emoji: impl AsRef<str>,
    ) -> Result<()> {
        let route = Route::<()>::delete_all_reactions_for_emoji(channel_id, message_id, emoji);

        let _res = self._make_request(route).await?;

        Ok(())
    }

    /// Edits message, and returns the [`Message`]. This will also trigger [`MessageUpdate`] event
    ///
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    /// [`MessageUpdate`]: ../../panda/models/gateway/events/struct.MessageUpdate.html
    pub async fn edit_message(
        &self,
        channel_id: impl AsRef<str>,
        message_id: impl AsRef<str>,
        body: impl Serialize,
    ) -> Result<Message> {
        let body = serde_json::to_string(&body)?;

        let route = Route::<String>::edit_message(channel_id, message_id, body);

        let mut res = self._make_request(route).await?;

        Ok(res.json()?)
    }

    /// Delete a [`Message`], This will also trigger [`MessageDelete`] event
    ///
    /// [`Message`]: ../../panda/models/channel/struct.Message.html
    /// [`MessageDelete`]: ../../panda/models/gateway/events/struct.MessageDelete.html
    pub async fn delete_message(&self, channel_id: impl AsRef<str>, message_id: impl AsRef<str>) -> Result<()> {
        let route = Route::<()>::delete_message(channel_id, message_id);

        let _res = self._make_request(route).await?;

        Ok(())
    }

    // /// Delete a a bulk of [`Message`] (2 - 100), This will also trigger [`MessageDeleteBulk`] event.
    // ///
    // /// [`Message`]: ../../panda/models/channel/struct.Message.html
    // /// [`MessageDelete`]: ../../panda/models/gateway/events/struct.MessageDelete.html
    // pub async fn delete_many_messages(&self, channel_id: impl AsRef<str>, messages: &[&str]) -> Result<()> {
    //     // Parse URL
    //     let uri = format!("{}/channels/{}/messages/bulk-delete", DISCORD_URL, channel_id.as_ref(),);

    //     let body = serde_json::json!({ "messages": messages });
    //     let msg = serde_json::to_string(&body).unwrap();

    //     // Create RateLimit Key
    //     let rt_key = format!("channels:{}", channel_id.as_ref());

    //     let _res = self._make_request(uri, rt_key, msg).await?;

    //     Ok(())
    // }

    // /// Edit the channel permission overwrites for a user or role in a channel. Only usable
    // /// for guild channels. Requires the **MANAGE_ROLES** permission.
    // ///
    // /// [`Message`]: ../../panda/models/channel/struct.Message.html
    // /// [`MessageDelete`]: ../../panda/models/gateway/events/struct.MessageDelete.html
    // pub async fn edit_channel_permissions(&self, _channel_id: impl AsRef<str>) -> Result<()> {
    //     unimplemented!();

    //     // // Parse URL
    //     // let uri = format!("{}/channels/{}/permissions/{}", DISCORD_URL, channel_id.as_ref(), "");

    //     // // Create RateLimit Key
    //     // let rt_key = format!("channels:{}", channel_id.as_ref());

    //     // let _res = self._make_request(uri, rt_key).await?;

    //     // Ok(())
    // }

    // // pub async fn get_channel_invites() {}
    // // pub async fn create_channel_invite() {}

    // // pub async fn delete_channel_permissions() {}

    // /// Post a typing indicator for the specified channel.
    // /// Fires a [`TypingStart`] Gateway event
    // ///
    // /// [`TypingStart`]: ../../panda/models/gateway/events/struct.TypingStart.html
    // pub async fn trigger_typing(&self, channel_id: impl AsRef<str>) -> Result<()> {
    //     // Parse URL
    //     let uri = format!("{}/channels/{}/typing", DISCORD_URL, channel_id.as_ref());

    //     // Create RateLimit Key
    //     let rt_key = format!("channels:{}", channel_id.as_ref());

    //     let _res = self._make_request(uri, rt_key, ()).await?;

    //     // If an error wasn't returned, it's safe to unwrap
    //     Ok(())
    // }

    // /// Returns all pinned messages in the channel as a Vec of [`Message`] objects.
    // ///
    // /// [`Message`]: ../../panda/models/channel/struct.Message.html
    // pub async fn get_pinned_messages(&self, channel_id: impl AsRef<str>) -> Result<Vec<Message>> {
    //     // Parse URL
    //     let uri = format!("{}/channels/{}/pins", DISCORD_URL, channel_id.as_ref());

    //     // Create RateLimit Key
    //     let rt_key = format!("channels:{}", channel_id.as_ref());

    //     let mut res = self._make_request(uri, rt_key).await?;

    //     // If an error wasn't returned, it's safe to unwrap
    //     Ok(res.json().unwrap())
    // }

    // /// Pin a message in a channel. Requires the **MANAGE_MESSAGES** permission
    // pub async fn pin_message(&self, channel_id: impl AsRef<str>, message_id: impl AsRef<str>) -> Result<()> {
    //     // Parse URL
    //     let uri = format!(
    //         "{}/channels/{}/pins/{}",
    //         DISCORD_URL,
    //         channel_id.as_ref(),
    //         message_id.as_ref()
    //     );

    //     // Create RateLimit Key
    //     let rt_key = format!("channels:{}", channel_id.as_ref());

    //     let _res = self.__make_request(uri, rt_key).await?;

    //     // If an error wasn't returned, it's safe to unwrap
    //     Ok(())
    // }

    // /// Pin a message in a channel. Requires the **MANAGE_MESSAGES** permission.
    // pub async fn unpin_message(&self, channel_id: impl AsRef<str>, message_id: impl AsRef<str>) -> Result<()> {
    //     // Parse URL
    //     let uri = format!(
    //         "{}/channels/{}/pins/{}",
    //         DISCORD_URL,
    //         channel_id.as_ref(),
    //         message_id.as_ref()
    //     );

    //     // Create RateLimit Key
    //     let rt_key = format!("channels:{}", channel_id.as_ref());

    //     let _res = self.___make_request(uri, rt_key).await?;

    //     // If an error wasn't returned, it's safe to unwrap
    //     Ok(())
    // }

    // PUT/channels/{channel.id}/recipients/{user.id}

    // DELETE/channels/{channel.id}/recipients/{user.id}
}