From 75854e5965e046fac1071acc568a3a7fd63400de Mon Sep 17 00:00:00 2001 From: MedzikUser Date: Tue, 3 May 2022 10:42:53 +0200 Subject: [PATCH] server (/fs/list): add directory size --- server/src/fs/list.rs | 26 ++++++++++++++++++++++++-- types/src/fs/list.rs | 8 +++++++- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/server/src/fs/list.rs b/server/src/fs/list.rs index 532fc35..b3ee952 100644 --- a/server/src/fs/list.rs +++ b/server/src/fs/list.rs @@ -1,10 +1,12 @@ -use std::fs; +use std::path::PathBuf; +use std::{fs, io}; use crate::fs::validate_path; use axum::{extract::rejection::JsonRejection, Extension, Json}; use axum_auth::AuthBearer; use byte_unit::Byte; use homedisk_database::Database; +use homedisk_types::fs::list::DirInfo; use homedisk_types::{ config::types::Config, errors::{FsError, ServerError}, @@ -13,6 +15,21 @@ use homedisk_types::{ use crate::middleware::{find_user, validate_json, validate_jwt}; +fn dir_size(path: impl Into) -> io::Result { + fn dir_size(mut dir: fs::ReadDir) -> io::Result { + dir.try_fold(0, |acc, file| { + let file = file?; + let size = match file.metadata()? { + data if data.is_dir() => dir_size(fs::read_dir(file.path())?)?, + data => data.len(), + }; + Ok(acc + size) + }) + } + + dir_size(fs::read_dir(path.into())?) +} + pub async fn handle( Extension(db): Extension, Extension(config): Extension, @@ -51,7 +68,12 @@ pub async fn handle( let file_size = Byte::from_bytes(metadata.len().into()).get_appropriate_unit(true); if metadata.is_dir() { - dirs.push(name) + dirs.push(DirInfo { + name, + size: Byte::from_bytes(dir_size(f.path().display().to_string()).unwrap() as u128) + .get_appropriate_unit(true) + .to_string(), + }) } else { files.push(FileInfo { name, diff --git a/types/src/fs/list.rs b/types/src/fs/list.rs index 37728aa..8055908 100644 --- a/types/src/fs/list.rs +++ b/types/src/fs/list.rs @@ -8,7 +8,7 @@ pub struct Request { #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Response { pub files: Vec, - pub dirs: Vec, + pub dirs: Vec, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -16,3 +16,9 @@ pub struct FileInfo { pub name: String, pub size: String, } + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct DirInfo { + pub name: String, + pub size: String, +}