lemmy/crates/apub/src/objects/private_message.rs
Dessalines 5d837780f5
Add diesel_async, get rid of blocking function (#2510)
* Moving settings to Database.

- Moves many settings into the database. Fixes #2285
- Adds a local_site and instance table. Fixes #2365 . Fixes #2368
- Separates SQL update an insert forms, to avoid runtime errors.
- Adds TypedBuilder to all the SQL forms, instead of default.

* Fix weird clippy issue.

* Removing extra lines.

* Some fixes from suggestions.

* Fixing apub tests.

* Using instance creation helper function.

* Move forms to their own line.

* Trying to fix local_site_data, still broken.

* Testing out async

* Testing out async 2

* Fixing federation tests.

* Trying to fix check features 1.

* Starting on adding diesel async. 1/4th done.

* Added async to views and schema.

* Adding some more async

* Compiling now.

* Added diesel async. Fixes #2465

* Running clippy --fix

* Trying to fix cargo test on drone.

* Trying new muslrust.

* Trying a custom dns

* Trying a custom dns 2

* Trying a custom dns 3

* Trying a custom dns 4

* Trying a custom dns 5

* Trying a custom dns 6

* Trying a custom dns 7

* Addressing PR comments.

* Adding check_apub to all verify functions.

* Reverting back drone.

* Fixing merge

* Fix docker images.

* Adding missing discussion_languages.

* Trying to fix federation tests.

* Fix site setup user creation.

* Fix clippy

* Fix clippy 2

* Test api faster

* Try to fix 1

* Try to fix 2

* What are these lines about

* Trying to fix 3

* Moving federation test back to top.

* Remove logging cat.
2022-11-09 10:05:00 +00:00

254 lines
7.6 KiB
Rust

use crate::{
check_apub_id_valid_with_strictness,
fetch_local_site_data,
local_instance,
objects::read_from_string_or_source,
protocol::{
objects::chat_message::{ChatMessage, ChatMessageType},
Source,
},
};
use activitypub_federation::{
core::object_id::ObjectId,
deser::values::MediaTypeHtml,
traits::ApubObject,
utils::verify_domains_match,
};
use chrono::NaiveDateTime;
use lemmy_api_common::utils::check_person_block;
use lemmy_db_schema::{
source::{
person::Person,
private_message::{PrivateMessage, PrivateMessageInsertForm},
},
traits::Crud,
};
use lemmy_utils::{
error::LemmyError,
utils::{convert_datetime, markdown_to_html},
};
use lemmy_websocket::LemmyContext;
use std::ops::Deref;
use url::Url;
#[derive(Clone, Debug)]
pub struct ApubPrivateMessage(PrivateMessage);
impl Deref for ApubPrivateMessage {
type Target = PrivateMessage;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<PrivateMessage> for ApubPrivateMessage {
fn from(pm: PrivateMessage) -> Self {
ApubPrivateMessage(pm)
}
}
#[async_trait::async_trait(?Send)]
impl ApubObject for ApubPrivateMessage {
type DataType = LemmyContext;
type ApubType = ChatMessage;
type DbType = PrivateMessage;
type Error = LemmyError;
fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
None
}
#[tracing::instrument(skip_all)]
async fn read_from_apub_id(
object_id: Url,
context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> {
Ok(
PrivateMessage::read_from_apub_id(context.pool(), object_id)
.await?
.map(Into::into),
)
}
async fn delete(self, _context: &LemmyContext) -> Result<(), LemmyError> {
// do nothing, because pm can't be fetched over http
unimplemented!()
}
#[tracing::instrument(skip_all)]
async fn into_apub(self, context: &LemmyContext) -> Result<ChatMessage, LemmyError> {
let creator_id = self.creator_id;
let creator = Person::read(context.pool(), creator_id).await?;
let recipient_id = self.recipient_id;
let recipient = Person::read(context.pool(), recipient_id).await?;
let note = ChatMessage {
r#type: ChatMessageType::ChatMessage,
id: ObjectId::new(self.ap_id.clone()),
attributed_to: ObjectId::new(creator.actor_id),
to: [ObjectId::new(recipient.actor_id)],
content: markdown_to_html(&self.content),
media_type: Some(MediaTypeHtml::Html),
source: Some(Source::new(self.content.clone())),
published: Some(convert_datetime(self.published)),
updated: self.updated.map(convert_datetime),
};
Ok(note)
}
#[tracing::instrument(skip_all)]
async fn verify(
note: &ChatMessage,
expected_domain: &Url,
context: &LemmyContext,
request_counter: &mut i32,
) -> Result<(), LemmyError> {
verify_domains_match(note.id.inner(), expected_domain)?;
verify_domains_match(note.attributed_to.inner(), note.id.inner())?;
let local_site_data = fetch_local_site_data(context.pool()).await?;
check_apub_id_valid_with_strictness(
note.id.inner(),
false,
&local_site_data,
context.settings(),
)?;
let person = note
.attributed_to
.dereference(context, local_instance(context).await, request_counter)
.await?;
if person.banned {
return Err(LemmyError::from_message("Person is banned from site"));
}
Ok(())
}
#[tracing::instrument(skip_all)]
async fn from_apub(
note: ChatMessage,
context: &LemmyContext,
request_counter: &mut i32,
) -> Result<ApubPrivateMessage, LemmyError> {
let creator = note
.attributed_to
.dereference(context, local_instance(context).await, request_counter)
.await?;
let recipient = note.to[0]
.dereference(context, local_instance(context).await, request_counter)
.await?;
check_person_block(creator.id, recipient.id, context.pool()).await?;
let form = PrivateMessageInsertForm {
creator_id: creator.id,
recipient_id: recipient.id,
content: read_from_string_or_source(&note.content, &None, &note.source),
published: note.published.map(|u| u.naive_local()),
updated: note.updated.map(|u| u.naive_local()),
deleted: Some(false),
read: None,
ap_id: Some(note.id.into()),
local: Some(false),
};
let pm = PrivateMessage::create(context.pool(), &form).await?;
Ok(pm.into())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
objects::{
instance::{tests::parse_lemmy_instance, ApubSite},
person::ApubPerson,
tests::init_context,
},
protocol::tests::file_to_json_object,
};
use assert_json_diff::assert_json_include;
use lemmy_db_schema::source::site::Site;
use serial_test::serial;
async fn prepare_comment_test(
url: &Url,
context: &LemmyContext,
) -> (ApubPerson, ApubPerson, ApubSite) {
let lemmy_person = file_to_json_object("assets/lemmy/objects/person.json").unwrap();
let site = parse_lemmy_instance(context).await;
ApubPerson::verify(&lemmy_person, url, context, &mut 0)
.await
.unwrap();
let person1 = ApubPerson::from_apub(lemmy_person, context, &mut 0)
.await
.unwrap();
let pleroma_person = file_to_json_object("assets/pleroma/objects/person.json").unwrap();
let pleroma_url = Url::parse("https://queer.hacktivis.me/users/lanodan").unwrap();
ApubPerson::verify(&pleroma_person, &pleroma_url, context, &mut 0)
.await
.unwrap();
let person2 = ApubPerson::from_apub(pleroma_person, context, &mut 0)
.await
.unwrap();
(person1, person2, site)
}
async fn cleanup(data: (ApubPerson, ApubPerson, ApubSite), context: &LemmyContext) {
Person::delete(context.pool(), data.0.id).await.unwrap();
Person::delete(context.pool(), data.1.id).await.unwrap();
Site::delete(context.pool(), data.2.id).await.unwrap();
}
#[actix_rt::test]
#[serial]
async fn test_parse_lemmy_pm() {
let context = init_context().await;
let url = Url::parse("https://enterprise.lemmy.ml/private_message/1621").unwrap();
let data = prepare_comment_test(&url, &context).await;
let json: ChatMessage = file_to_json_object("assets/lemmy/objects/chat_message.json").unwrap();
let mut request_counter = 0;
ApubPrivateMessage::verify(&json, &url, &context, &mut request_counter)
.await
.unwrap();
let pm = ApubPrivateMessage::from_apub(json.clone(), &context, &mut request_counter)
.await
.unwrap();
assert_eq!(pm.ap_id.clone(), url.into());
assert_eq!(pm.content.len(), 20);
assert_eq!(request_counter, 0);
let pm_id = pm.id;
let to_apub = pm.into_apub(&context).await.unwrap();
assert_json_include!(actual: json, expected: to_apub);
PrivateMessage::delete(context.pool(), pm_id).await.unwrap();
cleanup(data, &context).await;
}
#[actix_rt::test]
#[serial]
async fn test_parse_pleroma_pm() {
let context = init_context().await;
let url = Url::parse("https://enterprise.lemmy.ml/private_message/1621").unwrap();
let data = prepare_comment_test(&url, &context).await;
let pleroma_url = Url::parse("https://queer.hacktivis.me/objects/2").unwrap();
let json = file_to_json_object("assets/pleroma/objects/chat_message.json").unwrap();
let mut request_counter = 0;
ApubPrivateMessage::verify(&json, &pleroma_url, &context, &mut request_counter)
.await
.unwrap();
let pm = ApubPrivateMessage::from_apub(json, &context, &mut request_counter)
.await
.unwrap();
assert_eq!(pm.ap_id, pleroma_url.into());
assert_eq!(pm.content.len(), 3);
assert_eq!(request_counter, 0);
PrivateMessage::delete(context.pool(), pm.id).await.unwrap();
cleanup(data, &context).await;
}
}