use laravel::db::{self, Values, col, values};
use laravel::model::{Column, CreateBuilder, Morph, UpdateBuilder};
use crate::author::{Author, Commenter};
use crate::config::{AutoApprove, CommentsConfig};
use crate::error::CommentError;
use crate::events::{CommentApproved, CommentDeleted, CommentEdited, CommentModerated, CommentPosted};
use crate::mentions::{self, CommentMention};
use crate::model::CommentModel;
use crate::moderation::{ModerationRule, NewComment};
use crate::revisions::CommentRevision;
use crate::status::Status;
pub(crate) const ATTEMPTS: u32 = 5;
pub(crate) fn config() -> CommentsConfig {
laravel::config().section::<CommentsConfig>().clone()
}
pub(crate) async fn post<C: CommentModel>(
on: C::Commentable,
author: Author<'_, C::Author>,
body: &str,
) -> laravel::Result<C> {
let config = config();
check_body(body, &config)?;
let columns = C::COLUMNS;
let status = status_for(&config, new_comment(on.morph().name(), *on.key(), None, &author, body)).await?;
check_author(&author)?;
let mentioned = mentions::resolve(body, author_id(&author)).await?;
let comment: C = db::transaction_with_attempts(ATTEMPTS, async |_| {
let mut create = author_values::<C>(CreateBuilder::new(), &author)
.set(columns.commentable_type, on.morph())
.set(columns.commentable_id, *on.key())
.set(columns.thread, laravel::str::ulid().to_string())
.set(columns.body, body.to_owned())
.set(columns.status, status)
.set(C::lft_column(), 1)
.set(C::rgt_column(), 2);
if let Some(depth) = C::depth_column() {
create = create.set(depth, 0);
}
let comment: C = create.await?;
mentions::record(comment.row().id, &mentioned).await?;
Ok(comment)
})
.await?;
posted(&comment).await?;
mentions::announce(&comment).await?;
Ok(comment)
}
pub(crate) async fn reply<C: CommentModel>(
parent: &mut C,
author: Author<'_, C::Author>,
body: &str,
) -> laravel::Result<C> {
let config = config();
check_body(body, &config)?;
if config.max_depth <= 0 {
return Err(CommentError::RepliesDisabled.into());
}
let row = parent.row();
let (parent_id, commentable_type, commentable_id) = (row.id, row.commentable_type, row.commentable_id);
if row.deleted_at.is_some() {
return Err(CommentError::Deleted { id: parent_id }.into());
}
if row.status != Status::Approved {
return Err(CommentError::NotApproved { id: parent_id }.into());
}
let too_deep = row.depth >= config.max_depth;
let columns = C::COLUMNS;
check_author(&author)?;
let status = status_for(
&config,
new_comment(commentable_type.name(), commentable_id, Some(parent_id), &author, body),
)
.await?;
let mentioned = mentions::resolve(body, author_id(&author)).await?;
let start = &*parent;
let reply = db::transaction_with_attempts(ATTEMPTS, async |_| {
let create = author_values::<C>(CreateBuilder::new(), &author)
.set(columns.commentable_type, commentable_type)
.set(columns.commentable_id, commentable_id)
.set(columns.body, body.to_owned())
.set(columns.status, status);
let mut anchor = if too_deep {
start
.ancestors()
.filter(depth_is::<C>(config.max_depth - 1))
.first()
.await?
.ok_or(CommentError::NotFound { id: parent_id })?
} else {
start.clone()
};
let reply = anchor.create_child(create).await?;
if status == Status::Approved {
adjust_replies::<C>(*anchor.node_key(), 1).await?;
}
mentions::record(reply.row().id, &mentioned).await?;
Ok(reply)
})
.await?;
*parent = find::<C>(parent_id).await?;
posted(&reply).await?;
mentions::announce(&reply).await?;
Ok(reply)
}
pub(crate) async fn edit<C: CommentModel>(comment: &mut C, body: &str) -> laravel::Result<()> {
let config = config();
check_body(body, &config)?;
let row = comment.row();
let (id, author_id, old_body) = (row.id, row.author_id, row.body.to_owned());
if row.deleted_at.is_some() {
return Err(CommentError::Deleted { id }.into());
}
if old_body == body {
return Ok(());
}
let mentioned = mentions::resolve(body, author_id).await?;
let columns = C::COLUMNS;
db::transaction_with_attempts(ATTEMPTS, async |_| {
let now = laravel::now().timestamp();
if config.revisions {
db::table("comment_revisions")
.insert(values! { comment_id: id, body: old_body.as_str(), created_at: now })
.await?;
}
let mut values = Values::new()
.set(columns.body.name(), body)
.set(columns.edited_at.name(), now);
if let Some(stamp) = C::META.updated_at {
values = values.set(stamp.name, now);
}
C::new_query().filter(C::META.key.eq(id)).update_values(values).await?;
mentions::record(id, &mentioned).await
})
.await?;
*comment = find::<C>(id).await?;
let row = comment.row();
CommentEdited {
comment_id: id,
commentable_type: row.commentable_type.name().to_owned(),
commentable_id: row.commentable_id,
status: row.status,
}
.dispatch()
.await?;
mentions::announce(&*comment).await
}
pub(crate) async fn moderate<C: CommentModel>(comment: &mut C, to: Status) -> laravel::Result<()> {
let row = comment.row();
let (id, from, parent_id) = (row.id, row.status, row.parent_id);
if from == to {
return Ok(());
}
let columns = C::COLUMNS;
db::transaction_with_attempts(ATTEMPTS, async |_| {
let now = laravel::now().timestamp();
let mut values = Values::new()
.set(columns.status.name(), to)
.set(columns.moderated_at.name(), now);
if let Some(stamp) = C::META.updated_at {
values = values.set(stamp.name, now);
}
C::new_query().filter(C::META.key.eq(id)).update_values(values).await?;
if let Some(parent_id) = parent_id {
if to == Status::Approved {
adjust_replies::<C>(parent_id, 1).await?;
} else if from == Status::Approved {
adjust_replies::<C>(parent_id, -1).await?;
}
}
Ok(())
})
.await?;
*comment = find::<C>(id).await?;
let row = comment.row();
let (commentable_type, commentable_id) = (row.commentable_type.name().to_owned(), row.commentable_id);
CommentModerated {
comment_id: id,
commentable_type: commentable_type.clone(),
commentable_id,
from,
to,
}
.dispatch()
.await?;
if to == Status::Approved {
CommentApproved {
comment_id: id,
commentable_type,
commentable_id,
}
.dispatch()
.await?;
mentions::announce(&*comment).await?;
}
Ok(())
}
pub(crate) async fn remove<C: CommentModel>(comment: C) -> laravel::Result<bool> {
let row = comment.row();
let (id, commentable_type, commentable_id) = (row.id, row.commentable_type.name().to_owned(), row.commentable_id);
let (placeholder, deleted) = db::transaction_with_attempts(ATTEMPTS, async |_| {
let mut current = find::<C>(id).await?;
let status = current.row().status;
if current.descendant_count() > 0 {
leave_placeholder(&mut current).await?;
return Ok((true, vec![(id, status)]));
}
let mut top = current;
let mut deleted = vec![(id, status)];
while let Some(parent_id) = top.row().parent_id {
let parent = find::<C>(parent_id).await?;
let left_empty = parent.descendant_count() == top.descendant_count() + 1;
if parent.row().deleted_at.is_none() || !left_empty {
break;
}
deleted.push((parent_id, parent.row().status));
top = parent;
}
let row = top.row();
let (parent_id, approved) = (row.parent_id, row.status == Status::Approved);
top.delete_subtree().await?;
if let (Some(parent_id), true) = (parent_id, approved) {
adjust_replies::<C>(parent_id, -1).await?;
}
Ok((false, deleted))
})
.await?;
for (comment_id, status) in deleted {
CommentDeleted {
comment_id,
commentable_type: commentable_type.clone(),
commentable_id,
placeholder,
status,
}
.dispatch()
.await?;
}
Ok(placeholder)
}
async fn leave_placeholder<C: CommentModel>(comment: &mut C) -> laravel::Result<()> {
let columns = C::COLUMNS;
let id = comment.row().id;
CommentRevision::query()
.filter(CommentRevision::comment_id.eq(id))
.delete()
.await?;
CommentMention::query()
.filter(CommentMention::comment_id.eq(id))
.delete()
.await?;
UpdateBuilder::new(comment)
.set(columns.body, String::new())
.set(columns.author_id, None::<i64>)
.set(columns.guest_name, None::<String>)
.set(columns.guest_email, None::<String>)
.set(columns.deleted_at, laravel::now())
.await
}
pub(crate) async fn find<C: CommentModel>(id: i64) -> laravel::Result<C> {
C::new_query()
.filter(C::META.key.eq(id))
.first()
.await?
.ok_or_else(|| CommentError::NotFound { id }.into())
}
fn depth_is<C: CommentModel>(depth: i64) -> laravel::db::Condition {
match C::depth_column() {
Some(column) => column.eq(depth),
None => laravel::db::raw!("1 = 0").into(),
}
}
async fn adjust_replies<C: CommentModel>(id: i64, by: i64) -> laravel::Result<()> {
bump(id, C::COLUMNS.replies_count, by).await
}
pub(crate) async fn bump<C: CommentModel>(id: i64, counter: Column<C, i64>, by: i64) -> laravel::Result<()> {
let name = counter.name();
let mut values = Values::new().set(name, col(name) + by);
if let Some(stamp) = C::META.updated_at {
values = values.set(stamp.name, col(stamp.name));
}
C::new_query().filter(C::META.key.eq(id)).update_values(values).await?;
Ok(())
}
fn author_id<U: Commenter>(author: &Author<'_, U>) -> Option<i64> {
match author {
Author::User(user) => Some(user.commenter_id()),
Author::Guest { .. } => None,
}
}
async fn posted<C: CommentModel>(comment: &C) -> laravel::Result<()> {
let row = comment.row();
CommentPosted {
comment_id: row.id,
commentable_type: row.commentable_type.name().to_owned(),
commentable_id: row.commentable_id,
parent_id: row.parent_id,
author_id: row.author_id,
status: row.status,
}
.dispatch()
.await
}
fn check_body(body: &str, config: &CommentsConfig) -> Result<(), CommentError> {
if body.trim().is_empty() {
return Err(CommentError::EmptyBody);
}
if body.chars().count() > config.max_length {
return Err(CommentError::BodyTooLong { max: config.max_length });
}
Ok(())
}
fn check_author<U>(author: &Author<'_, U>) -> Result<(), CommentError> {
match author {
Author::Guest { name, email } if name.trim().is_empty() || !email.contains('@') => {
Err(CommentError::InvalidGuest)
}
_ => Ok(()),
}
}
fn author_values<C: CommentModel>(create: CreateBuilder<C>, author: &Author<'_, C::Author>) -> CreateBuilder<C> {
let columns = C::COLUMNS;
match author {
Author::User(user) => create.set(columns.author_id, Some(user.commenter_id())),
Author::Guest { name, email } => create
.set(columns.guest_name, Some(name.trim().to_owned()))
.set(columns.guest_email, Some(email.trim().to_owned())),
}
}
fn new_comment<U: Commenter>(
commentable_type: &'static str,
commentable_id: i64,
parent_id: Option<i64>,
author: &Author<'_, U>,
body: &str,
) -> NewComment {
let (author_id, guest_email) = match author {
Author::User(user) => (Some(user.commenter_id()), None),
Author::Guest { email, .. } => (None, Some(email.trim().to_owned())),
};
NewComment {
commentable_type,
commentable_id,
parent_id,
author_id,
guest_email,
body: body.to_owned(),
}
}
async fn status_for(config: &CommentsConfig, comment: NewComment) -> laravel::Result<Status> {
let rule = laravel::resolve::<ModerationRule>().await?;
if let Some(rule) = &rule.0 {
return rule(comment).await;
}
let approved = match config.auto_approve {
AutoApprove::Everyone => true,
AutoApprove::Users => comment.author_id.is_some(),
AutoApprove::Nobody => false,
};
Ok(if approved { Status::Approved } else { Status::Pending })
}