-
Notifications
You must be signed in to change notification settings - Fork 94
/
model.rs
2296 lines (2112 loc) · 76 KB
/
model.rs
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Struct and enum definitions of values in the Discord model.
#![allow(missing_docs)]
use super::{Error, Result};
use serde_json::Value;
use std::collections::BTreeMap;
use std::fmt;
use std::borrow::Cow;
pub use self::permissions::Permissions;
macro_rules! req {
($opt:expr) => {
try!($opt.ok_or(Error::Decode(concat!("Type mismatch in model:", line!(), ": ", stringify!($opt)), Value::Null)))
}
}
macro_rules! warn_json {
(@ $name:expr, $json:ident, $value:expr) => {
(Ok($value), warn_field($name, $json)).0
};
($json:ident, $ty:ident $(::$ext:ident)* ( $($value:expr),*$(,)* ) ) => {
(Ok($ty$(::$ext)* ( $($value),* )), warn_field(stringify!($ty$(::$ext)*), $json)).0
};
($json:ident, $ty:ident $(::$ext:ident)* { $($name:ident: $value:expr),*$(,)* } ) => {
(Ok($ty$(::$ext)* { $($name: $value),* }), warn_field(stringify!($ty$(::$ext)*), $json)).0
};
}
macro_rules! map_names {
($typ:ident; $($entry:ident, $value:expr;)*) => {
impl $typ {
pub fn name(&self) -> &'static str {
match *self {
$($typ::$entry => $value,)*
}
}
pub fn from_str(name: &str) -> Option<Self> {
match name {
$($value => Some($typ::$entry),)*
_ => None,
}
}
#[allow(dead_code)]
fn decode_str(value: Value) -> Result<Self> {
let name = try!(into_string(value));
Self::from_str(&name).ok_or(Error::Decode(
concat!("Expected valid ", stringify!($typ)),
Value::String(name)
))
}
}
}
}
macro_rules! map_numbers {
($typ:ident; $($entry:ident, $value:expr;)*) => {
impl $typ {
pub fn num(&self) -> u64 {
match *self {
$($typ::$entry => $value,)*
}
}
pub fn from_num(num: u64) -> Option<Self> {
match num {
$($value => Some($typ::$entry),)*
_ => None,
}
}
fn decode(value: Value) -> Result<Self> {
value.as_u64().and_then(Self::from_num).ok_or(Error::Decode(
concat!("Expected valid ", stringify!($typ)),
value
))
}
}
}
}
//=================
// Discord identifier types
fn decode_id(value: Value) -> Result<u64> {
match value {
Value::U64(num) => Ok(num),
Value::String(text) => match text.parse::<u64>() {
Ok(num) => Ok(num),
Err(_) => Err(Error::Decode("Expected numeric ID", Value::String(text)))
},
value => Err(Error::Decode("Expected numeric ID", value))
}
}
macro_rules! id {
($(#[$attr:meta] $name:ident;)*) => {
$(
#[$attr]
///
/// Identifiers can be debug-printed using the `{:?}` specifier, or their
/// raw number value printed using the `{}` specifier.
/// Some identifiers have `mention()` methods as well.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug, Ord, PartialOrd)]
pub struct $name(pub u64);
impl $name {
#[inline]
fn decode(value: Value) -> Result<Self> {
decode_id(value).map($name)
}
/// Get the creation date of the object referred to by this ID.
///
/// Discord generates identifiers using a scheme based on [Twitter Snowflake]
/// (https://github.com/twitter/snowflake/tree/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231#snowflake).
pub fn creation_date(&self) -> ::time::Timespec {
::time::Timespec::new((1420070400 + (self.0 >> 22) / 1000) as i64, 0)
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
)*
}
}
id! {
/// An identifier for a User
UserId;
/// An identifier for a Server
ServerId;
/// An identifier for a Channel
ChannelId;
/// An identifier for a Message
MessageId;
/// An identifier for a Role
RoleId;
/// An identifier for an Emoji
EmojiId;
}
/// A mention targeted at a specific user, channel, or other entity.
///
/// A mention can be constructed by calling `.mention()` on a mentionable item
/// or an ID type which refers to it, and can be formatted into a string using
/// the `format!` macro:
///
/// ```ignore
/// let message = format!("Hey, {}, ping!", user.mention());
/// ```
///
/// If a `String` is required, call `mention.to_string()`.
pub struct Mention {
prefix: &'static str,
id: u64,
}
impl fmt::Display for Mention {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str(self.prefix));
try!(fmt::Display::fmt(&self.id, f));
fmt::Write::write_char(f, '>')
}
}
impl UserId {
/// Return a `Mention` which will ping this user.
#[inline(always)]
pub fn mention(&self) -> Mention {
Mention { prefix: "<@", id: self.0 }
}
}
impl RoleId {
/// Return a `Mention` which will ping members of this role.
#[inline(always)]
pub fn mention(&self) -> Mention {
Mention { prefix: "<@&", id: self.0 }
}
}
impl ChannelId {
/// Return a `Mention` which will link to this channel.
#[inline(always)]
pub fn mention(&self) -> Mention {
Mention { prefix: "<#", id: self.0 }
}
}
#[test]
fn mention_test() {
assert_eq!(UserId(1234).mention().to_string(), "<@1234>");
assert_eq!(RoleId(1234).mention().to_string(), "<@&1234>");
assert_eq!(ChannelId(1234).mention().to_string(), "<#1234>");
}
//=================
// Rest model
/// The type of a channel
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum ChannelType {
/// A group channel, separate from a server
Group,
/// A private channel with only one other person
Private,
/// A text channel in a server
Text,
/// A voice channel
Voice,
}
map_names! { ChannelType;
Group, "group";
Private, "private";
Text, "text";
Voice, "voice";
}
map_numbers! { ChannelType;
Text, 0;
Private, 1;
Voice, 2;
Group, 3;
}
/// The basic information about a server only
#[derive(Debug, Clone)]
pub struct ServerInfo {
pub id: ServerId,
pub name: String,
pub icon: Option<String>,
pub owner: bool,
pub permissions: Permissions,
}
impl ServerInfo {
pub fn decode(value: Value) -> Result<Self> {
let mut value = try!(into_map(value));
warn_json!(value, ServerInfo {
id: try!(remove(&mut value, "id").and_then(ServerId::decode)),
name: try!(remove(&mut value, "name").and_then(into_string)),
icon: try!(opt(&mut value, "icon", into_string)),
owner: req!(try!(remove(&mut value, "owner")).as_bool()),
permissions: try!(remove(&mut value, "permissions").and_then(Permissions::decode)),
})
}
/// Returns the formatted URL of the server's icon.
///
/// Returns None if the server does not have an icon.
pub fn icon_url(&self) -> Option<String> {
self.icon.as_ref().map(|icon|
format!(cdn_concat!("/icons/{}/{}.jpg"), self.id, icon))
}
}
/// Static information about a server
#[derive(Debug, Clone)]
pub struct Server {
pub id: ServerId,
pub name: String,
pub afk_timeout: u64,
pub afk_channel_id: Option<ChannelId>,
pub icon: Option<String>,
pub roles: Vec<Role>,
pub region: String,
pub embed_enabled: bool,
pub embed_channel_id: Option<ChannelId>,
pub owner_id: UserId,
pub verification_level: VerificationLevel,
pub emojis: Vec<Emoji>,
pub features: Vec<String>,
pub splash: Option<String>,
pub default_message_notifications: u64,
pub mfa_level: u64,
}
impl Server {
pub fn decode(value: Value) -> Result<Server> {
let mut value = try!(into_map(value));
warn_json!(value, Server {
id: try!(remove(&mut value, "id").and_then(ServerId::decode)),
name: try!(remove(&mut value, "name").and_then(into_string)),
icon: try!(opt(&mut value, "icon", into_string)),
afk_timeout: req!(try!(remove(&mut value, "afk_timeout")).as_u64()),
afk_channel_id: try!(opt(&mut value, "afk_channel_id", ChannelId::decode)),
embed_enabled: req!(try!(remove(&mut value, "embed_enabled")).as_bool()),
embed_channel_id: try!(opt(&mut value, "embed_channel_id", ChannelId::decode)),
owner_id: try!(remove(&mut value, "owner_id").and_then(UserId::decode)),
region: try!(remove(&mut value, "region").and_then(into_string)),
roles: try!(decode_array(try!(remove(&mut value, "roles")), Role::decode)),
verification_level: try!(remove(&mut value, "verification_level").and_then(VerificationLevel::decode)),
emojis: try!(remove(&mut value, "emojis").and_then(|v| decode_array(v, Emoji::decode))),
features: try!(remove(&mut value, "features").and_then(|v| decode_array(v, into_string))),
splash: try!(opt(&mut value, "splash", into_string)),
default_message_notifications: req!(try!(remove(&mut value, "default_message_notifications")).as_u64()),
mfa_level: req!(try!(remove(&mut value, "mfa_level")).as_u64()),
})
}
/// Returns the formatted URL of the server's icon.
///
/// Returns None if the server does not have an icon.
pub fn icon_url(&self) -> Option<String> {
self.icon.as_ref().map(|icon|
format!(cdn_concat!("/icons/{}/{}.jpg"), self.id, icon))
}
}
/// Representation of the number of member that would be pruned by a server
/// prune operation.
#[derive(Debug, Clone)]
pub struct ServerPrune {
pub pruned: u64,
}
impl ServerPrune {
pub fn decode(value: Value) -> Result<ServerPrune> {
let mut value = try!(into_map(value));
warn_json!(value, ServerPrune {
pruned: req!(try!(remove(&mut value, "pruned")).as_u64()),
})
}
}
/// Information about a role
#[derive(Debug, Clone)]
pub struct Role {
pub id: RoleId,
pub name: String,
/// Color in `0xRRGGBB` form
pub color: u64,
pub hoist: bool,
pub managed: bool,
pub position: i64,
pub mentionable: bool,
pub permissions: Permissions,
}
impl Role {
pub fn decode(value: Value) -> Result<Role> {
let mut value = try!(into_map(value));
warn_json!(value, Role {
id: try!(remove(&mut value, "id").and_then(RoleId::decode)),
name: try!(remove(&mut value, "name").and_then(into_string)),
permissions: try!(remove(&mut value, "permissions").and_then(Permissions::decode)),
color: req!(try!(remove(&mut value, "color")).as_u64()),
hoist: req!(try!(remove(&mut value, "hoist")).as_bool()),
managed: req!(try!(remove(&mut value, "managed")).as_bool()),
position: req!(try!(remove(&mut value, "position")).as_i64()),
mentionable: try!(opt(&mut value, "mentionable", |v| Ok(req!(v.as_bool())))).unwrap_or(false),
})
}
/// Return a `Mention` which will ping members of this role.
#[inline(always)]
pub fn mention(&self) -> Mention { self.id.mention() }
}
/// A banning of a user
#[derive(Debug, Clone)]
pub struct Ban {
reason: Option<String>,
user: User,
}
impl Ban {
pub fn decode(value: Value) -> Result<Ban> {
let mut value = try!(into_map(value));
warn_json!(value, Ban {
reason: try!(opt(&mut value, "reason", into_string)),
user: try!(remove(&mut value, "user").and_then(User::decode)),
})
}
}
/// Broadly-applicable user information
#[derive(Debug, Clone)]
pub struct User {
pub id: UserId,
pub name: String,
pub discriminator: u16,
pub avatar: Option<String>,
pub bot: bool,
}
impl User {
pub fn decode(value: Value) -> Result<User> {
let mut value = try!(into_map(value));
warn_json!(value, User {
id: try!(remove(&mut value, "id").and_then(UserId::decode)),
name: try!(remove(&mut value, "username").and_then(into_string)),
discriminator: try!(remove(&mut value, "discriminator").and_then(decode_discriminator)),
avatar: try!(opt(&mut value, "avatar", into_string)),
bot: try!(opt(&mut value, "bot", |v| Ok(req!(v.as_bool())))).unwrap_or(false),
})
}
/// Return a `Mention` which will ping this user.
#[inline(always)]
pub fn mention(&self) -> Mention { self.id.mention() }
/// Returns the formatted URL of the user's icon.
///
/// Returns None if the user does not have an avatar.
pub fn avatar_url(&self) -> Option<String> {
self.avatar.as_ref().map(|av|
format!(cdn_concat!("/avatars/{}/{}.jpg"), self.id, av))
}
}
/// Information about a member of a server
#[derive(Debug, Clone)]
pub struct Member {
pub user: User,
pub roles: Vec<RoleId>,
pub nick: Option<String>,
pub joined_at: String,
pub mute: bool,
pub deaf: bool,
}
impl Member {
pub fn decode(value: Value) -> Result<Member> {
let mut value = try!(into_map(value));
warn_json!(value, Member {
user: try!(remove(&mut value, "user").and_then(User::decode)),
roles: try!(decode_array(try!(remove(&mut value, "roles")), RoleId::decode)),
nick: try!(opt(&mut value, "nick", into_string)),
joined_at: try!(remove(&mut value, "joined_at").and_then(into_string)),
mute: req!(try!(remove(&mut value, "mute")).as_bool()),
deaf: req!(try!(remove(&mut value, "deaf")).as_bool()),
})
}
pub fn display_name(&self) -> &str {
if let Some(name) = self.nick.as_ref() {
name
} else {
&self.user.name
}
}
}
/// A private or public channel
#[derive(Debug, Clone)]
pub enum Channel {
/// A group channel separate from a server
Group(Group),
/// Text channel to another user
Private(PrivateChannel),
/// Voice or text channel within a server
Public(PublicChannel),
}
impl Channel {
pub fn decode(value: Value) -> Result<Channel> {
let map = try!(into_map(value));
match req!(map.get("type").and_then(|x| x.as_u64())) {
0 |
2 => PublicChannel::decode(Value::Object(map)).map(Channel::Public),
1 => PrivateChannel::decode(Value::Object(map)).map(Channel::Private),
3 => Group::decode(Value::Object(map)).map(Channel::Group),
other => Err(Error::Decode("Expected value Channel type", Value::U64(other))),
}
}
}
/// A group channel, potentially including other users, separate from a server.
#[derive(Debug, Clone)]
pub struct Group {
pub channel_id: ChannelId,
pub icon: Option<String>,
pub last_message_id: Option<MessageId>,
pub last_pin_timestamp: Option<String>,
pub name: Option<String>,
pub owner_id: UserId,
pub recipients: Vec<User>,
}
impl Group {
pub fn decode(value: Value) -> Result<Group> {
let mut value = try!(into_map(value));
let _ = remove(&mut value, "type"); // ignore "type" field
warn_json!(value, Group {
channel_id: try!(remove(&mut value, "id").and_then(ChannelId::decode)),
icon: try!(opt(&mut value, "icon", into_string)),
last_message_id: try!(opt(&mut value, "last_message_id", MessageId::decode)),
last_pin_timestamp: try!(opt(&mut value, "last_pin_timestamp", into_string)),
name: try!(opt(&mut value, "name", into_string)),
owner_id: try!(remove(&mut value, "owner_id").and_then(UserId::decode)),
recipients: try!(opt(&mut value, "recipients", |r| decode_array(r, User::decode))).unwrap_or(Vec::new()),
})
}
/// Get this group's name, building a default if needed
pub fn name(&self) -> Cow<str> {
match self.name {
Some(ref name) => Cow::Borrowed(name),
None => {
if self.recipients.is_empty() {
return Cow::Borrowed("Empty Group");
}
let mut result = self.recipients[0].name.clone();
for user in &self.recipients[1..] {
use std::fmt::Write;
let _ = write!(result, ", {}", user.name);
}
Cow::Owned(result)
}
}
}
/// Returns the formatted URL of the group's icon.
///
/// Returns None if the group does not have an icon.
pub fn icon_url(&self) -> Option<String> {
self.icon.as_ref().map(|icon|
format!(cdn_concat!("/channel-icons/{}/{}.jpg"), self.channel_id, icon))
}
}
/// An active group or private call
#[derive(Debug, Clone)]
pub struct Call {
pub channel_id: ChannelId,
pub message_id: MessageId,
pub region: String,
pub ringing: Vec<UserId>,
pub unavailable: bool,
pub voice_states: Vec<VoiceState>,
}
impl Call {
pub fn decode(value: Value) -> Result<Call> {
let mut value = try!(into_map(value));
warn_json!(value, Call {
channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)),
message_id: try!(remove(&mut value, "message_id").and_then(MessageId::decode)),
region: try!(remove(&mut value, "region").and_then(into_string)),
ringing: try!(decode_array(try!(remove(&mut value, "ringing")), UserId::decode)),
unavailable: req!(try!(remove(&mut value, "unavailable")).as_bool()),
voice_states: try!(decode_array(try!(remove(&mut value, "voice_states")), VoiceState::decode)),
})
}
}
/// Private text channel to another user
#[derive(Debug, Clone)]
pub struct PrivateChannel {
pub id: ChannelId,
pub kind: ChannelType,
pub recipient: User,
pub last_message_id: Option<MessageId>,
pub last_pin_timestamp: Option<String>,
}
impl PrivateChannel {
pub fn decode(value: Value) -> Result<PrivateChannel> {
let mut value = try!(into_map(value));
let mut recipients = try!(decode_array(try!(remove(&mut value, "recipients")), User::decode));
if recipients.len() != 1 {
warn!("expected 1 recipient, found {}: {:?}", recipients.len(), recipients);
}
warn_json!(value, PrivateChannel {
id: try!(remove(&mut value, "id").and_then(ChannelId::decode)),
kind: try!(remove(&mut value, "type").and_then(ChannelType::decode)),
recipient: recipients.remove(0),
last_message_id: try!(opt(&mut value, "last_message_id", MessageId::decode)),
last_pin_timestamp: try!(opt(&mut value, "last_pin_timestamp", into_string)),
})
}
}
/// Public voice or text channel within a server
#[derive(Debug, Clone)]
pub struct PublicChannel {
pub id: ChannelId,
pub name: String,
pub server_id: ServerId,
pub kind: ChannelType,
pub permission_overwrites: Vec<PermissionOverwrite>,
pub topic: Option<String>,
pub position: i64,
pub last_message_id: Option<MessageId>,
pub bitrate: Option<u64>,
pub user_limit: Option<u64>,
pub last_pin_timestamp: Option<String>,
}
impl PublicChannel {
pub fn decode(value: Value) -> Result<PublicChannel> {
let mut value = try!(into_map(value));
let id = try!(remove(&mut value, "guild_id").and_then(ServerId::decode));
PublicChannel::decode_server(Value::Object(value), id)
}
pub fn decode_server(value: Value, server_id: ServerId) -> Result<PublicChannel> {
let mut value = try!(into_map(value));
warn_json!(value, PublicChannel {
id: try!(remove(&mut value, "id").and_then(ChannelId::decode)),
name: try!(remove(&mut value, "name").and_then(into_string)),
server_id: server_id,
topic: try!(opt(&mut value, "topic", into_string)),
position: req!(try!(remove(&mut value, "position")).as_i64()),
kind: try!(remove(&mut value, "type").and_then(ChannelType::decode)),
last_message_id: try!(opt(&mut value, "last_message_id", MessageId::decode)),
permission_overwrites: try!(decode_array(try!(remove(&mut value, "permission_overwrites")), PermissionOverwrite::decode)),
bitrate: remove(&mut value, "bitrate").ok().and_then(|v| v.as_u64()),
user_limit: remove(&mut value, "user_limit").ok().and_then(|v| v.as_u64()),
last_pin_timestamp: try!(opt(&mut value, "last_pin_timestamp", into_string)),
})
}
/// Return a `Mention` which will link to this channel.
#[inline(always)]
pub fn mention(&self) -> Mention { self.id.mention() }
}
/// The type of edit being made to a Channel's permissions.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum PermissionOverwriteType {
Member(UserId),
Role(RoleId),
}
/// A channel-specific permission overwrite for a role or member.
#[derive(Debug, Clone)]
pub struct PermissionOverwrite {
pub kind: PermissionOverwriteType,
pub allow: Permissions,
pub deny: Permissions,
}
impl PermissionOverwrite {
pub fn decode(value: Value) -> Result<PermissionOverwrite> {
let mut value = try!(into_map(value));
let id = try!(remove(&mut value, "id").and_then(decode_id));
let kind = try!(remove(&mut value, "type").and_then(into_string));
let kind = match &*kind {
"member" => PermissionOverwriteType::Member(UserId(id)),
"role" => PermissionOverwriteType::Role(RoleId(id)),
_ => return Err(Error::Decode("Expected valid PermissionOverwrite type", Value::String(kind))),
};
warn_json!(value, PermissionOverwrite {
kind: kind,
allow: try!(remove(&mut value, "allow").and_then(Permissions::decode)),
deny: try!(remove(&mut value, "deny").and_then(Permissions::decode)),
})
}
}
pub mod permissions {
use ::{Error, Result};
use serde_json::Value;
bitflags! {
/// Set of permissions assignable to a Role or PermissionOverwrite
pub flags Permissions: u64 {
const CREATE_INVITE = 1 << 0,
const KICK_MEMBERS = 1 << 1,
const BAN_MEMBERS = 1 << 2,
/// Grant all permissions, bypassing channel-specific permissions
const ADMINISTRATOR = 1 << 3,
/// Modify roles below their own
const MANAGE_ROLES = 1 << 28,
/// Create channels or edit existing ones
const MANAGE_CHANNELS = 1 << 4,
/// Change the server's name or move regions
const MANAGE_SERVER = 1 << 5,
/// Change their own nickname
const CHANGE_NICKNAMES = 1 << 26,
/// Change the nickname of other users
const MANAGE_NICKNAMES = 1 << 27,
/// Manage the emojis in a a server.
const MANAGE_EMOJIS = 1 << 30,
/// Manage channel webhooks
const MANAGE_WEBHOOKS = 1 << 29,
const READ_MESSAGES = 1 << 10,
const SEND_MESSAGES = 1 << 11,
/// Send text-to-speech messages to those focused on the channel
const SEND_TTS_MESSAGES = 1 << 12,
/// Delete messages by other users
const MANAGE_MESSAGES = 1 << 13,
const EMBED_LINKS = 1 << 14,
const ATTACH_FILES = 1 << 15,
const READ_HISTORY = 1 << 16,
/// Trigger a push notification for an entire channel with "@everyone"
const MENTION_EVERYONE = 1 << 17,
/// Use emojis from other servers
const EXTERNAL_EMOJIS = 1 << 18,
/// Add emoji reactions to messages
const ADD_REACTIONS = 1 << 6,
const VOICE_CONNECT = 1 << 20,
const VOICE_SPEAK = 1 << 21,
const VOICE_MUTE_MEMBERS = 1 << 22,
const VOICE_DEAFEN_MEMBERS = 1 << 23,
/// Move users out of this channel into another
const VOICE_MOVE_MEMBERS = 1 << 24,
/// When denied, members must use push-to-talk
const VOICE_USE_VAD = 1 << 25,
}
}
impl Permissions {
pub fn decode(value: Value) -> Result<Permissions> {
Ok(Self::from_bits_truncate(req!(value.as_u64())))
}
}
}
/// File upload attached to a message
#[derive(Debug, Clone)]
pub struct Attachment {
pub id: String,
/// Short filename for the attachment
pub filename: String,
/// Shorter URL with message and attachment id
pub url: String,
/// Longer URL with large hash
pub proxy_url: String,
/// Size of the file in bytes
pub size: u64,
/// Dimensions if the file is an image
pub dimensions: Option<(u64, u64)>,
}
impl Attachment {
pub fn decode(value: Value) -> Result<Attachment> {
let mut value = try!(into_map(value));
let width = remove(&mut value, "width").ok().and_then(|x| x.as_u64());
let height = remove(&mut value, "height").ok().and_then(|x| x.as_u64());
warn_json!(value, Attachment {
id: try!(remove(&mut value, "id").and_then(into_string)),
filename: try!(remove(&mut value, "filename").and_then(into_string)),
url: try!(remove(&mut value, "url").and_then(into_string)),
proxy_url: try!(remove(&mut value, "proxy_url").and_then(into_string)),
size: req!(try!(remove(&mut value, "size")).as_u64()),
dimensions: width.and_then(|w| height.map(|h| (w, h))),
})
}
}
/// Message transmitted over a text channel
#[derive(Debug, Clone)]
pub struct Message {
pub id: MessageId,
pub channel_id: ChannelId,
pub content: String,
pub nonce: Option<String>,
pub tts: bool,
pub timestamp: String,
pub edited_timestamp: Option<String>,
pub pinned: bool,
pub kind: MessageType,
pub author: User,
pub mention_everyone: bool,
pub mentions: Vec<User>,
pub mention_roles: Vec<RoleId>,
pub attachments: Vec<Attachment>,
/// Follows OEmbed standard
pub embeds: Vec<Value>,
}
impl Message {
pub fn decode(value: Value) -> Result<Message> {
let mut value = try!(into_map(value));
warn_json!(value, Message {
id: try!(remove(&mut value, "id").and_then(MessageId::decode)),
channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)),
nonce: remove(&mut value, "nonce").and_then(into_string).ok(), // nb: swallow errors
content: try!(remove(&mut value, "content").and_then(into_string)),
tts: req!(try!(remove(&mut value, "tts")).as_bool()),
timestamp: try!(remove(&mut value, "timestamp").and_then(into_string)),
edited_timestamp: try!(opt(&mut value, "edited_timestamp", into_string)),
pinned: req!(try!(remove(&mut value, "pinned")).as_bool()),
kind: try!(remove(&mut value, "type").and_then(MessageType::decode)),
mention_everyone: req!(try!(remove(&mut value, "mention_everyone")).as_bool()),
mentions: try!(decode_array(try!(remove(&mut value, "mentions")), User::decode)),
mention_roles: try!(decode_array(try!(remove(&mut value, "mention_roles")), RoleId::decode)),
author: try!(remove(&mut value, "author").and_then(User::decode)),
attachments: try!(decode_array(try!(remove(&mut value, "attachments")), Attachment::decode)),
embeds: try!(decode_array(try!(remove(&mut value, "embeds")), Ok)),
})
}
}
/// The type of a message
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum MessageType {
/// A regular, text-based message
Regular,
/// A recipient was added to the group
GroupRecipientAddition,
/// A recipient was removed from the group
GroupRecipientRemoval,
/// A group call was created
GroupCallCreation,
/// A group name was updated
GroupNameUpdate,
/// A group icon was updated
GroupIconUpdate,
/// A message was pinned
MessagePinned,
}
map_numbers! { MessageType;
Regular, 0;
GroupRecipientAddition, 1;
GroupRecipientRemoval, 2;
GroupCallCreation, 3;
GroupNameUpdate, 4;
GroupIconUpdate, 5;
MessagePinned, 6;
}
/// Information about an invite
#[derive(Debug, Clone)]
pub struct Invite {
pub code: String,
pub server_id: ServerId,
pub server_name: String,
pub channel_type: ChannelType,
pub channel_id: ChannelId,
pub channel_name: String,
}
impl Invite {
pub fn decode(value: Value) -> Result<Invite> {
let mut value = try!(into_map(value));
let mut server = try!(remove(&mut value, "guild").and_then(into_map));
let server_id = try!(remove(&mut server, "id").and_then(ServerId::decode));
let server_name = try!(remove(&mut server, "name").and_then(into_string));
warn_field("Invite/guild", server);
let mut channel = try!(remove(&mut value, "channel").and_then(into_map));
let channel_type = try!(remove(&mut channel, "type").and_then(ChannelType::decode));
let channel_id = try!(remove(&mut channel, "id").and_then(ChannelId::decode));
let channel_name = try!(remove(&mut channel, "name").and_then(into_string));
warn_field("Invite/channel", channel);
warn_json!(value, Invite {
code: try!(remove(&mut value, "code").and_then(into_string)),
server_id: server_id,
server_name: server_name,
channel_type: channel_type,
channel_id: channel_id,
channel_name: channel_name,
})
}
}
/// Detailed information about an invite, available to server managers
#[derive(Debug, Clone)]
pub struct RichInvite {
pub code: String,
pub server_icon: Option<String>,
pub server_id: ServerId,
pub server_name: String,
pub server_splash_hash: Option<String>,
pub channel_type: ChannelType,
pub channel_id: ChannelId,
pub channel_name: String,
pub inviter: User,
pub created_at: String,
pub max_age: u64,
pub max_uses: u64,
pub temporary: bool,
pub uses: u64,
}
impl RichInvite {
pub fn decode(value: Value) -> Result<Self> {
let mut value = try!(into_map(value));
let mut server = try!(remove(&mut value, "guild").and_then(into_map));
let server_icon_hash = try!(opt(&mut server, "icon", into_string));
let server_id = try!(remove(&mut server, "id").and_then(ServerId::decode));
let server_name = try!(remove(&mut server, "name").and_then(into_string));
let server_splash_hash = try!(opt(&mut server, "splash_hash", into_string));
warn_field("RichInvite/guild", server);
let mut channel = try!(remove(&mut value, "channel").and_then(into_map));
let channel_type = try!(remove(&mut channel, "type").and_then(ChannelType::decode));
let channel_id = try!(remove(&mut channel, "id").and_then(ChannelId::decode));
let channel_name = try!(remove(&mut channel, "name").and_then(into_string));
warn_field("RichInvite/channel", channel);
warn_json!(value, RichInvite {
code: try!(remove(&mut value, "code").and_then(into_string)),
server_icon: server_icon_hash,
server_id: server_id,
server_name: server_name,
server_splash_hash: server_splash_hash,
channel_type: channel_type,
channel_id: channel_id,
channel_name: channel_name,
inviter: try!(remove(&mut value, "inviter").and_then(User::decode)),
created_at: try!(remove(&mut value, "created_at").and_then(into_string)),
max_age: req!(try!(remove(&mut value, "max_age")).as_u64()),
max_uses: req!(try!(remove(&mut value, "max_uses")).as_u64()),
temporary: req!(try!(remove(&mut value, "temporary")).as_bool()),
uses: req!(try!(remove(&mut value, "uses")).as_u64()),
})
}
}
/// Information about an available voice region
#[derive(Debug, Clone)]
pub struct VoiceRegion {
pub id: String,
pub name: String,
pub sample_hostname: String,
pub sample_port: u16,
pub optimal: bool,
pub vip: bool,
}
impl VoiceRegion {
pub fn decode(value: Value) -> Result<VoiceRegion> {
let mut value = try!(into_map(value));
warn_json!(value, VoiceRegion {
id: try!(remove(&mut value, "id").and_then(into_string)),
name: try!(remove(&mut value, "name").and_then(into_string)),
sample_hostname: try!(remove(&mut value, "sample_hostname").and_then(into_string)),
sample_port: req!(try!(remove(&mut value, "sample_port")).as_u64()) as u16,
optimal: req!(try!(remove(&mut value, "optimal")).as_bool()),
vip: req!(try!(remove(&mut value, "vip")).as_bool()),
})
}
}
//=================
// Event model
/// Summary of messages since last login
#[derive(Debug, Clone)]
pub struct ReadState {
/// Id of the relevant channel
pub id: ChannelId,
/// Last seen message in this channel
pub last_message_id: Option<MessageId>,
/// Mentions since that message in this channel
pub mention_count: u64,
}
impl ReadState {
pub fn decode(value: Value) -> Result<ReadState> {
let mut value = try!(into_map(value));
warn_json!(value, ReadState {
id: try!(remove(&mut value, "id").and_then(ChannelId::decode)),
last_message_id: try!(opt(&mut value, "last_message_id", MessageId::decode)),
mention_count: try!(opt(&mut value, "mention_count", |v| Ok(req!(v.as_u64())))).unwrap_or(0),
})
}
}
/// A user's online presence status
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum OnlineStatus {
DoNotDisturb,
Invisible,
Offline,
Online,
Idle,
}
map_names! { OnlineStatus;
DoNotDisturb, "dnd";
Invisible, "invisible";
Offline, "offline";
Online, "online";
Idle, "idle";
}
/// A type of game being played.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum GameType {
Playing,
Streaming,
}
map_numbers! { GameType;
Playing, 0;
Streaming, 1;
}
/// Information about a game being played
#[derive(Debug, Clone)]
pub struct Game {