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