1use scraper::{ElementRef, Html, Node};
4use serde::Serialize;
5
6use crate::commands::{CliPost, CliPostSubmitted, CliTrendingHashtag};
7
8const BLOCK_ELEMENTS: &[&str] = &["p", "div", "li", "ul", "ol", "blockquote", "pre", "h1", "h2", "h3", "h4", "h5", "h6"];
9
10pub fn render_post_html_to_text(post_html: &str) -> String {
22 let fragment = Html::parse_fragment(post_html);
23 let mut output = String::new();
24 render_children(fragment.root_element(), &mut output);
25 sanitize_for_terminal(output.trim_end_matches('\n'))
26}
27
28pub fn sanitize_for_terminal(text: &str) -> String {
32 let mut sanitized = String::with_capacity(text.len());
33 for character in text.chars() {
34 if character.is_control() && character != '\n' && character != '\t' {
35 sanitized.extend(character.escape_unicode());
36 } else {
37 sanitized.push(character);
38 }
39 }
40 sanitized
41}
42
43fn ensure_line_break(output: &mut String) {
44 if !output.is_empty() && !output.ends_with('\n') {
45 output.push('\n');
46 }
47}
48
49fn render_children(element_ref: ElementRef, output: &mut String) {
50 for child in element_ref.children() {
51 match child.value() {
52 Node::Text(text) => output.push_str(text),
53 Node::Element(_) => {
54 if let Some(child_element_ref) = ElementRef::wrap(child) {
55 render_element(child_element_ref, output);
56 }
57 }
58 _ => {}
59 }
60 }
61}
62
63fn render_element(element_ref: ElementRef, output: &mut String) {
64 let element = element_ref.value();
65 match element.name() {
66 "br" => output.push('\n'),
67 "mention" => {
68 output.push('@');
69 output.push_str(element.attr("client_id").unwrap_or_default());
70 render_children(element_ref, output);
73 }
74 "span" | "div" if element.attr("data-type").is_some_and(|data_type| data_type.ends_with("math-editor")) => {
76 let is_block = element.name() == "div";
77 if is_block {
78 ensure_line_break(output);
79 }
80 output.push('$');
81 output.push_str(element.attr("latex").unwrap_or_default());
82 output.push('$');
83 render_children(element_ref, output);
84 if is_block {
85 ensure_line_break(output);
86 }
87 }
88 "hashtag" => {
89 let mut visible_text = String::new();
90 render_children(element_ref, &mut visible_text);
91 if visible_text.is_empty() {
92 output.push('#');
93 output.push_str(element.attr("hashtag").unwrap_or_default());
94 } else {
95 output.push_str(&visible_text);
96 }
97 }
98 "img" => {
99 output.push_str("[image: ");
100 output.push_str(element.attr("src").unwrap_or_default());
101 output.push(']');
102 }
103 "a" => {
104 let mut link_text = String::new();
105 render_children(element_ref, &mut link_text);
106 output.push_str(&link_text);
107 let link_text_without_images = element_ref.text().collect::<String>();
109 if let Some(href) = element.attr("href") {
110 if !link_text_without_images.trim().is_empty() && link_text.trim() != href {
111 output.push_str(" <");
112 output.push_str(href);
113 output.push('>');
114 }
115 }
116 }
117 name if BLOCK_ELEMENTS.contains(&name) => {
118 ensure_line_break(output);
119 render_children(element_ref, output);
120 ensure_line_break(output);
121 }
122 _ => render_children(element_ref, output),
123 }
124}
125
126pub fn format_time_millis(time_millis: i64) -> String {
127 match chrono::DateTime::from_timestamp_millis(time_millis) {
128 Some(date_time) => date_time.format("%Y-%m-%d %H:%M:%SZ").to_string(),
129 None => format!("{}ms", time_millis),
130 }
131}
132
133pub fn format_posts_text(cli_posts: &[CliPost]) -> String {
134 if cli_posts.is_empty() {
135 return "(no posts)".to_string();
136 }
137 let mut output = String::new();
138 for (index, cli_post) in cli_posts.iter().enumerate() {
139 if index > 0 {
140 output.push('\n');
141 }
142 output.push_str(&format!("POST>> {} {} post:{}{}\n", format_time_millis(cli_post.time_millis), cli_post.client_id, cli_post.post_id, if cli_post.healed { " (healed)" } else { "" }));
143 output.push_str(&render_post_html_to_text(&cli_post.post_html));
144 output.push('\n');
145 }
146 output.trim_end_matches('\n').to_string()
147}
148
149pub fn format_trending_text(cli_trending_hashtags: &[CliTrendingHashtag]) -> String {
150 if cli_trending_hashtags.is_empty() {
151 return "(no trending hashtags)".to_string();
152 }
153 let count_width = cli_trending_hashtags.iter().map(|cli_trending_hashtag| cli_trending_hashtag.count.to_string().len()).max().unwrap_or(1);
154 cli_trending_hashtags
155 .iter()
156 .map(|cli_trending_hashtag| format!("{:>count_width$} #{}", cli_trending_hashtag.count, sanitize_for_terminal(&cli_trending_hashtag.hashtag)))
157 .collect::<Vec<_>>()
158 .join("\n")
159}
160
161pub fn format_post_submitted_text(cli_post_submitted: &CliPostSubmitted) -> String {
162 let mut output = format!("posted {}", cli_post_submitted.post_id);
163 for bucket_location in &cli_post_submitted.bucket_locations {
164 output.push_str(&format!("\n {}", bucket_location));
165 }
166 output
167}
168
169pub fn format_json<T: Serialize + ?Sized>(value: &T) -> anyhow::Result<String> {
170 Ok(serde_json::to_string_pretty(value)?)
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176 use hashiverse_lib::tools::plain_text_post::{convert_text_to_hashiverse_html, convert_text_to_hashiverse_html_x_url_preview};
177
178 fn assert_round_trip(text: &str) {
179 let post_html = convert_text_to_hashiverse_html(text);
180 assert_eq!(render_post_html_to_text(&post_html), text, "html was: {}", post_html);
181 }
182
183 #[test]
184 fn round_trip_plain_text() {
185 assert_round_trip("hello world");
186 }
187
188 #[test]
189 fn round_trip_hashtags_preserve_case() {
190 assert_round_trip("I like #Rust and #wasm32 a lot");
191 }
192
193 #[test]
194 fn round_trip_mention() {
195 assert_round_trip(&format!("hi @{} how are you", "ab".repeat(32)));
196 }
197
198 #[test]
199 fn round_trip_newlines() {
200 assert_round_trip("line one\nline two\n\nline four");
201 }
202
203 #[test]
204 fn round_trip_escaped_characters() {
205 assert_round_trip("a < b && c > \"d\" <script>alert(1)</script>");
206 }
207
208 #[test]
209 fn round_trip_lone_hash_and_at() {
210 assert_round_trip("# not a tag, @ not a mention, @abc too short");
211 }
212
213 #[test]
214 fn hashtag_without_visible_text_uses_attribute() {
215 assert_eq!(render_post_html_to_text("<hashtag hashtag=\"rust\"></hashtag>"), "#rust");
216 }
217
218 #[test]
219 fn non_closed_mention_does_not_swallow_following_text() {
220 assert_eq!(render_post_html_to_text("hi <mention client_id=\"ab\"/> and the rest"), "hi @ab and the rest");
221 }
222
223 #[test]
224 fn math_renders_its_latex() {
225 assert_eq!(render_post_html_to_text("x <span latex=\"a^2\" data-type=\"inline-math-editor\"></span> y"), "x $a^2$ y");
226 assert_eq!(render_post_html_to_text("x<div latex=\"\\sum\" data-type=\"block-math-editor\"></div>y"), "x\n$\\sum$\ny");
227 }
228
229 #[test]
230 fn news_agent_card_with_hashtags_renders_everything() {
231 let card_html = convert_text_to_hashiverse_html_x_url_preview("Title", "A long description that must not be cut", "", "https://x.org/a");
233 let post_html = format!("{}<p/>{} {}", card_html, hashiverse_lib::tools::plain_text_post::convert_text_to_hashiverse_html_x_hashtag("Tesla"), hashiverse_lib::tools::plain_text_post::convert_text_to_hashiverse_html_x_hashtag("ev"));
234 assert_eq!(render_post_html_to_text(&post_html), "x.org\nTitle <https://x.org/a>\nA long description that must not be cut\n#Tesla #ev");
235 }
236
237 #[test]
238 fn control_characters_in_text_and_attributes_are_escaped() {
239 assert_eq!(render_post_html_to_text("a\u{1b}]52;c;aGk=\u{7}b\u{1b}[31mc"), "a\\u{1b}]52;c;aGk=\\u{7}b\\u{1b}[31mc");
241 assert_eq!(render_post_html_to_text("<img src=\"x\u{1b}[2Jy\">"), "[image: x\\u{1b}[2Jy]");
242 assert_eq!(render_post_html_to_text("<mention client_id=\"\u{9b}31m\"></mention>"), "@\\u{9b}31m");
243 }
244
245 #[test]
246 fn line_breaks_and_tabs_survive_sanitising() {
247 assert_eq!(sanitize_for_terminal("a\nb\tc"), "a\nb\tc");
248 assert_eq!(sanitize_for_terminal("overwrite\rme"), "overwrite\\u{d}me");
249 }
250
251 #[test]
252 fn trending_hashtags_are_sanitised() {
253 let cli_trending_hashtags = vec![CliTrendingHashtag { hashtag: "x\u{1b}[31m".to_string(), count: 1 }];
254 assert_eq!(format_trending_text(&cli_trending_hashtags), "1 #x\\u{1b}[31m");
255 }
256
257 #[test]
258 fn paragraphs_become_lines() {
259 assert_eq!(render_post_html_to_text("<p>first</p><p>second</p>"), "first\nsecond");
260 }
261
262 #[test]
263 fn links_show_href_when_different() {
264 assert_eq!(render_post_html_to_text("<a href=\"https://x.org\">x</a>"), "x <https://x.org>");
265 assert_eq!(render_post_html_to_text("<a href=\"https://x.org\">https://x.org</a>"), "https://x.org");
266 assert_eq!(render_post_html_to_text("<a href=\"https://x.org\"><img src=\"https://x.org/i.png\"></a>"), "[image: https://x.org/i.png]");
267 }
268
269 #[test]
270 fn url_preview_card_renders_readably() {
271 let post_html = convert_text_to_hashiverse_html_x_url_preview("Title", "Desc", "https://x.org/i.png", "https://x.org/a");
272 assert_eq!(render_post_html_to_text(&post_html), "[image: https://x.org/i.png]\nx.org\nTitle <https://x.org/a>\nDesc");
273 }
274
275 fn sample_cli_post() -> CliPost {
276 CliPost {
277 post_id: "11".to_string(),
278 time_millis: 1_700_000_000_000,
279 client_id: "22".to_string(),
280 bucket_location: "1~x".to_string(),
281 post_html: convert_text_to_hashiverse_html("hi #there"),
282 healed: false,
283 }
284 }
285
286 #[test]
287 fn posts_text_has_header_and_body() {
288 assert_eq!(format_posts_text(&[sample_cli_post()]), "POST>> 2023-11-14 22:13:20Z 22 post:11\nhi #there");
289 assert_eq!(format_posts_text(&[]), "(no posts)");
290 }
291
292 #[test]
293 fn posts_json_shape() {
294 let json_value: serde_json::Value = serde_json::from_str(&format_json(&vec![sample_cli_post()]).unwrap()).unwrap();
295 let first = &json_value[0];
296 for field in ["post_id", "time_millis", "client_id", "bucket_location", "post_html", "healed"] {
297 assert!(first.get(field).is_some(), "missing field {}", field);
298 }
299 assert_eq!(first["time_millis"], 1_700_000_000_000i64);
300 }
301
302 #[test]
303 fn trending_text_aligns_counts() {
304 let cli_trending_hashtags = vec![
305 CliTrendingHashtag { hashtag: "rust".to_string(), count: 120 },
306 CliTrendingHashtag { hashtag: "wasm".to_string(), count: 7 },
307 ];
308 assert_eq!(format_trending_text(&cli_trending_hashtags), "120 #rust\n 7 #wasm");
309 }
310
311 #[test]
312 fn post_submitted_text() {
313 let cli_post_submitted = CliPostSubmitted { post_id: "ab".to_string(), bucket_locations: vec!["loc1".to_string(), "loc2".to_string()] };
314 assert_eq!(format_post_submitted_text(&cli_post_submitted), "posted ab\n loc1\n loc2");
315 }
316}