Skip to main content

djs_rest/endpoints/
invite.rs

1//! [Invite endpoints](https://docs.discord.com/developers/resources/invite): resolving and
2//! deleting invites, and the target users of invites only some users may accept.
3//!
4//! Invites are created per channel with
5//! [`create_channel_invite`](Rest::create_channel_invite) and listed with
6//! [`get_channel_invites`](Rest::get_channel_invites) and
7//! [`get_guild_invites`](Rest::get_guild_invites).
8
9use djs_model::{
10    id::UserId,
11    invite::{Invite, InviteTargetUsersJobStatus},
12    rest::{BulkTargetUsers, FileUpload, GetInvite},
13};
14
15use crate::client::boxed;
16use crate::{Error, ErrorKind, Request, Rest, Route};
17
18/// Invites.
19impl Rest {
20    /// [Get Invite](https://docs.discord.com/developers/resources/invite#get-invite):
21    /// resolves an invite code (the part after `discord.gg/`).
22    ///
23    /// discord.js counterpart: `Client#fetchInvite`.
24    ///
25    /// # Examples
26    ///
27    /// ```no_run
28    /// # async fn example(rest: djs_rest::Rest) -> Result<(), djs_rest::Error> {
29    /// use djs_model::rest::GetInvite;
30    ///
31    /// let mut query = GetInvite::default();
32    /// query.with_counts = Some(true);
33    /// let invite = rest.get_invite("rust-lang", &query).await?;
34    /// println!("{:?} members", invite.approximate_member_count);
35    /// # Ok(())
36    /// # }
37    /// ```
38    ///
39    /// # Errors
40    ///
41    /// See [`Rest::request`]; `10006` Unknown Invite.
42    pub fn get_invite<'a>(
43        &'a self,
44        invite_code: &'a str,
45        query: &'a GetInvite,
46    ) -> impl Future<Output = Result<Invite, Error>> + Send + 'a {
47        boxed(async move {
48            self.call(Request::new(Route::GetInvite { invite_code }).query(query))
49                .await
50        })
51    }
52
53    /// [Delete Invite](https://docs.discord.com/developers/resources/invite#delete-invite):
54    /// revokes an invite and returns it. Needs `MANAGE_CHANNELS` on its channel or
55    /// `MANAGE_GUILD`.
56    ///
57    /// `reason` is shown in the audit log (D-086).
58    ///
59    /// discord.js counterpart: `Invite#delete`, `GuildInviteManager#delete`.
60    ///
61    /// # Errors
62    ///
63    /// See [`Rest::request`]; `10006` Unknown Invite.
64    pub fn delete_invite<'a>(
65        &'a self,
66        invite_code: &'a str,
67        reason: Option<&'a str>,
68    ) -> impl Future<Output = Result<Invite, Error>> + Send + 'a {
69        boxed(async move {
70            self.call(Request::new(Route::DeleteInvite { invite_code }).reason(reason))
71                .await
72        })
73    }
74}
75
76/// Target users: the users allowed to see and accept an invite. Each endpoint needs the bot to
77/// be the inviter or to have `MANAGE_GUILD` (reading also works with `VIEW_AUDIT_LOG`).
78impl Rest {
79    /// [Get Target Users](https://docs.discord.com/developers/resources/invite#get-target-users):
80    /// returns the users allowed to accept the invite. Discord sends a CSV file, which is
81    /// parsed (D-126).
82    ///
83    /// discord.js counterpart: `GuildInviteManager#fetchTargetUsers` (the raw file).
84    ///
85    /// # Errors
86    ///
87    /// See [`Rest::request`]; [`ErrorKind::Deserialize`] when a line of the file is not a user
88    /// ID; `10129` when the invite has no target users.
89    pub fn get_target_users<'a>(
90        &'a self,
91        invite_code: &'a str,
92    ) -> impl Future<Output = Result<Vec<UserId>, Error>> + Send + 'a {
93        boxed(async move {
94            let (_, body) = self
95                .execute(Request::new(Route::GetTargetUsers { invite_code }))
96                .await?;
97            parse_target_users(&body)
98        })
99    }
100
101    /// [Add Target User](https://docs.discord.com/developers/resources/invite#add-target-user):
102    /// allows one more user to accept the invite.
103    ///
104    /// discord.js counterpart: none.
105    ///
106    /// # Errors
107    ///
108    /// See [`Rest::request`]; `30084` at the limit of target users.
109    pub fn add_target_user<'a>(
110        &'a self,
111        invite_code: &'a str,
112        user_id: UserId,
113    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
114        boxed(async move {
115            self.call(Request::new(Route::AddTargetUser {
116                invite_code,
117                user_id,
118            }))
119            .await
120        })
121    }
122
123    /// [Remove Target User](https://docs.discord.com/developers/resources/invite#remove-target-user):
124    /// no longer allows a user to accept the invite.
125    ///
126    /// discord.js counterpart: none.
127    ///
128    /// # Errors
129    ///
130    /// See [`Rest::request`].
131    pub fn remove_target_user<'a>(
132        &'a self,
133        invite_code: &'a str,
134        user_id: UserId,
135    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
136        boxed(async move {
137            self.call(Request::new(Route::RemoveTargetUser {
138                invite_code,
139                user_id,
140            }))
141            .await
142        })
143    }
144
145    /// [Update Target Users](https://docs.discord.com/developers/resources/invite#update-target-users):
146    /// replaces the users allowed to accept the invite with those of a CSV file — build it
147    /// with [`FileUpload::target_users`] (D-127). Discord processes the file in the
148    /// background; follow it with [`get_target_users_job_status`](Self::get_target_users_job_status).
149    ///
150    /// discord.js counterpart: `GuildInviteManager#updateTargetUsers`.
151    ///
152    /// # Examples
153    ///
154    /// ```no_run
155    /// # async fn example(rest: djs_rest::Rest, invite_code: &str, members: Vec<djs_model::id::UserId>) -> Result<(), djs_rest::Error> {
156    /// use djs_model::rest::FileUpload;
157    ///
158    /// rest.update_target_users(invite_code, &FileUpload::target_users(members))
159    ///     .await?;
160    /// # Ok(())
161    /// # }
162    /// ```
163    ///
164    /// # Errors
165    ///
166    /// See [`Rest::request`]; `400` listing the invalid lines of the file; `40114` while a
167    /// previous file is still being processed.
168    pub fn update_target_users<'a>(
169        &'a self,
170        invite_code: &'a str,
171        file: &'a FileUpload,
172    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
173        boxed(async move {
174            self.request_ignoring_body(
175                Request::new(Route::UpdateTargetUsers { invite_code })
176                    .form_file("target_users_file", file),
177            )
178            .await
179        })
180    }
181
182    /// [Bulk-Add Target Users](https://docs.discord.com/developers/resources/invite#bulk-add-target-users):
183    /// allows up to 1000 more users to accept the invite.
184    ///
185    /// discord.js counterpart: none.
186    ///
187    /// # Errors
188    ///
189    /// See [`Rest::request`]; `30084` at the limit of target users.
190    pub fn bulk_add_target_users<'a>(
191        &'a self,
192        invite_code: &'a str,
193        body: &'a BulkTargetUsers,
194    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
195        boxed(async move {
196            self.call(Request::new(Route::BulkAddTargetUsers { invite_code }).json(body)?)
197                .await
198        })
199    }
200
201    /// [Bulk-Delete Target Users](https://docs.discord.com/developers/resources/invite#bulk-delete-target-users):
202    /// no longer allows up to 1000 users to accept the invite.
203    ///
204    /// discord.js counterpart: none.
205    ///
206    /// # Errors
207    ///
208    /// See [`Rest::request`].
209    pub fn bulk_delete_target_users<'a>(
210        &'a self,
211        invite_code: &'a str,
212        body: &'a BulkTargetUsers,
213    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
214        boxed(async move {
215            self.call(Request::new(Route::BulkDeleteTargetUsers { invite_code }).json(body)?)
216                .await
217        })
218    }
219
220    /// [Get Target Users Job Status](https://docs.discord.com/developers/resources/invite#get-target-users-job-status):
221    /// returns the progress of processing the invite's target users file.
222    ///
223    /// discord.js counterpart: `GuildInviteManager#fetchTargetUsersJobStatus`.
224    ///
225    /// # Errors
226    ///
227    /// See [`Rest::request`]; `10124` when there is no job for the invite.
228    pub fn get_target_users_job_status<'a>(
229        &'a self,
230        invite_code: &'a str,
231    ) -> impl Future<Output = Result<InviteTargetUsersJobStatus, Error>> + Send + 'a {
232        boxed(async move {
233            self.call(Request::new(Route::GetTargetUsersJobStatus { invite_code }))
234                .await
235        })
236    }
237}
238
239/// Parses the target users CSV: an optional `user_id` header, then one user ID per line.
240/// Blank lines and surrounding whitespace (including `\r`) are ignored.
241fn parse_target_users(body: &[u8]) -> Result<Vec<UserId>, Error> {
242    let text = core::str::from_utf8(body)
243        .map_err(|source| Error::with_source(ErrorKind::Deserialize, source))?;
244    let mut lines = text.lines().map(str::trim).enumerate().peekable();
245    // Skip the header that Discord's files start with.
246    lines.next_if(|(_, line)| *line == "user_id");
247    lines
248        .filter(|(_, line)| !line.is_empty())
249        .map(|(index, line)| {
250            line.parse().map_err(|source| {
251                Error::with_source(
252                    ErrorKind::Deserialize,
253                    format!(
254                        "line {} of the target users file is not a user ID: {source}",
255                        index + 1
256                    ),
257                )
258            })
259        })
260        .collect()
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn target_users_csv() {
269        let ids = |body: &str| parse_target_users(body.as_bytes()).unwrap();
270        assert_eq!(
271            ids("user_id\n7\n8\n"),
272            [UserId::new(7), UserId::new(8)],
273            "header and trailing newline"
274        );
275        assert_eq!(ids("7\r\n\r\n8"), [UserId::new(7), UserId::new(8)]);
276        assert_eq!(ids("user_id\n"), Vec::<UserId>::new());
277        assert_eq!(ids(""), Vec::<UserId>::new());
278
279        let error = parse_target_users(b"user_id\n7\nferris\n").unwrap_err();
280        assert!(matches!(error.kind(), ErrorKind::Deserialize));
281        assert!(
282            core::error::Error::source(&error)
283                .unwrap()
284                .to_string()
285                .starts_with("line 3 ")
286        );
287    }
288}