twilight_model/application/command/
permissions.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
//! Limit who and where commands can be executed.

use crate::id::{
    marker::{
        ApplicationMarker, ChannelMarker, CommandMarker, GenericMarker, GuildMarker, RoleMarker,
        UserMarker,
    },
    Id,
};
use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};

/// List of [`CommandPermission`]s for a command in a guild.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct GuildCommandPermissions {
    /// ID of the application the command belongs to.
    pub application_id: Id<ApplicationMarker>,
    /// ID of the guild.
    pub guild_id: Id<GuildMarker>,
    /// ID of the command.
    pub id: Id<CommandMarker>,
    /// Command permissions in the guild.
    ///
    /// Max 100.
    pub permissions: Vec<CommandPermission>,
}

/// Member, channel or role explicit permission to use a command.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct CommandPermission {
    /// Affected resource.
    pub id: CommandPermissionType,
    /// Whether the resource is allowed or disallowed to use the command.
    pub permission: bool,
}

/// Resources commands can allow or disallow from executing them.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum CommandPermissionType {
    /// Affected channel.
    ///
    /// Use `@everyone - 1` for all channels in the guild.
    Channel(Id<ChannelMarker>),
    /// Affected role.
    ///
    /// The `@everyone` role is permitted.
    Role(Id<RoleMarker>),
    /// Affected member.
    User(Id<UserMarker>),
}

impl CommandPermissionType {
    /// Get the inner ID.
    const fn id(self) -> Id<GenericMarker> {
        match self {
            Self::Channel(id) => id.cast(),
            Self::Role(id) => id.cast(),
            Self::User(id) => id.cast(),
        }
    }

    /// Get the associated resource type.
    const fn kind(self) -> CommandPermissionDataType {
        match self {
            Self::Channel(_) => CommandPermissionDataType::Channel,
            Self::Role(_) => CommandPermissionDataType::Role,
            Self::User(_) => CommandPermissionDataType::User,
        }
    }
}

#[derive(Deserialize, Serialize)]
struct CommandPermissionData {
    /// Affected resource.
    id: Id<GenericMarker>,
    /// Resource type.
    #[serde(rename = "type")]
    kind: CommandPermissionDataType,
    /// Whether the resource is allowed or disallowed.
    permission: bool,
}

#[derive(Clone, Debug, Deserialize_repr, Eq, PartialEq, Serialize_repr)]
#[non_exhaustive]
#[repr(u8)]
enum CommandPermissionDataType {
    Role = 1,
    User = 2,
    Channel = 3,
}

impl<'de> Deserialize<'de> for CommandPermission {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let data = CommandPermissionData::deserialize(deserializer)?;

        let id = match data.kind {
            CommandPermissionDataType::Role => CommandPermissionType::Role(data.id.cast()),
            CommandPermissionDataType::User => CommandPermissionType::User(data.id.cast()),
            CommandPermissionDataType::Channel => CommandPermissionType::Channel(data.id.cast()),
        };

        Ok(Self {
            id,
            permission: data.permission,
        })
    }
}

impl Serialize for CommandPermission {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let data = CommandPermissionData {
            id: self.id.id(),
            kind: self.id.kind(),
            permission: self.permission,
        };

        data.serialize(serializer)
    }
}

#[cfg(test)]
mod tests {
    use super::{
        CommandPermission, CommandPermissionDataType, CommandPermissionType,
        GuildCommandPermissions,
    };
    use crate::id::Id;
    use serde_test::Token;

    #[test]
    fn serde_command_permission() {
        let value = CommandPermission {
            id: CommandPermissionType::Role(Id::new(100)),
            permission: true,
        };

        serde_test::assert_tokens(
            &value,
            &[
                Token::Struct {
                    name: "CommandPermissionData",
                    len: 3,
                },
                Token::Str("id"),
                Token::NewtypeStruct { name: "Id" },
                Token::Str("100"),
                Token::Str("type"),
                Token::U8(CommandPermissionDataType::Role as u8),
                Token::Str("permission"),
                Token::Bool(true),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn serde_guild_command_permission() {
        let value = GuildCommandPermissions {
            application_id: Id::new(1),
            guild_id: Id::new(2),
            id: Id::new(3),
            permissions: Vec::from([
                CommandPermission {
                    id: CommandPermissionType::Channel(Id::new(50)),
                    permission: false,
                },
                CommandPermission {
                    id: CommandPermissionType::User(Id::new(200)),
                    permission: true,
                },
            ]),
        };

        serde_test::assert_tokens(
            &value,
            &[
                Token::Struct {
                    name: "GuildCommandPermissions",
                    len: 4,
                },
                Token::Str("application_id"),
                Token::NewtypeStruct { name: "Id" },
                Token::Str("1"),
                Token::Str("guild_id"),
                Token::NewtypeStruct { name: "Id" },
                Token::Str("2"),
                Token::Str("id"),
                Token::NewtypeStruct { name: "Id" },
                Token::Str("3"),
                Token::Str("permissions"),
                Token::Seq { len: Some(2) },
                Token::Struct {
                    name: "CommandPermissionData",
                    len: 3,
                },
                Token::Str("id"),
                Token::NewtypeStruct { name: "Id" },
                Token::Str("50"),
                Token::Str("type"),
                Token::U8(CommandPermissionDataType::Channel as u8),
                Token::Str("permission"),
                Token::Bool(false),
                Token::StructEnd,
                Token::Struct {
                    name: "CommandPermissionData",
                    len: 3,
                },
                Token::Str("id"),
                Token::NewtypeStruct { name: "Id" },
                Token::Str("200"),
                Token::Str("type"),
                Token::U8(CommandPermissionDataType::User as u8),
                Token::Str("permission"),
                Token::Bool(true),
                Token::StructEnd,
                Token::SeqEnd,
                Token::StructEnd,
            ],
        );
    }
}