fedimovies/src/validators/posts.rs

54 lines
1.6 KiB
Rust
Raw Normal View History

2023-04-25 13:49:35 +00:00
use fedimovies_utils::html::clean_html_strict;
2023-02-18 22:25:49 +00:00
2022-10-06 21:16:52 +00:00
use crate::errors::ValidationError;
pub const ATTACHMENT_LIMIT: usize = 15;
pub const MENTION_LIMIT: usize = 50;
pub const LINK_LIMIT: usize = 10;
pub const EMOJI_LIMIT: usize = 50;
pub const OBJECT_ID_SIZE_MAX: usize = 2000;
2022-10-25 19:03:38 +00:00
pub const CONTENT_MAX_SIZE: usize = 100000;
2023-04-24 15:35:32 +00:00
const CONTENT_ALLOWED_TAGS: [&str; 8] = ["a", "br", "pre", "code", "strong", "em", "p", "span"];
2022-10-06 21:16:52 +00:00
pub fn content_allowed_classes() -> Vec<(&'static str, Vec<&'static str>)> {
vec![
("a", vec!["hashtag", "mention", "u-url"]),
("span", vec!["h-card"]),
("p", vec!["inline-quote"]),
]
}
2023-04-24 15:35:32 +00:00
pub fn clean_content(content: &str) -> Result<String, ValidationError> {
2022-10-25 19:03:38 +00:00
// Check content size to not exceed the hard limit
// Character limit from config is not enforced at the backend
if content.len() > CONTENT_MAX_SIZE {
2023-04-26 10:55:42 +00:00
return Err(ValidationError("post is too long".to_string()));
2022-10-06 21:16:52 +00:00
};
2023-04-24 15:35:32 +00:00
let content_safe = clean_html_strict(content, &CONTENT_ALLOWED_TAGS, content_allowed_classes());
2022-10-06 21:16:52 +00:00
let content_trimmed = content_safe.trim();
if content_trimmed.is_empty() {
2023-04-26 10:55:42 +00:00
return Err(ValidationError("post can not be empty".to_string()));
2022-10-06 21:16:52 +00:00
};
Ok(content_trimmed.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_clean_content_empty() {
let content = " ";
2022-10-25 19:03:38 +00:00
let result = clean_content(content);
2023-04-27 22:15:44 +00:00
assert!(result.is_err());
2022-10-06 21:16:52 +00:00
}
#[test]
fn test_clean_content_trimming() {
let content = "test ";
2022-10-25 19:03:38 +00:00
let cleaned = clean_content(content).unwrap();
2022-10-06 21:16:52 +00:00
assert_eq!(cleaned, "test");
}
}