2 check_is_apub_id_valid,
3 objects::{read_from_string_or_source_opt, verify_image_domain_matches},
5 objects::instance::{Instance, InstanceType},
10 use chrono::NaiveDateTime;
11 use lemmy_api_common::utils::blocking;
14 traits::{ActorType, ApubObject},
15 values::MediaTypeHtml,
16 verify::verify_domains_match,
18 use lemmy_db_schema::{
19 source::site::{Site, SiteForm},
23 utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
26 use lemmy_websocket::LemmyContext;
31 #[derive(Clone, Debug)]
32 pub struct ApubSite(Site);
34 impl Deref for ApubSite {
36 fn deref(&self) -> &Self::Target {
41 impl From<Site> for ApubSite {
42 fn from(s: Site) -> Self {
47 #[async_trait::async_trait(?Send)]
48 impl ApubObject for ApubSite {
49 type DataType = LemmyContext;
50 type ApubType = Instance;
52 type TombstoneType = ();
54 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
55 Some(self.last_refreshed_at)
58 #[tracing::instrument(skip_all)]
59 async fn read_from_apub_id(
61 data: &Self::DataType,
62 ) -> Result<Option<Self>, LemmyError> {
64 blocking(data.pool(), move |conn| {
65 Site::read_from_apub_id(conn, object_id)
72 async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
76 #[tracing::instrument(skip_all)]
77 async fn into_apub(self, _data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
78 let instance = Instance {
79 kind: InstanceType::Service,
80 id: ObjectId::new(self.actor_id()),
81 name: self.name.clone(),
82 content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
83 source: self.sidebar.clone().map(Source::new),
84 summary: self.description.clone(),
85 media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
86 icon: self.icon.clone().map(ImageObject::new),
87 image: self.banner.clone().map(ImageObject::new),
88 inbox: self.inbox_url.clone().into(),
89 outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
90 public_key: self.get_public_key()?,
91 published: convert_datetime(self.published),
92 updated: self.updated.map(convert_datetime),
97 fn to_tombstone(&self) -> Result<Self::TombstoneType, LemmyError> {
101 #[tracing::instrument(skip_all)]
103 apub: &Self::ApubType,
104 expected_domain: &Url,
105 data: &Self::DataType,
106 _request_counter: &mut i32,
107 ) -> Result<(), LemmyError> {
108 check_is_apub_id_valid(apub.id.inner(), true, &data.settings())?;
109 verify_domains_match(expected_domain, apub.id.inner())?;
110 verify_image_domain_matches(expected_domain, &apub.icon)?;
111 verify_image_domain_matches(expected_domain, &apub.image)?;
113 let slur_regex = &data.settings().slur_regex();
114 check_slurs(&apub.name, slur_regex)?;
115 check_slurs_opt(&apub.summary, slur_regex)?;
119 #[tracing::instrument(skip_all)]
121 apub: Self::ApubType,
122 data: &Self::DataType,
123 _request_counter: &mut i32,
124 ) -> Result<Self, LemmyError> {
125 let site_form = SiteForm {
126 name: apub.name.clone(),
127 sidebar: Some(read_from_string_or_source_opt(
132 updated: apub.updated.map(|u| u.clone().naive_local()),
133 icon: Some(apub.icon.clone().map(|i| i.url.into())),
134 banner: Some(apub.image.clone().map(|i| i.url.into())),
135 description: Some(apub.summary.clone()),
136 actor_id: Some(apub.id.clone().into()),
137 last_refreshed_at: Some(naive_now()),
138 inbox_url: Some(apub.inbox.clone().into()),
139 public_key: Some(apub.public_key.public_key_pem.clone()),
140 ..SiteForm::default()
142 let site = blocking(data.pool(), move |conn| Site::upsert(conn, &site_form)).await??;
147 impl ActorType for ApubSite {
148 fn actor_id(&self) -> Url {
149 self.actor_id.to_owned().into()
151 fn public_key(&self) -> String {
152 self.public_key.to_owned()
154 fn private_key(&self) -> Option<String> {
155 self.private_key.to_owned()
158 fn inbox_url(&self) -> Url {
159 self.inbox_url.clone().into()
162 fn shared_inbox_url(&self) -> Option<Url> {
167 /// Instance actor is at the root path, so we simply need to clear the path and other unnecessary
168 /// parts of the url.
169 pub fn instance_actor_id_from_url(mut url: Url) -> Url {
170 url.set_fragment(None);
176 /// try to fetch the instance actor (to make things like instance rules available)
177 pub(in crate::objects) async fn fetch_instance_actor_for_object(
179 context: &LemmyContext,
180 request_counter: &mut i32,
182 // try to fetch the instance actor (to make things like instance rules available)
183 let instance_id = instance_actor_id_from_url(object_id);
184 let site = ObjectId::<ApubSite>::new(instance_id.clone())
185 .dereference(context, context.client(), request_counter)
187 if let Err(e) = site {
188 debug!("Failed to dereference site for {}: {}", instance_id, e);
193 pub(crate) mod tests {
195 use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
196 use lemmy_db_schema::traits::Crud;
197 use serial_test::serial;
199 pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
200 let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
201 let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
202 let mut request_counter = 0;
203 ApubSite::verify(&json, &id, context, &mut request_counter)
206 let site = ApubSite::from_apub(json, context, &mut request_counter)
209 assert_eq!(request_counter, 0);
215 async fn test_parse_lemmy_instance() {
216 let context = init_context();
217 let site = parse_lemmy_instance(&context).await;
219 assert_eq!(site.name, "Enterprise");
220 assert_eq!(site.description.as_ref().unwrap().len(), 15);
222 Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();