From 1595c5e8eb03e729b10c70adb291f7bf0083fb78 Mon Sep 17 00:00:00 2001 From: Rusty Striker Date: Mon, 30 Jun 2025 19:44:39 +0300 Subject: [PATCH] allow listing assets directories, no filters currently (maybe should add for web and non-image stuff) --- src/main.rs | 46 +++++++++++++++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 13 deletions(-) diff --git a/src/main.rs b/src/main.rs index 033ed8d..c385958 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,9 @@ use axum::{ - extract::ws::{self, Message}, http::StatusCode, response::{self, IntoResponse}, routing, Router + Router, + extract::ws::{self, Message}, + http::StatusCode, + response::{self, IntoResponse}, + routing, }; use futures_util::{ SinkExt, StreamExt, @@ -195,16 +199,34 @@ async fn style() -> impl response::IntoResponse { async fn get_asset(asset: axum::extract::Path) -> impl IntoResponse { println!("Asset requested: {}", asset.0); let supported_file_types = [ - (".jpg", "image/jpeg"), (".jpeg", "image/jpeg"), - (".png", "image/png"), (".jxl", "image/jxl"), - ]; - let mime = match supported_file_types.iter() + (".jpg", "image/jpeg"), + (".jpeg", "image/jpeg"), + (".png", "image/png"), + (".jxl", "image/jxl"), + ]; + // check if file is a folder. if so, list it + if let Ok(mut dir) = tokio::fs::read_dir(format!("assets/{}", asset.0)).await { + let mut files = Vec::new(); + + while let Ok(Some(entry)) = dir.next_entry().await { + if let Ok(name) = entry.file_name().into_string() { + files.push(name); + } + } + return Ok(( + [(axum::http::header::CONTENT_TYPE, "application/json")], + axum::body::Body::from(serde_json::to_string(&files).unwrap_or(String::new())), + )); + } + let mime = match supported_file_types + .iter() .filter(|t| asset.0.ends_with(t.0)) .map(|t| t.1) - .next() { - Some(t) => t, - None => return Err((StatusCode::UNSUPPORTED_MEDIA_TYPE, "Unsupported file type".to_string())), - }; + .next() + { + Some(t) => t, + None => return Err((StatusCode::UNSUPPORTED_MEDIA_TYPE, "Unsupported file type".to_string())), + }; let file = match tokio::fs::File::open(format!("assets/{}", asset.0)).await { Ok(f) => f, Err(err) => return Err((StatusCode::NOT_FOUND, format!("File not found: {}", err))), @@ -212,8 +234,6 @@ async fn get_asset(asset: axum::extract::Path) -> impl IntoResponse { let stream = ReaderStream::new(file); let body = axum::body::Body::from_stream(stream); - let headers = [ - (axum::http::header::CONTENT_TYPE, mime) - ]; + let headers = [(axum::http::header::CONTENT_TYPE, mime)]; Ok((headers, body)) -} \ No newline at end of file +}