Merge pull request 'v1.5.0' (#12) from dev into master
Reviewed-on: #12
This commit was merged in pull request #12.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -19,6 +19,13 @@ CI 规则(.gitea/workflows/release.yml):
|
||||
需要更正请发补丁版本
|
||||
-->
|
||||
|
||||
## v1.5.0
|
||||
|
||||
### 调整
|
||||
|
||||
- 应用内可以直接下载并安装新版本,不再跳转浏览器;系统提示时请允许本应用安装未知应用
|
||||
- 新版本安装完成后登录状态和数据都会保留
|
||||
|
||||
## v1.4.0
|
||||
|
||||
### 新增
|
||||
|
||||
@@ -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:…`)。
|
||||
签名不一致时系统会拒绝覆盖安装,老用户只能卸载重装
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
<!-- Permissions -->
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
</manifest>
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+151
@@ -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();
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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<UpdateInfo | null> {
|
||||
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<BundleInfo | null> {
|
||||
|
||||
/** 立即应用并重启 */
|
||||
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 : "更新失败";
|
||||
}
|
||||
}
|
||||
|
||||
/** 排队到下次启动应用 */
|
||||
@@ -143,6 +169,9 @@ 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) {
|
||||
@@ -152,7 +181,7 @@ async function restorePending(): Promise<void> {
|
||||
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<void> {
|
||||
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()) {
|
||||
|
||||
@@ -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<void>;
|
||||
downloadAndInstall(options: { url: string; sha256: string; fileName: string }): Promise<void>;
|
||||
addListener(eventName: "downloadProgress", listener: (progress: { percent: number; received: number; total: number }) => void): Promise<PluginListenerHandle>;
|
||||
addListener(eventName: "resume", listener: () => void): Promise<PluginListenerHandle>;
|
||||
}
|
||||
|
||||
const ShellUpdater = registerPlugin<ShellUpdaterPlugin>("ShellUpdater");
|
||||
|
||||
/** 管理更新页的外壳安装和授权流程 */
|
||||
export function useShellUpdate(latest: Ref<UpdateInfo | null>) {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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 };
|
||||
}
|
||||
@@ -33,6 +33,11 @@
|
||||
>
|
||||
检查更新
|
||||
</t-button>
|
||||
<template v-else-if="updateStage === 'shell-error'">
|
||||
<center-tips><span v-text="shellError" /></center-tips>
|
||||
<t-button class="cell-button" theme="primary" size="large" @click="handleShellDownload">重试</t-button>
|
||||
<t-button class="cell-button" size="large" @click="openShellDownload">用浏览器下载</t-button>
|
||||
</template>
|
||||
<t-button
|
||||
v-else-if="updateStage === 'shell'"
|
||||
class="cell-button"
|
||||
@@ -52,7 +57,7 @@
|
||||
下载更新
|
||||
</t-button>
|
||||
<template v-else-if="updateStage === 'downloading'">
|
||||
<t-progress class="progress" stroke-width=".5rem" :percentage="percent" />
|
||||
<t-progress class="progress" stroke-width=".5rem" :percentage="shellDownloading ? shellPercent : percent" />
|
||||
<t-button
|
||||
class="cell-button"
|
||||
theme="primary"
|
||||
@@ -118,6 +123,7 @@ import { Timeline, TimelineItem, usePane } from "timi-tdesign-mobile";
|
||||
import { MarkdownView, TimeLabel } from "timi-web";
|
||||
import AppUpdateAPI from "@/api/AppUpdateAPI";
|
||||
import { APP_ID, setAutoUpdate, useAppUpdate } from "@/composables/useAppUpdate";
|
||||
import { useShellUpdate } from "@/composables/useShellUpdate";
|
||||
import type { AppUpdateNote } from "@/types/AppUpdate";
|
||||
import { Message } from "@/utils/message";
|
||||
|
||||
@@ -159,6 +165,8 @@ const {
|
||||
restorePending
|
||||
} = useAppUpdate();
|
||||
|
||||
const { downloading: shellDownloading, percent: shellPercent, error: shellError, start: startShellUpdate } = useShellUpdate(latest);
|
||||
|
||||
/** 系统版本:原生端优先取热更包版本,未热更过或 web 端回落到构建版本 */
|
||||
const displayVersion = computed<string>(
|
||||
() => (currentVersion.value && currentVersion.value !== "builtin" ? currentVersion.value : version)
|
||||
@@ -168,13 +176,13 @@ const displayVersion = computed<string>(
|
||||
const latestVersionText = computed<string>(() => (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<void> {
|
||||
await loadNotes();
|
||||
}
|
||||
|
||||
/** 外壳更新:交给系统浏览器下载安装包 */
|
||||
function handleShellDownload(): void {
|
||||
openShellDownload();
|
||||
/** 外壳更新:优先使用原生安装能力 */
|
||||
async function handleShellDownload(): Promise<void> {
|
||||
await startShellUpdate();
|
||||
}
|
||||
|
||||
async function handleDownload(): Promise<void> {
|
||||
@@ -279,6 +287,10 @@ async function handleApply(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
await apply(bundle);
|
||||
// 应用成功会直接重启,走到这里说明包是坏的,已经清理掉,提示后可以重新检查
|
||||
if (updateError.value) {
|
||||
Message.error(`更新失败:${updateError.value}`);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user