Plume/src/routes/posts.rs

215 lines
8.3 KiB
Rust
Raw Normal View History

use activitypub::object::Article;
use heck::{CamelCase, KebabCase};
use rocket::{State, request::LenientForm};
2018-06-04 19:57:03 +00:00
use rocket::response::{Redirect, Flash};
2018-04-23 14:25:39 +00:00
use rocket_contrib::Template;
2018-05-10 09:44:57 +00:00
use serde_json;
use std::{collections::HashMap, borrow::Cow};
2018-07-06 09:51:19 +00:00
use validator::{Validate, ValidationError, ValidationErrors};
use workerpool::{Pool, thunk::*};
2018-04-23 14:25:39 +00:00
use plume_common::activity_pub::{broadcast, ActivityStream, ApRequest, inbox::Deletable};
use plume_common::utils;
use plume_models::{
2018-05-19 07:39:59 +00:00
blogs::*,
db_conn::DbConn,
2018-05-19 07:39:59 +00:00
comments::Comment,
instance::Instance,
2018-06-20 20:58:11 +00:00
mentions::Mention,
2018-05-19 07:39:59 +00:00
post_authors::*,
posts::*,
safe_string::SafeString,
tags::*,
2018-05-19 07:39:59 +00:00
users::User
};
#[derive(FromForm)]
struct CommentQuery {
responding_to: Option<i32>
}
2018-04-23 14:25:39 +00:00
// See: https://github.com/SergioBenitez/Rocket/pull/454
#[get("/~/<blog>/<slug>", rank = 4)]
2018-05-10 20:31:52 +00:00
fn details(blog: String, slug: String, conn: DbConn, user: Option<User>) -> Template {
details_response(blog, slug, conn, user, None)
}
#[get("/~/<blog>/<slug>?<query>")]
fn details_response(blog: String, slug: String, conn: DbConn, user: Option<User>, query: Option<CommentQuery>) -> Template {
2018-09-03 13:59:02 +00:00
may_fail!(user.map(|u| u.to_json(&*conn)), Blog::find_by_fqn(&*conn, blog), "Couldn't find this blog", |blog| {
may_fail!(user.map(|u| u.to_json(&*conn)), Post::find_by_slug(&*conn, slug, blog.id), "Couldn't find this post", |post| {
let comments = Comment::list_by_post(&*conn, post.id);
let comms = comments.clone();
Template::render("posts/details", json!({
"author": post.get_authors(&*conn)[0].to_json(&*conn),
"article": post.to_json(&*conn),
2018-07-26 17:08:18 +00:00
"blog": blog.to_json(&*conn),
"comments": &comments.into_iter().filter_map(|c| if c.in_response_to_id.is_none() {
Some(c.to_json(&*conn, &comms))
} else {
None
}).collect::<Vec<serde_json::Value>>(),
"n_likes": post.get_likes(&*conn).len(),
"has_liked": user.clone().map(|u| u.has_liked(&*conn, &post)).unwrap_or(false),
"n_reshares": post.get_reshares(&*conn).len(),
"has_reshared": user.clone().map(|u| u.has_reshared(&*conn, &post)).unwrap_or(false),
2018-09-03 13:59:02 +00:00
"account": &user.clone().map(|u| u.to_json(&*conn)),
"date": &post.creation_date.timestamp(),
"previous": query.and_then(|q| q.responding_to.map(|r| Comment::get(&*conn, r).expect("Error retrieving previous comment").to_json(&*conn, &vec![]))),
"user_fqn": user.clone().map(|u| u.get_fqn(&*conn)).unwrap_or(String::new()),
"is_author": user.clone().map(|u| post.get_authors(&*conn).into_iter().any(|a| u.id == a.id)).unwrap_or(false),
"is_following": user.map(|u| u.is_following(&*conn, post.get_authors(&*conn)[0].id)).unwrap_or(false)
}))
})
})
2018-04-23 14:25:39 +00:00
}
#[get("/~/<blog>/<slug>", rank = 3)]
fn activity_details(blog: String, slug: String, conn: DbConn, _ap: ApRequest) -> ActivityStream<Article> {
let blog = Blog::find_by_fqn(&*conn, blog).unwrap();
let post = Post::find_by_slug(&*conn, slug, blog.id).unwrap();
ActivityStream::new(post.into_activity(&*conn))
2018-04-23 14:25:39 +00:00
}
2018-06-04 19:57:03 +00:00
#[get("/~/<blog>/new", rank = 2)]
fn new_auth(blog: String) -> Flash<Redirect> {
utils::requires_login("You need to be logged in order to write a new post", uri!(new: blog = blog))
2018-04-23 14:25:39 +00:00
}
#[get("/~/<blog>/new", rank = 1)]
fn new(blog: String, user: User, conn: DbConn) -> Template {
let b = Blog::find_by_fqn(&*conn, blog.to_string()).unwrap();
if !user.is_author_in(&*conn, b.clone()) {
Template::render("errors/403", json!({
"error_message": "You are not author in this blog."
}))
} else {
Template::render("posts/new", json!({
2018-09-03 13:59:02 +00:00
"account": user.to_json(&*conn),
"instance": Instance::get_local(&*conn),
"errors": null,
"form": null
}))
}
}
#[derive(FromForm, Validate, Serialize)]
2018-04-23 14:25:39 +00:00
struct NewPostForm {
#[validate(custom(function = "valid_slug", message = "Invalid title"))]
2018-04-23 14:25:39 +00:00
pub title: String,
2018-09-04 11:26:13 +00:00
pub subtitle: String,
2018-04-23 14:25:39 +00:00
pub content: String,
pub tags: String,
2018-04-23 14:25:39 +00:00
pub license: String
}
2018-06-29 12:56:00 +00:00
fn valid_slug(title: &str) -> Result<(), ValidationError> {
let slug = title.to_string().to_kebab_case();
if slug.len() == 0 {
Err(ValidationError::new("empty_slug"))
2018-07-06 09:51:19 +00:00
} else if slug == "new" {
Err(ValidationError::new("invalid_slug"))
2018-06-29 12:56:00 +00:00
} else {
Ok(())
}
}
2018-04-23 14:25:39 +00:00
#[post("/~/<blog_name>/new", data = "<data>")]
fn create(blog_name: String, data: LenientForm<NewPostForm>, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>) -> Result<Redirect, Template> {
let blog = Blog::find_by_fqn(&*conn, blog_name.to_string()).unwrap();
2018-04-23 14:25:39 +00:00
let form = data.get();
let slug = form.title.to_string().to_kebab_case();
2018-09-03 13:59:02 +00:00
2018-07-06 09:51:19 +00:00
let mut errors = match form.validate() {
Ok(_) => ValidationErrors::new(),
Err(e) => e
};
if let Some(_) = Post::find_by_slug(&*conn, slug.clone(), blog.id) {
errors.add("title", ValidationError {
code: Cow::from("existing_slug"),
message: Some(Cow::from("A post with the same title already exists.")),
params: HashMap::new()
});
2018-07-06 09:51:19 +00:00
}
2018-05-24 10:42:45 +00:00
2018-07-06 09:51:19 +00:00
if errors.is_empty() {
if !user.is_author_in(&*conn, blog.clone()) {
// actually it's not "Ok"…
Ok(Redirect::to(uri!(super::blogs::details: name = blog_name)))
} else {
2018-06-20 20:58:11 +00:00
let (content, mentions) = utils::md_to_html(form.content.to_string().as_ref());
2018-05-24 10:42:45 +00:00
let post = Post::insert(&*conn, NewPost {
blog_id: blog.id,
slug: slug.to_string(),
title: form.title.to_string(),
content: SafeString::new(&content),
published: true,
license: if form.license.len() > 0 {
form.license.to_string()
} else {
Instance::get_local(&*conn).map(|i| i.default_license).unwrap_or(String::from("CC-0"))
},
ap_url: "".to_string(),
2018-09-04 11:26:13 +00:00
creation_date: None,
subtitle: form.subtitle.clone(),
source: form.content.clone(),
});
2018-06-22 15:17:53 +00:00
let post = post.update_ap_url(&*conn);
PostAuthor::insert(&*conn, NewPostAuthor {
post_id: post.id,
author_id: user.id
});
2018-05-01 15:51:49 +00:00
2018-06-20 20:58:11 +00:00
for m in mentions.into_iter() {
Mention::from_activity(&*conn, Mention::build_activity(&*conn, m), post.id, true);
2018-06-20 20:58:11 +00:00
}
let tags = form.tags.split(",").map(|t| t.trim().to_camel_case()).filter(|t| t.len() > 0);
for tag in tags {
Tag::insert(&*conn, NewTag {
tag: tag,
is_hastag: false,
post_id: post.id
});
}
let act = post.create_activity(&*conn);
let followers = user.get_followers(&*conn);
worker.execute(Thunk::of(move || broadcast(&user, act, followers)));
2018-05-01 15:51:49 +00:00
2018-07-06 09:51:19 +00:00
Ok(Redirect::to(uri!(details: blog = blog_name, slug = slug)))
}
2018-07-06 09:51:19 +00:00
} else {
Err(Template::render("posts/new", json!({
2018-09-03 13:59:02 +00:00
"account": user.to_json(&*conn),
"instance": Instance::get_local(&*conn),
"errors": errors.inner(),
"form": form
2018-07-06 09:51:19 +00:00
})))
}
2018-04-23 14:25:39 +00:00
}
2018-09-01 15:46:23 +00:00
#[get("/~/<blog_name>/<slug>/delete")]
fn delete(blog_name: String, slug: String, conn: DbConn, user: User, worker: State<Pool<ThunkWorker<()>>>) -> Redirect {
let post = Blog::find_by_fqn(&*conn, blog_name.clone())
.and_then(|blog| Post::find_by_slug(&*conn, slug.clone(), blog.id));
if let Some(post) = post {
if !post.get_authors(&*conn).into_iter().any(|a| a.id == user.id) {
Redirect::to(uri!(details: blog = blog_name.clone(), slug = slug.clone()))
} else {
let audience = user.get_followers(&*conn);
let delete_activity = post.delete(&*conn);
worker.execute(Thunk::of(move || broadcast(&user, delete_activity, audience)));
Redirect::to(uri!(super::blogs::details: name = blog_name))
}
} else {
Redirect::to(uri!(super::blogs::details: name = blog_name))
}
}