9 use actix_web::web::Data;
11 use lemmy_apub::fetcher::search_by_apub_id;
13 diesel_option_overwrite,
15 source::{category::*, moderator::*, site::*},
17 comment_view::CommentQueryBuilder,
18 community::community_view::CommunityQueryBuilder,
20 mod_add_community_view::ModAddCommunityView,
21 mod_add_view::ModAddView,
22 mod_ban_from_community_view::ModBanFromCommunityView,
23 mod_ban_view::ModBanView,
24 mod_lock_post_view::ModLockPostView,
25 mod_remove_comment_view::ModRemoveCommentView,
26 mod_remove_community_view::ModRemoveCommunityView,
27 mod_remove_post_view::ModRemovePostView,
28 mod_sticky_post_view::ModStickyPostView,
30 post_view::PostQueryBuilder,
32 user_view::{UserQueryBuilder, UserViewSafe},
38 use lemmy_structs::{blocking, site::*, user::Register};
42 utils::{check_slurs, check_slurs_opt},
47 use lemmy_websocket::{
48 messages::{GetUsersOnline, SendAllMessage},
52 use log::{debug, info};
53 use std::str::FromStr;
55 #[async_trait::async_trait(?Send)]
56 impl Perform for ListCategories {
57 type Response = ListCategoriesResponse;
61 context: &Data<LemmyContext>,
62 _websocket_id: Option<ConnectionId>,
63 ) -> Result<ListCategoriesResponse, LemmyError> {
64 let _data: &ListCategories = &self;
66 let categories = blocking(context.pool(), move |conn| Category::list_all(conn)).await??;
69 Ok(ListCategoriesResponse { categories })
73 #[async_trait::async_trait(?Send)]
74 impl Perform for GetModlog {
75 type Response = GetModlogResponse;
79 context: &Data<LemmyContext>,
80 _websocket_id: Option<ConnectionId>,
81 ) -> Result<GetModlogResponse, LemmyError> {
82 let data: &GetModlog = &self;
84 let community_id = data.community_id;
85 let mod_user_id = data.mod_user_id;
87 let limit = data.limit;
88 let removed_posts = blocking(context.pool(), move |conn| {
89 ModRemovePostView::list(conn, community_id, mod_user_id, page, limit)
93 let locked_posts = blocking(context.pool(), move |conn| {
94 ModLockPostView::list(conn, community_id, mod_user_id, page, limit)
98 let stickied_posts = blocking(context.pool(), move |conn| {
99 ModStickyPostView::list(conn, community_id, mod_user_id, page, limit)
103 let removed_comments = blocking(context.pool(), move |conn| {
104 ModRemoveCommentView::list(conn, community_id, mod_user_id, page, limit)
108 let banned_from_community = blocking(context.pool(), move |conn| {
109 ModBanFromCommunityView::list(conn, community_id, mod_user_id, page, limit)
113 let added_to_community = blocking(context.pool(), move |conn| {
114 ModAddCommunityView::list(conn, community_id, mod_user_id, page, limit)
118 // These arrays are only for the full modlog, when a community isn't given
119 let (removed_communities, banned, added) = if data.community_id.is_none() {
120 blocking(context.pool(), move |conn| {
122 ModRemoveCommunityView::list(conn, mod_user_id, page, limit)?,
123 ModBanView::list(conn, mod_user_id, page, limit)?,
124 ModAddView::list(conn, mod_user_id, page, limit)?,
125 )) as Result<_, LemmyError>
129 (Vec::new(), Vec::new(), Vec::new())
133 Ok(GetModlogResponse {
139 banned_from_community,
147 #[async_trait::async_trait(?Send)]
148 impl Perform for CreateSite {
149 type Response = SiteResponse;
153 context: &Data<LemmyContext>,
154 _websocket_id: Option<ConnectionId>,
155 ) -> Result<SiteResponse, LemmyError> {
156 let data: &CreateSite = &self;
158 let read_site = move |conn: &'_ _| Site::read_simple(conn);
159 if blocking(context.pool(), read_site).await?.is_ok() {
160 return Err(APIError::err("site_already_exists").into());
163 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
165 check_slurs(&data.name)?;
166 check_slurs_opt(&data.description)?;
168 // Make sure user is an admin
169 is_admin(context.pool(), user.id).await?;
171 let site_form = SiteForm {
172 name: data.name.to_owned(),
173 description: data.description.to_owned(),
174 icon: Some(data.icon.to_owned()),
175 banner: Some(data.banner.to_owned()),
177 enable_downvotes: data.enable_downvotes,
178 open_registration: data.open_registration,
179 enable_nsfw: data.enable_nsfw,
183 let create_site = move |conn: &'_ _| Site::create(conn, &site_form);
184 if blocking(context.pool(), create_site).await?.is_err() {
185 return Err(APIError::err("site_already_exists").into());
188 let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
190 Ok(SiteResponse { site_view })
194 #[async_trait::async_trait(?Send)]
195 impl Perform for EditSite {
196 type Response = SiteResponse;
199 context: &Data<LemmyContext>,
200 websocket_id: Option<ConnectionId>,
201 ) -> Result<SiteResponse, LemmyError> {
202 let data: &EditSite = &self;
203 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
205 check_slurs(&data.name)?;
206 check_slurs_opt(&data.description)?;
208 // Make sure user is an admin
209 is_admin(context.pool(), user.id).await?;
211 let found_site = blocking(context.pool(), move |conn| Site::read_simple(conn)).await??;
213 let icon = diesel_option_overwrite(&data.icon);
214 let banner = diesel_option_overwrite(&data.banner);
216 let site_form = SiteForm {
217 name: data.name.to_owned(),
218 description: data.description.to_owned(),
221 creator_id: found_site.creator_id,
222 updated: Some(naive_now()),
223 enable_downvotes: data.enable_downvotes,
224 open_registration: data.open_registration,
225 enable_nsfw: data.enable_nsfw,
228 let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form);
229 if blocking(context.pool(), update_site).await?.is_err() {
230 return Err(APIError::err("couldnt_update_site").into());
233 let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
235 let res = SiteResponse { site_view };
237 context.chat_server().do_send(SendAllMessage {
238 op: UserOperation::EditSite,
239 response: res.clone(),
247 #[async_trait::async_trait(?Send)]
248 impl Perform for GetSite {
249 type Response = GetSiteResponse;
253 context: &Data<LemmyContext>,
254 websocket_id: Option<ConnectionId>,
255 ) -> Result<GetSiteResponse, LemmyError> {
256 let data: &GetSite = &self;
258 let site_view = match blocking(context.pool(), move |conn| SiteView::read(conn)).await? {
259 Ok(site_view) => Some(site_view),
260 // If the site isn't created yet, check the setup
262 if let Some(setup) = Settings::get().setup.as_ref() {
263 let register = Register {
264 username: setup.admin_username.to_owned(),
265 email: setup.admin_email.to_owned(),
266 password: setup.admin_password.to_owned(),
267 password_verify: setup.admin_password.to_owned(),
271 captcha_answer: None,
273 let login_response = register.perform(context, websocket_id).await?;
274 info!("Admin {} created", setup.admin_username);
276 let create_site = CreateSite {
277 name: setup.site_name.to_owned(),
281 enable_downvotes: true,
282 open_registration: true,
284 auth: login_response.jwt,
286 create_site.perform(context, websocket_id).await?;
287 info!("Site {} created", setup.site_name);
288 Some(blocking(context.pool(), move |conn| SiteView::read(conn)).await??)
295 let mut admins = blocking(context.pool(), move |conn| UserViewSafe::admins(conn)).await??;
297 // Make sure the site creator is the top admin
298 if let Some(site_view) = site_view.to_owned() {
299 let site_creator_id = site_view.creator.id;
300 // TODO investigate why this is sometimes coming back null
301 // Maybe user_.admin isn't being set to true?
302 if let Some(creator_index) = admins.iter().position(|r| r.user.id == site_creator_id) {
303 let creator_user = admins.remove(creator_index);
304 admins.insert(0, creator_user);
308 let banned = blocking(context.pool(), move |conn| UserViewSafe::banned(conn)).await??;
312 .send(GetUsersOnline)
316 let my_user = get_user_from_jwt_opt(&data.auth, context.pool())
319 u.password_encrypted = "".to_string();
320 u.private_key = None;
330 version: version::VERSION.to_string(),
332 federated_instances: linked_instances(context.pool()).await?,
337 #[async_trait::async_trait(?Send)]
338 impl Perform for Search {
339 type Response = SearchResponse;
343 context: &Data<LemmyContext>,
344 _websocket_id: Option<ConnectionId>,
345 ) -> Result<SearchResponse, LemmyError> {
346 let data: &Search = &self;
348 match search_by_apub_id(&data.q, context).await {
349 Ok(r) => return Ok(r),
350 Err(e) => debug!("Failed to resolve search query as activitypub ID: {}", e),
353 let user = get_user_from_jwt_opt(&data.auth, context.pool()).await?;
354 let user_id = user.map(|u| u.id);
356 let type_ = SearchType::from_str(&data.type_)?;
358 let mut posts = Vec::new();
359 let mut comments = Vec::new();
360 let mut communities = Vec::new();
361 let mut users = Vec::new();
363 // TODO no clean / non-nsfw searching rn
365 let q = data.q.to_owned();
366 let page = data.page;
367 let limit = data.limit;
368 let sort = SortType::from_str(&data.sort)?;
369 let community_id = data.community_id;
370 let community_name = data.community_name.to_owned();
372 SearchType::Posts => {
373 posts = blocking(context.pool(), move |conn| {
374 PostQueryBuilder::create(conn)
377 .community_id(community_id)
378 .community_name(community_name)
387 SearchType::Comments => {
388 comments = blocking(context.pool(), move |conn| {
389 CommentQueryBuilder::create(&conn)
399 SearchType::Communities => {
400 communities = blocking(context.pool(), move |conn| {
401 CommunityQueryBuilder::create(conn)
410 SearchType::Users => {
411 users = blocking(context.pool(), move |conn| {
412 UserQueryBuilder::create(conn)
422 posts = blocking(context.pool(), move |conn| {
423 PostQueryBuilder::create(conn)
426 .community_id(community_id)
427 .community_name(community_name)
436 let q = data.q.to_owned();
437 let sort = SortType::from_str(&data.sort)?;
439 comments = blocking(context.pool(), move |conn| {
440 CommentQueryBuilder::create(conn)
450 let q = data.q.to_owned();
451 let sort = SortType::from_str(&data.sort)?;
453 communities = blocking(context.pool(), move |conn| {
454 CommunityQueryBuilder::create(conn)
463 let q = data.q.to_owned();
464 let sort = SortType::from_str(&data.sort)?;
466 users = blocking(context.pool(), move |conn| {
467 UserQueryBuilder::create(conn)
477 posts = blocking(context.pool(), move |conn| {
478 PostQueryBuilder::create(conn)
481 .community_id(community_id)
482 .community_name(community_name)
494 type_: data.type_.to_owned(),
503 #[async_trait::async_trait(?Send)]
504 impl Perform for TransferSite {
505 type Response = GetSiteResponse;
509 context: &Data<LemmyContext>,
510 _websocket_id: Option<ConnectionId>,
511 ) -> Result<GetSiteResponse, LemmyError> {
512 let data: &TransferSite = &self;
513 let mut user = get_user_from_jwt(&data.auth, context.pool()).await?;
515 is_admin(context.pool(), user.id).await?;
517 // TODO add a User_::read_safe() for this.
518 user.password_encrypted = "".to_string();
519 user.private_key = None;
520 user.public_key = None;
522 let read_site = blocking(context.pool(), move |conn| Site::read_simple(conn)).await??;
524 // Make sure user is the creator
525 if read_site.creator_id != user.id {
526 return Err(APIError::err("not_an_admin").into());
529 let new_creator_id = data.user_id;
530 let transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id);
531 if blocking(context.pool(), transfer_site).await?.is_err() {
532 return Err(APIError::err("couldnt_update_site").into());
536 let form = ModAddForm {
537 mod_user_id: user.id,
538 other_user_id: data.user_id,
539 removed: Some(false),
542 blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
544 let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
546 let mut admins = blocking(context.pool(), move |conn| UserViewSafe::admins(conn)).await??;
547 let creator_index = admins
549 .position(|r| r.user.id == site_view.creator.id)
550 .context(location_info!())?;
551 let creator_user = admins.remove(creator_index);
552 admins.insert(0, creator_user);
554 let banned = blocking(context.pool(), move |conn| UserViewSafe::banned(conn)).await??;
557 site_view: Some(site_view),
561 version: version::VERSION.to_string(),
563 federated_instances: linked_instances(context.pool()).await?,
568 #[async_trait::async_trait(?Send)]
569 impl Perform for GetSiteConfig {
570 type Response = GetSiteConfigResponse;
574 context: &Data<LemmyContext>,
575 _websocket_id: Option<ConnectionId>,
576 ) -> Result<GetSiteConfigResponse, LemmyError> {
577 let data: &GetSiteConfig = &self;
578 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
580 // Only let admins read this
581 is_admin(context.pool(), user.id).await?;
583 let config_hjson = Settings::read_config_file()?;
585 Ok(GetSiteConfigResponse { config_hjson })
589 #[async_trait::async_trait(?Send)]
590 impl Perform for SaveSiteConfig {
591 type Response = GetSiteConfigResponse;
595 context: &Data<LemmyContext>,
596 _websocket_id: Option<ConnectionId>,
597 ) -> Result<GetSiteConfigResponse, LemmyError> {
598 let data: &SaveSiteConfig = &self;
599 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
601 // Only let admins read this
602 let user_id = user.id;
603 is_admin(context.pool(), user_id).await?;
605 // Make sure docker doesn't have :ro at the end of the volume, so its not a read-only filesystem
606 let config_hjson = match Settings::save_config_file(&data.config_hjson) {
607 Ok(config_hjson) => config_hjson,
608 Err(_e) => return Err(APIError::err("couldnt_update_site").into()),
611 Ok(GetSiteConfigResponse { config_hjson })