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