]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/comment/mod.rs
Merge pull request #1877 from LemmyNet/refactor-apub-2
[lemmy.git] / crates / apub / src / activities / comment / mod.rs
1 use crate::objects::{comment::ApubComment, community::ApubCommunity, person::ApubPerson};
2 use activitystreams::{
3   base::BaseExt,
4   link::{LinkExt, Mention},
5 };
6 use anyhow::anyhow;
7 use itertools::Itertools;
8 use lemmy_api_common::blocking;
9 use lemmy_apub_lib::{object_id::ObjectId, traits::ActorType, webfinger::WebfingerResponse};
10 use lemmy_db_schema::{
11   newtypes::LocalUserId,
12   source::{comment::Comment, person::Person, post::Post},
13   traits::Crud,
14   DbPool,
15 };
16 use lemmy_utils::{
17   request::{retry, RecvError},
18   utils::{scrape_text_for_mentions, MentionData},
19   LemmyError,
20 };
21 use lemmy_websocket::{send::send_local_notifs, LemmyContext};
22 use log::debug;
23 use url::Url;
24
25 pub mod create_or_update;
26
27 async fn get_notif_recipients(
28   actor: &ObjectId<ApubPerson>,
29   comment: &Comment,
30   context: &LemmyContext,
31   request_counter: &mut i32,
32 ) -> Result<Vec<LocalUserId>, LemmyError> {
33   let post_id = comment.post_id;
34   let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
35   let actor = actor.dereference(context, request_counter).await?;
36
37   // Note:
38   // Although mentions could be gotten from the post tags (they are included there), or the ccs,
39   // Its much easier to scrape them from the comment body, since the API has to do that
40   // anyway.
41   // TODO: for compatibility with other projects, it would be much better to read this from cc or tags
42   let mentions = scrape_text_for_mentions(&comment.content);
43   send_local_notifs(mentions, comment, &*actor, &post, true, context).await
44 }
45
46 pub struct MentionsAndAddresses {
47   pub ccs: Vec<Url>,
48   pub inboxes: Vec<Url>,
49   pub tags: Vec<Mention>,
50 }
51
52 /// This takes a comment, and builds a list of to_addresses, inboxes,
53 /// and mention tags, so they know where to be sent to.
54 /// Addresses are the persons / addresses that go in the cc field.
55 pub async fn collect_non_local_mentions(
56   comment: &ApubComment,
57   community: &ApubCommunity,
58   context: &LemmyContext,
59 ) -> Result<MentionsAndAddresses, LemmyError> {
60   let parent_creator = get_comment_parent_creator(context.pool(), comment).await?;
61   let mut addressed_ccs: Vec<Url> = vec![community.actor_id(), parent_creator.actor_id()];
62   // Note: dont include community inbox here, as we send to it separately with `send_to_community()`
63   let mut inboxes = vec![parent_creator.shared_inbox_or_inbox_url()];
64
65   // Add the mention tag
66   let mut tags = Vec::new();
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     if let Ok(actor_id) = fetch_webfinger_url(mention, context).await {
78       let actor_id: ObjectId<ApubPerson> = ObjectId::new(actor_id);
79       debug!("mention actor_id: {}", actor_id);
80       addressed_ccs.push(actor_id.to_string().parse()?);
81
82       let mention_person = actor_id.dereference(context, &mut 0).await?;
83       inboxes.push(mention_person.shared_inbox_or_inbox_url());
84
85       let mut mention_tag = Mention::new();
86       mention_tag
87         .set_href(actor_id.into())
88         .set_name(mention.full_name());
89       tags.push(mention_tag);
90     }
91   }
92
93   let inboxes = inboxes.into_iter().unique().collect();
94
95   Ok(MentionsAndAddresses {
96     ccs: addressed_ccs,
97     inboxes,
98     tags,
99   })
100 }
101
102 /// Returns the apub ID of the person this comment is responding to. Meaning, in case this is a
103 /// top-level comment, the creator of the post, otherwise the creator of the parent comment.
104 async fn get_comment_parent_creator(
105   pool: &DbPool,
106   comment: &Comment,
107 ) -> Result<ApubPerson, LemmyError> {
108   let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id {
109     let parent_comment =
110       blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??;
111     parent_comment.creator_id
112   } else {
113     let parent_post_id = comment.post_id;
114     let parent_post = blocking(pool, move |conn| Post::read(conn, parent_post_id)).await??;
115     parent_post.creator_id
116   };
117   Ok(
118     blocking(pool, move |conn| Person::read(conn, parent_creator_id))
119       .await??
120       .into(),
121   )
122 }
123
124 /// Turns a person id like `@name@example.com` into an apub ID, like `https://example.com/user/name`,
125 /// using webfinger.
126 async fn fetch_webfinger_url(
127   mention: &MentionData,
128   context: &LemmyContext,
129 ) -> Result<Url, LemmyError> {
130   let fetch_url = format!(
131     "{}://{}/.well-known/webfinger?resource=acct:{}@{}",
132     context.settings().get_protocol_string(),
133     mention.domain,
134     mention.name,
135     mention.domain
136   );
137   debug!("Fetching webfinger url: {}", &fetch_url);
138
139   let response = retry(|| context.client().get(&fetch_url).send()).await?;
140
141   let res: WebfingerResponse = response
142     .json()
143     .await
144     .map_err(|e| RecvError(e.to_string()))?;
145
146   let link = res
147     .links
148     .iter()
149     .find(|l| l.type_.eq(&Some("application/activity+json".to_string())))
150     .ok_or_else(|| anyhow!("No application/activity+json link found."))?;
151   link
152     .href
153     .to_owned()
154     .ok_or_else(|| anyhow!("No href found.").into())
155 }