]> Untitled Git - lemmy.git/blob - crates/apub/src/http/mod.rs
Handle Like, Undo/Like activities from Mastodon, add tests (fixes #2378) (#2380)
[lemmy.git] / crates / apub / src / http / mod.rs
1 use crate::{
2   activity_lists::SharedInboxActivities,
3   fetcher::user_or_community::UserOrCommunity,
4   insert_activity,
5   local_instance,
6   protocol::objects::tombstone::Tombstone,
7   CONTEXT,
8 };
9 use activitypub_federation::{
10   core::inbox::receive_activity,
11   data::Data,
12   deser::context::WithContext,
13   traits::{ActivityHandler, Actor, ApubObject},
14   APUB_JSON_CONTENT_TYPE,
15 };
16 use actix_web::{web, HttpRequest, HttpResponse};
17 use http::StatusCode;
18 use lemmy_api_common::utils::blocking;
19 use lemmy_db_schema::source::activity::Activity;
20 use lemmy_utils::error::LemmyError;
21 use lemmy_websocket::LemmyContext;
22 use once_cell::sync::OnceCell;
23 use serde::{de::DeserializeOwned, Deserialize, Serialize};
24 use serde_json::Value;
25 use std::ops::Deref;
26 use tracing::{debug, log::info};
27 use url::Url;
28
29 mod comment;
30 mod community;
31 mod person;
32 mod post;
33 pub mod routes;
34 pub mod site;
35
36 #[tracing::instrument(skip_all)]
37 pub async fn shared_inbox(
38   request: HttpRequest,
39   payload: String,
40   context: web::Data<LemmyContext>,
41 ) -> Result<HttpResponse, LemmyError> {
42   receive_lemmy_activity::<SharedInboxActivities, UserOrCommunity>(request, payload, context).await
43 }
44
45 pub async fn receive_lemmy_activity<Activity, ActorT>(
46   request: HttpRequest,
47   payload: String,
48   context: web::Data<LemmyContext>,
49 ) -> Result<HttpResponse, LemmyError>
50 where
51   Activity: ActivityHandler<DataType = LemmyContext, Error = LemmyError>
52     + DeserializeOwned
53     + Send
54     + 'static,
55   ActorT: ApubObject<DataType = LemmyContext, Error = LemmyError> + Actor + Send + 'static,
56   for<'de2> <ActorT as ApubObject>::ApubType: serde::Deserialize<'de2>,
57 {
58   let activity_value: Value = serde_json::from_str(&payload)?;
59   debug!("Received activity {:#}", payload.as_str());
60   let activity: Activity = serde_json::from_value(activity_value.clone())?;
61   // Log the activity, so we avoid receiving and parsing it twice.
62   let insert = insert_activity(activity.id(), activity_value, false, true, context.pool()).await?;
63   if !insert {
64     debug!("Received duplicate activity {}", activity.id().to_string());
65     return Ok(HttpResponse::BadRequest().finish());
66   }
67   info!("Received activity {}", payload);
68
69   static DATA: OnceCell<Data<LemmyContext>> = OnceCell::new();
70   let data = DATA.get_or_init(|| Data::new(context.get_ref().clone()));
71   receive_activity::<Activity, ActorT, LemmyContext>(
72     request,
73     activity,
74     local_instance(&context),
75     data,
76   )
77   .await
78 }
79
80 /// Convert the data to json and turn it into an HTTP Response with the correct ActivityPub
81 /// headers.
82 fn create_apub_response<T>(data: &T) -> HttpResponse
83 where
84   T: Serialize,
85 {
86   HttpResponse::Ok()
87     .content_type(APUB_JSON_CONTENT_TYPE)
88     .json(WithContext::new(data, CONTEXT.deref().clone()))
89 }
90
91 fn create_json_apub_response(data: serde_json::Value) -> HttpResponse {
92   HttpResponse::Ok()
93     .content_type(APUB_JSON_CONTENT_TYPE)
94     .json(data)
95 }
96
97 fn create_apub_tombstone_response<T: Into<Url>>(id: T) -> HttpResponse {
98   let tombstone = Tombstone::new(id.into());
99   HttpResponse::Gone()
100     .content_type(APUB_JSON_CONTENT_TYPE)
101     .status(StatusCode::GONE)
102     .json(WithContext::new(tombstone, CONTEXT.deref().clone()))
103 }
104
105 #[derive(Deserialize)]
106 pub struct ActivityQuery {
107   type_: String,
108   id: String,
109 }
110
111 /// Return the ActivityPub json representation of a local activity over HTTP.
112 #[tracing::instrument(skip_all)]
113 pub(crate) async fn get_activity(
114   info: web::Path<ActivityQuery>,
115   context: web::Data<LemmyContext>,
116 ) -> Result<HttpResponse, LemmyError> {
117   let settings = context.settings();
118   let activity_id = Url::parse(&format!(
119     "{}/activities/{}/{}",
120     settings.get_protocol_and_hostname(),
121     info.type_,
122     info.id
123   ))?
124   .into();
125   let activity = blocking(context.pool(), move |conn| {
126     Activity::read_from_apub_id(conn, &activity_id)
127   })
128   .await??;
129
130   let sensitive = activity.sensitive.unwrap_or(true);
131   if !activity.local || sensitive {
132     Ok(HttpResponse::NotFound().finish())
133   } else {
134     Ok(create_json_apub_response(activity.data))
135   }
136 }