From a071d33efd12492edb662f1a9444dda897f398f4 Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Thu, 9 Jul 2020 10:48:44 +0200 Subject: [PATCH] Delete the comments associated to a post --- src/helpers/comments_helper.rs | 34 +++++++++++++++++++++++++++++++++- src/helpers/posts_helper.rs | 5 ++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/helpers/comments_helper.rs b/src/helpers/comments_helper.rs index a41f082..696d0e9 100644 --- a/src/helpers/comments_helper.rs +++ b/src/helpers/comments_helper.rs @@ -5,7 +5,9 @@ use crate::constants::database_tables_names::COMMENTS_TABLE; use crate::data::comment::Comment; use crate::data::error::ResultBoxError; -use crate::helpers::database; +use crate::helpers::{database, likes_helper}; +use crate::helpers::likes_helper::LikeType; +use crate::utils::user_data_utils::user_data_path; /// Get the comments of a post pub fn get(post_id: u64) -> ResultBoxError> { @@ -26,4 +28,34 @@ fn db_to_comment(row: &database::RowResult) -> ResultBoxError { content: row.get_str("commentaire")?, image_path: row.get_optional_str("image_commentaire")?, }) +} + +/// Delete a single comment +pub fn delete(c: &Comment) -> ResultBoxError { + // Delete associated image (if any) + if let Some(image) = &c.image_path { + let path = user_data_path(image.as_ref()); + if path.exists() { + std::fs::remove_file(&path)?; + } + } + + // Remove the likes associated with the comment + likes_helper::delete_all(c.id, LikeType::COMMENT)?; + + // Remove the comment from the database + database::DeleteQuery::new(COMMENTS_TABLE) + .cond_u64("ID", c.id) + .exec()?; + + Ok(()) +} + +/// Delete all the comments associated to a post +pub fn delete_all(post_id: u64) -> ResultBoxError { + for c in &get(post_id)? { + delete(c)?; + } + + Ok(()) } \ No newline at end of file diff --git a/src/helpers/posts_helper.rs b/src/helpers/posts_helper.rs index b5d0f05..7b5214e 100644 --- a/src/helpers/posts_helper.rs +++ b/src/helpers/posts_helper.rs @@ -11,7 +11,7 @@ use crate::data::group_member::GroupMembershipLevel; use crate::data::post::{Post, PostAccessLevel, PostFile, PostKind, PostPageKind, PostVisibilityLevel, PostWebLink}; use crate::data::post::PostKind::{POST_KIND_COUNTDOWN, POST_KIND_IMAGE, POST_KIND_MOVIE, POST_KIND_PDF, POST_KIND_SURVEY, POST_KIND_WEBLINK, POST_KIND_YOUTUBE}; use crate::data::user::UserID; -use crate::helpers::{database, friends_helper, groups_helper, likes_helper, user_helper}; +use crate::helpers::{database, friends_helper, groups_helper, likes_helper, user_helper, comments_helper}; use crate::helpers::likes_helper::LikeType; use crate::utils::date_utils::{mysql_date, time}; @@ -407,6 +407,9 @@ pub fn delete(p: &Post) -> ResultBoxError { // Delete all the likes associated with the post likes_helper::delete_all(p.id, LikeType::POST)?; + // Delete all the comments associated to the post + comments_helper::delete_all(p.id)?; + Ok(()) }