Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430use 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<Vec<PostRecord>> { 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<usize>> = 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<usize>], memo: &mut HashMap<usize, bool>, visiting: &mut HashSet<usize>,) -> 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<usize>], lengths: &mut HashMap<usize, usize>,) -> 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<usize>], memo: &mut HashMap<usize, usize>,) -> 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<String> { 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<String> { 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, Quote>,) -> 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<String, Quote>, depth: usize, seen: &mut HashSet<String>,) -> Vec<String> { 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")]; }
tracing::debug!(kind, "ignoring an embed shape longread does not render"); Vec::new()}
fn render_quote_ref( uri: &str, quotes: &HashMap<String, Quote>, depth: usize, seen: &mut HashSet<String>,) -> Vec<String> { 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", bsky_url(uri))]}
fn render_quote( quote: &Quote, quotes: &HashMap<String, Quote>, depth: usize, seen: &mut HashSet<String>,) -> Vec<String> { 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")];
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<String> { 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!( "", pds.trim_end_matches('/') )) }) .collect()}
fn external_lines(embed: &Value) -> Vec<String> { 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")]}
fn single_line(text: &str) -> String { text.replace(['\n', '\r'], " ")}