]> Untitled Git - lemmy.git/blob - server/src/apub/community.rs
Merge branch 'dev' into federation
[lemmy.git] / server / src / apub / community.rs
1 use crate::apub::fetcher::{fetch_remote_object, fetch_remote_user};
2 use crate::apub::signatures::PublicKey;
3 use crate::apub::*;
4 use crate::db::community::{Community, CommunityForm};
5 use crate::db::community_view::CommunityFollowerView;
6 use crate::db::establish_unpooled_connection;
7 use crate::db::post::Post;
8 use crate::db::user::User_;
9 use crate::db::Crud;
10 use crate::settings::Settings;
11 use crate::{convert_datetime, naive_now};
12 use activitystreams::actor::properties::ApActorProperties;
13 use activitystreams::collection::OrderedCollection;
14 use activitystreams::{
15   actor::Group, collection::UnorderedCollection, context, ext::Extensible,
16   object::properties::ObjectProperties,
17 };
18 use actix_web::body::Body;
19 use actix_web::web::Path;
20 use actix_web::HttpResponse;
21 use actix_web::{web, Result};
22 use diesel::r2d2::{ConnectionManager, Pool};
23 use diesel::PgConnection;
24 use failure::Error;
25 use serde::Deserialize;
26 use url::Url;
27
28 #[derive(Deserialize)]
29 pub struct CommunityQuery {
30   community_name: String,
31 }
32
33 pub async fn get_apub_community_list(
34   db: web::Data<Pool<ConnectionManager<PgConnection>>>,
35 ) -> Result<HttpResponse<Body>, Error> {
36   // TODO: implement pagination
37   let communities = Community::list_local(&db.get().unwrap())?
38     .iter()
39     .map(|c| c.as_group(&db.get().unwrap()))
40     .collect::<Result<Vec<GroupExt>, Error>>()?;
41   let mut collection = UnorderedCollection::default();
42   let oprops: &mut ObjectProperties = collection.as_mut();
43   oprops.set_context_xsd_any_uri(context())?.set_id(format!(
44     "{}://{}/federation/communities",
45     get_apub_protocol_string(),
46     Settings::get().hostname
47   ))?;
48
49   collection
50     .collection_props
51     .set_total_items(communities.len() as u64)?
52     .set_many_items_base_boxes(communities)?;
53   Ok(create_apub_response(&collection))
54 }
55
56 impl Community {
57   fn as_group(&self, conn: &PgConnection) -> Result<GroupExt, Error> {
58     let mut group = Group::default();
59     let oprops: &mut ObjectProperties = group.as_mut();
60
61     let creator = User_::read(conn, self.creator_id)?;
62     oprops
63       .set_context_xsd_any_uri(context())?
64       .set_id(self.actor_id.to_owned())?
65       .set_name_xsd_string(self.name.to_owned())?
66       .set_published(convert_datetime(self.published))?
67       .set_attributed_to_xsd_any_uri(creator.actor_id)?;
68
69     if let Some(u) = self.updated.to_owned() {
70       oprops.set_updated(convert_datetime(u))?;
71     }
72     if let Some(d) = self.description.to_owned() {
73       // TODO: this should be html, also add source field with raw markdown
74       //       -> same for post.content and others
75       oprops.set_summary_xsd_string(d)?;
76     }
77
78     let mut actor_props = ApActorProperties::default();
79
80     actor_props
81       .set_preferred_username(self.title.to_owned())?
82       .set_inbox(self.get_inbox_url())?
83       .set_outbox(self.get_outbox_url())?
84       .set_followers(self.get_followers_url())?;
85
86     let public_key = PublicKey {
87       id: format!("{}#main-key", self.actor_id),
88       owner: self.actor_id.to_owned(),
89       public_key_pem: self.public_key.to_owned().unwrap(),
90     };
91
92     Ok(group.extend(actor_props).extend(public_key.to_ext()))
93   }
94
95   pub fn get_followers_url(&self) -> String {
96     format!("{}/followers", &self.actor_id)
97   }
98   pub fn get_inbox_url(&self) -> String {
99     format!("{}/inbox", &self.actor_id)
100   }
101   pub fn get_outbox_url(&self) -> String {
102     format!("{}/outbox", &self.actor_id)
103   }
104 }
105
106 impl CommunityForm {
107   pub fn from_group(group: &GroupExt, conn: &PgConnection) -> Result<Self, Error> {
108     let oprops = &group.base.base.object_props;
109     let aprops = &group.base.extension;
110     let public_key: &PublicKey = &group.extension.public_key;
111
112     let followers_uri = Url::parse(&aprops.get_followers().unwrap().to_string())?;
113     let outbox_uri = Url::parse(&aprops.get_outbox().to_string())?;
114     let _outbox = fetch_remote_object::<OrderedCollection>(&outbox_uri)?;
115     let _followers = fetch_remote_object::<UnorderedCollection>(&followers_uri)?;
116     let apub_id = Url::parse(&oprops.get_attributed_to_xsd_any_uri().unwrap().to_string())?;
117     let creator = fetch_remote_user(&apub_id, conn)?;
118
119     Ok(CommunityForm {
120       name: oprops.get_name_xsd_string().unwrap().to_string(),
121       title: aprops.get_preferred_username().unwrap().to_string(),
122       // TODO: should be parsed as html and tags like <script> removed (or use markdown source)
123       //       -> same for post.content etc
124       description: oprops.get_content_xsd_string().map(|s| s.to_string()),
125       category_id: 1, // -> peertube uses `"category": {"identifier": "9","name": "Comedy"},`
126       creator_id: creator.id,
127       removed: None,
128       published: oprops
129         .get_published()
130         .map(|u| u.as_ref().to_owned().naive_local()),
131       updated: oprops
132         .get_updated()
133         .map(|u| u.as_ref().to_owned().naive_local()),
134       deleted: None,
135       nsfw: false,
136       actor_id: oprops.get_id().unwrap().to_string(),
137       local: false,
138       private_key: None,
139       public_key: Some(public_key.to_owned().public_key_pem),
140       last_refreshed_at: Some(naive_now()),
141     })
142   }
143 }
144
145 pub async fn get_apub_community_http(
146   info: Path<CommunityQuery>,
147   db: web::Data<Pool<ConnectionManager<PgConnection>>>,
148 ) -> Result<HttpResponse<Body>, Error> {
149   let community = Community::read_from_name(&&db.get()?, info.community_name.to_owned())?;
150   let c = community.as_group(&db.get().unwrap())?;
151   Ok(create_apub_response(&c))
152 }
153
154 pub async fn get_apub_community_followers(
155   info: Path<CommunityQuery>,
156   db: web::Data<Pool<ConnectionManager<PgConnection>>>,
157 ) -> Result<HttpResponse<Body>, Error> {
158   let community = Community::read_from_name(&&db.get()?, info.community_name.to_owned())?;
159
160   let connection = establish_unpooled_connection();
161   //As we are an object, we validated that the community id was valid
162   let community_followers =
163     CommunityFollowerView::for_community(&connection, community.id).unwrap();
164
165   let mut collection = UnorderedCollection::default();
166   let oprops: &mut ObjectProperties = collection.as_mut();
167   oprops
168     .set_context_xsd_any_uri(context())?
169     .set_id(community.actor_id)?;
170   collection
171     .collection_props
172     .set_total_items(community_followers.len() as u64)?;
173   Ok(create_apub_response(&collection))
174 }
175
176 pub async fn get_apub_community_outbox(
177   info: Path<CommunityQuery>,
178   db: web::Data<Pool<ConnectionManager<PgConnection>>>,
179 ) -> Result<HttpResponse<Body>, Error> {
180   let community = Community::read_from_name(&&db.get()?, info.community_name.to_owned())?;
181
182   let conn = establish_unpooled_connection();
183   //As we are an object, we validated that the community id was valid
184   let community_posts: Vec<Post> = Post::list_for_community(&conn, community.id)?;
185
186   let mut collection = OrderedCollection::default();
187   let oprops: &mut ObjectProperties = collection.as_mut();
188   oprops
189     .set_context_xsd_any_uri(context())?
190     .set_id(community.actor_id)?;
191   collection
192     .collection_props
193     .set_many_items_base_boxes(
194       community_posts
195         .iter()
196         .map(|c| c.as_page(&conn).unwrap())
197         .collect(),
198     )?
199     .set_total_items(community_posts.len() as u64)?;
200
201   Ok(create_apub_response(&collection))
202 }