feat(updater): add plugin (#350)
Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>pull/353/head
parent
012d32e8ed
commit
a95fb473a2
File diff suppressed because it is too large
Load Diff
@ -1,76 +1,86 @@
|
||||
<script>
|
||||
import { onMount, onDestroy } from 'svelte'
|
||||
import { check } from "tauri-plugin-updater-api";
|
||||
import { relaunch } from "tauri-plugin-process-api";
|
||||
|
||||
// This example show how updater events work when dialog is disabled.
|
||||
// This allow you to use custom dialog for the updater.
|
||||
// This is your responsibility to restart the application after you receive the STATUS: DONE.
|
||||
export let onMessage;
|
||||
|
||||
import { checkUpdate, installUpdate } from '@tauri-apps/api/updater'
|
||||
import { listen } from '@tauri-apps/api/event'
|
||||
import { relaunch } from 'tauri-plugin-process-api'
|
||||
let isChecking, isInstalling, newUpdate;
|
||||
let totalSize = 0,
|
||||
downloadedSize = 0;
|
||||
|
||||
export let onMessage
|
||||
let unlisten
|
||||
|
||||
onMount(async () => {
|
||||
unlisten = await listen('tauri://update-status', onMessage)
|
||||
})
|
||||
onDestroy(() => {
|
||||
if (unlisten) {
|
||||
unlisten()
|
||||
}
|
||||
})
|
||||
|
||||
let isChecking, isInstalling, newUpdate
|
||||
|
||||
async function check() {
|
||||
isChecking = true
|
||||
async function checkUpdate() {
|
||||
isChecking = true;
|
||||
try {
|
||||
const { shouldUpdate, manifest } = await checkUpdate()
|
||||
onMessage(`Should update: ${shouldUpdate}`)
|
||||
onMessage(manifest)
|
||||
const update = await check();
|
||||
onMessage(`Should update: ${update.response.available}`);
|
||||
onMessage(update.response);
|
||||
|
||||
newUpdate = shouldUpdate
|
||||
newUpdate = update;
|
||||
} catch (e) {
|
||||
onMessage(e)
|
||||
onMessage(e);
|
||||
} finally {
|
||||
isChecking = false
|
||||
isChecking = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function install() {
|
||||
isInstalling = true
|
||||
isInstalling = true;
|
||||
downloadedSize = 0;
|
||||
try {
|
||||
await installUpdate()
|
||||
onMessage('Installation complete, restart required.')
|
||||
await relaunch()
|
||||
await newUpdate.downloadAndInstall((downloadProgress) => {
|
||||
switch (downloadProgress.event) {
|
||||
case "Started":
|
||||
totalSize = downloadProgress.data.contentLength;
|
||||
break;
|
||||
case "Progress":
|
||||
downloadedSize += downloadProgress.data.chunkLength;
|
||||
break;
|
||||
case "Finished":
|
||||
break;
|
||||
}
|
||||
});
|
||||
onMessage("Installation complete, restarting...");
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
await relaunch();
|
||||
} catch (e) {
|
||||
onMessage(e)
|
||||
console.error(e);
|
||||
onMessage(e);
|
||||
} finally {
|
||||
isInstalling = false
|
||||
isInstalling = false;
|
||||
}
|
||||
}
|
||||
|
||||
$: progress = totalSize ? Math.round((downloadedSize / totalSize) * 100) : 0;
|
||||
</script>
|
||||
|
||||
<div class="flex children:grow children:h10">
|
||||
{#if !isChecking && !newUpdate}
|
||||
<button class="btn" on:click={check}>Check update</button>
|
||||
<button class="btn" on:click={checkUpdate}>Check update</button>
|
||||
{:else if !isInstalling && newUpdate}
|
||||
<button class="btn" on:click={install}>Install update</button>
|
||||
{:else}
|
||||
<button
|
||||
class="btn text-accentText dark:text-darkAccentText flex items-center justify-center"
|
||||
><div class="spinner animate-spin" /></button
|
||||
>
|
||||
<div class="progress">
|
||||
<span>{progress}%</span>
|
||||
<div class="progress-bar" style="width: {progress}%" />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.spinner {
|
||||
height: 1.2rem;
|
||||
width: 1.2rem;
|
||||
border-radius: 50rem;
|
||||
color: currentColor;
|
||||
border: 2px dashed currentColor;
|
||||
.progress {
|
||||
width: 100%;
|
||||
height: 50px;
|
||||
position: relative;
|
||||
margin-top: 5%;
|
||||
}
|
||||
|
||||
.progress > span {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
height: 30px;
|
||||
background-color: hsl(32, 94%, 46%);
|
||||
border: 1px solid #333;
|
||||
}
|
||||
</style>
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,39 @@
|
||||
[package]
|
||||
name = "tauri-plugin-updater"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
#edition.workspace = true
|
||||
#authors.workspace = true
|
||||
#license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
#tauri = { workspace = true, features = ["updater"] }
|
||||
#serde.workspace = true
|
||||
#serde_json.workspace = true
|
||||
#thiserror.workspace = true
|
||||
tauri = { git = "https://github.com/tauri-apps/tauri", branch = "next", features = ["updater", "fs-extract-api"] }
|
||||
serde = "1"
|
||||
serde_json = "1"
|
||||
thiserror = "1"
|
||||
|
||||
tokio = "1"
|
||||
reqwest = { version = "0.11", default-features = false, features = [ "json", "stream" ] }
|
||||
url = "2"
|
||||
http = "0.2"
|
||||
dirs-next = "2"
|
||||
minisign-verify = "0.2"
|
||||
time = { version = "0.3", features = [ "parsing", "formatting" ] }
|
||||
base64 = "0.21"
|
||||
percent-encoding = "2"
|
||||
semver = { version = "1", features = [ "serde" ] }
|
||||
futures-util = "0.3"
|
||||
tempfile = "3"
|
||||
|
||||
[dev-dependencies]
|
||||
mockito = "0.31"
|
||||
tokio-test = "0.4.2"
|
||||
|
||||
[features]
|
||||
native-tls = [ "reqwest/native-tls" ]
|
||||
native-tls-vendored = [ "reqwest/native-tls-vendored" ]
|
||||
rustls-tls = [ "reqwest/rustls-tls" ]
|
@ -0,0 +1,20 @@
|
||||
SPDXVersion: SPDX-2.1
|
||||
DataLicense: CC0-1.0
|
||||
PackageName: tauri
|
||||
DataFormat: SPDXRef-1
|
||||
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
|
||||
PackageHomePage: https://tauri.app
|
||||
PackageLicenseDeclared: Apache-2.0
|
||||
PackageLicenseDeclared: MIT
|
||||
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
|
||||
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
|
||||
and small desktop applications using a web frontend.
|
||||
</text>
|
||||
PackageComment: <text>The package includes the following libraries; see
|
||||
Relationship information.
|
||||
</text>
|
||||
Created: 2019-05-20T09:00:00Z
|
||||
PackageDownloadLocation: git://github.com/tauri-apps/tauri
|
||||
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
|
||||
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
|
||||
Creator: Person: Daniel Thompson-Yvetot
|
@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@ -0,0 +1,65 @@
|
||||
# Updater plugin
|
||||
|
||||
In-app updates for Tauri applications.
|
||||
|
||||
## Install
|
||||
|
||||
_This plugin requires a Rust version of at least **1.64**_
|
||||
|
||||
There are three general methods of installation that we can recommend.
|
||||
|
||||
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
|
||||
2. Pull sources directly from Github using git tags / revision hashes (most secure)
|
||||
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
|
||||
|
||||
Install the Core plugin by adding the following to your `Cargo.toml` file:
|
||||
|
||||
`src-tauri/Cargo.toml`
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tauri-plugin-updater = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
```
|
||||
|
||||
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
|
||||
|
||||
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
|
||||
|
||||
```sh
|
||||
pnpm add https://github.com/tauri-apps/tauri-plugin-updater#v2
|
||||
# or
|
||||
npm add https://github.com/tauri-apps/tauri-plugin-updater#v2
|
||||
# or
|
||||
yarn add https://github.com/tauri-apps/tauri-plugin-updater#v2
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
First you need to register the core plugin with Tauri:
|
||||
|
||||
`src-tauri/src/main.rs`
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
|
||||
|
||||
```javascript
|
||||
import * as updater from "tauri-plugin-updater-api";
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
|
||||
|
||||
## License
|
||||
|
||||
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
|
||||
|
||||
MIT or MIT/Apache 2.0 where applicable.
|
@ -0,0 +1,14 @@
|
||||
fn main() {
|
||||
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
let mobile = target_os == "ios" || target_os == "android";
|
||||
alias("desktop", !mobile);
|
||||
alias("mobile", mobile);
|
||||
}
|
||||
|
||||
// creates a cfg alias if `has_feature` is true.
|
||||
// `alias` must be a snake case string.
|
||||
fn alias(alias: &str, has_feature: bool) {
|
||||
if has_feature {
|
||||
println!("cargo:rustc-cfg={alias}");
|
||||
}
|
||||
}
|
@ -0,0 +1,84 @@
|
||||
import { invoke, transformCallback } from "@tauri-apps/api/tauri";
|
||||
|
||||
interface CheckOptions {
|
||||
/**
|
||||
* Request headers
|
||||
*/
|
||||
headers?: Record<string, unknown>;
|
||||
/**
|
||||
* Timeout in seconds
|
||||
*/
|
||||
timeout?: number;
|
||||
/**
|
||||
* Target identifier for the running application. This is sent to the backend.
|
||||
*/
|
||||
target?: string;
|
||||
}
|
||||
|
||||
interface UpdateResponse {
|
||||
available: boolean;
|
||||
currentVersion: string;
|
||||
latestVersion: string;
|
||||
date?: string;
|
||||
body?: string;
|
||||
}
|
||||
|
||||
// TODO: use channel from @tauri-apps/api on v2
|
||||
class Channel<T = unknown> {
|
||||
id: number;
|
||||
// @ts-expect-error field used by the IPC serializer
|
||||
private readonly __TAURI_CHANNEL_MARKER__ = true;
|
||||
#onmessage: (response: T) => void = () => {
|
||||
// no-op
|
||||
};
|
||||
|
||||
constructor() {
|
||||
this.id = transformCallback((response: T) => {
|
||||
this.#onmessage(response);
|
||||
});
|
||||
}
|
||||
|
||||
set onmessage(handler: (response: T) => void) {
|
||||
this.#onmessage = handler;
|
||||
}
|
||||
|
||||
get onmessage(): (response: T) => void {
|
||||
return this.#onmessage;
|
||||
}
|
||||
|
||||
toJSON(): string {
|
||||
return `__CHANNEL__:${this.id}`;
|
||||
}
|
||||
}
|
||||
|
||||
type DownloadEvent =
|
||||
| { event: "Started"; data: { contentLength?: number } }
|
||||
| { event: "Progress"; data: { chunkLength: number } }
|
||||
| { event: "Finished" };
|
||||
|
||||
class Update {
|
||||
response: UpdateResponse;
|
||||
|
||||
constructor(response: UpdateResponse) {
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
async downloadAndInstall(
|
||||
onEvent?: (progress: DownloadEvent) => void
|
||||
): Promise<void> {
|
||||
const channel = new Channel<DownloadEvent>();
|
||||
if (onEvent != null) {
|
||||
channel.onmessage = onEvent;
|
||||
}
|
||||
return invoke("plugin:updater|download_and_install", { onEvent: channel });
|
||||
}
|
||||
}
|
||||
|
||||
async function check(options?: CheckOptions): Promise<Update> {
|
||||
return invoke<UpdateResponse>("plugin:updater|check", { ...options }).then(
|
||||
(response) => new Update(response)
|
||||
);
|
||||
}
|
||||
|
||||
export type { CheckOptions, UpdateResponse, DownloadEvent };
|
||||
export { check, Update };
|
@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "tauri-plugin-updater-api",
|
||||
"version": "0.0.0",
|
||||
"license": "MIT or APACHE-2.0",
|
||||
"authors": [
|
||||
"Tauri Programme within The Commons Conservancy"
|
||||
],
|
||||
"type": "module",
|
||||
"browser": "dist-js/index.min.js",
|
||||
"module": "dist-js/index.mjs",
|
||||
"types": "dist-js/index.d.ts",
|
||||
"exports": {
|
||||
"import": "./dist-js/index.mjs",
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"browser": "./dist-js/index.min.js"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c"
|
||||
},
|
||||
"files": [
|
||||
"dist-js",
|
||||
"!dist-js/**/*.map",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"devDependencies": {
|
||||
"tslib": "^2.5.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^1.2.0"
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
import { readFileSync } from "fs";
|
||||
|
||||
import { createConfig } from "../../shared/rollup.config.mjs";
|
||||
|
||||
export default createConfig({
|
||||
input: "guest-js/index.ts",
|
||||
pkg: JSON.parse(
|
||||
readFileSync(new URL("./package.json", import.meta.url), "utf8")
|
||||
),
|
||||
external: [/^@tauri-apps\/api/],
|
||||
});
|
@ -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 }
|
||||
}
|
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()
|
||||
}
|
After Width: | Height: | Size: 11 KiB |
After Width: | Height: | Size: 23 KiB |
After Width: | Height: | Size: 2.2 KiB |
Binary file not shown.
After Width: | Height: | Size: 37 KiB |
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");
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
Loading…
Reference in new issue