1use crate::{Request, SpiderError};
14use psl::{List, Psl};
15use scraper::Selector;
16use std::fs;
17use std::path::Path;
18use url::Url;
19
20pub fn normalize_origin(request: &Request) -> String {
22 let url = &request.url;
23 let scheme = url.scheme();
24 let host = url.host_str().unwrap_or("");
25 let port = url.port_or_known_default().unwrap_or(0);
26
27 format!("{scheme}://{host}:{port}")
28}
29pub fn is_same_site(a: &Url, b: &Url) -> bool {
31 a.host_str().and_then(|h| List.domain(h.as_bytes()))
32 == b.host_str().and_then(|h| List.domain(h.as_bytes()))
33}
34
35pub 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> {
50 fs::create_dir_all(dir_path)?;
51 Ok(())
52}
53
54pub trait ToSelector {
55 fn to_selector(&self) -> Result<Selector, SpiderError>;
57}
58
59impl ToSelector for &str {
60 fn to_selector(&self) -> Result<Selector, SpiderError> {
61 Selector::parse(self).map_err(|e| SpiderError::HtmlParseError(e.to_string()))
62 }
63}
64
65impl ToSelector for String {
66 fn to_selector(&self) -> Result<Selector, SpiderError> {
67 Selector::parse(self).map_err(|e| SpiderError::HtmlParseError(e.to_string()))
68 }
69}