mirror of
https://github.com/tauri-apps/tauri-plugin-updater.git
synced 2026-01-31 00:55:19 +01:00
chore: add remaining mirrors (#382)
Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de> Committed via a GitHub action: https://github.com/tauri-apps/plugins-workspace/actions/runs/5038084282 Co-authored-by: lucasfernog <lucasfernog@users.noreply.github.com>
This commit is contained in:
40
Cargo.toml
Normal file
40
Cargo.toml
Normal file
@@ -0,0 +1,40 @@
|
||||
[package]
|
||||
name = "tauri-plugin-updater"
|
||||
version = "1.0.0"
|
||||
edition = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
tauri = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
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"
|
||||
flate2 = "1"
|
||||
tar = "0.4"
|
||||
ignore = "0.4"
|
||||
|
||||
[target."cfg(target_os = \"windows\")".dependencies]
|
||||
zip = { version = "0.6", default-features = false }
|
||||
|
||||
[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" ]
|
||||
20
LICENSE.spdx
Normal file
20
LICENSE.spdx
Normal file
@@ -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
|
||||
177
LICENSE_APACHE-2.0
Normal file
177
LICENSE_APACHE-2.0
Normal file
@@ -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
|
||||
21
LICENSE_MIT
Normal file
21
LICENSE_MIT
Normal file
@@ -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.
|
||||
87
README.md
Normal file
87
README.md
Normal file
@@ -0,0 +1,87 @@
|
||||
# Updater
|
||||
|
||||
In-app updates for Tauri applications.
|
||||
|
||||
- Supported platforms: Windows, Linux and macOS.
|
||||
|
||||
## Install
|
||||
|
||||
_This plugin requires a Rust version of at least **1.65**_
|
||||
|
||||
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
|
||||
# you can add the dependencies on the `[dependencies]` section if you do not target mobile
|
||||
[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]
|
||||
tauri-plugin-updater = "2.0.0-alpha"
|
||||
# alternatively with Git:
|
||||
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 @tauri-apps/plugin-updater
|
||||
# or
|
||||
npm add @tauri-apps/plugin-updater
|
||||
# or
|
||||
yarn add @tauri-apps/plugin-updater
|
||||
|
||||
# alternatively with Git:
|
||||
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()
|
||||
.setup(|app| {
|
||||
#[cfg(desktop)]
|
||||
app.handle().plugin(tauri_plugin_updater::Builder::new().build())?;
|
||||
Ok(())
|
||||
})
|
||||
.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 { check } from "@tauri-apps/plugin-updater";
|
||||
import { relaunch } from "@tauri-apps/plugin-process";
|
||||
const update = await check();
|
||||
if (update.response.available) {
|
||||
await update.downloadAndInstall();
|
||||
await relaunch();
|
||||
}
|
||||
```
|
||||
|
||||
## 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.
|
||||
14
build.rs
Normal file
14
build.rs
Normal file
@@ -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}");
|
||||
}
|
||||
}
|
||||
42
dist-js/index.d.ts
vendored
Normal file
42
dist-js/index.d.ts
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
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;
|
||||
}
|
||||
type DownloadEvent = {
|
||||
event: "Started";
|
||||
data: {
|
||||
contentLength?: number;
|
||||
};
|
||||
} | {
|
||||
event: "Progress";
|
||||
data: {
|
||||
chunkLength: number;
|
||||
};
|
||||
} | {
|
||||
event: "Finished";
|
||||
};
|
||||
declare class Update {
|
||||
response: UpdateResponse;
|
||||
constructor(response: UpdateResponse);
|
||||
downloadAndInstall(onEvent?: (progress: DownloadEvent) => void): Promise<void>;
|
||||
}
|
||||
declare function check(options?: CheckOptions): Promise<Update>;
|
||||
export type { CheckOptions, UpdateResponse, DownloadEvent };
|
||||
export { check, Update };
|
||||
22
dist-js/index.min.js
vendored
Normal file
22
dist-js/index.min.js
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
var f$1=Object.defineProperty;var g=(a,b)=>{for(var c in b)f$1(a,c,{get:b[c],enumerable:!0});};var e=(a,b,c)=>{if(!b.has(a))throw TypeError("Cannot "+c)};var h$1=(a,b,c)=>(e(a,b,"read from private field"),c?c.call(a):b.get(a)),i=(a,b,c)=>{if(b.has(a))throw TypeError("Cannot add the same private member more than once");b instanceof WeakSet?b.add(a):b.set(a,c);},j=(a,b,c,d)=>(e(a,b,"write to private field"),d?d.call(a,c):b.set(a,c),c);
|
||||
|
||||
var f={};g(f,{Channel:()=>a,PluginListener:()=>c,addPluginListener:()=>v,convertFileSrc:()=>m,invoke:()=>u,transformCallback:()=>o});function h(){return window.crypto.getRandomValues(new Uint32Array(1))[0]}function o(t,e=!1){let n=h(),r=`_${n}`;return Object.defineProperty(window,r,{value:i=>(e&&Reflect.deleteProperty(window,r),t?.(i)),writable:!1,configurable:!0}),n}var s,a=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0;i(this,s,()=>{});this.id=o(e=>{h$1(this,s).call(this,e);});}set onmessage(e){j(this,s,e);}get onmessage(){return h$1(this,s)}toJSON(){return `__CHANNEL__:${this.id}`}};s=new WeakMap;var c=class{constructor(e,n,r){this.plugin=e,this.event=n,this.channelId=r;}async unregister(){return u(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function v(t,e,n){let r=new a;return r.onmessage=n,u(`plugin:${t}|register_listener`,{event:e,handler:r}).then(()=>new c(t,e,r.id))}async function u(t,e={}){return new Promise((n,r)=>{let i=o(d=>{n(d),Reflect.deleteProperty(window,`_${g}`);},!0),g=o(d=>{r(d),Reflect.deleteProperty(window,`_${i}`);},!0);window.__TAURI_IPC__({cmd:t,callback:i,error:g,...e});})}function m(t,e="asset"){let n=encodeURIComponent(t);return navigator.userAgent.includes("Windows")?`https://${e}.localhost/${n}`:`${e}://localhost/${n}`}
|
||||
|
||||
class Update {
|
||||
constructor(response) {
|
||||
this.response = response;
|
||||
}
|
||||
async downloadAndInstall(onEvent) {
|
||||
const channel = new a();
|
||||
if (onEvent != null) {
|
||||
channel.onmessage = onEvent;
|
||||
}
|
||||
return u("plugin:updater|download_and_install", { onEvent: channel });
|
||||
}
|
||||
}
|
||||
async function check(options) {
|
||||
return u("plugin:updater|check", { ...options }).then((response) => new Update(response));
|
||||
}
|
||||
|
||||
export { Update, check };
|
||||
//# sourceMappingURL=index.min.js.map
|
||||
1
dist-js/index.min.js.map
Normal file
1
dist-js/index.min.js.map
Normal file
File diff suppressed because one or more lines are too long
20
dist-js/index.mjs
Normal file
20
dist-js/index.mjs
Normal file
@@ -0,0 +1,20 @@
|
||||
import { Channel, invoke } from '@tauri-apps/api/tauri';
|
||||
|
||||
class Update {
|
||||
constructor(response) {
|
||||
this.response = response;
|
||||
}
|
||||
async downloadAndInstall(onEvent) {
|
||||
const channel = new Channel();
|
||||
if (onEvent != null) {
|
||||
channel.onmessage = onEvent;
|
||||
}
|
||||
return invoke("plugin:updater|download_and_install", { onEvent: channel });
|
||||
}
|
||||
}
|
||||
async function check(options) {
|
||||
return invoke("plugin:updater|check", { ...options }).then((response) => new Update(response));
|
||||
}
|
||||
|
||||
export { Update, check };
|
||||
//# sourceMappingURL=index.mjs.map
|
||||
1
dist-js/index.mjs.map
Normal file
1
dist-js/index.mjs.map
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.mjs","sources":["../guest-js/index.ts"],"sourcesContent":[null],"names":[],"mappings":";;AA8BA,MAAM,MAAM,CAAA;AAGV,IAAA,WAAA,CAAY,QAAwB,EAAA;AAClC,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;KAC1B;IAED,MAAM,kBAAkB,CACtB,OAA2C,EAAA;AAE3C,QAAA,MAAM,OAAO,GAAG,IAAI,OAAO,EAAiB,CAAC;QAC7C,IAAI,OAAO,IAAI,IAAI,EAAE;AACnB,YAAA,OAAO,CAAC,SAAS,GAAG,OAAO,CAAC;AAC7B,SAAA;QACD,OAAO,MAAM,CAAC,qCAAqC,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;KAC5E;AACF,CAAA;AAED,eAAe,KAAK,CAAC,OAAsB,EAAA;IACzC,OAAO,MAAM,CAAiB,sBAAsB,EAAE,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,IAAI,CACxE,CAAC,QAAQ,KAAK,IAAI,MAAM,CAAC,QAAQ,CAAC,CACnC,CAAC;AACJ;;;;"}
|
||||
56
guest-js/index.ts
Normal file
56
guest-js/index.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { invoke, Channel } 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;
|
||||
}
|
||||
|
||||
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 };
|
||||
1
node_modules/@tauri-apps/api
generated
vendored
Symbolic link
1
node_modules/@tauri-apps/api
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
||||
../../../../node_modules/.pnpm/@tauri-apps+api@2.0.0-alpha.4/node_modules/@tauri-apps/api
|
||||
1
node_modules/tslib
generated
vendored
Symbolic link
1
node_modules/tslib
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
||||
../../../node_modules/.pnpm/tslib@2.5.0/node_modules/tslib
|
||||
32
package.json
Normal file
32
package.json
Normal file
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "@tauri-apps/plugin-updater",
|
||||
"version": "1.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": "2.0.0-alpha.4"
|
||||
}
|
||||
}
|
||||
11
rollup.config.mjs
Normal file
11
rollup.config.mjs
Normal file
@@ -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/],
|
||||
});
|
||||
102
src/commands.rs
Normal file
102
src/commands.rs
Normal file
@@ -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(())
|
||||
}
|
||||
42
src/config.rs
Normal file
42
src/config.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use url::Url;
|
||||
|
||||
/// Updater configuration.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Config {
|
||||
#[serde(default)]
|
||||
pub endpoints: Vec<UpdaterEndpoint>,
|
||||
/// Additional arguments given to the NSIS or WiX installer.
|
||||
#[serde(default, alias = "installer-args")]
|
||||
pub installer_args: Vec<String>,
|
||||
}
|
||||
|
||||
/// A URL to an updater server.
|
||||
///
|
||||
/// The URL must use the `https` scheme on production.
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub struct UpdaterEndpoint(pub Url);
|
||||
|
||||
impl std::fmt::Display for UpdaterEndpoint {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for UpdaterEndpoint {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let url = Url::deserialize(deserializer)?;
|
||||
#[cfg(all(not(debug_assertions), not(feature = "schema")))]
|
||||
{
|
||||
if url.scheme() != "https" {
|
||||
return Err(serde::de::Error::custom(
|
||||
"The configured updater endpoint must use the `https` protocol.",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(Self(url))
|
||||
}
|
||||
}
|
||||
100
src/error.rs
Normal file
100
src/error.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
// 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,
|
||||
/// The path StripPrefixError error.
|
||||
#[error("Path Error: {0}")]
|
||||
PathPrefix(#[from] std::path::StripPrefixError),
|
||||
/// Ignore error.
|
||||
#[error("failed to walkdir: {0}")]
|
||||
Ignore(#[from] ignore::Error),
|
||||
/// Zip error.
|
||||
#[cfg(windows)]
|
||||
#[error(transparent)]
|
||||
ZipError(#[from] zip::result::ZipError),
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
}
|
||||
96
src/lib.rs
Normal file
96
src/lib.rs
Normal file
@@ -0,0 +1,96 @@
|
||||
use tauri::{
|
||||
plugin::{Builder as PluginBuilder, TauriPlugin},
|
||||
Manager, Runtime,
|
||||
};
|
||||
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
mod commands;
|
||||
mod config;
|
||||
mod error;
|
||||
mod updater;
|
||||
|
||||
pub use config::Config;
|
||||
pub use error::Error;
|
||||
pub use updater::*;
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
struct UpdaterState {
|
||||
target: Option<String>,
|
||||
config: Config,
|
||||
}
|
||||
|
||||
struct PendingUpdate<R: Runtime>(Mutex<Option<UpdateResponse<R>>>);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Builder {
|
||||
target: Option<String>,
|
||||
installer_args: Option<Vec<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 installer_args<I, S>(mut self, args: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: Into<String>,
|
||||
{
|
||||
self.installer_args
|
||||
.replace(args.into_iter().map(Into::into).collect());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build<R: Runtime>(self) -> TauriPlugin<R, Config> {
|
||||
let target = self.target;
|
||||
let installer_args = self.installer_args;
|
||||
PluginBuilder::<R, Config>::new("updater")
|
||||
.setup(move |app, api| {
|
||||
let mut config = api.config().clone();
|
||||
if let Some(installer_args) = installer_args {
|
||||
config.installer_args = installer_args;
|
||||
}
|
||||
app.manage(UpdaterState { target, config });
|
||||
app.manage(PendingUpdate::<R>(Default::default()));
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::check,
|
||||
commands::download_and_install
|
||||
])
|
||||
.build()
|
||||
}
|
||||
}
|
||||
1678
src/updater/core.rs
Normal file
1678
src/updater/core.rs
Normal file
File diff suppressed because it is too large
Load Diff
344
src/updater/extract.rs
Normal file
344
src/updater/extract.rs
Normal file
@@ -0,0 +1,344 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
fs,
|
||||
io::{self, Read, Seek},
|
||||
path::{self, Path},
|
||||
};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// The archive reader.
|
||||
#[derive(Debug)]
|
||||
pub enum ArchiveReader<R: Read + Seek> {
|
||||
/// A plain reader.
|
||||
Plain(R),
|
||||
/// A GZ- compressed reader (decoder).
|
||||
GzCompressed(Box<flate2::read::GzDecoder<R>>),
|
||||
}
|
||||
|
||||
impl<R: Read + Seek> Read for ArchiveReader<R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
match self {
|
||||
Self::Plain(r) => r.read(buf),
|
||||
Self::GzCompressed(decoder) => decoder.read(buf),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Read + Seek> ArchiveReader<R> {
|
||||
#[allow(dead_code)]
|
||||
fn get_mut(&mut self) -> &mut R {
|
||||
match self {
|
||||
Self::Plain(r) => r,
|
||||
Self::GzCompressed(decoder) => decoder.get_mut(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The supported archive formats.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ArchiveFormat {
|
||||
/// Tar archive.
|
||||
Tar(Option<Compression>),
|
||||
/// Zip archive.
|
||||
#[cfg(windows)]
|
||||
Zip,
|
||||
}
|
||||
|
||||
impl ArchiveFormat {
|
||||
fn compression(self) -> Option<Compression> {
|
||||
match self {
|
||||
Self::Tar(c) => c,
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The supported compression types.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Compression {
|
||||
/// Gz compression (e.g. `.tar.gz` archives)
|
||||
Gz,
|
||||
}
|
||||
|
||||
/// The zip entry.
|
||||
#[cfg(windows)]
|
||||
pub struct ZipEntry {
|
||||
path: std::path::PathBuf,
|
||||
is_dir: bool,
|
||||
file_contents: Vec<u8>,
|
||||
}
|
||||
|
||||
/// A read-only view into an entry of an archive.
|
||||
#[non_exhaustive]
|
||||
pub enum Entry<'a, R: Read> {
|
||||
/// An entry of a tar archive.
|
||||
#[non_exhaustive]
|
||||
Tar(Box<tar::Entry<'a, R>>),
|
||||
/// An entry of a zip archive.
|
||||
#[non_exhaustive]
|
||||
#[cfg(windows)]
|
||||
Zip(ZipEntry),
|
||||
}
|
||||
|
||||
impl<'a, R: Read> Entry<'a, R> {
|
||||
/// The entry path.
|
||||
pub fn path(&self) -> Result<Cow<'_, Path>> {
|
||||
match self {
|
||||
Self::Tar(e) => e.path().map_err(Into::into),
|
||||
#[cfg(windows)]
|
||||
Self::Zip(e) => Ok(Cow::Borrowed(&e.path)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract this entry into `into_path`.
|
||||
/// If it's a directory, the target will be created, if it's a file, it'll be extracted at this location.
|
||||
/// Note: You need to include the complete path, with file name and extension.
|
||||
pub fn extract(self, into_path: &path::Path) -> Result<()> {
|
||||
match self {
|
||||
Self::Tar(mut entry) => {
|
||||
// determine if it's a file or a directory
|
||||
if entry.header().entry_type() == tar::EntryType::Directory {
|
||||
// this is a directory, lets create it
|
||||
match fs::create_dir_all(into_path) {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
if e.kind() != io::ErrorKind::AlreadyExists {
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mut out_file = fs::File::create(into_path)?;
|
||||
io::copy(&mut entry, &mut out_file)?;
|
||||
|
||||
// make sure we set permissions
|
||||
if let Ok(mode) = entry.header().mode() {
|
||||
set_perms(into_path, Some(&mut out_file), mode, true)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
Self::Zip(entry) => {
|
||||
if entry.is_dir {
|
||||
// this is a directory, lets create it
|
||||
match fs::create_dir_all(into_path) {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
if e.kind() != io::ErrorKind::AlreadyExists {
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mut out_file = fs::File::create(into_path)?;
|
||||
io::copy(
|
||||
&mut std::io::Cursor::new(entry.file_contents),
|
||||
&mut out_file,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The extract manager to retrieve files from archives.
|
||||
pub struct Extract<'a, R: Read + Seek> {
|
||||
reader: ArchiveReader<R>,
|
||||
archive_format: ArchiveFormat,
|
||||
tar_archive: Option<tar::Archive<&'a mut ArchiveReader<R>>>,
|
||||
}
|
||||
|
||||
impl<'a, R: std::fmt::Debug + Read + Seek> std::fmt::Debug for Extract<'a, R> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Extract")
|
||||
.field("reader", &self.reader)
|
||||
.field("archive_format", &self.archive_format)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, R: Read + Seek> Extract<'a, R> {
|
||||
/// Create archive from reader.
|
||||
pub fn from_cursor(mut reader: R, archive_format: ArchiveFormat) -> Extract<'a, R> {
|
||||
if reader.rewind().is_err() {
|
||||
#[cfg(debug_assertions)]
|
||||
eprintln!("Could not seek to start of the file");
|
||||
}
|
||||
let compression = archive_format.compression();
|
||||
Extract {
|
||||
reader: match compression {
|
||||
Some(Compression::Gz) => {
|
||||
ArchiveReader::GzCompressed(Box::new(flate2::read::GzDecoder::new(reader)))
|
||||
}
|
||||
_ => ArchiveReader::Plain(reader),
|
||||
},
|
||||
archive_format,
|
||||
tar_archive: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the archive content.
|
||||
pub fn with_files<
|
||||
E: Into<Error>,
|
||||
F: FnMut(Entry<'_, &mut ArchiveReader<R>>) -> std::result::Result<bool, E>,
|
||||
>(
|
||||
&'a mut self,
|
||||
mut f: F,
|
||||
) -> Result<()> {
|
||||
match self.archive_format {
|
||||
ArchiveFormat::Tar(_) => {
|
||||
let archive = tar::Archive::new(&mut self.reader);
|
||||
self.tar_archive.replace(archive);
|
||||
for entry in self.tar_archive.as_mut().unwrap().entries()? {
|
||||
let entry = entry?;
|
||||
if entry.path().is_ok() {
|
||||
let stop = f(Entry::Tar(Box::new(entry))).map_err(Into::into)?;
|
||||
if stop {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
ArchiveFormat::Zip => {
|
||||
let mut archive = zip::ZipArchive::new(self.reader.get_mut())?;
|
||||
let file_names = archive
|
||||
.file_names()
|
||||
.map(|f| f.to_string())
|
||||
.collect::<Vec<String>>();
|
||||
for path in file_names {
|
||||
let mut zip_file = archive.by_name(&path)?;
|
||||
let is_dir = zip_file.is_dir();
|
||||
let mut file_contents = Vec::new();
|
||||
zip_file.read_to_end(&mut file_contents)?;
|
||||
let stop = f(Entry::Zip(ZipEntry {
|
||||
path: path.into(),
|
||||
is_dir,
|
||||
file_contents,
|
||||
}))
|
||||
.map_err(Into::into)?;
|
||||
if stop {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Extract an entire source archive into a specified path. If the source is a single compressed
|
||||
/// file and not an archive, it will be extracted into a file with the same name inside of
|
||||
/// `into_dir`.
|
||||
#[allow(dead_code)]
|
||||
pub fn extract_into(&mut self, into_dir: &path::Path) -> Result<()> {
|
||||
match self.archive_format {
|
||||
ArchiveFormat::Tar(_) => {
|
||||
let mut archive = tar::Archive::new(&mut self.reader);
|
||||
archive.unpack(into_dir)?;
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
ArchiveFormat::Zip => {
|
||||
let mut archive = zip::ZipArchive::new(self.reader.get_mut())?;
|
||||
for i in 0..archive.len() {
|
||||
let mut file = archive.by_index(i)?;
|
||||
// Decode the file name from raw bytes instead of using file.name() directly.
|
||||
// file.name() uses String::from_utf8_lossy() which may return messy characters
|
||||
// such as: 爱交易.app/, that does not work as expected.
|
||||
// Here we require the file name must be a valid UTF-8.
|
||||
let file_name = String::from_utf8(file.name_raw().to_vec())?;
|
||||
let out_path = into_dir.join(file_name);
|
||||
if file.is_dir() {
|
||||
fs::create_dir_all(&out_path)?;
|
||||
} else {
|
||||
if let Some(out_path_parent) = out_path.parent() {
|
||||
fs::create_dir_all(out_path_parent)?;
|
||||
}
|
||||
let mut out_file = fs::File::create(&out_path)?;
|
||||
io::copy(&mut file, &mut out_file)?;
|
||||
}
|
||||
// Get and Set permissions
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if let Some(mode) = file.unix_mode() {
|
||||
fs::set_permissions(&out_path, fs::Permissions::from_mode(mode))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn set_perms(
|
||||
dst: &Path,
|
||||
f: Option<&mut std::fs::File>,
|
||||
mode: u32,
|
||||
preserve: bool,
|
||||
) -> io::Result<()> {
|
||||
_set_perms(dst, f, mode, preserve).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!(
|
||||
"failed to set permissions to {mode:o} \
|
||||
for `{}`",
|
||||
dst.display()
|
||||
),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn _set_perms(
|
||||
dst: &Path,
|
||||
f: Option<&mut std::fs::File>,
|
||||
mode: u32,
|
||||
preserve: bool,
|
||||
) -> io::Result<()> {
|
||||
use std::os::unix::prelude::*;
|
||||
|
||||
let mode = if preserve { mode } else { mode & 0o777 };
|
||||
let perm = fs::Permissions::from_mode(mode as _);
|
||||
match f {
|
||||
Some(f) => f.set_permissions(perm),
|
||||
None => fs::set_permissions(dst, perm),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn _set_perms(
|
||||
dst: &Path,
|
||||
f: Option<&mut std::fs::File>,
|
||||
mode: u32,
|
||||
_preserve: bool,
|
||||
) -> io::Result<()> {
|
||||
if mode & 0o200 == 0o200 {
|
||||
return Ok(());
|
||||
}
|
||||
match f {
|
||||
Some(f) => {
|
||||
let mut perm = f.metadata()?.permissions();
|
||||
perm.set_readonly(true);
|
||||
f.set_permissions(perm)
|
||||
}
|
||||
None => {
|
||||
let mut perm = fs::metadata(dst)?.permissions();
|
||||
perm.set_readonly(true);
|
||||
fs::set_permissions(dst, perm)
|
||||
}
|
||||
}
|
||||
}
|
||||
308
src/updater/mod.rs
Normal file
308
src/updater/mod.rs
Normal file
@@ -0,0 +1,308 @@
|
||||
// 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;
|
||||
mod extract;
|
||||
mod move_file;
|
||||
|
||||
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, UpdaterState};
|
||||
|
||||
/// 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.bundle.updater.pubkey.clone(),
|
||||
on_event,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes the [`UpdateBuilder`] using the app configuration.
|
||||
pub fn builder<R: Runtime>(handle: AppHandle<R>) -> UpdateBuilder<R> {
|
||||
let package_info = handle.package_info().clone();
|
||||
|
||||
// prepare our endpoints
|
||||
let endpoints = handle
|
||||
.state::<UpdaterState>()
|
||||
.config
|
||||
.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 }
|
||||
}
|
||||
118
src/updater/move_file.rs
Normal file
118
src/updater/move_file.rs
Normal file
@@ -0,0 +1,118 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use ignore::WalkBuilder;
|
||||
use std::{fs, path};
|
||||
|
||||
use crate::Result;
|
||||
|
||||
/// Moves a file from the given path to the specified destination.
|
||||
///
|
||||
/// `source` and `dest` must be on the same filesystem.
|
||||
/// If `replace_using_temp` is specified, the destination file will be
|
||||
/// replaced using the given temporary path.
|
||||
///
|
||||
/// * Errors:
|
||||
/// * Io - copying / renaming
|
||||
#[derive(Debug)]
|
||||
pub struct Move<'a> {
|
||||
source: &'a path::Path,
|
||||
temp: Option<&'a path::Path>,
|
||||
}
|
||||
impl<'a> Move<'a> {
|
||||
/// Specify source file
|
||||
pub fn from_source(source: &'a path::Path) -> Move<'a> {
|
||||
Self { source, temp: None }
|
||||
}
|
||||
|
||||
/// If specified and the destination file already exists, the "destination"
|
||||
/// file will be moved to the given temporary location before the "source"
|
||||
/// file is moved to the "destination" file.
|
||||
///
|
||||
/// In the event of an `io` error while renaming "source" to "destination",
|
||||
/// the temporary file will be moved back to "destination".
|
||||
///
|
||||
/// The `temp` dir must be explicitly provided since `rename` operations require
|
||||
/// files to live on the same filesystem.
|
||||
#[allow(dead_code)]
|
||||
pub fn replace_using_temp(&mut self, temp: &'a path::Path) -> &mut Self {
|
||||
self.temp = Some(temp);
|
||||
self
|
||||
}
|
||||
|
||||
/// Move source file to specified destination (replace whole directory)
|
||||
pub fn to_dest(&self, dest: &path::Path) -> Result<()> {
|
||||
match self.temp {
|
||||
None => {
|
||||
fs::rename(self.source, dest)?;
|
||||
}
|
||||
Some(temp) => {
|
||||
if dest.exists() {
|
||||
fs::rename(dest, temp)?;
|
||||
if let Err(e) = fs::rename(self.source, dest) {
|
||||
fs::rename(temp, dest)?;
|
||||
return Err(e.into());
|
||||
}
|
||||
} else {
|
||||
fs::rename(self.source, dest)?;
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Walk in the source and copy all files and create directories if needed by
|
||||
/// replacing existing elements. (equivalent to a cp -R)
|
||||
#[allow(dead_code)]
|
||||
pub fn walk_to_dest(&self, dest: &path::Path) -> Result<()> {
|
||||
match self.temp {
|
||||
None => {
|
||||
// got no temp -- no need to backup
|
||||
walkdir_and_copy(self.source, dest)?;
|
||||
}
|
||||
Some(temp) => {
|
||||
if dest.exists() {
|
||||
// we got temp and our dest exist, lets make a backup
|
||||
// of current files
|
||||
walkdir_and_copy(dest, temp)?;
|
||||
|
||||
if let Err(e) = walkdir_and_copy(self.source, dest) {
|
||||
// if we got something wrong we reset the dest with our backup
|
||||
fs::rename(temp, dest)?;
|
||||
return Err(e);
|
||||
}
|
||||
} else {
|
||||
// got temp but dest didnt exist
|
||||
walkdir_and_copy(self.source, dest)?;
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
// Walk into the source and create directories, and copy files
|
||||
// Overwriting existing items but keeping untouched the files in the dest
|
||||
// not provided in the source.
|
||||
fn walkdir_and_copy(source: &path::Path, dest: &path::Path) -> Result<()> {
|
||||
let walkdir = WalkBuilder::new(source).hidden(false).build();
|
||||
|
||||
for entry in walkdir {
|
||||
// Check if it's a file
|
||||
|
||||
let element = entry?;
|
||||
let metadata = element.metadata()?;
|
||||
let destination = dest.join(element.path().strip_prefix(source)?);
|
||||
|
||||
// we make sure it's a directory and destination doesnt exist
|
||||
if metadata.is_dir() && !&destination.exists() {
|
||||
fs::create_dir_all(&destination)?;
|
||||
}
|
||||
|
||||
// we make sure it's a file
|
||||
if metadata.is_file() {
|
||||
fs::copy(element.path(), destination)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
0
tests/app-updater/.gitignore
vendored
Normal file
0
tests/app-updater/.gitignore
vendored
Normal file
19
tests/app-updater/Cargo.toml
Normal file
19
tests/app-updater/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "app-updater"
|
||||
version = "0.1.0"
|
||||
edition = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
tauri = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tauri-plugin-updater = { path = "../.." }
|
||||
tiny_http = "0.11"
|
||||
time = { version = "0.3", features = ["formatting"] }
|
||||
|
||||
[features]
|
||||
default = ["custom-protocol"]
|
||||
custom-protocol = ["tauri/custom-protocol"]
|
||||
7
tests/app-updater/build.rs
Normal file
7
tests/app-updater/build.rs
Normal file
@@ -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()
|
||||
}
|
||||
BIN
tests/app-updater/icons/128x128.png
Normal file
BIN
tests/app-updater/icons/128x128.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
BIN
tests/app-updater/icons/128x128@2x.png
Normal file
BIN
tests/app-updater/icons/128x128@2x.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
BIN
tests/app-updater/icons/32x32.png
Normal file
BIN
tests/app-updater/icons/32x32.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.2 KiB |
BIN
tests/app-updater/icons/icon.icns
Normal file
BIN
tests/app-updater/icons/icon.icns
Normal file
Binary file not shown.
BIN
tests/app-updater/icons/icon.ico
Normal file
BIN
tests/app-updater/icons/icon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 37 KiB |
BIN
tests/app-updater/icons/icon.png
Normal file
BIN
tests/app-updater/icons/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
53
tests/app-updater/src/main.rs
Normal file
53
tests/app-updater/src/main.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
// 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() {
|
||||
#[allow(unused_mut)]
|
||||
let mut context = tauri::generate_context!();
|
||||
|
||||
let mut updater = tauri_plugin_updater::Builder::new();
|
||||
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
|
||||
updater = updater.installer_args(vec![format!(
|
||||
"/D={}",
|
||||
tauri::utils::platform::current_exe()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.display()
|
||||
)]);
|
||||
}
|
||||
|
||||
tauri::Builder::default()
|
||||
.plugin(updater.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(|_event| {}).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");
|
||||
}
|
||||
39
tests/app-updater/tauri.conf.json
Normal file
39
tests/app-updater/tauri.conf.json
Normal file
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"$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
|
||||
}
|
||||
},
|
||||
"updater": {
|
||||
"active": true,
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDE5QzMxNjYwNTM5OEUwNTgKUldSWTRKaFRZQmJER1h4d1ZMYVA3dnluSjdpN2RmMldJR09hUFFlZDY0SlFqckkvRUJhZDJVZXAK",
|
||||
"windows": {
|
||||
"installMode": "quiet"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"endpoints": ["http://localhost:3007"]
|
||||
}
|
||||
}
|
||||
}
|
||||
298
tests/app-updater/tests/update.rs
Normal file
298
tests/app-updater/tests/update.rs
Normal file
@@ -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.join("../../../..");
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
4
tsconfig.json
Normal file
4
tsconfig.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user