PronounsToday/web/src/main.rs

157 lines
4.5 KiB
Rust

use std::collections::HashMap;
use std::fmt::{self, Display};
use actix_web::dev::HttpResponseBuilder;
use actix_web::http::{header, StatusCode};
use actix_web::middleware::normalize::TrailingSlash;
use actix_web::middleware::{self, Logger};
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, ResponseError, Result};
use askama::Template;
use pronouns_today::user_preferences::Preference;
use pronouns_today::{InstanceSettings, Pronoun};
#[derive(Template)]
#[template(path = "index.html")]
struct IndexTemplate<'a> {
name: Option<String>,
pronoun: &'a Pronoun,
pronouns: Vec<(usize, &'a Pronoun)>,
}
fn render_page(pronoun: &Pronoun, settings: &InstanceSettings, name: Option<String>) -> String {
IndexTemplate {
name,
pronoun,
pronouns: settings.pronoun_list.iter().enumerate().collect(),
}
.render()
.unwrap()
}
#[post("/")]
async fn create_link(
settings: web::Data<InstanceSettings>,
form: web::Form<HashMap<String, String>>,
) -> Result<impl Responder> {
let mut weights = vec![0; settings.pronoun_list.len()];
for (k, v) in form.iter() {
if let Ok(i) = k.parse::<usize>() {
let w = v.parse::<u8>().map_err(|_| Error::InvlaidPrefString)?;
if i < weights.len() - 1 {
weights[i] = w;
}
}
}
let prefs = InstanceSettings::create_preferences(&weights);
let pref_string = prefs.as_prefstring();
let url = match form.get("name") {
Some(name) if !name.is_empty() => format!("/{}/{}", name, pref_string),
_ => format!("/{}", pref_string),
};
Ok(HttpResponse::SeeOther()
.header(header::LOCATION, url)
.finish())
}
#[get("/")]
async fn default(settings: web::Data<InstanceSettings>) -> Result<impl Responder> {
let pronoun = settings
.select_pronouns(None, None)
.map_err(|_| Error::InvlaidPrefString)?;
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(render_page(&pronoun, &settings, None)))
}
#[get("/{prefs}")]
async fn only_prefs(
web::Path(prefs): web::Path<String>,
settings: web::Data<InstanceSettings>,
) -> Result<impl Responder> {
let pronoun = settings
.select_pronouns(None, Some(&prefs))
.map_err(|_| Error::InvlaidPrefString)?;
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(render_page(&pronoun, &settings, None)))
}
#[get("/{name}/{prefs}")]
async fn prefs_and_name(
web::Path((name, prefs)): web::Path<(String, String)>,
settings: web::Data<InstanceSettings>,
) -> Result<impl Responder> {
let pronoun = settings
.select_pronouns(Some(&name), Some(&prefs))
.map_err(|_| Error::InvlaidPrefString)?;
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(render_page(&pronoun, &settings, Some(name))))
}
async fn not_found() -> impl Responder {
HttpResponse::NotFound()
.content_type("text/html; charset=utf-8")
.body(include_str!("../templates/404.html"))
}
#[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)
.wrap(middleware::NormalizePath::new(TrailingSlash::Trim))
.service(prefs_and_name)
.service(only_prefs)
.service(default)
.service(create_link)
.default_service(web::to(not_found))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
#[derive(Template)]
#[template(path = "error.html")]
struct ErrorPage {
msg: String,
}
#[derive(Debug)]
enum Error {
InvlaidPrefString,
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let msg = match self {
&Error::InvlaidPrefString => "This URL contains an invalid pronoun preference string",
};
write!(f, "{}", msg)
}
}
impl ResponseError for Error {
fn status_code(&self) -> actix_web::http::StatusCode {
match self {
&Error::InvlaidPrefString => StatusCode::BAD_REQUEST,
}
}
fn error_response(&self) -> HttpResponse {
HttpResponseBuilder::new(self.status_code())
.set_header(header::CONTENT_TYPE, "text/html; charset=utf-8")
.body(
ErrorPage {
msg: self.to_string(),
}
.render()
.unwrap(),
)
}
}