useAppUpdate.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. import { ref, onUnmounted } from 'vue'
  2. import { useI18n } from 'vue-i18n'
  3. import { useProgress } from './useProgress'
  4. import useUserStore from '@/stores/use-user-store'
  5. import { ucardApi } from '@/api/ucard'
  6. import { userToken } from '@/composables/config'
  7. // ================== 类型声明 ==================
  8. declare const plus: any
  9. declare const uni: any
  10. interface PlusDownloaderDownload {
  11. filename: string
  12. pause?: () => void
  13. resume?: () => void
  14. start: () => void
  15. abort: () => void
  16. addEventListener: (event: string, callback: (data: any) => void) => void
  17. removeEventListener?: (event: string, callback: (data: any) => void) => void
  18. }
  19. // ================== 常量定义 ==================
  20. /** 存储键名 */
  21. const STORAGE_KEYS = {
  22. LAST_CHECK: 'last_update_check_time',
  23. SKIP_VERSION: 'skip_update_version',
  24. DOWNLOAD_CACHE: 'app_download_cache'
  25. } as const
  26. /** 下载状态码 */
  27. enum DownloadState {
  28. DOWNLOADING = 3, // 下载中
  29. COMPLETED = 4 // 下载完成
  30. }
  31. /** HTTP 成功状态码 */
  32. enum HttpStatus {
  33. OK = 200, // 成功
  34. PARTIAL_CONTENT = 206 // 部分内容(断点续传)
  35. }
  36. /** 下载配置 */
  37. const DOWNLOAD_CONFIG = {
  38. FILE_PATH: '_downloads/app_update.wgt',
  39. MAX_RETRY: 3, // 最大重试次数
  40. RETRY_DELAY: 2000, // 重试延迟(毫秒)
  41. TOAST_DURATION: 2000 // Toast 显示时长
  42. } as const
  43. // ================== 类型定义 ==================
  44. /** 更新信息 */
  45. interface UpdateInfo {
  46. version: string
  47. forceUpdate: boolean
  48. wgtUrl?: string
  49. iosStoreUrl?: string
  50. }
  51. /** 下载缓存 */
  52. interface DownloadCache {
  53. url: string
  54. progress: number
  55. time: number
  56. }
  57. /** API 响应 */
  58. interface ApiResponse<T = any> {
  59. code: number
  60. data?: T
  61. message?: string
  62. }
  63. /** 下载状态变化事件 */
  64. interface DownloadStateEvent {
  65. state: number
  66. downloadedSize: number
  67. totalSize: number
  68. }
  69. /** 平台类型 */
  70. type PlatformType = 'ios' | 'android'
  71. /** 设备类型 */
  72. type EquipmentType = 'ios' | 'Android'
  73. // ================== 工具函数 ==================
  74. /**
  75. * 获取当前应用版本
  76. */
  77. function getCurrentVersion(): Promise<string> {
  78. return new Promise((resolve, reject) => {
  79. // #ifdef APP-PLUS
  80. try {
  81. plus.runtime.getProperty(plus.runtime.appid, (info) => {
  82. resolve(info.version)
  83. }, (error) => {
  84. reject(error)
  85. })
  86. } catch (error) {
  87. reject(error)
  88. }
  89. // #endif
  90. // #ifndef APP-PLUS
  91. reject(new Error('Not in APP-PLUS environment'))
  92. // #endif
  93. })
  94. }
  95. /**
  96. * 比较版本号
  97. * @returns 1: v1 > v2, -1: v1 < v2, 0: v1 === v2
  98. */
  99. function compareVersion(v1: string, v2: string): number {
  100. const normalizeVersion = (v: string): number[] => {
  101. return v.split('.').map(segment => parseInt(segment || '0', 10))
  102. }
  103. const parts1 = normalizeVersion(v1)
  104. const parts2 = normalizeVersion(v2)
  105. const maxLength = Math.max(parts1.length, parts2.length)
  106. for (let i = 0; i < maxLength; i++) {
  107. const num1 = parts1[i] || 0
  108. const num2 = parts2[i] || 0
  109. if (num1 > num2) return 1
  110. if (num1 < num2) return -1
  111. }
  112. return 0
  113. }
  114. /**
  115. * 获取平台类型
  116. */
  117. function getPlatform(): PlatformType {
  118. // #ifdef APP-PLUS
  119. try {
  120. const platform = uni.getSystemInfoSync().platform
  121. return platform === 'ios' ? 'ios' : 'android'
  122. } catch (error) {
  123. // console.error('获取平台类型失败:', error)
  124. return 'android'
  125. }
  126. // #endif
  127. // #ifndef APP-PLUS
  128. return 'android'
  129. // #endif
  130. }
  131. /**
  132. * 获取设备类型(API 参数格式)
  133. */
  134. function getEquipmentType(): EquipmentType {
  135. return getPlatform() === 'ios' ? 'ios' : 'Android'
  136. }
  137. /**
  138. * 显示 Toast 提示
  139. */
  140. function showToast(message: string, duration = DOWNLOAD_CONFIG.TOAST_DURATION): void {
  141. uni.showToast({
  142. title: message,
  143. icon: 'none',
  144. duration
  145. })
  146. }
  147. /**
  148. * 安全地获取存储值
  149. */
  150. function getStorageSync<T = any>(key: string, defaultValue: T | null = null): T | null {
  151. try {
  152. return uni.getStorageSync(key) || defaultValue
  153. } catch (error) {
  154. // console.warn(`获取存储失败: ${key}`, error)
  155. return defaultValue
  156. }
  157. }
  158. /**
  159. * 安全地设置存储值
  160. */
  161. function setStorageSync(key: string, value: any): boolean {
  162. try {
  163. uni.setStorageSync(key, value)
  164. return true
  165. } catch (error) {
  166. // console.warn(`设置存储失败: ${key}`, error)
  167. return false
  168. }
  169. }
  170. /**
  171. * 安全地移除存储值
  172. */
  173. function removeStorageSync(key: string): boolean {
  174. try {
  175. uni.removeStorageSync(key)
  176. return true
  177. } catch (error) {
  178. // console.warn(`移除存储失败: ${key}`, error)
  179. return false
  180. }
  181. }
  182. // ================== 主函数 ==================
  183. export function useAppUpdate() {
  184. const { t } = useI18n()
  185. const userStore = useUserStore()
  186. const progress = useProgress()
  187. const checking = ref(false)
  188. const updating = ref(false)
  189. let downloadTask: PlusDownloaderDownload | null = null
  190. let networkListener: ((res: any) => void) | null = null
  191. let downloadUrl = ''
  192. let retryCount = 0
  193. let stateChangeHandler: ((d: any) => void) | null = null
  194. // ================== 对外入口 ==================
  195. /**
  196. * 检查应用更新
  197. */
  198. async function checkUpdate(): Promise<void> {
  199. // #ifdef APP-PLUS
  200. if (checking.value) {
  201. // console.warn('更新检查已在进行中')
  202. return
  203. }
  204. checking.value = true
  205. try {
  206. const equipmentType = getEquipmentType()
  207. if (!userToken.value) {
  208. return
  209. }
  210. const res: ApiResponse<UpdateInfo> = await ucardApi.getAppVersionDetail({ equipmentType })
  211. if (res.code !== 200 || !res.data) {
  212. const errorMsg = res.message || '获取版本信息失败'
  213. // console.warn(errorMsg)
  214. return
  215. }
  216. const update = res.data
  217. const currentVersion = await getCurrentVersion()
  218. const needUpdate = compareVersion(update.version, currentVersion) > 0
  219. // 保存版本信息
  220. userStore.saveAppVersion({
  221. currentVersion,
  222. version: update.version,
  223. isUpdate: !needUpdate
  224. })
  225. if (!needUpdate) {
  226. // console.log('当前已是最新版本')
  227. return
  228. }
  229. // 检查是否已跳过此版本
  230. // const skipVersion = getStorageSync<string>(STORAGE_KEYS.SKIP_VERSION)
  231. // if (!update.forceUpdate && skipVersion === update.version) {
  232. // // console.log('用户已跳过此版本更新')
  233. // return
  234. // }
  235. // 显示更新提示
  236. if (update.forceUpdate) {
  237. showForceUpdate(update)
  238. } else {
  239. showOptionalUpdate(update)
  240. }
  241. } catch (error) {
  242. // console.error('检查更新失败:', error)
  243. const errorMsg = error instanceof Error ? error.message : String(error)
  244. showToast(t('mine.p28') || `检查更新失败: ${errorMsg}`)
  245. } finally {
  246. checking.value = false
  247. }
  248. // #endif
  249. }
  250. // ================== 更新流程 ==================
  251. /**
  252. * 显示强制更新弹窗
  253. */
  254. function showForceUpdate(update: UpdateInfo): void {
  255. uni.showModal({
  256. title: t('mine.p22'),
  257. content: t('mine.p23'),
  258. showCancel: false,
  259. confirmText: t('mine.p35'),
  260. success: () => doUpdate(update)
  261. })
  262. }
  263. /**
  264. * 显示可选更新弹窗
  265. */
  266. function showOptionalUpdate(update: UpdateInfo): void {
  267. uni.showModal({
  268. title: t('mine.p24'),
  269. content: t('mine.p25', { version: `v${update.version}` }),
  270. confirmText: t('mine.p35'),
  271. cancelText: t('mine.p36'),
  272. success: (res) => {
  273. if (res.confirm) {
  274. doUpdate(update)
  275. } else {
  276. // 记录跳过的版本
  277. setStorageSync(STORAGE_KEYS.SKIP_VERSION, update.version)
  278. }
  279. }
  280. })
  281. }
  282. /**
  283. * 执行更新
  284. */
  285. function doUpdate(update: UpdateInfo): void {
  286. const platform = getPlatform()
  287. if (platform === 'ios') {
  288. handleIosUpdate(update)
  289. } else {
  290. handleAndroidUpdate(update)
  291. }
  292. }
  293. /**
  294. * 处理 iOS 更新
  295. */
  296. function handleIosUpdate(update: UpdateInfo): void {
  297. if (!update.iosStoreUrl) {
  298. showToast(t('mine.p28') || 'iOS 更新链接不存在')
  299. return
  300. }
  301. try {
  302. plus.runtime.openURL(update.iosStoreUrl)
  303. } catch (error) {
  304. // console.error('打开 App Store 失败:', error)
  305. showToast(t('mine.p28') || '打开 App Store 失败')
  306. }
  307. }
  308. /**
  309. * 处理 Android 更新
  310. */
  311. function handleAndroidUpdate(update: UpdateInfo): void {
  312. if (!update.wgtUrl) {
  313. showToast(t('mine.p28') || '更新包链接不存在')
  314. return
  315. }
  316. downloadWgt(update.wgtUrl)
  317. }
  318. // ================== 下载核心 ==================
  319. /**
  320. * 下载 wgt 更新包
  321. */
  322. function downloadWgt(url: string): void {
  323. // #ifdef APP-PLUS
  324. if (downloadTask) {
  325. // console.warn('下载任务已存在')
  326. return
  327. }
  328. if (!url || !isValidUrl(url)) {
  329. handleDownloadFail(t('mine.p28') || '下载链接无效')
  330. return
  331. }
  332. downloadUrl = url
  333. retryCount = 0
  334. updating.value = true
  335. progress.show(t('mine.p29'))
  336. // 初始化网络监听
  337. initNetworkType()
  338. startNetworkMonitor()
  339. createDownloadTask(url)
  340. // #endif
  341. }
  342. /**
  343. * 创建下载任务
  344. */
  345. function createDownloadTask(url: string): void {
  346. try {
  347. downloadTask = plus.downloader.createDownload(
  348. url,
  349. { filename: DOWNLOAD_CONFIG.FILE_PATH },
  350. handleDownloadComplete
  351. )
  352. if (!downloadTask) {
  353. throw new Error('创建下载任务失败')
  354. }
  355. // 创建状态变化处理器
  356. stateChangeHandler = handleDownloadStateChanged
  357. downloadTask.addEventListener('statechanged', stateChangeHandler)
  358. downloadTask.start()
  359. } catch (error) {
  360. // console.error('创建下载任务失败:', error)
  361. downloadTask = null
  362. handleDownloadFail(t('mine.p28') || '创建下载任务失败')
  363. }
  364. }
  365. /**
  366. * 验证 URL 格式
  367. */
  368. function isValidUrl(url: string): boolean {
  369. try {
  370. return /^https?:\/\/.+/.test(url)
  371. } catch {
  372. return false
  373. }
  374. }
  375. /**
  376. * 处理下载完成回调
  377. */
  378. function handleDownloadComplete(download: PlusDownloaderDownload, status: number): void {
  379. const isSuccess = status === HttpStatus.OK || status === HttpStatus.PARTIAL_CONTENT
  380. if (isSuccess) {
  381. // console.log('下载成功,准备安装')
  382. clearCache()
  383. stopNetworkMonitor()
  384. installWgt(download.filename)
  385. } else {
  386. // console.error('下载失败,状态码:', status)
  387. retryDownload()
  388. }
  389. }
  390. /**
  391. * 处理下载状态变化
  392. */
  393. function handleDownloadStateChanged(event: DownloadStateEvent): void {
  394. if (event.state === DownloadState.DOWNLOADING && event.totalSize > 0) {
  395. const percent = Math.min(100, Math.floor((event.downloadedSize / event.totalSize) * 100))
  396. const progressText = `${t('mine.p29')} ${percent}%`
  397. progress.update(percent, progressText)
  398. saveCache(percent)
  399. }
  400. }
  401. /**
  402. * 重试下载
  403. */
  404. function retryDownload(): void {
  405. if (retryCount >= DOWNLOAD_CONFIG.MAX_RETRY) {
  406. // console.error(`下载失败,已重试 ${retryCount} 次`)
  407. handleDownloadFail(t('mine.p28') || '下载失败')
  408. return
  409. }
  410. retryCount++
  411. // console.log(`下载失败,${DOWNLOAD_CONFIG.RETRY_DELAY / 1000}秒后重试 (${retryCount}/${DOWNLOAD_CONFIG.MAX_RETRY})`)
  412. cleanupDownloadTask()
  413. setTimeout(() => {
  414. if (downloadUrl) {
  415. createDownloadTask(downloadUrl)
  416. }
  417. }, DOWNLOAD_CONFIG.RETRY_DELAY)
  418. }
  419. /**
  420. * 初始化网络类型
  421. */
  422. function initNetworkType(): void {
  423. uni.getNetworkType({
  424. success: (res) => {
  425. // console.log('当前网络类型:', res.networkType)
  426. },
  427. fail: (error) => {
  428. // console.warn('获取网络类型失败:', error)
  429. }
  430. })
  431. }
  432. // ================== 网络处理 ==================
  433. /**
  434. * 启动网络监听
  435. */
  436. function startNetworkMonitor(): void {
  437. // #ifdef APP-PLUS
  438. if (networkListener) {
  439. // console.warn('网络监听已存在')
  440. return
  441. }
  442. networkListener = (res: any) => {
  443. if (!downloadTask || !updating.value) {
  444. return
  445. }
  446. if (!res.isConnected) {
  447. // 网络断开,暂停下载
  448. pauseDownload()
  449. return
  450. }
  451. // 网络恢复,继续下载
  452. resumeDownload()
  453. }
  454. uni.onNetworkStatusChange(networkListener)
  455. // #endif
  456. }
  457. /**
  458. * 暂停下载
  459. */
  460. function pauseDownload(): void {
  461. if (!downloadTask) return
  462. try {
  463. if (typeof downloadTask.pause === 'function') {
  464. downloadTask.pause()
  465. }
  466. } catch (error) {
  467. // console.error('暂停下载失败:', error)
  468. }
  469. }
  470. /**
  471. * 恢复下载
  472. */
  473. function resumeDownload(): void {
  474. if (!downloadTask) return
  475. try {
  476. if (typeof downloadTask.resume === 'function') {
  477. downloadTask.resume()
  478. } else if (typeof downloadTask.start === 'function') {
  479. downloadTask.start()
  480. }
  481. } catch (error) {
  482. // console.error('恢复下载失败,尝试重新开始:', error)
  483. // 失败时尝试重新开始
  484. try {
  485. if (downloadTask.start) {
  486. downloadTask.start()
  487. }
  488. } catch (e2) {
  489. // console.error('重新开始下载也失败:', e2)
  490. }
  491. }
  492. }
  493. /**
  494. * 停止网络监听
  495. */
  496. function stopNetworkMonitor(): void {
  497. if (networkListener) {
  498. uni.offNetworkStatusChange(networkListener)
  499. networkListener = null
  500. }
  501. }
  502. // ================== 安装 ==================
  503. /**
  504. * 安装 wgt 更新包
  505. */
  506. function installWgt(path: string): void {
  507. // #ifdef APP-PLUS
  508. try {
  509. plus.runtime.install(
  510. path,
  511. { force: false },
  512. () => {
  513. // 安装成功
  514. progress.hide()
  515. updating.value = false
  516. uni.showModal({
  517. title: t('mine.p37'),
  518. content: t('mine.p38'),
  519. showCancel: false,
  520. success: () => {
  521. plus.runtime.restart()
  522. }
  523. })
  524. },
  525. (error) => {
  526. // 安装失败
  527. // console.error('安装失败:', error)
  528. handleDownloadFail(t('mine.p33'))
  529. }
  530. )
  531. } catch (error) {
  532. // console.error('安装异常:', error)
  533. handleDownloadFail(t('mine.p33'))
  534. }
  535. // #endif
  536. }
  537. // ================== 缓存管理 ==================
  538. /**
  539. * 保存下载缓存
  540. */
  541. function saveCache(progressPercent: number): void {
  542. const cache: DownloadCache = {
  543. url: downloadUrl,
  544. progress: progressPercent,
  545. time: Date.now()
  546. }
  547. setStorageSync(STORAGE_KEYS.DOWNLOAD_CACHE, cache)
  548. }
  549. /**
  550. * 清除下载缓存
  551. */
  552. function clearCache(): void {
  553. removeStorageSync(STORAGE_KEYS.DOWNLOAD_CACHE)
  554. }
  555. // ================== 错误处理 ==================
  556. /**
  557. * 处理下载失败
  558. */
  559. function handleDownloadFail(msg: string): void {
  560. progress.hide()
  561. updating.value = false
  562. retryCount = 0
  563. stopNetworkMonitor()
  564. cleanupDownloadTask()
  565. showToast(msg)
  566. }
  567. /**
  568. * 清理下载任务
  569. */
  570. function cleanupDownloadTask(): void {
  571. if (!downloadTask) return
  572. try {
  573. // 移除事件监听
  574. if (stateChangeHandler && downloadTask.removeEventListener) {
  575. downloadTask.removeEventListener('statechanged', stateChangeHandler)
  576. }
  577. // 中止下载
  578. downloadTask.abort()
  579. } catch (error) {
  580. // console.warn('清理下载任务失败:', error)
  581. } finally {
  582. downloadTask = null
  583. stateChangeHandler = null
  584. }
  585. }
  586. /**
  587. * 取消更新
  588. */
  589. function cancelUpdate(): void {
  590. if (!updating.value) {
  591. // console.warn('当前没有正在进行的更新')
  592. return
  593. }
  594. // console.log('用户取消更新')
  595. handleDownloadFail(t('mine.p39') || '已取消更新')
  596. }
  597. // ================== 生命周期 ==================
  598. onUnmounted(() => {
  599. // console.log('useAppUpdate 组件卸载,清理资源')
  600. stopNetworkMonitor()
  601. cleanupDownloadTask()
  602. retryCount = 0
  603. })
  604. return {
  605. checkUpdate,
  606. cancelUpdate,
  607. checking,
  608. updating
  609. }
  610. }