Plume/plume-models/src/comments.rs

603 lines
21 KiB
Rust
Raw Permalink Normal View History

2020-01-21 06:02:03 +00:00
use crate::{
comment_seers::{CommentSeers, NewCommentSeers},
instance::Instance,
medias::Media,
mentions::Mention,
notifications::*,
posts::Post,
safe_string::SafeString,
schema::comments,
users::User,
Connection, Error, Result, CONFIG,
2020-01-21 06:02:03 +00:00
};
2022-04-03 11:51:36 +00:00
use activitystreams::{
activity::{Create, Delete},
2022-04-23 13:46:49 +00:00
base::{AnyBase, Base},
2022-04-03 12:44:21 +00:00
iri_string::types::IriString,
link::{self, kind::MentionType},
object::{Note, Tombstone},
2022-04-03 12:44:21 +00:00
prelude::*,
2022-04-23 13:46:49 +00:00
primitives::OneOrMany,
2022-04-03 12:44:21 +00:00
time::OffsetDateTime,
2022-04-03 11:51:36 +00:00
};
use chrono::{self, NaiveDateTime};
use diesel::{self, ExpressionMethods, QueryDsl, RunQueryDsl, SaveChangesDsl};
2020-01-21 06:02:03 +00:00
use plume_common::{
activity_pub::{
2022-05-02 08:43:03 +00:00
inbox::{AsActor, AsObject, FromId},
2021-11-24 13:50:16 +00:00
sign::Signer,
IntoId, ToAsString, ToAsUri, PUBLIC_VISIBILITY,
2020-01-21 06:02:03 +00:00
},
utils,
};
use std::collections::HashSet;
#[derive(Queryable, Identifiable, Clone, AsChangeset)]
2018-05-09 20:35:02 +00:00
pub struct Comment {
pub id: i32,
pub content: SafeString,
2018-05-09 20:35:02 +00:00
pub in_response_to_id: Option<i32>,
pub post_id: i32,
pub author_id: i32,
2018-09-27 21:06:40 +00:00
pub creation_date: NaiveDateTime,
2018-05-09 20:35:02 +00:00
pub ap_url: Option<String>,
pub sensitive: bool,
pub spoiler_text: String,
pub public_visibility: bool,
2018-05-09 20:35:02 +00:00
}
#[derive(Insertable, Default)]
2018-05-09 20:35:02 +00:00
#[table_name = "comments"]
pub struct NewComment {
pub content: SafeString,
2018-05-09 20:35:02 +00:00
pub in_response_to_id: Option<i32>,
pub post_id: i32,
pub author_id: i32,
pub ap_url: Option<String>,
pub sensitive: bool,
pub spoiler_text: String,
pub public_visibility: bool,
2018-05-09 20:35:02 +00:00
}
impl Comment {
insert!(comments, NewComment, |inserted, conn| {
if inserted.ap_url.is_none() {
2019-03-20 16:56:17 +00:00
inserted.ap_url = Some(format!(
2022-01-09 04:10:54 +00:00
"{}/comment/{}",
2019-03-20 16:56:17 +00:00
inserted.get_post(conn)?.ap_url,
inserted.id
));
let _: Comment = inserted.save_changes(conn)?;
}
Ok(inserted)
});
get!(comments);
2018-06-21 10:38:07 +00:00
list_by!(comments, list_by_post, post_id as i32);
list_by!(comments, list_by_author, author_id as i32);
find_by!(comments, find_by_ap_url, ap_url as &str);
2018-05-10 10:52:56 +00:00
pub fn get_author(&self, conn: &Connection) -> Result<User> {
User::get(conn, self.author_id)
2018-05-10 09:44:57 +00:00
}
2018-05-10 15:36:32 +00:00
pub fn get_post(&self, conn: &Connection) -> Result<Post> {
Post::get(conn, self.post_id)
2018-05-10 15:36:32 +00:00
}
2018-05-18 22:04:30 +00:00
pub fn count_local(conn: &Connection) -> Result<i64> {
2020-01-21 06:02:03 +00:00
use crate::schema::users;
let local_authors = users::table
.filter(users::instance_id.eq(Instance::get_local()?.id))
.select(users::id);
comments::table
.filter(comments::author_id.eq_any(local_authors))
.count()
.get_result(conn)
.map_err(Error::from)
2018-06-10 19:33:42 +00:00
}
pub fn get_responses(&self, conn: &Connection) -> Result<Vec<Comment>> {
2019-03-20 16:56:17 +00:00
comments::table
.filter(comments::in_response_to_id.eq(self.id))
.load::<Comment>(conn)
.map_err(Error::from)
}
pub fn can_see(&self, conn: &Connection, user: Option<&User>) -> bool {
2019-03-20 16:56:17 +00:00
self.public_visibility
|| user
.as_ref()
.map(|u| CommentSeers::can_see(conn, self, u).unwrap_or(false))
.unwrap_or(false)
}
2022-12-16 21:51:14 +00:00
pub fn to_activity(&self, conn: &Connection) -> Result<Note> {
2022-04-03 11:51:36 +00:00
let author = User::get(conn, self.author_id)?;
let (html, mentions, _hashtags) = utils::md_to_html(
self.content.get().as_ref(),
Some(&Instance::get_local()?.public_domain),
true,
Some(Media::get_media_processor(conn, vec![&author])),
);
let mut note = Note::new();
2022-04-03 11:51:36 +00:00
let to = vec![PUBLIC_VISIBILITY.parse::<IriString>()?];
note.set_id(
self.ap_url
.clone()
.unwrap_or_default()
.parse::<IriString>()?,
);
note.set_summary(self.spoiler_text.clone());
note.set_content(html);
note.set_in_reply_to(self.in_response_to_id.map_or_else(
|| Post::get(conn, self.post_id).map(|post| post.ap_url),
|id| Comment::get(conn, id).map(|comment| comment.ap_url.unwrap_or_default()),
)?);
note.set_published(
OffsetDateTime::from_unix_timestamp_nanos(self.creation_date.timestamp_nanos().into())
.expect("OffsetDateTime"),
);
note.set_attributed_to(author.into_id().parse::<IriString>()?);
note.set_many_tos(to);
note.set_many_tags(mentions.into_iter().filter_map(|m| {
2022-05-02 16:26:15 +00:00
Mention::build_activity(conn, &m)
2022-04-03 11:51:36 +00:00
.map(|mention| mention.into_any_base().expect("Can convert"))
.ok()
}));
Ok(note)
}
2022-12-16 21:51:14 +00:00
pub fn create_activity(&self, conn: &Connection) -> Result<Create> {
2022-04-03 12:33:19 +00:00
let author = User::get(conn, self.author_id)?;
2022-05-02 16:26:15 +00:00
let note = self.to_activity(conn)?;
2022-04-23 16:37:30 +00:00
let note_clone = note.clone();
2022-04-03 12:33:19 +00:00
let mut act = Create::new(
2022-04-03 12:33:19 +00:00
author.into_id().parse::<IriString>()?,
Base::retract(note)?.into_generic()?,
);
act.set_id(
format!(
"{}/activity",
self.ap_url.clone().ok_or(Error::MissingApProperty)?,
)
.parse::<IriString>()?,
);
2022-04-23 16:37:30 +00:00
act.set_many_tos(
note_clone
.to()
.iter()
.flat_map(|tos| tos.iter().map(|to| to.to_owned())),
);
act.set_many_ccs(vec![self.get_author(conn)?.followers_endpoint]);
2022-04-03 12:33:19 +00:00
Ok(act)
}
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 17:31:47 +00:00
pub fn notify(&self, conn: &Connection) -> Result<()> {
for author in self.get_post(conn)?.get_authors(conn)? {
if Mention::list_for_comment(conn, self.id)?
.iter()
.all(|m| m.get_mentioned(conn).map(|u| u != author).unwrap_or(true))
&& author.is_local()
{
Notification::insert(
conn,
NewNotification {
kind: notification_kind::COMMENT.to_string(),
object_id: self.id,
user_id: author.id,
},
)?;
}
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 17:31:47 +00:00
}
Ok(())
}
2022-05-02 17:11:46 +00:00
pub fn build_delete(&self, conn: &Connection) -> Result<Delete> {
let mut tombstone = Tombstone::new();
2022-04-03 12:44:21 +00:00
tombstone.set_id(
self.ap_url
.as_ref()
.ok_or(Error::MissingApProperty)?
.parse::<IriString>()?,
);
let mut act = Delete::new(
2022-04-03 12:44:21 +00:00
self.get_author(conn)?.into_id().parse::<IriString>()?,
Base::retract(tombstone)?.into_generic()?,
);
act.set_id(format!("{}#delete", self.ap_url.clone().unwrap()).parse::<IriString>()?);
act.set_many_tos(vec![PUBLIC_VISIBILITY.parse::<IriString>()?]);
Ok(act)
}
2018-05-10 15:36:32 +00:00
}
2022-12-16 21:51:14 +00:00
impl FromId<Connection> for Comment {
2022-04-23 13:46:49 +00:00
type Error = Error;
type Object = Note;
2022-04-23 13:46:49 +00:00
2022-12-16 21:51:14 +00:00
fn from_db(conn: &Connection, id: &str) -> Result<Self> {
2022-04-23 13:46:49 +00:00
Self::find_by_ap_url(conn, id)
}
2022-12-16 21:51:14 +00:00
fn from_activity(conn: &Connection, note: Note) -> Result<Self> {
2022-04-23 13:46:49 +00:00
let comm = {
let previous_url = note
.in_reply_to()
.ok_or(Error::MissingApProperty)?
.iter()
.next()
.ok_or(Error::MissingApProperty)?
2022-04-30 19:45:56 +00:00
.id()
2022-04-23 13:46:49 +00:00
.ok_or(Error::MissingApProperty)?;
2022-04-30 19:45:56 +00:00
let previous_comment = Comment::find_by_ap_url(conn, previous_url.as_str());
2022-04-23 13:46:49 +00:00
let is_public = |v: &Option<&OneOrMany<AnyBase>>| match v {
Some(one_or_many) => one_or_many.iter().any(|any_base| {
2022-04-30 19:45:56 +00:00
let id = any_base.id();
id.is_some() && id.unwrap() == PUBLIC_VISIBILITY
2022-04-23 13:46:49 +00:00
}),
None => false,
};
let public_visibility = is_public(&note.to())
|| is_public(&note.bto())
|| is_public(&note.cc())
|| is_public(&note.bcc());
let summary = note.summary().and_then(|summary| summary.to_as_string());
let sensitive = summary.is_some();
let comm = Comment::insert(
conn,
NewComment {
content: SafeString::new(
&note
.content()
.ok_or(Error::MissingApProperty)?
.to_as_string()
.ok_or(Error::InvalidValue)?,
),
spoiler_text: summary.unwrap_or_default(),
ap_url: Some(
note.id_unchecked()
.ok_or(Error::MissingApProperty)?
.to_string(),
),
in_response_to_id: previous_comment.iter().map(|c| c.id).next(),
post_id: previous_comment.map(|c| c.post_id).or_else(|_| {
2022-04-30 19:45:56 +00:00
Ok(Post::find_by_ap_url(conn, previous_url.as_str())?.id) as Result<i32>
2022-04-23 13:46:49 +00:00
})?,
2022-05-02 10:24:36 +00:00
author_id: User::from_id(
2022-04-23 13:46:49 +00:00
conn,
&note
.attributed_to()
.ok_or(Error::MissingApProperty)?
.to_as_uri()
.ok_or(Error::MissingApProperty)?,
None,
CONFIG.proxy(),
)
.map_err(|(_, e)| e)?
.id,
sensitive,
public_visibility,
},
)?;
// save mentions
if let Some(tags) = note.tag() {
let author_url = &Post::get(conn, comm.post_id)?.get_authors(conn)?[0].ap_url;
for tag in tags.iter() {
let m = tag.clone().extend::<link::Mention, MentionType>()?; // FIXME: Don't clone
2022-04-23 13:46:49 +00:00
if m.is_none() {
continue;
}
let m = m.unwrap();
let not_author = m.href().ok_or(Error::MissingApProperty)? != author_url;
let _ = Mention::from_activity(conn, &m, comm.id, false, not_author);
2022-04-23 13:46:49 +00:00
}
}
comm
};
if !comm.public_visibility {
let mut receiver_ids = HashSet::new();
let mut receivers_id = |v: Option<&'_ OneOrMany<AnyBase>>| {
if let Some(one_or_many) = v {
for any_base in one_or_many.iter() {
if let Some(id) = any_base.id() {
receiver_ids.insert(id.to_string());
}
}
}
};
receivers_id(note.to());
receivers_id(note.cc());
receivers_id(note.bto());
receivers_id(note.bcc());
let receivers_ap_url = receiver_ids
.into_iter()
.flat_map(|v| {
2022-05-02 10:24:36 +00:00
if let Ok(user) = User::from_id(conn, v.as_ref(), None, CONFIG.proxy()) {
2022-04-23 13:46:49 +00:00
vec![user]
} else {
vec![] // TODO try to fetch collection
}
})
.filter(|u| u.get_instance(conn).map(|i| i.local).unwrap_or(false))
.collect::<HashSet<User>>(); //remove duplicates (prevent db error)
for user in &receivers_ap_url {
CommentSeers::insert(
conn,
NewCommentSeers {
comment_id: comm.id,
user_id: user.id,
},
)?;
}
}
comm.notify(conn)?;
Ok(comm)
}
2022-05-02 16:24:22 +00:00
fn get_sender() -> &'static dyn Signer {
2022-04-23 13:46:49 +00:00
Instance::get_local_instance_user().expect("Failed to local instance user")
2021-11-24 13:50:16 +00:00
}
}
2022-12-16 21:51:14 +00:00
impl AsObject<User, Create, &Connection> for Comment {
2022-04-23 16:49:27 +00:00
type Error = Error;
type Output = Self;
2022-12-16 21:51:14 +00:00
fn activity(self, _conn: &Connection, _actor: User, _id: &str) -> Result<Self> {
2022-04-23 16:49:27 +00:00
// The actual creation takes place in the FromId impl
Ok(self)
}
}
2022-12-16 21:51:14 +00:00
impl AsObject<User, Delete, &Connection> for Comment {
2022-04-23 16:49:27 +00:00
type Error = Error;
type Output = ();
2022-12-16 21:51:14 +00:00
fn activity(self, conn: &Connection, actor: User, _id: &str) -> Result<()> {
2022-04-23 16:49:27 +00:00
if self.author_id != actor.id {
return Err(Error::Unauthorized);
}
for m in Mention::list_for_comment(conn, self.id)? {
for n in Notification::find_for_mention(conn, &m)? {
n.delete(conn)?;
}
m.delete(conn)?;
}
for n in Notification::find_for_comment(conn, &self)? {
2022-12-16 21:51:14 +00:00
n.delete(conn)?;
2022-04-23 16:49:27 +00:00
}
diesel::update(comments::table)
.filter(comments::in_response_to_id.eq(self.id))
.set(comments::in_response_to_id.eq(self.in_response_to_id))
2022-12-16 21:51:14 +00:00
.execute(conn)?;
diesel::delete(&self).execute(conn)?;
2022-04-23 16:49:27 +00:00
Ok(())
}
}
pub struct CommentTree {
pub comment: Comment,
pub responses: Vec<CommentTree>,
}
impl CommentTree {
pub fn from_post(conn: &Connection, p: &Post, user: Option<&User>) -> Result<Vec<Self>> {
2019-03-20 16:56:17 +00:00
Ok(Comment::list_by_post(conn, p.id)?
.into_iter()
.filter(|c| c.in_response_to_id.is_none())
.filter(|c| c.can_see(conn, user))
.filter_map(|c| Self::from_comment(conn, c, user).ok())
.collect())
}
pub fn from_comment(conn: &Connection, comment: Comment, user: Option<&User>) -> Result<Self> {
2019-03-20 16:56:17 +00:00
let responses = comment
.get_responses(conn)?
.into_iter()
.filter(|c| c.can_see(conn, user))
.filter_map(|c| Self::from_comment(conn, c, user).ok())
.collect();
2019-03-20 16:56:17 +00:00
Ok(CommentTree { comment, responses })
}
}
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 17:31:47 +00:00
#[cfg(test)]
mod tests {
use super::*;
use crate::blogs::Blog;
2023-03-19 16:21:39 +00:00
use crate::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 17:31:47 +00:00
use crate::inbox::{inbox, tests::fill_database, InboxResult};
use crate::safe_string::SafeString;
2022-01-09 04:10:38 +00:00
use crate::tests::{db, format_datetime};
use assert_json_diff::assert_json_eq;
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 17:31:47 +00:00
use diesel::Connection;
2022-01-09 04:10:38 +00:00
use serde_json::{json, to_value};
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 17:31:47 +00:00
fn prepare_activity(conn: &DbConn) -> (Comment, Vec<Post>, Vec<User>, Vec<Blog>) {
2023-01-02 17:45:13 +00:00
let (posts, users, blogs) = fill_database(conn);
let comment = Comment::insert(
conn,
NewComment {
content: SafeString::new("My comment, mentioning to @user"),
in_response_to_id: None,
post_id: posts[0].id,
author_id: users[0].id,
ap_url: None,
sensitive: true,
spoiler_text: "My CW".into(),
public_visibility: true,
},
)
.unwrap();
(comment, posts, users, blogs)
}
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 17:31:47 +00:00
// creates a post, get it's Create activity, delete the post,
2022-04-23 16:37:03 +00:00
// "send" the Create to the inbox, and check it works
#[test]
2022-05-02 17:11:46 +00:00
fn self_federation() {
2022-04-23 16:37:03 +00:00
let conn = &db();
conn.test_transaction::<_, (), _>(|| {
2023-01-02 17:45:13 +00:00
let (original_comm, posts, users, _blogs) = prepare_activity(conn);
let act = original_comm.create_activity(conn).unwrap();
2022-04-23 16:37:03 +00:00
assert_json_eq!(to_value(&act).unwrap(), json!({
"actor": "https://plu.me/@/admin/",
"cc": ["https://plu.me/@/admin/followers"],
"id": format!("https://plu.me/~/BlogName/testing/comment/{}/activity", original_comm.id),
"object": {
"attributedTo": "https://plu.me/@/admin/",
"content": r###"<p dir="auto">My comment, mentioning to <a href="https://plu.me/@/user/" title="user">@user</a></p>
"###,
"id": format!("https://plu.me/~/BlogName/testing/comment/{}", original_comm.id),
"inReplyTo": "https://plu.me/~/BlogName/testing",
"published": format_datetime(&original_comm.creation_date),
"summary": "My CW",
"tag": [
{
"href": "https://plu.me/@/user/",
"name": "@user",
"type": "Mention"
}
],
"to": ["https://www.w3.org/ns/activitystreams#Public"],
"type": "Note"
},
"to": ["https://www.w3.org/ns/activitystreams#Public"],
"type": "Create",
}));
let reply = Comment::insert(
conn,
NewComment {
content: SafeString::new(""),
in_response_to_id: Some(original_comm.id),
post_id: posts[0].id,
author_id: users[1].id,
ap_url: None,
sensitive: false,
spoiler_text: "".into(),
public_visibility: true,
},
)
.unwrap();
2023-01-02 17:45:13 +00:00
let reply_act = reply.create_activity(conn).unwrap();
2022-04-23 16:37:03 +00:00
assert_json_eq!(to_value(&reply_act).unwrap(), json!({
"actor": "https://plu.me/@/user/",
"cc": ["https://plu.me/@/user/followers"],
"id": format!("https://plu.me/~/BlogName/testing/comment/{}/activity", reply.id),
"object": {
"attributedTo": "https://plu.me/@/user/",
"content": "",
"id": format!("https://plu.me/~/BlogName/testing/comment/{}", reply.id),
"inReplyTo": format!("https://plu.me/~/BlogName/testing/comment/{}", original_comm.id),
"published": format_datetime(&reply.creation_date),
"summary": "",
"tag": [],
"to": ["https://www.w3.org/ns/activitystreams#Public"],
"type": "Note"
},
"to": ["https://www.w3.org/ns/activitystreams#Public"],
"type": "Create"
}));
inbox(
2023-01-02 17:45:13 +00:00
conn,
serde_json::to_value(original_comm.build_delete(conn).unwrap()).unwrap(),
2022-04-23 16:37:03 +00:00
)
.unwrap();
2023-01-02 17:45:13 +00:00
match inbox(conn, to_value(act).unwrap()).unwrap() {
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 17:31:47 +00:00
InboxResult::Commented(c) => {
// TODO: one is HTML, the other markdown: assert_eq!(c.content, original_comm.content);
assert_eq!(c.in_response_to_id, original_comm.in_response_to_id);
assert_eq!(c.post_id, original_comm.post_id);
assert_eq!(c.author_id, original_comm.author_id);
assert_eq!(c.ap_url, original_comm.ap_url);
assert_eq!(c.spoiler_text, original_comm.spoiler_text);
assert_eq!(c.public_visibility, original_comm.public_visibility);
}
_ => panic!("Unexpected result"),
};
Ok(())
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 17:08:20 +00:00
})
}
2022-04-03 11:51:47 +00:00
#[test]
2022-05-02 16:26:15 +00:00
fn to_activity() {
2022-04-03 11:51:47 +00:00
let conn = db();
conn.test_transaction::<_, Error, _>(|| {
let (comment, _posts, _users, _blogs) = prepare_activity(&conn);
2022-05-02 16:26:15 +00:00
let act = comment.to_activity(&conn)?;
2022-04-03 11:51:47 +00:00
let expected = json!({
"attributedTo": "https://plu.me/@/admin/",
"content": r###"<p dir="auto">My comment, mentioning to <a href="https://plu.me/@/user/" title="user">@user</a></p>
"###,
"id": format!("https://plu.me/~/BlogName/testing/comment/{}", comment.id),
"inReplyTo": "https://plu.me/~/BlogName/testing",
"published": format_datetime(&comment.creation_date),
"summary": "My CW",
"tag": [
{
"href": "https://plu.me/@/user/",
"name": "@user",
"type": "Mention"
}
],
"to": ["https://www.w3.org/ns/activitystreams#Public"],
"type": "Note"
});
assert_json_eq!(to_value(act)?, expected);
Ok(())
});
}
2022-04-03 12:44:32 +00:00
#[test]
2022-05-02 17:11:46 +00:00
fn build_delete() {
2022-04-03 12:44:32 +00:00
let conn = db();
conn.test_transaction::<_, Error, _>(|| {
let (comment, _posts, _users, _blogs) = prepare_activity(&conn);
2022-05-02 17:11:46 +00:00
let act = comment.build_delete(&conn)?;
2022-04-03 12:44:32 +00:00
let expected = json!({
"actor": "https://plu.me/@/admin/",
"id": format!("https://plu.me/~/BlogName/testing/comment/{}#delete", comment.id),
"object": {
"id": format!("https://plu.me/~/BlogName/testing/comment/{}", comment.id),
"type": "Tombstone"
},
"to": ["https://www.w3.org/ns/activitystreams#Public"],
"type": "Delete"
});
assert_json_eq!(to_value(act)?, expected);
Ok(())
});
}
}