1use crate::{Request, SpiderError};
2use psl::{List, Psl};
3use scraper::Selector;
4use std::fs;
5use std::path::Path;
6use url::Url;
7
8pub fn normalize_origin(request: &Request) -> String {
10 let url = &request.url;
11 let scheme = url.scheme();
12 let host = url.host_str().unwrap_or("");
13 let port = url.port_or_known_default().unwrap_or(0);
14
15 format!("{scheme}://{host}:{port}")
16}
17pub fn is_same_site(a: &Url, b: &Url) -> bool {
19 a.host_str().and_then(|h| List.domain(h.as_bytes()))
20 == b.host_str().and_then(|h| List.domain(h.as_bytes()))
21}
22
23pub fn validate_output_dir(file_path: impl AsRef<Path>) -> Result<(), SpiderError> {
25 let Some(parent_dir) = file_path.as_ref().parent() else {
26 return Ok(());
27 };
28
29 if !parent_dir.as_os_str().is_empty() && !parent_dir.exists() {
30 fs::create_dir_all(parent_dir)?;
31 }
32
33 Ok(())
34}
35
36pub fn create_dir(dir_path: impl AsRef<Path>) -> Result<(), SpiderError> {
38 fs::create_dir_all(dir_path)?;
39 Ok(())
40}
41
42pub trait ToSelector {
43 fn to_selector(&self) -> Result<Selector, SpiderError>;
45}
46
47impl ToSelector for &str {
48 fn to_selector(&self) -> Result<Selector, SpiderError> {
49 Selector::parse(self).map_err(|e| SpiderError::HtmlParseError(e.to_string()))
50 }
51}
52
53impl ToSelector for String {
54 fn to_selector(&self) -> Result<Selector, SpiderError> {
55 Selector::parse(self).map_err(|e| SpiderError::HtmlParseError(e.to_string()))
56 }
57}