1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use include_dir::{Dir, include_dir};
30use std::iter;
31
32pub mod entities;
33pub mod markdown;
34pub mod text_clipper;
35pub mod text_decorator;
36
37static HTML_DATA_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/data");
38
39pub(crate) fn get_html_data(key: &str) -> Option<Vec<u8>> {
40 get_embedded_asset(&HTML_DATA_DIR, key)
41}
42
43pub fn html2text(html: Vec<u8>) -> Result<Vec<u8>> {
45 html2text_with_width(html, 80)
46}
47
48pub fn html2text_with_width(html: Vec<u8>, width: u16) -> Result<Vec<u8>> {
50 let width_usize = usize::from(width);
51 let text = html2text::from_read_with_decorator(
52 html.as_slice(),
53 width_usize,
54 crate::text_decorator::PlainTextDecorator::new(),
55 )
56 .map_err(|e| anyhow::anyhow!("Failed to parse HTML to text: {e}"))?;
57 Ok(text.into_bytes())
58}
59
60pub fn sanitize_html(document: Vec<u8>) -> Vec<u8> {
61 let mut builder = ammonia::Builder::default();
62
63 builder.add_generic_attributes(iter::once("class").chain(iter::once("id")));
64
65 builder
66 .clean(&String::from_utf8_lossy(&document))
67 .to_string()
68 .into_bytes()
69}
70
71#[cfg(test)]
72#[allow(
73 clippy::panic,
74 clippy::expect_used,
75 clippy::unwrap_used,
76 clippy::unwrap_in_result,
77 clippy::panic_in_result_fn,
78 clippy::indexing_slicing,
79 clippy::arithmetic_side_effects,
80 reason = "Standard repository test boilerplate"
81)]
82mod tests {
83 use super::*;
84
85 #[crate::ctb_test]
86 fn test_html2text_no_markdown_links() -> Result<()> {
87 let html = b"<p>Visit <a href=\"https://example.com/\">our website</a> for more details.</p>";
88 let text = html2text(html.to_vec())?;
89 let text_str = String::from_utf8(text)?;
90 assert_eq!(text_str.trim(), "Visit our website for more details.");
91 Ok(())
92 }
93
94 #[crate::ctb_test]
95 fn test_html2text_preserves_lists_and_quotes() -> Result<()> {
96 let html = b"<ul><li>Alpha</li><li>Beta</li></ul><blockquote><p>Quote text</p></blockquote>";
97 let text = html2text(html.to_vec())?;
98 let text_str = String::from_utf8(text)?;
99 assert!(text_str.contains("* Alpha"));
100 assert!(text_str.contains("* Beta"));
101 assert!(text_str.contains("> Quote text"));
102 Ok(())
103 }
104}