Files
gao-customer-h5/src/composables/useAppUpdate.ts
T

286 lines
7.5 KiB
TypeScript

import { Capacitor } from "@capacitor/core";
import { CapacitorUpdater, type BundleInfo, type LatestVersion } from "@capgo/capacitor-updater";
import { DialogPlugin } from "tdesign-mobile-vue";
import { ref } from "vue";
/** 自动更新的存储键 */
export const AUTO_UPDATE_KEY = "app.autoUpdate";
/** Capacitor appId,与 capacitor.config.ts 保持一致 */
export const APP_ID = "com.imyeyu.gao.customer";
/**
* 服务端下发的更新信息
*
* 在插件协议基础上增加更新说明与外壳字段,插件会原样透传:
* note 是更新说明,shell 标记产物为安装包(外壳),mandatory 标记强制更新
*/
export type UpdateInfo = LatestVersion & {
note?: string;
shell?: boolean;
mandatory?: boolean;
shellUrl?: string;
shellVersion?: string;
shellChecksum?: string;
shellMandatory?: boolean;
};
// 模块级状态,页面与启动逻辑共享同一份
const supported = Capacitor.isNativePlatform();
const currentVersion = ref("");
const nativeVersion = ref("");
const latest = ref<UpdateInfo | null>(null);
const checking = ref(false);
const downloading = ref(false);
const percent = ref(0);
const ready = ref<BundleInfo | null>(null);
const error = ref("");
const autoUpdate = ref(localStorage.getItem(AUTO_UPDATE_KEY) === "1");
/** 读取当前运行的 Web 包版本与原生壳版本 */
async function loadCurrent(): Promise<void> {
if (!supported) {
return;
}
try {
const result = await CapacitorUpdater.current();
currentVersion.value = result.bundle?.version ?? "builtin";
nativeVersion.value = result.native ?? "";
} catch {
currentVersion.value = "";
nativeVersion.value = "";
}
}
/** 查询服务端最新版本 */
async function check(): Promise<UpdateInfo | null> {
if (!supported) {
error.value = "仅在 App 内可用";
return null;
}
checking.value = true;
error.value = "";
try {
const result: UpdateInfo = await CapacitorUpdater.getLatest();
// 新协议的独立外壳地址优先,统一转换为页面已有的外壳更新格式
const target: UpdateInfo = result.shellUrl ? {
...result,
url: result.shellUrl,
version: result.shellVersion ?? result.version,
checksum: result.shellChecksum,
mandatory: result.shellMandatory,
shell: true
} : result;
latest.value = target;
return target;
} catch (e) {
error.value = e instanceof Error ? e.message : "检查更新失败";
return null;
} finally {
checking.value = false;
}
}
/** 是否发现新版本(外壳更新不看版本号,只认服务端下发的地址) */
function hasUpdate(): boolean {
const target = latest.value;
if (!target?.url) {
return false;
}
return Boolean(target.shell) || target.version !== currentVersion.value;
}
/** 是否为外壳更新,只能下载安装包覆盖安装,热更装不进去 */
function isShellUpdate(): boolean {
const target = latest.value;
return Boolean(target?.shell && target?.url);
}
/**
* 把安装包交给系统浏览器下载
*
* Capacitor 对非同源地址走 Bridge.launchIntent,用 ACTION_VIEW 外抛给浏览器,
* 安装动作由浏览器和系统安装器发起,应用自身不需要安装权限,所以老壳也能用
*/
function openShellDownload(): void {
const target = latest.value;
if (!target?.url) {
error.value = "没有可下载的版本";
return;
}
window.location.assign(target.url);
}
/** 下载最新版本,只落盘不激活 */
async function download(): Promise<BundleInfo | null> {
const target = latest.value;
if (!target?.url) {
error.value = "没有可下载的版本";
return null;
}
if (target.shell) {
error.value = "外壳更新需要下载安装包";
return null;
}
downloading.value = true;
percent.value = 0;
error.value = "";
const listener = await CapacitorUpdater.addListener("download", info => {
percent.value = info.percent;
});
try {
const bundle = await CapacitorUpdater.download({
url: target.url,
version: target.version,
checksum: target.checksum,
sessionKey: target.sessionKey
});
ready.value = bundle;
return bundle;
} catch (e) {
error.value = e instanceof Error ? e.message : "下载失败";
return null;
} finally {
downloading.value = false;
await listener.remove();
}
}
/** 立即应用并重启 */
async function apply(bundle: BundleInfo): Promise<void> {
error.value = "";
try {
await CapacitorUpdater.set({ id: bundle.id });
} catch (e) {
// 包目录已被清理或本身就是坏的(例如把安装包当热更包下下来),
// set 会报 id 不存在。不清理的话每次启动都卡在「已下载,重启生效」
try {
await CapacitorUpdater.delete({ id: bundle.id });
} catch {
// 包可能已经被插件清理
}
ready.value = null;
error.value = e instanceof Error ? e.message : "更新失败";
}
}
/** 排队到下次启动应用 */
async function defer(bundle: BundleInfo): Promise<void> {
await CapacitorUpdater.next({ id: bundle.id });
}
/** 可以应用的包状态:剩下的都是删除中或下载失败的残骸,set 会报 id 不存在 */
const USABLE_STATUS: Array<BundleInfo["status"]> = ["success", "pending"];
/** 查找已下载但尚未应用的版本 */
async function restorePending(): Promise<void> {
if (!supported) {
return;
}
try {
const [current, list] = await Promise.all([CapacitorUpdater.current(), CapacitorUpdater.list()]);
const currentId = current.bundle?.id;
const pending = list.bundles
.filter(bundle => bundle.id !== currentId && USABLE_STATUS.includes(bundle.status))
.sort((a, b) => Date.parse(b.downloaded) - Date.parse(a.downloaded))[0];
ready.value = pending ?? null;
} catch {
ready.value = null;
}
}
/**
* 应用热更新
*
* 只在原生环境可用,Web 端 supported 恒为 false
*/
export function useAppUpdate() {
return {
supported,
currentVersion,
nativeVersion,
latest,
checking,
downloading,
percent,
ready,
error,
autoUpdate,
loadCurrent,
check,
hasUpdate,
isShellUpdate,
openShellDownload,
download,
apply,
defer,
restorePending
};
}
/** 是否开启自动更新 */
export function isAutoUpdateEnabled(): boolean {
return autoUpdate.value;
}
/** 切换自动更新,同时写入本地存储 */
export function setAutoUpdate(enabled: boolean): void {
autoUpdate.value = enabled;
localStorage.setItem(AUTO_UPDATE_KEY, enabled ? "1" : "0");
}
/** 弹窗让用户决定立即更新还是下次启动 */
function promptUpdate(bundle: BundleInfo): void {
const dialog = DialogPlugin.confirm({
title: "发现新版本",
content: `v${bundle.version} 已下载完成,重启后生效`,
cancelBtn: "稍后更新",
confirmBtn: "现在更新",
onCancel() {
dialog.destroy();
// 稍后更新即排队,下次启动自动应用
void defer(bundle);
},
async onConfirm() {
dialog.destroy();
await apply(bundle);
}
});
}
/**
* 启动时检查更新
*
* 检查每次启动都做;是否静默下载取决于自动更新开关
* 下载完成后弹窗让用户选择立即重启还是稍后
* 外壳更新优先处理:热更包是 JS,装不进旧壳
*/
export async function runAutoUpdate(): Promise<void> {
if (!supported) {
return;
}
await loadCurrent();
await restorePending();
if (ready.value) {
if (isAutoUpdateEnabled()) {
promptUpdate(ready.value);
}
return;
}
const result = await check();
// 外壳更新不弹窗,入口统一在「版本更新」页
if (result?.shell) {
return;
}
if (!result?.url) {
return;
}
if (result.version === currentVersion.value || !isAutoUpdateEnabled()) {
return;
}
await download();
if (ready.value) {
promptUpdate(ready.value);
}
}