tenebrous-sheets/src/routes/characters.rs

90 lines
2.5 KiB
Rust
Raw Normal View History

use crate::db::{Dao, TenebrousDbConn};
2020-12-01 21:32:16 +00:00
use crate::errors::Error;
use crate::models::characters::{Character, CharacterDataType, DynCharacterData, Visibility};
use crate::models::users::User;
2020-12-01 21:32:16 +00:00
use rocket_contrib::templates::Template;
use std::collections::HashMap;
mod new;
2020-12-01 21:32:16 +00:00
pub(crate) fn routes() -> Vec<rocket::Route> {
routes![
view_character,
new::new_character_page,
new::new_character_submit,
new::new_character_not_logged_in,
edit_character
]
2020-12-01 21:32:16 +00:00
}
#[derive(Serialize)]
struct ViewCharacterTemplate<'a> {
pub name: &'a str,
pub username: &'a str,
pub data_type: &'a CharacterDataType,
pub sheet: Box<DynCharacterData>,
}
fn view_character_template(user: &User, character: Character) -> Result<Template, Error> {
let character = character.uprade()?;
2020-12-01 21:32:16 +00:00
let context = ViewCharacterTemplate {
name: &character.character_name,
username: &user.username,
data_type: &character.data_type,
sheet: character.dyn_deserialize()?,
};
use CharacterDataType::*;
let template = match character.data_type {
ChroniclesOfDarknessV1 => Template::render("characters/view_character", context),
ChangelingV1 => Template::render("characters/view_changeling_character", context),
};
2020-12-01 21:32:16 +00:00
Ok(template)
}
#[get("/<username>/<character_id>")]
async fn view_character(
character_id: i32,
username: String,
conn: TenebrousDbConn,
logged_in_user: Option<&User>,
) -> Result<Template, Error> {
let user = &conn.load_user(username).await?.ok_or(Error::NotFound)?;
let character = conn
.load_character(character_id)
.await?
.and_then(|c| c.as_visible_for(logged_in_user))
.ok_or(Error::NotFound)?;
let template = view_character_template(user, character)?;
Ok(template)
}
2020-12-01 21:32:16 +00:00
#[get("/<owner>/<character_id>/edit")]
async fn edit_character(
2020-12-01 21:32:16 +00:00
character_id: i32,
owner: String,
logged_in_user: Option<&User>,
2020-12-01 21:32:16 +00:00
conn: TenebrousDbConn,
) -> Result<Template, Error> {
let owner = conn.load_user(owner).await?.ok_or(Error::NotFound)?;
2020-12-01 21:32:16 +00:00
let logged_in_user = logged_in_user.ok_or(Error::NotLoggedIn)?;
let character = conn
.load_character(character_id)
.await?
.ok_or(Error::NotFound)?;
2020-12-01 21:32:16 +00:00
if logged_in_user != &owner {
2020-12-01 21:32:16 +00:00
return Err(Error::NoPermission);
}
let mut context = HashMap::new();
context.insert("name", character.character_name);
2020-12-01 21:32:16 +00:00
context.insert("username", owner.username);
Ok(Template::render("view_character", context))
}