Skip to main content

lamprey_common/v1/types/
invite.rs

1use std::fmt;
2
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5
6#[cfg(feature = "utoipa")]
7use utoipa::ToSchema;
8
9#[cfg(feature = "validator")]
10use validator::Validate;
11
12use crate::v1::types::util::Time;
13use crate::v1::types::{ChannelId, PaginationKey, Role, RoleId, RoomId, UserId};
14
15#[cfg(feature = "serde")]
16use crate::v1::types::util::deserialize_sorted;
17
18use super::{Channel, Room, User};
19
20/// a short, unique identifier. knowing the code grants access to the invite's target.
21#[derive(Debug, Hash, Clone, PartialEq, Eq, PartialOrd, Ord)]
22#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
23#[cfg_attr(feature = "utoipa", derive(ToSchema), schema(examples("a1b2c3")))]
24pub struct InviteCode(pub String);
25
26#[derive(Debug, Clone)]
27#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
28#[cfg_attr(feature = "utoipa", derive(ToSchema))]
29pub struct Invite {
30    /// the invite code for this invite
31    pub code: InviteCode,
32
33    /// where this invite leads
34    pub target: InviteTarget,
35
36    /// the user who created this invite
37    // #[deprecated = "use creator_id"]
38    pub creator: User,
39
40    /// the id of the user who created this invite
41    pub creator_id: UserId,
42
43    /// the time when this invite was created
44    pub created_at: Time,
45
46    /// the time when this invite will stop working
47    pub expires_at: Option<Time>,
48
49    /// a description for this invite
50    pub description: Option<String>,
51
52    /// if this invite's code is custom (instead of random)
53    // TODO(#263): vanity (custom) invite codes
54    pub is_vanity: bool,
55    // TODO: maybe enable/disable invites without revoking them?
56    // pub enabled: bool,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
61#[cfg_attr(feature = "utoipa", derive(ToSchema))]
62pub struct InviteWithMetadata {
63    /// the maximum number of times this invite can be used
64    pub max_uses: Option<u16>,
65
66    /// the number of time this invite has been used
67    pub uses: u64,
68
69    /// the invite this metadata is for
70    #[cfg_attr(feature = "serde", serde(flatten))]
71    pub invite: Invite,
72}
73
74/// where this invite leads
75#[derive(Debug, Clone)]
76#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
77#[cfg_attr(feature = "utoipa", derive(ToSchema))]
78#[cfg_attr(feature = "serde", serde(tag = "type"))]
79pub enum InviteTarget {
80    /// join a room
81    Room {
82        /// the room itself
83        room: Room,
84
85        /// which channel in the room to open
86        channel: Option<Box<Channel>>,
87
88        /// which roles to apply when accepting the invite
89        roles: Vec<Role>,
90    },
91
92    /// join a group dm
93    Gdm { channel: Box<Channel> },
94
95    /// register on this server
96    Server,
97
98    /// add this user as a friend
99    User { user: Box<User> },
100}
101
102/// the type and id of this invite's target
103#[derive(Debug, Clone, PartialEq, Eq)]
104#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
105#[cfg_attr(feature = "utoipa", derive(ToSchema))]
106#[cfg_attr(feature = "serde", serde(tag = "type"))]
107pub enum InviteTargetId {
108    Room {
109        room_id: RoomId,
110        channel_id: Option<ChannelId>,
111
112        #[cfg_attr(
113            feature = "serde",
114            serde(default, deserialize_with = "deserialize_sorted")
115        )]
116        role_ids: Vec<RoleId>,
117    },
118
119    Gdm {
120        channel_id: ChannelId,
121    },
122
123    Server,
124
125    User {
126        user_id: UserId,
127    },
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
131#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
132#[cfg_attr(feature = "utoipa", derive(ToSchema))]
133pub struct InvitePatch {
134    /// a description for this invite
135    pub description: Option<Option<String>>,
136
137    /// the time when this invite will stop working
138    pub expires_at: Option<Option<Time>>,
139
140    /// the maximum number of times this invite can be used
141    /// be sure to account for existing `uses` and `max_uses` when patching
142    pub max_uses: Option<Option<u16>>,
143
144    // can only be used with room invites
145    pub role_ids: Option<Vec<RoleId>>,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
149#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
150#[cfg_attr(feature = "utoipa", derive(ToSchema))]
151#[cfg_attr(feature = "validator", derive(Validate))]
152pub struct InviteCreate {
153    /// a description for this invite
154    #[cfg_attr(feature = "utoipa", schema(required = false))]
155    pub description: Option<String>,
156
157    /// the time when this invite will stop working
158    #[cfg_attr(feature = "utoipa", schema(required = false))]
159    pub expires_at: Option<Time>,
160
161    /// the maximum number of times this invite can be used
162    /// be sure to account for existing `uses` and `max_uses` when patching
163    #[cfg_attr(feature = "utoipa", schema(required = false))]
164    pub max_uses: Option<u16>,
165
166    /// which roles to apply when accepting the invite
167    #[cfg_attr(feature = "serde", serde(default))]
168    pub role_ids: Option<Vec<RoleId>>,
169}
170
171impl fmt::Display for InviteCode {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        write!(f, "{}", self.0)
174    }
175}
176
177impl PaginationKey for InviteCode {
178    fn min() -> Self {
179        InviteCode("".to_string())
180    }
181
182    fn max() -> Self {
183        InviteCode("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ".to_string())
184    }
185}
186
187impl From<InviteWithMetadata> for Invite {
188    fn from(value: InviteWithMetadata) -> Self {
189        value.invite
190    }
191}
192
193impl From<InviteTarget> for InviteTargetId {
194    fn from(value: InviteTarget) -> Self {
195        match value {
196            InviteTarget::Room {
197                room,
198                channel,
199                roles,
200            } => InviteTargetId::Room {
201                room_id: room.id,
202                channel_id: channel.map(|c| c.id),
203                role_ids: roles.into_iter().map(|r| r.id).collect(),
204            },
205            InviteTarget::Gdm { channel } => InviteTargetId::Gdm {
206                channel_id: channel.id,
207            },
208            InviteTarget::Server => InviteTargetId::Server,
209            InviteTarget::User { user } => InviteTargetId::User { user_id: user.id },
210        }
211    }
212}
213
214impl InviteWithMetadata {
215    pub fn strip_metadata(self) -> Invite {
216        self.into()
217    }
218
219    pub fn is_dead(&self) -> bool {
220        if let Some(max_uses) = self.max_uses {
221            if self.uses >= max_uses as u64 {
222                return true;
223            }
224        }
225        if let Some(ref expires_at) = self.invite.expires_at {
226            if *expires_at < Time::now_utc() {
227                return true;
228            }
229        }
230        false
231    }
232}
233
234impl Invite {
235    pub fn new(
236        code: InviteCode,
237        target: InviteTarget,
238        creator: User,
239        creator_id: UserId,
240        created_at: Time,
241        expires_at: Option<Time>,
242        description: Option<String>,
243        is_vanity: bool,
244    ) -> Self {
245        Self {
246            code,
247            target,
248            creator,
249            creator_id,
250            created_at,
251            expires_at,
252            description,
253            is_vanity,
254        }
255    }
256}
257
258impl PartialEq for Invite {
259    fn eq(&self, other: &Self) -> bool {
260        self.code == other.code
261    }
262}
263
264impl Eq for Invite {}