djs_rs/manager/thread.rs
1//! [`ThreadManager`], [`ThreadMemberManager`] and [`FetchedThreads`] (D-242).
2
3use std::{future::Future, sync::Arc};
4
5use djs_cache::Backend;
6use djs_collection::Collection;
7use djs_model::{
8 channel::{Channel, ThreadMember},
9 id::{ChannelId, UserId},
10 rest::{
11 GetThreadMember, ListArchivedThreads, ListJoinedPrivateArchivedThreads, ListThreadMembers,
12 StartThreadInForumOrMediaChannel, StartThreadWithoutMessage,
13 },
14};
15use djs_rest::Error;
16
17use super::Fetch;
18use crate::Context;
19
20/// A list of threads from Discord: active or archived ones (discord.js: `FetchedThreads`).
21#[derive(Clone, Debug)]
22#[non_exhaustive]
23pub struct FetchedThreads {
24 /// The threads, in Discord's order; they are cached.
25 pub threads: Collection<ChannelId, Arc<Channel>>,
26 /// The bot's own memberships of the threads it joined.
27 pub members: Vec<ThreadMember>,
28 /// Whether more archived threads follow (pass the last thread's archive timestamp as
29 /// `before`); always `false` for active threads.
30 pub has_more: bool,
31}
32
33impl<B: Backend> Context<B> {
34 pub(crate) fn fetched_threads(
35 &self,
36 threads: &[Channel],
37 members: Vec<ThreadMember>,
38 has_more: bool,
39 ) -> FetchedThreads {
40 FetchedThreads {
41 threads: threads
42 .iter()
43 .map(|thread| (thread.id(), self.store_channel(thread)))
44 .collect(),
45 members,
46 has_more,
47 }
48 }
49}
50
51/// The threads of one parent channel: creating them and listing the archived ones.
52/// Returned by [`Context::threads`].
53///
54/// A thread is a channel: edit or delete it through [`Context::channels`]
55/// ([`edit_thread`](super::ChannelManager::edit_thread), [`delete`](super::ChannelManager::delete)),
56/// and list a guild's active threads with
57/// [`GuildChannelManager::list_active_threads`](super::GuildChannelManager::list_active_threads).
58///
59/// discord.js counterpart: `GuildTextThreadManager` / `GuildForumThreadManager`
60/// (`channel.threads`).
61#[derive(Debug)]
62pub struct ThreadManager<'a, B: Backend> {
63 ctx: &'a Context<B>,
64 channel_id: ChannelId,
65}
66
67impl<B: Backend> Clone for ThreadManager<'_, B> {
68 fn clone(&self) -> Self {
69 *self
70 }
71}
72
73impl<B: Backend> Copy for ThreadManager<'_, B> {}
74
75impl<'a, B: Backend> ThreadManager<'a, B> {
76 pub(crate) const fn new(ctx: &'a Context<B>, channel_id: ChannelId) -> Self {
77 Self { ctx, channel_id }
78 }
79
80 /// The parent channel.
81 ///
82 /// discord.js counterpart: `ThreadManager#channel`.
83 #[must_use]
84 pub const fn channel_id(self) -> ChannelId {
85 self.channel_id
86 }
87
88 /// Starts a thread without a message ([Start Thread without
89 /// Message](djs_rest::Rest::start_thread_without_message)); it is cached.
90 ///
91 /// discord.js counterpart: `GuildTextThreadManager#create`.
92 ///
93 /// # Errors
94 ///
95 /// Returns the REST error if the request failed (it needs `CREATE_PUBLIC_THREADS` or
96 /// `CREATE_PRIVATE_THREADS`).
97 pub async fn create(
98 self,
99 body: &StartThreadWithoutMessage,
100 reason: Option<&str>,
101 ) -> Result<Arc<Channel>, Error> {
102 let thread = self
103 .ctx
104 .rest()
105 .start_thread_without_message(self.channel_id, body, reason)
106 .await?;
107 Ok(self.ctx.store_channel(&thread))
108 }
109
110 /// Starts a post in a forum or media channel ([Start Thread in Forum or Media
111 /// Channel](djs_rest::Rest::start_thread_in_forum_or_media_channel)). The thread and its
112 /// starter message (whose ID is the thread's) are cached.
113 ///
114 /// discord.js counterpart: `GuildForumThreadManager#create`.
115 ///
116 /// # Errors
117 ///
118 /// Returns the REST error if the request failed (it needs `SEND_MESSAGES`).
119 pub async fn create_in_forum(
120 self,
121 body: &StartThreadInForumOrMediaChannel,
122 reason: Option<&str>,
123 ) -> Result<Arc<Channel>, Error> {
124 let post = self
125 .ctx
126 .rest()
127 .start_thread_in_forum_or_media_channel(self.channel_id, body, reason)
128 .await?;
129 if let Some(message) = &post.message {
130 self.ctx.store_message(message);
131 }
132 Ok(self.ctx.store_channel(&post.channel))
133 }
134
135 /// Archived public threads, newest first ([List Public Archived
136 /// Threads](djs_rest::Rest::list_public_archived_threads)).
137 ///
138 /// discord.js counterpart: `GuildTextThreadManager#fetchArchived({ type: 'public' })`.
139 ///
140 /// # Errors
141 ///
142 /// Returns the REST error if the request failed (it needs `READ_MESSAGE_HISTORY`).
143 pub async fn list_public_archived(
144 self,
145 query: &ListArchivedThreads,
146 ) -> Result<FetchedThreads, Error> {
147 let list = self
148 .ctx
149 .rest()
150 .list_public_archived_threads(self.channel_id, query)
151 .await?;
152 Ok(self
153 .ctx
154 .fetched_threads(&list.threads, list.members, list.has_more))
155 }
156
157 /// Archived private threads, newest first ([List Private Archived
158 /// Threads](djs_rest::Rest::list_private_archived_threads)).
159 ///
160 /// discord.js counterpart: `GuildTextThreadManager#fetchArchived({ type: 'private' })`.
161 ///
162 /// # Errors
163 ///
164 /// Returns the REST error if the request failed (it needs `READ_MESSAGE_HISTORY` and
165 /// `MANAGE_THREADS`).
166 pub async fn list_private_archived(
167 self,
168 query: &ListArchivedThreads,
169 ) -> Result<FetchedThreads, Error> {
170 let list = self
171 .ctx
172 .rest()
173 .list_private_archived_threads(self.channel_id, query)
174 .await?;
175 Ok(self
176 .ctx
177 .fetched_threads(&list.threads, list.members, list.has_more))
178 }
179
180 /// Archived private threads the bot joined, newest first ([List Joined Private Archived
181 /// Threads](djs_rest::Rest::list_joined_private_archived_threads)).
182 ///
183 /// discord.js counterpart: `GuildTextThreadManager#fetchArchived({ type: 'private',
184 /// fetchAll: false })`.
185 ///
186 /// # Errors
187 ///
188 /// Returns the REST error if the request failed.
189 pub async fn list_joined_private_archived(
190 self,
191 query: &ListJoinedPrivateArchivedThreads,
192 ) -> Result<FetchedThreads, Error> {
193 let list = self
194 .ctx
195 .rest()
196 .list_joined_private_archived_threads(self.channel_id, query)
197 .await?;
198 Ok(self
199 .ctx
200 .fetched_threads(&list.threads, list.members, list.has_more))
201 }
202}
203
204/// The members of one thread. Returned by [`Context::thread_members`].
205///
206/// The cache does not keep thread memberships, so the [`djs-model`](djs_model)
207/// [`ThreadMember`] is returned.
208///
209/// discord.js counterpart: `ThreadMemberManager` (`thread.members`).
210#[derive(Debug)]
211pub struct ThreadMemberManager<'a, B: Backend> {
212 ctx: &'a Context<B>,
213 thread_id: ChannelId,
214}
215
216impl<B: Backend> Clone for ThreadMemberManager<'_, B> {
217 fn clone(&self) -> Self {
218 *self
219 }
220}
221
222impl<B: Backend> Copy for ThreadMemberManager<'_, B> {}
223
224impl<'a, B: Backend> ThreadMemberManager<'a, B> {
225 pub(crate) const fn new(ctx: &'a Context<B>, thread_id: ChannelId) -> Self {
226 Self { ctx, thread_id }
227 }
228
229 /// The thread.
230 ///
231 /// discord.js counterpart: `ThreadMemberManager#thread`.
232 #[must_use]
233 pub const fn thread_id(self) -> ChannelId {
234 self.thread_id
235 }
236
237 /// A user's membership of the thread ([Get Thread
238 /// Member](djs_rest::Rest::get_thread_member)).
239 ///
240 /// discord.js counterpart: `ThreadMemberManager#fetch(member)`.
241 ///
242 /// # Errors
243 ///
244 /// Returns the REST error if the request failed (404 when the user is not a member).
245 pub fn fetch<'r>(
246 self,
247 user_id: UserId,
248 query: &'r GetThreadMember,
249 ) -> Fetch<ThreadMember, impl Future<Output = Result<ThreadMember, Error>> + Send + 'r>
250 where
251 'a: 'r,
252 {
253 let Self { ctx, thread_id } = self;
254 Fetch::new(None, async move {
255 ctx.rest()
256 .get_thread_member(thread_id, user_id, query)
257 .await
258 })
259 }
260
261 /// A page of the thread's members, by user ID ([List Thread
262 /// Members](djs_rest::Rest::list_thread_members); needs the `GUILD_MEMBERS` intent).
263 ///
264 /// discord.js counterpart: `ThreadMemberManager#fetch()`.
265 ///
266 /// # Errors
267 ///
268 /// Returns the REST error if the request failed.
269 pub async fn list(
270 self,
271 query: &ListThreadMembers,
272 ) -> Result<Collection<UserId, ThreadMember>, Error> {
273 let members = self
274 .ctx
275 .rest()
276 .list_thread_members(self.thread_id, query)
277 .await?;
278 Ok(members
279 .into_iter()
280 .filter_map(|member| Some((member.user_id?, member)))
281 .collect())
282 }
283
284 /// Adds a user to the thread ([Add Thread Member](djs_rest::Rest::add_thread_member)).
285 ///
286 /// discord.js counterpart: `ThreadMemberManager#add`.
287 ///
288 /// # Errors
289 ///
290 /// Returns the REST error if the request failed (the thread must not be archived).
291 pub async fn add(self, user_id: UserId) -> Result<(), Error> {
292 self.ctx
293 .rest()
294 .add_thread_member(self.thread_id, user_id)
295 .await
296 }
297
298 /// Removes a user from the thread ([Remove Thread
299 /// Member](djs_rest::Rest::remove_thread_member)).
300 ///
301 /// discord.js counterpart: `ThreadMemberManager#remove`.
302 ///
303 /// # Errors
304 ///
305 /// Returns the REST error if the request failed (it needs `MANAGE_THREADS`, or to be the
306 /// creator of a private thread).
307 pub async fn remove(self, user_id: UserId) -> Result<(), Error> {
308 self.ctx
309 .rest()
310 .remove_thread_member(self.thread_id, user_id)
311 .await
312 }
313
314 /// Makes the bot join the thread ([Join Thread](djs_rest::Rest::join_thread)).
315 ///
316 /// discord.js counterpart: `ThreadChannel#join`.
317 ///
318 /// # Errors
319 ///
320 /// Returns the REST error if the request failed.
321 pub async fn join(self) -> Result<(), Error> {
322 self.ctx.rest().join_thread(self.thread_id).await
323 }
324
325 /// Makes the bot leave the thread ([Leave Thread](djs_rest::Rest::leave_thread)).
326 ///
327 /// discord.js counterpart: `ThreadChannel#leave`.
328 ///
329 /// # Errors
330 ///
331 /// Returns the REST error if the request failed.
332 pub async fn leave(self) -> Result<(), Error> {
333 self.ctx.rest().leave_thread(self.thread_id).await
334 }
335}