1 use super::user::Register;
13 apub::fetcher::search_by_apub_id,
16 websocket::{server::SendAllMessage, UserOperation, WebsocketInfo},
24 diesel_option_overwrite,
37 use lemmy_utils::settings::Settings;
38 use log::{debug, info};
39 use serde::{Deserialize, Serialize};
40 use std::str::FromStr;
42 #[derive(Serialize, Deserialize)]
43 pub struct ListCategories {}
45 #[derive(Serialize, Deserialize)]
46 pub struct ListCategoriesResponse {
47 categories: Vec<Category>,
50 #[derive(Serialize, Deserialize, Debug)]
54 community_id: Option<i32>,
61 #[derive(Serialize, Deserialize, Debug)]
62 pub struct SearchResponse {
64 pub comments: Vec<CommentView>,
65 pub posts: Vec<PostView>,
66 pub communities: Vec<CommunityView>,
67 pub users: Vec<UserView>,
70 #[derive(Serialize, Deserialize)]
71 pub struct GetModlog {
72 mod_user_id: Option<i32>,
73 community_id: Option<i32>,
78 #[derive(Serialize, Deserialize)]
79 pub struct GetModlogResponse {
80 removed_posts: Vec<ModRemovePostView>,
81 locked_posts: Vec<ModLockPostView>,
82 stickied_posts: Vec<ModStickyPostView>,
83 removed_comments: Vec<ModRemoveCommentView>,
84 removed_communities: Vec<ModRemoveCommunityView>,
85 banned_from_community: Vec<ModBanFromCommunityView>,
86 banned: Vec<ModBanView>,
87 added_to_community: Vec<ModAddCommunityView>,
88 added: Vec<ModAddView>,
91 #[derive(Serialize, Deserialize)]
92 pub struct CreateSite {
94 pub description: Option<String>,
95 pub icon: Option<String>,
96 pub banner: Option<String>,
97 pub enable_downvotes: bool,
98 pub open_registration: bool,
99 pub enable_nsfw: bool,
103 #[derive(Serialize, Deserialize)]
104 pub struct EditSite {
106 description: Option<String>,
107 icon: Option<String>,
108 banner: Option<String>,
109 enable_downvotes: bool,
110 open_registration: bool,
115 #[derive(Serialize, Deserialize)]
117 auth: Option<String>,
120 #[derive(Serialize, Deserialize, Clone)]
121 pub struct SiteResponse {
125 #[derive(Serialize, Deserialize)]
126 pub struct GetSiteResponse {
127 site: Option<SiteView>,
128 admins: Vec<UserView>,
129 banned: Vec<UserView>,
132 my_user: Option<User_>,
135 #[derive(Serialize, Deserialize)]
136 pub struct TransferSite {
141 #[derive(Serialize, Deserialize)]
142 pub struct GetSiteConfig {
146 #[derive(Serialize, Deserialize)]
147 pub struct GetSiteConfigResponse {
148 config_hjson: String,
151 #[derive(Serialize, Deserialize)]
152 pub struct SaveSiteConfig {
153 config_hjson: String,
157 #[async_trait::async_trait(?Send)]
158 impl Perform for Oper<ListCategories> {
159 type Response = ListCategoriesResponse;
164 _websocket_info: Option<WebsocketInfo>,
165 ) -> Result<ListCategoriesResponse, LemmyError> {
166 let _data: &ListCategories = &self.data;
168 let categories = blocking(pool, move |conn| Category::list_all(conn)).await??;
171 Ok(ListCategoriesResponse { categories })
175 #[async_trait::async_trait(?Send)]
176 impl Perform for Oper<GetModlog> {
177 type Response = GetModlogResponse;
182 _websocket_info: Option<WebsocketInfo>,
183 ) -> Result<GetModlogResponse, LemmyError> {
184 let data: &GetModlog = &self.data;
186 let community_id = data.community_id;
187 let mod_user_id = data.mod_user_id;
188 let page = data.page;
189 let limit = data.limit;
190 let removed_posts = blocking(pool, move |conn| {
191 ModRemovePostView::list(conn, community_id, mod_user_id, page, limit)
195 let locked_posts = blocking(pool, move |conn| {
196 ModLockPostView::list(conn, community_id, mod_user_id, page, limit)
200 let stickied_posts = blocking(pool, move |conn| {
201 ModStickyPostView::list(conn, community_id, mod_user_id, page, limit)
205 let removed_comments = blocking(pool, move |conn| {
206 ModRemoveCommentView::list(conn, community_id, mod_user_id, page, limit)
210 let banned_from_community = blocking(pool, move |conn| {
211 ModBanFromCommunityView::list(conn, community_id, mod_user_id, page, limit)
215 let added_to_community = blocking(pool, move |conn| {
216 ModAddCommunityView::list(conn, community_id, mod_user_id, page, limit)
220 // These arrays are only for the full modlog, when a community isn't given
221 let (removed_communities, banned, added) = if data.community_id.is_none() {
222 blocking(pool, move |conn| {
224 ModRemoveCommunityView::list(conn, mod_user_id, page, limit)?,
225 ModBanView::list(conn, mod_user_id, page, limit)?,
226 ModAddView::list(conn, mod_user_id, page, limit)?,
227 )) as Result<_, LemmyError>
231 (Vec::new(), Vec::new(), Vec::new())
235 Ok(GetModlogResponse {
241 banned_from_community,
249 #[async_trait::async_trait(?Send)]
250 impl Perform for Oper<CreateSite> {
251 type Response = SiteResponse;
256 _websocket_info: Option<WebsocketInfo>,
257 ) -> Result<SiteResponse, LemmyError> {
258 let data: &CreateSite = &self.data;
260 let user = get_user_from_jwt(&data.auth, pool).await?;
262 check_slurs(&data.name)?;
263 check_slurs_opt(&data.description)?;
265 // Make sure user is an admin
266 is_admin(pool, user.id).await?;
268 let site_form = SiteForm {
269 name: data.name.to_owned(),
270 description: data.description.to_owned(),
271 icon: Some(data.icon.to_owned()),
272 banner: Some(data.banner.to_owned()),
274 enable_downvotes: data.enable_downvotes,
275 open_registration: data.open_registration,
276 enable_nsfw: data.enable_nsfw,
280 let create_site = move |conn: &'_ _| Site::create(conn, &site_form);
281 if blocking(pool, create_site).await?.is_err() {
282 return Err(APIError::err("site_already_exists").into());
285 let site_view = blocking(pool, move |conn| SiteView::read(conn)).await??;
287 Ok(SiteResponse { site: site_view })
291 #[async_trait::async_trait(?Send)]
292 impl Perform for Oper<EditSite> {
293 type Response = SiteResponse;
297 websocket_info: Option<WebsocketInfo>,
298 ) -> Result<SiteResponse, LemmyError> {
299 let data: &EditSite = &self.data;
300 let user = get_user_from_jwt(&data.auth, pool).await?;
302 check_slurs(&data.name)?;
303 check_slurs_opt(&data.description)?;
305 // Make sure user is an admin
306 is_admin(pool, user.id).await?;
308 let found_site = blocking(pool, move |conn| Site::read(conn, 1)).await??;
310 let icon = diesel_option_overwrite(&data.icon);
311 let banner = diesel_option_overwrite(&data.banner);
313 let site_form = SiteForm {
314 name: data.name.to_owned(),
315 description: data.description.to_owned(),
318 creator_id: found_site.creator_id,
319 updated: Some(naive_now()),
320 enable_downvotes: data.enable_downvotes,
321 open_registration: data.open_registration,
322 enable_nsfw: data.enable_nsfw,
325 let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form);
326 if blocking(pool, update_site).await?.is_err() {
327 return Err(APIError::err("couldnt_update_site").into());
330 let site_view = blocking(pool, move |conn| SiteView::read(conn)).await??;
332 let res = SiteResponse { site: site_view };
334 if let Some(ws) = websocket_info {
335 ws.chatserver.do_send(SendAllMessage {
336 op: UserOperation::EditSite,
337 response: res.clone(),
346 #[async_trait::async_trait(?Send)]
347 impl Perform for Oper<GetSite> {
348 type Response = GetSiteResponse;
353 websocket_info: Option<WebsocketInfo>,
354 ) -> Result<GetSiteResponse, LemmyError> {
355 let data: &GetSite = &self.data;
357 // TODO refactor this a little
358 let res = blocking(pool, move |conn| Site::read(conn, 1)).await?;
359 let site_view = if res.is_ok() {
360 Some(blocking(pool, move |conn| SiteView::read(conn)).await??)
361 } else if let Some(setup) = Settings::get().setup.as_ref() {
362 let register = Register {
363 username: setup.admin_username.to_owned(),
364 email: setup.admin_email.to_owned(),
365 password: setup.admin_password.to_owned(),
366 password_verify: setup.admin_password.to_owned(),
370 captcha_answer: None,
372 let login_response = Oper::new(register, self.client.clone())
373 .perform(pool, websocket_info.clone())
375 info!("Admin {} created", setup.admin_username);
377 let create_site = CreateSite {
378 name: setup.site_name.to_owned(),
382 enable_downvotes: true,
383 open_registration: true,
385 auth: login_response.jwt,
387 Oper::new(create_site, self.client.clone())
388 .perform(pool, websocket_info.clone())
390 info!("Site {} created", setup.site_name);
391 Some(blocking(pool, move |conn| SiteView::read(conn)).await??)
396 let mut admins = blocking(pool, move |conn| UserView::admins(conn)).await??;
398 // Make sure the site creator is the top admin
399 if let Some(site_view) = site_view.to_owned() {
400 let site_creator_id = site_view.creator_id;
401 // TODO investigate why this is sometimes coming back null
402 // Maybe user_.admin isn't being set to true?
403 if let Some(creator_index) = admins.iter().position(|r| r.id == site_creator_id) {
404 let creator_user = admins.remove(creator_index);
405 admins.insert(0, creator_user);
409 let banned = blocking(pool, move |conn| UserView::banned(conn)).await??;
411 let online = if let Some(_ws) = websocket_info {
415 // ws.chatserver.send(GetUsersOnline).await.unwrap()
417 // Runtime::new().unwrap().block_on(fut)
422 let my_user = get_user_from_jwt_opt(&data.auth, pool).await?.map(|mut u| {
423 u.password_encrypted = "".to_string();
424 u.private_key = None;
434 version: version::VERSION.to_string(),
440 #[async_trait::async_trait(?Send)]
441 impl Perform for Oper<Search> {
442 type Response = SearchResponse;
447 _websocket_info: Option<WebsocketInfo>,
448 ) -> Result<SearchResponse, LemmyError> {
449 let data: &Search = &self.data;
453 match search_by_apub_id(&data.q, &self.client, pool).await {
454 Ok(r) => return Ok(r),
455 Err(e) => debug!("Failed to resolve search query as activitypub ID: {}", e),
458 let user = get_user_from_jwt_opt(&data.auth, pool).await?;
459 let user_id = user.map(|u| u.id);
461 let type_ = SearchType::from_str(&data.type_)?;
463 let mut posts = Vec::new();
464 let mut comments = Vec::new();
465 let mut communities = Vec::new();
466 let mut users = Vec::new();
468 // TODO no clean / non-nsfw searching rn
470 let q = data.q.to_owned();
471 let page = data.page;
472 let limit = data.limit;
473 let sort = SortType::from_str(&data.sort)?;
474 let community_id = data.community_id;
476 SearchType::Posts => {
477 posts = blocking(pool, move |conn| {
478 PostQueryBuilder::create(conn)
481 .for_community_id(community_id)
490 SearchType::Comments => {
491 comments = blocking(pool, move |conn| {
492 CommentQueryBuilder::create(&conn)
502 SearchType::Communities => {
503 communities = blocking(pool, move |conn| {
504 CommunityQueryBuilder::create(conn)
513 SearchType::Users => {
514 users = blocking(pool, move |conn| {
515 UserQueryBuilder::create(conn)
525 posts = blocking(pool, move |conn| {
526 PostQueryBuilder::create(conn)
529 .for_community_id(community_id)
538 let q = data.q.to_owned();
539 let sort = SortType::from_str(&data.sort)?;
541 comments = blocking(pool, move |conn| {
542 CommentQueryBuilder::create(conn)
552 let q = data.q.to_owned();
553 let sort = SortType::from_str(&data.sort)?;
555 communities = blocking(pool, move |conn| {
556 CommunityQueryBuilder::create(conn)
565 let q = data.q.to_owned();
566 let sort = SortType::from_str(&data.sort)?;
568 users = blocking(pool, move |conn| {
569 UserQueryBuilder::create(conn)
579 posts = blocking(pool, move |conn| {
580 PostQueryBuilder::create(conn)
583 .for_community_id(community_id)
595 type_: data.type_.to_owned(),
604 #[async_trait::async_trait(?Send)]
605 impl Perform for Oper<TransferSite> {
606 type Response = GetSiteResponse;
611 _websocket_info: Option<WebsocketInfo>,
612 ) -> Result<GetSiteResponse, LemmyError> {
613 let data: &TransferSite = &self.data;
614 let mut user = get_user_from_jwt(&data.auth, pool).await?;
616 // TODO add a User_::read_safe() for this.
617 user.password_encrypted = "".to_string();
618 user.private_key = None;
619 user.public_key = None;
621 let read_site = blocking(pool, move |conn| Site::read(conn, 1)).await??;
623 // Make sure user is the creator
624 if read_site.creator_id != user.id {
625 return Err(APIError::err("not_an_admin").into());
628 let new_creator_id = data.user_id;
629 let transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id);
630 if blocking(pool, transfer_site).await?.is_err() {
631 return Err(APIError::err("couldnt_update_site").into());
635 let form = ModAddForm {
636 mod_user_id: user.id,
637 other_user_id: data.user_id,
638 removed: Some(false),
641 blocking(pool, move |conn| ModAdd::create(conn, &form)).await??;
643 let site_view = blocking(pool, move |conn| SiteView::read(conn)).await??;
645 let mut admins = blocking(pool, move |conn| UserView::admins(conn)).await??;
646 let creator_index = admins
648 .position(|r| r.id == site_view.creator_id)
650 let creator_user = admins.remove(creator_index);
651 admins.insert(0, creator_user);
653 let banned = blocking(pool, move |conn| UserView::banned(conn)).await??;
656 site: Some(site_view),
660 version: version::VERSION.to_string(),
666 #[async_trait::async_trait(?Send)]
667 impl Perform for Oper<GetSiteConfig> {
668 type Response = GetSiteConfigResponse;
673 _websocket_info: Option<WebsocketInfo>,
674 ) -> Result<GetSiteConfigResponse, LemmyError> {
675 let data: &GetSiteConfig = &self.data;
676 let user = get_user_from_jwt(&data.auth, pool).await?;
678 // Only let admins read this
679 is_admin(pool, user.id).await?;
681 let config_hjson = Settings::read_config_file()?;
683 Ok(GetSiteConfigResponse { config_hjson })
687 #[async_trait::async_trait(?Send)]
688 impl Perform for Oper<SaveSiteConfig> {
689 type Response = GetSiteConfigResponse;
694 _websocket_info: Option<WebsocketInfo>,
695 ) -> Result<GetSiteConfigResponse, LemmyError> {
696 let data: &SaveSiteConfig = &self.data;
697 let user = get_user_from_jwt(&data.auth, pool).await?;
699 // Only let admins read this
700 let admins = blocking(pool, move |conn| UserView::admins(conn)).await??;
701 let admin_ids: Vec<i32> = admins.into_iter().map(|m| m.id).collect();
703 if !admin_ids.contains(&user.id) {
704 return Err(APIError::err("not_an_admin").into());
707 // Make sure docker doesn't have :ro at the end of the volume, so its not a read-only filesystem
708 let config_hjson = match Settings::save_config_file(&data.config_hjson) {
709 Ok(config_hjson) => config_hjson,
710 Err(_e) => return Err(APIError::err("couldnt_update_site").into()),
713 Ok(GetSiteConfigResponse { config_hjson })