PronounsToday/web/src/main.rs

101 lines
2.9 KiB
Rust

use std::collections::HashMap;
use actix_web::error::ErrorBadRequest;
use actix_web::http::header::LOCATION;
use actix_web::middleware::Logger;
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, Result};
use askama::Template;
use pronouns_today::user_preferences::Preference;
use pronouns_today::{InstanceSettings, Pronoun};
#[derive(Template)]
#[template(path = "index.html")]
struct IndexTemplate<'a> {
short: String,
pronouns: Vec<(usize, &'a Pronoun)>,
}
fn render_page(pronoun: &Pronoun, settings: &InstanceSettings) -> String {
IndexTemplate {
short: pronoun.render_threeform(),
pronouns: settings.pronoun_list.iter().enumerate().collect(),
}
.render()
.unwrap()
}
#[get("/")]
async fn default(settings: web::Data<InstanceSettings>) -> Result<impl Responder> {
eprintln!("default");
let pronoun = settings
.select_pronouns(None, None)
.map_err(ErrorBadRequest)?;
Ok(HttpResponse::Ok()
.content_type("text/html")
.body(render_page(&pronoun, &settings)))
}
#[post("/")]
async fn create_link(
settings: web::Data<InstanceSettings>,
form: web::Form<HashMap<usize, u8>>,
) -> Result<impl Responder> {
eprintln!("create {:?}", form);
let weights: Vec<_> = (0..settings.pronoun_list.len())
.map(|i| form.get(&i).map(|v| *v).unwrap_or(0))
.collect();
let prefs = InstanceSettings::create_preferences(&weights);
eprintln!("prefs: {:?}", prefs);
let pref_string = prefs.as_prefstring();
eprintln!("prefstring: {}", pref_string);
Ok(HttpResponse::SeeOther()
.header(LOCATION, format!("/{}", pref_string))
.finish())
}
#[get("/{prefs}")]
async fn only_prefs(
web::Path(prefs): web::Path<String>,
settings: web::Data<InstanceSettings>,
) -> Result<impl Responder> {
eprintln!("prefs {}", prefs);
let pronoun = settings
.select_pronouns(None, Some(&prefs))
.map_err(ErrorBadRequest)?;
Ok(HttpResponse::Ok()
.content_type("text/html")
.body(render_page(&pronoun, &settings)))
}
#[get("/{name}/{prefs}")]
async fn prefs_and_name(
web::Path((name, prefs)): web::Path<(String, String)>,
settings: web::Data<InstanceSettings>,
) -> Result<impl Responder> {
eprintln!("prefs+name");
let pronoun = settings
.select_pronouns(Some(&name), Some(&prefs))
.map_err(ErrorBadRequest)?;
Ok(HttpResponse::Ok()
.content_type("text/html")
.body(render_page(&pronoun, &settings)))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init();
HttpServer::new(|| {
let logger = Logger::default();
App::new()
.data(InstanceSettings::default())
.wrap(logger)
.service(prefs_and_name)
.service(only_prefs)
.service(default)
.service(create_link)
})
.bind("127.0.0.1:8080")?
.run()
.await
}