//! # Comments controller //! //! @author Pierre Hubert use crate::api_data::comment_api::CommentAPI; use crate::api_data::res_create_comment::ResCreateComment; use crate::constants::PATH_COMMENTS_IMAGES; use crate::controllers::routes::RequestResult; use crate::data::comment::Comment; use crate::data::http_request_handler::HttpRequestHandler; use crate::data::notification::NotifEventType; use crate::data::post::PostAccessLevel; use crate::helpers::{comments_helper, notifications_helper, posts_helper}; use crate::utils::date_utils::time; use crate::utils::string_utils::remove_html_nodes; /// Create a new comment pub fn create(r: &mut HttpRequestHandler) -> RequestResult { let post = r.post_post_with_access("postID", PostAccessLevel::BASIC_ACCESS)?; if !posts_helper::allow_comments_on_post(&post)? { r.forbidden("You can not create comments on this post!".to_string())?; } let (content, image) = if r.has_file("image") { ( remove_html_nodes(&r.post_string_opt("content", 0, false)?), Some(r.save_post_image("image", PATH_COMMENTS_IMAGES, 700, 700)?) ) } else { ( r.post_content("content", 2, true)?, None ) }; let comment = Comment { id: 0, time_sent: time(), user_id: r.user_id()?, post_id: post.id, content, image_path: image, }; let comment_id = comments_helper::create(&comment)?; // Create notifications notifications_helper::create_post_notification(&r.user_id()?, post.id, NotifEventType::COMMENT_CREATED)?; // TODO : Remove notifications targeting current user about the post r.set_response(ResCreateComment::new(comment_id)) } /// Get information about a single comment pub fn get_single(r: &mut HttpRequestHandler) -> RequestResult { let comment = r.post_comment_with_access("commentID")?; r.set_response(CommentAPI::new(&comment, &r.user_id_opt())?) } /// Change a comment's content pub fn edit(r: &mut HttpRequestHandler) -> RequestResult { let comment = r.post_comment_with_full_access("commentID")?; let new_content = r.post_content("content", 2, true)?; comments_helper::edit(comment.id, &new_content)?; r.success("Content updated.") } /// Delete a comment pub fn delete(r: &mut HttpRequestHandler) -> RequestResult { let comment = r.post_comment_with_full_access("commentID")?; comments_helper::delete(&comment)?; r.success("Comment deleted.") }