仰望星辰工作室

starmusic-pc

1/**
2 * 酷狗音乐 (kg) 歌单导入
3 *
4 * 迁移自 lx-music-mobile/src/utils/musicSdk/kg/songList.js(精简)
5 *
6 * 设计说明:原项目部分路径依赖 infSign.min.js(需要浏览器环境),
7 * 本实现刻意避开这些路径,全部使用无需 infSign 的接口:
8 * - 酷狗码(纯数字 id):t.kugou.com/command 接口(固定参数)
9 * - special/single/xxx.html:直接抓 HTML 页正则提取 global.data
10 * - global_collection_id=xxx:mobiles.kugou.com info_v2 + song_v2(MD5 签名)
11 * - chain=xxx 短链:m.kugou.com/schain/transfer
12 * - 酷狗分享短链 / 用户歌单:跟随跳转后按上述规则解析
13 * - hash 批量换歌曲详情:gateway.kugou.com/v2/album_audio/audio(固定 key)
14 */
15import { httpFetch } from '../request.js'
16import { decodeName, formatPlayTime, sizeFormate, formatPlayCount } from '../../utils.js'
17import { md5 } from '../../crypto.js'
18
19const LIST_DETAIL_LIMIT = 10000
20
21const regExps = {
22 // https://www.kugou.com/yy/special/single/1067062.html
23 listDetailLink: /^.+\/(\d+)\.html(?:\?.*|&.*$|#.*$|$)/,
24 // HTML 页内歌单数据
25 listData: /global\.data = (\[.+\]);/,
26 // HTML 页内歌单信息
27 listInfo: /global = {[\s\S]+?name: "(.+)"[\s\S]+?pic: "(.+)"[\s\S]+?};/,
28}
29
30/**
31 * 签名(kg 接口用)
32 * 平台 web 用 NVPh5oo...,android 用 OIlwieks...
33 */
34const signatureParams = (params, platform = 'android', body = '') => {
35 const keyparam = platform === 'web' ? 'NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt' : 'OIlwieks28dk2k092lksi2UIkp'
36 const param_list = params.split('&').sort()
37 return md5(`${keyparam}${param_list.join('')}${body}${keyparam}`)
38}
39
40/**
41 * 带重试的请求封装:校验 statusCode 与 error_code/errcode,返回 data/info
42 */
43const createHttp = async (url, options, retryNum = 0) => {
44 if (retryNum > 2) throw new Error('try max num')
45 let result
46 try {
47 result = await httpFetch(url, options).promise
48 } catch (err) {
49 console.log('[kg createHttp]', err.message)
50 return createHttp(url, options, retryNum + 1)
51 }
52 const errCode = result.body.error_code ?? result.body.errcode ?? result.body.err_code
53 if (result.statusCode !== 200 || (errCode !== undefined && errCode !== 0 && errCode !== null)) {
54 return createHttp(url, options, retryNum + 1)
55 }
56 if (result.body.data) return result.body.data
57 if (Array.isArray(result.body.info)) return result.body
58 return result.body.info
59}
60
61// ============ hash 批量换歌曲详情 ============
62
63/** 按 100 个一组创建请求任务 */
64const createTask = (hashs) => {
65 const data = {
66 area_code: '1',
67 show_privilege: 1,
68 show_album_info: '1',
69 is_publish: '',
70 appid: 1005,
71 clientver: 11451,
72 mid: '1',
73 dfid: '-',
74 clienttime: Date.now(),
75 key: 'OIlwieks28dk2k092lksi2UIkp',
76 fields: 'album_info,author_name,audio_info,ori_audio_name,base,songname',
77 }
78 let list = hashs
79 const tasks = []
80 while (list.length) {
81 tasks.push(Object.assign({ data: list.slice(0, 100) }, data))
82 if (list.length < 100) break
83 list = list.slice(100)
84 }
85 const url = 'http://gateway.kugou.com/v2/album_audio/audio'
86 return tasks.map((task) =>
87 createHttp(url, {
88 method: 'POST',
89 body: task,
90 headers: {
91 'KG-THash': '13a3164',
92 'KG-RC': '1',
93 'KG-Fake': '0',
94 'KG-RF': '00869891',
95 'User-Agent': 'Android712-AndroidPhone-11451-376-0-FeeCacheUpdate-wifi',
96 'x-router': 'kmr.service.kugou.com',
97 },
98 }).then((data) => data.map((s) => s[0])),
99 )
100}
101
102/** hash 去重 */
103const deDuplication = (datas) => {
104 const ids = new Set()
105 return datas.filter(({ hash }) => {
106 if (ids.has(hash)) return false
107 ids.add(hash)
108 return true
109 })
110}
111
112/** 按 hash 列表批量获取歌曲完整信息 */
113const getMusicInfos = async (list) => {
114 const datas = await Promise.all(createTask(deDuplication(list).map((item) => ({ hash: item.hash })))).then(([...all]) => all.flat())
115 return filterData2(datas)
116}
117
118/** 歌曲信息格式化(audio_info 结构) */
119const filterData2 = (rawList) => {
120 const ids = new Set()
121 const list = []
122 rawList.forEach((item) => {
123 if (!item) return
124 if (ids.has(item.audio_info.audio_id)) return
125 ids.add(item.audio_info.audio_id)
126 const types = []
127 const _types = {}
128 if (item.audio_info.filesize !== '0') {
129 const size = sizeFormate(parseInt(item.audio_info.filesize))
130 types.push({ type: '128k', size, hash: item.audio_info.hash })
131 _types['128k'] = { size, hash: item.audio_info.hash }
132 }
133 if (item.audio_info.filesize_320 !== '0') {
134 const size = sizeFormate(parseInt(item.audio_info.filesize_320))
135 types.push({ type: '320k', size, hash: item.audio_info.hash_320 })
136 _types['320k'] = { size, hash: item.audio_info.hash_320 }
137 }
138 if (item.audio_info.filesize_flac !== '0') {
139 const size = sizeFormate(parseInt(item.audio_info.filesize_flac))
140 types.push({ type: 'flac', size, hash: item.audio_info.hash_flac })
141 _types.flac = { size, hash: item.audio_info.hash_flac }
142 }
143 if (item.audio_info.filesize_high !== '0') {
144 const size = sizeFormate(parseInt(item.audio_info.filesize_high))
145 types.push({ type: 'flac24bit', size, hash: item.audio_info.hash_high })
146 _types.flac24bit = { size, hash: item.audio_info.hash_high }
147 }
148 list.push({
149 singer: decodeName(item.author_name),
150 name: decodeName(item.songname),
151 albumName: decodeName(item.album_info && item.album_info.album_name),
152 albumId: item.album_info && item.album_info.album_id,
153 songmid: item.audio_info.audio_id,
154 source: 'kg',
155 interval: formatPlayTime(parseInt(item.audio_info.timelength) / 1000),
156 img: null,
157 lrc: null,
158 hash: item.audio_info.hash,
159 otherSource: null,
160 types,
161 _types,
162 typeUrl: {},
163 })
164 })
165 return list
166}
167
168// ============ 歌单详情各路径 ============
169
170/** special/single/xxx.html:抓 HTML 页解析 */
171const getListDetailBySpecialId = async (id, page, tryNum = 0) => {
172 if (tryNum > 2) throw new Error('try max num')
173 const { body } = await httpFetch(`http://www2.kugou.kugou.com/yueku/v9/special/single/${id}-5-9999.html`).promise
174 const listData = String(body || '').match(regExps.listData)
175 const listInfo = String(body || '').match(regExps.listInfo)
176 if (!listData) return getListDetailBySpecialId(id, page, tryNum + 1)
177 const list = await getMusicInfos(JSON.parse(listData[1]))
178 return {
179 list,
180 page: 1,
181 limit: LIST_DETAIL_LIMIT,
182 total: list.length,
183 source: 'kg',
184 info: {
185 name: listInfo ? listInfo[1] : '',
186 img: listInfo ? listInfo[2] : '',
187 desc: '',
188 },
189 }
190}
191
192/** 酷狗码(纯数字 id):t.kugou.com/command 接口 */
193const getUserListDetailByCode = async (id) => {
194 const songInfo = await createHttp('http://t.kugou.com/command/', {
195 method: 'POST',
196 headers: {
197 'KG-RC': 1,
198 'KG-THash': 'network_super_call.cpp:3676261689:379',
199 'User-Agent': '',
200 },
201 body: {
202 appid: 1001,
203 clientver: 9020,
204 mid: '21511157a05844bd085308bc76ef3343',
205 clienttime: 640612895,
206 key: '36164c4015e704673c588ee202b9ecb8',
207 data: id,
208 },
209 })
210 const info = songInfo.info
211 // type 1单曲,2歌单,3电台,4酷狗码,5别人的播放队列
212 let songList
213 switch (info.type) {
214 case 2:
215 if (!info.global_collection_id) return getListDetailBySpecialId(info.id)
216 break
217 default:
218 break
219 }
220 if (info.global_collection_id) return getUserListDetail2(info.global_collection_id)
221 if (info.userid != null) {
222 songList = await createHttp('http://www2.kugou.kugou.com/apps/kucodeAndShare/app/', {
223 method: 'POST',
224 headers: {
225 'KG-RC': 1,
226 'KG-THash': 'network_super_call.cpp:3676261689:379',
227 'User-Agent': '',
228 },
229 body: {
230 appid: 1001,
231 clientver: 9020,
232 mid: '21511157a05844bd085308bc76ef3343',
233 clienttime: 640612895,
234 key: '36164c4015e704673c588ee202b9ecb8',
235 data: { id: info.id, type: 3, userid: info.userid, collect_type: 0, page: 1, pagesize: info.count },
236 },
237 })
238 }
239 const list = await getMusicInfos(songList || songInfo.list)
240 return {
241 list,
242 page: 1,
243 limit: info.count,
244 total: list.length,
245 source: 'kg',
246 info: {
247 name: info.name,
248 img: (info.img_size && info.img_size.replace('{size}', 240)) || info.img,
249 author: info.username,
250 play_count: formatPlayCount(info.count),
251 },
252 }
253}
254
255/** global_collection_id:info_v2 + song_v2(MD5 签名) */
256const createGetListDetail2Task = (id, total) => {
257 const tasks = []
258 let page = 0
259 while (total) {
260 const limit = total > 300 ? 300 : total
261 total -= limit
262 page += 1
263 const params = `appid=1058&global_specialid=${id}&specialid=0&plat=0&version=8000&page=${page}&pagesize=${limit}&srcappid=2919&clientver=20000&clienttime=1586163263991&mid=1586163263991&uuid=1586163263991&dfid=-`
264 tasks.push(
265 createHttp(`https://mobiles.kugou.com/api/v5/special/song_v2?${params}&signature=${signatureParams(params, 'web')}`, {
266 headers: {
267 mid: '1586163263991',
268 Referer: 'https://m3ws.kugou.com/share/index.php',
269 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
270 dfid: '-',
271 clienttime: '1586163263991',
272 },
273 }).then((data) => data.info),
274 )
275 }
276 return Promise.all(tasks).then(([...datas]) => datas.flat())
277}
278
279const getUserListDetail2 = async (global_collection_id) => {
280 const id = global_collection_id
281 if (id.length > 1000) throw new Error('get list error')
282 const params = `appid=1058&specialid=0&global_specialid=${id}&format=jsonp&srcappid=2919&clientver=20000&clienttime=1586163242519&mid=1586163242519&uuid=1586163242519&dfid=-`
283 const info = await createHttp(`https://mobiles.kugou.com/api/v5/special/info_v2?${params}&signature=${signatureParams(params, 'web')}`, {
284 headers: {
285 mid: '1586163242519',
286 Referer: 'https://m3ws.kugou.com/share/index.php',
287 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
288 dfid: '-',
289 clienttime: '1586163242519',
290 },
291 })
292 const songInfo = await createGetListDetail2Task(id, info.songcount)
293 const list = await getMusicInfos(songInfo)
294 return {
295 list,
296 page: 1,
297 limit: LIST_DETAIL_LIMIT,
298 total: list.length,
299 source: 'kg',
300 info: {
301 name: info.specialname,
302 img: info.imgurl && info.imgurl.replace('{size}', 240),
303 desc: info.intro,
304 author: info.nickname,
305 play_count: formatPlayCount(info.playcount),
306 },
307 }
308}
309
310/** chain 短链:schain/transfer */
311const getUserListDetail3 = async (chain, page) => {
312 const songInfo = await createHttp(
313 `http://m.kugou.com/schain/transfer?pagesize=${LIST_DETAIL_LIMIT}&chain=${chain}&su=1&page=${page}&n=0.7928855356604456`,
314 {
315 headers: {
316 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1',
317 },
318 },
319 )
320 if (!songInfo.list) {
321 if (songInfo.global_collection_id) return getUserListDetail2(songInfo.global_collection_id)
322 // 原项目走 infSign 路径,这里改为 PC 端分享页解析
323 return getUserListDetailByPcChain(chain)
324 }
325 const list = await getMusicInfos(songInfo.list)
326 return {
327 list,
328 page: 1,
329 limit: LIST_DETAIL_LIMIT,
330 total: list.length,
331 source: 'kg',
332 info: {
333 name: songInfo.info && songInfo.info.name,
334 img: songInfo.info && songInfo.info.img,
335 author: songInfo.info && songInfo.info.username,
336 },
337 }
338}
339
340/** PC 分享页解析(share/xxx.html 内 dataFromSmarty) */
341const getUserListDetailByPcChain = async (chain) => {
342 const { body } = await httpFetch(`http://www.kugou.com/share/${chain}.html`, {
343 headers: {
344 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
345 },
346 }).promise
347 const result = String(body || '').match(/var\sdataFromSmarty\s=\s(\[.+?\])/)
348 if (!result) throw new Error('share page parse failed')
349 const list = await getMusicInfos(JSON.parse(result[1]))
350 return {
351 list,
352 page: 1,
353 limit: LIST_DETAIL_LIMIT,
354 total: list.length,
355 source: 'kg',
356 info: {},
357 }
358}
359
360/**
361 * 链接解析主流程(迁移自 getUserListDetail,去掉 infSign 路径)
362 * 支持:
363 * - 链接内含 global_collection_id=xxx
364 * - 链接内含 chain=xxx
365 * - 链接内含 gcid_xxx(需 batch_decode 转 global_collection_id)
366 * - special/single/xxx.html 歌单页
367 * - t.kugou.com 短链 / 酷狗码
368 * - 其他分享链接:跟随跳转后递归解析
369 */
370const getUserListDetail = async (link, page, retryNum = 0) => {
371 if (retryNum > 3) return Promise.reject(new Error('link try max num'))
372 if (link.includes('#')) link = link.replace(/#.*$/, '')
373 if (link.includes('global_collection_id')) return getUserListDetail2(link.replace(/^.*?global_collection_id=(\w+)(?:&.*$|#.*$|$)/, '$1'))
374 if (link.includes('gcid_')) {
375 const gcid = link.match(/gcid_\w+/)?.[0]
376 if (gcid) {
377 const global_collection_id = await decodeGcid(gcid)
378 if (global_collection_id) return getUserListDetail2(global_collection_id)
379 }
380 }
381 if (link.includes('chain=')) return getUserListDetail3(link.replace(/^.*?chain=(\w+)(?:&.*$|#.*$|$)/, '$1'), page)
382 if (link.includes('.html')) {
383 if (!link.includes('song.html')) {
384 const m = link.match(/.+\/(\w+)\.html(?:\?.*|&.*$|#.*$|$)/)
385 if (m) return getUserListDetail3(m[1], page)
386 }
387 }
388
389 // 其余链接:跟随跳转
390 const { url: location, statusCode, body } = await httpFetch(link, {
391 headers: {
392 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1',
393 Referer: link,
394 },
395 }).promise
396 if (statusCode > 400) return getUserListDetail(link, page, retryNum + 1)
397 if (location.split('?')[0] != link.split('?')[0]) {
398 if (location.includes('global_collection_id')) return getUserListDetail2(location.replace(/^.*?global_collection_id=(\w+)(?:&.*$|#.*$|$)/, '$1'))
399 if (location.includes('chain=')) return getUserListDetail3(location.replace(/^.*?chain=(\w+)(?:&.*$|#.*$|$)/, '$1'), page)
400 if (location.includes('gcid_')) {
401 const gcid = location.match(/gcid_\w+/)?.[0]
402 if (gcid) {
403 const global_collection_id = await decodeGcid(gcid)
404 if (global_collection_id) return getUserListDetail2(global_collection_id)
405 }
406 }
407 return getUserListDetail(location, page, retryNum + 1)
408 }
409 // 响应体里含 global_collection_id(HTML 页)
410 if (typeof body == 'string') {
411 const m = body.match(/^[\s\S]+?"global_collection_id":"(\w+)"[\s\S]+?$/)
412 if (m) return getUserListDetail2(m[1])
413 }
414 return getUserListDetailByPcChain(link)
415}
416
417/** gcid → global_collection_id(batch_decode,MD5 签名) */
418const decodeGcid = async (gcid) => {
419 const params = 'dfid=-&appid=1005&mid=0&clientver=20109&clienttime=640612895&uuid=-'
420 const body = {
421 ret_info: 1,
422 data: [{ id: gcid, id_type: 2 }],
423 }
424 const result = await createHttp(
425 `https://t.kugou.com/v1/songlist/batch_decode?${params}&signature=${signatureParams(params, 'android', JSON.stringify(body))}`,
426 {
427 method: 'POST',
428 headers: {
429 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; HUAWEI HMA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Mobile Safari/537.36',
430 Referer: 'https://m.kugou.com/',
431 },
432 body,
433 },
434 )
435 return result.list[0].global_collection_id
436}
437
438export default {
439 /** 获取歌单内歌曲列表 */
440 async getListDetail(rawId, page = 1) {
441 let id = String(rawId)
442 if (id.includes('special/single/')) {
443 id = id.replace(regExps.listDetailLink, '$1')
444 return getListDetailBySpecialId(id, page)
445 }
446 if (/https?:/.test(id)) {
447 return getUserListDetail(id.replace(/^.*?http/, 'http'), page)
448 }
449 if (/^\d+$/.test(id)) {
450 return getUserListDetailByCode(id)
451 }
452 if (id.startsWith('id_')) {
453 id = id.replace('id_', '')
454 }
455 return getListDetailBySpecialId(id, page)
456 },
457}