2 check_apub_id_valid_with_strictness,
5 objects::read_from_string_or_source_opt,
8 instance::{Instance, InstanceType},
16 use activitypub_federation::{
17 core::object_id::ObjectId,
18 deser::values::MediaTypeHtml,
19 traits::{Actor, ApubObject},
20 utils::verify_domains_match,
22 use chrono::NaiveDateTime;
23 use lemmy_api_common::utils::{blocking, local_site_opt_to_slur_regex};
24 use lemmy_db_schema::{
26 actor_language::SiteLanguage,
27 instance::Instance as DbInstance,
28 site::{Site, SiteInsertForm},
31 utils::{naive_now, DbPool},
35 utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
37 use lemmy_websocket::LemmyContext;
42 #[derive(Clone, Debug)]
43 pub struct ApubSite(Site);
45 impl Deref for ApubSite {
47 fn deref(&self) -> &Self::Target {
52 impl From<Site> for ApubSite {
53 fn from(s: Site) -> Self {
58 #[async_trait::async_trait(?Send)]
59 impl ApubObject for ApubSite {
60 type DataType = LemmyContext;
61 type ApubType = Instance;
63 type Error = LemmyError;
65 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
66 Some(self.last_refreshed_at)
69 #[tracing::instrument(skip_all)]
70 async fn read_from_apub_id(
72 data: &Self::DataType,
73 ) -> Result<Option<Self>, LemmyError> {
75 blocking(data.pool(), move |conn| {
76 Site::read_from_apub_id(conn, object_id)
83 async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
87 #[tracing::instrument(skip_all)]
88 async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
89 let site_id = self.id;
90 let langs = blocking(data.pool(), move |conn| SiteLanguage::read(conn, site_id)).await??;
91 let language = LanguageTag::new_multiple(langs, data.pool()).await?;
93 let instance = Instance {
94 kind: InstanceType::Service,
95 id: ObjectId::new(self.actor_id()),
96 name: self.name.clone(),
97 content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
98 source: self.sidebar.clone().map(Source::new),
99 summary: self.description.clone(),
100 media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
101 icon: self.icon.clone().map(ImageObject::new),
102 image: self.banner.clone().map(ImageObject::new),
103 inbox: self.inbox_url.clone().into(),
104 outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
105 public_key: self.get_public_key(),
107 published: convert_datetime(self.published),
108 updated: self.updated.map(convert_datetime),
113 #[tracing::instrument(skip_all)]
115 apub: &Self::ApubType,
116 expected_domain: &Url,
117 data: &Self::DataType,
118 _request_counter: &mut i32,
119 ) -> Result<(), LemmyError> {
120 let local_site_data = blocking(data.pool(), fetch_local_site_data).await??;
122 check_apub_id_valid_with_strictness(apub.id.inner(), true, &local_site_data, data.settings())?;
123 verify_domains_match(expected_domain, apub.id.inner())?;
125 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
127 check_slurs(&apub.name, slur_regex)?;
128 check_slurs_opt(&apub.summary, slur_regex)?;
132 #[tracing::instrument(skip_all)]
134 apub: Self::ApubType,
135 data: &Self::DataType,
136 _request_counter: &mut i32,
137 ) -> Result<Self, LemmyError> {
138 let apub_id = apub.id.inner().to_owned();
139 let instance = blocking(data.pool(), move |conn| {
140 DbInstance::create_from_actor_id(conn, &apub_id)
144 let site_form = SiteInsertForm {
145 name: apub.name.clone(),
146 sidebar: read_from_string_or_source_opt(&apub.content, &None, &apub.source),
147 updated: apub.updated.map(|u| u.clone().naive_local()),
148 icon: apub.icon.clone().map(|i| i.url.into()),
149 banner: apub.image.clone().map(|i| i.url.into()),
150 description: apub.summary.clone(),
151 actor_id: Some(apub.id.clone().into()),
152 last_refreshed_at: Some(naive_now()),
153 inbox_url: Some(apub.inbox.clone().into()),
154 public_key: Some(apub.public_key.public_key_pem.clone()),
156 instance_id: instance.id,
158 let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
160 let site = blocking(data.pool(), move |conn| {
161 let site = Site::create(conn, &site_form)?;
162 SiteLanguage::update(conn, languages, site.id)?;
163 Ok::<Site, diesel::result::Error>(site)
170 impl ActorType for ApubSite {
171 fn actor_id(&self) -> Url {
172 self.actor_id.to_owned().into()
174 fn private_key(&self) -> Option<String> {
175 self.private_key.to_owned()
179 impl Actor for ApubSite {
180 fn public_key(&self) -> &str {
184 fn inbox(&self) -> Url {
185 self.inbox_url.clone().into()
189 /// Instance actor is at the root path, so we simply need to clear the path and other unnecessary
190 /// parts of the url.
191 pub fn instance_actor_id_from_url(mut url: Url) -> Url {
192 url.set_fragment(None);
198 /// try to fetch the instance actor (to make things like instance rules available)
199 pub(in crate::objects) async fn fetch_instance_actor_for_object(
201 context: &LemmyContext,
202 request_counter: &mut i32,
204 // try to fetch the instance actor (to make things like instance rules available)
205 let instance_id = instance_actor_id_from_url(object_id);
206 let site = ObjectId::<ApubSite>::new(instance_id.clone())
207 .dereference(context, local_instance(context), request_counter)
209 if let Err(e) = site {
210 debug!("Failed to dereference site for {}: {}", instance_id, e);
214 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
216 blocking(pool, Site::read_remote_sites)
219 .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
225 pub(crate) mod tests {
227 use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
228 use lemmy_db_schema::traits::Crud;
229 use serial_test::serial;
231 pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
232 let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
233 let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
234 let mut request_counter = 0;
235 ApubSite::verify(&json, &id, context, &mut request_counter)
238 let site = ApubSite::from_apub(json, context, &mut request_counter)
241 assert_eq!(request_counter, 0);
247 async fn test_parse_lemmy_instance() {
248 let context = init_context();
249 let conn = &mut context.pool().get().unwrap();
250 let site = parse_lemmy_instance(&context).await;
252 assert_eq!(site.name, "Enterprise");
253 assert_eq!(site.description.as_ref().unwrap().len(), 15);
255 Site::delete(conn, site.id).unwrap();