Debian Codegraph @

src/response/entity.rs

raw
1 //! Entity object class.
2 use std::collections::HashSet;
3
4 use crate::{contact::jscontact::JsContactCard, prelude::ContentExtensions};
5
6 use {
7 crate::{
8 contact::Contact,
9 prelude::{Common, Extension, ObjectCommon},
10 },
11 serde::{Deserialize, Serialize},
12 serde_json::Value,
13 };
14
15 use super::{
16 CommonFields, Event, GetSelfLink, Notice, ObjectCommonFields, Port43, PublicId, Remark,
17 SelfLink, ToChild, ToResponse, VectorStringish,
18 autnum::Autnum,
19 network::Network,
20 to_opt_vec, to_opt_vectorstringish,
21 types::{Events, Link, PublicIds},
22 };
23
24 /// Represents an RDAP [entity](https://rdap.rcode3.com/protocol/object_classes.html#entity) response.
25 ///
26 /// Use of the builder is recommended when constructing this structure as it
27 /// will fill-in the mandatory fields.
28 /// The following is an example.
29 ///
30 /// ```rust
31 /// use icann_rdap_common::prelude::*;
32 ///
33 /// let contact = Contact::builder()
34 /// .kind("individual")
35 /// .full_name("Bob Smurd")
36 /// .build();
37 ///
38 /// let entity = Entity::response_obj()
39 /// .handle("foo_example_com-1")
40 /// .status("active")
41 /// .role("registrant")
42 /// .contact(contact)
43 /// .build();
44 /// let c = serde_json::to_string_pretty(&entity).unwrap();
45 /// eprintln!("{c}");
46 /// ```
47 ///
48 /// This will produce the following.
49 ///
50 /// ```norust
51 /// {
52 /// "rdapConformance": [
53 /// "rdap_level_0"
54 /// ],
55 /// "objectClassName": "entity",
56 /// "handle": "foo_example_com-1",
57 /// "status": [
58 /// "active"
59 /// ],
60 /// "vcardArray": [
61 /// "vcard",
62 /// [
63 /// [
64 /// "version",
65 /// {},
66 /// "text",
67 /// "4.0"
68 /// ],
69 /// [
70 /// "fn",
71 /// {},
72 /// "text",
73 /// "Bob Smurd"
74 /// ],
75 /// [
76 /// "kind",
77 /// {},
78 /// "text",
79 /// "individual"
80 /// ]
81 /// ]
82 /// ],
83 /// "roles": [
84 /// "registrant"
85 /// ]
86 /// }
87 /// ```
88 ///
89 /// Use the getter functions to get the data in the entity. Because
90 /// data from vCard can be difficult to handle, you can use the [Contact]
91 /// abstraction for address information.
92 /// See [CommonFields] and [ObjectCommonFields] for common getter functions.
93 /// ```rust
94 /// # use icann_rdap_common::prelude::*;
95 /// # let entity = Entity::builder()
96 /// # .handle("foo_example_com-1")
97 /// # .build();
98 /// let contact = entity.contact();
99 /// let public_ids = entity.public_ids();
100 /// let handle = entity.handle();
101 /// ```
102 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
103 pub struct Entity {
104 #[serde(flatten)]
105 pub common: Common,
106
107 #[serde(flatten)]
108 pub object_common: ObjectCommon,
109
110 #[serde(rename = "vcardArray")]
111 #[serde(skip_serializing_if = "Option::is_none")]
112 pub(crate) vcard_array: Option<Vec<Value>>,
113
114 #[serde(skip_serializing_if = "Option::is_none")]
115 pub(crate) jscontact_card: Option<JsContactCard>,
116
117 #[serde(skip_serializing_if = "Option::is_none")]
118 pub roles: Option<VectorStringish>,
119
120 #[serde(rename = "publicIds")]
121 #[serde(skip_serializing_if = "Option::is_none")]
122 pub public_ids: Option<PublicIds>,
123
124 #[serde(rename = "asEventActor")]
125 #[serde(skip_serializing_if = "Option::is_none")]
126 pub as_event_actor: Option<Events>,
127
128 #[serde(skip_serializing_if = "Option::is_none")]
129 pub autnums: Option<Vec<Autnum>>,
130
131 #[serde(skip_serializing_if = "Option::is_none")]
132 pub networks: Option<Vec<Network>>,
133 }
134
135 #[buildstructor::buildstructor]
136 impl Entity {
137 /// Builds a basic entity object for with embedding into other objects.
138 ///
139 /// ```rust
140 /// use icann_rdap_common::prelude::*;
141 ///
142 /// let contact = Contact::builder()
143 /// .kind("individual")
144 /// .full_name("Bob Smurd")
145 /// .build();
146 ///
147 /// let entity = Entity::builder()
148 /// .handle("foo_example_com-1")
149 /// .status("active")
150 /// .role("registrant")
151 /// .contact(contact)
152 /// .build();
153 /// ```
154 ///
155 /// An entity without a handle can be
156 /// built if a generic type is specified.
157 ///
158 /// ```rust
159 /// use icann_rdap_common::prelude::*;
160 ///
161 /// let entity = Entity::builder::<String>()
162 /// .status("active")
163 /// .build();
164 /// ```
165 #[builder(visibility = "pub")]
166 fn new<T: Into<String>>(
167 handle: Option<T>,
168 remarks: Vec<Remark>,
169 links: Vec<Link>,
170 events: Vec<Event>,
171 statuses: Vec<String>,
172 port_43: Option<Port43>,
173 entities: Vec<Entity>,
174 as_event_actors: Vec<Event>,
175 contact: Option<Contact>,
176 no_vcard: Option<bool>,
177 jscontact: Option<bool>,
178 roles: Vec<String>,
179 public_ids: Vec<PublicId>,
180 networks: Vec<Network>,
181 autnums: Vec<Autnum>,
182 redacted: Option<Vec<crate::response::redacted::Redacted>>,
183 ) -> Self {
184 Self {
185 common: Common::builder().build(),
186 object_common: ObjectCommon::entity()
187 .and_handle(handle.map(|h| h.into()))
188 .and_remarks(to_opt_vec(remarks))
189 .and_links(to_opt_vec(links))
190 .and_events(to_opt_vec(events))
191 .status(statuses)
192 .and_port_43(port_43)
193 .and_entities(to_opt_vec(entities))
194 .and_redacted(redacted)
195 .build(),
196 vcard_array: if no_vcard.unwrap_or(false) {
197 None
198 } else {
199 contact.as_ref().map(|c| c.to_vcard())
200 },
201 jscontact_card: if jscontact.unwrap_or(false) {
202 contact.as_ref().map(|c| c.to_jscontact())
203 } else {
204 None
205 },
206 roles: to_opt_vectorstringish(roles),
207 public_ids: to_opt_vec(public_ids),
208 as_event_actor: to_opt_vec(as_event_actors),
209 autnums: to_opt_vec(autnums),
210 networks: to_opt_vec(networks),
211 }
212 }
213
214 /// Builds an entity object as a response.
215 ///
216 /// ```rust
217 /// use icann_rdap_common::prelude::*;
218 ///
219 /// let contact = Contact::builder()
220 /// .kind("individual")
221 /// .full_name("Bob Smurd")
222 /// .build();
223 ///
224 /// let entity = Entity::response_obj()
225 /// .handle("foo_example_com-1")
226 /// .status("active")
227 /// .role("registrant")
228 /// .contact(contact)
229 /// .extension(ExtensionId::IcannRdapResponseProfile1.as_ref())
230 /// .extension(ExtensionId::IcannRdapTechnicalImplementationGuide1.as_ref())
231 /// .notice(Notice::builder().title("test").build())
232 /// .build();
233 /// ```
234 ///
235 /// An entity without a handle can be
236 /// built if a generic type is specified.
237 ///
238 /// ```rust
239 /// use icann_rdap_common::prelude::*;
240 ///
241 /// let entity = Entity::response_obj::<String>()
242 /// .status("active")
243 /// .build();
244 /// ```
245 #[builder(entry = "response_obj", visibility = "pub")]
246 fn new_response_obj<T: Into<String>>(
247 handle: Option<T>,
248 remarks: Vec<Remark>,
249 links: Vec<Link>,
250 events: Vec<Event>,
251 statuses: Vec<String>,
252 port_43: Option<Port43>,
253 entities: Vec<Entity>,
254 as_event_actors: Vec<Event>,
255 contact: Option<Contact>,
256 no_vcard: Option<bool>,
257 jscontact: Option<bool>,
258 roles: Vec<String>,
259 public_ids: Vec<PublicId>,
260 notices: Vec<Notice>,
261 networks: Vec<Network>,
262 autnums: Vec<Autnum>,
263 extensions: Vec<Extension>,
264 redacted: Option<Vec<crate::response::redacted::Redacted>>,
265 ) -> Self {
266 let common = Common::level0()
267 .extensions(extensions)
268 .and_notices(to_opt_vec(notices))
269 .build();
270 let mut entity = Entity::builder()
271 .and_handle(handle)
272 .remarks(remarks)
273 .links(links)
274 .events(events)
275 .statuses(statuses)
276 .and_port_43(port_43)
277 .as_event_actors(as_event_actors)
278 .and_contact(contact)
279 .and_no_vcard(no_vcard)
280 .and_jscontact(jscontact)
281 .roles(roles)
282 .entities(entities)
283 .public_ids(public_ids)
284 .autnums(autnums)
285 .networks(networks)
286 .and_redacted(redacted)
287 .build();
288 entity.common = common;
289 entity
290 }
291
292 /// Get a [Contact].
293 ///
294 /// If the contact is represented as a JSContact, that will be
295 /// preferred, else the contact will come from the impenetrable vCard.
296 pub fn contact(&self) -> Option<Contact> {
297 if let Some(jscontact) = &self.jscontact_card {
298 return Some(Contact::from_jscontact(jscontact));
299 }
300 //else
301 let vcard = self.vcard_array.as_ref()?;
302 Contact::from_vcard(vcard)
303 }
304
305 /// Get the roles.
306 pub fn roles(&self) -> &[String] {
307 self.roles
308 .as_ref()
309 .map(|v| v.vec().as_ref())
310 .unwrap_or_default()
311 }
312
313 /// Get the public IDs.
314 pub fn public_ids(&self) -> &[PublicId] {
315 self.public_ids.as_deref().unwrap_or_default()
316 }
317
318 /// Get the events this entity acted on.
319 pub fn as_event_actors(&self) -> &[Event] {
320 self.as_event_actor.as_deref().unwrap_or_default()
321 }
322
323 /// Get the autnums.
324 pub fn autnums(&self) -> &[Autnum] {
325 self.autnums.as_deref().unwrap_or_default()
326 }
327
328 /// Get the networks.
329 pub fn networks(&self) -> &[Network] {
330 self.networks.as_deref().unwrap_or_default()
331 }
332
333 /// True if an entity is a role.
334 ///
335 /// Registered roles can be found in [crate::response::EntityRole]. This method
336 /// purposefully allows using unregistered roles as well.
337 ///
338 /// ```rust
339 /// use icann_rdap_common::prelude::*;
340 ///
341 /// let entity = Entity::response_obj()
342 /// .handle("foo_example_com-1")
343 /// .role("registrant")
344 /// .build();
345 ///
346 /// assert!(entity.is_entity_role(&EntityRole::Registrant.to_string()));
347 /// ```
348 pub fn is_entity_role(&self, role: &str) -> bool {
349 self.roles().iter().any(|r| r.eq(role))
350 }
351
352 /// Set the contact as a vcard.
353 pub fn with_contact_as_vcard(&mut self, contact: &Contact) -> &mut Self {
354 self.vcard_array = Some(contact.to_vcard());
355 self
356 }
357
358 /// Set the contact as a vcard if it already has a vcard representation.
359 pub fn with_contact_if_vcard(&mut self, contact: &Contact) -> &mut Self {
360 if self.is_contact_as_vcard() {
361 self.with_contact_as_vcard(contact);
362 };
363 self
364 }
365
366 /// Set the contact as a jscontact.
367 pub fn with_contact_as_jscontact(&mut self, contact: &Contact) -> &mut Self {
368 self.jscontact_card = Some(contact.to_jscontact());
369 self
370 }
371
372 /// Set the contact as a jscontact if it already has a jscontact representation.
373 pub fn with_contact_if_jscontact(&mut self, contact: &Contact) -> &mut Self {
374 if self.is_contact_as_jscontact() {
375 self.with_contact_as_jscontact(contact);
376 };
377 self
378 }
379
380 /// True if the contact is represented as a vcard.
381 pub fn is_contact_as_vcard(&self) -> bool {
382 self.vcard_array.is_some()
383 }
384
385 /// True if the contact is represented as a JSContact.
386 pub fn is_contact_as_jscontact(&self) -> bool {
387 self.jscontact_card.is_some()
388 }
389 }
390
391 impl ToResponse for Entity {
392 fn to_response(self) -> super::RdapResponse {
393 super::RdapResponse::Entity(Box::new(self))
394 }
395 }
396
397 impl GetSelfLink for Entity {
398 fn self_link(&self) -> Option<&Link> {
399 self.object_common.self_link()
400 }
401 }
402
403 impl SelfLink for Entity {
404 fn with_self_link(mut self, link: Link) -> Self {
405 self.object_common = self.object_common.with_self_link(link);
406 self
407 }
408 }
409
410 impl ToChild for Entity {
411 fn to_child(mut self) -> Self {
412 self.common = Common {
413 rdap_conformance: None,
414 notices: None,
415 };
416 self
417 }
418 }
419
420 impl CommonFields for Entity {
421 fn common(&self) -> &Common {
422 &self.common
423 }
424 }
425
426 impl ObjectCommonFields for Entity {
427 fn object_common(&self) -> &ObjectCommon {
428 &self.object_common
429 }
430 }
431
432 impl ContentExtensions for Entity {
433 fn content_extensions(&self) -> std::collections::HashSet<super::ExtensionId> {
434 let mut exts = HashSet::new();
435 exts.extend(self.common().content_extensions());
436 exts.extend(self.object_common().content_extensions());
437 if self.jscontact_card.is_some() {
438 exts.insert(super::ExtensionId::JsContact);
439 }
440 exts
441 }
442 }
443
444 #[cfg(test)]
445 mod tests {
446 use super::Entity;
447
448 #[test]
449 fn test_entity_deserialize() {
450 // GIVEN
451 let expected = r#"
452 {
453 "objectClassName" : "entity",
454 "handle":"XXXX",
455 "vcardArray":[
456 "vcard",
457 [
458 ["version", {}, "text", "4.0"],
459 ["fn", {}, "text", "Joe User"],
460 ["n", {}, "text",
461 ["User", "Joe", "", "", ["ing. jr", "M.Sc."]]
462 ],
463 ["kind", {}, "text", "individual"],
464 ["lang", {
465 "pref":"1"
466 }, "language-tag", "fr"],
467 ["lang", {
468 "pref":"2"
469 }, "language-tag", "en"],
470 ["org", {
471 "type":"work"
472 }, "text", "Example"],
473 ["title", {}, "text", "Research Scientist"],
474 ["role", {}, "text", "Project Lead"],
475 ["adr",
476 { "type":"work" },
477 "text",
478 [
479 "",
480 "Suite 1234",
481 "4321 Rue Somewhere",
482 "Quebec",
483 "QC",
484 "G1V 2M2",
485 "Canada"
486 ]
487 ],
488 ["adr",
489 {
490 "type":"home",
491 "label":"123 Maple Ave\nSuite 90001\nVancouver\nBC\n1239\n"
492 },
493 "text",
494 [
495 "", "", "", "", "", "", ""
496 ]
497 ],
498 ["tel",
499 {
500 "type":["work", "voice"],
501 "pref":"1"
502 },
503 "uri",
504 "tel:+1-555-555-1234;ext=102"
505 ],
506 ["tel",
507 { "type":["work", "cell", "voice", "video", "text"] },
508 "uri",
509 "tel:+1-555-555-4321"
510 ],
511 ["email",
512 { "type":"work" },
513 "text",
514 "[email protected]"
515 ],
516 ["geo", {
517 "type":"work"
518 }, "uri", "geo:46.772673,-71.282945"],
519 ["key",
520 { "type":"work" },
521 "uri",
522 "https://www.example.com/joe.user/joe.asc"
523 ],
524 ["tz", {},
525 "utc-offset", "-05:00"],
526 ["url", { "type":"home" },
527 "uri", "https://example.org"]
528 ]
529 ],
530 "roles":[ "registrar" ],
531 "publicIds":[
532 {
533 "type":"IANA Registrar ID",
534 "identifier":"1"
535 }
536 ],
537 "remarks":[
538 {
539 "description":[
540 "She sells sea shells down by the sea shore.",
541 "Originally written by Terry Sullivan."
542 ]
543 }
544 ],
545 "links":[
546 {
547 "value":"https://example.com/entity/XXXX",
548 "rel":"self",
549 "href":"https://example.com/entity/XXXX",
550 "type" : "application/rdap+json"
551 }
552 ],
553 "events":[
554 {
555 "eventAction":"registration",
556 "eventDate":"1990-12-31T23:59:59Z"
557 }
558 ],
559 "asEventActor":[
560
561 {
562 "eventAction":"last changed",
563 "eventDate":"1991-12-31T23:59:59Z"
564 }
565 ]
566 }
567 "#;
568
569 // WHEN
570 let actual = serde_json::from_str::<Entity>(expected);
571
572 // THEN
573 let actual = actual.unwrap();
574 assert_eq!(actual.object_common.object_class_name, "entity");
575 assert!(actual.object_common.handle.is_some());
576 assert!(actual.vcard_array.is_some());
577 assert!(actual.roles.is_some());
578 assert!(actual.public_ids.is_some());
579 assert!(actual.object_common.remarks.is_some());
580 assert!(actual.object_common.links.is_some());
581 assert!(actual.object_common.events.is_some());
582 assert!(actual.as_event_actor.is_some());
583 }
584 }