feat: add manual and optional auto update in settings

This commit is contained in:
Timi
2026-11-07 01:08:59 +08:00
parent b00bba0377
commit 1a5855e1d0
4 changed files with 261 additions and 3 deletions
+9 -3
View File
@@ -1,6 +1,12 @@
import type { CapacitorConfig } from "@capacitor/cli";
const updateUrl = process.env.CAPACITOR_UPDATE_URL;
/**
* 热更新检查接口
*
* 默认指向生产,可用 CAPACITOR_UPDATE_URL 覆盖后指向本地服务调试
* 更新时机由应用内控制(设置页手动检查或用户开启自动检查),插件本身不主动拉取
*/
const updateUrl = process.env.CAPACITOR_UPDATE_URL ?? "https://api.imyeyu.com/app/update/check";
if (updateUrl && !updateUrl.startsWith("https://")) {
throw new Error("热更新接口必须使用 HTTPS");
}
@@ -11,8 +17,8 @@ const config: CapacitorConfig = {
webDir: "dist",
plugins: {
CapacitorUpdater: {
autoUpdate: updateUrl ? "atBackground" : false,
...(updateUrl ? { updateUrl } : {}),
autoUpdate: false,
updateUrl,
statsUrl: ""
}
}
+144
View File
@@ -0,0 +1,144 @@
import { Capacitor } from "@capacitor/core";
import { CapacitorUpdater, type BundleInfo, type LatestVersion } from "@capgo/capacitor-updater";
import { ref } from "vue";
/** 自动检查更新的存储键 */
export const AUTO_UPDATE_KEY = "app.autoUpdate";
/**
* 应用热更新
*
* 只在原生环境可用,Web 端调用会得到 supported = false
*
* 下载完成后调用 next 排队,下次切后台或重启自动生效,不打断当前操作
*/
export function useAppUpdate() {
const supported = Capacitor.isNativePlatform();
const currentVersion = ref("");
const latest = ref<LatestVersion | null>(null);
const checking = ref(false);
const downloading = ref(false);
const percent = ref(0);
const ready = ref<BundleInfo | null>(null);
const error = ref("");
/** 读取当前运行的 Web 包版本,内置包为 builtin */
async function loadCurrent(): Promise<void> {
if (!supported) {
return;
}
try {
const result = await CapacitorUpdater.current();
currentVersion.value = result.bundle?.version ?? "builtin";
} catch {
currentVersion.value = "";
}
}
/** 查询服务端最新版本 */
async function check(): Promise<LatestVersion | null> {
if (!supported) {
error.value = "仅在 App 内可用";
return null;
}
checking.value = true;
error.value = "";
try {
const result = await CapacitorUpdater.getLatest();
latest.value = result;
return result;
} catch (e) {
error.value = e instanceof Error ? e.message : "检查更新失败";
return null;
} finally {
checking.value = false;
}
}
/** 是否发现新版本 */
function hasUpdate(): boolean {
const target = latest.value;
return Boolean(target?.url) && target?.version !== currentVersion.value;
}
/** 下载最新版本并排队等待生效 */
async function download(): Promise<BundleInfo | null> {
const target = latest.value;
if (!target?.url) {
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
});
await CapacitorUpdater.next({ id: bundle.id });
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 reload(): Promise<void> {
await CapacitorUpdater.reload();
}
/** 检查并下载,供启动时自动更新调用 */
async function checkAndDownload(): Promise<boolean> {
await loadCurrent();
const result = await check();
if (!result?.url || result.version === currentVersion.value) {
return false;
}
return (await download()) !== null;
}
return {
supported,
currentVersion,
latest,
checking,
downloading,
percent,
ready,
error,
loadCurrent,
check,
hasUpdate,
download,
reload,
checkAndDownload
};
}
/** 是否开启自动检查更新 */
export function isAutoUpdateEnabled(): boolean {
return localStorage.getItem(AUTO_UPDATE_KEY) === "1";
}
/**
* 启动时静默检查更新
*
* 只下载排队,不重启,下次打开 App 自动生效
*/
export async function runAutoUpdate(): Promise<void> {
if (!Capacitor.isNativePlatform() || !isAutoUpdateEnabled()) {
return;
}
await useAppUpdate().checkAndDownload();
}
+3
View File
@@ -11,6 +11,7 @@ import Network from "timi-web-api/utils/Network";
import { VCan, VRole } from "timi-web-api/utils/directives/Access";
import type { ApiResponse } from "timi-web-api";
import { Message } from "@/utils/message";
import { runAutoUpdate } from "@/composables/useAppUpdate";
import { initializeTwaBridge } from "@/utils/twaBridge";
import { VEntranceTransition } from "timi-tdesign-mobile";
import timiWebStyle from "timi-web/src/assets/style/timi-web.less?inline";
@@ -92,6 +93,8 @@ async function bootstrap(): Promise<void> {
app.mount("#root");
if (Capacitor.isNativePlatform()) {
await CapacitorUpdater.notifyAppReady();
// 用户开启自动检查才执行,只下载排队,不打断当前会话
void runAutoUpdate().catch(() => undefined);
}
}
+105
View File
@@ -47,6 +47,29 @@
</template>
</t-cell>
</t-cell-group>
<t-cell-group title="版本更新" theme="card" v-entrance-transition>
<t-cell title="当前版本" :note="currentVersion || '—'" />
<t-cell title="自动检查更新">
<template #right-icon>
<t-switch :model-value="autoUpdate" @change="handleAutoUpdateChange" />
</template>
</t-cell>
<t-cell
title="检查更新"
:note="updateNote"
:arrow="canCheckUpdate"
@click="handleCheckUpdate"
/>
<div v-if="downloading" class="update-progress">
<t-progress :percentage="percent" :label="false" />
</div>
<t-cell
v-if="ready"
title="立即重启生效"
arrow
@click="handleReload"
/>
</t-cell-group>
</div>
</main>
</div>
@@ -57,6 +80,8 @@ import type { ThemeMode } from "@/store/globalUI";
import { useGlobalUIStore } from "@/store/globalUI";
import SegmentedSlider from "@/components/SegmentedSlider.vue";
import { useSettingStore } from "@/store/settingStore";
import { AUTO_UPDATE_KEY, isAutoUpdateEnabled, useAppUpdate } from "@/composables/useAppUpdate";
import { Message } from "@/utils/message";
defineOptions({
name: "AppSettings"
@@ -112,6 +137,82 @@ async function playSettingSoundPreview(type: "scanSuccess" | "registerSuccess"):
await settingStore.playRegisterSuccessSound();
}
// ---------- 版本更新 ----------
const {
supported: updateSupported,
currentVersion,
latest,
checking,
downloading,
percent,
ready,
error: updateError,
loadCurrent,
check,
hasUpdate,
download,
reload
} = useAppUpdate();
const autoUpdate = ref(isAutoUpdateEnabled());
const canCheckUpdate = computed(() => updateSupported && !checking.value && !downloading.value);
const updateNote = computed<string>(() => {
if (!updateSupported) {
return "仅在 App 内可用";
}
if (downloading.value) {
return `下载中 ${percent.value}%`;
}
if (ready.value) {
return "已下载,下次启动生效";
}
if (checking.value) {
return "检查中";
}
if (latest.value) {
return hasUpdate() ? `发现 v${latest.value.version}` : "已是最新";
}
return "";
});
onMounted(async () => {
await loadCurrent();
});
function handleAutoUpdateChange(value: boolean | string | number): void {
const enabled = value === true;
autoUpdate.value = enabled;
localStorage.setItem(AUTO_UPDATE_KEY, enabled ? "1" : "0");
}
async function handleCheckUpdate(): Promise<void> {
if (!canCheckUpdate.value) {
return;
}
const result = await check();
if (!result) {
Message.error(updateError.value || "检查更新失败");
return;
}
if (!hasUpdate()) {
Message.info("已是最新版本");
return;
}
const bundle = await download();
if (bundle) {
Message.success(`v${bundle.version} 已下载,下次启动生效`);
return;
}
Message.error(updateError.value || "下载失败");
}
async function handleReload(): Promise<void> {
await reload();
}
</script>
<style scoped lang="less">
@@ -150,6 +251,10 @@ async function playSettingSoundPreview(type: "scanSuccess" | "registerSuccess"):
text-align: right;
}
}
.update-progress {
padding: 0 1rem .75rem;
}
}
:global(html.theme-dark) {