diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml
index de057d9..e1dfa04 100644
--- a/.gitea/workflows/release.yml
+++ b/.gitea/workflows/release.yml
@@ -285,6 +285,77 @@ jobs:
-H "Token: $API_TOKEN"
echo "OK: 已发布到 stable"
+ # 打 tag 的时机是「上线成功」而不是「PR 合并」:草稿发布和失败发布都不该留下版本标记。
+ # Gitea 建 release 会顺带创建 tag,所以不需要单独 git push refs/tags。
+ - name: Tag release
+ if: ${{ steps.version.outputs.publish == 'true' }}
+ env:
+ GITEA_TOKEN: ${{ secrets.RUNNER_TOKEN }}
+ GITEA_SERVER_URL: ${{ github.server_url }}
+ GITEA_INTERNAL_URL: ${{ vars.TIMI_GITEA_INTERNAL_URL }}
+ GITEA_REPOSITORY: ${{ github.repository }}
+ VERSION: ${{ steps.version.outputs.version }}
+ TARGET: ${{ github.sha }}
+ NOTE_FILE: release-note.txt
+ MAX_RETRIES: 3
+ RETRY_DELAY: 10
+ run: |
+ if [ -z "$GITEA_TOKEN" ]; then
+ echo "FAIL: 缺少 secrets.RUNNER_TOKEN,无法创建 tag"
+ exit 1
+ fi
+
+ if [ -n "$GITEA_INTERNAL_URL" ]; then
+ api_base_url="$GITEA_INTERNAL_URL"
+ else
+ api_base_url="$GITEA_SERVER_URL"
+ fi
+ api_url="$api_base_url/api/v1/repos/$GITEA_REPOSITORY/releases"
+
+ # 用 node 拼 payload:release note 是多行 markdown,手拼 JSON 会炸
+ payload=$(node -e "
+ const fs = require('fs');
+ const file = process.env.NOTE_FILE;
+ const note = file && fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
+ process.stdout.write(JSON.stringify({
+ tag_name: 'v' + process.env.VERSION,
+ name: 'v' + process.env.VERSION,
+ target_commitish: process.env.TARGET,
+ draft: false,
+ prerelease: false,
+ body: note
+ }));
+ ")
+
+ attempt=1
+ while [ $attempt -le $MAX_RETRIES ]; do
+ echo "[Create release] 第 $attempt/$MAX_RETRIES 次"
+ http_code=$(curl -sS -o /tmp/release.json -w "%{http_code}" -X POST "$api_url" \
+ -H "Authorization: token $GITEA_TOKEN" \
+ -H "Content-Type: application/json" \
+ --connect-timeout 30 \
+ --max-time 60 \
+ -d "$payload" 2>/dev/null) || http_code="000"
+ echo "HTTP Status: $http_code"
+
+ # 409 表示 tag 与 release 已存在(重跑流水线时的正常情况)
+ if [ "$http_code" = "201" ] || [ "$http_code" = "409" ]; then
+ echo "OK: v$VERSION 的 tag 与 release 已就绪"
+ head -c 400 /tmp/release.json
+ echo
+ exit 0
+ fi
+
+ if [ $attempt -lt $MAX_RETRIES ]; then
+ echo "重试中,${RETRY_DELAY}s 后继续"
+ sleep $RETRY_DELAY
+ fi
+ attempt=$((attempt + 1))
+ done
+
+ echo "FAIL: 创建 tag / release 失败(接口或 token 权限问题)"
+ exit 1
+
- name: Summary
run: |
if [ "${{ steps.version.outputs.publish }}" = "true" ]; then
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 200fafa..8b6dc6d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,13 @@ CI 规则(.gitea/workflows/release.yml):
需要更正请发补丁版本
-->
+## v1.5.0
+
+### 调整
+
+- 应用内可以直接下载并安装新版本,不再跳转浏览器;系统提示时请允许本应用安装未知应用
+- 新版本安装完成后登录状态和数据都会保留
+
## v1.4.0
### 新增
diff --git a/NATIVE_UPGRADE.md b/NATIVE_UPGRADE.md
index 8d1d1eb..8f23739 100644
--- a/NATIVE_UPGRADE.md
+++ b/NATIVE_UPGRADE.md
@@ -40,6 +40,11 @@ grep versionCode android/app/build.gradle
- 增删插件后执行 `pnpm exec cap sync android`
- 确认 `capacitor.config.ts` 无遗漏
+- **打壳前先 `pnpm run android:sync:prod` 重建资源**:它用 `.env.production` 构建并会清掉
+ 残留的 `VITE_API_BASE_URL`。真机调试用的 `android:sync:dev`(或 `android:open`)会把局域网地址
+ 写进 `dist` 和 `android/app/src/main/assets/public`,直接拿去打包就会打出一个连内网的正式包
+- 打完核对:`aapt2 dump badging` 的 versionCode、`apksigner verify --print-certs` 的证书,
+ 以及解包 grep 接口地址(内网地址必须为 0 次)
- 用 Android Studio 打包,**签名必须与线上包一致**:线上 1.0.0 用的是
`twa/android.keystore`(alias `gao-customer`,证书 `CN=yeyu` / SHA-256 `3E:9C:CC:8A:…`)。
签名不一致时系统会拒绝覆盖安装,老用户只能卸载重装
diff --git a/android/app/build.gradle b/android/app/build.gradle
index 731ee0b..f5f1e69 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -7,8 +7,8 @@ android {
applicationId "com.imyeyu.gao.customer"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
- versionCode 2
- versionName "1.0.1"
+ versionCode 3
+ versionName "1.1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 994ef2d..1e7c891 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -38,6 +38,7 @@
+
diff --git a/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java b/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java
index ad886a2..8c7b4e3 100644
--- a/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java
+++ b/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java
@@ -14,12 +14,14 @@ import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import com.getcapacitor.BridgeActivity;
+import com.imyeyu.gao.customer.shellupdater.ShellUpdaterPlugin;
import java.util.Locale;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
+ registerPlugin(ShellUpdaterPlugin.class);
super.onCreate(savedInstanceState);
applyEdgeToEdge();
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
diff --git a/android/app/src/main/java/com/imyeyu/gao/customer/shellupdater/ShellUpdaterPlugin.java b/android/app/src/main/java/com/imyeyu/gao/customer/shellupdater/ShellUpdaterPlugin.java
new file mode 100644
index 0000000..f469f49
--- /dev/null
+++ b/android/app/src/main/java/com/imyeyu/gao/customer/shellupdater/ShellUpdaterPlugin.java
@@ -0,0 +1,151 @@
+package com.imyeyu.gao.customer.shellupdater;
+
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Build;
+import android.provider.Settings;
+import androidx.core.content.FileProvider;
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.security.MessageDigest;
+import java.util.Locale;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/// 应用外壳下载与安装
+@CapacitorPlugin(name = "ShellUpdater")
+public class ShellUpdaterPlugin extends Plugin {
+ private final ExecutorService executor = Executors.newSingleThreadExecutor();
+ private final AtomicBoolean downloading = new AtomicBoolean(false);
+ private File directory;
+ private boolean awaitingSettings;
+
+ @Override
+ public void load() {
+ directory = new File(getContext().getCacheDir(), "shell-updates");
+ executor.execute(() -> {
+ File[] files = directory.listFiles();
+ if (files == null) return;
+ // 只清 6 小时前的残留:安装期间进程可能被杀后重启,立刻删除会让安装器读不到文件
+ long cutoff = System.currentTimeMillis() - 6 * 60 * 60 * 1000L;
+ for (File file : files) {
+ if (file.isFile() && file.lastModified() < cutoff) file.delete();
+ }
+ });
+ }
+
+ /// 检查安装未知应用权限
+ @PluginMethod
+ public void canInstall(PluginCall call) {
+ JSObject result = new JSObject();
+ result.put("allowed", Build.VERSION.SDK_INT < Build.VERSION_CODES.O || getContext().getPackageManager().canRequestPackageInstalls());
+ call.resolve(result);
+ }
+
+ /// 打开本应用的安装权限设置
+ @PluginMethod
+ public void openInstallSettings(PluginCall call) {
+ try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getContext().getPackageName()));
+ awaitingSettings = true;
+ getActivity().startActivity(intent);
+ }
+ call.resolve();
+ } catch (Exception e) {
+ call.reject("无法打开安装权限设置", e);
+ }
+ }
+
+ /// 下载并校验安装包,然后打开系统安装器
+ @PluginMethod
+ public void downloadAndInstall(PluginCall call) {
+ String url = call.getString("url");
+ String sha256 = call.getString("sha256");
+ String fileName = call.getString("fileName");
+ if (url == null || sha256 == null || !sha256.matches("(?i)[0-9a-f]{64}") || fileName == null || !fileName.matches("[a-zA-Z0-9._-]+\\.apk")) {
+ call.reject("安装包参数无效");
+ return;
+ }
+ if (!downloading.compareAndSet(false, true)) {
+ call.reject("安装包正在下载");
+ return;
+ }
+ executor.execute(() -> download(call, url, sha256, fileName));
+ }
+
+ private void download(PluginCall call, String address, String expected, String fileName) {
+ File file = new File(directory, fileName);
+ HttpURLConnection connection = null;
+ try {
+ if (!directory.exists() && !directory.mkdirs()) throw new Exception("无法创建下载目录");
+ URL url = new URL(address);
+ if (!"https".equalsIgnoreCase(url.getProtocol()) && !"http".equalsIgnoreCase(url.getProtocol())) throw new Exception("下载地址无效");
+ connection = (HttpURLConnection) url.openConnection();
+ connection.setConnectTimeout(15000);
+ connection.setReadTimeout(30000);
+ connection.setInstanceFollowRedirects(true);
+ if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) throw new Exception("安装包下载失败");
+ long total = connection.getContentLengthLong();
+ long received = 0;
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ try (InputStream input = connection.getInputStream(); FileOutputStream output = new FileOutputStream(file)) {
+ byte[] buffer = new byte[32768];
+ int size;
+ while ((size = input.read(buffer)) != -1) {
+ output.write(buffer, 0, size);
+ digest.update(buffer, 0, size);
+ received += size;
+ JSObject progress = new JSObject();
+ progress.put("received", received);
+ progress.put("total", total);
+ progress.put("percent", 0 < total ? (int) Math.min(100, received * 100 / total) : 0);
+ notifyListeners("downloadProgress", progress);
+ }
+ }
+ StringBuilder actual = new StringBuilder();
+ for (byte b : digest.digest()) actual.append(String.format(Locale.ROOT, "%02x", b & 255));
+ if (!actual.toString().equalsIgnoreCase(expected)) throw new Exception("安装包校验失败");
+ Uri uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", file);
+ Intent intent = new Intent(Intent.ACTION_VIEW);
+ intent.setDataAndType(uri, "application/vnd.android.package-archive");
+ intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
+ getActivity().runOnUiThread(() -> {
+ try {
+ getActivity().startActivity(intent);
+ call.resolve();
+ } catch (Exception e) {
+ call.reject("无法打开系统安装器", e);
+ }
+ });
+ } catch (Exception e) {
+ file.delete();
+ call.reject("安装包下载或校验失败", e);
+ } finally {
+ if (connection != null) connection.disconnect();
+ downloading.set(false);
+ }
+ }
+
+ @Override
+ protected void handleOnResume() {
+ if (awaitingSettings) {
+ awaitingSettings = false;
+ notifyListeners("resume", new JSObject());
+ }
+ }
+
+ @Override
+ protected void handleOnDestroy() {
+ executor.shutdown();
+ }
+}
diff --git a/package.json b/package.json
index b4ef357..bc468e6 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "gao-customer-h5",
"private": true,
- "version": "1.4.0",
+ "version": "1.5.0",
"type": "module",
"scripts": {
"dev": "vite --host",
@@ -14,9 +14,11 @@
"lint": "eslint . --ext .ts,.vue",
"type-check": "vue-tsc -p tsconfig.app.json --noEmit",
"type-check:publish": "vue-tsc -p tsconfig.publish.json --noEmit",
- "android:sync": "pnpm run build && cap sync android",
+ "android:sync:dev": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-sync.ps1 -Mode dev",
+ "android:sync:prod": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-sync.ps1 -Mode prod",
+ "android:sync": "pnpm run android:sync:prod",
"android:open": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-open.ps1",
- "android:apk": "pnpm run android:sync && cd android && gradlew.bat assembleDebug"
+ "android:apk": "pnpm run android:sync:prod && cd android && gradlew.bat assembleDebug"
},
"dependencies": {
"@capacitor/android": "^8",
diff --git a/scripts/android-open.ps1 b/scripts/android-open.ps1
index 5dad8e1..38582b6 100644
--- a/scripts/android-open.ps1
+++ b/scripts/android-open.ps1
@@ -1,13 +1,7 @@
$ErrorActionPreference = "Stop"
-$env:VITE_API_BASE_URL = if ($env:ANDROID_API_BASE_URL) {
- $env:ANDROID_API_BASE_URL
-} else {
- "http://192.168.11.14:18091"
-}
-Write-Host "Android 调试接口地址:$env:VITE_API_BASE_URL"
-
-& pnpm run android:sync
+# 真机调试固定用开发环境构建,环境变量与构建流程统一收在 android-sync.ps1
+& pnpm run android:sync:dev
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& pnpm exec cap open android
diff --git a/scripts/android-sync.ps1 b/scripts/android-sync.ps1
new file mode 100644
index 0000000..9b5c70c
--- /dev/null
+++ b/scripts/android-sync.ps1
@@ -0,0 +1,26 @@
+param(
+ [ValidateSet("dev", "prod")]
+ [string]$Mode = "prod"
+)
+
+$ErrorActionPreference = "Stop"
+
+if ($Mode -eq "dev") {
+ # 调试包打局域网后端:真机访问不到 localhost,模拟器才用 10.0.2.2
+ $env:VITE_API_BASE_URL = if ($env:ANDROID_API_BASE_URL) {
+ $env:ANDROID_API_BASE_URL
+ } else {
+ "http://192.168.11.14:18091"
+ }
+ Write-Host "接口地址(开发):$env:VITE_API_BASE_URL"
+} else {
+ # 生产包只能用 .env.production,父进程残留的同名变量会覆盖文件配置,先清掉
+ Remove-Item Env:VITE_API_BASE_URL -ErrorAction SilentlyContinue
+ Write-Host "接口地址(生产):取 .env.production"
+}
+
+& pnpm run build
+if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+
+& pnpm exec cap sync android
+exit $LASTEXITCODE
diff --git a/src/composables/useAppUpdate.ts b/src/composables/useAppUpdate.ts
index d619d09..be7e9bc 100644
--- a/src/composables/useAppUpdate.ts
+++ b/src/composables/useAppUpdate.ts
@@ -12,13 +12,17 @@ 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;
};
// 模块级状态,页面与启动逻辑共享同一份
@@ -57,9 +61,18 @@ async function check(): Promise {
checking.value = true;
error.value = "";
try {
- const result = await CapacitorUpdater.getLatest();
- latest.value = result;
- return result;
+ 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;
@@ -135,7 +148,20 @@ async function download(): Promise {
/** 立即应用并重启 */
async function apply(bundle: BundleInfo): Promise {
- await CapacitorUpdater.set({ id: bundle.id });
+ 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 : "更新失败";
+ }
}
/** 排队到下次启动应用 */
@@ -143,6 +169,9 @@ async function defer(bundle: BundleInfo): Promise {
await CapacitorUpdater.next({ id: bundle.id });
}
+/** 可以应用的包状态:剩下的都是删除中或下载失败的残骸,set 会报 id 不存在 */
+const USABLE_STATUS: Array = ["success", "pending"];
+
/** 查找已下载但尚未应用的版本 */
async function restorePending(): Promise {
if (!supported) {
@@ -152,7 +181,7 @@ async function restorePending(): Promise {
const [current, list] = await Promise.all([CapacitorUpdater.current(), CapacitorUpdater.list()]);
const currentId = current.bundle?.id;
const pending = list.bundles
- .filter(bundle => bundle.id !== currentId)
+ .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 {
@@ -219,27 +248,6 @@ function promptUpdate(bundle: BundleInfo): void {
});
}
-/**
- * 弹窗引导下载安装包
- *
- * 外壳更新装不进热更,只能走浏览器下载后覆盖安装;强制更新不给「稍后」按钮
- */
-function promptShellUpdate(info: UpdateInfo): void {
- const dialog = DialogPlugin.confirm({
- title: "需要安装新版本",
- content: `v${info.version} 是应用外壳更新,需要下载安装包覆盖安装`,
- cancelBtn: info.mandatory ? null : "稍后",
- confirmBtn: "下载安装包",
- onCancel() {
- dialog.destroy();
- },
- onConfirm() {
- dialog.destroy();
- openShellDownload();
- }
- });
-}
-
/**
* 启动时检查更新
*
@@ -260,11 +268,11 @@ export async function runAutoUpdate(): Promise {
return;
}
const result = await check();
- if (!result?.url) {
+ // 外壳更新不弹窗,入口统一在「版本更新」页
+ if (result?.shell) {
return;
}
- if (result.shell) {
- promptShellUpdate(result);
+ if (!result?.url) {
return;
}
if (result.version === currentVersion.value || !isAutoUpdateEnabled()) {
diff --git a/src/composables/useShellUpdate.ts b/src/composables/useShellUpdate.ts
new file mode 100644
index 0000000..f391d0c
--- /dev/null
+++ b/src/composables/useShellUpdate.ts
@@ -0,0 +1,132 @@
+import { Capacitor, registerPlugin, type PluginListenerHandle } from "@capacitor/core";
+import { DialogPlugin } from "tdesign-mobile-vue";
+import type { Ref } from "vue";
+import type { UpdateInfo } from "@/composables/useAppUpdate";
+
+interface ShellUpdaterPlugin {
+ canInstall(): Promise<{ allowed: boolean }>;
+ openInstallSettings(): Promise;
+ downloadAndInstall(options: { url: string; sha256: string; fileName: string }): Promise;
+ addListener(eventName: "downloadProgress", listener: (progress: { percent: number; received: number; total: number }) => void): Promise;
+ addListener(eventName: "resume", listener: () => void): Promise;
+}
+
+const ShellUpdater = registerPlugin("ShellUpdater");
+
+/** 管理更新页的外壳安装和授权流程 */
+export function useShellUpdate(latest: Ref) {
+ const downloading = ref(false);
+ const percent = ref(0);
+ const error = ref("");
+ let waitingForSettings = false;
+ let resumeListener: PluginListenerHandle | undefined;
+ let disposed = false;
+
+ /** 下载并交给系统安装器 */
+ async function install(): Promise {
+ const target = latest.value;
+ if (!target?.url || !target.checksum) {
+ error.value = "缺少安装包地址或校验值";
+ return;
+ }
+ downloading.value = true;
+ percent.value = 0;
+ error.value = "";
+ let listener: PluginListenerHandle | undefined;
+ try {
+ listener = await ShellUpdater.addListener("downloadProgress", progress => {
+ percent.value = progress.percent;
+ });
+ await ShellUpdater.downloadAndInstall({
+ url: target.url,
+ sha256: target.checksum,
+ fileName: `app-${target.version}.apk`
+ });
+ } catch (e) {
+ error.value = e instanceof Error ? e.message : "安装包下载失败";
+ } finally {
+ if (listener) {
+ await listener.remove();
+ }
+ downloading.value = false;
+ }
+ }
+
+ /** 从授权页返回后只检查一次 */
+ async function handleResume(): Promise {
+ if (!waitingForSettings) {
+ return;
+ }
+ waitingForSettings = false;
+ try {
+ const result = await ShellUpdater.canInstall();
+ if (result.allowed) {
+ await install();
+ } else {
+ error.value = "未获得安装权限,可重试或使用浏览器下载";
+ }
+ } catch (e) {
+ error.value = e instanceof Error ? e.message : "检查安装权限失败";
+ }
+ }
+
+ /** 检查权限,旧壳交给浏览器下载 */
+ async function start(): Promise {
+ error.value = "";
+ if (!Capacitor.isPluginAvailable("ShellUpdater")) {
+ if (latest.value?.url) {
+ window.location.assign(latest.value.url);
+ }
+ return;
+ }
+ try {
+ const result = await ShellUpdater.canInstall();
+ if (result.allowed) {
+ await install();
+ return;
+ }
+ const dialog = DialogPlugin.confirm({
+ title: "需要安装权限",
+ content: "请允许此应用安装未知应用,返回后将继续下载并安装。",
+ cancelBtn: "稍后",
+ confirmBtn: "去设置",
+ onCancel() {
+ dialog.destroy();
+ },
+ async onConfirm() {
+ dialog.destroy();
+ waitingForSettings = true;
+ try {
+ await ShellUpdater.openInstallSettings();
+ } catch (e) {
+ waitingForSettings = false;
+ error.value = e instanceof Error ? e.message : "无法打开安装权限设置";
+ }
+ }
+ });
+ } catch (e) {
+ error.value = e instanceof Error ? e.message : "检查安装权限失败";
+ }
+ }
+
+ onMounted(async () => {
+ if (!Capacitor.isPluginAvailable("ShellUpdater")) {
+ return;
+ }
+ const listener = await ShellUpdater.addListener("resume", () => { void handleResume(); });
+ if (disposed) {
+ await listener.remove();
+ } else {
+ resumeListener = listener;
+ }
+ });
+ onUnmounted(async () => {
+ disposed = true;
+ waitingForSettings = false;
+ if (resumeListener) {
+ await resumeListener.remove();
+ }
+ });
+
+ return { downloading, percent, error, start };
+}
diff --git a/src/pages/setting/AppUpdate.vue b/src/pages/setting/AppUpdate.vue
index a1d62b3..a9a9efc 100644
--- a/src/pages/setting/AppUpdate.vue
+++ b/src/pages/setting/AppUpdate.vue
@@ -33,6 +33,11 @@
>
检查更新
+
+
+ 重试
+ 用浏览器下载
+
-
+
(
() => (currentVersion.value && currentVersion.value !== "builtin" ? currentVersion.value : version)
@@ -168,13 +176,13 @@ const displayVersion = computed(
const latestVersionText = computed(() => (hasUpdate() ? `v${latest.value?.version ?? ""}` : ""));
/** 当前所处的更新阶段 */
-const updateStage = computed<"check" | "shell" | "download" | "downloading" | "apply">(() => {
- if (isShellUpdate()) {
- return "shell";
- }
- if (downloading.value) {
+const updateStage = computed<"check" | "shell" | "shell-error" | "download" | "downloading" | "apply">(() => {
+ if (downloading.value || shellDownloading.value) {
return "downloading";
}
+ if (isShellUpdate()) {
+ return shellError.value ? "shell-error" : "shell";
+ }
if (ready.value) {
return "apply";
}
@@ -259,9 +267,9 @@ async function handleCheck(): Promise {
await loadNotes();
}
-/** 外壳更新:交给系统浏览器下载安装包 */
-function handleShellDownload(): void {
- openShellDownload();
+/** 外壳更新:优先使用原生安装能力 */
+async function handleShellDownload(): Promise {
+ await startShellUpdate();
}
async function handleDownload(): Promise {
@@ -279,6 +287,10 @@ async function handleApply(): Promise {
return;
}
await apply(bundle);
+ // 应用成功会直接重启,走到这里说明包是坏的,已经清理掉,提示后可以重新检查
+ if (updateError.value) {
+ Message.error(`更新失败:${updateError.value}`);
+ }
}
diff --git a/src/pages/tabs/component/PendingNoticeBar.vue b/src/pages/tabs/component/PendingNoticeBar.vue
index d0e8df6..d2a1a83 100644
--- a/src/pages/tabs/component/PendingNoticeBar.vue
+++ b/src/pages/tabs/component/PendingNoticeBar.vue
@@ -23,11 +23,21 @@ import { usePendingNoticeStore } from "@/store/pendingNoticeStore";
const pendingNoticeStore = usePendingNoticeStore();
const router = useRouter();
-const { supported, latest, autoUpdate, hasUpdate } = useAppUpdate();
+const { supported, latest, autoUpdate, hasUpdate, isShellUpdate } = useAppUpdate();
const noticeList = computed(() => {
const notices = [...pendingNoticeStore.pendingNoticeList];
- if (supported && !autoUpdate.value && hasUpdate() && latest.value) {
- notices.push({ content: `有可用新版本 v${latest.value.version} 更新`, name: "AppUpdate", query: {} });
+ if (supported && hasUpdate() && latest.value) {
+ // 外壳更新不会自动下载,自动更新开着也必须提示;热更开着开关就不提示了
+ const shell = isShellUpdate();
+ if (shell || !autoUpdate.value) {
+ notices.push({
+ content: shell
+ ? `需要安装新版本 v${latest.value.version},点击前往更新`
+ : `有可用新版本 v${latest.value.version} 更新`,
+ name: "AppUpdate",
+ query: {}
+ });
+ }
}
return notices;
});