use std::collections::HashMap;
use std::ffi::OsString;
use std::io::Read as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{channel, Receiver, TryRecvError};
use std::sync::Arc;
use std::time::Duration;
use eframe::egui;
use sha2::{Digest, Sha256};
#[cfg(feature = "automation")]
pub mod fixture;
pub const FORMAT: &str = "brep-help-bundle-v1";
pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
pub const BUNDLE_PATH: &str = "/public/app/master/web/help-bundle";
pub const ONLINE_PATH: &str = "/public/app/master/web/help/index.html";
const MARKER: &str = ".bundle.json";
const MAX_BYTES: u64 = 1 << 30;
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct BundleManifest {
pub format: String,
pub version: String,
pub file: String,
pub sha256: String,
pub bytes: u64,
}
fn safe_name(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 128
&& !s.starts_with('.')
&& s.chars().all(|c| c.is_ascii_alphanumeric() || "._-+".contains(c))
}
impl BundleManifest {
pub fn parse(text: &str) -> Result<BundleManifest, String> {
let m: BundleManifest = serde_json::from_str(text).map_err(|e| format!("help manifest: {e}"))?;
if m.format != FORMAT {
return Err(format!("help manifest format {:?} is not {FORMAT}", m.format));
}
if !safe_name(&m.version) {
return Err(format!("help manifest version {:?} is not a plain name", m.version));
}
if !safe_name(&m.file) || !m.file.ends_with(".tar.gz") {
return Err(format!("help manifest file {:?} is not a plain .tar.gz name", m.file));
}
if m.sha256.len() != 64 || !m.sha256.chars().all(|c| c.is_ascii_hexdigit()) {
return Err("help manifest sha256 is not 64 hex digits".into());
}
if m.bytes == 0 || m.bytes > MAX_BYTES {
return Err(format!("help manifest size {} is out of range", m.bytes));
}
Ok(m)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Source {
pub base: String,
pub online: String,
}
impl Source {
pub fn site(server: &str) -> Source {
let server = server.trim_end_matches('/');
Source { base: format!("{server}{BUNDLE_PATH}"), online: format!("{server}{ONLINE_PATH}") }
}
}
pub fn data_dir() -> PathBuf {
let os = if cfg!(windows) {
"windows"
} else if cfg!(target_os = "macos") {
"macos"
} else {
"linux"
};
data_dir_from(&|name| std::env::var_os(name), os)
}
pub fn data_dir_from(env: &dyn Fn(&str) -> Option<OsString>, os: &str) -> PathBuf {
let var = |name: &str| env(name).filter(|v| !v.is_empty()).map(PathBuf::from);
var("XDG_DATA_HOME")
.or_else(|| if os == "windows" { var("LOCALAPPDATA").or_else(|| var("APPDATA")) } else { None })
.or_else(|| {
var("HOME").map(|h| if os == "macos" { h.join("Library/Application Support") } else { h.join(".local/share") })
})
.unwrap_or_else(|| PathBuf::from("."))
.join("brep-app")
}
pub fn file_url(path: &Path) -> String {
let s = path.to_string_lossy().replace('\\', "/");
let mut out = String::from("file://");
if !s.starts_with('/') {
out.push('/');
}
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' | b':' => out.push(b as char),
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
pub fn installed(root: &Path, version: &str) -> Option<PathBuf> {
let dir = root.join(version);
(safe_name(version) && dir.join("index.html").is_file() && dir.join(MARKER).is_file()).then(|| dir.join("index.html"))
}
fn installed_manifest(root: &Path, version: &str) -> Option<BundleManifest> {
installed(root, version)?;
serde_json::from_str(&std::fs::read_to_string(root.join(version).join(MARKER)).ok()?).ok()
}
fn version_key(v: &str) -> Vec<u64> {
v.split(['.', '-', '+'])
.map(|p| p.chars().take_while(|c| c.is_ascii_digit()).collect::<String>().parse().unwrap_or(0))
.collect()
}
pub fn newest_installed(root: &Path) -> Option<(String, PathBuf)> {
let mut best: Option<(String, PathBuf)> = None;
for entry in std::fs::read_dir(root).ok()?.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if let Some(index) = installed(root, &name) {
if best.as_ref().is_none_or(|(v, _)| version_key(&name) > version_key(v)) {
best = Some((name, index));
}
}
}
best
}
#[derive(Default)]
pub struct Progress {
pub received: AtomicU64,
pub total: AtomicU64,
pub cancel: AtomicBool,
}
pub const CANCELLED: &str = "the download was cancelled";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Fetched {
pub index: PathBuf,
pub version: String,
}
fn get_manifest(url: &str) -> Result<Option<BundleManifest>, String> {
let response = crate::net::fetch_blocking(&crate::net::Request::get(url))?;
if response.status == 404 {
return Ok(None);
}
if !response.ok {
return Err(format!("the help manifest: HTTP {} {}", response.status, response.status_text));
}
BundleManifest::parse(&String::from_utf8_lossy(&response.bytes)).map(Some)
}
pub fn fetch_bundle(source: &Source, root: &Path, want: &str, progress: &Progress) -> Result<Fetched, String> {
let base = source.base.trim_end_matches('/');
let manifest = match get_manifest(&format!("{base}/brep-help-{want}.json"))? {
Some(m) => m,
None => get_manifest(&format!("{base}/brep-help-latest.json"))?
.ok_or_else(|| format!("the server has no help bundle (neither {want}'s nor the latest)"))?,
};
if let Some(have) = installed_manifest(root, &manifest.version) {
if have.sha256 == manifest.sha256 {
if let Some(index) = installed(root, &manifest.version) {
return Ok(Fetched { index, version: manifest.version });
}
}
}
progress.total.store(manifest.bytes, Ordering::Relaxed);
let bytes = download(&format!("{base}/{}", manifest.file), &manifest, progress)?;
let index = unpack(&bytes, root, &manifest)?;
Ok(Fetched { index, version: manifest.version })
}
fn download(url: &str, m: &BundleManifest, progress: &Progress) -> Result<Vec<u8>, String> {
let agent = ureq::AgentBuilder::new()
.timeout_connect(Duration::from_secs(15))
.timeout_read(Duration::from_secs(60))
.build();
let reply = agent.get(url).set("Accept-Encoding", "identity").call().map_err(|e| match e {
ureq::Error::Status(code, r) => format!("the help archive: HTTP {code} {}", r.status_text()),
ureq::Error::Transport(t) => t.to_string(),
})?;
let mut reader = reply.into_reader();
let mut buf = vec![0u8; 64 * 1024];
let mut out = Vec::with_capacity(m.bytes as usize);
let mut hash = Sha256::new();
loop {
if progress.cancel.load(Ordering::Relaxed) {
return Err(CANCELLED.into());
}
let n = reader.read(&mut buf).map_err(|e| format!("the help download stopped: {e}"))?;
if n == 0 {
break;
}
if out.len() as u64 + n as u64 > m.bytes {
return Err(format!("the server sent more than the {} bytes the manifest names", m.bytes));
}
hash.update(&buf[..n]);
out.extend_from_slice(&buf[..n]);
progress.received.store(out.len() as u64, Ordering::Relaxed);
}
if out.len() as u64 != m.bytes {
return Err(format!("the help download stopped at {} of {} bytes", out.len(), m.bytes));
}
let got: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect();
if !got.eq_ignore_ascii_case(&m.sha256) {
return Err(format!("the help download does not match its sha256 (got {got}, expected {})", m.sha256));
}
Ok(out)
}
fn clean_relative(p: &Path) -> Option<PathBuf> {
let mut out = PathBuf::new();
for c in p.components() {
match c {
std::path::Component::Normal(part) => out.push(part),
std::path::Component::CurDir => {}
_ => return None,
}
}
Some(out)
}
pub fn unpack(gz: &[u8], root: &Path, m: &BundleManifest) -> Result<PathBuf, String> {
std::fs::create_dir_all(root).map_err(|e| format!("{}: {e}", root.display()))?;
let partial = root.join(format!(".partial-{}-{}", m.version, std::process::id()));
let _ = std::fs::remove_dir_all(&partial);
let result = (|| -> Result<PathBuf, String> {
let io = |e: std::io::Error| format!("unpacking the help: {e}");
std::fs::create_dir_all(&partial).map_err(io)?;
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(gz));
for entry in archive.entries().map_err(io)? {
let mut entry = entry.map_err(io)?;
let path = entry.path().map_err(io)?.into_owned();
let rel = clean_relative(&path).ok_or_else(|| format!("the help archive holds an unsafe path {}", path.display()))?;
if rel.as_os_str().is_empty() {
continue;
}
let to = partial.join(&rel);
match entry.header().entry_type() {
tar::EntryType::Regular | tar::EntryType::Continuous => {
if let Some(parent) = to.parent() {
std::fs::create_dir_all(parent).map_err(io)?;
}
let mut file = std::fs::File::create(&to).map_err(io)?;
std::io::copy(&mut entry, &mut file).map_err(io)?;
}
tar::EntryType::Directory => std::fs::create_dir_all(&to).map_err(io)?,
_ => {}
}
}
if !partial.join("index.html").is_file() {
return Err("the help archive has no index.html".into());
}
std::fs::write(partial.join(MARKER), serde_json::to_string_pretty(m).unwrap_or_default()).map_err(io)?;
let dest = root.join(&m.version);
if dest.exists() {
std::fs::remove_dir_all(&dest).map_err(io)?;
}
std::fs::rename(&partial, &dest).map_err(io)?;
Ok(dest.join("index.html"))
})();
if result.is_err() {
let _ = std::fs::remove_dir_all(&partial);
}
result
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Phase {
None,
Downloading,
Ready { index: PathBuf, version: String },
Failed { error: String },
}
struct Job {
progress: Arc<Progress>,
rx: Receiver<Result<Fetched, String>>,
}
pub struct HelpDownloader {
source: Option<Source>,
root: PathBuf,
phase: Phase,
job: Option<Job>,
notice: bool,
note: Option<String>,
opened: Option<String>,
hits: HashMap<String, egui::Rect>,
#[cfg(feature = "automation")]
fixture: Option<fixture::FixtureServer>,
#[cfg(feature = "automation")]
fixture_dirs: Vec<PathBuf>,
}
#[cfg(feature = "automation")]
impl Drop for HelpDownloader {
fn drop(&mut self) {
self.cancel_job();
for dir in &self.fixture_dirs {
let _ = std::fs::remove_dir_all(dir);
}
}
}
impl Default for HelpDownloader {
fn default() -> Self {
Self::inert()
}
}
impl HelpDownloader {
pub fn inert() -> HelpDownloader {
HelpDownloader {
source: None,
root: data_dir().join("help"),
phase: Phase::None,
job: None,
notice: false,
note: None,
opened: None,
hits: HashMap::new(),
#[cfg(feature = "automation")]
fixture: None,
#[cfg(feature = "automation")]
fixture_dirs: Vec::new(),
}
}
pub fn start_site(&mut self) {
self.source = Some(Source::site(&crate::update::server()));
}
pub fn configure(&mut self, source: Source, root: PathBuf) {
self.cancel_job();
self.source = Some(source);
self.root = root;
self.phase = Phase::None;
self.notice = false;
self.note = None;
self.opened = None;
}
fn open(&mut self, ctx: &egui::Context, url: String) {
ctx.open_url(egui::OpenUrl::new_tab(url.clone()));
self.opened = Some(url);
}
pub fn press(&mut self, ctx: &egui::Context) -> Option<String> {
self.drain(ctx);
let Some(source) = self.source.clone() else {
self.open(ctx, crate::automation::HELP_URL.to_string());
return self.opened.clone();
};
if let Some(index) = installed(&self.root, APP_VERSION) {
self.open(ctx, file_url(&index));
self.phase = Phase::Ready { index, version: APP_VERSION.to_string() };
self.notice = false;
self.note = None;
return self.opened.clone();
}
self.notice = true;
if self.job.is_some() {
return None;
}
let progress = Arc::new(Progress::default());
let (tx, rx) = channel();
let (thread_progress, root, ctx2) = (progress.clone(), self.root.clone(), ctx.clone());
let spawned = std::thread::Builder::new().name("brep-help-download".into()).spawn(move || {
let result = fetch_bundle(&source, &root, APP_VERSION, &thread_progress);
let _ = tx.send(result);
ctx2.request_repaint();
});
match spawned {
Ok(_) => {
self.job = Some(Job { progress, rx });
self.phase = Phase::Downloading;
self.note = None;
}
Err(e) => self.fail(ctx, format!("could not start the download: {e}")),
}
None
}
fn cancel_job(&mut self) {
if let Some(job) = self.job.take() {
job.progress.cancel.store(true, Ordering::Relaxed);
}
}
pub fn cancel(&mut self) {
if self.job.is_some() {
self.cancel_job();
self.phase = Phase::None;
self.note = Some("The help download was cancelled.".into());
self.notice = false;
}
}
fn fail(&mut self, ctx: &egui::Context, error: String) {
if let Some((version, index)) = newest_installed(&self.root) {
self.open(ctx, file_url(&index));
self.note = Some(format!(
"The help for this version could not be downloaded ({error}). Opened the copy for version {version} on this computer."
));
self.phase = Phase::Ready { index, version };
} else {
self.phase = Phase::Failed { error };
self.note = None;
}
self.notice = true;
}
fn drain(&mut self, ctx: &egui::Context) {
let Some(job) = &self.job else { return };
let result = match job.rx.try_recv() {
Ok(result) => result,
Err(TryRecvError::Empty) => return,
Err(TryRecvError::Disconnected) => Err("the download stopped unexpectedly".into()),
};
self.job = None;
match result {
Ok(fetched) => {
self.open(ctx, file_url(&fetched.index));
if fetched.version == APP_VERSION {
self.note = None;
self.notice = false;
} else {
let relation = if version_key(&fetched.version) > version_key(APP_VERSION) { "newer than" } else { "not" };
self.note = Some(format!(
"This help is for version {}, {relation} this app ({APP_VERSION}): the server no longer has this version's.",
fetched.version
));
self.notice = true;
}
self.phase = Phase::Ready { index: fetched.index, version: fetched.version };
}
Err(error) => self.fail(ctx, error),
}
}
pub fn online_url(&self) -> String {
self.source.as_ref().map(|s| s.online.clone()).unwrap_or_else(|| crate::automation::HELP_URL.to_string())
}
pub fn show(&mut self, ctx: &egui::Context) {
self.drain(ctx);
self.hits.clear();
if !self.notice {
return;
}
enum Act {
Cancel,
Online,
Close,
}
let mut act = None;
let hits = &mut self.hits;
let (received, total) = self
.job
.as_ref()
.map(|j| (j.progress.received.load(Ordering::Relaxed), j.progress.total.load(Ordering::Relaxed)))
.unwrap_or((0, 0));
egui::Area::new(egui::Id::new("brep-help-notice"))
.anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-12.0, -150.0))
.order(egui::Order::Foreground)
.show(ctx, |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.set_max_width(360.0);
match &self.phase {
Phase::Downloading => {
ui.strong("Downloading the help");
let mb = |b: u64| b as f64 / 1_000_000.0;
let (fraction, text) = if total > 0 {
(received as f32 / total as f32, format!("{:.1} of {:.1} MB", mb(received), mb(total)))
} else {
(0.0, "Asking the server…".to_string())
};
ui.add(egui::ProgressBar::new(fraction).text(text));
ui.label("Once, for this version: later it opens from this computer, offline.");
let r = ui.button("Cancel");
hits.insert("help:cancel".into(), r.rect);
if r.clicked() {
act = Some(Act::Cancel);
}
}
Phase::Failed { error } => {
ui.strong("The help could not be downloaded");
ui.label(error);
ui.horizontal(|ui| {
let r = ui.button("Open the online help");
hits.insert("help:online".into(), r.rect);
if r.clicked() {
act = Some(Act::Online);
}
let r = ui.button("Close");
hits.insert("help:close".into(), r.rect);
if r.clicked() {
act = Some(Act::Close);
}
});
}
Phase::Ready { .. } | Phase::None => {
if let Some(note) = &self.note {
ui.label(note);
}
let r = ui.button("Close");
hits.insert("help:close".into(), r.rect);
if r.clicked() {
act = Some(Act::Close);
}
}
}
});
});
match act {
Some(Act::Cancel) => self.cancel(),
Some(Act::Online) => {
let url = self.online_url();
self.open(ctx, url);
self.notice = false;
}
Some(Act::Close) => self.notice = false,
None => {}
}
if self.job.is_some() {
ctx.request_repaint_after(Duration::from_millis(200));
}
}
pub fn state_json(&self) -> serde_json::Value {
let (received, total) = self
.job
.as_ref()
.map(|j| (j.progress.received.load(Ordering::Relaxed), j.progress.total.load(Ordering::Relaxed)))
.unwrap_or((0, 0));
let (state, path, version, error) = match &self.phase {
Phase::None => ("none", None, None, None),
Phase::Downloading => ("downloading", None, None, None),
Phase::Ready { index, version } => ("ready", Some(index.display().to_string()), Some(version.clone()), None),
Phase::Failed { error } => ("failed", None, None, Some(error.clone())),
};
serde_json::json!({
"state": state,
"source": self.source.as_ref().map(|s| s.base.clone()),
"appVersion": APP_VERSION,
"dir": self.root.display().to_string(),
"path": path,
"version": version,
"received": received,
"total": total,
"error": error,
"note": self.note,
"notice": self.notice,
"opened": self.opened,
})
}
pub fn hits_json(&self) -> String {
crate::automation::hit_rects::hits_json(&self.hits)
}
#[cfg(feature = "automation")]
pub fn fixture_action(&mut self, action: &str, variant: Option<&str>, keep_dir: bool) -> Result<serde_json::Value, String> {
match action {
"start" => {
let variant = fixture::Variant::parse(variant.unwrap_or("ok"))?;
let server = match self.fixture.take() {
Some(server) => server.restart(variant)?,
None => fixture::FixtureServer::start(variant)?,
};
let url = server.url.clone();
let root = if keep_dir && self.source.is_some() {
self.root.clone()
} else {
let dir = std::env::temp_dir().join(format!("brep-help-fixture-{}", uuid::Uuid::new_v4()));
self.fixture_dirs.push(dir.clone());
dir
};
self.configure(Source { base: url.clone(), online: format!("{url}/online/index.html") }, root);
self.fixture = Some(server);
Ok(serde_json::json!({ "url": url, "dir": self.root.display().to_string() }))
}
"stop" => {
let server = self.fixture.as_mut().ok_or("no help fixture is running")?;
server.stop();
Ok(serde_json::json!({ "stopped": true }))
}
"hold" | "release" => {
let server = self.fixture.as_ref().ok_or("no help fixture is running")?;
server.set_hold(action == "hold");
Ok(serde_json::json!({ "hold": action == "hold", "requests": server.requests() }))
}
other => Err(format!("`help_fixture` action `{other}`: expected start, stop, hold or release")),
}
}
}