2 check_is_apub_id_valid,
3 objects::{get_summary_from_string_or_source, verify_image_domain_matches},
4 protocol::{objects::instance::Instance, ImageObject, Source},
6 use activitystreams_kinds::actor::ServiceType;
7 use chrono::NaiveDateTime;
8 use lemmy_api_common::blocking;
11 traits::{ActorType, ApubObject},
12 values::MediaTypeHtml,
13 verify::verify_domains_match,
15 use lemmy_db_schema::{
17 source::site::{Site, SiteForm},
20 utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
23 use lemmy_websocket::LemmyContext;
28 #[derive(Clone, Debug)]
29 pub struct ApubSite(Site);
31 impl Deref for ApubSite {
33 fn deref(&self) -> &Self::Target {
38 impl From<Site> for ApubSite {
39 fn from(s: Site) -> Self {
44 #[async_trait::async_trait(?Send)]
45 impl ApubObject for ApubSite {
46 type DataType = LemmyContext;
47 type ApubType = Instance;
48 type TombstoneType = ();
50 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
51 Some(self.last_refreshed_at)
54 #[tracing::instrument(skip_all)]
55 async fn read_from_apub_id(
57 data: &Self::DataType,
58 ) -> Result<Option<Self>, LemmyError> {
60 blocking(data.pool(), move |conn| {
61 Site::read_from_apub_id(conn, object_id)
68 async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
72 #[tracing::instrument(skip_all)]
73 async fn into_apub(self, _data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
74 let instance = Instance {
75 kind: ServiceType::Service,
76 id: ObjectId::new(self.actor_id()),
77 name: self.name.clone(),
78 content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
79 source: self.sidebar.clone().map(Source::new),
80 summary: self.description.clone(),
81 media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
82 icon: self.icon.clone().map(ImageObject::new),
83 image: self.banner.clone().map(ImageObject::new),
84 inbox: self.inbox_url.clone().into(),
85 outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
86 public_key: self.get_public_key()?,
87 published: convert_datetime(self.published),
88 updated: self.updated.map(convert_datetime),
93 fn to_tombstone(&self) -> Result<Self::TombstoneType, LemmyError> {
97 #[tracing::instrument(skip_all)]
99 apub: &Self::ApubType,
100 expected_domain: &Url,
101 data: &Self::DataType,
102 _request_counter: &mut i32,
103 ) -> Result<(), LemmyError> {
104 check_is_apub_id_valid(apub.id.inner(), true, &data.settings())?;
105 verify_domains_match(expected_domain, apub.id.inner())?;
106 verify_image_domain_matches(expected_domain, &apub.icon)?;
107 verify_image_domain_matches(expected_domain, &apub.image)?;
109 let slur_regex = &data.settings().slur_regex();
110 check_slurs(&apub.name, slur_regex)?;
111 check_slurs_opt(&apub.summary, slur_regex)?;
115 #[tracing::instrument(skip_all)]
117 apub: Self::ApubType,
118 data: &Self::DataType,
119 _request_counter: &mut i32,
120 ) -> Result<Self, LemmyError> {
121 let site_form = SiteForm {
122 name: apub.name.clone(),
123 sidebar: Some(get_summary_from_string_or_source(
127 updated: apub.updated.map(|u| u.clone().naive_local()),
128 icon: Some(apub.icon.clone().map(|i| i.url.into())),
129 banner: Some(apub.image.clone().map(|i| i.url.into())),
130 description: Some(apub.summary.clone()),
131 actor_id: Some(apub.id.clone().into()),
132 last_refreshed_at: Some(naive_now()),
133 inbox_url: Some(apub.inbox.clone().into()),
134 public_key: Some(apub.public_key.public_key_pem.clone()),
135 ..SiteForm::default()
137 let site = blocking(data.pool(), move |conn| Site::upsert(conn, &site_form)).await??;
142 impl ActorType for ApubSite {
143 fn actor_id(&self) -> Url {
144 self.actor_id.to_owned().into()
146 fn public_key(&self) -> String {
147 self.public_key.to_owned()
149 fn private_key(&self) -> Option<String> {
150 self.private_key.to_owned()
153 fn inbox_url(&self) -> Url {
154 self.inbox_url.clone().into()
157 fn shared_inbox_url(&self) -> Option<Url> {
162 /// Instance actor is at the root path, so we simply need to clear the path and other unnecessary
163 /// parts of the url.
164 pub fn instance_actor_id_from_url(mut url: Url) -> Url {
165 url.set_fragment(None);
171 /// try to fetch the instance actor (to make things like instance rules available)
172 pub(in crate::objects) async fn fetch_instance_actor_for_object(
174 context: &LemmyContext,
175 request_counter: &mut i32,
177 // try to fetch the instance actor (to make things like instance rules available)
178 let instance_id = instance_actor_id_from_url(object_id);
179 let site = ObjectId::<ApubSite>::new(instance_id.clone())
180 .dereference(context, context.client(), request_counter)
182 if let Err(e) = site {
183 debug!("Failed to dereference site for {}: {}", instance_id, e);
188 pub(crate) mod tests {
190 use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
191 use lemmy_db_schema::traits::Crud;
192 use serial_test::serial;
194 pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
195 let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
196 let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
197 let mut request_counter = 0;
198 ApubSite::verify(&json, &id, context, &mut request_counter)
201 let site = ApubSite::from_apub(json, context, &mut request_counter)
204 assert_eq!(request_counter, 0);
210 async fn test_parse_lemmy_instance() {
211 let context = init_context();
212 let site = parse_lemmy_instance(&context).await;
214 assert_eq!(site.name, "Enterprise");
215 assert_eq!(site.description.as_ref().unwrap().len(), 15);
217 Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();