use serde::{Deserialize, Serialize};
use crate::lexicon::Facet;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct StrongRef {
pub uri: String,
pub cid: String,
}
impl StrongRef {
#[must_use]
pub fn new(uri: impl Into<String>, cid: impl Into<String>) -> Self {
Self {
uri: uri.into(),
cid: cid.into(),
}
}
#[must_use]
pub fn did(&self) -> Option<&str> {
let stripped = self.uri.strip_prefix("at://")?;
let did = stripped.split('/').next()?;
if did.starts_with("did:") {
Some(did)
} else {
None
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ReplyRef {
pub root: StrongRef,
pub parent: StrongRef,
}
impl ReplyRef {
#[must_use]
pub fn new(root: StrongRef, parent: StrongRef) -> Self {
Self { root, parent }
}
#[must_use]
pub fn parent_did(&self) -> Option<&str> {
self.parent.did()
}
#[must_use]
pub fn root_did(&self) -> Option<&str> {
self.root.did()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecordEmbed {
#[serde(rename = "$type", default)]
pub record_type: Option<String>,
pub record: StrongRef,
}
impl RecordEmbed {
#[must_use]
pub fn new(record: StrongRef) -> Self {
Self {
record_type: Some("app.bsky.embed.record".to_string()),
record,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecordWithMediaEmbed {
#[serde(rename = "$type", default)]
pub record_type: Option<String>,
pub record: RecordEmbed,
#[serde(default)]
pub media: Option<serde_json::Value>,
}
impl RecordWithMediaEmbed {
#[must_use]
pub fn new(record: RecordEmbed, media: Option<serde_json::Value>) -> Self {
Self {
record_type: Some("app.bsky.embed.recordWithMedia".to_string()),
record,
media,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "$type")]
pub enum Embed {
#[serde(rename = "app.bsky.embed.record")]
Record(RecordEmbed),
#[serde(rename = "app.bsky.embed.recordWithMedia")]
RecordWithMedia(Box<RecordWithMediaEmbed>),
#[serde(rename = "app.bsky.embed.images")]
Images(serde_json::Value),
#[serde(rename = "app.bsky.embed.gallery")]
Gallery(serde_json::Value),
#[serde(rename = "app.bsky.embed.external")]
External(serde_json::Value),
#[serde(rename = "app.bsky.embed.video")]
Video(serde_json::Value),
#[serde(other)]
Unknown,
}
impl Embed {
#[must_use]
pub fn quote_uri(&self) -> Option<&str> {
match self {
Self::Record(r) => Some(r.record.uri.as_str()),
Self::RecordWithMedia(rwm) => Some(rwm.record.record.uri.as_str()),
_ => None,
}
}
#[must_use]
pub fn quote_cid(&self) -> Option<&str> {
match self {
Self::Record(r) => Some(r.record.cid.as_str()),
Self::RecordWithMedia(rwm) => Some(rwm.record.record.cid.as_str()),
_ => None,
}
}
#[must_use]
pub fn is_quote(&self) -> bool {
matches!(self, Self::Record(_) | Self::RecordWithMedia(_))
}
#[must_use]
pub fn extract_images(&self) -> Vec<(String, String)> {
match self {
Self::Images(val) => Self::extract_images_from_value(val),
Self::Gallery(val) => Self::extract_gallery_items(val),
Self::RecordWithMedia(rwm) => {
if let Some(ref media) = rwm.media {
let mut imgs = Self::extract_images_from_value(media);
if imgs.is_empty() {
imgs = Self::extract_gallery_items(media);
}
imgs
} else {
Vec::new()
}
}
_ => Vec::new(),
}
}
#[must_use]
pub fn extract_gallery_items(val: &serde_json::Value) -> Vec<(String, String)> {
let Some(items) = val
.get("items")
.or_else(|| val.get("images"))
.and_then(|v| v.as_array())
else {
return Vec::new();
};
let mut results = Vec::with_capacity(items.len());
for item in items {
let alt = item
.get("alt")
.or_else(|| item.get("media").and_then(|m| m.get("alt")))
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string();
let img_obj = item
.get("image")
.or_else(|| item.get("media").and_then(|m| m.get("image")));
let cid = img_obj
.and_then(|img| {
img.get("ref")
.and_then(|r| r.get("$link"))
.and_then(|l| l.as_str())
.or_else(|| img.get("cid").and_then(|c| c.as_str()))
})
.or_else(|| item.get("cid").and_then(|c| c.as_str()));
if let Some(c) = cid.filter(|s| !s.is_empty()) {
results.push((c.to_string(), alt));
}
}
results
}
fn extract_images_from_value(val: &serde_json::Value) -> Vec<(String, String)> {
let mut results = Vec::new();
let images_array = if let Some(arr) = val.get("images").and_then(|v| v.as_array()) {
arr
} else if let Some(arr) = val.as_array() {
arr
} else {
return results;
};
for item in images_array {
let alt = item
.get("alt")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string();
let cid = item
.get("image")
.and_then(|img| {
img.get("ref")
.and_then(|r| r.get("$link"))
.and_then(|l| l.as_str())
.or_else(|| img.get("cid").and_then(|c| c.as_str()))
})
.or_else(|| item.get("cid").and_then(|c| c.as_str()));
if let Some(c) = cid {
if !c.is_empty() {
results.push((c.to_string(), alt));
}
}
}
results
}
}
pub const NSFW_SELF_LABEL_VALUES: [&str; 10] = [
"porn",
"sexual",
"nudity",
"graphic-media",
"graphic",
"adult",
"nsfw",
"suggestive",
"gore",
"corpse",
];
#[must_use]
pub fn has_nsfw_self_label(record: &serde_json::Value) -> bool {
let Some(values) = record
.get("labels")
.and_then(|labels| labels.get("values"))
.and_then(serde_json::Value::as_array)
else {
return false;
};
values.iter().any(|entry| {
let raw = entry
.get("val")
.and_then(serde_json::Value::as_str)
.or_else(|| entry.as_str());
raw.is_some_and(|val| {
let trimmed = val.trim();
NSFW_SELF_LABEL_VALUES
.iter()
.any(|nsfw| trimmed.eq_ignore_ascii_case(nsfw))
|| SelfLabels::NSFW_LABELS
.iter()
.any(|nsfw| trimmed.eq_ignore_ascii_case(nsfw))
})
})
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SelfLabel {
pub val: String,
}
impl SelfLabel {
#[must_use]
pub fn new(val: impl Into<String>) -> Self {
Self { val: val.into() }
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SelfLabels {
#[serde(rename = "$type", default, skip_serializing_if = "Option::is_none")]
pub record_type: Option<String>,
#[serde(default)]
pub values: Vec<SelfLabel>,
}
impl SelfLabels {
pub const NSFW_LABELS: &'static [&'static str] = &[
"porn",
"sexual",
"nudity",
"nsfw",
"graphic-media",
"graphic",
"suggestive",
"gore",
"corpse",
"adult",
];
#[must_use]
pub fn has_nsfw(&self) -> bool {
self.values.iter().any(|l| {
let trimmed = l.val.trim();
Self::NSFW_LABELS
.iter()
.any(|nsfw| trimmed.eq_ignore_ascii_case(nsfw))
})
}
#[must_use]
pub fn contains(&self, target: &str) -> bool {
self.values
.iter()
.any(|l| l.val.trim().eq_ignore_ascii_case(target))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PostRecord {
#[serde(rename = "$type", default)]
pub record_type: Option<String>,
#[serde(default)]
pub text: String,
#[serde(default)]
pub reply: Option<ReplyRef>,
#[serde(default)]
pub facets: Option<Vec<Facet>>,
#[serde(default)]
pub embed: Option<Embed>,
#[serde(default)]
pub created_at: String,
#[serde(default)]
pub langs: Option<Vec<String>>,
#[serde(default)]
pub tags: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub labels: Option<SelfLabels>,
}
impl PostRecord {
#[must_use]
pub fn new(text: impl Into<String>, created_at: impl Into<String>) -> Self {
Self {
record_type: Some("app.bsky.feed.post".to_string()),
text: text.into(),
reply: None,
facets: None,
embed: None,
created_at: created_at.into(),
langs: None,
tags: None,
labels: None,
}
}
#[must_use]
pub fn with_reply(mut self, reply: ReplyRef) -> Self {
self.reply = Some(reply);
self
}
#[must_use]
pub fn with_facets(mut self, facets: Vec<Facet>) -> Self {
self.facets = Some(facets);
self
}
#[must_use]
pub fn with_embed(mut self, embed: Embed) -> Self {
self.embed = Some(embed);
self
}
pub fn mentioned_dids(&self) -> impl Iterator<Item = &str> {
self.facets
.as_deref()
.into_iter()
.flatten()
.flat_map(Facet::mentioned_dids)
}
#[must_use]
pub fn quote_uri(&self) -> Option<&str> {
self.embed.as_ref().and_then(Embed::quote_uri)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FollowRecord {
#[serde(rename = "$type", default)]
pub record_type: Option<String>,
pub subject: String,
pub created_at: String,
}
impl FollowRecord {
#[must_use]
pub fn new(subject: impl Into<String>, created_at: impl Into<String>) -> Self {
Self {
record_type: Some("app.bsky.graph.follow".to_string()),
subject: subject.into(),
created_at: created_at.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModListRecord {
#[serde(rename = "$type", default, skip_serializing_if = "Option::is_none")]
pub record_type: Option<String>,
pub purpose: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description_facets: Option<Vec<Facet>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub avatar: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub labels: Option<SelfLabels>,
pub created_at: String,
}
impl ModListRecord {
#[must_use]
pub fn new_modlist(
name: impl Into<String>,
description: Option<String>,
created_at: impl Into<String>,
) -> Self {
Self {
record_type: Some("app.bsky.graph.list".to_string()),
purpose: "app.bsky.graph.defs#modlist".to_string(),
name: name.into(),
description,
description_facets: None,
avatar: None,
labels: None,
created_at: created_at.into(),
}
}
#[must_use]
pub fn new(
purpose: impl Into<String>,
name: impl Into<String>,
description: Option<String>,
created_at: impl Into<String>,
) -> Self {
Self {
record_type: Some("app.bsky.graph.list".to_string()),
purpose: purpose.into(),
name: name.into(),
description,
description_facets: None,
avatar: None,
labels: None,
created_at: created_at.into(),
}
}
#[must_use]
pub fn is_modlist(&self) -> bool {
self.purpose == "app.bsky.graph.defs#modlist"
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListItemRecord {
#[serde(rename = "$type", default, skip_serializing_if = "Option::is_none")]
pub record_type: Option<String>,
pub subject: String,
pub list: String,
pub created_at: String,
}
impl ListItemRecord {
#[must_use]
pub fn new(
subject: impl Into<String>,
list: impl Into<String>,
created_at: impl Into<String>,
) -> Self {
Self {
record_type: Some("app.bsky.graph.listitem".to_string()),
subject: subject.into(),
list: list.into(),
created_at: created_at.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListBlockRecord {
#[serde(rename = "$type", default, skip_serializing_if = "Option::is_none")]
pub record_type: Option<String>,
pub subject: String,
pub created_at: String,
}
impl ListBlockRecord {
#[must_use]
pub fn new(subject: impl Into<String>, created_at: impl Into<String>) -> Self {
Self {
record_type: Some("app.bsky.graph.listblock".to_string()),
subject: subject.into(),
created_at: created_at.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RepoRecordItem<T = serde_json::Value> {
pub uri: String,
pub cid: String,
pub value: T,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ListRecordsResponse<T = serde_json::Value> {
pub records: Vec<RepoRecordItem<T>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cursor: Option<String>,
}
#[must_use]
pub fn format_system_time_iso8601(time: std::time::SystemTime) -> String {
let dur = time
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or(std::time::Duration::ZERO);
let total_secs = dur.as_secs();
let millis = dur.subsec_millis();
let days = (total_secs / 86400) as i64;
let day_secs = (total_secs % 86400) as u32;
let hour = day_secs / 3600;
let minute = (day_secs % 3600) / 60;
let second = day_secs % 60;
let z = days + 719468;
let era = if z >= 0 { z } else { z - 146096 } / 146097;
let doe = (z - era * 146097) as u64;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let y = (yoe as i64) + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let year = if m <= 2 { y + 1 } else { y };
format!("{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z")
}
#[must_use]
pub fn now_iso8601() -> String {
format_system_time_iso8601(std::time::SystemTime::now())
}
#[must_use]
pub fn format_unix_secs_iso8601(secs: u64) -> String {
let mut days = secs / 86400;
let day_secs = secs % 86400;
let hours = day_secs / 3600;
let mins = (day_secs % 3600) / 60;
let seconds = day_secs % 60;
days += 719_468;
let era = days / 146_097;
let doe = days - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!("{y:04}-{m:02}-{d:02}T{hours:02}:{mins:02}:{seconds:02}Z")
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod tests {
use super::*;
use std::time::{Duration, UNIX_EPOCH};
#[test]
fn test_format_system_time_epoch() {
assert_eq!(
format_system_time_iso8601(UNIX_EPOCH),
"1970-01-01T00:00:00.000Z"
);
}
#[test]
fn test_format_system_time_known_date() {
let time = UNIX_EPOCH + Duration::from_millis(1_790_906_400_500);
assert_eq!(format_system_time_iso8601(time), "2026-10-02T02:00:00.500Z");
}
#[test]
fn test_now_iso8601_non_empty() {
let now = now_iso8601();
assert!(now.ends_with('Z'));
assert!(now.contains('T'));
}
#[test]
fn test_strong_ref_did_extraction() {
let r = StrongRef::new("at://did:plc:alice/app.bsky.feed.post/1", "bafy");
assert_eq!(r.did(), Some("did:plc:alice"));
let bad = StrongRef::new("at://alice.bsky.social/app.bsky.feed.post/1", "bafy");
assert_eq!(bad.did(), None);
}
#[test]
fn test_mod_list_record_serde_roundtrip() {
let record = ModListRecord::new_modlist(
"Test Mod List",
Some("Description".to_string()),
"2026-10-02T00:00:00.000Z",
);
let json = serde_json::to_string(&record).unwrap();
assert!(json.contains("\"purpose\":\"app.bsky.graph.defs#modlist\""));
let deserialized: ModListRecord = serde_json::from_str(&json).unwrap();
assert_eq!(record, deserialized);
assert!(deserialized.is_modlist());
}
#[test]
fn test_list_item_record_serde_roundtrip() {
let record = ListItemRecord::new(
"did:plc:badactor",
"at://did:plc:alice/app.bsky.graph.list/123",
"2026-10-02T00:00:00.000Z",
);
let json = serde_json::to_string(&record).unwrap();
assert!(json.contains("\"subject\":\"did:plc:badactor\""));
let deserialized: ListItemRecord = serde_json::from_str(&json).unwrap();
assert_eq!(record, deserialized);
}
#[test]
fn test_embed_extract_images_direct() {
let json = serde_json::json!({
"$type": "app.bsky.embed.images",
"images": [
{ "alt": "A test visual", "image": { "ref": { "$link": "bafkreicid12345" } } },
{ "alt": "Second visual", "image": { "cid": "bafkreicid67890" } }
]
});
let embed: Embed = serde_json::from_value(json).unwrap();
let images = embed.extract_images();
assert_eq!(images.len(), 2);
assert_eq!(images[0].0, "bafkreicid12345");
assert_eq!(images[1].0, "bafkreicid67890");
}
#[test]
fn test_embed_extract_images_record_with_media() {
let json = serde_json::json!({
"$type": "app.bsky.embed.recordWithMedia",
"record": {
"record": { "uri": "at://did:plc:alice/app.bsky.feed.post/123", "cid": "bafyquoted" }
},
"media": {
"$type": "app.bsky.embed.images",
"images": [{ "alt": "Embedded image", "image": { "ref": { "$link": "bafkmediaimage1" } } }]
}
});
let embed: Embed = serde_json::from_value(json).unwrap();
let images = embed.extract_images();
assert_eq!(images.len(), 1);
assert_eq!(images[0].0, "bafkmediaimage1");
assert!(embed.is_quote());
assert_eq!(
embed.quote_uri(),
Some("at://did:plc:alice/app.bsky.feed.post/123")
);
assert_eq!(embed.quote_cid(), Some("bafyquoted"));
}
#[test]
fn test_records_builders_gallery_labels_and_unix_secs_iso8601() {
let root = StrongRef::new("at://did:plc:root/app.bsky.feed.post/1", "cid_root");
let parent = StrongRef::new("at://did:plc:parent/app.bsky.feed.post/2", "cid_parent");
let reply = ReplyRef::new(root.clone(), parent);
assert_eq!(reply.root_did(), Some("did:plc:root"));
assert_eq!(reply.parent_did(), Some("did:plc:parent"));
let rec_embed = RecordEmbed::new(root);
let rwm = RecordWithMediaEmbed::new(
rec_embed.clone(),
Some(serde_json::json!({
"items": [
{"media": {"alt": "gallery alt", "image": {"ref": {"$link": "bafygallery1"}}}},
{"cid": "bafygallery2"}
]
})),
);
let embed_rec = Embed::Record(rec_embed);
assert!(embed_rec.is_quote());
assert_eq!(embed_rec.quote_cid(), Some("cid_root"));
assert!(embed_rec.extract_images().is_empty());
let embed_rwm = Embed::RecordWithMedia(Box::new(rwm));
let rwm_imgs = embed_rwm.extract_images();
assert_eq!(rwm_imgs.len(), 2);
assert_eq!(
rwm_imgs[0],
("bafygallery1".to_string(), "gallery alt".to_string())
);
let embed_gallery = Embed::Gallery(serde_json::json!({
"items": [{"alt": "g1", "image": {"cid": "bafyg1"}}]
}));
assert!(!embed_gallery.is_quote());
assert_eq!(embed_gallery.quote_uri(), None);
assert_eq!(embed_gallery.quote_cid(), None);
assert_eq!(embed_gallery.extract_images().len(), 1);
assert!(Embed::extract_gallery_items(&serde_json::json!({})).is_empty());
let rwm_no_media = Embed::RecordWithMedia(Box::new(RecordWithMediaEmbed::new(
RecordEmbed::new(StrongRef::new("at://did:plc:x/col/1", "c")),
None,
)));
assert!(rwm_no_media.extract_images().is_empty());
let sl = SelfLabel::new("Porn");
let sls = SelfLabels {
record_type: None,
values: vec![sl],
};
assert!(sls.has_nsfw());
assert!(sls.contains("porn"));
assert!(!sls.contains("safe"));
assert!(has_nsfw_self_label(&serde_json::json!({
"labels": {"values": [{"val": "nudity"}]}
})));
assert!(has_nsfw_self_label(&serde_json::json!({
"labels": {"values": ["suggestive"]}
})));
assert!(!has_nsfw_self_label(&serde_json::json!({
"labels": {"values": [{"val": "clean"}]}
})));
assert!(!has_nsfw_self_label(&serde_json::json!({})));
let facet = crate::lexicon::Facet::new(
crate::lexicon::ByteSlice::new(0, 6),
vec![crate::lexicon::FacetFeature::Mention {
did: "did:plc:mentioned".to_string(),
}],
);
let post = PostRecord::new("hi @alice", "2026-11-03T00:00:00Z")
.with_reply(reply)
.with_facets(vec![facet])
.with_embed(embed_rec);
assert_eq!(
post.mentioned_dids().collect::<Vec<_>>(),
vec!["did:plc:mentioned"]
);
assert_eq!(
post.quote_uri(),
Some("at://did:plc:root/app.bsky.feed.post/1")
);
let follow = FollowRecord::new("did:plc:target", "2026-11-03T00:00:00Z");
assert_eq!(follow.subject, "did:plc:target");
let curatelist = ModListRecord::new(
"app.bsky.graph.defs#curatelist",
"Curate",
None,
"2026-11-03T00:00:00Z",
);
assert!(!curatelist.is_modlist());
let lb = ListBlockRecord::new(
"at://did:plc:alice/app.bsky.graph.list/1",
"2026-11-03T00:00:00Z",
);
assert_eq!(lb.subject, "at://did:plc:alice/app.bsky.graph.list/1");
assert_eq!(format_unix_secs_iso8601(0), "1970-01-01T00:00:00Z");
assert_eq!(
format_unix_secs_iso8601(1_790_906_400),
"2026-10-02T02:00:00Z"
);
}
}