use crate::error::CheckContext;
use crate::{
base::{check_timestamp_ordering, Stix},
common::validation::validate_refs_are_type,
error::StixError as Error,
types::{stix_case, Identifier, ScoTypes, SdoTypes, SroTypes, StixMetaTypes, Timestamp},
};
use serde::{Deserialize, Serialize};
use serde_this_or_that::as_opt_u64;
use serde_with::skip_serializing_none;
use stixflayer_derive::StixProperties;
use strum::IntoEnumIterator;
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, StixProperties)]
pub struct Sighting {
pub first_seen: Option<Timestamp>,
pub last_seen: Option<Timestamp>,
#[serde(default, deserialize_with = "as_opt_u64")]
pub count: Option<u64>,
pub sighting_of_ref: Identifier,
pub observed_data_refs: Option<Vec<Identifier>>,
pub where_sighted_refs: Option<Vec<Identifier>>,
pub summary: Option<bool>,
}
impl Stix for Sighting {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
if let Some(count) = &self.count {
count.check(ctx)?;
}
if let (Some(start), Some(stop)) = (&self.first_seen, &self.last_seen) {
check_timestamp_ordering(start, stop, "first_seen", "last_seen", "Sighting")?;
}
if let Some(count) = self.count {
if count > 999999999 {
return Err(Error::ValidationError(format!("This sighting SRO has a count of {}. This field cannot have a value larger than 999,999,999.",
count
)));
}
}
if SdoTypes::iter().all(|x| x.as_ref() != stix_case(self.sighting_of_ref.get_type())) {
return Err(Error::ValidationError(format!(
"Sighting of ref must be an SDO. Sighting of ref is type {}.",
self.sighting_of_ref.get_type()
)));
}
if !ScoTypes::iter().all(|x| x.as_ref() != stix_case(self.sighting_of_ref.get_type()))
|| !StixMetaTypes::iter()
.all(|x| x.as_ref() != stix_case(self.sighting_of_ref.get_type()))
|| !SroTypes::iter().all(|x| x.as_ref() != stix_case(self.sighting_of_ref.get_type()))
{
return Err(Error::ValidationError(format!(
"Sighting of ref must be an SDO. Sighting of ref is type {}.",
self.sighting_of_ref.get_type()
)));
}
self.sighting_of_ref.check(ctx)?;
if let Some(observed_data_refs) = &self.observed_data_refs {
validate_refs_are_type(observed_data_refs, &["observed-data"], "observed_data_refs")?;
}
if let Some(where_sighted_refs) = &self.where_sighted_refs {
validate_refs_are_type(
where_sighted_refs,
&["identity", "location"],
"where_sighted_refs",
)?;
}
Ok(())
}
}