]> Untitled Git - lemmy.git/blob - crates/api/src/site.rs
aae400ca7464188a48ef8778567280ac4b5cc140
[lemmy.git] / crates / api / src / site.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use anyhow::Context;
4 use lemmy_api_common::{
5   blocking,
6   build_federated_instances,
7   get_local_user_settings_view_from_jwt,
8   get_local_user_view_from_jwt,
9   get_local_user_view_from_jwt_opt,
10   is_admin,
11   site::*,
12   user_show_bot_accounts,
13   user_show_nsfw,
14 };
15 use lemmy_apub::fetcher::search::search_by_apub_id;
16 use lemmy_db_queries::{source::site::Site_, Crud, SearchType, SortType};
17 use lemmy_db_schema::source::{moderator::*, site::Site};
18 use lemmy_db_views::{
19   comment_view::CommentQueryBuilder,
20   post_view::PostQueryBuilder,
21   site_view::SiteView,
22 };
23 use lemmy_db_views_actor::{
24   community_view::CommunityQueryBuilder,
25   person_view::{PersonQueryBuilder, PersonViewSafe},
26 };
27 use lemmy_db_views_moderator::{
28   mod_add_community_view::ModAddCommunityView,
29   mod_add_view::ModAddView,
30   mod_ban_from_community_view::ModBanFromCommunityView,
31   mod_ban_view::ModBanView,
32   mod_lock_post_view::ModLockPostView,
33   mod_remove_comment_view::ModRemoveCommentView,
34   mod_remove_community_view::ModRemoveCommunityView,
35   mod_remove_post_view::ModRemovePostView,
36   mod_sticky_post_view::ModStickyPostView,
37 };
38 use lemmy_utils::{
39   location_info,
40   settings::structs::Settings,
41   version,
42   ApiError,
43   ConnectionId,
44   LemmyError,
45 };
46 use lemmy_websocket::LemmyContext;
47 use log::debug;
48 use std::str::FromStr;
49
50 #[async_trait::async_trait(?Send)]
51 impl Perform for GetModlog {
52   type Response = GetModlogResponse;
53
54   async fn perform(
55     &self,
56     context: &Data<LemmyContext>,
57     _websocket_id: Option<ConnectionId>,
58   ) -> Result<GetModlogResponse, LemmyError> {
59     let data: &GetModlog = &self;
60
61     let community_id = data.community_id;
62     let mod_person_id = data.mod_person_id;
63     let page = data.page;
64     let limit = data.limit;
65     let removed_posts = blocking(context.pool(), move |conn| {
66       ModRemovePostView::list(conn, community_id, mod_person_id, page, limit)
67     })
68     .await??;
69
70     let locked_posts = blocking(context.pool(), move |conn| {
71       ModLockPostView::list(conn, community_id, mod_person_id, page, limit)
72     })
73     .await??;
74
75     let stickied_posts = blocking(context.pool(), move |conn| {
76       ModStickyPostView::list(conn, community_id, mod_person_id, page, limit)
77     })
78     .await??;
79
80     let removed_comments = blocking(context.pool(), move |conn| {
81       ModRemoveCommentView::list(conn, community_id, mod_person_id, page, limit)
82     })
83     .await??;
84
85     let banned_from_community = blocking(context.pool(), move |conn| {
86       ModBanFromCommunityView::list(conn, community_id, mod_person_id, page, limit)
87     })
88     .await??;
89
90     let added_to_community = blocking(context.pool(), move |conn| {
91       ModAddCommunityView::list(conn, community_id, mod_person_id, page, limit)
92     })
93     .await??;
94
95     // These arrays are only for the full modlog, when a community isn't given
96     let (removed_communities, banned, added) = if data.community_id.is_none() {
97       blocking(context.pool(), move |conn| {
98         Ok((
99           ModRemoveCommunityView::list(conn, mod_person_id, page, limit)?,
100           ModBanView::list(conn, mod_person_id, page, limit)?,
101           ModAddView::list(conn, mod_person_id, page, limit)?,
102         )) as Result<_, LemmyError>
103       })
104       .await??
105     } else {
106       (Vec::new(), Vec::new(), Vec::new())
107     };
108
109     // Return the jwt
110     Ok(GetModlogResponse {
111       removed_posts,
112       locked_posts,
113       stickied_posts,
114       removed_comments,
115       removed_communities,
116       banned_from_community,
117       banned,
118       added_to_community,
119       added,
120     })
121   }
122 }
123
124 #[async_trait::async_trait(?Send)]
125 impl Perform for Search {
126   type Response = SearchResponse;
127
128   async fn perform(
129     &self,
130     context: &Data<LemmyContext>,
131     _websocket_id: Option<ConnectionId>,
132   ) -> Result<SearchResponse, LemmyError> {
133     let data: &Search = &self;
134
135     match search_by_apub_id(&data.q, context).await {
136       Ok(r) => return Ok(r),
137       Err(e) => debug!("Failed to resolve search query as activitypub ID: {}", e),
138     }
139
140     let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?;
141
142     let show_nsfw = user_show_nsfw(&local_user_view);
143     let show_bot_accounts = user_show_bot_accounts(&local_user_view);
144
145     let person_id = local_user_view.map(|u| u.person.id);
146
147     let type_ = SearchType::from_str(&data.type_)?;
148
149     let mut posts = Vec::new();
150     let mut comments = Vec::new();
151     let mut communities = Vec::new();
152     let mut users = Vec::new();
153
154     // TODO no clean / non-nsfw searching rn
155
156     let q = data.q.to_owned();
157     let page = data.page;
158     let limit = data.limit;
159     let sort = SortType::from_str(&data.sort)?;
160     let community_id = data.community_id;
161     let community_name = data.community_name.to_owned();
162     match type_ {
163       SearchType::Posts => {
164         posts = blocking(context.pool(), move |conn| {
165           PostQueryBuilder::create(conn)
166             .sort(&sort)
167             .show_nsfw(show_nsfw)
168             .show_bot_accounts(show_bot_accounts)
169             .community_id(community_id)
170             .community_name(community_name)
171             .my_person_id(person_id)
172             .search_term(q)
173             .page(page)
174             .limit(limit)
175             .list()
176         })
177         .await??;
178       }
179       SearchType::Comments => {
180         comments = blocking(context.pool(), move |conn| {
181           CommentQueryBuilder::create(&conn)
182             .sort(&sort)
183             .search_term(q)
184             .show_bot_accounts(show_bot_accounts)
185             .my_person_id(person_id)
186             .page(page)
187             .limit(limit)
188             .list()
189         })
190         .await??;
191       }
192       SearchType::Communities => {
193         communities = blocking(context.pool(), move |conn| {
194           CommunityQueryBuilder::create(conn)
195             .sort(&sort)
196             .search_term(q)
197             .my_person_id(person_id)
198             .page(page)
199             .limit(limit)
200             .list()
201         })
202         .await??;
203       }
204       SearchType::Users => {
205         users = blocking(context.pool(), move |conn| {
206           PersonQueryBuilder::create(conn)
207             .sort(&sort)
208             .search_term(q)
209             .page(page)
210             .limit(limit)
211             .list()
212         })
213         .await??;
214       }
215       SearchType::All => {
216         posts = blocking(context.pool(), move |conn| {
217           PostQueryBuilder::create(conn)
218             .sort(&sort)
219             .show_nsfw(show_nsfw)
220             .show_bot_accounts(show_bot_accounts)
221             .community_id(community_id)
222             .community_name(community_name)
223             .my_person_id(person_id)
224             .search_term(q)
225             .page(page)
226             .limit(limit)
227             .list()
228         })
229         .await??;
230
231         let q = data.q.to_owned();
232         let sort = SortType::from_str(&data.sort)?;
233
234         comments = blocking(context.pool(), move |conn| {
235           CommentQueryBuilder::create(conn)
236             .sort(&sort)
237             .search_term(q)
238             .show_bot_accounts(show_bot_accounts)
239             .my_person_id(person_id)
240             .page(page)
241             .limit(limit)
242             .list()
243         })
244         .await??;
245
246         let q = data.q.to_owned();
247         let sort = SortType::from_str(&data.sort)?;
248
249         communities = blocking(context.pool(), move |conn| {
250           CommunityQueryBuilder::create(conn)
251             .sort(&sort)
252             .search_term(q)
253             .my_person_id(person_id)
254             .page(page)
255             .limit(limit)
256             .list()
257         })
258         .await??;
259
260         let q = data.q.to_owned();
261         let sort = SortType::from_str(&data.sort)?;
262
263         users = blocking(context.pool(), move |conn| {
264           PersonQueryBuilder::create(conn)
265             .sort(&sort)
266             .search_term(q)
267             .page(page)
268             .limit(limit)
269             .list()
270         })
271         .await??;
272       }
273       SearchType::Url => {
274         posts = blocking(context.pool(), move |conn| {
275           PostQueryBuilder::create(conn)
276             .sort(&sort)
277             .show_nsfw(show_nsfw)
278             .show_bot_accounts(show_bot_accounts)
279             .my_person_id(person_id)
280             .community_id(community_id)
281             .community_name(community_name)
282             .url_search(q)
283             .page(page)
284             .limit(limit)
285             .list()
286         })
287         .await??;
288       }
289     };
290
291     // Return the jwt
292     Ok(SearchResponse {
293       type_: data.type_.to_owned(),
294       comments,
295       posts,
296       communities,
297       users,
298     })
299   }
300 }
301
302 #[async_trait::async_trait(?Send)]
303 impl Perform for TransferSite {
304   type Response = GetSiteResponse;
305
306   async fn perform(
307     &self,
308     context: &Data<LemmyContext>,
309     _websocket_id: Option<ConnectionId>,
310   ) -> Result<GetSiteResponse, LemmyError> {
311     let data: &TransferSite = &self;
312     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
313
314     is_admin(&local_user_view)?;
315
316     let read_site = blocking(context.pool(), move |conn| Site::read_simple(conn)).await??;
317
318     // Make sure user is the creator
319     if read_site.creator_id != local_user_view.person.id {
320       return Err(ApiError::err("not_an_admin").into());
321     }
322
323     let new_creator_id = data.person_id;
324     let transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id);
325     if blocking(context.pool(), transfer_site).await?.is_err() {
326       return Err(ApiError::err("couldnt_update_site").into());
327     };
328
329     // Mod tables
330     let form = ModAddForm {
331       mod_person_id: local_user_view.person.id,
332       other_person_id: data.person_id,
333       removed: Some(false),
334     };
335
336     blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
337
338     let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
339
340     let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
341     let creator_index = admins
342       .iter()
343       .position(|r| r.person.id == site_view.creator.id)
344       .context(location_info!())?;
345     let creator_person = admins.remove(creator_index);
346     admins.insert(0, creator_person);
347
348     let banned = blocking(context.pool(), move |conn| PersonViewSafe::banned(conn)).await??;
349     let federated_instances = build_federated_instances(context.pool()).await?;
350
351     let my_user = Some(get_local_user_settings_view_from_jwt(&data.auth, context.pool()).await?);
352
353     Ok(GetSiteResponse {
354       site_view: Some(site_view),
355       admins,
356       banned,
357       online: 0,
358       version: version::VERSION.to_string(),
359       my_user,
360       federated_instances,
361     })
362   }
363 }
364
365 #[async_trait::async_trait(?Send)]
366 impl Perform for GetSiteConfig {
367   type Response = GetSiteConfigResponse;
368
369   async fn perform(
370     &self,
371     context: &Data<LemmyContext>,
372     _websocket_id: Option<ConnectionId>,
373   ) -> Result<GetSiteConfigResponse, LemmyError> {
374     let data: &GetSiteConfig = &self;
375     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
376
377     // Only let admins read this
378     is_admin(&local_user_view)?;
379
380     let config_hjson = Settings::read_config_file()?;
381
382     Ok(GetSiteConfigResponse { config_hjson })
383   }
384 }
385
386 #[async_trait::async_trait(?Send)]
387 impl Perform for SaveSiteConfig {
388   type Response = GetSiteConfigResponse;
389
390   async fn perform(
391     &self,
392     context: &Data<LemmyContext>,
393     _websocket_id: Option<ConnectionId>,
394   ) -> Result<GetSiteConfigResponse, LemmyError> {
395     let data: &SaveSiteConfig = &self;
396     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
397
398     // Only let admins read this
399     is_admin(&local_user_view)?;
400
401     // Make sure docker doesn't have :ro at the end of the volume, so its not a read-only filesystem
402     let config_hjson = Settings::save_config_file(&data.config_hjson)
403       .map_err(|_| ApiError::err("couldnt_update_site"))?;
404
405     Ok(GetSiteConfigResponse { config_hjson })
406   }
407 }