import { requestUpdatePackage } from '@/api/modules/sys' import { getMaxVersion } from './tools' import { getFileExtension } from '@/utils' /** * 统一检查更新入口 */ export default async function checkUpdate() { // #ifdef APP-PLUS try { const upgradeData = await getUpgradeCheckData() // 优先调用 uni-upgrade-center(3 秒超时) const result = await withTimeout( callUpgradeCenter(upgradeData), 3000 ) console.log('检查版本更新成功:', result) return result } catch (err) { console.warn('uniCloud更新方案失败,启用备用方案:', err?.message) return await useBackupUpdate() } // #endif // #ifndef APP-PLUS throw { message: '请在 App 中使用' } // #endif } /** * 备用更新方案 */ async function useBackupUpdate() { const currentVersion = await getCurrentVersion() if (!currentVersion) { throw { message: '获取当前版本号失败' } } console.log('当前版本号:', currentVersion) const res = await requestUpdatePackage('10', currentVersion) if (!res || !res.updateUrl) { throw { message: '没有匹配的更新包,当前版本无需升级,如您确定有更新,请卸载本版本后前往应用市场重新安装' } } // 将服务器返回的更新信息转换为 uni-upgrade-center 格式 return { result: { ...res, url: res.updateUrl, platform: ['Android', 'Ios'], type: getFileExtension(res.updateUrl), is_mandatory: true, is_backup_update: true, title: "更新", contents: "当前版本已经弃用,请立即更新", } } } /** * uni-upgrade-center 调用 Promise 化 */ function callUpgradeCenter(data) { return new Promise((resolve, reject) => { uniCloud.callFunction({ name: 'uni-upgrade-center', data, success: resolve, fail: reject }) }) } /** * 超时控制 */ function withTimeout(promise, timeout) { return Promise.race([ promise, new Promise((_, reject) => setTimeout(() => reject(new Error('请求超时')), timeout) ) ]) } /** * 获取 upgrade-center 所需参数 */ function getUpgradeCheckData() { return new Promise((resolve, reject) => { plus.runtime.getProperty( plus.runtime.appid, (widgetInfo) => { resolve({ action: 'checkVersion', appid: plus.runtime.appid, appVersion: plus.runtime.version, wgtVersion: widgetInfo.version }) } ) }) } /** * 获取当前客户端版本(app / wgt 取最大) */ export async function getCurrentVersion() { // #ifdef APP-PLUS const widgetInfo = await new Promise(resolve => { plus.runtime.getProperty(plus.runtime.appid, resolve) }) return getMaxVersion( plus.runtime.version, widgetInfo.version ) // #endif }