]> Untitled Git - lemmy.git/blob - server/src/apub/user.rs
Preferred usernames, banners and icons. (#1055)
[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     if let Some(banner_url) = &self.banner {
67       let mut image = Image::new();
68       image.set_url(banner_url.to_owned());
69       person.set_image(image.into_any_base()?);
70     }
71
72     if let Some(bio) = &self.bio {
73       person.set_summary(bio.to_owned());
74     }
75
76     let mut ap_actor = ApActor::new(self.get_inbox_url()?, person);
77     ap_actor
78       .set_outbox(self.get_outbox_url()?)
79       .set_followers(self.get_followers_url().parse()?)
80       .set_following(self.get_following_url().parse()?)
81       .set_liked(self.get_liked_url().parse()?)
82       .set_endpoints(Endpoints {
83         shared_inbox: Some(self.get_shared_inbox_url().parse()?),
84         ..Default::default()
85       });
86
87     if let Some(i) = &self.preferred_username {
88       ap_actor.set_preferred_username(i.to_owned());
89     }
90
91     Ok(Ext1::new(ap_actor, self.get_public_key_ext()))
92   }
93   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
94     unimplemented!()
95   }
96 }
97
98 #[async_trait::async_trait(?Send)]
99 impl ActorType for User_ {
100   fn actor_id_str(&self) -> String {
101     self.actor_id.to_owned()
102   }
103
104   fn public_key(&self) -> String {
105     self.public_key.to_owned().unwrap()
106   }
107
108   fn private_key(&self) -> String {
109     self.private_key.to_owned().unwrap()
110   }
111
112   /// As a given local user, send out a follow request to a remote community.
113   async fn send_follow(
114     &self,
115     follow_actor_id: &str,
116     client: &Client,
117     pool: &DbPool,
118   ) -> Result<(), LemmyError> {
119     let mut follow = Follow::new(self.actor_id.to_owned(), follow_actor_id);
120     follow
121       .set_context(context())
122       .set_id(generate_activity_id(FollowType::Follow)?);
123     let to = format!("{}/inbox", follow_actor_id);
124
125     insert_activity(self.id, follow.clone(), true, pool).await?;
126
127     send_activity(client, &follow.into_any_base()?, self, vec![to]).await?;
128     Ok(())
129   }
130
131   async fn send_unfollow(
132     &self,
133     follow_actor_id: &str,
134     client: &Client,
135     pool: &DbPool,
136   ) -> Result<(), LemmyError> {
137     let mut follow = Follow::new(self.actor_id.to_owned(), follow_actor_id);
138     follow
139       .set_context(context())
140       .set_id(generate_activity_id(FollowType::Follow)?);
141
142     let to = format!("{}/inbox", follow_actor_id);
143
144     // Undo that fake activity
145     let mut undo = Undo::new(Url::parse(&self.actor_id)?, follow.into_any_base()?);
146     undo
147       .set_context(context())
148       .set_id(generate_activity_id(UndoType::Undo)?);
149
150     insert_activity(self.id, undo.clone(), true, pool).await?;
151
152     send_activity(client, &undo.into_any_base()?, self, vec![to]).await?;
153     Ok(())
154   }
155
156   async fn send_delete(
157     &self,
158     _creator: &User_,
159     _client: &Client,
160     _pool: &DbPool,
161   ) -> Result<(), LemmyError> {
162     unimplemented!()
163   }
164
165   async fn send_undo_delete(
166     &self,
167     _creator: &User_,
168     _client: &Client,
169     _pool: &DbPool,
170   ) -> Result<(), LemmyError> {
171     unimplemented!()
172   }
173
174   async fn send_remove(
175     &self,
176     _creator: &User_,
177     _client: &Client,
178     _pool: &DbPool,
179   ) -> Result<(), LemmyError> {
180     unimplemented!()
181   }
182
183   async fn send_undo_remove(
184     &self,
185     _creator: &User_,
186     _client: &Client,
187     _pool: &DbPool,
188   ) -> Result<(), LemmyError> {
189     unimplemented!()
190   }
191
192   async fn send_accept_follow(
193     &self,
194     _follow: Follow,
195     _client: &Client,
196     _pool: &DbPool,
197   ) -> Result<(), LemmyError> {
198     unimplemented!()
199   }
200
201   async fn get_follower_inboxes(&self, _pool: &DbPool) -> Result<Vec<String>, LemmyError> {
202     unimplemented!()
203   }
204
205   fn user_id(&self) -> i32 {
206     self.id
207   }
208 }
209
210 #[async_trait::async_trait(?Send)]
211 impl FromApub for UserForm {
212   type ApubType = PersonExt;
213   /// Parse an ActivityPub person received from another instance into a Lemmy user.
214   async fn from_apub(person: &PersonExt, _: &Client, _: &DbPool) -> Result<Self, LemmyError> {
215     let avatar = match person.icon() {
216       Some(any_image) => Some(
217         Image::from_any_base(any_image.as_one().unwrap().clone())
218           .unwrap()
219           .unwrap()
220           .url()
221           .unwrap()
222           .as_single_xsd_any_uri()
223           .map(|u| u.to_string()),
224       ),
225       None => None,
226     };
227
228     let banner = match person.image() {
229       Some(any_image) => Some(
230         Image::from_any_base(any_image.as_one().unwrap().clone())
231           .unwrap()
232           .unwrap()
233           .url()
234           .unwrap()
235           .as_single_xsd_any_uri()
236           .map(|u| u.to_string()),
237       ),
238       None => None,
239     };
240
241     Ok(UserForm {
242       name: person
243         .name()
244         .unwrap()
245         .one()
246         .unwrap()
247         .as_xsd_string()
248         .unwrap()
249         .to_string(),
250       preferred_username: person.inner.preferred_username().map(|u| u.to_string()),
251       password_encrypted: "".to_string(),
252       admin: false,
253       banned: false,
254       email: None,
255       avatar,
256       banner,
257       updated: person.updated().map(|u| u.to_owned().naive_local()),
258       show_nsfw: false,
259       theme: "".to_string(),
260       default_sort_type: 0,
261       default_listing_type: 0,
262       lang: "".to_string(),
263       show_avatars: false,
264       send_notifications_to_email: false,
265       matrix_user_id: None,
266       actor_id: person.id_unchecked().unwrap().to_string(),
267       bio: person
268         .inner
269         .summary()
270         .map(|s| s.as_single_xsd_string().unwrap().into()),
271       local: false,
272       private_key: None,
273       public_key: Some(person.ext_one.public_key.to_owned().public_key_pem),
274       last_refreshed_at: Some(naive_now()),
275     })
276   }
277 }
278
279 /// Return the user json over HTTP.
280 pub async fn get_apub_user_http(
281   info: web::Path<UserQuery>,
282   db: DbPoolParam,
283 ) -> Result<HttpResponse<Body>, LemmyError> {
284   let user_name = info.into_inner().user_name;
285   let user = blocking(&db, move |conn| {
286     User_::find_by_email_or_username(conn, &user_name)
287   })
288   .await??;
289   let u = user.to_apub(&db).await?;
290   Ok(create_apub_response(&u))
291 }