starmusic-mobile
1/**
2 * QQ音乐 (tx) 源 SDK(迁移自 lx-music-mobile/src/utils/musicSdk/tx)
3 */
4import { httpFetch } from './request.js'
5import { decodeName, formatPlayTime, sizeFormate } from '../utils.js'
6import { sha1, bytesToB64, b64ToBytes, bytesToUtf8 } from '../crypto.js'
7
8/** 生成 zzc 签名 */
9const zzcSign = (text) => {
10 const PART_1_INDEXES = [23, 14, 6, 36, 16, 40, 7, 19]
11 const PART_2_INDEXES = [16, 1, 32, 12, 19, 27, 8, 5]
12 const SCRAMBLE_VALUES = [89, 39, 179, 150, 218, 82, 58, 252, 177, 52, 186, 123, 120, 64, 242, 133, 143, 161, 121, 179]
13 const hash = sha1(text)
14 const part1 = PART_1_INDEXES.map((idx) => hash[idx]).join('')
15 const part2 = PART_2_INDEXES.map((idx) => hash[idx]).join('')
16 // base64 编码 part3(模拟 Buffer.from(part3).toString('base64') 去掉特殊字符)
17 const part3 = SCRAMBLE_VALUES.map((value, i) => value ^ parseInt(hash.slice(i * 2, i * 2 + 2), 16))
18 const b64Str = bytesToB64(part3).replace(/[\\/+=]/g, '')
19 return `zzc${part1}${b64Str}${part2}`.toLowerCase()
20}
21
22const formatSingerName = (singers) => {
23 if (Array.isArray(singers)) {
24 return decodeName(singers.map((item) => item.name).join('、'))
25 }
26 return decodeName(String(singers || ''))
27}
28
29const tx = {
30 name: 'QQ音乐',
31 limit: 50,
32 total: 0,
33 page: 0,
34 allPage: 1,
35 successCode: 0,
36
37 /** 签名请求 */
38 signRequest(data) {
39 const sign = zzcSign(JSON.stringify(data))
40 return httpFetch(`https://u.y.qq.com/cgi-bin/musics.fcg?sign=${sign}`, {
41 method: 'post',
42 headers: {
43 'User-Agent': 'QQMusic 14090508(android 12)',
44 },
45 body: data,
46 }).promise
47 },
48
49 /** 搜索请求 */
50 musicSearch(str, page, limit, retryNum = 0) {
51 if (retryNum > 5) return Promise.reject(new Error('搜索失败'))
52 const searchRequest = this.signRequest({
53 comm: {
54 ct: '11',
55 cv: '14090508',
56 v: '14090508',
57 tmeAppID: 'qqmusic',
58 phonetype: 'EBG-AN10',
59 deviceScore: '553.47',
60 devicelevel: '50',
61 newdevicelevel: '20',
62 rom: 'HuaWei/EMOTION/EmotionUI_14.2.0',
63 os_ver: '12',
64 OpenUDID: '0',
65 OpenUDID2: '0',
66 QIMEI36: '0',
67 udid: '0',
68 chid: '0',
69 aid: '0',
70 oaid: '0',
71 taid: '0',
72 tid: '0',
73 wid: '0',
74 uid: '0',
75 sid: '0',
76 modeSwitch: '6',
77 teenMode: '0',
78 ui_mode: '2',
79 nettype: '1020',
80 v4ip: '',
81 },
82 req: {
83 module: 'music.search.SearchCgiService',
84 method: 'DoSearchForQQMusicMobile',
85 param: {
86 search_type: 0,
87 searchid: Math.random().toString().slice(2),
88 query: str,
89 page_num: page,
90 num_per_page: limit,
91 highlight: 0,
92 nqc_flag: 0,
93 multi_zhida: 0,
94 cat: 2,
95 grp: 1,
96 sin: 0,
97 sem: 0,
98 },
99 },
100 })
101 return searchRequest.then(({ body }) => {
102 if (!body || !body.req || body.code != this.successCode || body.req.code != this.successCode) {
103 return this.musicSearch(str, page, limit, ++retryNum)
104 }
105 return body.req.data
106 })
107 },
108
109 /** 处理搜索结果 */
110 handleResult(rawList) {
111 if (!rawList || !Array.isArray(rawList)) return []
112 const list = []
113 rawList.forEach((item) => {
114 if (!item.file || !item.file.media_mid) return
115
116 const types = []
117 const _types = {}
118 const file = item.file
119 if (file.size_128mp3 != 0) {
120 const size = sizeFormate(file.size_128mp3)
121 types.push({ type: '128k', size })
122 _types['128k'] = { size }
123 }
124 if (file.size_320mp3 !== 0) {
125 const size = sizeFormate(file.size_320mp3)
126 types.push({ type: '320k', size })
127 _types['320k'] = { size }
128 }
129 if (file.size_flac !== 0) {
130 const size = sizeFormate(file.size_flac)
131 types.push({ type: 'flac', size })
132 _types.flac = { size }
133 }
134 if (file.size_hires !== 0) {
135 const size = sizeFormate(file.size_hires)
136 types.push({ type: 'flac24bit', size })
137 _types.flac24bit = { size }
138 }
139 let albumId = ''
140 let albumName = ''
141 if (item.album) {
142 albumName = item.album.name
143 albumId = item.album.mid
144 }
145 list.push({
146 singer: formatSingerName(item.singer),
147 name: item.title,
148 albumName,
149 albumId,
150 source: 'tx',
151 interval: formatPlayTime(item.interval),
152 songId: item.id,
153 albumMid: item.album && item.album.mid ? item.album.mid : '',
154 strMediaMid: item.file.media_mid,
155 songmid: item.mid,
156 img: (albumId === '' || albumId === '空')
157 ? item.singer && item.singer.length ? `https://y.gtimg.cn/music/photo_new/T001R500x500M000${item.singer[0].mid}.jpg` : ''
158 : `https://y.gtimg.cn/music/photo_new/T002R500x500M000${albumId}.jpg`,
159 types,
160 _types,
161 typeUrl: {},
162 })
163 })
164 return list
165 },
166
167 /** 搜索 */
168 search(str, page = 1, limit) {
169 if (limit == null) limit = this.limit
170 return this.musicSearch(str, page, limit).then(({ body, meta }) => {
171 const list = this.handleResult(body.item_song)
172
173 this.total = meta.estimate_sum
174 this.page = page
175 this.allPage = Math.ceil(this.total / limit)
176
177 return Promise.resolve({
178 list,
179 allPage: this.allPage,
180 limit,
181 total: this.total,
182 source: 'tx',
183 })
184 })
185 },
186
187 /** 获取封面 */
188 getPic(songInfo) {
189 return Promise.resolve(`https://y.gtimg.cn/music/photo_new/T002R500x500M000${songInfo.albumId}.jpg`)
190 },
191
192 /** 歌词 base64 → UTF-8 字符串 */
193 b64DecodeUnicode(b64) {
194 if (!b64) return ''
195 try {
196 return bytesToUtf8(b64ToBytes(b64))
197 } catch (e) {
198 return ''
199 }
200 },
201
202 /** 获取歌词 */
203 getLyric(songInfo) {
204 const songmid = songInfo.songmid
205 return httpFetch(`https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?songmid=${songmid}&g_tk=5381&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&platform=yqq`, {
206 headers: {
207 Referer: 'https://y.qq.com/portal/player.html',
208 },
209 }).promise.then(({ body }) => {
210 if (!body || body.code != 0 || !body.lyric) return Promise.reject(new Error('获取歌词失败'))
211 return {
212 lyric: decodeName(this.b64DecodeUnicode(body.lyric)),
213 tlyric: decodeName(this.b64DecodeUnicode(body.trans)),
214 }
215 })
216 },
217}
218
219export default tx