Aurora-Print/Core/chromium/download.rs

86 lines
2.8 KiB
Rust

use std::{fs, io, path::{Path, PathBuf}};
use reqwest::blocking::Client;
use super::utils::extract_zip; // <-- statt util
#[cfg(target_os = "windows")]
const PLATFORM_DIR: &str = "Win_x64";
#[cfg(target_os = "linux")]
const PLATFORM_DIR: &str = "Linux_x64";
#[cfg(target_os = "macos")]
const PLATFORM_DIR: &str = "Mac";
fn zip_name() -> &'static str {
#[cfg(target_os = "windows")] { "chrome-win.zip" }
#[cfg(target_os = "linux")] { "chrome-linux.zip" }
#[cfg(target_os = "macos")] { "chrome-mac.zip" }
}
fn bin_relative_path() -> &'static str {
#[cfg(target_os = "windows")] { "chrome-win/chrome.exe" }
#[cfg(target_os = "linux")] { "chrome-linux/chrome" }
#[cfg(target_os = "macos")] { "chrome-mac/Chromium.app/Contents/MacOS/Chromium" }
}
fn fetch_latest_revision(client: &Client) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
let url = format!(
"https://storage.googleapis.com/chromium-browser-snapshots/{}/LAST_CHANGE",
PLATFORM_DIR
);
let txt = client.get(url).send()?.error_for_status()?.text()?;
Ok(txt.trim().to_string())
}
pub fn find_latest_local(cache_dir: &Path) -> io::Result<Option<PathBuf>> {
let mut best: Option<(u64, PathBuf)> = None;
if !cache_dir.exists() { return Ok(None); }
for entry in fs::read_dir(cache_dir)? {
let entry = entry?;
if !entry.file_type()?.is_dir() { continue; }
let name = entry.file_name().to_string_lossy().to_string();
if let Ok(n) = name.parse::<u64>() {
let bin = entry.path().join(bin_relative_path());
if bin.exists() {
if let Some((best_n, _)) = best {
if n > best_n { best = Some((n, bin)); }
} else {
best = Some((n, bin));
}
}
}
}
Ok(best.map(|(_, p)| p))
}
fn download_to(client: &Client, url: &str, dest: &Path) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut resp = client.get(url).send()?.error_for_status()?;
let mut file = fs::File::create(dest)?;
io::copy(&mut resp, &mut file)?;
Ok(())
}
pub fn get_or_install_latest(cache_dir: &Path) -> Result<PathBuf, Box<dyn std::error::Error + Send + Sync>>
{
fs::create_dir_all(cache_dir)?;
let client = Client::builder().build()?;
let rev = fetch_latest_revision(&client)?;
let rev_dir = cache_dir.join(&rev);
let bin_path = rev_dir.join(bin_relative_path());
if bin_path.exists() {
return Ok(bin_path);
}
let url = format!(
"https://storage.googleapis.com/chromium-browser-snapshots/{}/{}/{}",
PLATFORM_DIR, rev, zip_name()
);
let zip_path = cache_dir.join(format!("chromium-{}.zip", rev));
if !zip_path.exists() {
download_to(&client, &url, &zip_path)?;
}
extract_zip(&zip_path, &rev_dir)?;
Ok(bin_path)
}