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.21";
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
825 if let Some(id) = find_child(root, "id") {
826 feed.text("id", text_of(Some(id)));
827 }
828 if let Some(title) = find_child(root, "title") {
829 feed.set("title", parse_text(title));
830 }
831 if let Some(updated) = find_child(root, if atom03 { "modified" } else { "updated" }) {
832 feed.text("updated", text_of(Some(updated)));
833 }
834
835 feed.maybe_list("authors", map_children(root, "author", parse_person));
836 feed.maybe_list(
837 "contributors",
838 map_children(root, "contributor", parse_person),
839 );
840 feed.maybe_list("categories", map_children(root, "category", parse_category));
841 feed.maybe_list("links", map_children(root, "link", parse_link));
842
843 if let Some(generator) = find_child(root, "generator") {
844 feed.set("generator", parse_generator(generator));
845 }
846 if let Some(icon) = find_child(root, "icon") {
847 feed.text("icon", text_of(Some(icon)));
848 }
849 if let Some(logo) = find_child(root, "logo") {
850 feed.text("logo", text_of(Some(logo)));
851 }
852 if let Some(rights) = find_child(root, if atom03 { "copyright" } else { "rights" }) {
853 feed.set("rights", parse_text(rights));
854 }
855 if let Some(subtitle) = find_child(root, if atom03 { "tagline" } else { "subtitle" }) {
856 feed.set("subtitle", parse_text(subtitle));
857 }
858
859 let entries: Vec<Value> = find_children(root, "entry")
860 .into_iter()
861 .map(|entry| parse_atom_entry(entry, atom03))
862 .collect();
863 feed.set("entries", Value::array(entries));
864
865 feed.done()
866}
867
868fn parse_rss2_image(element: &Value) -> Value {
871 let mut image = Obj::new();
872 image.text("url", text_of(find_child(element, "url")));
873 image.text("title", text_of(find_child(element, "title")));
874 image.text("link", text_of(find_child(element, "link")));
875 if let Some(width) = text_or_none(find_child(element, "width")) {
876 image.set("width", Value::Number(js_parse_int(&width)));
877 }
878 if let Some(height) = text_or_none(find_child(element, "height")) {
879 image.set("height", Value::Number(js_parse_int(&height)));
880 }
881 image.maybe_text(
882 "description",
883 text_or_none(find_child(element, "description")),
884 );
885 image.done()
886}
887
888fn parse_rss2_cloud(element: &Value) -> Value {
889 Obj::new()
890 .text("domain", attribute(element, "domain").unwrap_or(""))
891 .set(
892 "port",
893 Value::Number(js_parse_int(
894 attribute_truthy(element, "port").unwrap_or("0"),
895 )),
896 )
897 .text("path", attribute(element, "path").unwrap_or(""))
898 .text(
899 "registerProcedure",
900 attribute(element, "registerProcedure").unwrap_or(""),
901 )
902 .text("protocol", attribute(element, "protocol").unwrap_or(""))
903 .done()
904}
905
906fn parse_rss2_text_input(element: &Value) -> Value {
907 Obj::new()
908 .text("title", text_of(find_child(element, "title")))
909 .text("description", text_of(find_child(element, "description")))
910 .text("name", text_of(find_child(element, "name")))
911 .text("link", text_of(find_child(element, "link")))
912 .done()
913}
914
915fn parse_rss2_category(element: &Value) -> Value {
918 Obj::new()
919 .maybe_text("domain", attribute(element, "domain"))
920 .text("value", text_of(Some(element)))
921 .done()
922}
923
924fn parse_rss2_item(element: &Value) -> Value {
925 let mut item = Obj::new();
926
927 if let Some(title) = find_child(element, "title") {
928 item.text("title", text_of(Some(title)));
929 }
930 if let Some(link) = find_child(element, "link") {
931 item.text("link", text_of(Some(link)));
932 }
933 if let Some(description) = find_child(element, "description") {
934 item.text("description", text_of(Some(description)));
935 }
936 if let Some(author) = find_child(element, "author") {
937 item.text("author", text_of(Some(author)));
938 }
939
940 item.maybe_list(
941 "categories",
942 map_children(element, "category", parse_rss2_category),
943 );
944
945 if let Some(comments) = find_child(element, "comments") {
946 item.text("comments", text_of(Some(comments)));
947 }
948
949 if let Some(enclosure) = find_child(element, "enclosure") {
950 let mut out = Obj::new();
951 out.text("url", attribute(enclosure, "url").unwrap_or(""));
952 if let Some(length) = attribute_truthy(enclosure, "length") {
953 out.set("length", Value::Number(js_parse_int(length)));
954 }
955 out.maybe_text("type", attribute_truthy(enclosure, "type"));
956 item.set("enclosure", out.done());
957 }
958
959 if let Some(guid) = find_child(element, "guid") {
960 let mut out = Obj::new();
961 out.text("value", text_of(Some(guid)));
962 if let Some(permalink) = attribute(guid, "isPermaLink") {
965 out.set("isPermaLink", Value::Bool(permalink != "false"));
966 }
967 item.set("guid", out.done());
968 }
969
970 if let Some(pub_date) = find_child(element, "pubDate") {
971 item.text("pubDate", text_of(Some(pub_date)));
972 }
973
974 if let Some(source) = find_child(element, "source") {
975 item.set(
976 "source",
977 Obj::new()
978 .maybe_text("url", attribute(source, "url"))
979 .text("value", text_of(Some(source)))
980 .done(),
981 );
982 }
983
984 item.done()
985}
986
987fn parse_rss2(root: &Value, version: FeedVersion) -> Value {
988 let channel = find_child(root, "channel").unwrap_or(root);
989 let declared = match version {
990 FeedVersion::Rss092 => "0.92",
991 FeedVersion::Rss091u | FeedVersion::Rss091n => "0.91",
992 _ => "2.0",
993 };
994
995 let mut feed = Obj::new();
996 feed.text("format", "rss");
997 feed.text("version", declared);
998 feed.text("title", text_of(find_child(channel, "title")));
999 feed.text("link", text_of(find_child(channel, "link")));
1000 feed.text("description", text_of(find_child(channel, "description")));
1001 feed.set("items", Value::array(Vec::new()));
1002
1003 for (key, name) in [
1004 ("language", "language"),
1005 ("copyright", "copyright"),
1006 ("managingEditor", "managingEditor"),
1007 ("webMaster", "webMaster"),
1008 ("pubDate", "pubDate"),
1009 ("lastBuildDate", "lastBuildDate"),
1010 ] {
1011 if let Some(element) = find_child(channel, name) {
1012 feed.text(key, text_of(Some(element)));
1013 }
1014 }
1015
1016 feed.maybe_list(
1017 "categories",
1018 map_children(channel, "category", parse_rss2_category),
1019 );
1020
1021 if let Some(generator) = find_child(channel, "generator") {
1022 feed.text("generator", text_of(Some(generator)));
1023 }
1024 if let Some(docs) = find_child(channel, "docs") {
1025 feed.text("docs", text_of(Some(docs)));
1026 }
1027 if let Some(cloud) = find_child(channel, "cloud") {
1028 feed.set("cloud", parse_rss2_cloud(cloud));
1029 }
1030 if let Some(ttl) = find_child(channel, "ttl") {
1031 feed.set("ttl", Value::Number(js_parse_int(&text_of(Some(ttl)))));
1032 }
1033 if let Some(image) = find_child(channel, "image") {
1034 feed.set("image", parse_rss2_image(image));
1035 }
1036 if let Some(text_input) = find_child_either(channel, "textInput", "textinput") {
1037 feed.set("textInput", parse_rss2_text_input(text_input));
1038 }
1039 if let Some(skip_hours) = find_child(channel, "skipHours") {
1040 let hours: Vec<Value> = find_children(skip_hours, "hour")
1041 .into_iter()
1042 .map(|hour| Value::Number(js_parse_int(&text_of(Some(hour)))))
1043 .collect();
1044 feed.set("skipHours", Value::array(hours));
1045 }
1046 if let Some(skip_days) = find_child(channel, "skipDays") {
1047 let days: Vec<Value> = find_children(skip_days, "day")
1048 .into_iter()
1049 .map(|day| Value::String(text_of(Some(day))))
1050 .collect();
1051 feed.set("skipDays", Value::array(days));
1052 }
1053
1054 let items: Vec<Value> = find_children(channel, "item")
1056 .into_iter()
1057 .map(parse_rss2_item)
1058 .collect();
1059 feed.set("items", Value::array(items));
1060
1061 feed.done()
1062}
1063
1064fn parse_rss1_image(element: &Value) -> Value {
1067 Obj::new()
1068 .maybe_text("about", attribute(element, "rdf:about"))
1069 .text("title", text_of(find_child(element, "title")))
1070 .text("link", text_of(find_child(element, "link")))
1071 .text("url", text_of(find_child(element, "url")))
1072 .done()
1073}
1074
1075fn parse_rss1_text_input(element: &Value) -> Value {
1076 Obj::new()
1077 .maybe_text("about", attribute(element, "rdf:about"))
1078 .text("title", text_of(find_child(element, "title")))
1079 .text("description", text_of(find_child(element, "description")))
1080 .text("name", text_of(find_child(element, "name")))
1081 .text("link", text_of(find_child(element, "link")))
1082 .done()
1083}
1084
1085fn parse_rss1_item(element: &Value) -> Value {
1086 let mut item = Obj::new();
1087 item.text("title", text_of(find_child(element, "title")));
1088 item.text("link", text_of(find_child(element, "link")));
1089 item.maybe_text("about", attribute_truthy(element, "rdf:about"));
1090 if let Some(description) = find_child(element, "description") {
1091 item.text("description", text_of(Some(description)));
1092 }
1093 item.done()
1094}
1095
1096fn parse_rss1(root: &Value, version: FeedVersion) -> Value {
1097 let channel = find_child(root, "channel");
1098 let items: Vec<Value> = find_children(root, "item")
1099 .into_iter()
1100 .map(parse_rss1_item)
1101 .collect();
1102
1103 let mut feed = Obj::new();
1104 feed.text("format", "rdf");
1105 feed.text(
1106 "version",
1107 if version == FeedVersion::Rss090 {
1108 "0.90"
1109 } else {
1110 "1.0"
1111 },
1112 );
1113 feed.text("title", text_of(find_child_in(channel, "title")));
1114 feed.text("link", text_of(find_child_in(channel, "link")));
1115 feed.set("items", Value::array(items));
1116
1117 if let Some(about) = channel.and_then(|channel| attribute_truthy(channel, "rdf:about")) {
1118 feed.text("about", about);
1119 }
1120 if let Some(description) = find_child_in(channel, "description") {
1121 feed.text("description", text_of(Some(description)));
1122 }
1123 if let Some(image) = find_child(root, "image") {
1124 feed.set("image", parse_rss1_image(image));
1125 }
1126 if let Some(text_input) = find_child_either(root, "textinput", "textInput") {
1127 feed.set("textInput", parse_rss1_text_input(text_input));
1128 }
1129
1130 feed.done()
1131}
1132
1133fn rss_author_pattern() -> &'static Regex {
1141 static PATTERN: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
1142 PATTERN.get_or_init(|| {
1143 Regex::new(&format!(
1144 r"^[{space}]*([^{space}()]+@[^{space}]+)[{space}]*(?:\(([^)]+)\))?[{space}]*$",
1145 space = JS_SPACE
1146 ))
1147 .expect("the author pattern compiles")
1148 })
1149}
1150
1151fn parse_rss_person(text: &str) -> Value {
1153 if let Some(captured) = rss_author_pattern().captures(text) {
1154 let email = captured
1155 .get(1)
1156 .map(|email| email.as_str())
1157 .unwrap_or_default();
1158 let name = captured.get(2).map_or(email, |name| name.as_str());
1159 return Obj::new().text("name", name).text("email", email).done();
1160 }
1161 Obj::new().text("name", js_trim(text)).done()
1162}
1163
1164fn category_to_atom(category: &Value) -> Value {
1167 Obj::new()
1168 .text(
1169 "term",
1170 field(category, "value")
1171 .and_then(|value| match value {
1172 Value::String(text) => Some(text.as_str()),
1173 _ => None,
1174 })
1175 .unwrap_or(""),
1176 )
1177 .maybe_text(
1178 "scheme",
1179 field(category, "domain").and_then(|domain| match domain {
1180 Value::String(text) => Some(text.as_str()),
1181 _ => None,
1182 }),
1183 )
1184 .done()
1185}
1186
1187fn rss2_to_atom(rss: &Value) -> Value {
1188 let mut out = Obj::new();
1189 out.text("format", "atom");
1190 out.text("version", "1.0");
1191
1192 if let Some(title) = truthy(rss, "title") {
1193 out.set("title", atom_text("text", title));
1194 }
1195 if let Some(description) = truthy(rss, "description") {
1196 out.set("subtitle", atom_text("text", description));
1197 }
1198 if let Some(copyright) = truthy(rss, "copyright") {
1199 out.set("rights", atom_text("text", copyright));
1200 }
1201
1202 if let Some(link) = truthy(rss, "link") {
1205 out.text("id", link);
1206 }
1207
1208 if let Some(updated) = truthy(rss, "lastBuildDate").or_else(|| truthy(rss, "pubDate")) {
1210 out.text("updated", updated);
1211 }
1212
1213 if let Some(generator) = truthy(rss, "generator") {
1214 out.set("generator", Obj::new().text("value", generator).done());
1215 }
1216
1217 if let Some(logo) = field(rss, "image").and_then(|image| truthy(image, "url")) {
1218 out.text("logo", logo);
1219 }
1220
1221 if let Some(link) = truthy(rss, "link") {
1222 out.set(
1223 "links",
1224 Value::array(vec![Obj::new()
1225 .text("href", link)
1226 .text("rel", "alternate")
1227 .done()]),
1228 );
1229 }
1230
1231 out.maybe_list(
1232 "categories",
1233 list(rss, "categories")
1234 .iter()
1235 .map(category_to_atom)
1236 .collect(),
1237 );
1238
1239 if let Some(person) = truthy(rss, "managingEditor").or_else(|| truthy(rss, "webMaster")) {
1242 out.set("authors", Value::array(vec![parse_rss_person(person)]));
1243 }
1244
1245 out.set(
1246 "entries",
1247 Value::array(
1248 list(rss, "items")
1249 .iter()
1250 .map(rss2_item_to_atom_entry)
1251 .collect(),
1252 ),
1253 );
1254
1255 out.done()
1256}
1257
1258fn rss2_item_to_atom_entry(item: &Value) -> Value {
1259 let mut entry = Obj::new();
1260
1261 if let Some(title) = truthy(item, "title") {
1262 entry.set("title", atom_text("text", title));
1263 }
1264 if let Some(description) = truthy(item, "description") {
1265 entry.set("summary", atom_text("html", description));
1266 }
1267 if let Some(pub_date) = truthy(item, "pubDate") {
1268 entry.text("published", pub_date);
1269 entry.text("updated", pub_date);
1270 }
1271
1272 if let Some(guid) = field(item, "guid") {
1274 entry.text(
1275 "id",
1276 match field(guid, "value") {
1277 Some(Value::String(text)) => text.as_str(),
1278 _ => "",
1279 },
1280 );
1281 } else if let Some(link) = truthy(item, "link") {
1282 entry.text("id", link);
1283 }
1284
1285 let mut links = Vec::new();
1286 if let Some(link) = truthy(item, "link") {
1287 links.push(
1288 Obj::new()
1289 .text("href", link)
1290 .text("rel", "alternate")
1291 .done(),
1292 );
1293 }
1294 if let Some(enclosure) = field(item, "enclosure") {
1295 if let Some(url) = truthy(enclosure, "url") {
1296 let mut link = Obj::new();
1297 link.text("href", url);
1298 link.text("rel", "enclosure");
1299 link.maybe_text("type", truthy(enclosure, "type"));
1300 link.maybe("length", field(enclosure, "length").cloned());
1303 links.push(link.done());
1304 }
1305 }
1306 if let Some(comments) = truthy(item, "comments") {
1307 links.push(
1308 Obj::new()
1309 .text("href", comments)
1310 .text("rel", "replies")
1311 .text("type", "text/html")
1312 .done(),
1313 );
1314 }
1315 entry.maybe_list("links", links);
1316
1317 if let Some(author) = truthy(item, "author") {
1318 entry.set("authors", Value::array(vec![parse_rss_person(author)]));
1319 }
1320
1321 entry.maybe_list(
1322 "categories",
1323 list(item, "categories")
1324 .iter()
1325 .map(category_to_atom)
1326 .collect(),
1327 );
1328
1329 if let Some(source) = field(item, "source") {
1330 let mut src = Obj::new();
1331 src.text("format", "atom");
1332 src.text("version", "1.0");
1333 if let Some(value) = truthy(source, "value") {
1334 src.set("title", atom_text("text", value));
1335 }
1336 if let Some(url) = truthy(source, "url") {
1337 src.set(
1338 "links",
1339 Value::array(vec![Obj::new()
1340 .text("href", url)
1341 .text("rel", "self")
1342 .done()]),
1343 );
1344 }
1345 entry.set("source", src.done());
1346 }
1347
1348 entry.done()
1349}
1350
1351fn rss1_to_atom(rss: &Value) -> Value {
1352 let mut out = Obj::new();
1353 out.text("format", "atom");
1354 out.text("version", "1.0");
1355
1356 if let Some(title) = truthy(rss, "title") {
1357 out.set("title", atom_text("text", title));
1358 }
1359 if let Some(description) = truthy(rss, "description") {
1360 out.set("subtitle", atom_text("text", description));
1361 }
1362 if let Some(id) = truthy(rss, "about").or_else(|| truthy(rss, "link")) {
1363 out.text("id", id);
1364 }
1365 if let Some(link) = truthy(rss, "link") {
1366 out.set(
1367 "links",
1368 Value::array(vec![Obj::new()
1369 .text("href", link)
1370 .text("rel", "alternate")
1371 .done()]),
1372 );
1373 }
1374 if let Some(logo) = field(rss, "image").and_then(|image| truthy(image, "url")) {
1375 out.text("logo", logo);
1376 }
1377
1378 let entries: Vec<Value> = list(rss, "items")
1379 .iter()
1380 .map(|item| {
1381 let mut entry = Obj::new();
1382 if let Some(title) = truthy(item, "title") {
1383 entry.set("title", atom_text("text", title));
1384 }
1385 if let Some(description) = truthy(item, "description") {
1386 entry.set("summary", atom_text("text", description));
1387 }
1388 entry.text(
1392 "id",
1393 truthy(item, "about")
1394 .or_else(|| match field(item, "link") {
1395 Some(Value::String(text)) => Some(text.as_str()),
1396 _ => None,
1397 })
1398 .unwrap_or(""),
1399 );
1400 if let Some(link) = truthy(item, "link") {
1401 entry.set(
1402 "links",
1403 Value::array(vec![Obj::new()
1404 .text("href", link)
1405 .text("rel", "alternate")
1406 .done()]),
1407 );
1408 }
1409 entry.done()
1410 })
1411 .collect();
1412 out.set("entries", Value::array(entries));
1413
1414 out.done()
1415}
1416
1417pub fn convert(root: &Value, format: FeedFormat) -> Result<Value, String> {
1433 if format == FeedFormat::Raw {
1434 return Ok(root.clone());
1435 }
1436 if !is_element(root) {
1437 return Err("feed: input did not parse to an XML element".to_string());
1438 }
1439
1440 let Detection { dialect, version } = detect(root);
1441 if dialect == FeedDialect::Unknown {
1442 return Err(format!(
1443 "feed: unrecognized root element \"{}\"; expected one of feed, rss, RDF",
1444 local_name(root)
1445 ));
1446 }
1447
1448 let native = match dialect {
1450 FeedDialect::Atom => parse_atom(root, version == FeedVersion::Atom03),
1451 FeedDialect::Rss => parse_rss2(root, version),
1452 FeedDialect::Rdf => parse_rss1(root, version),
1453 FeedDialect::Unknown => unreachable!("an unknown dialect returned above"),
1454 };
1455
1456 if format == FeedFormat::Native {
1457 return Ok(native);
1458 }
1459
1460 Ok(match dialect {
1461 FeedDialect::Atom => native,
1462 FeedDialect::Rss => rss2_to_atom(&native),
1463 _ => rss1_to_atom(&native),
1464 })
1465}
1466
1467pub fn feed(parser: &mut Tabnas, options: &FeedOptions) -> Result<(), PluginError> {
1487 if parser.decoration::<bool>(INIT_DECORATION).is_some() {
1488 return Ok(());
1489 }
1490 parser.decorate(INIT_DECORATION, true);
1491
1492 let xml_options = tabnas_xml::XmlOptions {
1493 strict_namespaces: options.strict_namespaces,
1494 ..tabnas_xml::XmlOptions::default()
1495 };
1496 parser
1497 .use_plugin(tabnas_xml::plugin(), Some(xml_options.to_value()))
1498 .map_err(|error| PluginError(format!("feed: setup xml: {error}")))?;
1499
1500 let format = options.format;
1501
1502 parser.define_rule("xml", move |spec| {
1510 spec.add_bc_with_state(Arc::new(
1511 move |rule: &mut Rule,
1512 _context: &mut Context,
1513 _next: Option<&RuleSnapshot>,
1514 _out: Option<Token>|
1515 -> Result<Option<Token>, ActionError> {
1516 if rule.child_node.is_undefined() {
1517 return Ok(None);
1518 }
1519 let root = rule.node.borrow().clone();
1520 if !is_element(&root) {
1521 return Ok(None);
1522 }
1523 match convert(&root, format) {
1524 Ok(value) => {
1527 *rule.node.borrow_mut() = value;
1528 Ok(None)
1529 }
1530 Err(message) => Err(ActionError::new(ERROR_UNRECOGNIZED_ROOT, message)),
1531 }
1532 },
1533 ));
1534 });
1535
1536 Ok(())
1537}
1538
1539pub fn plugin() -> Plugin {
1550 Plugin::new(PLUGIN_NAME, |parser, options| {
1551 feed(parser, &FeedOptions::from_value(options))
1552 })
1553 .with_defaults(FeedOptions::default().to_value())
1554}
1555
1556pub fn make_with(options: &FeedOptions) -> Tabnas {
1580 let mut parser = Tabnas::new();
1581 parser
1582 .use_plugin(plugin(), Some(options.to_value()))
1583 .expect("the feed plugin installs on the engine");
1584 parser
1585 .set_options(|options| options.lex.window = true)
1586 .expect("lex.window sets");
1587 parser
1588}
1589
1590pub fn make() -> Tabnas {
1602 make_with(&FeedOptions::default())
1603}
1604
1605pub fn parse(src: &str) -> Result<Value, FeedError> {
1613 static SHARED: std::sync::OnceLock<Tabnas> = std::sync::OnceLock::new();
1614 SHARED.get_or_init(make).parse(src)
1615}
1616
1617#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1621pub struct TranslationPart {
1622 pub entry: &'static str,
1624 pub source: Option<&'static str>,
1626}
1627
1628#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1630pub struct TranslationParts {
1631 pub manifest: &'static str,
1633 pub lift: Option<TranslationPart>,
1635 pub embed: Option<TranslationPart>,
1637 pub render: Option<TranslationPart>,
1639 pub transduce: Option<TranslationPart>,
1642}
1643
1644const TRANSLATION: TranslationParts = TranslationParts {
1645 manifest: include_str!("../translate/manifest.json"),
1646 lift: None,
1647 embed: Some(TranslationPart {
1648 entry: "feed-embed",
1649 source: Some(include_str!("../translate/embed.alc")),
1650 }),
1651 render: Some(TranslationPart {
1652 entry: "feed-render",
1653 source: Some(include_str!("../translate/render.alc")),
1654 }),
1655 transduce: Some(TranslationPart {
1656 entry: "feed-transduce",
1657 source: Some(include_str!("../translate/transduce.alc")),
1658 }),
1659};
1660
1661#[must_use]
1663pub const fn translate() -> Option<TranslationParts> {
1664 Some(TRANSLATION)
1665}
1666
1667pub fn manifest_text() -> &'static str {
1683 TRANSLATION.manifest
1684}
1685
1686pub fn render_text() -> &'static str {
1702 match TRANSLATION.render {
1703 Some(part) => part.source.unwrap_or_default(),
1704 None => "",
1705 }
1706}
1707
1708#[cfg(doctest)]
1709#[doc = include_str!("../README.md")]
1710mod readme_examples {}