A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
//! Add-ons: separate programs rustyfiles can install on the user's click and talk to (the first: HyperDownload, the download
//! manager, `gelenmedya/hyperdownload`). An add-on is never code loaded into rustyfiles: it is a program of its own in its own
//! folder, so its licence and its crashes stay apart.
//!
//! WHERE THEY COME FROM. The list is `addons.json` in rustyfiles' own repository: each add-on's version and, for each processor,
//! the URL of its zip (a GitHub release of the add-on's repository) and that zip's SHA-256. A zip whose SHA-256 is not the listed one
//! is not installed. Nothing is downloaded until the user clicks Install or Update.
//!
//! WHERE THEY GO. `<local data>\addons\<id>\<version>\` (local data: `%LOCALAPPDATA%\rustyfiles`, or the portable copy's own
//! `data` folder), with `<local data>\addons\<id>\installed.json` naming the version that is in use. An update unpacks the new
//! version beside the old one and then switches `installed.json`, so a failed update leaves the old one working.
//!
//! `RUSTYFILES_ADDONS_MANIFEST` names another list (a URL, or a file path) for testing.
use std::io::Read;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
pub const MANIFEST_URL: &str = "https://raw.githubusercontent.com/gelenmedya/rustyfiles/main/addons.json";
#[derive(Clone, Debug, Deserialize)]
pub struct Manifest {
pub addons: Vec<AddonInfo>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct AddonInfo {
pub id: String,
pub name: String,
pub version: String,
pub license: String,
/// The source code (shown as a link).
pub source: String,
/// One per processor: "x64", "arm64".
#[serde(default)]
pub files: std::collections::HashMap<String, FileRef>,
/// The add-on's browser extension for this version: a zip with the extension's files at its top (HyperDownload). It is loaded
/// by hand in the browser until it is in the stores; Settings puts the folder ready ([`install_extension`]).
#[serde(default)]
pub extension: Option<FileRef>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct FileRef {
pub url: String,
pub sha256: String,
#[serde(default)]
pub size: u64,
}
/// What `installed.json` says.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Installed {
pub version: String,
/// The program to start, relative to the version's folder.
pub exe: String,
}
/// This machine's processor as the list names it.
pub fn arch() -> &'static str {
if cfg!(target_arch = "aarch64") { "arm64" } else { "x64" }
}
impl AddonInfo {
/// The zip for this machine, if the add-on has one.
pub fn file(&self) -> Option<&FileRef> {
self.files.get(arch())
}
}
/// `<local data>\addons`.
pub fn root() -> Option<PathBuf> {
crate::settings::local_data_dir().map(|d| d.join("addons"))
}
pub(crate) fn dir_of(id: &str) -> Option<PathBuf> {
// (an id from the list becomes a folder name: only plain names)
(!id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')).then(|| root().map(|r| r.join(id))).flatten()
}
/// The version of `id` that is installed, if one is.
pub fn installed(id: &str) -> Option<Installed> {
let d = dir_of(id)?;
let i: Installed = serde_json::from_slice(&std::fs::read(d.join("installed.json")).ok()?).ok()?;
d.join(&i.version).join(&i.exe).is_file().then_some(i)
}
/// The folder name of an add-on's browser extension, beside its version folders.
const EXTENSION_DIR: &str = "extension";
/// Where the browser extension of `id` is unpacked. ONE place for every version: a browser remembers an extension loaded by hand
/// by its folder, so the folder must not move when the add-on is updated.
pub fn extension_dir(id: &str) -> Option<PathBuf> {
dir_of(id).map(|d| d.join(EXTENSION_DIR))
}
/// The version of the extension unpacked in `dir` (its manifest's "version"), when there is one.
fn extension_version_in(dir: &Path) -> Option<String> {
let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join(EXTENSION_DIR).join("manifest.json")).ok()?).ok()?;
manifest.get("version")?.as_str().map(str::to_string)
}
/// The version of `id`'s extension that is unpacked, when one is.
pub fn extension_version(id: &str) -> Option<String> {
extension_version_in(&dir_of(id)?)
}
/// Brings `file` (the extension's zip), checks its SHA-256 and unpacks it into `dir`'s extension folder, in place of what was
/// there. Gives the folder. A zip that is not the listed one, or that has no manifest.json at its top, changes nothing.
fn unpack_extension(dir: &Path, file: &FileRef, cancelled: &dyn Fn() -> bool) -> Result<PathBuf, String> {
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
let zip = dir.join(".extension.zip");
let sha = match download(&file.url, &zip, file.size, &|_| {}, cancelled) {
Ok(s) => s,
Err(e) => {
let _ = std::fs::remove_file(&zip);
return Err(e);
}
};
if !sha.eq_ignore_ascii_case(file.sha256.trim()) {
let _ = std::fs::remove_file(&zip);
return Err("the download is not the file the list names (its SHA-256 differs): it was not unpacked".into());
}
let staging = dir.join(".extension.tmp");
let _ = std::fs::remove_dir_all(&staging);
let unpacked = rf_archive::extract(&zip, &staging, &mut |_| {}, cancelled);
let _ = std::fs::remove_file(&zip);
if let Err(e) = unpacked {
let _ = std::fs::remove_dir_all(&staging);
return Err(e.to_string());
}
if !staging.join("manifest.json").is_file() {
let _ = std::fs::remove_dir_all(&staging);
return Err("manifest.json is not at the top of the extension's zip".into());
}
let target = dir.join(EXTENSION_DIR);
if target.exists() {
std::fs::remove_dir_all(&target).map_err(|e| format!("{}: {e}", target.display()))?;
}
std::fs::rename(&staging, &target).map_err(|e| e.to_string())?;
Ok(target)
}
/// Puts the browser extension of `info` ready in its folder ([`extension_dir`]): downloaded, checked, unpacked. Blocking.
pub fn install_extension(info: &AddonInfo, cancelled: &dyn Fn() -> bool) -> Result<PathBuf, String> {
let file = info.extension.as_ref().ok_or_else(|| format!("{} has no browser extension in the list", info.name))?;
let dir = dir_of(&info.id).ok_or("no folder for add-ons")?;
unpack_extension(&dir, file, cancelled)
}
/// The installed program of `id`.
pub fn program(id: &str) -> Option<PathBuf> {
let i = installed(id)?;
Some(dir_of(id)?.join(&i.version).join(&i.exe))
}
/// Whether `a` is a newer version than `b` (dotted numbers; a part that is not a number counts as 0).
pub fn newer(a: &str, b: &str) -> bool {
let parts = |v: &str| -> Vec<u64> { v.trim_start_matches('v').split(['.', '-']).take(3).map(|p| p.parse().unwrap_or(0)).collect() };
parts(a) > parts(b)
}
/// How long one request may take to bring its body. It covers the WHOLE body, not a pause in it, which is why a download asks
/// again for the rest when it runs out ([`download`]).
const BODY_LIMIT: std::time::Duration = std::time::Duration::from_secs(60);
fn agent() -> ureq::Agent {
agent_with(BODY_LIMIT)
}
fn agent_with(body_limit: std::time::Duration) -> ureq::Agent {
ureq::Agent::config_builder()
.timeout_connect(Some(std::time::Duration::from_secs(15)))
.timeout_recv_body(Some(body_limit))
.http_status_as_error(false)
.tls_config(ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::PlatformVerifier).build())
.build()
.into()
}
/// Reads the list (blocking: call it off the UI thread).
pub fn fetch_manifest() -> Result<Manifest, String> {
let from = std::env::var("RUSTYFILES_ADDONS_MANIFEST").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| MANIFEST_URL.to_string());
let bytes = if from.starts_with("http://") || from.starts_with("https://") {
let resp = agent().get(&from).call().map_err(|e| e.to_string())?;
if resp.status().as_u16() != 200 {
return Err(format!("HTTP {}", resp.status().as_u16()));
}
let mut v = Vec::new();
resp.into_body().into_reader().take(1 << 20).read_to_end(&mut v).map_err(|e| e.to_string())?;
v
} else {
std::fs::read(&from).map_err(|e| format!("{from}: {e}"))?
};
serde_json::from_slice(&bytes).map_err(|e| e.to_string())
}
/// Where a download is written: the file, the hash of what is in it and how much that is.
struct Sink<'a> {
out: std::fs::File,
hash: Sha256,
done: u64,
progress: &'a dyn Fn(u64),
}
impl Sink<'_> {
fn take(&mut self, bytes: &[u8]) -> Result<(), String> {
std::io::Write::write_all(&mut self.out, bytes).map_err(|e| e.to_string())?;
self.hash.update(bytes);
self.done += bytes.len() as u64;
(self.progress)(self.done);
Ok(())
}
/// From the file's start again (a server that does not continue a file sends it whole).
fn restart(&mut self) -> Result<(), String> {
use std::io::Seek;
self.out.set_len(0).map_err(|e| e.to_string())?;
self.out.rewind().map_err(|e| e.to_string())?;
self.hash = Sha256::new();
self.done = 0;
(self.progress)(0);
Ok(())
}
}
/// How one request for a file ended: the server sent all it had, or the transfer broke off (with the reason).
enum Got {
All,
Cut(String),
}
/// One request for `url` from the byte the sink stands at. A transfer that breaks off is not an error here: the caller asks again
/// from where it stopped.
fn fetch(url: &str, sink: &mut Sink, body_limit: std::time::Duration, cancelled: &dyn Fn() -> bool) -> Result<Got, String> {
let from = sink.done;
let mut req = agent_with(body_limit).get(url);
if from > 0 {
req = req.header("Range", format!("bytes={from}-"));
}
let resp = match req.call() {
Ok(r) => r,
Err(e) => return Ok(Got::Cut(e.to_string())),
};
match (resp.status().as_u16(), from) {
(200, 0) | (206, _) => {}
(200, _) => sink.restart()?,
(status, _) => return Err(format!("HTTP {status}")),
}
let mut reader = resp.into_body().into_reader();
let mut buf = vec![0u8; 256 * 1024];
loop {
if cancelled() {
return Err("cancelled".into());
}
match reader.read(&mut buf) {
Ok(0) => return Ok(Got::All),
Ok(n) => sink.take(&buf[..n])?,
Err(e) => return Ok(Got::Cut(e.to_string())),
}
}
}
/// How many requests in a row may bring nothing new before a download is given up.
const DRY_TRIES: u32 = 3;
/// The bytes of `url` (a URL, or for testing a file path) into `to`, with the bytes so far told to `progress`; the SHA-256 of what
/// was written. `total` is the size the list names (0: not known).
///
/// A TRANSFER THAT BREAKS OFF IS CONTINUED (issue 1042: "timeout: receive body" at every try, on a connection that brings 50 to
/// 300 KB/s). The time limit of a request covers its whole body, so a 7 MB file never arrived within it, and each try began again
/// from nothing. Now the next request asks for the rest (`Range`), the file and its hash go on from where they stood, and the
/// download is given up only when [`DRY_TRIES`] requests in a row bring nothing. The SHA-256 check afterwards is unchanged, so a
/// file put together wrongly is still refused.
fn download(url: &str, to: &Path, total: u64, progress: &dyn Fn(u64), cancelled: &dyn Fn() -> bool) -> Result<String, String> {
download_within(BODY_LIMIT, url, to, total, progress, cancelled)
}
/// [`download`] with the time one request may take (the tests use a short one).
fn download_within(body_limit: std::time::Duration, url: &str, to: &Path, total: u64, progress: &dyn Fn(u64), cancelled: &dyn Fn() -> bool) -> Result<String, String> {
let out = std::fs::File::create(to).map_err(|e| format!("{}: {e}", to.display()))?;
let mut sink = Sink { out, hash: Sha256::new(), done: 0, progress };
if !(url.starts_with("http://") || url.starts_with("https://")) {
let mut reader = std::fs::File::open(url).map_err(|e| format!("{url}: {e}"))?;
let mut buf = vec![0u8; 256 * 1024];
loop {
if cancelled() {
return Err("cancelled".into());
}
let n = reader.read(&mut buf).map_err(|e| e.to_string())?;
if n == 0 {
break;
}
sink.take(&buf[..n])?;
}
} else {
let mut dry = 0u32;
while total == 0 || sink.done < total {
let before = sink.done;
let why = match fetch(url, &mut sink, body_limit, cancelled)? {
Got::All if total == 0 || sink.done >= total => break,
Got::All => "the connection closed before the file was complete".to_string(),
Got::Cut(e) => e,
};
if sink.done > before {
dry = 0;
} else {
dry += 1;
if dry >= DRY_TRIES {
return Err(why);
}
std::thread::sleep(std::time::Duration::from_millis(400 * u64::from(dry)));
}
log::info!("add-on download: broke off at {} of {total} bytes ({why}); asking for the rest", sink.done);
}
}
Ok(sink.hash.finalize().iter().map(|b| format!("{b:02x}")).collect())
}
/// Installs (or updates to) `info`'s version for this machine: download, SHA-256 check, unpack beside any older version, switch
/// `installed.json`, remove the older versions. Blocking.
pub fn install(info: &AddonInfo, progress: &dyn Fn(u64, u64), cancelled: &dyn Fn() -> bool) -> Result<Installed, String> {
let file = info.file().ok_or_else(|| format!("no {} build of {}", arch(), info.name))?;
let dir = dir_of(&info.id).ok_or("no folder for add-ons")?;
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let zip = dir.join(".download.zip");
let total = file.size;
let got = download(&file.url, &zip, total, &|n| progress(n, total), cancelled);
let sha = match got {
Ok(s) => s,
Err(e) => {
let _ = std::fs::remove_file(&zip);
// (nothing of an add-on that never arrived stays behind: an empty folder looked like a half install, issue 1042.
// `remove_dir` takes an empty folder only, so an installed version is safe)
let _ = std::fs::remove_dir(&dir);
return Err(e);
}
};
if !sha.eq_ignore_ascii_case(file.sha256.trim()) {
let _ = std::fs::remove_file(&zip);
return Err("the download is not the file the list names (its SHA-256 differs): it was not installed".into());
}
let staging = dir.join(format!(".{}.tmp", info.version));
let _ = std::fs::remove_dir_all(&staging);
let unpacked = rf_archive::extract(&zip, &staging, &mut |_| {}, cancelled);
let _ = std::fs::remove_file(&zip);
if let Err(e) = unpacked {
let _ = std::fs::remove_dir_all(&staging);
return Err(e.to_string());
}
let exe = format!("{}.exe", info.id);
if !staging.join(&exe).is_file() {
let _ = std::fs::remove_dir_all(&staging);
return Err(format!("{exe} is not in the zip"));
}
let target = dir.join(&info.version);
let _ = std::fs::remove_dir_all(&target);
std::fs::rename(&staging, &target).map_err(|e| e.to_string())?;
let now = Installed { version: info.version.clone(), exe };
std::fs::write(dir.join("installed.json"), serde_json::to_vec_pretty(&now).unwrap_or_default()).map_err(|e| e.to_string())?;
// the older versions (one still running keeps its files until it ends: what cannot be removed now is left)
if let Ok(rd) = std::fs::read_dir(&dir) {
for e in rd.flatten() {
let n = e.file_name().to_string_lossy().into_owned();
// (the browser extension's folder is no version: it stays where the browser knows it)
if e.path().is_dir() && n != info.version && n != EXTENSION_DIR && !n.starts_with('.') {
let _ = std::fs::remove_dir_all(e.path());
}
}
}
// an extension put ready before goes with the program's version (in the same folder, so the browser keeps it)
if extension_version_in(&dir).is_some()
&& info.extension.is_some()
&& let Err(e) = install_extension(info, cancelled)
{
log::warn!("add-on {}: its browser extension was not brought up to {}: {e}", info.id, info.version);
}
CHANGES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Ok(now)
}
/// Removes `id` (its folder; its own data elsewhere stays).
pub fn remove(id: &str) -> Result<(), String> {
let dir = dir_of(id).ok_or("no folder for add-ons")?;
let r = std::fs::remove_dir_all(&dir).map_err(|e| e.to_string());
CHANGES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
r
}
/// Bumped when an add-on was installed, updated or removed: what shows an add-on's place (the sidebar's HyperDownload row) looks again.
pub static CHANGES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn versions_compare_as_numbers() {
assert!(newer("0.10.0", "0.9.9"));
assert!(newer("1.0.0", "0.99.0"));
assert!(!newer("0.1.0", "0.1.0"));
assert!(!newer("0.1.0", "0.2.0"));
assert!(newer("v0.2.0", "0.1.9"));
}
/// A server on this machine that sends at most `chunk` bytes of `body` per request and then closes the connection, as a
/// transfer that breaks off; with `continues` it goes on from the `Range` asked for, without it it always starts again.
/// Returns its address and the count of requests it got.
fn breaking_server(body: Vec<u8>, chunk: usize, continues: bool) -> (String, std::sync::Arc<std::sync::atomic::AtomicU32>) {
stalling_server(body, chunk, continues, std::time::Duration::ZERO)
}
/// The same, but after its part the server keeps the connection open and silent for `stall` (a slow line: the request's time
/// runs out with the body unfinished).
fn stalling_server(body: Vec<u8>, chunk: usize, continues: bool, stall: std::time::Duration) -> (String, std::sync::Arc<std::sync::atomic::AtomicU32>) {
use std::io::{BufRead, BufReader, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/addon.zip", listener.local_addr().unwrap());
let hits = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
let counted = hits.clone();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { break };
counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut asked = 0usize;
let mut lines = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
while lines.read_line(&mut line).is_ok_and(|n| n > 2) {
if let Some(v) = line.to_ascii_lowercase().strip_prefix("range: bytes=") {
asked = v.trim().trim_end_matches('-').parse().unwrap_or(0);
}
line.clear();
}
let from = if continues { asked.min(body.len()) } else { 0 };
let rest = &body[from..];
let status = if from > 0 { "206 Partial Content" } else { "200 OK" };
let _ = write!(stream, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", rest.len());
let _ = stream.write_all(&rest[..rest.len().min(chunk)]);
let _ = stream.flush();
if !stall.is_zero() && rest.len() > chunk {
std::thread::spawn(move || {
std::thread::sleep(stall);
drop(stream);
});
}
}
});
(url, hits)
}
/// The browser extension's zip is checked, unpacked into ONE folder that stays, and a second one replaces the first in place.
#[test]
fn the_extension_is_unpacked_into_a_folder_that_stays() {
let base = scratch_file("extension");
let _ = std::fs::remove_dir_all(&base);
let make = |version: &str| -> FileRef {
let src = base.join(format!("src-{version}"));
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("manifest.json"), format!("{{\"manifest_version\": 3, \"version\": \"{version}\"}}")).unwrap();
std::fs::write(src.join("background.js"), b"// nothing").unwrap();
let zip = base.join(format!("ext-{version}.zip"));
rf_archive::compress(&[src.join("manifest.json"), src.join("background.js")], &zip, rf_archive::Format::Zip, 5, &mut |_| {}, &|| false).unwrap();
let bytes = std::fs::read(&zip).unwrap();
FileRef { url: zip.to_string_lossy().into_owned(), sha256: sha_of(&bytes), size: bytes.len() as u64 }
};
let dir = base.join("addon");
let first = unpack_extension(&dir, &make("0.1.0"), &|| false).unwrap();
assert_eq!(first, dir.join("extension"));
assert!(first.join("background.js").is_file());
assert_eq!(extension_version_in(&dir).as_deref(), Some("0.1.0"));
// the next version lands in the same folder
let second = unpack_extension(&dir, &make("0.2.0"), &|| false).unwrap();
assert_eq!(second, first);
assert_eq!(extension_version_in(&dir).as_deref(), Some("0.2.0"));
// a zip that is not the listed one changes nothing
let mut wrong = make("0.3.0");
wrong.sha256 = "00".repeat(32);
assert!(unpack_extension(&dir, &wrong, &|| false).is_err());
assert_eq!(extension_version_in(&dir).as_deref(), Some("0.2.0"));
assert!(!dir.join(".extension.zip").exists() && !dir.join(".extension.tmp").exists());
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn the_list_may_name_an_extension_and_an_older_list_has_none() {
let with: Manifest = serde_json::from_str(r#"{"addons":[{"id":"x","name":"X","version":"1.0.0","license":"MIT","source":"","files":{},"extension":{"url":"https://example.com/e.zip","sha256":"ab"}}]}"#).unwrap();
assert_eq!(with.addons[0].extension.as_ref().map(|e| e.url.as_str()), Some("https://example.com/e.zip"));
let without: Manifest = serde_json::from_str(r#"{"addons":[{"id":"x","name":"X","version":"1.0.0","license":"MIT","source":"","files":{}}]}"#).unwrap();
assert!(without.addons[0].extension.is_none());
}
fn sha_of(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
}
fn scratch_file(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("rf-addon-{}-{name}", std::process::id()))
}
/// Issue 1042: a connection that drops after every 300 KB still brings the whole megabyte, in four requests, and it is the
/// same file.
#[test]
fn a_download_that_breaks_off_goes_on_from_where_it_stopped() {
let body: Vec<u8> = (0..1_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect();
let (url, hits) = breaking_server(body.clone(), 300_000, true);
let to = scratch_file("resume.zip");
let told = std::cell::Cell::new(0u64);
let sha = download(&url, &to, body.len() as u64, &|n| told.set(n), &|| false).unwrap();
assert_eq!(sha, sha_of(&body));
assert_eq!(std::fs::read(&to).unwrap(), body);
assert_eq!(told.get(), body.len() as u64);
assert_eq!(hits.load(std::sync::atomic::Ordering::Relaxed), 4);
let _ = std::fs::remove_file(&to);
}
/// The report itself (issue 1042): the request's time runs out with part of the body there ("timeout: receive body"). The next
/// request brings the rest.
#[test]
fn a_download_whose_request_runs_out_of_time_goes_on_too() {
let body: Vec<u8> = (0..400_000u32).map(|i| (i.wrapping_mul(40_503) >> 8) as u8).collect();
let (url, hits) = stalling_server(body.clone(), 150_000, true, std::time::Duration::from_secs(4));
let to = scratch_file("slow.zip");
let sha = download_within(std::time::Duration::from_millis(700), &url, &to, body.len() as u64, &|_| {}, &|| false).unwrap();
assert_eq!(sha, sha_of(&body));
assert_eq!(hits.load(std::sync::atomic::Ordering::Relaxed), 3);
let _ = std::fs::remove_file(&to);
}
/// A server that brings nothing is given up after a few requests, with an error.
#[test]
fn a_download_that_brings_nothing_is_given_up() {
let (url, hits) = breaking_server(vec![7u8; 50_000], 0, true);
let to = scratch_file("dry.zip");
assert!(download(&url, &to, 50_000, &|_| {}, &|| false).is_err());
assert_eq!(hits.load(std::sync::atomic::Ordering::Relaxed), DRY_TRIES);
let _ = std::fs::remove_file(&to);
}
/// A server that cannot continue a file starts it again each time: the file never grows past the first part, and that ends
/// too (no endless asking), with nothing wrong left as if it were whole.
#[test]
fn a_server_that_always_starts_again_does_not_keep_the_download_going_for_ever() {
let (url, hits) = breaking_server(vec![9u8; 100_000], 30_000, false);
let to = scratch_file("again.zip");
assert!(download(&url, &to, 100_000, &|_| {}, &|| false).is_err());
assert_eq!(hits.load(std::sync::atomic::Ordering::Relaxed), 1 + DRY_TRIES);
let _ = std::fs::remove_file(&to);
}
#[test]
fn a_list_is_read_and_the_machines_file_is_picked() {
let m: Manifest = serde_json::from_str(
r#"{"addons":[{"id":"hyperdownload","name":"HyperDownload","version":"0.1.0","license":"MIT","source":"https://github.com/gelenmedya/hyperdownload",
"files":{"x64":{"url":"https://x/a-x64.zip","sha256":"ab","size":10},"arm64":{"url":"https://x/a-arm64.zip","sha256":"cd"}}}]}"#,
)
.unwrap();
let a = &m.addons[0];
assert_eq!(a.file().map(|f| f.url.ends_with(&format!("-{}.zip", arch()))), Some(true));
// a list from a later version with fields this one does not know is still read
let later: Manifest = serde_json::from_str(r#"{"addons":[{"id":"x","name":"X","version":"1","license":"MIT","source":"s","new":1}],"more":true}"#).unwrap();
assert!(later.addons[0].file().is_none());
}
#[test]
fn an_install_checks_the_sha256_and_switches_only_when_it_is_right() {
let tmp = std::env::temp_dir().join(format!("rf-addons-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).unwrap();
// SAFETY of the env change: this test is the only one that reads RUSTYFILES_CONFIG_DIR in this module's tests
unsafe { std::env::set_var("RUSTYFILES_CONFIG_DIR", tmp.join("cfg")) };
// a zip with the program in it
let src = tmp.join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("demo.exe"), b"MZ demo").unwrap();
let zip = tmp.join("demo.zip");
rf_archive::compress(&[src.join("demo.exe")], &zip, rf_archive::Format::Zip, 5, &mut |_| {}, &|| false).unwrap();
let sha: String = Sha256::digest(std::fs::read(&zip).unwrap()).iter().map(|b| format!("{b:02x}")).collect();
let mut info = AddonInfo { id: "demo".into(), name: "Demo".into(), version: "0.1.0".into(), license: "MIT".into(), source: String::new(), extension: None, files: Default::default() };
info.files.insert(arch().into(), FileRef { url: zip.display().to_string(), sha256: "00".into(), size: 0 });
let err = install(&info, &|_, _| {}, &|| false).unwrap_err();
assert!(err.contains("SHA-256"), "{err}");
assert!(installed("demo").is_none(), "nothing installed from a wrong file");
info.files.get_mut(arch()).unwrap().sha256 = sha.to_uppercase();
let got = install(&info, &|_, _| {}, &|| false).unwrap();
assert_eq!(installed("demo"), Some(got));
assert!(program("demo").unwrap().ends_with("0.1.0/demo.exe") || program("demo").unwrap().ends_with(r"0.1.0\demo.exe"));
// an update replaces it and the old version's folder goes
info.version = "0.2.0".into();
install(&info, &|_, _| {}, &|| false).unwrap();
assert_eq!(installed("demo").unwrap().version, "0.2.0");
assert!(!root().unwrap().join("demo").join("0.1.0").exists());
remove("demo").unwrap();
assert!(installed("demo").is_none());
unsafe { std::env::remove_var("RUSTYFILES_CONFIG_DIR") };
let _ = std::fs::remove_dir_all(&tmp);
}
}