use std::collections::HashMap; use std::time::Duration; use anyhow::{Context, Result, anyhow, bail}; use chrono::{DateTime, Utc}; use reqwest::{Client, StatusCode}; use serde_json::Value; use crate::model::{ DidDocument, Engagement, GetFollowsResponse, GetPostsResponse, GetRecordResponse, ListRecordsResponse, PostRecord, PostView, Quote, QuoteAuthor, RepoRecord, has_self_label, view_label_values, }; const PUBLIC_API: &str = "https://public.api.bsky.app"; const PLC_DIRECTORY: &str = "https://plc.directory"; const PAGE_LIMIT: u32 = 100; const POSTS_PER_GET: usize = 25; const MAX_PAGES: usize = 200; #[derive(Debug, Clone)] pub struct Identity { pub did: String, pub handle: String, pub pds: String, } #[derive(Debug, Clone)] pub struct PostPage { pub posts: Vec, pub truncated: bool, } #[derive(Debug, Clone)] pub struct Follow { pub did: String, pub handle: String, } #[derive(Clone)] pub struct Api { client: Client, public_api: String, plc_directory: String, } impl Api { pub fn new() -> Result { let client = Client::builder() .user_agent(concat!("longread/", env!("CARGO_PKG_VERSION"))) .timeout(Duration::from_secs(30)) .build() .context("building the HTTP client")?; Ok(Self { client, public_api: base_url("LONGREAD_PUBLIC_API", PUBLIC_API), plc_directory: base_url("LONGREAD_PLC_DIRECTORY", PLC_DIRECTORY), }) } /// Resolve a handle or DID to its DID, handle and PDS. pub async fn identity(&self, handle_or_did: &str) -> Result { let did = if handle_or_did.starts_with("did:") { handle_or_did.to_string() } else { self.resolve_handle(handle_or_did).await? }; let document = self.did_document(&did).await?; let handle = document .handle() .or_else(|| (!handle_or_did.starts_with("did:")).then(|| handle_or_did.to_string())) .unwrap_or_else(|| did.clone()); let pds = document .pds_endpoint() .ok_or_else(|| anyhow!("{did} has no #atproto_pds service"))? .to_string(); Ok(Identity { did, handle, pds }) } pub async fn resolve_handle(&self, handle: &str) -> Result { let value = self .request_json( &format!( "{}/xrpc/com.atproto.identity.resolveHandle", self.public_api ), &[("handle", handle.to_string())], ) .await?; value .get("did") .and_then(Value::as_str) .map(str::to_string) .ok_or_else(|| anyhow!("resolveHandle({handle}) returned no did")) } pub async fn did_document(&self, did: &str) -> Result { let url = self.did_url(did)?; let value = self.request_json(&url, &[]).await?; serde_json::from_value(value).with_context(|| format!("reading the DID document for {did}")) } fn did_url(&self, did: &str) -> Result { if did.starts_with("did:plc:") { return Ok(format!("{}/{}", self.plc_directory, did)); } if let Some(rest) = did.strip_prefix("did:web:") { let mut parts = rest.split(':'); let host = parts .next() .filter(|host| !host.is_empty()) .ok_or_else(|| anyhow!("{did} names no host"))?; let path: Vec<&str> = parts.filter(|part| !part.is_empty()).collect(); return Ok(if path.is_empty() { format!("https://{host}/.well-known/did.json") } else { format!("https://{host}/{}/did.json", path.join("/")) }); } bail!("unsupported DID method in {did}") } pub async fn list_records( &self, pds: &str, repo: &str, collection: &str, cursor: Option<&str>, limit: u32, ) -> Result { let mut query = vec![ ("repo", repo.to_string()), ("collection", collection.to_string()), ("limit", limit.to_string()), ]; if let Some(cursor) = cursor { query.push(("cursor", cursor.to_string())); } let value = self .request_json( &format!( "{}/xrpc/com.atproto.repo.listRecords", pds.trim_end_matches('/') ), &query, ) .await?; serde_json::from_value(value).context("reading listRecords") } /// Read posts newest first, stopping before the page that crosses `cutoff`. pub async fn fetch_posts_since( &self, identity: &Identity, cutoff: DateTime, ) -> Result { let mut posts = Vec::new(); let mut cursor: Option = None; let mut pages = 0usize; let mut truncated = false; loop { pages += 1; let page = self .list_records( &identity.pds, &identity.did, "app.bsky.feed.post", cursor.as_deref(), PAGE_LIMIT, ) .await?; tracing::debug!( did = %identity.did, records = page.records.len(), cursor = ?page.cursor, "read a page of posts" ); let mut crossed_cutoff = false; for record in page.records { let post = PostRecord::from_repo(record)?; if post.created_at < cutoff { crossed_cutoff = true; } else { posts.push(post); } } if crossed_cutoff { break; } match page.cursor { Some(next) if !next.is_empty() => { if pages >= MAX_PAGES { truncated = true; break; } cursor = Some(next); } _ => break, } } Ok(PostPage { posts, truncated }) } /// The root at-uris of the author's published standard.site documents. pub async fn published_roots(&self, identity: &Identity) -> Result> { let mut roots = Vec::new(); let mut cursor: Option = None; loop { let page = self .list_records( &identity.pds, &identity.did, "site.standard.document", cursor.as_deref(), PAGE_LIMIT, ) .await?; for record in page.records { if let Some(uri) = document_post_uri(&record) { roots.push(uri); } } match page.cursor { Some(next) if !next.is_empty() => cursor = Some(next), _ => break, } } Ok(roots) } /// The author's profile record, or None when there is none. pub async fn profile(&self, identity: &Identity) -> Result> { let value = self .request_json_optional( &format!( "{}/xrpc/com.atproto.repo.getRecord", identity.pds.trim_end_matches('/') ), &[ ("repo", identity.did.clone()), ("collection", "app.bsky.actor.profile".to_string()), ("rkey", "self".to_string()), ], ) .await?; Ok(value.and_then(|value| { serde_json::from_value::(value) .ok() .and_then(|record| record.value) })) } pub async fn opted_out(&self, identity: &Identity) -> Result { let profile = self.profile(identity).await?; Ok(profile .as_ref() .is_some_and(|profile| has_self_label(profile, "!no-unauthenticated"))) } pub async fn get_post_views(&self, uris: &[String]) -> Result> { let mut views = Vec::new(); for batch in uris.chunks(POSTS_PER_GET) { let mut query: Vec<(&str, String)> = Vec::with_capacity(batch.len()); for uri in batch { query.push(("uris", uri.clone())); } let value = self .request_json( &format!("{}/xrpc/app.bsky.feed.getPosts", self.public_api), &query, ) .await?; let response: GetPostsResponse = serde_json::from_value(value).context("reading getPosts")?; views.extend(response.posts); } Ok(views) } pub async fn get_engagement(&self, uris: &[String]) -> Result> { let mut engagement = HashMap::new(); for post in self.get_post_views(uris).await? { engagement.insert( post.uri, Engagement { likes: post.like_count, reposts: post.repost_count, quotes: post.quote_count, replies: post.reply_count, labels: view_label_values(&post.labels), }, ); } Ok(engagement) } /// Fetch quote posts for inline rendering. Opted-out authors are omitted, /// so callers fall back to a plain link. pub async fn quotes(&self, uris: &[String]) -> Result> { let mut quotes = HashMap::new(); let mut pds_by_did: HashMap = HashMap::new(); for view in self.get_post_views(uris).await? { let Some(author) = view.author else { continue; }; if has_self_label(&author.labels, "!no-unauthenticated") || has_self_label(&view.labels, "!no-unauthenticated") { tracing::debug!(uri = %view.uri, "quote author opted out; linking instead"); continue; } let Some(record) = view.record else { continue; }; let pds = if let Some(pds) = pds_by_did.get(&author.did) { pds.clone() } else { match self.identity(&author.did).await { Ok(identity) => { pds_by_did.insert(author.did.clone(), identity.pds.clone()); identity.pds } Err(error) => { tracing::warn!(did = %author.did, %error, "cannot resolve quote author's PDS"); continue; } } }; let handle = if author.handle.is_empty() { author.did.clone() } else { author.handle.clone() }; quotes.insert( view.uri.clone(), Quote { uri: view.uri, author: QuoteAuthor { did: author.did, handle, display_name: author.display_name, avatar: author.avatar, pds, }, text: record.text, facets: record.facets, embed: record.embed, }, ); } Ok(quotes) } pub async fn get_record_value( &self, pds: &str, repo: &str, collection: &str, rkey: &str, ) -> Result> { let value = self .request_json_optional( &format!( "{}/xrpc/com.atproto.repo.getRecord", pds.trim_end_matches('/') ), &[ ("repo", repo.to_string()), ("collection", collection.to_string()), ("rkey", rkey.to_string()), ], ) .await?; Ok(value.and_then(|value| { serde_json::from_value::(value) .ok() .and_then(|record| record.value) })) } pub async fn get_follows(&self, actor: &str, limit: usize) -> Result> { let mut follows = Vec::new(); let mut cursor: Option = None; while follows.len() < limit { let remaining = limit - follows.len(); let page_limit = remaining.min(PAGE_LIMIT as usize) as u32; let mut query = vec![ ("actor", actor.to_string()), ("limit", page_limit.to_string()), ]; if let Some(cursor) = &cursor { query.push(("cursor", cursor.clone())); } let value = self .request_json( &format!("{}/xrpc/app.bsky.graph.getFollows", self.public_api), &query, ) .await?; let response: GetFollowsResponse = serde_json::from_value(value).context("reading getFollows")?; for follow in response.follows { follows.push(Follow { did: follow.did, handle: follow.handle, }); if follows.len() == limit { break; } } match response.cursor { Some(next) if !next.is_empty() => cursor = Some(next), _ => break, } } Ok(follows) } async fn request_json(&self, url: &str, query: &[(&str, String)]) -> Result { match self.request_json_status(url, query, &[]).await? { Some(value) => Ok(value), None => unreachable!("no status was allowed to be empty"), } } async fn request_json_optional( &self, url: &str, query: &[(&str, String)], ) -> Result> { self.request_json_status( url, query, &[StatusCode::BAD_REQUEST, StatusCode::NOT_FOUND], ) .await } pub async fn request_text(&self, url: &str) -> Result { for attempt in 0..=1 { let response = self .client .get(url) .send() .await .with_context(|| format!("GET {url}"))?; let status = response.status(); if status == StatusCode::TOO_MANY_REQUESTS && attempt == 0 { let delay = retry_delay(response.headers()); tracing::warn!(url, ?delay, "rate limited; retrying once"); tokio::time::sleep(delay).await; continue; } let body = response.text().await.unwrap_or_default(); if !status.is_success() { return Err(anyhow!( "GET {url} returned {status}: {}", truncate(&body, 400) )); } return Ok(body); } unreachable!("the retry loop always returns or continues") } async fn request_json_status( &self, url: &str, query: &[(&str, String)], allowed: &[StatusCode], ) -> Result> { let query: Vec<(String, String)> = query .iter() .map(|(key, value)| ((*key).to_string(), value.clone())) .collect(); for attempt in 0..=1 { let response = self .client .get(url) .query(&query) .send() .await .with_context(|| format!("GET {url}"))?; let status = response.status(); if status == StatusCode::TOO_MANY_REQUESTS && attempt == 0 { let delay = retry_delay(response.headers()); tracing::warn!(url, ?delay, "rate limited; retrying once"); tokio::time::sleep(delay).await; continue; } let body = response.text().await.unwrap_or_default(); if allowed.contains(&status) { return Ok(None); } if !status.is_success() { return Err(anyhow!( "GET {url} returned {status}: {}", truncate(&body, 400) )); } let value = serde_json::from_str(&body) .with_context(|| format!("decoding the response from {url}"))?; return Ok(Some(value)); } unreachable!("the retry loop always returns or continues") } } fn base_url(variable: &str, fallback: &str) -> String { std::env::var(variable) .unwrap_or_else(|_| fallback.to_string()) .trim_end_matches('/') .to_string() } fn retry_delay(headers: &reqwest::header::HeaderMap) -> Duration { if let Some(value) = headers .get("retry-after") .and_then(|value| value.to_str().ok()) && let Ok(seconds) = value.trim().parse::() { return Duration::from_secs_f64(seconds.max(0.0)); } if let Some(value) = headers .get("ratelimit-reset") .and_then(|value| value.to_str().ok()) && let Ok(reset) = value.trim().parse::() { let wait = reset.saturating_sub(Utc::now().timestamp()); return Duration::from_secs(wait.max(0) as u64); } Duration::from_secs(1) } fn truncate(text: &str, limit: usize) -> &str { match text.char_indices().nth(limit) { Some((index, _)) => &text[..index], None => text, } } fn document_post_uri(record: &RepoRecord) -> Option { let reference = record.value.get("bskyPostRef")?; if let Some(uri) = reference.as_str() { return Some(uri.to_string()); } reference .get("uri") .and_then(Value::as_str) .map(str::to_string) }