1 use super::user::Register;
13 apub::fetcher::search_by_apub_id,
16 websocket::{server::SendAllMessage, UserOperation, WebsocketInfo},
36 use lemmy_utils::settings::Settings;
37 use log::{debug, info};
38 use serde::{Deserialize, Serialize};
39 use std::str::FromStr;
41 #[derive(Serialize, Deserialize)]
42 pub struct ListCategories {}
44 #[derive(Serialize, Deserialize)]
45 pub struct ListCategoriesResponse {
46 categories: Vec<Category>,
49 #[derive(Serialize, Deserialize, Debug)]
53 community_id: Option<i32>,
60 #[derive(Serialize, Deserialize, Debug)]
61 pub struct SearchResponse {
63 pub comments: Vec<CommentView>,
64 pub posts: Vec<PostView>,
65 pub communities: Vec<CommunityView>,
66 pub users: Vec<UserView>,
69 #[derive(Serialize, Deserialize)]
70 pub struct GetModlog {
71 mod_user_id: Option<i32>,
72 community_id: Option<i32>,
77 #[derive(Serialize, Deserialize)]
78 pub struct GetModlogResponse {
79 removed_posts: Vec<ModRemovePostView>,
80 locked_posts: Vec<ModLockPostView>,
81 stickied_posts: Vec<ModStickyPostView>,
82 removed_comments: Vec<ModRemoveCommentView>,
83 removed_communities: Vec<ModRemoveCommunityView>,
84 banned_from_community: Vec<ModBanFromCommunityView>,
85 banned: Vec<ModBanView>,
86 added_to_community: Vec<ModAddCommunityView>,
87 added: Vec<ModAddView>,
90 #[derive(Serialize, Deserialize)]
91 pub struct CreateSite {
93 pub description: Option<String>,
94 pub enable_downvotes: bool,
95 pub open_registration: bool,
96 pub enable_nsfw: bool,
100 #[derive(Serialize, Deserialize)]
101 pub struct EditSite {
103 description: Option<String>,
104 enable_downvotes: bool,
105 open_registration: bool,
110 #[derive(Serialize, Deserialize)]
112 auth: Option<String>,
115 #[derive(Serialize, Deserialize, Clone)]
116 pub struct SiteResponse {
120 #[derive(Serialize, Deserialize)]
121 pub struct GetSiteResponse {
122 site: Option<SiteView>,
123 admins: Vec<UserView>,
124 banned: Vec<UserView>,
127 my_user: Option<User_>,
130 #[derive(Serialize, Deserialize)]
131 pub struct TransferSite {
136 #[derive(Serialize, Deserialize)]
137 pub struct GetSiteConfig {
141 #[derive(Serialize, Deserialize)]
142 pub struct GetSiteConfigResponse {
143 config_hjson: String,
146 #[derive(Serialize, Deserialize)]
147 pub struct SaveSiteConfig {
148 config_hjson: String,
152 #[async_trait::async_trait(?Send)]
153 impl Perform for Oper<ListCategories> {
154 type Response = ListCategoriesResponse;
159 _websocket_info: Option<WebsocketInfo>,
160 ) -> Result<ListCategoriesResponse, LemmyError> {
161 let _data: &ListCategories = &self.data;
163 let categories = blocking(pool, move |conn| Category::list_all(conn)).await??;
166 Ok(ListCategoriesResponse { categories })
170 #[async_trait::async_trait(?Send)]
171 impl Perform for Oper<GetModlog> {
172 type Response = GetModlogResponse;
177 _websocket_info: Option<WebsocketInfo>,
178 ) -> Result<GetModlogResponse, LemmyError> {
179 let data: &GetModlog = &self.data;
181 let community_id = data.community_id;
182 let mod_user_id = data.mod_user_id;
183 let page = data.page;
184 let limit = data.limit;
185 let removed_posts = blocking(pool, move |conn| {
186 ModRemovePostView::list(conn, community_id, mod_user_id, page, limit)
190 let locked_posts = blocking(pool, move |conn| {
191 ModLockPostView::list(conn, community_id, mod_user_id, page, limit)
195 let stickied_posts = blocking(pool, move |conn| {
196 ModStickyPostView::list(conn, community_id, mod_user_id, page, limit)
200 let removed_comments = blocking(pool, move |conn| {
201 ModRemoveCommentView::list(conn, community_id, mod_user_id, page, limit)
205 let banned_from_community = blocking(pool, move |conn| {
206 ModBanFromCommunityView::list(conn, community_id, mod_user_id, page, limit)
210 let added_to_community = blocking(pool, move |conn| {
211 ModAddCommunityView::list(conn, community_id, mod_user_id, page, limit)
215 // These arrays are only for the full modlog, when a community isn't given
216 let (removed_communities, banned, added) = if data.community_id.is_none() {
217 blocking(pool, move |conn| {
219 ModRemoveCommunityView::list(conn, mod_user_id, page, limit)?,
220 ModBanView::list(conn, mod_user_id, page, limit)?,
221 ModAddView::list(conn, mod_user_id, page, limit)?,
222 )) as Result<_, LemmyError>
226 (Vec::new(), Vec::new(), Vec::new())
230 Ok(GetModlogResponse {
236 banned_from_community,
244 #[async_trait::async_trait(?Send)]
245 impl Perform for Oper<CreateSite> {
246 type Response = SiteResponse;
251 _websocket_info: Option<WebsocketInfo>,
252 ) -> Result<SiteResponse, LemmyError> {
253 let data: &CreateSite = &self.data;
255 let user = get_user_from_jwt(&data.auth, pool).await?;
257 check_slurs(&data.name)?;
258 check_slurs_opt(&data.description)?;
260 // Make sure user is an admin
261 is_admin(pool, user.id).await?;
263 let site_form = SiteForm {
264 name: data.name.to_owned(),
265 description: data.description.to_owned(),
267 enable_downvotes: data.enable_downvotes,
268 open_registration: data.open_registration,
269 enable_nsfw: data.enable_nsfw,
273 let create_site = move |conn: &'_ _| Site::create(conn, &site_form);
274 if blocking(pool, create_site).await?.is_err() {
275 return Err(APIError::err("site_already_exists").into());
278 let site_view = blocking(pool, move |conn| SiteView::read(conn)).await??;
280 Ok(SiteResponse { site: site_view })
284 #[async_trait::async_trait(?Send)]
285 impl Perform for Oper<EditSite> {
286 type Response = SiteResponse;
290 websocket_info: Option<WebsocketInfo>,
291 ) -> Result<SiteResponse, LemmyError> {
292 let data: &EditSite = &self.data;
293 let user = get_user_from_jwt(&data.auth, pool).await?;
295 check_slurs(&data.name)?;
296 check_slurs_opt(&data.description)?;
298 // Make sure user is an admin
299 is_admin(pool, user.id).await?;
301 let found_site = blocking(pool, move |conn| Site::read(conn, 1)).await??;
303 let site_form = SiteForm {
304 name: data.name.to_owned(),
305 description: data.description.to_owned(),
306 creator_id: found_site.creator_id,
307 updated: Some(naive_now()),
308 enable_downvotes: data.enable_downvotes,
309 open_registration: data.open_registration,
310 enable_nsfw: data.enable_nsfw,
313 let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form);
314 if blocking(pool, update_site).await?.is_err() {
315 return Err(APIError::err("couldnt_update_site").into());
318 let site_view = blocking(pool, move |conn| SiteView::read(conn)).await??;
320 let res = SiteResponse { site: site_view };
322 if let Some(ws) = websocket_info {
323 ws.chatserver.do_send(SendAllMessage {
324 op: UserOperation::EditSite,
325 response: res.clone(),
334 #[async_trait::async_trait(?Send)]
335 impl Perform for Oper<GetSite> {
336 type Response = GetSiteResponse;
341 websocket_info: Option<WebsocketInfo>,
342 ) -> Result<GetSiteResponse, LemmyError> {
343 let data: &GetSite = &self.data;
345 // TODO refactor this a little
346 let res = blocking(pool, move |conn| Site::read(conn, 1)).await?;
347 let site_view = if res.is_ok() {
348 Some(blocking(pool, move |conn| SiteView::read(conn)).await??)
349 } else if let Some(setup) = Settings::get().setup.as_ref() {
350 let register = Register {
351 username: setup.admin_username.to_owned(),
352 email: setup.admin_email.to_owned(),
353 password: setup.admin_password.to_owned(),
354 password_verify: setup.admin_password.to_owned(),
358 captcha_answer: None,
360 let login_response = Oper::new(register, self.client.clone())
361 .perform(pool, websocket_info.clone())
363 info!("Admin {} created", setup.admin_username);
365 let create_site = CreateSite {
366 name: setup.site_name.to_owned(),
368 enable_downvotes: true,
369 open_registration: true,
371 auth: login_response.jwt,
373 Oper::new(create_site, self.client.clone())
374 .perform(pool, websocket_info.clone())
376 info!("Site {} created", setup.site_name);
377 Some(blocking(pool, move |conn| SiteView::read(conn)).await??)
382 let mut admins = blocking(pool, move |conn| UserView::admins(conn)).await??;
384 // Make sure the site creator is the top admin
385 if let Some(site_view) = site_view.to_owned() {
386 let site_creator_id = site_view.creator_id;
387 // TODO investigate why this is sometimes coming back null
388 // Maybe user_.admin isn't being set to true?
389 if let Some(creator_index) = admins.iter().position(|r| r.id == site_creator_id) {
390 let creator_user = admins.remove(creator_index);
391 admins.insert(0, creator_user);
395 let banned = blocking(pool, move |conn| UserView::banned(conn)).await??;
397 let online = if let Some(_ws) = websocket_info {
401 // ws.chatserver.send(GetUsersOnline).await.unwrap()
403 // Runtime::new().unwrap().block_on(fut)
408 let my_user = get_user_from_jwt_opt(&data.auth, pool).await?.map(|mut u| {
409 u.password_encrypted = "".to_string();
410 u.private_key = None;
420 version: version::VERSION.to_string(),
426 #[async_trait::async_trait(?Send)]
427 impl Perform for Oper<Search> {
428 type Response = SearchResponse;
433 _websocket_info: Option<WebsocketInfo>,
434 ) -> Result<SearchResponse, LemmyError> {
435 let data: &Search = &self.data;
439 match search_by_apub_id(&data.q, &self.client, pool).await {
440 Ok(r) => return Ok(r),
441 Err(e) => debug!("Failed to resolve search query as activitypub ID: {}", e),
444 let user = get_user_from_jwt_opt(&data.auth, pool).await?;
445 let user_id = user.map(|u| u.id);
447 let type_ = SearchType::from_str(&data.type_)?;
449 let mut posts = Vec::new();
450 let mut comments = Vec::new();
451 let mut communities = Vec::new();
452 let mut users = Vec::new();
454 // TODO no clean / non-nsfw searching rn
456 let q = data.q.to_owned();
457 let page = data.page;
458 let limit = data.limit;
459 let sort = SortType::from_str(&data.sort)?;
460 let community_id = data.community_id;
462 SearchType::Posts => {
463 posts = blocking(pool, move |conn| {
464 PostQueryBuilder::create(conn)
467 .for_community_id(community_id)
476 SearchType::Comments => {
477 comments = blocking(pool, move |conn| {
478 CommentQueryBuilder::create(&conn)
488 SearchType::Communities => {
489 communities = blocking(pool, move |conn| {
490 CommunityQueryBuilder::create(conn)
499 SearchType::Users => {
500 users = blocking(pool, move |conn| {
501 UserQueryBuilder::create(conn)
511 posts = blocking(pool, move |conn| {
512 PostQueryBuilder::create(conn)
515 .for_community_id(community_id)
524 let q = data.q.to_owned();
525 let sort = SortType::from_str(&data.sort)?;
527 comments = blocking(pool, move |conn| {
528 CommentQueryBuilder::create(conn)
538 let q = data.q.to_owned();
539 let sort = SortType::from_str(&data.sort)?;
541 communities = blocking(pool, move |conn| {
542 CommunityQueryBuilder::create(conn)
551 let q = data.q.to_owned();
552 let sort = SortType::from_str(&data.sort)?;
554 users = blocking(pool, move |conn| {
555 UserQueryBuilder::create(conn)
565 posts = blocking(pool, move |conn| {
566 PostQueryBuilder::create(conn)
569 .for_community_id(community_id)
581 type_: data.type_.to_owned(),
590 #[async_trait::async_trait(?Send)]
591 impl Perform for Oper<TransferSite> {
592 type Response = GetSiteResponse;
597 _websocket_info: Option<WebsocketInfo>,
598 ) -> Result<GetSiteResponse, LemmyError> {
599 let data: &TransferSite = &self.data;
600 let mut user = get_user_from_jwt(&data.auth, pool).await?;
602 // TODO add a User_::read_safe() for this.
603 user.password_encrypted = "".to_string();
604 user.private_key = None;
605 user.public_key = None;
607 let read_site = blocking(pool, move |conn| Site::read(conn, 1)).await??;
609 // Make sure user is the creator
610 if read_site.creator_id != user.id {
611 return Err(APIError::err("not_an_admin").into());
614 let site_form = SiteForm {
615 name: read_site.name,
616 description: read_site.description,
617 creator_id: data.user_id,
618 updated: Some(naive_now()),
619 enable_downvotes: read_site.enable_downvotes,
620 open_registration: read_site.open_registration,
621 enable_nsfw: read_site.enable_nsfw,
624 let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form);
625 if blocking(pool, update_site).await?.is_err() {
626 return Err(APIError::err("couldnt_update_site").into());
630 let form = ModAddForm {
631 mod_user_id: user.id,
632 other_user_id: data.user_id,
633 removed: Some(false),
636 blocking(pool, move |conn| ModAdd::create(conn, &form)).await??;
638 let site_view = blocking(pool, move |conn| SiteView::read(conn)).await??;
640 let mut admins = blocking(pool, move |conn| UserView::admins(conn)).await??;
641 let creator_index = admins
643 .position(|r| r.id == site_view.creator_id)
645 let creator_user = admins.remove(creator_index);
646 admins.insert(0, creator_user);
648 let banned = blocking(pool, move |conn| UserView::banned(conn)).await??;
651 site: Some(site_view),
655 version: version::VERSION.to_string(),
661 #[async_trait::async_trait(?Send)]
662 impl Perform for Oper<GetSiteConfig> {
663 type Response = GetSiteConfigResponse;
668 _websocket_info: Option<WebsocketInfo>,
669 ) -> Result<GetSiteConfigResponse, LemmyError> {
670 let data: &GetSiteConfig = &self.data;
671 let user = get_user_from_jwt(&data.auth, pool).await?;
673 // Only let admins read this
674 is_admin(pool, user.id).await?;
676 let config_hjson = Settings::read_config_file()?;
678 Ok(GetSiteConfigResponse { config_hjson })
682 #[async_trait::async_trait(?Send)]
683 impl Perform for Oper<SaveSiteConfig> {
684 type Response = GetSiteConfigResponse;
689 _websocket_info: Option<WebsocketInfo>,
690 ) -> Result<GetSiteConfigResponse, LemmyError> {
691 let data: &SaveSiteConfig = &self.data;
692 let user = get_user_from_jwt(&data.auth, pool).await?;
694 // Only let admins read this
695 let admins = blocking(pool, move |conn| UserView::admins(conn)).await??;
696 let admin_ids: Vec<i32> = admins.into_iter().map(|m| m.id).collect();
698 if !admin_ids.contains(&user.id) {
699 return Err(APIError::err("not_an_admin").into());
702 // Make sure docker doesn't have :ro at the end of the volume, so its not a read-only filesystem
703 let config_hjson = match Settings::save_config_file(&data.config_hjson) {
704 Ok(config_hjson) => config_hjson,
705 Err(_e) => return Err(APIError::err("couldnt_update_site").into()),
708 Ok(GetSiteConfigResponse { config_hjson })