use std::collections::{BTreeMap, HashMap};
use laravel::db::{self, col, values};
use laravel::model::model;
use laravel::time::Timestamp;
use crate::error::CommentError;
use crate::events::{ReactionAdded, ReactionRemoved};
use crate::model::CommentModel;
use crate::ops;
use crate::status::Visibility;
const REACTIONS: &str = "comment_reactions";
const COUNTS: &str = "comment_reaction_counts";
#[model(table = "comment_reactions")]
pub struct CommentReaction {
pub id: i64,
pub comment_id: i64,
pub user_id: i64,
pub reaction: String,
pub created_at: Option<Timestamp>,
}
pub(crate) async fn react<C: CommentModel>(comment: &C, user_id: i64, reaction: &str) -> laravel::Result<bool> {
check(comment, reaction)?;
let id = comment.row().id;
let added = db::transaction_with_attempts(ops::ATTEMPTS, async |_| {
lock::<C>(id).await?;
add::<C>(id, user_id, reaction).await
})
.await?;
if added {
dispatch_added(comment, user_id, reaction).await?;
}
Ok(added)
}
pub(crate) async fn unreact<C: CommentModel>(comment: &C, user_id: i64, reaction: &str) -> laravel::Result<bool> {
let id = comment.row().id;
let removed = db::transaction_with_attempts(ops::ATTEMPTS, async |_| {
lock::<C>(id).await?;
take_back::<C>(id, user_id, reaction).await
})
.await?;
if removed {
ReactionRemoved {
comment_id: id,
commentable_type: comment.row().commentable_type.name().to_owned(),
commentable_id: comment.row().commentable_id,
user_id,
reaction: reaction.to_owned(),
}
.dispatch()
.await?;
}
Ok(removed)
}
pub(crate) async fn toggle<C: CommentModel>(comment: &C, user_id: i64, reaction: &str) -> laravel::Result<bool> {
check(comment, reaction)?;
let id = comment.row().id;
let added = db::transaction_with_attempts(ops::ATTEMPTS, async |_| {
lock::<C>(id).await?;
if add::<C>(id, user_id, reaction).await? {
return Ok(true);
}
take_back::<C>(id, user_id, reaction).await?;
Ok(false)
})
.await?;
if added {
dispatch_added(comment, user_id, reaction).await?;
} else {
ReactionRemoved {
comment_id: id,
commentable_type: comment.row().commentable_type.name().to_owned(),
commentable_id: comment.row().commentable_id,
user_id,
reaction: reaction.to_owned(),
}
.dispatch()
.await?;
}
Ok(added)
}
pub async fn reaction_counts(ids: &[i64]) -> laravel::Result<HashMap<i64, BTreeMap<String, i64>>> {
let mut counts: HashMap<i64, BTreeMap<String, i64>> = HashMap::new();
if ids.is_empty() {
return Ok(counts);
}
let rows: Vec<(i64, String, i64)> = db::table(COUNTS)
.select(["comment_id", "reaction", "count"])
.filter(col("comment_id").is_in(ids) & col("count").gt(0))
.get()
.await?;
for (comment_id, reaction, count) in rows {
counts.entry(comment_id).or_default().insert(reaction, count);
}
Ok(counts)
}
pub async fn reactions_of(user_id: i64, ids: &[i64]) -> laravel::Result<HashMap<i64, Vec<String>>> {
let mut mine: HashMap<i64, Vec<String>> = HashMap::new();
if ids.is_empty() {
return Ok(mine);
}
let rows = CommentReaction::query()
.filter(CommentReaction::user_id.eq(user_id) & CommentReaction::comment_id.is_in(ids))
.order_by(CommentReaction::reaction.asc())
.get()
.await?;
for row in rows {
mine.entry(row.comment_id).or_default().push(row.reaction);
}
Ok(mine)
}
fn check<C: CommentModel>(comment: &C, reaction: &str) -> Result<(), CommentError> {
if !ops::config().reactions.iter().any(|allowed| allowed == reaction) {
return Err(CommentError::UnknownReaction {
reaction: reaction.to_owned(),
});
}
let id = comment.row().id;
match comment.visibility() {
Visibility::Visible => Ok(()),
Visibility::Deleted => Err(CommentError::Deleted { id }),
Visibility::Hidden => Err(CommentError::NotApproved { id }),
}
}
async fn lock<C: CommentModel>(id: i64) -> laravel::Result<()> {
C::new_query()
.filter(C::META.key.eq(id))
.lock_for_update()
.first()
.await?
.ok_or(CommentError::NotFound { id })?;
Ok(())
}
async fn add<C: CommentModel>(id: i64, user_id: i64, reaction: &str) -> laravel::Result<bool> {
let now = laravel::now().timestamp();
let inserted = db::table(REACTIONS)
.insert_or_ignore([values! { comment_id: id, user_id: user_id, reaction: reaction, created_at: now }])
.await?;
if inserted == 0 {
return Ok(false);
}
count(id, reaction, 1).await?;
ops::bump(id, C::COLUMNS.reactions_count, 1).await?;
Ok(true)
}
async fn take_back<C: CommentModel>(id: i64, user_id: i64, reaction: &str) -> laravel::Result<bool> {
let deleted = CommentReaction::query()
.filter(
CommentReaction::comment_id.eq(id)
& CommentReaction::user_id.eq(user_id)
& CommentReaction::reaction.eq(reaction),
)
.delete()
.await?;
if deleted == 0 {
return Ok(false);
}
count(id, reaction, -1).await?;
ops::bump(id, C::COLUMNS.reactions_count, -1).await?;
Ok(true)
}
async fn dispatch_added<C: CommentModel>(comment: &C, user_id: i64, reaction: &str) -> laravel::Result<()> {
let row = comment.row();
ReactionAdded {
comment_id: row.id,
commentable_type: row.commentable_type.name().to_owned(),
commentable_id: row.commentable_id,
user_id,
reaction: reaction.to_owned(),
}
.dispatch()
.await
}
async fn count(id: i64, reaction: &str, by: i64) -> laravel::Result<()> {
db::table(COUNTS)
.insert_or_ignore([values! { comment_id: id, reaction: reaction, count: 0 }])
.await?;
db::table(COUNTS)
.filter(col("comment_id").eq(id) & col("reaction").eq(reaction))
.update(values! { count: col("count") + by })
.await?;
Ok(())
}