charcuterie/src/main.rs

61 lines
1.7 KiB
Rust

#[macro_use]
extern crate serde_json;
use async_std::task;
use glob::glob;
use handlebars::Handlebars;
use log::*;
use rodio::Source;
use tide::{Body, Request, StatusCode};
use std::fs::File;
use std::io::BufReader;
async fn index(req: Request<()>) -> Result<Body, tide::Error> {
let mut hb = Handlebars::new();
hb.register_templates_directory(".hbs", "views")
.expect("Failed to register templates");
let mut sounds = vec![];
for sound in glob("sounds/*.wav").expect("Failed to glob sounds") {
if let Ok(sound) = sound {
if let Some(name) = sound.as_path().file_stem() {
sounds.push(name.to_os_string().into_string().unwrap());
}
}
}
info!("sounds: {:?}", sounds);
let view = hb.render("index", &json!({"sounds": sounds}))
.expect("Failed to render");
let mut body = Body::from_string(view);
body.set_mime("text/html");
Ok(body)
}
async fn play(req: Request<()>) -> tide::Result {
if let Ok(sound) = req.param::<String>("sound") {
let device = rodio::default_output_device().unwrap();
let file = File::open(format!("sounds/{}.wav", sound)).unwrap();
let source = rodio::Decoder::new(BufReader::new(file)).unwrap();
rodio::play_raw(&device, source.convert_samples());
Ok(tide::Redirect::new("/").into())
}
else {
Err(tide::Error::from_str(StatusCode::NotFound, "Could not find sound"))
}
}
#[async_std::main]
async fn main() -> Result<(), tide::Error> {
pretty_env_logger::init();
let mut app = tide::new();
app.at("/play/:sound").post(play);
app.at("/").get(index);
Ok(app.listen("0.0.0.0:9077").await?)
}