dsh-cloudmusic-player 0.5.0 → 0.7.19

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.
@@ -0,0 +1,1444 @@
1
+ /**
2
+ * web-backend.mjs — 网易云「网页版」播放通道(CDP 全包方案,前端零改动)
3
+ *
4
+ * 背景:cloudmusic-player 原本只控制本机客户端(windows-powershell 后端 +
5
+ * helper.ps1 + SMTC)。客户端没装/没开时,用户仍希望用悬浮框完成同样的动作。
6
+ * 这个后端不碰前端 client.js,只守住 Host 侧 6 条路由契约 + 状态形状:
7
+ * - 通过 CDP 驱动 ego-lite 的持久浏览器(default space)里的 music.163.com 页面;
8
+ * - 登录态复用:优先用客户端解出的 cookie 注入浏览器(Storage.setCookies),
9
+ * 浏览器已登录则直接用,未登录返回一个可读的 ok:false;
10
+ * - 出声:网页版本身点播放只会提示"去客户端播放",所以真实音频走明文
11
+ * POST https://music.163.com/api/song/enhance/player/url/v1 + 登录 cookie
12
+ * 拿到 URL,再注入页面 <audio> 播放(带 Referer 防盗链)。
13
+ *
14
+ * 设计约束(来自 k65 验收):
15
+ * - 上层 action 接口形状不变(state/action/volume/lyrics 的返回跟原生后端一致);
16
+ * - 网页版未登录/未打开/浏览器没起,一律 {ok:false,error,message} 不抛异常;
17
+ * - play_daily 复用 DailyService 的 cookie/取数,打通 songId→song/url→audio。
18
+ *
19
+ * 不依赖任何 npm 包:Node 内置 fetch / WebSocket(Node ≥ 22)。
20
+ */
21
+
22
+ import { readFileSync } from 'node:fs'
23
+ import { join } from 'node:path'
24
+ import { homedir } from 'node:os'
25
+ import { loadCookieHeader } from './cookies.mjs'
26
+ import { LikeService } from './like.mjs'
27
+ import { SmtcBrowser } from './smtc-browser.mjs'
28
+ import { WinrtAudio } from './winrt-audio.mjs'
29
+
30
+ const MUSIC_ORIGIN = 'https://music.163.com'
31
+ const MUSIC_HOME = `${MUSIC_ORIGIN}/`
32
+ const SONG_URL_API = `${MUSIC_ORIGIN}/api/song/enhance/player/url/v1`
33
+ const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
34
+ const PAGE_TARGET_HINT = 'music.163.com'
35
+ const AUDIO_ID = '__dsh_cmp_audio'
36
+ const CONNECT_TIMEOUT_MS = 4000
37
+ const EVAL_TIMEOUT_MS = 6000
38
+ // 播放顺序:上层/前端用短值 order/cycle/single/random(index.js set_mode 参数),
39
+ // 状态 now.mode 必须回内部枚举 playOrder/playCycle/playOneCycle/playRandom,
40
+ // 前端 client.js 的 MODE_ORDER 才认、图标才会跟着切。
41
+ const MODE_SHORT_TO_ENUM = { order: 'playOrder', cycle: 'playCycle', single: 'playOneCycle', random: 'playRandom' }
42
+ const MODE_ENUM_DEFAULT = 'playCycle'
43
+
44
+ /** 浏览器 CDP 配置:从 ego-lite 的 browser.json 读(Windows 在 %LOCALAPPDATA%\ego-lite-linux)。 */
45
+ function egoConfigPath() {
46
+ if (process.env.LOCALAPPDATA) return join(process.env.LOCALAPPDATA, 'ego-lite-linux', 'browser.json')
47
+ return join(homedir(), '.ego-lite-linux', 'browser.json')
48
+ }
49
+
50
+ function readEgoConfig(overridePath) {
51
+ try {
52
+ const p = overridePath || egoConfigPath()
53
+ const cfg = JSON.parse(readFileSync(p, 'utf8'))
54
+ if (!cfg.wsUrl) throw new Error('browser.json 缺少 wsUrl')
55
+ return cfg
56
+ } catch (err) {
57
+ return { error: `读 ego 浏览器配置失败:${String(err?.message || err)}` }
58
+ }
59
+ }
60
+
61
+ /**
62
+ * 极简 CDP 客户端:一个 browser-level WebSocket,attach 到页面 target 后用
63
+ * sessionId 发 Runtime.evaluate / Page.reload;不依赖 ws / playwright。
64
+ */
65
+ class CdpClient {
66
+ constructor(wsUrl) {
67
+ this.wsUrl = wsUrl
68
+ this.ws = null
69
+ this.seq = 0
70
+ this.pending = new Map()
71
+ this.closed = false
72
+ }
73
+
74
+ async connect(timeoutMs = CONNECT_TIMEOUT_MS) {
75
+ if (this.ws && this.ws.readyState === 1) return
76
+ if (typeof WebSocket === 'undefined') throw new Error('Node 版本过低,缺少内置 WebSocket(需 ≥ 22)')
77
+ const ws = new WebSocket(this.wsUrl)
78
+ this.ws = ws
79
+ await new Promise((resolve, reject) => {
80
+ const timer = setTimeout(() => reject(new Error('连接 CDP 超时')), timeoutMs)
81
+ ws.onopen = () => { clearTimeout(timer); resolve() }
82
+ ws.onerror = (e) => { clearTimeout(timer); reject(new Error(`CDP 连接错误:${e?.message || 'unknown'}`)) }
83
+ })
84
+ ws.onmessage = (ev) => {
85
+ let msg
86
+ try { msg = JSON.parse(ev.data) } catch { return }
87
+ if (msg.id && this.pending.has(msg.id)) {
88
+ const { resolve, reject, timer } = this.pending.get(msg.id)
89
+ clearTimeout(timer)
90
+ this.pending.delete(msg.id)
91
+ if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error)))
92
+ else resolve(msg.result)
93
+ }
94
+ }
95
+ ws.onclose = () => {
96
+ this.ws = null
97
+ for (const { reject, timer } of this.pending.values()) {
98
+ clearTimeout(timer)
99
+ reject(new Error('CDP 连接已关闭'))
100
+ }
101
+ this.pending.clear()
102
+ }
103
+ }
104
+
105
+ cmd(method, params = {}, sessionId, timeoutMs = EVAL_TIMEOUT_MS) {
106
+ if (!this.ws || this.ws.readyState !== 1) throw new Error('CDP 未连接')
107
+ const id = ++this.seq
108
+ return new Promise((resolve, reject) => {
109
+ const timer = setTimeout(() => {
110
+ this.pending.delete(id)
111
+ reject(new Error(`CDP 调用超时:${method}`))
112
+ }, timeoutMs)
113
+ this.pending.set(id, { resolve, reject, timer })
114
+ this.ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }))
115
+ })
116
+ }
117
+
118
+ /** 连接是否仍存活。浏览器重启后 ws 会关闭,旧连接必须丢弃重建。 */
119
+ isAlive() { return !this.closed && !!this.ws && this.ws.readyState === 1 }
120
+
121
+ close() {
122
+ this.closed = true
123
+ try { this.ws?.close() } catch { /* ignore */ }
124
+ this.ws = null
125
+ }
126
+ }
127
+
128
+ /** 把 loadCookieHeader 的 header 解析成 CDP Storage.setCookies 需要的数组。 */
129
+ function cookieHeaderToCdp(cookieHeader, domain = '.music.163.com') {
130
+ const cookies = []
131
+ for (const part of String(cookieHeader || '').split(';')) {
132
+ const idx = part.indexOf('=')
133
+ if (idx <= 0) continue
134
+ const name = part.slice(0, idx).trim()
135
+ const value = part.slice(idx + 1).trim()
136
+ if (!name) continue
137
+ cookies.push({ name, value, domain, path: '/', secure: false, httpOnly: false, sameSite: 'None' })
138
+ }
139
+ return cookies
140
+ }
141
+
142
+ /** 页面内取值:返回 { status, pos, end, title, artist, songId, liked, playing }。
143
+ * 用户手动在网页放歌时是「打开客户端播放」模式——没有 <audio>、时间栏 00:00,
144
+ * 但 window.player.getPlaying().track 带着完整元数据(歌名/id/歌手/时长/playing),
145
+ * 这是识别当前歌曲最可靠的数据源。DOM 标题常是「网易云音乐」,只做兜底。 */
146
+ const READ_STATE_EXPR = `(() => {
147
+ const a = document.getElementById(${JSON.stringify(AUDIO_ID)})
148
+ const gp = (window.player && typeof window.player.getPlaying === 'function')
149
+ ? window.player.getPlaying() : null
150
+ const rawTrack = gp ? gp.track : null
151
+ // getPlaying().track 有两种形态:完整对象 {id,name,artists...} 或裸数字 songId。
152
+ const track = rawTrack && typeof rawTrack === 'object' ? rawTrack : null
153
+ const trackId = track ? (track.id || '') : (typeof rawTrack === 'number' ? rawTrack : '')
154
+ const titleEl = document.querySelector('.m-playbar .title, .m-playbar .name, .m-playbar .j-title')
155
+ const artistEl = document.querySelector('.m-playbar .artist, .m-playbar .s-fc4, .m-playbar .j-artist')
156
+ const statusEl = document.querySelector('.m-playbar .ply, .m-playbar .play')
157
+ const isPlaying = !!(a && !a.paused && !a.ended) ||
158
+ !!(gp && gp.playing === true) ||
159
+ !!(statusEl && (statusEl.classList.contains('ply') === false))
160
+ // 进度:<audio> 为准;用户手动放歌无 audio 时退到 getPlaying().track.position(秒),再退 0。
161
+ const posMs = a ? Math.round((a.currentTime || 0) * 1000)
162
+ : (track && Number(track.position) > 0 ? Math.round(Number(track.position) * 1000) : 0)
163
+ const endMs = a ? Math.round((a.duration || 0) * 1000)
164
+ : (track && Number(track.duration) > 0 ? Math.round(Number(track.duration)) : 0)
165
+ const artists = track && Array.isArray(track.artists)
166
+ ? track.artists.map((x) => (x && x.name) || '').filter(Boolean).join(' / ') : ''
167
+ return {
168
+ status: isPlaying ? 'Playing' : 'Paused',
169
+ pos: posMs,
170
+ end: endMs,
171
+ title: (track && track.name) || (titleEl && titleEl.textContent || '').trim(),
172
+ artist: artists || (artistEl && artistEl.textContent || '').trim(),
173
+ songId: String(trackId || ''),
174
+ liked: null,
175
+ hasAudio: !!a,
176
+ audioReady: a ? a.readyState : 0,
177
+ // audio 自己在放哪首:注入时写在 dataset 上。页面手动点的那首和插件接管的那首
178
+ // 常常不是同一首,state() 必须按这个 id 取元数据,否则歌名/时长会张冠李戴。
179
+ audioSongId: a ? String(a.dataset && a.dataset.songId || '') : '',
180
+ pageTitle: document.title || '',
181
+ }
182
+ })()`
183
+
184
+ export class WebBackend {
185
+ /**
186
+ * @param {{ getConfig?: () => any, log?: (msg:string)=>void,
187
+ * daily?: import('./daily.mjs').DailyService }} deps
188
+ */
189
+ constructor(deps = {}) {
190
+ this.getConfig = typeof deps.getConfig === 'function' ? deps.getConfig : () => ({})
191
+ this.log = typeof deps.log === 'function' ? deps.log : () => {}
192
+ this.daily = deps.daily || null
193
+ // 日推出声引擎:WinRT MediaPlayer 常驻后台进程(无窗口、不弹页、不依赖 CDP/ego)。
194
+ // 只有 Windows 才建真实实例;测试可注入 mock。ego 关着、个人 Edge 无 CDP 时,
195
+ // 日推靠它精确播指定曲目;个人 Edge 手动放歌仍走 SMTC(互不干扰)。
196
+ this.winrtAudio = deps.winrtAudio || (process.platform === 'win32'
197
+ ? new WinrtAudio({ getConfig: this.getConfig, log: this.log })
198
+ : null)
199
+ this.winrtPlaying = false // 日推引擎是否占用当前播放
200
+ this.winrtSong = null // 引擎当前曲目 { id, name, artist }
201
+ // 可注入 CDP 工厂(测试用):默认用真实 CdpClient。
202
+ this._cdpFactory = typeof deps.cdpFactory === 'function' ? deps.cdpFactory : ((wsUrl) => new CdpClient(wsUrl))
203
+ // SMTC 回退:ego-lite 的网页是「去客户端播放」占位,用户真正在放的歌在个人 Edge
204
+ // (无 CDP 端口),只能靠系统媒体会话读到。可注入测试。
205
+ this.smtc = deps.smtc || new SmtcBrowser({ getConfig: this.getConfig, log: this.log })
206
+ // 本次 state 实际采用的数据源:'cdp'(插件自己的 audio / 网页队列)或 'smtc'(个人浏览器媒体会话)
207
+ this.dataSource = 'cdp'
208
+ this.smtcState = null
209
+ this.id = 'web-cdp'
210
+ this.platform = 'web'
211
+ this.reason = ''
212
+ this.capabilities = { playback: true, sessionVolume: true, systemVolume: false, lyrics: true, web: true }
213
+ // 播放队列:daily 取数后的 id 列表;当前曲目索引;正在播放的音频 URL 缓存
214
+ this.queue = []
215
+ this.queueIndex = -1
216
+ // 播放顺序(内部枚举)。set_mode 会改它,next/prev/自动切歌按它决定走向,
217
+ // state().now.mode 回它给前端切图标。persist 到配置以便重启后保持。
218
+ this.mode = MODE_ENUM_DEFAULT
219
+ this.audioUrlCache = new Map() // songId -> { url, at }
220
+ this.songMetaCache = new Map() // songId -> { name, artist, durationMs, at };数字 track 时按 id 补元数据
221
+ this.cdp = null
222
+ this.sessionId = null
223
+ this.injectedCookies = false
224
+ this.lastError = ''
225
+ this.volumeLevel = 0.8
226
+ this.muted = false
227
+ // 用户在网页里手动点的那首(getPlaying().track 给的裸 songId)。
228
+ // 网页播放器已被网易云阉割成「去客户端播放」,页面里没有 <audio>,
229
+ // 所以要把这首接管过来:用 Host 侧 cookie 取 URL,在同一个页面注入 <audio>。
230
+ this.manualSongId = ''
231
+ // 喜欢(红心):网页版没有客户端 CEF cookie,用一个改用浏览器/手填 cookie 的
232
+ // LikeService 实例;cookie 来源统一走 _cookieForApi()(手填 > 客户端解出 > 浏览器)。
233
+ // 可注入测试。上层 client.js 只读 now.liked,无需知道走的是哪个实例。
234
+ this.likeWeb = deps.likeWeb || new LikeService({
235
+ getConfig: this.getConfig,
236
+ log: this.log,
237
+ cookieLoader: async () => {
238
+ // 网页版通道优先用浏览器已登录会话(个人 Edge / ego 都可能是登录源);
239
+ // 拿不到再退到手填 cookie / 客户端解出的 cookie。
240
+ try {
241
+ const bc = await this._browserCookies()
242
+ if (bc.hasLogin && bc.header) return { ok: true, cookie: bc.header }
243
+ } catch { /* fallthrough */ }
244
+ const cookie = await this._cookieForApi()
245
+ return cookie ? { ok: true, cookie } : { ok: false, error: 'cookie-missing' }
246
+ },
247
+ })
248
+ // state() 里 liked 查询的节流(参照 player.mjs:485-517):切歌即查,否则 likeSyncMs 一次
249
+ this.likedForSong = ''
250
+ this.likedCheckedAt = 0
251
+ this.likedFailAt = 0
252
+ // title+artist -> songId 搜索缓存(SMTC 场景没有 songId,按歌名搜),60 分钟
253
+ this.songSearchCache = new Map()
254
+ // 系统音量:Windows 端点级、与播放通道无关。复用 native PlayerService 的
255
+ // helper(不依赖客户端进程)。注入后自动把 capabilities.systemVolume 打开,
256
+ // 让 web 通道也能读/写系统音量、跟随系统。
257
+ let _svc = deps.systemVolumeService || null
258
+ Object.defineProperty(this, 'systemVolumeService', {
259
+ configurable: true,
260
+ get() { return _svc },
261
+ set(v) {
262
+ _svc = v
263
+ this.capabilities.systemVolume = !!(v && process.platform === 'win32')
264
+ },
265
+ })
266
+ this.capabilities.systemVolume = !!(_svc && process.platform === 'win32')
267
+ }
268
+
269
+ /** 系统音量能力是否可用(注入了 native helper 且在 Windows)。 */
270
+ _hasSystemVolume() {
271
+ return !!(this.systemVolumeService && process.platform === 'win32')
272
+ }
273
+
274
+ /** 读系统音量读数,失败返回 null(不影响 state 其它字段)。 */
275
+ async _readSystemVolume() {
276
+ if (!this._hasSystemVolume()) return null
277
+ try {
278
+ // 不强制 fresh:native state 自带 400ms 缓存,系统音量低频变化,够用且省一次 helper 往返。
279
+ const st = await this.systemVolumeService.state({})
280
+ return st?.systemVolume || st?.volume || null
281
+ } catch { return null }
282
+ }
283
+
284
+ _cfg() {
285
+ const c = this.getConfig() || {}
286
+ return {
287
+ webBrowserJson: String(c.webBrowserJson || ''),
288
+ webLoginCookie: String(c.webLoginCookie || ''),
289
+ webAutoInjectCookie: c.webAutoInjectCookie !== false,
290
+ webSongUrlApi: String(c.webSongUrlApi || SONG_URL_API),
291
+ webSongUrlLevel: String(c.webSongUrlLevel || 'standard'),
292
+ requestTimeoutMs: Number(c.requestTimeoutMs) > 0 ? Number(c.requestTimeoutMs) : 6000,
293
+ }
294
+ }
295
+
296
+ /**
297
+ * 数字形态的 getPlaying().track(只有一个 songId)时,按 id 从页面内同源
298
+ * /api/song/detail 补歌名/歌手/时长。60 分钟缓存。失败返回 null,调用方用占位。
299
+ */
300
+ async _songMeta(songId) {
301
+ const id = String(songId || '')
302
+ if (!id || id === 'undefined') return null
303
+ const hit = this.songMetaCache.get(id)
304
+ if (hit && Date.now() - hit.at < 60 * 60 * 1000) return hit.meta
305
+ try {
306
+ const raw = await this._eval(`(async () => {
307
+ try {
308
+ const r = await fetch('/api/song/detail?ids=[${id}]', { credentials: 'include' })
309
+ const j = await r.json()
310
+ const s = (j.songs && j.songs[0]) || null
311
+ if (!s) return null
312
+ return JSON.stringify({
313
+ name: s.name || '',
314
+ artist: (s.artists || []).map((a) => a.name).filter(Boolean).join(' / '),
315
+ durationMs: Number(s.duration) || 0,
316
+ })
317
+ } catch (e) { return null }
318
+ })()`)
319
+ const meta = raw ? JSON.parse(raw) : null
320
+ if (meta && meta.name) {
321
+ this.songMetaCache.set(id, { meta, at: Date.now() })
322
+ return meta
323
+ }
324
+ } catch { /* 取不到就返回 null */ }
325
+ return null
326
+ }
327
+
328
+ /** 是否支持播放(后端抽象要求) */
329
+ supported() { return true }
330
+
331
+ /** 建立 CDP 连接、复用已打开的 music.163.com 页面、注入登录 cookie。幂等。
332
+ * 绝不新建浏览器窗口/标签:用户没打开网页版时返回可读错误。 */
333
+ async ensure() {
334
+ // 连接还在就复用;浏览器重启后旧 ws 会关闭,必须丢弃重建。
335
+ if (this.cdp && this.cdp.isAlive?.() && this.sessionId) {
336
+ this.lastError = ''
337
+ return { ok: true }
338
+ }
339
+ // 浏览器重启瞬间会重写 browser.json,这里重试几次,避免偶发 ENOENT 挂成陈旧错误。
340
+ const cfg = this._cfg()
341
+ let ec
342
+ for (let i = 0; i < 4; i++) {
343
+ ec = readEgoConfig(cfg.webBrowserJson)
344
+ if (!ec.error) break
345
+ await new Promise((r) => setTimeout(r, 200))
346
+ }
347
+ if (ec.error) return this._fail('web-browser-unavailable', ec.error)
348
+ try {
349
+ const cdp = this._cdpFactory(ec.wsUrl)
350
+ await cdp.connect()
351
+ // 只复用用户已经打开的网易云页面。找不到就报错,绝不 Target.createTarget——
352
+ // 那会弹出一个新浏览器窗口,正是"点重试弹新窗口"的根因。
353
+ const targets = await cdp.cmd('Target.getTargets')
354
+ let page = (targets.targetInfos || []).find(
355
+ (t) => t.type === 'page' && String(t.url || '').includes(PAGE_TARGET_HINT),
356
+ )
357
+ if (!page) {
358
+ cdp.close()
359
+ return this._fail('web-page-not-found', '没有找到已打开的 music.163.com 页面')
360
+ }
361
+ const attached = await cdp.cmd('Target.attachToTarget', { targetId: page.targetId, flatten: true })
362
+ const sessionId = attached.sessionId
363
+ this.cdp = cdp
364
+ this.sessionId = sessionId
365
+ // 等页面加载出来
366
+ await this._eval('document.readyState', sessionId).catch(() => {})
367
+
368
+ // 用户可能已在网页里登录、甚至正在放歌。此时绝不能注入 cookie / reload——
369
+ // 那样会打断播放、把当前歌曲清掉。已登录或已读到正在播的歌,直接复用现状。
370
+ let alreadyPlaying = false
371
+ try {
372
+ const s = await this._eval(READ_STATE_EXPR, sessionId)
373
+ alreadyPlaying = !!(s && (
374
+ (s.songId && s.songId !== 'undefined') ||
375
+ (s.title && s.title !== '网易云音乐')
376
+ ))
377
+ } catch { /* 读不到就按没在播处理 */ }
378
+ const browserLoggedIn = (await this._browserCookies()).hasLogin
379
+ // 连上了、页面也在,旧错误就该清掉,免得 health 一直挂着 ENOENT。
380
+ this.lastError = ''
381
+ if (alreadyPlaying || browserLoggedIn) return { ok: true }
382
+
383
+ // 浏览器没登录:注入手填 / 客户端解出的 cookie,reload 一次让登录态生效
384
+ let cookie = cfg.webLoginCookie
385
+ if (!cookie && cfg.webAutoInjectCookie) {
386
+ try {
387
+ const got = await loadCookieHeader({})
388
+ if (got?.ok && got.cookie) cookie = got.cookie
389
+ } catch (err) {
390
+ this.log(`web: loadCookieHeader failed: ${String(err?.message || err)}`)
391
+ }
392
+ }
393
+ if (cookie) {
394
+ await cdp.cmd('Storage.setCookies', { cookies: cookieHeaderToCdp(cookie) })
395
+ this.injectedCookies = true
396
+ await cdp.cmd('Page.reload', { ignoreCache: false }, sessionId).catch(() => {})
397
+ await this._waitReady(sessionId)
398
+ }
399
+ return { ok: true }
400
+ } catch (err) {
401
+ return this._fail('web-cdp-error', String(err?.message || err))
402
+ }
403
+ }
404
+
405
+ async _waitReady(sessionId) {
406
+ for (let i = 0; i < 10; i++) {
407
+ try {
408
+ const s = await this._eval('document.readyState', sessionId)
409
+ if (s === 'complete' || s === 'interactive') return
410
+ } catch { /* not ready yet */ }
411
+ await new Promise((r) => setTimeout(r, 300))
412
+ }
413
+ }
414
+
415
+ async _eval(expression, sessionId = this.sessionId) {
416
+ const r = await this.cdp.cmd('Runtime.evaluate', {
417
+ expression,
418
+ returnByValue: true,
419
+ awaitPromise: true,
420
+ userGesture: true,
421
+ }, sessionId)
422
+ if (r.exceptionDetails) {
423
+ const e = r.exceptionDetails.exception?.description || r.exceptionDetails.text || 'eval error'
424
+ throw new Error(e)
425
+ }
426
+ return r.result?.value
427
+ }
428
+
429
+ _fail(error, detail) {
430
+ this.lastError = detail || error
431
+ return { ok: false, error, message: this._message(error), detail: detail || '' }
432
+ }
433
+
434
+ _message(error) {
435
+ const map = {
436
+ 'web-browser-unavailable': '网页版通道不可用:没有找到 ego 浏览器,请先打开浏览器并登录网易云网页版',
437
+ 'web-page-not-found': '网易云网页版页面未打开,请先在浏览器里打开 music.163.com(插件不会替你新开窗口)',
438
+ 'web-cdp-error': '网页版通道出错:无法连接或操作浏览器',
439
+ 'web-not-logged-in': '网易云网页版尚未登录,请先在浏览器里登录(或确保本机客户端已登录以复用 cookie)',
440
+ 'web-no-audio-url': '这首歌暂时拿不到播放地址(可能无版权或需 VIP),换一首试试',
441
+ 'web-no-song': '当前没有可播放的歌曲',
442
+ 'web-action-failed': '网页版播放动作执行失败',
443
+ }
444
+ return map[error] || '网页版通道出错'
445
+ }
446
+
447
+ /**
448
+ * 读浏览器完整 cookie(含 httpOnly 的 MUSIC_U)——必须在 browser-level CDP
449
+ * 连接上发 Storage.getCookies,document.cookie 读不到 httpOnly。
450
+ * @returns {Promise<{header:string, hasLogin:boolean}>}
451
+ */
452
+ async _browserCookies() {
453
+ try {
454
+ const res = await this.cdp.cmd('Storage.getCookies', {})
455
+ const list = (res?.cookies || []).filter((c) => String(c.domain || '').includes('music.163.com'))
456
+ const header = list.map((c) => `${c.name}=${c.value}`).join('; ')
457
+ const hasLogin = list.some((c) => c.name === 'MUSIC_U' && c.value && c.value.length > 6)
458
+ return { header, hasLogin }
459
+ } catch {
460
+ return { header: '', hasLogin: false }
461
+ }
462
+ }
463
+
464
+ /** 登录态探测:浏览器 cookie 有 MUSIC_U,或页面有昵称,即视为已登录。 */
465
+ async _isLoggedIn() {
466
+ const bc = await this._browserCookies()
467
+ if (bc.hasLogin) return true
468
+ try {
469
+ const r = await this._eval(`(() => {
470
+ const nickEl = document.querySelector('.m-tophead .name, .m-tophead .u-name, .head .name, .m-tophead a')
471
+ const nick = nickEl ? (nickEl.textContent || '').trim() : ''
472
+ const loginBtn = document.querySelector('.m-tophead .u-login, .m-tophead .login, a[href*="/login"]')
473
+ return { nick: !!nick, hasLoginBtn: !!loginBtn }
474
+ })()`)
475
+ if (r && r.nick && !r.hasLoginBtn) return true
476
+ // 页面还没渲染出用户态但 httpOnly cookie 在,也算登录
477
+ return bc.hasLogin
478
+ } catch {
479
+ return bc.hasLogin
480
+ }
481
+ }
482
+
483
+ /** 供 API 调用取 cookie:手填 > 客户端解出 > 浏览器完整 cookie。 */
484
+ async _cookieForApi() {
485
+ const cfg = this._cfg()
486
+ if (cfg.webLoginCookie) return cfg.webLoginCookie
487
+ try {
488
+ const got = await loadCookieHeader({})
489
+ if (got?.ok && got.cookie) return got.cookie
490
+ } catch { /* fallthrough */ }
491
+ const bc = await this._browserCookies()
492
+ return bc.header
493
+ }
494
+
495
+ /** 明文拿歌曲播放 URL(实测 /api/song/enhance/player/url/v1 + cookie 即可,无需 weapi 加密)。 */
496
+ async _songUrl(songId) {
497
+ if (!songId) return this._fail('web-no-song', '')
498
+ const cfg = this._cfg()
499
+ const cached = this.audioUrlCache.get(String(songId))
500
+ if (cached && Date.now() - cached.at < 30 * 60 * 1000) return { ok: true, url: cached.url }
501
+ const cookie = await this._cookieForApi()
502
+ const body = new URLSearchParams({
503
+ ids: JSON.stringify([Number(songId)]),
504
+ level: cfg.webSongUrlLevel,
505
+ encodeType: 'aac',
506
+ })
507
+ let parsed
508
+ try {
509
+ const res = await fetch(cfg.webSongUrlApi, {
510
+ method: 'POST',
511
+ headers: {
512
+ 'Content-Type': 'application/x-www-form-urlencoded',
513
+ Referer: MUSIC_ORIGIN + '/',
514
+ 'User-Agent': UA,
515
+ Cookie: cookie,
516
+ },
517
+ body: body.toString(),
518
+ signal: AbortSignal.timeout(cfg.requestTimeoutMs),
519
+ })
520
+ const text = await res.text()
521
+ parsed = JSON.parse(text)
522
+ } catch (err) {
523
+ return this._fail('web-no-audio-url', String(err?.message || err))
524
+ }
525
+ const info = Array.isArray(parsed?.data) ? parsed.data[0] : null
526
+ const url = info && info.url ? String(info.url) : ''
527
+ if (!url) return this._fail('web-no-audio-url', `code=${parsed?.code} ${info?.message || ''}`)
528
+ this.audioUrlCache.set(String(songId), { url, at: Date.now() })
529
+ return { ok: true, url }
530
+ }
531
+
532
+ /** 在页面里注入/复用 <audio>,加载指定 URL 并播放。 */
533
+ async _playUrl(url, { positionMs = 0, songId = '' } = {}) {
534
+ const expr = `(() => {
535
+ let a = document.getElementById(${JSON.stringify(AUDIO_ID)})
536
+ if (!a) {
537
+ a = document.createElement('audio')
538
+ a.id = ${JSON.stringify(AUDIO_ID)}
539
+ a.style.display = 'none'
540
+ document.body.appendChild(a)
541
+ }
542
+ if (${JSON.stringify(String(songId))}) a.dataset.songId = ${JSON.stringify(String(songId))}
543
+ a.src = ${JSON.stringify(url)}
544
+ a.volume = ${Number(this.volumeLevel)}
545
+ a.muted = ${this.muted ? 'true' : 'false'}
546
+ a.load()
547
+ const p = a.play()
548
+ if (p && typeof p.catch === 'function') p.catch(() => {})
549
+ if (${Number(positionMs)} > 0) {
550
+ const seek = () => { try { a.currentTime = ${Number(positionMs)} / 1000 } catch (e) {} }
551
+ if (a.readyState >= 1) seek(); else a.addEventListener('loadedmetadata', seek, { once: true })
552
+ }
553
+ return { paused: a.paused, readyState: a.readyState }
554
+ })()`
555
+ return await this._eval(expr)
556
+ }
557
+
558
+ async _controlAudio(method, arg) {
559
+ const call = {
560
+ play: `(() => { const a=document.getElementById(${JSON.stringify(AUDIO_ID)}); if(!a) return false; const p=a.play(); if(p&&p.catch)p.catch(()=>{}); return true })()`,
561
+ pause: `(() => { const a=document.getElementById(${JSON.stringify(AUDIO_ID)}); if(!a) return false; a.pause(); return true })()`,
562
+ next: null,
563
+ prev: null,
564
+ seek: `(() => { const a=document.getElementById(${JSON.stringify(AUDIO_ID)}); if(a){a.currentTime=${Number(arg)}/1000} return !!a })()`,
565
+ }[method]
566
+ if (call) return await this._eval(call)
567
+ return false
568
+ }
569
+
570
+ /** 播放「网页里手动点的那首」。
571
+ * 网易云网页版已把播放器改成「去客户端播放」占位,页面里根本没有 <audio>,
572
+ * window.player.addTo() 也只是空转。所以手动点播的歌要由插件接管:
573
+ * 用它给的 songId 走 Host 侧 cookie 取真实音频 URL,在同一个页面注入 <audio> 播放。
574
+ * 这样 play/pause/seek 对「手动点的歌」也生效,进度也才开始走。 */
575
+ async _playManual() {
576
+ const s = await this._eval(READ_STATE_EXPR).catch(() => null)
577
+ const songId = String(s?.songId || this.manualSongId || '')
578
+ if (!songId || songId === 'undefined') return this._fail('web-no-song', '')
579
+ this.manualSongId = songId
580
+ // 已经在放这首:别重新 load,那会把进度打回 0。
581
+ // 但「在放」得是同一首——页面手动切歌后 audio 还停在上一首,必须换。
582
+ const cur = await this._eval(`(() => {
583
+ const a = document.getElementById(${JSON.stringify(AUDIO_ID)})
584
+ if (!a) return 'none'
585
+ const same = String(a.dataset && a.dataset.songId || '') === ${JSON.stringify(songId)}
586
+ if (!same) return 'other'
587
+ if (!a.paused && !a.ended) return 'playing'
588
+ return a.readyState >= 1 ? 'paused' : 'empty'
589
+ })()`).catch(() => 'none')
590
+ if (cur === 'playing') return { ok: true, songId, reused: true }
591
+ if (cur === 'paused') {
592
+ const r = await this._controlAudio('play')
593
+ if (r !== false) return { ok: true, songId, resumed: true }
594
+ }
595
+ const got = await this._songUrl(songId)
596
+ if (!got.ok) return got
597
+ const r = await this._playUrl(got.url, { songId })
598
+ return { ok: true, songId, url: got.url, audio: r }
599
+ }
600
+
601
+ /** 暂停任意一路:优先插件自己的 <audio>;没有 audio(从没让插件播过)就退到
602
+ * 页面播放器 window.player.pause(),让「手动点的歌」也能被暂停。 */
603
+ async _pauseAny() {
604
+ const r = await this._controlAudio('pause').catch(() => false)
605
+ if (r !== false) return { ok: true, via: 'audio' }
606
+ try {
607
+ await this._eval(`(() => { try { window.player && window.player.pause && window.player.pause() } catch (e) {} return true })()`)
608
+ return { ok: true, via: 'page-player' }
609
+ } catch (err) {
610
+ return this._fail('web-action-failed', String(err?.message || err))
611
+ }
612
+ }
613
+
614
+ /** 播放队列里的第 idx 首(取 URL → 注入 audio → 播放)。 */
615
+ async _playQueueIndex(idx) {
616
+ if (idx < 0 || idx >= this.queue.length) return this._fail('web-no-song', '')
617
+ const song = this.queue[idx]
618
+ const id = song?.id || song?.songId
619
+ const got = await this._songUrl(id)
620
+ if (!got.ok) return got
621
+ this.queueIndex = idx
622
+ const r = await this._playUrl(got.url, { songId: id })
623
+ // 用播放器 DOM 标题兜底:让悬浮框即使拿不到 api 元数据也有东西显示
624
+ try { await this._eval(`window.player && window.player.addTo && window.player.addTo([${Number(id)}])`) } catch { /* ignore */ }
625
+ return { ok: true, url: got.url, audio: r, song }
626
+ }
627
+
628
+ /**
629
+ * 按当前播放顺序算「下一首/上一首」的目标索引。
630
+ * - order 顺序:到头就停在边界(返回 null 表示没有下一首);
631
+ * - cycle 列表循环:越界回环;
632
+ * - single 单曲循环:原地不动;
633
+ * - random 随机:换一首不同的(列表只有 1 首则原地)。
634
+ * delta = +1 下一首 / -1 上一首。
635
+ */
636
+ _advanceIndex(delta = 1) {
637
+ const n = this.queue.length
638
+ if (!n) return null
639
+ const cur = this.queueIndex >= 0 ? this.queueIndex : 0
640
+ switch (this.mode) {
641
+ case 'playOneCycle':
642
+ return cur
643
+ case 'playRandom': {
644
+ if (n <= 1) return 0
645
+ let next = cur
646
+ while (next === cur) next = Math.floor(Math.random() * n)
647
+ return next
648
+ }
649
+ case 'playOrder': {
650
+ const to = cur + delta
651
+ return to >= 0 && to < n ? to : null
652
+ }
653
+ case 'playCycle':
654
+ default:
655
+ return (cur + delta + n) % n
656
+ }
657
+ }
658
+
659
+ // ---------------------------------------------------------------- 后端接口
660
+
661
+ /** SMTC 是否启用(配置默认开)。 */
662
+ _smtcEnabled() {
663
+ try { return this.getConfig().smtcEnabled !== false } catch { return true }
664
+ }
665
+
666
+ /** 喜欢状态查询的节流窗口(ms),与原生 likeSyncMs 同源。 */
667
+ _likeSyncMs() {
668
+ try {
669
+ const v = Number(this.getConfig().likeSyncMs)
670
+ if (v > 0) return v
671
+ } catch { /* fallthrough */ }
672
+ return 8000
673
+ }
674
+
675
+ /**
676
+ * 带节流的 liked 查询:切歌必查,否则 likeSyncMs 一次;失败 15s 退避。
677
+ * 返回 true/false(已喜欢/未喜欢)或 null(查不到,前端按空心处理)。
678
+ */
679
+ async _likedFor(songId) {
680
+ const id = String(songId || '')
681
+ if (!id || id === '0' || id === 'undefined' || id === 'NaN') return null
682
+ try {
683
+ const nowMs = Date.now()
684
+ const changed = this.likedForSong !== id
685
+ const due = nowMs - this.likedCheckedAt >= this._likeSyncMs()
686
+ const retryOk = !this.likedFailAt || nowMs - this.likedFailAt >= 15000
687
+ if (changed || (due && retryOk)) {
688
+ const res = await this.likeWeb.isLiked(id, { force: true })
689
+ this.likedForSong = id
690
+ this.likedCheckedAt = nowMs
691
+ if (res && res.ok) {
692
+ this.likedFailAt = 0
693
+ return !!res.liked
694
+ }
695
+ this.likedFailAt = nowMs
696
+ return null
697
+ }
698
+ const cached = this.likeWeb.cache?.get(id)
699
+ return cached ? !!cached.liked : null
700
+ } catch {
701
+ return null
702
+ }
703
+ }
704
+
705
+ /** 把 liked 字段挂到 state 的 now 上(前端红心只读这个字段)。 */
706
+ async _attachLiked(now, songId) {
707
+ if (!now) return now
708
+ now.liked = await this._likedFor(songId)
709
+ return now
710
+ }
711
+
712
+ /**
713
+ * SMTC 场景没有 songId 时,按 title+artist 在页面内同源搜一首最像的。
714
+ * 60 分钟缓存;搜不到返回 ''(上层 liked 显示 null、like 动作返回 like-no-song)。
715
+ */
716
+ async _songIdBySearch(title, artist) {
717
+ const t = String(title || '').trim()
718
+ if (!t) return ''
719
+ const key = `${t}|${String(artist || '').trim()}`
720
+ const hit = this.songSearchCache.get(key)
721
+ if (hit && Date.now() - hit.at < 60 * 60 * 1000) return hit.id
722
+ const q = String(artist || '').trim() ? `${t} ${String(artist).trim()}` : t
723
+ const norm = (x) => String(x || '').toLowerCase().replace(/[^\p{L}\p{N}]/gu, '')
724
+ const want = norm(t)
725
+ const pick = (songs) => {
726
+ if (!Array.isArray(songs) || !songs.length) return ''
727
+ const match = songs.find((s) => norm(s.name) === want) || songs[0]
728
+ return match && match.id ? String(match.id) : ''
729
+ }
730
+ const save = (id) => { this.songSearchCache.set(key, { id, at: Date.now() }); return id }
731
+ // 1) CDP 页面内同源 fetch(ego 浏览器开着、music 页在时最稳,带页面登录态)
732
+ try {
733
+ const raw = await this._eval(`(async () => {
734
+ try {
735
+ const r = await fetch('/api/search/get?s=' + encodeURIComponent(${JSON.stringify(q)}) + '&type=1&limit=8', { credentials: 'include' })
736
+ const j = await r.json()
737
+ return JSON.stringify((j.result && j.result.songs) || [])
738
+ } catch (e) { return '[]' }
739
+ })()`)
740
+ const id = pick(raw ? JSON.parse(raw) : [])
741
+ if (id) return save(id)
742
+ } catch { /* 浏览器/CDP 没开 → 走 Node 侧兜底 */ }
743
+ // 2) Node 侧明文 fetch:ego 浏览器关了、CDP 断了也能搜。SMTC 场景红心与
744
+ // 「喜欢」都依赖这个 songId,不能因为 agent 浏览器没开就失效。
745
+ try {
746
+ const cfg = this._cfg()
747
+ const cookie = await this._cookieForApi()
748
+ const url = `${MUSIC_ORIGIN}/api/search/get?s=${encodeURIComponent(q)}&type=1&limit=8`
749
+ const res = await fetch(url, {
750
+ headers: { Referer: MUSIC_ORIGIN + '/', 'User-Agent': UA, Cookie: cookie },
751
+ signal: AbortSignal.timeout(cfg.requestTimeoutMs),
752
+ })
753
+ const j = JSON.parse(await res.text())
754
+ const id = pick((j?.result && j.result.songs) || [])
755
+ if (id) return save(id)
756
+ } catch { /* fallthrough */ }
757
+ return ''
758
+ }
759
+
760
+ /** 视频站标题兜底:即便 probe 因会话顺序漏判,Node 层也拒接视频页。 */
761
+ _isVideoTitle(title) {
762
+ const t = String(title || '').toLowerCase()
763
+ return ['bilibili', 'youtube', 'youtu.be', 'acfun', 'nicovideo'].some((m) => t.includes(m))
764
+ }
765
+
766
+ /** 把 SMTC 会话包装成与原生一致的 state 返回形状。 */
767
+ _smtcResult(sm) {
768
+ const status = /playing/i.test(String(sm.status || '')) ? 'Playing' : 'Paused'
769
+ const now = {
770
+ aumid: sm.aumid || 'msedge.exe',
771
+ title: sm.title || '',
772
+ artist: sm.artist || '',
773
+ album: sm.album || '',
774
+ songId: '',
775
+ status,
776
+ pos: Number(sm.pos) || 0,
777
+ end: Number(sm.end) || 0,
778
+ start: 0,
779
+ positionSource: 'smtc-web',
780
+ canPlay: sm.canPlay !== false,
781
+ canPause: sm.canPause !== false,
782
+ canNext: sm.canNext !== false,
783
+ canPrev: sm.canPrev !== false,
784
+ canSeek: sm.canSeek !== false,
785
+ channel: 'web',
786
+ mode: this.mode,
787
+ }
788
+ return {
789
+ ok: true,
790
+ now,
791
+ volume: { level: this.volumeLevel, muted: this.muted, scope: 'process' },
792
+ systemVolume: null,
793
+ sessions: [],
794
+ winrt: true,
795
+ helper: {
796
+ healthy: true, ready: true, backend: 'smtc-browser', platform: 'web',
797
+ capabilities: this.capabilities, degraded: '',
798
+ },
799
+ serverTime: Date.now(),
800
+ }
801
+ }
802
+
803
+ /**
804
+ * 日推引擎(WinRT MediaPlayer)在播时,状态直接从引擎读——它不进 SMTC、也不在
805
+ * 网页 DOM 里,CDP/SMTC 两条路都读不到它。返回的 now 形状与原生一致。
806
+ */
807
+ _winrtResult(st) {
808
+ const song = this.winrtSong || {}
809
+ const songId = String(st.songId || song.id || '')
810
+ const status = (st.status === 'Playing' || st.status === 'Opening') ? 'Playing' : 'Paused'
811
+ const now = {
812
+ aumid: 'winrt',
813
+ title: String(st.title || song.name || ''),
814
+ artist: String(st.artist || song.artist || ''),
815
+ album: '',
816
+ songId,
817
+ status,
818
+ pos: Number(st.pos) || 0,
819
+ end: Number(st.end) || 0,
820
+ start: 0,
821
+ positionSource: 'winrt',
822
+ canPlay: true,
823
+ canPause: true,
824
+ canNext: this.queue.length > 0,
825
+ canPrev: this.queue.length > 0,
826
+ canSeek: true,
827
+ channel: 'web',
828
+ mode: this.mode,
829
+ }
830
+ return {
831
+ ok: true,
832
+ now,
833
+ volume: { level: Number(st.volume) || this.volumeLevel, muted: !!st.muted, scope: 'process' },
834
+ sessions: [],
835
+ winrt: true,
836
+ helper: {
837
+ healthy: true, ready: true, backend: 'winrt-mediaplayer', platform: 'web',
838
+ capabilities: this.capabilities, degraded: '',
839
+ },
840
+ serverTime: Date.now(),
841
+ }
842
+ }
843
+
844
+ /** state:返回与原生后端一致的形状。 */
845
+ async state() {
846
+ // 日推引擎正在播时优先读它(零 CDP、零 SMTC spawn)。引擎在 SMTC 里看不见,
847
+ // 若这时落回下面的 SMTC 分支会把「个人 Edge 里暂停的歌」当成当前曲,错。
848
+ if (this.winrtPlaying && this.winrtAudio) {
849
+ const st = await this.winrtAudio.state().catch(() => null)
850
+ if (st && st.ok && st.active !== false) {
851
+ const result = this._winrtResult(st)
852
+ result.systemVolume = await this._readSystemVolume()
853
+ await this._attachLiked(result.now, result.now.songId)
854
+ return result
855
+ }
856
+ }
857
+ const ready = await this.ensure()
858
+ let s = null
859
+ if (ready.ok) {
860
+ try { s = await this._eval(READ_STATE_EXPR) } catch { s = null }
861
+ }
862
+ // ego-lite 网页是「去客户端播放」占位:getPlaying().track 只是残留态、页面无 <audio>。
863
+ // 用户真正在放的歌在个人 Edge(无 CDP 端口)——只要 CDP 没有真实在播的 audio,
864
+ // 就用 SMTC 系统媒体会话读标题/歌手/进度,这样才识别得到用户点的那首。
865
+ const cdpReal = !!(s && s.hasAudio && s.status === 'Playing')
866
+ if (!cdpReal && this._smtcEnabled()) {
867
+ const sm = await this.smtc.readState().catch(() => null)
868
+ if (sm && sm.ok && sm.title && !sm.artist && this._isVideoTitle(sm.title)) {
869
+ // probe 已尽力排除视频标题;这里挡住任何穿透到 Node 层的视频会话(artist 空 + 站点标记)。
870
+ } else if (sm && sm.ok && sm.title) {
871
+ this.dataSource = 'smtc'
872
+ this.smtcState = sm
873
+ const result = this._smtcResult(sm)
874
+ // SYS 读数与播放通道无关:从 native helper 读真实系统音量,让 SYS 能跟随系统
875
+ result.systemVolume = await this._readSystemVolume()
876
+ // 媒体会话不带 songId:按歌名+歌手搜一首(带缓存),这样红心能读/能点。
877
+ const sid = await this._songIdBySearch(sm.title, sm.artist)
878
+ if (sid) result.now.songId = sid
879
+ await this._attachLiked(result.now, sid)
880
+ return result
881
+ }
882
+ }
883
+ this.dataSource = 'cdp'
884
+ if (!ready.ok) return { ...ready, now: null, volume: null, systemVolume: null, sessions: [], serverTime: Date.now() }
885
+ try {
886
+ const audioIdForMeta = String(s?.audioSongId || '')
887
+ const cur = audioIdForMeta
888
+ ? (this.queue.find((q) => String(q?.id || q?.songId || '') === audioIdForMeta) || null)
889
+ : (this.queue[this.queueIndex] || null)
890
+ // 队列元数据(日推/播放列表带的歌名)比网页 DOM 标题更准——网页标题常是
891
+ // "网易云音乐",播放栏 DOM 也可能没渲染完。优先用它,DOM 兜底。
892
+ const artistsText = Array.isArray(cur?.artists)
893
+ ? cur.artists.map((a) => (typeof a === 'string' ? a : a.name)).join(' / ')
894
+ : (cur?.artists || '')
895
+ // 插件自己的 <audio> 正在放某首时,页面那首(用户手动点的)已经不是「当前曲」了,
896
+ // 元数据必须以 audio 为准,否则会出现「在放 A、显示 B」的错位。
897
+ const audioId = String(s?.audioSongId || '')
898
+ const songId = String(audioId || cur?.id || s?.songId || '')
899
+ // 队列空但页面在放歌 = 用户手动点的;记住它,play/pause/seek 才能接管。
900
+ if (songId && songId !== 'undefined' && !cur) this.manualSongId = songId
901
+ let title = (cur?.name || s?.title || '').trim()
902
+ let artist = (artistsText || s?.artist || '').trim()
903
+ let endMs = Number(s?.end) || 0
904
+ // 用户手动放歌时 getPlaying().track 可能只是数字 songId,没带名字。
905
+ // 用页面内同源 detail API 按 id 补元数据(带缓存),别再显示「网易云音乐」占位。
906
+ if ((!title || title === '网易云音乐' || title === s?.pageTitle) && songId && songId !== 'undefined') {
907
+ const meta = await this._songMeta(songId)
908
+ if (meta) {
909
+ title = title && title !== '网易云音乐' && title !== s?.pageTitle ? title : meta.name
910
+ artist = artist || meta.artist
911
+ if (!endMs && meta.durationMs) endMs = meta.durationMs
912
+ }
913
+ }
914
+ const now = {
915
+ aumid: 'web',
916
+ title: title || (s?.pageTitle || '').trim(),
917
+ artist,
918
+ album: cur?.album || '',
919
+ songId,
920
+ status: s?.status === 'Playing' ? 'Playing' : 'Paused',
921
+ // 与原生通道统一为「秒」:READ_STATE_EXPR 读的是 audio 毫秒,转成秒后上层 fmt() 才不会把毫秒当秒。
922
+ pos: (Number(s?.pos) || 0) / 1000,
923
+ end: endMs / 1000,
924
+ start: 0,
925
+ positionSource: 'web',
926
+ canPlay: true,
927
+ canPause: true,
928
+ canNext: this.queue.length > 0,
929
+ canPrev: this.queue.length > 0,
930
+ // 有 audio 就能跳;手动点播的歌虽然暂时没 audio,但点一次 play 就能建起来
931
+ canSeek: !!s?.hasAudio || (!!songId && songId !== 'undefined'),
932
+ channel: 'web',
933
+ mode: this.mode,
934
+ }
935
+ await this._attachLiked(now, songId || this.manualSongId)
936
+ return {
937
+ ok: true,
938
+ now,
939
+ volume: { level: this.volumeLevel, muted: this.muted, scope: 'process' },
940
+ systemVolume: await this._readSystemVolume(),
941
+ sessions: [],
942
+ winrt: false,
943
+ helper: {
944
+ healthy: true,
945
+ ready: true,
946
+ backend: this.id,
947
+ platform: 'web',
948
+ capabilities: this.capabilities,
949
+ degraded: this.lastError || '',
950
+ },
951
+ serverTime: Date.now(),
952
+ }
953
+ } catch (err) {
954
+ const f = this._fail('web-cdp-error', String(err?.message || err))
955
+ return { ...f, now: null, volume: null, systemVolume: null, sessions: [], serverTime: Date.now() }
956
+ }
957
+ }
958
+
959
+ /** action:保持上层 action 形状不变。 */
960
+ async action(action, extra = {}) {
961
+ const allowed = ['play', 'pause', 'toggle', 'next', 'prev', 'seek', 'play_daily', 'set_mode', 'like']
962
+ if (!allowed.includes(action)) return { ok: false, error: 'bad-action', detail: `unknown action: ${action}` }
963
+
964
+ // set_mode 是纯本地状态(改队列怎么走 + now.mode 给前端切图标),不碰 CDP、
965
+ // 不需要网页登录、也不依赖 SMTC。放在所有联网/连通性检查之前,个人 Edge
966
+ // 放歌(SMTC 场景,通常没登录 ego CDP)时也能切。
967
+ if (action === 'set_mode') {
968
+ const value = String(extra.value || '').trim()
969
+ const mapped = MODE_SHORT_TO_ENUM[value]
970
+ if (!mapped) return { ok: false, error: 'bad-mode', detail: `unknown mode: ${value || '(empty)'}` }
971
+ this.mode = mapped
972
+ try { this.getConfig().webPlayMode = mapped } catch { /* volatile 配置可选 */ }
973
+ const after = await this.state().catch(() => null)
974
+ // 前端 run() 见 res.now!==undefined 会整体替换 now。若此刻读不到歌(SMTC 无会话、
975
+ // CDP 页没开)state() 会返回 now:null,那会把前端状态清空、图标回退成默认「顺序」。
976
+ // 所以 set_mode 无论读不读得到歌,都回一个带新 mode 的 now;其余字段尽量沿用。
977
+ let outNow = after?.now
978
+ if (!outNow) {
979
+ // 尽量用上一次的 SMTC 快照重建,避免清空标题/进度
980
+ try { outNow = this.smtcState ? this._smtcResult(this.smtcState).now : null } catch { outNow = null }
981
+ }
982
+ outNow = outNow
983
+ ? { ...outNow, mode: this.mode }
984
+ : { aumid: 'web', title: '', artist: '', songId: '', status: 'Paused', channel: 'web', mode: this.mode, positionSource: this.dataSource === 'smtc' ? 'smtc-web' : 'web' }
985
+ return { ok: true, channel: 'web', action, value, mode: this.mode, now: outNow, volume: after?.volume || null }
986
+ }
987
+
988
+ // 日推:取数/取 URL/出声全走 Node 侧 + WinRT 后台引擎,零 CDP。必须放在 ensure() 之前,
989
+ // 否则 ego 关着(browser.json 不存在)时下面的 ensure() 会直接返回 web-browser-unavailable,
990
+ // 永远到不了 switch 里的 play_daily 分支——这正是「点日推报没有找到 ego 浏览器」的根因。
991
+ if (action === 'play_daily') return await this._playDaily()
992
+
993
+ // 日推引擎(WinRT)在播时点红心:收藏队列里当前这首,不碰 CDP/SMTC(ego 可能关着、
994
+ // SMTC 里是个人 Edge 的旧歌)。_webLike 的 songId 优先级第一条就是 queue[queueIndex]。
995
+ if (action === 'like' && this.winrtPlaying) {
996
+ const r = await this._webLike(extra)
997
+ if (r && r.ok === false) return r
998
+ return { ok: true, channel: 'web', action, liked: r.liked, songId: r.songId, now: r.now || (await this.state()).now, volume: r.volume || null }
999
+ }
1000
+
1001
+ // 「喜欢」在 SMTC 场景(用户在个人 Edge 放歌、ego CDP 没开)必须走零 CDP 路径。
1002
+ // 不能复用下面那套依赖 probe.positionSource/dataSource 快照的分支:state() 会把
1003
+ // dataSource 改写成 cdp,快照一漂移 like 就掉进需要 ego 浏览器的 ensure() → 报
1004
+ // web-browser-unavailable / like-no-song。这里显式读一次 SMTC 拿歌名搜 songId。
1005
+ if (action === 'like' && this._smtcEnabled()) {
1006
+ const smtced = await this._smtcLike(extra)
1007
+ if (smtced) return smtced
1008
+ }
1009
+
1010
+ // 日推引擎(WinRT)在播时,播放控制全走它——它不在 SMTC/CDP 里,别的通道管不到。
1011
+ if (this.winrtPlaying && this.winrtAudio && ['play', 'pause', 'toggle', 'next', 'prev', 'seek'].includes(action)) {
1012
+ let r
1013
+ if (action === 'next' || action === 'prev') {
1014
+ const to = this._advanceIndex(action === 'next' ? 1 : -1)
1015
+ if (to === null) {
1016
+ return { ok: true, channel: 'web', action, atEnd: action === 'next', atStart: action === 'prev', now: (await this.state()).now }
1017
+ }
1018
+ const played = await this._playWinrtIndex(to)
1019
+ if (!played.ok) return played
1020
+ r = played
1021
+ } else if (action === 'seek') {
1022
+ r = await this.winrtAudio.seek(Math.max(0, Math.round(Number(extra.positionMs) || 0)))
1023
+ } else if (action === 'play') {
1024
+ // 引擎里已有当前曲目 Source,续播用 resume;play(url) 是换歌用的,这里没 url。
1025
+ r = await this.winrtAudio.resume()
1026
+ } else {
1027
+ r = await this.winrtAudio[action]()
1028
+ }
1029
+ if (r && r.ok === false) return { ok: false, error: r.error || 'winrt-control-failed', message: '日推播放控制失败', detail: r.detail }
1030
+ const after = await this.state()
1031
+ return { ok: true, channel: 'web', action, now: after.now, volume: after.volume }
1032
+ }
1033
+
1034
+ // 用户在个人 Edge 用网页版放歌(无 CDP 端口)时,状态来自 SMTC;这几种播放控制
1035
+ // 必须走同一个 SMTC 通道才生效。like/play_daily/set_mode 仍走原来的 CDP + API 逻辑。
1036
+ const SMTC_ACTIONS = ['play', 'pause', 'toggle', 'next', 'prev', 'seek']
1037
+ if (this._smtcEnabled() && (SMTC_ACTIONS.includes(action) || action === 'like')) {
1038
+ // 如果最近一次 state 已经确认数据源是 smtc,直接用那个快照判断,省掉一次
1039
+ // state() 里的 PowerShell spawn(前端刚轮询过,快照新鲜)。否则才重新 probe。
1040
+ let probe = null
1041
+ if (this.dataSource === 'smtc' && this.smtcState) {
1042
+ probe = { ok: true, now: this._smtcResult(this.smtcState).now }
1043
+ } else {
1044
+ probe = await this.state().catch(() => null)
1045
+ }
1046
+ if (probe && probe.ok && probe.now && probe.now.positionSource === 'smtc-web') {
1047
+ // 收藏不走 smtc.control(SMTC 没有"喜欢"语义),改用带浏览器 cookie 的 LikeService;
1048
+ // songId 由 state() 按歌名+歌手搜出来,纯 SMTC 场景也不依赖 ego CDP 的 ensure。
1049
+ if (action === 'like') {
1050
+ const r = await this._webLike(extra)
1051
+ if (r && r.ok === false) return r
1052
+ return { ok: true, channel: 'web', action, now: r.now || probe.now, volume: r.volume || probe.volume, liked: r.liked }
1053
+ }
1054
+ const r = await this.smtc.control(action, { positionMs: Number(extra.positionMs) || 0 }).catch(
1055
+ (err) => ({ ok: false, error: 'smtc-unavailable', detail: String(err?.message || err) }),
1056
+ )
1057
+ if (!r.ok) {
1058
+ return { ok: false, error: r.error || 'smtc-control-failed', message: '系统媒体控制失败', detail: r.detail }
1059
+ }
1060
+ // probe 的 control 已在同一个 PowerShell 进程里回读了状态,直接用它当 after,
1061
+ // 省掉再调一次 state()(那会 spawn 新 PowerShell,多花 ~280ms)。
1062
+ if (r.title) {
1063
+ this.dataSource = 'smtc'
1064
+ this.smtcState = r
1065
+ const after = this._smtcResult(r)
1066
+ after.systemVolume = await this._readSystemVolume()
1067
+ // songId 搜索有 60min 缓存、liked 有节流,都不 spawn PowerShell,补上让红心正确。
1068
+ const sid = await this._songIdBySearch(r.title, r.artist)
1069
+ if (sid) after.now.songId = sid
1070
+ await this._attachLiked(after.now, sid)
1071
+ return { ok: true, channel: 'web', action, now: after.now, volume: after.volume, systemVolume: after.systemVolume }
1072
+ }
1073
+ const after = await this.state()
1074
+ return { ok: true, channel: 'web', action, now: after.now, volume: after.volume }
1075
+ }
1076
+ }
1077
+
1078
+ const ready = await this.ensure()
1079
+ if (!ready.ok) {
1080
+ // ego 关着(CDP 不可用)时的最后兜底:个人 Edge 放歌、SMTC 会话被视频顶掉,
1081
+ // 且插件刚重启(sticky 记忆空、state 读不到歌)时,控制流会落到这里的 CDP
1082
+ // ensure 失败。但下发 pause/next 到浏览器会话仍能作用于实际在响的媒体——
1083
+ // probe 对控制动作已放宽(视频标题也能定位会话)。直接尝试 SMTC 控制。
1084
+ if (this._smtcEnabled() && SMTC_ACTIONS.includes(action)) {
1085
+ const r = await this.smtc.control(action, { positionMs: Number(extra.positionMs) || 0 }).catch(
1086
+ (err) => ({ ok: false, error: 'smtc-unavailable', detail: String(err?.message || err) }),
1087
+ )
1088
+ if (r && r.ok) {
1089
+ this.dataSource = 'smtc'
1090
+ this.smtcState = r
1091
+ const after = this._smtcResult(r)
1092
+ after.systemVolume = await this._readSystemVolume()
1093
+ return { ok: true, channel: 'web', action, now: after.now, volume: after.volume, systemVolume: after.systemVolume }
1094
+ }
1095
+ }
1096
+ return ready
1097
+ }
1098
+ if (!(await this._isLoggedIn().catch(() => false))) return this._fail('web-not-logged-in', '')
1099
+
1100
+ try {
1101
+ let r
1102
+ switch (action) {
1103
+ case 'play':
1104
+ if (this.queue.length && this.queueIndex >= 0) {
1105
+ r = await this._controlAudio('play')
1106
+ // 队列里有歌但 audio 还没建(插件重启过)→ 按队列重放这首
1107
+ if (r === false) r = await this._playQueueIndex(this.queueIndex)
1108
+ } else {
1109
+ r = await this._playManual()
1110
+ }
1111
+ break
1112
+ case 'pause':
1113
+ r = await this._pauseAny()
1114
+ break
1115
+ case 'toggle': {
1116
+ const s = await this._eval(READ_STATE_EXPR)
1117
+ if (s?.status === 'Playing') r = await this._pauseAny()
1118
+ else if (this.queue.length && this.queueIndex >= 0) {
1119
+ r = await this._controlAudio('play')
1120
+ if (r === false) r = await this._playQueueIndex(this.queueIndex)
1121
+ } else r = await this._playManual()
1122
+ break
1123
+ }
1124
+ case 'next': {
1125
+ const to = this._advanceIndex(1)
1126
+ if (to === null) return { ok: true, channel: 'web', action, atEnd: true, now: (await this.state()).now, volume: (this.volumeLevel !== undefined ? { level: this.volumeLevel, muted: this.muted, scope: 'process' } : null) }
1127
+ r = await this._playQueueIndex(to)
1128
+ break
1129
+ }
1130
+ case 'prev': {
1131
+ const to = this._advanceIndex(-1)
1132
+ if (to === null) return { ok: true, channel: 'web', action, atStart: true, now: (await this.state()).now, volume: { level: this.volumeLevel, muted: this.muted, scope: 'process' } }
1133
+ r = await this._playQueueIndex(to)
1134
+ break
1135
+ }
1136
+ case 'seek': {
1137
+ r = await this._controlAudio('seek', Math.max(0, Math.round(Number(extra.positionMs) || 0)))
1138
+ // 没有 <audio> 就没得跳:手动点的歌要先让插件接管(play 一次)才有时间轴
1139
+ if (r === false) return this._fail('web-no-audio-url', '这首还没被插件接管,先点一次播放再拖进度')
1140
+ break
1141
+ }
1142
+ case 'like':
1143
+ r = await this._webLike(extra)
1144
+ break
1145
+ case 'play_daily':
1146
+ return await this._playDaily()
1147
+ default:
1148
+ r = this._fail('web-action-failed', action)
1149
+ }
1150
+ if (r && r.ok === false) return r
1151
+ const after = await this.state()
1152
+ const out = { ok: true, channel: 'web', action, now: after.now, volume: after.volume }
1153
+ // like 的状态要透传给上层文案(index.js 读 res.liked 决定「已收藏/已取消」)
1154
+ if (r && typeof r.liked === 'boolean') out.liked = r.liked
1155
+ return out
1156
+ } catch (err) {
1157
+ return this._fail('web-action-failed', String(err?.message || err))
1158
+ }
1159
+ }
1160
+
1161
+ /**
1162
+ * SMTC 场景的「喜欢」:全程零 CDP,不调 state()/ensure()。
1163
+ * 显式读一次 SMTC 会话拿歌名 → 搜 songId(CDP 有则快、没则 Node 兜底)→ LikeService 收藏。
1164
+ * SMTC 没有有效音乐会话(或读到视频)时返回 null,交回 action() 走原 CDP 路径。
1165
+ */
1166
+ async _smtcLike(extra) {
1167
+ const svc = this.likeWeb || this.like
1168
+ if (!svc) return null
1169
+ let sm = this.smtcState
1170
+ try {
1171
+ const fresh = await this.smtc.readState()
1172
+ if (fresh && fresh.ok && fresh.title) sm = fresh
1173
+ } catch { /* 用上一次快照 */ }
1174
+ const title = String(sm?.title || '')
1175
+ const artist = String(sm?.artist || '')
1176
+ if (!title || (!artist && this._isVideoTitle(title))) return null
1177
+ // songId 一律按当前歌名+歌手搜:songSearchCache 命中是纯内存(零网络零 spawn),
1178
+ // 且保证收藏的就是当前这首——别用 likedForSong,那可能是切歌前上一首的 id。
1179
+ let id = await this._songIdBySearch(title, artist)
1180
+ if (!id || id === '0' || id === 'undefined' || id === 'NaN') return null // 搜不到 → 交回原路径报错
1181
+ let want = extra?.like
1182
+ if (typeof want !== 'boolean') {
1183
+ const cur = await svc.isLiked(id)
1184
+ want = !(cur.ok ? cur.liked : false)
1185
+ }
1186
+ const res = await svc.setLiked(id, want)
1187
+ if (!res.ok) return { ok: false, channel: 'web', action: 'like', error: res.error || 'like-failed', message: res.message, detail: res.detail }
1188
+ svc.forget?.(id)
1189
+ this.likedForSong = id
1190
+ this.likedCheckedAt = Date.now()
1191
+ // 用 SMTC 快照构造 now(纯函数,零 spawn/fetch),直接回填刚设置的 liked,红心立即更新。
1192
+ const after = this._smtcResult(sm)
1193
+ after.now.songId = id
1194
+ after.now.liked = want
1195
+ after.systemVolume = await this._readSystemVolume()
1196
+ return { ok: true, channel: 'web', action: 'like', liked: want, songId: id, now: after.now, volume: after.volume, systemVolume: after.systemVolume }
1197
+ }
1198
+
1199
+ async _webLike(extra) {
1200
+ const svc = this.likeWeb || this.like
1201
+ if (!svc) return { ok: false, error: 'like-unavailable', message: '网页版喜欢功能未接入' }
1202
+ // songId 来源优先级:插件队列 → 手动点播记住的 → 当前 state(SMTC 分支会按歌名搜出 id)
1203
+ let id = String((this.queue[this.queueIndex]?.id) || '')
1204
+ if (!id || id === 'undefined') id = String(this.manualSongId || '')
1205
+ let probe = null
1206
+ if (!id || id === 'undefined') {
1207
+ probe = await this.state().catch(() => null)
1208
+ id = String((probe?.now?.songId) || '')
1209
+ }
1210
+ if (!id || id === '0' || id === 'undefined' || id === 'NaN') {
1211
+ return { ok: false, error: 'like-no-song', message: '播放中才能喜欢' }
1212
+ }
1213
+ let want = extra?.like
1214
+ if (typeof want !== 'boolean') {
1215
+ const cur = await svc.isLiked(id)
1216
+ want = !(cur.ok ? cur.liked : false)
1217
+ }
1218
+ const res = await svc.setLiked(id, want)
1219
+ if (!res.ok) return { ok: false, error: res.error || 'like-failed', message: res.message, detail: res.detail }
1220
+ svc.forget?.(id)
1221
+ // 强制重读 liked:清掉节流状态后重新查一次,别用操作前的 probe(那样红心会停在旧值)。
1222
+ this.likedForSong = ''
1223
+ this.likedCheckedAt = 0
1224
+ const after = await this.state().catch(() => null)
1225
+ return { ok: true, liked: want, songId: id, now: after?.now || null, volume: after?.volume || null }
1226
+ }
1227
+
1228
+ /**
1229
+ * 用 WinRT 常驻引擎播队列里的第 idx 首(取 URL → 交给引擎 → 出声)。
1230
+ * 全程不碰 CDP/ego/SMTC,个人 Edge 关着也能播。日推引擎在播时状态由引擎自己回报。
1231
+ */
1232
+ async _playWinrtIndex(idx) {
1233
+ if (!this.winrtAudio) return this._fail('web-no-audio-engine', '当前环境不支持后台音频引擎')
1234
+ const song = this.queue[idx]
1235
+ if (!song) return this._fail('web-no-song', '')
1236
+ const id = song.id || song.songId
1237
+ const got = await this._songUrl(id)
1238
+ if (!got.ok) return got
1239
+ this.queueIndex = idx
1240
+ this.winrtSong = { id, name: song.name, artist: song.artist }
1241
+ const artist = Array.isArray(song.artists)
1242
+ ? song.artists.map((a) => (typeof a === 'string' ? a : a.name)).join(' / ')
1243
+ : (song.artist || song.artists || '')
1244
+ const r = await this.winrtAudio.play({
1245
+ url: got.url,
1246
+ songId: String(id),
1247
+ title: song.name || '',
1248
+ artist,
1249
+ level: this.volumeLevel,
1250
+ muted: this.muted,
1251
+ })
1252
+ if (r && r.ok === false) {
1253
+ this.winrtPlaying = false
1254
+ return { ok: false, error: r.error || 'web-play-failed', message: '后台音频播放失败', detail: r.detail }
1255
+ }
1256
+ this.winrtPlaying = true
1257
+ return { ok: true, url: got.url, engine: r, song }
1258
+ }
1259
+
1260
+ /**
1261
+ * 日推:复用 DailyService 的取数(cookie + 按天缓存),把结果灌进队列并从第一首播。
1262
+ * 出声走 WinRT 常驻后台引擎——不依赖 ego 浏览器 CDP、不弹任何页面、不进 SMTC。
1263
+ * 这样即使 ego 关着、个人 Edge 没开 CDP 端口,点日推也能立刻出声。
1264
+ */
1265
+ async _playDaily() {
1266
+ if (!this.daily) return this._fail('web-no-song', '日推服务未接入')
1267
+ try {
1268
+ const list = await this.daily.fetch({})
1269
+ if (!list.ok) return { ok: false, error: list.error, message: list.message, detail: list.detail }
1270
+ const songs = (list.songs || []).map((s) => ({
1271
+ id: s.id || s.songId,
1272
+ name: s.name,
1273
+ artists: s.artists || s.artistsName,
1274
+ })).filter((s) => s.id)
1275
+ if (!songs.length) return this._fail('web-no-song', '日推列表为空')
1276
+ this.queue = songs
1277
+ const played = await this._playWinrtIndex(0)
1278
+ if (!played.ok) return played
1279
+ const first = songs[0]
1280
+ const firstArtist = Array.isArray(first.artists)
1281
+ ? first.artists.map((a) => (typeof a === 'string' ? a : a.name)).join(' / ')
1282
+ : (first.artists || '')
1283
+ // 字段与原生通道 #playDaily 对齐(songCount/firstSong),上层 index.js 无需区分通道。
1284
+ return {
1285
+ ok: true,
1286
+ channel: 'web',
1287
+ action: 'play_daily',
1288
+ songCount: songs.length,
1289
+ firstSong: { id: first.id, name: first.name, artist: firstArtist },
1290
+ now: (await this.state()).now,
1291
+ }
1292
+ } catch (err) {
1293
+ return this._fail('web-action-failed', String(err?.message || err))
1294
+ }
1295
+ }
1296
+
1297
+ /**
1298
+ * volume:系统音量走 native helper(Windows 端点,与播放通道无关、不依赖 CDP),
1299
+ * APP 音量走网页 <audio>。真正的声音来自个人 Edge 时 <audio> 不存在,那种情况下
1300
+ * APP 也落到系统音量,免得拖动没反应。
1301
+ */
1302
+ async volume({ level, muted, scope } = {}) {
1303
+ const wantScope = scope === 'system' ? 'system'
1304
+ : scope === 'process' ? 'process'
1305
+ : (String(this.getConfig().volumeScope || 'process'))
1306
+ // SYS:调系统端点。走 native helper,不需要 CDP,助手没连网页也能调。
1307
+ if (wantScope === 'system') {
1308
+ if (!this._hasSystemVolume()) {
1309
+ return { ok: false, error: 'volume-unsupported', detail: '当前环境不支持系统音量' }
1310
+ }
1311
+ try {
1312
+ const res = await this.systemVolumeService.volume({ level, muted, scope: 'system' })
1313
+ if (res && res.ok === false) return res
1314
+ return {
1315
+ ok: true,
1316
+ scope: 'system',
1317
+ volume: res?.volume || null,
1318
+ systemVolume: res?.systemVolume || res?.volume || null,
1319
+ }
1320
+ } catch (err) {
1321
+ return { ok: false, error: 'volume-failed', detail: String(err?.message || err) }
1322
+ }
1323
+ }
1324
+ // APP 音量:日推引擎在播时直接调 WinRT MediaPlayer 的音量,别去动网页 <audio>。
1325
+ if (typeof level === 'number' && level >= 0 && level <= 1) this.volumeLevel = level
1326
+ if (typeof muted === 'boolean') this.muted = muted
1327
+ if (this.winrtPlaying && this.winrtAudio) {
1328
+ const r = await this.winrtAudio.volume(this.volumeLevel, this.muted).catch(() => null)
1329
+ return {
1330
+ ok: true, scope: 'process',
1331
+ volume: { level: this.volumeLevel, muted: this.muted, scope: 'process' },
1332
+ systemVolume: await this._readSystemVolume(),
1333
+ engine: r?.ok === true,
1334
+ }
1335
+ }
1336
+ // SMTC 场景(个人 Edge 放歌):真正出声在浏览器进程,没有插件自己的 <audio>。
1337
+ // APP 音量必须调浏览器的「进程音量」(Core Audio per-process session),绝不能
1338
+ // 回退到系统音量——否则用户拖 APP 音量会把 SYS 一起拖走(报过的 bug)。
1339
+ // 出声进程名取自 SMTC 会话的 aumid(msedge.exe → msedge);helper 按 pid 精确
1340
+ // 命中有音频会话的那个进程,找不到就如实报失败、不回退。
1341
+ const smAumid = this.dataSource === 'smtc' ? String(this.smtcState?.aumid || '') : ''
1342
+ const smProc = smAumid.replace(/\.exe$/i, '').trim()
1343
+ if (smProc && this.systemVolumeService && this._hasSystemVolume()) {
1344
+ // 关键:只有当本次调用明确要改静音时才传 muted。native.volume() 只要收到
1345
+ // muted(非 undefined)就走 mute 命令,而 mute 命令不写 level——若拖滑杆时
1346
+ // 也带上 this.muted,level 根本不会生效,回读是旧值,前端滑杆就会「跳回」。
1347
+ const payload = {
1348
+ level: this.volumeLevel, scope: 'process',
1349
+ procName: smProc, noFallback: true,
1350
+ }
1351
+ if (typeof muted === 'boolean') payload.muted = muted
1352
+ const res = await this.systemVolumeService.volume(payload).catch(() => null)
1353
+ if (res && res.ok !== false) {
1354
+ // 回显用刚写入的目标值,不依赖助手回读(避免任何回读延迟让滑杆跳回)。
1355
+ return {
1356
+ ok: true, scope: 'process',
1357
+ volume: { level: this.volumeLevel, muted: this.muted, scope: 'process' },
1358
+ systemVolume: await this._readSystemVolume(),
1359
+ via: 'smtc-process',
1360
+ }
1361
+ }
1362
+ // 出声进程的音频会话不存在(用户已停播)→ 如实报错,绝不改系统音量
1363
+ return { ok: false, error: 'volume-no-session', message: '当前没有可单独调节的浏览器音频会话', detail: '' }
1364
+ }
1365
+
1366
+ // APP:网页 <audio> 音量(非 SMTC 场景)。
1367
+ const ready = await this.ensure()
1368
+ if (!ready.ok && !this._hasSystemVolume()) return ready
1369
+ try {
1370
+ let appliedVia = 'audio'
1371
+ if (ready.ok) {
1372
+ const r = await this._eval(`(() => { const a=document.getElementById(${JSON.stringify(AUDIO_ID)}); if(!a) return false; a.volume=${this.volumeLevel};a.muted=${this.muted?'true':'false'}; return true })()`)
1373
+ appliedVia = r ? 'audio' : 'system'
1374
+ } else {
1375
+ appliedVia = 'system'
1376
+ }
1377
+ if (appliedVia === 'system' && this._hasSystemVolume()) {
1378
+ const res = await this.systemVolumeService.volume({ level, muted, scope: 'system' })
1379
+ const sys = res?.systemVolume || res?.volume || null
1380
+ return { ok: true, scope: 'process', volume: sys || { level: this.volumeLevel, muted: this.muted, scope: 'process' }, systemVolume: sys }
1381
+ }
1382
+ return { ok: true, scope: 'process', volume: { level: this.volumeLevel, muted: this.muted, scope: 'process' }, systemVolume: await this._readSystemVolume() }
1383
+ } catch (err) {
1384
+ return this._fail('web-action-failed', String(err?.message || err))
1385
+ }
1386
+ }
1387
+
1388
+ /** 歌词:复用 LyricsService(Host 侧另一个实例),网页版只是把调用转给它。 */
1389
+ async lyrics(params) {
1390
+ if (!this.lyricsResolver) return { ok: false, error: 'lyrics-unavailable', message: '歌词服务未接入' }
1391
+ try { return await this.lyricsResolver(params) } catch (err) {
1392
+ return { ok: false, error: 'lyrics-failed', detail: String(err?.message || err) }
1393
+ }
1394
+ }
1395
+
1396
+ async deepHealth() {
1397
+ const ready = await this.ensure()
1398
+ const smtcState = this._smtcEnabled() ? await this.smtc.readState().catch(() => null) : null
1399
+ const smtc = {
1400
+ enabled: this._smtcEnabled(),
1401
+ available: !!(smtcState && smtcState.ok),
1402
+ title: smtcState?.title || '',
1403
+ artist: smtcState?.artist || '',
1404
+ error: smtcState?.error || '',
1405
+ }
1406
+ if (!ready.ok) {
1407
+ // CDP 没连上但 SMTC 能读到个人浏览器在放的歌,也算网页通道可用
1408
+ if (smtc.available) {
1409
+ return {
1410
+ ok: true, backend: this.id, platform: 'web', capabilities: this.capabilities,
1411
+ helper: { healthy: true, backend: 'smtc-browser', degraded: '' },
1412
+ loggedIn: true, dataSource: 'smtc', smtc, lastError: '',
1413
+ }
1414
+ }
1415
+ return { ok: false, backend: this.id, platform: 'web', ...ready, smtc }
1416
+ }
1417
+ const loggedIn = await this._isLoggedIn().catch(() => false)
1418
+ return {
1419
+ ok: loggedIn || smtc.available,
1420
+ backend: this.id,
1421
+ platform: 'web',
1422
+ capabilities: this.capabilities,
1423
+ helper: { healthy: loggedIn || smtc.available, backend: this.id, degraded: (loggedIn || smtc.available) ? '' : 'web-not-logged-in' },
1424
+ loggedIn,
1425
+ injectedCookies: this.injectedCookies,
1426
+ queueSize: this.queue.length,
1427
+ manualSongId: this.manualSongId || '',
1428
+ dataSource: this.dataSource,
1429
+ smtc,
1430
+ lastError: this.lastError,
1431
+ }
1432
+ }
1433
+
1434
+ async stop() {
1435
+ try { this.cdp?.close() } catch { /* ignore */ }
1436
+ this.cdp = null
1437
+ this.sessionId = null
1438
+ try { await this.winrtAudio?.close() } catch { /* ignore */ }
1439
+ this.winrtPlaying = false
1440
+ this.winrtSong = null
1441
+ }
1442
+ }
1443
+
1444
+ export default WebBackend