1use std::collections::HashMap;
29use std::ffi::OsString;
30use std::io::Read as _;
31use std::path::{Path, PathBuf};
32use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
33use std::sync::mpsc::{channel, Receiver, TryRecvError};
34use std::sync::Arc;
35use std::time::Duration;
36
37use eframe::egui;
38use sha2::{Digest, Sha256};
39
40#[cfg(feature = "automation")]
41pub mod fixture;
42
43pub const FORMAT: &str = "brep-help-bundle-v1";
45pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
47pub const BUNDLE_PATH: &str = "/public/app/master/web/help-bundle";
49pub const ONLINE_PATH: &str = "/public/app/master/web/help/index.html";
51const MARKER: &str = ".bundle.json";
53const MAX_BYTES: u64 = 1 << 30;
55
56#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
58pub struct BundleManifest {
59 pub format: String,
60 pub version: String,
61 pub file: String,
62 pub sha256: String,
63 pub bytes: u64,
64}
65
66fn safe_name(s: &str) -> bool {
68 !s.is_empty()
69 && s.len() <= 128
70 && !s.starts_with('.')
71 && s.chars().all(|c| c.is_ascii_alphanumeric() || "._-+".contains(c))
72}
73
74impl BundleManifest {
75 pub fn parse(text: &str) -> Result<BundleManifest, String> {
76 let m: BundleManifest = serde_json::from_str(text).map_err(|e| format!("help manifest: {e}"))?;
77 if m.format != FORMAT {
78 return Err(format!("help manifest format {:?} is not {FORMAT}", m.format));
79 }
80 if !safe_name(&m.version) {
81 return Err(format!("help manifest version {:?} is not a plain name", m.version));
82 }
83 if !safe_name(&m.file) || !m.file.ends_with(".tar.gz") {
84 return Err(format!("help manifest file {:?} is not a plain .tar.gz name", m.file));
85 }
86 if m.sha256.len() != 64 || !m.sha256.chars().all(|c| c.is_ascii_hexdigit()) {
87 return Err("help manifest sha256 is not 64 hex digits".into());
88 }
89 if m.bytes == 0 || m.bytes > MAX_BYTES {
90 return Err(format!("help manifest size {} is out of range", m.bytes));
91 }
92 Ok(m)
93 }
94}
95
96#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct Source {
100 pub base: String,
101 pub online: String,
102}
103
104impl Source {
105 pub fn site(server: &str) -> Source {
107 let server = server.trim_end_matches('/');
108 Source { base: format!("{server}{BUNDLE_PATH}"), online: format!("{server}{ONLINE_PATH}") }
109 }
110}
111
112pub fn data_dir() -> PathBuf {
114 let os = if cfg!(windows) {
115 "windows"
116 } else if cfg!(target_os = "macos") {
117 "macos"
118 } else {
119 "linux"
120 };
121 data_dir_from(&|name| std::env::var_os(name), os)
122}
123
124pub fn data_dir_from(env: &dyn Fn(&str) -> Option<OsString>, os: &str) -> PathBuf {
128 let var = |name: &str| env(name).filter(|v| !v.is_empty()).map(PathBuf::from);
129 var("XDG_DATA_HOME")
130 .or_else(|| if os == "windows" { var("LOCALAPPDATA").or_else(|| var("APPDATA")) } else { None })
131 .or_else(|| {
132 var("HOME").map(|h| if os == "macos" { h.join("Library/Application Support") } else { h.join(".local/share") })
133 })
134 .unwrap_or_else(|| PathBuf::from("."))
135 .join("brep-app")
136}
137
138pub fn file_url(path: &Path) -> String {
141 let s = path.to_string_lossy().replace('\\', "/");
142 let mut out = String::from("file://");
143 if !s.starts_with('/') {
144 out.push('/');
145 }
146 for b in s.bytes() {
147 match b {
148 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' | b':' => out.push(b as char),
149 _ => out.push_str(&format!("%{b:02X}")),
150 }
151 }
152 out
153}
154
155pub fn installed(root: &Path, version: &str) -> Option<PathBuf> {
158 let dir = root.join(version);
159 (safe_name(version) && dir.join("index.html").is_file() && dir.join(MARKER).is_file()).then(|| dir.join("index.html"))
160}
161
162fn installed_manifest(root: &Path, version: &str) -> Option<BundleManifest> {
163 installed(root, version)?;
164 serde_json::from_str(&std::fs::read_to_string(root.join(version).join(MARKER)).ok()?).ok()
165}
166
167fn version_key(v: &str) -> Vec<u64> {
169 v.split(['.', '-', '+'])
170 .map(|p| p.chars().take_while(|c| c.is_ascii_digit()).collect::<String>().parse().unwrap_or(0))
171 .collect()
172}
173
174pub fn newest_installed(root: &Path) -> Option<(String, PathBuf)> {
176 let mut best: Option<(String, PathBuf)> = None;
177 for entry in std::fs::read_dir(root).ok()?.flatten() {
178 let name = entry.file_name().to_string_lossy().to_string();
179 if let Some(index) = installed(root, &name) {
180 if best.as_ref().is_none_or(|(v, _)| version_key(&name) > version_key(v)) {
181 best = Some((name, index));
182 }
183 }
184 }
185 best
186}
187
188#[derive(Default)]
190pub struct Progress {
191 pub received: AtomicU64,
192 pub total: AtomicU64,
193 pub cancel: AtomicBool,
194}
195
196pub const CANCELLED: &str = "the download was cancelled";
198
199#[derive(Clone, Debug, PartialEq, Eq)]
201pub struct Fetched {
202 pub index: PathBuf,
203 pub version: String,
204}
205
206fn get_manifest(url: &str) -> Result<Option<BundleManifest>, String> {
208 let response = crate::net::fetch_blocking(&crate::net::Request::get(url))?;
209 if response.status == 404 {
210 return Ok(None);
211 }
212 if !response.ok {
213 return Err(format!("the help manifest: HTTP {} {}", response.status, response.status_text));
214 }
215 BundleManifest::parse(&String::from_utf8_lossy(&response.bytes)).map(Some)
216}
217
218pub fn fetch_bundle(source: &Source, root: &Path, want: &str, progress: &Progress) -> Result<Fetched, String> {
221 let base = source.base.trim_end_matches('/');
222 let manifest = match get_manifest(&format!("{base}/brep-help-{want}.json"))? {
223 Some(m) => m,
224 None => get_manifest(&format!("{base}/brep-help-latest.json"))?
225 .ok_or_else(|| format!("the server has no help bundle (neither {want}'s nor the latest)"))?,
226 };
227 if let Some(have) = installed_manifest(root, &manifest.version) {
229 if have.sha256 == manifest.sha256 {
230 if let Some(index) = installed(root, &manifest.version) {
231 return Ok(Fetched { index, version: manifest.version });
232 }
233 }
234 }
235 progress.total.store(manifest.bytes, Ordering::Relaxed);
236 let bytes = download(&format!("{base}/{}", manifest.file), &manifest, progress)?;
237 let index = unpack(&bytes, root, &manifest)?;
238 Ok(Fetched { index, version: manifest.version })
239}
240
241fn download(url: &str, m: &BundleManifest, progress: &Progress) -> Result<Vec<u8>, String> {
242 let agent = ureq::AgentBuilder::new()
243 .timeout_connect(Duration::from_secs(15))
244 .timeout_read(Duration::from_secs(60))
245 .build();
246 let reply = agent.get(url).set("Accept-Encoding", "identity").call().map_err(|e| match e {
248 ureq::Error::Status(code, r) => format!("the help archive: HTTP {code} {}", r.status_text()),
249 ureq::Error::Transport(t) => t.to_string(),
250 })?;
251 let mut reader = reply.into_reader();
252 let mut buf = vec![0u8; 64 * 1024];
253 let mut out = Vec::with_capacity(m.bytes as usize);
254 let mut hash = Sha256::new();
255 loop {
256 if progress.cancel.load(Ordering::Relaxed) {
257 return Err(CANCELLED.into());
258 }
259 let n = reader.read(&mut buf).map_err(|e| format!("the help download stopped: {e}"))?;
260 if n == 0 {
261 break;
262 }
263 if out.len() as u64 + n as u64 > m.bytes {
264 return Err(format!("the server sent more than the {} bytes the manifest names", m.bytes));
265 }
266 hash.update(&buf[..n]);
267 out.extend_from_slice(&buf[..n]);
268 progress.received.store(out.len() as u64, Ordering::Relaxed);
269 }
270 if out.len() as u64 != m.bytes {
271 return Err(format!("the help download stopped at {} of {} bytes", out.len(), m.bytes));
272 }
273 let got: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect();
274 if !got.eq_ignore_ascii_case(&m.sha256) {
275 return Err(format!("the help download does not match its sha256 (got {got}, expected {})", m.sha256));
276 }
277 Ok(out)
278}
279
280fn clean_relative(p: &Path) -> Option<PathBuf> {
283 let mut out = PathBuf::new();
284 for c in p.components() {
285 match c {
286 std::path::Component::Normal(part) => out.push(part),
287 std::path::Component::CurDir => {}
288 _ => return None,
289 }
290 }
291 Some(out)
292}
293
294pub fn unpack(gz: &[u8], root: &Path, m: &BundleManifest) -> Result<PathBuf, String> {
296 std::fs::create_dir_all(root).map_err(|e| format!("{}: {e}", root.display()))?;
297 let partial = root.join(format!(".partial-{}-{}", m.version, std::process::id()));
298 let _ = std::fs::remove_dir_all(&partial);
299 let result = (|| -> Result<PathBuf, String> {
300 let io = |e: std::io::Error| format!("unpacking the help: {e}");
301 std::fs::create_dir_all(&partial).map_err(io)?;
302 let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(gz));
303 for entry in archive.entries().map_err(io)? {
304 let mut entry = entry.map_err(io)?;
305 let path = entry.path().map_err(io)?.into_owned();
306 let rel = clean_relative(&path).ok_or_else(|| format!("the help archive holds an unsafe path {}", path.display()))?;
307 if rel.as_os_str().is_empty() {
308 continue;
309 }
310 let to = partial.join(&rel);
311 match entry.header().entry_type() {
312 tar::EntryType::Regular | tar::EntryType::Continuous => {
313 if let Some(parent) = to.parent() {
314 std::fs::create_dir_all(parent).map_err(io)?;
315 }
316 let mut file = std::fs::File::create(&to).map_err(io)?;
317 std::io::copy(&mut entry, &mut file).map_err(io)?;
318 }
319 tar::EntryType::Directory => std::fs::create_dir_all(&to).map_err(io)?,
320 _ => {}
322 }
323 }
324 if !partial.join("index.html").is_file() {
325 return Err("the help archive has no index.html".into());
326 }
327 std::fs::write(partial.join(MARKER), serde_json::to_string_pretty(m).unwrap_or_default()).map_err(io)?;
328 let dest = root.join(&m.version);
329 if dest.exists() {
330 std::fs::remove_dir_all(&dest).map_err(io)?;
331 }
332 std::fs::rename(&partial, &dest).map_err(io)?;
333 Ok(dest.join("index.html"))
334 })();
335 if result.is_err() {
336 let _ = std::fs::remove_dir_all(&partial);
337 }
338 result
339}
340
341#[derive(Clone, Debug, PartialEq, Eq)]
343pub enum Phase {
344 None,
346 Downloading,
347 Ready { index: PathBuf, version: String },
348 Failed { error: String },
349}
350
351struct Job {
352 progress: Arc<Progress>,
353 rx: Receiver<Result<Fetched, String>>,
354}
355
356pub struct HelpDownloader {
358 source: Option<Source>,
359 root: PathBuf,
360 phase: Phase,
361 job: Option<Job>,
362 notice: bool,
364 note: Option<String>,
367 opened: Option<String>,
369 hits: HashMap<String, egui::Rect>,
370 #[cfg(feature = "automation")]
371 fixture: Option<fixture::FixtureServer>,
372 #[cfg(feature = "automation")]
374 fixture_dirs: Vec<PathBuf>,
375}
376
377#[cfg(feature = "automation")]
378impl Drop for HelpDownloader {
379 fn drop(&mut self) {
380 self.cancel_job();
381 for dir in &self.fixture_dirs {
382 let _ = std::fs::remove_dir_all(dir);
383 }
384 }
385}
386
387impl Default for HelpDownloader {
388 fn default() -> Self {
389 Self::inert()
390 }
391}
392
393impl HelpDownloader {
394 pub fn inert() -> HelpDownloader {
396 HelpDownloader {
397 source: None,
398 root: data_dir().join("help"),
399 phase: Phase::None,
400 job: None,
401 notice: false,
402 note: None,
403 opened: None,
404 hits: HashMap::new(),
405 #[cfg(feature = "automation")]
406 fixture: None,
407 #[cfg(feature = "automation")]
408 fixture_dirs: Vec::new(),
409 }
410 }
411
412 pub fn start_site(&mut self) {
415 self.source = Some(Source::site(&crate::update::server()));
416 }
417
418 pub fn configure(&mut self, source: Source, root: PathBuf) {
420 self.cancel_job();
421 self.source = Some(source);
422 self.root = root;
423 self.phase = Phase::None;
424 self.notice = false;
425 self.note = None;
426 self.opened = None;
427 }
428
429 fn open(&mut self, ctx: &egui::Context, url: String) {
430 ctx.open_url(egui::OpenUrl::new_tab(url.clone()));
431 self.opened = Some(url);
432 }
433
434 pub fn press(&mut self, ctx: &egui::Context) -> Option<String> {
436 self.drain(ctx);
437 let Some(source) = self.source.clone() else {
438 self.open(ctx, crate::automation::HELP_URL.to_string());
439 return self.opened.clone();
440 };
441 if let Some(index) = installed(&self.root, APP_VERSION) {
442 self.open(ctx, file_url(&index));
443 self.phase = Phase::Ready { index, version: APP_VERSION.to_string() };
444 self.notice = false;
445 self.note = None;
446 return self.opened.clone();
447 }
448 self.notice = true;
449 if self.job.is_some() {
450 return None;
451 }
452 let progress = Arc::new(Progress::default());
453 let (tx, rx) = channel();
454 let (thread_progress, root, ctx2) = (progress.clone(), self.root.clone(), ctx.clone());
455 let spawned = std::thread::Builder::new().name("brep-help-download".into()).spawn(move || {
456 let result = fetch_bundle(&source, &root, APP_VERSION, &thread_progress);
457 let _ = tx.send(result);
458 ctx2.request_repaint();
459 });
460 match spawned {
461 Ok(_) => {
462 self.job = Some(Job { progress, rx });
463 self.phase = Phase::Downloading;
464 self.note = None;
465 }
466 Err(e) => self.fail(ctx, format!("could not start the download: {e}")),
467 }
468 None
469 }
470
471 fn cancel_job(&mut self) {
472 if let Some(job) = self.job.take() {
473 job.progress.cancel.store(true, Ordering::Relaxed);
474 }
475 }
476
477 pub fn cancel(&mut self) {
480 if self.job.is_some() {
481 self.cancel_job();
482 self.phase = Phase::None;
483 self.note = Some("The help download was cancelled.".into());
484 self.notice = false;
485 }
486 }
487
488 fn fail(&mut self, ctx: &egui::Context, error: String) {
489 if let Some((version, index)) = newest_installed(&self.root) {
490 self.open(ctx, file_url(&index));
491 self.note = Some(format!(
492 "The help for this version could not be downloaded ({error}). Opened the copy for version {version} on this computer."
493 ));
494 self.phase = Phase::Ready { index, version };
495 } else {
496 self.phase = Phase::Failed { error };
497 self.note = None;
498 }
499 self.notice = true;
500 }
501
502 fn drain(&mut self, ctx: &egui::Context) {
503 let Some(job) = &self.job else { return };
504 let result = match job.rx.try_recv() {
505 Ok(result) => result,
506 Err(TryRecvError::Empty) => return,
507 Err(TryRecvError::Disconnected) => Err("the download stopped unexpectedly".into()),
508 };
509 self.job = None;
510 match result {
511 Ok(fetched) => {
512 self.open(ctx, file_url(&fetched.index));
513 if fetched.version == APP_VERSION {
514 self.note = None;
515 self.notice = false;
516 } else {
517 let relation = if version_key(&fetched.version) > version_key(APP_VERSION) { "newer than" } else { "not" };
518 self.note = Some(format!(
519 "This help is for version {}, {relation} this app ({APP_VERSION}): the server no longer has this version's.",
520 fetched.version
521 ));
522 self.notice = true;
523 }
524 self.phase = Phase::Ready { index: fetched.index, version: fetched.version };
525 }
526 Err(error) => self.fail(ctx, error),
527 }
528 }
529
530 pub fn online_url(&self) -> String {
532 self.source.as_ref().map(|s| s.online.clone()).unwrap_or_else(|| crate::automation::HELP_URL.to_string())
533 }
534
535 pub fn show(&mut self, ctx: &egui::Context) {
537 self.drain(ctx);
538 self.hits.clear();
539 if !self.notice {
540 return;
541 }
542 enum Act {
543 Cancel,
544 Online,
545 Close,
546 }
547 let mut act = None;
548 let hits = &mut self.hits;
549 let (received, total) = self
550 .job
551 .as_ref()
552 .map(|j| (j.progress.received.load(Ordering::Relaxed), j.progress.total.load(Ordering::Relaxed)))
553 .unwrap_or((0, 0));
554 egui::Area::new(egui::Id::new("brep-help-notice"))
555 .anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-12.0, -150.0))
556 .order(egui::Order::Foreground)
557 .show(ctx, |ui| {
558 egui::Frame::popup(ui.style()).show(ui, |ui| {
559 ui.set_max_width(360.0);
560 match &self.phase {
561 Phase::Downloading => {
562 ui.strong("Downloading the help");
563 let mb = |b: u64| b as f64 / 1_000_000.0;
564 let (fraction, text) = if total > 0 {
565 (received as f32 / total as f32, format!("{:.1} of {:.1} MB", mb(received), mb(total)))
566 } else {
567 (0.0, "Asking the server…".to_string())
568 };
569 ui.add(egui::ProgressBar::new(fraction).text(text));
570 ui.label("Once, for this version: later it opens from this computer, offline.");
571 let r = ui.button("Cancel");
572 hits.insert("help:cancel".into(), r.rect);
573 if r.clicked() {
574 act = Some(Act::Cancel);
575 }
576 }
577 Phase::Failed { error } => {
578 ui.strong("The help could not be downloaded");
579 ui.label(error);
580 ui.horizontal(|ui| {
581 let r = ui.button("Open the online help");
582 hits.insert("help:online".into(), r.rect);
583 if r.clicked() {
584 act = Some(Act::Online);
585 }
586 let r = ui.button("Close");
587 hits.insert("help:close".into(), r.rect);
588 if r.clicked() {
589 act = Some(Act::Close);
590 }
591 });
592 }
593 Phase::Ready { .. } | Phase::None => {
594 if let Some(note) = &self.note {
595 ui.label(note);
596 }
597 let r = ui.button("Close");
598 hits.insert("help:close".into(), r.rect);
599 if r.clicked() {
600 act = Some(Act::Close);
601 }
602 }
603 }
604 });
605 });
606 match act {
607 Some(Act::Cancel) => self.cancel(),
608 Some(Act::Online) => {
609 let url = self.online_url();
610 self.open(ctx, url);
611 self.notice = false;
612 }
613 Some(Act::Close) => self.notice = false,
614 None => {}
615 }
616 if self.job.is_some() {
617 ctx.request_repaint_after(Duration::from_millis(200));
618 }
619 }
620
621 pub fn state_json(&self) -> serde_json::Value {
624 let (received, total) = self
625 .job
626 .as_ref()
627 .map(|j| (j.progress.received.load(Ordering::Relaxed), j.progress.total.load(Ordering::Relaxed)))
628 .unwrap_or((0, 0));
629 let (state, path, version, error) = match &self.phase {
630 Phase::None => ("none", None, None, None),
631 Phase::Downloading => ("downloading", None, None, None),
632 Phase::Ready { index, version } => ("ready", Some(index.display().to_string()), Some(version.clone()), None),
633 Phase::Failed { error } => ("failed", None, None, Some(error.clone())),
634 };
635 serde_json::json!({
636 "state": state,
637 "source": self.source.as_ref().map(|s| s.base.clone()),
638 "appVersion": APP_VERSION,
639 "dir": self.root.display().to_string(),
640 "path": path,
641 "version": version,
642 "received": received,
643 "total": total,
644 "error": error,
645 "note": self.note,
646 "notice": self.notice,
647 "opened": self.opened,
648 })
649 }
650
651 pub fn hits_json(&self) -> String {
653 crate::automation::hit_rects::hits_json(&self.hits)
654 }
655
656 #[cfg(feature = "automation")]
661 pub fn fixture_action(&mut self, action: &str, variant: Option<&str>, keep_dir: bool) -> Result<serde_json::Value, String> {
662 match action {
663 "start" => {
664 let variant = fixture::Variant::parse(variant.unwrap_or("ok"))?;
665 let server = match self.fixture.take() {
666 Some(server) => server.restart(variant)?,
667 None => fixture::FixtureServer::start(variant)?,
668 };
669 let url = server.url.clone();
670 let root = if keep_dir && self.source.is_some() {
671 self.root.clone()
672 } else {
673 let dir = std::env::temp_dir().join(format!("brep-help-fixture-{}", uuid::Uuid::new_v4()));
674 self.fixture_dirs.push(dir.clone());
675 dir
676 };
677 self.configure(Source { base: url.clone(), online: format!("{url}/online/index.html") }, root);
678 self.fixture = Some(server);
679 Ok(serde_json::json!({ "url": url, "dir": self.root.display().to_string() }))
680 }
681 "stop" => {
682 let server = self.fixture.as_mut().ok_or("no help fixture is running")?;
683 server.stop();
684 Ok(serde_json::json!({ "stopped": true }))
685 }
686 "hold" | "release" => {
687 let server = self.fixture.as_ref().ok_or("no help fixture is running")?;
688 server.set_hold(action == "hold");
689 Ok(serde_json::json!({ "hold": action == "hold", "requests": server.requests() }))
690 }
691 other => Err(format!("`help_fixture` action `{other}`: expected start, stop, hold or release")),
692 }
693 }
694}
695