9 use actix_web::web::Data;
11 use lemmy_apub::fetcher::search_by_apub_id;
13 aggregates::site_aggregates::SiteAggregates,
14 diesel_option_overwrite,
16 source::{category::*, moderator::*, site::*},
18 comment_view::CommentQueryBuilder,
19 community::community_view::CommunityQueryBuilder,
21 mod_add_community_view::ModAddCommunityView,
22 mod_add_view::ModAddView,
23 mod_ban_from_community_view::ModBanFromCommunityView,
24 mod_ban_view::ModBanView,
25 mod_lock_post_view::ModLockPostView,
26 mod_remove_comment_view::ModRemoveCommentView,
27 mod_remove_community_view::ModRemoveCommunityView,
28 mod_remove_post_view::ModRemovePostView,
29 mod_sticky_post_view::ModStickyPostView,
31 post_view::PostQueryBuilder,
33 user_view::{UserQueryBuilder, UserViewSafe},
39 use lemmy_structs::{blocking, site::*, user::Register};
43 utils::{check_slurs, check_slurs_opt},
48 use lemmy_websocket::{
49 messages::{GetUsersOnline, SendAllMessage},
53 use log::{debug, info};
54 use std::str::FromStr;
56 #[async_trait::async_trait(?Send)]
57 impl Perform for ListCategories {
58 type Response = ListCategoriesResponse;
62 context: &Data<LemmyContext>,
63 _websocket_id: Option<ConnectionId>,
64 ) -> Result<ListCategoriesResponse, LemmyError> {
65 let _data: &ListCategories = &self;
67 let categories = blocking(context.pool(), move |conn| Category::list_all(conn)).await??;
70 Ok(ListCategoriesResponse { categories })
74 #[async_trait::async_trait(?Send)]
75 impl Perform for GetModlog {
76 type Response = GetModlogResponse;
80 context: &Data<LemmyContext>,
81 _websocket_id: Option<ConnectionId>,
82 ) -> Result<GetModlogResponse, LemmyError> {
83 let data: &GetModlog = &self;
85 let community_id = data.community_id;
86 let mod_user_id = data.mod_user_id;
88 let limit = data.limit;
89 let removed_posts = blocking(context.pool(), move |conn| {
90 ModRemovePostView::list(conn, community_id, mod_user_id, page, limit)
94 let locked_posts = blocking(context.pool(), move |conn| {
95 ModLockPostView::list(conn, community_id, mod_user_id, page, limit)
99 let stickied_posts = blocking(context.pool(), move |conn| {
100 ModStickyPostView::list(conn, community_id, mod_user_id, page, limit)
104 let removed_comments = blocking(context.pool(), move |conn| {
105 ModRemoveCommentView::list(conn, community_id, mod_user_id, page, limit)
109 let banned_from_community = blocking(context.pool(), move |conn| {
110 ModBanFromCommunityView::list(conn, community_id, mod_user_id, page, limit)
114 let added_to_community = blocking(context.pool(), move |conn| {
115 ModAddCommunityView::list(conn, community_id, mod_user_id, page, limit)
119 // These arrays are only for the full modlog, when a community isn't given
120 let (removed_communities, banned, added) = if data.community_id.is_none() {
121 blocking(context.pool(), move |conn| {
123 ModRemoveCommunityView::list(conn, mod_user_id, page, limit)?,
124 ModBanView::list(conn, mod_user_id, page, limit)?,
125 ModAddView::list(conn, mod_user_id, page, limit)?,
126 )) as Result<_, LemmyError>
130 (Vec::new(), Vec::new(), Vec::new())
134 Ok(GetModlogResponse {
140 banned_from_community,
148 #[async_trait::async_trait(?Send)]
149 impl Perform for CreateSite {
150 type Response = SiteResponse;
154 context: &Data<LemmyContext>,
155 _websocket_id: Option<ConnectionId>,
156 ) -> Result<SiteResponse, LemmyError> {
157 let data: &CreateSite = &self;
159 let read_site = move |conn: &'_ _| Site::read(conn, 1);
160 if blocking(context.pool(), read_site).await?.is_ok() {
161 return Err(APIError::err("site_already_exists").into());
164 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
166 check_slurs(&data.name)?;
167 check_slurs_opt(&data.description)?;
169 // Make sure user is an admin
170 is_admin(context.pool(), user.id).await?;
172 let site_form = SiteForm {
173 name: data.name.to_owned(),
174 description: data.description.to_owned(),
175 icon: Some(data.icon.to_owned()),
176 banner: Some(data.banner.to_owned()),
178 enable_downvotes: data.enable_downvotes,
179 open_registration: data.open_registration,
180 enable_nsfw: data.enable_nsfw,
184 let create_site = move |conn: &'_ _| Site::create(conn, &site_form);
185 if blocking(context.pool(), create_site).await?.is_err() {
186 return Err(APIError::err("site_already_exists").into());
189 let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
191 Ok(SiteResponse { site: site_view })
195 #[async_trait::async_trait(?Send)]
196 impl Perform for EditSite {
197 type Response = SiteResponse;
200 context: &Data<LemmyContext>,
201 websocket_id: Option<ConnectionId>,
202 ) -> Result<SiteResponse, LemmyError> {
203 let data: &EditSite = &self;
204 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
206 check_slurs(&data.name)?;
207 check_slurs_opt(&data.description)?;
209 // Make sure user is an admin
210 is_admin(context.pool(), user.id).await?;
212 let found_site = blocking(context.pool(), move |conn| Site::read(conn, 1)).await??;
214 let icon = diesel_option_overwrite(&data.icon);
215 let banner = diesel_option_overwrite(&data.banner);
217 let site_form = SiteForm {
218 name: data.name.to_owned(),
219 description: data.description.to_owned(),
222 creator_id: found_site.creator_id,
223 updated: Some(naive_now()),
224 enable_downvotes: data.enable_downvotes,
225 open_registration: data.open_registration,
226 enable_nsfw: data.enable_nsfw,
229 let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form);
230 if blocking(context.pool(), update_site).await?.is_err() {
231 return Err(APIError::err("couldnt_update_site").into());
234 let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
236 let res = SiteResponse { site: site_view };
238 context.chat_server().do_send(SendAllMessage {
239 op: UserOperation::EditSite,
240 response: res.clone(),
248 #[async_trait::async_trait(?Send)]
249 impl Perform for GetSite {
250 type Response = GetSiteResponse;
254 context: &Data<LemmyContext>,
255 websocket_id: Option<ConnectionId>,
256 ) -> Result<GetSiteResponse, LemmyError> {
257 let data: &GetSite = &self;
259 // TODO refactor this a little
260 let res = blocking(context.pool(), move |conn| Site::read(conn, 1)).await?;
261 let site_view = if res.is_ok() {
262 Some(blocking(context.pool(), move |conn| SiteView::read(conn)).await??)
263 } else if let Some(setup) = Settings::get().setup.as_ref() {
264 let register = Register {
265 username: setup.admin_username.to_owned(),
266 email: setup.admin_email.to_owned(),
267 password: setup.admin_password.to_owned(),
268 password_verify: setup.admin_password.to_owned(),
272 captcha_answer: None,
274 let login_response = register.perform(context, websocket_id).await?;
275 info!("Admin {} created", setup.admin_username);
277 let create_site = CreateSite {
278 name: setup.site_name.to_owned(),
282 enable_downvotes: true,
283 open_registration: true,
285 auth: login_response.jwt,
287 create_site.perform(context, websocket_id).await?;
288 info!("Site {} created", setup.site_name);
289 Some(blocking(context.pool(), move |conn| SiteView::read(conn)).await??)
294 let mut admins = blocking(context.pool(), move |conn| UserViewSafe::admins(conn)).await??;
296 // Make sure the site creator is the top admin
297 if let Some(site_view) = site_view.to_owned() {
298 let site_creator_id = site_view.creator.id;
299 // TODO investigate why this is sometimes coming back null
300 // Maybe user_.admin isn't being set to true?
301 if let Some(creator_index) = admins.iter().position(|r| r.user.id == site_creator_id) {
302 let creator_user = admins.remove(creator_index);
303 admins.insert(0, creator_user);
307 let banned = blocking(context.pool(), move |conn| UserViewSafe::banned(conn)).await??;
311 .send(GetUsersOnline)
315 let my_user = get_user_from_jwt_opt(&data.auth, context.pool())
318 u.password_encrypted = "".to_string();
319 u.private_key = None;
324 let counts = blocking(context.pool(), move |conn| SiteAggregates::read(conn)).await??;
331 version: version::VERSION.to_string(),
333 federated_instances: linked_instances(context.pool()).await?,
339 #[async_trait::async_trait(?Send)]
340 impl Perform for Search {
341 type Response = SearchResponse;
345 context: &Data<LemmyContext>,
346 _websocket_id: Option<ConnectionId>,
347 ) -> Result<SearchResponse, LemmyError> {
348 let data: &Search = &self;
350 match search_by_apub_id(&data.q, context).await {
351 Ok(r) => return Ok(r),
352 Err(e) => debug!("Failed to resolve search query as activitypub ID: {}", e),
355 let user = get_user_from_jwt_opt(&data.auth, context.pool()).await?;
356 let user_id = user.map(|u| u.id);
358 let type_ = SearchType::from_str(&data.type_)?;
360 let mut posts = Vec::new();
361 let mut comments = Vec::new();
362 let mut communities = Vec::new();
363 let mut users = Vec::new();
365 // TODO no clean / non-nsfw searching rn
367 let q = data.q.to_owned();
368 let page = data.page;
369 let limit = data.limit;
370 let sort = SortType::from_str(&data.sort)?;
371 let community_id = data.community_id;
372 let community_name = data.community_name.to_owned();
374 SearchType::Posts => {
375 posts = blocking(context.pool(), move |conn| {
376 PostQueryBuilder::create(conn)
379 .community_id(community_id)
380 .community_name(community_name)
389 SearchType::Comments => {
390 comments = blocking(context.pool(), move |conn| {
391 CommentQueryBuilder::create(&conn)
401 SearchType::Communities => {
402 communities = blocking(context.pool(), move |conn| {
403 CommunityQueryBuilder::create(conn)
412 SearchType::Users => {
413 users = blocking(context.pool(), move |conn| {
414 UserQueryBuilder::create(conn)
424 posts = blocking(context.pool(), move |conn| {
425 PostQueryBuilder::create(conn)
428 .community_id(community_id)
429 .community_name(community_name)
438 let q = data.q.to_owned();
439 let sort = SortType::from_str(&data.sort)?;
441 comments = blocking(context.pool(), move |conn| {
442 CommentQueryBuilder::create(conn)
452 let q = data.q.to_owned();
453 let sort = SortType::from_str(&data.sort)?;
455 communities = blocking(context.pool(), move |conn| {
456 CommunityQueryBuilder::create(conn)
465 let q = data.q.to_owned();
466 let sort = SortType::from_str(&data.sort)?;
468 users = blocking(context.pool(), move |conn| {
469 UserQueryBuilder::create(conn)
479 posts = blocking(context.pool(), move |conn| {
480 PostQueryBuilder::create(conn)
483 .community_id(community_id)
484 .community_name(community_name)
496 type_: data.type_.to_owned(),
505 #[async_trait::async_trait(?Send)]
506 impl Perform for TransferSite {
507 type Response = GetSiteResponse;
511 context: &Data<LemmyContext>,
512 _websocket_id: Option<ConnectionId>,
513 ) -> Result<GetSiteResponse, LemmyError> {
514 let data: &TransferSite = &self;
515 let mut user = get_user_from_jwt(&data.auth, context.pool()).await?;
517 is_admin(context.pool(), user.id).await?;
519 // TODO add a User_::read_safe() for this.
520 user.password_encrypted = "".to_string();
521 user.private_key = None;
522 user.public_key = None;
524 let read_site = blocking(context.pool(), move |conn| Site::read(conn, 1)).await??;
526 // Make sure user is the creator
527 if read_site.creator_id != user.id {
528 return Err(APIError::err("not_an_admin").into());
531 let new_creator_id = data.user_id;
532 let transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id);
533 if blocking(context.pool(), transfer_site).await?.is_err() {
534 return Err(APIError::err("couldnt_update_site").into());
538 let form = ModAddForm {
539 mod_user_id: user.id,
540 other_user_id: data.user_id,
541 removed: Some(false),
544 blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
546 let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
548 let mut admins = blocking(context.pool(), move |conn| UserViewSafe::admins(conn)).await??;
549 let creator_index = admins
551 .position(|r| r.user.id == site_view.creator.id)
552 .context(location_info!())?;
553 let creator_user = admins.remove(creator_index);
554 admins.insert(0, creator_user);
556 let banned = blocking(context.pool(), move |conn| UserViewSafe::banned(conn)).await??;
558 let counts = blocking(context.pool(), move |conn| SiteAggregates::read(conn)).await??;
561 site: Some(site_view),
565 version: version::VERSION.to_string(),
567 federated_instances: linked_instances(context.pool()).await?,
573 #[async_trait::async_trait(?Send)]
574 impl Perform for GetSiteConfig {
575 type Response = GetSiteConfigResponse;
579 context: &Data<LemmyContext>,
580 _websocket_id: Option<ConnectionId>,
581 ) -> Result<GetSiteConfigResponse, LemmyError> {
582 let data: &GetSiteConfig = &self;
583 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
585 // Only let admins read this
586 is_admin(context.pool(), user.id).await?;
588 let config_hjson = Settings::read_config_file()?;
590 Ok(GetSiteConfigResponse { config_hjson })
594 #[async_trait::async_trait(?Send)]
595 impl Perform for SaveSiteConfig {
596 type Response = GetSiteConfigResponse;
600 context: &Data<LemmyContext>,
601 _websocket_id: Option<ConnectionId>,
602 ) -> Result<GetSiteConfigResponse, LemmyError> {
603 let data: &SaveSiteConfig = &self;
604 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
606 // Only let admins read this
607 let admins = blocking(context.pool(), move |conn| UserViewSafe::admins(conn)).await??;
608 let admin_ids: Vec<i32> = admins.into_iter().map(|m| m.user.id).collect();
610 if !admin_ids.contains(&user.id) {
611 return Err(APIError::err("not_an_admin").into());
614 // Make sure docker doesn't have :ro at the end of the volume, so its not a read-only filesystem
615 let config_hjson = match Settings::save_config_file(&data.config_hjson) {
616 Ok(config_hjson) => config_hjson,
617 Err(_e) => return Err(APIError::err("couldnt_update_site").into()),
620 Ok(GetSiteConfigResponse { config_hjson })