2 activity_lists::SharedInboxActivities,
3 check_is_apub_id_valid,
5 fetcher::user_or_community::UserOrCommunity,
6 http::{community::receive_group_inbox, person::receive_person_inbox},
11 web::{Bytes, BytesMut, Payload},
16 use futures::StreamExt;
18 use lemmy_api_common::blocking;
22 signatures::verify_signature,
23 traits::{ActivityHandler, ActorType},
24 APUB_JSON_CONTENT_TYPE,
26 use lemmy_db_schema::source::activity::Activity;
27 use lemmy_utils::{location_info, LemmyError};
28 use lemmy_websocket::LemmyContext;
29 use serde::{Deserialize, Serialize};
30 use std::{fmt::Debug, io::Read};
41 #[tracing::instrument(skip_all)]
42 pub async fn shared_inbox(
45 context: web::Data<LemmyContext>,
46 ) -> Result<HttpResponse, LemmyError> {
47 let unparsed = payload_to_string(payload).await?;
48 info!("Received shared inbox activity {}", unparsed);
49 let activity_data: ActivityCommonFields = serde_json::from_str(&unparsed)?;
50 let activity = serde_json::from_str::<WithContext<SharedInboxActivities>>(&unparsed)?;
51 match activity.inner() {
52 SharedInboxActivities::GroupInboxActivities(g) => {
53 receive_group_inbox(*g, activity_data, request, &context).await
55 SharedInboxActivities::PersonInboxActivities(p) => {
56 receive_person_inbox(*p, activity_data, request, &context).await
61 async fn payload_to_string(mut payload: Payload) -> Result<String, LemmyError> {
62 let mut bytes = BytesMut::new();
63 while let Some(item) = payload.next().await {
64 bytes.extend_from_slice(&item?);
66 let mut unparsed = String::new();
67 Bytes::from(bytes).as_ref().read_to_string(&mut unparsed)?;
71 #[derive(Clone, Debug, Deserialize, Serialize)]
72 #[serde(rename_all = "camelCase")]
73 pub(crate) struct ActivityCommonFields {
75 pub(crate) actor: Url,
78 // TODO: move most of this code to library
79 #[tracing::instrument(skip_all)]
80 async fn receive_activity<'a, T>(
83 activity_data: ActivityCommonFields,
84 context: &LemmyContext,
85 ) -> Result<HttpResponse, LemmyError>
87 T: ActivityHandler<DataType = LemmyContext>
95 check_is_apub_id_valid(&activity_data.actor, false, &context.settings())?;
96 let request_counter = &mut 0;
97 let actor = ObjectId::<UserOrCommunity>::new(activity_data.actor)
98 .dereference(context, context.client(), request_counter)
100 verify_signature(&request, &actor.public_key())?;
102 info!("Verifying activity {}", activity_data.id.to_string());
104 .verify(&Data::new(context.clone()), request_counter)
106 assert_activity_not_local(&activity_data.id, &context.settings().hostname)?;
108 // Log the activity, so we avoid receiving and parsing it twice. Note that this could still happen
109 // if we receive the same activity twice in very quick succession.
110 let object_value = serde_json::to_value(&activity)?;
111 insert_activity(&activity_data.id, object_value, false, true, context.pool()).await?;
113 info!("Receiving activity {}", activity_data.id.to_string());
115 .receive(&Data::new(context.clone()), request_counter)
117 Ok(HttpResponse::Ok().finish())
120 /// Convert the data to json and turn it into an HTTP Response with the correct ActivityPub
122 fn create_apub_response<T>(data: &T) -> HttpResponse
127 .content_type(APUB_JSON_CONTENT_TYPE)
128 .json(WithContext::new(data))
131 fn create_json_apub_response(data: serde_json::Value) -> HttpResponse {
133 .content_type(APUB_JSON_CONTENT_TYPE)
137 fn create_apub_tombstone_response<T>(data: &T) -> HttpResponse
142 .content_type(APUB_JSON_CONTENT_TYPE)
143 .status(StatusCode::GONE)
144 .json(WithContext::new(data))
147 #[derive(Deserialize)]
148 pub struct ActivityQuery {
153 /// Return the ActivityPub json representation of a local activity over HTTP.
154 #[tracing::instrument(skip_all)]
155 pub(crate) async fn get_activity(
156 info: web::Path<ActivityQuery>,
157 context: web::Data<LemmyContext>,
158 ) -> Result<HttpResponse, LemmyError> {
159 let settings = context.settings();
160 let activity_id = Url::parse(&format!(
161 "{}/activities/{}/{}",
162 settings.get_protocol_and_hostname(),
167 let activity = blocking(context.pool(), move |conn| {
168 Activity::read_from_apub_id(conn, &activity_id)
172 let sensitive = activity.sensitive.unwrap_or(true);
173 if !activity.local || sensitive {
174 Ok(HttpResponse::NotFound().finish())
176 Ok(create_json_apub_response(activity.data))
180 fn assert_activity_not_local(id: &Url, hostname: &str) -> Result<(), LemmyError> {
181 let activity_domain = id.domain().context(location_info!())?;
183 if activity_domain == hostname {
184 let error = LemmyError::from(anyhow::anyhow!(
185 "Error: received activity which was sent by local instance: {:?}",
188 return Err(error.with_message("received_local_activity"));