use crate::domain::AllowedOrigin;
use crate::error::{AppError, AppResult, ErrorDetail, Subject};
use super::constants::{APP_NAME, APP_VERSION, DEFAULT_CONTACT_URL, MAX_USER_AGENT_CHARS};
pub use crate::domain::is_stdlib_name as is_stdlib_crate;
pub fn default_user_agent(contact: Option<&str>) -> String {
match contact {
Some(c) if !c.is_empty() => {
if c.starts_with("http://") || c.starts_with("https://") {
format!("{APP_NAME}/{APP_VERSION} (+{c})")
} else {
format!("{APP_NAME}/{APP_VERSION} ({c})")
}
}
_ => format!("{APP_NAME}/{APP_VERSION} (+{DEFAULT_CONTACT_URL})"),
}
}
pub fn validate_origin(raw: &str) -> AppResult<AllowedOrigin> {
AllowedOrigin::parse(raw)
}
pub fn validate_origin_with(raw: &str, allow_loopback: bool) -> AppResult<AllowedOrigin> {
AllowedOrigin::parse_with(raw, allow_loopback)
}
pub fn validate_user_agent(ua: &str) -> AppResult<()> {
if ua.is_empty() {
return Err(AppError::of(ErrorDetail::Empty {
subject: Subject::UserAgent,
}));
}
if ua.chars().count() > MAX_USER_AGENT_CHARS {
return Err(AppError::of(ErrorDetail::TooLong {
subject: Subject::UserAgent,
limit: MAX_USER_AGENT_CHARS,
}));
}
if !ua.bytes().all(|b| (0x20..=0x7e).contains(&b)) {
return Err(AppError::of(ErrorDetail::NotVisibleAscii {
subject: Subject::UserAgent,
}));
}
Ok(())
}
pub fn validate_contact(contact: &str) -> AppResult<()> {
if contact.is_empty() {
return Err(AppError::of(ErrorDetail::Empty {
subject: Subject::Contact,
}));
}
if contact.chars().count() > MAX_USER_AGENT_CHARS {
return Err(AppError::of(ErrorDetail::TooLong {
subject: Subject::Contact,
limit: MAX_USER_AGENT_CHARS,
}));
}
if !contact.bytes().all(|b| (0x20..=0x7e).contains(&b)) {
return Err(AppError::of(ErrorDetail::NotVisibleAscii {
subject: Subject::Contact,
}));
}
Ok(())
}