From 85188d268a4160ea9988f872356e8d50ec01c2fd Mon Sep 17 00:00:00 2001
From: 15233722133 <15233722133@163.com>
Date: Tue, 26 May 2026 16:33:32 +0800
Subject: [PATCH] =?UTF-8?q?feat:=20=E7=89=88=E6=9C=AC=E6=9B=B4=E6=96=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
App.vue | 261 ++++++++----------
main.js | 28 +-
pages.json | 18 +-
pages/public/setting.vue | 7 -
pages/public/versions/versions.vue | 320 ++++++++++-----------
sheep/api/home/pay.js | 7 -
utils/hotUpdate.js | 428 +++++++++++++++++++++++++++++
7 files changed, 732 insertions(+), 337 deletions(-)
create mode 100644 utils/hotUpdate.js
diff --git a/App.vue b/App.vue
index 4495b17..081d0c2 100644
--- a/App.vue
+++ b/App.vue
@@ -15,107 +15,12 @@
import {
ShoproInit
} from './sheep';
- import {
- gethotupdatelist
- } from '@/sheep/api/index/index';
let globalData = ref({
statusBarHeight: 0, // 状态导航栏高度
navHeight: 0, // 总体高度
navigationBarHeight: 0, // 导航栏高度(标题栏高度)
windowHeight: 0,
});
- let filePath = ref();
- const wgtUp = async () => {
- // console.log(plus.runtime);
-
- let res = await gethotupdatelist();
- if (res.code !== 0) return;
- filePath.value = res.data.filePath;
-
- let localVersion = uni.getSystemInfoSync().appWgtVersion;
- if (res.data.versionNumber != localVersion) {
- if (res.data.type == 'min') {
- if (res.data.isForceUpdate) {
- // 强制更新
- downloadFile();
- } else {
- uni.showModal({
- title: '提示',
- content: '发现新的版本,是否更新?',
- confirmColor: '#FA7E31',
- success: (res) => {
- if (res.confirm) {
- downloadFile();
- } else if (res.cancel) {
- if (res.data.isForceUpdate) {
- plus.runtime.quit(); //退出应用
- }
- }
- },
- });
- }
- } else {
- uni.showModal({
- title: '提示',
- content: '发现新的版本,请到立即更新到最新版本',
- confirmText: '立即更新',
- cancelText: res.data.isForceUpdate ? '关闭' : '取消',
- confirmColor: '#FA7E31',
-
- success: (res) => {
- if (res.confirm) {
- updateApp(filePath.value);
- } else if (res.cancel) {
- if (res.data.isForceUpdate) {
- plus.runtime.quit(); //退出应用
- }
- }
- },
- });
- }
- }
- };
- const updateApp = (url) => {
- uni.showLoading({
- title: '下载中',
- });
- uni.downloadFile({
- url: url, //下载地址
- success: (res) => {
- console.log(res, '下载成功');
- if (res.statusCode === 200) {
- console.log('下载成功');
- uni.hideLoading();
- uni.showToast({
- title: '下载成功',
- icon: 'success',
- });
- uni.saveFile({
- tempFilePath: res.tempFilePath,
- success: function(res) {
- uni.openDocument({
- filePath: res.savedFilePath,
- success: function(res) {
- console.log(res, '打开安装包');
- },
- });
- },
- fail: (err) => {
- console.log(err, '打开安装包-失败');
- },
- });
- }
- },
- fail(e) {
- uni.hideLoading();
- uni.showToast({
- title: '下载失败,请检查网络',
- icon: 'none',
- });
- console.log(e);
- },
- });
- };
const socket = () => {
let url = 'ws://192.168.101.229:48080/aishop/ws';
let socketTask = uni.connectSocket({
@@ -138,6 +43,122 @@
console.log('WebSocket 错误!', res);
});
};
+
+ const parseTitleToProgress = (title) => {
+ const text = String(title || '');
+ const percentMatch = text.match(/(\d{1,3})%/);
+ const percent = percentMatch ? Number(percentMatch[1]) : null;
+ const cleanText = text.replace(/\s*\d{1,3}%\s*$/, '').trim() || text;
+ const normalizedPercent =
+ percent !== null && Number.isFinite(percent) ?
+ Math.max(0, Math.min(100, percent)) :
+ text.includes('安装') && !text.includes('下载') ? 100 : null;
+ return {
+ percent: normalizedPercent,
+ text: cleanText
+ };
+ };
+
+ const shouldUseUpdateOverlay = (title) => {
+ const text = String(title || '');
+ if (!text) return false;
+ if (/下载|安装|更新/.test(text) && (/%/.test(text) || /下载中|安装中/.test(text))) {
+ return true;
+ }
+ return false;
+ };
+
+ const ensureLoadingPatched = () => {
+ if (!uni || uni.__updateLoadingPatched) return;
+ const originalShowLoading = uni.showLoading;
+ const originalHideLoading = uni.hideLoading;
+ if (typeof originalShowLoading !== 'function' || typeof originalHideLoading !== 'function') {
+ uni.__updateLoadingPatched = true;
+ return;
+ }
+
+ const HOT_UPDATE_PROGRESS_EVENT = '__hot_update_progress__';
+ const canEmit = () => typeof uni !== 'undefined' && typeof uni.$emit === 'function';
+ const emitProgress = (payload) => {
+ if (!canEmit()) return false;
+ uni.__hotUpdatePendingProgress = payload;
+ uni.$emit(HOT_UPDATE_PROGRESS_EVENT, payload);
+ return true;
+ };
+
+ uni.showLoading = (options = {}) => {
+ const title = options?.title ?? '';
+ if (shouldUseUpdateOverlay(title) && canEmit()) {
+ const parsed = parseTitleToProgress(title);
+ if (!uni.__updateProgressShown) {
+ uni.__updateProgressShown = true;
+ emitProgress({
+ type: 'show',
+ text: parsed.text || '下载中...'
+ });
+ }
+ if (parsed.percent !== null) {
+ emitProgress({
+ type: 'set',
+ percent: parsed.percent,
+ text: parsed.text || ''
+ });
+ }
+ return;
+ }
+ return originalShowLoading.call(uni, options);
+ };
+
+ uni.hideLoading = () => {
+ if (uni.__updateProgressShown && canEmit()) {
+ uni.__updateProgressShown = false;
+ emitProgress({
+ type: 'hide'
+ });
+ return;
+ }
+ return originalHideLoading.call(uni);
+ };
+
+ uni.__updateLoadingPatched = true;
+ };
+
+ const waitForPlusRuntime = ({
+ timeoutMs = 5000,
+ intervalMs = 50
+ } = {}) =>
+ new Promise((resolve) => {
+ const ready = () => typeof plus !== 'undefined' && !!plus?.runtime;
+ if (ready()) {
+ resolve(true);
+ return;
+ }
+ const startedAt = Date.now();
+ const timer = setInterval(() => {
+ if (ready()) {
+ clearInterval(timer);
+ resolve(true);
+ return;
+ }
+ if (Date.now() - startedAt >= timeoutMs) {
+ clearInterval(timer);
+ resolve(false);
+ }
+ }, intervalMs);
+ });
+
+ const ensureGlobalHotUpdateChecked = async () => {
+ if (uni.__globalHotUpdateCheckedInApp) return;
+ uni.__globalHotUpdateCheckedInApp = true;
+ const ok = await waitForPlusRuntime();
+ if (!ok) return;
+ if (typeof uni.__globalHotUpdateCheck === 'function') {
+ await uni.__globalHotUpdateCheck({
+ force: true,
+ source: 'app'
+ });
+ }
+ };
onMounted(() => {
// #ifdef APP-PLUS
// plus.nativeUI.setUIStyle('dark');
@@ -156,54 +177,10 @@
globalData.value.statusBarHeight = uni.getSystemInfoSync()?.statusBarHeight;
globalData.value.windowHeight = uni.getSystemInfoSync()?.windowHeight;
- // 热更新
- // #ifdef APP-PLUS
- wgtUp();
- // #endif
+ ensureLoadingPatched();
+ ensureGlobalHotUpdateChecked();
// socket()
});
- const downloadFile = () => {
- let url = filePath.value;
- uni.downloadFile({
- url: url,
- success: (downloadResult) => {
- uni.showToast({
- title: '更新中....',
- icon: 'none',
- });
- if (downloadResult) {
- if (downloadResult.statusCode === 200) {
- plus.runtime.install(
- downloadResult.tempFilePath, {
- force: true,
- },
- function() {
- uni.showModal({
- title: '成功提示',
- content: '热更新成功,请重启应用',
- confirmColor: '#FA7E31',
- showCancel: false,
- success: function(res) {
- if (res.confirm) {
- plus.runtime.restart(); //自动重启软件
- }
- },
- });
- },
- function(e) {
- uni.showModal({
- title: '失败提示',
- content: e,
- showCancel: false,
- confirmColor: '#FA7E31',
- });
- },
- );
- }
- }
- },
- });
- };
onLaunch(() => {
// 隐藏原生导航栏 使用自定义底部导航
// uni.hideTabBar({
@@ -264,4 +241,4 @@
.uni-app--showtopwindow uni-page-head {
display: none;
}
-
\ No newline at end of file
+
diff --git a/main.js b/main.js
index 53bff8f..6e5a267 100644
--- a/main.js
+++ b/main.js
@@ -14,13 +14,39 @@ import {
import {
debounce
} from '@/utils/common'
+import { createHotUpdate, createLoadingProgress } from '@/utils/hotUpdate'
+import { gethotupdatelist } from '@/sheep/api/index/index'
export function createApp() {
+ const hotUpdate = createHotUpdate({
+ progress: createLoadingProgress(),
+ apkMode: 'download',
+ getLatest: gethotupdatelist,
+ })
+
+ uni.__globalHotUpdateCheck = (options = {}) => {
+ const force = !!options?.force
+ if (!force && uni.__hotUpdateCheckedOnce) return
+ uni.__hotUpdateCheckedOnce = true
+ return hotUpdate.checkUpdate({ allowSkipPrompt: true })
+ }
+
const app = createSSRApp(App);
+ app.mixin({
+ onShow() {
+ if (typeof uni.__globalHotUpdateCheck === 'function') {
+ uni.__globalHotUpdateCheck({ force: true, source: 'pageShow' })
+ }
+ },
+ })
+ setTimeout(() => {
+ if (typeof uni.__globalHotUpdateCheck === 'function') uni.__globalHotUpdateCheck({ source: 'boot' })
+ }, 0)
+
setupPinia(app);
app.config.globalProperties.$url = 'https://sycbuck.oss-cn-hangzhou.aliyuncs.com/app/'
app.config.globalProperties.$ygUrl = 'https://swzhyg.oss-cn-hangzhou.aliyuncs.com/static/'
@@ -32,4 +58,4 @@ export function createApp() {
return {
app,
};
-}
\ No newline at end of file
+}
diff --git a/pages.json b/pages.json
index d8f4585..20560db 100644
--- a/pages.json
+++ b/pages.json
@@ -738,13 +738,6 @@
"enablePullDownRefresh": false
}
},
- {
- "path": "bankCard",
- "style": {
- "navigationBarTitleText": "银行卡",
- "enablePullDownRefresh": false
- }
- },
{
"path": "phone",
"style": {
@@ -971,11 +964,12 @@
]
},
"condition": {
- "current": 0,
+ //模式配置,仅开发期间生效
+ "current": 0, //当前激活的模式(list 的索引项)
"list": [{
- "name": "",
- "path": "",
- "query": ""
+ "name": "", //模式名称
+ "path": "", //启动页面,必选
+ "query": "" //启动参数,在页面的onLoad函数里面得到
}]
}
-}
+}
\ No newline at end of file
diff --git a/pages/public/setting.vue b/pages/public/setting.vue
index c77c53b..5f9fcb2 100644
--- a/pages/public/setting.vue
+++ b/pages/public/setting.vue
@@ -76,13 +76,6 @@
link: 'navigateTo',
to: '/pages/home/pass',
},
- {
- id: '12',
- title: '银行卡',
- clickable: true,
- link: 'navigateTo',
- to: '/pages/home/bankCard',
- },
{
id: '5',
title: '隐私政策',
diff --git a/pages/public/versions/versions.vue b/pages/public/versions/versions.vue
index f1700ed..1a6b269 100644
--- a/pages/public/versions/versions.vue
+++ b/pages/public/versions/versions.vue
@@ -6,186 +6,170 @@
最新版本号: {{ newversion }}
当前版本号: {{ version }}
+
- 更新最新版本
+ 更新最新版本
复制APP下载链接
+
+
+
+
+
+ {{ updateProgressText }}
+
+
+
+ {{ updateProgress }}%
+
-
diff --git a/sheep/api/home/pay.js b/sheep/api/home/pay.js
index 24efec9..ce22bd0 100644
--- a/sheep/api/home/pay.js
+++ b/sheep/api/home/pay.js
@@ -93,13 +93,6 @@ export const getBankList = (params) => {
params,
});
};
-export const addBank = (data) => {
- return request({
- url: '/member/user/bank/create',
- method: 'POST',
- data,
- });
-};
//获取待释放列表
export const getReleaseList = (params) => {
return request({
diff --git a/utils/hotUpdate.js b/utils/hotUpdate.js
new file mode 100644
index 0000000..6a27f8a
--- /dev/null
+++ b/utils/hotUpdate.js
@@ -0,0 +1,428 @@
+import { gethotupdatelist } from '@/sheep/api/index/index'
+
+const HOT_UPDATE_PROMPT_EVENT = '__hot_update_prompt__'
+const HOT_UPDATE_PROMPT_RESPONSE_EVENT = '__hot_update_prompt_response__'
+const HOT_UPDATE_PROMPT_CLOSE_EVENT = '__hot_update_prompt_close__'
+const HOT_UPDATE_PROGRESS_EVENT = '__hot_update_progress__'
+
+const emitUniEvent = (name, payload) => {
+ if (typeof uni !== 'undefined' && typeof uni.$emit === 'function') uni.$emit(name, payload)
+}
+
+const waitForPromptDecision = (payload) => {
+ const id = `${Date.now()}_${Math.random().toString(16).slice(2)}`
+ return new Promise((resolve) => {
+ if (typeof uni === 'undefined' || typeof uni.$on !== 'function' || typeof uni.$off !== 'function') {
+ resolve(false)
+ return
+ }
+ const handler = (res) => {
+ if (!res || res.id !== id) return
+ uni.$off(HOT_UPDATE_PROMPT_RESPONSE_EVENT, handler)
+ if (uni.__hotUpdatePendingPrompt?.id === id) uni.__hotUpdatePendingPrompt = null
+ resolve(res.action === 'confirm')
+ }
+ uni.$on(HOT_UPDATE_PROMPT_RESPONSE_EVENT, handler)
+ uni.__hotUpdatePendingPrompt = { id, ...payload }
+ emitUniEvent(HOT_UPDATE_PROMPT_EVENT, { id, ...payload })
+ })
+}
+
+export const compareVersion = (a, b) => {
+ const pa = String(a || '')
+ .split('.')
+ .map((n) => parseInt(n, 10) || 0)
+ const pb = String(b || '')
+ .split('.')
+ .map((n) => parseInt(n, 10) || 0)
+ const len = Math.max(pa.length, pb.length)
+ for (let i = 0; i < len; i += 1) {
+ const na = pa[i] ?? 0
+ const nb = pb[i] ?? 0
+ if (na > nb) return 1
+ if (na < nb) return -1
+ }
+ return 0
+}
+
+export const getNativeAppVersion = async () => {
+ try {
+ const baseInfo = typeof uni.getAppBaseInfo === 'function' ? uni.getAppBaseInfo() : null
+ if (baseInfo?.appVersion) return String(baseInfo.appVersion)
+ } catch (e) {}
+
+ try {
+ const sysInfo = typeof uni.getSystemInfoSync === 'function' ? uni.getSystemInfoSync() : null
+ if (sysInfo?.appVersion) return String(sysInfo.appVersion)
+ } catch (e) {}
+
+ try {
+ if (typeof plus !== 'undefined' && plus?.runtime?.getProperty) {
+ const appid = plus.runtime.appid
+ const info = await new Promise((resolve) => {
+ plus.runtime.getProperty(appid, (res) => resolve(res || {}))
+ })
+ if (info?.version) return String(info.version)
+ }
+ } catch (e) {}
+
+ try {
+ const sysInfo = typeof uni.getSystemInfoSync === 'function' ? uni.getSystemInfoSync() : null
+ if (sysInfo?.appWgtVersion) return String(sysInfo.appWgtVersion)
+ } catch (e) {}
+
+ return ''
+}
+
+export const getUpdateDesc = (info) => {
+ if (!info) return ''
+ const candidates = [info.updateContent, info.content, info.description, info.remark, info.updateDesc]
+ return String(candidates.find((v) => String(v || '').trim()) || '').trim()
+}
+
+export const createLoadingProgress = () => {
+ let shown = false
+ let lastTitle = ''
+ let lastAt = 0
+ return {
+ show: (text = '下载中...') => {
+ shown = true
+ lastTitle = String(text || '下载中...')
+ lastAt = Date.now()
+ uni.showLoading({ title: lastTitle, mask: true })
+ },
+ set: (percent, text) => {
+ if (!shown) return
+ const p = Math.max(0, Math.min(100, Number(percent) || 0))
+ const title = text ? String(text) : `下载中... ${p}%`
+ const now = Date.now()
+ if (title === lastTitle) return
+ if (p !== 100 && now - lastAt < 500) return
+ lastTitle = title
+ lastAt = now
+ uni.showLoading({ title, mask: true })
+ },
+ hide: () => {
+ if (!shown) return
+ shown = false
+ lastTitle = ''
+ lastAt = 0
+ uni.hideLoading()
+ },
+ }
+}
+
+export const createEventProgress = () => {
+ let shown = false
+ return {
+ show: (text = '下载中...') => {
+ shown = true
+ const payload = { type: 'show', text: String(text || '下载中...') }
+ if (typeof uni !== 'undefined') uni.__hotUpdatePendingProgress = payload
+ emitUniEvent(HOT_UPDATE_PROGRESS_EVENT, payload)
+ },
+ set: (percent, text) => {
+ if (!shown) return
+ const p = Math.max(0, Math.min(100, Math.round(Number(percent) || 0)))
+ const payload = { type: 'set', percent: p, text: text ? String(text) : '' }
+ if (typeof uni !== 'undefined') uni.__hotUpdatePendingProgress = payload
+ emitUniEvent(HOT_UPDATE_PROGRESS_EVENT, payload)
+ },
+ hide: () => {
+ if (!shown) return
+ shown = false
+ if (typeof uni !== 'undefined') uni.__hotUpdatePendingProgress = null
+ emitUniEvent(HOT_UPDATE_PROGRESS_EVENT, { type: 'hide' })
+ },
+ }
+}
+
+const createProgressSetter = (progress) => {
+ let lastProgress = -1
+ let lastAt = 0
+ const set = (p, stageText = '下载中...') => {
+ if (!progress || typeof progress.set !== 'function') return
+ const next = Math.round(Math.max(0, Math.min(100, Number(p) || 0)))
+ if (next <= lastProgress) return
+ const now = Date.now()
+ if (next !== 100 && now - lastAt < 500) return
+ lastProgress = next
+ lastAt = now
+ const title = stageText ? `${String(stageText)} ${lastProgress}%` : undefined
+ progress.set(lastProgress, title)
+ }
+ const reset = () => {
+ lastProgress = -1
+ lastAt = 0
+ }
+ const markShown = () => {
+ lastProgress = 0
+ lastAt = Date.now()
+ }
+ return { set, reset, markShown }
+}
+
+export const downloadFileWithProgress = (url, { progress, stageText = '下载中...' } = {}) => {
+ return new Promise((resolve, reject) => {
+ if (!url) {
+ reject(new Error('empty url'))
+ return
+ }
+ const setter = createProgressSetter(progress)
+ setter.reset()
+ if (progress?.show) progress.show(stageText)
+ if (setter?.markShown) setter.markShown()
+
+ const task = uni.downloadFile({
+ url,
+ success: (res) => {
+ if (!res || res.statusCode !== 200) {
+ reject(new Error('download failed'))
+ return
+ }
+ setter.set(100, stageText)
+ resolve(res.tempFilePath)
+ },
+ fail: () => reject(new Error('download failed')),
+ })
+
+ if (task && typeof task.onProgressUpdate === 'function') {
+ task.onProgressUpdate((res) => {
+ const p = Number(res?.progress) || 0
+ setter.set(p, stageText)
+ })
+ }
+ })
+}
+
+export const downloadAndInstallWgt = async (url, { progress, confirmColor = 'var(--color2)' } = {}) => {
+ if (!url) {
+ uni.showToast({ title: '暂无下载链接', icon: 'none' })
+ return
+ }
+ if (typeof plus === 'undefined' || !plus?.runtime?.install) {
+ uni.showToast({ title: '当前环境不支持更新', icon: 'none' })
+ return
+ }
+
+ try {
+ const tempFilePath = await downloadFileWithProgress(url, { progress, stageText: '下载中...' })
+ if (progress?.set) progress.set(100, '安装中...')
+ await new Promise((resolve, reject) => {
+ plus.runtime.install(
+ tempFilePath,
+ { force: true },
+ () => resolve(),
+ (e) => reject(e),
+ )
+ })
+ if (progress?.hide) progress.hide()
+ uni.showModal({
+ title: '成功提示',
+ content: '热更新成功,请重启应用',
+ confirmColor,
+ showCancel: false,
+ success: function (res) {
+ if (res.confirm) plus.runtime.restart()
+ },
+ })
+ } catch (e) {
+ if (progress?.hide) progress.hide()
+ uni.showModal({
+ title: '失败提示',
+ content: String(e?.message || e || '安装失败'),
+ showCancel: false,
+ confirmColor,
+ })
+ }
+}
+
+export const downloadAndOpenApk = async (url, { progress } = {}) => {
+ if (!url) {
+ uni.showToast({ title: '暂无下载链接', icon: 'none' })
+ return
+ }
+ try {
+ const tempFilePath = await downloadFileWithProgress(url, { progress, stageText: '下载中...' })
+ if (progress?.hide) progress.hide()
+ uni.showToast({ title: '下载成功', icon: 'success' })
+ uni.saveFile({
+ tempFilePath,
+ success: (res) => {
+ uni.openDocument({ filePath: res.savedFilePath })
+ },
+ })
+ } catch (e) {
+ if (progress?.hide) progress.hide()
+ uni.showToast({ title: '下载失败,请检查网络', icon: 'none' })
+ }
+}
+
+export const createHotUpdate = ({
+ progress,
+ confirmColor = 'var(--color2)',
+ storageKey = '__last_update_prompt__',
+ latestKeyStorageKey = '__hot_update_latest_key__',
+ skipNewsStorageKey = '__hot_update_skip_news_key__',
+ getLatest = gethotupdatelist,
+ apkMode = 'openUrlOrCopy',
+ openUrlOrCopy,
+ promptMode = 'modal',
+} = {}) => {
+ const state = {
+ inFlight: false,
+ lastAt: 0,
+ lastPromptKey: '',
+ latestInfo: null,
+ localWgtVersion: '',
+ localAppVersion: '',
+ localCompareVersion: '',
+ lastAutoUpdateAttemptKey: '',
+ }
+
+ const fetchLatest = async () => {
+ const res = await getLatest()
+ if (!res || res.code !== 0) return null
+ const updateInfo = res.data || {}
+ state.latestInfo = updateInfo
+ state.localWgtVersion = String(uni.getSystemInfoSync()?.appWgtVersion || '')
+ state.localAppVersion = await getNativeAppVersion()
+ state.localCompareVersion = updateInfo.type == 'min' ? state.localWgtVersion : state.localAppVersion
+ return {
+ updateInfo,
+ localWgtVersion: state.localWgtVersion,
+ localAppVersion: state.localAppVersion,
+ localCompareVersion: state.localCompareVersion,
+ latestVersion: String(updateInfo.versionNumber || ''),
+ }
+ }
+
+ const hasNewVersion = (updateInfo, localCompareVersion) => {
+ const latest = String(updateInfo?.versionNumber || '')
+ if (!latest || !localCompareVersion) return false
+ return compareVersion(latest, localCompareVersion) > 0
+ }
+
+ const promptAndUpdate = async (updateInfo, { source = 'auto' } = {}) => {
+ const info = updateInfo || state.latestInfo || {}
+ const latest = String(info?.versionNumber || '')
+ const localCompareVersion = state.localCompareVersion || ''
+ if (!hasNewVersion(info, localCompareVersion)) {
+ uni.showToast({ title: '已经是最新版本', icon: 'none' })
+ return
+ }
+ const promptKey = String(info.type || '') + ':' + String(latest || '')
+ const desc = getUpdateDesc(info)
+ const content = desc
+ ? `更新内容:${desc}`
+ : info.type == 'min'
+ ? '发现新的版本,是否更新?'
+ : '发现新的版本,请立即更新到最新版本'
+ const title = latest ? `发现新版本 v${latest}` : '提示'
+ const confirmText = '立即升级'
+ const cancelText = info.isForceUpdate ? '关闭' : '取消'
+
+ const doUpdate = () => {
+ const wgtUrl = String(info.filePath || '')
+ const apkUrl = String(info.apkPath || info.filePath || '')
+ if (info.type == 'min') {
+ downloadAndInstallWgt(wgtUrl, { progress, confirmColor })
+ return
+ }
+ if (apkMode === 'download') {
+ downloadAndOpenApk(apkUrl, { progress })
+ return
+ }
+ if (typeof openUrlOrCopy === 'function') openUrlOrCopy(apkUrl)
+ emitUniEvent(HOT_UPDATE_PROMPT_CLOSE_EVENT, {})
+ }
+
+ if (info.isForceUpdate) {
+ if (source !== 'manual' && state.lastAutoUpdateAttemptKey === promptKey) return
+ state.lastAutoUpdateAttemptKey = promptKey
+ try {
+ if (skipNewsStorageKey) uni.removeStorageSync(skipNewsStorageKey)
+ } catch (e) {}
+ doUpdate()
+ return
+ }
+
+ const confirm =
+ promptMode === 'event'
+ ? await waitForPromptDecision({
+ title,
+ content,
+ version: latest,
+ isForceUpdate: !!info.isForceUpdate,
+ confirmText,
+ cancelText,
+ })
+ : await new Promise((resolve) => {
+ uni.showModal({
+ title,
+ content,
+ confirmText,
+ cancelText,
+ confirmColor,
+ success: (modalRes) => resolve(!!modalRes?.confirm),
+ })
+ })
+
+ if (confirm) {
+ if (source !== 'manual') state.lastAutoUpdateAttemptKey = promptKey
+ try {
+ if (skipNewsStorageKey) uni.removeStorageSync(skipNewsStorageKey)
+ } catch (e) {}
+ doUpdate()
+ return
+ }
+
+ try {
+ if (skipNewsStorageKey) uni.setStorageSync(skipNewsStorageKey, promptKey)
+ } catch (e) {}
+ }
+
+ const checkUpdate = async ({ allowSkipPrompt = true } = {}) => {
+ const isAppPlus = typeof plus !== 'undefined' && !!plus?.runtime
+ if (!isAppPlus) return
+ if (state.inFlight) return
+ state.inFlight = true
+ try {
+ const payload = await fetchLatest()
+ if (!payload) return
+ const { updateInfo, localCompareVersion, latestVersion } = payload
+ if (!hasNewVersion(updateInfo, localCompareVersion)) return
+
+ const promptKey = String(updateInfo.type || '') + ':' + String(latestVersion || '')
+ try {
+ if (latestKeyStorageKey) uni.setStorageSync(latestKeyStorageKey, promptKey)
+ } catch (e) {}
+ const storedPrompt = String(uni.getStorageSync(storageKey) || '')
+ const shouldSkipPrompt =
+ allowSkipPrompt &&
+ !updateInfo.isForceUpdate &&
+ (state.lastPromptKey === promptKey || storedPrompt === promptKey)
+ if (shouldSkipPrompt) return
+ state.lastPromptKey = promptKey
+ uni.setStorageSync(storageKey, promptKey)
+
+ if (updateInfo.type == 'min' && updateInfo.isForceUpdate) {
+ if (state.lastAutoUpdateAttemptKey === promptKey) return
+ state.lastAutoUpdateAttemptKey = promptKey
+ const wgtUrl = String(updateInfo.filePath || '')
+ await downloadAndInstallWgt(wgtUrl, { progress, confirmColor })
+ return
+ }
+ await promptAndUpdate(updateInfo, { source: 'auto' })
+ } finally {
+ state.inFlight = false
+ }
+ }
+
+ return {
+ state,
+ fetchLatest,
+ checkUpdate,
+ promptAndUpdate,
+ }
+}