Files
bytesize/src-tauri/src/bootstrap.rs
T

349 lines
10 KiB
Rust

use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, Context, Result};
use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FfmpegStatus {
Ready,
Missing,
}
pub fn bin_dir(app_dir: &Path) -> PathBuf {
app_dir.join("bin")
}
pub fn ffmpeg_path(app_dir: &Path) -> PathBuf {
bin_dir(app_dir).join("ffmpeg.exe")
}
pub fn check(app_dir: &Path) -> FfmpegStatus {
if ffmpeg_path(app_dir).is_file() {
FfmpegStatus::Ready
} else {
FfmpegStatus::Missing
}
}
#[derive(Clone, Copy)]
enum ArchiveKind {
SevenZ,
Zip,
}
struct Source {
name: &'static str,
release_api_url: &'static str,
asset_name_suffix: &'static str,
kind: ArchiveKind,
}
const SOURCES: &[Source] = &[
Source {
name: "GyanD",
release_api_url: "https://api.github.com/repos/GyanD/codexffmpeg/releases/tags/latest",
asset_name_suffix: "full_build.7z",
kind: ArchiveKind::SevenZ,
},
Source {
name: "BtbN",
release_api_url: "https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/tags/latest",
asset_name_suffix: "win64-gpl.zip",
kind: ArchiveKind::Zip,
},
];
#[derive(Debug, Deserialize)]
struct GithubRelease {
tag_name: String,
assets: Vec<GithubAsset>,
}
#[derive(Debug, Deserialize)]
struct GithubAsset {
name: String,
browser_download_url: String,
}
pub async fn download<F>(app_dir: &Path, mut on_progress: F) -> Result<()>
where
F: FnMut(u64, Option<u64>) + Send,
{
let bin = bin_dir(app_dir);
fs::create_dir_all(&bin).context("creating ./bin/")?;
let dest = bin.join("ffmpeg.exe");
let mut last_err: Option<anyhow::Error> = None;
for source in SOURCES {
match try_source(source, &dest, &mut on_progress).await {
Ok(()) => {
tracing::info!("ffmpeg installed via {}", source.name);
return Ok(());
}
Err(e) => {
tracing::warn!("source {} failed: {e:#}", source.name);
last_err = Some(e);
}
}
}
Err(last_err.unwrap_or_else(|| anyhow!("no ffmpeg source succeeded")))
}
async fn try_source<F>(source: &Source, dest: &Path, on_progress: &mut F) -> Result<()>
where
F: FnMut(u64, Option<u64>),
{
let client = reqwest::Client::builder()
.user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION")))
.build()?;
let (asset, version) = pick_asset(&client, source).await?;
// GyanD publishes a .sha256 file alongside each release.
// BtbN does not, so we skip verification for BtbN.
let expected = if source.name == "GyanD" {
let checksum_url = format!(
"https://github.com/GyanD/codexffmpeg/releases/download/{}/{}.sha256",
version,
asset.name
);
Some(fetch_sha256(&client, &checksum_url).await?)
} else {
tracing::warn!("BtbN build: skipping SHA-256 verification (no checksum file)");
None
};
let app_dir = dest
.parent()
.and_then(|p| p.parent())
.context("invalid dest path for temp archive")?;
let scratch_dir = app_dir.join("temp");
fs::create_dir_all(&scratch_dir).context("creating temp dir for archive")?;
let archive_path = scratch_dir.join(format!(
"ffmpeg-archive-{}.tmp",
source.name.to_lowercase()
));
if let Some(ref hash) = expected {
download_verified(
&client,
&asset.browser_download_url,
hash,
&archive_path,
on_progress,
)
.await
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
} else {
download_plain(&client, &asset.browser_download_url, &archive_path, on_progress)
.await
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
};
let result = match source.kind {
ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest),
ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive_path, dest),
};
drop(fs::remove_file(&archive_path));
result
}
/// Fetch and parse a SHA-256 checksums file from GyanD.
/// The file contains a line like:
/// abc123def456... ffmpeg-8.1.1-full_build.7z
async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> {
let resp = client.get(url).send().await?.error_for_status()?;
let text = resp.text().await?;
// Each line is: "<hex> <filename>" - find the line with our filename
let hash_str = text
.lines()
.find_map(|line| {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return None;
}
// SHA-256 hex is 64 chars, followed by spaces and the filename
if line.len() < 64 {
return None;
}
let (hash, _file) = line.split_at(64);
let remainder = _file.trim_start();
// Must be followed by two spaces and a filename
if !remainder.starts_with(" ") {
return None;
}
Some(hash)
})
.ok_or_else(|| anyhow!("SHA-256 for this build not found in checksums file"))?;
let bytes = hex::decode(hash_str).context("checksum is not valid hex")?;
if bytes.len() != 32 {
bail!("checksum length is {} bytes, expected 32", bytes.len());
}
let mut sha = [0u8; 32];
sha.copy_from_slice(&bytes);
Ok(sha)
}
async fn download_plain<F>(
client: &reqwest::Client,
url: &str,
dest: &Path,
mut on_progress: F,
) -> Result<()>
where
F: FnMut(u64, Option<u64>),
{
let resp = client.get(url).send().await?.error_for_status()?;
let total = resp.content_length();
let mut file = std::fs::File::create(dest).context("creating archive temp file")?;
let mut downloaded = 0u64;
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
file.write_all(&chunk)?;
downloaded += chunk.len() as u64;
on_progress(downloaded, total);
}
file.flush()?;
Ok(())
}
async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(GithubAsset, String)> {
let resp = client
.get(source.release_api_url)
.header("Accept", "application/vnd.github+json")
.send()
.await?
.error_for_status()?;
let body = resp.text().await?;
let release: GithubRelease =
serde_json::from_str(&body).context("parsing release metadata")?;
let version = release
.tag_name
.trim_start_matches('v')
.to_string();
let asset = release
.assets
.into_iter()
.find(|a| a.name.ends_with(source.asset_name_suffix))
.ok_or_else(|| {
anyhow!(
"no asset matching '*{}' in release",
source.asset_name_suffix
)
})?;
Ok((asset, version))
}
async fn download_verified<F>(
client: &reqwest::Client,
url: &str,
expected: &[u8; 32],
dest: &Path,
on_progress: &mut F,
) -> Result<()>
where
F: FnMut(u64, Option<u64>),
{
let resp = client.get(url).send().await?.error_for_status()?;
let total = resp.content_length();
let mut hasher = Sha256::new();
let mut file = std::fs::File::create(dest).context("creating archive temp file")?;
let mut downloaded = 0u64;
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
hasher.update(&chunk);
file.write_all(&chunk)?;
downloaded += chunk.len() as u64;
on_progress(downloaded, total);
}
file.flush()?;
let got: [u8; 32] = hasher.finalize().into();
if &got != expected {
drop(std::fs::remove_file(dest));
bail!(
"sha256 mismatch: expected {} got {}",
hex::encode(expected),
hex::encode(got)
);
}
Ok(())
}
fn is_ffmpeg_entry(name: &str) -> bool {
let normalized: String = name
.chars()
.map(|c| if c == '\\' { '/' } else { c })
.collect();
normalized
.rsplit('/')
.next()
.map(|leaf| leaf.eq_ignore_ascii_case("ffmpeg.exe"))
.unwrap_or(false)
}
fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> {
let app_dir = dest
.parent()
.and_then(|p| p.parent())
.context("invalid dest path")?;
let scratch = app_dir.join("temp").join("ffmpeg-extract");
drop(fs::remove_dir_all(&scratch));
fs::create_dir_all(&scratch).context("create 7z scratch dir")?;
let file = std::fs::File::open(archive_path).context("opening 7z archive")?;
let extract_result =
sevenz_rust2::decompress_with_extract_fn(file, &scratch, |_, _, _| Ok(true))
.map_err(|e| anyhow!("7z extraction failed: {e}"));
let found = find_ffmpeg_in(&scratch);
drop(fs::remove_dir_all(&scratch));
extract_result?;
let Some(src) = found else {
bail!("ffmpeg.exe not found inside the 7z archive");
};
fs::copy(&src, dest).context("write ffmpeg.exe from 7z")?;
Ok(())
}
fn find_ffmpeg_in(dir: &Path) -> Option<PathBuf> {
let entries = fs::read_dir(dir).ok()?;
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
if let Some(found) = find_ffmpeg_in(&p) {
return Some(found);
}
} else if let Some(name) = p.file_name() {
if is_ffmpeg_entry(&name.to_string_lossy()) {
return Some(p);
}
}
}
None
}
fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> {
let file = std::fs::File::open(archive_path).context("opening zip archive")?;
let mut zip = zip::ZipArchive::new(file).context("open zip archive")?;
for i in 0..zip.len() {
let mut entry = zip.by_index(i)?;
if entry.is_dir() {
continue;
}
let name = entry.name().to_string();
if is_ffmpeg_entry(&name) {
let mut out = File::create(dest).context("create ffmpeg.exe")?;
io::copy(&mut entry, &mut out).context("write ffmpeg.exe from zip")?;
return Ok(());
}
}
bail!("ffmpeg.exe not found inside the zip archive");
}