song-idea-generator/sigweb/src/main.rs

97 lines
2.1 KiB
Rust

#[macro_use]
extern crate rocket;
use libsig;
use rocket::response::content::{Css, Html};
use rocket::serde::json::Json;
use rocket::State;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
mod templates;
struct BaseUrl {
url: String,
}
#[get("/api")]
fn api_version_available() -> Json<Value> {
Json(json! ({
"versions": [ "v1" ]
}))
}
#[get("/api/v1")]
fn api_v1_index() -> Json<Value> {
Json(json! ({
"endpoints": [ "generate", "generate_ambient" ]
}))
}
#[derive(Debug, Serialize, Deserialize)]
struct Output {
data: libsig::SongIdea,
text: String,
}
#[get("/api/v1/generate")]
fn api_v1_generate() -> Json<Output> {
let idea = libsig::SongIdea::generate();
Json(Output {
data: idea.clone(),
text: idea.to_string(),
})
}
#[get("/api/v1/generate_ambient")]
fn api_v1_generate_ambient() -> Json<Output> {
let idea = libsig::SongIdea::generate_ambient();
Json(Output {
data: idea.clone(),
text: idea.to_string(),
})
}
#[get("/")]
fn index(base: &State<BaseUrl>) -> Html<String> {
Html(templates::main_page_template(None, &base.url))
}
#[get("/generate")]
fn generate(base: &State<BaseUrl>) -> Html<String> {
Html(templates::main_page_template(Some(
libsig::SongIdea::generate(),
), &base.url))
}
#[get("/generate_ambient")]
fn generate_ambient(base: &State<BaseUrl>) -> Html<String> {
Html(templates::main_page_template(Some(
libsig::SongIdea::generate_ambient(),
), &base.url))
}
#[get("/style.css")]
async fn style_css() -> Css<String> {
Css(include_str!("../static/style.css").into())
}
#[launch]
fn rocket() -> _ {
rocket::build()
.manage(BaseUrl {
url: std::env::var("SIGWEB_BASE_URL").unwrap_or("/".to_string()),
})
.mount(
"/",
routes![
api_version_available,
api_v1_index,
api_v1_generate,
api_v1_generate_ambient,
generate,
generate_ambient,
index,
style_css,
],
)
}