feat(updater): add plugin (#350)

Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>
This commit is contained in:
Lucas Fernandes Nogueira
2023-05-11 09:33:24 -07:00
committed by GitHub
parent 012d32e8ed
commit a95fb473a2
38 changed files with 11939 additions and 517 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,20 @@
[package]
name = "app-updater"
version = "0.1.0"
edition = "2021"
#edition.workspace = true
[build-dependencies]
tauri-build = { path = "../../../../../tauri/core/tauri-build", features = [] }
[dependencies]
tauri = { git = "https://github.com/tauri-apps/tauri", branch = "next" }
tauri-plugin-updater = { path = "../.." }
tiny_http = "0.11"
serde = "1"
serde_json = "1"
time = { version = "0.3", features = ["formatting"] }
[features]
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
@@ -0,0 +1,7 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
fn main() {
tauri_build::build()
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

@@ -0,0 +1,49 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use tauri_plugin_updater::UpdaterExt;
fn main() {
let mut context = tauri::generate_context!();
if std::env::var("TARGET").unwrap_or_default() == "nsis" {
// /D sets the default installation directory ($INSTDIR),
// overriding InstallDir and InstallDirRegKey.
// It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces.
// Only absolute paths are supported.
// NOTE: we only need this because this is an integration test and we don't want to install the app in the programs folder
context.config_mut().tauri.updater.windows.installer_args = vec![format!(
"/D={}",
tauri::utils::platform::current_exe()
.unwrap()
.parent()
.unwrap()
.display()
)];
}
tauri::Builder::default()
.plugin(tauri_plugin_updater::Builder::new().build())
.setup(|app| {
let handle = app.handle();
tauri::async_runtime::spawn(async move {
match handle.updater().check().await {
Ok(update) => {
if let Err(e) = update.download_and_install().await {
println!("{e}");
std::process::exit(1);
}
std::process::exit(0);
}
Err(e) => {
println!("{e}");
std::process::exit(1);
}
}
});
Ok(())
})
.run(context)
.expect("error while running tauri application");
}
@@ -0,0 +1,38 @@
{
"$schema": "../../../../node_modules/.pnpm/@tauri-apps+cli@2.0.0-alpha.8/node_modules/@tauri-apps/cli/schema.json",
"build": {
"distDir": [],
"devPath": []
},
"tauri": {
"bundle": {
"active": true,
"targets": "all",
"identifier": "com.tauri.updater",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"category": "DeveloperTool",
"windows": {
"wix": {
"skipWebviewInstall": true
}
}
},
"allowlist": {
"all": false
},
"updater": {
"active": true,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDE5QzMxNjYwNTM5OEUwNTgKUldSWTRKaFRZQmJER1h4d1ZMYVA3dnluSjdpN2RmMldJR09hUFFlZDY0SlFqckkvRUJhZDJVZXAK",
"endpoints": ["http://localhost:3007"],
"windows": {
"installMode": "quiet"
}
}
}
}
@@ -0,0 +1,298 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![allow(dead_code, unused_imports)]
use std::{
collections::HashMap,
fs::File,
path::{Path, PathBuf},
process::Command,
};
use serde::Serialize;
const UPDATER_PRIVATE_KEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IHJzaWduIGVuY3J5cHRlZCBzZWNyZXQga2V5ClJXUlRZMEl5YTBGV3JiTy9lRDZVd3NkL0RoQ1htZmExNDd3RmJaNmRMT1ZGVjczWTBKZ0FBQkFBQUFBQUFBQUFBQUlBQUFBQWdMekUzVkE4K0tWQ1hjeGt1Vkx2QnRUR3pzQjVuV0ZpM2czWXNkRm9hVUxrVnB6TUN3K1NheHJMREhQbUVWVFZRK3NIL1VsMDBHNW5ET1EzQno0UStSb21nRW4vZlpTaXIwZFh5ZmRlL1lSN0dKcHdyOUVPclVvdzFhVkxDVnZrbHM2T1o4Tk1NWEU9Cg==";
#[derive(Serialize)]
struct PackageConfig {
version: &'static str,
}
#[derive(Serialize)]
struct Config {
package: PackageConfig,
}
#[derive(Serialize)]
struct PlatformUpdate {
signature: String,
url: &'static str,
with_elevated_task: bool,
}
#[derive(Serialize)]
struct Update {
version: &'static str,
date: String,
platforms: HashMap<String, PlatformUpdate>,
}
fn get_cli_bin_path(cli_dir: &Path, debug: bool) -> Option<PathBuf> {
let mut cli_bin_path = cli_dir.join(format!(
"target/{}/cargo-tauri",
if debug { "debug" } else { "release" }
));
if cfg!(windows) {
cli_bin_path.set_extension("exe");
}
if cli_bin_path.exists() {
Some(cli_bin_path)
} else {
None
}
}
fn build_app(cwd: &Path, config: &Config, bundle_updater: bool, target: BundleTarget) {
let mut command = Command::new("cargo");
command
.args(["tauri", "build", "--debug", "--verbose"])
.arg("--config")
.arg(serde_json::to_string(config).unwrap())
.current_dir(cwd);
#[cfg(target_os = "linux")]
command.args(["--bundles", target.name()]);
#[cfg(target_os = "macos")]
command.args(["--bundles", target.name()]);
if bundle_updater {
#[cfg(windows)]
command.args(["--bundles", "msi", "nsis"]);
command
.env("TAURI_PRIVATE_KEY", UPDATER_PRIVATE_KEY)
.env("TAURI_KEY_PASSWORD", "")
.args(["--bundles", "updater"]);
} else {
#[cfg(windows)]
command.args(["--bundles", target.name()]);
}
let status = command
.status()
.expect("failed to run Tauri CLI to bundle app");
if !status.code().map(|c| c == 0).unwrap_or(true) {
panic!("failed to bundle app {:?}", status.code());
}
}
#[derive(Copy, Clone)]
enum BundleTarget {
AppImage,
App,
Msi,
Nsis,
}
impl BundleTarget {
fn name(self) -> &'static str {
match self {
Self::AppImage => "appimage",
Self::App => "app",
Self::Msi => "msi",
Self::Nsis => "nsis",
}
}
}
impl Default for BundleTarget {
fn default() -> Self {
#[cfg(any(target_os = "macos", target_os = "ios"))]
return Self::App;
#[cfg(target_os = "linux")]
return Self::App;
#[cfg(windows)]
return Self::Nsis;
}
}
#[cfg(target_os = "linux")]
fn bundle_paths(root_dir: &Path, version: &str) -> Vec<(BundleTarget, PathBuf)> {
vec![(
BundleTarget::AppImage,
root_dir.join(format!(
"target/debug/bundle/appimage/app-updater_{version}_amd64.AppImage"
)),
)]
}
#[cfg(target_os = "macos")]
fn bundle_paths(root_dir: &Path, _version: &str) -> Vec<(BundleTarget, PathBuf)> {
vec![(
BundleTarget::App,
root_dir.join("target/debug/bundle/macos/app-updater.app"),
)]
}
#[cfg(target_os = "ios")]
fn bundle_paths(root_dir: &Path, _version: &str) -> Vec<(BundleTarget, PathBuf)> {
vec![(
BundleTarget::App,
root_dir.join("target/debug/bundle/ios/app-updater.ipa"),
)]
}
#[cfg(target_os = "android")]
fn bundle_path(root_dir: &Path, _version: &str) -> PathBuf {
root_dir.join("target/debug/bundle/android/app-updater.apk")
}
#[cfg(windows)]
fn bundle_paths(root_dir: &Path, version: &str) -> Vec<(BundleTarget, PathBuf)> {
vec![
(
BundleTarget::Nsis,
root_dir.join(format!(
"target/debug/bundle/nsis/app-updater_{version}_x64-setup.exe"
)),
),
(
BundleTarget::Msi,
root_dir.join(format!(
"target/debug/bundle/msi/app-updater_{version}_x64_en-US.msi"
)),
),
]
}
#[test]
#[ignore]
fn update_app() {
let target =
tauri_plugin_updater::target().expect("running updater test in an unsupported platform");
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let root_dir = manifest_dir.clone();
let mut config = Config {
package: PackageConfig { version: "1.0.0" },
};
// bundle app update
build_app(&manifest_dir, &config, true, Default::default());
let updater_zip_ext = if cfg!(windows) { "zip" } else { "tar.gz" };
for (bundle_target, out_bundle_path) in bundle_paths(&root_dir, "1.0.0") {
let bundle_updater_ext = out_bundle_path
.extension()
.unwrap()
.to_str()
.unwrap()
.replace("exe", "nsis");
let signature_path =
out_bundle_path.with_extension(format!("{bundle_updater_ext}.{updater_zip_ext}.sig"));
let signature = std::fs::read_to_string(&signature_path).unwrap_or_else(|_| {
panic!("failed to read signature file {}", signature_path.display())
});
let out_updater_path =
out_bundle_path.with_extension(format!("{}.{}", bundle_updater_ext, updater_zip_ext));
let updater_path = root_dir.join(format!(
"target/debug/{}",
out_updater_path.file_name().unwrap().to_str().unwrap()
));
std::fs::rename(&out_updater_path, &updater_path).expect("failed to rename bundle");
let target = target.clone();
std::thread::spawn(move || {
// start the updater server
let server =
tiny_http::Server::http("localhost:3007").expect("failed to start updater server");
loop {
if let Ok(request) = server.recv() {
match request.url() {
"/" => {
let mut platforms = HashMap::new();
platforms.insert(
target.clone(),
PlatformUpdate {
signature: signature.clone(),
url: "http://localhost:3007/download",
with_elevated_task: false,
},
);
let body = serde_json::to_vec(&Update {
version: "1.0.0",
date: time::OffsetDateTime::now_utc()
.format(&time::format_description::well_known::Rfc3339)
.unwrap(),
platforms,
})
.unwrap();
let len = body.len();
let response = tiny_http::Response::new(
tiny_http::StatusCode(200),
Vec::new(),
std::io::Cursor::new(body),
Some(len),
None,
);
let _ = request.respond(response);
}
"/download" => {
let _ = request.respond(tiny_http::Response::from_file(
File::open(&updater_path).unwrap_or_else(|_| {
panic!(
"failed to open updater bundle {}",
updater_path.display()
)
}),
));
// close server
return;
}
_ => (),
}
}
}
});
config.package.version = "0.1.0";
// bundle initial app version
build_app(&manifest_dir, &config, false, bundle_target);
let mut binary_cmd = if cfg!(windows) {
Command::new(root_dir.join("target/debug/app-updater.exe"))
} else if cfg!(target_os = "macos") {
Command::new(
bundle_paths(&root_dir, "0.1.0")
.first()
.unwrap()
.1
.join("Contents/MacOS/app-updater"),
)
} else if std::env::var("CI").map(|v| v == "true").unwrap_or_default() {
let mut c = Command::new("xvfb-run");
c.arg("--auto-servernum")
.arg(&bundle_paths(&root_dir, "0.1.0").first().unwrap().1);
c
} else {
Command::new(&bundle_paths(&root_dir, "0.1.0").first().unwrap().1)
};
binary_cmd.env("TARGET", bundle_target.name());
let status = binary_cmd.status().expect("failed to run app");
if !status.success() {
panic!("failed to run app");
}
}
}