useAppUpdate.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. // 测试环境地址
  189. // const Host80 = 'https://secure.44a5c8109e4.com/'
  190. const userStore = useUserStore()
  191. const progress = useProgress()
  192. const checking = ref(false)
  193. const updating = ref(false)
  194. const lastVersion = ref('')
  195. let downloadTask: PlusDownloaderDownload | null = null
  196. let networkListener: ((res: any) => void) | null = null
  197. let downloadUrl = ''
  198. let retryCount = 0
  199. let stateChangeHandler: ((d: any) => void) | null = null
  200. // ================== 对外入口 ==================
  201. /**
  202. * 检查应用更新
  203. */
  204. async function checkUpdate(): Promise<void> {
  205. // #ifdef APP-PLUS
  206. if (checking.value) {
  207. // console.warn('更新检查已在进行中')
  208. return
  209. }
  210. checking.value = true
  211. try {
  212. const res = await uni.request({
  213. url: `${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 = `${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. showToast(t('mine.p28') || `检查更新失败: ${errorMsg}`)
  256. } finally {
  257. checking.value = false
  258. }
  259. // #endif
  260. }
  261. // ================== 更新流程 ==================
  262. /**
  263. * 显示强制更新弹窗
  264. */
  265. function showForceUpdate(update: UpdateInfo): void {
  266. uni.showModal({
  267. title: t('mine.p22'),
  268. content: t('mine.p23'),
  269. showCancel: false,
  270. confirmText: t('mine.p35'),
  271. success: () => doUpdate(update),
  272. })
  273. }
  274. /**
  275. * 显示可选更新弹窗
  276. */
  277. function showOptionalUpdate(update: UpdateInfo): void {
  278. uni.showModal({
  279. title: t('mine.p24'),
  280. content: t('mine.p25', { version: `v${update.version}` }),
  281. confirmText: t('mine.p35'),
  282. cancelText: t('mine.p36'),
  283. success: (res) => {
  284. if (res.confirm) {
  285. doUpdate(update)
  286. } else {
  287. // 记录跳过的版本
  288. setStorageSync(STORAGE_KEYS.SKIP_VERSION, update.version)
  289. }
  290. },
  291. })
  292. }
  293. /**
  294. * 执行更新
  295. */
  296. function doUpdate(update: UpdateInfo): void {
  297. console.log(update)
  298. const platform = getPlatform()
  299. // ios不走这里面
  300. if (platform === 'ios') {
  301. // handleIosUpdate(update)
  302. } else {
  303. handleAndroidUpdate(update)
  304. }
  305. }
  306. /**
  307. * 处理 iOS 更新
  308. */
  309. function handleIosUpdate(update: UpdateInfo): void {
  310. if (!update.iosStoreUrl) {
  311. showToast(t('mine.p28') || 'iOS 更新链接不存在')
  312. return
  313. }
  314. try {
  315. plus.runtime.openURL(update.iosStoreUrl)
  316. } catch (error) {
  317. // console.error('打开 App Store 失败:', error)
  318. showToast(t('mine.p28') || '打开 App Store 失败')
  319. }
  320. }
  321. /**
  322. * 处理 Android 更新
  323. */
  324. function handleAndroidUpdate(update: UpdateInfo): void {
  325. console.log('up2',update)
  326. if (!update.wgtUrl) {
  327. showToast(t('mine.p28') || '更新包链接不存在')
  328. return
  329. }
  330. downloadWgt(update.wgtUrl)
  331. }
  332. // ================== 下载核心 ==================
  333. /**
  334. * 下载 wgt 更新包
  335. */
  336. function downloadWgt(url: string): void {
  337. // #ifdef APP-PLUS
  338. if (downloadTask) {
  339. console.log('下载任务已存在')
  340. return
  341. }
  342. if (!url || !isValidUrl(url)) {
  343. handleDownloadFail(t('mine.p28') || '下载链接无效')
  344. return
  345. }
  346. downloadUrl = url
  347. retryCount = 0
  348. updating.value = true
  349. progress.show(t('mine.p29'))
  350. // 初始化网络监听
  351. initNetworkType()
  352. startNetworkMonitor()
  353. createDownloadTask(url)
  354. // #endif
  355. }
  356. /**
  357. * 创建下载任务
  358. */
  359. function createDownloadTask(url: string): void {
  360. try {
  361. downloadTask = plus.downloader.createDownload(
  362. url,
  363. { filename: DOWNLOAD_CONFIG.FILE_PATH },
  364. handleDownloadComplete,
  365. )
  366. if (!downloadTask) {
  367. throw new Error('创建下载任务失败')
  368. }
  369. // 创建状态变化处理器
  370. stateChangeHandler = handleDownloadStateChanged
  371. downloadTask.addEventListener('statechanged', stateChangeHandler)
  372. downloadTask.start()
  373. } catch (error) {
  374. // console.error('创建下载任务失败:', error)
  375. downloadTask = null
  376. handleDownloadFail(t('mine.p28') || '创建下载任务失败')
  377. }
  378. }
  379. /**
  380. * 验证 URL 格式
  381. */
  382. function isValidUrl(url: string): boolean {
  383. try {
  384. return /^https?:\/\/.+/.test(url)
  385. } catch {
  386. return false
  387. }
  388. }
  389. /**
  390. * 处理下载完成回调
  391. */
  392. function handleDownloadComplete(download: PlusDownloaderDownload, status: number): void {
  393. const isSuccess = status === HttpStatus.OK || status === HttpStatus.PARTIAL_CONTENT
  394. if (isSuccess) {
  395. // console.log('下载成功,准备安装')
  396. clearCache()
  397. stopNetworkMonitor()
  398. installWgt(download.filename)
  399. } else {
  400. // console.error('下载失败,状态码:', status)
  401. retryDownload()
  402. }
  403. }
  404. /**
  405. * 处理下载状态变化
  406. */
  407. function handleDownloadStateChanged(event: DownloadStateEvent): void {
  408. if (event.state === DownloadState.DOWNLOADING && event.totalSize > 0) {
  409. const percent = Math.min(100, Math.floor((event.downloadedSize / event.totalSize) * 100))
  410. const progressText = `${t('mine.p29')} ${percent}%`
  411. progress.update(percent, progressText)
  412. saveCache(percent)
  413. }
  414. }
  415. /**
  416. * 重试下载
  417. */
  418. function retryDownload(): void {
  419. if (retryCount >= DOWNLOAD_CONFIG.MAX_RETRY) {
  420. // console.error(`下载失败,已重试 ${retryCount} 次`)
  421. handleDownloadFail(t('mine.p28') || '下载失败')
  422. return
  423. }
  424. retryCount++
  425. // console.log(`下载失败,${DOWNLOAD_CONFIG.RETRY_DELAY / 1000}秒后重试 (${retryCount}/${DOWNLOAD_CONFIG.MAX_RETRY})`)
  426. cleanupDownloadTask()
  427. setTimeout(() => {
  428. if (downloadUrl) {
  429. createDownloadTask(downloadUrl)
  430. }
  431. }, DOWNLOAD_CONFIG.RETRY_DELAY)
  432. }
  433. /**
  434. * 初始化网络类型
  435. */
  436. function initNetworkType(): void {
  437. uni.getNetworkType({
  438. success: (res) => {
  439. // console.log('当前网络类型:', res.networkType)
  440. },
  441. fail: (error) => {
  442. // console.warn('获取网络类型失败:', error)
  443. },
  444. })
  445. }
  446. // ================== 网络处理 ==================
  447. /**
  448. * 启动网络监听
  449. */
  450. function startNetworkMonitor(): void {
  451. // #ifdef APP-PLUS
  452. if (networkListener) {
  453. // console.warn('网络监听已存在')
  454. return
  455. }
  456. networkListener = (res: any) => {
  457. if (!downloadTask || !updating.value) {
  458. return
  459. }
  460. if (!res.isConnected) {
  461. // 网络断开,暂停下载
  462. pauseDownload()
  463. return
  464. }
  465. // 网络恢复,继续下载
  466. resumeDownload()
  467. }
  468. uni.onNetworkStatusChange(networkListener)
  469. // #endif
  470. }
  471. /**
  472. * 暂停下载
  473. */
  474. function pauseDownload(): void {
  475. if (!downloadTask) return
  476. try {
  477. if (typeof downloadTask.pause === 'function') {
  478. downloadTask.pause()
  479. }
  480. } catch (error) {
  481. // console.error('暂停下载失败:', error)
  482. }
  483. }
  484. /**
  485. * 恢复下载
  486. */
  487. function resumeDownload(): void {
  488. if (!downloadTask) return
  489. try {
  490. if (typeof downloadTask.resume === 'function') {
  491. downloadTask.resume()
  492. } else if (typeof downloadTask.start === 'function') {
  493. downloadTask.start()
  494. }
  495. } catch (error) {
  496. // console.error('恢复下载失败,尝试重新开始:', error)
  497. // 失败时尝试重新开始
  498. try {
  499. if (downloadTask.start) {
  500. downloadTask.start()
  501. }
  502. } catch (e2) {
  503. // console.error('重新开始下载也失败:', e2)
  504. }
  505. }
  506. }
  507. /**
  508. * 停止网络监听
  509. */
  510. function stopNetworkMonitor(): void {
  511. if (networkListener) {
  512. uni.offNetworkStatusChange(networkListener)
  513. networkListener = null
  514. }
  515. }
  516. // ================== 安装 ==================
  517. /**
  518. * 安装 wgt 更新包
  519. */
  520. function installWgt(path: string): void {
  521. // #ifdef APP-PLUS
  522. try {
  523. plus.runtime.install(
  524. path,
  525. { force: true },
  526. () => {
  527. // 安装成功
  528. progress.hide()
  529. updating.value = false
  530. uni.showModal({
  531. title: t('mine.p37'),
  532. content: t('mine.p38'),
  533. showCancel: false,
  534. success: () => {
  535. uni.setStorageSync('lastWgtVersion', lastVersion.value)
  536. console.log('[wgt] install success:', lastVersion.value)
  537. uni.setStorageSync('wgtNeedRestart', true)
  538. plus.runtime.restart()
  539. },
  540. })
  541. },
  542. (error) => {
  543. // 安装失败
  544. // console.error('安装失败:', error)
  545. handleDownloadFail(t('mine.p33'))
  546. },
  547. )
  548. } catch (error) {
  549. // console.error('安装异常:', error)
  550. handleDownloadFail(t('mine.p33'))
  551. }
  552. // #endif
  553. }
  554. // ================== 缓存管理 ==================
  555. /**
  556. * 保存下载缓存
  557. */
  558. function saveCache(progressPercent: number): void {
  559. const cache: DownloadCache = {
  560. url: downloadUrl,
  561. progress: progressPercent,
  562. time: Date.now(),
  563. }
  564. setStorageSync(STORAGE_KEYS.DOWNLOAD_CACHE, cache)
  565. }
  566. /**
  567. * 清除下载缓存
  568. */
  569. function clearCache(): void {
  570. removeStorageSync(STORAGE_KEYS.DOWNLOAD_CACHE)
  571. }
  572. // ================== 错误处理 ==================
  573. /**
  574. * 处理下载失败
  575. */
  576. function handleDownloadFail(msg: string): void {
  577. progress.hide()
  578. updating.value = false
  579. retryCount = 0
  580. stopNetworkMonitor()
  581. cleanupDownloadTask()
  582. showToast(msg)
  583. }
  584. /**
  585. * 清理下载任务
  586. */
  587. function cleanupDownloadTask(): void {
  588. if (!downloadTask) return
  589. try {
  590. // 移除事件监听
  591. if (stateChangeHandler && downloadTask.removeEventListener) {
  592. downloadTask.removeEventListener('statechanged', stateChangeHandler)
  593. }
  594. // 中止下载
  595. downloadTask.abort()
  596. } catch (error) {
  597. // console.warn('清理下载任务失败:', error)
  598. } finally {
  599. downloadTask = null
  600. stateChangeHandler = null
  601. }
  602. }
  603. /**
  604. * 取消更新
  605. */
  606. function cancelUpdate(): void {
  607. if (!updating.value) {
  608. // console.warn('当前没有正在进行的更新')
  609. return
  610. }
  611. // console.log('用户取消更新')
  612. handleDownloadFail(t('mine.p39') || '已取消更新')
  613. }
  614. // ================== 生命周期 ==================
  615. onUnmounted(() => {
  616. // console.log('useAppUpdate 组件卸载,清理资源')
  617. stopNetworkMonitor()
  618. cleanupDownloadTask()
  619. retryCount = 0
  620. })
  621. return {
  622. checkUpdate,
  623. cancelUpdate,
  624. checking,
  625. updating,
  626. }
  627. }