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