1 use crate::{fetcher::person::get_or_fetch_and_upsert_person, ActorType};
4 link::{LinkExt, Mention},
7 use itertools::Itertools;
8 use lemmy_api_common::{blocking, comment::CommentResponse, send_local_notifs, WebFingerResponse};
9 use lemmy_db_queries::{Crud, DbPool};
10 use lemmy_db_schema::{
11 source::{comment::Comment, community::Community, person::Person, post::Post},
15 use lemmy_db_views::comment_view::CommentView;
17 request::{retry, RecvError},
18 settings::structs::Settings,
19 utils::{scrape_text_for_mentions, MentionData},
22 use lemmy_websocket::{messages::SendComment, LemmyContext};
27 pub mod create_or_update;
29 async fn get_notif_recipients(
32 context: &LemmyContext,
33 request_counter: &mut i32,
34 ) -> Result<Vec<LocalUserId>, LemmyError> {
35 let post_id = comment.post_id;
36 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
37 let actor = get_or_fetch_and_upsert_person(actor, context, request_counter).await?;
40 // Although mentions could be gotten from the post tags (they are included there), or the ccs,
41 // Its much easier to scrape them from the comment body, since the API has to do that
43 // TODO: for compatibility with other projects, it would be much better to read this from cc or tags
44 let mentions = scrape_text_for_mentions(&comment.content);
45 send_local_notifs(mentions, comment.clone(), actor, post, context.pool(), true).await
48 // TODO: in many call sites we are setting an empty vec for recipient_ids, we should get the actual
49 // recipient actors from somewhere
50 pub(crate) async fn send_websocket_message<
51 OP: ToString + Send + lemmy_websocket::OperationType + 'static,
53 comment_id: CommentId,
54 recipient_ids: Vec<LocalUserId>,
56 context: &LemmyContext,
57 ) -> Result<(), LemmyError> {
59 let comment_view = blocking(context.pool(), move |conn| {
60 CommentView::read(conn, comment_id, None)
64 let res = CommentResponse {
70 context.chat_server().do_send(SendComment {
79 pub struct MentionsAndAddresses {
81 pub inboxes: Vec<Url>,
82 pub tags: Vec<Mention>,
85 /// This takes a comment, and builds a list of to_addresses, inboxes,
86 /// and mention tags, so they know where to be sent to.
87 /// Addresses are the persons / addresses that go in the cc field.
88 pub async fn collect_non_local_mentions(
90 community: &Community,
91 context: &LemmyContext,
92 ) -> Result<MentionsAndAddresses, LemmyError> {
93 let parent_creator = get_comment_parent_creator(context.pool(), comment).await?;
94 let mut addressed_ccs = vec![community.actor_id(), parent_creator.actor_id()];
95 // Note: dont include community inbox here, as we send to it separately with `send_to_community()`
96 let mut inboxes = vec![parent_creator.get_shared_inbox_or_inbox_url()];
98 // Add the mention tag
99 let mut tags = Vec::new();
101 // Get the person IDs for any mentions
102 let mentions = scrape_text_for_mentions(&comment.content)
104 // Filter only the non-local ones
105 .filter(|m| !m.is_local())
106 .collect::<Vec<MentionData>>();
108 for mention in &mentions {
109 // TODO should it be fetching it every time?
110 if let Ok(actor_id) = fetch_webfinger_url(mention, context.client()).await {
111 debug!("mention actor_id: {}", actor_id);
112 addressed_ccs.push(actor_id.to_owned().to_string().parse()?);
114 let mention_person = get_or_fetch_and_upsert_person(&actor_id, context, &mut 0).await?;
115 inboxes.push(mention_person.get_shared_inbox_or_inbox_url());
117 let mut mention_tag = Mention::new();
118 mention_tag.set_href(actor_id).set_name(mention.full_name());
119 tags.push(mention_tag);
123 let inboxes = inboxes.into_iter().unique().collect();
125 Ok(MentionsAndAddresses {
132 /// Returns the apub ID of the person this comment is responding to. Meaning, in case this is a
133 /// top-level comment, the creator of the post, otherwise the creator of the parent comment.
134 async fn get_comment_parent_creator(
137 ) -> Result<Person, LemmyError> {
138 let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id {
140 blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??;
141 parent_comment.creator_id
143 let parent_post_id = comment.post_id;
144 let parent_post = blocking(pool, move |conn| Post::read(conn, parent_post_id)).await??;
145 parent_post.creator_id
147 Ok(blocking(pool, move |conn| Person::read(conn, parent_creator_id)).await??)
150 /// Turns a person id like `@name@example.com` into an apub ID, like `https://example.com/user/name`,
152 async fn fetch_webfinger_url(mention: &MentionData, client: &Client) -> Result<Url, LemmyError> {
153 let fetch_url = format!(
154 "{}://{}/.well-known/webfinger?resource=acct:{}@{}",
155 Settings::get().get_protocol_string(),
160 debug!("Fetching webfinger url: {}", &fetch_url);
162 let response = retry(|| client.get(&fetch_url).send()).await?;
164 let res: WebFingerResponse = response
167 .map_err(|e| RecvError(e.to_string()))?;
172 .find(|l| l.type_.eq(&Some("application/activity+json".to_string())))
173 .ok_or_else(|| anyhow!("No application/activity+json link found."))?;
177 .ok_or_else(|| anyhow!("No href found.").into())