Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: 自定义检查更新插件 #554

Merged
merged 1 commit into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 77 additions & 77 deletions src-tauri/Cargo.lock

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ mod plugins;

use core::setup;
use plugins::{
backup, clipboard, fs_extra, locale, macos_permissions, mouse, ocr, paste, tray,
backup, clipboard, fs_extra, locale, macos_permissions, mouse, ocr, paste, tray, updater,
window::{self, show_main_window, MAIN_WINDOW_LABEL, PREFERENCE_WINDOW_LABEL},
};
use tauri::{generate_context, generate_handler, Builder, Manager, WindowEvent};
Expand Down Expand Up @@ -83,6 +83,8 @@ fn main() {
.plugin(macos_permissions::init())
// 自定义托盘插件
.plugin(tray::init())
// 自定义更新插件
.plugin(updater::init())
.invoke_handler(generate_handler![])
// 让 app 保持在后台运行:https://tauri.app/v1/guides/features/system-tray/#preventing-the-app-from-closing
.on_window_event(|event| match event.event() {
Expand Down
3 changes: 0 additions & 3 deletions src-tauri/src/plugins/clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,9 +288,6 @@ async fn write_rtf(
text: String,
rtf: String,
) -> Result<(), String> {
println!("text: {text}");
println!("rtf: {rtf}");

let contents = vec![ClipboardContent::Text(text), ClipboardContent::Rtf(rtf)];

manager
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/plugins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ pub mod mouse;
pub mod ocr;
pub mod paste;
pub mod tray;
pub mod updater;
pub mod window;
58 changes: 58 additions & 0 deletions src-tauri/src/plugins/updater.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use tauri::{
command, generate_handler,
plugin::{Builder, TauriPlugin},
updater::builder,
AppHandle, Wry,
};

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct CheckUpdateResult {
manifest: Option<UpdateManifest>,
should_update: bool,
}

#[derive(Debug, serde::Serialize)]
struct UpdateManifest {
version: String,
date: String,
body: String,
}

#[command]
async fn check_update(app_handle: AppHandle, join_beta: bool) -> Result<CheckUpdateResult, String> {
builder(app_handle)
.header("join-beta", join_beta.to_string())
.map_err(|err| err.to_string())?
.check()
.await
.map(|update| {
let should_update = update.is_update_available();
let version = update.latest_version().to_string();
let date = update.date().unwrap().unix_timestamp().to_string();
let body = update.body().unwrap().to_string();

if should_update {
CheckUpdateResult {
should_update,
manifest: Some(UpdateManifest {
version,
date,
body,
}),
}
} else {
CheckUpdateResult {
should_update,
manifest: None,
}
}
})
.map_err(|err| err.to_string())
}

pub fn init() -> TauriPlugin<Wry> {
Builder::new("updater")
.invoke_handler(generate_handler![check_update])
.build()
}
4 changes: 1 addition & 3 deletions src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,7 @@
},
"updater": {
"active": true,
"endpoints": [
"https://gh-proxy.com/https://github.com/EcoPasteHub/EcoPaste/releases/latest/download/latest.json"
],
"endpoints": ["https://ecopaste-updater.ayangweb.cn/api/update"],
"dialog": false,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDcwNEIyQkUwRjNEMTg4NgpSV1NHR0QwUHZySUVCeXFRQzZ4aEpNRWdFdThVQ2I4b2dSQktRcmNtV1dYTFJJV1h2VmVVZXBWSgo="
}
Expand Down
95 changes: 36 additions & 59 deletions src/components/Update/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { listen } from "@tauri-apps/api/event";
import { relaunch } from "@tauri-apps/api/process";
import {
type UpdateManifest,
checkUpdate,
installUpdate,
onUpdaterEvent,
} from "@tauri-apps/api/updater";
Expand All @@ -20,7 +19,8 @@ interface State {
manifest?: UpdateManifest;
}

const MESSAGE_KEY = "updatable";
const MESSAGE_KEY = "update";

let timer: Timeout;

const Update = () => {
Expand All @@ -31,11 +31,7 @@ const Update = () => {

useMount(() => {
// 监听更新事件
listen<boolean>(LISTEN_KEY.UPDATE_APP, async ({ payload }) => {
check(payload);

if (!payload) return;

listen<boolean>(LISTEN_KEY.UPDATE_APP, () => {
messageApi.open({
key: MESSAGE_KEY,
type: "loading",
Expand All @@ -54,46 +50,50 @@ const Update = () => {

timer = setInterval(check, 1000 * 60 * 60 * 24);
});
});

// 本地化更新时间
const updateTime = useCreation(() => {
const date = state.manifest?.date?.split(" ")?.slice(0, 2)?.join(" ");
// 监听参与测试版本配置变化
watchKey(globalStore.update, "beta", (value) => {
if (!value) return;

return dayjs.utc(date).local().format("YYYY-MM-DD HH:mm:ss");
}, [state.manifest?.date]);
check();
});
});

// 检查更新
const check = async (showMessage = false) => {
try {
const { shouldUpdate, manifest } = await checkUpdate();
const { shouldUpdate, manifest } = await checkUpdate(
globalStore.update.beta,
);

if (shouldUpdate && manifest) {
const { version, body } = manifest;

const isBeta = /[a-z]/.test(version);

if (isBeta && !globalStore.update.beta) {
return showLatestMessage(showMessage);
}
const { version, body, date } = manifest;

showWindow();

messageApi.destroy(MESSAGE_KEY);

manifest.body = replaceManifestBody(body);
Object.assign(manifest, {
version: `v${version}`,
body: replaceManifestBody(body),
date: Number(date) * 1000,
});

Object.assign(state, { manifest, open: true });
} else if (showMessage) {
showLatestMessage();
messageApi.open({
key: MESSAGE_KEY,
type: "success",
content: t("component.app_update.hints.latest_version"),
});
}
} catch {
} catch (error: any) {
if (!showMessage) return;

messageApi.open({
key: MESSAGE_KEY,
type: "error",
content: t("component.app_update.hints.update_check_error"),
content: error,
});
}
};
Expand All @@ -115,17 +115,6 @@ const Update = () => {
);
};

// 显示最新版本的提示信息
const showLatestMessage = (show = true) => {
if (!show) return;

messageApi.open({
key: MESSAGE_KEY,
type: "success",
content: t("component.app_update.hints.latest_version"),
});
};

const handleOk = async () => {
state.downloading = true;

Expand All @@ -136,31 +125,15 @@ const Update = () => {

switch (status) {
case "DONE":
relaunch();
break;
case "PENDING":
messageApi.open({
key: MESSAGE_KEY,
type: "loading",
content: t("component.app_update.hints.downloading_latest_package"),
duration: 0,
});
break;
return relaunch();
case "ERROR":
messageApi.open({
state.downloading = false;

return messageApi.open({
key: MESSAGE_KEY,
type: "error",
content: error,
});

state.downloading = false;
break;
case "UPTODATE":
messageApi.open({
key: MESSAGE_KEY,
type: "success",
content: t("component.app_update.hints.download_complete_restart"),
});
}
});
};
Expand Down Expand Up @@ -194,15 +167,19 @@ const Update = () => {
{t("component.app_update.label.release_version")}:
<span>
v{env.appVersion} 👉{" "}
<a href={`${GITHUB_LINK}/releases/latest`}>
v{state.manifest?.version}
<a
href={`${GITHUB_LINK}/releases/tag/${state.manifest?.version}`}
>
{state.manifest?.version}
</a>
</span>
</Flex>

<Flex align="center">
{t("component.app_update.label.release_time")}:
<span>{updateTime}</span>
<span>
{dayjs(state.manifest?.date).format("YYYY-MM-DD HH:mm:ss")}
</span>
</Flex>

<Flex vertical>
Expand Down
4 changes: 4 additions & 0 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,7 @@ export const WINDOW_LABEL = {
MAIN: "main",
PREFERENCE: "preference",
} as const;

export const UPDATER_PLUGIN = {
CHECK_UPDATE: "plugin:updater|check_update",
};
Loading