2 check_apub_id_valid_with_strictness,
3 local_site_data_cached,
4 objects::read_from_string_or_source_opt,
6 objects::{instance::Instance, LanguageTag},
11 use activitypub_federation::{
13 fetch::object_id::ObjectId,
14 kinds::actor::ApplicationType,
15 protocol::{values::MediaTypeHtml, verification::verify_domains_match},
16 traits::{Actor, Object},
18 use chrono::NaiveDateTime;
19 use lemmy_api_common::{context::LemmyContext, utils::local_site_opt_to_slur_regex};
20 use lemmy_db_schema::{
23 actor_language::SiteLanguage,
24 instance::Instance as DbInstance,
25 site::{Site, SiteInsertForm},
28 utils::{naive_now, DbPool},
33 markdown::markdown_to_html,
34 slurs::{check_slurs, check_slurs_opt},
35 time::convert_datetime,
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]
59 impl Object for ApubSite {
60 type DataType = LemmyContext;
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_id(
71 data: &Data<Self::DataType>,
72 ) -> Result<Option<Self>, LemmyError> {
74 Site::read_from_apub_id(data.pool(), &object_id.into())
80 async fn delete(self, _data: &Data<Self::DataType>) -> Result<(), LemmyError> {
84 #[tracing::instrument(skip_all)]
85 async fn into_json(self, data: &Data<Self::DataType>) -> Result<Self::Kind, 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: ApplicationType::Application,
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.public_key(),
104 published: convert_datetime(self.published),
105 updated: self.updated.map(convert_datetime),
110 #[tracing::instrument(skip_all)]
113 expected_domain: &Url,
114 data: &Data<Self::DataType>,
115 ) -> Result<(), LemmyError> {
116 check_apub_id_valid_with_strictness(apub.id.inner(), true, data).await?;
117 verify_domains_match(expected_domain, apub.id.inner())?;
119 let local_site_data = local_site_data_cached(data.pool()).await?;
120 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
121 check_slurs(&apub.name, slur_regex)?;
122 check_slurs_opt(&apub.summary, slur_regex)?;
127 #[tracing::instrument(skip_all)]
128 async fn from_json(apub: Self::Kind, data: &Data<Self::DataType>) -> Result<Self, LemmyError> {
129 let domain = apub.id.inner().domain().expect("group id has domain");
130 let instance = DbInstance::read_or_create(data.pool(), domain.to_string()).await?;
132 let site_form = SiteInsertForm {
133 name: apub.name.clone(),
134 sidebar: read_from_string_or_source_opt(&apub.content, &None, &apub.source),
135 updated: apub.updated.map(|u| u.clone().naive_local()),
136 icon: apub.icon.clone().map(|i| i.url.into()),
137 banner: apub.image.clone().map(|i| i.url.into()),
138 description: apub.summary.clone(),
139 actor_id: Some(apub.id.clone().into()),
140 last_refreshed_at: Some(naive_now()),
141 inbox_url: Some(apub.inbox.clone().into()),
142 public_key: Some(apub.public_key.public_key_pem.clone()),
144 instance_id: instance.id,
146 let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
148 let site = Site::create(data.pool(), &site_form).await?;
149 SiteLanguage::update(data.pool(), languages, &site).await?;
154 impl Actor for ApubSite {
155 fn id(&self) -> Url {
156 self.actor_id.inner().clone()
159 fn public_key_pem(&self) -> &str {
163 fn private_key_pem(&self) -> Option<String> {
164 self.private_key.clone()
167 fn inbox(&self) -> Url {
168 self.inbox_url.clone().into()
172 /// Try to fetch the instance actor (to make things like instance rules available).
173 pub(in crate::objects) async fn fetch_instance_actor_for_object<T: Into<Url> + Clone>(
175 context: &Data<LemmyContext>,
176 ) -> Result<InstanceId, LemmyError> {
177 let object_id: Url = object_id.clone().into();
178 let instance_id = Site::instance_actor_id_from_url(object_id);
179 let site = ObjectId::<ApubSite>::from(instance_id.clone())
180 .dereference(context)
183 Ok(s) => Ok(s.instance_id),
185 // Failed to fetch instance actor, its probably not a lemmy instance
186 debug!("Failed to dereference site for {}: {}", &instance_id, e);
187 let domain = instance_id.domain().expect("has domain");
189 DbInstance::read_or_create(context.pool(), domain.to_string())
197 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
199 Site::read_remote_sites(pool)
202 .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
208 pub(crate) mod tests {
210 use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
211 use lemmy_db_schema::traits::Crud;
212 use serial_test::serial;
214 pub(crate) async fn parse_lemmy_instance(context: &Data<LemmyContext>) -> ApubSite {
215 let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
216 let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
217 ApubSite::verify(&json, &id, context).await.unwrap();
218 let site = ApubSite::from_json(json, context).await.unwrap();
219 assert_eq!(context.request_count(), 0);
225 async fn test_parse_lemmy_instance() {
226 let context = init_context().await;
227 let site = parse_lemmy_instance(&context).await;
229 assert_eq!(site.name, "Enterprise");
230 assert_eq!(site.description.as_ref().unwrap().len(), 15);
232 Site::delete(context.pool(), site.id).await.unwrap();