mirror of
https://github.com/tauri-apps/plugins-workspace.git
synced 2026-06-06 13:53:54 +02:00
feat(updater): add plugin (#350)
Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>
This commit is contained in:
committed by
GitHub
parent
012d32e8ed
commit
a95fb473a2
@@ -0,0 +1,102 @@
|
||||
use crate::{PendingUpdate, Result, UpdaterExt};
|
||||
|
||||
use http::header;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use tauri::{api::ipc::Channel, AppHandle, Runtime, State};
|
||||
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct Metadata {
|
||||
available: bool,
|
||||
current_version: String,
|
||||
latest_version: String,
|
||||
date: Option<String>,
|
||||
body: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct HeaderMap(header::HeaderMap);
|
||||
|
||||
impl<'de> Deserialize<'de> for HeaderMap {
|
||||
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let map = HashMap::<String, String>::deserialize(deserializer)?;
|
||||
let mut headers = header::HeaderMap::default();
|
||||
for (key, value) in map {
|
||||
if let (Ok(key), Ok(value)) = (
|
||||
header::HeaderName::from_bytes(key.as_bytes()),
|
||||
header::HeaderValue::from_str(&value),
|
||||
) {
|
||||
headers.insert(key, value);
|
||||
} else {
|
||||
return Err(serde::de::Error::custom(format!(
|
||||
"invalid header `{key}` `{value}`"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(Self(headers))
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub(crate) async fn check<R: Runtime>(
|
||||
app: AppHandle<R>,
|
||||
pending: State<'_, PendingUpdate<R>>,
|
||||
headers: Option<HeaderMap>,
|
||||
timeout: Option<u64>,
|
||||
target: Option<String>,
|
||||
) -> Result<Metadata> {
|
||||
let mut builder = app.updater();
|
||||
if let Some(headers) = headers {
|
||||
for (k, v) in headers.0.iter() {
|
||||
builder = builder.header(k, v)?;
|
||||
}
|
||||
}
|
||||
if let Some(timeout) = timeout {
|
||||
builder = builder.timeout(Duration::from_secs(timeout));
|
||||
}
|
||||
if let Some(target) = target {
|
||||
builder = builder.target(target);
|
||||
}
|
||||
|
||||
let response = builder.check().await?;
|
||||
|
||||
let metadata = Metadata {
|
||||
available: response.is_update_available(),
|
||||
current_version: response.current_version().to_string(),
|
||||
latest_version: response.latest_version().to_string(),
|
||||
date: response.date().map(|d| d.to_string()),
|
||||
body: response.body().cloned(),
|
||||
};
|
||||
|
||||
pending.0.lock().await.replace(response);
|
||||
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct DownloadProgress {
|
||||
chunk_length: usize,
|
||||
content_length: Option<u64>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub(crate) async fn download_and_install<R: Runtime>(
|
||||
_app: AppHandle<R>,
|
||||
pending: State<'_, PendingUpdate<R>>,
|
||||
on_event: Channel<R>,
|
||||
) -> Result<()> {
|
||||
if let Some(pending) = &*pending.0.lock().await {
|
||||
pending
|
||||
.download_and_install(move |event| {
|
||||
on_event.send(&event).unwrap();
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use http::StatusCode;
|
||||
use serde::{Serialize, Serializer};
|
||||
|
||||
/// All errors that can occur while running the updater.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
/// IO Errors.
|
||||
#[error("`{0}`")]
|
||||
Io(#[from] std::io::Error),
|
||||
/// Semver Errors.
|
||||
#[error("Unable to compare version: {0}")]
|
||||
Semver(#[from] semver::Error),
|
||||
/// JSON (Serde) Errors.
|
||||
#[error("JSON error: {0}")]
|
||||
SerdeJson(#[from] serde_json::Error),
|
||||
/// Minisign is used for signature validation.
|
||||
#[error("Verify signature error: {0}")]
|
||||
Minisign(#[from] minisign_verify::Error),
|
||||
/// Error with Minisign base64 decoding.
|
||||
#[error("Signature decoding error: {0}")]
|
||||
Base64(#[from] base64::DecodeError),
|
||||
/// UTF8 Errors in signature.
|
||||
#[error("The signature {0} could not be decoded, please check if it is a valid base64 string. The signature must be the contents of the `.sig` file generated by the Tauri bundler, as a string.")]
|
||||
SignatureUtf8(String),
|
||||
/// Tauri utils, mainly extract and file move.
|
||||
#[error("Tauri API error: {0}")]
|
||||
TauriApi(#[from] tauri::api::Error),
|
||||
/// Network error.
|
||||
#[error("Download request failed with status: {0}")]
|
||||
DownloadFailed(StatusCode),
|
||||
/// Network error.
|
||||
#[error("Network error: {0}")]
|
||||
Network(#[from] reqwest::Error),
|
||||
/// Failed to serialize header value as string.
|
||||
#[error(transparent)]
|
||||
Utf8(#[from] std::string::FromUtf8Error),
|
||||
/// Could not fetch a valid response from the server.
|
||||
#[error("Could not fetch a valid release JSON from the remote")]
|
||||
ReleaseNotFound,
|
||||
/// Error building updater.
|
||||
#[error("Unable to prepare the updater: {0}")]
|
||||
Builder(String),
|
||||
/// Error building updater.
|
||||
#[error("Unable to extract the new version: {0}")]
|
||||
Extract(String),
|
||||
/// Updater cannot be executed on this Linux package. Currently the updater is enabled only on AppImages.
|
||||
#[error(
|
||||
"Cannot run updater on this Linux package. Currently only an AppImage can be updated."
|
||||
)]
|
||||
UnsupportedLinuxPackage,
|
||||
/// Operating system is not supported.
|
||||
#[error("unsupported OS, expected one of `linux`, `darwin` or `windows`.")]
|
||||
UnsupportedOs,
|
||||
/// Unsupported app architecture.
|
||||
#[error(
|
||||
"Unsupported application architecture, expected one of `x86`, `x86_64`, `arm` or `aarch64`."
|
||||
)]
|
||||
UnsupportedArch,
|
||||
/// The platform was not found on the updater JSON response.
|
||||
#[error("the platform `{0}` was not found on the response `platforms` object")]
|
||||
TargetNotFound(String),
|
||||
/// Triggered when there is NO error and the two versions are equals.
|
||||
/// On client side, it's important to catch this error.
|
||||
#[error("No updates available")]
|
||||
UpToDate,
|
||||
/// The updater responded with an invalid signature type.
|
||||
#[error("the updater response field `{0}` type is invalid, expected {1} but found {2}")]
|
||||
InvalidResponseType(&'static str, &'static str, serde_json::Value),
|
||||
/// HTTP error.
|
||||
#[error(transparent)]
|
||||
Http(#[from] http::Error),
|
||||
/// Temp dir is not on same mount mount. This prevents our updater to rename the AppImage to a temp file.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[error("temp directory is not on the same mount point as the AppImage")]
|
||||
TempDirNotOnSameMountPoint,
|
||||
}
|
||||
|
||||
impl Serialize for Error {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use tauri::{
|
||||
plugin::{Builder as PluginBuilder, TauriPlugin},
|
||||
Manager, Runtime,
|
||||
};
|
||||
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
mod commands;
|
||||
mod error;
|
||||
mod updater;
|
||||
|
||||
pub use error::Error;
|
||||
pub use updater::*;
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
struct UpdaterState {
|
||||
target: Option<String>,
|
||||
}
|
||||
|
||||
struct PendingUpdate<R: Runtime>(Mutex<Option<UpdateResponse<R>>>);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Builder {
|
||||
target: Option<String>,
|
||||
}
|
||||
|
||||
/// Extension trait to use the updater on [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`].
|
||||
pub trait UpdaterExt<R: Runtime> {
|
||||
/// Gets the updater builder to manually check if an update is available.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_updater::UpdaterExt;
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let handle = app.handle();
|
||||
/// tauri::async_runtime::spawn(async move {
|
||||
/// let response = handle.updater().check().await;
|
||||
/// });
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
fn updater(&self) -> updater::UpdateBuilder<R>;
|
||||
}
|
||||
|
||||
impl<R: Runtime, T: Manager<R>> UpdaterExt<R> for T {
|
||||
fn updater(&self) -> updater::UpdateBuilder<R> {
|
||||
updater::builder(self.app_handle())
|
||||
}
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn target(mut self, target: impl Into<String>) -> Self {
|
||||
self.target.replace(target.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
|
||||
let target = self.target;
|
||||
PluginBuilder::<R>::new("updater")
|
||||
.setup(move |app, _api| {
|
||||
app.manage(UpdaterState { target });
|
||||
app.manage(PendingUpdate::<R>(Default::default()));
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::check,
|
||||
commands::download_and_install
|
||||
])
|
||||
.build()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,307 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! The Tauri updater.
|
||||
//!
|
||||
//! The updater is focused on making Tauri's application updates **as safe and transparent as updates to a website**.
|
||||
//!
|
||||
//! For a full guide on setting up the updater, see <https://tauri.app/v1/guides/distribution/updater>.
|
||||
//!
|
||||
//! Check [`UpdateBuilder`] to see how to trigger and customize the updater at runtime.
|
||||
//! ```
|
||||
|
||||
mod core;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use http::header::{HeaderName, HeaderValue};
|
||||
use semver::Version;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
pub use self::core::{DownloadEvent, RemoteRelease};
|
||||
|
||||
use tauri::{AppHandle, Manager, Runtime};
|
||||
|
||||
use crate::Result;
|
||||
|
||||
/// Gets the target string used on the updater.
|
||||
pub fn target() -> Option<String> {
|
||||
if let (Some(target), Some(arch)) = (core::get_updater_target(), core::get_updater_arch()) {
|
||||
Some(format!("{target}-{arch}"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
struct StatusEvent {
|
||||
status: String,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DownloadProgressEvent {
|
||||
chunk_length: usize,
|
||||
content_length: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
struct UpdateManifest {
|
||||
version: String,
|
||||
date: Option<String>,
|
||||
body: String,
|
||||
}
|
||||
|
||||
/// An update check builder.
|
||||
#[derive(Debug)]
|
||||
pub struct UpdateBuilder<R: Runtime> {
|
||||
inner: core::UpdateBuilder<R>,
|
||||
}
|
||||
|
||||
impl<R: Runtime> UpdateBuilder<R> {
|
||||
/// Sets the current platform's target name for the updater.
|
||||
///
|
||||
/// The target is injected in the endpoint URL by replacing `{{target}}`.
|
||||
/// Note that this does not affect the `{{arch}}` variable.
|
||||
///
|
||||
/// If the updater response JSON includes the `platforms` field,
|
||||
/// that object must contain a value for the target key.
|
||||
///
|
||||
/// By default Tauri uses `$OS_NAME` as the replacement for `{{target}}`
|
||||
/// and `$OS_NAME-$ARCH` as the key in the `platforms` object,
|
||||
/// where `$OS_NAME` is the current operating system name "linux", "windows" or "darwin")
|
||||
/// and `$ARCH` is one of the supported architectures ("i686", "x86_64", "armv7" or "aarch64").
|
||||
///
|
||||
/// See [`Builder::updater_target`](crate::Builder#method.updater_target) for a way to set the target globally.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ## Use a macOS Universal binary target name
|
||||
///
|
||||
/// In this example, we set the updater target only on macOS.
|
||||
/// On other platforms, we set the default target.
|
||||
/// Note that `{{target}}` will be replaced with `darwin-universal`,
|
||||
/// but `{{arch}}` is still the running platform's architecture.
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_updater::{target as updater_target, UpdaterExt};
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let handle = app.handle();
|
||||
/// tauri::async_runtime::spawn(async move {
|
||||
/// let builder = handle.updater().target(if cfg!(target_os = "macos") {
|
||||
/// "darwin-universal".to_string()
|
||||
/// } else {
|
||||
/// updater_target().unwrap()
|
||||
/// });
|
||||
/// match builder.check().await {
|
||||
/// Ok(update) => {}
|
||||
/// Err(error) => {}
|
||||
/// }
|
||||
/// });
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// ## Append debug information to the target
|
||||
///
|
||||
/// This allows you to provide updates for both debug and release applications.
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_updater::{UpdaterExt, target as updater_target};
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let handle = app.handle();
|
||||
/// tauri::async_runtime::spawn(async move {
|
||||
/// let kind = if cfg!(debug_assertions) { "debug" } else { "release" };
|
||||
/// let builder = handle.updater().target(format!("{}-{kind}", updater_target().unwrap()));
|
||||
/// match builder.check().await {
|
||||
/// Ok(update) => {}
|
||||
/// Err(error) => {}
|
||||
/// }
|
||||
/// });
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// ## Use the platform's target triple
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_updater::UpdaterExt;
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let handle = app.handle();
|
||||
/// tauri::async_runtime::spawn(async move {
|
||||
/// let builder = handle.updater().target(tauri::utils::platform::target_triple().unwrap());
|
||||
/// match builder.check().await {
|
||||
/// Ok(update) => {}
|
||||
/// Err(error) => {}
|
||||
/// }
|
||||
/// });
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub fn target(mut self, target: impl Into<String>) -> Self {
|
||||
self.inner = self.inner.target(target);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a closure that is invoked to compare the current version and the latest version returned by the updater server.
|
||||
/// The first argument is the current version, and the second one is the latest version.
|
||||
///
|
||||
/// The closure must return `true` if the update should be installed.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// - Always install the version returned by the server:
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_updater::UpdaterExt;
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// app.handle().updater().should_install(|_current, _latest| true);
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub fn should_install<F: FnOnce(&Version, &RemoteRelease) -> bool + Send + 'static>(
|
||||
mut self,
|
||||
f: F,
|
||||
) -> Self {
|
||||
self.inner = self.inner.should_install(f);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the timeout for the requests to the updater endpoints.
|
||||
pub fn timeout(mut self, timeout: Duration) -> Self {
|
||||
self.inner = self.inner.timeout(timeout);
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a `Header` to the request.
|
||||
pub fn header<K, V>(mut self, key: K, value: V) -> Result<Self>
|
||||
where
|
||||
HeaderName: TryFrom<K>,
|
||||
<HeaderName as TryFrom<K>>::Error: Into<http::Error>,
|
||||
HeaderValue: TryFrom<V>,
|
||||
<HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
|
||||
{
|
||||
self.inner = self.inner.header(key, value)?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Check if an update is available.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_updater::{UpdaterExt, DownloadEvent};
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let handle = app.handle();
|
||||
/// tauri::async_runtime::spawn(async move {
|
||||
/// match handle.updater().check().await {
|
||||
/// Ok(update) => {
|
||||
/// if update.is_update_available() {
|
||||
/// update.download_and_install(|event| {
|
||||
/// match event {
|
||||
/// DownloadEvent::Started { content_length } => println!("started! size: {:?}", content_length),
|
||||
/// DownloadEvent::Progress { chunk_length } => println!("Downloaded {chunk_length} bytes"),
|
||||
/// DownloadEvent::Finished => println!("download finished"),
|
||||
/// }
|
||||
/// }).await.unwrap();
|
||||
/// }
|
||||
/// }
|
||||
/// Err(e) => {
|
||||
/// println!("failed to get update: {}", e);
|
||||
/// }
|
||||
/// }
|
||||
/// });
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub async fn check(self) -> Result<UpdateResponse<R>> {
|
||||
self.inner
|
||||
.build()
|
||||
.await
|
||||
.map(|update| UpdateResponse { update })
|
||||
}
|
||||
}
|
||||
|
||||
/// The response of an updater check.
|
||||
pub struct UpdateResponse<R: Runtime> {
|
||||
update: core::Update<R>,
|
||||
}
|
||||
|
||||
impl<R: Runtime> Clone for UpdateResponse<R> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
update: self.update.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Runtime> UpdateResponse<R> {
|
||||
/// Whether the updater found a newer release or not.
|
||||
pub fn is_update_available(&self) -> bool {
|
||||
self.update.should_update
|
||||
}
|
||||
|
||||
/// The current version of the application as read by the updater.
|
||||
pub fn current_version(&self) -> &Version {
|
||||
&self.update.current_version
|
||||
}
|
||||
|
||||
/// The latest version of the application found by the updater.
|
||||
pub fn latest_version(&self) -> &str {
|
||||
&self.update.version
|
||||
}
|
||||
|
||||
/// The update date.
|
||||
pub fn date(&self) -> Option<&OffsetDateTime> {
|
||||
self.update.date.as_ref()
|
||||
}
|
||||
|
||||
/// The update description.
|
||||
pub fn body(&self) -> Option<&String> {
|
||||
self.update.body.as_ref()
|
||||
}
|
||||
|
||||
/// Downloads and installs the update.
|
||||
pub async fn download_and_install<F: Fn(DownloadEvent)>(&self, on_event: F) -> Result<()> {
|
||||
// Launch updater download process
|
||||
// macOS we display the `Ready to restart dialog` asking to restart
|
||||
// Windows is closing the current App and launch the downloaded MSI when ready (the process stop here)
|
||||
// Linux we replace the AppImage by launching a new install, it start a new AppImage instance, so we're closing the previous. (the process stop here)
|
||||
self.update
|
||||
.download_and_install(
|
||||
self.update.app.config().tauri.updater.pubkey.clone(),
|
||||
on_event,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes the [`UpdateBuilder`] using the app configuration.
|
||||
pub fn builder<R: Runtime>(handle: AppHandle<R>) -> UpdateBuilder<R> {
|
||||
let updater_config = &handle.config().tauri.updater;
|
||||
let package_info = handle.package_info().clone();
|
||||
|
||||
// prepare our endpoints
|
||||
let endpoints = updater_config
|
||||
.endpoints
|
||||
.as_ref()
|
||||
.expect("Something wrong with endpoints")
|
||||
.iter()
|
||||
.map(|e| e.to_string())
|
||||
.collect::<Vec<String>>();
|
||||
|
||||
let mut builder = self::core::builder(handle.clone())
|
||||
.urls(&endpoints[..])
|
||||
.current_version(package_info.version);
|
||||
if let Some(target) = &handle.state::<crate::UpdaterState>().target {
|
||||
builder = builder.target(target);
|
||||
}
|
||||
UpdateBuilder { inner: builder }
|
||||
}
|
||||
Reference in New Issue
Block a user