2 activity_lists::SharedInboxActivities,
3 check_is_apub_id_valid,
5 fetcher::get_or_fetch_and_upsert_actor,
6 http::{community::receive_group_inbox, person::receive_person_inbox},
12 web::{Bytes, BytesMut, Payload},
16 use anyhow::{anyhow, Context};
17 use futures::StreamExt;
19 use lemmy_api_common::blocking;
22 signatures::verify_signature,
23 traits::{ActivityFields, ActivityHandler},
24 APUB_JSON_CONTENT_TYPE,
26 use lemmy_db_schema::{source::activity::Activity, DbPool};
27 use lemmy_utils::{location_info, LemmyError};
28 use lemmy_websocket::LemmyContext;
30 use serde::{Deserialize, Serialize};
31 use std::{fmt::Debug, io::Read};
40 pub async fn shared_inbox(
43 context: web::Data<LemmyContext>,
44 ) -> Result<HttpResponse, LemmyError> {
45 let unparsed = payload_to_string(payload).await?;
46 info!("Received shared inbox activity {}", unparsed);
47 let activity = serde_json::from_str::<WithContext<SharedInboxActivities>>(&unparsed)?;
48 match activity.inner() {
49 SharedInboxActivities::GroupInboxActivities(g) => {
50 receive_group_inbox(g, request, &context).await
52 SharedInboxActivities::PersonInboxActivities(p) => {
53 receive_person_inbox(p, request, &context).await
58 async fn payload_to_string(mut payload: Payload) -> Result<String, LemmyError> {
59 let mut bytes = BytesMut::new();
60 while let Some(item) = payload.next().await {
61 bytes.extend_from_slice(&item?);
63 let mut unparsed = String::new();
64 Bytes::from(bytes).as_ref().read_to_string(&mut unparsed)?;
68 // TODO: move most of this code to library
69 async fn receive_activity<'a, T>(
72 context: &LemmyContext,
73 ) -> Result<HttpResponse, LemmyError>
75 T: ActivityHandler<DataType = LemmyContext>
84 let request_counter = &mut 0;
86 get_or_fetch_and_upsert_actor(activity.actor().clone(), context, request_counter).await?;
87 verify_signature(&request, &actor.public_key().context(location_info!())?)?;
89 // Do nothing if we received the same activity before
90 if is_activity_already_known(context.pool(), activity.id_unchecked()).await? {
91 return Ok(HttpResponse::Ok().finish());
93 check_is_apub_id_valid(activity.actor(), false, &context.settings())?;
94 info!("Verifying activity {}", activity.id_unchecked().to_string());
96 .verify(&Data::new(context.clone()), request_counter)
98 assert_activity_not_local(&activity, &context.settings().hostname)?;
100 // Log the activity, so we avoid receiving and parsing it twice. Note that this could still happen
101 // if we receive the same activity twice in very quick succession.
103 activity.id_unchecked(),
111 info!("Receiving activity {}", activity.id_unchecked().to_string());
113 .receive(&Data::new(context.clone()), request_counter)
115 Ok(HttpResponse::Ok().finish())
118 /// Convert the data to json and turn it into an HTTP Response with the correct ActivityPub
120 fn create_apub_response<T>(data: &T) -> HttpResponse<Body>
125 .content_type(APUB_JSON_CONTENT_TYPE)
126 .json(WithContext::new(data))
129 fn create_apub_tombstone_response<T>(data: &T) -> HttpResponse<Body>
134 .content_type(APUB_JSON_CONTENT_TYPE)
135 .status(StatusCode::GONE)
136 .json(WithContext::new(data))
139 #[derive(Deserialize)]
140 pub struct ActivityQuery {
145 /// Return the ActivityPub json representation of a local activity over HTTP.
146 pub(crate) async fn get_activity(
147 info: web::Path<ActivityQuery>,
148 context: web::Data<LemmyContext>,
149 ) -> Result<HttpResponse<Body>, LemmyError> {
150 let settings = context.settings();
151 let activity_id = Url::parse(&format!(
152 "{}/activities/{}/{}",
153 settings.get_protocol_and_hostname(),
158 let activity = blocking(context.pool(), move |conn| {
159 Activity::read_from_apub_id(conn, &activity_id)
163 let sensitive = activity.sensitive.unwrap_or(true);
164 if !activity.local || sensitive {
165 Ok(HttpResponse::NotFound().finish())
167 Ok(create_apub_response(&activity.data))
171 pub(crate) async fn is_activity_already_known(
174 ) -> Result<bool, LemmyError> {
175 let activity_id = activity_id.to_owned().into();
176 let existing = blocking(pool, move |conn| {
177 Activity::read_from_apub_id(conn, &activity_id)
186 fn assert_activity_not_local<T: Debug + ActivityFields>(
189 ) -> Result<(), LemmyError> {
190 let activity_domain = activity.id_unchecked().domain().context(location_info!())?;
192 if activity_domain == hostname {
195 "Error: received activity which was sent by local instance: {:?}",