feat: 版本更新

This commit is contained in:
2026-05-26 16:33:32 +08:00
parent 30fdac8a06
commit 85188d268a
7 changed files with 732 additions and 337 deletions
+119 -142
View File
@@ -15,107 +15,12 @@
import { import {
ShoproInit ShoproInit
} from './sheep'; } from './sheep';
import {
gethotupdatelist
} from '@/sheep/api/index/index';
let globalData = ref({ let globalData = ref({
statusBarHeight: 0, // 状态导航栏高度 statusBarHeight: 0, // 状态导航栏高度
navHeight: 0, // 总体高度 navHeight: 0, // 总体高度
navigationBarHeight: 0, // 导航栏高度(标题栏高度) navigationBarHeight: 0, // 导航栏高度(标题栏高度)
windowHeight: 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 = () => { const socket = () => {
let url = 'ws://192.168.101.229:48080/aishop/ws'; let url = 'ws://192.168.101.229:48080/aishop/ws';
let socketTask = uni.connectSocket({ let socketTask = uni.connectSocket({
@@ -138,6 +43,122 @@
console.log('WebSocket 错误!', res); 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(() => { onMounted(() => {
// #ifdef APP-PLUS // #ifdef APP-PLUS
// plus.nativeUI.setUIStyle('dark'); // plus.nativeUI.setUIStyle('dark');
@@ -156,54 +177,10 @@
globalData.value.statusBarHeight = uni.getSystemInfoSync()?.statusBarHeight; globalData.value.statusBarHeight = uni.getSystemInfoSync()?.statusBarHeight;
globalData.value.windowHeight = uni.getSystemInfoSync()?.windowHeight; globalData.value.windowHeight = uni.getSystemInfoSync()?.windowHeight;
// 热更新 ensureLoadingPatched();
// #ifdef APP-PLUS ensureGlobalHotUpdateChecked();
wgtUp();
// #endif
// socket() // 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(() => { onLaunch(() => {
// 隐藏原生导航栏 使用自定义底部导航 // 隐藏原生导航栏 使用自定义底部导航
// uni.hideTabBar({ // uni.hideTabBar({
@@ -264,4 +241,4 @@
.uni-app--showtopwindow uni-page-head { .uni-app--showtopwindow uni-page-head {
display: none; display: none;
} }
</style> </style>
+27 -1
View File
@@ -14,13 +14,39 @@ import {
import { import {
debounce debounce
} from '@/utils/common' } from '@/utils/common'
import { createHotUpdate, createLoadingProgress } from '@/utils/hotUpdate'
import { gethotupdatelist } from '@/sheep/api/index/index'
export function createApp() { 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); 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); setupPinia(app);
app.config.globalProperties.$url = 'https://sycbuck.oss-cn-hangzhou.aliyuncs.com/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/' app.config.globalProperties.$ygUrl = 'https://swzhyg.oss-cn-hangzhou.aliyuncs.com/static/'
@@ -32,4 +58,4 @@ export function createApp() {
return { return {
app, app,
}; };
} }
+6 -12
View File
@@ -738,13 +738,6 @@
"enablePullDownRefresh": false "enablePullDownRefresh": false
} }
}, },
{
"path": "bankCard",
"style": {
"navigationBarTitleText": "银行卡",
"enablePullDownRefresh": false
}
},
{ {
"path": "phone", "path": "phone",
"style": { "style": {
@@ -971,11 +964,12 @@
] ]
}, },
"condition": { "condition": {
"current": 0, //模式配置,仅开发期间生效
"current": 0, //当前激活的模式(list 的索引项)
"list": [{ "list": [{
"name": "", "name": "", //模式名称
"path": "", "path": "", //启动页面,必选
"query": "" "query": "" //启动参数,在页面的onLoad函数里面得到
}] }]
} }
} }
-7
View File
@@ -76,13 +76,6 @@
link: 'navigateTo', link: 'navigateTo',
to: '/pages/home/pass', to: '/pages/home/pass',
}, },
{
id: '12',
title: '银行卡',
clickable: true,
link: 'navigateTo',
to: '/pages/home/bankCard',
},
{ {
id: '5', id: '5',
title: '隐私政策', title: '隐私政策',
+152 -168
View File
@@ -6,186 +6,170 @@
</view> </view>
<view class="center"> 最新版本号: {{ newversion }} </view> <view class="center"> 最新版本号: {{ newversion }} </view>
<view class="center m-t-50"> 当前版本号: {{ version }} </view> <view class="center m-t-50"> 当前版本号: {{ version }} </view>
<!-- #ifdef APP-PLUS -->
<view class="flex-center m-t-100 absolute b50 w100 p-x-32"> <view class="flex-center m-t-100 absolute b50 w100 p-x-32">
<view class="ai-button2 m-r-20" @click="downloadFile()">更新最新版本</view> <view class="ai-button2 m-r-20" @click="onClickUpdate()">更新最新版本</view>
<view class="ai-button2" @click="copy()">复制APP下载链接</view> <view class="ai-button2" @click="copy()">复制APP下载链接</view>
</view> </view>
<!-- #endif -->
</view>
<view v-if="showUpdateProgress" class="update-progress-mask">
<view class="update-progress-card">
<view class="update-progress-title">{{ updateProgressText }}</view>
<view class="update-progress-bar">
<view class="update-progress-bar__fill" :style="{ width: updateProgress + '%' }"></view>
</view>
<view class="update-progress-percent">{{ updateProgress }}%</view>
</view>
</view> </view>
</s-pages> </s-pages>
</template> </template>
<script setup lang="ts"> <script setup>
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance, watch, nextTick } from 'vue'; import { ref, onMounted } from 'vue'
import { gethotupdatelist, getAndroidAppUrl } from '@/sheep/api/index/index'; import { createHotUpdate, downloadAndOpenApk } from '@/utils/hotUpdate'
import sheep from '@/sheep'; import { getAndroidAppUrl, gethotupdatelist } from '@/sheep/api/index/index'
let { proxy } = getCurrentInstance();
let newversion = ref('');
let version = ref('');
let filePath = ref();
let androidUrl = ref(); //安卓apk地址
const wgtUp = async () => { const newversion = ref('')
// console.log(plus.runtime); const version = ref('')
let res = await gethotupdatelist(); const appVersion = ref('')
if (res.code !== 0) return; const wgtVersion = ref('')
filePath.value = res.data.filePath; const updateInfoRef = ref({})
let localVersion = uni.getSystemInfoSync().appWgtVersion; const apkPath = ref('')
version.value = localVersion;
newversion.value = res.data.versionNumber;
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) => { const showUpdateProgress = ref(false)
if (res.confirm) { const updateProgress = ref(0)
updateApp(filePath.value); const updateProgressText = ref('下载中...')
} 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 copy = () => {
uni.setClipboardData({
data: androidUrl.value,
success: () => {
uni.showToast({
title: '链接已复制,请在浏览器打开',
icon: 'none',
});
},
});
};
const downloadFile = () => {
if (newversion.value == version.value) {
uni.showToast({ title: '已经是最新版本', icon: 'none' });
return;
}
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',
});
},
);
}
}
},
});
};
//获取安卓apk const progress = {
function getAndroid() { show: (text) => {
getAndroidAppUrl().then((res) => { showUpdateProgress.value = true
console.log(res.data); updateProgress.value = 0
androidUrl.value = res.data || 'http://8.136.55.200:1080/app.apk'; updateProgressText.value = String(text || '下载中...')
}); },
set: (p, text) => {
updateProgress.value = Math.max(0, Math.min(100, Number(p) || 0))
if (text) updateProgressText.value = String(text)
},
hide: () => {
showUpdateProgress.value = false
},
}
const hotUpdate = createHotUpdate({
progress,
apkMode: 'download',
getLatest: gethotupdatelist,
})
const wgtUp = async () => {
const payload = await hotUpdate.fetchLatest()
if (!payload) return
const { updateInfo, localWgtVersion, localAppVersion, localCompareVersion, latestVersion } = payload
updateInfoRef.value = updateInfo || {}
wgtVersion.value = String(localWgtVersion || '')
appVersion.value = String(localAppVersion || '')
version.value = String(localCompareVersion || localAppVersion || localWgtVersion || '')
newversion.value = String(latestVersion || '')
apkPath.value = String(updateInfo?.apkPath || '')
}
const onClickUpdate = async () => {
await wgtUp()
await hotUpdate.promptAndUpdate(updateInfoRef.value, { source: 'manual' })
}
const copy = async () => {
if (!apkPath.value) {
try {
const res = await getAndroidAppUrl({})
apkPath.value = String(res?.data || '')
} catch (e) {}
} }
onMounted(() => { if (!apkPath.value) {
getAndroid(); uni.showToast({ title: '暂无下载链接', icon: 'none' })
wgtUp(); return
}); }
const url = apkPath.value
uni.setClipboardData({
data: url,
success: () => {
uni.showToast({ title: '链接已复制', icon: 'none' })
uni.showModal({
title: '提示',
content: '是否立即下载更新?',
confirmText: '立即下载',
cancelText: '暂不下载',
confirmColor: 'var(--color2)',
success: (res) => {
if (!res?.confirm) return
downloadAndOpenApk(apkPath.value, { progress })
},
})
},
})
}
onMounted(() => {
// #ifdef APP-PLUS
wgtUp()
// #endif
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.pages { .pages {
} }
.update-progress-mask {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.45);
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
padding: 40rpx;
box-sizing: border-box;
}
.update-progress-card {
width: 100%;
max-width: 560rpx;
background: #fff;
border-radius: 16rpx;
padding: 32rpx;
box-sizing: border-box;
}
.update-progress-title {
font-size: 28rpx;
color: #333;
text-align: center;
margin-bottom: 20rpx;
}
.update-progress-bar {
height: 18rpx;
background: rgba(0, 0, 0, 0.08);
border-radius: 999rpx;
overflow: hidden;
}
.update-progress-bar__fill {
height: 100%;
background: var(--color2);
border-radius: 999rpx;
width: 0%;
transition: width 0.2s linear;
}
.update-progress-percent {
font-size: 28rpx;
color: #333;
text-align: center;
margin-top: 16rpx;
}
</style> </style>
-7
View File
@@ -93,13 +93,6 @@ export const getBankList = (params) => {
params, params,
}); });
}; };
export const addBank = (data) => {
return request({
url: '/member/user/bank/create',
method: 'POST',
data,
});
};
//获取待释放列表 //获取待释放列表
export const getReleaseList = (params) => { export const getReleaseList = (params) => {
return request({ return request({
+428
View File
@@ -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,
}
}