use std::collections::HashSet;
use crate::constants::EXTRA_RESOURCES;
pub fn should_block_resource(resource_type: &str, disable_resources: bool) -> bool {
if !disable_resources {
return false;
}
EXTRA_RESOURCES.contains(&resource_type)
}
pub fn is_domain_blocked(hostname: &str, blocked_domains: &HashSet<String>) -> bool {
if blocked_domains.is_empty() {
return false;
}
if blocked_domains.contains(hostname) {
return true;
}
let mut parts: &str = hostname;
while let Some(pos) = parts.find('.') {
parts = &parts[pos + 1..];
if blocked_domains.contains(parts) {
return true;
}
}
false
}
pub fn should_block_request(
resource_type: &str,
url: &str,
disable_resources: bool,
blocked_domains: &HashSet<String>,
) -> bool {
if should_block_resource(resource_type, disable_resources) {
return true;
}
if !blocked_domains.is_empty() {
if let Ok(parsed) = url::Url::parse(url) {
if let Some(host) = parsed.host_str() {
return is_domain_blocked(&host.to_lowercase(), blocked_domains);
}
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resource_blocking() {
assert!(should_block_resource("font", true));
assert!(should_block_resource("image", true));
assert!(should_block_resource("stylesheet", true));
assert!(!should_block_resource("document", true));
assert!(!should_block_resource("font", false));
}
#[test]
fn domain_blocking_exact() {
let mut domains = HashSet::new();
domains.insert("ads.example.com".to_owned());
assert!(is_domain_blocked("ads.example.com", &domains));
assert!(!is_domain_blocked("example.com", &domains));
}
#[test]
fn domain_blocking_suffix() {
let mut domains = HashSet::new();
domains.insert("doubleclick.net".to_owned());
assert!(is_domain_blocked("ad.doubleclick.net", &domains));
assert!(is_domain_blocked("sub.ad.doubleclick.net", &domains));
assert!(is_domain_blocked("doubleclick.net", &domains));
assert!(!is_domain_blocked("notdoubleclick.net", &domains));
}
#[test]
fn domain_blocking_empty() {
let domains = HashSet::new();
assert!(!is_domain_blocked("anything.com", &domains));
}
#[test]
fn should_block_request_combined() {
let mut domains = HashSet::new();
domains.insert("tracker.com".to_owned());
assert!(should_block_request(
"document",
"https://tracker.com/pixel",
false,
&domains
));
assert!(should_block_request(
"font",
"https://cdn.com/font.woff",
true,
&domains
));
assert!(!should_block_request(
"document",
"https://example.com",
false,
&domains
));
}
}