Skip to content

Commit

Permalink
🐛 Corrected some errors in data structure handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
langyo committed Oct 11, 2024
1 parent c8a94b3 commit 39c2b7f
Show file tree
Hide file tree
Showing 5 changed files with 157 additions and 33 deletions.
72 changes: 61 additions & 11 deletions packages/client/src/pages/users.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use std::collections::HashMap;

use stylist::{css, yew::styled_component};
use yew::prelude::*;

use crate::components::{icons, GlobalSkeleton};
use _functions::{
models::user::{delete, list},
models::user::{count, delete, list},
utils::global_state::GlobalStateContext,
};
use _types::request::Permission;
Expand All @@ -17,15 +15,19 @@ pub fn Users() -> HtmlResult {
let t = global_state.language.to_config().unwrap();

let is_downloading = use_state(|| true);
let user_list = use_state(HashMap::new);
let user_count = use_state(|| 0);
let user_list = use_state(Vec::new);
use_effect_with((), {
let is_downloading = is_downloading.clone();
let user_count = user_count.clone();
let user_list = user_list.clone();
|_| {
wasm_bindgen_futures::spawn_local(async move {
let user_count = user_count.clone();
let user_list = user_list.clone();
let ret = list().await.unwrap();
user_list.set(ret);

user_count.set(count().await.unwrap());
user_list.set(list(None, None).await.unwrap());

is_downloading.set(false);
});
Expand All @@ -49,7 +51,7 @@ pub fn Users() -> HtmlResult {
justify-content: center;
")}>
{
user_list.iter().map(|(name, item)| html! {
user_list.iter().map(|item| html! {
<div class={css!("
width: 80%;
height: 64px;
Expand Down Expand Up @@ -85,7 +87,7 @@ pub fn Users() -> HtmlResult {
align-items: center;
justify-content: center;
")}>
{name.clone()}
{item.name.clone()}

{
if item.permission == Permission::Manager {
Expand Down Expand Up @@ -136,11 +138,11 @@ pub fn Users() -> HtmlResult {
box-shadow: var(--shadow-half);
")}
onclick={
let name = name.clone();
let email = item.email.clone();
Callback::from(move |_| {
let name = name.clone();
let email = email.clone();
wasm_bindgen_futures::spawn_local(async move {
if delete(name).await.is_ok() {
if delete(email).await.is_ok() {
gloo::utils::window().location().reload().unwrap();
} else {
gloo::dialogs::alert("Failed to delete user.");
Expand All @@ -156,6 +158,54 @@ pub fn Users() -> HtmlResult {
}).collect::<Html>()
}

<button
class={classes!(css!("
width: 128px;
height: 32px;
margin: 16px;
font-size: 16px;
font-weight: bolder;
text-align: center;
"), {
if (*user_count) <= (*user_list).len() {
css!("
background: var(--color-dark-less);
pointer-events: none;
")
} else {
css!("")
}
})}
onclick={
let user_count = user_count.clone();
let user_list = user_list.clone();

Callback::from(move |_| {
let user_count = user_count.clone();
let user_list = user_list.clone();

wasm_bindgen_futures::spawn_local(async move {
let user_count = user_count.clone();
let user_list = user_list.clone();

let current_count_raw = count().await.unwrap();
let current_list_raw = (*user_list).clone();

user_count.set(current_count_raw);
if current_count_raw > current_list_raw.len() {
user_list.set(list(
Some(current_list_raw.len()),
Some(100),
).await.unwrap());
}
});
})
}
>
{ t.images.load_more }
</button>

<button
class={css!("
width: 64px;
Expand Down
62 changes: 49 additions & 13 deletions packages/database/src/functions/backend/media.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,34 +34,40 @@ pub async fn get(env: RouteEnv, id: String) -> Result<Option<Model>> {
}
}

pub async fn count(env: RouteEnv) -> Result<u64> {
pub async fn count(env: RouteEnv) -> Result<usize> {
let count = env
.kv
.global_config
.get(GLOBAL_CONFIG_MEDIA_COUNT_KEY.to_string())
.await?
.map(|x| x.parse::<u64>().unwrap_or(0))
.map(|x| x.parse::<usize>().unwrap_or(0))
.unwrap_or(0);

Ok(count)
}

pub async fn list(env: RouteEnv, offset: usize, limit: usize) -> Result<Vec<Model>> {
let ret = env
let keys = env
.kv
.images
.list_by_prefix("".to_string(), Some(limit), Some(offset.to_string()))
.await?
.into_iter()
.map(|x| {
serde_json::from_str(&x)
.map_err(|err| anyhow!("Failed to parse JSON from string: {}", err))
.await?;
let values = keys
.iter()
.map(|key| async {
let value = env
.kv
.images
.get(key.clone())
.await?
.ok_or(anyhow!("Key not found"))?;
Ok(serde_json::from_str(&value)?)
})
.collect::<Vec<Result<Model>>>()
.into_iter()
.collect::<Result<Vec<Model>>>()?;
.collect::<Vec<_>>();
let values: Vec<Result<Model>> = futures::future::join_all(values).await;
let values = values.into_iter().collect::<Result<Vec<Model>>>()?;

Ok(ret)
Ok(values)
}

pub async fn set(
Expand All @@ -87,7 +93,7 @@ pub async fn set(

// Check if the image is already uploaded
ensure!(
env.kv.images.get(db_key.clone()).await?.is_some(),
env.kv.images.get(db_key.clone()).await?.is_none(),
"Image already uploaded"
);

Expand Down Expand Up @@ -158,6 +164,21 @@ pub async fn set(
.set(db_key.clone(), serde_json::to_string(&value)?)
.await?;

let count = env
.kv
.global_config
.get(GLOBAL_CONFIG_MEDIA_COUNT_KEY.to_string())
.await?
.map(|x| x.parse::<usize>().unwrap_or(0))
.unwrap_or(0);
env.kv
.global_config
.set(
GLOBAL_CONFIG_MEDIA_COUNT_KEY.to_string(),
(count + 1).to_string(),
)
.await?;

std::thread::spawn({
let db_key = db_key.clone();
let hash = hash.clone();
Expand Down Expand Up @@ -215,5 +236,20 @@ pub fn generate_thumbnail(hash: impl ToString, data: Bytes) -> Result<Bytes> {
pub async fn delete(env: RouteEnv, id: String) -> Result<()> {
env.kv.images.delete(id).await?;

let count = env
.kv
.global_config
.get(GLOBAL_CONFIG_MEDIA_COUNT_KEY.to_string())
.await?
.map(|x| x.parse::<usize>().unwrap_or(0))
.unwrap_or(0);
env.kv
.global_config
.set(
GLOBAL_CONFIG_MEDIA_COUNT_KEY.to_string(),
(count - 1).to_string(),
)
.await?;

Ok(())
}
4 changes: 2 additions & 2 deletions packages/database/src/functions/backend/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ pub async fn get(env: RouteEnv, email: String) -> Result<Option<Model>> {
Ok(ret)
}

pub async fn count(env: RouteEnv) -> Result<u64> {
let count = Entity::find().count(&**env.sql).await?;
pub async fn count(env: RouteEnv) -> Result<usize> {
let count = Entity::find().count(&**env.sql).await? as usize;

Ok(count)
}
Expand Down
10 changes: 6 additions & 4 deletions packages/functions/src/models/user.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::collections::HashMap;

use anyhow::{anyhow, Result};

use reqwest::Client;

use crate::utils::{get_auth_cache, get_host};
use _types::{request::RegisterParams, response::UserBasicInfo};
use _types::{
request::{PageArgs, RegisterParams},
response::UserBasicInfo,
};

pub async fn count() -> Result<usize> {
let token = get_auth_cache()?;
Expand All @@ -22,10 +23,11 @@ pub async fn count() -> Result<usize> {
}
}

pub async fn list() -> Result<HashMap<String, UserBasicInfo>> {
pub async fn list(offset: Option<usize>, limit: Option<usize>) -> Result<Vec<UserBasicInfo>> {
let token = get_auth_cache()?;
let res = Client::new()
.get(format!("{}/api/user/list", get_host()?))
.query(&PageArgs { offset, limit })
.bearer_auth(token.token)
.send()
.await?;
Expand Down
42 changes: 39 additions & 3 deletions packages/types/src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,19 @@ pub static CACHE_DIR: Lazy<PathBuf> = Lazy::new(|| {
path
});
pub static MEDIA_DIR: Lazy<PathBuf> = Lazy::new(|| {
let mut path = CACHE_DIR.clone();
let mut path = {
#[cfg(debug_assertions)]
{
std::env::current_dir().unwrap().join("target/cache")
}
#[cfg(not(debug_assertions))]
{
std::env::var("ROOT_DIR")
.ok()
.map(|dir| Path::new(&dir).to_path_buf().join("cache"))
.expect("ROOT_DIR is not set")
}
};
path.push("media");

// If directory does not exist, create it
Expand All @@ -75,7 +87,19 @@ pub static MEDIA_DIR: Lazy<PathBuf> = Lazy::new(|| {
path
});
pub static MEDIA_CACHE_DIR: Lazy<PathBuf> = Lazy::new(|| {
let mut path = CACHE_DIR.clone();
let mut path = {
#[cfg(debug_assertions)]
{
std::env::current_dir().unwrap().join("target/cache")
}
#[cfg(not(debug_assertions))]
{
std::env::var("ROOT_DIR")
.ok()
.map(|dir| Path::new(&dir).to_path_buf().join("cache"))
.expect("ROOT_DIR is not set")
}
};
path.push("media-cache");

// If directory does not exist, create it
Expand All @@ -86,7 +110,19 @@ pub static MEDIA_CACHE_DIR: Lazy<PathBuf> = Lazy::new(|| {
});

pub static LOG_DIR: Lazy<PathBuf> = Lazy::new(|| {
let mut path = CACHE_DIR.clone();
let mut path = {
#[cfg(debug_assertions)]
{
std::env::current_dir().unwrap().join("target/cache")
}
#[cfg(not(debug_assertions))]
{
std::env::var("ROOT_DIR")
.ok()
.map(|dir| Path::new(&dir).to_path_buf().join("cache"))
.expect("ROOT_DIR is not set")
}
};
path.push("log");

// If directory does not exist, create it
Expand Down

0 comments on commit 39c2b7f

Please sign in to comment.