use std::sync::Arc;
use crate::{
User,
common::Result,
connection::server::{server_manager::ServerManager, server_routing::ServerRouting},
};
#[derive(Debug)]
pub struct UserManager {
server_manager: Arc<ServerManager>,
}
impl UserManager {
pub(crate) fn new(server_manager: Arc<ServerManager>) -> Self {
Self { server_manager }
}
#[cfg_attr(feature = "sync", doc = "driver.users().contains(username);")]
#[cfg_attr(not(feature = "sync"), doc = "driver.users().contains(username).await;")]
#[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
pub async fn contains(&self, username: impl Into<String>) -> Result<bool> {
let username = username.into();
self.server_manager
.execute(ServerRouting::Auto, move |server_connection| {
let username = username.clone();
async move { server_connection.contains_user(username).await }
})
.await
}
#[cfg_attr(feature = "sync", doc = "driver.users().get(username);")]
#[cfg_attr(not(feature = "sync"), doc = "driver.users().get(username).await;")]
#[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
pub async fn get(&self, username: impl Into<String>) -> Result<Option<User>> {
let username = username.into();
self.server_manager
.execute(ServerRouting::Auto, |server_connection| {
let username = username.clone();
let server_manager = self.server_manager.clone();
async move {
let user_info = server_connection.get_user(username).await?;
Ok(user_info.map(|user_info| User::from_info(user_info, server_manager)))
}
})
.await
}
#[cfg_attr(feature = "sync", doc = "driver.users().get_current();")]
#[cfg_attr(not(feature = "sync"), doc = "driver.users().get_current().await;")]
#[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
pub async fn get_current(&self) -> Result<Option<User>> {
self.get(self.server_manager.username()?).await
}
#[cfg_attr(feature = "sync", doc = "driver.users().all();")]
#[cfg_attr(not(feature = "sync"), doc = "driver.users().all().await;")]
#[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
pub async fn all(&self) -> Result<Vec<User>> {
self.server_manager
.execute(ServerRouting::Auto, |server_connection| {
let server_manager = self.server_manager.clone();
async move {
let user_infos = server_connection.all_users().await?;
Ok(user_infos
.into_iter()
.map(|user_info| User::from_info(user_info, server_manager.clone()))
.collect())
}
})
.await
}
#[cfg_attr(feature = "sync", doc = "driver.users().create(username, password);")]
#[cfg_attr(not(feature = "sync"), doc = "driver.users().create(username, password).await;")]
#[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
pub async fn create(&self, username: impl Into<String>, password: impl Into<String>) -> Result {
let username = username.into();
let password = password.into();
self.server_manager
.execute(ServerRouting::Auto, move |server_connection| {
let username = username.clone();
let password = password.clone();
async move { server_connection.create_user(username, password).await }
})
.await
}
}