twilight_http/request/channel/invite/create_invite.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
use crate::{
client::Client,
error::Error,
request::{self, AuditLogReason, Request, TryIntoRequest},
response::{Response, ResponseFuture},
routing::Route,
};
use serde::Serialize;
use std::future::IntoFuture;
use twilight_model::{
guild::invite::{Invite, TargetType},
id::{
marker::{ApplicationMarker, ChannelMarker, UserMarker},
Id,
},
};
use twilight_validate::request::{
audit_reason as validate_audit_reason, invite_max_age as validate_invite_max_age,
invite_max_uses as validate_invite_max_uses, ValidationError,
};
#[derive(Serialize)]
struct CreateInviteFields {
#[serde(skip_serializing_if = "Option::is_none")]
max_age: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
max_uses: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
temporary: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
target_application_id: Option<Id<ApplicationMarker>>,
#[serde(skip_serializing_if = "Option::is_none")]
target_user_id: Option<Id<UserMarker>>,
#[serde(skip_serializing_if = "Option::is_none")]
target_type: Option<TargetType>,
#[serde(skip_serializing_if = "Option::is_none")]
unique: Option<bool>,
}
/// Create an invite, with options.
///
/// Requires the [`CREATE_INVITE`] permission.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let channel_id = Id::new(123);
/// let invite = client.create_invite(channel_id).max_uses(3).await?;
/// # Ok(()) }
/// ```
///
/// [`CREATE_INVITE`]: twilight_model::guild::Permissions::CREATE_INVITE
#[must_use = "requests must be configured and executed"]
pub struct CreateInvite<'a> {
channel_id: Id<ChannelMarker>,
fields: Result<CreateInviteFields, ValidationError>,
http: &'a Client,
reason: Result<Option<&'a str>, ValidationError>,
}
impl<'a> CreateInvite<'a> {
pub(crate) const fn new(http: &'a Client, channel_id: Id<ChannelMarker>) -> Self {
Self {
channel_id,
fields: Ok(CreateInviteFields {
max_age: None,
max_uses: None,
temporary: None,
target_application_id: None,
target_user_id: None,
target_type: None,
unique: None,
}),
http,
reason: Ok(None),
}
}
/// Set the maximum age for an invite.
///
/// If no age is specified, Discord sets the age to 86400 seconds, or 24 hours.
/// Set to 0 to never expire.
///
/// # Examples
///
/// Create an invite for a channel with a maximum of 1 use and an age of 1
/// hour:
///
/// ```no_run
/// use std::env;
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new(env::var("DISCORD_TOKEN")?);
/// let invite = client
/// .create_invite(Id::new(1))
/// .max_age(60 * 60)
/// .await?
/// .model()
/// .await?;
///
/// println!("invite code: {}", invite.code);
/// # Ok(()) }
/// ```
///
/// # Errors
///
/// Returns an error of type [`InviteMaxAge`] if the age is invalid.
///
/// [`InviteMaxAge`]: twilight_validate::request::ValidationErrorType::InviteMaxAge
pub fn max_age(mut self, max_age: u32) -> Self {
self.fields = self.fields.and_then(|mut fields| {
validate_invite_max_age(max_age)?;
fields.max_age = Some(max_age);
Ok(fields)
});
self
}
/// Set the maximum uses for an invite, or 0 for infinite.
///
/// Discord defaults this to 0, or infinite.
///
/// # Examples
///
/// Create an invite for a channel with a maximum of 5 uses:
///
/// ```no_run
/// use std::env;
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new(env::var("DISCORD_TOKEN")?);
/// let invite = client
/// .create_invite(Id::new(1))
/// .max_uses(5)
/// .await?
/// .model()
/// .await?;
///
/// println!("invite code: {}", invite.code);
/// # Ok(()) }
/// ```
///
/// # Errors
///
/// Returns an error of type [`InviteMaxUses`] if the uses is invalid.
///
/// [`InviteMaxUses`]: twilight_validate::request::ValidationErrorType::InviteMaxUses
pub fn max_uses(mut self, max_uses: u16) -> Self {
self.fields = self.fields.and_then(|mut fields| {
validate_invite_max_uses(max_uses)?;
fields.max_uses = Some(max_uses);
Ok(fields)
});
self
}
/// Set the target application ID for this invite.
///
/// This only works if [`target_type`] is set to [`TargetType::EmbeddedApplication`].
///
/// [`target_type`]: Self::target_type
pub fn target_application_id(mut self, target_application_id: Id<ApplicationMarker>) -> Self {
if let Ok(fields) = self.fields.as_mut() {
fields.target_application_id = Some(target_application_id);
}
self
}
/// Set the target user id for this invite.
pub fn target_user_id(mut self, target_user_id: Id<UserMarker>) -> Self {
if let Ok(fields) = self.fields.as_mut() {
fields.target_user_id = Some(target_user_id);
}
self
}
/// Set the target type for this invite.
pub fn target_type(mut self, target_type: TargetType) -> Self {
if let Ok(fields) = self.fields.as_mut() {
fields.target_type = Some(target_type);
}
self
}
/// Specify true if the invite should grant temporary membership.
///
/// Defaults to false.
pub fn temporary(mut self, temporary: bool) -> Self {
if let Ok(fields) = self.fields.as_mut() {
fields.temporary = Some(temporary);
}
self
}
/// Specify true if the invite should be unique. Defaults to false.
///
/// If true, don't try to reuse a similar invite (useful for creating many
/// unique one time use invites). See [Discord Docs/Create Channel Invite].
///
/// [Discord Docs/Create Channel Invite]: https://discord.com/developers/docs/resources/channel#create-channel-invite
pub fn unique(mut self, unique: bool) -> Self {
if let Ok(fields) = self.fields.as_mut() {
fields.unique = Some(unique);
}
self
}
}
impl<'a> AuditLogReason<'a> for CreateInvite<'a> {
fn reason(mut self, reason: &'a str) -> Self {
self.reason = validate_audit_reason(reason).and(Ok(Some(reason)));
self
}
}
impl IntoFuture for CreateInvite<'_> {
type Output = Result<Response<Invite>, Error>;
type IntoFuture = ResponseFuture<Invite>;
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 CreateInvite<'_> {
fn try_into_request(self) -> Result<Request, Error> {
let fields = self.fields.map_err(Error::validation)?;
let mut request = Request::builder(&Route::CreateInvite {
channel_id: self.channel_id.get(),
})
.json(&fields);
if let Some(reason) = self.reason.map_err(Error::validation)? {
request = request.headers(request::audit_header(reason)?);
}
request.build()
}
}
#[cfg(test)]
mod tests {
use super::CreateInvite;
use crate::Client;
use std::error::Error;
use twilight_model::id::Id;
#[test]
fn max_age() -> Result<(), Box<dyn Error>> {
let client = Client::new("foo".to_owned());
let mut builder = CreateInvite::new(&client, Id::new(1)).max_age(0);
assert_eq!(Some(0), builder.fields.as_ref().unwrap().max_age);
builder = builder.max_age(604_800);
assert_eq!(Some(604_800), builder.fields.as_ref().unwrap().max_age);
builder = builder.max_age(604_801);
assert!(builder.fields.is_err());
Ok(())
}
#[test]
fn max_uses() -> Result<(), Box<dyn Error>> {
let client = Client::new("foo".to_owned());
let mut builder = CreateInvite::new(&client, Id::new(1)).max_uses(0);
assert_eq!(Some(0), builder.fields.as_ref().unwrap().max_uses);
builder = builder.max_uses(100);
assert_eq!(Some(100), builder.fields.as_ref().unwrap().max_uses);
builder = builder.max_uses(101);
assert!(builder.fields.is_err());
Ok(())
}
}