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::{context::LemmyContext, utils::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},
41 #[derive(Clone, Debug)]
42 pub struct ApubSite(Site);
44 impl Deref for ApubSite {
46 fn deref(&self) -> &Self::Target {
51 impl From<Site> for ApubSite {
52 fn from(s: Site) -> Self {
57 #[async_trait::async_trait(?Send)]
58 impl ApubObject for ApubSite {
59 type DataType = LemmyContext;
60 type ApubType = Instance;
62 type Error = LemmyError;
64 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
65 Some(self.last_refreshed_at)
68 #[tracing::instrument(skip_all)]
69 async fn read_from_apub_id(
71 data: &Self::DataType,
72 ) -> Result<Option<Self>, LemmyError> {
74 Site::read_from_apub_id(data.pool(), object_id)
80 async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
84 #[tracing::instrument(skip_all)]
85 async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
86 let site_id = self.id;
87 let langs = SiteLanguage::read(data.pool(), site_id).await?;
88 let language = LanguageTag::new_multiple(langs, data.pool()).await?;
90 let instance = Instance {
91 kind: InstanceType::Service,
92 id: ObjectId::new(self.actor_id()),
93 name: self.name.clone(),
94 content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
95 source: self.sidebar.clone().map(Source::new),
96 summary: self.description.clone(),
97 media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
98 icon: self.icon.clone().map(ImageObject::new),
99 image: self.banner.clone().map(ImageObject::new),
100 inbox: self.inbox_url.clone().into(),
101 outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
102 public_key: self.get_public_key(),
104 published: convert_datetime(self.published),
105 updated: self.updated.map(convert_datetime),
110 #[tracing::instrument(skip_all)]
112 apub: &Self::ApubType,
113 expected_domain: &Url,
114 data: &Self::DataType,
115 _request_counter: &mut i32,
116 ) -> Result<(), LemmyError> {
117 let local_site_data = fetch_local_site_data(data.pool()).await?;
119 check_apub_id_valid_with_strictness(apub.id.inner(), true, &local_site_data, data.settings())?;
120 verify_domains_match(expected_domain, apub.id.inner())?;
122 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
124 check_slurs(&apub.name, slur_regex)?;
125 check_slurs_opt(&apub.summary, slur_regex)?;
129 #[tracing::instrument(skip_all)]
131 apub: Self::ApubType,
132 data: &Self::DataType,
133 _request_counter: &mut i32,
134 ) -> Result<Self, LemmyError> {
135 let apub_id = apub.id.inner().clone();
136 let instance = DbInstance::create_from_actor_id(data.pool(), &apub_id).await?;
138 let site_form = SiteInsertForm {
139 name: apub.name.clone(),
140 sidebar: read_from_string_or_source_opt(&apub.content, &None, &apub.source),
141 updated: apub.updated.map(|u| u.clone().naive_local()),
142 icon: apub.icon.clone().map(|i| i.url.into()),
143 banner: apub.image.clone().map(|i| i.url.into()),
144 description: apub.summary.clone(),
145 actor_id: Some(apub.id.clone().into()),
146 last_refreshed_at: Some(naive_now()),
147 inbox_url: Some(apub.inbox.clone().into()),
148 public_key: Some(apub.public_key.public_key_pem.clone()),
150 instance_id: instance.id,
152 let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
154 let site = Site::create(data.pool(), &site_form).await?;
155 SiteLanguage::update(data.pool(), languages, &site).await?;
160 impl ActorType for ApubSite {
161 fn actor_id(&self) -> Url {
162 self.actor_id.clone().into()
164 fn private_key(&self) -> Option<String> {
165 self.private_key.clone()
169 impl Actor for ApubSite {
170 fn public_key(&self) -> &str {
174 fn inbox(&self) -> Url {
175 self.inbox_url.clone().into()
179 /// try to fetch the instance actor (to make things like instance rules available)
180 pub(in crate::objects) async fn fetch_instance_actor_for_object(
182 context: &LemmyContext,
183 request_counter: &mut i32,
185 // try to fetch the instance actor (to make things like instance rules available)
186 let instance_id = Site::instance_actor_id_from_url(object_id);
187 let site = ObjectId::<ApubSite>::new(instance_id.clone())
188 .dereference(context, local_instance(context).await, request_counter)
190 if let Err(e) = site {
191 debug!("Failed to dereference site for {}: {}", instance_id, e);
195 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
197 Site::read_remote_sites(pool)
200 .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
206 pub(crate) mod tests {
208 use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
209 use lemmy_db_schema::traits::Crud;
210 use serial_test::serial;
212 pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
213 let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
214 let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
215 let mut request_counter = 0;
216 ApubSite::verify(&json, &id, context, &mut request_counter)
219 let site = ApubSite::from_apub(json, context, &mut request_counter)
222 assert_eq!(request_counter, 0);
228 async fn test_parse_lemmy_instance() {
229 let context = init_context().await;
230 let site = parse_lemmy_instance(&context).await;
232 assert_eq!(site.name, "Enterprise");
233 assert_eq!(site.description.as_ref().unwrap().len(), 15);
235 Site::delete(context.pool(), site.id).await.unwrap();