Skip to main content

djs_rs/manager/
invite.rs

1//! [`InviteManager`].
2
3use std::future::Future;
4
5use djs_cache::Backend;
6use djs_collection::Collection;
7use djs_model::{
8    id::{ChannelId, GuildId},
9    invite::{Invite, InviteWithMetadata},
10    rest::{CreateChannelInvite, GetInvite},
11};
12use djs_rest::Error;
13
14use super::Fetch;
15use crate::Context;
16
17/// Invites, by code (D-239). Returned by [`Context::invites`].
18///
19/// The cache does not keep invites, so every method asks Discord and returns the
20/// [`djs-model`](djs_model) types. Lists are keyed by the invite code.
21///
22/// discord.js counterpart: `GuildInviteManager` (`guild.invites`) and `Client#fetchInvite`.
23#[derive(Debug)]
24pub struct InviteManager<'a, B: Backend> {
25    ctx: &'a Context<B>,
26}
27
28impl<B: Backend> Clone for InviteManager<'_, B> {
29    fn clone(&self) -> Self {
30        *self
31    }
32}
33
34impl<B: Backend> Copy for InviteManager<'_, B> {}
35
36impl<'a, B: Backend> InviteManager<'a, B> {
37    pub(crate) const fn new(ctx: &'a Context<B>) -> Self {
38        Self { ctx }
39    }
40
41    /// An invite by its code, to any guild ([Get Invite](djs_rest::Rest::get_invite)).
42    ///
43    /// discord.js counterpart: `Client#fetchInvite`.
44    ///
45    /// # Errors
46    ///
47    /// Returns the REST error if the request failed (Discord answers 404 for an unknown or
48    /// expired invite).
49    pub fn fetch<'r>(
50        self,
51        code: &'r str,
52        query: &'r GetInvite,
53    ) -> Fetch<Invite, impl Future<Output = Result<Invite, Error>> + Send + 'r>
54    where
55        'a: 'r,
56    {
57        let ctx = self.ctx;
58        Fetch::new(
59            None,
60            async move { ctx.rest().get_invite(code, query).await },
61        )
62    }
63
64    /// Deletes an invite ([Delete Invite](djs_rest::Rest::delete_invite)), returning it.
65    ///
66    /// discord.js counterpart: `GuildInviteManager#delete` / `Invite#delete`.
67    ///
68    /// # Errors
69    ///
70    /// Returns the REST error if the request failed (it needs `MANAGE_CHANNELS` on the
71    /// channel or `MANAGE_GUILD`).
72    pub async fn delete(self, code: &str, reason: Option<&str>) -> Result<Invite, Error> {
73        self.ctx.rest().delete_invite(code, reason).await
74    }
75
76    /// Creates an invite to a channel ([Create Channel
77    /// Invite](djs_rest::Rest::create_channel_invite)).
78    ///
79    /// discord.js counterpart: `GuildInviteManager#create` / `TextChannel#createInvite`.
80    ///
81    /// # Errors
82    ///
83    /// Returns the REST error if the request failed (it needs `CREATE_INSTANT_INVITE`).
84    pub async fn create(
85        self,
86        channel_id: ChannelId,
87        body: &CreateChannelInvite,
88        reason: Option<&str>,
89    ) -> Result<InviteWithMetadata, Error> {
90        self.ctx
91            .rest()
92            .create_channel_invite(channel_id, body, reason)
93            .await
94    }
95
96    /// The invites to a channel ([Get Channel Invites](djs_rest::Rest::get_channel_invites)).
97    ///
98    /// discord.js counterpart: `TextChannel#fetchInvites`.
99    ///
100    /// # Errors
101    ///
102    /// Returns the REST error if the request failed (it needs `MANAGE_CHANNELS`).
103    pub async fn list_channel(
104        self,
105        channel_id: ChannelId,
106    ) -> Result<Collection<String, InviteWithMetadata>, Error> {
107        let invites = self.ctx.rest().get_channel_invites(channel_id).await?;
108        Ok(by_code(invites))
109    }
110
111    /// The invites to a guild ([Get Guild Invites](djs_rest::Rest::get_guild_invites)).
112    ///
113    /// discord.js counterpart: `GuildInviteManager#fetch()`.
114    ///
115    /// # Errors
116    ///
117    /// Returns the REST error if the request failed (it needs `MANAGE_GUILD` or
118    /// `VIEW_AUDIT_LOG`).
119    pub async fn list_guild(
120        self,
121        guild_id: GuildId,
122    ) -> Result<Collection<String, InviteWithMetadata>, Error> {
123        let invites = self.ctx.rest().get_guild_invites(guild_id).await?;
124        Ok(by_code(invites))
125    }
126}
127
128fn by_code(invites: Vec<InviteWithMetadata>) -> Collection<String, InviteWithMetadata> {
129    invites
130        .into_iter()
131        .map(|invite| (invite.code.to_string(), invite))
132        .collect()
133}