use 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, } impl PostRecord { pub fn from_repo(record: RepoRecord) -> Result { 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 { 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, #[serde(default)] pub cursor: Option, } #[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, #[serde(default)] pub facets: Vec, #[serde(default)] pub embed: Option, #[serde(default)] pub labels: Option, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Reply { #[serde(default)] pub root: Option, pub parent: Option, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct StrongRef { pub uri: String, #[serde(default)] pub cid: Option, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Facet { pub index: FacetIndex, #[serde(default)] pub features: Vec, } #[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, } #[derive(Debug, Clone, Deserialize)] pub struct GetPostsResponse { #[serde(default)] pub posts: Vec, } #[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, #[serde(default)] pub author: Option, #[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, #[serde(default)] pub avatar: Option, #[serde(default)] pub labels: Value, } #[derive(Debug, Clone, Deserialize)] pub struct GetFollowsResponse { #[serde(default)] pub follows: Vec, #[serde(default)] pub cursor: Option, } #[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, #[serde(default)] pub service: Vec, } #[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 { 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 { 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 { 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, } 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, pub embed: Option, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct QuoteAuthor { pub did: String, pub handle: String, pub display_name: Option, pub avatar: Option, pub pds: String, } #[derive(Debug, Clone, Serialize)] pub struct AuthorRow { pub did: String, pub handle: String, #[serde(default)] pub display_name: Option, #[serde(default)] pub avatar: Option, } #[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, } #[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, pub cohort_percentile: f64, pub craft: crate::craft::Craft, pub score: f64, pub published: bool, pub labels: Vec, pub label_state: LabelState, pub forks: Vec, pub topics: Vec, pub root_text: String, pub root_thumb: Option, 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, } #[derive(Debug, Clone, Serialize)] pub struct DocumentRow { pub uri: String, pub title: String, pub path: Option, pub published_at: Option, pub url: Option, pub source_uri: Option, } #[derive(Debug, Clone, Serialize)] pub struct PublicationResult { pub account: AuthorRow, pub publications: Vec, pub documents: Vec, pub threads: Vec, #[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"]); } }