use std::collections::{HashMap, HashSet}; use chrono::{DateTime, Utc}; use serde_json::Value; use crate::craft; use crate::model::{ AuthorRow, Engagement, Fork, ForkOption, PostRecord, ThreadRow, bsky_url, label_state, self_label_values, }; use crate::text::{grapheme_count, strip_thread_counter}; use crate::topics; #[derive(Debug, Clone)] pub struct Candidate { pub root_uri: String, pub root_created_at: DateTime, pub posts: Vec, pub graphemes: usize, pub dropped_branches: usize, pub forks: Vec, } impl Candidate { pub fn post_count(&self) -> usize { self.posts.len() } } /// The absolute length-and-engagement part of the score. pub fn score(graphemes: usize, likes: i64, reposts: i64, quotes: i64) -> f64 { let engagement = 1.0 + likes as f64 + 2.0 * reposts as f64 + 3.0 * quotes as f64; graphemes as f64 * (1.0 + engagement.ln()) } /// Turn candidates into ranked rows, dropping published threads unless asked. pub fn build_rows( author: &AuthorRow, pds: &str, candidates: Vec, engagement: &HashMap, published: &HashSet, include_published: bool, author_median: Option, ) -> Vec { let mut rows = Vec::with_capacity(candidates.len()); for candidate in candidates { let is_published = published.contains(&candidate.root_uri); if is_published && !include_published { continue; } let parts = engagement .get(&candidate.root_uri) .cloned() .unwrap_or_default(); let topics = topics::labels(&candidate.posts); let craft = craft::analyze(&candidate.posts); let root = &candidate.posts[0]; let root_text = strip_thread_counter(&root.value.text); let root_thumb = root_thumbnail(root.value.embed.as_ref(), pds, &author.did); let reach_score = score( candidate.graphemes, parts.likes, parts.reposts, parts.quotes, ); let relative = author_median.map(|median| (parts.index() as f64 + 1.0) / (median + 1.0)); let relative_factor = relative .map(|value| (1.0 + 0.25 * (value - 1.0)).clamp(0.75, 1.25)) .unwrap_or(1.0); let score = reach_score * relative_factor * (0.75 + 0.5 * craft.score); let mut labels = root .value .labels .as_ref() .map(self_label_values) .unwrap_or_default(); labels.extend(parts.labels.iter().cloned()); labels.sort(); labels.dedup(); let label_state = label_state(&labels); rows.push(ThreadRow { author: author.clone(), root_uri: candidate.root_uri.clone(), root_date: candidate.root_created_at.format("%Y-%m-%d").to_string(), post_count: candidate.post_count(), graphemes: candidate.graphemes, likes: parts.likes, reposts: parts.reposts, quotes: parts.quotes, replies: parts.replies, dropped_branches: candidate.dropped_branches, reach_score, relative_factor, author_median, cohort_percentile: 0.0, craft, score, published: is_published, labels, label_state, forks: candidate.forks, topics, root_text, root_thumb, url: bsky_url(&candidate.root_uri), }); } ThreadRow::sort_best_first(&mut rows); let count = rows.len(); for (index, row) in rows.iter_mut().enumerate() { row.cohort_percentile = if count <= 1 { 100.0 } else { 100.0 * (count - 1 - index) as f64 / (count - 1) as f64 }; } rows } /// The median engagement index of the author's sampled posts. pub fn median_engagement( engagement: &HashMap, sample: &[String], ) -> Option { let mut values: Vec = sample .iter() .filter_map(|uri| engagement.get(uri)) .map(|entry| entry.index() as f64) .collect(); if values.is_empty() { return None; } values.sort_by(|left, right| left.total_cmp(right)); let middle = values.len() / 2; Some(if values.len().is_multiple_of(2) { (values[middle - 1] + values[middle]) / 2.0 } else { values[middle] }) } /// Build every chain that meets both length thresholds. pub fn candidates( posts: &[PostRecord], min_posts: usize, min_graphemes: usize, include_replies: bool, ) -> Vec { if posts.is_empty() { return Vec::new(); } let index: HashMap<&str, usize> = posts .iter() .enumerate() .map(|(position, post)| (post.uri.as_str(), position)) .collect(); let mut children: Vec> = vec![Vec::new(); posts.len()]; for (position, post) in posts.iter().enumerate() { if let Some(parent) = post.parent_uri() && let Some(&parent_position) = index.get(parent) { children[parent_position].push(position); } } let starts = posts .iter() .enumerate() .filter_map(|(position, post)| match post.parent_uri() { None => Some(position), Some(parent) => (include_replies && !index.contains_key(parent)).then_some(position), }); let mut memo = HashMap::new(); let mut visiting = HashSet::new(); let mut candidates = Vec::new(); for start in starts { let (path, dropped_branches) = longest_from(start, posts, &children, &mut memo, &mut visiting); let graphemes: usize = path .iter() .map(|&position| grapheme_count(&posts[position].value.text)) .sum(); if path.len() < min_posts || graphemes < min_graphemes { continue; } let thread_posts: Vec = path.into_iter().map(|index| posts[index].clone()).collect(); let root = &thread_posts[0]; let forks = forks_for_path(posts, &thread_posts); candidates.push(Candidate { root_uri: root.uri.clone(), root_created_at: root.created_at, posts: thread_posts, graphemes, dropped_branches, forks, }); } candidates } fn longest_from( position: usize, posts: &[PostRecord], children: &[Vec], memo: &mut HashMap, usize)>, visiting: &mut HashSet, ) -> (Vec, usize) { if let Some(found) = memo.get(&position) { return found.clone(); } if !visiting.insert(position) { return (vec![position], 0); } let child_count = children[position].len(); let mut best: Option<(usize, DateTime, Vec, usize)> = None; for &child in &children[position] { let (path, dropped) = longest_from(child, posts, children, memo, visiting); let better = match &best { None => true, Some((best_length, best_created, _, _)) => { path.len() > *best_length || (path.len() == *best_length && posts[child].created_at < *best_created) } }; if better { best = Some((path.len(), posts[child].created_at, path, dropped)); } } visiting.remove(&position); let result = match best { Some((_, _, child_path, dropped)) => { let mut path = Vec::with_capacity(child_path.len() + 1); path.push(position); path.extend(child_path); (path, dropped + child_count.saturating_sub(1)) } None => (vec![position], 0), }; memo.insert(position, result.clone()); result } /// The forks along a chosen path, with every alternative branch. pub fn forks_for_path(posts: &[PostRecord], path: &[PostRecord]) -> Vec { if path.len() < 2 { return Vec::new(); } let index: HashMap<&str, usize> = posts .iter() .enumerate() .map(|(position, post)| (post.uri.as_str(), position)) .collect(); let mut children: Vec> = vec![Vec::new(); posts.len()]; for (position, post) in posts.iter().enumerate() { if let Some(parent) = post.parent_uri() && let Some(&parent_position) = index.get(parent) { children[parent_position].push(position); } } let mut lengths = HashMap::new(); let mut forks = Vec::new(); for pair in path.windows(2) { let (parent, chosen) = (&pair[0], &pair[1]); let Some(&parent_position) = index.get(parent.uri.as_str()) else { continue; }; if children[parent_position].len() < 2 { continue; } let chosen_position = index.get(chosen.uri.as_str()).copied(); let mut options: Vec = children[parent_position] .iter() .map(|&child| { let post = &posts[child]; ForkOption { uri: post.uri.clone(), posts: chain_length(child, &children, &mut lengths), date: post.created_at.format("%Y-%m-%d").to_string(), snippet: snippet(post), chosen: Some(child) == chosen_position, } }) .collect(); options.sort_by(|left, right| { right .posts .cmp(&left.posts) .then_with(|| left.date.cmp(&right.date)) }); forks.push(Fork { parent_uri: parent.uri.clone(), parent_snippet: snippet(parent), options, }); } forks } fn chain_length( position: usize, children: &[Vec], memo: &mut HashMap, ) -> usize { if let Some(found) = memo.get(&position) { return *found; } let length = 1 + children[position] .iter() .map(|&child| chain_length(child, children, memo)) .max() .unwrap_or(0); memo.insert(position, length); length } fn snippet(post: &PostRecord) -> String { let text = strip_thread_counter(&post.value.text); let mut snippet: String = text.chars().take(160).collect(); if text.chars().count() > 160 { snippet.push('…'); } snippet } fn root_thumbnail(embed: Option<&Value>, pds: &str, did: &str) -> Option { let embed = embed?; let kind = embed.get("$type").and_then(Value::as_str).unwrap_or(""); let cid = if kind.starts_with("app.bsky.embed.images") { embed.pointer("/images/0/image/ref/$link") } else if kind.starts_with("app.bsky.embed.recordWithMedia") { return root_thumbnail(embed.get("media"), pds, did); } else if kind.starts_with("app.bsky.embed.external") { embed.pointer("/external/thumb/ref/$link") } else { None }?; let cid = cid.as_str()?; Some(format!( "{}/xrpc/com.atproto.sync.getBlob?did={did}&cid={cid}", pds.trim_end_matches('/') )) }