1use nostr_sdk::prelude::{EventId, Nip21, NostrParser, PublicKey, RelayUrl, ToBech32, Token, Url};
26
27use crate::http;
28use crate::nostr::markdown::{self, Block, Run, Style};
29use crate::nostr::outbox::Whereabouts;
30use crate::youtube;
31
32pub const FEED_NOTE_MAX_CHARS: usize = 600;
36
37const LINK_LABEL_MAX_CHARS: usize = 50;
39
40const REFERENCE_CHARS: usize = 12;
42
43const MAX_NOTE_IMAGES: usize = 4;
45
46const MAX_NOTE_VIDEOS: usize = 4;
48
49pub const MAX_NOTE_QUOTES: usize = 3;
51
52pub const QUOTE_DEPTH: usize = 2;
56
57const IMAGE_EXTENSIONS: [&str; 6] = ["jpg", "jpeg", "png", "gif", "webp", "bmp"];
59
60const VIDEO_EXTENSIONS: [&str; 7] = ["mp4", "webm", "mov", "mkv", "m4v", "ogv", "avi"];
64
65const FILE_EXTENSIONS: [&str; 16] =
68 ["svg", "avif", "heic", "tiff", "m3u8", "mp3", "m4a", "ogg", "opus", "wav", "flac", "pdf", "zip", "gz", "json", "txt"];
69
70const MENTION_CHARS: usize = 16;
73
74const CODE_CHARS_PER_FOUR: usize = 5;
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum Segment {
81 Text(String),
83 Styled { text: String, style: Style },
86 Link { url: String, label: String },
88 Mention(PublicKey),
91 Hashtag(String),
93 Reference(String),
96 Block(Block<Vec<Segment>>),
100}
101
102impl Segment {
103 pub fn words(&self, named: &dyn Fn(&PublicKey) -> String) -> String {
106 match self {
107 Self::Text(text) | Self::Styled { text, .. } => text.clone(),
108 Self::Link { label, .. } | Self::Reference(label) => label.clone(),
109 Self::Mention(person) => named(person),
110 Self::Hashtag(tag) => format!("#{tag}"),
111 Self::Block(Block::Code(code)) => format!(" {code} "),
112 Self::Block(Block::Rule) => " ".to_string(),
113 Self::Block(Block::Table(table)) => {
114 let cells =
115 table.rows.iter().flatten().map(|cell| cell.iter().map(|piece| piece.words(named)).collect::<String>());
116 format!(" {} ", cells.collect::<Vec<_>>().join(" "))
117 }
118 }
119 }
120}
121
122pub fn inline(segments: &[Segment]) -> impl Iterator<Item = &Segment> {
125 segments.iter().flat_map(|segment| -> Box<dyn Iterator<Item = &Segment>> {
126 match segment {
127 Segment::Block(Block::Table(table)) => Box::new(table.rows.iter().flatten().flatten()),
128 other => Box::new(std::iter::once(other)),
129 }
130 })
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Quote {
138 pub id: EventId,
140 pub author: Option<PublicKey>,
143 pub relay: Option<RelayUrl>,
144 pub label: String,
147}
148
149impl Quote {
150 pub fn whereabouts(&self) -> Whereabouts {
153 Whereabouts { author: self.author, relay: self.relay.clone() }
154 }
155}
156
157#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct NoteImage {
161 pub url: String,
162 pub label: String,
165 pub size: Option<(u32, u32)>,
168}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct NoteVideo {
174 pub url: String,
175 pub label: String,
177 pub size: Option<(u32, u32)>,
180 pub posters: Vec<String>,
184 pub page: bool,
188}
189
190#[derive(Debug, Clone, Default, PartialEq, Eq)]
193pub struct Attachment {
194 pub url: String,
196 pub kind: Option<String>,
198 pub size: Option<(u32, u32)>,
200 pub picture: Option<String>,
203}
204
205#[derive(Debug, Clone, Default, PartialEq, Eq)]
208pub struct Whole {
209 pub segments: Vec<Segment>,
210 pub line_chars: Vec<usize>,
212}
213
214#[derive(Debug, Clone, Default, PartialEq, Eq)]
216pub struct Content {
217 pub segments: Vec<Segment>,
219 pub whole: Option<Whole>,
222 pub images: Vec<NoteImage>,
225 pub videos: Vec<NoteVideo>,
227 pub quotes: Vec<Quote>,
230 pub line_chars: Vec<usize>,
234 pub preview: Option<String>,
237 pub first_link: Option<String>,
242}
243
244pub(crate) fn link_label(url: &Url) -> String {
247 let host = url.host_str().unwrap_or_default();
248 let host = host.strip_prefix("www.").unwrap_or(host);
249 let path = if url.path() == "/" { "" } else { url.path() };
250 let label = format!("{host}{path}");
251 match label.char_indices().nth(LINK_LABEL_MAX_CHARS) {
252 Some(_) => {
253 let head: String = label.chars().take(LINK_LABEL_MAX_CHARS - 1).collect();
254 format!("{head}\u{2026}")
255 }
256 None => label,
257 }
258}
259
260fn labelled(url: &Url, label: Option<&str>) -> String {
266 let Some(label) = label.map(str::trim).filter(|label| !label.is_empty()) else {
267 return link_label(url);
268 };
269 let host = url.host_str().unwrap_or_default();
270 let host = host.strip_prefix("www.").unwrap_or(host);
271 if label.to_lowercase().contains(&host.to_lowercase()) { label.to_string() } else { format!("{label} ({host})") }
272}
273
274fn has_extension(url: &Url, extensions: &[&str]) -> bool {
276 url.path().rsplit_once('.').is_some_and(|(_, extension)| extensions.iter().any(|known| extension.eq_ignore_ascii_case(known)))
277}
278
279fn is_image(url: &Url) -> bool {
282 url.scheme() == "https" && has_extension(url, &IMAGE_EXTENSIONS)
283}
284
285fn is_video(url: &Url, said: Option<&Attachment>) -> bool {
289 let called_one = said.and_then(|said| said.kind.as_deref()).is_some_and(http::is_video);
290 url.scheme() == "https" && (has_extension(url, &VIDEO_EXTENSIONS) || called_one || youtube::video(url).is_some())
291}
292
293fn may_be_page(url: &Url) -> bool {
297 url.scheme() == "https"
298 && ![&IMAGE_EXTENSIONS[..], &VIDEO_EXTENSIONS, &FILE_EXTENSIONS].iter().any(|extensions| has_extension(url, extensions))
299}
300
301fn short_reference(bech32: &str) -> String {
303 let head: String = bech32.chars().take(REFERENCE_CHARS).collect();
304 format!("{head}\u{2026}")
305}
306
307fn quote(id: EventId, author: Option<PublicKey>, relay: Option<RelayUrl>) -> Quote {
310 let Ok(note) = id.to_bech32();
313 Quote { id, author, relay, label: short_reference(¬e) }
314}
315
316enum Named {
318 Inline(Segment),
320 Quote(Quote),
322}
323
324fn named(uri: Nip21) -> Named {
326 match uri {
327 Nip21::Pubkey(public_key) => Named::Inline(Segment::Mention(public_key)),
328 Nip21::Profile(profile) => Named::Inline(Segment::Mention(profile.public_key)),
329 Nip21::EventId(id) => Named::Quote(quote(id, None, None)),
330 Nip21::Event(event) => Named::Quote(quote(event.event_id, event.author, event.relays.into_iter().next())),
331 Nip21::Coordinate(coordinate) => Named::Inline(Segment::Reference(
332 coordinate.to_bech32().map_or_else(|_| "naddr1\u{2026}".to_string(), |naddr| short_reference(&naddr)),
333 )),
334 }
335}
336
337struct Builder<'a> {
339 content: Content,
340 attached: &'a [Attachment],
342 room: usize,
344 full: bool,
346 gap: bool,
349}
350
351impl<'a> Builder<'a> {
352 fn new(max_chars: usize, attached: &'a [Attachment]) -> Self {
353 Self {
354 content: Content { line_chars: vec![0], ..Content::default() },
355 attached,
356 room: max_chars,
357 full: false,
358 gap: false,
359 }
360 }
361
362 fn repeats(&self, space: char) -> bool {
366 match self.content.segments.last() {
367 Some(Segment::Text(before) | Segment::Styled { text: before, .. }) => before.ends_with(space),
368 Some(Segment::Block(_)) | None => true,
369 Some(_) => false,
370 }
371 }
372
373 fn said_of(&self, url: &Url) -> Option<&'a Attachment> {
375 self.attached.iter().find(|said| said.url == url.as_str())
376 }
377
378 fn image(&mut self, url: &Url) {
381 if self.content.images.len() < MAX_NOTE_IMAGES {
382 let size = self.said_of(url).and_then(|said| said.size);
383 self.content.images.push(NoteImage { url: url.to_string(), label: link_label(url), size });
384 }
385 }
386
387 fn video(&mut self, url: &Url) {
389 if self.content.videos.len() >= MAX_NOTE_VIDEOS {
390 return;
391 }
392 let (said, hosted) = (self.said_of(url), youtube::video(url));
393 let (url, label) = (url.to_string(), link_label(url));
394 self.content.videos.push(match hosted {
395 Some(hosted) => NoteVideo { url, label, size: hosted.size, posters: hosted.posters(), page: true },
397 None => NoteVideo {
398 url,
399 label,
400 size: said.and_then(|said| said.size),
401 posters: said.and_then(|said| said.picture.clone()).into_iter().collect(),
402 page: false,
403 },
404 });
405 }
406
407 fn quote(&mut self, quote: Quote) {
410 if !self.content.quotes.iter().any(|known| known.id == quote.id) {
411 self.content.quotes.push(quote);
412 }
413 }
414
415 fn finish(mut self) -> Content {
418 if let Some(Segment::Text(first)) = self.content.segments.first_mut() {
419 *first = first.trim_start().to_string();
420 }
421 if let Some(Segment::Text(last)) = self.content.segments.last_mut() {
422 last.truncate(last.trim_end().len());
423 }
424 self.content.segments.retain(|segment| !matches!(segment, Segment::Text(text) if text.is_empty()));
425 while self.content.line_chars.len() > 1 && self.content.line_chars.last() == Some(&0) {
426 self.content.line_chars.pop();
427 }
428 while self.content.line_chars.len() > 1 && self.content.line_chars.first() == Some(&0) {
429 self.content.line_chars.remove(0);
430 }
431 self.content
432 }
433
434 fn count(&mut self, chars: usize) {
436 if let Some(line) = self.content.line_chars.last_mut() {
437 *line += chars;
438 }
439 self.room = self.room.saturating_sub(chars);
440 }
441
442 fn append(&mut self, text: &str, style: Style) {
445 match self.content.segments.last_mut() {
446 Some(Segment::Text(last)) if style.is_plain() => last.push_str(text),
447 Some(Segment::Styled { text: last, style: same }) if *same == style => last.push_str(text),
448 _ if style.is_plain() => self.content.segments.push(Segment::Text(text.to_string())),
449 _ => self.content.segments.push(Segment::Styled { text: text.to_string(), style }),
450 }
451 }
452
453 fn cut(&mut self) {
455 if let Some(Segment::Text(last)) = self.content.segments.last_mut() {
456 last.truncate(last.trim_end().len());
457 }
458 if matches!(self.content.segments.last(), Some(Segment::Block(_))) {
460 self.count(1);
461 }
462 self.append("\u{2026}", Style::default());
463 self.full = true;
464 }
465
466 fn run(&mut self, run: Run) {
468 match run {
469 Run::Text { text, style } => self.read(&text, style),
470 Run::Code { .. } if self.full => {}
471 Run::Code { text, style } => {
472 self.gap = false;
473 self.text(&text, style);
474 }
475 Run::Link { url, label } => self.link(url, Some(&label), Style::default()),
476 Run::Block(block) => self.block(block),
477 }
478 }
479
480 fn block(&mut self, block: Block<Vec<Run>>) {
483 self.gap = false;
484 let chars = |runs: &[Run]| -> usize {
485 runs.iter()
486 .map(|run| match run {
487 Run::Text { text, .. } | Run::Code { text, .. } => text.chars().count(),
488 Run::Link { label, .. } => label.chars().count(),
489 Run::Block(_) => 0,
490 })
491 .sum()
492 };
493 match block {
494 Block::Rule if !self.full => self.stand_apart(Block::Rule),
495 Block::Code(code) if !self.full => {
496 let wanted = code.chars().count();
497 let fits: String = code.chars().take(self.room).collect();
498 let fits = fits.trim_end();
499 if !fits.is_empty() {
500 self.stand_apart(Block::Code(fits.to_string()));
501 }
502 if wanted > self.room {
503 self.cut();
504 }
505 self.room = self.room.saturating_sub(wanted);
506 }
507 Block::Rule | Block::Code(_) => {}
508 Block::Table(table) => {
509 let wanted: usize = table.rows.iter().flatten().map(|cell| chars(cell)).sum();
510 let fits = !self.full && wanted <= self.room;
511 if !fits && !self.full {
512 self.cut();
513 }
514 let room = std::mem::replace(&mut self.room, usize::MAX);
518 let block = Block::Table(table).map(|cell| self.cell(cell));
519 self.room = room.saturating_sub(usize::MAX - self.room);
520 if fits {
521 self.stand_apart(block);
522 }
523 }
524 }
525 }
526
527 fn cell(&mut self, runs: Vec<Run>) -> Vec<Segment> {
530 let text = std::mem::take(&mut self.content.segments);
531 let lines = std::mem::replace(&mut self.content.line_chars, vec![0]);
532 self.gap = false;
533 for run in runs {
534 self.run(run);
535 }
536 self.gap = false;
537 self.content.line_chars = lines;
538 let mut cell = std::mem::replace(&mut self.content.segments, text);
539 if let Some(Segment::Text(first)) = cell.first_mut() {
540 *first = first.trim_start().to_string();
541 }
542 if let Some(Segment::Text(last)) = cell.last_mut() {
543 last.truncate(last.trim_end().len());
544 }
545 cell.retain(|piece| !matches!(piece, Segment::Text(text) if text.is_empty()));
546 cell
547 }
548
549 fn stand_apart(&mut self, block: Block<Vec<Segment>>) {
553 while let Some(Segment::Text(last) | Segment::Styled { text: last, .. }) = self.content.segments.last_mut() {
554 last.truncate(last.trim_end().len());
555 if !last.is_empty() {
556 break;
557 }
558 self.content.segments.pop();
559 }
560 while self.content.line_chars.len() > 1 && self.content.line_chars.last() == Some(&0) {
561 self.content.line_chars.pop();
562 }
563 self.content.segments.push(Segment::Block(block));
564 if self.content.line_chars.last().is_some_and(|chars| *chars > 0) {
565 self.content.line_chars.push(0);
566 }
567 }
568
569 fn text(&mut self, text: &str, style: Style) {
571 for (index, line) in text.split('\n').enumerate() {
572 if index > 0 {
573 self.append("\n", style);
574 self.content.line_chars.push(0);
575 }
576 let chars = line.chars().count();
577 if chars > self.room {
578 let fits: String = line.chars().take(self.room).collect();
579 self.append(&fits, style);
580 self.count(self.room);
581 self.cut();
582 return;
583 }
584 self.append(line, style);
585 self.count(if style.code { (chars * CODE_CHARS_PER_FOUR).div_ceil(4) } else { chars });
587 }
588 }
589
590 fn read(&mut self, text: &str, style: Style) {
594 for token in NostrParser::new().parse(text) {
595 let token = match token {
596 Token::Url(url) => {
597 self.link(url, None, style);
598 continue;
599 }
600 token => token,
601 };
602 let was_gap = std::mem::take(&mut self.gap);
606 match token {
607 Token::Nostr(uri) => match named(uri) {
608 Named::Quote(quote) => {
609 self.quote(quote);
610 self.gap = true;
611 }
612 Named::Inline(_) if self.full => {}
616 Named::Inline(segment) => {
617 let chars = match &segment {
618 Segment::Reference(label) => label.chars().count(),
619 _ => MENTION_CHARS,
620 };
621 self.whole(segment, chars);
622 }
623 },
624 _ if self.full => {}
625 Token::Whitespace if was_gap && self.repeats(' ') => self.gap = true,
626 Token::LineBreak if was_gap && self.repeats('\n') => self.gap = true,
627 Token::Text(text) => self.text(text, style),
628 Token::Whitespace => self.text(" ", style),
629 Token::LineBreak => self.text("\n", style),
630 Token::Hashtag(tag) => {
631 let tag = tag.trim_start_matches('#');
632 self.whole(Segment::Hashtag(tag.to_string()), tag.chars().count() + 1);
633 }
634 Token::Url(_) => {}
636 }
637 }
638 }
639
640 fn link(&mut self, url: Url, label: Option<&str>, style: Style) {
645 let video = is_video(&url, self.said_of(&url));
646 if !video && may_be_page(&url) {
649 self.content.preview = Some(url.to_string());
650 }
651 if self.content.first_link.is_none() && (video || (!is_image(&url) && matches!(url.scheme(), "http" | "https"))) {
654 self.content.first_link = Some(url.to_string());
655 }
656 self.gap = false;
657 if video {
658 self.video(&url);
659 self.gap = true;
660 } else if is_image(&url) {
661 self.image(&url);
662 self.gap = true;
663 } else if self.full {
664 } else if matches!(url.scheme(), "http" | "https") {
665 let label = labelled(&url, label);
666 let chars = label.chars().count();
667 self.whole(Segment::Link { url: url.to_string(), label }, chars);
668 } else {
669 self.text(url.as_str(), style);
671 }
672 }
673
674 fn whole(&mut self, segment: Segment, chars: usize) {
677 if chars > self.room {
678 self.cut();
679 } else {
680 self.content.segments.push(segment);
681 self.count(chars);
682 }
683 }
684}
685
686pub fn parse(content: &str, max_chars: usize) -> Content {
689 parse_attached(content, max_chars, &[])
690}
691
692pub fn parse_attached(content: &str, max_chars: usize, attached: &[Attachment]) -> Content {
694 let (mut cut, was_cut) = parse_up_to(content, max_chars, attached);
695 if was_cut {
696 let (whole, _) = parse_up_to(content, usize::MAX, attached);
699 cut.whole = Some(Whole { segments: whole.segments, line_chars: whole.line_chars });
700 }
701 cut
702}
703
704fn parse_up_to(content: &str, max_chars: usize, attached: &[Attachment]) -> (Content, bool) {
707 let mut builder = Builder::new(max_chars, attached);
708 for run in markdown::runs(content.trim()) {
709 builder.run(run);
710 }
711 let was_cut = builder.full;
712 (builder.finish(), was_cut)
713}
714
715fn parse_dimensions(dim: &str) -> Option<(u32, u32)> {
717 let (width, height) = dim.split_once('x')?;
718 Some((width.parse().ok()?, height.parse().ok()?)).filter(|(width, height)| *width > 0 && *height > 0)
719}
720
721pub fn imeta(tag: &[String]) -> Option<Attachment> {
724 let mut fields = tag.iter();
725 if fields.next().map(String::as_str) != Some("imeta") {
726 return None;
727 }
728 let https = |value: &str| Url::parse(value.trim()).ok().filter(|url| url.scheme() == "https").map(String::from);
729 let (mut url, mut said, mut thumb) = (None, Attachment::default(), None);
730 for field in fields {
731 match field.split_once(' ') {
732 Some(("url", value)) => url = Url::parse(value.trim()).ok(),
733 Some(("m", value)) => said.kind = Some(value.trim().to_string()),
734 Some(("dim", value)) => said.size = parse_dimensions(value.trim()),
735 Some(("image", value)) => said.picture = https(value),
736 Some(("thumb", value)) => thumb = https(value),
737 _ => {}
738 }
739 }
740 Some(Attachment { url: url?.to_string(), picture: said.picture.or(thumb), ..said })
741}
742
743impl Content {
744 pub fn text(&self, in_full: bool) -> (&[Segment], &[usize]) {
747 match &self.whole {
748 Some(whole) if in_full => (&whole.segments, &whole.line_chars),
749 _ => (&self.segments, &self.line_chars),
750 }
751 }
752
753 pub fn mentions(&self) -> impl Iterator<Item = PublicKey> + '_ {
757 inline(self.text(true).0).filter_map(|segment| match segment {
758 Segment::Mention(public_key) => Some(*public_key),
759 _ => None,
760 })
761 }
762}
763
764#[cfg(test)]
765mod tests {
766 use super::{Attachment, Content, FEED_NOTE_MAX_CHARS, NoteImage, NoteVideo, Quote, Segment, imeta, parse, parse_attached};
767 use crate::nostr::markdown::{Block, Style};
768 use nostr_sdk::prelude::{EventId, Keys, Nip19Event, Nip19Profile, RelayUrl, ToBech32};
769
770 fn text(text: &str) -> Segment {
771 Segment::Text(text.to_string())
772 }
773
774 fn link(url: &str, label: &str) -> Segment {
775 Segment::Link { url: url.to_string(), label: label.to_string() }
776 }
777
778 fn segments(content: &str) -> Vec<Segment> {
779 parse(content, 10_000).segments
780 }
781
782 #[test]
783 fn plain_text_stays_one_piece_with_its_line_breaks() {
784 let content = parse(" gm nostr\n\nhow is everyone? ", 10_000);
785 assert_eq!(content.segments, [text("gm nostr\n\nhow is everyone?")]);
786 assert_eq!(content.line_chars, [8, 0, 16]);
787 }
788
789 #[test]
790 fn a_link_is_labelled_by_host_and_path_and_keeps_its_address() {
791 assert_eq!(
792 segments("read https://www.example.com/a/page?utm=1, then reply"),
793 [text("read "), link("https://www.example.com/a/page?utm=1", "example.com/a/page"), text(", then reply")]
794 );
795 assert_eq!(segments("https://example.com"), [link("https://example.com/", "example.com")]);
796 }
797
798 fn styled(text: &str, style: Style) -> Segment {
800 Segment::Styled { text: text.to_string(), style }
801 }
802
803 const BOLD: Style = Style { bold: true, italic: false, strike: false, code: false, quiet: false, heading: 0 };
804 const ITALIC: Style = Style { italic: true, bold: false, ..BOLD };
805 const CODE: Style = Style { code: true, bold: false, ..BOLD };
806
807 #[test]
808 fn what_a_note_marks_is_set_so_and_read_for_links_and_hashtags_like_the_rest() {
809 assert_eq!(
810 segments("**gm** #nostr, *see https://example.com/a now* and **#bitcoin**"),
811 [
812 styled("gm", BOLD),
813 text(" "),
814 Segment::Hashtag("nostr".into()),
815 text(", "),
816 styled("see ", ITALIC),
817 link("https://example.com/a", "example.com/a"),
818 styled(" now", ITALIC),
819 text(" and "),
820 Segment::Hashtag("bitcoin".into()),
821 ]
822 );
823 }
824
825 #[test]
826 fn code_is_shown_as_written_and_read_for_nothing() {
827 let content = parse("run `curl https://example.com/x #now` first", 10_000);
828 assert_eq!(content.segments, [text("run "), styled("curl https://example.com/x #now", CODE), text(" first")]);
829 assert_eq!((content.preview, content.first_link), (None, None), "what is in code is no link");
830 assert_eq!(parse("`abcdefgh`", 10_000).line_chars, [10]);
832 }
833
834 #[test]
835 fn a_link_the_note_labels_says_its_label_and_where_it_goes() {
836 let labelled = |written: &str| match segments(written).as_slice() {
837 [Segment::Link { label, .. }] => label.clone(),
838 other => panic!("not one link: {other:?}"),
839 };
840 assert_eq!(labelled("[the docs](https://docs.rs/nostr)"), "the docs (docs.rs)");
842 assert_eq!(labelled("[paypal.com](https://evil.example/paypal.com)"), "paypal.com (evil.example)");
844 assert_eq!(labelled("[docs.rs/nostr](https://www.docs.rs/nostr)"), "docs.rs/nostr");
846 assert_eq!(labelled("[](https://example.com/a/page)"), "example.com/a/page");
848
849 let content = parse("see [this](https://example.com/page)", 10_000);
851 assert_eq!(content.preview.as_deref(), Some("https://example.com/page"));
852 assert_eq!(content.first_link.as_deref(), Some("https://example.com/page"));
853 let content = parse("look  there", 10_000);
855 assert_eq!(content.segments, [text("look there")]);
856 assert_eq!(content.images.iter().map(|image| image.url.as_str()).collect::<Vec<_>>(), ["https://example.com/cat.png"]);
857 }
858
859 #[test]
860 fn a_note_cut_inside_what_it_marks_is_cut_as_any_other() {
861 let content = parse(&format!("**{}**", "bold ".repeat(40).trim_end()), 12);
862 assert_eq!(content.segments, [styled("bold bold bo", BOLD), text("\u{2026}")]);
863 assert!(content.whole.is_some());
864 }
865
866 #[test]
867 fn a_table_stands_apart_and_its_cells_are_read_as_the_text_is() {
868 let friend = Keys::generate().public_key();
869 let written = format!(
870 "Who:\n\n| Who | Where |\n|---|---|\n| nostr:{} | #nostr at https://example.com/page |\n| a cat | https://example.com/cat.png |\n\nso",
871 friend.to_bech32().unwrap()
872 );
873 let content = parse(&written, 10_000);
874 let [Segment::Text(before), Segment::Block(Block::Table(table)), Segment::Text(after)] = content.segments.as_slice()
875 else {
876 panic!("text, a table, text: {:?}", content.segments);
877 };
878 assert_eq!((before.as_str(), after.as_str()), ("Who:", "so"), "no line break is left on either side");
879 assert_eq!(
880 table.rows,
881 [
882 vec![vec![text("Who")], vec![text("Where")]],
883 vec![
884 vec![Segment::Mention(friend)],
885 vec![Segment::Hashtag("nostr".into()), text(" at "), link("https://example.com/page", "example.com/page")]
886 ],
887 vec![vec![text("a cat")], vec![]],
889 ]
890 );
891 assert_eq!(content.images.iter().map(|image| image.url.as_str()).collect::<Vec<_>>(), ["https://example.com/cat.png"]);
892 assert_eq!(content.preview.as_deref(), Some("https://example.com/page"));
893 assert_eq!(content.mentions().collect::<Vec<_>>(), [friend], "who is named in a cell is named");
894 assert_eq!(content.line_chars, [4, 2]);
896 }
897
898 #[test]
899 fn a_table_is_shown_whole_or_not_at_all_and_code_as_far_as_there_is_room() {
900 let table = "| a | b |\n|---|---|\n| one | two |\n| three | https://example.com/cat.png |";
901 let content = parse(&format!("see\n{table}"), 12);
902 assert_eq!(content.segments, [text("see\u{2026}")]);
903 assert_eq!(content.images.len(), 1, "what a cell sets aside is found past the cut");
904 let whole = content.whole.expect("it was cut");
905 assert!(matches!(whole.segments.as_slice(), [Segment::Text(_), Segment::Block(Block::Table(_))]), "{:?}", whole.segments);
906
907 let content = parse("```\nlet a = 1;\nlet b = 2;\n```", 12);
908 assert_eq!(content.segments, [Segment::Block(Block::Code("let a = 1;\nl".into())), text("\u{2026}")]);
909 assert!(content.whole.is_some());
910 }
911
912 #[test]
913 fn what_stands_apart_reads_as_words_where_there_is_one_line_for_a_note() {
914 let content = parse("Dams\n|Where|Count|\n|-|-|\n|U.S.|92,000+|\n---\n```\ncode\n```", 10_000);
915 let said: String = content.segments.iter().map(|piece| piece.words(&|_| String::new())).collect();
916 assert_eq!(said.split_whitespace().collect::<Vec<_>>().join(" "), "Dams Where Count U.S. 92,000+ code");
917 }
918
919 #[test]
920 fn a_long_link_gets_a_short_label() {
921 let url = format!("https://example.com/{}", "x".repeat(100));
922 let parsed = segments(&url);
923 let [Segment::Link { url: target, label }] = &parsed[..] else {
924 panic!("one link");
925 };
926 assert_eq!(target, &url, "the address is whole");
927 assert_eq!(label.chars().count(), 50);
928 assert!(label.ends_with('…'));
929 }
930
931 #[test]
932 fn only_web_links_are_links() {
933 for content in ["file:///etc/passwd", "javascript://alert(1)", "ftp://example.com/file"] {
935 assert!(
936 segments(content).iter().all(|segment| matches!(segment, Segment::Text(_))),
937 "{content} must stay text: {:?}",
938 segments(content)
939 );
940 }
941 }
942
943 #[test]
944 fn people_are_mentioned_by_key_whichever_way_the_key_is_written() {
945 let key = Keys::generate().public_key();
946 let npub = key.to_bech32().unwrap();
947 assert_eq!(segments(&format!("hey nostr:{npub}!")), [text("hey "), Segment::Mention(key), text("!")]);
948
949 let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
950 let nprofile = Nip19Profile::new(key, [relay]).to_bech32().unwrap();
951 let content = parse(&format!("nostr:{nprofile}"), 10_000);
952 assert_eq!(content.segments, [Segment::Mention(key)]);
953 assert_eq!(content.mentions().collect::<Vec<_>>(), [key]);
954 }
955
956 #[test]
957 fn another_note_is_referred_to_by_the_start_of_its_address() {
958 let id = EventId::from_byte_array([7; 32]);
959 let note = id.to_bech32().unwrap();
960 let label = format!("{}…", ¬e[..12]);
961 let content = parse(&format!("look at this\n\nnostr:{note}"), 10_000);
962 assert_eq!(content.quotes, [Quote { id, author: None, relay: None, label: label.clone() }]);
963 assert_eq!((content.segments, content.line_chars), (vec![text("look at this")], vec![12]));
965
966 let author = Keys::generate().public_key();
969 let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
970 let nevent = Nip19Event::new(id).author(author).relays([relay.clone()]).to_bech32().unwrap();
971 let quoted = Quote { id, author: Some(author), relay: Some(relay), label };
972 assert_eq!(parse(&format!("nostr:{nevent}"), 10_000).quotes, [quoted.clone()]);
973
974 let other = EventId::from_byte_array([8; 32]);
977 let long = format!("{} nostr:{nevent} nostr:{note} nostr:{}", "word ".repeat(50), other.to_bech32().unwrap());
978 let content = parse(&long, 20);
979 assert_eq!(content.segments, [text("word word word word…")]);
980 assert_eq!(content.quotes.iter().map(|quote| quote.id).collect::<Vec<_>>(), [id, other]);
981 assert_eq!(content.quotes[0], quoted);
982 }
983
984 #[test]
985 fn hashtags_lose_their_hash() {
986 assert_eq!(segments("#nostr is #fun"), [Segment::Hashtag("nostr".into()), text(" is "), Segment::Hashtag("fun".into())]);
987 }
988
989 #[test]
990 fn a_long_note_is_cut_at_the_limit_and_marked() {
991 let content = parse("one two three four five", 9);
992 assert_eq!(content.segments, [text("one two t…")]);
993
994 assert_eq!(parse("one two three", 8).segments, [text("one two…")]);
996
997 assert_eq!(parse("one two", 7).segments, [text("one two")]);
999 }
1000
1001 #[test]
1002 fn a_note_that_is_cut_keeps_all_of_its_text_beside_what_is_shown() {
1003 let someone = Keys::generate().public_key();
1004 let said = format!("one two three\nfour https://example.com/page nostr:{} five", someone.to_bech32().unwrap());
1005 let content = parse(&said, 9);
1006 assert_eq!(content.segments, [text("one two t…")]);
1007 let whole = content.whole.clone().expect("it was cut");
1008 let all = parse(&said, 10_000);
1009 assert_eq!((&whole.segments, &whole.line_chars), (&all.segments, &all.line_chars));
1010 assert_eq!(whole.line_chars.len(), 2);
1011
1012 assert_eq!(content.text(false), (&content.segments[..], &content.line_chars[..]));
1015 assert_eq!(content.text(true), (&whole.segments[..], &whole.line_chars[..]));
1016 assert_eq!(content.mentions().collect::<Vec<_>>(), [someone]);
1017
1018 assert_eq!(all.whole, None);
1021 assert_eq!(all.text(true), all.text(false));
1022 assert_eq!(parse("one two", 7).whole, None);
1024 assert!(parse("one two", 6).whole.is_some());
1025
1026 let with_picture = format!("{} https://example.com/end.png", "word ".repeat(50));
1028 let cut = parse(&with_picture, 20);
1029 assert_eq!(image_urls(&cut), ["https://example.com/end.png"]);
1030 assert_eq!(cut.whole.map(|whole| whole.segments), Some(parse(&with_picture, 10_000).segments));
1031 }
1032
1033 #[test]
1034 fn a_link_is_shown_whole_or_not_at_all() {
1035 let content = parse("see https://example.com/page now", 10);
1037 assert_eq!(content.segments, [text("see…")]);
1038
1039 let content = parse("see https://example.com/page now", 20);
1041 assert_eq!(content.segments, [text("see "), link("https://example.com/page", "example.com/page"), text("…")]);
1042 assert_eq!(parse("see https://example.com/page now", 22).segments.last(), Some(&text(" n…")));
1043 }
1044
1045 #[test]
1046 fn an_empty_note_has_one_empty_line() {
1047 assert_eq!(parse(" ", 100), Content { line_chars: vec![0], ..Content::default() });
1048 }
1049
1050 fn image_urls(content: &Content) -> Vec<&str> {
1051 content.images.iter().map(|image| image.url.as_str()).collect()
1052 }
1053
1054 #[test]
1055 fn a_picture_is_set_aside_and_leaves_no_gap_in_the_text() {
1056 let content = parse("look at this\n\nhttps://example.com/cat.JPG?size=large\n", 10_000);
1057 assert_eq!(content.segments, [text("look at this")]);
1058 assert_eq!(content.line_chars, [12]);
1059 assert_eq!(
1060 content.images,
1061 [NoteImage { url: "https://example.com/cat.JPG?size=large".into(), label: "example.com/cat.JPG".into(), size: None }]
1062 );
1063
1064 let between = |content: &str| (parse(content, 10_000).segments, parse(content, 10_000).line_chars);
1067 assert_eq!(between("before https://example.com/cat.png after"), (vec![text("before after")], vec![12]));
1068 assert_eq!(between("before\nhttps://example.com/cat.png\nafter"), (vec![text("before\nafter")], vec![6, 5]));
1069 assert_eq!(between("before\n\nhttps://example.com/cat.png\n\nafter"), (vec![text("before\n\nafter")], vec![6, 0, 5]));
1070 assert_eq!(between("before https://example.com/cat.png\nafter"), (vec![text("before \nafter")], vec![7, 5]));
1072 let note = EventId::from_byte_array([7; 32]).to_bech32().unwrap();
1073 assert_eq!(between(&format!("see nostr:{note} and https://example.com/a.png then")).0, [text("see and then")]);
1074
1075 let content = parse("https://example.com/cat.png\ncaption", 10_000);
1077 assert_eq!((content.segments, content.line_chars), (vec![text("caption")], vec![7]));
1078
1079 let content = parse("https://example.com/cat.png", 10_000);
1081 assert!(content.segments.is_empty());
1082 assert_eq!(image_urls(&content), ["https://example.com/cat.png"]);
1083 }
1084
1085 #[test]
1086 fn only_what_can_be_fetched_and_decoded_is_a_picture() {
1087 assert!(matches!(&segments("http://example.com/cat.png")[..], [Segment::Link { .. }]));
1089 for url in ["https://example.com/song.mp3", "https://example.com/drawing.svg", "https://example.com/page"] {
1091 let content = parse(url, 10_000);
1092 assert!(content.images.is_empty(), "{url}");
1093 assert!(matches!(&content.segments[..], [Segment::Link { .. }]), "{url}");
1094 }
1095 }
1096
1097 #[test]
1098 fn a_picture_after_the_cut_is_still_shown_and_only_so_many_are() {
1099 let note = format!("{} https://example.com/end.png", "word ".repeat(50));
1100 let content = parse(¬e, 20);
1101 assert_eq!(content.segments, [text("word word word word…")]);
1102 assert_eq!(image_urls(&content), ["https://example.com/end.png"]);
1103
1104 let many: String = (0..6).map(|n| format!("https://example.com/{n}.png ")).collect();
1105 assert_eq!(parse(&many, 10_000).images.len(), 4);
1106 }
1107
1108 #[test]
1109 fn the_last_page_a_note_links_to_is_the_one_previewed() {
1110 let preview = |content: &str| parse(content, 10_000).preview;
1111 assert_eq!(preview("no links here"), None);
1112 assert_eq!(
1113 preview("first https://example.com/one then https://example.org/two?x=1 and a word").as_deref(),
1114 Some("https://example.org/two?x=1")
1115 );
1116 assert!(matches!(&segments("see https://example.com/one")[..], [Segment::Text(_), Segment::Link { .. }]));
1118
1119 assert_eq!(preview("http://example.com/plain"), None);
1121 assert_eq!(preview("https://example.com/cat.png https://example.com/clip.MP4 https://example.com/paper.pdf"), None);
1122 assert_eq!(preview("https://example.com/page https://example.com/cat.png").as_deref(), Some("https://example.com/page"));
1123
1124 let long = format!("{} https://example.com/at-the-end", "word ".repeat(50));
1126 let content = parse(&long, 20);
1127 assert_eq!(content.segments, [text("word word word word…")]);
1128 assert_eq!(content.preview.as_deref(), Some("https://example.com/at-the-end"));
1129 }
1130
1131 fn tag(fields: &[&str]) -> Vec<String> {
1132 fields.iter().map(|field| (*field).to_string()).collect()
1133 }
1134
1135 #[test]
1136 fn the_first_link_of_a_note_is_its_first_that_is_no_picture() {
1137 let first = |said: &str| parse(said, FEED_NOTE_MAX_CHARS).first_link;
1138 let (picture, video, page) = ("https://example.com/a.jpg", "https://example.com/b.mp4", "https://example.com/read");
1139 assert_eq!(first(&format!("{picture} {video} {page}")).as_deref(), Some(video));
1140 assert_eq!(first(&format!("{picture} {page} {video}")).as_deref(), Some(page));
1141 assert_eq!(first(&format!("only {picture}")), None);
1142 assert_eq!(first("only words, and ftp://example.com/not-followed"), None);
1143 assert_eq!(first("https://example.com/paper.pdf").as_deref(), Some("https://example.com/paper.pdf"));
1145 let long = format!("{} {page}", "word ".repeat(FEED_NOTE_MAX_CHARS));
1147 assert_eq!(first(&long).as_deref(), Some(page));
1148 }
1149
1150 #[test]
1151 fn imeta_tags_say_what_a_link_is() {
1152 let said = imeta(&tag(&[
1153 "imeta",
1154 "url https://example.com/clip",
1155 "m video/mp4",
1156 "dim 1920x1080",
1157 "thumb https://example.com/small.jpg",
1158 "image https://example.com/poster.jpg",
1159 "blurhash eVF$^OI:${M{o#*0-nNFxakD",
1160 ]))
1161 .unwrap();
1162 assert_eq!(
1163 said,
1164 Attachment {
1165 url: "https://example.com/clip".into(),
1166 kind: Some("video/mp4".into()),
1167 size: Some((1920, 1080)),
1168 picture: Some("https://example.com/poster.jpg".into()),
1169 }
1170 );
1171
1172 let of = |fields: &[&str]| imeta(&tag(fields));
1173 let bare = Attachment { url: "https://example.com/cat.png".into(), ..Attachment::default() };
1174 assert_eq!(of(&["imeta", "url https://example.com/cat.png"]), Some(bare.clone()), "only what it says");
1175 assert_eq!(of(&["imeta", "url https://example.com/cat.png", "dim 0x800"]), Some(bare.clone()));
1176 assert_eq!(of(&["imeta", "url https://example.com/cat.png", "dim wide"]), Some(bare.clone()));
1177 let pictured = |fields: &[&str]| of(fields).unwrap().picture;
1180 assert_eq!(
1181 pictured(&["imeta", "url https://example.com/a", "thumb https://example.com/small.jpg"]).as_deref(),
1182 Some("https://example.com/small.jpg")
1183 );
1184 assert_eq!(pictured(&["imeta", "url https://example.com/a", "image http://example.com/poster.jpg"]), None);
1185 assert_eq!(of(&["imeta", "m video/mp4", "dim 1x1"]), None, "of no address");
1186 assert_eq!(of(&["e", "url https://example.com/cat.png", "dim 1x1"]), None, "not an imeta tag");
1187 }
1188
1189 #[test]
1190 fn imeta_tags_give_pictures_their_size() {
1191 let known = imeta(&tag(&["imeta", "url https://example.com/cat.png", "m image/png", "dim 1200x800"])).unwrap();
1192 let content = parse_attached("https://example.com/cat.png https://example.com/dog.png", 100, &[known]);
1193 assert_eq!(content.images[0].size, Some((1200, 800)));
1194 assert_eq!(content.images[1].size, None);
1195 }
1196
1197 #[test]
1198 fn a_video_is_set_aside_as_a_picture_is() {
1199 let content = parse("watch this\n\nhttps://example.com/clip.MP4?download=1\n\nand say what you think", 10_000);
1200 assert_eq!(content.segments, [text("watch this\n\nand say what you think")]);
1201 assert_eq!(
1202 content.videos,
1203 [NoteVideo {
1204 url: "https://example.com/clip.MP4?download=1".into(),
1205 label: "example.com/clip.MP4".into(),
1206 size: None,
1207 posters: Vec::new(),
1208 page: false
1209 }]
1210 );
1211 assert!(content.images.is_empty());
1213 assert_eq!(content.preview, None);
1214
1215 for played in ["mp4", "webm", "mov", "mkv", "m4v", "ogv", "avi"] {
1216 assert_eq!(parse(&format!("https://example.com/clip.{played}"), 100).videos.len(), 1, "{played}");
1217 }
1218 for link in ["http://example.com/clip.mp4", "https://example.com/song.mp3", "https://example.com/live.m3u8"] {
1221 let content = parse(link, 100);
1222 assert!(content.videos.is_empty(), "{link}");
1223 assert!(matches!(&content.segments[..], [Segment::Link { .. }]), "{link}");
1224 }
1225
1226 let long = format!("{} https://example.com/end.webm", "word ".repeat(50));
1228 let content = parse(&long, 20);
1229 assert_eq!(content.segments, [text("word word word word…")]);
1230 assert_eq!(content.videos.len(), 1);
1231 let many: String = (0..6).map(|n| format!("https://example.com/{n}.mp4 ")).collect();
1232 assert_eq!(parse(&many, 10_000).videos.len(), 4);
1233 }
1234
1235 #[test]
1236 fn a_youtube_link_is_a_video_and_no_page_to_preview() {
1237 let content = parse("worth an evening\nhttps://youtu.be/aqz-KE-bpKQ?si=Wh0Sh4redIt\nall of it", 10_000);
1238 assert_eq!(content.segments, [text("worth an evening\nall of it")]);
1239 assert_eq!(
1240 content.videos,
1241 [NoteVideo {
1242 url: "https://youtu.be/aqz-KE-bpKQ?si=Wh0Sh4redIt".into(),
1244 label: "youtu.be/aqz-KE-bpKQ".into(),
1245 size: None,
1246 posters: vec![
1247 "https://i.ytimg.com/vi/aqz-KE-bpKQ/maxresdefault.jpg".into(),
1248 "https://i.ytimg.com/vi/aqz-KE-bpKQ/mqdefault.jpg".into()
1249 ],
1250 page: true,
1251 }]
1252 );
1253 assert_eq!(content.preview, None);
1254
1255 let short = parse("https://www.youtube.com/shorts/aqz-KE-bpKQ", 100);
1257 assert_eq!(short.videos[0].size, Some((1080, 1920)));
1258 let channel = parse("https://www.youtube.com/@BlenderOfficial", 100);
1260 assert!(channel.videos.is_empty());
1261 assert_eq!(channel.preview.as_deref(), Some("https://www.youtube.com/@BlenderOfficial"));
1262 }
1263
1264 #[test]
1265 fn a_link_the_note_calls_a_video_is_one_whatever_its_address() {
1266 let said = |fields: &[&str]| imeta(&tag(fields)).unwrap();
1267 let address = "https://blossom.example.com/b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553";
1268 let note = format!("look {address} at this https://example.com/page");
1269
1270 let plain = parse(¬e, 10_000);
1273 assert!(plain.videos.is_empty());
1274 assert!(matches!(&plain.segments[..], [Segment::Text(_), Segment::Link { .. }, Segment::Text(_), Segment::Link { .. }]));
1275
1276 let attached = [said(&[
1277 "imeta",
1278 &format!("url {address}"),
1279 "m Video/Quicktime",
1280 "dim 1080x1920",
1281 "image https://blossom.example.com/poster.jpg",
1282 ])];
1283 let content = parse_attached(¬e, 10_000, &attached);
1284 assert_eq!(
1285 content.videos,
1286 [NoteVideo {
1287 url: address.into(),
1288 label: "blossom.example.com/b1674191a88ec5cdd733e4240a818…".into(),
1289 size: Some((1080, 1920)),
1290 posters: vec!["https://blossom.example.com/poster.jpg".into()],
1291 page: false,
1292 }]
1293 );
1294 assert_eq!(content.segments, [text("look at this "), link("https://example.com/page", "example.com/page")]);
1295 assert_eq!(content.preview.as_deref(), Some("https://example.com/page"));
1296 assert_eq!(parse_attached(address, 100, &attached).preview, None);
1298
1299 let sized = [said(&["imeta", "url https://example.com/clip.mp4", "dim 640x360"])];
1301 assert_eq!(parse_attached("https://example.com/clip.mp4", 100, &sized).videos[0].size, Some((640, 360)));
1302 let other = [said(&["imeta", &format!("url {address}"), "m application/pdf"])];
1305 assert!(parse_attached(address, 100, &other).videos.is_empty());
1306 let insecure = [said(&["imeta", "url http://example.com/clip", "m video/mp4"])];
1307 assert!(parse_attached("http://example.com/clip", 100, &insecure).videos.is_empty());
1308 }
1309}