仰望星辰工作室

starmusic-mobile

starmusic-mobile/ common/update.js 8.0 KB · 241 行 原始文件
1/**
2 * 在线更新模块
3 *
4 * 流程:
5 * 1. 每次启动(App.vue onLaunch)或设置页手动触发时调用 checkUpdate()
6 * 2. 请求服务器检查更新(GET api.php?action=check&v=版本代码)
7 * 3. 发现新版本 → promptUpdate() 弹窗提醒
8 * 4. 用户点击"立即更新" → startUpdate() 立即下载(显示进度)
9 * - App(Android):下载完成后 plus.runtime.install 安装
10 * - App(iOS):无法直接安装,转浏览器打开下载地址
11 * - H5:window.open 交给浏览器下载
12 *
13 * 服务端接口约定(官网/api.php):
14 * GET ?action=check&v=121 → { code: 0, data: { version, versionCode, log, force, size, md5, fileName, time, url } }
15 * GET ?action=download → 安装包文件流
16 */
17import { APP_VERSION, APP_VERSION_CODE, UPDATE_API } from './constants.js'
18
19/** 当前应用版本名(如 1.2.1),App 端以原生版本为准 */
20export const getAppVersion = () => {
21 // #ifdef APP-PLUS
22 try {
23 if (plus && plus.runtime && plus.runtime.version) return String(plus.runtime.version)
24 } catch (e) {}
25 // #endif
26 return APP_VERSION
27}
28
29/** 当前应用版本代码(数字,如 118),用于大小比较 */
30export const getAppVersionCode = () => {
31 // #ifdef APP-PLUS
32 try {
33 if (plus && plus.runtime && plus.runtime.versionCode) return parseInt(plus.runtime.versionCode, 10) || 0
34 } catch (e) {}
35 // #endif
36 return APP_VERSION_CODE
37}
38
39/**
40 * 请求服务器检查更新(公共逻辑)
41 * 服务端约定:
42 * - code 0 + data:有新版本(data 为新版本信息)
43 * - code !=0 + data:无新版本(data 为当前版本信息,含更新日志)
44 * - code !=0 + 无 data:服务器无版本数据或异常
45 * @returns {Promise<{update: boolean, info: object|null}>}
46 * update: 是否有可用更新;info: 服务器返回的版本信息(无版本数据时为 null)
47 */
48const requestUpdateInfo = () => {
49 const versionCode = getAppVersionCode()
50 return new Promise((resolve) => {
51 uni.request({
52 url: `${UPDATE_API}?action=check&v=${versionCode}`,
53 method: 'GET',
54 timeout: 10000,
55 success: (res) => {
56 let body = res.data
57 try {
58 if (typeof body === 'string') body = JSON.parse(body)
59 } catch (e) {
60 resolve({ update: false, info: null })
61 return
62 }
63 const info = body && body.data ? body.data : null
64 if (!info) {
65 resolve({ update: false, info: null })
66 return
67 }
68 // 双重校验:服务器已按 v 参数对比过,这里再兜底一次
69 const hasUpdate = body.code === 0 && info.url && (!info.versionCode || info.versionCode > versionCode)
70 resolve({ update: hasUpdate, info })
71 },
72 fail: () => resolve({ update: false, info: null }),
73 })
74 })
75}
76
77/**
78 * 检查更新(启动时静默调用;有更新返回更新信息,否则返回 null)
79 * @returns {Promise<object|null>} 有可用更新返回更新信息对象,否则返回 null(网络异常也返回 null,静默失败)
80 */
81export const checkUpdate = () => {
82 return requestUpdateInfo().then(({ update, info }) => (update ? info : null))
83}
84
85/**
86 * 检查更新(设置页手动调用;无论是否最新都返回版本信息)
87 * @returns {Promise<{update: boolean, info: object|null}>}
88 * update: 是否有可用更新
89 * info: 服务器版本信息;已是最新版本时 info.log 为当前版本的更新日志
90 */
91export const checkUpdateDetail = () => requestUpdateInfo()
92
93/**
94 * 弹窗提示更新;用户点击"立即更新"后立即开始下载
95 * @param {object} info checkUpdate 返回的更新信息
96 */
97export const promptUpdate = (info) => {
98 if (!info) return
99 let content = `当前版本 v${getAppVersion()},发现新版本 v${info.version},是否立即下载更新?`
100 if (info.log) content += `\n\n更新内容:\n${info.log}`
101 uni.showModal({
102 title: '发现新版本',
103 content,
104 confirmText: '立即更新',
105 cancelText: '以后再说',
106 // 强制更新时不允许取消
107 showCancel: !info.force,
108 success: (res) => {
109 if (res.confirm) startUpdate(info)
110 },
111 })
112}
113
114/**
115 * 下载中的等待框(仅 App 端使用)
116 *
117 * 为什么不用 uni.showLoading 反复刷新进度:
118 * 它在原生层每次调用都会新建一个带遮罩的等待框,而 hideLoading 只关掉最后一个,
119 * 之前的遮罩会残留在页面上 —— 表现就是"转圈闪一下就没了,然后页面点不动"。
120 * plus.nativeUI.showWaiting 是应用级单例:重复调用只更新文案,closeWaiting 一次性清干净,
121 * 且默认不锁触摸(padlock:false),下载期间用户仍可正常操作页面。
122 */
123let waitingShown = false
124
125const showWaiting = (title) => {
126 // #ifdef APP-PLUS
127 try {
128 plus.nativeUI.showWaiting(title, { padlock: false })
129 } catch (e) {
130 // plus 异常时退回 uni 实现,保证至少有可见反馈
131 uni.showLoading({ title, mask: false })
132 }
133 waitingShown = true
134 // #endif
135}
136
137const closeWaiting = () => {
138 // #ifdef APP-PLUS
139 if (!waitingShown) return
140 waitingShown = false
141 try {
142 plus.nativeUI.closeWaiting()
143 } catch (e) {}
144 // #endif
145}
146
147/** 正在进行的下载任务:防止用户重复点击导致多个任务/多个等待框叠加 */
148let updateTask = null
149
150/** 立即下载更新包;下载完成后进入安装流程 */
151export const startUpdate = (info) => {
152 const url = info && info.url
153 if (!url) {
154 uni.showToast({ title: '更新地址无效', icon: 'none' })
155 return
156 }
157
158 // #ifdef H5
159 // H5:交给浏览器下载
160 window.open(url, '_blank')
161 // #endif
162
163 // #ifdef APP-PLUS
164 const sysInfo = uni.getSystemInfoSync()
165 if (sysInfo.platform === 'ios') {
166 // iOS 无法直接安装 APK,用系统浏览器打开下载地址由用户处理
167 plus.runtime.openURL(url)
168 return
169 }
170
171 if (updateTask) {
172 uni.showToast({ title: '更新包正在下载中', icon: 'none' })
173 return
174 }
175
176 showWaiting('正在下载更新…')
177 let percent = -1
178 let lastUpdateAt = 0
179 updateTask = uni.downloadFile({
180 url,
181 // 电视/盒子带宽有限,安装包动辄几十 MB,给足超时(仍受系统网络栈约束)
182 timeout: 600000,
183 success: (res) => {
184 updateTask = null
185 if (res.statusCode === 200 && res.tempFilePath) {
186 installPackage(res.tempFilePath, info)
187 } else {
188 closeWaiting()
189 uni.showToast({ title: '下载失败,请重试', icon: 'none' })
190 }
191 },
192 fail: () => {
193 updateTask = null
194 closeWaiting()
195 uni.showToast({ title: '下载失败,请检查网络', icon: 'none' })
196 },
197 })
198 // 进度回调节流:等待框文案刷新无需跟得那么细,避免高频调用原生接口
199 if (updateTask && typeof updateTask.onProgressUpdate === 'function') {
200 updateTask.onProgressUpdate((res) => {
201 const progress = (res && res.progress) || 0
202 if (progress === percent) return
203 const now = Date.now()
204 if (progress < 100 && now - lastUpdateAt < 300) return
205 percent = progress
206 lastUpdateAt = now
207 showWaiting(`正在下载更新 ${progress}%`)
208 })
209 }
210 // #endif
211}
212
213/**
214 * App 端:安装下载好的安装包
215 * plus.runtime.install 内部已处理 Android 7+ 的 FileProvider,可直接安装
216 */
217const installPackage = (filePath, info) => {
218 // 安装界面是系统级的,先收起等待框,避免它盖在安装器上面
219 closeWaiting()
220 updateTask = null
221 plus.runtime.install(
222 filePath,
223 { force: true },
224 () => {
225 // 安装成功(部分机型会直接进入系统安装界面,无需额外处理)
226 console.log('[update] install success')
227 },
228 (err) => {
229 console.error('[update] install failed', err)
230 uni.showModal({
231 title: '安装失败',
232 content: '安装失败,可能是未开启"允许安装未知来源应用"。可改用浏览器下载安装包后手动安装。',
233 confirmText: '浏览器下载',
234 cancelText: '关闭',
235 success: (res) => {
236 if (res.confirm) plus.runtime.openURL(info.url)
237 },
238 })
239 }
240 )
241}