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::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 Site::read_from_apub_id(data.pool(), object_id)
81 async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
85 #[tracing::instrument(skip_all)]
86 async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
87 let site_id = self.id;
88 let langs = SiteLanguage::read(data.pool(), site_id).await?;
89 let language = LanguageTag::new_multiple(langs, data.pool()).await?;
91 let instance = Instance {
92 kind: InstanceType::Service,
93 id: ObjectId::new(self.actor_id()),
94 name: self.name.clone(),
95 content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
96 source: self.sidebar.clone().map(Source::new),
97 summary: self.description.clone(),
98 media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
99 icon: self.icon.clone().map(ImageObject::new),
100 image: self.banner.clone().map(ImageObject::new),
101 inbox: self.inbox_url.clone().into(),
102 outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
103 public_key: self.get_public_key(),
105 published: convert_datetime(self.published),
106 updated: self.updated.map(convert_datetime),
111 #[tracing::instrument(skip_all)]
113 apub: &Self::ApubType,
114 expected_domain: &Url,
115 data: &Self::DataType,
116 _request_counter: &mut i32,
117 ) -> Result<(), LemmyError> {
118 let local_site_data = fetch_local_site_data(data.pool()).await?;
120 check_apub_id_valid_with_strictness(apub.id.inner(), true, &local_site_data, data.settings())?;
121 verify_domains_match(expected_domain, apub.id.inner())?;
123 let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
125 check_slurs(&apub.name, slur_regex)?;
126 check_slurs_opt(&apub.summary, slur_regex)?;
130 #[tracing::instrument(skip_all)]
132 apub: Self::ApubType,
133 data: &Self::DataType,
134 _request_counter: &mut i32,
135 ) -> Result<Self, LemmyError> {
136 let apub_id = apub.id.inner().clone();
137 let instance = DbInstance::create_from_actor_id(data.pool(), &apub_id).await?;
139 let site_form = SiteInsertForm {
140 name: apub.name.clone(),
141 sidebar: read_from_string_or_source_opt(&apub.content, &None, &apub.source),
142 updated: apub.updated.map(|u| u.clone().naive_local()),
143 icon: apub.icon.clone().map(|i| i.url.into()),
144 banner: apub.image.clone().map(|i| i.url.into()),
145 description: apub.summary.clone(),
146 actor_id: Some(apub.id.clone().into()),
147 last_refreshed_at: Some(naive_now()),
148 inbox_url: Some(apub.inbox.clone().into()),
149 public_key: Some(apub.public_key.public_key_pem.clone()),
151 instance_id: instance.id,
153 let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
155 let site = Site::create(data.pool(), &site_form).await?;
156 SiteLanguage::update(data.pool(), languages, &site).await?;
161 impl ActorType for ApubSite {
162 fn actor_id(&self) -> Url {
163 self.actor_id.clone().into()
165 fn private_key(&self) -> Option<String> {
166 self.private_key.clone()
170 impl Actor for ApubSite {
171 fn public_key(&self) -> &str {
175 fn inbox(&self) -> Url {
176 self.inbox_url.clone().into()
180 /// Instance actor is at the root path, so we simply need to clear the path and other unnecessary
181 /// parts of the url.
182 pub fn instance_actor_id_from_url(mut url: Url) -> Url {
183 url.set_fragment(None);
189 /// try to fetch the instance actor (to make things like instance rules available)
190 pub(in crate::objects) async fn fetch_instance_actor_for_object(
192 context: &LemmyContext,
193 request_counter: &mut i32,
195 // try to fetch the instance actor (to make things like instance rules available)
196 let instance_id = instance_actor_id_from_url(object_id);
197 let site = ObjectId::<ApubSite>::new(instance_id.clone())
198 .dereference(context, local_instance(context).await, request_counter)
200 if let Err(e) = site {
201 debug!("Failed to dereference site for {}: {}", instance_id, e);
205 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
207 Site::read_remote_sites(pool)
210 .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
216 pub(crate) mod tests {
218 use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
219 use lemmy_db_schema::traits::Crud;
220 use serial_test::serial;
222 pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
223 let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
224 let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
225 let mut request_counter = 0;
226 ApubSite::verify(&json, &id, context, &mut request_counter)
229 let site = ApubSite::from_apub(json, context, &mut request_counter)
232 assert_eq!(request_counter, 0);
238 async fn test_parse_lemmy_instance() {
239 let context = init_context().await;
240 let site = parse_lemmy_instance(&context).await;
242 assert_eq!(site.name, "Enterprise");
243 assert_eq!(site.description.as_ref().unwrap().len(), 15);
245 Site::delete(context.pool(), site.id).await.unwrap();