仰望星辰工作室

starmusic-mobile

starmusic-mobile/ common/user-api/api-executor.js 16.9 KB · 468 行 原始文件
1/**
2 * API 执行器(迁移自 lx-music-mobile/src/core/init/userApi/index.ts)
3 *
4 * 职责:
5 * - 加载/销毁自定义源脚本
6 * - 处理脚本 inited 事件,构建 global.lx.apis / global.lx.qualityList
7 * - 处理脚本发起的 HTTP 请求(lx.request)
8 * - 处理应用侧 musicUrl/lyric/pic 请求与脚本的往返(20s 超时、源切换取消)
9 */
10import * as sandbox from './sandbox.js'
11import { getUserApiList, getUserApiScript, updateUserApiScript } from '../data.js'
12import { getSetting } from '../setting.js'
13import event from '../event.js'
14import { addLog } from './logger.js'
15import { extractSourceScript, fetchSourceScript, markAttempted, hasAttempted } from './script-updater.js'
16
17// 全局 lx 状态(等价原项目 global.lx)
18const lxGlobal = {
19 apis: {},
20 qualityList: {},
21 apiInitPromise: [null, true, null],
22}
23
24/** 用户源列表 */
25let userApiList = []
26let currentApiId = ''
27
28// 应用 → 脚本 的请求映射
29const userApiRequestMap = new Map()
30
31/** 注册事件监听(供 UI 层获取源状态) */
32const notifyStatusChange = (status, message) => {
33 event.emit('userApiStatusChanged', { status, message, id: currentApiId })
34}
35
36const notifyListChange = (list) => {
37 event.emit('userApiListChanged', [...list])
38}
39
40/** 设置源状态 */
41const setUserApiStatus = (status, message = '') => {
42 notifyStatusChange(status, message)
43}
44
45/** 更新用户源列表 */
46const setUserApiList = (list) => {
47 userApiList = list
48 notifyListChange(list)
49}
50
51/** 汇总脚本返回值(URL 只保留长度与开头,避免日志过长) */
52const summarizeApiResult = (action, result) => {
53 const data = (result && result.data) || {}
54 if (action === 'musicUrl') {
55 const url = data.url || ''
56 return url ? `URL 长度 ${url.length}:${String(url).substring(0, 80)}` : '未返回 URL'
57 }
58 if (action === 'lyric') {
59 const len = ((data.lyric || '') + (data.tlyric || '')).length
60 return `歌词长度 ${len}`
61 }
62 if (action === 'pic') {
63 const url = typeof data === 'string' ? data : data.url || ''
64 return url ? `封面:${String(url).substring(0, 80)}` : '未返回封面'
65 }
66 return ''
67}
68
69/** 描述一次 API 请求(用于日志) */
70const describeApiRequest = (data) => {
71 const { source, action, info } = data
72 const music = (info && info.musicInfo) || {}
73 const name = [music.singer, music.name].filter(Boolean).join(' - ') || '未知歌曲'
74 const actionText = { musicUrl: '获取播放地址', lyric: '获取歌词', pic: '获取封面' }[action] || action
75 const quality = info && info.type ? ` [${info.type}]` : ''
76 return `${actionText}|${source}|${name}${quality}`
77}
78
79/** 应用 → 脚本 的 API 请求(musicUrl/lyric/pic) */
80const sendUserApiRequest = (data) => {
81 const label = describeApiRequest(data)
82 addLog('request', label)
83
84 const handleApiUpdate = () => {
85 const target = userApiRequestMap.get(data.requestKey)
86 if (!target) return
87 userApiRequestMap.delete(data.requestKey)
88 clearTimeout(target.timeout)
89 addLog('error', `${label} → 已取消(音源切换)`)
90 target.reject(new Error('request failed'))
91 }
92
93 const requestPromise = new Promise((resolve, reject) => {
94 userApiRequestMap.set(data.requestKey, {
95 resolve,
96 reject,
97 timeout: setTimeout(() => {
98 const target = userApiRequestMap.get(data.requestKey)
99 if (!target) return
100 userApiRequestMap.delete(data.requestKey)
101 addLog('error', `${label} → 超时(20 秒未响应)`)
102 target.reject(new Error('request timeout'))
103 }, 20_000),
104 })
105 sandbox
106 .sendAction('request', data.data)
107 .then((result) => {
108 const target = userApiRequestMap.get(data.requestKey)
109 if (!target) return
110 userApiRequestMap.delete(data.requestKey)
111 clearTimeout(target.timeout)
112 addLog('response', `${label} → 已返回`, summarizeApiResult(data.action, result))
113 target.resolve(result)
114 })
115 .catch((err) => {
116 const target = userApiRequestMap.get(data.requestKey)
117 if (!target) return
118 userApiRequestMap.delete(data.requestKey)
119 clearTimeout(target.timeout)
120 addLog('error', `${label} → 失败`, err && err.message)
121 target.reject(err)
122 })
123 })
124
125 const offHandler = () => handleApiUpdate()
126 event.on('apiSourceUpdated', offHandler)
127 requestPromise.finally(() => {
128 event.off('apiSourceUpdated', offHandler)
129 })
130 return requestPromise
131}
132
133/** 处理脚本 inited 事件,构建 apis */
134const handleStateChange = ({ id, status, errorMessage, info }) => {
135 setUserApiStatus(status, errorMessage)
136 if (id !== currentApiId) return
137 if (status) {
138 if (info && info.sources) {
139 const apis = {}
140 const qualitys = {}
141 for (const [source, { actions, type, qualitys: sourceQualitys }] of Object.entries(info.sources)) {
142 if (type != 'music') continue
143 apis[source] = {}
144 for (const action of actions) {
145 switch (action) {
146 case 'musicUrl':
147 apis[source].getMusicUrl = (songInfo, type) => {
148 const requestKey = 'request__' + Math.random().toString().substring(2)
149 return {
150 canceleFn() {},
151 promise: sendUserApiRequest({
152 requestKey,
153 data: { source, action: 'musicUrl', info: { type, musicInfo: songInfo } },
154 }).then((res) => ({ type, url: res.data.url })),
155 }
156 }
157 break
158 case 'lyric':
159 apis[source].getLyric = (songInfo) => {
160 const requestKey = 'request__' + Math.random().toString().substring(2)
161 return {
162 canceleFn() {},
163 promise: sendUserApiRequest({
164 requestKey,
165 data: { source, action: 'lyric', info: { type: null, musicInfo: songInfo } },
166 }).then((res) => res.data),
167 }
168 }
169 break
170 case 'pic':
171 apis[source].getPic = (songInfo) => {
172 const requestKey = 'request__' + Math.random().toString().substring(2)
173 return {
174 canceleFn() {},
175 promise: sendUserApiRequest({
176 requestKey,
177 data: { source, action: 'pic', info: { type: null, musicInfo: songInfo } },
178 }).then((res) => res.data),
179 }
180 }
181 break
182 }
183 }
184 qualitys[source] = sourceQualitys
185 }
186 lxGlobal.apis = apis
187 lxGlobal.qualityList = qualitys
188 const supportDesc = Object.keys(apis)
189 .map((s) => `${s}(${Object.keys(apis[s]).map((k) => k.replace('get', '')).join('/')})`)
190 .join(',')
191 addLog('init', `源初始化成功:${currentApiId}`, supportDesc ? `支持平台:${supportDesc}` : '')
192 event.emit('apiSourceUpdated', currentApiId)
193 }
194 } else {
195 addLog('error', `源初始化失败:${currentApiId}`, errorMessage)
196 if (errorMessage) {
197 uni.showToast({ title: `${errorMessage}`, icon: 'none', duration: 3000 })
198 }
199 }
200 if (!lxGlobal.apiInitPromise[1]) lxGlobal.apiInitPromise[2](status)
201}
202
203/** 格式化脚本 lx.log 的参数(可能是多个值或对象) */
204const formatScriptLog = (data) => {
205 const format = (item) => {
206 if (item == null) return String(item)
207 if (typeof item === 'object') {
208 try {
209 return JSON.stringify(item)
210 } catch (e) {
211 return String(item)
212 }
213 }
214 return String(item)
215 }
216 return Array.isArray(data) ? data.map(format).join(' ') : format(data)
217}
218
219/**
220 * 打开音源更新页(自动更新不可用时的回退行为)
221 * H5 直接开新窗口;App 无浏览器能力,复制链接让用户自行打开
222 */
223const openUpdateUrl = (updateUrl) => {
224 // #ifdef H5
225 window.open(updateUrl)
226 // #endif
227 // #ifndef H5
228 uni.setClipboardData({
229 data: updateUrl,
230 success: () => uni.showToast({ title: '更新地址已复制', icon: 'none' }),
231 })
232 // #endif
233}
234
235/**
236 * 执行一次音源更新:下载 → 校验 → 原地替换 → 重载(仅当该源启用中)
237 * 任一步失败都会抛错,且绝不留下损坏的音源内容,调用方据此回退到手动弹窗
238 * @param {object} params { apiId, name, updateUrl }
239 * @returns {Promise<void>}
240 */
241const autoUpdateApiScript = async ({ apiId, name, updateUrl }) => {
242 // 保护:先备份旧脚本。替换后若新脚本加载失败必须写回旧脚本并恢复旧源,
243 // 否则用户会彻底失去这个可用音源 —— 这是本功能最大的风险点
244 const oldScript = getUserApiScript(apiId)
245 const res = await fetchSourceScript(updateUrl)
246 // 更新接口普遍是 JSON(脚本藏在某个字段里),按"内容像不像音源脚本"挑出来;
247 // 取不到时 reason 会带上服务端原话(如"卡密失效"),不再一律报"不是有效脚本"
248 const { script, reason } = extractSourceScript(res.data)
249 if (!script) throw new Error(reason || `下载失败:HTTP ${res.statusCode}`)
250 updateUserApiScript(apiId, script)
251 // 刷新执行器内的源列表并通知 UI:音源列表显示的名称/版本号需要跟着更新
252 updateUserApiList()
253
254 // 该源此刻是否启用中(内存里的 currentApiId 或设置里的启用源)
255 const isEnabled = currentApiId === apiId || getSetting()['common.apiSource'] === apiId
256 if (!isEnabled) return
257
258 try {
259 // loadUserApi 初始化失败会 reject,这里能拿到明确的失败信号
260 await loadUserApi(apiId)
261 } catch (err) {
262 addLog('error', `音源更新失败,正在回滚:${name}`, err && err.message)
263 try {
264 updateUserApiScript(apiId, oldScript)
265 updateUserApiList()
266 await loadUserApi(apiId)
267 } catch (rollbackErr) {
268 addLog('error', `音源回滚失败:${name}`, rollbackErr && rollbackErr.message)
269 }
270 throw err
271 }
272}
273
274/**
275 * 手动更新提醒弹窗
276 * - 无更新地址:仅提示(保持原有语义)
277 * - 有地址且能定位音源:提供「重试更新」,手动路径不受会话去重限制,可反复尝试
278 * - 有地址但定位不到音源:退化为原有的「打开更新页 / 复制链接」
279 */
280const showManualUpdateAlert = ({ name, log, updateUrl, apiId }) => {
281 if (!updateUrl) {
282 uni.showModal({ title: `源更新提醒:${name}`, content: log, showCancel: false })
283 return
284 }
285 const canRetry = !!apiId
286 uni.showModal({
287 title: `源更新提醒:${name}`,
288 content: log,
289 confirmText: canRetry ? '重试更新' : '打开更新页',
290 cancelText: '关闭',
291 success: (res) => {
292 if (!res.confirm) return
293 if (!canRetry) {
294 openUpdateUrl(updateUrl)
295 return
296 }
297 autoUpdateApiScript({ apiId, name, updateUrl })
298 .then(() => {
299 addLog('init', `音源已手动更新:${name}`)
300 uni.showToast({ title: '音源已更新', icon: 'none' })
301 })
302 .catch((err) => {
303 addLog('error', `音源手动更新失败:${name}`, err && err.message)
304 // 失败原因要如实展示(卡密失效 / 接口改版等),否则用户只会以为"音源坏了"
305 uni.showModal({
306 title: '更新失败',
307 content: `${(err && err.message) || '未知原因'}\n\n已保留原音源,可稍后重试或前往更新页手动下载。`,
308 confirmText: updateUrl ? '打开更新页' : '知道了',
309 showCancel: !!updateUrl,
310 cancelText: '关闭',
311 success: (r) => {
312 if (r.confirm && updateUrl) openUpdateUrl(updateUrl)
313 },
314 })
315 })
316 },
317 })
318}
319
320/** 注册脚本动作处理 */
321const initScriptActions = () => {
322 sandbox.onScriptAction((eventData) => {
323 switch (eventData.action) {
324 case 'init':
325 handleStateChange(eventData.data)
326 break
327 case 'showUpdateAlert':
328 {
329 const { name, log, updateUrl } = eventData.data
330 // 定位音源:先按名字匹配,再退回当前启用源(脚本名可能与列表 name 不完全一致)
331 const apiList = getUserApiList()
332 const target = apiList.find((api) => api.name === name) || apiList.find((api) => api.id === currentApiId)
333 // 用户已对该源关闭更新提醒 → 完全跳过(连自动更新也不做)
334 if (target && target.allowShowUpdateAlert === false) {
335 addLog('log', `已关闭更新提醒:${name}`)
336 break
337 }
338 const apiId = target ? target.id : ''
339 if (!updateUrl) {
340 showManualUpdateAlert({ name, log, updateUrl: null, apiId })
341 break
342 }
343 // 定位不到音源(已被删除等)无法原地替换 → 直接走手动提醒
344 if (!apiId) {
345 showManualUpdateAlert({ name, log, updateUrl, apiId })
346 break
347 }
348 // 本次运行已自动更新过一次仍弹出(新脚本没解决问题)→ 不再自动更新,交给用户选择
349 if (hasAttempted(apiId)) {
350 addLog('log', `更新后仍提示更新,改为手动确认:${name}`)
351 showManualUpdateAlert({ name, log, updateUrl, apiId })
352 break
353 }
354 // 进入流程立即登记,确保同一次运行内不会重复下载 / 反复重载
355 markAttempted(apiId)
356 addLog('init', `检测到音源更新,开始自动更新:${name}`)
357 autoUpdateApiScript({ apiId, name, updateUrl })
358 .then(() => {
359 addLog('init', `音源已自动更新:${name}`)
360 uni.showToast({ title: '音源已自动更新', icon: 'none' })
361 })
362 .catch((err) => {
363 addLog('error', `音源自动更新失败:${name}`, err && err.message)
364 // 把失败原因拼进弹窗内容:卡密失效 / 接口改版这类原因得让用户看到,
365 // 否则用户只会以为"音源坏了"
366 const reason = err && err.message ? `自动更新失败:${err.message}` : ''
367 showManualUpdateAlert({
368 name,
369 log: [log, reason].filter(Boolean).join('\n\n'),
370 updateUrl,
371 apiId,
372 })
373 })
374 }
375 break
376 case 'log':
377 console.log('[user api log]', eventData.data)
378 addLog('log', formatScriptLog(eventData.data))
379 break
380 }
381 })
382}
383
384/**
385 * 加载自定义源
386 * @param {string} apiId 源 id(user_api_xxx)
387 * @returns {Promise<boolean>} 初始化是否成功
388 */
389export const loadUserApi = async (apiId) => {
390 lxGlobal.qualityList = {}
391 setUserApiStatus('initing', '')
392 currentApiId = apiId
393
394 // 直接从存储读取源列表(避免内存缓存未同步导致找不到)
395 const target = getUserApiList().find((api) => api.id === apiId)
396 if (!target) {
397 addLog('error', `加载源失败:未找到源(${apiId})`)
398 throw new Error('api not found')
399 }
400 addLog('init', `正在加载源:${target.name || apiId}`)
401 const script = await getUserApiScript(target.id)
402 if (!script) {
403 addLog('error', `加载源失败:脚本内容为空(${target.name || apiId})`)
404 throw new Error('api script not found')
405 }
406
407 // 创建初始化 Promise(inited 事件后 resolve)
408 lxGlobal.apiInitPromise[0] = new Promise((resolve) => {
409 lxGlobal.apiInitPromise[1] = false
410 lxGlobal.apiInitPromise[2] = (result) => {
411 lxGlobal.apiInitPromise[1] = true
412 resolve(result)
413 }
414 })
415
416 sandbox.loadScript({ ...target, script })
417
418 // 等待 inited 结果(20s 超时保护)
419 const timeoutPromise = new Promise((resolve) => {
420 setTimeout(() => resolve(false), 20_000)
421 })
422 const result = await Promise.race([lxGlobal.apiInitPromise[0], timeoutPromise])
423 lxGlobal.apiInitPromise[1] = true
424 if (!result) throw new Error('源初始化失败')
425 return result
426}
427
428/**
429 * 等待当前自定义源初始化完成(供播放等操作调用)
430 * @returns {Promise<boolean>}
431 */
432export const waitForApiInit = () => {
433 // 加载中:返回初始化 Promise
434 if (lxGlobal.apiInitPromise[0]) return lxGlobal.apiInitPromise[0]
435 // 已启用自定义源且 apis 已构建成功
436 if (currentApiId && Object.keys(lxGlobal.apis).length > 0) return Promise.resolve(true)
437 // 未启用自定义源或初始化失败
438 return Promise.resolve(false)
439}
440
441/** 销毁自定义源 */
442export const destroyUserApi = () => {
443 sandbox.destroy()
444 currentApiId = ''
445 lxGlobal.apis = {}
446 lxGlobal.qualityList = {}
447 lxGlobal.apiInitPromise = [null, true, null]
448}
449
450/** 获取用户源列表 */
451export const getUserApiListFromStore = () => [...userApiList]
452
453/** 更新用户源列表(导入/删除后) */
454export const updateUserApiList = () => {
455 setUserApiList(getUserApiList())
456}
457
458/** 获取全局 lx 状态 */
459export const getLxGlobal = () => lxGlobal
460
461/** 初始化:注册脚本动作 + 加载列表 */
462export const initUserApi = () => {
463 initScriptActions()
464 updateUserApiList()
465}
466
467/** 当前启用源 */
468export const getCurrentApiId = () => currentApiId