1use std::collections::{BTreeMap, HashMap};
4
5use laravel::db::{self, col, values};
6use laravel::model::model;
7use laravel::time::Timestamp;
8
9use crate::error::CommentError;
10use crate::events::{ReactionAdded, ReactionRemoved};
11use crate::model::CommentModel;
12use crate::ops;
13use crate::status::Visibility;
14
15const REACTIONS: &str = "comment_reactions";
16const COUNTS: &str = "comment_reaction_counts";
17
18#[model(table = "comment_reactions")]
20pub struct CommentReaction {
21 pub id: i64,
22 pub comment_id: i64,
23 pub user_id: i64,
24 pub reaction: String,
25 pub created_at: Option<Timestamp>,
26}
27
28pub(crate) async fn react<C: CommentModel>(comment: &C, user_id: i64, reaction: &str) -> laravel::Result<bool> {
29 check(comment, reaction)?;
30 let id = comment.row().id;
31 let added = db::transaction_with_attempts(ops::ATTEMPTS, async |_| {
32 lock::<C>(id).await?;
33 add::<C>(id, user_id, reaction).await
34 })
35 .await?;
36 if added {
37 dispatch_added(comment, user_id, reaction).await?;
38 }
39 Ok(added)
40}
41
42pub(crate) async fn unreact<C: CommentModel>(comment: &C, user_id: i64, reaction: &str) -> laravel::Result<bool> {
43 let id = comment.row().id;
44 let removed = db::transaction_with_attempts(ops::ATTEMPTS, async |_| {
45 lock::<C>(id).await?;
46 take_back::<C>(id, user_id, reaction).await
47 })
48 .await?;
49 if removed {
50 ReactionRemoved {
51 comment_id: id,
52 commentable_type: comment.row().commentable_type.name().to_owned(),
53 commentable_id: comment.row().commentable_id,
54 user_id,
55 reaction: reaction.to_owned(),
56 }
57 .dispatch()
58 .await?;
59 }
60 Ok(removed)
61}
62
63pub(crate) async fn toggle<C: CommentModel>(comment: &C, user_id: i64, reaction: &str) -> laravel::Result<bool> {
64 check(comment, reaction)?;
65 let id = comment.row().id;
66 let added = db::transaction_with_attempts(ops::ATTEMPTS, async |_| {
67 lock::<C>(id).await?;
68 if add::<C>(id, user_id, reaction).await? {
69 return Ok(true);
70 }
71 take_back::<C>(id, user_id, reaction).await?;
72 Ok(false)
73 })
74 .await?;
75 if added {
76 dispatch_added(comment, user_id, reaction).await?;
77 } else {
78 ReactionRemoved {
79 comment_id: id,
80 commentable_type: comment.row().commentable_type.name().to_owned(),
81 commentable_id: comment.row().commentable_id,
82 user_id,
83 reaction: reaction.to_owned(),
84 }
85 .dispatch()
86 .await?;
87 }
88 Ok(added)
89}
90
91pub async fn reaction_counts(ids: &[i64]) -> laravel::Result<HashMap<i64, BTreeMap<String, i64>>> {
97 let mut counts: HashMap<i64, BTreeMap<String, i64>> = HashMap::new();
98 if ids.is_empty() {
99 return Ok(counts);
100 }
101 let rows: Vec<(i64, String, i64)> = db::table(COUNTS)
102 .select(["comment_id", "reaction", "count"])
103 .filter(col("comment_id").is_in(ids) & col("count").gt(0))
104 .get()
105 .await?;
106 for (comment_id, reaction, count) in rows {
107 counts.entry(comment_id).or_default().insert(reaction, count);
108 }
109 Ok(counts)
110}
111
112pub async fn reactions_of(user_id: i64, ids: &[i64]) -> laravel::Result<HashMap<i64, Vec<String>>> {
119 let mut mine: HashMap<i64, Vec<String>> = HashMap::new();
120 if ids.is_empty() {
121 return Ok(mine);
122 }
123 let rows = CommentReaction::query()
124 .filter(CommentReaction::user_id.eq(user_id) & CommentReaction::comment_id.is_in(ids))
125 .order_by(CommentReaction::reaction.asc())
126 .get()
127 .await?;
128 for row in rows {
129 mine.entry(row.comment_id).or_default().push(row.reaction);
130 }
131 Ok(mine)
132}
133
134fn check<C: CommentModel>(comment: &C, reaction: &str) -> Result<(), CommentError> {
135 if !ops::config().reactions.iter().any(|allowed| allowed == reaction) {
136 return Err(CommentError::UnknownReaction {
137 reaction: reaction.to_owned(),
138 });
139 }
140 let id = comment.row().id;
141 match comment.visibility() {
142 Visibility::Visible => Ok(()),
143 Visibility::Deleted => Err(CommentError::Deleted { id }),
144 Visibility::Hidden => Err(CommentError::NotApproved { id }),
145 }
146}
147
148async fn lock<C: CommentModel>(id: i64) -> laravel::Result<()> {
153 C::new_query()
154 .filter(C::META.key.eq(id))
155 .lock_for_update()
156 .first()
157 .await?
158 .ok_or(CommentError::NotFound { id })?;
159 Ok(())
160}
161
162async fn add<C: CommentModel>(id: i64, user_id: i64, reaction: &str) -> laravel::Result<bool> {
166 let now = laravel::now().timestamp();
167 let inserted = db::table(REACTIONS)
168 .insert_or_ignore([values! { comment_id: id, user_id: user_id, reaction: reaction, created_at: now }])
169 .await?;
170 if inserted == 0 {
171 return Ok(false);
172 }
173 count(id, reaction, 1).await?;
174 ops::bump(id, C::COLUMNS.reactions_count, 1).await?;
175 Ok(true)
176}
177
178async fn take_back<C: CommentModel>(id: i64, user_id: i64, reaction: &str) -> laravel::Result<bool> {
179 let deleted = CommentReaction::query()
180 .filter(
181 CommentReaction::comment_id.eq(id)
182 & CommentReaction::user_id.eq(user_id)
183 & CommentReaction::reaction.eq(reaction),
184 )
185 .delete()
186 .await?;
187 if deleted == 0 {
188 return Ok(false);
189 }
190 count(id, reaction, -1).await?;
191 ops::bump(id, C::COLUMNS.reactions_count, -1).await?;
192 Ok(true)
193}
194
195async fn dispatch_added<C: CommentModel>(comment: &C, user_id: i64, reaction: &str) -> laravel::Result<()> {
196 let row = comment.row();
197 ReactionAdded {
198 comment_id: row.id,
199 commentable_type: row.commentable_type.name().to_owned(),
200 commentable_id: row.commentable_id,
201 user_id,
202 reaction: reaction.to_owned(),
203 }
204 .dispatch()
205 .await
206}
207
208async fn count(id: i64, reaction: &str, by: i64) -> laravel::Result<()> {
210 db::table(COUNTS)
211 .insert_or_ignore([values! { comment_id: id, reaction: reaction, count: 0 }])
212 .await?;
213 db::table(COUNTS)
214 .filter(col("comment_id").eq(id) & col("reaction").eq(reaction))
215 .update(values! { count: col("count") + by })
216 .await?;
217 Ok(())
218}