icann-rdap-common 0.0.29

Common RDAP data structures.
Documentation
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
//! Common data structures, etc...
use std::{collections::HashSet, ops::DerefMut};

use serde::{Deserialize, Serialize};

use crate::prelude::ContentExtensions;

use super::lenient::{Stringish, VectorStringish};

/// Represents an RDAP extension identifier.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Extension(pub String);

impl From<&str> for Extension {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

impl std::ops::Deref for Extension {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// The RDAP conformance array.
///
/// This is a vec of [Extension] specifically to be able to handle one or more
/// unknown extension ids. Known extension identifiers are enumerated by [crate::prelude::ExtensionId].
pub type RdapConformance = Vec<Extension>;

/// HrefLang, either a string or an array of strings.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(untagged)]
pub enum HrefLang {
    Langs(Vec<String>),
    Lang(String),
}

/// An array of RDAP link structures.
pub type Links = Vec<Link>;

/// Represents and RDAP link structure.
///
/// This structure allows `value`, `rel`, and `href` to be
/// optional to be tolerant of misbehaving servers,
/// but those are fields required by RFC 9083.
///
/// To create an RFC valid structure, use the builder
/// which will not allow omission of required fields.
///
/// ```rust
/// use icann_rdap_common::prelude::*;
///
/// let link = Link::builder()
///   .value("https://example.com/domains?domain=foo.*")
///   .rel("related")
///   .href("https://example.com/domain/foo.example")
///   .hreflang("ch")
///   .title("Related Object")
///   .media("print")
///   .media_type("application/rdap+json")
///   .build();
/// ```
///
/// Note also that this structure allows for `hreflang` to
/// be either a single string or an array of strings. However,
/// the builder will always construct an array of strings.
///
/// Use the getter functions to get the data.
/// ```rust
/// # use icann_rdap_common::prelude::*;
/// # let link = Link::builder()
/// #  .value("https://example.com/domains?domain=foo.*")
/// #  .rel("related")
/// #  .href("https://example.com/domain/foo.example")
/// #  .hreflang("ch")
/// #  .title("Related Object")
/// #  .media("print")
/// #  .media_type("application/rdap+json")
/// #  .build();
/// let href = link.href();
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Link {
    /// Represents the value part of a link in an RDAP response.
    /// According to RFC 9083, this field is required
    /// but many servers do not return it as it was
    /// optional in RFC 7483.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,

    /// Represents the relationship of a link in an RDAP response.
    /// According to RFC 9083, this field is required
    /// but many servers do not return it as it was
    /// optional in RFC 7483.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rel: Option<String>,

    /// This is required by RDAP, both RFC 7043 and 9083,
    /// but is optional because some servers do the wrong thing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub href: Option<String>,

    /// This can either be a string or an array of strings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hreflang: Option<HrefLang>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub media: Option<String>,

    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_type: Option<String>,
}

#[buildstructor::buildstructor]
impl Link {
    /// True if the link `rel` property is equal to the given value.
    pub fn is_relation(&self, rel: &str) -> bool {
        let Some(link_rel) = &self.rel else {
            return false;
        };
        link_rel == rel
    }

    /// Builds an RDAP link.
    ///
    /// To create an RFC valid structure, use the builder
    /// which will not allow omission of required fields.
    ///
    /// ```rust
    /// use icann_rdap_common::prelude::*;
    ///
    /// let link = Link::builder()
    ///   .value("https://example.com/domains?domain=foo.*") //required
    ///   .rel("related")                                    //required
    ///   .href("https://example.com/domain/foo.example")    //required
    ///   .hreflang("ch")
    ///   .title("Related Object")
    ///   .media("print")
    ///   .media_type("application/rdap+json")
    ///   .build();
    /// ```
    #[builder(visibility = "pub")]
    fn new(
        value: String,
        href: String,
        rel: String,
        hreflang: Option<String>,
        title: Option<String>,
        media: Option<String>,
        media_type: Option<String>,
    ) -> Self {
        let hreflang = hreflang.map(HrefLang::Lang);
        Self {
            value: Some(value),
            rel: Some(rel),
            href: Some(href),
            hreflang,
            title,
            media,
            media_type,
        }
    }

    /// Builds a potentially illegal RDAP link.
    #[builder(entry = "illegal", visibility = "pub(crate)")]
    #[allow(dead_code)]
    fn new_illegal(
        value: Option<String>,
        href: Option<String>,
        rel: Option<String>,
        hreflang: Option<String>,
        title: Option<String>,
        media: Option<String>,
        media_type: Option<String>,
    ) -> Self {
        let hreflang = hreflang.map(HrefLang::Lang);
        Self {
            value,
            rel,
            href,
            hreflang,
            title,
            media,
            media_type,
        }
    }

    /// Returns the value of the link.
    pub fn value(&self) -> Option<&str> {
        self.value.as_deref()
    }

    /// Returns the relationship of the link.
    pub fn rel(&self) -> Option<&str> {
        self.rel.as_deref()
    }

    /// Returns the target URL of the link.
    pub fn href(&self) -> Option<&str> {
        self.href.as_deref()
    }

    /// Returns the language(s) of the linked resource.
    pub fn hreflang(&self) -> Option<&HrefLang> {
        self.hreflang.as_ref()
    }

    /// Returns the title of the link.
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Returns the media type for which the link is designed.
    pub fn media(&self) -> Option<&str> {
        self.media.as_deref()
    }

    /// Returns the media type of the linked resource.
    pub fn media_type(&self) -> Option<&str> {
        self.media_type.as_deref()
    }
}

/// An array of notices.
pub type Notices = Vec<Notice>;

/// Represents an RDAP Notice.
///
/// It is recommended to use builder to construct an RFC valid
/// structure.
///
/// ```rust
/// use icann_rdap_common::prelude::*;
///
/// let link = Link::builder()
///   .value("https://example.com/domains/foo.example")
///   .rel("about")
///   .href("https://example.com/tou.html")
///   .hreflang("en")
///   .title("ToU Link")
///   .media_type("text/html")
///   .build();
///
/// let notice = Notice::builder()
///   .title("Terms of Use")
///   .description_entry("Please read our terms of use.")
///   .description_entry("TOS can be found in the link.")
///   .link(link)
///   .build();
/// ```
///
/// Use the getter functions to get the data.
/// ```rust
/// # use icann_rdap_common::prelude::*;
/// # let notice = Notice::builder()
/// #  .title("Terms of Use")
/// #  .description_entry("Please read our terms of use.")
/// #  .description_entry("TOS can be found in the link.")
/// #  .build();
/// let title = notice.title();
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Notice(pub NoticeOrRemark);

#[buildstructor::buildstructor]
impl Notice {
    /// Builds an RDAP notice.
    #[builder(visibility = "pub")]
    fn new(
        title: Option<String>,
        description: Vec<String>,
        links: Vec<Link>,
        nr_type: Option<String>,
        simple_redaction_keys: Option<Vec<String>>,
    ) -> Self {
        let nr = NoticeOrRemark::builder()
            .description(description)
            .and_title(title)
            .links(links)
            .and_nr_type(nr_type)
            .and_simple_redaction_keys(simple_redaction_keys)
            .build();
        Self(nr)
    }
}

impl std::ops::Deref for Notice {
    type Target = NoticeOrRemark;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl ContentExtensions for Notice {
    fn content_extensions(&self) -> HashSet<super::ExtensionId> {
        self.0.content_extensions()
    }
}

/// An array of remarks.
pub type Remarks = Vec<Remark>;

/// Represents an RDAP Remark.
///
/// It is recommended to use builder to construct an RFC valid
/// structure.
///
/// ```rust
/// use icann_rdap_common::prelude::*;
///
/// let link = Link::builder()
///   .value("https://example.com/domains/foo.example")
///   .rel("about")
///   .href("https://example.com/tou.html")
///   .hreflang("en")
///   .title("ToU Link")
///   .media_type("text/html")
///   .build();
///
/// let remark = Remark::builder()
///   .title("Terms of Use")
///   .description_entry("Please read our terms of use.")
///   .description_entry("TOS can be found in the link.")
///   .link(link)
///   .build();
/// ```
///
/// Use the getter functions to get the data.
/// ```rust
/// # use icann_rdap_common::prelude::*;
/// # let remark = Remark::builder()
/// #  .title("Terms of Use")
/// #  .description_entry("Please read our terms of use.")
/// #  .description_entry("TOS can be found in the link.")
/// #  .build();
/// let title = remark.title();
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Remark(pub NoticeOrRemark);

impl DerefMut for Remark {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[buildstructor::buildstructor]
impl Remark {
    /// Builds an RDAP notice.
    #[builder(visibility = "pub")]
    fn new(
        title: Option<String>,
        description: Vec<String>,
        links: Vec<Link>,
        nr_type: Option<String>,
        simple_redaction_keys: Option<Vec<String>>,
    ) -> Self {
        let nr = NoticeOrRemark::builder()
            .description(description)
            .and_title(title)
            .links(links)
            .and_nr_type(nr_type)
            .and_simple_redaction_keys(simple_redaction_keys)
            .build();
        Self(nr)
    }
}

impl std::ops::Deref for Remark {
    type Target = NoticeOrRemark;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl ContentExtensions for Remark {
    fn content_extensions(&self) -> HashSet<super::ExtensionId> {
        self.0.content_extensions()
    }
}

/// Represents an RDAP Notice or Remark (they are the same thing in RDAP).
///
/// It is probably easier to use [Notice] or [Remark] directly.
///
/// RFC 9083 requires that `description` be required, but some servers
/// do not follow this rule. Therefore, this structure allows `description`
/// to be optional. It is recommended to use builder to construct an RFC valid
/// structure.
///
/// ```rust
/// use icann_rdap_common::prelude::*;
///
/// let link = Link::builder()
///   .value("https://example.com/domains/foo.example")
///   .rel("about")
///   .href("https://example.com/tou.html")
///   .hreflang("en")
///   .title("ToU Link")
///   .media_type("text/html")
///   .build();
///
/// let nr = NoticeOrRemark::builder()
///   .title("Terms of Use")
///   .description_entry("Please read our terms of use.")
///   .description_entry("TOS can be found in the link.")
///   .links(vec![link])
///   .build();
/// ```
///
/// Use the getter functions to get the data.
/// ```rust
/// # use icann_rdap_common::prelude::*;
/// # let nr = NoticeOrRemark::builder()
/// #  .title("Terms of Use")
/// #  .description_entry("Please read our terms of use.")
/// #  .description_entry("TOS can be found in the link.")
/// #  .build();
/// let title = nr.title();
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct NoticeOrRemark {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<VectorStringish>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Links>,

    /// Description `type` as is found in the IANA registry.
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nr_type: Option<String>,

    /// Redaction key from the simple redaction extension.
    #[serde(rename = "simpleRedaction_keys")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub simple_redaction_keys: Option<Vec<String>>,
}

#[buildstructor::buildstructor]
impl NoticeOrRemark {
    /// Builds an RDAP notice/remark.
    #[builder(visibility = "pub")]
    fn new(
        title: Option<String>,
        description: Vec<String>,
        links: Vec<Link>,
        nr_type: Option<String>,
        simple_redaction_keys: Option<Vec<String>>,
    ) -> Self {
        Self {
            title,
            description: Some(VectorStringish::from(description)),
            links: (!links.is_empty()).then_some(links),
            nr_type,
            simple_redaction_keys,
        }
    }

    /// Builds an illegal RDAP notice/remark.
    #[builder(entry = "illegal", visibility = "pub(crate)")]
    #[allow(dead_code)]
    fn new_illegal(
        title: Option<String>,
        description: Option<Vec<String>>,
        links: Option<Vec<Link>>,
        nr_type: Option<String>,
        simple_redaction_keys: Option<Vec<String>>,
    ) -> Self {
        let d = description
            .is_some()
            .then_some(VectorStringish::from(description.unwrap()));
        Self {
            title,
            description: d,
            links,
            nr_type,
            simple_redaction_keys,
        }
    }

    /// Returns the title of the notice/remark.
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Returns the description of the notice/remark.
    pub fn description(&self) -> &[String] {
        self.description
            .as_ref()
            .map(|v| v.vec().as_ref())
            .unwrap_or_default()
    }

    /// Returns the description where lines that are
    /// not sentences are consolidated into paragraphs.
    pub fn description_as_pgs(&self) -> Vec<String> {
        let mut pgs = vec![];
        let mut acc_line = String::new();
        for line in self.description() {
            acc_line.push_str(line.trim());
            if acc_line.ends_with('.') || acc_line.to_ascii_uppercase().eq(&acc_line) {
                pgs.push(acc_line);
                acc_line = String::new();
            } else {
                acc_line.push(' ');
            }
        }
        if !acc_line.is_empty() {
            pgs.push(acc_line);
        }
        pgs
    }

    /// Returns the links associated with the notice/remark.
    pub fn links(&self) -> &[Link] {
        self.links.as_deref().unwrap_or_default()
    }

    /// Returns the `type` of the notice or remark.
    ///
    /// These values are suppose to come from the IANA RDAP registry.
    pub fn nr_type(&self) -> Option<&str> {
        self.nr_type.as_deref()
    }

    /// Returns the simple redactions keys.
    pub fn simple_redaction_keys(&self) -> &[String] {
        self.simple_redaction_keys.as_deref().unwrap_or_default()
    }

    /// Returns true if a key is a simple redaction key for this notice or remark.
    pub fn has_simple_redaction_key(&self, key: &str) -> bool {
        self.simple_redaction_keys().iter().any(|k| k.eq(key))
    }
}

/// Conversion for collection of notices.
pub trait ToNotices {
    /// Convert to a collection of notices.
    fn to_notices(self) -> Vec<Notice>;
    /// Convert to a collection if some; otherwise, none.
    fn to_opt_notices(self) -> Option<Vec<Notice>>;
}

impl ToNotices for &[NoticeOrRemark] {
    fn to_notices(self) -> Vec<Notice> {
        self.iter().map(|n| Notice(n.clone())).collect::<Notices>()
    }

    fn to_opt_notices(self) -> Option<Vec<Notice>> {
        let notices = self.to_notices();
        (!notices.is_empty()).then_some(notices)
    }
}

impl ToNotices for Vec<NoticeOrRemark> {
    fn to_notices(self) -> Vec<Notice> {
        self.into_iter().map(Notice).collect::<Notices>()
    }

    fn to_opt_notices(self) -> Option<Vec<Notice>> {
        let notices = self.to_notices();
        (!notices.is_empty()).then_some(notices)
    }
}

/// Conversion for collection of remarks.
pub trait ToRemarks {
    /// Convert to a collection of remarks.
    fn to_remarks(self) -> Vec<Remark>;
    /// Convert to a collection if some; otherwise, none.
    fn to_opt_remarks(self) -> Option<Vec<Remark>>;
}

impl ToRemarks for &[NoticeOrRemark] {
    fn to_remarks(self) -> Vec<Remark> {
        self.iter().map(|n| Remark(n.clone())).collect::<Remarks>()
    }

    fn to_opt_remarks(self) -> Option<Vec<Remark>> {
        let remarks = self.to_remarks();
        (!remarks.is_empty()).then_some(remarks)
    }
}

impl ToRemarks for Vec<NoticeOrRemark> {
    fn to_remarks(self) -> Vec<Remark> {
        self.into_iter().map(Remark).collect::<Remarks>()
    }

    fn to_opt_remarks(self) -> Option<Vec<Remark>> {
        let remarks = self.to_remarks();
        (!remarks.is_empty()).then_some(remarks)
    }
}

impl ContentExtensions for NoticeOrRemark {
    fn content_extensions(&self) -> std::collections::HashSet<super::ExtensionId> {
        if self.simple_redaction_keys.is_some() {
            HashSet::from([super::ExtensionId::SimpleRedaction])
        } else {
            HashSet::new()
        }
    }
}

/// An array of events.
pub type Events = Vec<Event>;

/// Represents an RDAP event.
///
/// RFC 9083 requires `eventAction` (event_action) and `eventDate` (event_date), but
/// this structure allows those to be optional to be able to parse responses from
/// servers that do not strictly obey the RFC.
///
/// Use of the builder to construct an RFC valid structure is recommended.
///
/// ```rust
/// use icann_rdap_common::prelude::*;
///
/// let link = Link::builder()
///   .value("https://example.com/domains/foo.example")
///   .rel("about")
///   .href("https://example.com/registration-duration.html")
///   .hreflang("en")
///   .title("Domain Validity Period")
///   .media_type("text/html")
///   .build();
///
/// let event = Event::builder()
///   .event_action("expiration")
///   .event_date("1990-12-31T23:59:59Z")
///   .links(vec![link])
///   .build();
/// ```
///
/// NOTE: `event_date` is to be an RFC 3339 valid date and time.
/// The builder does not enforce RFC 3339 validity.
///
/// Use the getter functions to get the data.
/// ```rust
/// # use icann_rdap_common::prelude::*;
/// # let event = Event::builder()
/// #   .event_action("expiration")
/// #  .event_date("1990-12-31T23:59:59Z")
/// #  .build();
/// let event_date = event.event_date();
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Event {
    /// This value is required by RFC 9083 (and 7483),
    /// however some servers don't include it. Therefore
    /// it is optional here to be compatible with these
    /// types of non-compliant servers.
    #[serde(rename = "eventAction")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_action: Option<String>,

    #[serde(rename = "eventActor")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_actor: Option<String>,

    /// This value is required by RFC 9083 (and 7483),
    /// however some servers don't include it. Therefore
    /// it is optional here to be compatible with these
    /// types of non-compliant servers.
    #[serde(rename = "eventDate")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_date: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Links>,
}

#[buildstructor::buildstructor]
impl Event {
    /// Builds an Event.
    ///
    /// Use of the builder to construct an RFC valid structure is recommended.
    ///
    /// ```rust
    /// use icann_rdap_common::prelude::*;
    ///
    /// let event = Event::builder()
    ///   .event_action("expiration")         //required
    ///   .event_date("1990-12-31T23:59:59Z") //required
    ///   .event_actor("FOO")
    ///   .build();
    /// ```
    #[builder(visibility = "pub")]
    fn new(
        event_action: String,
        event_date: String,
        event_actor: Option<String>,
        links: Option<Links>,
    ) -> Self {
        Self {
            event_action: Some(event_action),
            event_actor,
            event_date: Some(event_date),
            links,
        }
    }

    #[builder(entry = "illegal", visibility = "pub(crate)")]
    #[allow(dead_code)]
    fn new_illegal(
        event_action: Option<String>,
        event_date: Option<String>,
        event_actor: Option<String>,
        links: Option<Links>,
    ) -> Self {
        Self {
            event_action,
            event_actor,
            event_date,
            links,
        }
    }

    /// Returns the action associated with the event.
    pub fn event_action(&self) -> Option<&str> {
        self.event_action.as_deref()
    }

    /// Returns the actor associated with the event.
    pub fn event_actor(&self) -> Option<&str> {
        self.event_actor.as_deref()
    }

    /// Returns the date and time of the event.
    pub fn event_date(&self) -> Option<&str> {
        self.event_date.as_deref()
    }

    /// Returns the links associated with the event.
    pub fn links(&self) -> &[Link] {
        self.links.as_deref().unwrap_or_default()
    }
}

/// An RDAP port53 type.
pub type Port43 = String;

/// An array of RDAP public IDs.
pub type PublicIds = Vec<PublicId>;

/// An RDAP Public ID.
///
/// RFC 9083 requires `type` (id_type) and `identifier`, but
/// this structure allows those to be optional to be able to parse responses from
/// servers that do not strictly obey the RFC.
///
/// Use of the builder to construct an RFC valid structure is recommended.
///
/// ```rust
/// use icann_rdap_common::prelude::*;
///
/// let public_id = PublicId::builder()
///   .id_type("IANA Registrar ID")
///   .identifier("1990")
///   .build();
/// ```
///
/// Use the getter functions to get the data.
/// ```rust
/// # use icann_rdap_common::prelude::*;
/// # let public_id = PublicId::builder()
/// #   .id_type("IANA Registrar ID")
/// #   .identifier("1990")
/// #   .build();
/// let id_type = public_id.id_type();
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct PublicId {
    /// This are mandatory per RFC 9083.
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id_type: Option<Stringish>,

    /// This are mandatory per RFC 9083.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identifier: Option<Stringish>,
}

#[buildstructor::buildstructor]
impl PublicId {
    /// Builds a public ID.
    #[builder(visibility = "pub")]
    fn new(id_type: String, identifier: String) -> Self {
        Self {
            id_type: Some(id_type.into()),
            identifier: Some(identifier.into()),
        }
    }

    /// Builds an illegal public ID.
    #[builder(entry = "illegal", visibility = "pub(crate)")]
    #[allow(dead_code)]
    fn new_illegal(id_type: Option<String>, identifier: Option<String>) -> Self {
        Self {
            id_type: id_type.map(|s| s.into()),
            identifier: identifier.map(|s| s.into()),
        }
    }

    /// Returns the type of the public ID.
    pub fn id_type(&self) -> Option<&str> {
        self.id_type.as_deref()
    }

    /// Returns the identifier of the public ID.
    pub fn identifier(&self) -> Option<&str> {
        self.identifier.as_deref()
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        prelude::ObjectCommon,
        response::types::{Extension, Notice, Notices, RdapConformance, Remark, Remarks},
    };

    use super::{Event, Link, Links, NoticeOrRemark, PublicId};

    #[test]
    fn test_rdap_conformance_serialize() {
        // GIVEN rdap conformance
        let rdap_conformance: RdapConformance =
            vec![Extension("foo".to_string()), Extension("bar".to_string())];

        // WHEN serialized
        let actual = serde_json::to_string(&rdap_conformance).unwrap();

        // THEN expect array of strings
        let expected = r#"["foo","bar"]"#;
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_an_array_of_links_deserialize() {
        // GIVEN array of links
        let expected = r#"
        [
            {
                "value" : "https://1.example.com/context_uri",
                "rel" : "self",
                "href" : "https://1.example.com/target_uri",
                "hreflang" : [ "en", "ch" ],
                "title" : "title1",
                "media" : "screen",
                "type" : "application/json"
            },
            {
                "value" : "https://2.example.com/context_uri",
                "rel" : "self",
                "href" : "https://2.example.com/target_uri",
                "hreflang" : [ "en", "ch" ],
                "title" : "title2",
                "media" : "screen",
                "type" : "application/json"
            }
        ]   
        "#;

        // WHEN deserialize
        let links = serde_json::from_str::<Links>(expected);

        // THEN data is correct
        let actual = links.unwrap();
        assert_eq!(actual.len(), 2);
        let actual_1 = actual.first().unwrap();
        let actual_2 = actual.last().unwrap();
        assert_eq!(
            actual_1.value.as_ref().unwrap(),
            "https://1.example.com/context_uri"
        );
        assert_eq!(
            actual_2.value.as_ref().unwrap(),
            "https://2.example.com/context_uri"
        );
        assert_eq!(
            actual_1.href.as_ref().unwrap(),
            "https://1.example.com/target_uri"
        );
        assert_eq!(
            actual_2.href.as_ref().unwrap(),
            "https://2.example.com/target_uri"
        );
        assert_eq!(actual_1.title.as_ref().unwrap(), "title1");
        assert_eq!(actual_2.title.as_ref().unwrap(), "title2");
        assert_eq!(actual_1.media_type.as_ref().unwrap(), "application/json");
        assert_eq!(actual_2.media_type.as_ref().unwrap(), "application/json");
    }

    #[test]
    fn test_an_array_of_links_with_one_lang() {
        // GIVEN array of links with one lang
        let expected = r#"
        [
            {
                "value" : "https://1.example.com/context_uri",
                "rel" : "self",
                "href" : "https://1.example.com/target_uri",
                "hreflang" : "en",
                "title" : "title1",
                "media" : "screen",
                "type" : "application/json"
            },
            {
                "value" : "https://2.example.com/context_uri",
                "rel" : "self",
                "href" : "https://2.example.com/target_uri",
                "hreflang" : "ch",
                "title" : "title2",
                "media" : "screen",
                "type" : "application/json"
            }
        ]   
        "#;

        // WHEN deserialize
        let links = serde_json::from_str::<Links>(expected);

        // THEN data is accurate
        let actual = links.unwrap();
        assert_eq!(actual.len(), 2);
        let actual_1 = actual.first().unwrap();
        let actual_2 = actual.last().unwrap();
        assert_eq!(
            actual_1.value.as_ref().unwrap(),
            "https://1.example.com/context_uri"
        );
        assert_eq!(
            actual_2.value.as_ref().unwrap(),
            "https://2.example.com/context_uri"
        );
        assert_eq!(
            actual_1.href.as_ref().unwrap(),
            "https://1.example.com/target_uri"
        );
        assert_eq!(
            actual_2.href.as_ref().unwrap(),
            "https://2.example.com/target_uri"
        );
        assert_eq!(actual_1.title.as_ref().unwrap(), "title1");
        assert_eq!(actual_2.title.as_ref().unwrap(), "title2");
        assert_eq!(actual_1.media_type.as_ref().unwrap(), "application/json");
        assert_eq!(actual_2.media_type.as_ref().unwrap(), "application/json");
    }

    #[test]
    fn test_a_notice_or_remark_deserialize() {
        // GIVEN notice or remark
        let expected = r#"
        {
            "title" : "Terms of Use",
            "description" :
            [
                "Service subject to The Registry of the Moon's TOS.",
                "Copyright (c) 2020 LunarNIC"
            ],
            "links" :
            [
                {
                    "value" : "https://example.net/entity/XXXX",
                    "rel" : "alternate",
                    "type" : "text/html",
                    "href" : "https://www.example.com/terms_of_use.html"
                }
            ]
        }
        "#;

        // WHEN deserialize
        let actual = serde_json::from_str::<NoticeOrRemark>(expected);

        // THEN data is accurate
        let actual = actual.unwrap();
        actual.title.as_ref().unwrap();
        let description: Vec<String> = actual.description.expect("must have description").into();
        assert_eq!(description.len(), 2);
        actual.links.unwrap();
    }

    #[test]
    fn test_notices_serialize() {
        // GIVEN notices
        let notices: Notices = vec![
            Notice(
                NoticeOrRemark::builder()
                    .description(vec!["foo".to_string()])
                    .build(),
            ),
            Notice(
                NoticeOrRemark::builder()
                    .description(vec!["bar".to_string()])
                    .build(),
            ),
        ];

        // WHEN deserialize
        let actual = serde_json::to_string(&notices).unwrap();

        // THEN then array of notices
        let expected = r#"[{"description":["foo"]},{"description":["bar"]}]"#;
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_remarks_serialize() {
        // GIVEN remarks
        let remarks: Remarks = vec![
            Remark(
                NoticeOrRemark::builder()
                    .description(vec!["foo".to_string()])
                    .build(),
            ),
            Remark(
                NoticeOrRemark::builder()
                    .description(vec!["bar".to_string()])
                    .build(),
            ),
        ];

        // WHEN serialize
        let actual = serde_json::to_string(&remarks).unwrap();

        // THEN array of remarks
        let expected = r#"[{"description":["foo"]},{"description":["bar"]}]"#;
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_an_event_deserialize() {
        // GIVEN an event
        let expected = r#"
        {
            "eventAction" : "last changed",
            "eventActor" : "OTHERID-LUNARNIC",
            "eventDate" : "1991-12-31T23:59:59Z"
        }
        "#;

        // WHEN deserialize
        let actual = serde_json::from_str::<Event>(expected);

        // THEN success
        let actual = actual.unwrap();
        actual.event_actor.as_ref().unwrap();
    }

    #[test]
    fn test_a_public_id_deserialize() {
        // GIVEN public id
        let expected = r#"
        {
            "type":"IANA Registrar ID",
            "identifier":"1"
        }
        "#;

        // WHEN deserialize
        let actual = serde_json::from_str::<PublicId>(expected);

        // THEN
        let _actual = actual.unwrap();
    }

    #[test]
    fn test_set_self_link() {
        // GIVEN no self links
        let mut oc = ObjectCommon::domain()
            .links(vec![Link::builder()
                .href("http://bar.example")
                .value("http://bar.example")
                .rel("unknown")
                .build()])
            .build();

        // WHEN set self link
        oc = oc.with_self_link(
            Link::builder()
                .href("http://foo.example")
                .value("http://foo.example")
                .rel("unknown")
                .build(),
        );

        // THEN it is the only one
        assert_eq!(
            oc.links
                .expect("links are empty")
                .iter()
                .filter(|link| link.is_relation("self"))
                .count(),
            1
        );
    }

    #[test]
    fn test_set_self_link_on_no_links() {
        // GIVEN no links
        let mut oc = ObjectCommon::domain().build();

        // WHEN set self link
        oc = oc.with_self_link(
            Link::builder()
                .href("http://foo.example")
                .value("http://foo.example")
                .rel("unknown")
                .build(),
        );

        // THEN then it is the only one
        assert_eq!(
            oc.links
                .expect("links are empty")
                .iter()
                .filter(|link| link.is_relation("self"))
                .count(),
            1
        );
    }

    #[test]
    fn test_set_self_link_when_one_exists() {
        // GIVEN one self link
        let mut oc = ObjectCommon::domain()
            .links(vec![Link::builder()
                .href("http://bar.example")
                .value("http://bar.example")
                .rel("self")
                .build()])
            .build();

        // WHEN set self link
        oc = oc.with_self_link(
            Link::builder()
                .href("http://foo.example")
                .value("http://foo.example")
                .rel("unknown")
                .build(),
        );

        // THEN
        // new link is in
        assert_eq!(
            oc.links
                .as_ref()
                .expect("links are empty")
                .iter()
                .filter(|link| link.is_relation("self")
                    && link.href.as_ref().unwrap() == "http://foo.example")
                .count(),
            1
        );
        // all self links count == 1
        assert_eq!(
            oc.links
                .as_ref()
                .expect("links are empty")
                .iter()
                .filter(|link| link.is_relation("self"))
                .count(),
            1
        );
    }

    #[test]
    fn test_description_as_pgs() {
        // GIVEN notice
        let notice = Notice::builder()
            .description_entry("This is a test")
            .description_entry("that should be consolidated.")
            .description_entry("SEPARATE LINE")
            .description_entry("Another line.")
            .build();

        // WHEN converted to pgs
        let actual = notice.description_as_pgs();

        // THEN
        assert_eq!(
            actual.first().unwrap(),
            "This is a test that should be consolidated."
        );
        assert_eq!(actual.get(1).unwrap(), "SEPARATE LINE");
        assert_eq!(actual.get(2).unwrap(), "Another line.");
    }
}