Skip to content

Commit 0879a87

Browse files
authored
refactor(updater): migrate to tauri's new resource table (#899)
* refactor(updater): migrate to tauri's new resource table * fmt * fmt * Create updater-js-started-event.md
1 parent 8505a75 commit 0879a87

8 files changed

Lines changed: 58 additions & 46 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"updater": "patch"
3+
"updater-js": "patch"
4+
---
5+
6+
Fix `Started` event not emitted to JS when downloading update.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"updater": "patch"
3+
---
4+
5+
**Breaking change**: Changed `Update::download` and `Update::download_and_install` first argument to take `FnMut` instead of just `Fn`.

plugins/updater/guest-js/index.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// SPDX-License-Identifier: Apache-2.0
33
// SPDX-License-Identifier: MIT
44

5-
import { invoke, Channel } from "@tauri-apps/api/core";
5+
import { invoke, Channel, Resource } from "@tauri-apps/api/core";
66

77
/** Options used to check for updates */
88
interface CheckOptions {
@@ -25,6 +25,7 @@ interface CheckOptions {
2525
}
2626

2727
interface UpdateMetadata {
28+
rid: number;
2829
available: boolean;
2930
currentVersion: string;
3031
version: string;
@@ -38,14 +39,15 @@ type DownloadEvent =
3839
| { event: "Progress"; data: { chunkLength: number } }
3940
| { event: "Finished" };
4041

41-
class Update {
42+
class Update extends Resource {
4243
available: boolean;
4344
currentVersion: string;
4445
version: string;
4546
date?: string;
4647
body?: string;
4748

4849
constructor(metadata: UpdateMetadata) {
50+
super(metadata.rid);
4951
this.available = metadata.available;
5052
this.currentVersion = metadata.currentVersion;
5153
this.version = metadata.version;
@@ -58,11 +60,12 @@ class Update {
5860
onEvent?: (progress: DownloadEvent) => void,
5961
): Promise<void> {
6062
const channel = new Channel<DownloadEvent>();
61-
if (onEvent != null) {
63+
if (onEvent) {
6264
channel.onmessage = onEvent;
6365
}
6466
return invoke("plugin:updater|download_and_install", {
6567
onEvent: channel,
68+
rid: this.rid,
6669
});
6770
}
6871
}
@@ -73,9 +76,9 @@ async function check(options?: CheckOptions): Promise<Update | null> {
7376
options.headers = Array.from(new Headers(options.headers).entries());
7477
}
7578

76-
return invoke<UpdateMetadata>("plugin:updater|check", { ...options }).then(
77-
(meta) => (meta.available ? new Update(meta) : null),
78-
);
79+
return invoke<UpdateMetadata>("plugin:updater|check", {
80+
...options,
81+
}).then((meta) => (meta.available ? new Update(meta) : null));
7982
}
8083

8184
export type { CheckOptions, DownloadEvent };

plugins/updater/src/api-iife.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

plugins/updater/src/commands.rs

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,12 @@
22
// SPDX-License-Identifier: Apache-2.0
33
// SPDX-License-Identifier: MIT
44

5-
use crate::{PendingUpdate, Result, UpdaterExt};
5+
use crate::{Result, Update, UpdaterExt};
66

77
use serde::Serialize;
8-
use tauri::{ipc::Channel, AppHandle, Runtime, State};
8+
use tauri::{ipc::Channel, AppHandle, Manager, ResourceId, Runtime};
99

10-
use std::{
11-
sync::atomic::{AtomicBool, Ordering},
12-
time::Duration,
13-
};
10+
use std::time::Duration;
1411
use url::Url;
1512

1613
#[derive(Debug, Serialize)]
@@ -30,6 +27,7 @@ pub enum DownloadEvent {
3027
#[derive(Serialize, Default)]
3128
#[serde(rename_all = "camelCase")]
3229
pub(crate) struct Metadata {
30+
rid: Option<ResourceId>,
3331
available: bool,
3432
current_version: String,
3533
version: String,
@@ -40,7 +38,6 @@ pub(crate) struct Metadata {
4038
#[tauri::command]
4139
pub(crate) async fn check<R: Runtime>(
4240
app: AppHandle<R>,
43-
pending: State<'_, PendingUpdate>,
4441
headers: Option<Vec<(String, String)>>,
4542
timeout: Option<u64>,
4643
proxy: Option<String>,
@@ -72,38 +69,36 @@ pub(crate) async fn check<R: Runtime>(
7269
metadata.version = update.version.clone();
7370
metadata.date = update.date.map(|d| d.to_string());
7471
metadata.body = update.body.clone();
75-
pending.0.lock().await.replace(update);
72+
metadata.rid = Some(app.resources_table().add(update));
7673
}
7774

7875
Ok(metadata)
7976
}
8077

8178
#[tauri::command]
8279
pub(crate) async fn download_and_install<R: Runtime>(
83-
_app: AppHandle<R>,
84-
pending: State<'_, PendingUpdate>,
80+
app: AppHandle<R>,
81+
rid: ResourceId,
8582
on_event: Channel,
8683
) -> Result<()> {
87-
if let Some(pending) = &*pending.0.lock().await {
88-
let first_chunk = AtomicBool::new(false);
89-
let on_event_c = on_event.clone();
90-
pending
91-
.download_and_install(
92-
move |chunk_length, content_length| {
93-
if first_chunk.swap(false, Ordering::Acquire) {
94-
on_event
95-
.send(DownloadEvent::Started { content_length })
96-
.unwrap();
97-
}
98-
on_event
99-
.send(DownloadEvent::Progress { chunk_length })
100-
.unwrap();
101-
},
102-
move || {
103-
on_event_c.send(&DownloadEvent::Finished).unwrap();
104-
},
105-
)
106-
.await?;
107-
}
84+
let update = app.resources_table().get::<Update>(rid)?;
85+
86+
let mut first_chunk = true;
87+
88+
update
89+
.download_and_install(
90+
|chunk_length, content_length| {
91+
if first_chunk {
92+
first_chunk = !first_chunk;
93+
let _ = on_event.send(DownloadEvent::Started { content_length });
94+
}
95+
let _ = on_event.send(DownloadEvent::Progress { chunk_length });
96+
},
97+
|| {
98+
let _ = on_event.send(&DownloadEvent::Finished);
99+
},
100+
)
101+
.await?;
102+
108103
Ok(())
109104
}

plugins/updater/src/error.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ pub enum Error {
6666
BinaryNotFoundInArchive,
6767
#[error(transparent)]
6868
Http(#[from] http::Error),
69+
#[error(transparent)]
70+
Tauri(#[from] tauri::Error),
6971
}
7072

7173
impl Serialize for Error {

plugins/updater/src/lib.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
)]
1515

1616
use tauri::{
17-
async_runtime::Mutex,
1817
plugin::{Builder as PluginBuilder, TauriPlugin},
1918
Manager, Runtime,
2019
};
@@ -28,8 +27,6 @@ pub use config::Config;
2827
pub use error::{Error, Result};
2928
pub use updater::*;
3029

31-
struct PendingUpdate(Mutex<Option<Update>>);
32-
3330
/// Extension trait to use the updater on [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`].
3431
pub trait UpdaterExt<R: Runtime> {
3532
/// Gets the updater builder to build and updater
@@ -145,7 +142,6 @@ impl Builder {
145142
config.installer_args = installer_args;
146143
}
147144
app.manage(UpdaterState { target, config });
148-
app.manage(PendingUpdate(Default::default()));
149145
Ok(())
150146
})
151147
.invoke_handler(tauri::generate_handler![

plugins/updater/src/updater.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@ use reqwest::{
2020
};
2121
use semver::Version;
2222
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize};
23-
use tauri::utils::{config::UpdaterConfig, platform::current_exe};
23+
use tauri::{
24+
utils::{config::UpdaterConfig, platform::current_exe},
25+
Resource,
26+
};
2427
use time::OffsetDateTime;
2528
use url::Url;
2629

@@ -385,13 +388,15 @@ pub struct Update {
385388
pub headers: HeaderMap,
386389
}
387390

391+
impl Resource for Update {}
392+
388393
impl Update {
389394
/// Downloads the updater package, verifies it then return it as bytes.
390395
///
391396
/// Use [`Update::install`] to install it
392-
pub async fn download<C: Fn(usize, Option<u64>), D: FnOnce()>(
397+
pub async fn download<C: FnMut(usize, Option<u64>), D: FnOnce()>(
393398
&self,
394-
on_chunk: C,
399+
mut on_chunk: C,
395400
on_download_finish: D,
396401
) -> Result<Vec<u8>> {
397402
// set our headers
@@ -458,7 +463,7 @@ impl Update {
458463
}
459464

460465
/// Downloads and installs the updater package
461-
pub async fn download_and_install<C: Fn(usize, Option<u64>), D: FnOnce()>(
466+
pub async fn download_and_install<C: FnMut(usize, Option<u64>), D: FnOnce()>(
462467
&self,
463468
on_chunk: C,
464469
on_download_finish: D,

0 commit comments

Comments
 (0)