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