1use std::cmp::Ordering;
4use std::collections::{BTreeMap, HashMap};
5
6use laravel::db::{Builder, Condition};
7use laravel::model::Morph;
8use serde::Serialize;
9
10use crate::author::Commenter;
11use crate::model::CommentModel;
12use crate::reactions::{reaction_counts, reactions_of};
13use crate::status::Visibility;
14
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
17#[serde(rename_all = "snake_case")]
18pub enum Sort {
19 #[default]
21 Oldest,
22 Newest,
24 Best,
26}
27
28#[must_use]
49pub struct Threads<C: CommentModel> {
50 source: Source<C>,
51 sort: Sort,
52 page: u64,
53 per_page: u64,
54 depth: Option<i64>,
55 viewer: Option<i64>,
56}
57
58enum Source<C: CommentModel> {
59 On(C::Commentable),
60 Thread(String),
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
65pub struct Location {
66 pub page: u64,
68 pub thread_id: i64,
70 pub comment_id: i64,
72 pub cut_at: Option<i64>,
75}
76
77#[derive(Debug, Serialize)]
79#[serde(bound = "C: Serialize")]
80pub struct ThreadPage<C> {
81 pub threads: Vec<ThreadNode<C>>,
83 pub page: u64,
85 pub per_page: u64,
87 pub total: u64,
89 pub has_more: bool,
91}
92
93#[derive(Debug, Serialize)]
95#[serde(bound = "C: Serialize")]
96pub struct ThreadNode<C> {
97 pub id: i64,
99 pub visibility: Visibility,
101 pub comment: Option<C>,
104 #[cfg(feature = "markdown")]
106 pub body_html: Option<String>,
107 pub reactions: BTreeMap<String, i64>,
109 pub viewer_reactions: Vec<String>,
111 pub replies: Vec<ThreadNode<C>>,
113 pub more_replies: i64,
115}
116
117impl<C: CommentModel> Threads<C> {
118 pub(crate) fn on(on: C::Commentable) -> Self {
119 Self::new(Source::On(on))
120 }
121
122 pub(crate) fn thread(thread: String) -> Self {
123 Self::new(Source::Thread(thread))
124 }
125
126 fn new(source: Source<C>) -> Self {
127 Self {
128 source,
129 sort: Sort::default(),
130 page: 1,
131 per_page: 20,
132 depth: None,
133 viewer: None,
134 }
135 }
136
137 pub fn sort(mut self, sort: Sort) -> Self {
139 self.sort = sort;
140 self
141 }
142
143 pub fn page(mut self, page: u64) -> Self {
145 self.page = page.max(1);
146 self
147 }
148
149 pub fn per_page(mut self, per_page: u64) -> Self {
151 self.per_page = per_page.max(1);
152 self
153 }
154
155 pub fn depth(mut self, depth: i64) -> Self {
158 self.depth = Some(depth.max(0));
159 self
160 }
161
162 pub fn viewer(mut self, viewer: &C::Author) -> Self {
164 self.viewer = Some(viewer.commenter_id());
165 self
166 }
167
168 pub async fn locate(&self, comment: &C) -> laravel::Result<Option<Location>> {
197 let columns = C::COLUMNS;
198 let key = C::META.key;
199 let row = comment.row();
200 let Some(root) = C::new_query()
201 .filter(self.roots_condition() & columns.thread.eq(row.thread.to_owned()))
202 .first()
203 .await?
204 else {
205 return Ok(None);
206 };
207
208 let top = root.row();
209 let (created_at, id, reactions) = (top.created_at, top.id, top.reactions_count);
210 let same_time = columns.created_at.eq(created_at);
211 let before = match self.sort {
212 Sort::Oldest => columns.created_at.lt(created_at) | (same_time & key.lt(id)),
213 Sort::Newest => columns.created_at.gt(created_at) | (same_time & key.gt(id)),
214 Sort::Best => {
215 columns.reactions_count.gt(reactions)
216 | (columns.reactions_count.eq(reactions)
217 & (columns.created_at.lt(created_at) | (columns.created_at.eq(created_at) & key.lt(id))))
218 }
219 };
220 let ahead = C::new_query().filter(self.roots_condition() & before).count().await?;
221
222 let cut_at = match (self.depth, C::depth_column()) {
223 (Some(depth), Some(column)) if row.depth > depth => comment
224 .ancestors()
225 .filter(column.eq(depth))
226 .first()
227 .await?
228 .map(|cut| cut.row().id),
229 _ => None,
230 };
231 Ok(Some(Location {
232 page: ahead / self.per_page + 1,
233 thread_id: id,
234 comment_id: row.id,
235 cut_at,
236 }))
237 }
238
239 fn roots(&self) -> Builder<C> {
241 C::new_query().filter(self.roots_condition())
242 }
243
244 fn roots_condition(&self) -> Condition {
245 let columns = C::COLUMNS;
246 match &self.source {
247 Source::On(on) => {
248 let shown = C::new_query()
252 .filter(
253 columns.commentable_type.eq(on.morph())
254 & columns.commentable_id.eq(*on.key())
255 & C::where_visible(),
256 )
257 .select_column(columns.thread);
258 columns.commentable_type.eq(on.morph())
259 & columns.commentable_id.eq(*on.key())
260 & C::where_root()
261 & columns.thread.is_in(shown)
262 }
263 Source::Thread(thread) => columns.thread.eq(thread.clone()) & C::where_root(),
264 }
265 }
266
267 pub async fn get(self) -> laravel::Result<ThreadPage<C>> {
275 let columns = C::COLUMNS;
276 let roots = self.roots();
277 let total = roots.count().await?;
278 let offset = (self.page - 1) * self.per_page;
279 let roots = C::with_author(order(roots, self.sort))
280 .offset(offset)
281 .limit(self.per_page)
282 .get()
283 .await?;
284
285 let threads: Vec<String> = roots.iter().map(|root| root.row().thread.to_owned()).collect();
286 let mut replies = C::new_query().filter(columns.thread.is_in(threads) & C::where_has_parent());
287 if let (Some(depth), Some(column)) = (self.depth, C::depth_column()) {
288 replies = replies.filter(column.le(depth));
289 }
290 let replies = if roots.is_empty() {
291 Vec::new()
292 } else {
293 C::with_author(replies.order_by(C::lft_column().asc())).get().await?
294 };
295
296 let ids: Vec<i64> = roots.iter().chain(&replies).map(|comment| comment.row().id).collect();
297 let mut counts = reaction_counts(&ids).await?;
298 let mut mine = match self.viewer {
299 Some(viewer) => reactions_of(viewer, &ids).await?,
300 None => HashMap::new(),
301 };
302
303 let mut children: HashMap<i64, Vec<C>> = HashMap::new();
304 for reply in replies {
305 if let Some(parent) = reply.row().parent_id {
306 children.entry(parent).or_default().push(reply);
307 }
308 }
309 let arrange = Arrange {
310 sort: self.sort,
311 depth: self.depth,
312 };
313 let threads = roots
314 .into_iter()
315 .filter_map(|root| arrange.node(root, &mut children, &mut counts, &mut mine))
316 .collect();
317
318 Ok(ThreadPage {
319 threads,
320 page: self.page,
321 per_page: self.per_page,
322 total,
323 has_more: offset + self.per_page < total,
324 })
325 }
326}
327
328struct Arrange {
329 sort: Sort,
330 depth: Option<i64>,
331}
332
333impl Arrange {
334 fn node<C: CommentModel>(
337 &self,
338 comment: C,
339 children: &mut HashMap<i64, Vec<C>>,
340 counts: &mut HashMap<i64, BTreeMap<String, i64>>,
341 mine: &mut HashMap<i64, Vec<String>>,
342 ) -> Option<ThreadNode<C>> {
343 let row = comment.row();
344 let (id, depth, replies_count) = (row.id, row.depth, row.replies_count);
345 let mut below = children.remove(&id).unwrap_or_default();
346 below.sort_by(|a, b| compare(a, b, self.sort));
347 let replies: Vec<ThreadNode<C>> = below
348 .into_iter()
349 .filter_map(|child| self.node(child, children, counts, mine))
350 .collect();
351
352 let visibility = comment.visibility();
353 if visibility != Visibility::Visible && replies.is_empty() {
354 return None;
355 }
356 let cut_here = self.depth == Some(depth) && comment.descendant_count() > 0;
357 Some(ThreadNode {
358 id,
359 visibility,
360 #[cfg(feature = "markdown")]
361 body_html: (visibility == Visibility::Visible).then(|| comment.body_html()),
362 comment: (visibility == Visibility::Visible).then_some(comment),
363 reactions: counts.remove(&id).unwrap_or_default(),
364 viewer_reactions: mine.remove(&id).unwrap_or_default(),
365 replies,
366 more_replies: if cut_here { replies_count } else { 0 },
367 })
368 }
369}
370
371fn order<C: CommentModel>(query: Builder<C>, sort: Sort) -> Builder<C> {
372 let columns = C::COLUMNS;
373 let key = C::META.key;
374 match sort {
375 Sort::Oldest => query.order_by(columns.created_at.asc()).order_by(key.asc()),
376 Sort::Newest => query.order_by(columns.created_at.desc()).order_by(key.desc()),
377 Sort::Best => query
378 .order_by(columns.reactions_count.desc())
379 .order_by(columns.created_at.asc())
380 .order_by(key.asc()),
381 }
382}
383
384fn compare<C: CommentModel>(a: &C, b: &C, sort: Sort) -> Ordering {
385 let (a, b) = (a.row(), b.row());
386 let oldest = a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id));
387 match sort {
388 Sort::Oldest => oldest,
389 Sort::Newest => oldest.reverse(),
390 Sort::Best => b.reactions_count.cmp(&a.reactions_count).then(oldest),
391 }
392}