encode.rs (2269B)
1 #[cfg(not(feature = "std"))] 2 use alloc::{ 3 string::{String, ToString}, 4 vec::Vec, 5 }; 6 7 use radroots_event::{ 8 envelope::kind::KIND_ARTICLE, 9 post::article::Article, 10 tag::name::{TAG_D, TAG_IMAGE, TAG_PUBLISHED_AT, TAG_SUMMARY, TAG_T, TAG_TITLE}, 11 }; 12 13 use crate::d_tag::validate_d_tag; 14 use crate::error::EventEncodeError; 15 use crate::field_helpers::{push_optional_tag, push_tag, validate_non_empty_field}; 16 use crate::social_helpers::push_location_tags; 17 use radroots_event::wire::Nip01EventWireParts; 18 19 const DEFAULT_KIND: u32 = KIND_ARTICLE; 20 21 pub fn article_build_tags(article: &Article) -> Result<Vec<Vec<String>>, EventEncodeError> { 22 validate_article(article)?; 23 let mut tags = Vec::new(); 24 push_tag(&mut tags, TAG_D, article.d_tag.as_str()); 25 push_tag(&mut tags, TAG_TITLE, article.title.as_str()); 26 push_optional_tag(&mut tags, TAG_SUMMARY, article.summary.as_deref()); 27 push_optional_tag(&mut tags, TAG_IMAGE, article.image.as_deref()); 28 if let Some(published_at) = article.published_at { 29 push_tag(&mut tags, TAG_PUBLISHED_AT, published_at.to_string()); 30 } 31 if let Some(farm) = article.farm.as_ref() { 32 crate::social_helpers::push_farm_anchor(&mut tags, farm); 33 } 34 if let Some(location) = article.location.as_ref() { 35 push_location_tags(&mut tags, location); 36 } 37 if let Some(topics) = article.topics.as_ref() { 38 for topic in topics { 39 push_optional_tag(&mut tags, TAG_T, Some(topic.as_str())); 40 } 41 } 42 Ok(tags) 43 } 44 45 pub fn to_wire_parts(article: &Article) -> Result<Nip01EventWireParts, EventEncodeError> { 46 to_wire_parts_with_kind(article, DEFAULT_KIND) 47 } 48 49 pub fn to_wire_parts_with_kind( 50 article: &Article, 51 kind: u32, 52 ) -> Result<Nip01EventWireParts, EventEncodeError> { 53 if kind != DEFAULT_KIND { 54 return Err(EventEncodeError::InvalidKind(kind)); 55 } 56 Ok(Nip01EventWireParts { 57 kind, 58 content: article.content.clone(), 59 tags: article_build_tags(article)?, 60 }) 61 } 62 63 fn validate_article(article: &Article) -> Result<(), EventEncodeError> { 64 validate_d_tag(&article.d_tag, "d_tag")?; 65 validate_non_empty_field(&article.title, "title")?; 66 validate_non_empty_field(&article.content, "content")?; 67 Ok(()) 68 }