useAppUpdate.ts 17 KB

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