仰望星辰工作室

starmusic-mobile

starmusic-mobile/ common/music-sdk/kg.js 6.7 KB · 210 行 原始文件
1/**
2 * 酷狗音乐 (kg) 源 SDK(迁移自 lx-music-mobile/src/utils/musicSdk/kg)
3 */
4import { httpFetch } from './request.js'
5import { decodeName, formatPlayTime, sizeFormate } from '../utils.js'
6import { b64ToBytes, bytesToUtf8 } from '../crypto.js'
7
8const formatSingerName = (singers) => {
9 if (Array.isArray(singers)) {
10 return decodeName(singers.map((item) => item.name).join('、'))
11 }
12 return decodeName(String(singers || ''))
13}
14
15const kg = {
16 name: '酷狗音乐',
17 limit: 30,
18 total: 0,
19 page: 0,
20 allPage: 1,
21
22 /** 搜索请求 */
23 musicSearch(str, page, limit) {
24 return httpFetch(
25 `https://songsearch.kugou.com/song_search_v2?keyword=${encodeURIComponent(str)}&page=${page}&pagesize=${limit}&userid=0&clientver=&platform=WebFilter&filter=2&iscorrection=1&privilege_filter=0&area_code=1`,
26 ).promise.then(({ body }) => body)
27 },
28
29 /** 过滤单条数据 */
30 filterData(rawData) {
31 const types = []
32 const _types = {}
33 if (rawData.FileSize !== 0) {
34 const size = sizeFormate(rawData.FileSize)
35 types.push({ type: '128k', size, hash: rawData.FileHash })
36 _types['128k'] = { size, hash: rawData.FileHash }
37 }
38 if (rawData.HQFileSize !== 0) {
39 const size = sizeFormate(rawData.HQFileSize)
40 types.push({ type: '320k', size, hash: rawData.HQFileHash })
41 _types['320k'] = { size, hash: rawData.HQFileHash }
42 }
43 if (rawData.SQFileSize !== 0) {
44 const size = sizeFormate(rawData.SQFileSize)
45 types.push({ type: 'flac', size, hash: rawData.SQFileHash })
46 _types.flac = { size, hash: rawData.SQFileHash }
47 }
48 if (rawData.ResFileSize !== 0) {
49 const size = sizeFormate(rawData.ResFileSize)
50 types.push({ type: 'flac24bit', size, hash: rawData.ResFileHash })
51 _types.flac24bit = { size, hash: rawData.ResFileHash }
52 }
53 return {
54 singer: formatSingerName(rawData.Singers),
55 name: decodeName(rawData.SongName),
56 albumName: decodeName(rawData.AlbumName),
57 albumId: rawData.AlbumID,
58 songmid: rawData.Audioid,
59 source: 'kg',
60 interval: formatPlayTime(rawData.Duration),
61 _interval: rawData.Duration,
62 img: null,
63 lrc: null,
64 otherSource: null,
65 hash: rawData.FileHash,
66 audioId: rawData.Audioid,
67 types,
68 _types,
69 typeUrl: {},
70 }
71 },
72
73 /** 处理搜索结果 */
74 handleResult(rawData) {
75 const ids = new Set()
76 const list = []
77 rawData.forEach((item) => {
78 const key = item.Audioid + item.FileHash
79 if (ids.has(key)) return
80 ids.add(key)
81 list.push(this.filterData(item))
82 for (const childItem of item.Grp || []) {
83 const childKey = childItem.Audioid + childItem.FileHash
84 if (ids.has(childKey)) continue
85 ids.add(childKey)
86 list.push(this.filterData(childItem))
87 }
88 })
89 return list
90 },
91
92 /** 搜索 */
93 search(str, page = 1, limit, retryNum = 0) {
94 if (++retryNum > 3) return Promise.reject(new Error('try max num'))
95 if (limit == null) limit = this.limit
96 return this.musicSearch(str, page, limit).then((result) => {
97 if (!result || result.error_code !== 0) return this.search(str, page, limit, retryNum)
98 const list = this.handleResult(result.data.lists)
99 if (list == null) return this.search(str, page, limit, retryNum)
100
101 this.total = result.data.total
102 this.page = page
103 this.allPage = Math.ceil(this.total / limit)
104
105 return Promise.resolve({
106 list,
107 allPage: this.allPage,
108 limit,
109 total: this.total,
110 source: 'kg',
111 })
112 })
113 },
114
115 /** 获取封面 */
116 getPic(songInfo) {
117 return httpFetch('http://media.store.kugou.com/v1/get_res_privilege', {
118 method: 'POST',
119 headers: {
120 'KG-RC': 1,
121 'KG-THash': 'expand_search_manager.cpp:852736169:451',
122 'User-Agent': 'KuGou2012-9020-ExpandSearchManager',
123 },
124 body: {
125 appid: 1001,
126 area_code: '1',
127 behavior: 'play',
128 clientver: '9020',
129 need_hash_offset: 1,
130 relate: 1,
131 resource: [
132 {
133 album_audio_id: (songInfo.songmid && songInfo.songmid.length == 32)
134 ? String(songInfo.audioId || '').split('_')[0]
135 : songInfo.songmid,
136 album_id: songInfo.albumId,
137 hash: songInfo.hash,
138 id: 0,
139 name: `${songInfo.singer} - ${songInfo.name}.mp3`,
140 type: 'audio',
141 },
142 ],
143 token: '',
144 userid: 2626431536,
145 vip: 1,
146 },
147 }).promise.then(({ body }) => {
148 if (body.error_code !== 0) return Promise.reject(new Error('图片获取失败'))
149 const info = body.data[0].info
150 const img = info.imgsize ? info.image.replace('{size}', info.imgsize[0]) : info.image
151 if (!img) return Promise.reject(new Error('Pic get failed'))
152 return img
153 })
154 },
155
156 /** 歌词请求头 */
157 getLyricHeaders() {
158 return {
159 'KG-RC': 1,
160 'KG-THash': 'expand_search_manager.cpp:852736169:451',
161 'User-Agent': 'KuGou2012-9020-ExpandSearchManager',
162 }
163 },
164
165 /** mm:ss 转秒 */
166 getIntv(interval) {
167 if (!interval) return 0
168 const intvArr = interval.split(':')
169 let intv = 0
170 let unit = 1
171 while (intvArr.length) {
172 intv += parseInt(intvArr.pop()) * unit
173 unit *= 60
174 }
175 return intv
176 },
177
178 /** 搜索歌词(返回候选 id/accesskey) */
179 searchLyric(name, hash, time) {
180 return httpFetch(`http://lyrics.kugou.com/search?ver=1&man=yes&client=pc&keyword=${encodeURIComponent(name)}&hash=${hash}&timelength=${time}&lrctxt=1`, {
181 headers: this.getLyricHeaders(),
182 }).promise.then(({ body }) => {
183 if (!body || !body.candidates || !body.candidates.length) return Promise.reject(new Error('获取歌词失败'))
184 const info = body.candidates[0]
185 return { id: info.id, accessKey: info.accesskey }
186 })
187 },
188
189 /** 获取歌词(download 接口强制 lrc 格式,无需 KRC 解密) */
190 getLyric(songInfo) {
191 const time = songInfo._interval || this.getIntv(songInfo.interval)
192 return this.searchLyric(songInfo.name, songInfo.hash, time).then(({ id, accessKey }) => {
193 return httpFetch(`http://lyrics.kugou.com/download?ver=1&client=pc&id=${id}&accesskey=${accessKey}&fmt=lrc&charset=utf8`, {
194 headers: this.getLyricHeaders(),
195 }).promise.then(({ body }) => {
196 if (!body || !body.content) return Promise.reject(new Error('获取歌词失败'))
197 let lyric = ''
198 try {
199 lyric = decodeName(bytesToUtf8(b64ToBytes(body.content)))
200 } catch (e) {
201 return Promise.reject(new Error('获取歌词失败'))
202 }
203 if (!lyric) return Promise.reject(new Error('获取歌词失败'))
204 return { lyric, tlyric: '' }
205 })
206 })
207 },
208}
209
210export default kg