]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/comment/mod.rs
Merge crates db_schema and db_queries
[lemmy.git] / crates / apub / src / activities / comment / mod.rs
1 use crate::fetcher::object_id::ObjectId;
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, send_local_notifs};
9 use lemmy_apub_lib::{traits::ActorType, webfinger::WebfingerResponse};
10 use lemmy_db_schema::{
11   newtypes::LocalUserId,
12   source::{comment::Comment, community::Community, 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::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<Person>,
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(
44     mentions,
45     comment.clone(),
46     actor,
47     post,
48     context.pool(),
49     true,
50     &context.settings(),
51   )
52   .await
53 }
54
55 pub struct MentionsAndAddresses {
56   pub ccs: Vec<Url>,
57   pub inboxes: Vec<Url>,
58   pub tags: Vec<Mention>,
59 }
60
61 /// This takes a comment, and builds a list of to_addresses, inboxes,
62 /// and mention tags, so they know where to be sent to.
63 /// Addresses are the persons / addresses that go in the cc field.
64 pub async fn collect_non_local_mentions(
65   comment: &Comment,
66   community: &Community,
67   context: &LemmyContext,
68 ) -> Result<MentionsAndAddresses, LemmyError> {
69   let parent_creator = get_comment_parent_creator(context.pool(), comment).await?;
70   let mut addressed_ccs = vec![community.actor_id(), parent_creator.actor_id()];
71   // Note: dont include community inbox here, as we send to it separately with `send_to_community()`
72   let mut inboxes = vec![parent_creator.shared_inbox_or_inbox_url()];
73
74   // Add the mention tag
75   let mut tags = Vec::new();
76
77   // Get the person IDs for any mentions
78   let mentions = scrape_text_for_mentions(&comment.content)
79     .into_iter()
80     // Filter only the non-local ones
81     .filter(|m| !m.is_local(&context.settings().hostname))
82     .collect::<Vec<MentionData>>();
83
84   for mention in &mentions {
85     // TODO should it be fetching it every time?
86     if let Ok(actor_id) = fetch_webfinger_url(mention, context).await {
87       let actor_id: ObjectId<Person> = ObjectId::new(actor_id);
88       debug!("mention actor_id: {}", actor_id);
89       addressed_ccs.push(actor_id.to_owned().to_string().parse()?);
90
91       let mention_person = actor_id.dereference(context, &mut 0).await?;
92       inboxes.push(mention_person.shared_inbox_or_inbox_url());
93
94       let mut mention_tag = Mention::new();
95       mention_tag
96         .set_href(actor_id.into())
97         .set_name(mention.full_name());
98       tags.push(mention_tag);
99     }
100   }
101
102   let inboxes = inboxes.into_iter().unique().collect();
103
104   Ok(MentionsAndAddresses {
105     ccs: addressed_ccs,
106     inboxes,
107     tags,
108   })
109 }
110
111 /// Returns the apub ID of the person this comment is responding to. Meaning, in case this is a
112 /// top-level comment, the creator of the post, otherwise the creator of the parent comment.
113 async fn get_comment_parent_creator(
114   pool: &DbPool,
115   comment: &Comment,
116 ) -> Result<Person, LemmyError> {
117   let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id {
118     let parent_comment =
119       blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??;
120     parent_comment.creator_id
121   } else {
122     let parent_post_id = comment.post_id;
123     let parent_post = blocking(pool, move |conn| Post::read(conn, parent_post_id)).await??;
124     parent_post.creator_id
125   };
126   Ok(blocking(pool, move |conn| Person::read(conn, parent_creator_id)).await??)
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 }