Files
DPM/src/utils/updateCheck.js
T

53 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* =========================================================
客户端更新检测与安装(仅 Windows)
后端 POST /api/update/check 返回最新版本 + 安装包下载地址;
前端 fetch 下载安装包字节 → invoke install_update(写盘 → 启动安装程序 → 退出应用)。
========================================================= */
import { getApiBase } from '../config';
import { invoke } from '@tauri-apps/api/core';
/** 读取真实安装的应用版本(Tauri getVersion = package.json/tauri.conf.json version);失败时兜底。 */
async function getCurrentVersion() {
try {
const { getVersion } = await import('@tauri-apps/api/app');
const v = await getVersion();
return v || '0.1.0';
} catch {
return '0.1.0';
}
}
export async function checkForUpdate() {
try {
const current = await getCurrentVersion();
const res = await fetch(`${getApiBase()}/api/update/check`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ current }),
});
const data = await res.json();
if (data && data.ok) {
return {
current,
latest: data.latest_version,
available: !!data.update_available,
url: `${getApiBase()}${data.download_url || '/download'}`,
name: data.installer_name || 'dpm_update_setup.exe',
};
}
} catch { /* 后端不可达时忽略 */ }
return null;
}
/** 下载安装包并交给后端安装(写盘 → 启动安装程序 → 退出应用)。 */
export async function downloadAndInstall(url, filename) {
const res = await fetch(url);
if (!res.ok) throw new Error(`下载失败(HTTP ${res.status}`);
const buf = new Uint8Array(await res.arrayBuffer());
if (buf.length < 1000) throw new Error('安装包内容无效');
return invoke('install_update', {
bytes: Array.from(buf),
filename: filename || 'dpm_update_setup.exe',
});
}