starmusic-mobile
1/**
2 * 音乐核心模块(迁移自 lx-music-mobile/src/core/music/utils.ts + index.ts)
3 *
4 * 职责:
5 * - getMusicUrl / getLyric / getPic:统一入口,分发到自定义源或本地
6 * - 音质选择(根据源支持的音质降级)
7 * - 跨源切换兜底(在自定义源失败时用其他源尝试)
8 */
9import { getLxGlobal, waitForApiInit } from '../user-api/api-executor.js'
10import { getSetting } from '../setting.js'
11import { searchMusic, getSourcePic, getSourceLyric } from '../music-sdk/index.js'
12import { SOURCE_NAMES, STORAGE_KEYS } from '../constants.js'
13import { getData, saveData } from '../data.js'
14
15const QUALITYS = ['flac24bit', 'flac', 'wav', 'ape', '320k', '192k', '128k']
16
17/** 获取音乐音质(根据源支持列表降级) */
18export const getMusicType = (musicInfo, type) => {
19 const list = getLxGlobal().qualityList[musicInfo.source]
20 if (!list || !list.length) return '128k'
21 if (!list.includes(type)) type = list[list.length - 1]
22 const rangeType = QUALITYS.slice(Math.max(0, QUALITYS.indexOf(type)))
23 for (const t of rangeType) {
24 if (musicInfo._types && musicInfo._types[t]) return t
25 }
26 return type
27}
28
29/** 根据用户设置选择播放音质 */
30const getPlayQuality = (highQuality, musicInfo) => {
31 const quality = highQuality
32 const list = getLxGlobal().qualityList[musicInfo.source]
33 if (!list || !list.includes(quality)) return quality
34 return getMusicType(musicInfo, quality)
35}
36
37/**
38 * 调用自定义源 apis 获取音乐 URL
39 * 通过 global.lx.apis[source].getMusicUrl
40 */
41const getApiMusicUrl = async (musicInfo, quality) => {
42 // 等待自定义源初始化完成
43 const inited = await waitForApiInit()
44 if (!inited) return Promise.reject(new Error('自定义源未初始化,请先在设置中启用音源'))
45 const lx = getLxGlobal()
46 const api = lx.apis[musicInfo.source]
47 if (!api || !api.getMusicUrl) return Promise.reject(new Error('当前音源不支持获取播放地址,请导入自定义源'))
48 const result = api.getMusicUrl(musicInfo, quality)
49 return result.promise.then((info) => ({ ...musicInfo, url: info.url, quality: info.type || quality }))
50}
51
52/** URL 缓存上限(条) */
53const URL_CACHE_LIMIT = 500
54
55/**
56 * URL 缓存(仅内存,不落盘)
57 * 各源返回的播放地址多为短时效的 CDN 链接,若跨重启持久化,
58 * 下次启动会命中已失效的旧地址,导致"显示播放中但无声音"。
59 * 因此只在本运行周期内缓存,重启后重新获取新鲜地址。
60 */
61const urlCacheMemory = new Map()
62
63/** 读取 URL 缓存 */
64const getUrlCache = () => urlCacheMemory
65
66/** 超限时丢弃最早写入的一半(Map 保持插入顺序) */
67const trimUrlCache = () => {
68 if (urlCacheMemory.size <= URL_CACHE_LIMIT) return
69 const keys = [...urlCacheMemory.keys()]
70 for (const key of keys.slice(0, Math.floor(keys.length / 2))) urlCacheMemory.delete(key)
71}
72
73/**
74 * 多音源兜底:当前源获取播放地址失败后,按用户设置的备用源顺序,
75 * 逐个跨源匹配同一首歌并尝试获取播放地址,直到某个源成功。
76 * 一轮全部失败时抛出汇总错误(由播放层统一 toast 提醒用户)。
77 * @returns 成功时返回备用源歌曲信息(含 url/quality/fallbackFrom)
78 */
79const tryFallbackSources = async (musicInfo, quality, originErr) => {
80 const fallbackIds = (getSetting()['common.fallbackSources'] || []).filter(
81 (id) => id && id !== musicInfo.source,
82 )
83 if (!fallbackIds.length) throw originErr
84
85 // 跨源搜索匹配同一首歌(一次搜索覆盖全部备用平台,失败则无法兜底)
86 let matched = []
87 try {
88 matched = await findMusic(musicInfo)
89 } catch (err) {
90 console.log('[fallback findMusic]', err.message)
91 }
92
93 const tried = []
94 for (const sid of fallbackIds) {
95 const api = getLxGlobal().apis[sid]
96 if (!api || !api.getMusicUrl) continue
97 const target = matched.find((m) => m.source === sid)
98 if (!target) continue
99 tried.push(sid)
100 try {
101 const info = await getApiMusicUrl(target, getMusicType(target, quality))
102 if (!info.url) throw new Error('返回空地址')
103 // 缓存备用源的地址(key 按备用源歌曲标识,主源缓存不受影响)
104 getUrlCache().set(`${sid}_${target.songmid || target.id}_${info.quality}`, info.url)
105 trimUrlCache()
106 console.log('[fallback]', musicInfo.source, '→', sid, '成功')
107 return { ...target, url: info.url, quality: info.quality, fallbackFrom: musicInfo.source }
108 } catch (err) {
109 console.log('[fallback]', sid, err.message)
110 }
111 }
112
113 // 一轮结束仍无源可用:汇总提醒
114 throw new Error(
115 tried.length
116 ? `所有音源均获取失败(已尝试:${tried.map((id) => SOURCE_NAMES[id] || id).join('、')})`
117 : `备用音源不可用(${originErr.message})`,
118 )
119}
120
121/**
122 * 获取音乐 URL(核心入口)
123 * @param {object} param0
124 * @param {object} param0.musicInfo 音乐信息
125 * @param {string} [param0.quality] 指定音质
126 * @param {boolean} [param0.isRefresh] 是否刷新
127 */
128export const getMusicUrl = ({ musicInfo, quality, isRefresh = false }) => {
129 const setting = getSetting()
130 const targetQuality = quality != null ? quality : getPlayQuality(setting['player.playQuality'], musicInfo)
131 const urlCacheKey = `${musicInfo.source}_${musicInfo.songmid || musicInfo.id}_${targetQuality}`
132
133 // 缓存
134 if (!isRefresh) {
135 const cache = getUrlCache()
136 const cachedUrl = cache.get(urlCacheKey)
137 if (cachedUrl) {
138 return Promise.resolve({ ...musicInfo, url: cachedUrl, quality: targetQuality, isFromCache: true })
139 }
140 }
141
142 return getApiMusicUrl(musicInfo, targetQuality)
143 .then((info) => {
144 // 保存缓存(仅内存,重启后自动失效重新获取)
145 if (info.url) {
146 getUrlCache().set(urlCacheKey, info.url)
147 trimUrlCache()
148 }
149 return info
150 })
151 .catch((err) => {
152 console.log('[getMusicUrl]', musicInfo.source, err.message, '→ 尝试多音源兜底')
153 return tryFallbackSources(musicInfo, targetQuality, err)
154 })
155}
156
157// ============ 歌词 ============
158
159/** 歌词缓存上限(条) */
160const LYRIC_CACHE_LIMIT = 200
161
162/** 歌词内存缓存:lyricKey -> lyricInfo */
163const lyricMemoryCache = new Map()
164let lyricCacheLoaded = false
165let lyricCacheSaveTimer = null
166
167/** 歌词缓存 key */
168const getLyricKey = (musicInfo) => `${musicInfo.source}_${musicInfo.songmid || musicInfo.id}`
169
170/** 惰性加载歌词缓存(仅首次从 storage 载入) */
171const getLyricCache = () => {
172 if (!lyricCacheLoaded) {
173 lyricCacheLoaded = true
174 const cache = getData(STORAGE_KEYS.LYRIC_CACHE, {})
175 for (const key of Object.keys(cache)) lyricMemoryCache.set(key, cache[key])
176 }
177 return lyricMemoryCache
178}
179
180/** 落盘歌词缓存(防抖合并,超出上限时丢弃最早的一半) */
181const flushLyricCache = () => {
182 if (lyricCacheSaveTimer) return
183 lyricCacheSaveTimer = setTimeout(() => {
184 lyricCacheSaveTimer = null
185 if (lyricMemoryCache.size > LYRIC_CACHE_LIMIT) {
186 const keys = [...lyricMemoryCache.keys()]
187 for (const key of keys.slice(0, Math.floor(keys.length / 2))) lyricMemoryCache.delete(key)
188 }
189 saveData(STORAGE_KEYS.LYRIC_CACHE, Object.fromEntries(lyricMemoryCache))
190 }, 800)
191}
192
193/** 写入歌词缓存(仅内存 + 防抖落盘) */
194const saveLyricCache = (key, lyricInfo) => {
195 if (!lyricInfo || !lyricInfo.lyric) return
196 getLyricCache().set(key, lyricInfo)
197 flushLyricCache()
198}
199
200/** 统一歌词返回结构 */
201const formatLyricInfo = (data) => ({
202 lyric: data.lyric || '',
203 tlyric: data.tlyric || '',
204 rlyric: data.rlyric || '',
205 lxlyric: data.lxlyric || '',
206 rawlrcInfo: { lyric: data.lyric || '' },
207})
208
209/** 清空歌词缓存 */
210export const clearLyricCache = () => {
211 if (lyricCacheSaveTimer) {
212 clearTimeout(lyricCacheSaveTimer)
213 lyricCacheSaveTimer = null
214 }
215 lyricMemoryCache.clear()
216 lyricCacheLoaded = true
217 saveData(STORAGE_KEYS.LYRIC_CACHE, {})
218}
219
220/**
221 * 获取歌词信息
222 *
223 * 兜底链(任一环节拿到非空歌词即返回):
224 * 1. 本地缓存
225 * 2. 自定义源(若已启用且声明了 lyric action)
226 * 3. 当前源的内置 SDK
227 * 4. 跨源兜底:用 findMusic 匹配其它平台的同一首歌,取其歌词
228 *
229 * 注意:第 2 步失败或返回空歌词时必须继续往下走,
230 * 否则启用自定义源后内置源的歌词能力会完全失效。
231 *
232 * @param {object} param0.musicInfo
233 * @param {boolean} [param0.isRefresh] 跳过缓存重新获取
234 */
235export const getLyricInfo = async ({ musicInfo, isRefresh = false }) => {
236 const lyricKey = getLyricKey(musicInfo)
237
238 // 1. 缓存
239 if (!isRefresh) {
240 const cached = getLyricCache().get(lyricKey)
241 if (cached && cached.lyric) return cached
242 }
243
244 // 2. 自定义源优先
245 const inited = await waitForApiInit()
246 if (inited) {
247 const api = getLxGlobal().apis[musicInfo.source]
248 if (api && api.getLyric) {
249 try {
250 const data = await api.getLyric(musicInfo).promise
251 if (data && data.lyric) {
252 const info = formatLyricInfo(data)
253 saveLyricCache(lyricKey, info)
254 return info
255 }
256 console.log('[getLyricInfo userApi] 返回空歌词,尝试内置源', musicInfo.source)
257 } catch (err) {
258 console.log('[getLyricInfo userApi]', musicInfo.source, err.message)
259 }
260 }
261 }
262
263 // 3. 当前源的内置 SDK
264 try {
265 const result = await getSourceLyric(musicInfo.source, musicInfo)
266 if (result && result.lyric) {
267 const info = formatLyricInfo(result)
268 saveLyricCache(lyricKey, info)
269 return info
270 }
271 } catch (err) {
272 console.log('[getLyricInfo builtin]', musicInfo.source, err.message)
273 }
274
275 // 4. 跨源兜底:其它平台的同一首歌
276 try {
277 const otherSources = await findMusic(musicInfo)
278 for (const other of otherSources.slice(0, 3)) {
279 try {
280 const result = await getSourceLyric(other.source, other)
281 if (result && result.lyric) {
282 const info = formatLyricInfo(result)
283 saveLyricCache(lyricKey, info)
284 return info
285 }
286 } catch (e) {}
287 }
288 } catch (e) {
289 console.log('[getLyricInfo findMusic]', e.message)
290 }
291
292 return Promise.reject(new Error('未找到该歌曲的歌词'))
293}
294
295// ============ 封面缓存 ============
296
297/**
298 * 封面缓存说明:
299 * kw/kg/wy 的搜索接口不返回封面,需为每首歌单独发一次请求。
300 * 为避免列表滚动时重复请求,这里做三层防护:
301 * 1. 内存缓存 picMemoryCache:本次会话内命中即返回
302 * 2. 持久化缓存 STORAGE_KEYS.PIC_CACHE:跨会话复用,上限 PIC_CACHE_LIMIT 条
303 * 3. 在途请求表 picPendingMap:同一首歌并发请求只发一次
304 */
305const PIC_CACHE_LIMIT = 500
306
307/** 内存缓存:picKey -> url */
308let picMemoryCache = null
309/** 在途请求:picKey -> Promise<string> */
310const picPendingMap = new Map()
311
312/** 封面缓存 key */
313export const getPicKey = (musicInfo) => `${musicInfo.source}_${musicInfo.songmid || musicInfo.id}`
314
315/** 惰性加载持久化缓存到内存 */
316const getPicCache = () => {
317 if (!picMemoryCache) picMemoryCache = getData(STORAGE_KEYS.PIC_CACHE, {})
318 return picMemoryCache
319}
320
321/** 持久化定时器:合并短时间内的多次写入 */
322let picCacheSaveTimer = null
323
324/**
325 * 将内存缓存落盘(延迟合并写入)
326 * uni.setStorageSync 是同步阻塞的,列表懒加载会在短时间内产生几十次写入,
327 * 逐次落盘会造成明显卡顿,因此这里合并为 1 秒一次。
328 */
329const flushPicCache = () => {
330 if (picCacheSaveTimer) return
331 picCacheSaveTimer = setTimeout(() => {
332 picCacheSaveTimer = null
333 const cache = getPicCache()
334 const keys = Object.keys(cache)
335 if (keys.length > PIC_CACHE_LIMIT) {
336 // 对象 key 基本保持插入顺序,去掉前一半即最早写入的记录
337 for (const k of keys.slice(0, Math.floor(keys.length / 2))) delete cache[k]
338 }
339 saveData(STORAGE_KEYS.PIC_CACHE, cache)
340 }, 1000)
341}
342
343/**
344 * 写入封面缓存
345 * @param {string} key
346 * @param {string} url 封面地址;空串表示"已尝试但无封面"
347 * @param {boolean} persist 是否落盘。失败记录仅存内存,
348 * 这样下次启动仍会重试(接口可能只是临时故障)
349 */
350const savePicCache = (key, url, persist = true) => {
351 getPicCache()[key] = url || ''
352 if (persist && url) flushPicCache()
353}
354
355/**
356 * 当前页面是否运行在 https 站点下
357 *
358 * 只有 https 页面才存在"混合内容"限制——http 图片会被浏览器直接拦掉,
359 * 此时把封面升级成 https 是唯一选择。
360 * 而 App(原生渲染)与桌面端(Wails,页面源是 http://wails.localhost)
361 * 本身不是 https,没有混合内容限制,强行升级反而会踩坑:
362 * 部分音乐 CDN(如 img1.kwcdn.kuwo.cn)并未为自有域名配置证书,
363 * https 握手必然失败,结果就是"封面一张都出不来"。
364 */
365const isSecurePage = () => {
366 try {
367 return typeof location !== 'undefined' && !!location && location.protocol === 'https:'
368 } catch (err) {
369 return false
370 }
371}
372
373/**
374 * 封面地址规范化:仅在 https 页面下把 http 升级为 https。
375 *
376 * 这里能做的只是"避免被浏览器按混合内容拦截",无法判断目标 CDN 的
377 * https 是否真的可用(证书不匹配同样会失败,而且失败发生在 <img> 里)。
378 * 因此真正的兜底交给图片元素:加载失败时会自动回退到 http 再试一次。
379 */
380export const normalizePicUrl = (url) => {
381 if (!url || typeof url !== 'string') return ''
382 // #ifdef H5
383 if (isSecurePage() && /^http:\/\//.test(url)) return url.replace(/^http:\/\//, 'https://')
384 // #endif
385 return url
386}
387
388/**
389 * 获取封面图
390 * 逻辑与 lx-music-mobile 一致:优先使用搜索结果自带的 img,否则调用内置源 SDK 的 getPic
391 */
392export const getPicPath = async ({ musicInfo }) => {
393 if (musicInfo.img) return Promise.resolve(normalizePicUrl(musicInfo.img))
394 if (musicInfo.meta && musicInfo.meta.picUrl) return Promise.resolve(normalizePicUrl(musicInfo.meta.picUrl))
395
396 const picKey = getPicKey(musicInfo)
397 const cached = getPicCache()[picKey]
398 if (cached) {
399 musicInfo.img = cached
400 return cached
401 }
402
403 // 调用内置源 SDK 获取封面(kw/kg/tx/wy/mg 均内置 getPic)
404 try {
405 const url = normalizePicUrl(await getSourcePic(musicInfo.source, musicInfo))
406 if (url) {
407 musicInfo.img = url
408 savePicCache(picKey, url)
409 return url
410 }
411 } catch (err) {
412 console.log('[getPicPath]', musicInfo.source, err.message)
413 }
414 // 跨源兜底:从其他源查找同首歌获取封面
415 try {
416 const otherSources = await findMusic(musicInfo)
417 for (const other of otherSources.slice(0, 3)) {
418 try {
419 const url = normalizePicUrl(other.img || (await getSourcePic(other.source, other)))
420 if (url) {
421 savePicCache(picKey, url)
422 return url
423 }
424 } catch (e) {}
425 }
426 } catch (e) {}
427 return ''
428}
429
430/**
431 * 获取列表项封面(供音乐列表懒加载使用)
432 *
433 * 与 getPicPath 的区别:
434 * - 不做跨源兜底(列表场景下 findMusic 会打所有源,代价过高)
435 * - 相同歌曲的并发调用共享同一个请求
436 * - 失败时缓存空串,避免无版权歌曲被反复重试
437 *
438 * @param {object} musicInfo
439 * @returns {Promise<string>} 封面地址,获取失败返回空串
440 */
441export const getPicUrl = (musicInfo) => {
442 if (!musicInfo) return Promise.resolve('')
443 if (musicInfo.img) return Promise.resolve(normalizePicUrl(musicInfo.img))
444 if (musicInfo.meta && musicInfo.meta.picUrl) return Promise.resolve(normalizePicUrl(musicInfo.meta.picUrl))
445
446 const picKey = getPicKey(musicInfo)
447 const cache = getPicCache()
448 // 命中缓存(含失败记录的空串,避免重复重试)
449 if (picKey in cache) return Promise.resolve(cache[picKey] || '')
450
451 const pending = picPendingMap.get(picKey)
452 if (pending) return pending
453
454 const task = (async () => {
455 try {
456 const url = normalizePicUrl(await getSourcePic(musicInfo.source, musicInfo))
457 // 成功则落盘;接口返回空表示该歌确实没有封面,仅记内存
458 savePicCache(picKey, url, !!url)
459 return url || ''
460 } catch (err) {
461 console.log('[getPicUrl]', musicInfo.source, err.message)
462 // 失败仅记内存:本次会话内不再重试,重启后仍会再试一次
463 savePicCache(picKey, '', false)
464 return ''
465 } finally {
466 picPendingMap.delete(picKey)
467 }
468 })()
469
470 picPendingMap.set(picKey, task)
471 return task
472}
473
474/** 清空封面缓存 */
475export const clearPicCache = () => {
476 // 先取消待落盘的定时器,否则它会把旧数据写回
477 if (picCacheSaveTimer) {
478 clearTimeout(picCacheSaveTimer)
479 picCacheSaveTimer = null
480 }
481 picMemoryCache = {}
482 picPendingMap.clear()
483 saveData(STORAGE_KEYS.PIC_CACHE, {})
484}
485
486/**
487 * 跨源搜索匹配(迁移自 musicSdk.findMusic)
488 */
489export const findMusic = async (musicInfo) => {
490 const { name, singer, albumName, interval, source: s } = musicInfo
491
492 const lists = await searchMusic({ name, singer, source: s, limit: 25 })
493
494 const singersRxp = /、|&|;|;|\/|,|,|\|/
495 const sortSingle = (singer) =>
496 singersRxp.test(singer || '')
497 ? singer
498 .split(singersRxp)
499 .sort((a, b) => a.localeCompare(b))
500 .join('、')
501 : singer || ''
502 const getIntv = (interval) => {
503 if (!interval) return 0
504 const intvArr = interval.split(':')
505 let intv = 0
506 let unit = 1
507 while (intvArr.length) {
508 intv += parseInt(intvArr.pop()) * unit
509 unit *= 60
510 }
511 return intv
512 }
513 const trimStr = (str) => (typeof str == 'string' ? str.trim() : str || '')
514 const filterStr = (str) =>
515 typeof str == 'string' ? str.replace(/\s|'|\.|,|,|&|"|、|\(|\)|(|)|`|~|-|<|>|\||\/|\]|\[|!|!/g, '') : String(str || '')
516 const fMusicName = filterStr(name).toLowerCase()
517 const fSinger = filterStr(sortSingle(singer)).toLowerCase()
518 const fAlbumName = filterStr(albumName).toLowerCase()
519 const fInterval = getIntv(interval)
520 const isEqualsInterval = (intv) => Math.abs((fInterval || intv) - (intv || fInterval)) < 5
521 const isIncludesName = (n) => (fMusicName.includes(n) || n.includes(fMusicName))
522 const isIncludesSinger = (sg) => (fSinger ? fSinger.includes(sg) || sg.includes(fSinger) : true)
523 const isEqualsAlbum = (al) => (fAlbumName ? fAlbumName == al : true)
524
525 const result = lists
526 .map((source) => {
527 for (const item of source.list) {
528 item.name = trimStr(item.name)
529 item.singer = trimStr(item.singer)
530 const iFMusicName = filterStr(String(item.name || '')).toLowerCase()
531 const iFSinger = filterStr(sortSingle(item.singer).toLowerCase())
532 const iFAlbumName = filterStr(String(item.albumName || '')).toLowerCase()
533 const iFInterval = getIntv(item.interval)
534 if (!isEqualsInterval(iFInterval)) {
535 item.name = null
536 continue
537 }
538 if (iFMusicName == fMusicName && isIncludesSinger(iFSinger)) return item
539 }
540 for (const item of source.list) {
541 if (item.name == null) continue
542 const iFSinger = filterStr(sortSingle(item.singer).toLowerCase())
543 const iFMusicName = filterStr(String(item.name || '')).toLowerCase()
544 if (iFSinger == fSinger && isIncludesName(iFMusicName)) return item
545 }
546 for (const item of source.list) {
547 if (item.name == null) continue
548 const iFAlbumName = filterStr(String(item.albumName || '')).toLowerCase()
549 const iFSinger = filterStr(sortSingle(item.singer).toLowerCase())
550 const iFMusicName = filterStr(String(item.name || '')).toLowerCase()
551 if (isEqualsAlbum(iFAlbumName) && isIncludesSinger(iFSinger) && isIncludesName(iFMusicName)) return item
552 }
553 return null
554 })
555 .filter((r) => r)
556
557 return result
558}