Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486use anyhow::Result;use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};use serde_json::Value;
#[derive(Debug, Clone)]pub struct PostRecord { pub uri: String, pub value: PostValue, pub created_at: DateTime<Utc>,}
impl PostRecord { pub fn from_repo(record: RepoRecord) -> Result<Self> { let value: PostValue = serde_json::from_value(record.value) .map_err(|error| anyhow::anyhow!("reading post {}: {error}", record.uri))?; let created_at = DateTime::parse_from_rfc3339(&value.created_at) .map(|time| time.with_timezone(&Utc)) .unwrap_or_else(|error| { tracing::warn!( uri = %record.uri, createdAt = %value.created_at, %error, "unreadable createdAt; using the current time" ); Utc::now() }); Ok(Self { uri: record.uri, value, created_at, }) }
pub fn parent_uri(&self) -> Option<&str> { self.value.parent_uri() }}
pub fn uri_rkey(uri: &str) -> &str { uri.rsplit('/').next().unwrap_or("")}
pub fn uri_author(uri: &str) -> Option<&str> { uri.strip_prefix("at://") .and_then(|rest| rest.split('/').next()) .filter(|author| !author.is_empty())}
pub fn bsky_url(uri: &str) -> String { let author = uri_author(uri).unwrap_or(""); format!("https://bsky.app/profile/{author}/post/{}", uri_rkey(uri))}
/// The avatar URL for a profile record, served from the account's PDS.pub fn avatar_url(profile: &Value, pds: &str, did: &str) -> Option<String> { let avatar = profile.get("avatar")?; if let Some(url) = avatar.as_str() { return Some(url.to_string()); } let cid = avatar.pointer("/ref/$link").and_then(Value::as_str)?; Some(format!( "{}/xrpc/com.atproto.sync.getBlob?did={did}&cid={cid}", pds.trim_end_matches('/') ))}
#[derive(Debug, Clone, Deserialize)]pub struct ListRecordsResponse { #[serde(default)] pub records: Vec<RepoRecord>, #[serde(default)] pub cursor: Option<String>,}
#[derive(Debug, Clone, Deserialize)]pub struct RepoRecord { pub uri: String, pub value: Value,}
#[derive(Debug, Clone, Deserialize, Serialize)]pub struct PostValue { #[serde(default)] pub text: String, #[serde(rename = "createdAt")] pub created_at: String, #[serde(default)] pub reply: Option<Reply>, #[serde(default)] pub facets: Vec<Facet>, #[serde(default)] pub embed: Option<Value>, #[serde(default)] pub labels: Option<Value>,}
#[derive(Debug, Clone, Deserialize, Serialize)]pub struct Reply { #[serde(default)] pub root: Option<StrongRef>, pub parent: Option<StrongRef>,}
#[derive(Debug, Clone, Deserialize, Serialize)]pub struct StrongRef { pub uri: String, #[serde(default)] pub cid: Option<String>,}
#[derive(Debug, Clone, Deserialize, Serialize)]pub struct Facet { pub index: FacetIndex, #[serde(default)] pub features: Vec<Value>,}
#[derive(Debug, Clone, Deserialize, Serialize)]pub struct FacetIndex { #[serde(rename = "byteStart")] pub byte_start: usize, #[serde(rename = "byteEnd")] pub byte_end: usize,}
#[derive(Debug, Clone, Deserialize)]pub struct GetRecordResponse { #[serde(default)] pub value: Option<Value>,}
#[derive(Debug, Clone, Deserialize)]pub struct GetPostsResponse { #[serde(default)] pub posts: Vec<PostView>,}
#[derive(Debug, Clone, Deserialize)]#[serde(rename_all = "camelCase")]pub struct PostView { pub uri: String, #[serde(default)] pub like_count: i64, #[serde(default)] pub repost_count: i64, #[serde(default)] pub quote_count: i64, #[serde(default)] pub reply_count: i64, #[serde(default)] pub record: Option<PostValue>, #[serde(default)] pub author: Option<AuthorView>, #[serde(default)] pub labels: Value,}
#[derive(Debug, Clone, Deserialize)]#[serde(rename_all = "camelCase")]pub struct AuthorView { pub did: String, #[serde(default)] pub handle: String, #[serde(default)] pub display_name: Option<String>, #[serde(default)] pub avatar: Option<String>, #[serde(default)] pub labels: Value,}
#[derive(Debug, Clone, Deserialize)]pub struct GetFollowsResponse { #[serde(default)] pub follows: Vec<FollowView>, #[serde(default)] pub cursor: Option<String>,}
#[derive(Debug, Clone, Deserialize)]pub struct FollowView { pub did: String, #[serde(default)] pub handle: String,}
#[derive(Debug, Clone, Deserialize)]pub struct DidDocument { #[serde(default, rename = "alsoKnownAs")] pub also_known_as: Vec<String>, #[serde(default)] pub service: Vec<DidService>,}
#[derive(Debug, Clone, Deserialize)]pub struct DidService { pub id: String, #[serde(default, rename = "serviceEndpoint")] pub service_endpoint: String,}
impl PostValue { /// The URI of the post this one replies to, when the author set one. pub fn parent_uri(&self) -> Option<&str> { self.reply .as_ref() .and_then(|reply| reply.parent.as_ref()) .map(|parent| parent.uri.as_str()) }}
impl DidDocument { pub fn handle(&self) -> Option<String> { self.also_known_as.iter().find_map(|alias| { alias .strip_prefix("at://") .filter(|handle| !handle.is_empty()) .map(str::to_string) }) }
pub fn pds_endpoint(&self) -> Option<&str> { self.service .iter() .find(|service| service.id.ends_with("#atproto_pds")) .map(|service| service.service_endpoint.trim_end_matches('/')) .filter(|endpoint| !endpoint.is_empty()) }}
pub fn self_label_values(value: &Value) -> Vec<String> { let labels = value.get("labels").unwrap_or(value); let Some(values) = labels.get("values").and_then(Value::as_array) else { return Vec::new(); }; values .iter() .filter_map(|value| value.get("val").and_then(Value::as_str)) .map(str::to_string) .collect()}
pub fn view_label_values(value: &Value) -> Vec<String> { let Some(items) = value.as_array() else { return Vec::new(); }; items .iter() .filter(|item| item.get("neg").and_then(Value::as_bool) != Some(true)) .filter_map(|item| item.get("val").and_then(Value::as_str)) .map(str::to_string) .collect()}
/// Follow the core app's broad behaviour: hide the strongest labels, warn on/// adult and graphic labels, and show everything else.pub fn label_state(labels: &[String]) -> LabelState { let hidden = [ "!hide", "!no-unauthenticated", "spam", "scam", "impersonation", ]; let warn = [ "!warn", "porn", "sexual", "nudity", "graphic-media", "gore", "misleading", ]; if labels.iter().any(|label| hidden.contains(&label.as_str())) { LabelState::Hidden } else if labels.iter().any(|label| warn.contains(&label.as_str())) { LabelState::Warn } else { LabelState::Visible }}
/// Self-labels may be an object with a `values` array, or a bare array.pub fn has_self_label(value: &Value, wanted: &str) -> bool { fn visit(value: &Value, wanted: &str) -> bool { match value { Value::String(label) => label == wanted, Value::Array(items) => items.iter().any(|item| visit(item, wanted)), Value::Object(map) => { if map.get("val").and_then(Value::as_str) == Some(wanted) { return true; } map.values().any(|value| visit(value, wanted)) } _ => false, } }
visit(value, wanted)}
#[derive(Debug, Clone, Default)]pub struct Engagement { pub likes: i64, pub reposts: i64, pub quotes: i64, pub replies: i64, pub labels: Vec<String>,}
impl Engagement { pub fn index(&self) -> i64 { self.likes + 2 * self.reposts + 3 * self.quotes }}
/// The author information a Markdown render needs.#[derive(Debug, Clone)]pub struct ThreadAuthor { pub did: String, pub handle: String, pub pds: String,}
/// A fetched quote post, ready to render inline.#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct Quote { pub uri: String, pub author: QuoteAuthor, pub text: String, pub facets: Vec<Facet>, pub embed: Option<Value>,}
#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct QuoteAuthor { pub did: String, pub handle: String, pub display_name: Option<String>, pub avatar: Option<String>, pub pds: String,}
#[derive(Debug, Clone, Serialize)]pub struct AuthorRow { pub did: String, pub handle: String, #[serde(default)] pub display_name: Option<String>, #[serde(default)] pub avatar: Option<String>,}
#[derive(Debug, Clone, Serialize)]pub struct ForkOption { pub uri: String, pub posts: usize, pub date: String, pub snippet: String, pub chosen: bool,}
#[derive(Debug, Clone, Serialize)]pub struct Fork { pub parent_uri: String, pub parent_snippet: String, pub options: Vec<ForkOption>,}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "lowercase")]pub enum LabelState { Visible, Warn, Hidden,}
#[derive(Debug, Clone, Serialize)]pub struct ThreadRow { pub author: AuthorRow, pub root_uri: String, pub root_date: String, pub post_count: usize, pub graphemes: usize, pub likes: i64, pub reposts: i64, pub quotes: i64, pub replies: i64, pub dropped_branches: usize, pub reach_score: f64, pub relative_factor: f64, pub author_median: Option<f64>, pub cohort_percentile: f64, pub craft: crate::craft::Craft, pub score: f64, pub published: bool, pub labels: Vec<String>, pub label_state: LabelState, pub forks: Vec<Fork>, pub topics: Vec<String>, pub root_text: String, pub root_thumb: Option<String>, pub url: String,}
impl ThreadRow { pub fn sort_best_first(rows: &mut [ThreadRow]) { rows.sort_by(|left, right| { right .score .total_cmp(&left.score) .then_with(|| right.graphemes.cmp(&left.graphemes)) .then_with(|| left.root_uri.cmp(&right.root_uri)) }); }}
#[derive(Debug, Clone, Serialize)]pub struct PublicationRow { pub uri: String, pub did: String, pub name: String, pub url: String, pub description: Option<String>,}
#[derive(Debug, Clone, Serialize)]pub struct DocumentRow { pub uri: String, pub title: String, pub path: Option<String>, pub published_at: Option<String>, pub url: Option<String>, pub source_uri: Option<String>,}
#[derive(Debug, Clone, Serialize)]pub struct PublicationResult { pub account: AuthorRow, pub publications: Vec<PublicationRow>, pub documents: Vec<DocumentRow>, pub threads: Vec<ThreadRow>, #[serde(default)] pub threads_truncated: bool,}
#[cfg(test)]mod tests { use serde_json::json;
use super::*;
#[test] fn label_state_follows_the_core_states() { assert_eq!(label_state(&[]), LabelState::Visible); assert_eq!(label_state(&["!warn".to_string()]), LabelState::Warn); assert_eq!(label_state(&["porn".to_string()]), LabelState::Warn); assert_eq!(label_state(&["!hide".to_string()]), LabelState::Hidden); assert_eq!(label_state(&["spam".to_string()]), LabelState::Hidden); assert_eq!( label_state(&["!no-unauthenticated".to_string()]), LabelState::Hidden ); }
#[test] fn reads_self_and_view_labels() { let self_labels = json!({ "labels": { "$type": "com.atproto.label.defs#selfLabels", "values": [{ "val": "!warn" }] } }); assert_eq!(self_label_values(&self_labels), vec!["!warn"]);
let view_labels = json!([ { "val": "porn", "src": "did:plc:labeler" }, { "val": "spam", "src": "did:plc:labeler", "neg": true } ]); assert_eq!(view_label_values(&view_labels), vec!["porn"]); }}