]> Untitled Git - lemmy.git/blob - server/src/apub/mod.rs
Merge branch 'federation_add_fed_columns' of https://yerbamate.dev/dessalines/lemmy...
[lemmy.git] / server / src / apub / mod.rs
1 pub mod community;
2 pub mod post;
3 pub mod puller;
4 pub mod user;
5 use crate::Settings;
6 use openssl::{pkey::PKey, rsa::Rsa};
7
8 use activitystreams::actor::{properties::ApActorProperties, Group};
9 use activitystreams::ext::Ext;
10 use actix_web::body::Body;
11 use actix_web::HttpResponse;
12 use url::Url;
13
14 type GroupExt = Ext<Group, ApActorProperties>;
15
16 fn create_apub_response<T>(json: &T) -> HttpResponse<Body>
17 where
18   T: serde::ser::Serialize,
19 {
20   HttpResponse::Ok()
21     .content_type("application/activity+json")
22     .json(json)
23 }
24
25 pub enum EndpointType {
26   Community,
27   User,
28   Post,
29 }
30
31 pub fn make_apub_endpoint(endpoint_type: EndpointType, name: &str) -> Url {
32   let point = match endpoint_type {
33     EndpointType::Community => "c",
34     EndpointType::User => "u",
35     EndpointType::Post => "p",
36   };
37
38   Url::parse(&format!(
39     "{}://{}/federation/{}/{}",
40     get_apub_protocol_string(),
41     Settings::get().hostname,
42     point,
43     name
44   ))
45   .unwrap()
46 }
47
48 pub fn get_apub_protocol_string() -> &'static str {
49   if Settings::get().federation.tls_enabled {
50     "https"
51   } else {
52     "http"
53   }
54 }
55
56 pub fn gen_keypair() -> (Vec<u8>, Vec<u8>) {
57   let rsa = Rsa::generate(2048).expect("sign::gen_keypair: key generation error");
58   let pkey = PKey::from_rsa(rsa).expect("sign::gen_keypair: parsing error");
59   (
60     pkey
61       .public_key_to_pem()
62       .expect("sign::gen_keypair: public key encoding error"),
63     pkey
64       .private_key_to_pem_pkcs8()
65       .expect("sign::gen_keypair: private key encoding error"),
66   )
67 }
68
69 pub fn gen_keypair_str() -> (String, String) {
70   let (public_key, private_key) = gen_keypair();
71   (vec_bytes_to_str(public_key), vec_bytes_to_str(private_key))
72 }
73
74 fn vec_bytes_to_str(bytes: Vec<u8>) -> String {
75   String::from_utf8_lossy(&bytes).into_owned()
76 }