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 /// Deprecated, for compatibility with Lemmy 0.17
67 pub(crate) stickied: Option<bool>,
68 pub(crate) published: Option<DateTime<FixedOffset>>,
69 pub(crate) updated: Option<DateTime<FixedOffset>>,
70 pub(crate) language: Option<LanguageTag>,
71 pub(crate) audience: Option<ObjectId<ApubCommunity>>,
74 #[derive(Clone, Debug, Deserialize, Serialize)]
75 #[serde(rename_all = "camelCase")]
76 pub(crate) struct Link {
78 pub(crate) r#type: LinkType,
81 #[derive(Clone, Debug, Deserialize, Serialize)]
82 #[serde(rename_all = "camelCase")]
83 pub(crate) struct Image {
84 #[serde(rename = "type")]
85 pub(crate) kind: ImageType,
89 #[derive(Clone, Debug, Deserialize, Serialize)]
90 #[serde(rename_all = "camelCase")]
91 pub(crate) struct Document {
92 #[serde(rename = "type")]
93 pub(crate) kind: DocumentType,
97 #[derive(Clone, Debug, Deserialize, Serialize)]
99 pub(crate) enum Attachment {
106 pub(crate) fn url(self) -> Url {
108 // url as sent by Lemmy (new)
109 Attachment::Link(l) => l.href,
110 // image sent by lotide
111 Attachment::Image(i) => i.url,
113 Attachment::Document(d) => d.url,
118 #[derive(Clone, Debug, Deserialize, Serialize)]
120 pub(crate) enum AttributedTo {
121 Lemmy(ObjectId<ApubPerson>),
122 Peertube([AttributedToPeertube; 2]),
125 #[derive(Clone, Debug, Deserialize, Serialize)]
126 #[serde(rename_all = "camelCase")]
127 pub(crate) struct AttributedToPeertube {
128 #[serde(rename = "type")]
129 pub kind: PersonOrGroupType,
130 pub id: ObjectId<UserOrCommunity>,
134 /// Only mods can change the post's stickied/locked status. So if either of these is changed from
135 /// the current value, it is a mod action and needs to be verified as such.
137 /// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]].
138 pub(crate) async fn is_mod_action(
140 context: &Data<LemmyContext>,
141 ) -> Result<bool, LemmyError> {
142 let old_post = self.id.clone().dereference_local(context).await;
144 let featured_changed = Page::is_featured_changed(&old_post, &self.stickied);
145 let locked_changed = Page::is_locked_changed(&old_post, &self.comments_enabled);
146 Ok(featured_changed || locked_changed)
149 pub(crate) fn is_featured_changed<E>(
150 old_post: &Result<ApubPost, E>,
151 new_featured_community: &Option<bool>,
153 if let Some(new_featured_community) = new_featured_community {
154 if let Ok(old_post) = old_post {
155 return new_featured_community != &old_post.featured_community;
162 pub(crate) fn is_locked_changed<E>(
163 old_post: &Result<ApubPost, E>,
164 new_comments_enabled: &Option<bool>,
166 if let Some(new_comments_enabled) = new_comments_enabled {
167 if let Ok(old_post) = old_post {
168 return new_comments_enabled != &!old_post.locked;
175 pub(crate) fn creator(&self) -> Result<ObjectId<ApubPerson>, LemmyError> {
176 match &self.attributed_to {
177 AttributedTo::Lemmy(l) => Ok(l.clone()),
178 AttributedTo::Peertube(p) => p
180 .find(|a| a.kind == PersonOrGroupType::Person)
181 .map(|a| ObjectId::<ApubPerson>::from(a.id.clone().into_inner()))
182 .ok_or_else(|| LemmyError::from_message("page does not specify creator person")),
188 pub(crate) fn new(url: DbUrl) -> Attachment {
189 Attachment::Link(Link {
191 r#type: Default::default(),
196 // Used for community outbox, so that it can be compatible with Pleroma/Mastodon.
197 #[async_trait::async_trait]
198 impl ActivityHandler for Page {
199 type DataType = LemmyContext;
200 type Error = LemmyError;
201 fn id(&self) -> &Url {
204 fn actor(&self) -> &Url {
207 async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), LemmyError> {
208 ApubPost::verify(self, self.id.inner(), data).await
210 async fn receive(self, data: &Data<Self::DataType>) -> Result<(), LemmyError> {
211 ApubPost::from_json(self, data).await?;
216 #[async_trait::async_trait]
217 impl InCommunity for Page {
218 async fn community(&self, context: &Data<LemmyContext>) -> Result<ApubCommunity, LemmyError> {
219 let community = match &self.attributed_to {
220 AttributedTo::Lemmy(_) => {
221 let mut iter = self.to.iter().merge(self.cc.iter());
223 if let Some(cid) = iter.next() {
224 let cid = ObjectId::from(cid.clone());
225 if let Ok(c) = cid.dereference(context).await {
229 return Err(LemmyError::from_message("No community found in cc"));
233 AttributedTo::Peertube(p) => {
235 .find(|a| a.kind == PersonOrGroupType::Group)
236 .map(|a| ObjectId::<ApubCommunity>::from(a.id.clone().into_inner()))
237 .ok_or_else(|| LemmyError::from_message("page does not specify group"))?
238 .dereference(context)
242 if let Some(audience) = &self.audience {
243 verify_community_matches(audience, community.actor_id.clone())?;
249 /// Only allows deserialization if the field is missing or null. If it is present, throws an error.
250 pub fn deserialize_not_present<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
252 D: Deserializer<'de>,
254 let result: Option<String> = Deserialize::deserialize(deserializer)?;
257 Some(_) => Err(D::Error::custom("Post must not have inReplyTo property")),
263 use crate::protocol::{objects::page::Page, tests::test_parse_lemmy_item};
266 fn test_not_parsing_note_as_page() {
267 assert!(test_parse_lemmy_item::<Page>("assets/lemmy/objects/note.json").is_err());