useAppUpdate.ts 17 KB

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