Files
2026-06-23 13:29:38 +08:00

482 lines
15 KiB
JavaScript

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 })
})
}
const toBoolean = (v) => {
if (v === true) return true
if (v === false || v === null || typeof v === 'undefined') return false
if (typeof v === 'number') return v === 1
if (typeof v === 'string') {
const s = v.trim().toLowerCase()
if (s === '1' || s === 'true') return true
if (s === '0' || s === 'false' || s === '') return false
}
return !!v
}
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 markHotUpdateInFlight = (delta) => {
try {
const current = Number(uni.__hotUpdateInFlightCount || 0)
const next = Math.max(0, current + Number(delta || 0))
uni.__hotUpdateInFlightCount = next
uni.__hotUpdateInFlight = next > 0
} catch (e) {}
}
let cleaned = false
const cleanup = () => {
if (cleaned) return
cleaned = true
markHotUpdateInFlight(-1)
}
markHotUpdateInFlight(1)
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) {
cleanup()
reject(new Error('download failed'))
return
}
setter.set(100, stageText)
cleanup()
resolve(res.tempFilePath)
},
fail: () => {
cleanup()
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: '下载中...' })
const isAppPlus = typeof plus !== 'undefined' && !!plus?.runtime?.install
if (isAppPlus) {
if (progress?.set) progress.set(100, '安装中...')
await new Promise((resolve, reject) => {
plus.runtime.install(
tempFilePath,
{},
() => resolve(),
(e) => reject(e),
)
})
if (progress?.hide) progress.hide()
return
}
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.showModal({
title: '失败提示',
content: String(e?.message || e?.code || e || '安装失败'),
showCancel: false,
confirmColor: 'var(--color2)',
})
}
}
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 isForceUpdate = toBoolean(info?.isForceUpdate)
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 = 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 (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,
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 isForceUpdate = toBoolean(updateInfo?.isForceUpdate)
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 &&
!isForceUpdate &&
(state.lastPromptKey === promptKey || storedPrompt === promptKey)
if (shouldSkipPrompt) return
state.lastPromptKey = promptKey
uni.setStorageSync(storageKey, promptKey)
if (updateInfo.type == 'min' && 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,
}
}