use std::str::FromStr;
use stixflayer_derive::StixProperties;
use crate::{
base::{CommonProperties, CommonPropertiesBuilder, Stix},
error::{add_error, return_multiple_errors, CheckContext, Outcome, StixError as Error},
relationship_objects::{Related, RelationshipObjectBuilder},
types::{
DictionaryValue, ExternalReference, GranularMarking, Identified, Identifier,
StixDictionary, Timestamp,
},
validation::validate_value,
};
use language_tags::LanguageTag;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;
use std::collections::{BTreeMap, HashMap};
use uuid::Uuid;
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, StixProperties)]
pub struct LanguageContent {
#[serde(rename = "type")]
pub object_type: String,
#[serde(flatten)]
pub common_properties: CommonProperties,
pub object_ref: Identifier,
pub object_modified: Option<Timestamp>,
pub contents: StixDictionary<StixDictionary<ContentType>>,
}
impl LanguageContent {
pub fn from_json(json: &str, allow_custom: bool) -> Result<Self, Error> {
let value: serde_json::Value =
serde_json::from_str(json).map_err(|e| Error::DeserializationError(e.to_string()))?;
validate_value(value, allow_custom, true)
}
pub fn is_revoked(&self) -> bool {
matches!(self.common_properties.revoked, Some(true))
}
pub fn add_sighting(self) -> Result<RelationshipObjectBuilder, Error> {
let sighting_of_ref = self.get_id().to_owned();
RelationshipObjectBuilder::new_sighting(sighting_of_ref)
}
}
impl Identified for LanguageContent {
fn get_id(&self) -> &Identifier {
&self.common_properties.id
}
}
impl Related for LanguageContent {
fn add_relationship<T: Related + Identified>(
self,
target: T,
relationship_type: String,
) -> Result<RelationshipObjectBuilder, Error> {
let source_id = self.get_id().to_owned();
let target_id = target.get_id().to_owned();
RelationshipObjectBuilder::new(source_id, target_id, &relationship_type)
}
}
crate::impl_custom_properties_holder!(LanguageContent);
impl Stix for LanguageContent {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
ctx.set_object_id(Some(self.get_id().to_string()));
let mut errors = Vec::new();
add_error(&mut errors, self.common_properties.check(ctx));
if self.common_properties.spec_version.is_none() {
errors.push(Error::ValidationError(
"Language Content SMOs must have a `spec_version` property.".to_string(),
));
}
if self.common_properties.created.is_none() {
errors.push(Error::ValidationError(
"Language Content SMOs must have a `created` property.".to_string(),
));
}
if self.common_properties.modified.is_none() {
errors.push(Error::ValidationError(
"Language Content SMOs must have a `modified` property.".to_string(),
));
}
if self.common_properties.lang.is_some() {
errors.push(Error::ValidationError(
"Language Content SMOs cannot have a `lang` property.".to_string(),
));
}
if self.common_properties.defanged.is_some() {
errors.push(Error::ValidationError(
"Language Content SMOs cannot have a `defanged` property.".to_string(),
));
}
if self.object_type != "language-content" {
errors.push(Error::ValidationError(
"Language Content SMOs must have a type of 'language-content'".to_string(),
));
}
add_error(&mut errors, self.contents.check(ctx));
for (key, value) in self.contents.iter() {
match LanguageTag::parse(key) {
Ok(tag) => if let Err(e) = LanguageTag::validate(&tag) {
errors.push(Error::ValidationError(format!("One of the keys for LanguageContent Object {}'s `contents` dictionary is {}. A `content` key must conform to RFC5646. Details: {}",
self.common_properties.id,
key,
e
)));
}
Err(e) => errors.push(Error::ValidationError(format!("One of the keys for LanguageContent Object {}'s `contents` dictionary is {}. A `content` key must conform to RFC5646. Details: {}",
self.common_properties.id,
key,
e
))),
}
add_error(&mut errors, value.check(ctx));
for (subkey, _) in value.iter() {
let valid = subkey.len() >= 3
&& subkey.len() <= 250
&& subkey
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
if !valid {
errors.push(Error::ValidationError(format!(
"'{}' in '{}' of the 'contents' property is invalid and must match a valid property name",
subkey, key,
)));
}
}
}
return_multiple_errors(errors)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ContentType {
String(String),
List(Vec<String>),
Object(Box<LanguageContent>),
}
impl Stix for ContentType {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
match self {
ContentType::String(string) => string.check(ctx),
ContentType::List(list) => list.check(ctx),
ContentType::Object(content) => content.check(ctx),
}
}
}
#[derive(Clone, Debug)]
pub struct LanguageContentBuilder {
common_properties: CommonPropertiesBuilder,
object_ref: Identifier,
object_modified: Option<Timestamp>,
contents: StixDictionary<StixDictionary<ContentType>>,
}
impl LanguageContentBuilder {
pub fn new(object_ref: &str) -> Result<Self, Error> {
let object_ref_id = Identifier::from_str(object_ref)?;
let common_properties =
CommonPropertiesBuilder::new("language-content", "language-content")?;
Ok(Self {
common_properties,
object_ref: object_ref_id,
object_modified: None,
contents: StixDictionary::new(),
})
}
pub fn version(old: &LanguageContent) -> Result<Self, Error> {
if old.is_revoked() {
return Err(Error::UnableToVersion(format!(
"LanguageContent SMO {} is revoked. Versioning a revoked object is prohibited.",
old.common_properties.id
)));
}
let object_ref = old.object_ref.clone();
let object_modified = old.object_modified.clone();
let contents = old.contents.clone();
let old_properties = old.common_properties.clone();
let common_properties =
CommonPropertiesBuilder::version("language-content", &old_properties)?;
Ok(Self {
common_properties,
object_ref,
object_modified,
contents,
})
}
pub fn from_parsed(old: &LanguageContent) -> Result<Self, Error> {
let object_ref = old.object_ref.clone();
let object_modified = old.object_modified.clone();
let contents = old.contents.clone();
let old_properties = old.common_properties.clone();
let common_properties =
CommonPropertiesBuilder::from_existing("language-content", &old_properties)?;
Ok(Self {
common_properties,
object_ref,
object_modified,
contents,
})
}
pub fn created_by_ref(mut self, id: Identifier) -> Result<Self, Error> {
self.common_properties = self.common_properties.clone().created_by_ref(id)?;
Ok(self)
}
pub fn labels(mut self, labels: Vec<String>) -> Self {
self.common_properties = self.common_properties.clone().labels(labels);
self
}
pub fn confidence(mut self, confidence: u8) -> Self {
self.common_properties = self.common_properties.clone().confidence(confidence);
self
}
pub fn external_references(mut self, references: Vec<ExternalReference>) -> Self {
self.common_properties = self
.common_properties
.clone()
.external_references(references);
self
}
pub fn object_marking_refs(mut self, references: Vec<Identifier>) -> Self {
self.common_properties = self
.common_properties
.clone()
.object_marking_refs(references);
self
}
pub fn granular_markings(mut self, markings: Vec<GranularMarking>) -> Self {
self.common_properties = self.common_properties.clone().granular_markings(markings);
self
}
pub fn add_extension(
mut self,
key: &str,
extension: StixDictionary<DictionaryValue>,
) -> Result<Self, Error> {
self.common_properties = self
.common_properties
.clone()
.add_extension(key, extension)?;
Ok(self)
}
pub fn object_modified(mut self, object_modified: &str) -> Result<Self, Error> {
self.object_modified = Some(Timestamp(
object_modified.parse().map_err(Error::DateTimeError)?,
));
Ok(self)
}
pub fn insert_content(
mut self,
lang: &str,
content: StixDictionary<ContentType>,
) -> Result<Self, Error> {
self.contents.insert(lang, content)?;
Ok(self)
}
pub fn insert_content_strings(
mut self,
lang: &str,
content: HashMap<String, String>,
) -> Result<Self, Error> {
let mut dict = StixDictionary::new();
for (key, value) in content {
dict.insert(&key, ContentType::String(value))?;
}
self.contents.insert(lang, dict)?;
Ok(self)
}
pub fn insert_content_lists(
mut self,
lang: &str,
content: HashMap<String, Vec<String>>,
) -> Result<Self, Error> {
let mut dict = StixDictionary::new();
for (key, value) in content {
dict.insert(&key, ContentType::List(value))?;
}
self.contents.insert(lang, dict)?;
Ok(self)
}
pub fn insert_content_objects(
mut self,
lang: &str,
content: HashMap<String, HashMap<String, Value>>,
) -> Result<Self, Error> {
let object_ref = self.object_ref.to_string();
let mut dict = StixDictionary::new();
for (key, value_map) in content.iter() {
let mut nested_dict = StixDictionary::new();
for (prop_key, prop_value) in value_map.iter() {
let content_type = match prop_value {
Value::String(s) => ContentType::String(s.clone()),
Value::Array(arr) => {
let mut vec = Vec::new();
for item in arr {
if let Value::String(s) = item {
vec.push(s.clone());
} else {
vec.push("".to_string());
}
}
ContentType::List(vec)
}
Value::Object(map) => {
let mut inner_map = HashMap::new();
for (k, v) in map.iter() {
if let Value::String(s) = v {
inner_map.insert(k.clone(), s.clone());
} else {
inner_map.insert(k.clone(), "".to_string());
}
}
ContentType::Object(Box::new(
LanguageContentBuilder::new(&format!(
"{}--{}--{}",
object_ref,
key,
Uuid::new_v4()
))?
.object_modified("2017-02-08T21:31:22.007Z")?
.insert_content_strings(lang, inner_map)?
.build()?,
))
}
_ => ContentType::String("".to_string()),
};
nested_dict.insert(prop_key, content_type)?;
}
let nested_lc = LanguageContentBuilder::new(&format!(
"{}--{}--{}",
object_ref,
key,
Uuid::new_v4()
))?
.object_modified("2017-02-08T21:31:22.007Z")?
.insert_content(lang, nested_dict)?
.build()?;
dict.insert(key.as_str(), ContentType::Object(Box::new(nested_lc)))?;
}
self.contents.insert(lang, dict)?;
Ok(self)
}
pub fn custom_properties(mut self, custom_properties: BTreeMap<String, Value>) -> Self {
self.common_properties = self
.common_properties
.clone()
.custom_properties(custom_properties);
self
}
pub fn build_no_validate(self) -> Result<LanguageContent, Error> {
let common_properties = self.common_properties.build();
let object_ref = self.object_ref;
let object_modified = self.object_modified;
let contents = self.contents;
let language_content = LanguageContent {
object_type: "language-content".to_string(),
common_properties,
object_ref,
object_modified,
contents,
};
Ok(language_content)
}
pub fn build(self) -> Result<LanguageContent, Error> {
let object = self.build_no_validate()?;
object.stix_check()?;
Ok(object)
}
pub fn build_outcome(self) -> Outcome<LanguageContent> {
let object = match self.build_no_validate() {
Ok(object) => object,
Err(error) => return Outcome::err(error, Vec::new()),
};
let mut ctx = CheckContext::new();
let result = object.check(&mut ctx).map(|()| object);
Outcome::from_result(result, ctx.into_warnings())
}
}