2 check_apub_id_valid_with_strictness,
4 objects::read_from_string_or_source_opt,
7 instance::{Instance, InstanceType},
15 use activitypub_federation::{
16 core::object_id::ObjectId,
17 deser::values::MediaTypeHtml,
18 traits::{Actor, ApubObject},
19 utils::verify_domains_match,
21 use chrono::NaiveDateTime;
22 use lemmy_api_common::utils::blocking;
23 use lemmy_db_schema::{
25 actor_language::SiteLanguage,
26 site::{Site, SiteForm},
28 utils::{naive_now, DbPool},
32 utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
34 use lemmy_websocket::LemmyContext;
39 #[derive(Clone, Debug)]
40 pub struct ApubSite(Site);
42 impl Deref for ApubSite {
44 fn deref(&self) -> &Self::Target {
49 impl From<Site> for ApubSite {
50 fn from(s: Site) -> Self {
55 #[async_trait::async_trait(?Send)]
56 impl ApubObject for ApubSite {
57 type DataType = LemmyContext;
58 type ApubType = Instance;
60 type Error = LemmyError;
62 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
63 Some(self.last_refreshed_at)
66 #[tracing::instrument(skip_all)]
67 async fn read_from_apub_id(
69 data: &Self::DataType,
70 ) -> Result<Option<Self>, LemmyError> {
72 blocking(data.pool(), move |conn| {
73 Site::read_from_apub_id(conn, 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 = blocking(data.pool(), move |conn| SiteLanguage::read(conn, 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 check_apub_id_valid_with_strictness(apub.id.inner(), true, data.settings())?;
118 verify_domains_match(expected_domain, apub.id.inner())?;
120 let slur_regex = &data.settings().slur_regex();
121 check_slurs(&apub.name, slur_regex)?;
122 check_slurs_opt(&apub.summary, slur_regex)?;
126 #[tracing::instrument(skip_all)]
128 apub: Self::ApubType,
129 data: &Self::DataType,
130 _request_counter: &mut i32,
131 ) -> Result<Self, LemmyError> {
132 let site_form = SiteForm {
133 name: apub.name.clone(),
134 sidebar: Some(read_from_string_or_source_opt(
139 updated: apub.updated.map(|u| u.clone().naive_local()),
140 icon: Some(apub.icon.clone().map(|i| i.url.into())),
141 banner: Some(apub.image.clone().map(|i| i.url.into())),
142 description: Some(apub.summary.clone()),
143 actor_id: Some(apub.id.clone().into()),
144 last_refreshed_at: Some(naive_now()),
145 inbox_url: Some(apub.inbox.clone().into()),
146 public_key: Some(apub.public_key.public_key_pem.clone()),
147 ..SiteForm::default()
149 let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
151 let site = blocking(data.pool(), move |conn| {
152 let site = Site::upsert(conn, &site_form)?;
153 SiteLanguage::update(conn, languages, site.id)?;
154 Ok::<Site, diesel::result::Error>(site)
161 impl ActorType for ApubSite {
162 fn actor_id(&self) -> Url {
163 self.actor_id.to_owned().into()
165 fn private_key(&self) -> Option<String> {
166 self.private_key.to_owned()
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), 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 blocking(pool, Site::read_remote_sites)
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();
240 let conn = &mut context.pool().get().unwrap();
241 let site = parse_lemmy_instance(&context).await;
243 assert_eq!(site.name, "Enterprise");
244 assert_eq!(site.description.as_ref().unwrap().len(), 15);
246 Site::delete(conn, site.id).unwrap();