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
use crate::{
    client::Client,
    error::Error,
    request::{self, AuditLogReason, Request, TryIntoRequest},
    response::{marker::EmptyBody, Response, ResponseFuture},
    routing::Route,
};
use serde::Serialize;
use std::future::IntoFuture;
use twilight_model::{
    guild::Permissions,
    http::permission_overwrite::{PermissionOverwrite, PermissionOverwriteType},
    id::{
        marker::{ChannelMarker, GenericMarker},
        Id,
    },
};
use twilight_validate::request::{audit_reason as validate_audit_reason, ValidationError};

#[derive(Serialize)]
struct UpdateChannelPermissionFields {
    #[serde(skip_serializing_if = "Option::is_none")]
    allow: Option<Permissions>,
    #[serde(skip_serializing_if = "Option::is_none")]
    deny: Option<Permissions>,
    #[serde(rename = "type")]
    kind: PermissionOverwriteType,
}

/// Update the permissions for a role or a user in a channel.
///
/// # Examples:
///
/// Create permission overrides for a role to view the channel, but not send
/// messages:
///
/// ```no_run
/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # use twilight_http::Client;
/// # let client = Client::new("my token".to_owned());
/// #
/// use twilight_model::{
///     guild::Permissions,
///     http::permission_overwrite::{PermissionOverwrite, PermissionOverwriteType},
///     id::Id,
/// };
///
/// let channel_id = Id::new(123);
/// let permission_overwrite = PermissionOverwrite {
///     allow: Some(Permissions::VIEW_CHANNEL),
///     deny: Some(Permissions::SEND_MESSAGES),
///     id: Id::new(432),
///     kind: PermissionOverwriteType::Role,
/// };
///
/// client
///     .update_channel_permission(channel_id, &permission_overwrite)
///     .await?;
/// # Ok(()) }
/// ```
#[must_use = "requests must be configured and executed"]
pub struct UpdateChannelPermission<'a> {
    channel_id: Id<ChannelMarker>,
    fields: UpdateChannelPermissionFields,
    http: &'a Client,
    reason: Option<&'a str>,
    target_id: Id<GenericMarker>,
}

impl<'a> UpdateChannelPermission<'a> {
    pub(crate) const fn new(
        http: &'a Client,
        channel_id: Id<ChannelMarker>,
        permission_overwrite: &PermissionOverwrite,
    ) -> Self {
        Self {
            channel_id,
            http,
            fields: UpdateChannelPermissionFields {
                allow: permission_overwrite.allow,
                deny: permission_overwrite.deny,
                kind: permission_overwrite.kind,
            },
            reason: None,
            target_id: permission_overwrite.id,
        }
    }

    /// Execute the request, returning a future resolving to a [`Response`].
    #[deprecated(since = "0.14.0", note = "use `.await` or `into_future` instead")]
    pub fn exec(self) -> ResponseFuture<EmptyBody> {
        self.into_future()
    }
}

impl<'a> AuditLogReason<'a> for UpdateChannelPermission<'a> {
    fn reason(mut self, reason: &'a str) -> Result<Self, ValidationError> {
        validate_audit_reason(reason)?;

        self.reason.replace(reason);

        Ok(self)
    }
}

impl IntoFuture for UpdateChannelPermission<'_> {
    type Output = Result<Response<EmptyBody>, Error>;

    type IntoFuture = ResponseFuture<EmptyBody>;

    fn into_future(self) -> Self::IntoFuture {
        let http = self.http;

        match self.try_into_request() {
            Ok(request) => http.request(request),
            Err(source) => ResponseFuture::error(source),
        }
    }
}

impl TryIntoRequest for UpdateChannelPermission<'_> {
    fn try_into_request(self) -> Result<Request, Error> {
        let mut request = Request::builder(&Route::UpdatePermissionOverwrite {
            channel_id: self.channel_id.get(),
            target_id: self.target_id.get(),
        })
        .json(&self.fields)?;

        if let Some(reason) = &self.reason {
            request = request.headers(request::audit_header(reason)?);
        }

        Ok(request.build())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn request() {
        let permission_overwrite = PermissionOverwrite {
            allow: None,
            deny: Some(Permissions::SEND_MESSAGES),
            id: Id::new(2),
            kind: PermissionOverwriteType::Member,
        };

        let client = Client::new("foo".to_owned());
        let builder = UpdateChannelPermission::new(&client, Id::new(1), &permission_overwrite);
        let actual = builder
            .try_into_request()
            .expect("failed to create request");

        let body = crate::json::to_vec(&UpdateChannelPermissionFields {
            allow: None,
            deny: Some(Permissions::SEND_MESSAGES),
            kind: PermissionOverwriteType::Member,
        })
        .expect("failed to serialize payload");
        let route = Route::UpdatePermissionOverwrite {
            channel_id: 1,
            target_id: 2,
        };
        let expected = Request::builder(&route).body(body).build();

        assert_eq!(expected.body, actual.body);
        assert_eq!(expected.path, actual.path);
    }
}