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