magnetar/fe_calckey/src/frontend_api.rs

42 lines
1002 B
Rust

use axum::extract::State;
use axum::routing::get;
use axum::{Json, Router};
use std::path::Path;
use walkdir::WalkDir;
pub fn create_frontend_api(assets_dir: &str) -> Router {
Router::new().route(
"/default-sounds",
get(default_sounds).with_state(assets_dir.to_owned()),
)
}
async fn default_sounds(State(ref assets_dir): State<String>) -> Json<Vec<String>> {
let sounds_dir = &Path::new(assets_dir).join("sounds");
let mut sounds = Vec::new();
for entry in WalkDir::new(sounds_dir) {
let Ok(entry) = entry else {
continue;
};
if !entry.file_type().is_file() {
continue;
}
let Ok(Some(entry)) = entry
.path()
.strip_prefix(sounds_dir)
.map(|p| p.to_str())
.map(|p| p.and_then(|pp| pp.strip_suffix(".mp3"))) else {
continue;
};
sounds.push(entry.to_owned());
}
sounds.sort();
Json(sounds)
}