rss_gen/
data.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
// Copyright © 2024 RSS Gen. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

// src/data.rs

//! This module contains the core data structures and functionality for RSS feeds.
//!
//! It includes definitions for RSS versions, RSS data, and RSS items, as well as
//! utility functions for URL validation and date parsing.

use crate::{
    error::{Result, RssError},
    MAX_FEED_SIZE, MAX_GENERAL_LENGTH,
};
use dtt::datetime::DateTime;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;
use time::{
    format_description::well_known::Iso8601,
    format_description::well_known::Rfc2822, OffsetDateTime,
};
use url::Url;

/// Represents the different versions of RSS.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize,
)]
#[non_exhaustive]
pub enum RssVersion {
    /// RSS version 0.90
    RSS0_90,
    /// RSS version 0.91
    RSS0_91,
    /// RSS version 0.92
    RSS0_92,
    /// RSS version 1.0
    RSS1_0,
    /// RSS version 2.0
    RSS2_0,
}

impl RssVersion {
    /// Returns the string representation of the RSS version.
    ///
    /// # Returns
    ///
    /// A static string slice representing the RSS version.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::RSS0_90 => "0.90",
            Self::RSS0_91 => "0.91",
            Self::RSS0_92 => "0.92",
            Self::RSS1_0 => "1.0",
            Self::RSS2_0 => "2.0",
        }
    }
}

impl Default for RssVersion {
    fn default() -> Self {
        Self::RSS2_0
    }
}

impl fmt::Display for RssVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl FromStr for RssVersion {
    type Err = RssError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "0.90" => Ok(Self::RSS0_90),
            "0.91" => Ok(Self::RSS0_91),
            "0.92" => Ok(Self::RSS0_92),
            "1.0" => Ok(Self::RSS1_0),
            "2.0" => Ok(Self::RSS2_0),
            _ => Err(RssError::InvalidRssVersion(s.to_string())),
        }
    }
}

/// Represents the main structure for an RSS feed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub struct RssData {
    /// The Atom link of the RSS feed.
    pub atom_link: String,
    /// The author of the RSS feed.
    pub author: String,
    /// The category of the RSS feed.
    pub category: String,
    /// The copyright notice for the content of the feed.
    pub copyright: String,
    /// The description of the RSS feed.
    pub description: String,
    /// The docs link of the RSS feed.
    pub docs: String,
    /// The generator of the RSS feed.
    pub generator: String,
    /// The GUID of the RSS feed.
    pub guid: String,
    /// The image title of the RSS feed.
    pub image_title: String,
    /// The image URL of the RSS feed.
    pub image_url: String,
    /// The image link of the RSS feed.
    pub image_link: String,
    /// The language of the RSS feed.
    pub language: String,
    /// The last build date of the RSS feed.
    pub last_build_date: String,
    /// The main link to the RSS feed.
    pub link: String,
    /// The managing editor of the RSS feed.
    pub managing_editor: String,
    /// The publication date of the RSS feed.
    pub pub_date: String,
    /// The title of the RSS feed.
    pub title: String,
    /// Time To Live (TTL), the number of minutes the feed should be cached before refreshing.
    pub ttl: String,
    /// The webmaster of the RSS feed.
    pub webmaster: String,
    /// A collection of additional items in the RSS feed.
    pub items: Vec<RssItem>,
    /// The version of the RSS feed.
    pub version: RssVersion,
    /// The creator of the RSS feed.
    pub creator: String,
    /// The date the RSS feed was created.
    pub date: String,
}

impl RssData {
    /// Creates a new `RssData` instance with default values and a specified RSS version.
    ///
    /// # Arguments
    ///
    /// * `version` - An optional `RssVersion` specifying the RSS version for the feed.
    ///
    /// # Returns
    ///
    /// A new `RssData` instance.
    #[must_use]
    pub fn new(version: Option<RssVersion>) -> Self {
        Self {
            version: version.unwrap_or_default(),
            ..Default::default()
        }
    }

    /// Sets the value of a specified field and returns the `RssData` instance for method chaining.
    ///
    /// # Arguments
    ///
    /// * `field` - The field to set.
    /// * `value` - The value to assign to the field.
    ///
    /// # Returns
    ///
    /// The updated `RssData` instance.
    #[must_use]
    pub fn set<T: Into<String>>(
        mut self,
        field: RssDataField,
        value: T,
    ) -> Self {
        let value = sanitize_input(&value.into());
        match field {
            RssDataField::AtomLink => self.atom_link = value,
            RssDataField::Author => self.author = value,
            RssDataField::Category => self.category = value,
            RssDataField::Copyright => self.copyright = value,
            RssDataField::Description => self.description = value,
            RssDataField::Docs => self.docs = value,
            RssDataField::Generator => self.generator = value,
            RssDataField::Guid => self.guid = value,
            RssDataField::ImageTitle => self.image_title = value,
            RssDataField::ImageUrl => self.image_url = value,
            RssDataField::ImageLink => self.image_link = value,
            RssDataField::Language => self.language = value,
            RssDataField::LastBuildDate => self.last_build_date = value,
            RssDataField::Link => self.link = value,
            RssDataField::ManagingEditor => {
                self.managing_editor = value;
            }
            RssDataField::PubDate => self.pub_date = value,
            RssDataField::Title => self.title = value,
            RssDataField::Ttl => self.ttl = value,
            RssDataField::Webmaster => self.webmaster = value,
        }
        self
    }

    /// Sets the value of a specified field for the last `RssItem` and updates it.
    ///
    /// # Arguments
    ///
    /// * `field` - The field to set for the `RssItem`.
    /// * `value` - The value to assign to the field.
    ///
    /// # Panics
    ///
    /// This function will panic if `self.items` is empty, as it uses `.unwrap()` to
    /// retrieve the last mutable item in the list.
    ///
    /// Ensure that `self.items` contains at least one `RssItem` before calling this method.
    pub fn set_item_field<T: Into<String>>(
        &mut self,
        field: RssItemField,
        value: T,
    ) {
        let value = sanitize_input(&value.into());
        if self.items.is_empty() {
            self.items.push(RssItem::new());
        }
        let item = self.items.last_mut().unwrap();
        match field {
            RssItemField::Guid => item.guid = value,
            RssItemField::Category => item.category = Some(value),
            RssItemField::Description => item.description = value,
            RssItemField::Link => item.link = value,
            RssItemField::PubDate => item.pub_date = value,
            RssItemField::Title => item.title = value,
            RssItemField::Author => item.author = value,
            RssItemField::Comments => item.comments = Some(value),
            RssItemField::Enclosure => item.enclosure = Some(value),
            RssItemField::Source => item.source = Some(value),
        }
    }

    /// Validates the size of the RSS feed to ensure it does not exceed the maximum allowed size.
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the feed size is valid.
    /// * `Err(RssError)` if the feed size exceeds the maximum allowed size.
    ///
    /// # Errors
    ///
    /// This function returns an `Err(RssError::InvalidInput)` if the total size of the feed
    /// exceeds the maximum allowed size (`MAX_FEED_SIZE`).
    pub fn validate_size(&self) -> Result<()> {
        let mut total_size = 0;
        total_size += self.title.len();
        total_size += self.link.len();
        total_size += self.description.len();
        // Add sizes of other fields...

        for item in &self.items {
            total_size += item.title.len();
            total_size += item.link.len();
            total_size += item.description.len();
            // Add sizes of other item fields...
        }

        if total_size > MAX_FEED_SIZE {
            return Err(RssError::InvalidInput(
                format!("Total feed size exceeds maximum allowed size of {} bytes", MAX_FEED_SIZE)
            ));
        }

        Ok(())
    }

    /// Sets the image for the RSS feed.
    ///
    /// # Arguments
    ///
    /// * `title` - The title of the image.
    /// * `url` - The URL of the image.
    /// * `link` - The link associated with the image.
    pub fn set_image(&mut self, title: &str, url: &str, link: &str) {
        self.image_title = sanitize_input(title);
        self.image_url = sanitize_input(url);
        self.image_link = sanitize_input(link);
    }

    /// Adds an item to the RSS feed.
    ///
    /// This method appends the given `RssItem` to the `items` vector of the `RssData` struct.
    ///
    /// # Arguments
    ///
    /// * `item` - The `RssItem` to be added to the feed.
    pub fn add_item(&mut self, item: RssItem) {
        self.items.push(item);
    }

    /// Removes an item from the RSS feed by its GUID.
    ///
    /// # Arguments
    ///
    /// * `guid` - The GUID of the item to remove.
    ///
    /// # Returns
    ///
    /// `true` if an item was removed, `false` otherwise.
    pub fn remove_item(&mut self, guid: &str) -> bool {
        let initial_len = self.items.len();
        self.items.retain(|item| item.guid != guid);
        self.items.len() < initial_len
    }

    /// Returns the number of items in the RSS feed.
    #[must_use]
    pub fn item_count(&self) -> usize {
        self.items.len()
    }

    /// Clears all items from the RSS feed.
    pub fn clear_items(&mut self) {
        self.items.clear();
    }

    /// Validates the `RssData` to ensure that all required fields are set and valid.
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the `RssData` is valid.
    /// * `Err(RssError)` if any validation errors are found.
    ///
    /// # Errors
    ///
    /// This function returns an `Err(RssError)` in the following cases:
    ///
    /// * `RssError::InvalidInput` if the category exceeds the maximum allowed length.
    /// * `RssError::ValidationErrors` if there are missing or invalid fields (e.g., title, link, description, publication date).
    ///
    /// Additionally, it can return an error if the link format is invalid or the publication date cannot be parsed.
    pub fn validate(&self) -> Result<()> {
        let mut errors = Vec::new();

        if self.title.is_empty() {
            errors.push("Title is missing".to_string());
        }

        if self.link.is_empty() {
            errors.push("Link is missing".to_string());
        } else if let Err(e) = validate_url(&self.link) {
            errors.push(format!("Invalid link: {}", e));
        }

        if self.description.is_empty() {
            errors.push("Description is missing".to_string());
        }

        // Check category length
        if self.category.len() > MAX_GENERAL_LENGTH {
            return Err(RssError::InvalidInput(format!(
            "Category exceeds maximum allowed length of {} characters",
            MAX_GENERAL_LENGTH
        )));
        }

        if !self.pub_date.is_empty() {
            if let Err(e) = parse_date(&self.pub_date) {
                errors.push(format!("Invalid publication date: {}", e));
            }
        }

        if !errors.is_empty() {
            return Err(RssError::ValidationErrors(errors));
        }

        Ok(())
    }

    /// Converts the `RssData` into a `HashMap<String, String>` for easier manipulation.
    ///
    /// # Returns
    ///
    /// A `HashMap<String, String>` containing the RSS feed data.
    #[must_use]
    pub fn to_hash_map(&self) -> HashMap<String, String> {
        let mut map = HashMap::new();
        map.insert("atom_link".to_string(), self.atom_link.clone());
        map.insert("author".to_string(), self.author.clone());
        map.insert("category".to_string(), self.category.clone());
        map.insert("copyright".to_string(), self.copyright.clone());
        map.insert("description".to_string(), self.description.clone());
        map.insert("docs".to_string(), self.docs.clone());
        map.insert("generator".to_string(), self.generator.clone());
        map.insert("guid".to_string(), self.guid.clone());
        map.insert("image_title".to_string(), self.image_title.clone());
        map.insert("image_url".to_string(), self.image_url.clone());
        map.insert("image_link".to_string(), self.image_link.clone());
        map.insert("language".to_string(), self.language.clone());
        map.insert(
            "last_build_date".to_string(),
            self.last_build_date.clone(),
        );
        map.insert("link".to_string(), self.link.clone());
        map.insert(
            "managing_editor".to_string(),
            self.managing_editor.clone(),
        );
        map.insert("pub_date".to_string(), self.pub_date.clone());
        map.insert("title".to_string(), self.title.clone());
        map.insert("ttl".to_string(), self.ttl.clone());
        map.insert("webmaster".to_string(), self.webmaster.clone());
        map
    }

    // Field setter methods

    /// Sets the RSS version.
    #[must_use]
    pub fn version(mut self, version: RssVersion) -> Self {
        self.version = version;
        self
    }

    /// Sets the Atom link.
    #[must_use]
    pub fn atom_link<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::AtomLink, value)
    }

    /// Sets the author.
    #[must_use]
    pub fn author<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Author, value)
    }

    /// Sets the category.
    #[must_use]
    pub fn category<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Category, value)
    }

    /// Sets the copyright.
    #[must_use]
    pub fn copyright<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Copyright, value)
    }

    /// Sets the description.
    #[must_use]
    pub fn description<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Description, value)
    }

    /// Sets the docs link.
    #[must_use]
    pub fn docs<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Docs, value)
    }

    /// Sets the generator.
    #[must_use]
    pub fn generator<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Generator, value)
    }

    /// Sets the GUID.
    #[must_use]
    pub fn guid<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Guid, value)
    }

    /// Sets the image title.
    #[must_use]
    pub fn image_title<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::ImageTitle, value)
    }

    /// Sets the image URL.
    #[must_use]
    pub fn image_url<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::ImageUrl, value)
    }

    /// Sets the image link.
    #[must_use]
    pub fn image_link<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::ImageLink, value)
    }

    /// Sets the language.
    #[must_use]
    pub fn language<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Language, value)
    }

    /// Sets the last build date.
    #[must_use]
    pub fn last_build_date<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::LastBuildDate, value)
    }

    /// Sets the main link.
    #[must_use]
    pub fn link<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Link, value)
    }

    /// Sets the managing editor.
    #[must_use]
    pub fn managing_editor<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::ManagingEditor, value)
    }

    /// Sets the publication date.
    #[must_use]
    pub fn pub_date<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::PubDate, value)
    }

    /// Sets the title.
    #[must_use]
    pub fn title<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Title, value)
    }

    /// Sets the TTL (Time To Live).
    #[must_use]
    pub fn ttl<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Ttl, value)
    }

    /// Sets the webmaster.
    #[must_use]
    pub fn webmaster<T: Into<String>>(self, value: T) -> Self {
        self.set(RssDataField::Webmaster, value)
    }
}

/// Represents the fields of an RSS data structure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RssDataField {
    /// The Atom link of the RSS feed.
    AtomLink,
    /// The author of the RSS feed.
    Author,
    /// The category of the RSS feed.
    Category,
    /// The copyright notice.
    Copyright,
    /// The description of the RSS feed.
    Description,
    /// The docs link of the RSS feed.
    Docs,
    /// The generator of the RSS feed.
    Generator,
    /// The GUID of the RSS feed.
    Guid,
    /// The image title of the RSS feed.
    ImageTitle,
    /// The image URL of the RSS feed.
    ImageUrl,
    /// The image link of the RSS feed.
    ImageLink,
    /// The language of the RSS feed.
    Language,
    /// The last build date of the RSS feed.
    LastBuildDate,
    /// The main link to the RSS feed.
    Link,
    /// The managing editor of the RSS feed.
    ManagingEditor,
    /// The publication date of the RSS feed.
    PubDate,
    /// The title of the RSS feed.
    Title,
    /// Time To Live (TTL), the number of minutes the feed should be cached before refreshing.
    Ttl,
    /// The webmaster of the RSS feed.
    Webmaster,
}

/// Represents an item in the RSS feed.
#[derive(
    Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize,
)]
#[non_exhaustive]
pub struct RssItem {
    /// The GUID of the RSS item (unique identifier).
    pub guid: String,
    /// The category of the RSS item.
    pub category: Option<String>,
    /// The description of the RSS item.
    pub description: String,
    /// The link to the RSS item.
    pub link: String,
    /// The publication date of the RSS item.
    pub pub_date: String,
    /// The title of the RSS item.
    pub title: String,
    /// The author of the RSS item.
    pub author: String,
    /// The comments URL related to the RSS item (optional).
    pub comments: Option<String>,
    /// The enclosure (typically for media like podcasts) (optional).
    pub enclosure: Option<String>,
    /// The source of the RSS item (optional).
    pub source: Option<String>,
    /// The creator of the RSS item (optional).
    pub creator: Option<String>,
    /// The date the RSS item was created (optional).
    pub date: Option<String>,
}

impl RssItem {
    /// Creates a new `RssItem` with default values.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the value of a field and returns the `RssItem` instance for method chaining.
    ///
    /// # Arguments
    ///
    /// * `field` - The field to set.
    /// * `value` - The value to assign to the field.
    ///
    /// # Returns
    ///
    /// The updated `RssItem` instance.
    #[must_use]
    pub fn set<T: Into<String>>(
        mut self,
        field: RssItemField,
        value: T,
    ) -> Self {
        let value = sanitize_input(&value.into());
        match field {
            RssItemField::Guid => self.guid = value,
            RssItemField::Category => self.category = Some(value),
            RssItemField::Description => self.description = value,
            RssItemField::Link => self.link = value,
            RssItemField::PubDate => self.pub_date = value,
            RssItemField::Title => self.title = value,
            RssItemField::Author => self.author = value,
            RssItemField::Comments => self.comments = Some(value),
            RssItemField::Enclosure => self.enclosure = Some(value),
            RssItemField::Source => self.source = Some(value),
        }
        self
    }

    /// Validates the `RssData` to ensure that all required fields are set and valid.
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the `RssData` is valid.
    /// * `Err(RssError)` if any validation errors are found.
    ///
    /// # Errors
    ///
    /// This function returns an `Err(RssError)` in the following cases:
    ///
    /// * `RssError::InvalidInput` if any fields such as `title`, `link`, or `description` are missing or invalid.
    /// * `RssError::ValidationErrors` if there are multiple validation issues found (e.g., invalid link, missing title, etc.).
    /// * `RssError::DateParseError` if the `pub_date` cannot be parsed into a valid date.
    ///
    /// Additionally, it can return an error if any of the custom validation rules are violated (e.g., maximum length for certain fields).
    pub fn validate(&self) -> Result<()> {
        let mut errors = Vec::new();

        if self.title.is_empty() {
            errors.push("Title is missing".to_string());
        }

        if self.link.is_empty() {
            errors.push("Link is missing".to_string());
        } else if let Err(e) = validate_url(&self.link) {
            errors.push(format!("Invalid link: {}", e));
        }

        if self.description.is_empty() {
            errors.push("Description is missing".to_string());
        }

        // Add more field validations as needed...

        if !errors.is_empty() {
            return Err(RssError::ValidationErrors(errors));
        }

        Ok(())
    }

    /// Parses the `pub_date` string into a `DateTime` object.
    ///
    /// # Returns
    ///
    /// * `Ok(DateTime)` if the date is valid and successfully parsed.
    /// * `Err(RssError)` if the date is invalid or cannot be parsed.
    ///
    /// # Errors
    ///
    /// This function returns an `Err(RssError)` if the `pub_date` is invalid or
    /// cannot be parsed into a `DateTime` object.
    pub fn pub_date_parsed(&self) -> Result<DateTime> {
        parse_date(&self.pub_date)
    }

    // Field setter methods

    /// Sets the GUID.
    #[must_use]
    pub fn guid<T: Into<String>>(self, value: T) -> Self {
        self.set(RssItemField::Guid, value)
    }

    /// Sets the category.
    #[must_use]
    pub fn category<T: Into<String>>(self, value: T) -> Self {
        self.set(RssItemField::Category, value)
    }

    /// Sets the description.
    #[must_use]
    pub fn description<T: Into<String>>(self, value: T) -> Self {
        self.set(RssItemField::Description, value)
    }

    /// Sets the link.
    #[must_use]
    pub fn link<T: Into<String>>(self, value: T) -> Self {
        self.set(RssItemField::Link, value)
    }

    /// Sets the publication date.
    #[must_use]
    pub fn pub_date<T: Into<String>>(self, value: T) -> Self {
        self.set(RssItemField::PubDate, value)
    }

    /// Sets the title.
    #[must_use]
    pub fn title<T: Into<String>>(self, value: T) -> Self {
        self.set(RssItemField::Title, value)
    }

    /// Sets the author.
    #[must_use]
    pub fn author<T: Into<String>>(self, value: T) -> Self {
        self.set(RssItemField::Author, value)
    }

    /// Sets the comments URL.
    #[must_use]
    pub fn comments<T: Into<String>>(self, value: T) -> Self {
        self.set(RssItemField::Comments, value)
    }

    /// Sets the enclosure.
    #[must_use]
    pub fn enclosure<T: Into<String>>(self, value: T) -> Self {
        self.set(RssItemField::Enclosure, value)
    }

    /// Sets the source.
    #[must_use]
    pub fn source<T: Into<String>>(self, value: T) -> Self {
        self.set(RssItemField::Source, value)
    }
}

/// Represents the fields of an RSS item.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RssItemField {
    /// The GUID of the RSS item.
    Guid,
    /// The category of the RSS item.
    Category,
    /// The description of the RSS item.
    Description,
    /// The link to the RSS item.
    Link,
    /// The publication date of the RSS item.
    PubDate,
    /// The title of the RSS item.
    Title,
    /// The author of the RSS item.
    Author,
    /// The comments URL related to the RSS item.
    Comments,
    /// The enclosure (typically for media like podcasts).
    Enclosure,
    /// The source of the RSS item.
    Source,
}

/// Validates a URL string.
///
/// # Arguments
///
/// * `url` - A string slice that holds the URL to validate.
///
/// # Returns
///
/// * `Ok(())` if the URL is valid.
/// * `Err(RssError)` if the URL is invalid.
///
/// # Errors
///
/// This function returns an `Err(RssError::InvalidUrl)` if the URL is not valid or
/// if it does not use the `http` or `https` protocol.
pub fn validate_url(url: &str) -> Result<()> {
    let parsed_url = Url::parse(url)
        .map_err(|_| RssError::InvalidUrl(url.to_string()))?;

    if parsed_url.scheme() != "http" && parsed_url.scheme() != "https" {
        return Err(RssError::InvalidUrl(
            "URL must use http or https protocol".to_string(),
        ));
    }

    Ok(())
}

/// Parses a date string into a `DateTime`.
///
/// # Arguments
///
/// * `date_str` - A string slice that holds the date to parse.
///
/// # Returns
///
/// * `Ok(DateTime)` if the date is valid and successfully parsed.
/// * `Err(RssError)` if the date is invalid or cannot be parsed.
///
/// # Errors
///
/// This function returns an `Err(RssError::DateParseError)` if the date cannot
/// be parsed into a valid `DateTime`.
///
/// # Panics
///
/// This function will panic if the "UTC" time zone is invalid, but this is
/// highly unlikely as "UTC" is always valid.
pub fn parse_date(date_str: &str) -> Result<DateTime> {
    if OffsetDateTime::parse(date_str, &Rfc2822).is_ok() {
        return Ok(
            DateTime::new_with_tz("UTC").expect("UTC is always valid")
        );
    }

    if OffsetDateTime::parse(date_str, &Iso8601::DEFAULT).is_ok() {
        return Ok(
            DateTime::new_with_tz("UTC").expect("UTC is always valid")
        );
    }

    // Handle custom parsing logic here...

    Err(RssError::DateParseError(date_str.to_string()))
}

/// Sanitizes input by escaping HTML special characters.
///
/// # Arguments
///
/// * `input` - A string slice containing the input to sanitize.
///
/// # Returns
///
/// A `String` with HTML special characters escaped.
fn sanitize_input(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#x27;")
}

#[cfg(test)]
mod tests {
    use super::*;
    use quick_xml::de::from_str;

    #[derive(Debug, Deserialize, PartialEq)]
    struct Image {
        title: String,
        url: String,
        link: String,
    }

    #[derive(Debug, Deserialize, PartialEq)]
    struct Channel {
        title: String,
        link: String,
        description: String,
        image: Image,
    }

    #[derive(Debug, Deserialize, PartialEq)]
    struct Rss {
        #[serde(rename = "channel")]
        channel: Channel,
    }

    #[test]
    fn test_rss_version() {
        assert_eq!(RssVersion::RSS2_0.as_str(), "2.0");
        assert_eq!(RssVersion::default(), RssVersion::RSS2_0);
        assert_eq!(RssVersion::RSS1_0.to_string(), "1.0");
        assert!(matches!(
            "2.0".parse::<RssVersion>(),
            Ok(RssVersion::RSS2_0)
        ));
        assert!("3.0".parse::<RssVersion>().is_err());
    }

    #[test]
    fn test_rss_data_new() {
        let rss_data = RssData::new(Some(RssVersion::RSS2_0));
        assert_eq!(rss_data.version, RssVersion::RSS2_0);
    }

    #[test]
    fn test_rss_data_setters() {
        let rss_data = RssData::new(None)
            .title("Test Feed")
            .link("https://example.com")
            .description("A test feed")
            .generator("RSS Gen")
            .guid("unique-guid")
            .pub_date("2024-03-21T12:00:00Z")
            .language("en");

        assert_eq!(rss_data.title, "Test Feed");
        assert_eq!(rss_data.link, "https://example.com");
        assert_eq!(rss_data.description, "A test feed");
        assert_eq!(rss_data.generator, "RSS Gen");
        assert_eq!(rss_data.guid, "unique-guid");
        assert_eq!(rss_data.pub_date, "2024-03-21T12:00:00Z");
        assert_eq!(rss_data.language, "en");
    }

    #[test]
    fn test_rss_data_validate() {
        let valid_rss_data = RssData::new(None)
            .title("Valid Feed")
            .link("https://example.com")
            .description("A valid RSS feed");

        assert!(valid_rss_data.validate().is_ok());

        let invalid_rss_data = RssData::new(None)
            .title("Invalid Feed")
            .link("not a valid url")
            .description("An invalid RSS feed");

        let result = invalid_rss_data.validate();
        assert!(result.is_err());
        if let Err(RssError::ValidationErrors(errors)) = result {
            assert!(errors.iter().any(|e| e.contains("Invalid link")),
                "Expected an error containing 'Invalid link', but got: {:?}", errors);
        } else {
            panic!("Expected ValidationErrors");
        }
    }

    #[test]
    fn test_add_item() {
        let mut rss_data = RssData::new(None)
            .title("Test RSS Feed")
            .link("https://example.com")
            .description("A test RSS feed");

        let item = RssItem::new()
            .title("Test Item")
            .link("https://example.com/item")
            .description("A test item")
            .guid("unique-id-1")
            .pub_date("2024-03-21");

        rss_data.add_item(item);

        assert_eq!(rss_data.items.len(), 1);
        assert_eq!(rss_data.items[0].title, "Test Item");
        assert_eq!(rss_data.items[0].link, "https://example.com/item");
        assert_eq!(rss_data.items[0].description, "A test item");
        assert_eq!(rss_data.items[0].guid, "unique-id-1");
        assert_eq!(rss_data.items[0].pub_date, "2024-03-21");
    }

    #[test]
    fn test_remove_item() {
        let mut rss_data = RssData::new(None)
            .title("Test RSS Feed")
            .link("https://example.com")
            .description("A test RSS feed");

        let item1 = RssItem::new()
            .title("Item 1")
            .link("https://example.com/item1")
            .description("First item")
            .guid("guid1");

        let item2 = RssItem::new()
            .title("Item 2")
            .link("https://example.com/item2")
            .description("Second item")
            .guid("guid2");

        rss_data.add_item(item1);
        rss_data.add_item(item2);

        assert_eq!(rss_data.item_count(), 2);

        assert!(rss_data.remove_item("guid1"));
        assert_eq!(rss_data.item_count(), 1);
        assert_eq!(rss_data.items[0].title, "Item 2");

        assert!(!rss_data.remove_item("non-existent-guid"));
        assert_eq!(rss_data.item_count(), 1);
    }

    #[test]
    fn test_clear_items() {
        let mut rss_data = RssData::new(None)
            .title("Test RSS Feed")
            .link("https://example.com")
            .description("A test RSS feed");

        rss_data.add_item(RssItem::new().title("Item 1").guid("guid1"));
        rss_data.add_item(RssItem::new().title("Item 2").guid("guid2"));

        assert_eq!(rss_data.item_count(), 2);

        rss_data.clear_items();

        assert_eq!(rss_data.item_count(), 0);
    }

    #[test]
    fn test_rss_item_validate() {
        let valid_item = RssItem::new()
            .title("Valid Item")
            .link("https://example.com/valid")
            .description("A valid item")
            .guid("valid-guid");

        assert!(valid_item.validate().is_ok());

        let invalid_item = RssItem::new()
            .title("Invalid Item")
            .description("An invalid item");

        let result = invalid_item.validate();
        assert!(result.is_err());

        if let Err(RssError::ValidationErrors(errors)) = result {
            assert_eq!(errors.len(), 1); // Adjust to expect 1 error if only one is returned
            assert!(errors.contains(&"Link is missing".to_string())); // Adjust to the actual error returned
        } else {
            panic!("Expected ValidationErrors");
        }
    }

    #[test]
    fn test_validate_url() {
        assert!(validate_url("https://example.com").is_ok());
        assert!(validate_url("not a url").is_err());
    }

    #[test]
    fn test_parse_date() {
        assert!(parse_date("Mon, 01 Jan 2024 00:00:00 GMT").is_ok());
        assert!(parse_date("2024-03-21T12:00:00Z").is_ok());
        assert!(parse_date("invalid date").is_err());
    }

    #[test]
    fn test_sanitize_input() {
        let input = "Test <script>alert('XSS')</script>";
        let sanitized = sanitize_input(input);
        assert_eq!(
            sanitized,
            "Test &lt;script&gt;alert(&#x27;XSS&#x27;)&lt;/script&gt;"
        );
    }

    #[test]
    fn test_rss_data_set_with_enum() {
        let rss_data = RssData::new(None)
            .set(RssDataField::Title, "Test Title")
            .set(RssDataField::Link, "https://example.com")
            .set(RssDataField::Description, "Test Description");

        assert_eq!(rss_data.title, "Test Title");
        assert_eq!(rss_data.link, "https://example.com");
        assert_eq!(rss_data.description, "Test Description");
    }

    #[test]
    fn test_rss_item_set_with_enum() {
        let item = RssItem::new()
            .set(RssItemField::Title, "Test Item")
            .set(RssItemField::Link, "https://example.com/item")
            .set(RssItemField::Guid, "unique-id");

        assert_eq!(item.title, "Test Item");
        assert_eq!(item.link, "https://example.com/item");
        assert_eq!(item.guid, "unique-id");
    }

    #[test]
    fn test_to_hash_map() {
        let rss_data = RssData::new(None)
            .title("Test Title")
            .link("https://example.com/rss")
            .description("A test RSS feed")
            .atom_link("https://example.com/atom")
            .language("en")
            .managing_editor("[email protected]")
            .webmaster("[email protected]")
            .last_build_date("2024-03-21T12:00:00Z")
            .pub_date("2024-03-21T12:00:00Z")
            .ttl("60")
            .generator("RSS Gen")
            .guid("unique-guid")
            .image_title("Image Title".to_string())
            .docs("https://docs.example.com");

        let map = rss_data.to_hash_map();

        assert_eq!(map.get("title").unwrap(), "Test Title");
        assert_eq!(map.get("link").unwrap(), "https://example.com/rss");
        assert_eq!(
            map.get("atom_link").unwrap(),
            "https://example.com/atom"
        );
        assert_eq!(map.get("language").unwrap(), "en");
        assert_eq!(
            map.get("managing_editor").unwrap(),
            "[email protected]"
        );
        assert_eq!(
            map.get("webmaster").unwrap(),
            "[email protected]"
        );
        assert_eq!(
            map.get("last_build_date").unwrap(),
            "2024-03-21T12:00:00Z"
        );
        assert_eq!(
            map.get("pub_date").unwrap(),
            "2024-03-21T12:00:00Z"
        );
        assert_eq!(map.get("ttl").unwrap(), "60");
        assert_eq!(map.get("generator").unwrap(), "RSS Gen");
        assert_eq!(map.get("guid").unwrap(), "unique-guid");
        assert_eq!(map.get("image_title").unwrap(), "Image Title");
        assert_eq!(
            map.get("docs").unwrap(),
            "https://docs.example.com"
        );
    }

    #[test]
    fn test_set_image() {
        let mut rss_data = RssData::new(None);
        rss_data.set_image(
            "Test Image Title",
            "https://example.com/image.jpg",
            "https://example.com",
        );
        rss_data.title = "RSS Feed Title".to_string();

        assert_eq!(rss_data.image_title, "Test Image Title");
        assert_eq!(rss_data.image_url, "https://example.com/image.jpg");
        assert_eq!(rss_data.image_link, "https://example.com");
        assert_eq!(rss_data.title, "RSS Feed Title");
    }

    #[test]
    fn test_rss_feed_parsing() {
        let rss_xml = r#"
        <?xml version="1.0" encoding="UTF-8"?>
        <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"
             xmlns:dc="http://purl.org/dc/elements/1.1/"
             xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
             xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/">
          <channel>
            <title>GETS Open Tenders or Quotes</title>
            <link>https://www.gets.govt.nz//ExternalIndex.htm</link>
            <description>This feed lists the current open tenders or requests for quote listed on the GETS.</description>
            <image>
              <title>Open tenders or Requests for Quote from GETS</title>
              <url>https://www.gets.govt.nz//ext/default/img/getsLogo.jpg</url>
              <link>https://www.gets.govt.nz//ExternalIndex.htm</link>
            </image>
          </channel>
        </rss>
        "#;

        let parsed: Rss =
            from_str(rss_xml).expect("Failed to parse RSS XML");

        assert_eq!(parsed.channel.title, "GETS Open Tenders or Quotes");
        assert_eq!(
            parsed.channel.link,
            "https://www.gets.govt.nz//ExternalIndex.htm"
        );
        assert_eq!(parsed.channel.description, "This feed lists the current open tenders or requests for quote listed on the GETS.");
        assert_eq!(
            parsed.channel.image.title,
            "Open tenders or Requests for Quote from GETS"
        );
        assert_eq!(
            parsed.channel.image.url,
            "https://www.gets.govt.nz//ext/default/img/getsLogo.jpg"
        );
        assert_eq!(
            parsed.channel.image.link,
            "https://www.gets.govt.nz//ExternalIndex.htm"
        );
    }

    #[test]
    fn test_rss_version_from_str() {
        assert_eq!(
            RssVersion::from_str("0.90").unwrap(),
            RssVersion::RSS0_90
        );
        assert_eq!(
            RssVersion::from_str("0.91").unwrap(),
            RssVersion::RSS0_91
        );
        assert_eq!(
            RssVersion::from_str("0.92").unwrap(),
            RssVersion::RSS0_92
        );
        assert_eq!(
            RssVersion::from_str("1.0").unwrap(),
            RssVersion::RSS1_0
        );
        assert_eq!(
            RssVersion::from_str("2.0").unwrap(),
            RssVersion::RSS2_0
        );
        assert!(RssVersion::from_str("3.0").is_err());
    }

    #[test]
    fn test_rss_version_display() {
        assert_eq!(format!("{}", RssVersion::RSS0_90), "0.90");
        assert_eq!(format!("{}", RssVersion::RSS0_91), "0.91");
        assert_eq!(format!("{}", RssVersion::RSS0_92), "0.92");
        assert_eq!(format!("{}", RssVersion::RSS1_0), "1.0");
        assert_eq!(format!("{}", RssVersion::RSS2_0), "2.0");
    }

    #[test]
    fn test_rss_data_set_methods() {
        let rss_data = RssData::new(None)
            .atom_link("https://example.com/atom")
            .author("John Doe")
            .category("Technology")
            .copyright("© 2024 Example Inc.")
            .description("A sample RSS feed")
            .docs("https://example.com/rss-docs")
            .generator("RSS Gen v1.0")
            .guid("unique-guid-123")
            .image_title("Feed Image")
            .image_url("https://example.com/image.jpg")
            .image_link("https://example.com")
            .language("en-US")
            .last_build_date("2024-03-21T12:00:00Z")
            .link("https://example.com")
            .managing_editor("[email protected]")
            .pub_date("2024-03-21T00:00:00Z")
            .title("Sample Feed")
            .ttl("60")
            .webmaster("[email protected]");

        assert_eq!(rss_data.atom_link, "https://example.com/atom");
        assert_eq!(rss_data.author, "John Doe");
        assert_eq!(rss_data.category, "Technology");
        assert_eq!(rss_data.copyright, "© 2024 Example Inc.");
        assert_eq!(rss_data.description, "A sample RSS feed");
        assert_eq!(rss_data.docs, "https://example.com/rss-docs");
        assert_eq!(rss_data.generator, "RSS Gen v1.0");
        assert_eq!(rss_data.guid, "unique-guid-123");
        assert_eq!(rss_data.image_title, "Feed Image");
        assert_eq!(rss_data.image_url, "https://example.com/image.jpg");
        assert_eq!(rss_data.image_link, "https://example.com");
        assert_eq!(rss_data.language, "en-US");
        assert_eq!(rss_data.last_build_date, "2024-03-21T12:00:00Z");
        assert_eq!(rss_data.link, "https://example.com");
        assert_eq!(rss_data.managing_editor, "[email protected]");
        assert_eq!(rss_data.pub_date, "2024-03-21T00:00:00Z");
        assert_eq!(rss_data.title, "Sample Feed");
        assert_eq!(rss_data.ttl, "60");
        assert_eq!(rss_data.webmaster, "[email protected]");
    }

    #[test]
    fn test_rss_data_empty() {
        let rss_data = RssData::new(None);
        assert!(rss_data.title.is_empty());
        assert!(rss_data.link.is_empty());
        assert!(rss_data.description.is_empty());
        assert_eq!(rss_data.items.len(), 0);
    }

    #[test]
    fn test_rss_item_empty() {
        let item = RssItem::new();
        assert!(item.title.is_empty());
        assert!(item.link.is_empty());
        assert!(item.guid.is_empty());
        assert!(item.description.is_empty());
    }

    #[test]
    fn test_rss_data_to_hash_map() {
        let rss_data = RssData::new(None)
            .title("Test Feed")
            .link("https://example.com")
            .description("A test feed");

        let hash_map = rss_data.to_hash_map();
        assert_eq!(hash_map.get("title").unwrap(), "Test Feed");
        assert_eq!(
            hash_map.get("link").unwrap(),
            "https://example.com"
        );
        assert_eq!(hash_map.get("description").unwrap(), "A test feed");
    }

    #[test]
    fn test_rss_data_version_setter() {
        let rss_data = RssData::new(None).version(RssVersion::RSS1_0);
        assert_eq!(rss_data.version, RssVersion::RSS1_0);
    }

    #[test]
    fn test_remove_item_not_found() {
        let mut rss_data = RssData::new(None);
        let item = RssItem::new().guid("existing-guid");
        rss_data.add_item(item);

        // Try removing an item with a non-existent GUID
        let removed = rss_data.remove_item("non-existent-guid");
        assert!(!removed);
        assert_eq!(rss_data.items.len(), 1);
    }

    #[test]
    fn test_set_item_field_empty_items() {
        let mut rss_data = RssData::new(None);
        rss_data.set_item_field(RssItemField::Title, "Test Item Title");

        assert_eq!(rss_data.items.len(), 1);
        assert_eq!(rss_data.items[0].title, "Test Item Title");
    }

    #[test]
    fn test_set_image_empty() {
        let mut rss_data = RssData::new(None);
        rss_data.set_image("", "", "");

        assert!(rss_data.image_title.is_empty());
        assert!(rss_data.image_url.is_empty());
        assert!(rss_data.image_link.is_empty());
    }

    #[test]
    fn test_rss_item_set_empty_field() {
        let item = RssItem::new().set(RssItemField::Title, "");
        assert!(item.title.is_empty());
    }
}