]> Untitled Git - lemmy.git/blob - server/src/apub/user.rs
routes.api: fix get_captcha endpoint (#1135)
[lemmy.git] / server / src / apub / user.rs
1 use crate::{
2   apub::{
3     activities::generate_activity_id,
4     activity_queue::send_activity,
5     check_actor_domain,
6     create_apub_response,
7     fetcher::get_or_fetch_and_upsert_actor,
8     insert_activity,
9     ActorType,
10     FromApub,
11     PersonExt,
12     ToApub,
13   },
14   DbPool,
15   LemmyContext,
16 };
17 use activitystreams::{
18   activity::{
19     kind::{FollowType, UndoType},
20     Follow,
21     Undo,
22   },
23   actor::{ApActor, Endpoints, Person},
24   object::{Image, Tombstone},
25   prelude::*,
26 };
27 use activitystreams_ext::Ext1;
28 use actix_web::{body::Body, web, HttpResponse};
29 use anyhow::Context;
30 use lemmy_api_structs::blocking;
31 use lemmy_db::{
32   naive_now,
33   user::{UserForm, User_},
34 };
35 use lemmy_utils::{
36   location_info,
37   utils::{check_slurs, check_slurs_opt, convert_datetime},
38   LemmyError,
39 };
40 use serde::Deserialize;
41 use url::Url;
42
43 #[derive(Deserialize)]
44 pub struct UserQuery {
45   user_name: String,
46 }
47
48 #[async_trait::async_trait(?Send)]
49 impl ToApub for User_ {
50   type Response = PersonExt;
51
52   // Turn a Lemmy Community into an ActivityPub group that can be sent out over the network.
53   async fn to_apub(&self, _pool: &DbPool) -> Result<PersonExt, LemmyError> {
54     // TODO go through all these to_string and to_owned()
55     let mut person = Person::new();
56     person
57       .set_context(activitystreams::context())
58       .set_id(Url::parse(&self.actor_id)?)
59       .set_name(self.name.to_owned())
60       .set_published(convert_datetime(self.published));
61
62     if let Some(u) = self.updated {
63       person.set_updated(convert_datetime(u));
64     }
65
66     if let Some(avatar_url) = &self.avatar {
67       let mut image = Image::new();
68       image.set_url(avatar_url.to_owned());
69       person.set_icon(image.into_any_base()?);
70     }
71
72     if let Some(banner_url) = &self.banner {
73       let mut image = Image::new();
74       image.set_url(banner_url.to_owned());
75       person.set_image(image.into_any_base()?);
76     }
77
78     if let Some(bio) = &self.bio {
79       person.set_summary(bio.to_owned());
80     }
81
82     let mut ap_actor = ApActor::new(self.get_inbox_url()?, person);
83     ap_actor
84       .set_outbox(self.get_outbox_url()?)
85       .set_followers(self.get_followers_url()?)
86       .set_following(self.get_following_url().parse()?)
87       .set_liked(self.get_liked_url().parse()?)
88       .set_endpoints(Endpoints {
89         shared_inbox: Some(self.get_shared_inbox_url()?),
90         ..Default::default()
91       });
92
93     if let Some(i) = &self.preferred_username {
94       ap_actor.set_preferred_username(i.to_owned());
95     }
96
97     Ok(Ext1::new(ap_actor, self.get_public_key_ext()?))
98   }
99   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
100     unimplemented!()
101   }
102 }
103
104 #[async_trait::async_trait(?Send)]
105 impl ActorType for User_ {
106   fn actor_id_str(&self) -> String {
107     self.actor_id.to_owned()
108   }
109
110   fn public_key(&self) -> Option<String> {
111     self.public_key.to_owned()
112   }
113
114   fn private_key(&self) -> Option<String> {
115     self.private_key.to_owned()
116   }
117
118   /// As a given local user, send out a follow request to a remote community.
119   async fn send_follow(
120     &self,
121     follow_actor_id: &Url,
122     context: &LemmyContext,
123   ) -> Result<(), LemmyError> {
124     let mut follow = Follow::new(self.actor_id.to_owned(), follow_actor_id.as_str());
125     follow
126       .set_context(activitystreams::context())
127       .set_id(generate_activity_id(FollowType::Follow)?);
128     let follow_actor = get_or_fetch_and_upsert_actor(follow_actor_id, context).await?;
129     let to = follow_actor.get_inbox_url()?;
130
131     insert_activity(self.id, follow.clone(), true, context.pool()).await?;
132
133     send_activity(context.activity_queue(), follow, self, vec![to])?;
134     Ok(())
135   }
136
137   async fn send_unfollow(
138     &self,
139     follow_actor_id: &Url,
140     context: &LemmyContext,
141   ) -> Result<(), LemmyError> {
142     let mut follow = Follow::new(self.actor_id.to_owned(), follow_actor_id.as_str());
143     follow
144       .set_context(activitystreams::context())
145       .set_id(generate_activity_id(FollowType::Follow)?);
146     let follow_actor = get_or_fetch_and_upsert_actor(follow_actor_id, context).await?;
147
148     let to = follow_actor.get_inbox_url()?;
149
150     // Undo that fake activity
151     let mut undo = Undo::new(Url::parse(&self.actor_id)?, follow.into_any_base()?);
152     undo
153       .set_context(activitystreams::context())
154       .set_id(generate_activity_id(UndoType::Undo)?);
155
156     insert_activity(self.id, undo.clone(), true, context.pool()).await?;
157
158     send_activity(context.activity_queue(), undo, self, vec![to])?;
159     Ok(())
160   }
161
162   async fn send_delete(&self, _creator: &User_, _context: &LemmyContext) -> Result<(), LemmyError> {
163     unimplemented!()
164   }
165
166   async fn send_undo_delete(
167     &self,
168     _creator: &User_,
169     _context: &LemmyContext,
170   ) -> Result<(), LemmyError> {
171     unimplemented!()
172   }
173
174   async fn send_remove(&self, _creator: &User_, _context: &LemmyContext) -> Result<(), LemmyError> {
175     unimplemented!()
176   }
177
178   async fn send_undo_remove(
179     &self,
180     _creator: &User_,
181     _context: &LemmyContext,
182   ) -> Result<(), LemmyError> {
183     unimplemented!()
184   }
185
186   async fn send_accept_follow(
187     &self,
188     _follow: Follow,
189     _context: &LemmyContext,
190   ) -> Result<(), LemmyError> {
191     unimplemented!()
192   }
193
194   async fn get_follower_inboxes(&self, _pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
195     unimplemented!()
196   }
197
198   fn user_id(&self) -> i32 {
199     self.id
200   }
201 }
202
203 #[async_trait::async_trait(?Send)]
204 impl FromApub for UserForm {
205   type ApubType = PersonExt;
206   /// Parse an ActivityPub person received from another instance into a Lemmy user.
207   async fn from_apub(
208     person: &PersonExt,
209     _context: &LemmyContext,
210     expected_domain: Option<Url>,
211   ) -> Result<Self, LemmyError> {
212     let avatar = match person.icon() {
213       Some(any_image) => Some(
214         Image::from_any_base(any_image.as_one().context(location_info!())?.clone())?
215           .context(location_info!())?
216           .url()
217           .context(location_info!())?
218           .as_single_xsd_any_uri()
219           .map(|u| u.to_string()),
220       ),
221       None => None,
222     };
223
224     let banner = match person.image() {
225       Some(any_image) => Some(
226         Image::from_any_base(any_image.as_one().context(location_info!())?.clone())
227           .context(location_info!())?
228           .context(location_info!())?
229           .url()
230           .context(location_info!())?
231           .as_single_xsd_any_uri()
232           .map(|u| u.to_string()),
233       ),
234       None => None,
235     };
236
237     let name = person
238       .name()
239       .context(location_info!())?
240       .one()
241       .context(location_info!())?
242       .as_xsd_string()
243       .context(location_info!())?
244       .to_string();
245     let preferred_username = person.inner.preferred_username().map(|u| u.to_string());
246     let bio = person
247       .inner
248       .summary()
249       .map(|s| s.as_single_xsd_string())
250       .flatten()
251       .map(|s| s.to_string());
252     check_slurs(&name)?;
253     check_slurs_opt(&preferred_username)?;
254     check_slurs_opt(&bio)?;
255
256     Ok(UserForm {
257       name,
258       preferred_username,
259       password_encrypted: "".to_string(),
260       admin: false,
261       banned: false,
262       email: None,
263       avatar,
264       banner,
265       updated: person.updated().map(|u| u.to_owned().naive_local()),
266       show_nsfw: false,
267       theme: "".to_string(),
268       default_sort_type: 0,
269       default_listing_type: 0,
270       lang: "".to_string(),
271       show_avatars: false,
272       send_notifications_to_email: false,
273       matrix_user_id: None,
274       actor_id: Some(check_actor_domain(person, expected_domain)?),
275       bio,
276       local: false,
277       private_key: None,
278       public_key: Some(person.ext_one.public_key.to_owned().public_key_pem),
279       last_refreshed_at: Some(naive_now()),
280     })
281   }
282 }
283
284 /// Return the user json over HTTP.
285 pub async fn get_apub_user_http(
286   info: web::Path<UserQuery>,
287   context: web::Data<LemmyContext>,
288 ) -> Result<HttpResponse<Body>, LemmyError> {
289   let user_name = info.into_inner().user_name;
290   let user = blocking(context.pool(), move |conn| {
291     User_::find_by_email_or_username(conn, &user_name)
292   })
293   .await??;
294   let u = user.to_apub(context.pool()).await?;
295   Ok(create_apub_response(&u))
296 }