djs_model/rest/lobby.rs
1//! Bodies and queries of the [lobby endpoints](https://docs.discord.com/developers/resources/lobby).
2//!
3//! Metadata are string key/value pairs of at most 1000 characters in total.
4
5use core::fmt;
6use std::collections::BTreeMap;
7
8use compact_str::CompactString;
9use serde::Serialize;
10
11use crate::{id::UserId, lobby::LobbyMemberFlags, message::MessageFlags, util::Patch};
12
13/// String key/value pairs set by the app on a lobby, a member or a message.
14pub type LobbyMetadata = BTreeMap<CompactString, CompactString>;
15
16/// The body of [Create Lobby](https://docs.discord.com/developers/resources/lobby#create-lobby).
17///
18/// Social SDK clients cannot join or leave lobbies created this way.
19///
20/// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
21///
22/// # Examples
23///
24/// ```
25/// use djs_model::{
26/// id::UserId,
27/// rest::{CreateLobby, LobbyMemberData},
28/// };
29///
30/// let mut body = CreateLobby::default();
31/// body.metadata.insert("map".into(), "harbor".into());
32/// body.members = vec![LobbyMemberData::new(UserId::new(7))];
33/// body.idle_timeout_seconds = Some(600);
34/// assert_eq!(
35/// serde_json::to_string(&body)?,
36/// r#"{"metadata":{"map":"harbor"},"members":[{"id":"7"}],"idle_timeout_seconds":600}"#
37/// );
38/// # Ok::<(), serde_json::Error>(())
39/// ```
40#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
41#[non_exhaustive]
42pub struct CreateLobby {
43 /// The lobby's metadata.
44 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
45 pub metadata: LobbyMetadata,
46 /// Users to add (up to 25).
47 #[serde(skip_serializing_if = "Vec::is_empty")]
48 pub members: Vec<LobbyMemberData>,
49 /// How many seconds an idle lobby lives before it is shut down (5 to 604 800, seven
50 /// days).
51 #[serde(skip_serializing_if = "Option::is_none")]
52 pub idle_timeout_seconds: Option<u32>,
53}
54
55/// A member in the body of [Create Lobby](https://docs.discord.com/developers/resources/lobby#create-lobby)
56/// or [Modify Lobby](https://docs.discord.com/developers/resources/lobby#modify-lobby), or one
57/// to [upsert](BulkLobbyMember::upsert) with Bulk Update Lobby Members (D-134).
58///
59/// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
60#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
61#[non_exhaustive]
62pub struct LobbyMemberData {
63 /// The user.
64 pub id: UserId,
65 /// The member's metadata; `Some` of an empty map clears it.
66 #[serde(skip_serializing_if = "Option::is_none")]
67 pub metadata: Option<LobbyMetadata>,
68 /// The member's flags.
69 #[serde(skip_serializing_if = "Option::is_none")]
70 pub flags: Option<LobbyMemberFlags>,
71 /// An extra display name (1-80 characters), e.g. an in-game character name;
72 /// [`Patch::Keep`] keeps a member's current one, [`Patch::Clear`] removes it.
73 #[serde(skip_serializing_if = "Patch::is_keep")]
74 pub additional_name: Patch<CompactString>,
75}
76
77impl LobbyMemberData {
78 /// The member `id`, without metadata, flags or additional name.
79 ///
80 /// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
81 #[must_use]
82 pub const fn new(id: UserId) -> Self {
83 Self {
84 id,
85 metadata: None,
86 flags: None,
87 additional_name: Patch::Keep,
88 }
89 }
90}
91
92/// The body of [Create or Join Lobby](https://docs.discord.com/developers/resources/lobby#create-or-join-lobby).
93///
94/// The secret is redacted in the `Debug` output: anyone who knows it can join the lobby.
95///
96/// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
97#[derive(Clone, PartialEq, Eq, Serialize)]
98#[non_exhaustive]
99pub struct CreateOrJoinLobby {
100 /// Identifies the lobby among the application's lobbies (up to 250 characters).
101 pub secret: CompactString,
102 /// How many seconds an idle lobby lives before it is shut down (5 to 604 800).
103 #[serde(skip_serializing_if = "Option::is_none")]
104 pub idle_timeout_seconds: Option<u32>,
105 /// Replaces the lobby's metadata.
106 #[serde(skip_serializing_if = "Option::is_none")]
107 pub lobby_metadata: Option<LobbyMetadata>,
108 /// Sets the calling user's member metadata.
109 #[serde(skip_serializing_if = "Option::is_none")]
110 pub member_metadata: Option<LobbyMetadata>,
111}
112
113impl CreateOrJoinLobby {
114 /// Creates the lobby with `secret`, or joins it if it exists.
115 ///
116 /// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
117 #[must_use]
118 pub fn new(secret: impl Into<CompactString>) -> Self {
119 Self {
120 secret: secret.into(),
121 idle_timeout_seconds: None,
122 lobby_metadata: None,
123 member_metadata: None,
124 }
125 }
126}
127
128impl fmt::Debug for CreateOrJoinLobby {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 f.debug_struct("CreateOrJoinLobby")
131 .field("secret", &"<redacted>")
132 .field("idle_timeout_seconds", &self.idle_timeout_seconds)
133 .field("lobby_metadata", &self.lobby_metadata)
134 .field("member_metadata", &self.member_metadata)
135 .finish()
136 }
137}
138
139/// The body of [Modify Lobby](https://docs.discord.com/developers/resources/lobby#modify-lobby).
140///
141/// Every field is optional.
142///
143/// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
144#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
145#[non_exhaustive]
146pub struct ModifyLobby {
147 /// Replaces the lobby's metadata.
148 #[serde(skip_serializing_if = "Option::is_none")]
149 pub metadata: Option<LobbyMetadata>,
150 /// Replaces the members (up to 25): members not in the list are removed.
151 #[serde(skip_serializing_if = "Option::is_none")]
152 pub members: Option<Vec<LobbyMemberData>>,
153 /// How many seconds an idle lobby lives before it is shut down (5 to 604 800).
154 #[serde(skip_serializing_if = "Option::is_none")]
155 pub idle_timeout_seconds: Option<u32>,
156}
157
158/// The body of [Add a Member to a Lobby](https://docs.discord.com/developers/resources/lobby#add-a-member-to-a-lobby)
159/// (D-134). The user is in the path; for a member already in the lobby, the fields that are
160/// set are updated.
161///
162/// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
163#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
164#[non_exhaustive]
165pub struct AddLobbyMember {
166 /// The member's metadata.
167 #[serde(skip_serializing_if = "Option::is_none")]
168 pub metadata: Option<LobbyMetadata>,
169 /// The member's flags.
170 #[serde(skip_serializing_if = "Option::is_none")]
171 pub flags: Option<LobbyMemberFlags>,
172 /// An extra display name (1-80 characters); [`Patch::Clear`] removes it.
173 #[serde(skip_serializing_if = "Patch::is_keep")]
174 pub additional_name: Patch<CompactString>,
175}
176
177/// One entry of [Bulk Update Lobby Members](https://docs.discord.com/developers/resources/lobby#bulk-update-lobby-members):
178/// a member to add or update, or one to remove (D-134).
179///
180/// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
181///
182/// # Examples
183///
184/// ```
185/// use djs_model::{
186/// id::UserId,
187/// rest::{BulkLobbyMember, LobbyMemberData},
188/// util::Patch,
189/// };
190///
191/// let mut ferris = LobbyMemberData::new(UserId::new(7));
192/// ferris.additional_name = Patch::Set("Ferris".into());
193/// let body = [
194/// BulkLobbyMember::upsert(ferris),
195/// BulkLobbyMember::remove(UserId::new(8)),
196/// ];
197/// assert_eq!(
198/// serde_json::to_string(&body)?,
199/// r#"[{"id":"7","additional_name":"Ferris"},{"id":"8","remove_member":true}]"#
200/// );
201/// # Ok::<(), serde_json::Error>(())
202/// ```
203#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
204#[non_exhaustive]
205pub struct BulkLobbyMember {
206 /// The member and the fields to set.
207 #[serde(flatten)]
208 pub member: LobbyMemberData,
209 /// Whether the member is removed instead of added or updated.
210 #[serde(skip_serializing_if = "core::ops::Not::not")]
211 pub remove_member: bool,
212}
213
214impl BulkLobbyMember {
215 /// Adds `member`, or updates it if the user is already in the lobby.
216 ///
217 /// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
218 #[must_use]
219 pub const fn upsert(member: LobbyMemberData) -> Self {
220 Self {
221 member,
222 remove_member: false,
223 }
224 }
225
226 /// Removes the user `id` from the lobby.
227 ///
228 /// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
229 #[must_use]
230 pub const fn remove(id: UserId) -> Self {
231 Self {
232 member: LobbyMemberData::new(id),
233 remove_member: true,
234 }
235 }
236}
237
238/// The body of [Send Lobby Message](https://docs.discord.com/developers/resources/lobby#send-lobby-message).
239///
240/// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
241#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
242#[non_exhaustive]
243pub struct SendLobbyMessage {
244 /// The text (not empty).
245 pub content: CompactString,
246 /// Metadata delivered with the message to Social SDK clients (not kept on the linked
247 /// channel's copy).
248 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
249 pub metadata: LobbyMetadata,
250 /// Message flags; only those the Social SDK may set are accepted.
251 #[serde(skip_serializing_if = "Option::is_none")]
252 pub flags: Option<MessageFlags>,
253}
254
255impl SendLobbyMessage {
256 /// A message with `content`.
257 ///
258 /// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
259 #[must_use]
260 pub fn new(content: impl Into<CompactString>) -> Self {
261 Self {
262 content: content.into(),
263 metadata: BTreeMap::new(),
264 flags: None,
265 }
266 }
267}
268
269/// The query of [Get Lobby Messages](https://docs.discord.com/developers/resources/lobby#get-lobby-messages).
270///
271/// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
272#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
273#[non_exhaustive]
274pub struct GetLobbyMessages {
275 /// How many of the most recent messages (1-200; Discord's default is 50).
276 pub limit: Option<u8>,
277}
278
279#[cfg(test)]
280mod tests {
281 use super::*;
282
283 #[test]
284 fn member_bodies() {
285 let add = AddLobbyMember {
286 flags: Some(LobbyMemberFlags::CAN_LINK_LOBBY),
287 additional_name: Patch::Clear,
288 ..AddLobbyMember::default()
289 };
290 assert_eq!(
291 serde_json::to_string(&add).unwrap(),
292 r#"{"flags":1,"additional_name":null}"#
293 );
294 let mut join = CreateOrJoinLobby::new("lobby-secret");
295 join.member_metadata = Some(LobbyMetadata::new());
296 assert_eq!(
297 serde_json::to_string(&join).unwrap(),
298 r#"{"secret":"lobby-secret","member_metadata":{}}"#
299 );
300 assert!(!format!("{join:?}").contains("lobby-secret"));
301 }
302}