use std::collections::BTreeSet;
#[cfg(feature = "serde")]
use std::str::FromStr as _;
use snafu::Snafu;
use unicode_segmentation::UnicodeSegmentation as _;
use url::Url;
#[cfg(feature = "serde")]
use super::{EventAuxKey, EventContentRaw, EventKind};
use super::{PersonaId, PersonaTag};
use crate::id::RostraId;
#[cfg(feature = "serde")]
use crate::id::ToShort as _;
use crate::{
ExternalEventId, array_type_define, array_type_impl_base32_str, array_type_impl_serde,
};
#[derive(Debug, Snafu)]
#[snafu(display("Content validation error: {public_message}"))]
pub struct ContentValidationError {
pub public_message: String,
}
pub type ContentValidationResult<T> = std::result::Result<T, ContentValidationError>;
#[cfg(feature = "serde")]
pub trait EventContentKind: ::serde::Serialize + ::serde::de::DeserializeOwned {
const KIND: EventKind;
fn serialize_cbor(&self) -> ContentValidationResult<EventContentRaw> {
self.validate()?;
let mut buf = Vec::with_capacity(128);
cbor4ii::serde::to_writer(&mut buf, self).expect("Can't fail");
Ok(EventContentRaw::new(buf))
}
fn singleton_key_aux(&self) -> Option<EventAuxKey> {
None
}
fn validate(&self) -> ContentValidationResult<()> {
Ok(())
}
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Follow {
#[cfg_attr(feature = "serde", serde(rename = "i"))]
pub followee: RostraId,
#[cfg_attr(feature = "serde", serde(rename = "p"))]
pub persona: Option<PersonaId>,
#[cfg_attr(feature = "serde", serde(rename = "s"))]
pub selector: Option<PersonaSelector>,
#[cfg_attr(feature = "serde", serde(rename = "t", default))]
pub persona_tags_selector: Option<PersonasTagsSelector>,
}
impl Follow {
pub fn selector(self) -> Option<PersonaSelector> {
if let Some(selector) = self.selector {
return Some(selector);
}
if let Some(persona) = self.persona {
return Some(PersonaSelector::Only { ids: vec![persona] });
}
None
}
pub fn is_unfollow(&self) -> bool {
self.persona.is_none() && self.selector.is_none() && self.persona_tags_selector.is_none()
}
}
#[cfg(feature = "serde")]
impl EventContentKind for Follow {
const KIND: EventKind = EventKind::FOLLOW;
fn singleton_key_aux(&self) -> Option<EventAuxKey> {
Some(EventAuxKey::from_bytes(self.followee.to_short().to_bytes()))
}
}
array_type_define!(
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct IrohNodeId, 32
);
array_type_impl_serde!(struct IrohNodeId, 32);
array_type_impl_base32_str!(IrohNodeId);
impl IrohNodeId {
pub fn to_z32(&self) -> String {
z32::encode(self.as_slice())
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize))]
#[cfg_attr(feature = "serde", serde(tag = "t"))]
pub enum NodeAnnouncement {
#[cfg_attr(feature = "serde", serde(rename = "i"))]
Iroh {
#[cfg_attr(feature = "serde", serde(rename = "a"))]
addr: IrohNodeId,
},
}
#[cfg(feature = "serde")]
impl EventContentKind for NodeAnnouncement {
const KIND: EventKind = EventKind::NODE_ANNOUNCEMENT;
}
#[cfg(feature = "serde")]
impl<'de> ::serde::de::Deserialize<'de> for NodeAnnouncement {
fn deserialize<D>(d: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
#[derive(::serde::Deserialize)]
struct NodeAnnouncementRaw<T> {
#[serde(rename = "t")]
t: String,
#[serde(rename = "a")]
addr: Option<T>,
}
let addr = if d.is_human_readable() {
let raw = NodeAnnouncementRaw::<String>::deserialize(d)?;
if raw.t != "i" {
return Err(::serde::de::Error::custom(format!(
"Unknown variant: {}",
raw.t
)));
}
let Some(addr) = raw.addr else {
return Err(::serde::de::Error::custom("Missing field: a"));
};
IrohNodeId::from_str(&addr)
.map_err(|e| ::serde::de::Error::custom(format!("Decoding a error: {e}")))?
} else {
let raw = NodeAnnouncementRaw::<serde_bytes::ByteArray<32>>::deserialize(d)?;
if raw.t != "i" {
return Err(::serde::de::Error::custom(format!(
"Unknown variant: {}",
raw.t
)));
}
let Some(addr) = raw.addr else {
return Err(::serde::de::Error::custom("Missing field: a"));
};
IrohNodeId::from_bytes(addr.into_array())
};
Ok(NodeAnnouncement::Iroh { addr })
}
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct SocialPost {
#[cfg_attr(feature = "serde", serde(rename = "p", default))]
persona: Option<PersonaId>,
#[cfg_attr(feature = "serde", serde(rename = "c"))]
pub djot_content: Option<String>,
#[cfg_attr(feature = "serde", serde(rename = "r"))]
pub reply_to: Option<ExternalEventId>,
#[cfg_attr(feature = "serde", serde(rename = "e"))]
pub reaction: Option<String>,
#[cfg_attr(feature = "serde", serde(rename = "u"))]
pub url: Option<Url>,
#[cfg_attr(feature = "serde", serde(rename = "h"))]
pub title: Option<String>,
#[cfg_attr(feature = "serde", serde(rename = "n", default))]
pub news: bool,
#[cfg_attr(feature = "serde", serde(rename = "t", default))]
persona_tags: BTreeSet<PersonaTag>,
}
impl SocialPost {
pub fn new(
body: String,
reply_to: Option<ExternalEventId>,
persona_tags: BTreeSet<PersonaTag>,
) -> Self {
let (djot_content, reaction) = if let Some(reaction) = Self::is_reaction(&reply_to, &body) {
(None, Some(reaction.to_owned()))
} else {
(Some(body), None)
};
Self::from_parts(djot_content, reply_to, reaction, persona_tags)
}
pub fn new_text(
body: String,
reply_to: Option<ExternalEventId>,
persona_tags: BTreeSet<PersonaTag>,
) -> Self {
Self::from_parts(Some(body), reply_to, None, persona_tags)
}
fn from_parts(
djot_content: Option<String>,
reply_to: Option<ExternalEventId>,
reaction: Option<String>,
persona_tags: BTreeSet<PersonaTag>,
) -> Self {
Self {
persona: Some(PersonaId(0)),
djot_content,
reply_to,
reaction,
url: None,
title: None,
news: false,
persona_tags,
}
}
pub fn persona_tags(&self) -> BTreeSet<PersonaTag> {
if !self.persona_tags.is_empty() {
return self.persona_tags.clone();
}
if let Some(tag) = self.persona.and_then(PersonaTag::from_persona_id) {
BTreeSet::from([tag])
} else {
BTreeSet::new()
}
}
pub fn is_reaction<'t>(
reply_to: &'_ Option<ExternalEventId>,
text: &'t str,
) -> Option<&'t str> {
if reply_to.is_none() {
return None;
}
if 8 < text.len() {
return None;
}
let text = text.trim();
let first_grapheme = text.graphemes(true).next()?;
let is_not_emoji = first_grapheme.chars().all(|c| {
c.is_ascii_alphanumeric() ||
c.is_ascii_punctuation() ||
c.is_ascii_whitespace() ||
c.is_ascii_control()
});
if !is_not_emoji {
Some(first_grapheme)
} else {
None
}
}
pub fn get_reaction(&self) -> Option<&str> {
let reaction = self.reaction.as_ref()?.trim();
Self::is_reaction(&self.reply_to, reaction)
}
pub fn with_news_fields(mut self, url: Option<Url>, title: Option<String>) -> Self {
self.url = url;
self.title = title;
self.news = true;
self
}
}
#[cfg(feature = "serde")]
impl EventContentKind for SocialPost {
const KIND: EventKind = EventKind::SOCIAL_POST;
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct SocialVote {
#[cfg_attr(feature = "serde", serde(rename = "r"))]
pub reply_to: Option<ExternalEventId>,
#[cfg_attr(feature = "serde", serde(rename = "v"))]
pub upvote: Option<bool>,
}
impl SocialVote {
pub fn new(reply_to: ExternalEventId, upvote: Option<bool>) -> Self {
Self {
reply_to: Some(reply_to),
upvote,
}
}
pub fn vote_value(&self) -> i64 {
match self.upvote {
Some(true) => 1,
None => 0,
Some(false) => -1,
}
}
}
#[cfg(feature = "serde")]
impl EventContentKind for SocialVote {
const KIND: EventKind = EventKind::SOCIAL_VOTE;
fn singleton_key_aux(&self) -> Option<EventAuxKey> {
self.reply_to
.map(|reply_to| EventAuxKey::from_bytes(reply_to.event_id().to_bytes()))
}
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Shoutbox {
#[cfg_attr(feature = "serde", serde(rename = "c"))]
pub djot_content: String,
}
#[cfg(feature = "serde")]
impl EventContentKind for Shoutbox {
const KIND: EventKind = EventKind::SHOUTBOX;
fn validate(&self) -> ContentValidationResult<()> {
if 1000 < self.djot_content.len() {
return Err(ContentValidationError {
public_message: "Shoutbox message too long (max 1000 characters)".into(),
});
}
if self.djot_content.is_empty() {
return Err(ContentValidationError {
public_message: "Shoutbox message cannot be empty".into(),
});
}
Ok(())
}
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct SocialMedia {
#[cfg_attr(feature = "serde", serde(rename = "m"))]
pub mime: String,
#[cfg_attr(feature = "serde", serde(rename = "d"))]
pub data: Vec<u8>,
}
#[cfg(feature = "serde")]
impl EventContentKind for SocialMedia {
const KIND: EventKind = EventKind::SOCIAL_MEDIA;
fn singleton_key_aux(&self) -> Option<EventAuxKey> {
let hash = blake3::hash(&self.data);
let hash_bytes = hash.as_bytes();
let mut key_bytes = [0u8; 16];
key_bytes.copy_from_slice(&hash_bytes[..16]);
Some(EventAuxKey::from_bytes(key_bytes))
}
fn validate(&self) -> ContentValidationResult<()> {
if 200 * 1024 * 1024 < self.data.len() {
return Err(ContentValidationError {
public_message: "File too large (max 200MB)".into(),
});
}
if 100 < self.mime.len() {
return Err(ContentValidationError {
public_message: "MIME type too long".into(),
});
}
if self.data.is_empty() {
return Err(ContentValidationError {
public_message: "File is empty".into(),
});
}
Ok(())
}
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct SocialProfileUpdate {
#[cfg_attr(feature = "serde", serde(rename = "n"))]
pub display_name: String,
#[cfg_attr(feature = "serde", serde(rename = "b"))]
pub bio: String,
#[cfg_attr(feature = "serde", serde(rename = "a"))]
pub avatar: Option<(String, Vec<u8>)>,
}
#[cfg(feature = "serde")]
impl EventContentKind for SocialProfileUpdate {
const KIND: EventKind = EventKind::SOCIAL_PROFILE_UPDATE;
fn validate(&self) -> ContentValidationResult<()> {
if 100 < self.display_name.len() {
return Err(ContentValidationError {
public_message: "Display name too long (max 100 characters)".into(),
});
}
if 1000 < self.bio.len() {
return Err(ContentValidationError {
public_message: "Bio too long (max 1000 characters)".into(),
});
}
if let Some(avatar) = self.avatar.as_ref() {
if 100 < avatar.0.len() {
return Err(ContentValidationError {
public_message: "Avatar MIME type too long".into(),
});
}
if !avatar.0.starts_with("image/") {
return Err(ContentValidationError {
public_message: "Avatar must be an image".into(),
});
}
if 1_000_000 < avatar.1.len() {
return Err(ContentValidationError {
public_message: "Avatar too large (max 1MB)".into(),
});
}
}
Ok(())
}
fn singleton_key_aux(&self) -> Option<EventAuxKey> {
Some(EventAuxKey::ZERO)
}
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[cfg_attr(feature = "bincode", derive(::bincode::Encode, ::bincode::Decode))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum PersonaSelector {
Only { ids: Vec<PersonaId> },
Except { ids: Vec<PersonaId> },
}
impl PersonaSelector {
pub fn matches(&self, persona: PersonaId) -> bool {
match self {
PersonaSelector::Only { ids } => ids.contains(&persona),
PersonaSelector::Except { ids } => !ids.contains(&persona),
}
}
}
impl Default for PersonaSelector {
fn default() -> Self {
Self::Except { ids: vec![] }
}
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[cfg_attr(feature = "bincode", derive(::bincode::Encode, ::bincode::Decode))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum PersonasTagsSelector {
Only { ids: BTreeSet<PersonaTag> },
Except { ids: BTreeSet<PersonaTag> },
}
impl PersonasTagsSelector {
pub fn matches_tags(&self, tags: &BTreeSet<PersonaTag>) -> bool {
match self {
PersonasTagsSelector::Only { ids } => {
tags.iter().any(|t| ids.contains(t))
}
PersonasTagsSelector::Except { ids } => {
!tags.iter().any(|t| ids.contains(t))
}
}
}
}
impl Default for PersonasTagsSelector {
fn default() -> Self {
Self::Except {
ids: BTreeSet::new(),
}
}
}
#[cfg(test)]
mod tests;