use std::collections::{HashMap, HashSet}; use std::io::Write; use std::path::Path; use crate::api::Api; use crate::model::{PostRecord, Quote, ThreadAuthor}; use crate::render::{ POST_COLLECTION, ancestors_resolved, build_path, parse_target, quote_uris_in_embed, render_markdown, thread_quote_uris, }; use anyhow::Result; pub async fn run(api: &Api, target: &str, out: Option<&Path>) -> Result<()> { let (actor, rkey) = parse_target(target)?; let identity = api.identity(&actor).await?; if api.opted_out(&identity).await? { return Ok(()); } let target_uri = format!("at://{}/{POST_COLLECTION}/{rkey}", identity.did); let posts = fetch_thread_records(api, &identity, &target_uri).await?; let path = build_path(&posts, &identity.did, &target_uri)?; let quotes = fetch_quotes(api, &path).await?; let author = ThreadAuthor { did: identity.did.clone(), handle: identity.handle.clone(), pds: identity.pds.clone(), }; let markdown = render_markdown(&author, &path, "es); match out { Some(path) => { if let Some(parent) = path .parent() .filter(|parent| !parent.as_os_str().is_empty()) { std::fs::create_dir_all(parent)?; } std::fs::write(path, markdown)?; } None => { let mut stdout = std::io::stdout().lock(); stdout.write_all(markdown.as_bytes())?; } } Ok(()) } async fn fetch_thread_records( api: &Api, identity: &crate::api::Identity, target_uri: &str, ) -> Result> { let mut posts: Vec = Vec::new(); let mut cursor: Option = None; let mut found_target = false; loop { let page = api .list_records( &identity.pds, &identity.did, POST_COLLECTION, cursor.as_deref(), 100, ) .await?; for record in page.records { let post = PostRecord::from_repo(record)?; if post.uri == target_uri { found_target = true; } posts.push(post); } if found_target && ancestors_resolved(&posts, &identity.did, target_uri) { break; } match page.cursor { Some(next) if !next.is_empty() => cursor = Some(next), _ => break, } } if !found_target { anyhow::bail!("{target_uri} is not in the author's post records"); } Ok(posts) } async fn fetch_quotes(api: &Api, path: &[PostRecord]) -> Result> { let mut quotes = HashMap::new(); let mut pending = thread_quote_uris(path); let mut seen: HashSet = pending.iter().cloned().collect(); for _ in 0..2 { if pending.is_empty() { break; } let fetched = match api.quotes(&pending).await { Ok(fetched) => fetched, Err(error) => { tracing::warn!(%error, "could not fetch quoted posts; linking instead"); break; } }; let mut next = Vec::new(); for (uri, quote) in fetched { if let Some(embed) = "e.embed { for child in quote_uris_in_embed(embed) { if seen.insert(child.clone()) { next.push(child); } } } quotes.insert(uri, quote); } pending = next; } Ok(quotes) }