use std::collections::{HashMap, HashSet}; use anyhow::{Context, Result, anyhow, bail}; use serde_json::Value; use url::Url; use crate::model::{PostRecord, Quote, ThreadAuthor, bsky_url, uri_author}; use crate::text::{first_line, render_facets, strip_thread_counter}; pub const POST_COLLECTION: &str = "app.bsky.feed.post"; pub const MAX_QUOTE_DEPTH: usize = 2; pub fn parse_target(target: &str) -> Result<(String, String)> { if target.starts_with("at://") { return parse_at_uri(target); } let candidate = if target.starts_with("bsky.app/") { format!("https://{target}") } else { target.to_string() }; let url = Url::parse(&candidate).with_context(|| format!("reading {target} as a URL"))?; let segments: Vec<&str> = url .path_segments() .map(|segments| segments.filter(|segment| !segment.is_empty()).collect()) .unwrap_or_default(); match segments.as_slice() { ["profile", actor, "post", rkey] => Ok(((*actor).to_string(), (*rkey).to_string())), _ => bail!("{target} is not a bsky.app post URL"), } } fn parse_at_uri(uri: &str) -> Result<(String, String)> { let rest = uri .strip_prefix("at://") .ok_or_else(|| anyhow!("{uri} is not an at-uri"))?; let mut parts = rest.split('/'); let author = parts.next().filter(|part| !part.is_empty()); let collection = parts.next(); let rkey = parts.next().filter(|part| !part.is_empty()); match (author, collection, rkey) { (Some(author), Some(POST_COLLECTION), Some(rkey)) => { Ok((author.to_string(), rkey.to_string())) } _ => bail!("{uri} is not an app.bsky.feed.post at-uri"), } } /// True when every author-owned ancestor of the target has been read. pub fn ancestors_resolved(posts: &[PostRecord], author: &str, target_uri: &str) -> bool { let index: HashMap<&str, &PostRecord> = posts.iter().map(|post| (post.uri.as_str(), post)).collect(); let mut current = target_uri; let mut visited = HashSet::new(); while visited.insert(current) { let Some(post) = index.get(current) else { return false; }; match post.parent_uri() { None => return true, Some(parent) if uri_author(parent) != Some(author) => return true, Some(parent) => { if !index.contains_key(parent) { return false; } current = parent; } } } true } pub fn build_path(posts: &[PostRecord], author: &str, target_uri: &str) -> Result> { let index: HashMap<&str, usize> = posts .iter() .enumerate() .map(|(position, post)| (post.uri.as_str(), position)) .collect(); let target = *index .get(target_uri) .ok_or_else(|| anyhow!("{target_uri} was not read from the author's repo"))?; 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 root = target; let mut seen = HashSet::new(); while seen.insert(root) { let Some(parent) = posts[root].parent_uri() else { break; }; if uri_author(parent) != Some(author) { break; } let Some(&parent_position) = index.get(parent) else { break; }; root = parent_position; } let mut lengths = HashMap::new(); let mut contains = HashMap::new(); let mut path = Vec::new(); let mut current = root; let mut visited = HashSet::new(); loop { path.push(posts[current].clone()); if !visited.insert(current) { break; } let options = &children[current]; let next = match options.as_slice() { [] => break, [only] => *only, many => many .iter() .copied() .find(|&child| { subtree_contains(child, target, &children, &mut contains, &mut HashSet::new()) }) .unwrap_or_else(|| best_child(many, posts, &children, &mut lengths)), }; current = next; } Ok(path) } fn subtree_contains( position: usize, target: usize, children: &[Vec], memo: &mut HashMap, visiting: &mut HashSet, ) -> bool { if position == target { return true; } if let Some(found) = memo.get(&position) { return *found; } if !visiting.insert(position) { return false; } let found = children[position] .iter() .any(|&child| subtree_contains(child, target, children, memo, visiting)); visiting.remove(&position); memo.insert(position, found); found } fn best_child( options: &[usize], posts: &[PostRecord], children: &[Vec], lengths: &mut HashMap, ) -> usize { let mut best = options[0]; let mut best_length = longest_length(best, children, lengths); for &option in &options[1..] { let length = longest_length(option, children, lengths); if length > best_length || (length == best_length && posts[option].created_at < posts[best].created_at) { best = option; best_length = length; } } best } fn longest_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| longest_length(child, children, memo)) .max() .unwrap_or(0); memo.insert(position, length); length } /// Every quote at-uri referenced by the thread, in first-seen order. pub fn thread_quote_uris(posts: &[PostRecord]) -> Vec { let mut seen = HashSet::new(); let mut uris = Vec::new(); for post in posts { if let Some(embed) = &post.value.embed { for uri in quote_uris_in_embed(embed) { if seen.insert(uri.clone()) { uris.push(uri); } } } } uris } pub fn quote_uris_in_embed(embed: &Value) -> Vec { let kind = embed.get("$type").and_then(Value::as_str).unwrap_or(""); let mut uris = Vec::new(); if kind.starts_with("app.bsky.embed.recordWithMedia") { if let Some(uri) = embed.pointer("/record/record/uri").and_then(Value::as_str) { uris.push(uri.to_string()); } else if let Some(uri) = embed.pointer("/record/uri").and_then(Value::as_str) { uris.push(uri.to_string()); } } else if kind.starts_with("app.bsky.embed.record") && let Some(uri) = embed.pointer("/record/uri").and_then(Value::as_str) { uris.push(uri.to_string()); } uris } pub fn render_markdown( identity: &ThreadAuthor, path: &[PostRecord], quotes: &HashMap, ) -> String { let root = &path[0]; let root_text = strip_thread_counter(&root.value.text); let title = first_line(&root_text, 80); let date = root.created_at.format("%Y-%m-%d"); let source = bsky_url(&root.uri); let mut markdown = String::new(); markdown.push_str("---\n"); markdown.push_str(&format!("title: {}\n", yaml_quote(&title))); markdown.push_str(&format!("date: {date}\n")); markdown.push_str(&format!("source: {source}\n")); markdown.push_str(&format!("author: @{}\n", identity.handle)); markdown.push_str("---\n\n"); for (position, post) in path.iter().enumerate() { if position > 0 { markdown.push('\n'); } let text = strip_thread_counter(&post.value.text); markdown.push_str(&render_facets(&text, &post.value.facets)); if let Some(embed) = &post.value.embed { let post_url = bsky_url(&post.uri); let mut seen = HashSet::new(); for line in render_embed( embed, &identity.pds, &identity.did, &post_url, quotes, 0, &mut seen, ) { markdown.push_str("\n\n"); markdown.push_str(&line); } } markdown.push('\n'); } markdown } fn yaml_quote(text: &str) -> String { format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\"")) } fn render_embed( embed: &Value, pds: &str, did: &str, post_url: &str, quotes: &HashMap, depth: usize, seen: &mut HashSet, ) -> Vec { let kind = embed.get("$type").and_then(Value::as_str).unwrap_or(""); if kind.starts_with("app.bsky.embed.images") { return image_lines(embed, pds, did); } if kind.starts_with("app.bsky.embed.external") { return external_lines(embed); } if kind.starts_with("app.bsky.embed.recordWithMedia") { let mut lines = Vec::new(); if let Some(uri) = embed.pointer("/record/record/uri").and_then(Value::as_str) { lines.extend(render_quote_ref(uri, quotes, depth, seen)); } else if let Some(uri) = embed.pointer("/record/uri").and_then(Value::as_str) { lines.extend(render_quote_ref(uri, quotes, depth, seen)); } if let Some(media) = embed.get("media") { lines.extend(render_embed(media, pds, did, post_url, quotes, depth, seen)); } return lines; } if kind.starts_with("app.bsky.embed.record") { if let Some(uri) = embed.pointer("/record/uri").and_then(Value::as_str) { return render_quote_ref(uri, quotes, depth, seen); } return Vec::new(); } if kind.starts_with("app.bsky.embed.video") { return vec![format!("[Video]({post_url})")]; } tracing::debug!(kind, "ignoring an embed shape longread does not render"); Vec::new() } fn render_quote_ref( uri: &str, quotes: &HashMap, depth: usize, seen: &mut HashSet, ) -> Vec { if depth < MAX_QUOTE_DEPTH && let Some(quote) = quotes.get(uri) && seen.insert(uri.to_string()) { return render_quote(quote, quotes, depth + 1, seen); } vec![format!("> [Quoted post]({})", bsky_url(uri))] } fn render_quote( quote: &Quote, quotes: &HashMap, depth: usize, seen: &mut HashSet, ) -> Vec { let url = bsky_url("e.uri); let handle = if quote.author.handle.is_empty() { quote.author.did.as_str() } else { quote.author.handle.as_str() }; let mut lines = vec![format!("> **@{handle}** ยท [post]({url})")]; let text = render_facets("e.text, "e.facets); if !text.trim().is_empty() { lines.push(">".to_string()); for line in text.lines() { lines.push(prefix_quote(line)); } } if let Some(embed) = "e.embed { let inner = render_embed( embed, "e.author.pds, "e.author.did, &url, quotes, depth, seen, ); if !inner.is_empty() { lines.push(">".to_string()); for line in inner { for part in line.lines() { lines.push(prefix_quote(part)); } } } } lines } fn prefix_quote(line: &str) -> String { if line.is_empty() { ">".to_string() } else { format!("> {line}") } } fn image_lines(embed: &Value, pds: &str, did: &str) -> Vec { let Some(images) = embed.get("images").and_then(Value::as_array) else { return Vec::new(); }; images .iter() .filter_map(|image| { let cid = image .pointer("/image/ref/$link") .and_then(Value::as_str) .or_else(|| image.pointer("/image/ref").and_then(Value::as_str)) .or_else(|| image.pointer("/image/cid").and_then(Value::as_str))?; let alt = single_line(image.get("alt").and_then(Value::as_str).unwrap_or("")); Some(format!( "![{alt}]({}/xrpc/com.atproto.sync.getBlob?did={did}&cid={cid})", pds.trim_end_matches('/') )) }) .collect() } fn external_lines(embed: &Value) -> Vec { let Some(external) = embed.get("external") else { return Vec::new(); }; let Some(uri) = external.get("uri").and_then(Value::as_str) else { return Vec::new(); }; let title = external .get("title") .and_then(Value::as_str) .filter(|title| !title.is_empty()) .map(single_line) .unwrap_or_else(|| uri.to_string()); vec![format!("[{title}]({uri})")] } fn single_line(text: &str) -> String { text.replace(['\n', '\r'], " ") }