starmusic-mobile
1/**
2 * 内置源 SDK(迁移自 lx-music-mobile/src/utils/musicSdk)
3 * 注意:与 lx-music-mobile 一致,内置源仅提供数据查询(搜索/热搜/榜单),
4 * 播放 URL/歌词/封面由自定义源脚本提供(global.lx.apis)
5 */
6import { SOURCE_NAMES } from '../constants.js'
7import { httpFetch } from './request.js'
8import { decodeName, formatSinger, formatPlayTime } from '../utils.js'
9import kg from './kg.js'
10import tx from './tx.js'
11import wy from './wy.js'
12import mg from './mg.js'
13
14// ============ 酷我音乐 (kw) ============
15const kw = {
16 name: SOURCE_NAMES.kw,
17 limit: 30,
18 total: 0,
19 page: 0,
20 allPage: 1,
21 regExps: {
22 mInfo: /level:(\w+),bitrate:(\d+),format:(\w+),size:([\w.]+)/,
23 },
24
25 /** 搜索歌曲 */
26 async musicSearch(str, page = 1, limit = 30) {
27 const { body: result } = await httpFetch(
28 `http://search.kuwo.cn/r.s?client=kt&all=${encodeURIComponent(str)}&pn=${page - 1}&rn=${limit}&uid=794762570&ver=kwplayer_ar_9.2.2.1&vipver=1&show_copyright_off=1&newver=1&ft=music&cluster=0&strategy=2012&encoding=utf8&rformat=json&vermerge=1&mobi=1&issubtitle=1`,
29 ).promise
30 if (!result || (result.TOTAL !== '0' && result.SHOW === '0')) throw new Error('搜索失败')
31 const list = this.handleResult(result.abslist)
32 this.total = parseInt(result.TOTAL)
33 this.page = page
34 this.allPage = Math.ceil(this.total / limit)
35 return {
36 list,
37 allPage: this.allPage,
38 total: this.total,
39 limit,
40 source: 'kw',
41 }
42 },
43
44 /** 搜索(统一入口,与其他源一致) */
45 search(str, page = 1, limit = 30) {
46 return this.musicSearch(str, page, limit)
47 },
48
49 handleResult(rawData) {
50 const result = []
51 if (!rawData) return result
52 for (const info of rawData) {
53 const songId = info.MUSICRID.replace('MUSIC_', '')
54 if (!info.N_MINFO) {
55 console.log('N_MINFO is undefined')
56 return []
57 }
58 const types = []
59 const _types = {}
60 const infoArr = info.N_MINFO.split(';')
61 for (let item of infoArr) {
62 item = item.match(this.regExps.mInfo)
63 if (item) {
64 switch (item[2]) {
65 case '4000':
66 types.push({ type: 'flac24bit', size: item[4] })
67 _types.flac24bit = { size: item[4].toLocaleUpperCase() }
68 break
69 case '2000':
70 types.push({ type: 'flac', size: item[4] })
71 _types.flac = { size: item[4].toLocaleUpperCase() }
72 break
73 case '320':
74 types.push({ type: '320k', size: item[4] })
75 _types['320k'] = { size: item[4].toLocaleUpperCase() }
76 break
77 case '128':
78 types.push({ type: '128k', size: item[4] })
79 _types['128k'] = { size: item[4].toLocaleUpperCase() }
80 break
81 }
82 }
83 }
84 types.reverse()
85 const interval = parseInt(info.DURATION)
86 result.push({
87 name: decodeName(info.SONGNAME),
88 singer: formatSinger(decodeName(info.ARTIST)),
89 source: 'kw',
90 songmid: songId,
91 albumId: decodeName(info.ALBUMID || ''),
92 interval: Number.isNaN(interval) ? 0 : formatPlayTime(interval),
93 albumName: info.ALBUM ? decodeName(info.ALBUM) : '',
94 lrc: null,
95 img: null,
96 otherSource: null,
97 types,
98 _types,
99 typeUrl: {},
100 })
101 }
102 return result
103 },
104
105 /** 获取热搜词 */
106 async getHotSearch() {
107 const { body, statusCode } = await httpFetch(
108 'http://hotword.kuwo.cn/hotword.s?prod=kwplayer_ar_9.3.0.1&corp=kuwo&newver=2&vipver=9.3.0.1&source=kwplayer_ar_9.3.0.1_40.apk&p2p=1¬race=0&uid=0&plat=kwplayer_ar&rformat=json&encoding=utf8&tabid=1',
109 {
110 headers: {
111 'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 9;)',
112 },
113 },
114 ).promise
115 if (statusCode != 200 || body.status !== 'ok') throw new Error('获取热搜词失败')
116 return { source: 'kw', list: (body.tagvalue || []).map((item) => item.key) }
117 },
118
119 /** 将秒数转成 LRC 时间标签 */
120 formatLrcTime(time) {
121 const t = parseFloat(time)
122 if (Number.isNaN(t) || t < 0) return '00:00.00'
123 const m = Math.floor(t / 60)
124 const s = t - m * 60
125 return `${m < 10 ? '0' + m : m}:${s < 10 ? '0' + s.toFixed(2) : s.toFixed(2)}`
126 },
127
128 /** 获取歌词(新 H5 接口,返回 lrclist,无需解密) */
129 getLyric(songInfo) {
130 return httpFetch(`http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId=${songInfo.songmid}`, {
131 headers: {
132 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
133 },
134 }).promise.then(({ body }) => {
135 if (!body || !body.data || !body.data.lrclist || !body.data.lrclist.length) {
136 return Promise.reject(new Error('获取歌词失败'))
137 }
138 const lines = body.data.lrclist
139 .map((l) => `[${this.formatLrcTime(l.time)}]${l.lineLyric || ''}`)
140 .join('\n')
141 return { lyric: decodeName(lines), tlyric: '' }
142 })
143 },
144
145 /** 获取封面 */
146 getPic(songInfo) {
147 return httpFetch(`http://artistpicserver.kuwo.cn/pic.web?corp=kuwo&type=rid_pic&pictype=500&size=500&rid=${songInfo.songmid}`)
148 .promise.then(({ body }) => (/^http/.test(body) ? body : null))
149 },
150
151 // ============ 搜索建议(输入联想,迁移自 lx-music-mobile/src/utils/musicSdk/kw/tipSearch) ============
152 /** 进行中的建议请求,用于取消上一次未完成的请求 */
153 tipSearchRequestObj: null,
154
155 /** 取消进行中的建议请求 */
156 cancelTipSearch() {
157 if (this.tipSearchRequestObj && this.tipSearchRequestObj.cancelHttp) {
158 this.tipSearchRequestObj.cancelHttp()
159 }
160 this.tipSearchRequestObj = null
161 },
162
163 /**
164 * 搜索建议(下拉候选词)
165 * @param {string} keyword 已输入的关键词
166 * @returns {Promise<string[]>} 候选关键词数组(按服务器返回顺序)
167 */
168 tipSearch(keyword) {
169 this.cancelTipSearch()
170 this.tipSearchRequestObj = httpFetch(
171 `https://tips.kuwo.cn/t.s?corp=kuwo&newver=3&p2p=1¬race=0&c=mbox&w=${encodeURIComponent(keyword)}&encoding=utf8&rformat=json`,
172 {
173 headers: {
174 Referer: 'http://www.kuwo.cn/',
175 },
176 },
177 )
178 return this.tipSearchRequestObj.promise
179 .then(({ body, statusCode }) => {
180 if (statusCode != 200 || !body || !body.WORDITEMS || !Array.isArray(body.WORDITEMS)) return []
181 return body.WORDITEMS.map((item) => item && item.RELWORD).filter((w) => typeof w === 'string' && w)
182 })
183 .catch(() => [])
184 },
185}
186
187// ============ 源注册表 ============
188const sources = {
189 sources: [
190 { name: SOURCE_NAMES.kw, id: 'kw' },
191 { name: SOURCE_NAMES.kg, id: 'kg' },
192 { name: SOURCE_NAMES.tx, id: 'tx' },
193 { name: SOURCE_NAMES.wy, id: 'wy' },
194 { name: SOURCE_NAMES.mg, id: 'mg' },
195 ],
196 kw,
197 kg,
198 tx,
199 wy,
200 mg,
201}
202
203/** 搜索来源列表(有 search 的源 + all) */
204export const getSearchSourceList = () => {
205 const list = []
206 for (const source of sources.sources) {
207 const sm = sources[source.id]
208 if (sm && sm.search) list.push(source)
209 }
210 return list
211}
212
213/** 全源搜索(迁移自 musicSdk.index searchMusic) */
214export const searchMusic = async ({ name, singer, source: s, limit = 25 }) => {
215 const trimStr = (str) => (typeof str == 'string' ? str.trim() : str)
216 const musicName = trimStr(name)
217 const tasks = []
218 for (const source of sources.sources) {
219 if (!sources[source.id].search || source.id == s) continue
220 tasks.push(sources[source.id].search(`${musicName} ${singer || ''}`.trim(), 1, limit).catch((_) => null))
221 }
222 return (await Promise.all(tasks)).filter((r) => r)
223}
224
225/** 获取某源的 SDK 实例 */
226export const getSourceSdk = (id) => sources[id] || null
227
228/** 获取内置源的封面 */
229export const getSourcePic = (id, musicInfo) => {
230 const sdk = sources[id]
231 if (!sdk || !sdk.getPic) return Promise.reject(new Error('该源不支持获取封面'))
232 return sdk.getPic(musicInfo)
233}
234
235/** 获取内置源的歌词(自定义源未提供时回退用) */
236export const getSourceLyric = (id, musicInfo) => {
237 const sdk = sources[id]
238 if (!sdk || !sdk.getLyric) return Promise.reject(new Error('该源暂不支持内置歌词'))
239 return sdk.getLyric(musicInfo)
240}
241
242/** 获取源的搜索建议(下拉候选词);源不支持时 reject */
243export const getSourceTipSearch = (id, keyword) => {
244 const sdk = sources[id]
245 if (!sdk || typeof sdk.tipSearch !== 'function') return Promise.reject(new Error('该源暂不支持搜索建议'))
246 return sdk.tipSearch(keyword)
247}
248
249export default {
250 ...sources,
251 getSearchSourceList,
252 searchMusic,
253 getSourceSdk,
254 getSourcePic,
255 getSourceLyric,
256 getSourceTipSearch,
257}