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