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 {
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)
}
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(())
}
}