]> Untitled Git - lemmy.git/blob - crates/apub/src/http/mod.rs
Extract Activitypub logic into separate library (#2288)
[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, ActorPublicKey},
11   data::Data,
12   deser::context::WithContext,
13   traits::{ActivityHandler, 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, Actor>(
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   Actor: ApubObject<DataType = LemmyContext, Error = LemmyError> + ActorPublicKey + Send + 'static,
56   for<'de2> <Actor as ApubObject>::ApubType: serde::Deserialize<'de2>,
57 {
58   let activity_value: Value = serde_json::from_str(&payload)?;
59   let activity: Activity = serde_json::from_value(activity_value.clone())?;
60   // Log the activity, so we avoid receiving and parsing it twice.
61   let insert = insert_activity(activity.id(), activity_value, false, true, context.pool()).await?;
62   if !insert {
63     debug!("Received duplicate activity {}", activity.id().to_string());
64     return Ok(HttpResponse::BadRequest().finish());
65   }
66   info!("Received activity {}", payload);
67
68   static DATA: OnceCell<Data<LemmyContext>> = OnceCell::new();
69   let data = DATA.get_or_init(|| Data::new(context.get_ref().clone()));
70   receive_activity::<Activity, Actor, LemmyContext, LemmyError>(
71     request,
72     activity,
73     local_instance(&context),
74     data,
75   )
76   .await
77 }
78
79 /// Convert the data to json and turn it into an HTTP Response with the correct ActivityPub
80 /// headers.
81 fn create_apub_response<T>(data: &T) -> HttpResponse
82 where
83   T: Serialize,
84 {
85   HttpResponse::Ok()
86     .content_type(APUB_JSON_CONTENT_TYPE)
87     .json(WithContext::new(data, CONTEXT.deref().clone()))
88 }
89
90 fn create_json_apub_response(data: serde_json::Value) -> HttpResponse {
91   HttpResponse::Ok()
92     .content_type(APUB_JSON_CONTENT_TYPE)
93     .json(data)
94 }
95
96 fn create_apub_tombstone_response<T: Into<Url>>(id: T) -> HttpResponse {
97   let tombstone = Tombstone::new(id.into());
98   HttpResponse::Gone()
99     .content_type(APUB_JSON_CONTENT_TYPE)
100     .status(StatusCode::GONE)
101     .json(WithContext::new(tombstone, CONTEXT.deref().clone()))
102 }
103
104 #[derive(Deserialize)]
105 pub struct ActivityQuery {
106   type_: String,
107   id: String,
108 }
109
110 /// Return the ActivityPub json representation of a local activity over HTTP.
111 #[tracing::instrument(skip_all)]
112 pub(crate) async fn get_activity(
113   info: web::Path<ActivityQuery>,
114   context: web::Data<LemmyContext>,
115 ) -> Result<HttpResponse, LemmyError> {
116   let settings = context.settings();
117   let activity_id = Url::parse(&format!(
118     "{}/activities/{}/{}",
119     settings.get_protocol_and_hostname(),
120     info.type_,
121     info.id
122   ))?
123   .into();
124   let activity = blocking(context.pool(), move |conn| {
125     Activity::read_from_apub_id(conn, &activity_id)
126   })
127   .await??;
128
129   let sensitive = activity.sensitive.unwrap_or(true);
130   if !activity.local || sensitive {
131     Ok(HttpResponse::NotFound().finish())
132   } else {
133     Ok(create_json_apub_response(activity.data))
134   }
135 }