Plume/src/routes/posts.rs

687 lines
22 KiB
Rust
Raw Normal View History

use chrono::Utc;
2021-01-02 21:49:45 +01:00
use rocket::http::uri::Uri;
use rocket::request::LenientForm;
2019-03-20 17:56:17 +01:00
use rocket::response::{Flash, Redirect};
use rocket_i18n::I18n;
use std::{
2019-03-20 17:56:17 +01:00
borrow::Cow,
collections::{HashMap, HashSet},
2019-03-20 17:56:17 +01:00
time::Duration,
};
2018-07-06 11:51:19 +02:00
use validator::{Validate, ValidationError, ValidationErrors};
2018-04-23 16:25:39 +02:00
2020-01-21 07:02:03 +01:00
use crate::routes::{
comments::NewCommentForm, errors::ErrorPage, ContentLen, RemoteForm, RespondOrRedirect,
};
use crate::template_utils::{IntoContext, Ructe};
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
use plume_common::activity_pub::{broadcast, ActivityStream, ApRequest};
use plume_common::utils;
use plume_models::{
2018-05-19 09:39:59 +02:00
blogs::*,
comments::{Comment, CommentTree},
2021-01-30 13:44:29 +01:00
db_conn::DbConn,
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
inbox::inbox,
instance::Instance,
medias::Media,
2018-06-20 22:58:11 +02:00
mentions::Mention,
2018-05-19 09:39:59 +02:00
post_authors::*,
posts::*,
safe_string::SafeString,
tags::*,
Add support for generic timeline (#525) * Begin adding support for timeline * fix some bugs with parser * fmt * add error reporting for parser * add tests for timeline query parser * add rejection tests for parse * begin adding support for lists also run migration before compiling, so schema.rs is up to date * add sqlite migration * end adding lists still miss tests and query integration * cargo fmt * try to add some tests * Add some constraint to db, and fix list test and refactor other tests to use begin_transaction * add more tests for lists * add support for lists in query executor * add keywords for including/excluding boosts and likes * cargo fmt * add function to list lists used by query will make it easier to warn users when creating timeline with unknown lists * add lang support * add timeline creation error message when using unexisting lists * Update .po files * WIP: interface for timelines * don't use diesel for migrations not sure how it passed the ci on the other branch * add some tests for timeline add an int representing the order of timelines (first one will be on top, second just under...) use first() instead of limit(1).get().into_iter().nth(0) remove migrations from build artifacts as they are now compiled in * cargo fmt * remove timeline order * fix tests * add tests for timeline creation failure * cargo fmt * add tests for timelines * add test for matching direct lists and keywords * add test for language filtering * Add a more complex test for Timeline::matches, and fix TQ::matches for TQ::Or * Make the main crate compile + FMT * Use the new timeline system - Replace the old "feed" system with timelines - Display all timelines someone can access on their home page (either their personal ones, or instance timelines) - Remove functions that were used to get user/local/federated feed - Add new posts to timelines - Create a default timeline called "My feed" for everyone, and "Local feed"/"Federated feed" with timelines @fdb-hiroshima I don't know if that's how you pictured it? If you imagined it differently I can of course make changes. I hope I didn't forgot anything… * Cargo fmt * Try to fix the migration * Fix tests * Fix the test (for real this time ?) * Fix the tests ? + fmt * Use Kind::Like and Kind::Reshare when needed * Forgot to run cargo fmt once again * revert translations * fix reviewed stuff * reduce code duplication by macros * cargo fmt
2019-10-07 19:08:20 +02:00
timeline::*,
2019-03-20 17:56:17 +01:00
users::User,
2021-01-11 21:27:52 +01:00
Error, PlumeRocket, CONFIG,
2018-05-19 09:39:59 +02:00
};
#[get("/~/<blog>/<slug>?<responding_to>", rank = 4)]
2019-03-20 17:56:17 +01:00
pub fn details(
blog: String,
slug: String,
responding_to: Option<i32>,
2021-01-30 13:44:29 +01:00
conn: DbConn,
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
rockets: PlumeRocket,
2019-03-20 17:56:17 +01:00
) -> Result<Ructe, ErrorPage> {
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
let user = rockets.user.clone();
2021-01-30 13:44:29 +01:00
let blog = Blog::find_by_fqn(&conn, &blog)?;
let post = Post::find_by_slug(&conn, &slug, blog.id)?;
if !(post.published
2019-03-20 17:56:17 +01:00
|| post
2021-01-30 13:44:29 +01:00
.get_authors(&conn)?
2019-03-20 17:56:17 +01:00
.into_iter()
.any(|a| a.id == user.clone().map(|u| u.id).unwrap_or(0)))
2019-03-20 17:56:17 +01:00
{
return Ok(render!(errors::not_authorized(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
i18n!(rockets.intl.catalog, "This post isn't published yet.")
)));
}
2021-01-30 13:44:29 +01:00
let comments = CommentTree::from_post(&conn, &post, user.as_ref())?;
2021-01-30 13:44:29 +01:00
let previous = responding_to.and_then(|r| Comment::get(&conn, r).ok());
Ok(render!(posts::details(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
post.clone(),
blog,
&NewCommentForm {
warning: previous.clone().map(|p| p.spoiler_text).unwrap_or_default(),
content: previous.clone().and_then(|p| Some(format!(
"@{} {}",
2021-01-30 13:44:29 +01:00
p.get_author(&conn).ok()?.fqn,
Mention::list_for_comment(&conn, p.id).ok()?
.into_iter()
.filter_map(|m| {
let user = user.clone();
2021-01-30 13:44:29 +01:00
if let Ok(mentioned) = m.get_mentioned(&conn) {
if user.is_none() || mentioned.id != user.expect("posts::details_response: user error while listing mentions").id {
Some(format!("@{}", mentioned.fqn))
} else {
None
}
} else {
None
}
}).collect::<Vec<String>>().join(" "))
)).unwrap_or_default(),
..NewCommentForm::default()
},
ValidationErrors::default(),
2021-01-30 13:44:29 +01:00
Tag::for_post(&conn, post.id)?,
comments,
previous,
2021-01-30 13:44:29 +01:00
post.count_likes(&conn)?,
post.count_reshares(&conn)?,
user.clone().and_then(|u| u.has_liked(&conn, &post).ok()).unwrap_or(false),
user.clone().and_then(|u| u.has_reshared(&conn, &post).ok()).unwrap_or(false),
user.and_then(|u| u.is_following(&conn, post.get_authors(&conn).ok()?[0].id).ok()).unwrap_or(false),
post.get_authors(&conn)?[0].clone()
)))
2018-04-23 16:25:39 +02:00
}
#[get("/~/<blog>/<slug>", rank = 3)]
2019-03-20 17:56:17 +01:00
pub fn activity_details(
blog: String,
slug: String,
_ap: ApRequest,
2021-01-30 13:44:29 +01:00
conn: DbConn,
2019-03-20 17:56:17 +01:00
) -> Result<ActivityStream<LicensedArticle>, Option<String>> {
2021-01-30 13:44:29 +01:00
let blog = Blog::find_by_fqn(&conn, &blog).map_err(|_| None)?;
let post = Post::find_by_slug(&conn, &slug, blog.id).map_err(|_| None)?;
if post.published {
2019-03-20 17:56:17 +01:00
Ok(ActivityStream::new(
2021-01-30 13:44:29 +01:00
post.to_activity(&conn)
2019-03-20 17:56:17 +01:00
.map_err(|_| String::from("Post serialization error"))?,
))
} else {
Err(Some(String::from("Not published yet.")))
}
2018-04-23 16:25:39 +02:00
}
2018-06-04 21:57:03 +02:00
#[get("/~/<blog>/new", rank = 2)]
pub fn new_auth(blog: String, i18n: I18n) -> Flash<Redirect> {
utils::requires_login(
2019-03-20 17:56:17 +01:00
&i18n!(
i18n.catalog,
"To write a new post, you need to be logged in"
2019-03-20 17:56:17 +01:00
),
uri!(new: blog = blog),
)
2018-04-23 16:25:39 +02:00
}
#[get("/~/<blog>/new", rank = 1)]
2021-01-30 13:44:29 +01:00
pub fn new(
blog: String,
cl: ContentLen,
conn: DbConn,
rockets: PlumeRocket,
) -> Result<Ructe, ErrorPage> {
let b = Blog::find_by_fqn(&conn, &blog)?;
let user = rockets.user.clone().unwrap();
2021-01-30 13:44:29 +01:00
if !user.is_author_in(&conn, &b)? {
// TODO actually return 403 error code
return Ok(render!(errors::not_authorized(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
i18n!(rockets.intl.catalog, "You are not an author of this blog.")
2019-03-20 17:56:17 +01:00
)));
}
2021-01-30 13:44:29 +01:00
let medias = Media::for_user(&conn, user.id)?;
Ok(render!(posts::new(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
i18n!(rockets.intl.catalog, "New post"),
b,
false,
&NewPostForm {
license: Instance::get_local()?.default_license,
..NewPostForm::default()
},
true,
None,
ValidationErrors::default(),
medias,
cl.0
)))
}
2018-09-06 23:39:22 +02:00
#[get("/~/<blog>/<slug>/edit")]
2019-03-20 17:56:17 +01:00
pub fn edit(
blog: String,
slug: String,
cl: ContentLen,
2021-01-30 13:44:29 +01:00
conn: DbConn,
2019-03-20 17:56:17 +01:00
rockets: PlumeRocket,
) -> Result<Ructe, ErrorPage> {
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
let intl = &rockets.intl.catalog;
2021-01-30 13:44:29 +01:00
let b = Blog::find_by_fqn(&conn, &blog)?;
let post = Post::find_by_slug(&conn, &slug, b.id)?;
let user = rockets.user.clone().unwrap();
2018-09-06 23:39:22 +02:00
2021-01-30 13:44:29 +01:00
if !user.is_author_in(&conn, &b)? {
return Ok(render!(errors::not_authorized(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
i18n!(intl, "You are not an author of this blog.")
2019-03-20 17:56:17 +01:00
)));
}
let source = if !post.source.is_empty() {
post.source.clone()
2018-09-06 23:39:22 +02:00
} else {
post.content.get().clone() // fallback to HTML if the markdown was not stored
};
2021-01-30 13:44:29 +01:00
let medias = Media::for_user(&conn, user.id)?;
let title = post.title.clone();
Ok(render!(posts::new(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
i18n!(intl, "Edit {0}"; &title),
b,
true,
&NewPostForm {
title: post.title.clone(),
subtitle: post.subtitle.clone(),
content: source,
2021-01-30 13:44:29 +01:00
tags: Tag::for_post(&conn, post.id)?
.into_iter()
2019-03-20 17:56:17 +01:00
.filter_map(|t| if !t.is_hashtag { Some(t.tag) } else { None })
.collect::<Vec<String>>()
.join(", "),
license: post.license.clone(),
draft: true,
cover: post.cover_id,
},
!post.published,
Some(post),
ValidationErrors::default(),
medias,
cl.0
)))
2018-09-06 23:39:22 +02:00
}
#[post("/~/<blog>/<slug>/edit", data = "<form>")]
2019-03-20 17:56:17 +01:00
pub fn update(
blog: String,
slug: String,
cl: ContentLen,
form: LenientForm<NewPostForm>,
2021-01-30 13:44:29 +01:00
conn: DbConn,
2019-03-20 17:56:17 +01:00
rockets: PlumeRocket,
) -> RespondOrRedirect {
2021-01-30 13:44:29 +01:00
let b = Blog::find_by_fqn(&conn, &blog).expect("post::update: blog error");
2019-03-20 17:56:17 +01:00
let mut post =
2021-01-30 13:44:29 +01:00
Post::find_by_slug(&conn, &slug, b.id).expect("post::update: find by slug error");
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
let user = rockets.user.clone().unwrap();
let intl = &rockets.intl.catalog;
2018-09-06 23:39:22 +02:00
let new_slug = if !post.published {
2021-04-10 09:32:58 +02:00
Post::slug(&form.title).to_string()
} else {
post.slug.clone()
};
2018-09-06 23:39:22 +02:00
let mut errors = match form.validate() {
Ok(_) => ValidationErrors::new(),
2019-03-20 17:56:17 +01:00
Err(e) => e,
2018-09-06 23:39:22 +02:00
};
2018-09-07 19:51:53 +02:00
2021-01-30 13:44:29 +01:00
if new_slug != slug && Post::find_by_slug(&conn, &new_slug, b.id).is_ok() {
2019-03-20 17:56:17 +01:00
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-09-06 23:39:22 +02:00
}
if errors.is_empty() {
2019-03-20 17:56:17 +01:00
if !user
2021-01-30 13:44:29 +01:00
.is_author_in(&conn, &b)
2019-03-20 17:56:17 +01:00
.expect("posts::update: is author in error")
{
2018-09-06 23:39:22 +02:00
// actually it's not "Ok"…
Flash::error(
Redirect::to(uri!(super::blogs::details: name = blog, page = _)),
i18n!(&intl, "You are not allowed to publish on this blog."),
)
.into()
2018-09-06 23:39:22 +02:00
} else {
2019-03-20 17:56:17 +01:00
let (content, mentions, hashtags) = utils::md_to_html(
form.content.to_string().as_ref(),
Some(
&Instance::get_local()
.expect("posts::update: Error getting local instance")
.public_domain,
),
false,
Some(Media::get_media_processor(
&conn,
b.list_authors(&conn)
.expect("Could not get author list")
.iter()
.collect(),
)),
2019-03-20 17:56:17 +01:00
);
2018-09-06 23:39:22 +02:00
// update publication date if when this article is no longer a draft
let newly_published = if !post.published && !form.draft {
post.published = true;
post.creation_date = Utc::now().naive_utc();
2021-04-09 03:55:09 +02:00
post.ap_url = Post::ap_url(post.get_blog(&conn).unwrap(), &new_slug);
true
} else {
false
};
2018-09-06 23:39:22 +02:00
post.slug = new_slug.clone();
post.title = form.title.clone();
post.subtitle = form.subtitle.clone();
post.content = SafeString::new(&content);
post.source = form.content.clone();
post.license = form.license.clone();
post.cover_id = form.cover;
2021-01-30 13:44:29 +01:00
post.update(&conn).expect("post::update: update error");
2018-09-06 23:39:22 +02:00
if post.published {
2019-03-20 17:56:17 +01:00
post.update_mentions(
&conn,
mentions
.into_iter()
2021-01-30 13:44:29 +01:00
.filter_map(|m| Mention::build_activity(&conn, &m).ok())
2019-03-20 17:56:17 +01:00
.collect(),
)
.expect("post::update: mentions error");
2018-09-06 23:39:22 +02:00
}
2019-03-20 17:56:17 +01:00
let tags = form
.tags
.split(',')
2020-11-22 14:24:43 +01:00
.map(|t| t.trim())
2019-03-20 17:56:17 +01:00
.filter(|t| !t.is_empty())
.collect::<HashSet<_>>()
.into_iter()
2020-12-01 00:38:58 +01:00
.filter_map(|t| Tag::build_activity(t.to_string()).ok())
2019-03-20 17:56:17 +01:00
.collect::<Vec<_>>();
post.update_tags(&conn, tags)
.expect("post::update: tags error");
2019-03-20 17:56:17 +01:00
let hashtags = hashtags
.into_iter()
.collect::<HashSet<_>>()
.into_iter()
.filter_map(|t| Tag::build_activity(t).ok())
2019-03-20 17:56:17 +01:00
.collect::<Vec<_>>();
post.update_hashtags(&conn, hashtags)
.expect("post::update: hashtags error");
2018-09-06 23:39:22 +02:00
if post.published {
if newly_published {
2019-03-20 17:56:17 +01:00
let act = post
.create_activity(&conn)
.expect("post::update: act error");
2021-01-30 13:44:29 +01:00
let dest = User::one_by_instance(&conn).expect("post::update: dest error");
2021-01-11 21:27:52 +01:00
rockets
.worker
.execute(move || broadcast(&user, act, dest, CONFIG.proxy().cloned()));
Add support for generic timeline (#525) * Begin adding support for timeline * fix some bugs with parser * fmt * add error reporting for parser * add tests for timeline query parser * add rejection tests for parse * begin adding support for lists also run migration before compiling, so schema.rs is up to date * add sqlite migration * end adding lists still miss tests and query integration * cargo fmt * try to add some tests * Add some constraint to db, and fix list test and refactor other tests to use begin_transaction * add more tests for lists * add support for lists in query executor * add keywords for including/excluding boosts and likes * cargo fmt * add function to list lists used by query will make it easier to warn users when creating timeline with unknown lists * add lang support * add timeline creation error message when using unexisting lists * Update .po files * WIP: interface for timelines * don't use diesel for migrations not sure how it passed the ci on the other branch * add some tests for timeline add an int representing the order of timelines (first one will be on top, second just under...) use first() instead of limit(1).get().into_iter().nth(0) remove migrations from build artifacts as they are now compiled in * cargo fmt * remove timeline order * fix tests * add tests for timeline creation failure * cargo fmt * add tests for timelines * add test for matching direct lists and keywords * add test for language filtering * Add a more complex test for Timeline::matches, and fix TQ::matches for TQ::Or * Make the main crate compile + FMT * Use the new timeline system - Replace the old "feed" system with timelines - Display all timelines someone can access on their home page (either their personal ones, or instance timelines) - Remove functions that were used to get user/local/federated feed - Add new posts to timelines - Create a default timeline called "My feed" for everyone, and "Local feed"/"Federated feed" with timelines @fdb-hiroshima I don't know if that's how you pictured it? If you imagined it differently I can of course make changes. I hope I didn't forgot anything… * Cargo fmt * Try to fix the migration * Fix tests * Fix the test (for real this time ?) * Fix the tests ? + fmt * Use Kind::Like and Kind::Reshare when needed * Forgot to run cargo fmt once again * revert translations * fix reviewed stuff * reduce code duplication by macros * cargo fmt
2019-10-07 19:08:20 +02:00
2021-01-30 13:44:29 +01:00
Timeline::add_to_all_timelines(&conn, &post, Kind::Original).ok();
} else {
2019-03-20 17:56:17 +01:00
let act = post
2021-01-30 13:44:29 +01:00
.update_activity(&conn)
2019-03-20 17:56:17 +01:00
.expect("post::update: act error");
2021-01-30 13:44:29 +01:00
let dest = User::one_by_instance(&conn).expect("posts::update: dest error");
2021-01-11 21:27:52 +01:00
rockets
.worker
.execute(move || broadcast(&user, act, dest, CONFIG.proxy().cloned()));
}
}
2018-09-06 23:39:22 +02:00
Flash::success(
2021-01-15 17:13:45 +01:00
Redirect::to(uri!(
details: blog = blog,
slug = new_slug,
responding_to = _
)),
i18n!(intl, "Your article has been updated."),
)
.into()
2018-09-06 23:39:22 +02:00
}
} else {
2021-01-30 13:44:29 +01:00
let medias = Media::for_user(&conn, user.id).expect("posts:update: medias error");
render!(posts::new(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
i18n!(intl, "Edit {0}"; &form.title),
b,
true,
&*form,
form.draft,
Some(post),
errors,
medias,
cl.0
))
.into()
2018-09-06 23:39:22 +02:00
}
}
#[derive(Default, FromForm, Validate)]
pub struct NewPostForm {
#[validate(custom(function = "valid_slug", message = "Invalid title"))]
2018-04-23 16:25:39 +02:00
pub title: String,
2018-09-04 13:26:13 +02:00
pub subtitle: String,
2018-04-23 16:25:39 +02:00
pub content: String,
pub tags: String,
pub license: String,
pub draft: bool,
pub cover: Option<i32>,
2018-04-23 16:25:39 +02:00
}
pub fn valid_slug(title: &str) -> Result<(), ValidationError> {
2021-04-10 09:32:58 +02:00
let slug = Post::slug(title);
if slug.is_empty() {
2018-06-29 14:56:00 +02:00
Err(ValidationError::new("empty_slug"))
2018-07-06 11:51:19 +02:00
} else if slug == "new" {
Err(ValidationError::new("invalid_slug"))
2018-06-29 14:56:00 +02:00
} else {
Ok(())
}
}
#[post("/~/<blog_name>/new", data = "<form>")]
2019-03-20 17:56:17 +01:00
pub fn create(
blog_name: String,
form: LenientForm<NewPostForm>,
cl: ContentLen,
2021-01-30 13:44:29 +01:00
conn: DbConn,
2019-03-20 17:56:17 +01:00
rockets: PlumeRocket,
) -> Result<RespondOrRedirect, ErrorPage> {
2021-01-30 13:44:29 +01:00
let blog = Blog::find_by_fqn(&conn, &blog_name).expect("post::create: blog error");
2021-04-10 09:32:58 +02:00
let slug = Post::slug(&form.title);
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
let user = rockets.user.clone().unwrap();
2018-09-03 15:59:02 +02:00
2018-07-06 11:51:19 +02:00
let mut errors = match form.validate() {
Ok(_) => ValidationErrors::new(),
2019-03-20 17:56:17 +01:00
Err(e) => e,
2018-07-06 11:51:19 +02:00
};
2021-11-27 23:53:13 +01:00
if Post::find_by_slug(&conn, slug, blog.id).is_ok() {
2019-03-20 17:56:17 +01:00
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 11:51:19 +02:00
}
2018-05-24 12:42:45 +02:00
2018-07-06 11:51:19 +02:00
if errors.is_empty() {
2019-03-20 17:56:17 +01:00
if !user
2021-01-30 13:44:29 +01:00
.is_author_in(&conn, &blog)
2019-03-20 17:56:17 +01:00
.expect("post::create: is author in error")
{
2018-07-06 11:51:19 +02:00
// actually it's not "Ok"…
return Ok(Flash::error(
Redirect::to(uri!(super::blogs::details: name = blog_name, page = _)),
i18n!(
&rockets.intl.catalog,
"You are not allowed to publish on this blog."
),
)
.into());
}
let (content, mentions, hashtags) = utils::md_to_html(
form.content.to_string().as_ref(),
Some(
&Instance::get_local()
.expect("post::create: local instance error")
.public_domain,
),
false,
Some(Media::get_media_processor(
&conn,
blog.list_authors(&conn)
.expect("Could not get author list")
.iter()
.collect(),
)),
);
2019-03-20 17:56:17 +01:00
let post = Post::insert(
2021-01-30 13:44:29 +01:00
&conn,
2019-03-20 17:56:17 +01:00
NewPost {
blog_id: blog.id,
slug: slug.to_string(),
title: form.title.to_string(),
content: SafeString::new(&content),
published: !form.draft,
license: form.license.clone(),
ap_url: "".to_string(),
creation_date: None,
subtitle: form.subtitle.clone(),
source: form.content.clone(),
cover_id: form.cover,
},
2019-03-20 17:56:17 +01:00
)
.expect("post::create: post save error");
PostAuthor::insert(
2021-01-30 13:44:29 +01:00
&conn,
2019-03-20 17:56:17 +01:00
NewPostAuthor {
post_id: post.id,
author_id: user.id,
},
)
.expect("post::create: author save error");
2019-03-20 17:56:17 +01:00
let tags = form
.tags
.split(',')
2020-11-22 14:24:43 +01:00
.map(|t| t.trim())
.filter(|t| !t.is_empty())
.collect::<HashSet<_>>();
for tag in tags {
2019-03-20 17:56:17 +01:00
Tag::insert(
2021-01-30 13:44:29 +01:00
&conn,
2019-03-20 17:56:17 +01:00
NewTag {
2020-11-22 14:24:43 +01:00
tag: tag.to_string(),
2019-03-20 17:56:17 +01:00
is_hashtag: false,
post_id: post.id,
},
)
.expect("post::create: tags save error");
}
for hashtag in hashtags {
2019-03-20 17:56:17 +01:00
Tag::insert(
2021-01-30 13:44:29 +01:00
&conn,
2019-03-20 17:56:17 +01:00
NewTag {
2020-11-22 14:24:43 +01:00
tag: hashtag,
2019-03-20 17:56:17 +01:00
is_hashtag: true,
post_id: post.id,
},
)
.expect("post::create: hashtags save error");
}
if post.published {
for m in mentions {
Mention::from_activity(
2021-01-30 13:44:29 +01:00
&conn,
&Mention::build_activity(&conn, &m).expect("post::create: mention build error"),
post.id,
true,
2019-03-20 17:56:17 +01:00
true,
)
.expect("post::create: mention save error");
}
2018-05-01 17:51:49 +02:00
2019-03-20 17:56:17 +01:00
let act = post
2021-01-30 13:44:29 +01:00
.create_activity(&conn)
2019-03-20 17:56:17 +01:00
.expect("posts::create: activity error");
2021-01-30 13:44:29 +01:00
let dest = User::one_by_instance(&conn).expect("posts::create: dest error");
Add support for generic timeline (#525) * Begin adding support for timeline * fix some bugs with parser * fmt * add error reporting for parser * add tests for timeline query parser * add rejection tests for parse * begin adding support for lists also run migration before compiling, so schema.rs is up to date * add sqlite migration * end adding lists still miss tests and query integration * cargo fmt * try to add some tests * Add some constraint to db, and fix list test and refactor other tests to use begin_transaction * add more tests for lists * add support for lists in query executor * add keywords for including/excluding boosts and likes * cargo fmt * add function to list lists used by query will make it easier to warn users when creating timeline with unknown lists * add lang support * add timeline creation error message when using unexisting lists * Update .po files * WIP: interface for timelines * don't use diesel for migrations not sure how it passed the ci on the other branch * add some tests for timeline add an int representing the order of timelines (first one will be on top, second just under...) use first() instead of limit(1).get().into_iter().nth(0) remove migrations from build artifacts as they are now compiled in * cargo fmt * remove timeline order * fix tests * add tests for timeline creation failure * cargo fmt * add tests for timelines * add test for matching direct lists and keywords * add test for language filtering * Add a more complex test for Timeline::matches, and fix TQ::matches for TQ::Or * Make the main crate compile + FMT * Use the new timeline system - Replace the old "feed" system with timelines - Display all timelines someone can access on their home page (either their personal ones, or instance timelines) - Remove functions that were used to get user/local/federated feed - Add new posts to timelines - Create a default timeline called "My feed" for everyone, and "Local feed"/"Federated feed" with timelines @fdb-hiroshima I don't know if that's how you pictured it? If you imagined it differently I can of course make changes. I hope I didn't forgot anything… * Cargo fmt * Try to fix the migration * Fix tests * Fix the test (for real this time ?) * Fix the tests ? + fmt * Use Kind::Like and Kind::Reshare when needed * Forgot to run cargo fmt once again * revert translations * fix reviewed stuff * reduce code duplication by macros * cargo fmt
2019-10-07 19:08:20 +02:00
let worker = &rockets.worker;
2021-01-11 21:27:52 +01:00
worker.execute(move || broadcast(&user, act, dest, CONFIG.proxy().cloned()));
Add support for generic timeline (#525) * Begin adding support for timeline * fix some bugs with parser * fmt * add error reporting for parser * add tests for timeline query parser * add rejection tests for parse * begin adding support for lists also run migration before compiling, so schema.rs is up to date * add sqlite migration * end adding lists still miss tests and query integration * cargo fmt * try to add some tests * Add some constraint to db, and fix list test and refactor other tests to use begin_transaction * add more tests for lists * add support for lists in query executor * add keywords for including/excluding boosts and likes * cargo fmt * add function to list lists used by query will make it easier to warn users when creating timeline with unknown lists * add lang support * add timeline creation error message when using unexisting lists * Update .po files * WIP: interface for timelines * don't use diesel for migrations not sure how it passed the ci on the other branch * add some tests for timeline add an int representing the order of timelines (first one will be on top, second just under...) use first() instead of limit(1).get().into_iter().nth(0) remove migrations from build artifacts as they are now compiled in * cargo fmt * remove timeline order * fix tests * add tests for timeline creation failure * cargo fmt * add tests for timelines * add test for matching direct lists and keywords * add test for language filtering * Add a more complex test for Timeline::matches, and fix TQ::matches for TQ::Or * Make the main crate compile + FMT * Use the new timeline system - Replace the old "feed" system with timelines - Display all timelines someone can access on their home page (either their personal ones, or instance timelines) - Remove functions that were used to get user/local/federated feed - Add new posts to timelines - Create a default timeline called "My feed" for everyone, and "Local feed"/"Federated feed" with timelines @fdb-hiroshima I don't know if that's how you pictured it? If you imagined it differently I can of course make changes. I hope I didn't forgot anything… * Cargo fmt * Try to fix the migration * Fix tests * Fix the test (for real this time ?) * Fix the tests ? + fmt * Use Kind::Like and Kind::Reshare when needed * Forgot to run cargo fmt once again * revert translations * fix reviewed stuff * reduce code duplication by macros * cargo fmt
2019-10-07 19:08:20 +02:00
2021-01-30 13:44:29 +01:00
Timeline::add_to_all_timelines(&conn, &post, Kind::Original)?;
}
Ok(Flash::success(
2021-01-15 17:13:45 +01:00
Redirect::to(uri!(
details: blog = blog_name,
slug = slug,
responding_to = _
)),
i18n!(&rockets.intl.catalog, "Your article has been saved."),
)
.into())
2018-07-06 11:51:19 +02:00
} else {
2021-01-30 13:44:29 +01:00
let medias = Media::for_user(&conn, user.id).expect("posts::create: medias error");
Ok(render!(posts::new(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
i18n!(rockets.intl.catalog, "New article"),
blog,
false,
&*form,
form.draft,
None,
errors,
medias,
cl.0
))
.into())
}
2018-04-23 16:25:39 +02:00
}
#[post("/~/<blog_name>/<slug>/delete")]
2019-03-20 17:56:17 +01:00
pub fn delete(
blog_name: String,
slug: String,
2021-01-30 13:44:29 +01:00
conn: DbConn,
2019-03-20 17:56:17 +01:00
rockets: PlumeRocket,
intl: I18n,
) -> Result<Flash<Redirect>, ErrorPage> {
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
let user = rockets.user.clone().unwrap();
2021-01-30 13:44:29 +01:00
let post = Blog::find_by_fqn(&conn, &blog_name)
.and_then(|blog| Post::find_by_slug(&conn, &slug, blog.id));
if let Ok(post) = post {
2019-03-20 17:56:17 +01:00
if !post
2021-01-30 13:44:29 +01:00
.get_authors(&conn)?
2019-03-20 17:56:17 +01:00
.into_iter()
.any(|a| a.id == user.id)
{
return Ok(Flash::error(
2021-01-15 17:13:45 +01:00
Redirect::to(uri!(
details: blog = blog_name,
slug = slug,
responding_to = _
)),
i18n!(intl.catalog, "You are not allowed to delete this article."),
2019-03-20 17:56:17 +01:00
));
}
2021-01-30 13:44:29 +01:00
let dest = User::one_by_instance(&conn)?;
let delete_activity = post.build_delete(&conn)?;
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
inbox(
2021-01-30 13:44:29 +01:00
&conn,
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
serde_json::to_value(&delete_activity).map_err(Error::from)?,
)?;
let user_c = user.clone();
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
rockets
.worker
2021-01-11 21:27:52 +01:00
.execute(move || broadcast(&user_c, delete_activity, dest, CONFIG.proxy().cloned()));
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
rockets
.worker
.execute_after(Duration::from_secs(10 * 60), move || {
2021-01-30 13:44:29 +01:00
user.rotate_keypair(&conn)
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
.expect("Failed to rotate keypair");
});
Ok(Flash::success(
Redirect::to(uri!(super::blogs::details: name = blog_name, page = _)),
i18n!(intl.catalog, "Your article has been deleted."),
2019-03-20 17:56:17 +01:00
))
} else {
Ok(Flash::error(Redirect::to(
2019-03-20 17:56:17 +01:00
uri!(super::blogs::details: name = blog_name, page = _),
), i18n!(intl.catalog, "It looks like the article you tried to delete doesn't exist. Maybe it is already gone?")))
}
}
#[get("/~/<blog_name>/<slug>/remote_interact")]
pub fn remote_interact(
2021-01-30 13:44:29 +01:00
conn: DbConn,
rockets: PlumeRocket,
blog_name: String,
slug: String,
) -> Result<Ructe, ErrorPage> {
2021-01-30 13:44:29 +01:00
let target = Blog::find_by_fqn(&conn, &blog_name)
.and_then(|blog| Post::find_by_slug(&conn, &slug, blog.id))?;
Ok(render!(posts::remote_interact(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
target,
super::session::LoginForm::default(),
ValidationErrors::default(),
RemoteForm::default(),
ValidationErrors::default()
)))
}
#[post("/~/<blog_name>/<slug>/remote_interact", data = "<remote>")]
pub fn remote_interact_post(
2021-01-30 13:44:29 +01:00
conn: DbConn,
rockets: PlumeRocket,
blog_name: String,
slug: String,
remote: LenientForm<RemoteForm>,
) -> Result<RespondOrRedirect, ErrorPage> {
2021-01-30 13:44:29 +01:00
let target = Blog::find_by_fqn(&conn, &blog_name)
.and_then(|blog| Post::find_by_slug(&conn, &slug, blog.id))?;
if let Some(uri) = User::fetch_remote_interact_uri(&remote.remote)
.ok()
2021-01-02 21:49:45 +01:00
.map(|uri| uri.replace("{uri}", &Uri::percent_encode(&target.ap_url)))
{
Ok(Redirect::to(uri).into())
} else {
let mut errs = ValidationErrors::new();
errs.add("remote", ValidationError {
code: Cow::from("invalid_remote"),
message: Some(Cow::from(i18n!(rockets.intl.catalog, "Couldn't obtain enough information about your account. Please make sure your username is correct."))),
params: HashMap::new(),
});
//could not get your remote url?
Ok(render!(posts::remote_interact(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
target,
super::session::LoginForm::default(),
ValidationErrors::default(),
remote.clone(),
errs
))
.into())
}
}