1use crate::{
12 error::{Result, RssError, ValidationError},
13 MAX_FEED_SIZE, MAX_GENERAL_LENGTH,
14};
15use serde::{Deserialize, Serialize};
16use std::collections::HashMap;
17use std::fmt;
18use std::str::FromStr;
19use time::{
20 format_description::well_known::Iso8601,
21 format_description::well_known::Rfc2822, OffsetDateTime,
22};
23use url::Url;
24
25#[derive(
27 Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize,
28)]
29#[non_exhaustive]
30#[derive(Default)]
31pub enum RssVersion {
32 RSS0_90,
34 RSS0_91,
36 RSS0_92,
38 RSS1_0,
40 #[default]
42 RSS2_0,
43}
44
45impl RssVersion {
46 #[must_use]
52 pub const fn as_str(&self) -> &'static str {
53 match self {
54 Self::RSS0_90 => "0.90",
55 Self::RSS0_91 => "0.91",
56 Self::RSS0_92 => "0.92",
57 Self::RSS1_0 => "1.0",
58 Self::RSS2_0 => "2.0",
59 }
60 }
61}
62
63impl fmt::Display for RssVersion {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 write!(f, "{}", self.as_str())
66 }
67}
68
69impl FromStr for RssVersion {
70 type Err = RssError;
71
72 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
73 match s {
74 "0.90" => Ok(Self::RSS0_90),
75 "0.91" => Ok(Self::RSS0_91),
76 "0.92" => Ok(Self::RSS0_92),
77 "1.0" => Ok(Self::RSS1_0),
78 "2.0" => Ok(Self::RSS2_0),
79 _ => Err(RssError::InvalidRssVersion(s.to_string())),
80 }
81 }
82}
83
84#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
86#[non_exhaustive]
87pub struct RssData {
88 pub atom_link: String,
90 pub author: String,
92 pub category: String,
94 pub copyright: String,
96 pub description: String,
98 pub docs: String,
100 pub generator: String,
102 pub guid: String,
104 pub image_title: String,
106 pub image_url: String,
108 pub image_link: String,
110 pub language: String,
112 pub last_build_date: String,
114 pub link: String,
116 pub managing_editor: String,
118 pub pub_date: String,
120 pub title: String,
122 pub ttl: String,
124 pub webmaster: String,
126 pub items: Vec<RssItem>,
128 pub version: RssVersion,
130 pub creator: String,
132 pub date: String,
134}
135
136impl RssData {
137 #[must_use]
147 pub fn new(version: Option<RssVersion>) -> Self {
148 Self {
149 version: version.unwrap_or_default(),
150 ..Default::default()
151 }
152 }
153
154 #[must_use]
165 pub fn set<T: Into<String>>(
166 mut self,
167 field: RssDataField,
168 value: T,
169 ) -> Self {
170 let value = sanitize_input(&value.into());
171 match field {
172 RssDataField::AtomLink => self.atom_link = value,
173 RssDataField::Author => self.author = value,
174 RssDataField::Category => self.category = value,
175 RssDataField::Copyright => self.copyright = value,
176 RssDataField::Description => self.description = value,
177 RssDataField::Docs => self.docs = value,
178 RssDataField::Generator => self.generator = value,
179 RssDataField::Guid => self.guid = value,
180 RssDataField::ImageTitle => self.image_title = value,
181 RssDataField::ImageUrl => self.image_url = value,
182 RssDataField::ImageLink => self.image_link = value,
183 RssDataField::Language => self.language = value,
184 RssDataField::LastBuildDate => self.last_build_date = value,
185 RssDataField::Link => self.link = value,
186 RssDataField::ManagingEditor => {
187 self.managing_editor = value;
188 }
189 RssDataField::PubDate => self.pub_date = value,
190 RssDataField::Title => self.title = value,
191 RssDataField::Ttl => self.ttl = value,
192 RssDataField::Webmaster => self.webmaster = value,
193 }
194 self
195 }
196
197 pub fn set_item_field<T: Into<String>>(
211 &mut self,
212 field: RssItemField,
213 value: T,
214 ) {
215 let value = sanitize_input(&value.into());
216 if self.items.is_empty() {
217 self.items.push(RssItem::new());
218 }
219 let item = self.items.last_mut().unwrap();
220 match field {
221 RssItemField::Guid => item.guid = value,
222 RssItemField::Category => item.category = Some(value),
223 RssItemField::Description => item.description = value,
224 RssItemField::Link => item.link = value,
225 RssItemField::PubDate => item.pub_date = value,
226 RssItemField::Title => item.title = value,
227 RssItemField::Author => item.author = value,
228 RssItemField::Comments => item.comments = Some(value),
229 RssItemField::Enclosure => item.enclosure = Some(value),
230 RssItemField::Source => item.source = Some(value),
231 }
232 }
233
234 pub fn validate_size(&self) -> Result<()> {
246 let mut total_size = 0;
247 total_size += self.title.len();
248 total_size += self.link.len();
249 total_size += self.description.len();
250 for item in &self.items {
253 total_size += item.title.len();
254 total_size += item.link.len();
255 total_size += item.description.len();
256 }
258
259 if total_size > MAX_FEED_SIZE {
260 return Err(RssError::InvalidInput(
261 format!("Total feed size exceeds maximum allowed size of {MAX_FEED_SIZE} bytes")
262 ));
263 }
264
265 Ok(())
266 }
267
268 pub fn set_image(&mut self, title: &str, url: &str, link: &str) {
276 self.image_title = sanitize_input(title);
277 self.image_url = sanitize_input(url);
278 self.image_link = sanitize_input(link);
279 }
280
281 pub fn add_item(&mut self, item: RssItem) {
289 self.items.push(item);
290 }
291
292 pub fn remove_item(&mut self, guid: &str) -> bool {
302 let initial_len = self.items.len();
303 self.items.retain(|item| item.guid != guid);
304 self.items.len() < initial_len
305 }
306
307 #[must_use]
309 pub fn item_count(&self) -> usize {
310 self.items.len()
311 }
312
313 pub fn clear_items(&mut self) {
315 self.items.clear();
316 }
317
318 pub fn validate(&self) -> Result<()> {
334 let mut errors: Vec<ValidationError> = Vec::new();
335
336 if self.title.is_empty() {
340 errors.push(ValidationError::new(
341 "channel.title",
342 "channel.title is missing",
343 ));
344 }
345
346 if self.link.is_empty() {
347 errors.push(ValidationError::new(
348 "channel.link",
349 "channel.link is missing",
350 ));
351 } else if let Err(e) = validate_url(&self.link) {
352 errors.push(ValidationError::new(
356 "channel.link",
357 format!("Invalid channel.link: {e}"),
358 ));
359 }
360
361 if self.description.is_empty() {
362 errors.push(ValidationError::new(
363 "channel.description",
364 "channel.description is missing",
365 ));
366 }
367
368 if self.category.len() > MAX_GENERAL_LENGTH {
370 return Err(RssError::InvalidInput(format!(
371 "channel.category exceeds maximum allowed length of {MAX_GENERAL_LENGTH} characters"
372 )));
373 }
374
375 if !self.pub_date.is_empty() {
376 if let Err(e) = parse_date(&self.pub_date) {
377 errors.push(ValidationError::new(
378 "channel.pub_date",
379 format!("Invalid channel.pub_date: {e}"),
380 ));
381 }
382 }
383
384 if !errors.is_empty() {
385 return Err(RssError::ValidationErrors(errors));
386 }
387
388 Ok(())
389 }
390
391 #[must_use]
397 pub fn to_hash_map(&self) -> HashMap<String, String> {
398 let mut map = HashMap::new();
399 map.insert("atom_link".to_string(), self.atom_link.clone());
400 map.insert("author".to_string(), self.author.clone());
401 map.insert("category".to_string(), self.category.clone());
402 map.insert("copyright".to_string(), self.copyright.clone());
403 map.insert("description".to_string(), self.description.clone());
404 map.insert("docs".to_string(), self.docs.clone());
405 map.insert("generator".to_string(), self.generator.clone());
406 map.insert("guid".to_string(), self.guid.clone());
407 map.insert("image_title".to_string(), self.image_title.clone());
408 map.insert("image_url".to_string(), self.image_url.clone());
409 map.insert("image_link".to_string(), self.image_link.clone());
410 map.insert("language".to_string(), self.language.clone());
411 map.insert(
412 "last_build_date".to_string(),
413 self.last_build_date.clone(),
414 );
415 map.insert("link".to_string(), self.link.clone());
416 map.insert(
417 "managing_editor".to_string(),
418 self.managing_editor.clone(),
419 );
420 map.insert("pub_date".to_string(), self.pub_date.clone());
421 map.insert("title".to_string(), self.title.clone());
422 map.insert("ttl".to_string(), self.ttl.clone());
423 map.insert("webmaster".to_string(), self.webmaster.clone());
424 map
425 }
426
427 #[must_use]
431 pub fn version(mut self, version: RssVersion) -> Self {
432 self.version = version;
433 self
434 }
435
436 #[must_use]
438 pub fn atom_link<T: Into<String>>(self, value: T) -> Self {
439 self.set(RssDataField::AtomLink, value)
440 }
441
442 #[must_use]
444 pub fn author<T: Into<String>>(self, value: T) -> Self {
445 self.set(RssDataField::Author, value)
446 }
447
448 #[must_use]
450 pub fn category<T: Into<String>>(self, value: T) -> Self {
451 self.set(RssDataField::Category, value)
452 }
453
454 #[must_use]
456 pub fn copyright<T: Into<String>>(self, value: T) -> Self {
457 self.set(RssDataField::Copyright, value)
458 }
459
460 #[must_use]
462 pub fn description<T: Into<String>>(self, value: T) -> Self {
463 self.set(RssDataField::Description, value)
464 }
465
466 #[must_use]
468 pub fn docs<T: Into<String>>(self, value: T) -> Self {
469 self.set(RssDataField::Docs, value)
470 }
471
472 #[must_use]
474 pub fn generator<T: Into<String>>(self, value: T) -> Self {
475 self.set(RssDataField::Generator, value)
476 }
477
478 #[must_use]
480 pub fn guid<T: Into<String>>(self, value: T) -> Self {
481 self.set(RssDataField::Guid, value)
482 }
483
484 #[must_use]
486 pub fn image_title<T: Into<String>>(self, value: T) -> Self {
487 self.set(RssDataField::ImageTitle, value)
488 }
489
490 #[must_use]
492 pub fn image_url<T: Into<String>>(self, value: T) -> Self {
493 self.set(RssDataField::ImageUrl, value)
494 }
495
496 #[must_use]
498 pub fn image_link<T: Into<String>>(self, value: T) -> Self {
499 self.set(RssDataField::ImageLink, value)
500 }
501
502 #[must_use]
504 pub fn language<T: Into<String>>(self, value: T) -> Self {
505 self.set(RssDataField::Language, value)
506 }
507
508 #[must_use]
510 pub fn last_build_date<T: Into<String>>(self, value: T) -> Self {
511 self.set(RssDataField::LastBuildDate, value)
512 }
513
514 #[must_use]
516 pub fn link<T: Into<String>>(self, value: T) -> Self {
517 self.set(RssDataField::Link, value)
518 }
519
520 #[must_use]
522 pub fn managing_editor<T: Into<String>>(self, value: T) -> Self {
523 self.set(RssDataField::ManagingEditor, value)
524 }
525
526 #[must_use]
528 pub fn pub_date<T: Into<String>>(self, value: T) -> Self {
529 self.set(RssDataField::PubDate, value)
530 }
531
532 #[must_use]
534 pub fn title<T: Into<String>>(self, value: T) -> Self {
535 self.set(RssDataField::Title, value)
536 }
537
538 #[must_use]
540 pub fn ttl<T: Into<String>>(self, value: T) -> Self {
541 self.set(RssDataField::Ttl, value)
542 }
543
544 #[must_use]
546 pub fn webmaster<T: Into<String>>(self, value: T) -> Self {
547 self.set(RssDataField::Webmaster, value)
548 }
549}
550
551#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
553pub enum RssDataField {
554 AtomLink,
556 Author,
558 Category,
560 Copyright,
562 Description,
564 Docs,
566 Generator,
568 Guid,
570 ImageTitle,
572 ImageUrl,
574 ImageLink,
576 Language,
578 LastBuildDate,
580 Link,
582 ManagingEditor,
584 PubDate,
586 Title,
588 Ttl,
590 Webmaster,
592}
593
594#[derive(
596 Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize,
597)]
598#[non_exhaustive]
599pub struct RssItem {
600 pub guid: String,
602 pub category: Option<String>,
604 pub description: String,
606 pub link: String,
608 pub pub_date: String,
610 pub title: String,
612 pub author: String,
614 pub comments: Option<String>,
616 pub enclosure: Option<String>,
618 pub source: Option<String>,
620 pub creator: Option<String>,
622 pub date: Option<String>,
624}
625
626impl RssItem {
627 #[must_use]
629 pub fn new() -> Self {
630 Self::default()
631 }
632
633 #[must_use]
644 pub fn set<T: Into<String>>(
645 mut self,
646 field: RssItemField,
647 value: T,
648 ) -> Self {
649 let value = sanitize_input(&value.into());
650 match field {
651 RssItemField::Guid => self.guid = value,
652 RssItemField::Category => self.category = Some(value),
653 RssItemField::Description => self.description = value,
654 RssItemField::Link => self.link = value,
655 RssItemField::PubDate => self.pub_date = value,
656 RssItemField::Title => self.title = value,
657 RssItemField::Author => self.author = value,
658 RssItemField::Comments => self.comments = Some(value),
659 RssItemField::Enclosure => self.enclosure = Some(value),
660 RssItemField::Source => self.source = Some(value),
661 }
662 self
663 }
664
665 pub fn validate(&self) -> Result<()> {
682 let mut errors: Vec<ValidationError> = Vec::new();
683
684 if self.title.is_empty() {
687 errors.push(ValidationError::new(
688 "item.title",
689 "item.title is missing",
690 ));
691 }
692
693 if self.link.is_empty() {
694 errors.push(ValidationError::new(
695 "item.link",
696 "item.link is missing",
697 ));
698 } else if let Err(e) = validate_link_field(&self.link) {
699 errors.push(ValidationError::new(
703 "item.link",
704 format!("Invalid item.link: {e}"),
705 ));
706 }
707
708 if self.description.is_empty() {
709 errors.push(ValidationError::new(
710 "item.description",
711 "item.description is missing",
712 ));
713 }
714
715 if !errors.is_empty() {
716 return Err(RssError::ValidationErrors(errors));
717 }
718
719 Ok(())
720 }
721
722 pub fn pub_date_parsed(&self) -> Result<OffsetDateTime> {
732 parse_date(&self.pub_date)
733 }
734
735 #[must_use]
739 pub fn guid<T: Into<String>>(self, value: T) -> Self {
740 self.set(RssItemField::Guid, value)
741 }
742
743 #[must_use]
745 pub fn category<T: Into<String>>(self, value: T) -> Self {
746 self.set(RssItemField::Category, value)
747 }
748
749 #[must_use]
751 pub fn description<T: Into<String>>(self, value: T) -> Self {
752 self.set(RssItemField::Description, value)
753 }
754
755 #[must_use]
757 pub fn link<T: Into<String>>(self, value: T) -> Self {
758 self.set(RssItemField::Link, value)
759 }
760
761 #[must_use]
763 pub fn pub_date<T: Into<String>>(self, value: T) -> Self {
764 self.set(RssItemField::PubDate, value)
765 }
766
767 #[must_use]
769 pub fn title<T: Into<String>>(self, value: T) -> Self {
770 self.set(RssItemField::Title, value)
771 }
772
773 #[must_use]
775 pub fn author<T: Into<String>>(self, value: T) -> Self {
776 self.set(RssItemField::Author, value)
777 }
778
779 #[must_use]
781 pub fn comments<T: Into<String>>(self, value: T) -> Self {
782 self.set(RssItemField::Comments, value)
783 }
784
785 #[must_use]
787 pub fn enclosure<T: Into<String>>(self, value: T) -> Self {
788 self.set(RssItemField::Enclosure, value)
789 }
790
791 #[must_use]
793 pub fn source<T: Into<String>>(self, value: T) -> Self {
794 self.set(RssItemField::Source, value)
795 }
796}
797
798#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
800pub enum RssItemField {
801 Guid,
803 Category,
805 Description,
807 Link,
809 PubDate,
811 Title,
813 Author,
815 Comments,
817 Enclosure,
819 Source,
821}
822
823pub fn validate_url(url: &str) -> Result<()> {
839 let parsed_url = Url::parse(url)
840 .map_err(|_| RssError::InvalidUrl(url.to_string()))?;
841
842 if parsed_url.scheme() != "http" && parsed_url.scheme() != "https" {
843 return Err(RssError::InvalidUrl(
844 "URL must use http or https protocol".to_string(),
845 ));
846 }
847
848 Ok(())
849}
850
851pub fn validate_link_field(value: &str) -> Result<()> {
873 if value.is_empty() {
874 return Err(RssError::InvalidUrl(
875 "empty link is not a valid relative or absolute URL"
876 .to_string(),
877 ));
878 }
879 if value.chars().any(|c| c.is_whitespace() || c.is_control()) {
880 return Err(RssError::InvalidUrl(format!(
881 "link contains whitespace or control characters: {value:?}"
882 )));
883 }
884 Ok(())
889}
890
891pub fn parse_date(date_str: &str) -> Result<OffsetDateTime> {
909 if let Ok(parsed) = OffsetDateTime::parse(date_str, &Rfc2822) {
910 return Ok(parsed);
911 }
912
913 if let Ok(parsed) =
914 OffsetDateTime::parse(date_str, &Iso8601::DEFAULT)
915 {
916 return Ok(parsed);
917 }
918
919 Err(RssError::DateParseError(date_str.to_string()))
920}
921
922fn sanitize_input(input: &str) -> String {
932 input
933 .replace('&', "&")
934 .replace('<', "<")
935 .replace('>', ">")
936 .replace('"', """)
937 .replace('\'', "'")
938}
939
940#[cfg(test)]
941mod tests {
942 use super::*;
943 use crate::parser::parse_rss;
944
945 #[test]
946 fn test_rss_version() {
947 assert_eq!(RssVersion::RSS2_0.as_str(), "2.0");
948 assert_eq!(RssVersion::default(), RssVersion::RSS2_0);
949 assert_eq!(RssVersion::RSS1_0.to_string(), "1.0");
950 assert!(matches!(
951 "2.0".parse::<RssVersion>(),
952 Ok(RssVersion::RSS2_0)
953 ));
954 assert!("3.0".parse::<RssVersion>().is_err());
955 }
956
957 #[test]
958 fn test_rss_data_new() {
959 let rss_data = RssData::new(Some(RssVersion::RSS2_0));
960 assert_eq!(rss_data.version, RssVersion::RSS2_0);
961 }
962
963 #[test]
964 fn test_rss_data_setters() {
965 let rss_data = RssData::new(None)
966 .title("Test Feed")
967 .link("https://example.com")
968 .description("A test feed")
969 .generator("RSS Gen")
970 .guid("unique-guid")
971 .pub_date("2024-03-21T12:00:00Z")
972 .language("en");
973
974 assert_eq!(rss_data.title, "Test Feed");
975 assert_eq!(rss_data.link, "https://example.com");
976 assert_eq!(rss_data.description, "A test feed");
977 assert_eq!(rss_data.generator, "RSS Gen");
978 assert_eq!(rss_data.guid, "unique-guid");
979 assert_eq!(rss_data.pub_date, "2024-03-21T12:00:00Z");
980 assert_eq!(rss_data.language, "en");
981 }
982
983 #[test]
984 fn test_rss_data_validate() {
985 let valid_rss_data = RssData::new(None)
986 .title("Valid Feed")
987 .link("https://example.com")
988 .description("A valid RSS feed");
989
990 assert!(valid_rss_data.validate().is_ok());
991
992 let invalid_rss_data = RssData::new(None)
993 .title("Invalid Feed")
994 .link("not a valid url")
995 .description("An invalid RSS feed");
996
997 let result = invalid_rss_data.validate();
998 assert!(result.is_err());
999 if let Err(RssError::ValidationErrors(errors)) = result {
1000 assert!(errors.iter().any(|e| e.field == "channel.link"
1001 && e.message.contains("Invalid channel.link")),
1002 "Expected a structured ValidationError on `channel.link`, got: {errors:?}");
1003 } else {
1004 panic!("Expected ValidationErrors");
1005 }
1006 }
1007
1008 #[test]
1009 fn test_add_item() {
1010 let mut rss_data = RssData::new(None)
1011 .title("Test RSS Feed")
1012 .link("https://example.com")
1013 .description("A test RSS feed");
1014
1015 let item = RssItem::new()
1016 .title("Test Item")
1017 .link("https://example.com/item")
1018 .description("A test item")
1019 .guid("unique-id-1")
1020 .pub_date("2024-03-21");
1021
1022 rss_data.add_item(item);
1023
1024 assert_eq!(rss_data.items.len(), 1);
1025 assert_eq!(rss_data.items[0].title, "Test Item");
1026 assert_eq!(rss_data.items[0].link, "https://example.com/item");
1027 assert_eq!(rss_data.items[0].description, "A test item");
1028 assert_eq!(rss_data.items[0].guid, "unique-id-1");
1029 assert_eq!(rss_data.items[0].pub_date, "2024-03-21");
1030 }
1031
1032 #[test]
1033 fn test_remove_item() {
1034 let mut rss_data = RssData::new(None)
1035 .title("Test RSS Feed")
1036 .link("https://example.com")
1037 .description("A test RSS feed");
1038
1039 let item1 = RssItem::new()
1040 .title("Item 1")
1041 .link("https://example.com/item1")
1042 .description("First item")
1043 .guid("guid1");
1044
1045 let item2 = RssItem::new()
1046 .title("Item 2")
1047 .link("https://example.com/item2")
1048 .description("Second item")
1049 .guid("guid2");
1050
1051 rss_data.add_item(item1);
1052 rss_data.add_item(item2);
1053
1054 assert_eq!(rss_data.item_count(), 2);
1055
1056 assert!(rss_data.remove_item("guid1"));
1057 assert_eq!(rss_data.item_count(), 1);
1058 assert_eq!(rss_data.items[0].title, "Item 2");
1059
1060 assert!(!rss_data.remove_item("non-existent-guid"));
1061 assert_eq!(rss_data.item_count(), 1);
1062 }
1063
1064 #[test]
1065 fn test_clear_items() {
1066 let mut rss_data = RssData::new(None)
1067 .title("Test RSS Feed")
1068 .link("https://example.com")
1069 .description("A test RSS feed");
1070
1071 rss_data.add_item(RssItem::new().title("Item 1").guid("guid1"));
1072 rss_data.add_item(RssItem::new().title("Item 2").guid("guid2"));
1073
1074 assert_eq!(rss_data.item_count(), 2);
1075
1076 rss_data.clear_items();
1077
1078 assert_eq!(rss_data.item_count(), 0);
1079 }
1080
1081 #[test]
1082 fn test_rss_item_validate() {
1083 let valid_item = RssItem::new()
1084 .title("Valid Item")
1085 .link("https://example.com/valid")
1086 .description("A valid item")
1087 .guid("valid-guid");
1088
1089 assert!(valid_item.validate().is_ok());
1090
1091 let invalid_item = RssItem::new()
1092 .title("Invalid Item")
1093 .description("An invalid item");
1094
1095 let result = invalid_item.validate();
1096 assert!(result.is_err());
1097
1098 if let Err(RssError::ValidationErrors(errors)) = result {
1099 assert_eq!(errors.len(), 1);
1100 assert!(
1101 errors.iter().any(|e| e.field == "item.link"
1102 && e.message == "item.link is missing"),
1103 "expected `item.link is missing`, got: {errors:?}"
1104 );
1105 } else {
1106 panic!("Expected ValidationErrors");
1107 }
1108 }
1109
1110 #[test]
1111 fn test_validate_url() {
1112 assert!(validate_url("https://example.com").is_ok());
1113 assert!(validate_url("not a url").is_err());
1114 }
1115
1116 #[test]
1117 fn test_parse_date() {
1118 assert!(parse_date("Mon, 01 Jan 2024 00:00:00 GMT").is_ok());
1119 assert!(parse_date("2024-03-21T12:00:00Z").is_ok());
1120 assert!(parse_date("invalid date").is_err());
1121 }
1122
1123 #[test]
1124 fn test_sanitize_input() {
1125 let input = "Test <script>alert('XSS')</script>";
1126 let sanitized = sanitize_input(input);
1127 assert_eq!(
1128 sanitized,
1129 "Test <script>alert('XSS')</script>"
1130 );
1131 }
1132
1133 #[test]
1134 fn test_rss_data_set_with_enum() {
1135 let rss_data = RssData::new(None)
1136 .set(RssDataField::Title, "Test Title")
1137 .set(RssDataField::Link, "https://example.com")
1138 .set(RssDataField::Description, "Test Description");
1139
1140 assert_eq!(rss_data.title, "Test Title");
1141 assert_eq!(rss_data.link, "https://example.com");
1142 assert_eq!(rss_data.description, "Test Description");
1143 }
1144
1145 #[test]
1146 fn test_rss_item_set_with_enum() {
1147 let item = RssItem::new()
1148 .set(RssItemField::Title, "Test Item")
1149 .set(RssItemField::Link, "https://example.com/item")
1150 .set(RssItemField::Guid, "unique-id");
1151
1152 assert_eq!(item.title, "Test Item");
1153 assert_eq!(item.link, "https://example.com/item");
1154 assert_eq!(item.guid, "unique-id");
1155 }
1156
1157 #[test]
1158 fn test_to_hash_map() {
1159 let rss_data = RssData::new(None)
1160 .title("Test Title")
1161 .link("https://example.com/rss")
1162 .description("A test RSS feed")
1163 .atom_link("https://example.com/atom")
1164 .language("en")
1165 .managing_editor("editor@example.com")
1166 .webmaster("webmaster@example.com")
1167 .last_build_date("2024-03-21T12:00:00Z")
1168 .pub_date("2024-03-21T12:00:00Z")
1169 .ttl("60")
1170 .generator("RSS Gen")
1171 .guid("unique-guid")
1172 .image_title("Image Title".to_string())
1173 .docs("https://docs.example.com");
1174
1175 let map = rss_data.to_hash_map();
1176
1177 assert_eq!(map.get("title").unwrap(), "Test Title");
1178 assert_eq!(map.get("link").unwrap(), "https://example.com/rss");
1179 assert_eq!(
1180 map.get("atom_link").unwrap(),
1181 "https://example.com/atom"
1182 );
1183 assert_eq!(map.get("language").unwrap(), "en");
1184 assert_eq!(
1185 map.get("managing_editor").unwrap(),
1186 "editor@example.com"
1187 );
1188 assert_eq!(
1189 map.get("webmaster").unwrap(),
1190 "webmaster@example.com"
1191 );
1192 assert_eq!(
1193 map.get("last_build_date").unwrap(),
1194 "2024-03-21T12:00:00Z"
1195 );
1196 assert_eq!(
1197 map.get("pub_date").unwrap(),
1198 "2024-03-21T12:00:00Z"
1199 );
1200 assert_eq!(map.get("ttl").unwrap(), "60");
1201 assert_eq!(map.get("generator").unwrap(), "RSS Gen");
1202 assert_eq!(map.get("guid").unwrap(), "unique-guid");
1203 assert_eq!(map.get("image_title").unwrap(), "Image Title");
1204 assert_eq!(
1205 map.get("docs").unwrap(),
1206 "https://docs.example.com"
1207 );
1208 }
1209
1210 #[test]
1211 fn test_set_image() {
1212 let mut rss_data = RssData::new(None);
1213 rss_data.set_image(
1214 "Test Image Title",
1215 "https://example.com/image.jpg",
1216 "https://example.com",
1217 );
1218 rss_data.title = "RSS Feed Title".to_string();
1219
1220 assert_eq!(rss_data.image_title, "Test Image Title");
1221 assert_eq!(rss_data.image_url, "https://example.com/image.jpg");
1222 assert_eq!(rss_data.image_link, "https://example.com");
1223 assert_eq!(rss_data.title, "RSS Feed Title");
1224 }
1225
1226 #[test]
1227 fn test_rss_feed_parsing() {
1228 let rss_xml = r#"
1229 <?xml version="1.0" encoding="UTF-8"?>
1230 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"
1231 xmlns:dc="http://purl.org/dc/elements/1.1/"
1232 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
1233 xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/">
1234 <channel>
1235 <title>GETS Open Tenders or Quotes</title>
1236 <link>https://www.gets.govt.nz//ExternalIndex.htm</link>
1237 <description>This feed lists the current open tenders or requests for quote listed on the GETS.</description>
1238 <image>
1239 <title>Open tenders or Requests for Quote from GETS</title>
1240 <url>https://www.gets.govt.nz//ext/default/img/getsLogo.jpg</url>
1241 <link>https://www.gets.govt.nz//ExternalIndex.htm</link>
1242 </image>
1243 </channel>
1244 </rss>
1245 "#;
1246
1247 let parsed =
1248 parse_rss(rss_xml, None).expect("Failed to parse RSS XML");
1249
1250 assert_eq!(parsed.title, "GETS Open Tenders or Quotes");
1251 assert_eq!(
1252 parsed.link,
1253 "https://www.gets.govt.nz//ExternalIndex.htm"
1254 );
1255 assert_eq!(parsed.description, "This feed lists the current open tenders or requests for quote listed on the GETS.");
1256 assert_eq!(
1257 parsed.image_title,
1258 "Open tenders or Requests for Quote from GETS"
1259 );
1260 assert_eq!(
1261 parsed.image_url,
1262 "https://www.gets.govt.nz//ext/default/img/getsLogo.jpg"
1263 );
1264 assert_eq!(
1265 parsed.image_link,
1266 "https://www.gets.govt.nz//ExternalIndex.htm"
1267 );
1268 }
1269
1270 #[test]
1271 fn test_rss_version_from_str() {
1272 assert_eq!(
1273 RssVersion::from_str("0.90").unwrap(),
1274 RssVersion::RSS0_90
1275 );
1276 assert_eq!(
1277 RssVersion::from_str("0.91").unwrap(),
1278 RssVersion::RSS0_91
1279 );
1280 assert_eq!(
1281 RssVersion::from_str("0.92").unwrap(),
1282 RssVersion::RSS0_92
1283 );
1284 assert_eq!(
1285 RssVersion::from_str("1.0").unwrap(),
1286 RssVersion::RSS1_0
1287 );
1288 assert_eq!(
1289 RssVersion::from_str("2.0").unwrap(),
1290 RssVersion::RSS2_0
1291 );
1292 assert!(RssVersion::from_str("3.0").is_err());
1293 }
1294
1295 #[test]
1296 fn test_rss_version_display() {
1297 assert_eq!(format!("{}", RssVersion::RSS0_90), "0.90");
1298 assert_eq!(format!("{}", RssVersion::RSS0_91), "0.91");
1299 assert_eq!(format!("{}", RssVersion::RSS0_92), "0.92");
1300 assert_eq!(format!("{}", RssVersion::RSS1_0), "1.0");
1301 assert_eq!(format!("{}", RssVersion::RSS2_0), "2.0");
1302 }
1303
1304 #[test]
1305 fn test_rss_data_set_methods() {
1306 let rss_data = RssData::new(None)
1307 .atom_link("https://example.com/atom")
1308 .author("John Doe")
1309 .category("Technology")
1310 .copyright("© 2024 Example Inc.")
1311 .description("A sample RSS feed")
1312 .docs("https://example.com/rss-docs")
1313 .generator("RSS Gen v1.0")
1314 .guid("unique-guid-123")
1315 .image_title("Feed Image")
1316 .image_url("https://example.com/image.jpg")
1317 .image_link("https://example.com")
1318 .language("en-US")
1319 .last_build_date("2024-03-21T12:00:00Z")
1320 .link("https://example.com")
1321 .managing_editor("editor@example.com")
1322 .pub_date("2024-03-21T00:00:00Z")
1323 .title("Sample Feed")
1324 .ttl("60")
1325 .webmaster("webmaster@example.com");
1326
1327 assert_eq!(rss_data.atom_link, "https://example.com/atom");
1328 assert_eq!(rss_data.author, "John Doe");
1329 assert_eq!(rss_data.category, "Technology");
1330 assert_eq!(rss_data.copyright, "© 2024 Example Inc.");
1331 assert_eq!(rss_data.description, "A sample RSS feed");
1332 assert_eq!(rss_data.docs, "https://example.com/rss-docs");
1333 assert_eq!(rss_data.generator, "RSS Gen v1.0");
1334 assert_eq!(rss_data.guid, "unique-guid-123");
1335 assert_eq!(rss_data.image_title, "Feed Image");
1336 assert_eq!(rss_data.image_url, "https://example.com/image.jpg");
1337 assert_eq!(rss_data.image_link, "https://example.com");
1338 assert_eq!(rss_data.language, "en-US");
1339 assert_eq!(rss_data.last_build_date, "2024-03-21T12:00:00Z");
1340 assert_eq!(rss_data.link, "https://example.com");
1341 assert_eq!(rss_data.managing_editor, "editor@example.com");
1342 assert_eq!(rss_data.pub_date, "2024-03-21T00:00:00Z");
1343 assert_eq!(rss_data.title, "Sample Feed");
1344 assert_eq!(rss_data.ttl, "60");
1345 assert_eq!(rss_data.webmaster, "webmaster@example.com");
1346 }
1347
1348 #[test]
1349 fn test_rss_data_empty() {
1350 let rss_data = RssData::new(None);
1351 assert!(rss_data.title.is_empty());
1352 assert!(rss_data.link.is_empty());
1353 assert!(rss_data.description.is_empty());
1354 assert_eq!(rss_data.items.len(), 0);
1355 }
1356
1357 #[test]
1358 fn test_rss_item_empty() {
1359 let item = RssItem::new();
1360 assert!(item.title.is_empty());
1361 assert!(item.link.is_empty());
1362 assert!(item.guid.is_empty());
1363 assert!(item.description.is_empty());
1364 }
1365
1366 #[test]
1367 fn test_rss_data_to_hash_map() {
1368 let rss_data = RssData::new(None)
1369 .title("Test Feed")
1370 .link("https://example.com")
1371 .description("A test feed");
1372
1373 let hash_map = rss_data.to_hash_map();
1374 assert_eq!(hash_map.get("title").unwrap(), "Test Feed");
1375 assert_eq!(
1376 hash_map.get("link").unwrap(),
1377 "https://example.com"
1378 );
1379 assert_eq!(hash_map.get("description").unwrap(), "A test feed");
1380 }
1381
1382 #[test]
1383 fn test_rss_data_version_setter() {
1384 let rss_data = RssData::new(None).version(RssVersion::RSS1_0);
1385 assert_eq!(rss_data.version, RssVersion::RSS1_0);
1386 }
1387
1388 #[test]
1389 fn test_remove_item_not_found() {
1390 let mut rss_data = RssData::new(None);
1391 let item = RssItem::new().guid("existing-guid");
1392 rss_data.add_item(item);
1393
1394 let removed = rss_data.remove_item("non-existent-guid");
1396 assert!(!removed);
1397 assert_eq!(rss_data.items.len(), 1);
1398 }
1399
1400 #[test]
1401 fn test_set_item_field_empty_items() {
1402 let mut rss_data = RssData::new(None);
1403 rss_data.set_item_field(RssItemField::Title, "Test Item Title");
1404
1405 assert_eq!(rss_data.items.len(), 1);
1406 assert_eq!(rss_data.items[0].title, "Test Item Title");
1407 }
1408
1409 #[test]
1410 fn test_set_image_empty() {
1411 let mut rss_data = RssData::new(None);
1412 rss_data.set_image("", "", "");
1413
1414 assert!(rss_data.image_title.is_empty());
1415 assert!(rss_data.image_url.is_empty());
1416 assert!(rss_data.image_link.is_empty());
1417 }
1418
1419 #[test]
1420 fn test_rss_item_set_empty_field() {
1421 let item = RssItem::new().set(RssItemField::Title, "");
1422 assert!(item.title.is_empty());
1423 }
1424
1425 #[test]
1426 fn test_rss_data_validate_invalid_pub_date() {
1427 let rss_data = RssData::new(None)
1428 .title("Test Feed")
1429 .link("https://example.com")
1430 .description("A test feed")
1431 .pub_date("not a valid date");
1432
1433 let result = rss_data.validate();
1434 assert!(result.is_err());
1435 if let Err(RssError::ValidationErrors(errors)) = result {
1436 assert!(
1437 errors.iter().any(|e| e.field == "channel.pub_date"
1438 && e.message.contains("Invalid channel.pub_date")),
1439 "Expected structured `channel.pub_date` error, got: {errors:?}"
1440 );
1441 } else {
1442 panic!("Expected ValidationErrors");
1443 }
1444 }
1445
1446 #[test]
1447 fn test_rss_item_validate_invalid_link() {
1448 let item = RssItem::new()
1452 .title("Item")
1453 .link("not a valid url with spaces")
1454 .description("Desc");
1455
1456 let result = item.validate();
1457 assert!(result.is_err());
1458 if let Err(RssError::ValidationErrors(errors)) = result {
1459 assert!(
1460 errors.iter().any(|e| e.field == "item.link"
1461 && e.message.contains("Invalid item.link")),
1462 "Expected structured `item.link` error, got: {errors:?}"
1463 );
1464 } else {
1465 panic!("Expected ValidationErrors");
1466 }
1467 }
1468
1469 #[test]
1470 fn test_validate_size_exceeds_max() {
1471 let mut rss_data = RssData::new(Some(RssVersion::RSS2_0));
1472 rss_data.description = "x".repeat(MAX_FEED_SIZE + 1);
1474 let result = rss_data.validate_size();
1475 assert!(result.is_err());
1476 if let Err(RssError::InvalidInput(msg)) = result {
1477 assert!(msg.contains("exceeds maximum allowed size"));
1478 } else {
1479 panic!("Expected InvalidInput error");
1480 }
1481 }
1482
1483 #[test]
1484 fn test_validate_size_ok() {
1485 let rss_data = RssData::new(Some(RssVersion::RSS2_0))
1486 .title("Test")
1487 .link("https://example.com")
1488 .description("Short description");
1489 assert!(rss_data.validate_size().is_ok());
1490 }
1491
1492 #[test]
1493 fn test_set_item_field_all_variants() {
1494 let mut rss_data = RssData::new(None);
1495 rss_data.set_item_field(RssItemField::Title, "Title");
1496 rss_data
1497 .set_item_field(RssItemField::Link, "https://example.com");
1498 rss_data.set_item_field(RssItemField::Description, "Desc");
1499 rss_data.set_item_field(RssItemField::Guid, "guid-1");
1500 rss_data.set_item_field(
1501 RssItemField::PubDate,
1502 "Mon, 01 Jan 2024 00:00:00 GMT",
1503 );
1504 rss_data
1505 .set_item_field(RssItemField::Author, "author@example.com");
1506 rss_data.set_item_field(RssItemField::Category, "tech");
1507 rss_data.set_item_field(
1508 RssItemField::Comments,
1509 "https://example.com/comments",
1510 );
1511 rss_data.set_item_field(
1512 RssItemField::Enclosure,
1513 "https://example.com/file.mp3",
1514 );
1515 rss_data.set_item_field(
1516 RssItemField::Source,
1517 "https://example.com/source",
1518 );
1519
1520 let item = &rss_data.items[0];
1521 assert_eq!(item.title, "Title");
1522 assert_eq!(item.link, "https://example.com");
1523 assert_eq!(item.description, "Desc");
1524 assert_eq!(item.guid, "guid-1");
1525 assert_eq!(item.author, "author@example.com");
1526 assert_eq!(item.category, Some("tech".to_string()));
1527 assert_eq!(
1528 item.comments,
1529 Some("https://example.com/comments".to_string())
1530 );
1531 assert_eq!(
1532 item.enclosure,
1533 Some("https://example.com/file.mp3".to_string())
1534 );
1535 assert_eq!(
1536 item.source,
1537 Some("https://example.com/source".to_string())
1538 );
1539 }
1540
1541 #[test]
1542 fn test_rss_item_builder_all_fields() {
1543 let item = RssItem::new()
1544 .title("Title")
1545 .link("https://example.com")
1546 .description("Desc")
1547 .guid("guid-1")
1548 .pub_date("Mon, 01 Jan 2024 00:00:00 GMT")
1549 .author("author@example.com")
1550 .category("tech")
1551 .comments("https://example.com/comments")
1552 .enclosure("https://example.com/file.mp3")
1553 .source("https://example.com/source");
1554
1555 assert_eq!(item.category, Some("tech".to_string()));
1556 assert_eq!(
1557 item.comments,
1558 Some("https://example.com/comments".to_string())
1559 );
1560 assert_eq!(
1561 item.enclosure,
1562 Some("https://example.com/file.mp3".to_string())
1563 );
1564 assert_eq!(
1565 item.source,
1566 Some("https://example.com/source".to_string())
1567 );
1568 }
1569
1570 #[test]
1571 fn test_rss_item_pub_date_parsed_valid() {
1572 let item =
1573 RssItem::new().pub_date("Sat, 07 Sep 2002 09:42:31 GMT");
1574 let result = item.pub_date_parsed();
1575 assert!(result.is_ok());
1576 }
1577
1578 #[test]
1579 fn test_rss_item_pub_date_parsed_invalid() {
1580 let item = RssItem::new().pub_date("not-a-date");
1581 let result = item.pub_date_parsed();
1582 assert!(result.is_err());
1583 }
1584
1585 #[test]
1586 fn test_parse_date_iso8601() {
1587 let result = parse_date("2024-01-15T10:30:00Z");
1588 assert!(result.is_ok());
1589 }
1590
1591 #[test]
1592 fn test_parse_date_invalid() {
1593 let result = parse_date("completely invalid date");
1594 assert!(result.is_err());
1595 }
1596
1597 #[test]
1598 fn test_rss_item_accepts_relative_link() {
1599 for link in ["/tags/", "articles/foo.html", "post.html"] {
1603 let item = RssItem::new()
1604 .title("Item")
1605 .link(link)
1606 .description("Desc");
1607 assert!(
1608 item.validate().is_ok(),
1609 "expected relative link {link:?} to be accepted"
1610 );
1611 }
1612 }
1613
1614 #[test]
1615 fn test_rss_data_still_rejects_relative_link() {
1616 let data = RssData::new(None)
1620 .title("Channel")
1621 .link("/tags/")
1622 .description("Desc");
1623 let result = data.validate();
1624 assert!(
1625 result.is_err(),
1626 "channel.link `/tags/` must be rejected"
1627 );
1628 if let Err(RssError::ValidationErrors(errors)) = result {
1629 assert!(
1630 errors.iter().any(|e| e.field == "channel.link"
1631 && e.message.contains("Invalid channel.link")),
1632 "expected channel-prefixed structured error, got: {errors:?}"
1633 );
1634 } else {
1635 panic!("expected ValidationErrors");
1636 }
1637 }
1638
1639 #[test]
1640 fn test_validate_link_field_rejects_whitespace_and_control() {
1641 assert!(validate_link_field("/path with space").is_err());
1644 assert!(validate_link_field("foo\tbar").is_err());
1645 assert!(validate_link_field("\u{0007}beep").is_err());
1646 assert!(validate_link_field("").is_err());
1647 }
1648
1649 #[test]
1650 fn test_validate_link_field_accepts_absolute_and_relative() {
1651 assert!(validate_link_field("https://example.com/post").is_ok());
1652 assert!(validate_link_field("http://example.com/").is_ok());
1653 assert!(validate_link_field("/tags/").is_ok());
1654 assert!(validate_link_field("articles/foo.html").is_ok());
1655 assert!(validate_link_field("mailto:hi@example.com").is_ok());
1657 }
1658}