]> Untitled Git - lemmy.git/blob - crates/apub/src/mentions.rs
Run cargo update as part of release script (#3369)
[lemmy.git] / crates / apub / src / mentions.rs
1 use crate::objects::{comment::ApubComment, community::ApubCommunity, person::ApubPerson};
2 use activitypub_federation::{
3   config::Data,
4   fetch::{object_id::ObjectId, webfinger::webfinger_resolve_actor},
5   kinds::link::MentionType,
6   traits::Actor,
7 };
8 use lemmy_api_common::context::LemmyContext;
9 use lemmy_db_schema::{
10   source::{comment::Comment, person::Person, post::Post},
11   traits::Crud,
12   utils::DbPool,
13 };
14 use lemmy_utils::{
15   error::LemmyError,
16   utils::mention::{scrape_text_for_mentions, MentionData},
17 };
18 use serde::{Deserialize, Serialize};
19 use serde_json::Value;
20 use url::Url;
21
22 #[derive(Clone, Debug, Deserialize, Serialize)]
23 #[serde(untagged)]
24 pub enum MentionOrValue {
25   Mention(Mention),
26   Value(Value),
27 }
28
29 #[derive(Clone, Debug, Deserialize, Serialize)]
30 pub struct Mention {
31   pub href: Url,
32   name: Option<String>,
33   #[serde(rename = "type")]
34   pub kind: MentionType,
35 }
36
37 pub struct MentionsAndAddresses {
38   pub ccs: Vec<Url>,
39   pub tags: Vec<MentionOrValue>,
40 }
41
42 /// This takes a comment, and builds a list of to_addresses, inboxes,
43 /// and mention tags, so they know where to be sent to.
44 /// Addresses are the persons / addresses that go in the cc field.
45 #[tracing::instrument(skip(comment, community_id, context))]
46 pub async fn collect_non_local_mentions(
47   comment: &ApubComment,
48   community_id: ObjectId<ApubCommunity>,
49   context: &Data<LemmyContext>,
50 ) -> Result<MentionsAndAddresses, LemmyError> {
51   let parent_creator = get_comment_parent_creator(context.pool(), comment).await?;
52   let mut addressed_ccs: Vec<Url> = vec![community_id.into(), parent_creator.id()];
53
54   // Add the mention tag
55   let parent_creator_tag = Mention {
56     href: parent_creator.actor_id.clone().into(),
57     name: Some(format!(
58       "@{}@{}",
59       &parent_creator.name,
60       &parent_creator.id().domain().expect("has domain")
61     )),
62     kind: MentionType::Mention,
63   };
64   let mut tags = vec![parent_creator_tag];
65
66   // Get the person IDs for any mentions
67   let mentions = scrape_text_for_mentions(&comment.content)
68     .into_iter()
69     // Filter only the non-local ones
70     .filter(|m| !m.is_local(&context.settings().hostname))
71     .collect::<Vec<MentionData>>();
72
73   for mention in &mentions {
74     let identifier = format!("{}@{}", mention.name, mention.domain);
75     let person = webfinger_resolve_actor::<LemmyContext, ApubPerson>(&identifier, context).await;
76     if let Ok(person) = person {
77       addressed_ccs.push(person.actor_id.to_string().parse()?);
78
79       let mention_tag = Mention {
80         href: person.id(),
81         name: Some(mention.full_name()),
82         kind: MentionType::Mention,
83       };
84       tags.push(mention_tag);
85     }
86   }
87
88   let tags = tags.into_iter().map(MentionOrValue::Mention).collect();
89   Ok(MentionsAndAddresses {
90     ccs: addressed_ccs,
91     tags,
92   })
93 }
94
95 /// Returns the apub ID of the person this comment is responding to. Meaning, in case this is a
96 /// top-level comment, the creator of the post, otherwise the creator of the parent comment.
97 #[tracing::instrument(skip(pool, comment))]
98 async fn get_comment_parent_creator(
99   pool: &DbPool,
100   comment: &Comment,
101 ) -> Result<ApubPerson, LemmyError> {
102   let parent_creator_id = if let Some(parent_comment_id) = comment.parent_comment_id() {
103     let parent_comment = Comment::read(pool, parent_comment_id).await?;
104     parent_comment.creator_id
105   } else {
106     let parent_post_id = comment.post_id;
107     let parent_post = Post::read(pool, parent_post_id).await?;
108     parent_post.creator_id
109   };
110   Ok(Person::read(pool, parent_creator_id).await?.into())
111 }