1#![allow(clippy::result_large_err)]
10
11use std::sync::Arc;
49
50use indexmap::IndexMap;
51use regex::Regex;
52use tabnas::{ActionError, Context, Plugin, PluginError, Rule, RuleSnapshot, Tabnas, Token, Value};
53
54pub use tabnas::TabnasError as FeedError;
55
56pub const VERSION: &str = "0.6.13";
60
61const PLUGIN_NAME: &str = "feed";
64
65const INIT_DECORATION: &str = "feed-init";
68
69pub const ERROR_UNRECOGNIZED_ROOT: &str = "feed_unrecognized_root";
74
75pub const NS_ATOM_10: &str = "http://www.w3.org/2005/Atom";
79pub const NS_ATOM_03: &str = "http://purl.org/atom/ns#";
81pub const NS_RSS_10: &str = "http://purl.org/rss/1.0/";
83pub const NS_RSS_090: &str = "http://my.netscape.com/rdf/simple/0.9/";
85pub const NS_RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
92pub enum FeedFormat {
93 #[default]
95 Atom,
96 Native,
98 Raw,
100}
101
102impl FeedFormat {
103 pub fn as_str(&self) -> &'static str {
105 match self {
106 FeedFormat::Atom => "atom",
107 FeedFormat::Native => "native",
108 FeedFormat::Raw => "raw",
109 }
110 }
111
112 pub fn from_name(name: &str) -> Self {
119 match name {
120 "native" => FeedFormat::Native,
121 "raw" => FeedFormat::Raw,
122 _ => FeedFormat::Atom,
123 }
124 }
125}
126
127#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct FeedOptions {
131 pub format: FeedFormat,
133
134 pub strict_namespaces: bool,
147}
148
149impl Default for FeedOptions {
150 fn default() -> Self {
151 FeedOptions {
152 format: FeedFormat::Atom,
153 strict_namespaces: true,
154 }
155 }
156}
157
158impl FeedOptions {
159 pub fn from_value(value: &Value) -> Self {
164 let bag = value.to_json();
165 let format = bag
166 .get("format")
167 .and_then(|format| format.as_str())
168 .map_or(FeedFormat::Atom, FeedFormat::from_name);
169 let strict_namespaces =
170 bag.get("strictNamespaces") != Some(&serde_json::Value::Bool(false));
171 FeedOptions {
172 format,
173 strict_namespaces,
174 }
175 }
176
177 pub fn to_value(&self) -> Value {
179 let mut bag = IndexMap::new();
180 bag.insert(
181 "format".to_string(),
182 Value::String(self.format.as_str().to_string()),
183 );
184 bag.insert(
185 "strictNamespaces".to_string(),
186 Value::Bool(self.strict_namespaces),
187 );
188 Value::object(bag)
189 }
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
196pub enum FeedDialect {
197 Atom,
199 Rss,
201 Rdf,
203 Unknown,
205}
206
207impl FeedDialect {
208 pub fn as_str(&self) -> &'static str {
210 match self {
211 FeedDialect::Atom => "atom",
212 FeedDialect::Rss => "rss",
213 FeedDialect::Rdf => "rdf",
214 FeedDialect::Unknown => "unknown",
215 }
216 }
217}
218
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
221pub enum FeedVersion {
222 Atom10,
224 Atom03,
226 Rss20,
228 Rss092,
230 Rss091u,
232 Rss091n,
234 Rss10,
236 Rss090,
238 Unknown,
240}
241
242impl FeedVersion {
243 pub fn as_str(&self) -> &'static str {
245 match self {
246 FeedVersion::Atom10 => "atom10",
247 FeedVersion::Atom03 => "atom03",
248 FeedVersion::Rss20 => "rss20",
249 FeedVersion::Rss092 => "rss092",
250 FeedVersion::Rss091u => "rss091u",
251 FeedVersion::Rss091n => "rss091n",
252 FeedVersion::Rss10 => "rss10",
253 FeedVersion::Rss090 => "rss090",
254 FeedVersion::Unknown => "unknown",
255 }
256 }
257}
258
259#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
261pub struct Detection {
262 pub dialect: FeedDialect,
264 pub version: FeedVersion,
266}
267
268impl Detection {
269 pub fn to_value(&self) -> Value {
271 let mut out = IndexMap::new();
272 out.insert(
273 "dialect".to_string(),
274 Value::String(self.dialect.as_str().to_string()),
275 );
276 out.insert(
277 "version".to_string(),
278 Value::String(self.version.as_str().to_string()),
279 );
280 Value::object(out)
281 }
282}
283
284pub fn detect(root: &Value) -> Detection {
301 let unknown = Detection {
302 dialect: FeedDialect::Unknown,
303 version: FeedVersion::Unknown,
304 };
305 if !is_element(root) {
306 return unknown;
307 }
308
309 match local_name(root) {
310 "feed" => {
311 if namespace_of(root) == NS_ATOM_03 {
312 Detection {
313 dialect: FeedDialect::Atom,
314 version: FeedVersion::Atom03,
315 }
316 } else {
317 Detection {
318 dialect: FeedDialect::Atom,
319 version: FeedVersion::Atom10,
320 }
321 }
322 }
323 "rss" => {
324 let version = match attribute(root, "version").unwrap_or("") {
325 "2.0" | "2.0.1" | "2.0.2" => FeedVersion::Rss20,
326 "0.92" | "0.93" | "0.94" => FeedVersion::Rss092,
327 "0.91" => FeedVersion::Rss091u,
331 _ => FeedVersion::Rss20,
332 };
333 Detection {
334 dialect: FeedDialect::Rss,
335 version,
336 }
337 }
338 "RDF" => {
339 let version = match find_child(root, "channel") {
341 Some(channel) if namespace_of(channel) == NS_RSS_090 => FeedVersion::Rss090,
342 _ => FeedVersion::Rss10,
343 };
344 Detection {
345 dialect: FeedDialect::Rdf,
346 version,
347 }
348 }
349 _ => unknown,
350 }
351}
352
353pub const JS_SPACE: &str = "\t\n\u{b}\u{c}\r \u{a0}\u{1680}\u{2000}-\u{200a}\
369 \u{2028}\u{2029}\u{202f}\u{205f}\u{3000}\u{feff}";
370
371fn is_js_space(c: char) -> bool {
373 match c {
374 '\u{9}' | '\u{b}' | '\u{c}' | '\u{20}' | '\u{a0}' | '\u{feff}' => true,
376 '\u{1680}' | '\u{202f}' | '\u{205f}' | '\u{3000}' => true,
378 '\u{2000}'..='\u{200a}' => true,
379 '\u{a}' | '\u{d}' | '\u{2028}' | '\u{2029}' => true,
381 _ => false,
382 }
383}
384
385pub fn js_trim(text: &str) -> &str {
387 text.trim_matches(is_js_space)
388}
389
390pub fn js_parse_int(text: &str) -> f64 {
400 let rest = text.trim_start_matches(is_js_space);
401 let mut chars = rest.char_indices();
402 let mut start = 0;
403 let negative = match chars.next() {
404 Some((_, '-')) => {
405 start = 1;
406 true
407 }
408 Some((_, '+')) => {
409 start = 1;
410 false
411 }
412 _ => false,
413 };
414 let digits: String = rest[start..]
415 .chars()
416 .take_while(char::is_ascii_digit)
417 .collect();
418 if digits.is_empty() {
419 return f64::NAN;
420 }
421 let magnitude: f64 = digits.parse().unwrap_or(f64::NAN);
424 if negative {
425 -magnitude
426 } else {
427 magnitude
428 }
429}
430
431fn is_element(node: &Value) -> bool {
436 match node {
437 Value::Object(entries) => {
438 entries.contains_key("localName") && entries.contains_key("children")
439 }
440 _ => false,
441 }
442}
443
444fn string_field<'a>(node: &'a Value, key: &str) -> &'a str {
446 match node {
447 Value::Object(entries) => match entries.get(key) {
448 Some(Value::String(text)) => text.as_str(),
449 _ => "",
450 },
451 _ => "",
452 }
453}
454
455fn local_name(element: &Value) -> &str {
459 let local = string_field(element, "localName");
460 if local.is_empty() {
461 string_field(element, "name")
462 } else {
463 local
464 }
465}
466
467fn namespace_of(element: &Value) -> &str {
469 string_field(element, "namespace")
470}
471
472fn attribute<'a>(element: &'a Value, name: &str) -> Option<&'a str> {
478 match element {
479 Value::Object(entries) => match entries.get("attributes") {
480 Some(Value::Object(attributes)) => match attributes.get(name) {
481 Some(Value::String(text)) => Some(text.as_str()),
482 _ => None,
483 },
484 _ => None,
485 },
486 _ => None,
487 }
488}
489
490fn attribute_truthy<'a>(element: &'a Value, name: &str) -> Option<&'a str> {
493 attribute(element, name).filter(|text| !text.is_empty())
494}
495
496fn children(element: &Value) -> &[Value] {
498 match element {
499 Value::Object(entries) => match entries.get("children") {
500 Some(Value::Array(items)) => items.as_slice(),
501 _ => &[],
502 },
503 _ => &[],
504 }
505}
506
507fn find_child<'a>(element: &'a Value, name: &str) -> Option<&'a Value> {
509 children(element)
510 .iter()
511 .find(|child| is_element(child) && local_name(child) == name)
512}
513
514fn find_child_either<'a>(element: &'a Value, first: &str, second: &str) -> Option<&'a Value> {
516 find_child(element, first).or_else(|| find_child(element, second))
517}
518
519fn find_children<'a>(element: &'a Value, name: &str) -> Vec<&'a Value> {
521 children(element)
522 .iter()
523 .filter(|child| is_element(child) && local_name(child) == name)
524 .collect()
525}
526
527fn find_child_in<'a>(element: Option<&'a Value>, name: &str) -> Option<&'a Value> {
531 element.and_then(|element| find_child(element, name))
532}
533
534fn text_of(element: Option<&Value>) -> String {
537 let Some(element) = element else {
538 return String::new();
539 };
540 let mut out = String::new();
541 for child in children(element) {
542 if let Value::String(text) = child {
543 out.push_str(text);
544 }
545 }
546 js_trim(&out).to_string()
547}
548
549fn text_or_none(element: Option<&Value>) -> Option<String> {
552 let text = text_of(element);
553 if text.is_empty() {
554 None
555 } else {
556 Some(text)
557 }
558}
559
560fn inner_xml(element: Option<&Value>) -> String {
564 let Some(element) = element else {
565 return String::new();
566 };
567 let mut out = String::new();
568 for child in children(element) {
569 match child {
570 Value::String(text) => out.push_str(text),
571 _ if is_element(child) => out.push_str(&serialize_element(child)),
572 _ => {}
573 }
574 }
575 out
576}
577
578fn serialize_element(element: &Value) -> String {
580 let name = {
581 let qualified = string_field(element, "name");
582 if qualified.is_empty() {
583 local_name(element)
584 } else {
585 qualified
586 }
587 };
588 let mut attributes = String::new();
589 if let Value::Object(entries) = element {
590 if let Some(Value::Object(pairs)) = entries.get("attributes") {
591 for (key, value) in pairs.iter() {
592 let text = match value {
593 Value::String(text) => text.as_str(),
594 _ => "",
595 };
596 attributes.push(' ');
597 attributes.push_str(key);
598 attributes.push_str("=\"");
599 attributes.push_str(&escape_attr(text));
600 attributes.push('"');
601 }
602 }
603 }
604 let inner = inner_xml(Some(element));
605 if inner.is_empty() {
606 format!("<{name}{attributes}/>")
607 } else {
608 format!("<{name}{attributes}>{inner}</{name}>")
609 }
610}
611
612fn escape_attr(text: &str) -> String {
614 text.replace('&', "&")
615 .replace('"', """)
616 .replace('<', "<")
617 .replace('>', ">")
618}
619
620#[derive(Default)]
626struct Obj(IndexMap<String, Value>);
627
628impl Obj {
629 fn new() -> Self {
630 Obj(IndexMap::new())
631 }
632
633 fn set(&mut self, key: &str, value: Value) -> &mut Self {
634 self.0.insert(key.to_string(), value);
635 self
636 }
637
638 fn text(&mut self, key: &str, value: impl Into<String>) -> &mut Self {
639 self.set(key, Value::String(value.into()))
640 }
641
642 fn maybe_text(&mut self, key: &str, value: Option<impl Into<String>>) -> &mut Self {
644 if let Some(value) = value {
645 self.text(key, value);
646 }
647 self
648 }
649
650 fn maybe(&mut self, key: &str, value: Option<Value>) -> &mut Self {
651 if let Some(value) = value {
652 self.set(key, value);
653 }
654 self
655 }
656
657 fn maybe_list(&mut self, key: &str, values: Vec<Value>) -> &mut Self {
658 if !values.is_empty() {
659 self.set(key, Value::array(values));
660 }
661 self
662 }
663
664 fn done(&mut self) -> Value {
665 Value::object(std::mem::take(&mut self.0))
666 }
667}
668
669fn field<'a>(object: &'a Value, key: &str) -> Option<&'a Value> {
673 match object {
674 Value::Object(entries) => entries.get(key),
675 _ => None,
676 }
677}
678
679fn truthy<'a>(object: &'a Value, key: &str) -> Option<&'a str> {
682 match field(object, key) {
683 Some(Value::String(text)) if !text.is_empty() => Some(text.as_str()),
684 _ => None,
685 }
686}
687
688fn list<'a>(object: &'a Value, key: &str) -> &'a [Value] {
690 match field(object, key) {
691 Some(Value::Array(items)) => items.as_slice(),
692 _ => &[],
693 }
694}
695
696fn atom_text(kind: &str, value: impl Into<String>) -> Value {
698 Obj::new().text("type", kind).text("value", value).done()
699}
700
701fn parse_person(element: &Value) -> Value {
704 let uri = text_or_none(find_child(element, "uri"))
705 .or_else(|| text_or_none(find_child(element, "url")));
706 Obj::new()
707 .text("name", text_of(find_child(element, "name")))
708 .maybe_text("uri", uri)
709 .maybe_text("email", text_or_none(find_child(element, "email")))
710 .done()
711}
712
713fn parse_link(element: &Value) -> Value {
714 let mut link = Obj::new();
715 link.text("href", attribute(element, "href").unwrap_or(""));
716 link.maybe_text("rel", attribute_truthy(element, "rel"));
717 link.maybe_text("type", attribute_truthy(element, "type"));
718 link.maybe_text("hreflang", attribute_truthy(element, "hreflang"));
719 link.maybe_text("title", attribute_truthy(element, "title"));
720 if let Some(length) = attribute_truthy(element, "length") {
721 link.set("length", Value::Number(js_parse_int(length)));
722 }
723 link.done()
724}
725
726fn parse_category(element: &Value) -> Value {
727 let term = match attribute_truthy(element, "term") {
728 Some(term) => term.to_string(),
729 None => text_of(Some(element)),
730 };
731 Obj::new()
732 .text("term", term)
733 .maybe_text("scheme", attribute(element, "scheme"))
737 .maybe_text("label", attribute(element, "label"))
738 .done()
739}
740
741fn parse_text(element: &Value) -> Value {
742 let kind = attribute_truthy(element, "type").unwrap_or("text");
743 if kind == "xhtml" {
744 let body = find_child(element, "div").unwrap_or(element);
746 return atom_text(kind, inner_xml(Some(body)));
747 }
748 atom_text(kind, text_of(Some(element)))
749}
750
751fn parse_content(element: &Value) -> Value {
752 let kind = attribute_truthy(element, "type").unwrap_or("text");
753 let mut content = Obj::new();
754 content.text("type", kind);
755 content.maybe_text("src", attribute_truthy(element, "src"));
756 if kind == "xhtml" {
757 let body = find_child(element, "div").unwrap_or(element);
758 content.text("value", inner_xml(Some(body)));
759 } else {
760 content.text("value", text_of(Some(element)));
761 }
762 content.done()
763}
764
765fn parse_generator(element: &Value) -> Value {
766 Obj::new()
767 .maybe_text("uri", attribute(element, "uri"))
768 .maybe_text("version", attribute(element, "version"))
769 .text("value", text_of(Some(element)))
770 .done()
771}
772
773fn parse_atom_entry(element: &Value, atom03: bool) -> Value {
774 let mut entry = Obj::new();
775
776 if let Some(id) = find_child(element, "id") {
777 entry.text("id", text_of(Some(id)));
778 }
779 if let Some(title) = find_child(element, "title") {
780 entry.set("title", parse_text(title));
781 }
782
783 if let Some(updated) = find_child(element, if atom03 { "modified" } else { "updated" }) {
786 entry.text("updated", text_of(Some(updated)));
787 }
788 if let Some(published) = find_child(element, if atom03 { "issued" } else { "published" }) {
789 entry.text("published", text_of(Some(published)));
790 }
791
792 entry.maybe_list("authors", map_children(element, "author", parse_person));
793 entry.maybe_list(
794 "contributors",
795 map_children(element, "contributor", parse_person),
796 );
797 entry.maybe_list(
798 "categories",
799 map_children(element, "category", parse_category),
800 );
801 entry.maybe_list("links", map_children(element, "link", parse_link));
802
803 if let Some(content) = find_child(element, "content") {
804 entry.set("content", parse_content(content));
805 }
806 if let Some(rights) = find_child(element, if atom03 { "copyright" } else { "rights" }) {
807 entry.set("rights", parse_text(rights));
808 }
809 if let Some(summary) = find_child(element, if atom03 { "tagline" } else { "summary" }) {
810 entry.set("summary", parse_text(summary));
811 }
812
813 entry.done()
814}
815
816fn map_children(element: &Value, name: &str, each: fn(&Value) -> Value) -> Vec<Value> {
817 find_children(element, name).into_iter().map(each).collect()
818}
819
820fn parse_atom(root: &Value, atom03: bool) -> Value {
821 let mut feed = Obj::new();
822 feed.text("format", "atom");
823 feed.text("version", if atom03 { "0.3" } else { "1.0" });
824 feed.set("entries", Value::array(Vec::new()));
825
826 if let Some(id) = find_child(root, "id") {
827 feed.text("id", text_of(Some(id)));
828 }
829 if let Some(title) = find_child(root, "title") {
830 feed.set("title", parse_text(title));
831 }
832 if let Some(updated) = find_child(root, if atom03 { "modified" } else { "updated" }) {
833 feed.text("updated", text_of(Some(updated)));
834 }
835
836 feed.maybe_list("authors", map_children(root, "author", parse_person));
837 feed.maybe_list(
838 "contributors",
839 map_children(root, "contributor", parse_person),
840 );
841 feed.maybe_list("categories", map_children(root, "category", parse_category));
842 feed.maybe_list("links", map_children(root, "link", parse_link));
843
844 if let Some(generator) = find_child(root, "generator") {
845 feed.set("generator", parse_generator(generator));
846 }
847 if let Some(icon) = find_child(root, "icon") {
848 feed.text("icon", text_of(Some(icon)));
849 }
850 if let Some(logo) = find_child(root, "logo") {
851 feed.text("logo", text_of(Some(logo)));
852 }
853 if let Some(rights) = find_child(root, if atom03 { "copyright" } else { "rights" }) {
854 feed.set("rights", parse_text(rights));
855 }
856 if let Some(subtitle) = find_child(root, if atom03 { "tagline" } else { "subtitle" }) {
857 feed.set("subtitle", parse_text(subtitle));
858 }
859
860 let entries: Vec<Value> = find_children(root, "entry")
861 .into_iter()
862 .map(|entry| parse_atom_entry(entry, atom03))
863 .collect();
864 feed.set("entries", Value::array(entries));
865
866 feed.done()
867}
868
869fn parse_rss2_image(element: &Value) -> Value {
872 let mut image = Obj::new();
873 image.text("url", text_of(find_child(element, "url")));
874 image.text("title", text_of(find_child(element, "title")));
875 image.text("link", text_of(find_child(element, "link")));
876 if let Some(width) = text_or_none(find_child(element, "width")) {
877 image.set("width", Value::Number(js_parse_int(&width)));
878 }
879 if let Some(height) = text_or_none(find_child(element, "height")) {
880 image.set("height", Value::Number(js_parse_int(&height)));
881 }
882 image.maybe_text(
883 "description",
884 text_or_none(find_child(element, "description")),
885 );
886 image.done()
887}
888
889fn parse_rss2_cloud(element: &Value) -> Value {
890 Obj::new()
891 .text("domain", attribute(element, "domain").unwrap_or(""))
892 .set(
893 "port",
894 Value::Number(js_parse_int(
895 attribute_truthy(element, "port").unwrap_or("0"),
896 )),
897 )
898 .text("path", attribute(element, "path").unwrap_or(""))
899 .text(
900 "registerProcedure",
901 attribute(element, "registerProcedure").unwrap_or(""),
902 )
903 .text("protocol", attribute(element, "protocol").unwrap_or(""))
904 .done()
905}
906
907fn parse_rss2_text_input(element: &Value) -> Value {
908 Obj::new()
909 .text("title", text_of(find_child(element, "title")))
910 .text("description", text_of(find_child(element, "description")))
911 .text("name", text_of(find_child(element, "name")))
912 .text("link", text_of(find_child(element, "link")))
913 .done()
914}
915
916fn parse_rss2_category(element: &Value) -> Value {
919 Obj::new()
920 .maybe_text("domain", attribute(element, "domain"))
921 .text("value", text_of(Some(element)))
922 .done()
923}
924
925fn parse_rss2_item(element: &Value) -> Value {
926 let mut item = Obj::new();
927
928 if let Some(title) = find_child(element, "title") {
929 item.text("title", text_of(Some(title)));
930 }
931 if let Some(link) = find_child(element, "link") {
932 item.text("link", text_of(Some(link)));
933 }
934 if let Some(description) = find_child(element, "description") {
935 item.text("description", text_of(Some(description)));
936 }
937 if let Some(author) = find_child(element, "author") {
938 item.text("author", text_of(Some(author)));
939 }
940
941 item.maybe_list(
942 "categories",
943 map_children(element, "category", parse_rss2_category),
944 );
945
946 if let Some(comments) = find_child(element, "comments") {
947 item.text("comments", text_of(Some(comments)));
948 }
949
950 if let Some(enclosure) = find_child(element, "enclosure") {
951 let mut out = Obj::new();
952 out.text("url", attribute(enclosure, "url").unwrap_or(""));
953 if let Some(length) = attribute_truthy(enclosure, "length") {
954 out.set("length", Value::Number(js_parse_int(length)));
955 }
956 out.maybe_text("type", attribute_truthy(enclosure, "type"));
957 item.set("enclosure", out.done());
958 }
959
960 if let Some(guid) = find_child(element, "guid") {
961 let mut out = Obj::new();
962 out.text("value", text_of(Some(guid)));
963 if let Some(permalink) = attribute(guid, "isPermaLink") {
966 out.set("isPermaLink", Value::Bool(permalink != "false"));
967 }
968 item.set("guid", out.done());
969 }
970
971 if let Some(pub_date) = find_child(element, "pubDate") {
972 item.text("pubDate", text_of(Some(pub_date)));
973 }
974
975 if let Some(source) = find_child(element, "source") {
976 item.set(
977 "source",
978 Obj::new()
979 .maybe_text("url", attribute(source, "url"))
980 .text("value", text_of(Some(source)))
981 .done(),
982 );
983 }
984
985 item.done()
986}
987
988fn parse_rss2(root: &Value, version: FeedVersion) -> Value {
989 let channel = find_child(root, "channel").unwrap_or(root);
990 let declared = match version {
991 FeedVersion::Rss092 => "0.92",
992 FeedVersion::Rss091u | FeedVersion::Rss091n => "0.91",
993 _ => "2.0",
994 };
995
996 let mut feed = Obj::new();
997 feed.text("format", "rss");
998 feed.text("version", declared);
999 feed.text("title", text_of(find_child(channel, "title")));
1000 feed.text("link", text_of(find_child(channel, "link")));
1001 feed.text("description", text_of(find_child(channel, "description")));
1002 feed.set("items", Value::array(Vec::new()));
1003
1004 for (key, name) in [
1005 ("language", "language"),
1006 ("copyright", "copyright"),
1007 ("managingEditor", "managingEditor"),
1008 ("webMaster", "webMaster"),
1009 ("pubDate", "pubDate"),
1010 ("lastBuildDate", "lastBuildDate"),
1011 ] {
1012 if let Some(element) = find_child(channel, name) {
1013 feed.text(key, text_of(Some(element)));
1014 }
1015 }
1016
1017 feed.maybe_list(
1018 "categories",
1019 map_children(channel, "category", parse_rss2_category),
1020 );
1021
1022 if let Some(generator) = find_child(channel, "generator") {
1023 feed.text("generator", text_of(Some(generator)));
1024 }
1025 if let Some(docs) = find_child(channel, "docs") {
1026 feed.text("docs", text_of(Some(docs)));
1027 }
1028 if let Some(cloud) = find_child(channel, "cloud") {
1029 feed.set("cloud", parse_rss2_cloud(cloud));
1030 }
1031 if let Some(ttl) = find_child(channel, "ttl") {
1032 feed.set("ttl", Value::Number(js_parse_int(&text_of(Some(ttl)))));
1033 }
1034 if let Some(image) = find_child(channel, "image") {
1035 feed.set("image", parse_rss2_image(image));
1036 }
1037 if let Some(text_input) = find_child_either(channel, "textInput", "textinput") {
1038 feed.set("textInput", parse_rss2_text_input(text_input));
1039 }
1040 if let Some(skip_hours) = find_child(channel, "skipHours") {
1041 let hours: Vec<Value> = find_children(skip_hours, "hour")
1042 .into_iter()
1043 .map(|hour| Value::Number(js_parse_int(&text_of(Some(hour)))))
1044 .collect();
1045 feed.set("skipHours", Value::array(hours));
1046 }
1047 if let Some(skip_days) = find_child(channel, "skipDays") {
1048 let days: Vec<Value> = find_children(skip_days, "day")
1049 .into_iter()
1050 .map(|day| Value::String(text_of(Some(day))))
1051 .collect();
1052 feed.set("skipDays", Value::array(days));
1053 }
1054
1055 let items: Vec<Value> = find_children(channel, "item")
1057 .into_iter()
1058 .map(parse_rss2_item)
1059 .collect();
1060 feed.set("items", Value::array(items));
1061
1062 feed.done()
1063}
1064
1065fn parse_rss1_image(element: &Value) -> Value {
1068 Obj::new()
1069 .maybe_text("about", attribute(element, "rdf:about"))
1070 .text("title", text_of(find_child(element, "title")))
1071 .text("link", text_of(find_child(element, "link")))
1072 .text("url", text_of(find_child(element, "url")))
1073 .done()
1074}
1075
1076fn parse_rss1_text_input(element: &Value) -> Value {
1077 Obj::new()
1078 .maybe_text("about", attribute(element, "rdf:about"))
1079 .text("title", text_of(find_child(element, "title")))
1080 .text("description", text_of(find_child(element, "description")))
1081 .text("name", text_of(find_child(element, "name")))
1082 .text("link", text_of(find_child(element, "link")))
1083 .done()
1084}
1085
1086fn parse_rss1_item(element: &Value) -> Value {
1087 let mut item = Obj::new();
1088 item.text("title", text_of(find_child(element, "title")));
1089 item.text("link", text_of(find_child(element, "link")));
1090 item.maybe_text("about", attribute_truthy(element, "rdf:about"));
1091 if let Some(description) = find_child(element, "description") {
1092 item.text("description", text_of(Some(description)));
1093 }
1094 item.done()
1095}
1096
1097fn parse_rss1(root: &Value, version: FeedVersion) -> Value {
1098 let channel = find_child(root, "channel");
1099 let items: Vec<Value> = find_children(root, "item")
1100 .into_iter()
1101 .map(parse_rss1_item)
1102 .collect();
1103
1104 let mut feed = Obj::new();
1105 feed.text("format", "rdf");
1106 feed.text(
1107 "version",
1108 if version == FeedVersion::Rss090 {
1109 "0.90"
1110 } else {
1111 "1.0"
1112 },
1113 );
1114 feed.text("title", text_of(find_child_in(channel, "title")));
1115 feed.text("link", text_of(find_child_in(channel, "link")));
1116 feed.set("items", Value::array(items));
1117
1118 if let Some(about) = channel.and_then(|channel| attribute_truthy(channel, "rdf:about")) {
1119 feed.text("about", about);
1120 }
1121 if let Some(description) = find_child_in(channel, "description") {
1122 feed.text("description", text_of(Some(description)));
1123 }
1124 if let Some(image) = find_child(root, "image") {
1125 feed.set("image", parse_rss1_image(image));
1126 }
1127 if let Some(text_input) = find_child_either(root, "textinput", "textInput") {
1128 feed.set("textInput", parse_rss1_text_input(text_input));
1129 }
1130
1131 feed.done()
1132}
1133
1134fn rss_author_pattern() -> &'static Regex {
1142 static PATTERN: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
1143 PATTERN.get_or_init(|| {
1144 Regex::new(&format!(
1145 r"^[{space}]*([^{space}()]+@[^{space}]+)[{space}]*(?:\(([^)]+)\))?[{space}]*$",
1146 space = JS_SPACE
1147 ))
1148 .expect("the author pattern compiles")
1149 })
1150}
1151
1152fn parse_rss_person(text: &str) -> Value {
1154 if let Some(captured) = rss_author_pattern().captures(text) {
1155 let email = captured
1156 .get(1)
1157 .map(|email| email.as_str())
1158 .unwrap_or_default();
1159 let name = captured.get(2).map_or(email, |name| name.as_str());
1160 return Obj::new().text("name", name).text("email", email).done();
1161 }
1162 Obj::new().text("name", js_trim(text)).done()
1163}
1164
1165fn category_to_atom(category: &Value) -> Value {
1168 Obj::new()
1169 .text(
1170 "term",
1171 field(category, "value")
1172 .and_then(|value| match value {
1173 Value::String(text) => Some(text.as_str()),
1174 _ => None,
1175 })
1176 .unwrap_or(""),
1177 )
1178 .maybe_text(
1179 "scheme",
1180 field(category, "domain").and_then(|domain| match domain {
1181 Value::String(text) => Some(text.as_str()),
1182 _ => None,
1183 }),
1184 )
1185 .done()
1186}
1187
1188fn rss2_to_atom(rss: &Value) -> Value {
1189 let mut out = Obj::new();
1190 out.text("format", "atom");
1191 out.text("version", "1.0");
1192 out.set("entries", Value::array(Vec::new()));
1193
1194 if let Some(title) = truthy(rss, "title") {
1195 out.set("title", atom_text("text", title));
1196 }
1197 if let Some(description) = truthy(rss, "description") {
1198 out.set("subtitle", atom_text("text", description));
1199 }
1200 if let Some(copyright) = truthy(rss, "copyright") {
1201 out.set("rights", atom_text("text", copyright));
1202 }
1203
1204 if let Some(link) = truthy(rss, "link") {
1207 out.text("id", link);
1208 }
1209
1210 if let Some(updated) = truthy(rss, "lastBuildDate").or_else(|| truthy(rss, "pubDate")) {
1212 out.text("updated", updated);
1213 }
1214
1215 if let Some(generator) = truthy(rss, "generator") {
1216 out.set("generator", Obj::new().text("value", generator).done());
1217 }
1218
1219 if let Some(logo) = field(rss, "image").and_then(|image| truthy(image, "url")) {
1220 out.text("logo", logo);
1221 }
1222
1223 if let Some(link) = truthy(rss, "link") {
1224 out.set(
1225 "links",
1226 Value::array(vec![Obj::new()
1227 .text("href", link)
1228 .text("rel", "alternate")
1229 .done()]),
1230 );
1231 }
1232
1233 out.maybe_list(
1234 "categories",
1235 list(rss, "categories")
1236 .iter()
1237 .map(category_to_atom)
1238 .collect(),
1239 );
1240
1241 if let Some(person) = truthy(rss, "managingEditor").or_else(|| truthy(rss, "webMaster")) {
1244 out.set("authors", Value::array(vec![parse_rss_person(person)]));
1245 }
1246
1247 out.set(
1248 "entries",
1249 Value::array(
1250 list(rss, "items")
1251 .iter()
1252 .map(rss2_item_to_atom_entry)
1253 .collect(),
1254 ),
1255 );
1256
1257 out.done()
1258}
1259
1260fn rss2_item_to_atom_entry(item: &Value) -> Value {
1261 let mut entry = Obj::new();
1262
1263 if let Some(title) = truthy(item, "title") {
1264 entry.set("title", atom_text("text", title));
1265 }
1266 if let Some(description) = truthy(item, "description") {
1267 entry.set("summary", atom_text("html", description));
1268 }
1269 if let Some(pub_date) = truthy(item, "pubDate") {
1270 entry.text("published", pub_date);
1271 entry.text("updated", pub_date);
1272 }
1273
1274 if let Some(guid) = field(item, "guid") {
1276 entry.text(
1277 "id",
1278 match field(guid, "value") {
1279 Some(Value::String(text)) => text.as_str(),
1280 _ => "",
1281 },
1282 );
1283 } else if let Some(link) = truthy(item, "link") {
1284 entry.text("id", link);
1285 }
1286
1287 let mut links = Vec::new();
1288 if let Some(link) = truthy(item, "link") {
1289 links.push(
1290 Obj::new()
1291 .text("href", link)
1292 .text("rel", "alternate")
1293 .done(),
1294 );
1295 }
1296 if let Some(enclosure) = field(item, "enclosure") {
1297 if let Some(url) = truthy(enclosure, "url") {
1298 let mut link = Obj::new();
1299 link.text("href", url);
1300 link.text("rel", "enclosure");
1301 link.maybe_text("type", truthy(enclosure, "type"));
1302 link.maybe("length", field(enclosure, "length").cloned());
1305 links.push(link.done());
1306 }
1307 }
1308 if let Some(comments) = truthy(item, "comments") {
1309 links.push(
1310 Obj::new()
1311 .text("href", comments)
1312 .text("rel", "replies")
1313 .text("type", "text/html")
1314 .done(),
1315 );
1316 }
1317 entry.maybe_list("links", links);
1318
1319 if let Some(author) = truthy(item, "author") {
1320 entry.set("authors", Value::array(vec![parse_rss_person(author)]));
1321 }
1322
1323 entry.maybe_list(
1324 "categories",
1325 list(item, "categories")
1326 .iter()
1327 .map(category_to_atom)
1328 .collect(),
1329 );
1330
1331 if let Some(source) = field(item, "source") {
1332 let mut src = Obj::new();
1333 src.text("format", "atom");
1334 src.text("version", "1.0");
1335 if let Some(value) = truthy(source, "value") {
1336 src.set("title", atom_text("text", value));
1337 }
1338 if let Some(url) = truthy(source, "url") {
1339 src.set(
1340 "links",
1341 Value::array(vec![Obj::new()
1342 .text("href", url)
1343 .text("rel", "self")
1344 .done()]),
1345 );
1346 }
1347 entry.set("source", src.done());
1348 }
1349
1350 entry.done()
1351}
1352
1353fn rss1_to_atom(rss: &Value) -> Value {
1354 let mut out = Obj::new();
1355 out.text("format", "atom");
1356 out.text("version", "1.0");
1357 out.set("entries", Value::array(Vec::new()));
1358
1359 if let Some(title) = truthy(rss, "title") {
1360 out.set("title", atom_text("text", title));
1361 }
1362 if let Some(description) = truthy(rss, "description") {
1363 out.set("subtitle", atom_text("text", description));
1364 }
1365 if let Some(id) = truthy(rss, "about").or_else(|| truthy(rss, "link")) {
1366 out.text("id", id);
1367 }
1368 if let Some(link) = truthy(rss, "link") {
1369 out.set(
1370 "links",
1371 Value::array(vec![Obj::new()
1372 .text("href", link)
1373 .text("rel", "alternate")
1374 .done()]),
1375 );
1376 }
1377 if let Some(logo) = field(rss, "image").and_then(|image| truthy(image, "url")) {
1378 out.text("logo", logo);
1379 }
1380
1381 let entries: Vec<Value> = list(rss, "items")
1382 .iter()
1383 .map(|item| {
1384 let mut entry = Obj::new();
1385 if let Some(title) = truthy(item, "title") {
1386 entry.set("title", atom_text("text", title));
1387 }
1388 if let Some(description) = truthy(item, "description") {
1389 entry.set("summary", atom_text("text", description));
1390 }
1391 entry.text(
1395 "id",
1396 truthy(item, "about")
1397 .or_else(|| match field(item, "link") {
1398 Some(Value::String(text)) => Some(text.as_str()),
1399 _ => None,
1400 })
1401 .unwrap_or(""),
1402 );
1403 if let Some(link) = truthy(item, "link") {
1404 entry.set(
1405 "links",
1406 Value::array(vec![Obj::new()
1407 .text("href", link)
1408 .text("rel", "alternate")
1409 .done()]),
1410 );
1411 }
1412 entry.done()
1413 })
1414 .collect();
1415 out.set("entries", Value::array(entries));
1416
1417 out.done()
1418}
1419
1420pub fn convert(root: &Value, format: FeedFormat) -> Result<Value, String> {
1436 if format == FeedFormat::Raw {
1437 return Ok(root.clone());
1438 }
1439 if !is_element(root) {
1440 return Err("feed: input did not parse to an XML element".to_string());
1441 }
1442
1443 let Detection { dialect, version } = detect(root);
1444 if dialect == FeedDialect::Unknown {
1445 return Err(format!(
1446 "feed: unrecognized root element \"{}\"; expected one of feed, rss, RDF",
1447 local_name(root)
1448 ));
1449 }
1450
1451 let native = match dialect {
1453 FeedDialect::Atom => parse_atom(root, version == FeedVersion::Atom03),
1454 FeedDialect::Rss => parse_rss2(root, version),
1455 FeedDialect::Rdf => parse_rss1(root, version),
1456 FeedDialect::Unknown => unreachable!("an unknown dialect returned above"),
1457 };
1458
1459 if format == FeedFormat::Native {
1460 return Ok(native);
1461 }
1462
1463 Ok(match dialect {
1464 FeedDialect::Atom => native,
1465 FeedDialect::Rss => rss2_to_atom(&native),
1466 _ => rss1_to_atom(&native),
1467 })
1468}
1469
1470pub fn feed(parser: &mut Tabnas, options: &FeedOptions) -> Result<(), PluginError> {
1490 if parser.decoration::<bool>(INIT_DECORATION).is_some() {
1491 return Ok(());
1492 }
1493 parser.decorate(INIT_DECORATION, true);
1494
1495 let xml_options = tabnas_xml::XmlOptions {
1496 strict_namespaces: options.strict_namespaces,
1497 ..tabnas_xml::XmlOptions::default()
1498 };
1499 parser
1500 .use_plugin(tabnas_xml::plugin(), Some(xml_options.to_value()))
1501 .map_err(|error| PluginError(format!("feed: setup xml: {error}")))?;
1502
1503 let format = options.format;
1504
1505 parser.define_rule("xml", move |spec| {
1513 spec.add_bc_with_state(Arc::new(
1514 move |rule: &mut Rule,
1515 _context: &mut Context,
1516 _next: Option<&RuleSnapshot>,
1517 _out: Option<Token>|
1518 -> Result<Option<Token>, ActionError> {
1519 if rule.child_node.is_undefined() {
1520 return Ok(None);
1521 }
1522 let root = rule.node.borrow().clone();
1523 if !is_element(&root) {
1524 return Ok(None);
1525 }
1526 match convert(&root, format) {
1527 Ok(value) => {
1530 *rule.node.borrow_mut() = value;
1531 Ok(None)
1532 }
1533 Err(message) => Err(ActionError::new(ERROR_UNRECOGNIZED_ROOT, message)),
1534 }
1535 },
1536 ));
1537 });
1538
1539 Ok(())
1540}
1541
1542pub fn plugin() -> Plugin {
1553 Plugin::new(PLUGIN_NAME, |parser, options| {
1554 feed(parser, &FeedOptions::from_value(options))
1555 })
1556 .with_defaults(FeedOptions::default().to_value())
1557}
1558
1559pub fn make_with(options: &FeedOptions) -> Tabnas {
1574 let mut parser = tabnas_jsonic::make();
1575 parser
1576 .use_plugin(plugin(), Some(options.to_value()))
1577 .expect("the feed plugin installs on a jsonic instance");
1578 parser
1579}
1580
1581pub fn make() -> Tabnas {
1593 make_with(&FeedOptions::default())
1594}
1595
1596pub fn parse(src: &str) -> Result<Value, FeedError> {
1604 static SHARED: std::sync::OnceLock<Tabnas> = std::sync::OnceLock::new();
1605 SHARED.get_or_init(make).parse(src)
1606}
1607
1608#[cfg(doctest)]
1609#[doc = include_str!("../README.md")]
1610mod readme_examples {}