仰望星辰工作室

starmusic-mobile

1/**
2 * 酷我音乐 (kw) 歌单导入
3 *
4 * 迁移自 lx-music-mobile/src/utils/musicSdk/kw/songList.js(精简:仅保留歌单详情相关)
5 * 支持:
6 * - https://www.kuwo.cn/playlist_detail/xxx
7 * - https://m.kuwo.cn/h5app/playlist/xxx
8 * - 收藏歌单(bodian):https://h5app.kuwo.cn/m/bodian/collection.html?playlistId=xxx&source=4|5
9 * - digest 形式 id(歌单广场列表项,如 digest-8__123)
10 */
11import { httpFetch } from '../request.js'
12import { decodeName, formatPlayTime } from '../../utils.js'
13
14const LIMIT_SONG = 1000
15
16const regExps = {
17 mInfo: /level:(\w+),bitrate:(\d+),format:(\w+),size:([\w.]+)/,
18 // https://www.kuwo.cn/playlist_detail/2886046289
19 // https://m.kuwo.cn/h5app/playlist/2736267853?t=qqfriend
20 listDetailLink: /^.+\/playlist(?:_detail)?\/(\d+)(?:\?.*|&.*$|#.*$|$)/,
21}
22
23/** 获取歌单列表 URL(digest8 常规接口) */
24const getListDetailUrl = (id, page) =>
25 `http://nplserver.kuwo.cn/pl.svc?op=getlistinfo&pid=${id}&pn=${page - 1}&rn=${LIMIT_SONG}&encode=utf8&keyset=pl2012&identity=kuwo&pcmp4=1&vipver=MUSIC_9.0.5.0_W1&newver=1`
26
27/** digest5 第一步:查 sourceid */
28const getListDetailDigest5Info = (id, tryNum = 0) => {
29 if (tryNum > 2) return Promise.reject(new Error('try max num'))
30 return httpFetch(`http://qukudata.kuwo.cn/q.k?op=query&cont=ninfo&node=${id}&pn=0&rn=1&fmt=json&src=mbox&level=2`)
31 .promise.then(({ statusCode, body }) => {
32 if (statusCode != 200 || !body.child) return getListDetailDigest5Info(id, tryNum + 1)
33 return body.child.length ? body.child[0].sourceid : null
34 })
35}
36
37/** digest5 第二步:按 sourceid 拉取列表 */
38const getListDetailDigest5Music = (id, page, tryNum = 0) => {
39 if (tryNum > 2) return Promise.reject(new Error('try max num'))
40 return httpFetch(`http://nplserver.kuwo.cn/pl.svc?op=getlistinfo&pid=${id}&pn=${page - 1}&rn=${LIMIT_SONG}&encode=utf-8&keyset=pl2012&identity=kuwo&pcmp4=1`)
41 .promise.then(({ body }) => {
42 if (body.result !== 'ok') return getListDetailDigest5Music(id, page, tryNum + 1)
43 return {
44 list: filterListDetail(body.musiclist),
45 page,
46 limit: body.rn,
47 total: body.total,
48 source: 'kw',
49 info: {
50 name: body.title,
51 img: body.pic,
52 desc: body.info,
53 author: body.uname,
54 play_count: body.playnum,
55 },
56 }
57 })
58}
59
60/** digest5:两步拉取 */
61const getListDetailDigest5 = async (id, page, retryNum) => {
62 const detailId = await getListDetailDigest5Info(id, retryNum)
63 return getListDetailDigest5Music(detailId, page, retryNum)
64}
65
66/** digest8:常规歌单 */
67const getListDetailDigest8 = (id, page, tryNum = 0) => {
68 if (tryNum > 2) return Promise.reject(new Error('try max num'))
69 return httpFetch(getListDetailUrl(id, page)).promise.then(({ body }) => {
70 if (body.result !== 'ok') return getListDetailDigest8(id, page, tryNum + 1)
71 return {
72 list: filterListDetail(body.musiclist),
73 page,
74 limit: body.rn,
75 total: body.total,
76 source: 'kw',
77 info: {
78 name: body.title,
79 img: body.pic,
80 desc: body.info,
81 author: body.uname,
82 play_count: body.playnum,
83 },
84 }
85 })
86}
87
88// ============ bodian(收藏歌单) ============
89
90/** 生成 reqId(16 位 hex) */
91const getReqId = () => {
92 const t = () => (65536 * (1 + Math.random()) | 0).toString(16).substring(1)
93 return t() + t() + t() + t() + t() + t() + t() + t()
94}
95
96/** bodian 歌单信息 */
97const getListDetailMusicListByBDListInfo = async (id, source) => {
98 const { body: infoData } = await httpFetch(`https://bd-api.kuwo.cn/api/service/playlist/info/${id}?reqId=${getReqId()}&source=${source}`, {
99 headers: {
100 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
101 plat: 'h5',
102 },
103 }).promise.catch(() => ({ code: 0 }))
104 if (infoData.code != 200) return null
105 return {
106 name: infoData.data.name,
107 img: infoData.data.pic,
108 desc: infoData.data.description,
109 author: infoData.data.creatorName,
110 play_count: infoData.data.playNum,
111 }
112}
113
114/** bodian 用户收藏歌单信息 */
115const getListDetailMusicListByBDUserPub = async (id) => {
116 const { body: infoData } = await httpFetch(`https://bd-api.kuwo.cn/api/ucenter/users/pub/${id}?reqId=${getReqId()}`, {
117 headers: {
118 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
119 plat: 'h5',
120 },
121 }).promise.catch(() => ({ code: 0 }))
122 if (infoData.code != 200) return null
123 return {
124 name: infoData.data.userInfo.nickname + '喜欢的音乐',
125 img: infoData.data.userInfo.headImg,
126 desc: '',
127 author: infoData.data.userInfo.nickname,
128 play_count: '',
129 }
130}
131
132/** bodian 歌单歌曲列表 */
133const getListDetailMusicListByBDList = async (id, source, page, tryNum = 0) => {
134 const { body: listData } = await httpFetch(`https://bd-api.kuwo.cn/api/service/playlist/${id}/musicList?reqId=${getReqId()}&source=${source}&pn=${page}&rn=${LIMIT_SONG}`, {
135 headers: {
136 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
137 plat: 'h5',
138 },
139 }).promise.catch(() => {
140 if (tryNum > 2) return Promise.reject(new Error('try max num'))
141 return getListDetailMusicListByBDList(id, source, page, tryNum + 1)
142 })
143 if (listData.code !== 200) return Promise.reject(new Error('failed'))
144 return {
145 list: filterBDListDetail(listData.data.list),
146 page,
147 limit: listData.data.pageSize,
148 total: listData.data.total,
149 source: 'kw',
150 }
151}
152
153/** bodian 歌单详情(source=4 歌单 / source=5 用户收藏) */
154const getListDetailMusicListByBD = async (id, page) => {
155 const uid = /uid=(\d+)/.exec(id)?.[1]
156 const listId = /playlistId=(\d+)/.exec(id)?.[1]
157 const source = /source=(\d+)/.exec(id)?.[1]
158 if (!listId) return Promise.reject(new Error('failed'))
159
160 const task = [getListDetailMusicListByBDList(listId, source, page)]
161 switch (source) {
162 case '4':
163 task.push(getListDetailMusicListByBDListInfo(listId, source))
164 break
165 case '5':
166 task.push(getListDetailMusicListByBDUserPub(uid ?? listId))
167 break
168 }
169 const [listData, info] = await Promise.all(task)
170 listData.info = info ?? { name: '', img: '', desc: '', author: '', play_count: '' }
171 return listData
172}
173
174/** bodian 歌曲格式化 */
175const filterBDListDetail = (rawList) =>
176 rawList.map((item) => {
177 const types = []
178 const _types = {}
179 for (const info of item.audios || []) {
180 info.size = info.size ? info.size.toLocaleUpperCase() : null
181 switch (info.bitrate) {
182 case '4000':
183 types.push({ type: 'flac24bit', size: info.size })
184 _types.flac24bit = { size: info.size }
185 break
186 case '2000':
187 types.push({ type: 'flac', size: info.size })
188 _types.flac = { size: info.size }
189 break
190 case '320':
191 types.push({ type: '320k', size: info.size })
192 _types['320k'] = { size: info.size }
193 break
194 case '128':
195 types.push({ type: '128k', size: info.size })
196 _types['128k'] = { size: info.size }
197 break
198 }
199 }
200 types.reverse()
201 return {
202 singer: (item.artists || []).map((s) => s.name).join('、'),
203 name: item.name,
204 albumName: item.album,
205 albumId: item.albumId,
206 songmid: item.id,
207 source: 'kw',
208 interval: formatPlayTime(item.duration || 0),
209 img: item.albumPic,
210 releaseDate: item.releaseDate,
211 lrc: null,
212 otherSource: null,
213 types,
214 _types,
215 typeUrl: {},
216 }
217 })
218
219/** 常规歌曲格式化(digest8/digest5) */
220const filterListDetail = (rawData) =>
221 rawData.map((item) => {
222 const types = []
223 const _types = {}
224 const infoArr = String(item.N_MINFO || '').split(';')
225 for (const info of infoArr) {
226 const match = info.match(regExps.mInfo)
227 if (match) {
228 switch (match[2]) {
229 case '4000':
230 types.push({ type: 'flac24bit', size: match[4] })
231 _types.flac24bit = { size: match[4].toLocaleUpperCase() }
232 break
233 case '2000':
234 types.push({ type: 'flac', size: match[4] })
235 _types.flac = { size: match[4].toLocaleUpperCase() }
236 break
237 case '320':
238 types.push({ type: '320k', size: match[4] })
239 _types['320k'] = { size: match[4].toLocaleUpperCase() }
240 break
241 case '128':
242 types.push({ type: '128k', size: match[4] })
243 _types['128k'] = { size: match[4].toLocaleUpperCase() }
244 break
245 }
246 }
247 }
248 types.reverse()
249 return {
250 singer: String(item.artist || '').replace(/&/g, '、'),
251 name: decodeName(item.name),
252 albumName: decodeName(item.album || ''),
253 albumId: item.albumid,
254 songmid: item.id,
255 source: 'kw',
256 interval: formatPlayTime(parseInt(item.duration) || 0),
257 img: null,
258 lrc: null,
259 otherSource: null,
260 types,
261 _types,
262 typeUrl: {},
263 }
264 })
265
266export default {
267 /** 获取歌单内歌曲列表 */
268 getListDetail(id, page = 1, retryNum = 0) {
269 // 收藏歌单(bodian)
270 if (/\/bodian\//.test(id)) return getListDetailMusicListByBD(id, page)
271 // 链接 → 提取 id
272 if (/[?&:/]/.test(id)) id = id.replace(regExps.listDetailLink, '$1')
273 else if (/^digest-/.test(id)) {
274 // digest 形式:digest-<digest>__<id>
275 const [digest, _id] = id.split('__')
276 id = _id
277 switch (digest.replace('digest-', '')) {
278 case '13': // 专辑
279 return Promise.reject(new Error('暂不支持专辑链接'))
280 case '5':
281 default:
282 return getListDetailDigest5(id, page, retryNum)
283 }
284 }
285 return getListDetailDigest8(id, page, retryNum)
286 },
287}