use super::errors::{DomainChangerError, DomainChangerResult};
#[cfg(feature = "json")]
use super::ToFromJson;
#[cfg(feature = "json")]
use serde::{Deserialize, Serialize};
use url::Url;
#[cfg_attr(feature = "json", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Domain {
pub old: Url,
pub new: Url,
}
impl Domain {
pub fn new(old: Url, new: Url) -> Self {
Self { old, new }
}
pub fn contain(&self, word: &str, just_old: bool) -> Option<Url> {
let host_with_https: String = "https://".to_owned() + word;
if let Ok(url) = Url::parse(
if word.starts_with("https://") || word.starts_with("http://") {
word
} else {
&host_with_https
},
) {
if let Some(str_host) = url.host_str() {
if self.old.has_host() && (self.old.host_str().unwrap() == str_host)
|| !just_old
&& self.new.has_host()
&& (self.new.host_str().unwrap() == str_host)
{
return Some(url);
}
}
}
None
}
}
#[cfg(feature = "json")]
impl ToFromJson<'_> for Domain {}
impl TryFrom<(&str, &str)> for Domain {
type Error = DomainChangerError;
fn try_from(domains: (&str, &str)) -> DomainChangerResult<Self> {
Ok(Self {
old: Url::parse(domains.0).map_err(|_| {
DomainChangerError::InvalidOldDomain(format!(
"'{}', is invalid old domain",
domains.0
))
})?,
new: Url::parse(domains.1).map_err(|_| {
DomainChangerError::InvalidNewDomain(format!(
"'{}', is invalid new domain",
domains.1
))
})?,
})
}
}
#[cfg(test)]
mod tests {
use crate::types::{errors::DomainChangerResult, Domain};
#[test]
fn domain_tryfrom_test() {
let domain: DomainChangerResult<Domain> =
Domain::try_from(("twitter.com", "https://nitter.net"));
assert!(domain.err().unwrap().is_invalid_old_domain());
let domain: DomainChangerResult<Domain> =
Domain::try_from(("https://twitter.com", "nitter.net"));
assert!(domain.err().unwrap().is_invalid_new_domain());
}
}