Skip to content

Commit

Permalink
Add a on_before_exit function instead
Browse files Browse the repository at this point in the history
  • Loading branch information
Legend-Master committed Mar 13, 2024
1 parent 448afe4 commit b4185ed
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 27 deletions.
4 changes: 1 addition & 3 deletions .changes/fix-updater-cleanup-md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,4 @@
"updater": patch
---

Fix updater doesn't shutdown the app gracefully on update

**Breaking change** `Update::download_and_install` now takes `AppHandle` as its first parameter
Add a `on_before_exit` hook for cleanup before spawning the updater on Windows, defaults to `app.cleanup_before_exit`
10 changes: 7 additions & 3 deletions plugins/updater/permissions/schemas/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,14 @@
},
"platforms": {
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
"type": [
"array",
"null"
"default": [
"linux",
"macOS",
"windows",
"android",
"iOS"
],
"type": "array",
"items": {
"$ref": "#/definitions/Target"
}
Expand Down
1 change: 0 additions & 1 deletion plugins/updater/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ pub(crate) async fn download_and_install<R: Runtime>(

update
.download_and_install(
app.app_handle(),
|chunk_length, content_length| {
if first_chunk {
first_chunk = !first_chunk;
Expand Down
5 changes: 5 additions & 0 deletions plugins/updater/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,11 @@ impl<R: Runtime, T: Manager<R>> UpdaterExt<R> for T {
}
}

let app_handle = app.app_handle().clone();
builder = builder.on_before_exit(move || {
app_handle.cleanup_before_exit();
});

builder
}

Expand Down
43 changes: 27 additions & 16 deletions plugins/updater/src/updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::{
io::{Cursor, Read},
path::{Path, PathBuf},
str::FromStr,
sync::Arc,
time::Duration,
};

Expand All @@ -21,7 +22,7 @@ use reqwest::{
};
use semver::Version;
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize};
use tauri::{utils::platform::current_exe, AppHandle, Resource};
use tauri::{utils::platform::current_exe, Resource};
use time::OffsetDateTime;
use url::Url;

Expand Down Expand Up @@ -88,6 +89,8 @@ impl RemoteRelease {
}
}

pub type OnBeforeExit = Arc<dyn Fn() -> () + Send + Sync + 'static>;

pub struct UpdaterBuilder {
current_version: Version,
config: Config,
Expand All @@ -99,6 +102,7 @@ pub struct UpdaterBuilder {
timeout: Option<Duration>,
proxy: Option<Url>,
installer_args: Vec<OsString>,
on_before_exit: Option<OnBeforeExit>,
}

impl UpdaterBuilder {
Expand All @@ -118,6 +122,7 @@ impl UpdaterBuilder {
headers: Default::default(),
timeout: None,
proxy: None,
on_before_exit: None,
}
}

Expand Down Expand Up @@ -197,6 +202,11 @@ impl UpdaterBuilder {
self
}

pub fn on_before_exit<F: Fn() -> () + Send + Sync + 'static>(mut self, f: F) -> Self {
self.on_before_exit.replace(Arc::new(f));
self
}

pub fn build(self) -> Result<Updater> {
let endpoints = self
.endpoints
Expand Down Expand Up @@ -236,6 +246,7 @@ impl UpdaterBuilder {
json_target,
headers: self.headers,
extract_path,
on_before_exit: self.on_before_exit,
})
}
}
Expand All @@ -256,6 +267,7 @@ pub struct Updater {
json_target: String,
headers: HeaderMap,
extract_path: PathBuf,
on_before_exit: Option<OnBeforeExit>,
}

impl Updater {
Expand Down Expand Up @@ -354,6 +366,7 @@ impl Updater {
let update = if should_update {
Some(Update {
config: self.config.clone(),
on_before_exit: self.on_before_exit.clone(),
current_version: self.current_version.to_string(),
target: self.target.clone(),
extract_path: self.extract_path.clone(),
Expand All @@ -375,9 +388,10 @@ impl Updater {
}
}

#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct Update {
config: Config,
on_before_exit: Option<OnBeforeExit>,
/// Update description
pub body: Option<String>,
/// Version used to check for update
Expand Down Expand Up @@ -475,27 +489,22 @@ impl Update {
}

/// Installs the updater package downloaded by [`Update::download`]
pub fn install<R: tauri::Runtime>(&self, app: &AppHandle<R>, bytes: Vec<u8>) -> Result<()> {
self.install_inner(app, bytes)
pub fn install(&self, bytes: Vec<u8>) -> Result<()> {
self.install_inner(bytes)
}

/// Downloads and installs the updater package
pub async fn download_and_install<
R: tauri::Runtime,
C: FnMut(usize, Option<u64>),
D: FnOnce(),
>(
pub async fn download_and_install<C: FnMut(usize, Option<u64>), D: FnOnce()>(
&self,
app: &AppHandle<R>,
on_chunk: C,
on_download_finish: D,
) -> Result<()> {
let bytes = self.download(on_chunk, on_download_finish).await?;
self.install(app, bytes)
self.install(bytes)
}

#[cfg(mobile)]
fn install_inner<R: tauri::Runtime>(&self, _app: &AppHandle<R>, _bytes: Vec<u8>) -> Result<()> {
fn install_inner(&self, _bytes: Vec<u8>) -> Result<()> {
Ok(())
}

Expand All @@ -516,7 +525,7 @@ impl Update {
// ## EXE
// Update server can provide a custom EXE (installer) who can run any task.
#[cfg(windows)]
fn install_inner<R: tauri::Runtime>(&self, app: &AppHandle<R>, bytes: Vec<u8>) -> Result<()> {
fn install_inner(&self, bytes: Vec<u8>) -> Result<()> {
use std::fs;
use windows_sys::{
w,
Expand Down Expand Up @@ -562,7 +571,9 @@ impl Update {
continue;
}

app.cleanup_before_exit();
if let Some(on_before_exit) = self.on_before_exit.as_ref() {
on_before_exit();
}

let file = encode_wide(found_path.as_os_str());
let parameters = encode_wide(installer_args.join(OsStr::new(" ")).as_os_str());
Expand Down Expand Up @@ -600,7 +611,7 @@ impl Update {
target_os = "netbsd",
target_os = "openbsd"
))]
fn install_inner<R: tauri::Runtime>(&self, _app: &AppHandle<R>, bytes: Vec<u8>) -> Result<()> {
fn install_inner(&self, bytes: Vec<u8>) -> Result<()> {
use flate2::read::GzDecoder;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let archive = Cursor::new(bytes);
Expand Down Expand Up @@ -666,7 +677,7 @@ impl Update {
// │ └── ...
// └── ...
#[cfg(target_os = "macos")]
fn install_inner<R: tauri::Runtime>(&self, _app: &AppHandle<R>, bytes: Vec<u8>) -> Result<()> {
fn install_inner(&self, bytes: Vec<u8>) -> Result<()> {
use flate2::read::GzDecoder;

let cursor = Cursor::new(bytes);
Expand Down
5 changes: 1 addition & 4 deletions plugins/updater/tests/app-updater/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,7 @@ fn main() {

match updater.check().await {
Ok(Some(update)) => {
if let Err(e) = update
.download_and_install(handle.app_handle(), |_, _| {}, || {})
.await
{
if let Err(e) = update.download_and_install(|_, _| {}, || {}).await {
println!("{e}");
std::process::exit(1);
}
Expand Down

0 comments on commit b4185ed

Please sign in to comment.