]> Untitled Git - lemmy.git/blob - crates/api/src/site.rs
Add creator id to search. Fixes #765
[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     let community_name_2 = data.community_name.to_owned();
163     let creator_id = data.creator_id;
164     match type_ {
165       SearchType::Posts => {
166         posts = blocking(context.pool(), move |conn| {
167           PostQueryBuilder::create(conn)
168             .sort(&sort)
169             .show_nsfw(show_nsfw)
170             .show_bot_accounts(show_bot_accounts)
171             .community_id(community_id)
172             .community_name(community_name)
173             .creator_id(creator_id)
174             .my_person_id(person_id)
175             .search_term(q)
176             .page(page)
177             .limit(limit)
178             .list()
179         })
180         .await??;
181       }
182       SearchType::Comments => {
183         comments = blocking(context.pool(), move |conn| {
184           CommentQueryBuilder::create(&conn)
185             .sort(&sort)
186             .search_term(q)
187             .show_bot_accounts(show_bot_accounts)
188             .community_id(community_id)
189             .community_name(community_name)
190             .creator_id(creator_id)
191             .my_person_id(person_id)
192             .page(page)
193             .limit(limit)
194             .list()
195         })
196         .await??;
197       }
198       SearchType::Communities => {
199         communities = blocking(context.pool(), move |conn| {
200           CommunityQueryBuilder::create(conn)
201             .sort(&sort)
202             .search_term(q)
203             .my_person_id(person_id)
204             .page(page)
205             .limit(limit)
206             .list()
207         })
208         .await??;
209       }
210       SearchType::Users => {
211         users = blocking(context.pool(), move |conn| {
212           PersonQueryBuilder::create(conn)
213             .sort(&sort)
214             .search_term(q)
215             .page(page)
216             .limit(limit)
217             .list()
218         })
219         .await??;
220       }
221       SearchType::All => {
222         posts = blocking(context.pool(), move |conn| {
223           PostQueryBuilder::create(conn)
224             .sort(&sort)
225             .show_nsfw(show_nsfw)
226             .show_bot_accounts(show_bot_accounts)
227             .community_id(community_id)
228             .community_name(community_name)
229             .creator_id(creator_id)
230             .my_person_id(person_id)
231             .search_term(q)
232             .page(page)
233             .limit(limit)
234             .list()
235         })
236         .await??;
237
238         let q = data.q.to_owned();
239         let sort = SortType::from_str(&data.sort)?;
240
241         comments = blocking(context.pool(), move |conn| {
242           CommentQueryBuilder::create(conn)
243             .sort(&sort)
244             .search_term(q)
245             .show_bot_accounts(show_bot_accounts)
246             .community_id(community_id)
247             .community_name(community_name_2)
248             .creator_id(creator_id)
249             .my_person_id(person_id)
250             .page(page)
251             .limit(limit)
252             .list()
253         })
254         .await??;
255
256         let q = data.q.to_owned();
257         let sort = SortType::from_str(&data.sort)?;
258
259         communities = blocking(context.pool(), move |conn| {
260           CommunityQueryBuilder::create(conn)
261             .sort(&sort)
262             .search_term(q)
263             .my_person_id(person_id)
264             .page(page)
265             .limit(limit)
266             .list()
267         })
268         .await??;
269
270         let q = data.q.to_owned();
271         let sort = SortType::from_str(&data.sort)?;
272
273         users = blocking(context.pool(), move |conn| {
274           PersonQueryBuilder::create(conn)
275             .sort(&sort)
276             .search_term(q)
277             .page(page)
278             .limit(limit)
279             .list()
280         })
281         .await??;
282       }
283       SearchType::Url => {
284         posts = blocking(context.pool(), move |conn| {
285           PostQueryBuilder::create(conn)
286             .sort(&sort)
287             .show_nsfw(show_nsfw)
288             .show_bot_accounts(show_bot_accounts)
289             .my_person_id(person_id)
290             .community_id(community_id)
291             .community_name(community_name)
292             .creator_id(creator_id)
293             .url_search(q)
294             .page(page)
295             .limit(limit)
296             .list()
297         })
298         .await??;
299       }
300     };
301
302     // Return the jwt
303     Ok(SearchResponse {
304       type_: data.type_.to_owned(),
305       comments,
306       posts,
307       communities,
308       users,
309     })
310   }
311 }
312
313 #[async_trait::async_trait(?Send)]
314 impl Perform for TransferSite {
315   type Response = GetSiteResponse;
316
317   async fn perform(
318     &self,
319     context: &Data<LemmyContext>,
320     _websocket_id: Option<ConnectionId>,
321   ) -> Result<GetSiteResponse, LemmyError> {
322     let data: &TransferSite = &self;
323     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
324
325     is_admin(&local_user_view)?;
326
327     let read_site = blocking(context.pool(), move |conn| Site::read_simple(conn)).await??;
328
329     // Make sure user is the creator
330     if read_site.creator_id != local_user_view.person.id {
331       return Err(ApiError::err("not_an_admin").into());
332     }
333
334     let new_creator_id = data.person_id;
335     let transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id);
336     if blocking(context.pool(), transfer_site).await?.is_err() {
337       return Err(ApiError::err("couldnt_update_site").into());
338     };
339
340     // Mod tables
341     let form = ModAddForm {
342       mod_person_id: local_user_view.person.id,
343       other_person_id: data.person_id,
344       removed: Some(false),
345     };
346
347     blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
348
349     let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
350
351     let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
352     let creator_index = admins
353       .iter()
354       .position(|r| r.person.id == site_view.creator.id)
355       .context(location_info!())?;
356     let creator_person = admins.remove(creator_index);
357     admins.insert(0, creator_person);
358
359     let banned = blocking(context.pool(), move |conn| PersonViewSafe::banned(conn)).await??;
360     let federated_instances = build_federated_instances(context.pool()).await?;
361
362     let my_user = Some(get_local_user_settings_view_from_jwt(&data.auth, context.pool()).await?);
363
364     Ok(GetSiteResponse {
365       site_view: Some(site_view),
366       admins,
367       banned,
368       online: 0,
369       version: version::VERSION.to_string(),
370       my_user,
371       federated_instances,
372     })
373   }
374 }
375
376 #[async_trait::async_trait(?Send)]
377 impl Perform for GetSiteConfig {
378   type Response = GetSiteConfigResponse;
379
380   async fn perform(
381     &self,
382     context: &Data<LemmyContext>,
383     _websocket_id: Option<ConnectionId>,
384   ) -> Result<GetSiteConfigResponse, LemmyError> {
385     let data: &GetSiteConfig = &self;
386     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
387
388     // Only let admins read this
389     is_admin(&local_user_view)?;
390
391     let config_hjson = Settings::read_config_file()?;
392
393     Ok(GetSiteConfigResponse { config_hjson })
394   }
395 }
396
397 #[async_trait::async_trait(?Send)]
398 impl Perform for SaveSiteConfig {
399   type Response = GetSiteConfigResponse;
400
401   async fn perform(
402     &self,
403     context: &Data<LemmyContext>,
404     _websocket_id: Option<ConnectionId>,
405   ) -> Result<GetSiteConfigResponse, LemmyError> {
406     let data: &SaveSiteConfig = &self;
407     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
408
409     // Only let admins read this
410     is_admin(&local_user_view)?;
411
412     // Make sure docker doesn't have :ro at the end of the volume, so its not a read-only filesystem
413     let config_hjson = Settings::save_config_file(&data.config_hjson)
414       .map_err(|_| ApiError::err("couldnt_update_site"))?;
415
416     Ok(GetSiteConfigResponse { config_hjson })
417   }
418 }