aria2-core 0.3.13

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
Documentation
use std::fs;
use std::path::Path;

use crate::error::{Aria2Error, Result};
use crate::http::ns_cookie_parser::NsCookieParser;
use crate::http::sqlite_cookie_parser::{Sqlite3CookieParser, is_sqlite_file};

use super::CookieStorage;

impl CookieStorage {
    /// Load cookies from a Netscape-format file or a browser SQLite cookie jar.
    ///
    /// The format is detected from the file's first 16 bytes rather than its
    /// name. Parsed cookies pass through `add`, which handles deduplication and
    /// eviction.
    pub fn load_file(&self, path: &Path) -> Result<usize> {
        let bytes = fs::read(path).map_err(|error| Aria2Error::Io(error.to_string()))?;

        let parsed = if is_sqlite_file(&bytes) {
            Sqlite3CookieParser::parse_auto(path)?
        } else {
            let text = String::from_utf8_lossy(&bytes);
            NsCookieParser::parse_str(&text)?
        };

        let count = parsed.len();
        for cookie in parsed {
            self.add(cookie);
        }
        Ok(count)
    }

    /// Save cookies to a Netscape-format file using a temporary file and rename.
    pub fn save_file(&self, path: &Path) -> Result<()> {
        let mut temp_path = path.to_path_buf();
        temp_path.set_extension("tmp");

        {
            let domains = self
                .domains
                .read()
                .unwrap_or_else(|error| error.into_inner());
            let lru = self
                .lru_tracker
                .read()
                .unwrap_or_else(|error| error.into_inner());

            let mut lines = Vec::with_capacity(self.count() + 3);
            lines.push("# Netscape HTTP Cookie File".to_string());
            lines.push("# This file is generated by aria2-rust".to_string());

            for (_, domain_key) in lru.iter() {
                if let Some(bucket) = domains.get(domain_key) {
                    lines.extend(
                        bucket
                            .cookies
                            .iter()
                            .map(|cookie| cookie.to_netscape_line()),
                    );
                }
            }

            fs::write(&temp_path, lines.join("\n"))
                .map_err(|error| Aria2Error::Io(error.to_string()))?;
        }

        fs::rename(&temp_path, path).map_err(|error| Aria2Error::Io(error.to_string()))?;
        Ok(())
    }
}