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 { 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. 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. }