Skip to main content

aria2_core/engine/
download_cookie.rs

1use std::sync::Arc;
2
3use crate::http::cookie::Cookie;
4use crate::http::cookie_storage::CookieStorage;
5
6#[derive(Clone)]
7pub struct CookieHelper {
8    cookie_storage: Arc<CookieStorage>,
9    cookie_file: Option<String>,
10}
11
12impl CookieHelper {
13    pub fn new(cookie_storage: Arc<CookieStorage>, cookie_file: Option<String>) -> Self {
14        Self {
15            cookie_storage,
16            cookie_file,
17        }
18    }
19
20    pub fn build_cookie_header(&self, uri: &str) -> Option<String> {
21        let url_parsed = reqwest::Url::parse(uri).ok()?;
22        let host = url_parsed.host_str()?;
23        let path = url_parsed.path();
24        let secure = url_parsed.scheme() == "https";
25        let hdr = self.cookie_storage.to_header_string(host, path, secure);
26        if hdr.is_empty() { None } else { Some(hdr) }
27    }
28
29    pub fn build_cookie_header_from_url(&self, url: &reqwest::Url) -> String {
30        let host = url.host_str().unwrap_or("");
31        let path = url.path();
32        let secure = url.scheme() == "https";
33        self.cookie_storage.to_header_string(host, path, secure)
34    }
35
36    pub fn extract_and_store_cookies(&self, uri: &str, response: &reqwest::Response) {
37        let url_parsed = reqwest::Url::parse(uri).ok();
38        if let Some(ref url) = url_parsed {
39            let domain = url.host_str().unwrap_or("");
40            let path = url.path();
41            for sc_val in response.headers().get_all("set-cookie").iter() {
42                if let Ok(sc_str) = sc_val.to_str()
43                    && let Some(c) = Cookie::from_set_cookie_header(sc_str, domain, path)
44                {
45                    self.cookie_storage.add(c);
46                    tracing::debug!("Received Set-Cookie: {}", sc_str);
47                }
48            }
49        }
50    }
51
52    pub fn save_cookies_if_configured(&self) {
53        if let Some(ref cf) = self.cookie_file {
54            if let Err(e) = self.cookie_storage.save_file(std::path::Path::new(cf)) {
55                tracing::warn!("Failed to save cookie file {}: {}", cf, e);
56            } else {
57                tracing::info!("Cookies saved to {}", cf);
58            }
59        }
60    }
61}