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