2 activities::verify_community_matches,
3 fetcher::user_or_community::{PersonOrGroupType, UserOrCommunity},
4 objects::{community::ApubCommunity, person::ApubPerson, post::ApubPost},
5 protocol::{objects::LanguageTag, ImageObject, InCommunity, Source},
7 use activitypub_federation::{
9 fetch::object_id::ObjectId,
12 object::{DocumentType, ImageType},
15 helpers::{deserialize_one_or_many, deserialize_skip_error},
16 values::MediaTypeMarkdownOrHtml,
18 traits::{ActivityHandler, Object},
20 use chrono::{DateTime, FixedOffset};
21 use itertools::Itertools;
22 use lemmy_api_common::context::LemmyContext;
23 use lemmy_db_schema::newtypes::DbUrl;
24 use lemmy_utils::error::LemmyError;
25 use serde::{de::Error, Deserialize, Deserializer, Serialize};
26 use serde_with::skip_serializing_none;
29 #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
38 #[skip_serializing_none]
39 #[derive(Clone, Debug, Deserialize, Serialize)]
40 #[serde(rename_all = "camelCase")]
42 #[serde(rename = "type")]
43 pub(crate) kind: PageType,
44 pub(crate) id: ObjectId<ApubPost>,
45 pub(crate) attributed_to: AttributedTo,
46 #[serde(deserialize_with = "deserialize_one_or_many")]
47 pub(crate) to: Vec<Url>,
48 // If there is inReplyTo field this is actually a comment and must not be parsed
49 #[serde(deserialize_with = "deserialize_not_present", default)]
50 pub(crate) in_reply_to: Option<String>,
52 pub(crate) name: Option<String>,
53 #[serde(deserialize_with = "deserialize_one_or_many", default)]
54 pub(crate) cc: Vec<Url>,
55 pub(crate) content: Option<String>,
56 pub(crate) media_type: Option<MediaTypeMarkdownOrHtml>,
57 #[serde(deserialize_with = "deserialize_skip_error", default)]
58 pub(crate) source: Option<Source>,
59 /// most software uses array type for attachment field, so we do the same. nevertheless, we only
60 /// use the first item
62 pub(crate) attachment: Vec<Attachment>,
63 pub(crate) image: Option<ImageObject>,
64 pub(crate) comments_enabled: Option<bool>,
65 pub(crate) sensitive: Option<bool>,
66 pub(crate) published: Option<DateTime<FixedOffset>>,
67 pub(crate) updated: Option<DateTime<FixedOffset>>,
68 pub(crate) language: Option<LanguageTag>,
69 pub(crate) audience: Option<ObjectId<ApubCommunity>>,
72 #[derive(Clone, Debug, Deserialize, Serialize)]
73 #[serde(rename_all = "camelCase")]
74 pub(crate) struct Link {
76 pub(crate) r#type: LinkType,
79 #[derive(Clone, Debug, Deserialize, Serialize)]
80 #[serde(rename_all = "camelCase")]
81 pub(crate) struct Image {
82 #[serde(rename = "type")]
83 pub(crate) kind: ImageType,
87 #[derive(Clone, Debug, Deserialize, Serialize)]
88 #[serde(rename_all = "camelCase")]
89 pub(crate) struct Document {
90 #[serde(rename = "type")]
91 pub(crate) kind: DocumentType,
95 #[derive(Clone, Debug, Deserialize, Serialize)]
97 pub(crate) enum Attachment {
104 pub(crate) fn url(self) -> Url {
106 // url as sent by Lemmy (new)
107 Attachment::Link(l) => l.href,
108 // image sent by lotide
109 Attachment::Image(i) => i.url,
111 Attachment::Document(d) => d.url,
116 #[derive(Clone, Debug, Deserialize, Serialize)]
118 pub(crate) enum AttributedTo {
119 Lemmy(ObjectId<ApubPerson>),
120 Peertube([AttributedToPeertube; 2]),
123 #[derive(Clone, Debug, Deserialize, Serialize)]
124 #[serde(rename_all = "camelCase")]
125 pub(crate) struct AttributedToPeertube {
126 #[serde(rename = "type")]
127 pub kind: PersonOrGroupType,
128 pub id: ObjectId<UserOrCommunity>,
132 /// Only mods can change the post's locked status. So if it is changed from the default value,
133 /// it is a mod action and needs to be verified as such.
135 /// Locked needs to be false on a newly created post (verified in [[CreatePost]].
136 pub(crate) async fn is_mod_action(
138 context: &Data<LemmyContext>,
139 ) -> Result<bool, LemmyError> {
140 let old_post = self.id.clone().dereference_local(context).await;
141 Ok(Page::is_locked_changed(&old_post, &self.comments_enabled))
144 pub(crate) fn is_locked_changed<E>(
145 old_post: &Result<ApubPost, E>,
146 new_comments_enabled: &Option<bool>,
148 if let Some(new_comments_enabled) = new_comments_enabled {
149 if let Ok(old_post) = old_post {
150 return new_comments_enabled != &!old_post.locked;
157 pub(crate) fn creator(&self) -> Result<ObjectId<ApubPerson>, LemmyError> {
158 match &self.attributed_to {
159 AttributedTo::Lemmy(l) => Ok(l.clone()),
160 AttributedTo::Peertube(p) => p
162 .find(|a| a.kind == PersonOrGroupType::Person)
163 .map(|a| ObjectId::<ApubPerson>::from(a.id.clone().into_inner()))
164 .ok_or_else(|| LemmyError::from_message("page does not specify creator person")),
170 pub(crate) fn new(url: DbUrl) -> Attachment {
171 Attachment::Link(Link {
173 r#type: Default::default(),
178 // Used for community outbox, so that it can be compatible with Pleroma/Mastodon.
179 #[async_trait::async_trait]
180 impl ActivityHandler for Page {
181 type DataType = LemmyContext;
182 type Error = LemmyError;
183 fn id(&self) -> &Url {
186 fn actor(&self) -> &Url {
189 async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), LemmyError> {
190 ApubPost::verify(self, self.id.inner(), data).await
192 async fn receive(self, data: &Data<Self::DataType>) -> Result<(), LemmyError> {
193 ApubPost::from_json(self, data).await?;
198 #[async_trait::async_trait]
199 impl InCommunity for Page {
200 async fn community(&self, context: &Data<LemmyContext>) -> Result<ApubCommunity, LemmyError> {
201 let community = match &self.attributed_to {
202 AttributedTo::Lemmy(_) => {
203 let mut iter = self.to.iter().merge(self.cc.iter());
205 if let Some(cid) = iter.next() {
206 let cid = ObjectId::from(cid.clone());
207 if let Ok(c) = cid.dereference(context).await {
211 return Err(LemmyError::from_message("No community found in cc"));
215 AttributedTo::Peertube(p) => {
217 .find(|a| a.kind == PersonOrGroupType::Group)
218 .map(|a| ObjectId::<ApubCommunity>::from(a.id.clone().into_inner()))
219 .ok_or_else(|| LemmyError::from_message("page does not specify group"))?
220 .dereference(context)
224 if let Some(audience) = &self.audience {
225 verify_community_matches(audience, community.actor_id.clone())?;
231 /// Only allows deserialization if the field is missing or null. If it is present, throws an error.
232 pub fn deserialize_not_present<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
234 D: Deserializer<'de>,
236 let result: Option<String> = Deserialize::deserialize(deserializer)?;
239 Some(_) => Err(D::Error::custom("Post must not have inReplyTo property")),
245 use crate::protocol::{objects::page::Page, tests::test_parse_lemmy_item};
248 fn test_not_parsing_note_as_page() {
249 assert!(test_parse_lemmy_item::<Page>("assets/lemmy/objects/note.json").is_err());