dsh-sidebar-media-player 0.2.0 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/qq.js ADDED
@@ -0,0 +1,1013 @@
1
+ // ── 来源声明(本插件唯一改动:仅在本行上方增加本注释块,正文逐字节未动)────────
2
+ // 来自 dsh-music-player v1.0.4(MIT),github.com/kendu76/dsh-music-player
3
+ // 原文件 lib/qq.js(996 行 / 57044 B / sha256 a647967fb358feb3…)
4
+ // 拷入 D:\...\dsh-sidebar-media-player\lib\ 时间 2026-11-10。上游 MIT,版权归原作者。
5
+ /**
6
+ * lib/qq.js — QQ 音乐「扫码登录 + 在线搜索 + 登录态取链」底层模块。
7
+ *
8
+ * 纯 Node(Node ≥ 20,用全局 fetch),无第三方依赖,无编译步骤。
9
+ * 实现参考 guohuiyuan/music-lib 的 qq/ 包(go-music-dl 的底层库),移植为 ESM:
10
+ * - 纯 QQ 扫码:ssl.ptlogin2.qq.com/ptqrshow + ptqrlogin(需大陆 IP,接口有地理/WAF 风控)
11
+ * - 微信扫码:open.weixin.qq.com/connect/qrconnect + lp.open.weixin.qq.com(各地可达)
12
+ * - 取链:u.y.qq.com/cgi-bin/musicu.fcg 的 music.vkey.GetVkey / UrlGetVkey(登录态可选高音质)
13
+ *
14
+ * ⚠️ 合规:均为非官方接口 + 流播受版权保护音乐,仅用于个人试听/学习,违反平台 ToS,风险自担。
15
+ */
16
+
17
+ import { decryptHex as qrcDecryptHex, parseQrc as qrcParse } from './qrc.js'
18
+
19
+ const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
20
+ const REF_WX = 'https://y.qq.com/portal/wx_redirect.html?login_type=2&surl=https://y.qq.com/'
21
+ const WX_APPID = 'wx48db31d50e334801'
22
+ const WX_CONNECT = 'https://open.weixin.qq.com/connect/qrconnect'
23
+ const WX_CHECK = 'https://lp.open.weixin.qq.com/connect/l/qrconnect'
24
+ const QQ_SHOW = 'https://ssl.ptlogin2.qq.com/ptqrshow'
25
+ const QQ_CHECK = 'https://ssl.ptlogin2.qq.com/ptqrlogin'
26
+
27
+ // QQ/微信端点到 Host 的网络不稳定(尤其微信 check 端点偶发挂起),Node 的
28
+ // fetch 默认无超时,一旦端点不响应,登录轮询会永久卡住、模态窗停在扫码界面。
29
+ // 统一给所有出网请求加超时(AbortController),超时即抛错,由 Host/前端继续轮询。
30
+ async function fetchWithTimeout(url, opts = {}, timeoutMs = 12000) {
31
+ const ctrl = new AbortController()
32
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs)
33
+ try {
34
+ return await fetch(url, { ...opts, signal: ctrl.signal })
35
+ } finally {
36
+ clearTimeout(timer)
37
+ }
38
+ }
39
+
40
+ // hash33: 与 QQ ptlogin 的 Go 参考实现一致 —— Go 源码为 `h += (h<<5) + c`,等价于 `h = h*33 + c`。
41
+ // 注意:不是 `h*32 + c`(即缺少 +h 会算错 ptqrtoken,导致 ptqrlogin 返回 403)。
42
+ export function hash33(s) { let h = 0; for (const c of s) h = ((h * 33) + c.charCodeAt(0)) >>> 0; return h & 0x7fffffff }
43
+
44
+ function responseCookies(res) {
45
+ const out = {}
46
+ const list = res.headers.getSetCookie ? res.headers.getSetCookie() : []
47
+ for (const c of list) {
48
+ const p = c.split(';')[0]; const i = p.indexOf('='); if (i < 0) continue
49
+ const k = p.slice(0, i).trim(); const v = p.slice(i + 1).trim()
50
+ // Set-Cookie 里可能同时给「真实值」和「删除标记」(空值 + Expires=1970 / Max-Age=0)。
51
+ // 空值删除标记不应覆盖已有的真实值(否则会把 p_skey / p_uin 等清空)。
52
+ if (v === '' && out[k] != null && out[k] !== '') continue
53
+ out[k] = v
54
+ }
55
+ return out
56
+ }
57
+ export function joinCookieMap(cookies) {
58
+ return Object.keys(cookies).filter(k => k.trim() && (cookies[k] || '').trim()).sort().map(k => `${k}=${cookies[k]}`).join('; ')
59
+ }
60
+
61
+ // =====================================================================
62
+ // 纯 QQ 扫码(ptqrshow / ptqrlogin)。ptqrlogin 凭证端点在非大陆 IP 下会被风控拦 403。
63
+ // =====================================================================
64
+ export async function createQRLogin() {
65
+ const p = new URLSearchParams()
66
+ p.set('appid', '716027609'); p.set('e', '2'); p.set('l', 'M'); p.set('s', '3'); p.set('d', '72'); p.set('v', '4')
67
+ p.set('t', (Date.now() / 1e12).toFixed(17)) // == go: float64(UnixNano)/1e18
68
+ p.set('daid', '383'); p.set('pt_3rd_aid', '100497308')
69
+ const res = await fetchWithTimeout(`${QQ_SHOW}?${p.toString()}`, { headers: { 'User-Agent': UA, 'Referer': 'https://y.qq.com/' }, redirect: 'manual' })
70
+ if (res.status !== 200) throw new Error(`qq qr show http ${res.status}`)
71
+ const image = Buffer.from(await res.arrayBuffer())
72
+ const cookies = responseCookies(res)
73
+ const qrsig = (cookies.qrsig || '').trim()
74
+ if (!qrsig) throw new Error('qq qr show missing qrsig')
75
+ return {
76
+ source: 'qq', key: new URLSearchParams({ qrsig }).toString(),
77
+ imageDataUrl: `data:image/png;base64,${image.toString('base64')}`,
78
+ expiresAt: Date.now() + 2 * 60 * 1000,
79
+ extra: { qrsig },
80
+ }
81
+ }
82
+
83
+ export async function checkQRLogin(keyStr) {
84
+ const v = new URLSearchParams(keyStr)
85
+ const qrsig = (v.get('qrsig') || '').trim()
86
+ if (!qrsig) throw new Error('qq qr login key missing qrsig')
87
+ const p = new URLSearchParams()
88
+ p.set('u1', 'https://graph.qq.com/oauth2.0/login_jump')
89
+ p.set('ptqrtoken', String(hash33(qrsig)))
90
+ p.set('ptredirect', '100'); p.set('h', '1'); p.set('t', '1'); p.set('g', '1'); p.set('from_ui', '1'); p.set('ptlang', '2052')
91
+ p.set('action', `0-0-${Date.now()}`)
92
+ p.set('js_ver', '21072115'); p.set('js_type', '1'); p.set('login_sig', '')
93
+ p.set('pt_uistyle', '40'); p.set('aid', '716027609'); p.set('daid', '383'); p.set('pt_3rd_aid', '100497308')
94
+ p.set('has_onekey', '1'); p.set('pttype', '1'); p.set('service', 'ptqrlogin'); p.set('nodirect', '0')
95
+ const res = await fetchWithTimeout(`${QQ_CHECK}?${p.toString()}`, {
96
+ headers: { 'User-Agent': UA, 'Referer': 'https://xui.ptlogin2.qq.com/', 'Cookie': `qrsig=${qrsig}` },
97
+ redirect: 'manual',
98
+ })
99
+ if (res.status !== 200) return { source: 'qq', key: keyStr, status: 'failed', message: `http ${res.status}`, extra: {} }
100
+ const raw = await res.text()
101
+ const [code, redirectURL, message] = parseQQQRCheck(raw)
102
+ const result = { source: 'qq', key: keyStr, status: mapQQQRStatus(code), message, extra: { code } }
103
+ if (result.status !== 'success') return result
104
+ let cookies = responseCookies(res)
105
+ if (redirectURL) { try { cookies = await fetchQQRedirectCookies(redirectURL, cookies) } catch (e) { result.extra.redirect_error = e.message } }
106
+ // 关键:QQ 扫码成功拿到的是 QQ 网页 cookie(uin/superkey…),本身不含 QQ 音乐的 musickey。
107
+ // 参照 GitHub-ZC/wp_MusicApi util/login_qq_scan.js:需再走「graph.qq.com OAuth 换取 code →
108
+ // musicu.fcg QQConnectLogin.LoginServer/QQLogin 换 musickey」两步,才能拿到 qm_keyst/musickey。
109
+ // 否则 getMyPlaylists 等接口因缺 authst 报 code 80030(未登录)。
110
+ try { cookies = await exchangeQQMusicAuthst(cookies, redirectURL, result) } catch (e) { result.extra.authst_error = e.message }
111
+ result.cookies = normalizeQQMusicCookies(cookies)
112
+ result.cookie = joinCookieMap(result.cookies)
113
+ return result
114
+ }
115
+
116
+ // 参考 GitHub-ZC/wp_MusicApi util/login_qq_scan.js:QQ 扫码登录后补齐 QQ 音乐登录态(musickey)。
117
+ // 步骤:① 跟随 pt_auth_key 跳转收集 graph.qq.com cookie;② OAuth authorize 拿 code;
118
+ // ③ musicu.fcg QQConnectLogin.LoginServer/QQLogin 用 code 换 musickey。
119
+ async function exchangeQQMusicAuthst(cookies, redirectURL, result) {
120
+ // 直接从 cookies 对象读取(不经过 joinCookieMap,避免它过滤掉空值/特殊字符的 key)。
121
+ const getC = (k) => { const v = cookies && typeof cookies === 'object' ? cookies[k] : undefined; return v != null ? String(v).trim() : '' }
122
+ const graphCookie = joinCookieMap(cookies)
123
+ const gtkSrc = getC('p_skey') || getC('skey') || getC('qqmusic_key') || getC('p_lskey') || getC('lskey') || getC('qm_keyst') || getC('p_skey_forbid')
124
+ const g_tk = qqGtk(gtkSrc)
125
+ const OAuth = 'https://graph.qq.com/oauth2.0/authorize'
126
+ const OAuthRedirect = 'https://y.qq.com/portal/wx_redirect.html?login_type=1&surl=https://y.qq.com/'
127
+ const ui = 'DFEC5395-9E69-4D3E-96A6-300BB770874D'
128
+ const oauthParams = new URLSearchParams()
129
+ oauthParams.set('response_type', 'code'); oauthParams.set('client_id', '100497308')
130
+ oauthParams.set('redirect_uri', OAuthRedirect); oauthParams.set('scope', 'all'); oauthParams.set('state', 'state')
131
+ oauthParams.set('switch', ''); oauthParams.set('from_ptlogin', '1'); oauthParams.set('src', '1')
132
+ oauthParams.set('update_auth', '1'); oauthParams.set('openapi', '80901010_1030'); oauthParams.set('g_tk', String(g_tk))
133
+ oauthParams.set('auth_time', String(Date.now())); oauthParams.set('ui', ui)
134
+ const oauthRes = await fetchWithTimeout(OAuth, { method: 'POST', headers: { 'User-Agent': UA, 'Referer': 'https://xui.ptlogin2.qq.com/', 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': graphCookie }, body: oauthParams.toString(), redirect: 'manual' })
135
+ const location = oauthRes.headers.get('location') || ''
136
+ for (const [k, v] of Object.entries(responseCookies(oauthRes))) cookies[k] = v
137
+ let code = (location.match(/[?&]code=([^&]+)/) || [])[1] || (location.match(/[?&]code%3D([^&]+)/) || [])[1] || ''
138
+ if (!code && getC('qm_keyst') && getC('uin')) return cookies
139
+ if (!code) { result.extra.oauth_no_code = location.slice(0, 120); return cookies }
140
+ // ③ musicu.fcg QQLogin 换 musickey
141
+ const payload = JSON.stringify({ comm: { g_tk: 5381, platform: 'yqq', ct: 24, cv: 0 }, req: { module: 'QQConnectLogin.LoginServer', method: 'QQLogin', param: { code } } })
142
+ const QQLoginCookie = joinCookieMap(cookies)
143
+ const endpoints = ['https://u.y.qq.com/cgi-bin/musicu.fcg', 'https://szu.y.qq.com/cgi-bin/musicu.fcg', 'https://shu.y.qq.com/cgi-bin/musicu.fcg']
144
+ let lastErr
145
+ for (const api of endpoints) {
146
+ const r = await fetchWithTimeout(api, { method: 'POST', headers: { 'User-Agent': UA, 'Referer': 'https://y.qq.com/portal/wx_redirect.html?login_type=1&surl=https://y.qq.com/', 'Origin': 'https://y.qq.com', 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': QQLoginCookie }, body: payload })
147
+ const body = await r.text()
148
+ for (const [k, v] of Object.entries(responseCookies(r))) if (!cookies[k]) cookies[k] = v
149
+ if (r.status !== 200) { lastErr = new Error(`qq login http ${r.status}`); continue }
150
+ let parsed; try { parsed = parseJsonPreserveBigInt(body) } catch { lastErr = new Error('qq login json'); continue }
151
+ if (parsed.code !== 0 || parsed.req?.code !== 0) { lastErr = new Error(`qq login api error: ${parsed.req?.message || parsed.req?.msg || parsed.message || parsed.msg}`); continue }
152
+ // 从响应 data 提取 musickey(与微信类似)
153
+ const data = parsed.req?.data || {}
154
+ const dataCookies = wxLoginDataCookies(data)
155
+ for (const [k, v] of Object.entries(dataCookies)) if (!cookies[k]) cookies[k] = v
156
+ const mu = cookies.musickey || cookies.qqmusic_key || cookies.qm_keyst
157
+ if (mu) { cookies.qqmusic_key = mu; cookies.qm_keyst = mu; if (!cookies.uin) cookies.uin = cookies.musicid || cookies.uin }
158
+ return cookies
159
+ }
160
+ if (lastErr) result.extra.authst_api_error = lastErr.message
161
+ return cookies
162
+ }
163
+
164
+ function parseQQQRCheck(raw) {
165
+ const matches = raw.match(/'([^']*)'/g) || []
166
+ const codes = matches.map(m => m.slice(1, -1))
167
+ return [codes[0] || '', codes[2] || '', codes[4] || '']
168
+ }
169
+ function mapQQQRStatus(code) { return { '0': 'success', '65': 'expired', '66': 'waiting', '67': 'scanned' }[code] || 'failed' }
170
+
171
+ async function fetchQQRedirectCookies(redirectURL, cookies) {
172
+ let currentURL = redirectURL
173
+ const collected = { ...cookies }
174
+ let referer = 'https://y.qq.com/'
175
+ for (let i = 0; i < 8 && currentURL; i++) {
176
+ const res = await fetchWithTimeout(currentURL, { headers: { 'User-Agent': UA, 'Referer': referer, 'Cookie': joinCookieMap(collected) }, redirect: 'manual' })
177
+ for (const [k, v] of Object.entries(responseCookies(res))) collected[k] = v
178
+ const location = res.headers.get('location')
179
+ if (!location || res.status < 300 || res.status >= 400) break
180
+ currentURL = new URL(location, currentURL).toString()
181
+ referer = currentURL
182
+ }
183
+ return collected
184
+ }
185
+
186
+ // =====================================================================
187
+ // 微信扫码(open.weixin.qq.com / lp.open.weixin.qq.com)—— 各地可达。
188
+ // =====================================================================
189
+ export async function createWXQRLogin() {
190
+ const state = `music-lib-${Date.now()}`
191
+ const p = new URLSearchParams()
192
+ p.set('appid', WX_APPID); p.set('redirect_uri', REF_WX); p.set('response_type', 'code')
193
+ p.set('scope', 'snsapi_login'); p.set('state', state)
194
+ p.set('href', 'https://y.qq.com/mediastyle/music_v17/src/css/popup_wechat.css#wechat_redirect')
195
+ const loginURL = `${WX_CONNECT}?${p.toString()}`
196
+ const res = await fetchWithTimeout(loginURL, { headers: { 'User-Agent': UA, 'Referer': 'https://y.qq.com/' }, redirect: 'manual' })
197
+ if (res.status !== 200) throw new Error(`wx qr connect http ${res.status}`)
198
+ const body = await res.text()
199
+ const uuid = parseWXUUID(body)
200
+ if (!uuid) throw new Error('wx qr connect missing uuid')
201
+ const imageUrl = `https://open.weixin.qq.com/connect/qrcode/${encodeURIComponent(uuid)}`
202
+ let imageDataUrl = ''
203
+ try {
204
+ const imgRes = await fetchWithTimeout(imageUrl)
205
+ const img = Buffer.from(await imgRes.arrayBuffer())
206
+ const ext = looksLikePng(img) ? 'png' : 'jpeg'
207
+ imageDataUrl = `data:image/${ext};base64,${img.toString('base64')}`
208
+ } catch { /* 拉图失败则让浏览器直接加载 imageUrl */ }
209
+ return {
210
+ source: 'qq', key: new URLSearchParams({ type: 'wx', uuid, state }).toString(),
211
+ url: loginURL, imageUrl, imageDataUrl,
212
+ expiresAt: Date.now() + 5 * 60 * 1000,
213
+ extra: { login_type: 'wx', uuid, state },
214
+ }
215
+ }
216
+ function looksLikePng(buf) { return buf.length >= 8 && buf[0] === 0x89 && buf[1] === 0x50 }
217
+
218
+ export async function checkWXQRLogin(keyStr) {
219
+ const v = new URLSearchParams(keyStr)
220
+ const uuid = (v.get('uuid') || '').trim()
221
+ const state = (v.get('state') || 'STATE').trim()
222
+ if (!uuid) throw new Error('wx qr login key missing uuid')
223
+ // 微信 check 端点是【长轮询】:连接会挂起约 15s 后才返回状态(wx_errcode)。
224
+ // 超时必须 >15s,否则长轮询还没返回就被 abort,永远读不到状态(扫码界面卡死)。
225
+ const res = await fetchWithTimeout(`${WX_CHECK}?${new URLSearchParams({ uuid, _: String(Date.now()) }).toString()}`, { headers: { 'User-Agent': UA, 'Referer': WX_CONNECT }, redirect: 'manual' }, 25000)
226
+ const raw = await res.text()
227
+ const [code, wxCode] = parseWXCheck(raw)
228
+ const status = mapWXStatus(code)
229
+ const message = { '405': '登录成功', '402': '二维码已过期', '404': '已扫码,请在微信中确认', '408': '等待扫码中' }[code] || raw.trim()
230
+ const result = { source: 'qq', key: keyStr, status, message, extra: { code, login_type: 'wx' } }
231
+ if (status !== 'success') return result
232
+ if (!wxCode) { result.status = 'failed'; result.message = 'wechat auth code missing'; return result }
233
+ const { cookies, extra } = await exchangeWXCodeForCookies(wxCode)
234
+ for (const k of Object.keys(extra)) result.extra[k] = extra[k]
235
+ result.extra.state = state
236
+ result.cookies = normalizeQQMusicCookies(cookies)
237
+ result.cookie = joinCookieMap(result.cookies)
238
+ return result
239
+ }
240
+ function parseWXCheck(raw) {
241
+ const code = (raw.match(/wx_errcode\s*=\s*'?([0-9]+)'?/) || [])[1] || ''
242
+ const wxCode = (raw.match(/wx_code\s*=\s*["']([^"']*)["']/) || [])[1] || ''
243
+ return [code, wxCode]
244
+ }
245
+ function mapWXStatus(code) { return { '405': 'success', '402': 'expired', '404': 'scanned', '408': 'waiting' }[code] || 'failed' }
246
+
247
+ // 保留大整数的 JSON 解析:QQ 音乐微信登录返回的 musicid/uin 高达 1e18(远超
248
+ // JS 安全整数 2^53),用 JSON.parse 会丢精度,导致拿到的 uin 是错的、歌单变成
249
+ // 别人的。此解析器把超出安全范围的整数字面量保留为字符串,避免精度丢失。
250
+ export function parseJsonPreserveBigInt(text) {
251
+ let i = 0
252
+ const ws = () => { while (i < text.length && /[\s]/.test(text[i])) i++ }
253
+ const parseValue = () => {
254
+ ws()
255
+ const c = text[i]
256
+ if (c === '{') return parseObject()
257
+ if (c === '[') return parseArray()
258
+ if (c === '"') return parseString()
259
+ if (text.startsWith('true', i)) { i += 4; return true }
260
+ if (text.startsWith('false', i)) { i += 5; return false }
261
+ if (text.startsWith('null', i)) { i += 4; return null }
262
+ return parseNumber()
263
+ }
264
+ const parseObject = () => {
265
+ i++
266
+ const o = {}
267
+ ws()
268
+ if (text[i] === '}') { i++; return o }
269
+ for (;;) {
270
+ ws()
271
+ const k = parseString()
272
+ ws()
273
+ if (text[i] === ':') i++
274
+ o[k] = parseValue()
275
+ ws()
276
+ if (text[i] === ',') { i++; continue }
277
+ if (text[i] === '}') { i++; return o }
278
+ throw new Error('bad object')
279
+ }
280
+ }
281
+ const parseArray = () => {
282
+ i++
283
+ const a = []
284
+ ws()
285
+ if (text[i] === ']') { i++; return a }
286
+ for (;;) {
287
+ a.push(parseValue())
288
+ ws()
289
+ if (text[i] === ',') { i++; continue }
290
+ if (text[i] === ']') { i++; return a }
291
+ throw new Error('bad array')
292
+ }
293
+ }
294
+ const parseString = () => {
295
+ i++
296
+ let s = ''
297
+ while (i < text.length && text[i] !== '"') {
298
+ if (text[i] === '\\') {
299
+ i++
300
+ const e = text[i]
301
+ if (e === 'n') s += '\n'
302
+ else if (e === 't') s += '\t'
303
+ else if (e === 'r') s += '\r'
304
+ else if (e === 'b') s += '\b'
305
+ else if (e === 'f') s += '\f'
306
+ else if (e === 'u') { s += String.fromCharCode(parseInt(text.slice(i + 1, i + 5), 16)); i += 4 }
307
+ else s += e
308
+ i++
309
+ } else { s += text[i]; i++ }
310
+ }
311
+ i++
312
+ return s
313
+ }
314
+ const parseNumber = () => {
315
+ const start = i
316
+ if (text[i] === '-') i++
317
+ while (i < text.length && /[0-9]/.test(text[i])) i++
318
+ let isFloat = false
319
+ if (text[i] === '.') { isFloat = true; i++; while (i < text.length && /[0-9]/.test(text[i])) i++ }
320
+ if (text[i] === 'e' || text[i] === 'E') { isFloat = true; i++; if (text[i] === '+' || text[i] === '-') i++; while (i < text.length && /[0-9]/.test(text[i])) i++ }
321
+ const raw = text.slice(start, i)
322
+ if (isFloat) return Number(raw)
323
+ const n = Number(raw)
324
+ return Number.isSafeInteger(n) ? n : raw // 超出安全范围 → 保留字符串
325
+ }
326
+ return parseValue()
327
+ }
328
+
329
+ async function exchangeWXCodeForCookies(wxCode) {
330
+ const payload = JSON.stringify({
331
+ comm: { tmeAppID: 'qqmusic', tmeLoginType: '1', g_tk: 5381, platform: 'yqq', ct: 24, cv: 0 },
332
+ req: { module: 'music.login.LoginServer', method: 'Login', param: { strAppid: WX_APPID, code: wxCode } },
333
+ })
334
+ const endpoints = ['https://u.y.qq.com/cgi-bin/musicu.fcg', 'https://szu.y.qq.com/cgi-bin/musicu.fcg', 'https://shu.y.qq.com/cgi-bin/musicu.fcg']
335
+ let lastErr
336
+ for (const api of endpoints) {
337
+ const res = await fetchWithTimeout(api, { method: 'POST', headers: { 'User-Agent': UA, 'Referer': REF_WX, 'Origin': 'https://y.qq.com', 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': 'login_type=2' }, body: payload })
338
+ const body = await res.text()
339
+ const cookies = responseCookies(res)
340
+ if (res.status !== 200) { lastErr = new Error(`wx login http ${res.status}`); continue }
341
+ let parsed; try { parsed = parseJsonPreserveBigInt(body) } catch { lastErr = new Error('wx login json parse'); continue }
342
+ if (parsed.code !== 0 || parsed.req?.code !== 0) { lastErr = new Error(`wx login api error: ${parsed.req?.message || parsed.req?.msg || parsed.message || parsed.msg}`); continue }
343
+ const data = parsed.req?.data || {}
344
+ for (const [k, val] of Object.entries(wxLoginDataCookies(data))) if (!cookies[k]) cookies[k] = val
345
+ return { cookies, extra: { endpoint: api, nickname: wxLoginNickname(data) } }
346
+ }
347
+ throw lastErr || new Error('wx login failed')
348
+ }
349
+ function val(data, ...keys) { for (const k of keys) { const v = data[k]; if (typeof v === 'string' && v.trim()) return v.trim(); if (typeof v === 'number' && v > 0) return String(v) } return '' }
350
+ // 尽力从微信登录响应里取一个可展示的昵称(不同版本键名不一,做兜底)。
351
+ // decodeEntities 是函数声明(提升),此处可安全引用;昵称也可能带 HTML 实体。
352
+ function wxLoginNickname(data) {
353
+ const direct = val(data, 'nickname', 'nick', 'name', 'user_name', 'strNickname', 'stringName', 'wx_nickname', 'nickName')
354
+ if (direct) return decodeEntities(direct)
355
+ const nested = data && typeof data === 'object' && (data.profile || data.user_info || data.userInfo || data.baseInfo)
356
+ if (nested && typeof nested === 'object') return decodeEntities(val(nested, 'nickname', 'nick', 'name', 'user_name', 'nickName'))
357
+ return ''
358
+ }
359
+ function wxLoginDataCookies(data) {
360
+ const r = {}
361
+ const musicID = val(data, 'musicid', 'musicId', 'userid', 'user_id', 'uin'); if (musicID) r.musicid = musicID
362
+ const musicKey = val(data, 'musickey', 'music_key', 'qqmusic_key', 'qm_keyst', 'strMusicKey'); if (musicKey) { r.musickey = musicKey; r.qqmusic_key = musicKey; r.qm_keyst = musicKey }
363
+ const refreshKey = val(data, 'refresh_key', 'refreshKey'); if (refreshKey) r.refresh_key = refreshKey
364
+ const refreshToken = val(data, 'refresh_token', 'refreshToken'); if (refreshToken) r.refresh_token = refreshToken
365
+ const openID = val(data, 'openid', 'openId', 'wxopenid', 'strOpenid'); if (openID) { r.openid = openID; r.wxopenid = openID }
366
+ const unionID = val(data, 'unionid', 'unionId', 'wxunionid', 'strUnionid'); if (unionID) { r.unionid = unionID; r.wxunionid = unionID }
367
+ const accessToken = val(data, 'access_token', 'accessToken', 'wxaccess_token'); if (accessToken) r.wxaccess_token = accessToken
368
+ // encrypt_uin:部分读接口(如 CgiGetDiss 取「我喜欢」)需要 enc_host_uin。
369
+ const encUin = val(data, 'encrypt_uin', 'encryptUin', 'encuin', 'euin', 'str_encrypt_uin'); if (encUin) r.encrypt_uin = encUin
370
+ return r
371
+ }
372
+
373
+ export function normalizeQQMusicCookies(cookies) {
374
+ const r = { ...cookies }
375
+ const first = (...xs) => { for (const x of xs) { if (x && String(x).trim()) return String(x).trim() } return '' }
376
+ if (!r.uin) r.uin = first(r.ptui_loginuin, r.luin, r.pt2gguin, r.superuin, r.p_uin, r.musicid, r.userid, r.wxuin)
377
+ if (!r.qqmusic_key) r.qqmusic_key = first(r.p_skey, r.skey, r.musickey)
378
+ if (!r.qm_keyst) r.qm_keyst = r.qqmusic_key
379
+ // 避免给 cookie map 塞 undefined/null 值(joinCookieMap / 后续字符串处理会崩溃)
380
+ for (const k of Object.keys(r)) if (r[k] == null) delete r[k]
381
+ return r
382
+ }
383
+
384
+ function parseWXUUID(raw) {
385
+ const pats = [/connect\/l\/qrconnect\?uuid=([A-Za-z0-9_-]+)/, /window\.QRLogin\.uuid\s*=\s*"([^"]+)"/, /\/connect\/qrcode\/([A-Za-z0-9_-]+)/]
386
+ for (const re of pats) { const m = raw.match(re); if (m && m[1]) return m[1] }
387
+ return ''
388
+ }
389
+
390
+ // =====================================================================
391
+ // 搜索(legacy,匿名可用)与登录态取链(UrlGetVkey,可反 VIP/高音质)
392
+ // =====================================================================
393
+ // 歌曲搜索:支持分页(page 从 1 起,每页 n=60,即接口单请求上限;实测 n≥61 仍只回 60、
394
+ // n≥100 直接返回空)。返回 { results, total, page },total 为接口返回的总条数
395
+ // (totalnum,实测热门词可达 600+,故单请求拿不全、前端仍需「加载更多」)。
396
+ export async function search(keyword, cookie = '', page = 1) {
397
+ const p = Math.max(1, parseInt(page, 10) || 1)
398
+ const url = `https://c.y.qq.com/soso/fcgi-bin/client_search_cp?${new URLSearchParams({ w: keyword, format: 'json', p: String(p), n: '60', t: '0', cr: '1' }).toString()}`
399
+ const headers = { 'User-Agent': UA, 'Referer': 'https://y.qq.com/' }
400
+ if (cookie) headers['Cookie'] = cookie
401
+ const res = await fetchWithTimeout(url, { headers })
402
+ const j = await res.json()
403
+ const results = (j.data?.song?.list || []).map(s => ({
404
+ id: s.songmid, songmid: s.songmid, title: dec(s.songname),
405
+ cover: qqAlbumCover(s),
406
+ songid: s.songid, songtype: s.songtype || 0,
407
+ artists: (s.singer || []).map(x => dec(x.name)),
408
+ album: dec(s.albumname), interval: s.interval,
409
+ payplay: s.pay?.payplay, pay: s.pay,
410
+ source: 'qq',
411
+ }))
412
+ const total = Number(j.data?.song?.totalnum) || results.length
413
+ return { results, total, page: p }
414
+ }
415
+
416
+ /**
417
+ * ⚠ 反面教材(别再踩):判断「QQ 音乐登录态是否还有效」**不要做主动探测**。
418
+ *
419
+ * 2026-09-16 实测:`music.UserInfo.userInfo/GetLoginUserInfo` 对**刚登录、明确有效**的微信会话
420
+ * 同样返回 `code 500003`(同一会话 `detectVip=true`、能取到 FLAC 直链;把 music key 改成垃圾值
421
+ * 后结果不变);`GetUserInfo`、`music.vip.VipInfo/GetVipInfo` 同理。歌单类读接口
422
+ * (`music.srfDissInfo.DissInfo/CgiGetDiss`、`GetPlaylistByUin`)匿名也返回 code 0。
423
+ * 也就是说:**没有一个便宜可靠的接口能判定登录态**,主动探测只会误报,而误报会把正常登录的
424
+ * 用户踢回登录页。
425
+ *
426
+ * 定稿:不做任何主动探测——过期只在**实际播放失败**时由客户端发现(在线曲目整列都播不出来 →
427
+ * 面板切回登录 UI),见 lib/index.js /qq/play 的说明与 lib/client.js 的 onError。
428
+ *
429
+ * `detectVip()` 只用于「VIP 档位」提示(能否取到无损),不承担登录态判定。
430
+ */
431
+
432
+ export async function detectVip(cookie) {
433
+ if (!cookie) return false
434
+ const songMID = '004YZbkL2MNHoY'
435
+ // VIP 探测用无损档(FLAC):无损只有 VIP 会员能取到;M500/M800 免费档在 VIP 歌曲上
436
+ // 往往被锁(无 purl),用它探测会把 VIP 账号误判为非 VIP。四个无损档都试一遍,
437
+ // 任一能取到即视为 VIP。
438
+ const prefixes = ['AI00', 'Q001', 'Q000', 'F000']
439
+ const filenames = prefixes.map((p) => `${p}${songMID}${songMID}.flac`)
440
+ const body = urlGetVkeyBody(cookie, prefixes.map(() => songMID), filenames)
441
+ const j = await postMusicu(body, cookie)
442
+ if (j.req_1?.code !== 0) return false
443
+ return (j.req_1?.data?.midurlinfo || []).some((x) => x && x.purl)
444
+ }
445
+
446
+ export async function getDownloadURL(songmid, cookie = '', isVip = false) {
447
+ const prefixes = isVip ? ['AI00', 'Q001', 'Q000', 'F000', 'O801', 'M800', 'M500'] : ['M800', 'M500']
448
+ const exts = isVip ? ['flac', 'flac', 'flac', 'flac', 'ogg', 'mp3', 'mp3'] : ['mp3', 'mp3']
449
+ const filenames = prefixes.map((p, i) => `${p}${songmid}${songmid}.${exts[i]}`)
450
+ const body = urlGetVkeyBody(cookie, prefixes.map(() => songmid), filenames)
451
+ const j = await postMusicu(body, cookie)
452
+ const infos = j.req_1?.data?.midurlinfo || []
453
+ for (const f of filenames) { const info = infos.find(x => x.filename === f); if (info && info.purl) return { url: 'https://ws.stream.qqmusic.qq.com/' + info.purl, filename: f } }
454
+ return { url: '', filename: '' }
455
+ }
456
+
457
+ function urlGetVkeyBody(cookie, songmids, filenames) {
458
+ return {
459
+ comm: { cv: 4747474, ct: 24, format: 'json', inCharset: 'utf-8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json', needNewCode: 1, uin: 0 },
460
+ req_1: { module: 'music.vkey.GetVkey', method: 'UrlGetVkey', param: { guid: String(Math.floor(Math.random() * 9e9) + 1e9), songmid: songmids, songtype: songmids.map(() => 0), uin: '0', loginflag: 1, platform: '20', filename: filenames } },
461
+ }
462
+ }
463
+ async function postMusicu(body, cookie) {
464
+ const headers = { 'User-Agent': UA, 'Referer': 'http://y.qq.com', 'Content-Type': 'application/json' }
465
+ if (cookie) headers['Cookie'] = cookie
466
+ const res = await fetchWithTimeout('https://u.y.qq.com/cgi-bin/musicu.fcg', { method: 'POST', headers, body: JSON.stringify(body) })
467
+ return res.json()
468
+ }
469
+
470
+ // =====================================================================
471
+ // 歌单:推荐 / 分类 / 分类歌单 / 歌单搜索 / 歌单歌曲(均匿名可用,登录只影响 VIP 可播性)
472
+ // 参考 go-music-dl/music-lib qq/playlist.go。
473
+ // =====================================================================
474
+ const httpsCover = (u) => (u || '').replace(/^http:/, 'https:')
475
+ // 单曲专辑封面:QQ 的 song 对象里封面 mid 有两种形状——
476
+ // 老接口/搜索:s.albummid(字符串)
477
+ // 新接口/歌单:s.album.mid(对象);但同一字段也可能是专辑名字符串,必须判类型。
478
+ // 拼成 QQ 图床直链,客户端拿它当卡片背景图。
479
+ const qqAlbumCover = (s) => {
480
+ if (!s) return ''
481
+ const mid = s.albummid || (s.album && typeof s.album === 'object' && s.album.mid) || ''
482
+ return mid ? 'https://y.qq.com/music/photo_new/T002R300x300M000' + String(mid) + '.jpg' : ''
483
+ }
484
+ const plLink = (id) => `https://y.qq.com/n/ryqq/playlist/${id}`
485
+ // 解码 QQ 音乐接口返回的 HTML 实体(标题/描述/歌手名里可能带 &#...; 或 &amp; 等)。
486
+ export function decodeEntities(str) {
487
+ if (typeof str !== 'string' || str === '') return str
488
+ return str
489
+ .replace(/&#(\d+);/g, (m, n) => { const cp = Number(n); return Number.isFinite(cp) && cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : m })
490
+ .replace(/&#x([0-9a-fA-F]+);/g, (m, h) => { const cp = parseInt(h, 16); return Number.isFinite(cp) && cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : m })
491
+ .replace(/&amp;/g, '&')
492
+ .replace(/&lt;/g, '<')
493
+ .replace(/&gt;/g, '>')
494
+ .replace(/&quot;/g, '"')
495
+ .replace(/&apos;/g, "'")
496
+ .replace(/&nbsp;/g, '\u00a0')
497
+ .replace(/<br\s*\/?>/gi, '\n')
498
+ .replace(/<[^>]+>/g, '')
499
+ }
500
+ const dec = decodeEntities
501
+
502
+ // 歌词:经典 fcg 接口(fcg_query_lyric_new),nobase64=1 直接返回纯 LRC 文本
503
+ // (含 [ti:]/[ar:]/[offset:] 元数据与 [mm:ss] 时间戳)。匿名可访问;`trans` 为
504
+ // 逐句翻译(部分外语歌才有)。与取链同构:纯 Node fetch、超时、HTML 实体解码。
505
+ export async function getLyric(songmid, cookie = '') {
506
+ const p = new URLSearchParams({
507
+ songmid, format: 'json', nobase64: '1', g_tk: '5381', loginUin: '0', hostUin: '0',
508
+ inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq.json', needNewCode: '0',
509
+ })
510
+ const url = `https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?${p.toString()}`
511
+ const res = await fetchWithTimeout(url, { headers: { 'User-Agent': UA, 'Referer': 'https://y.qq.com/', ...(cookie ? { Cookie: cookie } : {}) } })
512
+ const j = await res.json().catch(() => null)
513
+ if (!j || j.retcode !== 0 || typeof j.lyric !== 'string' || j.lyric === '') {
514
+ throw new Error('未获取到歌词(retcode=' + ((j && j.retcode) || res.status) + ')')
515
+ }
516
+ return { lyric: dec(j.lyric), trans: typeof j.trans === 'string' ? dec(j.trans) : '' }
517
+ }
518
+
519
+ // =====================================================================
520
+ // 逐字歌词(QRC):GetPlayLyricInfo 匿名接口。param 要求数字 songID + 时长 +
521
+ // 歌名/歌手/专辑的 base64(与 y.qq.com 客户端行为一致),qrc:1 表示想要逐字流。
522
+ // 响应 data.lyric 是 hex 密文;data.qrc_t ≠ 0 才代表这首歌确实有逐字歌词,
523
+ // 否则(qrc_t=0 而 lrc_t≠0)只是回落了普通 LRC —— 此时返回 null 让调用方走 LRC 路径。
524
+ // 解密/解析委托给 lib/qrc.js(独立实现的自定义 3DES + zlib inflate + 行解析)。
525
+ // 所有网络/解密错误一律向上抛错,由调用方(lyric.js 编排层)静默回落,不打扰播放。
526
+ // =====================================================================
527
+
528
+ // songmid → 数字 songID 等信息:经典单曲详情端点(匿名 GET)。
529
+ // QRC 接口只认数字 ID,而在线播放链路手里只有 songmid —— 这个端点补上缺环。
530
+ // 失败抛错由调用方静默处理(回落普通 LRC,不影响播放)。
531
+ export async function getSongInfoByMid(songmid, cookie = '') {
532
+ const p = new URLSearchParams({ songmid: String(songmid), format: 'json' })
533
+ const url = `https://c.y.qq.com/v8/fcg-bin/fcg_play_single_song.fcg?${p.toString()}`
534
+ const res = await fetchWithTimeout(url, { headers: { 'User-Agent': UA, 'Referer': 'https://y.qq.com/', ...(cookie ? { Cookie: cookie } : {}) } })
535
+ const j = await res.json().catch(() => null)
536
+ const s = Array.isArray(j && j.data) && j.data[0]
537
+ if (!s || !Number(s.id)) throw new Error('单曲信息未找到(songmid=' + songmid + ')')
538
+ return {
539
+ songid: Number(s.id),
540
+ interval: Math.round(Number(s.interval) || 0),
541
+ title: dec(s.name || ''),
542
+ artist: (s.singer || []).map((x) => dec(x.name)).join('/'),
543
+ album: dec((s.album && s.album.name) || ''),
544
+ }
545
+ }
546
+
547
+ export async function getQrcLyric({ songid, interval, title = '', artist = '', album = '' }, cookie = '') {
548
+ const idNum = Number(songid)
549
+ if (!Number.isFinite(idNum) || idNum <= 0) throw new Error('qrc 缺少数字 songid')
550
+ const b64 = (s) => Buffer.from(String(s ?? ''), 'utf8').toString('base64')
551
+ const param = {
552
+ albumName: b64(album),
553
+ crypt: 1,
554
+ ct: 19,
555
+ cv: 2111,
556
+ interval: Math.max(0, Math.round(Number(interval) || 0)),
557
+ lrc_t: 0,
558
+ qrc: 1,
559
+ qrc_t: 0,
560
+ roma: 1,
561
+ roma_t: 0,
562
+ singerName: b64(artist),
563
+ songID: idNum,
564
+ songName: b64(title),
565
+ trans: 1,
566
+ trans_t: 0,
567
+ type: 0,
568
+ }
569
+ const body = JSON.stringify({
570
+ comm: { ct: '19', cv: '2111', format: 'json' },
571
+ req: { module: 'music.musichallSong.PlayLyricInfo', method: 'GetPlayLyricInfo', param },
572
+ })
573
+ const res = await fetchWithTimeout('https://u.y.qq.com/cgi-bin/musicu.fcg', {
574
+ method: 'POST',
575
+ headers: { 'User-Agent': UA, Referer: 'https://y.qq.com/', Origin: 'https://y.qq.com', 'Content-Type': 'application/json', ...(cookie ? { Cookie: cookie } : {}) },
576
+ body,
577
+ })
578
+ const j = await res.json().catch(() => null)
579
+ if (!j || Number(j.code) !== 0) throw new Error(`GetPlayLyricInfo code=${j && j.code}`)
580
+ const r = j.req || {}
581
+ if (Number(r.code) !== 0) throw new Error(`GetPlayLyricInfo req.code=${r.code}`)
582
+ const data = r.data || {}
583
+ const cipherHex = typeof data.lyric === 'string' ? data.lyric : ''
584
+ if (cipherHex === '') return null
585
+ const hasWordData = String(data.qrc_t ?? '0') !== '0'
586
+ if (!hasWordData) return null // 只有普通 LRC,没有逐字流
587
+ const plain = qrcDecryptHex(cipherHex)
588
+ if (!plain.includes('<')) throw new Error('qrc 明文缺少 XML 包裹')
589
+ // 关键修正:QQ 的 QRC 行时长 [start,dur] 经常把行尾拖腔乃至后续间奏一并编码
590
+ // (实测「晴天」有一行标了 21.4s、实际演唱约 4s)——直接用它当扫色窗口就会在
591
+ // 长间奏被摊平。但词级时间是精确的:取最后一个词的结束时刻收紧行窗口,
592
+ // 无词级行回退原行时长。客户端消费的仍是 {t,end,text},零改动。
593
+ const VOCAL_TAIL_MS = 400 // 唱完后再让高亮保持一小会的自然尾巴
594
+ const lines = qrcParse(plain).map((l) => {
595
+ let endMs = l.startMs + l.durMs
596
+ if (Array.isArray(l.words) && l.words.length > 0) {
597
+ const wordEndMax = Math.max(...l.words.map((w) => w.startMs + w.durMs))
598
+ // 词结束合理(落在行区间内且不是坏数据)才采用;再保证最小可读时长。
599
+ if (wordEndMax > l.startMs && wordEndMax <= l.startMs + l.durMs) {
600
+ endMs = Math.min(endMs, Math.max(l.startMs + 600, wordEndMax + VOCAL_TAIL_MS))
601
+ }
602
+ }
603
+ return {
604
+ t: l.startMs / 1000, // 统一到客户端使用的秒时基
605
+ end: endMs / 1000,
606
+ text: l.text,
607
+ // 词级时间轴(words)当前不下发:逐字点亮渲染已移除,只保留精确行窗口喂
608
+ // 整行扫色;lib/qrc.js 的 words 解析能力保留(将来恢复零成本)。
609
+ }
610
+ }).filter((l) => l.text !== '')
611
+ return { kind: 'qrc', lines }
612
+ }
613
+
614
+ export async function getRecommendedPlaylists(cookie = '') {
615
+ const body = { comm: { ct: 24 }, recomPlaylist: { method: 'get_hot_recommend', module: 'playlist.HotRecommendServer', param: { async: 1, cmd: 2 } } }
616
+ const res = await postMusicu(body, cookie)
617
+ const vhot = (res.recomPlaylist && res.recomPlaylist.data && res.recomPlaylist.data.v_hot) || []
618
+ return vhot.filter((x) => x.content_id && x.title).map((x) => ({
619
+ id: String(x.content_id), name: dec(x.title), cover: httpsCover(x.cover),
620
+ playCount: x.listen_num || 0, trackCount: (x.song_cnt || x.song_count || 0), creator: dec(x.username || ''),
621
+ source: 'qq', link: plLink(x.content_id),
622
+ }))
623
+ }
624
+
625
+ export async function getPlaylistCategories(cookie = '') {
626
+ const apiURL = `https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_tag_conf.fcg?${new URLSearchParams({ format: 'json', inCharset: 'utf8', outCharset: 'utf-8' }).toString()}`
627
+ const res = await fetchWithTimeout(apiURL, { headers: { 'User-Agent': UA, 'Referer': 'https://y.qq.com/', ...(cookie ? { Cookie: cookie } : {}) } })
628
+ const j = await res.json()
629
+ const cats = []
630
+ for (const g of (j.data && j.data.categories) || []) {
631
+ for (const it of (g.items || [])) {
632
+ if (!it.categoryId || it.usable === 0 || it.categoryId === 10000000) continue
633
+ cats.push({ id: String(it.categoryId), name: dec(it.categoryName), group: dec(g.categoryGroupName || '') })
634
+ }
635
+ }
636
+ return cats
637
+ }
638
+
639
+ export async function getCategoryPlaylists(categoryID = '10000000', page = 1, limit = 20, cookie = '') {
640
+ const offset = (page - 1) * limit
641
+ const p = new URLSearchParams()
642
+ p.set('picmid', '1'); p.set('rnd', '0.1'); p.set('g_tk', '5381'); p.set('loginUin', '0'); p.set('hostUin', '0')
643
+ p.set('format', 'json'); p.set('inCharset', 'utf8'); p.set('outCharset', 'utf-8'); p.set('notice', '0')
644
+ p.set('platform', 'yqq.json'); p.set('needNewCode', '0')
645
+ p.set('categoryId', String(categoryID)); p.set('sortId', '5')
646
+ p.set('sin', String(offset)); p.set('ein', String(offset + limit - 1))
647
+ const apiURL = `https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg?${p.toString()}`
648
+ const res = await fetchWithTimeout(apiURL, { headers: { 'User-Agent': UA, 'Referer': 'https://y.qq.com/', ...(cookie ? { Cookie: cookie } : {}) } })
649
+ const j = await res.json()
650
+ return (j.data && j.data.list || []).filter((x) => x.dissid && x.dissname).map((x) => ({
651
+ id: x.dissid, name: dec(x.dissname), cover: httpsCover(x.imgurl),
652
+ trackCount: (x.song_count || x.song_num || 0), playCount: x.listennum || 0, creator: dec((x.creator && x.creator.name) || ''),
653
+ description: dec(x.introduction || ''), source: 'qq', link: plLink(x.dissid),
654
+ }))
655
+ }
656
+
657
+ /** 歌单搜索(每页 num_per_page=50,即接口单请求上限;实测 n≥60 返回空,且每页返回数
658
+ * 不固定:49/46/44/35)。注意:该接口响应里 totalnum/total_num 缺失(实测为 None),
659
+ * total 只能回退为当前页长度,前端「是否还有更多」须用「最近一页返回较满(≥20)」判定。 */
660
+ export async function searchPlaylist(keyword, cookie = '', page = 1) {
661
+ const p = Math.max(1, parseInt(page, 10) || 1)
662
+ const param = new URLSearchParams({ query: keyword, page_no: String(p - 1), num_per_page: '50', format: 'json', remoteplace: 'txt.yqq.playlist', flag_qc: '0' })
663
+ const apiURL = `http://c.y.qq.com/soso/fcgi-bin/client_music_search_songlist?${param.toString()}`
664
+ const res = await fetchWithTimeout(apiURL, { headers: { 'User-Agent': UA, 'Referer': 'https://y.qq.com/portal/search.html', ...(cookie ? { Cookie: cookie } : {}) } })
665
+ let text = await res.text()
666
+ const i = text.indexOf('('); const e = text.lastIndexOf(')')
667
+ if (i >= 0 && e > i) text = text.slice(i + 1, e)
668
+ const j = JSON.parse(text)
669
+ const results = (j.data && j.data.list || []).filter((x) => x.dissid && x.dissname).map((x) => ({
670
+ id: x.dissid, name: dec(x.dissname), cover: httpsCover(x.imgurl),
671
+ trackCount: x.song_count || 0, playCount: x.listennum || 0, creator: dec((x.creator && x.creator.name) || ''),
672
+ source: 'qq', link: plLink(x.dissid),
673
+ }))
674
+ const d = j.data || {}
675
+ const total = Number(d.totalnum ?? d.total_num) || results.length
676
+ return { results, total, page: p }
677
+ }
678
+
679
+ export async function getPlaylistSongs(id, cookie = '') {
680
+ id = String(id).trim()
681
+ const p = new URLSearchParams()
682
+ p.set('type', '1'); p.set('json', '1'); p.set('utf8', '1'); p.set('onlysong', '0'); p.set('disstid', id)
683
+ p.set('format', 'json'); p.set('g_tk', '5381'); p.set('loginUin', '0'); p.set('hostUin', '0')
684
+ p.set('inCharset', 'utf8'); p.set('outCharset', 'utf-8'); p.set('notice', '0'); p.set('platform', 'yqq'); p.set('needNewCode', '0')
685
+ const endpoints = [
686
+ `https://i.y.qq.com/qzone-music/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg?${p.toString()}`,
687
+ `http://c.y.qq.com/qzone/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg?${p.toString()}`,
688
+ ]
689
+ let lastErr
690
+ for (const apiURL of endpoints) {
691
+ try {
692
+ const res = await fetchWithTimeout(apiURL, { headers: { 'User-Agent': UA, 'Referer': 'https://y.qq.com/', ...(cookie ? { Cookie: cookie } : {}) } })
693
+ let text = await res.text()
694
+ if (text.trimStart().startsWith('MusicJsonCallback(')) { const i = text.indexOf('('); const e = text.lastIndexOf(')'); text = text.slice(i + 1, e) }
695
+ const j = JSON.parse(text)
696
+ const cd = (j.cdlist || [])[0]
697
+ if (!cd) { lastErr = new Error('playlist not found'); continue }
698
+ return {
699
+ id, name: dec(cd.dissname || ''), creator: dec(cd.nickname || ''), description: dec(cd.desc || ''),
700
+ cover: httpsCover(cd.logo), trackCount: cd.songnum || 0, source: 'qq', link: plLink(id),
701
+ songs: (cd.songlist || []).map((s) => ({
702
+ id: s.songmid, songmid: s.songmid, title: dec(s.songname),
703
+ cover: qqAlbumCover(s),
704
+ songid: s.songid, songtype: s.songtype || 0,
705
+ artists: (s.singer || []).map((x) => dec(x.name)), album: dec(s.albumname),
706
+ payplay: s.pay ? s.pay.payplay : 0, source: 'qq',
707
+ })).filter((s) => s.songmid),
708
+ }
709
+ } catch (err) { lastErr = err }
710
+ }
711
+ throw lastErr || new Error('playlist not found')
712
+ }
713
+
714
+ // 我的歌单(登录后):当前账号创建/收藏的歌单列表。需要登录态 cookie。
715
+ // 参考 @yakult-green-tea/qq-music-api 的 music.musicasset.PlaylistBaseRead / GetPlaylistByUin:
716
+ // comm 里必须带真实 App 版本号(cv/v) + authst/musickey + qq/uid/loginUin,否则接口当未登录返回空。
717
+ export async function getMyPlaylists(cookie = '') {
718
+ if (!cookie) return []
719
+ const cv = (k) => { const m = new RegExp('(?:^|;\\s*)' + k + '=([^;]+)').exec(cookie); return m ? m[1].trim() : '' }
720
+ const uin = cv('uin') || cv('musicid')
721
+ if (!uin) return []
722
+ const musickey = cv('qqmusic_key') || cv('qm_keyst') || cv('musickey') || cv('p_skey')
723
+ // 登录类型:cookie 里没有就按 musickey 前缀推断(W_X 开头 = 微信)。
724
+ let loginType = cv('tmeLoginType')
725
+ if (!loginType) loginType = (musickey && musickey.startsWith('W_X')) ? '1' : '2'
726
+ const comm = {
727
+ ct: 11, cv: 14090008, v: 14090008, format: 'json',
728
+ inCharset: 'utf-8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json',
729
+ needNewCode: 1, tmeAppID: 'qqmusic', uid: uin, qq: uin, loginUin: uin,
730
+ }
731
+ if (musickey) { comm.authst = musickey; comm.tmeLoginType = loginType }
732
+ const body = {
733
+ comm,
734
+ // 注意:GetPlaylistByUin 的 uin 必须是【字符串】(数值会触发上游 code 10006)。
735
+ req_0: { module: 'music.musicasset.PlaylistBaseRead', method: 'GetPlaylistByUin', param: { uin } },
736
+ }
737
+ const j = await postMusicu(body, cookie)
738
+ const res = j.req_0 || j['music.musicasset.PlaylistBaseRead']
739
+ const rawSnippet = (x) => { try { const s = JSON.stringify(x); return s ? s.slice(0, 300) : String(x) } catch { return String(x) } }
740
+ if (!res) throw new Error('我的歌单接口无响应(顶层 code=' + j.code + ',raw=' + rawSnippet(j) + ')')
741
+ if (Number(res.code) !== 0) throw new Error('获取我的歌单失败:' + ((res.message || res.msg) || ('code ' + res.code)) + '|raw=' + rawSnippet(res))
742
+ const list = res.data?.v_playlist || []
743
+ return list.filter((x) => x.tid && x.dirName).map((x) => {
744
+ const dirId = Number(x.dirId) || Number(x.tid) || 0
745
+ // QQ 的「我喜欢」是系统默认歌单(dirId 固定 201);其余为本账号自建歌单。
746
+ // 腾讯 GetPlaylistByUin 里没有「收藏别人的歌单」条目(收藏走单独的收藏接口),
747
+ // 所以只区分 默认(201) / 自建。
748
+ const isDefault = dirId === 201
749
+ return {
750
+ id: String(x.tid), dirId, tid: Number(x.tid) || 0,
751
+ name: dec(x.dirName), cover: httpsCover(x.picUrl),
752
+ trackCount: x.songNum || 0, playCount: 0, creator: dec(x.nick || ''), source: 'qq', link: plLink(x.tid),
753
+ isDefault,
754
+ kind: isDefault ? 'default' : 'own',
755
+ }
756
+ })
757
+ }
758
+
759
+ // 构建带登录态的 musicu comm(含版本号 cv/v + authst/musickey + qq/uid/loginUin)。
760
+ function buildAuthedComm(cookie) {
761
+ const cv = (k) => { const m = new RegExp('(?:^|;\\s*)' + k + '=([^;]+)').exec(cookie); return m ? m[1].trim() : '' }
762
+ const uin = cv('uin') || cv('musicid')
763
+ const musickey = cv('qqmusic_key') || cv('qm_keyst') || cv('musickey') || cv('p_skey')
764
+ let loginType = cv('tmeLoginType')
765
+ if (!loginType) loginType = (musickey && musickey.startsWith('W_X')) ? '1' : '2'
766
+ const comm = {
767
+ ct: 11, cv: 14090008, v: 14090008, format: 'json',
768
+ inCharset: 'utf-8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json',
769
+ needNewCode: 1, tmeAppID: 'qqmusic', uid: uin, qq: uin, loginUin: uin,
770
+ }
771
+ if (musickey) { comm.authst = musickey; comm.tmeLoginType = loginType }
772
+ return { comm, uin, musickey }
773
+ }
774
+
775
+ // QQ 音乐 g_tk(CSRF)由 musickey 计算,seed=5381。写操作(AddSonglist 等)必需。
776
+ function qqGtk(musickey) {
777
+ if (!musickey) return 5381
778
+ let h = 5381
779
+ for (let i = 0; i < musickey.length; i++) h += (h << 5) + musickey.charCodeAt(i)
780
+ return h & 0x7fffffff
781
+ }
782
+
783
+ // 通用的「歌单写操作」:调用指定 module 的写接口。
784
+ // method 为 AddSonglist / DelSonglist(PlaylistDetailWrite)或 AddPlaylist / DelPlaylist(PlaylistBaseWrite)。
785
+ // 成功返回 res.data(可能为 {});失败抛错。写操作需要登录态 + g_tk(CSRF)。
786
+ async function playlistDetailWrite(method, param, cookie, module = 'music.musicasset.PlaylistDetailWrite') {
787
+ if (!cookie) throw new Error('未登录,无法操作歌单')
788
+ const { comm, musickey } = buildAuthedComm(cookie)
789
+ const g_tk = qqGtk(musickey)
790
+ if (g_tk) { comm.g_tk = g_tk; comm.g_tk_new_20200303 = g_tk }
791
+ const body = { comm, req_0: { module, method, param } }
792
+ const j = await postMusicu(body, cookie)
793
+ const res = j.req_0 || j[module]
794
+ const rawSnippet = (x) => { try { const s = JSON.stringify(x); return s ? s.slice(0, 300) : String(x) } catch { return String(x) } }
795
+ const retCode = res?.data?.retCode
796
+ if (retCode !== undefined) {
797
+ if (Number(retCode) === 0) return res.data || {}
798
+ throw new Error('歌单操作失败(retCode=' + retCode + ',raw=' + rawSnippet(j) + ')')
799
+ }
800
+ const code = res ? Number(res.code) : (j.code !== undefined ? Number(j.code) : NaN)
801
+ if (code === 0) return (res && res.data) || {}
802
+ throw new Error('歌单操作失败(code=' + code + '|method=' + method + '|param=' + rawSnippet(param) + '|raw=' + rawSnippet(j) + ')')
803
+ }
804
+
805
+ // 收藏/取消收藏歌曲到「我喜欢」(dirId 固定 201)。song 需含 songid(数值)、songtype。
806
+ async function qqFavWrite(song, cookie, method) {
807
+ const songId = Number(song.songid) || 0
808
+ if (!songId) throw new Error('缺少歌曲 songid,无法收藏')
809
+ await playlistDetailWrite(method, {
810
+ dirId: 201,
811
+ tid: 0,
812
+ bFmtUtf8: true,
813
+ v_songInfo: [{ songId, songType: Number(song.songtype) || 0 }],
814
+ }, cookie)
815
+ return true
816
+ }
817
+
818
+ export async function addQQFav(song, cookie = '') {
819
+ return qqFavWrite(song, cookie, 'AddSonglist')
820
+ }
821
+ export async function removeQQFav(song, cookie = '') {
822
+ return qqFavWrite(song, cookie, 'DelSonglist')
823
+ }
824
+
825
+ // 把歌曲加入某个自建歌单(dirId = 该歌单的目录 id,tid = 歌单 tid,可为 0)。
826
+ export async function addSongToPlaylist(song, dirId, tid = 0, cookie = '') {
827
+ const songId = Number(song.songid) || 0
828
+ if (!songId) throw new Error('缺少歌曲 songid,无法加入歌单')
829
+ await playlistDetailWrite('AddSonglist', {
830
+ dirId: Number(dirId) || 0,
831
+ tid: Number(tid) || 0,
832
+ bFmtUtf8: true,
833
+ v_songInfo: [{ songId, songType: Number(song.songtype) || 0 }],
834
+ }, cookie)
835
+ return true
836
+ }
837
+
838
+ // 把歌曲从某个歌单移除(DelSonglist)。「我喜欢」也是 dirId=201,同在列。
839
+ // tid 固定 0 即可(与 addSongToPlaylist 一致)。
840
+ export async function deleteSongFromPlaylist(song, dirId, tid = 0, cookie = '') {
841
+ const songId = Number(song.songid) || 0
842
+ if (!songId) throw new Error('缺少歌曲 songid,无法从歌单移除')
843
+ await playlistDetailWrite('DelSonglist', {
844
+ dirId: Number(dirId) || 0,
845
+ tid: Number(tid) || 0,
846
+ bFmtUtf8: true,
847
+ v_songInfo: [{ songId, songType: Number(song.songtype) || 0 }],
848
+ }, cookie)
849
+ return true
850
+ }
851
+
852
+ // 创建自建歌单(AddPlaylist / PlaylistBaseWrite),返回 { id, name }。
853
+ // AddPlaylist 响应把新歌单信息嵌套在 data.result 下(dirId/dirName/tid)。
854
+ export async function createPlaylist(name, cookie = '') {
855
+ const dirName = String(name || '').trim()
856
+ if (dirName === '') throw new Error('歌单名不能为空')
857
+ const data = await playlistDetailWrite('AddPlaylist', { dirName }, cookie, 'music.musicasset.PlaylistBaseWrite')
858
+ const result = (data && data.result) || data || {}
859
+ const id = Number(result.dirId) || Number(result.dirid) || Number(result.tid) || Number(result.id) || Number(result.content_id) || 0
860
+ return { id, name: dec(result.dirName || result.dirname || result.name || dirName) }
861
+ }
862
+
863
+ // 删除自建歌单(DelPlaylist / PlaylistBaseWrite)。dirId = 该歌单的目录 id。
864
+ // 只能删除本人创建的歌单;「我喜欢」(dirId=201)不允许删除,由前端隐藏入口。
865
+ // DelPlaylist 响应把结果嵌套在 data.result 下;成功返回 true,失败抛错。
866
+ export async function deletePlaylist(dirId, cookie = '') {
867
+ const id = Number(dirId) || 0
868
+ if (!id) throw new Error('缺少歌单 dirId,无法删除')
869
+ if (id === 201) throw new Error('「我喜欢」不可删除')
870
+ await playlistDetailWrite('DelPlaylist', { dirId: id }, cookie, 'music.musicasset.PlaylistBaseWrite')
871
+ return true
872
+ }
873
+
874
+ // 获取「我喜欢」(dirid=201)里已收藏歌曲的 songid + songmid 集合,用于播放时判断当前曲目是否已收藏。
875
+ // 返回 { ids: number[], mids: string[] }——songmid 是稳定字符串标识,避免 songid 大整数/类型不一致导致匹配失败。
876
+ export async function getQQFavIds(cookie = '') {
877
+ if (!cookie) throw new Error('未登录,无法读取「我喜欢」')
878
+ const { comm, uin } = buildAuthedComm(cookie)
879
+ // enc_host_uin:CgiGetDiss 取「我喜欢」(dirid=201)需要加密后的 uin。
880
+ // 微信登录响应带 encrypt_uin;纯 QQ 账号退化为明文 uin(多数情况下可用)。
881
+ const cv = (k) => { const m = new RegExp('(?:^|;\\s*)' + k + '=([^;]+)').exec(cookie); return m ? m[1].trim() : '' }
882
+ const encUin = cv('encrypt_uin') || cv('encuin') || cv('euin') || uin
883
+ const param = { disstid: 0, dirid: 201, tag: true, song_begin: 0, song_num: 300, userinfo: true, orderlist: true }
884
+ if (encUin) param.enc_host_uin = encUin
885
+ const body = {
886
+ comm,
887
+ req_0: {
888
+ module: 'music.srfDissInfo.DissInfo',
889
+ method: 'CgiGetDiss',
890
+ param,
891
+ },
892
+ }
893
+ const j = await postMusicu(body, cookie)
894
+ const res = j.req_0 || j['music.srfDissInfo.DissInfo']
895
+ if (!res || Number(res.code) !== 0) {
896
+ throw new Error('读取「我喜欢」失败:' + ((res && (res.message || res.msg)) || ('code ' + (res && res.code))))
897
+ }
898
+ // 从 CgiGetDiss 响应 data 里找出歌曲列表:真实字段可能是 songlist / song_info /
899
+ // dirinfo.songlist 等,逐个扫描,取第一个含歌曲标识的数组。
900
+ // 注意 CgiGetDiss 的歌曲对象字段是 mid/id/name(搜索/歌单接口是 songmid/songid/songname)。
901
+ const findSongList = (data, depth = 0) => {
902
+ if (!data || typeof data !== 'object' || depth > 4) return null
903
+ // 优先直接命中已知的歌曲列表字段名(避免把 dirinfo 等带 id 的对象误判)。
904
+ for (const k of ['songlist', 'song_info', 'songInfoList', 'songinfo', 'songs', 'musiclist']) {
905
+ const v = data[k]
906
+ if (Array.isArray(v) && v.length > 0 && v[0] && typeof v[0] === 'object') return v
907
+ }
908
+ for (const k of Object.keys(data)) {
909
+ const v = data[k]
910
+ if (Array.isArray(v)) {
911
+ if (v.length > 0 && v[0] && typeof v[0] === 'object'
912
+ && (v[0].songmid || v[0].songid || v[0].songname || v[0].mid || v[0].id || v[0].name)) return v
913
+ continue
914
+ }
915
+ if (v && typeof v === 'object') {
916
+ const found = findSongList(v, depth + 1)
917
+ if (found) return found
918
+ }
919
+ }
920
+ return null
921
+ }
922
+ const songlist = findSongList(res.data) || []
923
+ // CgiGetDiss 字段:id/songid(数字 ID)、mid/songmid(字符串 ID);两者取其一,songmid 优先匹配。
924
+ const ids = songlist.map((s) => Number(s.songid || s.id)).filter((x) => Number.isFinite(x) && x > 0)
925
+ const mids = songlist.map((s) => String(s.songmid || s.mid || '')).filter((x) => x !== '')
926
+ return { ids, mids }
927
+ }
928
+
929
+ // =====================================================================
930
+ // 发现:排行榜 + 新歌速递(均匿名可用,无需登录)
931
+ // 参考 Rain120/qq-music-api:musicToplist.ToplistInfoServer + newsong.NewSongServer。
932
+ // =====================================================================
933
+
934
+ // 排行榜分类(所有榜单分组)。匿名可用。
935
+ export async function getTopLists(cookie = '') {
936
+ const body = { comm: { ct: 24, cv: 0, format: 'json', platform: 'yqq.json', needNewCode: 1 }, req_0: { module: 'musicToplist.ToplistInfoServer', method: 'GetAll', param: {} } }
937
+ const j = await postMusicu(body, cookie)
938
+ const res = j.req_0 || j['musicToplist.ToplistInfoServer']
939
+ if (!res || Number(res.code) !== 0) throw new Error('获取排行榜失败:' + ((res && (res.message || res.msg)) || ('code ' + (res && res.code))))
940
+ const groups = (res.data && res.data.group) || []
941
+ return groups.map((g) => ({
942
+ id: String(g.groupId || ''), name: dec(g.groupName || ''),
943
+ toplists: (g.toplist || []).map((t) => ({
944
+ id: String(t.topId), name: dec(t.title || ''), intro: dec(t.intro || ''),
945
+ // headPicUrl 是无文字版(纯色底 + 中央图标);R500x500 缩为 R300x300 减小体积。
946
+ // frontPicUrl 带榜名文字,仅在无 headPicUrl 时回退。
947
+ cover: httpsCover((t.headPicUrl || t.frontPicUrl || '').replace(/R[0-9]+x[0-9]+/, 'R300x300')),
948
+ listenNum: t.listenNum || 0, totalNum: t.totalNum || 0,
949
+ updateTime: t.updateTime || '', period: t.period || '',
950
+ })),
951
+ })).filter((g) => g.toplists.length > 0)
952
+ }
953
+
954
+ // 排行榜详情歌曲。匿名可用;返回带 songmid 的歌曲对象(可直接播放)。
955
+ // 用 musicu 的 music.musicToplist.Toplist/GetDetail 分页取数:offset/num 支持翻页;
956
+ // 接口本身不设 num 上限,大 num(实测 num≥榜单总数,最大榜 热歌榜 299 首)可一次拿全
957
+ // 整榜,无需前端「加载更多」(旧版 fcg_v8_toplist_cp.fcg 无法翻页且最多只返回 50 首)。
958
+ // 返回 { id, name, cover, updateTime, total, hasMore, songs }。
959
+ export async function getTopListSongs(topId, cookie = '', offset = 0, num = 30) {
960
+ const off = Math.max(0, parseInt(offset, 10) || 0)
961
+ const size = Math.max(1, Math.min(500, parseInt(num, 10) || 30))
962
+ const body = {
963
+ comm: { ct: 24, cv: 0, format: 'json', platform: 'yqq.json', needNewCode: 1 },
964
+ req_0: { module: 'music.musicToplist.Toplist', method: 'GetDetail', param: { topId: Number(topId), offset: off, num: size, withTags: true } },
965
+ }
966
+ const j = await postMusicu(body, cookie)
967
+ const res = j.req_0 || j['music.musicToplist.Toplist']
968
+ if (!res || Number(res.code) !== 0) throw new Error('获取榜单失败:' + ((res && (res.message || res.msg)) || ('code ' + (res && res.code))))
969
+ const data = (res.data && res.data.data) || {}
970
+ const list = (res.data && Array.isArray(res.data.songInfoList) ? res.data.songInfoList : []).map((x) => {
971
+ const s = (x && x.songInfo) || x || {}
972
+ return {
973
+ id: s.mid, songmid: s.mid, title: dec(s.name || s.title || ''),
974
+ cover: qqAlbumCover(s),
975
+ songid: s.id || s.songid, songtype: s.type || s.songtype || 0,
976
+ artists: (s.singer || []).map((v) => dec(v.name)),
977
+ album: s.album ? dec(s.album.name || '') : '', interval: s.interval,
978
+ payplay: (s.pay && (s.pay.payplay || s.pay.pay_play)) || 0, source: 'qq',
979
+ }
980
+ }).filter((s) => s.songmid)
981
+ const total = Number(data.totalNum) || list.length
982
+ return {
983
+ id: String(topId),
984
+ name: dec(data.title || ''),
985
+ cover: httpsCover((data.headPicUrl || data.frontPicUrl || '').replace(/R[0-9]+x[0-9]+/, 'R300x300')),
986
+ intro: dec(data.intro || ''),
987
+ updateTime: data.updateTime || data.period || '',
988
+ total,
989
+ hasMore: off + list.length < total,
990
+ songs: list,
991
+ }
992
+ }
993
+
994
+ // 新歌速递(首页推荐-新歌)。匿名可用。type: 5 最新 / 1 内地 / 6 港台 / 2 欧美 / 4 韩国。
995
+ export async function getNewSongs(type = 5, cookie = '') {
996
+ const body = { comm: { ct: 24, cv: 0, format: 'json', platform: 'yqq.json', needNewCode: 1 }, req_0: { module: 'newsong.NewSongServer', method: 'get_new_song_info', param: { type: Number(type) || 5 } } }
997
+ const j = await postMusicu(body, cookie)
998
+ const res = j.req_0 || j['newsong.NewSongServer']
999
+ if (!res || Number(res.code) !== 0) throw new Error('获取新歌失败:' + ((res && (res.message || res.msg)) || ('code ' + (res && res.code))))
1000
+ const data = res.data || {}
1001
+ const songlist = (data.songlist || []).filter((s) => s && s.mid).map((s) => ({
1002
+ id: s.mid, songmid: s.mid, title: dec(s.name || s.title || ''),
1003
+ cover: qqAlbumCover(s),
1004
+ songid: s.id, songtype: s.type || s.songtype || 0,
1005
+ artists: (s.singer || []).map((x) => dec(x.name)),
1006
+ album: s.album ? dec(s.album.name || '') : '', interval: s.interval,
1007
+ payplay: s.pay ? s.pay.payplay : 0, source: 'qq',
1008
+ }))
1009
+ const lan = (data.lanlist || []).find((x) => String(x.type) === String(type))
1010
+ return {
1011
+ type, label: dec((lan && lan.lan) || '最新'), songs: songlist,
1012
+ }
1013
+ }