1use std::{future::Future, sync::Arc};
4
5use djs_cache::{Backend, CacheView, CachedMessage, CachedUser};
6use djs_model::{
7 channel::Channel,
8 id::UserId,
9 rest::{CreateDm, CreateMessage},
10};
11use djs_rest::Error;
12
13use super::Fetch;
14use crate::Context;
15
16#[derive(Debug)]
20pub struct UserManager<'a, B: Backend> {
21 ctx: &'a Context<B>,
22}
23
24impl<B: Backend> Clone for UserManager<'_, B> {
25 fn clone(&self) -> Self {
26 *self
27 }
28}
29
30impl<B: Backend> Copy for UserManager<'_, B> {}
31
32impl<'a, B: Backend> UserManager<'a, B> {
33 pub(crate) const fn new(ctx: &'a Context<B>) -> Self {
34 Self { ctx }
35 }
36
37 #[must_use]
41 pub fn cache(self) -> Option<CacheView<'a, UserId, CachedUser, B>> {
42 self.ctx.cache().map(djs_cache::Cache::users)
43 }
44
45 pub fn fetch(
54 self,
55 user_id: UserId,
56 ) -> Fetch<Arc<CachedUser>, impl Future<Output = Result<Arc<CachedUser>, Error>> + Send + 'a>
57 {
58 let cached = self.ctx.ops().user(user_id);
59 let ctx = self.ctx;
60 Fetch::new(cached, async move {
61 let user = ctx.rest().get_user(user_id).await?;
62 Ok(ctx.store_user(&user))
63 })
64 }
65
66 pub async fn create_dm(self, user_id: UserId) -> Result<Arc<Channel>, Error> {
75 let channel = self.ctx.rest().create_dm(&CreateDm::new(user_id)).await?;
76 Ok(self.ctx.store_channel(&channel))
77 }
78
79 pub fn send(
88 self,
89 user_id: UserId,
90 body: impl Into<CreateMessage>,
91 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send + 'a {
92 let body = body.into();
93 async move {
94 let channel = self.create_dm(user_id).await?;
95 self.ctx.messages(channel.id()).send(body).await
96 }
97 }
98}