Use Ructe (#327)

All the template are now compiled at compile-time with the `ructe` crate.

I preferred to use it instead of askama because it allows more complex Rust expressions, where askama only supports a small subset of expressions and doesn't allow them everywhere (for instance, `{{ macro!() | filter }}` would result in a parsing error).

The diff is quite huge, but there is normally no changes in functionality.

Fixes #161 and unblocks #110 and #273
This commit is contained in:
Baptiste Gelez
2018-12-06 18:54:16 +01:00
committed by GitHub
parent 5f059c3e98
commit 70af57c6e1
121 changed files with 3132 additions and 3260 deletions
+143 -183
View File
@@ -5,9 +5,9 @@ use rocket::{
request::LenientForm,
response::{status, Content, Flash, Redirect},
};
use rocket_contrib::Template;
use rocket_i18n::I18n;
use serde_json;
use validator::{Validate, ValidationError};
use validator::{Validate, ValidationError, ValidationErrors};
use inbox::Inbox;
use plume_common::activity_pub::{
@@ -22,11 +22,12 @@ use plume_models::{
reshares::Reshare, users::*,
};
use routes::Page;
use template_utils::Ructe;
use Worker;
use Searcher;
#[get("/me")]
fn me(user: Option<User>) -> Result<Redirect, Flash<Redirect>> {
pub fn me(user: Option<User>) -> Result<Redirect, Flash<Redirect>> {
match user {
Some(user) => Ok(Redirect::to(uri!(details: name = user.username))),
None => Err(utils::requires_login("", uri!(me))),
@@ -34,7 +35,7 @@ fn me(user: Option<User>) -> Result<Redirect, Flash<Redirect>> {
}
#[get("/@/<name>", rank = 2)]
fn details(
pub fn details(
name: String,
conn: DbConn,
account: Option<User>,
@@ -42,111 +43,96 @@ fn details(
fetch_articles_conn: DbConn,
fetch_followers_conn: DbConn,
update_conn: DbConn,
intl: I18n,
searcher: Searcher,
) -> Template {
may_fail!(
account.map(|a| a.to_json(&*conn)),
User::find_by_fqn(&*conn, &name),
"Couldn't find requested user",
|user| {
let recents = Post::get_recents_for_author(&*conn, &user, 6);
let reshares = Reshare::get_recents_for_author(&*conn, &user, 6);
let user_id = user.id;
let n_followers = user.get_followers(&*conn).len();
) -> Result<Ructe, Ructe> {
let user = User::find_by_fqn(&*conn, &name).ok_or_else(|| render!(errors::not_found(&(&*conn, &intl.catalog, account.clone()))))?;
let recents = Post::get_recents_for_author(&*conn, &user, 6);
let reshares = Reshare::get_recents_for_author(&*conn, &user, 6);
if !user.get_instance(&*conn).local {
// Fetch new articles
let user_clone = user.clone();
let searcher = searcher.clone();
worker.execute(move || {
for create_act in user_clone.fetch_outbox::<Create>() {
match create_act.create_props.object_object::<Article>() {
Ok(article) => {
Post::from_activity(
&(&fetch_articles_conn, &searcher),
article,
user_clone.clone().into_id(),
);
println!("Fetched article from remote user");
}
Err(e) => {
println!("Error while fetching articles in background: {:?}", e)
}
}
}
});
// Fetch followers
let user_clone = user.clone();
worker.execute(move || {
for user_id in user_clone.fetch_followers_ids() {
let follower =
User::find_by_ap_url(&*fetch_followers_conn, &user_id)
.unwrap_or_else(|| {
User::fetch_from_url(&*fetch_followers_conn, &user_id)
.expect("user::details: Couldn't fetch follower")
});
follows::Follow::insert(
&*fetch_followers_conn,
follows::NewFollow {
follower_id: follower.id,
following_id: user_clone.id,
ap_url: format!("{}/follow/{}", follower.ap_url, user_clone.ap_url),
},
if !user.get_instance(&*conn).local {
// Fetch new articles
let user_clone = user.clone();
let searcher = searcher.clone();
worker.execute(move || {
for create_act in user_clone.fetch_outbox::<Create>() {
match create_act.create_props.object_object::<Article>() {
Ok(article) => {
Post::from_activity(
&(&*fetch_articles_conn, &searcher),
article,
user_clone.clone().into_id(),
);
println!("Fetched article from remote user");
}
Err(e) => {
println!("Error while fetching articles in background: {:?}", e)
}
});
// Update profile information if needed
let user_clone = user.clone();
if user.needs_update() {
worker.execute(move || {
user_clone.refetch(&*update_conn);
});
}
}
});
Template::render(
"users/details",
json!({
"user": user.to_json(&*conn),
"instance_url": user.get_instance(&*conn).public_domain,
"is_remote": user.instance_id != Instance::local_id(&*conn),
"follows": account.clone().map(|x| x.is_following(&*conn, user.id)).unwrap_or(false),
"account": account.clone().map(|a| a.to_json(&*conn)),
"recents": recents.into_iter().map(|p| p.to_json(&*conn)).collect::<Vec<serde_json::Value>>(),
"reshares": reshares.into_iter().map(|r| r.get_post(&*conn).unwrap().to_json(&*conn)).collect::<Vec<serde_json::Value>>(),
"is_self": account.map(|a| a.id == user_id).unwrap_or(false),
"n_followers": n_followers
}),
)
// Fetch followers
let user_clone = user.clone();
worker.execute(move || {
for user_id in user_clone.fetch_followers_ids() {
let follower =
User::find_by_ap_url(&*fetch_followers_conn, &user_id)
.unwrap_or_else(|| {
User::fetch_from_url(&*fetch_followers_conn, &user_id)
.expect("user::details: Couldn't fetch follower")
});
follows::Follow::insert(
&*fetch_followers_conn,
follows::NewFollow {
follower_id: follower.id,
following_id: user_clone.id,
ap_url: format!("{}/follow/{}", follower.ap_url, user_clone.ap_url),
},
);
}
});
// Update profile information if needed
let user_clone = user.clone();
if user.needs_update() {
worker.execute(move || {
user_clone.refetch(&*update_conn);
});
}
)
}
Ok(render!(users::details(
&(&*conn, &intl.catalog, account.clone()),
user.clone(),
account.map(|x| x.is_following(&*conn, user.id)).unwrap_or(false),
user.instance_id != Instance::local_id(&*conn),
user.get_instance(&*conn).public_domain,
recents,
reshares.into_iter().map(|r| r.get_post(&*conn).expect("user::details: Reshared post error")).collect()
)))
}
#[get("/dashboard")]
fn dashboard(user: User, conn: DbConn) -> Template {
pub fn dashboard(user: User, conn: DbConn, intl: I18n) -> Ructe {
let blogs = Blog::find_for_author(&*conn, &user);
Template::render(
"users/dashboard",
json!({
"account": user.to_json(&*conn),
"blogs": blogs,
"drafts": Post::drafts_by_author(&*conn, &user).into_iter().map(|a| a.to_json(&*conn)).collect::<Vec<serde_json::Value>>(),
}),
)
render!(users::dashboard(
&(&*conn, &intl.catalog, Some(user.clone())),
blogs,
Post::drafts_by_author(&*conn, &user)
))
}
#[get("/dashboard", rank = 2)]
fn dashboard_auth() -> Flash<Redirect> {
pub fn dashboard_auth(i18n: I18n) -> Flash<Redirect> {
utils::requires_login(
"You need to be logged in order to access your dashboard",
i18n!(i18n.catalog, "You need to be logged in order to access your dashboard"),
uri!(dashboard),
)
}
#[post("/@/<name>/follow")]
fn follow(name: String, conn: DbConn, user: User, worker: Worker) -> Option<Redirect> {
pub fn follow(name: String, conn: DbConn, user: User, worker: Worker) -> Option<Redirect> {
let target = User::find_by_fqn(&*conn, &name)?;
if let Some(follow) = follows::Follow::find(&*conn, user.id, target.id) {
let delete_act = follow.delete(&*conn);
@@ -171,49 +157,37 @@ fn follow(name: String, conn: DbConn, user: User, worker: Worker) -> Option<Redi
}
#[post("/@/<name>/follow", rank = 2)]
fn follow_auth(name: String) -> Flash<Redirect> {
pub fn follow_auth(name: String, i18n: I18n) -> Flash<Redirect> {
utils::requires_login(
"You need to be logged in order to follow someone",
i18n!(i18n.catalog, "You need to be logged in order to follow someone"),
uri!(follow: name = name),
)
}
#[get("/@/<name>/followers?<page>")]
fn followers_paginated(name: String, conn: DbConn, account: Option<User>, page: Page) -> Template {
may_fail!(
account.map(|a| a.to_json(&*conn)),
User::find_by_fqn(&*conn, &name),
"Couldn't find requested user",
|user| {
let user_id = user.id;
let followers_count = user.get_followers(&*conn).len();
pub fn followers_paginated(name: String, conn: DbConn, account: Option<User>, page: Page, intl: I18n) -> Result<Ructe, Ructe> {
let user = User::find_by_fqn(&*conn, &name).ok_or_else(|| render!(errors::not_found(&(&*conn, &intl.catalog, account.clone()))))?;
let followers_count = user.get_followers(&*conn).len(); // TODO: count in DB
Template::render(
"users/followers",
json!({
"user": user.to_json(&*conn),
"instance_url": user.get_instance(&*conn).public_domain,
"is_remote": user.instance_id != Instance::local_id(&*conn),
"follows": account.clone().map(|x| x.is_following(&*conn, user.id)).unwrap_or(false),
"followers": user.get_followers_page(&*conn, page.limits()).into_iter().map(|f| f.to_json(&*conn)).collect::<Vec<serde_json::Value>>(),
"account": account.clone().map(|a| a.to_json(&*conn)),
"is_self": account.map(|a| a.id == user_id).unwrap_or(false),
"n_followers": followers_count,
"page": page.page,
"n_pages": Page::total(followers_count as i32)
}),
)
}
)
Ok(render!(users::followers(
&(&*conn, &intl.catalog, account.clone()),
user.clone(),
account.map(|x| x.is_following(&*conn, user.id)).unwrap_or(false),
user.instance_id != Instance::local_id(&*conn),
user.get_instance(&*conn).public_domain,
user.get_followers_page(&*conn, page.limits()),
page.0,
Page::total(followers_count as i32)
)))
}
#[get("/@/<name>/followers", rank = 2)]
fn followers(name: String, conn: DbConn, account: Option<User>) -> Template {
followers_paginated(name, conn, account, Page::first())
pub fn followers(name: String, conn: DbConn, account: Option<User>, intl: I18n) -> Result<Ructe, Ructe> {
followers_paginated(name, conn, account, Page::first(), intl)
}
#[get("/@/<name>", rank = 1)]
fn activity_details(
pub fn activity_details(
name: String,
conn: DbConn,
_ap: ApRequest,
@@ -223,71 +197,60 @@ fn activity_details(
}
#[get("/users/new")]
fn new(user: Option<User>, conn: DbConn) -> Template {
Template::render(
"users/new",
json!({
"enabled": Instance::get_local(&*conn).map(|i| i.open_registrations).unwrap_or(true),
"account": user.map(|u| u.to_json(&*conn)),
"errors": null,
"form": null
}),
)
pub fn new(user: Option<User>, conn: DbConn, intl: I18n) -> Ructe {
render!(users::new(
&(&*conn, &intl.catalog, user),
Instance::get_local(&*conn).map(|i| i.open_registrations).unwrap_or(true),
&NewUserForm::default(),
ValidationErrors::default()
))
}
#[get("/@/<name>/edit")]
fn edit(name: String, user: User, conn: DbConn) -> Option<Template> {
pub fn edit(name: String, user: User, conn: DbConn, intl: I18n) -> Option<Ructe> {
if user.username == name && !name.contains('@') {
Some(Template::render(
"users/edit",
json!({
"account": user.to_json(&*conn)
}),
))
Some(render!(users::edit(
&(&*conn, &intl.catalog, Some(user.clone())),
UpdateUserForm {
display_name: user.display_name.clone(),
email: user.email.clone().unwrap_or_default(),
summary: user.summary.to_string(),
},
ValidationErrors::default()
)))
} else {
None
}
}
#[get("/@/<name>/edit", rank = 2)]
fn edit_auth(name: String) -> Flash<Redirect> {
pub fn edit_auth(name: String, i18n: I18n) -> Flash<Redirect> {
utils::requires_login(
"You need to be logged in order to edit your profile",
i18n!(i18n.catalog, "You need to be logged in order to edit your profile"),
uri!(edit: name = name),
)
}
#[derive(FromForm)]
struct UpdateUserForm {
display_name: Option<String>,
email: Option<String>,
summary: Option<String>,
pub struct UpdateUserForm {
pub display_name: String,
pub email: String,
pub summary: String,
}
#[put("/@/<_name>/edit", data = "<data>")]
fn update(_name: String, conn: DbConn, user: User, data: LenientForm<UpdateUserForm>) -> Redirect {
#[put("/@/<_name>/edit", data = "<form>")]
pub fn update(_name: String, conn: DbConn, user: User, form: LenientForm<UpdateUserForm>) -> Redirect {
user.update(
&*conn,
data.get()
.display_name
.clone()
.unwrap_or_else(|| user.display_name.to_string())
.to_string(),
data.get()
.email
.clone()
.unwrap_or_else(|| user.email.clone().unwrap())
.to_string(),
data.get()
.summary
.clone()
.unwrap_or_else(|| user.summary.to_string()),
if !form.display_name.is_empty() { form.display_name.clone() } else { user.display_name.clone() },
if !form.email.is_empty() { form.email.clone() } else { user.email.clone().unwrap_or_default() },
if !form.summary.is_empty() { form.summary.clone() } else { user.summary.to_string() },
);
Redirect::to(uri!(me))
}
#[post("/@/<name>/delete")]
fn delete(name: String, conn: DbConn, user: User, mut cookies: Cookies, searcher: Searcher) -> Option<Redirect> {
pub fn delete(name: String, conn: DbConn, user: User, mut cookies: Cookies, searcher: Searcher) -> Option<Redirect> {
let account = User::find_by_fqn(&*conn, &name)?;
if user.id == account.id {
account.delete(&*conn, &searcher);
@@ -302,7 +265,7 @@ fn delete(name: String, conn: DbConn, user: User, mut cookies: Cookies, searcher
}
}
#[derive(FromForm, Serialize, Validate)]
#[derive(Default, FromForm, Serialize, Validate)]
#[validate(
schema(
function = "passwords_match",
@@ -310,29 +273,29 @@ fn delete(name: String, conn: DbConn, user: User, mut cookies: Cookies, searcher
message = "Passwords are not matching"
)
)]
struct NewUserForm {
pub struct NewUserForm {
#[validate(length(min = "1", message = "Username can't be empty"),
custom( function = "validate_username", message = "User name is not allowed to contain any of < > & @ ' or \""))]
username: String,
pub username: String,
#[validate(email(message = "Invalid email"))]
email: String,
pub email: String,
#[validate(
length(
min = "8",
message = "Password should be at least 8 characters long"
)
)]
password: String,
pub password: String,
#[validate(
length(
min = "8",
message = "Password should be at least 8 characters long"
)
)]
password_confirmation: String,
pub password_confirmation: String,
}
fn passwords_match(form: &NewUserForm) -> Result<(), ValidationError> {
pub fn passwords_match(form: &NewUserForm) -> Result<(), ValidationError> {
if form.password != form.password_confirmation {
Err(ValidationError::new("password_match"))
} else {
@@ -340,7 +303,7 @@ fn passwords_match(form: &NewUserForm) -> Result<(), ValidationError> {
}
}
fn validate_username(username: &str) -> Result<(), ValidationError> {
pub fn validate_username(username: &str) -> Result<(), ValidationError> {
if username.contains(&['<', '>', '&', '@', '\'', '"'][..]) {
Err(ValidationError::new("username_illegal_char"))
} else {
@@ -348,16 +311,15 @@ fn validate_username(username: &str) -> Result<(), ValidationError> {
}
}
#[post("/users/new", data = "<data>")]
fn create(conn: DbConn, data: LenientForm<NewUserForm>) -> Result<Redirect, Template> {
if !Instance::get_local(&*conn)
#[post("/users/new", data = "<form>")]
pub fn create(conn: DbConn, form: LenientForm<NewUserForm>, intl: I18n) -> Result<Redirect, Ructe> {
if !Instance::get_local(&*conn)
.map(|i| i.open_registrations)
.unwrap_or(true)
{
return Ok(Redirect::to(uri!(new))); // Actually, it is an error
}
let form = data.get();
form.validate()
.map(|_| {
NewUser::new_local(
@@ -371,26 +333,24 @@ fn create(conn: DbConn, data: LenientForm<NewUserForm>) -> Result<Redirect, Temp
).update_boxes(&*conn);
Redirect::to(uri!(super::session::new))
})
.map_err(|e| {
Template::render(
"users/new",
json!({
"enabled": Instance::get_local(&*conn).map(|i| i.open_registrations).unwrap_or(true),
"errors": e.inner(),
"form": form
}),
)
.map_err(|err| {
render!(users::new(
&(&*conn, &intl.catalog, None),
Instance::get_local(&*conn).map(|i| i.open_registrations).unwrap_or(true),
&*form,
err
))
})
}
#[get("/@/<name>/outbox")]
fn outbox(name: String, conn: DbConn) -> Option<ActivityStream<OrderedCollection>> {
pub fn outbox(name: String, conn: DbConn) -> Option<ActivityStream<OrderedCollection>> {
let user = User::find_local(&*conn, &name)?;
Some(user.outbox(&*conn))
}
#[post("/@/<name>/inbox", data = "<data>")]
fn inbox(
pub fn inbox(
name: String,
conn: DbConn,
data: String,
@@ -433,7 +393,7 @@ fn inbox(
}
#[get("/@/<name>/followers")]
fn ap_followers(
pub fn ap_followers(
name: String,
conn: DbConn,
_ap: ApRequest,
@@ -459,7 +419,7 @@ fn ap_followers(
}
#[get("/@/<name>/atom.xml")]
fn atom_feed(name: String, conn: DbConn) -> Option<Content<String>> {
pub fn atom_feed(name: String, conn: DbConn) -> Option<Content<String>> {
let author = User::find_by_fqn(&*conn, &name)?;
let feed = FeedBuilder::default()
.title(author.display_name.clone())