use crate::entity_type::EntityType;
use crate::error::WikibaseError;
use regex::Regex;
fn number_is_integer(string: &str) -> bool {
string.parse::<u64>().is_ok()
}
pub fn parse_wikibase_entity_type(entity_id: &str) -> Result<EntityType, WikibaseError> {
if entity_id.chars().count() < 2 {
return Err(WikibaseError::Validation("ID is too short".to_string()));
}
let first_char = match entity_id.chars().next() {
Some(value) => value,
None => {
return Err(WikibaseError::Validation(
"Error getting first character of string".to_string(),
))
}
};
if !number_is_integer(&entity_id[1..]) {
return Err(WikibaseError::Serialization(
"Wikibase ID is not a valid integer".to_string(),
));
}
match first_char {
'P' => Ok(EntityType::Property),
'Q' => Ok(EntityType::Item),
_ => Err(WikibaseError::Serialization(
"Wikibase ID does not have a P or Q prefix".to_string(),
)),
}
}
pub fn validate_user_agent(user_agent: &str) -> Result<String, WikibaseError> {
let re = Regex::new(r"(?P<user_agent>[a-zA-Z0-9-_]+/[0-9\.]+)").unwrap();
let valid = match re.captures(user_agent) {
Some(value) => value,
None => {
return Err(WikibaseError::Configuration(
"User agent is not valid".to_string(),
))
}
};
Ok(valid["user_agent"].to_string())
}