]> Untitled Git - lemmy.git/blob - crates/apub/src/mentions.rs
Create and Note always need to tag parent creator, for mastodon notifications
[lemmy.git] / crates / apub / src / mentions.rs
1 use crate::{
2   fetcher::webfinger::WebfingerResponse,
3   objects::{comment::ApubComment, community::ApubCommunity, person::ApubPerson},
4 };
5 use activitystreams::{
6   base::BaseExt,
7   link::{LinkExt, Mention},
8 };
9 use anyhow::anyhow;
10 use lemmy_api_common::blocking;
11 use lemmy_apub_lib::{object_id::ObjectId, traits::ActorType};
12 use lemmy_db_schema::{
13   source::{comment::Comment, person::Person, post::Post},
14   traits::Crud,
15   DbPool,
16 };
17 use lemmy_utils::{
18   request::{retry, RecvError},
19   utils::{scrape_text_for_mentions, MentionData},
20   LemmyError,
21 };
22 use lemmy_websocket::LemmyContext;
23 use log::debug;
24 use url::Url;
25
26 pub struct MentionsAndAddresses {
27   pub ccs: Vec<Url>,
28   pub tags: Vec<Mention>,
29 }
30
31 /// This takes a comment, and builds a list of to_addresses, inboxes,
32 /// and mention tags, so they know where to be sent to.
33 /// Addresses are the persons / addresses that go in the cc field.
34 pub async fn collect_non_local_mentions(
35   comment: &ApubComment,
36   community_id: ObjectId<ApubCommunity>,
37   context: &LemmyContext,
38 ) -> Result<MentionsAndAddresses, LemmyError> {
39   let parent_creator = get_comment_parent_creator(context.pool(), comment).await?;
40   let mut addressed_ccs: Vec<Url> = vec![community_id.into(), parent_creator.actor_id()];
41
42   // Add the mention tag
43   let mut parent_creator_tag = Mention::new();
44   parent_creator_tag
45     .set_href(parent_creator.actor_id.clone().into())
46     .set_name(format!(
47       "@{}@{}",
48       &parent_creator.name,
49       &parent_creator.actor_id().domain().expect("has domain")
50     ));
51   let mut tags = vec![parent_creator_tag];
52
53   // Get the person IDs for any mentions
54   let mentions = scrape_text_for_mentions(&comment.content)
55     .into_iter()
56     // Filter only the non-local ones
57     .filter(|m| !m.is_local(&context.settings().hostname))
58     .collect::<Vec<MentionData>>();
59
60   for mention in &mentions {
61     // TODO should it be fetching it every time?
62     if let Ok(actor_id) = fetch_webfinger_url(mention, context).await {
63       let actor_id: ObjectId<ApubPerson> = ObjectId::new(actor_id);
64       debug!("mention actor_id: {}", actor_id);
65       addressed_ccs.push(actor_id.to_string().parse()?);
66
67       let mut mention_tag = Mention::new();
68       mention_tag
69         .set_href(actor_id.into())
70         .set_name(mention.full_name());
71       tags.push(mention_tag);
72     }
73   }
74
75   Ok(MentionsAndAddresses {
76     ccs: addressed_ccs,
77     tags,
78   })
79 }
80
81 /// Returns the apub ID of the person this comment is responding to. Meaning, in case this is a
82 /// top-level comment, the creator of the post, otherwise the creator of the parent comment.
83 async fn get_comment_parent_creator(
84   pool: &DbPool,
85   comment: &Comment,
86 ) -> Result<ApubPerson, LemmyError> {
87   let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id {
88     let parent_comment =
89       blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??;
90     parent_comment.creator_id
91   } else {
92     let parent_post_id = comment.post_id;
93     let parent_post = blocking(pool, move |conn| Post::read(conn, parent_post_id)).await??;
94     parent_post.creator_id
95   };
96   Ok(
97     blocking(pool, move |conn| Person::read(conn, parent_creator_id))
98       .await??
99       .into(),
100   )
101 }
102
103 /// Turns a person id like `@name@example.com` into an apub ID, like `https://example.com/user/name`,
104 /// using webfinger.
105 async fn fetch_webfinger_url(
106   mention: &MentionData,
107   context: &LemmyContext,
108 ) -> Result<Url, LemmyError> {
109   let fetch_url = format!(
110     "{}://{}/.well-known/webfinger?resource=acct:{}@{}",
111     context.settings().get_protocol_string(),
112     mention.domain,
113     mention.name,
114     mention.domain
115   );
116   debug!("Fetching webfinger url: {}", &fetch_url);
117
118   let response = retry(|| context.client().get(&fetch_url).send()).await?;
119
120   let res: WebfingerResponse = response
121     .json()
122     .await
123     .map_err(|e| RecvError(e.to_string()))?;
124
125   let link = res
126     .links
127     .iter()
128     .find(|l| l.type_.eq(&Some("application/activity+json".to_string())))
129     .ok_or_else(|| anyhow!("No application/activity+json link found."))?;
130   link
131     .href
132     .to_owned()
133     .ok_or_else(|| anyhow!("No href found.").into())
134 }