2 check_is_apub_id_valid,
3 objects::read_from_string_or_source_opt,
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())?;
111 let slur_regex = &data.settings().slur_regex();
112 check_slurs(&apub.name, slur_regex)?;
113 check_slurs_opt(&apub.summary, slur_regex)?;
117 #[tracing::instrument(skip_all)]
119 apub: Self::ApubType,
120 data: &Self::DataType,
121 _request_counter: &mut i32,
122 ) -> Result<Self, LemmyError> {
123 let site_form = SiteForm {
124 name: apub.name.clone(),
125 sidebar: Some(read_from_string_or_source_opt(
130 updated: apub.updated.map(|u| u.clone().naive_local()),
131 icon: Some(apub.icon.clone().map(|i| i.url.into())),
132 banner: Some(apub.image.clone().map(|i| i.url.into())),
133 description: Some(apub.summary.clone()),
134 actor_id: Some(apub.id.clone().into()),
135 last_refreshed_at: Some(naive_now()),
136 inbox_url: Some(apub.inbox.clone().into()),
137 public_key: Some(apub.public_key.public_key_pem.clone()),
138 ..SiteForm::default()
140 let site = blocking(data.pool(), move |conn| Site::upsert(conn, &site_form)).await??;
145 impl ActorType for ApubSite {
146 fn actor_id(&self) -> Url {
147 self.actor_id.to_owned().into()
149 fn public_key(&self) -> String {
150 self.public_key.to_owned()
152 fn private_key(&self) -> Option<String> {
153 self.private_key.to_owned()
156 fn inbox_url(&self) -> Url {
157 self.inbox_url.clone().into()
160 fn shared_inbox_url(&self) -> Option<Url> {
165 /// Instance actor is at the root path, so we simply need to clear the path and other unnecessary
166 /// parts of the url.
167 pub fn instance_actor_id_from_url(mut url: Url) -> Url {
168 url.set_fragment(None);
174 /// try to fetch the instance actor (to make things like instance rules available)
175 pub(in crate::objects) async fn fetch_instance_actor_for_object(
177 context: &LemmyContext,
178 request_counter: &mut i32,
180 // try to fetch the instance actor (to make things like instance rules available)
181 let instance_id = instance_actor_id_from_url(object_id);
182 let site = ObjectId::<ApubSite>::new(instance_id.clone())
183 .dereference(context, context.client(), request_counter)
185 if let Err(e) = site {
186 debug!("Failed to dereference site for {}: {}", instance_id, e);
191 pub(crate) mod tests {
193 use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
194 use lemmy_db_schema::traits::Crud;
195 use serial_test::serial;
197 pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
198 let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
199 let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
200 let mut request_counter = 0;
201 ApubSite::verify(&json, &id, context, &mut request_counter)
204 let site = ApubSite::from_apub(json, context, &mut request_counter)
207 assert_eq!(request_counter, 0);
213 async fn test_parse_lemmy_instance() {
214 let context = init_context();
215 let site = parse_lemmy_instance(&context).await;
217 assert_eq!(site.name, "Enterprise");
218 assert_eq!(site.description.as_ref().unwrap().len(), 15);
220 Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();