1use psl::{List, Psl};
7use scraper::Selector;
8use std::fs;
9use std::path::Path;
10use url::Url;
11
12use crate::error::SpiderError;
13use crate::request::Request;
14
15pub fn is_same_site(a: &Url, b: &Url) -> bool {
17 a.host_str().and_then(|h| List.domain(h.as_bytes()))
18 == b.host_str().and_then(|h| List.domain(h.as_bytes()))
19}
20
21pub fn normalize_origin(request: &Request) -> String {
23 let url = &request.url;
24 let scheme = url.scheme();
25 let host = url.host_str().unwrap_or("");
26 let port = url.port_or_known_default().unwrap_or(0);
27
28 format!("{scheme}://{host}:{port}")
29}
30
31pub fn validate_output_dir(file_path: impl AsRef<Path>) -> Result<(), SpiderError> {
37 let Some(parent_dir) = file_path.as_ref().parent() else {
38 return Ok(());
39 };
40
41 if !parent_dir.as_os_str().is_empty() && !parent_dir.exists() {
42 fs::create_dir_all(parent_dir)?;
43 }
44
45 Ok(())
46}
47
48pub fn create_dir(dir_path: impl AsRef<Path>) -> Result<(), SpiderError> {
54 fs::create_dir_all(dir_path)?;
55 Ok(())
56}
57
58pub trait ToSelector {
60 fn to_selector(&self) -> Result<Selector, SpiderError>;
66}
67
68impl ToSelector for &str {
69 fn to_selector(&self) -> Result<Selector, SpiderError> {
70 Selector::parse(self).map_err(|e| SpiderError::HtmlParseError(e.to_string()))
71 }
72}
73
74impl ToSelector for String {
75 fn to_selector(&self) -> Result<Selector, SpiderError> {
76 Selector::parse(self).map_err(|e| SpiderError::HtmlParseError(e.to_string()))
77 }
78}