]> Untitled Git - lemmy.git/blob - server/src/apub/user.rs
Federation async (#848)
[lemmy.git] / server / src / apub / user.rs
1 use crate::{
2   apub::{
3     activities::send_activity,
4     create_apub_response,
5     extensions::signatures::PublicKey,
6     ActorType,
7     FromApub,
8     PersonExt,
9     ToApub,
10   },
11   blocking,
12   convert_datetime,
13   db::{
14     activity::insert_activity,
15     user::{UserForm, User_},
16   },
17   naive_now,
18   routes::DbPoolParam,
19   DbPool,
20   LemmyError,
21 };
22 use activitystreams::{
23   actor::{properties::ApActorProperties, Person},
24   context,
25   endpoint::EndpointProperties,
26   object::{properties::ObjectProperties, AnyImage, Image},
27   primitives::XsdAnyUri,
28 };
29 use activitystreams_ext::Ext2;
30 use activitystreams_new::{
31   activity::{Follow, Undo},
32   object::Tombstone,
33   prelude::*,
34 };
35 use actix_web::{body::Body, client::Client, web, HttpResponse};
36 use serde::Deserialize;
37
38 #[derive(Deserialize)]
39 pub struct UserQuery {
40   user_name: String,
41 }
42
43 #[async_trait::async_trait(?Send)]
44 impl ToApub for User_ {
45   type Response = PersonExt;
46
47   // Turn a Lemmy Community into an ActivityPub group that can be sent out over the network.
48   async fn to_apub(&self, _pool: &DbPool) -> Result<PersonExt, LemmyError> {
49     // TODO go through all these to_string and to_owned()
50     let mut person = Person::default();
51     let oprops: &mut ObjectProperties = person.as_mut();
52     oprops
53       .set_context_xsd_any_uri(context())?
54       .set_id(self.actor_id.to_string())?
55       .set_name_xsd_string(self.name.to_owned())?
56       .set_published(convert_datetime(self.published))?;
57
58     if let Some(u) = self.updated {
59       oprops.set_updated(convert_datetime(u))?;
60     }
61
62     if let Some(i) = &self.preferred_username {
63       oprops.set_name_xsd_string(i.to_owned())?;
64     }
65
66     if let Some(avatar_url) = &self.avatar {
67       let mut image = Image::new();
68       image
69         .object_props
70         .set_url_xsd_any_uri(avatar_url.to_owned())?;
71       let any_image = AnyImage::from_concrete(image)?;
72       oprops.set_icon_any_image(any_image)?;
73     }
74
75     let mut endpoint_props = EndpointProperties::default();
76
77     endpoint_props.set_shared_inbox(self.get_shared_inbox_url())?;
78
79     let mut actor_props = ApActorProperties::default();
80
81     actor_props
82       .set_inbox(self.get_inbox_url())?
83       .set_outbox(self.get_outbox_url())?
84       .set_endpoints(endpoint_props)?
85       .set_followers(self.get_followers_url())?
86       .set_following(self.get_following_url())?
87       .set_liked(self.get_liked_url())?;
88
89     Ok(Ext2::new(person, actor_props, self.get_public_key_ext()))
90   }
91   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
92     unimplemented!()
93   }
94 }
95
96 #[async_trait::async_trait(?Send)]
97 impl ActorType for User_ {
98   fn actor_id(&self) -> String {
99     self.actor_id.to_owned()
100   }
101
102   fn public_key(&self) -> String {
103     self.public_key.to_owned().unwrap()
104   }
105
106   fn private_key(&self) -> String {
107     self.private_key.to_owned().unwrap()
108   }
109
110   /// As a given local user, send out a follow request to a remote community.
111   async fn send_follow(
112     &self,
113     follow_actor_id: &str,
114     client: &Client,
115     pool: &DbPool,
116   ) -> Result<(), LemmyError> {
117     let id = format!("{}/follow/{}", self.actor_id, uuid::Uuid::new_v4());
118     let mut follow = Follow::new(self.actor_id.to_owned(), follow_actor_id);
119     follow.set_context(context()).set_id(id.parse()?);
120     let to = format!("{}/inbox", follow_actor_id);
121
122     insert_activity(self.id, follow.clone(), true, pool).await?;
123
124     send_activity(client, &follow, self, vec![to]).await?;
125     Ok(())
126   }
127
128   async fn send_unfollow(
129     &self,
130     follow_actor_id: &str,
131     client: &Client,
132     pool: &DbPool,
133   ) -> Result<(), LemmyError> {
134     let id = format!("{}/follow/{}", self.actor_id, uuid::Uuid::new_v4());
135     let mut follow = Follow::new(self.actor_id.to_owned(), follow_actor_id);
136     follow.set_context(context()).set_id(id.parse()?);
137
138     let to = format!("{}/inbox", follow_actor_id);
139
140     // TODO
141     // Undo that fake activity
142     let undo_id = format!("{}/undo/follow/{}", self.actor_id, uuid::Uuid::new_v4());
143     let mut undo = Undo::new(self.actor_id.parse::<XsdAnyUri>()?, follow.into_any_base()?);
144     undo.set_context(context()).set_id(undo_id.parse()?);
145
146     insert_activity(self.id, undo.clone(), true, pool).await?;
147
148     send_activity(client, &undo, self, vec![to]).await?;
149     Ok(())
150   }
151
152   async fn send_delete(
153     &self,
154     _creator: &User_,
155     _client: &Client,
156     _pool: &DbPool,
157   ) -> Result<(), LemmyError> {
158     unimplemented!()
159   }
160
161   async fn send_undo_delete(
162     &self,
163     _creator: &User_,
164     _client: &Client,
165     _pool: &DbPool,
166   ) -> Result<(), LemmyError> {
167     unimplemented!()
168   }
169
170   async fn send_remove(
171     &self,
172     _creator: &User_,
173     _client: &Client,
174     _pool: &DbPool,
175   ) -> Result<(), LemmyError> {
176     unimplemented!()
177   }
178
179   async fn send_undo_remove(
180     &self,
181     _creator: &User_,
182     _client: &Client,
183     _pool: &DbPool,
184   ) -> Result<(), LemmyError> {
185     unimplemented!()
186   }
187
188   async fn send_accept_follow(
189     &self,
190     _follow: &Follow,
191     _client: &Client,
192     _pool: &DbPool,
193   ) -> Result<(), LemmyError> {
194     unimplemented!()
195   }
196
197   async fn get_follower_inboxes(&self, _pool: &DbPool) -> Result<Vec<String>, LemmyError> {
198     unimplemented!()
199   }
200 }
201
202 #[async_trait::async_trait(?Send)]
203 impl FromApub for UserForm {
204   type ApubType = PersonExt;
205   /// Parse an ActivityPub person received from another instance into a Lemmy user.
206   async fn from_apub(person: &PersonExt, _: &Client, _: &DbPool) -> Result<Self, LemmyError> {
207     let oprops = &person.inner.object_props;
208     let aprops = &person.ext_one;
209     let public_key: &PublicKey = &person.ext_two.public_key;
210
211     let avatar = match oprops.get_icon_any_image() {
212       Some(any_image) => any_image
213         .to_owned()
214         .into_concrete::<Image>()?
215         .object_props
216         .get_url_xsd_any_uri()
217         .map(|u| u.to_string()),
218       None => None,
219     };
220
221     Ok(UserForm {
222       name: oprops.get_name_xsd_string().unwrap().to_string(),
223       preferred_username: aprops.get_preferred_username().map(|u| u.to_string()),
224       password_encrypted: "".to_string(),
225       admin: false,
226       banned: false,
227       email: None,
228       avatar,
229       updated: oprops
230         .get_updated()
231         .map(|u| u.as_ref().to_owned().naive_local()),
232       show_nsfw: false,
233       theme: "".to_string(),
234       default_sort_type: 0,
235       default_listing_type: 0,
236       lang: "".to_string(),
237       show_avatars: false,
238       send_notifications_to_email: false,
239       matrix_user_id: None,
240       actor_id: oprops.get_id().unwrap().to_string(),
241       bio: oprops.get_summary_xsd_string().map(|s| s.to_string()),
242       local: false,
243       private_key: None,
244       public_key: Some(public_key.to_owned().public_key_pem),
245       last_refreshed_at: Some(naive_now()),
246     })
247   }
248 }
249
250 /// Return the user json over HTTP.
251 pub async fn get_apub_user_http(
252   info: web::Path<UserQuery>,
253   db: DbPoolParam,
254 ) -> Result<HttpResponse<Body>, LemmyError> {
255   let user_name = info.into_inner().user_name;
256   let user = blocking(&db, move |conn| {
257     User_::find_by_email_or_username(conn, &user_name)
258   })
259   .await??;
260   let u = user.to_apub(&db).await?;
261   Ok(create_apub_response(&u))
262 }